aboutsummaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--.gitignore39
-rw-r--r--.travis.yml128
-rw-r--r--BUILD313
-rw-r--r--CHANGES.txt324
-rw-r--r--Makefile.am445
-rw-r--r--Protobuf.podspec7
-rw-r--r--README.md43
-rw-r--r--WORKSPACE2
-rw-r--r--appveyor.bat8
-rw-r--r--appveyor.yml3
-rwxr-xr-xautogen.sh2
-rw-r--r--cmake/CMakeLists.txt28
-rw-r--r--cmake/extract_includes.bat.in227
-rw-r--r--cmake/install.cmake57
-rw-r--r--cmake/libprotobuf-lite.cmake28
-rw-r--r--cmake/libprotobuf.cmake60
-rw-r--r--cmake/libprotoc.cmake123
-rw-r--r--cmake/protobuf-config-version.cmake.in34
-rw-r--r--cmake/protobuf-config.cmake.in108
-rw-r--r--cmake/protobuf-lite.pc.cmake11
-rw-r--r--cmake/protobuf-module.cmake.in94
-rw-r--r--cmake/protobuf.pc.cmake11
-rw-r--r--cmake/tests.cmake12
-rw-r--r--composer.json12
-rw-r--r--configure.ac32
-rw-r--r--conformance/ConformanceJava.java250
-rw-r--r--conformance/Makefile.am110
-rw-r--r--conformance/README.md32
-rw-r--r--conformance/autoload.php21
-rw-r--r--conformance/conformance.proto5
-rw-r--r--conformance/conformance_cpp.cc32
-rwxr-xr-xconformance/conformance_nodejs.js182
-rw-r--r--conformance/conformance_objc.m14
-rwxr-xr-xconformance/conformance_php.php105
-rwxr-xr-xconformance/conformance_python.py21
-rwxr-xr-xconformance/conformance_ruby.rb21
-rw-r--r--conformance/conformance_test.cc393
-rw-r--r--conformance/conformance_test.h39
-rw-r--r--conformance/failure_list_cpp.txt79
-rw-r--r--conformance/failure_list_csharp.txt3
-rw-r--r--conformance/failure_list_java.txt74
-rw-r--r--conformance/failure_list_js.txt13
-rw-r--r--conformance/failure_list_objc.txt2
-rw-r--r--conformance/failure_list_php.txt20
-rw-r--r--conformance/failure_list_php_c.txt182
-rw-r--r--conformance/failure_list_php_zts_c.txt225
-rw-r--r--conformance/failure_list_python.txt34
-rw-r--r--conformance/failure_list_python_cpp.txt74
-rw-r--r--conformance/failure_list_ruby.txt324
-rwxr-xr-xconformance/update_failure_list.py6
-rw-r--r--csharp/Google.Protobuf.Tools.nuspec2
-rw-r--r--csharp/README.md39
-rw-r--r--csharp/build_packages.bat4
-rwxr-xr-xcsharp/buildall.sh5
-rw-r--r--csharp/compatibility_tests/v3.0.0/protos/csharp/protos/unittest_issues.proto126
-rw-r--r--csharp/compatibility_tests/v3.0.0/protos/src/google/protobuf/map_unittest_proto3.proto (renamed from src/google/protobuf/map_unittest_proto3.proto)0
-rw-r--r--csharp/compatibility_tests/v3.0.0/protos/src/google/protobuf/unittest_import_proto3.proto (renamed from src/google/protobuf/unittest_import_proto3.proto)0
-rw-r--r--csharp/compatibility_tests/v3.0.0/protos/src/google/protobuf/unittest_import_public_proto3.proto (renamed from src/google/protobuf/unittest_import_public_proto3.proto)0
-rw-r--r--csharp/compatibility_tests/v3.0.0/protos/src/google/protobuf/unittest_proto3.proto388
-rw-r--r--csharp/compatibility_tests/v3.0.0/protos/src/google/protobuf/unittest_well_known_types.proto114
-rw-r--r--csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/ByteStringTest.cs171
-rw-r--r--csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/CodedInputStreamExtensions.cs53
-rw-r--r--csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/CodedInputStreamTest.cs598
-rw-r--r--csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/CodedOutputStreamTest.cs419
-rw-r--r--csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Collections/MapFieldTest.cs532
-rw-r--r--csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Collections/RepeatedFieldTest.cs746
-rw-r--r--csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Compatibility/PropertyInfoExtensionsTest.cs98
-rw-r--r--csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Compatibility/TypeExtensionsTest.cs117
-rw-r--r--csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/DeprecatedMemberTest.cs55
-rw-r--r--csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/EqualityTester.cs64
-rw-r--r--csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/FieldCodecTest.cs196
-rw-r--r--csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/GeneratedMessageTest.cs723
-rw-r--r--csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Google.Protobuf.Test.csproj30
-rw-r--r--csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/IssuesTest.cs82
-rw-r--r--csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/JsonParserTest.cs939
-rw-r--r--csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/JsonTokenizerTest.cs408
-rw-r--r--csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Program.cs47
-rw-r--r--csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Reflection/DescriptorsTest.cs259
-rw-r--r--csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Reflection/FieldAccessTest.cs218
-rw-r--r--csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Reflection/TypeRegistryTest.cs94
-rw-r--r--csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/SampleEnum.cs42
-rw-r--r--csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/SampleMessages.cs99
-rw-r--r--csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/TestCornerCases.cs62
-rw-r--r--csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/TestProtos/ForeignMessagePartial.cs45
-rw-r--r--csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/WellKnownTypes/AnyTest.cs116
-rw-r--r--csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/WellKnownTypes/DurationTest.cs132
-rw-r--r--csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/WellKnownTypes/FieldMaskTest.cs62
-rw-r--r--csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/WellKnownTypes/TimestampTest.cs115
-rw-r--r--csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/WellKnownTypes/WrappersTest.cs421
-rwxr-xr-xcsharp/compatibility_tests/v3.0.0/test.sh104
-rwxr-xr-xcsharp/generate_protos.sh31
-rw-r--r--csharp/global.json5
-rw-r--r--csharp/protos/README.md3
-rw-r--r--csharp/protos/map_unittest_proto3.proto116
-rw-r--r--csharp/protos/unittest_custom_options_proto3.proto336
-rw-r--r--csharp/protos/unittest_import_proto3.proto56
-rw-r--r--csharp/protos/unittest_import_public_proto3.proto (renamed from src/google/protobuf/arena_nc.cc)18
-rw-r--r--csharp/protos/unittest_issues.proto16
-rw-r--r--csharp/protos/unittest_proto3.proto379
-rw-r--r--csharp/src/AddressBook/AddressBook.csproj14
-rw-r--r--csharp/src/AddressBook/AddressBook.xproj19
-rw-r--r--csharp/src/AddressBook/Addressbook.cs58
-rw-r--r--csharp/src/AddressBook/project.json20
-rw-r--r--csharp/src/Google.Protobuf.Conformance/Conformance.cs53
-rw-r--r--csharp/src/Google.Protobuf.Conformance/Google.Protobuf.Conformance.csproj14
-rw-r--r--csharp/src/Google.Protobuf.Conformance/Google.Protobuf.Conformance.xproj19
-rw-r--r--csharp/src/Google.Protobuf.Conformance/Program.cs23
-rw-r--r--csharp/src/Google.Protobuf.Conformance/project.json21
-rw-r--r--csharp/src/Google.Protobuf.JsonDump/Google.Protobuf.JsonDump.csproj13
-rw-r--r--csharp/src/Google.Protobuf.JsonDump/Google.Protobuf.JsonDump.xproj19
-rw-r--r--csharp/src/Google.Protobuf.JsonDump/project.json19
-rwxr-xr-x[-rw-r--r--]csharp/src/Google.Protobuf.Test/ByteStringTest.cs55
-rw-r--r--csharp/src/Google.Protobuf.Test/CodedInputStreamTest.cs23
-rw-r--r--csharp/src/Google.Protobuf.Test/CodedOutputStreamTest.cs9
-rw-r--r--csharp/src/Google.Protobuf.Test/Collections/MapFieldTest.cs32
-rwxr-xr-xcsharp/src/Google.Protobuf.Test/Compatibility/StreamExtensionsTest.cs67
-rwxr-xr-x[-rw-r--r--]csharp/src/Google.Protobuf.Test/Compatibility/TypeExtensionsTest.cs2
-rwxr-xr-x[-rw-r--r--]csharp/src/Google.Protobuf.Test/FieldCodecTest.cs5
-rw-r--r--csharp/src/Google.Protobuf.Test/Google.Protobuf.Test.csproj30
-rw-r--r--csharp/src/Google.Protobuf.Test/Google.Protobuf.Test.xproj21
-rw-r--r--csharp/src/Google.Protobuf.Test/IssuesTest.cs14
-rw-r--r--csharp/src/Google.Protobuf.Test/JsonFormatterTest.cs57
-rw-r--r--csharp/src/Google.Protobuf.Test/JsonParserTest.cs25
-rw-r--r--csharp/src/Google.Protobuf.Test/JsonTokenizerTest.cs16
-rwxr-xr-xcsharp/src/Google.Protobuf.Test/Program.cs48
-rw-r--r--csharp/src/Google.Protobuf.Test/Reflection/CustomOptionsTest.cs271
-rw-r--r--csharp/src/Google.Protobuf.Test/Reflection/DescriptorsTest.cs34
-rw-r--r--csharp/src/Google.Protobuf.Test/TestProtos/MapUnittestProto3.cs254
-rw-r--r--csharp/src/Google.Protobuf.Test/TestProtos/TestMessagesProto3.cs441
-rw-r--r--csharp/src/Google.Protobuf.Test/TestProtos/UnittestCustomOptionsProto3.cs2625
-rw-r--r--csharp/src/Google.Protobuf.Test/TestProtos/UnittestImportProto3.cs20
-rw-r--r--csharp/src/Google.Protobuf.Test/TestProtos/UnittestImportPublicProto3.cs14
-rw-r--r--csharp/src/Google.Protobuf.Test/TestProtos/UnittestIssues.cs357
-rw-r--r--csharp/src/Google.Protobuf.Test/TestProtos/UnittestProto3.cs440
-rw-r--r--csharp/src/Google.Protobuf.Test/TestProtos/UnittestWellKnownTypes.cs45
-rw-r--r--csharp/src/Google.Protobuf.Test/WellKnownTypes/AnyTest.cs34
-rw-r--r--csharp/src/Google.Protobuf.Test/project.json44
-rw-r--r--csharp/src/Google.Protobuf.sln16
-rwxr-xr-x[-rw-r--r--]csharp/src/Google.Protobuf/ByteString.cs56
-rw-r--r--csharp/src/Google.Protobuf/CodedInputStream.cs21
-rw-r--r--csharp/src/Google.Protobuf/Collections/MapField.cs15
-rwxr-xr-x[-rw-r--r--]csharp/src/Google.Protobuf/Collections/RepeatedField.cs3
-rwxr-xr-x[-rw-r--r--]csharp/src/Google.Protobuf/Compatibility/PropertyInfoExtensions.cs4
-rwxr-xr-xcsharp/src/Google.Protobuf/Compatibility/StreamExtensions.cs66
-rwxr-xr-x[-rw-r--r--]csharp/src/Google.Protobuf/Compatibility/TypeExtensions.cs2
-rw-r--r--csharp/src/Google.Protobuf/Google.Protobuf.csproj33
-rw-r--r--csharp/src/Google.Protobuf/Google.Protobuf.xproj19
-rwxr-xr-x[-rw-r--r--]csharp/src/Google.Protobuf/JsonFormatter.cs63
-rw-r--r--csharp/src/Google.Protobuf/JsonParser.cs54
-rw-r--r--csharp/src/Google.Protobuf/JsonTokenizer.cs30
-rw-r--r--csharp/src/Google.Protobuf/MessageExtensions.cs16
-rw-r--r--csharp/src/Google.Protobuf/MessageParser.cs32
-rw-r--r--csharp/src/Google.Protobuf/Reflection/CustomOptions.cs390
-rw-r--r--csharp/src/Google.Protobuf/Reflection/Descriptor.cs756
-rw-r--r--csharp/src/Google.Protobuf/Reflection/EnumDescriptor.cs5
-rw-r--r--csharp/src/Google.Protobuf/Reflection/EnumValueDescriptor.cs5
-rw-r--r--csharp/src/Google.Protobuf/Reflection/FieldDescriptor.cs5
-rw-r--r--csharp/src/Google.Protobuf/Reflection/FileDescriptor.cs5
-rwxr-xr-x[-rw-r--r--]csharp/src/Google.Protobuf/Reflection/MessageDescriptor.cs7
-rw-r--r--csharp/src/Google.Protobuf/Reflection/MethodDescriptor.cs5
-rw-r--r--csharp/src/Google.Protobuf/Reflection/OneofDescriptor.cs5
-rw-r--r--csharp/src/Google.Protobuf/Reflection/OriginalNameAttribute.cs9
-rw-r--r--csharp/src/Google.Protobuf/Reflection/ServiceDescriptor.cs5
-rw-r--r--csharp/src/Google.Protobuf/WellKnownTypes/Any.cs10
-rw-r--r--csharp/src/Google.Protobuf/WellKnownTypes/AnyPartial.cs43
-rw-r--r--csharp/src/Google.Protobuf/WellKnownTypes/Api.cs50
-rw-r--r--csharp/src/Google.Protobuf/WellKnownTypes/Duration.cs15
-rw-r--r--csharp/src/Google.Protobuf/WellKnownTypes/FieldMask.cs6
-rwxr-xr-x[-rw-r--r--]csharp/src/Google.Protobuf/WellKnownTypes/FieldMaskPartial.cs2
-rw-r--r--csharp/src/Google.Protobuf/WellKnownTypes/Struct.cs10
-rw-r--r--csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs25
-rw-r--r--csharp/src/Google.Protobuf/WellKnownTypes/Type.cs10
-rw-r--r--csharp/src/Google.Protobuf/project.json65
-rw-r--r--csharp/src/packages/repositories.config4
-rw-r--r--docs/third_party.md20
-rw-r--r--editors/protobuf-mode.el4
-rw-r--r--examples/BUILD101
-rw-r--r--examples/CMakeLists.txt17
-rw-r--r--examples/ListPeople.java3
-rw-r--r--examples/Makefile8
-rw-r--r--examples/README.md124
-rw-r--r--examples/README.txt54
-rw-r--r--examples/WORKSPACE33
-rw-r--r--examples/add_person.cc9
-rwxr-xr-xexamples/add_person.py13
-rw-r--r--examples/addressbook.proto4
-rw-r--r--examples/list_people.cc13
-rwxr-xr-xexamples/list_people.py19
-rwxr-xr-xgenerate_descriptor_proto.sh53
-rw-r--r--java/core/generate-test-sources-build.xml4
-rw-r--r--java/core/pom.xml5
-rw-r--r--java/core/src/main/java/com/google/protobuf/AbstractMessage.java41
-rw-r--r--java/core/src/main/java/com/google/protobuf/AbstractMessageLite.java94
-rw-r--r--java/core/src/main/java/com/google/protobuf/AbstractParser.java26
-rw-r--r--java/core/src/main/java/com/google/protobuf/BooleanArrayList.java12
-rw-r--r--java/core/src/main/java/com/google/protobuf/CodedInputStream.java1186
-rw-r--r--java/core/src/main/java/com/google/protobuf/CodedOutputStream.java82
-rw-r--r--java/core/src/main/java/com/google/protobuf/Descriptors.java7
-rw-r--r--java/core/src/main/java/com/google/protobuf/DiscardUnknownFieldsParser.java71
-rw-r--r--java/core/src/main/java/com/google/protobuf/DoubleArrayList.java12
-rw-r--r--java/core/src/main/java/com/google/protobuf/DynamicMessage.java17
-rw-r--r--java/core/src/main/java/com/google/protobuf/Extension.java7
-rw-r--r--java/core/src/main/java/com/google/protobuf/ExtensionRegistryFactory.java5
-rw-r--r--java/core/src/main/java/com/google/protobuf/FieldSet.java8
-rw-r--r--java/core/src/main/java/com/google/protobuf/FloatArrayList.java12
-rw-r--r--java/core/src/main/java/com/google/protobuf/GeneratedMessage.java4
-rw-r--r--java/core/src/main/java/com/google/protobuf/GeneratedMessageLite.java229
-rw-r--r--java/core/src/main/java/com/google/protobuf/GeneratedMessageV3.java105
-rw-r--r--java/core/src/main/java/com/google/protobuf/IntArrayList.java12
-rw-r--r--java/core/src/main/java/com/google/protobuf/Internal.java20
-rw-r--r--java/core/src/main/java/com/google/protobuf/InvalidProtocolBufferException.java4
-rw-r--r--java/core/src/main/java/com/google/protobuf/IterableByteBufferInputStream.java150
-rw-r--r--java/core/src/main/java/com/google/protobuf/LazyFieldLite.java1
-rw-r--r--java/core/src/main/java/com/google/protobuf/LongArrayList.java12
-rw-r--r--java/core/src/main/java/com/google/protobuf/MapEntry.java26
-rw-r--r--java/core/src/main/java/com/google/protobuf/MapEntryLite.java5
-rw-r--r--java/core/src/main/java/com/google/protobuf/MapField.java9
-rw-r--r--java/core/src/main/java/com/google/protobuf/MapFieldLite.java16
-rw-r--r--java/core/src/main/java/com/google/protobuf/Message.java2
-rw-r--r--java/core/src/main/java/com/google/protobuf/MessageReflection.java24
-rw-r--r--java/core/src/main/java/com/google/protobuf/Parser.java13
-rw-r--r--java/core/src/main/java/com/google/protobuf/PrimitiveNonBoxingCollection.java34
-rw-r--r--java/core/src/main/java/com/google/protobuf/RepeatedFieldBuilderV3.java18
-rw-r--r--java/core/src/main/java/com/google/protobuf/SingleFieldBuilderV3.java12
-rw-r--r--java/core/src/main/java/com/google/protobuf/SmallSortedMap.java25
-rw-r--r--java/core/src/main/java/com/google/protobuf/TextFormat.java233
-rw-r--r--java/core/src/main/java/com/google/protobuf/UnknownFieldSet.java33
-rw-r--r--java/core/src/main/java/com/google/protobuf/UnknownFieldSetLite.java33
-rw-r--r--java/core/src/main/java/com/google/protobuf/UnsafeUtil.java489
-rw-r--r--java/core/src/main/java/com/google/protobuf/Utf8.java35
-rw-r--r--java/core/src/main/java/com/google/protobuf/WireFormat.java6
-rw-r--r--java/core/src/test/java/com/google/protobuf/CodedInputStreamTest.java169
-rw-r--r--java/core/src/test/java/com/google/protobuf/DiscardUnknownFieldsTest.java157
-rw-r--r--java/core/src/test/java/com/google/protobuf/FieldPresenceTest.java42
-rw-r--r--java/core/src/test/java/com/google/protobuf/GeneratedMessageTest.java157
-rw-r--r--java/core/src/test/java/com/google/protobuf/LazyFieldTest.java2
-rw-r--r--java/core/src/test/java/com/google/protobuf/LazyStringArrayListTest.java1
-rw-r--r--java/core/src/test/java/com/google/protobuf/LiteTest.java369
-rw-r--r--java/core/src/test/java/com/google/protobuf/MapForProto2LiteTest.java8
-rw-r--r--java/core/src/test/java/com/google/protobuf/MapForProto2Test.java9
-rw-r--r--java/core/src/test/java/com/google/protobuf/MapTest.java71
-rw-r--r--java/core/src/test/java/com/google/protobuf/MessageTest.java20
-rw-r--r--java/core/src/test/java/com/google/protobuf/ParserTest.java95
-rw-r--r--java/core/src/test/java/com/google/protobuf/TestBadIdentifiers.java26
-rw-r--r--java/core/src/test/java/com/google/protobuf/TestBadIdentifiersLite.java83
-rw-r--r--java/core/src/test/java/com/google/protobuf/TestUtil.java5
-rw-r--r--java/core/src/test/java/com/google/protobuf/TextFormatTest.java130
-rw-r--r--java/core/src/test/java/com/google/protobuf/UnknownEnumValueTest.java14
-rw-r--r--java/core/src/test/java/com/google/protobuf/UnknownFieldSetLiteTest.java255
-rw-r--r--java/core/src/test/java/com/google/protobuf/UnknownFieldSetTest.java204
-rw-r--r--java/core/src/test/java/com/google/protobuf/WireFormatTest.java70
-rw-r--r--java/core/src/test/proto/com/google/protobuf/deprecated_file.proto38
-rw-r--r--java/core/src/test/proto/com/google/protobuf/lite_equals_and_hash.proto8
-rw-r--r--java/core/src/test/proto/com/google/protobuf/test_bad_identifiers.proto17
-rw-r--r--java/lite/pom.xml1
-rw-r--r--java/pom.xml8
-rw-r--r--java/util/pom.xml2
-rw-r--r--java/util/src/main/java/com/google/protobuf/util/Durations.java23
-rw-r--r--java/util/src/main/java/com/google/protobuf/util/FieldMaskTree.java6
-rw-r--r--java/util/src/main/java/com/google/protobuf/util/FieldMaskUtil.java9
-rw-r--r--java/util/src/main/java/com/google/protobuf/util/JsonFormat.java208
-rw-r--r--java/util/src/main/java/com/google/protobuf/util/Timestamps.java34
-rw-r--r--java/util/src/test/java/com/google/protobuf/util/FieldMaskTreeTest.java8
-rw-r--r--java/util/src/test/java/com/google/protobuf/util/JsonFormatTest.java195
-rw-r--r--java/util/src/test/proto/com/google/protobuf/util/json_test.proto30
-rw-r--r--javanano/README.md3
-rw-r--r--javanano/pom.xml6
-rw-r--r--javanano/src/test/java/com/google/protobuf/nano/NanoTest.java5
-rw-r--r--jenkins/docker/Dockerfile80
-rw-r--r--jenkins/docker32/Dockerfile68
-rw-r--r--jenkins/make_test_output.py11
-rw-r--r--js/README.md12
-rw-r--r--js/binary/arith_test.js109
-rw-r--r--js/binary/constants.js3
-rw-r--r--js/binary/decoder.js49
-rw-r--r--js/binary/decoder_test.js48
-rw-r--r--js/binary/encoder.js16
-rw-r--r--js/binary/message_test.js60
-rw-r--r--js/binary/proto_test.js6
-rw-r--r--js/binary/reader.js2
-rw-r--r--js/binary/utils.js5
-rw-r--r--js/binary/utils_test.js25
-rw-r--r--js/binary/writer.js14
-rw-r--r--js/binary/writer_test.js4
-rw-r--r--js/commonjs/export.js4
-rw-r--r--js/commonjs/export_asserts.js4
-rw-r--r--js/commonjs/export_testdeps.js4
-rw-r--r--js/compatibility_tests/v3.0.0/binary/arith_test.js355
-rw-r--r--js/compatibility_tests/v3.0.0/binary/decoder_test.js317
-rw-r--r--js/compatibility_tests/v3.0.0/binary/proto_test.js628
-rw-r--r--js/compatibility_tests/v3.0.0/binary/reader_test.js922
-rw-r--r--js/compatibility_tests/v3.0.0/binary/utils_test.js668
-rw-r--r--js/compatibility_tests/v3.0.0/binary/writer_test.js122
-rw-r--r--js/compatibility_tests/v3.0.0/commonjs/export_asserts.js37
-rw-r--r--js/compatibility_tests/v3.0.0/commonjs/export_testdeps.js18
-rw-r--r--js/compatibility_tests/v3.0.0/commonjs/import_test.js52
-rw-r--r--js/compatibility_tests/v3.0.0/commonjs/jasmine.json9
-rw-r--r--js/compatibility_tests/v3.0.0/commonjs/rewrite_tests_for_commonjs.js97
-rw-r--r--js/compatibility_tests/v3.0.0/commonjs/test6/test6.proto40
-rw-r--r--js/compatibility_tests/v3.0.0/commonjs/test7/test7.proto42
-rw-r--r--js/compatibility_tests/v3.0.0/data.proto51
-rw-r--r--js/compatibility_tests/v3.0.0/debug_test.js105
-rw-r--r--js/compatibility_tests/v3.0.0/jasmine1.json17
-rw-r--r--js/compatibility_tests/v3.0.0/jasmine2.json17
-rw-r--r--js/compatibility_tests/v3.0.0/jasmine3.json17
-rw-r--r--js/compatibility_tests/v3.0.0/message_test.js1080
-rw-r--r--js/compatibility_tests/v3.0.0/proto3_test.js329
-rw-r--r--js/compatibility_tests/v3.0.0/proto3_test.proto89
-rw-r--r--js/compatibility_tests/v3.0.0/test.proto236
-rwxr-xr-xjs/compatibility_tests/v3.0.0/test.sh92
-rw-r--r--js/compatibility_tests/v3.0.0/test2.proto54
-rw-r--r--js/compatibility_tests/v3.0.0/test3.proto53
-rw-r--r--js/compatibility_tests/v3.0.0/test4.proto42
-rw-r--r--js/compatibility_tests/v3.0.0/test5.proto44
-rw-r--r--js/compatibility_tests/v3.0.0/testbinary.proto212
-rw-r--r--js/compatibility_tests/v3.0.0/testempty.proto34
-rw-r--r--js/compatibility_tests/v3.1.0/binary/arith_test.js355
-rw-r--r--js/compatibility_tests/v3.1.0/binary/decoder_test.js317
-rw-r--r--js/compatibility_tests/v3.1.0/binary/proto_test.js628
-rw-r--r--js/compatibility_tests/v3.1.0/binary/reader_test.js922
-rw-r--r--js/compatibility_tests/v3.1.0/binary/utils_test.js668
-rw-r--r--js/compatibility_tests/v3.1.0/binary/writer_test.js122
-rw-r--r--js/compatibility_tests/v3.1.0/commonjs/test6/test6.proto40
-rw-r--r--js/compatibility_tests/v3.1.0/commonjs/test7/test7.proto42
-rw-r--r--js/compatibility_tests/v3.1.0/data.proto51
-rw-r--r--js/compatibility_tests/v3.1.0/debug_test.js105
-rw-r--r--js/compatibility_tests/v3.1.0/maps_test.js301
-rw-r--r--js/compatibility_tests/v3.1.0/message_test.js1032
-rw-r--r--js/compatibility_tests/v3.1.0/proto3_test.js329
-rw-r--r--js/compatibility_tests/v3.1.0/proto3_test.proto89
-rw-r--r--js/compatibility_tests/v3.1.0/test.proto262
-rw-r--r--js/compatibility_tests/v3.1.0/test2.proto54
-rw-r--r--js/compatibility_tests/v3.1.0/test3.proto53
-rw-r--r--js/compatibility_tests/v3.1.0/test4.proto42
-rw-r--r--js/compatibility_tests/v3.1.0/test5.proto44
-rw-r--r--js/compatibility_tests/v3.1.0/testbinary.proto212
-rw-r--r--js/compatibility_tests/v3.1.0/testempty.proto34
-rw-r--r--js/gulpfile.js93
-rw-r--r--js/jasmine.json4
-rw-r--r--js/map.js68
-rwxr-xr-xjs/maps_test.js44
-rw-r--r--js/message.js243
-rw-r--r--js/message_test.js50
-rw-r--r--js/package.json2
-rw-r--r--js/proto3_test.js48
-rw-r--r--js/proto3_test.proto1
-rw-r--r--js/test.proto8
-rw-r--r--js/test8.proto50
-rw-r--r--kokoro/README.md6
-rwxr-xr-xkokoro/linux/cpp_distcheck/build.sh11
-rw-r--r--kokoro/linux/cpp_distcheck/continuous.cfg5
-rw-r--r--kokoro/linux/cpp_distcheck/presubmit.cfg5
-rwxr-xr-xkokoro/linux/csharp/build.sh11
-rw-r--r--kokoro/linux/csharp/continuous.cfg5
-rw-r--r--kokoro/linux/csharp/presubmit.cfg5
-rwxr-xr-xkokoro/linux/java_compatibility/build.sh11
-rw-r--r--kokoro/linux/java_compatibility/continuous.cfg5
-rw-r--r--kokoro/linux/java_compatibility/presubmit.cfg5
-rw-r--r--kokoro/linux/prepare_build_linux_rc9
-rwxr-xr-xkokoro/linux/python_compatibility/build.sh11
-rw-r--r--kokoro/linux/python_compatibility/continuous.cfg5
-rw-r--r--kokoro/linux/python_compatibility/presubmit.cfg5
-rwxr-xr-xkokoro/macos/cpp/build.sh11
-rw-r--r--kokoro/macos/cpp/continuous.cfg5
-rw-r--r--kokoro/macos/cpp/presubmit.cfg5
-rwxr-xr-xkokoro/macos/cpp_distcheck/build.sh11
-rw-r--r--kokoro/macos/cpp_distcheck/continuous.cfg5
-rw-r--r--kokoro/macos/cpp_distcheck/presubmit.cfg5
-rwxr-xr-xkokoro/macos/javascript/build.sh11
-rw-r--r--kokoro/macos/javascript/continuous.cfg5
-rw-r--r--kokoro/macos/javascript/presubmit.cfg5
-rwxr-xr-xkokoro/macos/jruby/build.sh11
-rw-r--r--kokoro/macos/jruby/continuous.cfg5
-rw-r--r--kokoro/macos/jruby/presubmit.cfg5
-rwxr-xr-xkokoro/macos/objectivec_cocoapods_integration/build.sh11
-rw-r--r--kokoro/macos/objectivec_cocoapods_integration/continuous.cfg5
-rw-r--r--kokoro/macos/objectivec_cocoapods_integration/presubmit.cfg5
-rwxr-xr-xkokoro/macos/objectivec_ios_debug/build.sh11
-rw-r--r--kokoro/macos/objectivec_ios_debug/continuous.cfg5
-rw-r--r--kokoro/macos/objectivec_ios_debug/presubmit.cfg5
-rwxr-xr-xkokoro/macos/objectivec_ios_release/build.sh11
-rw-r--r--kokoro/macos/objectivec_ios_release/continuous.cfg5
-rw-r--r--kokoro/macos/objectivec_ios_release/presubmit.cfg5
-rwxr-xr-xkokoro/macos/objectivec_osx/build.sh11
-rw-r--r--kokoro/macos/objectivec_osx/continuous.cfg5
-rw-r--r--kokoro/macos/objectivec_osx/presubmit.cfg5
-rwxr-xr-xkokoro/macos/php5.6_mac/build.sh11
-rw-r--r--kokoro/macos/php5.6_mac/continuous.cfg5
-rw-r--r--kokoro/macos/php5.6_mac/presubmit.cfg5
-rwxr-xr-xkokoro/macos/php7.0_mac/build.sh11
-rw-r--r--kokoro/macos/php7.0_mac/continuous.cfg5
-rw-r--r--kokoro/macos/php7.0_mac/presubmit.cfg5
-rwxr-xr-xkokoro/macos/prepare_build_macos_rc35
-rwxr-xr-xkokoro/macos/python/build.sh11
-rw-r--r--kokoro/macos/python/continuous.cfg5
-rw-r--r--kokoro/macos/python/presubmit.cfg5
-rwxr-xr-xkokoro/macos/python_cpp/build.sh12
-rw-r--r--kokoro/macos/python_cpp/continuous.cfg5
-rw-r--r--kokoro/macos/python_cpp/presubmit.cfg5
-rwxr-xr-xkokoro/macos/ruby21/build.sh11
-rw-r--r--kokoro/macos/ruby21/continuous.cfg5
-rw-r--r--kokoro/macos/ruby21/presubmit.cfg5
-rwxr-xr-xkokoro/macos/ruby22/build.sh11
-rw-r--r--kokoro/macos/ruby22/continuous.cfg5
-rw-r--r--kokoro/macos/ruby22/presubmit.cfg5
-rw-r--r--m4/ax_cxx_compile_stdcxx.m419
-rw-r--r--m4/ax_prog_cc_for_build.m4125
-rw-r--r--m4/ax_prog_cxx_for_build.m4110
-rwxr-xr-xobjectivec/DevTools/full_mac_build.sh18
-rwxr-xr-xobjectivec/DevTools/pddm.py24
-rw-r--r--objectivec/GPBArray.h50
-rw-r--r--objectivec/GPBArray.m4
-rw-r--r--objectivec/GPBCodedInputStream.m80
-rw-r--r--objectivec/GPBCodedOutputStream.h9
-rw-r--r--objectivec/GPBCodedOutputStream.m11
-rw-r--r--objectivec/GPBDescriptor.m4
-rw-r--r--objectivec/GPBDescriptor_PackagePrivate.h4
-rw-r--r--objectivec/GPBDictionary.h3088
-rw-r--r--objectivec/GPBDictionary.m4525
-rw-r--r--objectivec/GPBExtensionRegistry.m37
-rw-r--r--objectivec/GPBMessage.h14
-rw-r--r--objectivec/GPBMessage.m90
-rw-r--r--objectivec/GPBMessage_PackagePrivate.h10
-rw-r--r--objectivec/GPBRootObject.m29
-rw-r--r--objectivec/GPBUnknownField.h3
-rw-r--r--objectivec/GPBUnknownField.m8
-rw-r--r--objectivec/GPBUnknownField_PackagePrivate.h2
-rw-r--r--objectivec/GPBUtilities.h5
-rw-r--r--objectivec/GPBUtilities.m457
-rw-r--r--objectivec/GPBUtilities_PackagePrivate.h5
-rw-r--r--objectivec/GPBWellKnownTypes.h17
-rw-r--r--objectivec/GPBWellKnownTypes.m52
-rw-r--r--objectivec/ProtocolBuffers_OSX.xcodeproj/project.pbxproj22
-rw-r--r--objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme13
-rw-r--r--objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme4
-rw-r--r--objectivec/ProtocolBuffers_iOS.xcodeproj/project.pbxproj24
-rw-r--r--objectivec/ProtocolBuffers_iOS.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme13
-rw-r--r--objectivec/ProtocolBuffers_iOS.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme4
-rw-r--r--objectivec/Tests/GPBArrayTests.m331
-rw-r--r--objectivec/Tests/GPBCodedInputStreamTests.m185
-rw-r--r--objectivec/Tests/GPBDescriptorTests.m117
-rw-r--r--objectivec/Tests/GPBDictionaryTests+Bool.m80
-rw-r--r--objectivec/Tests/GPBDictionaryTests+Int32.m105
-rw-r--r--objectivec/Tests/GPBDictionaryTests+Int64.m105
-rw-r--r--objectivec/Tests/GPBDictionaryTests+String.m95
-rw-r--r--objectivec/Tests/GPBDictionaryTests+UInt32.m105
-rw-r--r--objectivec/Tests/GPBDictionaryTests+UInt64.m105
-rw-r--r--objectivec/Tests/GPBDictionaryTests.m186
-rw-r--r--objectivec/Tests/GPBDictionaryTests.pddm35
-rw-r--r--objectivec/Tests/GPBExtensionRegistryTest.m138
-rw-r--r--objectivec/Tests/GPBMessageTests+Serialization.m117
-rw-r--r--objectivec/Tests/GPBMessageTests.m37
-rw-r--r--objectivec/Tests/GPBPerfTests.m106
-rw-r--r--objectivec/Tests/GPBTestUtilities.h3
-rw-r--r--objectivec/Tests/GPBUnknownFieldSetTest.m271
-rw-r--r--objectivec/Tests/GPBUtilitiesTests.m200
-rw-r--r--objectivec/Tests/GPBWellKnownTypesTest.m162
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/Contents.json80
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_1024.pngbin0 -> 205605 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_120.pngbin0 -> 7233 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_152.pngbin0 -> 10332 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_167.pngbin0 -> 11694 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_180.pngbin0 -> 13111 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_20.pngbin0 -> 752 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_29.pngbin0 -> 1197 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_40.pngbin0 -> 1730 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_58.pngbin0 -> 2748 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_60.pngbin0 -> 2834 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_76.pngbin0 -> 3931 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_80.pngbin0 -> 4125 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_87.pngbin0 -> 4671 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad6.pngbin8583 -> 0 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad6_2x.pngbin17744 -> 0 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad7.pngbin8969 -> 0 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad7_2x.pngbin18788 -> 0 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone6.pngbin7021 -> 0 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone6_2x.pngbin13348 -> 0 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone7_2x.pngbin11128 -> 0 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone7_3x.pngbin21792 -> 0 bytes
-rw-r--r--objectivec/Tests/iOSTestHarness/Images.xcassets/LaunchImage.launchimage/Contents.json25
-rw-r--r--objectivec/google/protobuf/Any.pbobjc.h10
-rw-r--r--objectivec/google/protobuf/Api.pbobjc.h50
-rw-r--r--objectivec/google/protobuf/Duration.pbobjc.h15
-rw-r--r--objectivec/google/protobuf/FieldMask.pbobjc.h6
-rw-r--r--objectivec/google/protobuf/Timestamp.pbobjc.h25
-rw-r--r--objectivec/google/protobuf/Type.pbobjc.h14
-rw-r--r--php/README.md4
-rw-r--r--php/composer.json14
-rw-r--r--php/ext/google/protobuf/array.c362
-rw-r--r--php/ext/google/protobuf/def.c892
-rw-r--r--php/ext/google/protobuf/encode_decode.c775
-rw-r--r--php/ext/google/protobuf/map.c291
-rw-r--r--php/ext/google/protobuf/message.c2009
-rw-r--r--php/ext/google/protobuf/package.xml115
-rw-r--r--php/ext/google/protobuf/protobuf.c214
-rw-r--r--php/ext/google/protobuf/protobuf.h1168
-rw-r--r--php/ext/google/protobuf/storage.c763
-rw-r--r--php/ext/google/protobuf/type_check.c170
-rw-r--r--php/ext/google/protobuf/upb.c4232
-rw-r--r--php/ext/google/protobuf/upb.h1566
-rwxr-xr-xphp/generate_descriptor_protos.sh16
-rw-r--r--php/phpunit.xml5
-rw-r--r--php/src/GPBMetadata/Google/Protobuf/Any.php30
-rw-r--r--php/src/GPBMetadata/Google/Protobuf/Api.php49
-rw-r--r--php/src/GPBMetadata/Google/Protobuf/Duration.php31
-rw-r--r--php/src/GPBMetadata/Google/Protobuf/FieldMask.php31
-rw-r--r--php/src/GPBMetadata/Google/Protobuf/GPBEmpty.php30
-rw-r--r--php/src/GPBMetadata/Google/Protobuf/Internal/Descriptor.php15
-rw-r--r--php/src/GPBMetadata/Google/Protobuf/SourceContext.php32
-rw-r--r--php/src/GPBMetadata/Google/Protobuf/Struct.php45
-rw-r--r--php/src/GPBMetadata/Google/Protobuf/Timestamp.php31
-rw-r--r--php/src/GPBMetadata/Google/Protobuf/Type.php78
-rw-r--r--php/src/GPBMetadata/Google/Protobuf/Wrappers.php38
-rw-r--r--php/src/Google/Protobuf/Any.php272
-rw-r--r--php/src/Google/Protobuf/Api.php310
-rw-r--r--php/src/Google/Protobuf/BoolValue.php58
-rw-r--r--php/src/Google/Protobuf/BytesValue.php58
-rw-r--r--php/src/Google/Protobuf/Descriptor.php100
-rw-r--r--php/src/Google/Protobuf/DescriptorPool.php76
-rw-r--r--php/src/Google/Protobuf/DoubleValue.php58
-rw-r--r--php/src/Google/Protobuf/Duration.php153
-rw-r--r--php/src/Google/Protobuf/Enum.php185
-rw-r--r--php/src/Google/Protobuf/EnumDescriptor.php79
-rw-r--r--php/src/Google/Protobuf/EnumValue.php121
-rw-r--r--php/src/Google/Protobuf/EnumValueDescriptor.php64
-rw-r--r--php/src/Google/Protobuf/Field.php351
-rw-r--r--php/src/Google/Protobuf/FieldDescriptor.php117
-rw-r--r--php/src/Google/Protobuf/FieldMask.php209
-rw-r--r--php/src/Google/Protobuf/Field_Cardinality.php39
-rw-r--r--php/src/Google/Protobuf/Field_Kind.php129
-rw-r--r--php/src/Google/Protobuf/FloatValue.php58
-rw-r--r--php/src/Google/Protobuf/GPBEmpty.php31
-rw-r--r--php/src/Google/Protobuf/Int32Value.php58
-rw-r--r--php/src/Google/Protobuf/Int64Value.php58
-rw-r--r--php/src/Google/Protobuf/Internal/CodedInputStream.php (renamed from php/src/Google/Protobuf/Internal/InputStream.php)129
-rw-r--r--php/src/Google/Protobuf/Internal/CodedOutputStream.php (renamed from php/src/Google/Protobuf/Internal/OutputStream.php)21
-rw-r--r--php/src/Google/Protobuf/Internal/Descriptor.php208
-rw-r--r--php/src/Google/Protobuf/Internal/DescriptorPool.php39
-rw-r--r--php/src/Google/Protobuf/Internal/DescriptorProto.php171
-rw-r--r--php/src/Google/Protobuf/Internal/DescriptorProto_ExtensionRange.php58
-rw-r--r--php/src/Google/Protobuf/Internal/DescriptorProto_ReservedRange.php39
-rw-r--r--php/src/Google/Protobuf/Internal/EnumBuilderContext.php4
-rw-r--r--php/src/Google/Protobuf/Internal/EnumDescriptor.php92
-rw-r--r--php/src/Google/Protobuf/Internal/EnumDescriptorProto.php133
-rw-r--r--php/src/Google/Protobuf/Internal/EnumDescriptorProto_EnumReservedRange.php109
-rw-r--r--php/src/Google/Protobuf/Internal/EnumOptions.php60
-rw-r--r--php/src/Google/Protobuf/Internal/EnumValueDescriptorProto.php40
-rw-r--r--php/src/Google/Protobuf/Internal/EnumValueOptions.php43
-rw-r--r--php/src/Google/Protobuf/Internal/ExtensionRangeOptions.php64
-rw-r--r--php/src/Google/Protobuf/Internal/FieldDescriptor.php265
-rw-r--r--php/src/Google/Protobuf/Internal/FieldDescriptorProto.php159
-rw-r--r--php/src/Google/Protobuf/Internal/FieldDescriptorProto_Label.php14
-rw-r--r--php/src/Google/Protobuf/Internal/FieldDescriptorProto_Type.php61
-rw-r--r--php/src/Google/Protobuf/Internal/FieldOptions.php173
-rw-r--r--php/src/Google/Protobuf/Internal/FieldOptions_CType.php14
-rw-r--r--php/src/Google/Protobuf/Internal/FieldOptions_JSType.php18
-rw-r--r--php/src/Google/Protobuf/Internal/FileDescriptor.php89
-rw-r--r--php/src/Google/Protobuf/Internal/FileDescriptorProto.php231
-rw-r--r--php/src/Google/Protobuf/Internal/FileDescriptorSet.php22
-rw-r--r--php/src/Google/Protobuf/Internal/FileOptions.php392
-rw-r--r--php/src/Google/Protobuf/Internal/FileOptions_OptimizeMode.php20
-rw-r--r--php/src/Google/Protobuf/Internal/GPBDecodeException.php47
-rw-r--r--php/src/Google/Protobuf/Internal/GPBJsonWire.php304
-rw-r--r--php/src/Google/Protobuf/Internal/GPBUtil.php437
-rw-r--r--php/src/Google/Protobuf/Internal/GPBWire.php140
-rw-r--r--php/src/Google/Protobuf/Internal/GPBWireType.php43
-rw-r--r--php/src/Google/Protobuf/Internal/GeneratedCodeInfo.php28
-rw-r--r--php/src/Google/Protobuf/Internal/GeneratedCodeInfo_Annotation.php77
-rw-r--r--php/src/Google/Protobuf/Internal/GetPublicDescriptorTrait.php41
-rw-r--r--php/src/Google/Protobuf/Internal/HasPublicDescriptorTrait.php43
-rw-r--r--php/src/Google/Protobuf/Internal/MapEntry.php4
-rw-r--r--php/src/Google/Protobuf/Internal/MapField.php211
-rw-r--r--php/src/Google/Protobuf/Internal/MapFieldIter.php124
-rw-r--r--php/src/Google/Protobuf/Internal/Message.php1181
-rw-r--r--php/src/Google/Protobuf/Internal/MessageOptions.php100
-rw-r--r--php/src/Google/Protobuf/Internal/MethodDescriptorProto.php91
-rw-r--r--php/src/Google/Protobuf/Internal/MethodOptions.php54
-rw-r--r--php/src/Google/Protobuf/Internal/MethodOptions_IdempotencyLevel.php18
-rw-r--r--php/src/Google/Protobuf/Internal/OneofDescriptor.php78
-rw-r--r--php/src/Google/Protobuf/Internal/OneofDescriptorProto.php29
-rw-r--r--php/src/Google/Protobuf/Internal/OneofOptions.php26
-rw-r--r--php/src/Google/Protobuf/Internal/RawInputStream.php50
-rw-r--r--php/src/Google/Protobuf/Internal/RepeatedField.php84
-rw-r--r--php/src/Google/Protobuf/Internal/RepeatedFieldIter.php118
-rw-r--r--php/src/Google/Protobuf/Internal/ServiceDescriptorProto.php46
-rw-r--r--php/src/Google/Protobuf/Internal/ServiceOptions.php43
-rw-r--r--php/src/Google/Protobuf/Internal/SourceCodeInfo.php28
-rw-r--r--php/src/Google/Protobuf/Internal/SourceCodeInfo_Location.php94
-rw-r--r--php/src/Google/Protobuf/Internal/UninterpretedOption.php94
-rw-r--r--php/src/Google/Protobuf/Internal/UninterpretedOption_NamePart.php27
-rw-r--r--php/src/Google/Protobuf/ListValue.php58
-rw-r--r--php/src/Google/Protobuf/Method.php249
-rw-r--r--php/src/Google/Protobuf/Mixin.php153
-rw-r--r--php/src/Google/Protobuf/NullValue.php23
-rw-r--r--php/src/Google/Protobuf/OneofDescriptor.php75
-rw-r--r--php/src/Google/Protobuf/Option.php108
-rw-r--r--php/src/Google/Protobuf/SourceContext.php61
-rw-r--r--php/src/Google/Protobuf/StringValue.php58
-rw-r--r--php/src/Google/Protobuf/Struct.php63
-rw-r--r--php/src/Google/Protobuf/Syntax.php27
-rw-r--r--php/src/Google/Protobuf/Timestamp.php184
-rw-r--r--php/src/Google/Protobuf/Type.php217
-rw-r--r--php/src/Google/Protobuf/UInt32Value.php58
-rw-r--r--php/src/Google/Protobuf/UInt64Value.php58
-rw-r--r--php/src/Google/Protobuf/Value.php194
-rw-r--r--php/src/Google/Protobuf/descriptor.php558
-rw-r--r--php/tests/array_test.php631
-rwxr-xr-xphp/tests/autoload.php2
-rw-r--r--php/tests/bootstrap_phpunit.php5
-rwxr-xr-xphp/tests/compatibility_test.sh140
-rw-r--r--php/tests/descriptors_test.php246
-rw-r--r--php/tests/encode_decode_test.php387
-rwxr-xr-xphp/tests/gdb_test.sh6
-rw-r--r--php/tests/generated_class_test.php920
-rw-r--r--php/tests/generated_phpdoc_test.php337
-rw-r--r--php/tests/generated_service_test.php110
-rw-r--r--php/tests/map_field_test.php319
-rw-r--r--php/tests/memory_leak_test.php53
-rw-r--r--php/tests/php_implementation_test.php142
-rw-r--r--php/tests/proto/test.proto64
-rw-r--r--php/tests/proto/test_descriptors.proto35
-rw-r--r--php/tests/proto/test_empty_php_namespace.proto8
-rw-r--r--php/tests/proto/test_import_descriptor_proto.proto14
-rw-r--r--php/tests/proto/test_no_namespace.proto13
-rw-r--r--php/tests/proto/test_php_namespace.proto8
-rw-r--r--php/tests/proto/test_prefix.proto12
-rw-r--r--php/tests/proto/test_reserved_enum_lower.proto77
-rw-r--r--php/tests/proto/test_reserved_enum_upper.proto77
-rw-r--r--php/tests/proto/test_reserved_enum_value_lower.proto79
-rw-r--r--php/tests/proto/test_reserved_enum_value_upper.proto79
-rw-r--r--php/tests/proto/test_reserved_message_lower.proto77
-rw-r--r--php/tests/proto/test_reserved_message_upper.proto77
-rw-r--r--php/tests/proto/test_service.proto18
-rw-r--r--php/tests/proto/test_service_namespace.proto13
-rwxr-xr-xphp/tests/test.sh14
-rw-r--r--php/tests/test_base.php236
-rw-r--r--php/tests/test_util.php277
-rw-r--r--php/tests/undefined_test.php920
-rw-r--r--php/tests/well_known_test.php388
-rw-r--r--protobuf.bzl42
-rw-r--r--protoc-artifacts/Dockerfile7
-rw-r--r--protoc-artifacts/README.md15
-rwxr-xr-xprotoc-artifacts/build-protoc.sh9
-rwxr-xr-xprotoc-artifacts/build-zip.sh4
-rw-r--r--protoc-artifacts/pom.xml6
-rw-r--r--python/MANIFEST.in3
-rw-r--r--python/README.md83
-rw-r--r--python/compatibility_tests/v2.5.0/protos/python/google/protobuf/internal/factory_test1.proto55
-rw-r--r--python/compatibility_tests/v2.5.0/protos/python/google/protobuf/internal/factory_test2.proto77
-rw-r--r--python/compatibility_tests/v2.5.0/protos/python/google/protobuf/internal/more_extensions.proto58
-rw-r--r--python/compatibility_tests/v2.5.0/protos/python/google/protobuf/internal/more_extensions_dynamic.proto49
-rw-r--r--python/compatibility_tests/v2.5.0/protos/python/google/protobuf/internal/more_messages.proto51
-rw-r--r--python/compatibility_tests/v2.5.0/protos/python/google/protobuf/internal/test_bad_identifiers.proto52
-rw-r--r--python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/descriptor.proto620
-rw-r--r--python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest.proto719
-rw-r--r--python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_custom_options.proto387
-rw-r--r--python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_import.proto64
-rw-r--r--python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_import_public.proto40
-rw-r--r--python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_mset.proto72
-rw-r--r--python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_no_generic_services.proto52
-rwxr-xr-xpython/compatibility_tests/v2.5.0/setup.py87
-rwxr-xr-xpython/compatibility_tests/v2.5.0/test.sh104
-rw-r--r--python/compatibility_tests/v2.5.0/tests/__init__.py4
-rw-r--r--python/compatibility_tests/v2.5.0/tests/google/__init__.py4
-rw-r--r--python/compatibility_tests/v2.5.0/tests/google/protobuf/__init__.py4
-rw-r--r--python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/__init__.py (renamed from src/google/protobuf/arena_nc_test.py)36
-rwxr-xr-xpython/compatibility_tests/v2.5.0/tests/google/protobuf/internal/descriptor_test.py613
-rwxr-xr-xpython/compatibility_tests/v2.5.0/tests/google/protobuf/internal/generator_test.py269
-rw-r--r--python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/golden_messagebin0 -> 509 bytes
-rw-r--r--python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/golden_packed_fields_messagebin0 -> 142 bytes
-rwxr-xr-xpython/compatibility_tests/v2.5.0/tests/google/protobuf/internal/message_test.py499
-rwxr-xr-xpython/compatibility_tests/v2.5.0/tests/google/protobuf/internal/service_reflection_test.py136
-rwxr-xr-xpython/compatibility_tests/v2.5.0/tests/google/protobuf/internal/test_util.py651
-rwxr-xr-xpython/compatibility_tests/v2.5.0/tests/google/protobuf/internal/text_format_test.py619
-rw-r--r--python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/text_format_unittest_data.txt128
-rw-r--r--python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/text_format_unittest_extensions_data.txt128
-rwxr-xr-xpython/compatibility_tests/v2.5.0/tests/google/protobuf/internal/wire_format_test.py253
-rwxr-xr-xpython/google/protobuf/__init__.py2
-rwxr-xr-xpython/google/protobuf/descriptor.py9
-rw-r--r--python/google/protobuf/descriptor_database.py27
-rw-r--r--python/google/protobuf/descriptor_pool.py155
-rw-r--r--python/google/protobuf/internal/any_test.proto1
-rwxr-xr-xpython/google/protobuf/internal/api_implementation.py65
-rwxr-xr-xpython/google/protobuf/internal/containers.py2
-rwxr-xr-xpython/google/protobuf/internal/decoder.py18
-rw-r--r--python/google/protobuf/internal/descriptor_database_test.py34
-rw-r--r--python/google/protobuf/internal/descriptor_pool_test.py307
-rwxr-xr-xpython/google/protobuf/internal/descriptor_test.py305
-rwxr-xr-xpython/google/protobuf/internal/encoder.py116
-rw-r--r--python/google/protobuf/internal/factory_test2.proto5
-rw-r--r--python/google/protobuf/internal/json_format_test.py169
-rw-r--r--python/google/protobuf/internal/message_factory_test.py38
-rwxr-xr-xpython/google/protobuf/internal/message_test.py335
-rw-r--r--python/google/protobuf/internal/more_extensions_dynamic.proto1
-rwxr-xr-xpython/google/protobuf/internal/python_message.py77
-rw-r--r--python/google/protobuf/internal/python_protobuf.cc63
-rwxr-xr-xpython/google/protobuf/internal/reflection_test.py74
-rwxr-xr-xpython/google/protobuf/internal/service_reflection_test.py4
-rw-r--r--python/google/protobuf/internal/symbol_database_test.py9
-rwxr-xr-xpython/google/protobuf/internal/test_util.py64
-rwxr-xr-xpython/google/protobuf/internal/text_format_test.py298
-rwxr-xr-xpython/google/protobuf/internal/unknown_fields_test.py157
-rw-r--r--python/google/protobuf/internal/well_known_types.py66
-rw-r--r--python/google/protobuf/internal/well_known_types_test.py189
-rw-r--r--python/google/protobuf/json_format.py59
-rwxr-xr-xpython/google/protobuf/message.py16
-rw-r--r--python/google/protobuf/message_factory.py27
-rw-r--r--python/google/protobuf/pyext/descriptor.cc29
-rw-r--r--python/google/protobuf/pyext/descriptor.h2
-rw-r--r--python/google/protobuf/pyext/descriptor_pool.cc20
-rw-r--r--python/google/protobuf/pyext/descriptor_pool.h1
-rw-r--r--python/google/protobuf/pyext/extension_dict.cc7
-rw-r--r--python/google/protobuf/pyext/map_container.cc27
-rw-r--r--python/google/protobuf/pyext/message.cc220
-rw-r--r--python/google/protobuf/pyext/message_factory.cc11
-rw-r--r--python/google/protobuf/pyext/message_module.cc33
-rw-r--r--python/google/protobuf/pyext/python.proto8
-rw-r--r--python/google/protobuf/pyext/repeated_composite_container.cc54
-rw-r--r--python/google/protobuf/pyext/repeated_scalar_container.cc37
-rw-r--r--python/google/protobuf/pyext/scoped_pyobject_ptr.h59
-rw-r--r--python/google/protobuf/python_protobuf.h (renamed from python/google/protobuf/pyext/python_protobuf.h)0
-rwxr-xr-xpython/google/protobuf/reflection.py11
-rw-r--r--python/google/protobuf/symbol_database.py37
-rwxr-xr-xpython/google/protobuf/text_format.py157
-rwxr-xr-xpython/mox.py2
-rwxr-xr-xpython/release.sh114
-rw-r--r--python/release/wheel/Dockerfile6
-rw-r--r--python/release/wheel/README.md17
-rwxr-xr-xpython/release/wheel/build_wheel_manylinux.sh27
-rwxr-xr-xpython/release/wheel/protobuf_optimized_pip.sh69
-rwxr-xr-xpython/setup.py11
-rw-r--r--python/tox.ini3
-rw-r--r--ruby/Rakefile12
-rw-r--r--ruby/compatibility_tests/v3.0.0/README.md5
-rw-r--r--ruby/compatibility_tests/v3.0.0/Rakefile25
-rwxr-xr-xruby/compatibility_tests/v3.0.0/test.sh17
-rw-r--r--ruby/compatibility_tests/v3.0.0/tests/basic.rb1182
-rw-r--r--ruby/compatibility_tests/v3.0.0/tests/generated_code.proto67
-rw-r--r--ruby/compatibility_tests/v3.0.0/tests/generated_code_test.rb19
-rw-r--r--ruby/compatibility_tests/v3.0.0/tests/repeated_field_test.rb640
-rw-r--r--ruby/compatibility_tests/v3.0.0/tests/stress.rb38
-rw-r--r--ruby/compatibility_tests/v3.0.0/tests/test_import.proto5
-rw-r--r--ruby/ext/google/protobuf_c/defs.c21
-rw-r--r--ruby/ext/google/protobuf_c/encode_decode.c219
-rw-r--r--ruby/ext/google/protobuf_c/extconf.rb9
-rw-r--r--ruby/ext/google/protobuf_c/map.c39
-rw-r--r--ruby/ext/google/protobuf_c/message.c63
-rw-r--r--ruby/ext/google/protobuf_c/protobuf.c4
-rw-r--r--ruby/ext/google/protobuf_c/protobuf.h25
-rw-r--r--ruby/ext/google/protobuf_c/storage.c13
-rw-r--r--ruby/ext/google/protobuf_c/upb.c4789
-rw-r--r--ruby/ext/google/protobuf_c/upb.h1888
-rw-r--r--ruby/ext/google/protobuf_c/wrap_memcpy.c51
-rw-r--r--ruby/google-protobuf.gemspec8
-rw-r--r--ruby/lib/google/protobuf/well_known_types.rb2
-rw-r--r--ruby/pom.xml4
-rw-r--r--ruby/src/main/java/com/google/protobuf/jruby/RubyMessage.java57
-rw-r--r--ruby/tests/basic.rb220
-rw-r--r--ruby/tests/gc_test.rb58
-rw-r--r--ruby/tests/well_known_types_test.rb12
-rwxr-xr-xruby/travis-test.sh4
-rw-r--r--src/Makefile.am132
-rw-r--r--src/google/protobuf/any.h6
-rw-r--r--src/google/protobuf/any.pb.cc279
-rw-r--r--src/google/protobuf/any.pb.h94
-rw-r--r--src/google/protobuf/any.proto10
-rw-r--r--src/google/protobuf/api.pb.cc1182
-rw-r--r--src/google/protobuf/api.pb.h365
-rw-r--r--src/google/protobuf/api.proto50
-rwxr-xr-xsrc/google/protobuf/arena.cc415
-rw-r--r--src/google/protobuf/arena.h699
-rw-r--r--src/google/protobuf/arena_impl.h242
-rw-r--r--src/google/protobuf/arena_unittest.cc60
-rw-r--r--src/google/protobuf/arenastring.cc10
-rwxr-xr-xsrc/google/protobuf/arenastring.h69
-rw-r--r--src/google/protobuf/arenastring_unittest.cc41
-rw-r--r--src/google/protobuf/compiler/annotation_test_util.cc187
-rw-r--r--src/google/protobuf/compiler/annotation_test_util.h119
-rw-r--r--src/google/protobuf/compiler/code_generator.h10
-rw-r--r--src/google/protobuf/compiler/command_line_interface.cc614
-rw-r--r--src/google/protobuf/compiler/command_line_interface.h72
-rw-r--r--src/google/protobuf/compiler/command_line_interface_unittest.cc608
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc5
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_enum.cc77
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_enum.h11
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_enum_field.cc143
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_enum_field.h9
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_extension.cc43
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_extension.h3
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_field.cc9
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_field.h11
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_file.cc1086
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_file.h47
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_generator.cc35
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_helpers.cc365
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_helpers.h234
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_map_field.cc108
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_map_field.h5
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_message.cc2223
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_message.h71
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_message_field.cc920
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_message_field.h21
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_message_layout_helper.h61
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_move_unittest.cc169
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_options.h16
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_padding_optimizer.cc220
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_padding_optimizer.h64
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc2
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_primitive_field.cc149
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_primitive_field.h9
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_service.cc7
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_string_field.cc467
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_string_field.h11
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_test_bad_identifiers.proto4
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_unittest.cc206
-rw-r--r--src/google/protobuf/compiler/cpp/metadata_test.cc113
-rw-r--r--src/google/protobuf/compiler/csharp/csharp_bootstrap_unittest.cc200
-rw-r--r--src/google/protobuf/compiler/csharp/csharp_enum.cc17
-rw-r--r--src/google/protobuf/compiler/csharp/csharp_enum_field.cc4
-rw-r--r--src/google/protobuf/compiler/csharp/csharp_enum_field.h1
-rw-r--r--src/google/protobuf/compiler/csharp/csharp_field_base.cc18
-rw-r--r--src/google/protobuf/compiler/csharp/csharp_field_base.h6
-rw-r--r--src/google/protobuf/compiler/csharp/csharp_generator.h2
-rw-r--r--src/google/protobuf/compiler/csharp/csharp_helpers.h16
-rw-r--r--src/google/protobuf/compiler/csharp/csharp_message.cc48
-rw-r--r--src/google/protobuf/compiler/csharp/csharp_message.h2
-rw-r--r--src/google/protobuf/compiler/csharp/csharp_message_field.cc8
-rw-r--r--src/google/protobuf/compiler/csharp/csharp_message_field.h1
-rw-r--r--src/google/protobuf/compiler/csharp/csharp_primitive_field.cc4
-rw-r--r--src/google/protobuf/compiler/csharp/csharp_primitive_field.h1
-rw-r--r--src/google/protobuf/compiler/csharp/csharp_wrapper_field.cc4
-rw-r--r--src/google/protobuf/compiler/csharp/csharp_wrapper_field.h1
-rw-r--r--src/google/protobuf/compiler/importer.cc28
-rw-r--r--src/google/protobuf/compiler/importer.h1
-rw-r--r--src/google/protobuf/compiler/importer_unittest.cc2
-rw-r--r--src/google/protobuf/compiler/java/java_context.cc4
-rw-r--r--src/google/protobuf/compiler/java/java_context.h2
-rw-r--r--src/google/protobuf/compiler/java/java_enum.cc12
-rw-r--r--src/google/protobuf/compiler/java/java_enum_field.cc134
-rw-r--r--src/google/protobuf/compiler/java/java_enum_field_lite.cc138
-rw-r--r--src/google/protobuf/compiler/java/java_enum_lite.cc61
-rw-r--r--src/google/protobuf/compiler/java/java_extension.cc2
-rw-r--r--src/google/protobuf/compiler/java/java_field.cc63
-rw-r--r--src/google/protobuf/compiler/java/java_field.h1
-rw-r--r--src/google/protobuf/compiler/java/java_file.cc79
-rw-r--r--src/google/protobuf/compiler/java/java_generator.cc2
-rw-r--r--src/google/protobuf/compiler/java/java_helpers.cc144
-rw-r--r--src/google/protobuf/compiler/java/java_helpers.h52
-rw-r--r--src/google/protobuf/compiler/java/java_lazy_message_field_lite.cc3
-rw-r--r--src/google/protobuf/compiler/java/java_lazy_message_field_lite.h3
-rw-r--r--src/google/protobuf/compiler/java/java_map_field.cc201
-rw-r--r--src/google/protobuf/compiler/java/java_map_field_lite.cc158
-rw-r--r--src/google/protobuf/compiler/java/java_map_field_lite.h1
-rw-r--r--src/google/protobuf/compiler/java/java_message.cc285
-rw-r--r--src/google/protobuf/compiler/java/java_message_builder.cc54
-rw-r--r--src/google/protobuf/compiler/java/java_message_builder_lite.cc7
-rw-r--r--src/google/protobuf/compiler/java/java_message_field.cc171
-rw-r--r--src/google/protobuf/compiler/java/java_message_field_lite.cc148
-rw-r--r--src/google/protobuf/compiler/java/java_message_field_lite.h2
-rw-r--r--src/google/protobuf/compiler/java/java_message_lite.cc393
-rw-r--r--src/google/protobuf/compiler/java/java_name_resolver.cc1
-rw-r--r--src/google/protobuf/compiler/java/java_options.h4
-rw-r--r--src/google/protobuf/compiler/java/java_primitive_field.cc92
-rw-r--r--src/google/protobuf/compiler/java/java_primitive_field_lite.cc77
-rw-r--r--src/google/protobuf/compiler/java/java_primitive_field_lite.h3
-rw-r--r--src/google/protobuf/compiler/java/java_shared_code_generator.cc32
-rw-r--r--src/google/protobuf/compiler/java/java_shared_code_generator.h5
-rw-r--r--src/google/protobuf/compiler/java/java_string_field.cc95
-rw-r--r--src/google/protobuf/compiler/java/java_string_field_lite.cc134
-rw-r--r--src/google/protobuf/compiler/java/java_string_field_lite.h3
-rw-r--r--src/google/protobuf/compiler/javanano/javanano_enum_field.cc2
-rw-r--r--src/google/protobuf/compiler/javanano/javanano_enum_field.h6
-rw-r--r--src/google/protobuf/compiler/javanano/javanano_extension.cc2
-rw-r--r--src/google/protobuf/compiler/javanano/javanano_extension.h2
-rw-r--r--src/google/protobuf/compiler/javanano/javanano_field.cc6
-rw-r--r--src/google/protobuf/compiler/javanano/javanano_field.h6
-rw-r--r--src/google/protobuf/compiler/javanano/javanano_file.cc6
-rw-r--r--src/google/protobuf/compiler/javanano/javanano_helpers.cc10
-rw-r--r--src/google/protobuf/compiler/javanano/javanano_helpers.h2
-rw-r--r--src/google/protobuf/compiler/javanano/javanano_map_field.cc2
-rw-r--r--src/google/protobuf/compiler/javanano/javanano_map_field.h2
-rw-r--r--src/google/protobuf/compiler/javanano/javanano_message.cc4
-rw-r--r--src/google/protobuf/compiler/javanano/javanano_message_field.cc2
-rw-r--r--src/google/protobuf/compiler/javanano/javanano_message_field.h6
-rw-r--r--src/google/protobuf/compiler/javanano/javanano_params.h4
-rw-r--r--src/google/protobuf/compiler/javanano/javanano_primitive_field.cc2
-rw-r--r--src/google/protobuf/compiler/javanano/javanano_primitive_field.h8
-rw-r--r--src/google/protobuf/compiler/js/embed.cc17
-rwxr-xr-xsrc/google/protobuf/compiler/js/js_generator.cc459
-rwxr-xr-xsrc/google/protobuf/compiler/js/js_generator.h6
-rw-r--r--src/google/protobuf/compiler/js/well_known_types/any.js2
-rw-r--r--src/google/protobuf/compiler/js/well_known_types/timestamp.js1
-rwxr-xr-xsrc/google/protobuf/compiler/js/well_known_types_embed.cc314
-rw-r--r--src/google/protobuf/compiler/mock_code_generator.cc83
-rw-r--r--src/google/protobuf/compiler/mock_code_generator.h8
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_enum_field.cc4
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_enum_field.h2
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_extension.cc10
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_field.cc8
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_field.h4
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_file.cc14
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_helpers.cc99
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_helpers.h6
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_map_field.cc2
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_map_field.h2
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_message.cc10
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_message.h2
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_message_field.cc6
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_message_field.h4
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_oneof.h2
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_primitive_field.cc2
-rw-r--r--src/google/protobuf/compiler/parser.cc156
-rw-r--r--src/google/protobuf/compiler/parser.h6
-rw-r--r--src/google/protobuf/compiler/parser_unittest.cc236
-rw-r--r--src/google/protobuf/compiler/php/php_generator.cc519
-rw-r--r--src/google/protobuf/compiler/plugin.cc19
-rw-r--r--src/google/protobuf/compiler/plugin.pb.cc1350
-rw-r--r--src/google/protobuf/compiler/plugin.pb.h459
-rw-r--r--src/google/protobuf/compiler/plugin.proto6
-rw-r--r--src/google/protobuf/compiler/python/python_generator.cc63
-rw-r--r--src/google/protobuf/compiler/python/python_generator.h4
-rw-r--r--src/google/protobuf/compiler/subprocess.cc17
-rw-r--r--src/google/protobuf/compiler/subprocess.h1
-rw-r--r--src/google/protobuf/compiler/test_plugin.cc1
-rwxr-xr-xsrc/google/protobuf/compiler/zip_output_unittest.sh17
-rw-r--r--src/google/protobuf/compiler/zip_writer.cc8
-rw-r--r--src/google/protobuf/descriptor.cc1078
-rw-r--r--src/google/protobuf/descriptor.h308
-rw-r--r--src/google/protobuf/descriptor.pb.cc12019
-rw-r--r--src/google/protobuf/descriptor.pb.h5403
-rw-r--r--src/google/protobuf/descriptor.proto72
-rw-r--r--src/google/protobuf/descriptor_database.cc9
-rw-r--r--src/google/protobuf/descriptor_database.h12
-rw-r--r--src/google/protobuf/descriptor_database_unittest.cc5
-rw-r--r--src/google/protobuf/descriptor_unittest.cc632
-rw-r--r--src/google/protobuf/drop_unknown_fields_test.cc50
-rw-r--r--src/google/protobuf/duration.pb.cc241
-rw-r--r--src/google/protobuf/duration.pb.h72
-rw-r--r--src/google/protobuf/duration.proto15
-rw-r--r--src/google/protobuf/dynamic_message.cc117
-rw-r--r--src/google/protobuf/dynamic_message.h86
-rw-r--r--src/google/protobuf/empty.pb.cc185
-rw-r--r--src/google/protobuf/empty.pb.h72
-rw-r--r--src/google/protobuf/extension_set.cc2
-rw-r--r--src/google/protobuf/extension_set.h73
-rw-r--r--src/google/protobuf/extension_set_heavy.cc71
-rw-r--r--src/google/protobuf/extension_set_unittest.cc3
-rw-r--r--src/google/protobuf/field_mask.pb.cc249
-rw-r--r--src/google/protobuf/field_mask.pb.h90
-rw-r--r--src/google/protobuf/field_mask.proto6
-rw-r--r--src/google/protobuf/generated_message_reflection.cc252
-rw-r--r--src/google/protobuf/generated_message_reflection.h151
-rw-r--r--src/google/protobuf/generated_message_reflection_unittest.cc126
-rw-r--r--src/google/protobuf/generated_message_table_driven.cc103
-rw-r--r--src/google/protobuf/generated_message_table_driven.h219
-rw-r--r--src/google/protobuf/generated_message_table_driven_lite.cc109
-rw-r--r--src/google/protobuf/generated_message_table_driven_lite.h823
-rw-r--r--src/google/protobuf/generated_message_util.cc654
-rw-r--r--src/google/protobuf/generated_message_util.h301
-rw-r--r--src/google/protobuf/has_bits.h41
-rw-r--r--src/google/protobuf/implicit_weak_message.cc51
-rw-r--r--src/google/protobuf/implicit_weak_message.h89
-rw-r--r--src/google/protobuf/io/coded_stream.cc84
-rw-r--r--src/google/protobuf/io/coded_stream.h195
-rw-r--r--src/google/protobuf/io/coded_stream_unittest.cc33
-rw-r--r--src/google/protobuf/io/printer.cc32
-rw-r--r--src/google/protobuf/io/printer.h10
-rw-r--r--src/google/protobuf/io/printer_unittest.cc77
-rw-r--r--src/google/protobuf/io/tokenizer_unittest.cc17
-rw-r--r--src/google/protobuf/io/zero_copy_stream.cc3
-rw-r--r--src/google/protobuf/io/zero_copy_stream.h8
-rw-r--r--src/google/protobuf/io/zero_copy_stream_impl.cc45
-rw-r--r--src/google/protobuf/io/zero_copy_stream_impl.h3
-rw-r--r--src/google/protobuf/io/zero_copy_stream_impl_lite.cc37
-rw-r--r--src/google/protobuf/io/zero_copy_stream_impl_lite.h30
-rw-r--r--src/google/protobuf/io/zero_copy_stream_unittest.cc18
-rw-r--r--src/google/protobuf/lite_arena_unittest.cc32
-rw-r--r--src/google/protobuf/lite_unittest.cc341
-rw-r--r--src/google/protobuf/map.h773
-rw-r--r--src/google/protobuf/map_entry.h256
-rw-r--r--src/google/protobuf/map_entry_lite.h315
-rw-r--r--src/google/protobuf/map_field.cc59
-rw-r--r--src/google/protobuf/map_field.h563
-rw-r--r--src/google/protobuf/map_field_inl.h308
-rw-r--r--src/google/protobuf/map_field_lite.h246
-rw-r--r--src/google/protobuf/map_field_test.cc51
-rw-r--r--src/google/protobuf/map_proto2_unittest.proto5
-rw-r--r--src/google/protobuf/map_test.cc397
-rw-r--r--src/google/protobuf/map_test_util.cc28
-rw-r--r--src/google/protobuf/map_test_util.h7
-rw-r--r--src/google/protobuf/map_test_util_impl.h41
-rw-r--r--src/google/protobuf/map_type_handler.h130
-rw-r--r--src/google/protobuf/map_unittest.proto1
-rw-r--r--src/google/protobuf/message.cc42
-rw-r--r--src/google/protobuf/message.h65
-rw-r--r--src/google/protobuf/message_lite.cc64
-rw-r--r--src/google/protobuf/message_lite.h196
-rw-r--r--src/google/protobuf/message_unittest.cc85
-rw-r--r--src/google/protobuf/metadata.h155
-rw-r--r--src/google/protobuf/metadata_lite.h224
-rw-r--r--src/google/protobuf/proto3_arena_unittest.cc25
-rwxr-xr-xsrc/google/protobuf/reflection.h4
-rw-r--r--src/google/protobuf/reflection_ops.cc22
-rw-r--r--src/google/protobuf/reflection_ops_unittest.cc1
-rw-r--r--src/google/protobuf/repeated_field.h341
-rw-r--r--src/google/protobuf/repeated_field_reflection_unittest.cc39
-rw-r--r--src/google/protobuf/repeated_field_unittest.cc328
-rw-r--r--src/google/protobuf/source_context.pb.cc230
-rw-r--r--src/google/protobuf/source_context.pb.h82
-rw-r--r--src/google/protobuf/struct.pb.cc1049
-rw-r--r--src/google/protobuf/struct.pb.h365
-rw-r--r--src/google/protobuf/stubs/atomicops.h46
-rw-r--r--src/google/protobuf/stubs/atomicops_internals_macosx.h225
-rw-r--r--src/google/protobuf/stubs/bytestream.h2
-rw-r--r--src/google/protobuf/stubs/callback.h30
-rwxr-xr-x[-rw-r--r--]src/google/protobuf/stubs/common.cc53
-rw-r--r--src/google/protobuf/stubs/common.h26
-rw-r--r--src/google/protobuf/stubs/fastmem.h3
-rw-r--r--src/google/protobuf/stubs/hash.h11
-rw-r--r--src/google/protobuf/stubs/int128_unittest.cc14
-rw-r--r--src/google/protobuf/stubs/io_win32.cc362
-rw-r--r--src/google/protobuf/stubs/io_win32.h104
-rw-r--r--src/google/protobuf/stubs/io_win32_unittest.cc373
-rw-r--r--src/google/protobuf/stubs/mathlimits.h17
-rw-r--r--src/google/protobuf/stubs/mutex.h8
-rw-r--r--src/google/protobuf/stubs/port.h116
-rw-r--r--src/google/protobuf/stubs/shared_ptr.h7
-rw-r--r--src/google/protobuf/stubs/stringpiece.h20
-rw-r--r--src/google/protobuf/stubs/stringpiece_unittest.cc2
-rw-r--r--src/google/protobuf/stubs/strutil.cc14
-rw-r--r--src/google/protobuf/test_messages_proto2.proto216
-rw-r--r--src/google/protobuf/test_messages_proto3.proto10
-rw-r--r--src/google/protobuf/test_util_lite.cc7
-rw-r--r--src/google/protobuf/testing/file.cc20
-rw-r--r--src/google/protobuf/testing/googletest.cc40
-rw-r--r--src/google/protobuf/testing/googletest.h7
-rw-r--r--src/google/protobuf/testing/zcgunzip.cc5
-rw-r--r--src/google/protobuf/text_format.cc676
-rw-r--r--src/google/protobuf/text_format.h115
-rw-r--r--src/google/protobuf/text_format_unittest.cc21
-rw-r--r--src/google/protobuf/timestamp.pb.cc241
-rw-r--r--src/google/protobuf/timestamp.pb.h72
-rw-r--r--src/google/protobuf/timestamp.proto25
-rw-r--r--src/google/protobuf/type.pb.cc2200
-rw-r--r--src/google/protobuf/type.pb.h836
-rw-r--r--src/google/protobuf/type.proto10
-rw-r--r--src/google/protobuf/unittest.proto26
-rw-r--r--src/google/protobuf/unittest_lazy_dependencies.proto75
-rw-r--r--src/google/protobuf/unittest_lazy_dependencies_custom_option.proto67
-rw-r--r--src/google/protobuf/unittest_lazy_dependencies_enum.proto61
-rw-r--r--src/google/protobuf/unittest_lite.proto15
-rw-r--r--src/google/protobuf/unittest_proto3.proto360
-rw-r--r--src/google/protobuf/unittest_proto3_arena.proto4
-rw-r--r--src/google/protobuf/unknown_field_set.cc48
-rw-r--r--src/google/protobuf/unknown_field_set.h49
-rw-r--r--src/google/protobuf/util/delimited_message_util.cc79
-rw-r--r--src/google/protobuf/util/delimited_message_util.h66
-rw-r--r--src/google/protobuf/util/delimited_message_util_test.cc57
-rw-r--r--src/google/protobuf/util/field_comparator.h2
-rw-r--r--src/google/protobuf/util/field_mask_util.cc148
-rw-r--r--src/google/protobuf/util/field_mask_util.h35
-rw-r--r--src/google/protobuf/util/field_mask_util_test.cc120
-rw-r--r--src/google/protobuf/util/internal/default_value_objectwriter.cc92
-rw-r--r--src/google/protobuf/util/internal/default_value_objectwriter.h55
-rw-r--r--src/google/protobuf/util/internal/field_mask_utility.cc7
-rw-r--r--src/google/protobuf/util/internal/json_escaping.cc56
-rw-r--r--src/google/protobuf/util/internal/json_escaping.h2
-rw-r--r--src/google/protobuf/util/internal/json_stream_parser.cc131
-rw-r--r--src/google/protobuf/util/internal/json_stream_parser.h3
-rw-r--r--src/google/protobuf/util/internal/json_stream_parser_test.cc17
-rw-r--r--src/google/protobuf/util/internal/proto_writer.h28
-rw-r--r--src/google/protobuf/util/internal/protostream_objectsource.cc77
-rw-r--r--src/google/protobuf/util/internal/protostream_objectsource.h18
-rw-r--r--src/google/protobuf/util/internal/protostream_objectsource_test.cc50
-rw-r--r--src/google/protobuf/util/internal/protostream_objectwriter.cc46
-rw-r--r--src/google/protobuf/util/internal/protostream_objectwriter.h11
-rw-r--r--src/google/protobuf/util/internal/protostream_objectwriter_test.cc20
-rw-r--r--src/google/protobuf/util/internal/testdata/books.proto9
-rw-r--r--src/google/protobuf/util/internal/type_info.cc28
-rw-r--r--src/google/protobuf/util/internal/utility.cc46
-rw-r--r--src/google/protobuf/util/json_format_proto3.proto2
-rw-r--r--src/google/protobuf/util/json_util.cc38
-rw-r--r--src/google/protobuf/util/json_util.h20
-rw-r--r--src/google/protobuf/util/json_util_test.cc91
-rw-r--r--src/google/protobuf/util/message_differencer.cc125
-rw-r--r--src/google/protobuf/util/message_differencer.h75
-rwxr-xr-xsrc/google/protobuf/util/message_differencer_unittest.cc187
-rw-r--r--src/google/protobuf/util/time_util.cc30
-rw-r--r--src/google/protobuf/util/time_util.h4
-rw-r--r--src/google/protobuf/wire_format.cc338
-rw-r--r--src/google/protobuf/wire_format.h9
-rw-r--r--src/google/protobuf/wire_format_lite.cc243
-rw-r--r--src/google/protobuf/wire_format_lite.h493
-rw-r--r--src/google/protobuf/wire_format_lite_inl.h224
-rw-r--r--src/google/protobuf/wire_format_unittest.cc153
-rw-r--r--src/google/protobuf/wrappers.pb.cc1366
-rw-r--r--src/google/protobuf/wrappers.pb.h424
-rw-r--r--src/libprotobuf-lite.map9
-rw-r--r--src/libprotobuf.map9
-rw-r--r--src/libprotoc.map9
-rwxr-xr-xtests.sh253
m---------third_party/benchmark0
-rwxr-xr-xupdate_file_lists.sh2
1103 files changed, 118659 insertions, 43627 deletions
diff --git a/.gitignore b/.gitignore
index 4383c623..af88e226 100644
--- a/.gitignore
+++ b/.gitignore
@@ -47,6 +47,7 @@ any_test.pb.*
map*unittest.pb.*
unittest*.pb.*
cpp_test*.pb.*
+src/google/protobuf/compiler/js/well_known_types_embed.cc
src/google/protobuf/util/**/*.pb.cc
src/google/protobuf/util/**/*.pb.h
@@ -60,9 +61,13 @@ python/build/
python/google/protobuf/compiler/
python/google/protobuf/util/
+src/js_embed
src/protoc
src/unittest_proto_middleman
+# vim generated
+*.swp
+
# Generated test scaffolding
src/no_warning_test.cc
src/no-warning-test
@@ -82,6 +87,8 @@ src/**/*.trs
java/core/target
java/util/target
javanano/target
+java/.idea
+java/**/*.iml
# Windows native output.
cmake/build
@@ -111,18 +118,29 @@ conformance/conformance.pb.cc
conformance/conformance.pb.h
conformance/Conformance.pbobjc.h
conformance/Conformance.pbobjc.m
+conformance/conformance_pb.js
conformance/conformance_pb.rb
conformance/failing_tests.txt
conformance/google/
+conformance/google-protobuf/
conformance/javac_middleman
conformance/lite/
conformance/nonexistent_tests.txt
conformance/protoc_middleman
conformance/succeeding_tests.txt
+conformance/Conformance/
+conformance/GPBMetadata/
+conformance/Google/
+conformance/Protobuf_test_messages/
+conformance/conformance-php
+conformance/conformance-php-c
+conformance/*.class
# php test output
composer.lock
php/tests/generated/
+php/tests/old_protoc
+php/tests/protobuf/
php/ext/google/protobuf/.libs/
php/ext/google/protobuf/Makefile.fragments
php/ext/google/protobuf/Makefile.global
@@ -138,8 +156,27 @@ vendor/
# JavaScript artifacts
js/commonjs_out/
+js/compatibility_tests/v3.0.0/commonjs_out*
+js/compatibility_tests/v3.0.0/protoc
+js/compatibility_tests/v3.0.0/testproto_libs1.js
+js/compatibility_tests/v3.0.0/testproto_libs1_new.js
+js/compatibility_tests/v3.0.0/testproto_libs2.js
+js/compatibility_tests/v3.0.0/testproto_libs2_new.js
js/deps.js
js/google-protobuf.js
js/google/
js/node_modules/
-js/testproto_libs.js
+js/testproto_libs1.js
+js/testproto_libs2.js
+
+# Ignore the bazel symlinks
+/bazel-*
+
+# ruby test output
+ruby/lib/
+ruby/tests/generated_code_pb.rb
+ruby/tests/test_import_pb.rb
+ruby/Gemfile.lock
+ruby/compatibility_tests/v3.0.0/protoc
+ruby/compatibility_tests/v3.0.0/tests/generated_code_pb.rb
+ruby/compatibility_tests/v3.0.0/tests/test_import_pb.rb
diff --git a/.travis.yml b/.travis.yml
index a34cb83b..4cfc5bf0 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,60 +1,75 @@
-sudo: required
-dist: trusty
-# Note: travis currently does not support listing more than one language so
-# this cheats and claims to only be cpp. If they add multiple language
-# support, this should probably get updated to install steps and/or
-# rvm/gemfile/jdk/etc. entries rather than manually doing the work.
+# Everything is driven by the test.sh, so the language doesn't really
+# matter, it just controls the default install/script/etc. steps on
+# travis.
language: cpp
-os:
- - osx
-# The Objective C build needs Xcode 7.0 or later.
-osx_image: xcode8.1
-script:
- - ./tests.sh $CONFIG
-env:
- - CONFIG=cpp
- - CONFIG=cpp_distcheck
- - CONFIG=golang
- - CONFIG=java_jdk7
- - CONFIG=java_oracle7
- - CONFIG=javanano_jdk7
- - CONFIG=javanano_oracle7
- - CONFIG=javascript
- # iOS build log was starting to choke travis UI, so split to cover the
- # Xcode Debug and Release Configurations independently.
- - CONFIG=objectivec_ios_debug
- - CONFIG=objectivec_ios_release
- - CONFIG=objectivec_osx
- - CONFIG=objectivec_cocoapods_integration
- - CONFIG=python
- - CONFIG=python_cpp
- - CONFIG=ruby21
- - CONFIG=ruby22
- - CONFIG=jruby
- - CONFIG=php5.6_mac
+script: ./tests.sh $CONFIG
+
+# The test matrix is manually built to cover a mix of linux and macOS
+# hosted setups; this lets some extra settings be done specific to each
+# host/language instead of forcing common values on all the tests.
matrix:
- exclude:
- # It's nontrivial to programmatically install a new JDK from the command
- # line on OS X, so we rely on testing on Linux for Java code.
+ include:
+ # -----------------------------------------------------------------
+ # macOS hosted tests for Objective-C
+
+ - os: osx
+ env: CONFIG=objectivec_osx
+ osx_image: xcode9.1
+ language: objective-c
+ # iOS build log was starting to choke travis UI, so split to cover the
+ # Xcode Debug and Release Configurations independently.
- os: osx
- env: CONFIG=java_jdk7
+ env: CONFIG=objectivec_ios_debug
+ osx_image: xcode9.1
+ language: objective-c
- os: osx
- env: CONFIG=java_oracle7
+ env: CONFIG=objectivec_ios_release
+ osx_image: xcode9.1
+ language: objective-c
- os: osx
- env: CONFIG=javanano_jdk7
+ env: CONFIG=objectivec_cocoapods_integration
+ osx_image: xcode9.1
+ language: objective-c
+
+ # -----------------------------------------------------------------
+ # macOS hosted tests for other languages.
+
- os: osx
- env: CONFIG=javanano_oracle7
- # Requires installing golang, currently travis.sh is doing that with apt-get
- # which doesn't work on OS X.
+ env: CONFIG=cpp
- os: osx
- env: CONFIG=golang
- include:
+ env: CONFIG=cpp_distcheck
+ - os: osx
+ env: CONFIG=javascript
+ - os: osx
+ env: CONFIG=python
+ - os: osx
+ env: CONFIG=python_cpp
+ - os: osx
+ env: CONFIG=php5.6_mac
+ # Xcode versions force a host version of macOS:
+ # https://docs.travis-ci.com/user/reference/osx/#OS-X-Version
+ # Force macOS 10.12, the default travis image is going to be
+ # updated "soon", at which point this came come out:
+ # https://blog.travis-ci.com/2017-10-16-a-new-default-os-x-image-is-coming
+ osx_image: xcode8.3
+ - os: osx
+ env: CONFIG=php7.0_mac
+ # Same note about macOS version as on the php5.6_mac config.
+ osx_image: xcode8.3
+
+ # -----------------------------------------------------------------
+ # Linux hosted tests
+
# The dotnet environment requires Ubuntu 14.04 or 16.04. This
# configuration is effectively an "extra" one, outside the
# autogenerated matrix.
- os: linux
env: CONFIG=csharp
+ language: csharp
dist: trusty
+ sudo: required
+ dotnet: 1.0.4
+ mono: none
# This test is kept on travis because it doesn't play nicely with other
# tests on jenkins running in parallel.
- os: linux
@@ -63,21 +78,14 @@ matrix:
# fetch pre-built Linux protoc binaries in the test.
- os: linux
env: CONFIG=java_compatibility
- allow_failures:
- # These currently do not work on OS X but are being worked on by @haberman.
- - os: osx
- env: CONFIG=ruby22
- - os: osx
- env: CONFIG=jruby
- # https://github.com/google/protobuf/issues/1253 - Started failing when
- # we moved to an OS X image that is 10.11.
- - os: osx
- env: CONFIG=python_cpp
- # Mark the iOS test as flakey as xcodebuild some times fails to start the
- # iOS Simulator.
- - os: osx
- env: CONFIG=objectivec_ios_debug
- - os: osx
- env: CONFIG=objectivec_ios_release
+ sudo: required
+ dist: trusty
+ # The Python compatibility test currently only runs on Linux because it will
+ # fetch pre-built Linux protoc binaries in the test.
+ - os: linux
+ env: CONFIG=python_compatibility
+ sudo: required
+ dist: trusty
+
notifications:
email: false
diff --git a/BUILD b/BUILD
index c9f40321..9c8fd864 100644
--- a/BUILD
+++ b/BUILD
@@ -8,15 +8,37 @@ exports_files(["LICENSE"])
# Protobuf Runtime Library
################################################################################
-COPTS = [
- "-DHAVE_PTHREAD",
- "-Wall",
- "-Wwrite-strings",
- "-Woverloaded-virtual",
- "-Wno-sign-compare",
- "-Wno-unused-function",
+WIN_COPTS = [
+ "/DHAVE_PTHREAD",
+ "/wd4018", # -Wno-sign-compare
+ "/wd4514", # -Wno-unused-function
]
+COPTS = select({
+ ":windows" : WIN_COPTS,
+ ":windows_msvc" : WIN_COPTS,
+ "//conditions:default": [
+ "-DHAVE_PTHREAD",
+ "-Wall",
+ "-Wwrite-strings",
+ "-Woverloaded-virtual",
+ "-Wno-sign-compare",
+ "-Wno-unused-function",
+ # Prevents ISO C++ const string assignment warnings for pyext sources.
+ "-Wno-writable-strings",
+ ],
+})
+
+config_setting(
+ name = "windows",
+ values = { "cpu": "x64_windows" },
+)
+
+config_setting(
+ name = "windows_msvc",
+ values = { "cpu": "x64_windows_msvc" },
+)
+
config_setting(
name = "android",
values = {
@@ -24,14 +46,16 @@ config_setting(
},
)
-# Android builds do not need to link in a separate pthread library.
+# Android and Windows builds do not need to link in a separate pthread library.
LINK_OPTS = select({
":android": [],
- "//conditions:default": ["-lpthread"],
+ ":windows": [],
+ ":windows_msvc": [],
+ "//conditions:default": ["-lpthread", "-lm"],
})
load(
- "protobuf",
+ ":protobuf.bzl",
"cc_proto_library",
"py_proto_library",
"internal_copied_filegroup",
@@ -39,37 +63,6 @@ load(
"internal_protobuf_py_tests",
)
-config_setting(
- name = "ios_armv7",
- values = {
- "ios_cpu": "armv7",
- },
-)
-
-config_setting(
- name = "ios_armv7s",
- values = {
- "ios_cpu": "armv7s",
- },
-)
-
-config_setting(
- name = "ios_arm64",
- values = {
- "ios_cpu": "arm64",
- },
-)
-
-IOS_ARM_COPTS = COPTS + [
- "-DOS_IOS",
- "-miphoneos-version-min=7.0",
- "-arch armv7",
- "-arch armv7s",
- "-arch arm64",
- "-D__thread=",
- "-isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.2.sdk/",
-]
-
cc_library(
name = "protobuf_lite",
srcs = [
@@ -77,6 +70,7 @@ cc_library(
"src/google/protobuf/arena.cc",
"src/google/protobuf/arenastring.cc",
"src/google/protobuf/extension_set.cc",
+ "src/google/protobuf/generated_message_table_driven_lite.cc",
"src/google/protobuf/generated_message_util.cc",
"src/google/protobuf/io/coded_stream.cc",
"src/google/protobuf/io/zero_copy_stream.cc",
@@ -88,6 +82,7 @@ cc_library(
"src/google/protobuf/stubs/bytestream.cc",
"src/google/protobuf/stubs/common.cc",
"src/google/protobuf/stubs/int128.cc",
+ "src/google/protobuf/stubs/io_win32.cc",
"src/google/protobuf/stubs/once.cc",
"src/google/protobuf/stubs/status.cc",
"src/google/protobuf/stubs/statusor.cc",
@@ -99,12 +94,7 @@ cc_library(
"src/google/protobuf/wire_format_lite.cc",
],
hdrs = glob(["src/google/protobuf/**/*.h"]),
- copts = select({
- ":ios_armv7": IOS_ARM_COPTS,
- ":ios_armv7s": IOS_ARM_COPTS,
- ":ios_arm64": IOS_ARM_COPTS,
- "//conditions:default": COPTS,
- }),
+ copts = COPTS,
includes = ["src/"],
linkopts = LINK_OPTS,
visibility = ["//visibility:public"],
@@ -128,6 +118,7 @@ cc_library(
"src/google/protobuf/extension_set_heavy.cc",
"src/google/protobuf/field_mask.pb.cc",
"src/google/protobuf/generated_message_reflection.cc",
+ "src/google/protobuf/generated_message_table_driven.cc",
"src/google/protobuf/io/gzip_stream.cc",
"src/google/protobuf/io/printer.cc",
"src/google/protobuf/io/strtod.cc",
@@ -145,6 +136,7 @@ cc_library(
"src/google/protobuf/timestamp.pb.cc",
"src/google/protobuf/type.pb.cc",
"src/google/protobuf/unknown_field_set.cc",
+ "src/google/protobuf/util/delimited_message_util.cc",
"src/google/protobuf/util/field_comparator.cc",
"src/google/protobuf/util/field_mask_util.cc",
"src/google/protobuf/util/internal/datapiece.cc",
@@ -169,18 +161,24 @@ cc_library(
"src/google/protobuf/wrappers.pb.cc",
],
hdrs = glob(["src/**/*.h"]),
- copts = select({
- ":ios_armv7": IOS_ARM_COPTS,
- ":ios_armv7s": IOS_ARM_COPTS,
- ":ios_arm64": IOS_ARM_COPTS,
- "//conditions:default": COPTS,
- }),
+ copts = COPTS,
includes = ["src/"],
linkopts = LINK_OPTS,
visibility = ["//visibility:public"],
deps = [":protobuf_lite"],
)
+# This provides just the header files for use in projects that need to build
+# shared libraries for dynamic loading. This target is available until Bazel
+# adds native support for such use cases.
+# TODO(keveman): Remove this target once the support gets added to Bazel.
+cc_library(
+ name = "protobuf_headers",
+ hdrs = glob(["src/**/*.h"]),
+ includes = ["src/"],
+ visibility = ["//visibility:public"],
+)
+
objc_library(
name = "protobuf_objc",
hdrs = ["objectivec/GPBProtocolBuffers.h"],
@@ -189,21 +187,24 @@ objc_library(
visibility = ["//visibility:public"],
)
-RELATIVE_WELL_KNOWN_PROTOS = [
- # AUTOGEN(well_known_protos)
- "google/protobuf/any.proto",
- "google/protobuf/api.proto",
- "google/protobuf/compiler/plugin.proto",
- "google/protobuf/descriptor.proto",
- "google/protobuf/duration.proto",
- "google/protobuf/empty.proto",
- "google/protobuf/field_mask.proto",
- "google/protobuf/source_context.proto",
- "google/protobuf/struct.proto",
- "google/protobuf/timestamp.proto",
- "google/protobuf/type.proto",
- "google/protobuf/wrappers.proto",
-]
+# Map of all well known protos.
+# name => (include path, imports)
+WELL_KNOWN_PROTO_MAP = {
+ "any" : ("google/protobuf/any.proto", []),
+ "api" : ("google/protobuf/api.proto", ["source_context", "type"]),
+ "compiler_plugin" : ("google/protobuf/compiler/plugin.proto", ["descriptor"]),
+ "descriptor" : ("google/protobuf/descriptor.proto", []),
+ "duration" : ("google/protobuf/duration.proto", []),
+ "empty" : ("google/protobuf/empty.proto", []),
+ "field_mask" : ("google/protobuf/field_mask.proto", []),
+ "source_context" : ("google/protobuf/source_context.proto", []),
+ "struct" : ("google/protobuf/struct.proto", []),
+ "timestamp" : ("google/protobuf/timestamp.proto", []),
+ "type" : ("google/protobuf/type.proto", ["any", "source_context"]),
+ "wrappers" : ("google/protobuf/wrappers.proto", []),
+}
+
+RELATIVE_WELL_KNOWN_PROTOS = [proto[1][0] for proto in WELL_KNOWN_PROTO_MAP.items()]
WELL_KNOWN_PROTOS = ["src/" + s for s in RELATIVE_WELL_KNOWN_PROTOS]
@@ -224,9 +225,54 @@ cc_proto_library(
)
################################################################################
+# Well Known Types Proto Library Rules
+#
+# These proto_library rules can be used with one of the language specific proto
+# library rules i.e. java_proto_library:
+#
+# java_proto_library(
+# name = "any_java_proto",
+# deps = ["@com_google_protobuf//:any_proto],
+# )
+################################################################################
+
+internal_copied_filegroup(
+ name = "_internal_wkt_protos",
+ srcs = WELL_KNOWN_PROTOS,
+ dest = "",
+ strip_prefix = "src",
+ visibility = ["//visibility:hidden"],
+)
+
+[proto_library(
+ name = proto[0] + "_proto",
+ srcs = [proto[1][0]],
+ deps = [dep + "_proto" for dep in proto[1][1]],
+ visibility = ["//visibility:public"],
+ ) for proto in WELL_KNOWN_PROTO_MAP.items()]
+
+################################################################################
# Protocol Buffers Compiler
################################################################################
+cc_binary(
+ name = "js_embed",
+ srcs = ["src/google/protobuf/compiler/js/embed.cc"],
+ visibility = ["//visibility:public"],
+)
+
+genrule(
+ name = "generate_js_well_known_types_embed",
+ srcs = [
+ "src/google/protobuf/compiler/js/well_known_types/any.js",
+ "src/google/protobuf/compiler/js/well_known_types/struct.js",
+ "src/google/protobuf/compiler/js/well_known_types/timestamp.js",
+ ],
+ outs = ["src/google/protobuf/compiler/js/well_known_types_embed.cc"],
+ cmd = "$(location :js_embed) $(SRCS) > $@",
+ tools = [":js_embed"],
+)
+
cc_library(
name = "protoc_lib",
srcs = [
@@ -243,6 +289,7 @@ cc_library(
"src/google/protobuf/compiler/cpp/cpp_map_field.cc",
"src/google/protobuf/compiler/cpp/cpp_message.cc",
"src/google/protobuf/compiler/cpp/cpp_message_field.cc",
+ "src/google/protobuf/compiler/cpp/cpp_padding_optimizer.cc",
"src/google/protobuf/compiler/cpp/cpp_primitive_field.cc",
"src/google/protobuf/compiler/cpp/cpp_service.cc",
"src/google/protobuf/compiler/cpp/cpp_string_field.cc",
@@ -371,6 +418,9 @@ RELATIVE_TEST_PROTOS = [
"google/protobuf/unittest_enormous_descriptor.proto",
"google/protobuf/unittest_import.proto",
"google/protobuf/unittest_import_public.proto",
+ "google/protobuf/unittest_lazy_dependencies.proto",
+ "google/protobuf/unittest_lazy_dependencies_custom_option.proto",
+ "google/protobuf/unittest_lazy_dependencies_enum.proto",
"google/protobuf/unittest_lite_imports_nonlite.proto",
"google/protobuf/unittest_mset.proto",
"google/protobuf/unittest_mset_wire_format.proto",
@@ -436,17 +486,30 @@ cc_binary(
)
cc_test(
+ name = "win32_test",
+ srcs = ["src/google/protobuf/stubs/io_win32_unittest.cc"],
+ deps = [
+ ":protobuf_lite",
+ "//external:gtest_main",
+ ],
+ tags = ["manual", "windows"],
+)
+
+cc_test(
name = "protobuf_test",
srcs = COMMON_TEST_SRCS + [
# AUTOGEN(test_srcs)
"src/google/protobuf/any_test.cc",
"src/google/protobuf/arena_unittest.cc",
"src/google/protobuf/arenastring_unittest.cc",
+ "src/google/protobuf/compiler/annotation_test_util.cc",
"src/google/protobuf/compiler/command_line_interface_unittest.cc",
"src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc",
+ "src/google/protobuf/compiler/cpp/cpp_move_unittest.cc",
"src/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc",
"src/google/protobuf/compiler/cpp/cpp_unittest.cc",
"src/google/protobuf/compiler/cpp/metadata_test.cc",
+ "src/google/protobuf/compiler/csharp/csharp_bootstrap_unittest.cc",
"src/google/protobuf/compiler/csharp/csharp_generator_unittest.cc",
"src/google/protobuf/compiler/importer_unittest.cc",
"src/google/protobuf/compiler/java/java_doc_comment_unittest.cc",
@@ -480,6 +543,7 @@ cc_test(
"src/google/protobuf/stubs/bytestream_unittest.cc",
"src/google/protobuf/stubs/common_unittest.cc",
"src/google/protobuf/stubs/int128_unittest.cc",
+ "src/google/protobuf/stubs/io_win32_unittest.cc",
"src/google/protobuf/stubs/once_unittest.cc",
"src/google/protobuf/stubs/status_test.cc",
"src/google/protobuf/stubs/statusor_test.cc",
@@ -492,6 +556,7 @@ cc_test(
"src/google/protobuf/stubs/type_traits_unittest.cc",
"src/google/protobuf/text_format_unittest.cc",
"src/google/protobuf/unknown_field_set_unittest.cc",
+ "src/google/protobuf/util/delimited_message_util_test.cc",
"src/google/protobuf/util/field_comparator_test.cc",
"src/google/protobuf/util/field_mask_util_test.cc",
"src/google/protobuf/util/internal/default_value_objectwriter_test.cc",
@@ -512,6 +577,9 @@ cc_test(
":test_plugin",
] + glob([
"src/google/protobuf/**/*",
+ # Files for csharp_bootstrap_unittest.cc.
+ "conformance/**/*",
+ "csharp/src/**/*",
]),
includes = [
"src/",
@@ -539,6 +607,7 @@ java_library(
]) + [
":gen_well_known_protos_java",
],
+ javacopts = ["-source 6", "-target 6"],
visibility = ["//visibility:public"],
)
@@ -547,12 +616,13 @@ java_library(
srcs = glob([
"java/util/src/main/java/com/google/protobuf/util/*.java",
]),
+ javacopts = ["-source 6", "-target 6"],
+ visibility = ["//visibility:public"],
deps = [
"protobuf_java",
"//external:gson",
"//external:guava",
],
- visibility = ["//visibility:public"],
)
################################################################################
@@ -573,8 +643,8 @@ py_library(
"python/google/protobuf/internal/test_util.py",
],
),
- srcs_version = "PY2AND3",
imports = ["python"],
+ srcs_version = "PY2AND3",
)
cc_binary(
@@ -639,8 +709,8 @@ config_setting(
internal_copied_filegroup(
name = "protos_python",
srcs = WELL_KNOWN_PROTOS,
- strip_prefix = "src",
dest = "python",
+ strip_prefix = "src",
)
# TODO(dzc): Remove this once py_proto_library can have labels in srcs, in
@@ -662,7 +732,7 @@ py_proto_library(
protoc = ":protoc",
py_libs = [
":python_srcs",
- "//external:six"
+ "//external:six",
],
srcs_version = "PY2AND3",
visibility = ["//visibility:public"],
@@ -676,13 +746,14 @@ py_proto_library(
internal_copied_filegroup(
name = "protos_python_test",
srcs = LITE_TEST_PROTOS + TEST_PROTOS,
- strip_prefix = "src",
dest = "python",
+ strip_prefix = "src",
)
# TODO(dzc): Remove this once py_proto_library can have labels in srcs, in
# which case we can simply add :protos_python_test in srcs.
COPIED_LITE_TEST_PROTOS = ["python/" + s for s in RELATIVE_LITE_TEST_PROTOS]
+
COPIED_TEST_PROTOS = ["python/" + s for s in RELATIVE_TEST_PROTOS]
py_proto_library(
@@ -752,8 +823,96 @@ internal_protobuf_py_tests(
)
proto_lang_toolchain(
- name = "cc_toolchain",
- runtime = ":protobuf",
- command_line = "--cpp_out=$(OUT)",
- visibility = ["//visibility:public"],
+ name = "cc_toolchain",
+ command_line = "--cpp_out=$(OUT)",
+ runtime = ":protobuf",
+ visibility = ["//visibility:public"],
+)
+
+proto_lang_toolchain(
+ name = "java_toolchain",
+ command_line = "--java_out=$(OUT)",
+ runtime = ":protobuf_java",
+ visibility = ["//visibility:public"],
+)
+
+OBJC_HDRS = [
+ "objectivec/GPBArray.h",
+ "objectivec/GPBBootstrap.h",
+ "objectivec/GPBCodedInputStream.h",
+ "objectivec/GPBCodedOutputStream.h",
+ "objectivec/GPBDescriptor.h",
+ "objectivec/GPBDictionary.h",
+ "objectivec/GPBExtensionInternals.h",
+ "objectivec/GPBExtensionRegistry.h",
+ "objectivec/GPBMessage.h",
+ "objectivec/GPBProtocolBuffers.h",
+ "objectivec/GPBProtocolBuffers_RuntimeSupport.h",
+ "objectivec/GPBRootObject.h",
+ "objectivec/GPBRuntimeTypes.h",
+ "objectivec/GPBUnknownField.h",
+ "objectivec/GPBUnknownFieldSet.h",
+ "objectivec/GPBUtilities.h",
+ "objectivec/GPBWellKnownTypes.h",
+ "objectivec/GPBWireFormat.h",
+ "objectivec/google/protobuf/Any.pbobjc.h",
+ "objectivec/google/protobuf/Api.pbobjc.h",
+ "objectivec/google/protobuf/Duration.pbobjc.h",
+ "objectivec/google/protobuf/Empty.pbobjc.h",
+ "objectivec/google/protobuf/FieldMask.pbobjc.h",
+ "objectivec/google/protobuf/SourceContext.pbobjc.h",
+ "objectivec/google/protobuf/Struct.pbobjc.h",
+ "objectivec/google/protobuf/Timestamp.pbobjc.h",
+ "objectivec/google/protobuf/Type.pbobjc.h",
+ "objectivec/google/protobuf/Wrappers.pbobjc.h",
+]
+
+OBJC_PRIVATE_HDRS = [
+ "objectivec/GPBArray_PackagePrivate.h",
+ "objectivec/GPBCodedInputStream_PackagePrivate.h",
+ "objectivec/GPBCodedOutputStream_PackagePrivate.h",
+ "objectivec/GPBDescriptor_PackagePrivate.h",
+ "objectivec/GPBDictionary_PackagePrivate.h",
+ "objectivec/GPBMessage_PackagePrivate.h",
+ "objectivec/GPBRootObject_PackagePrivate.h",
+ "objectivec/GPBUnknownFieldSet_PackagePrivate.h",
+ "objectivec/GPBUnknownField_PackagePrivate.h",
+ "objectivec/GPBUtilities_PackagePrivate.h",
+]
+
+OBJC_SRCS = [
+ "objectivec/GPBArray.m",
+ "objectivec/GPBCodedInputStream.m",
+ "objectivec/GPBCodedOutputStream.m",
+ "objectivec/GPBDescriptor.m",
+ "objectivec/GPBDictionary.m",
+ "objectivec/GPBExtensionInternals.m",
+ "objectivec/GPBExtensionRegistry.m",
+ "objectivec/GPBMessage.m",
+ "objectivec/GPBRootObject.m",
+ "objectivec/GPBUnknownField.m",
+ "objectivec/GPBUnknownFieldSet.m",
+ "objectivec/GPBUtilities.m",
+ "objectivec/GPBWellKnownTypes.m",
+ "objectivec/GPBWireFormat.m",
+ "objectivec/google/protobuf/Any.pbobjc.m",
+ "objectivec/google/protobuf/Api.pbobjc.m",
+ "objectivec/google/protobuf/Duration.pbobjc.m",
+ "objectivec/google/protobuf/Empty.pbobjc.m",
+ "objectivec/google/protobuf/FieldMask.pbobjc.m",
+ "objectivec/google/protobuf/SourceContext.pbobjc.m",
+ "objectivec/google/protobuf/Struct.pbobjc.m",
+ "objectivec/google/protobuf/Timestamp.pbobjc.m",
+ "objectivec/google/protobuf/Type.pbobjc.m",
+ "objectivec/google/protobuf/Wrappers.pbobjc.m",
+]
+
+objc_library(
+ name = "objectivec",
+ hdrs = OBJC_HDRS + OBJC_PRIVATE_HDRS,
+ includes = [
+ "objectivec",
+ ],
+ non_arc_srcs = OBJC_SRCS,
+ visibility = ["//visibility:public"],
)
diff --git a/CHANGES.txt b/CHANGES.txt
index 7fb2da2e..c83da2d6 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -1,3 +1,315 @@
+2017-08-14 version 3.4.0 (C++/Java/Python/PHP/Objective-C/C#/Ruby/JavaScript)
+ Planned Future Changes
+ * There are some changes that are not included in this release but are planned
+ for the near future
+ - Preserve unknown fields in proto3: We are going to bring unknown fields
+ back into proto3. In this release, some languages start to support
+ preserving unknown fields in proto3, controlled by flags/options. Some
+ languages also introduce explicit APIs to drop unknown fields for
+ migration. Please read the change log sections by languages for details.
+ For general timeline and plan:
+
+ https://docs.google.com/document/d/1KMRX-G91Aa-Y2FkEaHeeviLRRNblgIahbsk4wA14gRk/view
+
+ For issues and discussions:
+
+ https://github.com/google/protobuf/issues/272
+
+ - Make C++ implementation C++11 only: we plan to require C++11 to build
+ protobuf code starting from 3.5.0 or 3.6.0 release, after unknown fields
+ semantic changes are finished. Please join this
+ github issue:
+
+ https://github.com/google/protobuf/issues/2780
+
+ to provide your feedback.
+
+ General
+ * Extension ranges now accept options and are customizable.
+ * "reserve" keyword now supports “max” in field number ranges,
+ e.g. reserve 1000 to max;
+
+ C++
+ * Proto3 messages are now able to preserve unknown fields. The default
+ behavior is still to drop unknowns, which will be flipped in a future
+ release. If you rely on unknowns fields being dropped. Please use
+ Message::DiscardUnknownFields() explicitly.
+ * Packable proto3 fields are now packed by default in serialization.
+ * Following C++11 features are introduced when C++11 is available:
+ - move-constructor and move-assignment are introduced to messages
+ - Repeated fields constructor now takes std::initializer_list
+ - rvalue setters are introduced for string fields
+ * Experimental Table-Driven parsing and serialization available to test. To
+ enable it, pass in table_driven_parsing table_driven_serialization protoc
+ generator flags for C++
+
+ $ protoc --cpp_out=table_driven_parsing,table_driven_serialization:./ \
+ test.proto
+
+ * lite generator parameter supported by the generator. Once set, all generated
+ files, use lite runtime regardless of the optimizer_for setting in the
+ .proto file.
+ * Various optimizations to make C++ code more performant on PowerPC platform
+ * Fixed maps data corruption when the maps are modified by both reflection API
+ and generated API.
+ * Deterministic serialization on maps reflection now uses stable sort.
+ * file() accessors are introduced to various *Descriptor classes to make
+ writing template function easier.
+ * ByteSize() and SpaceUsed() are deprecated.Use ByteSizeLong() and
+ SpaceUsedLong() instead
+ * Consistent hash function is used for maps in DEBUG and NDEBUG build.
+ * "using namespace std" is removed from stubs/common.h
+ * Various performance optimizations and bug fixes
+
+ Java
+ * Introduced new parser API DiscardUnknownFieldsParser in preparation of
+ proto3 unknown fields preservation change. Users who want to drop unknown
+ fields should migrate to use this new parser API. For example:
+
+ Parser<Foo> parser = DiscardUnknownFieldsParser.wrap(Foo.parser());
+ Foo foo = parser.parseFrom(input);
+
+ * Introduced new TextFormat API printUnicodeFieldValue() that prints field
+ value without escaping unicode characters.
+ * Added Durations.compare(Duration, Duration) and
+ Timestamps.compare(Timestamp, Timestamp).
+ * JsonFormat now accepts base64url encoded bytes fields.
+ * Optimized CodedInputStream to do less copies when parsing large bytes
+ fields.
+ * Optimized TextFormat to allocate less memory when printing.
+
+ Python
+ * SerializeToString API is changed to SerializeToString(self, **kwargs),
+ deterministic parameter is accepted for deterministic serialization.
+ * Added sort_keys parameter in json format to make the output deterministic.
+ * Added indent parameter in json format.
+ * Added extension support in json format.
+ * Added __repr__ support for repeated field in cpp implementation.
+ * Added file in FieldDescriptor.
+ * Added pretty-print filter to text format.
+ * Services and method descriptors are always printed even if generic_service
+ option is turned off.
+ * Note: AppEngine 2.5 is deprecated on June 2017 that AppEngine 2.5 will
+ never update protobuf runtime. Users who depend on AppEngine 2.5 should use
+ old protoc.
+
+ PHP
+ * Support PHP generic services. Specify file option php_generic_service=true
+ to enable generating service interface.
+ * Message, repeated and map fields setters take value instead of reference.
+ * Added map iterator in c extension.
+ * Support json  encode/decode.
+ * Added more type info in getter/setter phpdoc
+ * Fixed the problem that c extension and php implementation cannot be used
+ together.
+ * Added file option php_namespace to use custom php namespace instead of
+ package.
+ * Added fluent setter.
+ * Added descriptor API in runtime for custom encode/decode.
+ * Various bug fixes.
+
+ Objective-C
+ * Fix for GPBExtensionRegistry copying and add tests.
+ * Optimize GPBDictionary.m codegen to reduce size of overall library by 46K
+ per architecture.
+ * Fix some cases of reading of 64bit map values.
+ * Properly error on a tag with field number zero.
+ * Preserve unknown fields in proto3 syntax files.
+ * Document the exceptions on some of the writing apis.
+
+ C#
+ * Implemented IReadOnlyDictionary<K,V> in MapField<K,V>
+ * Added TryUnpack method for Any message in addition to Unpack.
+ * Converted C# projects to MSBuild (csproj) format.
+
+ Ruby
+ * Several bug fixes.
+
+ Javascript
+ * Added support of field option js_type. Now one can specify the JS type of a
+ 64-bit integer field to be string in the generated code by adding option
+ [jstype = JS_STRING] on the field.
+
+2017-04-05 version 3.3.0 (C++/Java/Python/PHP/Objective-C/C#/Ruby/JavaScript)
+ Planned Future Changes
+ * There are some changes that are not included in this release but are
+ planned for the near future:
+ - Preserve unknown fields in proto3: please read this doc:
+
+ https://docs.google.com/document/d/1KMRX-G91Aa-Y2FkEaHeeviLRRNblgIahbsk4wA14gRk/view
+
+ for the timeline and follow up this github issue:
+
+ https://github.com/google/protobuf/issues/272
+
+ for discussion.
+ - Make C++ implementation C++11 only: we plan to require C++11 to build
+ protobuf code starting from 3.4.0 or 3.5.0 release. Please join this
+ github issue:
+
+ https://github.com/google/protobuf/issues/2780
+
+ to provide your feedback.
+
+ C++
+ * Fixed map fields serialization of DynamicMessage to correctly serialize
+ both key and value regardless of their presence.
+ * Parser now rejects field number 0 correctly.
+ * New API Message::SpaceUsedLong() that’s equivalent to
+ Message::SpaceUsed() but returns the value in size_t.
+ * JSON support
+ - New flag always_print_enums_as_ints in JsonPrintOptions.
+ - New flag preserve_proto_field_names in JsonPrintOptions. It will instruct
+ the JSON printer to use the original field name declared in the .proto
+ file instead of converting them to lowerCamelCase when printing JSON.
+ - JsonPrintOptions.always_print_primtive_fields now works for oneof message
+ fields.
+ - Fixed a bug that doesn’t allow different fields to set the same json_name
+ value.
+ - Fixed a performance bug that causes excessive memory copy when printing
+ large messages.
+ * Various performance optimizations.
+
+ Java
+ * Map field setters eagerly validate inputs and throw NullPointerExceptions
+ as appropriate.
+ * Added ByteBuffer overloads to the generated parsing methods and the Parser
+ interface.
+ * proto3 enum's getNumber() method now throws on UNRECOGNIZED values.
+ * Output of JsonFormat is now locale independent.
+
+ Python
+ * Added FindServiceByName() in the pure-Python DescriptorPool. This works only
+ for descriptors added with DescriptorPool.Add(). Generated descriptor_pool
+ does not support this yet.
+ * Added a descriptor_pool parameter for parsing Any in text_format.Parse().
+ * descriptor_pool.FindFileContainingSymbol() now is able to find nested
+ extensions.
+ * Extending empty [] to repeated field now sets parent message presence.
+
+ PHP
+ * Added file option php_class_prefix. The prefix will be prepended to all
+ generated classes defined in the file.
+ * When encoding, negative int32 values are sign-extended to int64.
+ * Repeated/Map field setter accepts a regular PHP array. Type checking is
+ done on the array elements.
+ * encode/decode are renamed to serializeToString/mergeFromString.
+ * Added mergeFrom, clear method on Message.
+ * Fixed a bug that oneof accessor didn’t return the field name that is
+ actually set.
+ * C extension now works with php7.
+ * This is the first GA release of PHP. We guarantee that old generated code
+ can always work with new runtime and new generated code.
+
+ Objective-C
+ * Fixed help for GPBTimestamp for dates before the epoch that contain
+ fractional seconds.
+ * Added GPBMessageDropUnknownFieldsRecursively() to remove unknowns from a
+ message and any sub messages.
+ * Addressed a threading race in extension registration/lookup.
+ * Increased the max message parsing depth to 100 to match the other languages.
+ * Removed some use of dispatch_once in favor of atomic compare/set since it
+ needs to be heap based.
+ * Fixes for new Xcode 8.3 warnings.
+
+ C#
+ * Fixed MapField.Values.CopyTo, which would throw an exception unnecessarily
+ if provided exactly the right size of array to copy to.
+ * Fixed enum JSON formatting when multiple names mapped to the same numeric
+ value.
+ * Added JSON formatting option to format enums as integers.
+ * Modified RepeatedField<T> to implement IReadOnlyList<T>.
+ * Introduced the start of custom option handling; it's not as pleasant as it
+ might be, but the information is at least present. We expect to extend code
+ generation to improve this in the future.
+ * Introduced ByteString.FromStream and ByteString.FromStreamAsync to
+ efficiently create a ByteString from a stream.
+ * Added whole-message deprecation, which decorates the class with [Obsolete].
+
+ Ruby
+ * Fixed Message#to_h for messages with map fields.
+ * Fixed memcpy() in binary gems to work for old glibc, without breaking the
+ build for non-glibc libc’s like musl.
+
+ Javascript
+ * Added compatibility tests for version 3.0.0.
+ * Added conformance tests.
+ * Fixed serialization of extensions: we need to emit a value even if it is
+ falsy (like the number 0).
+ * Use closurebuilder.py in favor of calcdeps.py for compiling JavaScript.
+
+2017-01-23 version 3.2.0 (C++/Java/Python/PHP/Ruby/Objective-C/C#/JavaScript/Lite)
+ General
+ * Added protoc version number to protoc plugin protocol. It can be used by
+ protoc plugin to detect which version of protoc is used with the plugin and
+ mitigate known problems in certain version of protoc.
+
+ C++
+ * The default parsing byte size limit has been raised from 64MB to 2GB.
+ * Added rvalue setters for non-arena string fields.
+ * Enabled debug logging for Android.
+ * Fixed a double-free problem when using Reflection::SetAllocatedMessage()
+ with extension fields.
+ * Fixed several deterministic serialization bugs:
+ * MessageLite::SerializeAsString() now respects the global deterministic
+ serialization flag.
+ * Extension fields are serialized deterministically as well. Fixed protocol
+ compiler to correctly report importing-self as an error.
+ * Fixed FileDescriptor::DebugString() to print custom options correctly.
+ * Various performance/codesize optimizations and cleanups.
+
+ Java
+ * The default parsing byte size limit has been raised from 64MB to 2GB.
+ * Added recursion limit when parsing JSON.
+ * Fixed a bug that enumType.getDescriptor().getOptions() doesn't have custom
+ options.
+ * Fixed generated code to support field numbers up to 2^29-1.
+
+ Python
+ * You can now assign NumPy scalars/arrays (np.int32, np.int64) to protobuf
+ fields, and assigning other numeric types has been optimized for
+ performance.
+ * Pure-Python: message types are now garbage-collectable.
+ * Python/C++: a lot of internal cleanup/refactoring.
+
+ PHP (Alpha)
+ * For 64-bit integers type (int64/uint64/sfixed64/fixed64/sint64), use PHP
+ integer on 64-bit environment and PHP string on 32-bit environment.
+ * PHP generated code also conforms to PSR-4 now.
+ * Fixed ZTS build for c extension.
+ * Fixed c extension build on Mac.
+ * Fixed c extension build on 32-bit linux.
+ * Fixed the bug that message without namespace is not found in the descriptor
+ pool. (#2240)
+ * Fixed the bug that repeated field is not iterable in c extension.
+ * Message names Empty will be converted to GPBEmpty in generated code.
+ * Added phpdoc in generated files.
+ * The released API is almost stable. Unless there is large problem, we won't
+ change it. See
+ https://developers.google.com/protocol-buffers/docs/reference/php-generated
+ for more details.
+
+ Objective-C
+ * Added support for push/pop of the stream limit on CodedInputStream for
+ anyone doing manual parsing.
+
+ C#
+ * No changes.
+
+ Ruby
+ * Message objects now support #respond_to? for field getters/setters.
+ * You can now compare “message == non_message_object” and it will return false
+ instead of throwing an exception.
+ * JRuby: fixed #hashCode to properly reflect the values in the message.
+
+ Javascript
+ * Deserialization of repeated fields no longer has quadratic performance
+ behavior.
+ * UTF-8 encoding/decoding now properly supports high codepoints.
+ * Added convenience methods for some well-known types: Any, Struct, and
+ Timestamp. These make it easier to convert data between native JavaScript
+ types and the well-known protobuf types.
+
2016-09-23 version 3.1.0 (C++/Java/Python/PHP/Ruby/Objective-C/C#/JavaScript/Lite)
General
* Proto3 support in PHP (alpha).
@@ -40,23 +352,23 @@
APIs and share the same generated code. Users don’t need to re-generate
code for the same proto definition when they want to switch the
implementation later. The pure PHP package is included in the php/src
- directory, and the c extension is included in the php/ext directory.
-
+ directory, and the c extension is included in the php/ext directory.
+
Both implementations provide idiomatic PHP APIs:
* All messages and enums are defined as PHP classes.
* All message fields can only be accessed via getter/setter.
* Both repeated field elements and map elements are stored in containers
that act like a normal PHP array.
-
+
Unlike several existing third-party PHP implementations for protobuf, our
implementations are built on a "strongly-typed" philosophy: message fields
and array/map containers will throw exceptions eagerly when values of the
incorrect type (not including those that can be type converted, e.g.,
double <-> integer <-> numeric string) are inserted.
-
+
Currently, pure PHP runtime supports php5.5, 5.6 and 7 on linux. C
extension runtime supports php5.5 and 5.6 on linux.
-
+
See php/README.md for more details about installment. See
https://developers.google.com/protocol-buffers/docs/phptutorial for more
details about APIs.
@@ -1309,7 +1621,7 @@
2008-09-29 version 2.0.2:
General
- * License changed from Apache 2.0 to New BSD.
+ * License changed from Apache 2.0 to 3-Clause BSD.
* It is now possible to define custom "options", which are basically
annotations which may be placed on definitions in a .proto file.
For example, you might define a field option called "foo" like so:
diff --git a/Makefile.am b/Makefile.am
index 4ece5217..81e78a5d 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -57,24 +57,28 @@ csharp_EXTRA_DIST= \
csharp/build_tools.sh \
csharp/buildall.sh \
csharp/generate_protos.sh \
+ csharp/global.json \
csharp/keys/Google.Protobuf.public.snk \
csharp/keys/Google.Protobuf.snk \
csharp/keys/README.md \
+ csharp/protos/README.md \
+ csharp/protos/map_unittest_proto3.proto \
+ csharp/protos/unittest_custom_options_proto3.proto \
+ csharp/protos/unittest_import_public_proto3.proto \
+ csharp/protos/unittest_import_proto3.proto \
csharp/protos/unittest_issues.proto \
+ csharp/protos/unittest_proto3.proto \
csharp/src/AddressBook/AddPerson.cs \
csharp/src/AddressBook/Addressbook.cs \
- csharp/src/AddressBook/AddressBook.xproj \
+ csharp/src/AddressBook/AddressBook.csproj \
csharp/src/AddressBook/ListPeople.cs \
csharp/src/AddressBook/Program.cs \
csharp/src/AddressBook/SampleUsage.cs \
- csharp/src/AddressBook/project.json \
csharp/src/Google.Protobuf.Conformance/Conformance.cs \
- csharp/src/Google.Protobuf.Conformance/Google.Protobuf.Conformance.xproj \
+ csharp/src/Google.Protobuf.Conformance/Google.Protobuf.Conformance.csproj \
csharp/src/Google.Protobuf.Conformance/Program.cs \
- csharp/src/Google.Protobuf.Conformance/project.json \
- csharp/src/Google.Protobuf.JsonDump/Google.Protobuf.JsonDump.xproj \
+ csharp/src/Google.Protobuf.JsonDump/Google.Protobuf.JsonDump.csproj \
csharp/src/Google.Protobuf.JsonDump/Program.cs \
- csharp/src/Google.Protobuf.JsonDump/project.json \
csharp/src/Google.Protobuf.Test/ByteStringTest.cs \
csharp/src/Google.Protobuf.Test/CodedInputStreamExtensions.cs \
csharp/src/Google.Protobuf.Test/CodedInputStreamTest.cs \
@@ -82,16 +86,19 @@ csharp_EXTRA_DIST= \
csharp/src/Google.Protobuf.Test/Collections/MapFieldTest.cs \
csharp/src/Google.Protobuf.Test/Collections/RepeatedFieldTest.cs \
csharp/src/Google.Protobuf.Test/Compatibility/PropertyInfoExtensionsTest.cs \
+ csharp/src/Google.Protobuf.Test/Compatibility/StreamExtensionsTest.cs \
csharp/src/Google.Protobuf.Test/Compatibility/TypeExtensionsTest.cs \
csharp/src/Google.Protobuf.Test/DeprecatedMemberTest.cs \
csharp/src/Google.Protobuf.Test/EqualityTester.cs \
csharp/src/Google.Protobuf.Test/FieldCodecTest.cs \
csharp/src/Google.Protobuf.Test/GeneratedMessageTest.cs \
- csharp/src/Google.Protobuf.Test/Google.Protobuf.Test.xproj \
+ csharp/src/Google.Protobuf.Test/Google.Protobuf.Test.csproj \
csharp/src/Google.Protobuf.Test/IssuesTest.cs \
csharp/src/Google.Protobuf.Test/JsonFormatterTest.cs \
csharp/src/Google.Protobuf.Test/JsonParserTest.cs \
csharp/src/Google.Protobuf.Test/JsonTokenizerTest.cs \
+ csharp/src/Google.Protobuf.Test/Program.cs \
+ csharp/src/Google.Protobuf.Test/Reflection/CustomOptionsTest.cs \
csharp/src/Google.Protobuf.Test/Reflection/DescriptorsTest.cs \
csharp/src/Google.Protobuf.Test/Reflection/FieldAccessTest.cs \
csharp/src/Google.Protobuf.Test/Reflection/TypeRegistryTest.cs \
@@ -101,6 +108,7 @@ csharp_EXTRA_DIST= \
csharp/src/Google.Protobuf.Test/TestProtos/ForeignMessagePartial.cs \
csharp/src/Google.Protobuf.Test/TestProtos/MapUnittestProto3.cs \
csharp/src/Google.Protobuf.Test/TestProtos/TestMessagesProto3.cs \
+ csharp/src/Google.Protobuf.Test/TestProtos/UnittestCustomOptionsProto3.cs \
csharp/src/Google.Protobuf.Test/TestProtos/UnittestImportProto3.cs \
csharp/src/Google.Protobuf.Test/TestProtos/UnittestImportPublicProto3.cs \
csharp/src/Google.Protobuf.Test/TestProtos/UnittestIssues.cs \
@@ -111,7 +119,6 @@ csharp_EXTRA_DIST= \
csharp/src/Google.Protobuf.Test/WellKnownTypes/FieldMaskTest.cs \
csharp/src/Google.Protobuf.Test/WellKnownTypes/TimestampTest.cs \
csharp/src/Google.Protobuf.Test/WellKnownTypes/WrappersTest.cs \
- csharp/src/Google.Protobuf.Test/project.json \
csharp/src/Google.Protobuf.sln \
csharp/src/Google.Protobuf/ByteArray.cs \
csharp/src/Google.Protobuf/ByteString.cs \
@@ -122,10 +129,11 @@ csharp_EXTRA_DIST= \
csharp/src/Google.Protobuf/Collections/ReadOnlyDictionary.cs \
csharp/src/Google.Protobuf/Collections/RepeatedField.cs \
csharp/src/Google.Protobuf/Compatibility/PropertyInfoExtensions.cs \
+ csharp/src/Google.Protobuf/Compatibility/StreamExtensions.cs \
csharp/src/Google.Protobuf/Compatibility/TypeExtensions.cs \
csharp/src/Google.Protobuf/FieldCodec.cs \
csharp/src/Google.Protobuf/FrameworkPortability.cs \
- csharp/src/Google.Protobuf/Google.Protobuf.xproj \
+ csharp/src/Google.Protobuf/Google.Protobuf.csproj \
csharp/src/Google.Protobuf/ICustomDiagnosticMessage.cs \
csharp/src/Google.Protobuf/IDeepCloneable.cs \
csharp/src/Google.Protobuf/IMessage.cs \
@@ -140,6 +148,7 @@ csharp_EXTRA_DIST= \
csharp/src/Google.Protobuf/MessageParser.cs \
csharp/src/Google.Protobuf/ProtoPreconditions.cs \
csharp/src/Google.Protobuf/Properties/AssemblyInfo.cs \
+ csharp/src/Google.Protobuf/Reflection/CustomOptions.cs \
csharp/src/Google.Protobuf/Reflection/Descriptor.cs \
csharp/src/Google.Protobuf/Reflection/DescriptorBase.cs \
csharp/src/Google.Protobuf/Reflection/DescriptorPool.cs \
@@ -184,9 +193,7 @@ csharp_EXTRA_DIST= \
csharp/src/Google.Protobuf/WellKnownTypes/ValuePartial.cs \
csharp/src/Google.Protobuf/WellKnownTypes/Wrappers.cs \
csharp/src/Google.Protobuf/WellKnownTypes/WrappersPartial.cs \
- csharp/src/Google.Protobuf/WireFormat.cs \
- csharp/src/Google.Protobuf/project.json \
- csharp/src/packages/repositories.config
+ csharp/src/Google.Protobuf/WireFormat.cs
java_EXTRA_DIST= \
java/README.md \
@@ -205,6 +212,7 @@ java_EXTRA_DIST=
java/core/src/main/java/com/google/protobuf/ByteString.java \
java/core/src/main/java/com/google/protobuf/CodedInputStream.java \
java/core/src/main/java/com/google/protobuf/CodedOutputStream.java \
+ java/core/src/main/java/com/google/protobuf/DiscardUnknownFieldsParser.java \
java/core/src/main/java/com/google/protobuf/Descriptors.java \
java/core/src/main/java/com/google/protobuf/DoubleArrayList.java \
java/core/src/main/java/com/google/protobuf/DynamicMessage.java \
@@ -222,6 +230,7 @@ java_EXTRA_DIST=
java/core/src/main/java/com/google/protobuf/IntArrayList.java \
java/core/src/main/java/com/google/protobuf/Internal.java \
java/core/src/main/java/com/google/protobuf/InvalidProtocolBufferException.java \
+ java/core/src/main/java/com/google/protobuf/IterableByteBufferInputStream.java \
java/core/src/main/java/com/google/protobuf/LazyField.java \
java/core/src/main/java/com/google/protobuf/LazyFieldLite.java \
java/core/src/main/java/com/google/protobuf/LazyStringArrayList.java \
@@ -240,6 +249,7 @@ java_EXTRA_DIST=
java/core/src/main/java/com/google/protobuf/MutabilityOracle.java \
java/core/src/main/java/com/google/protobuf/NioByteString.java \
java/core/src/main/java/com/google/protobuf/Parser.java \
+ java/core/src/main/java/com/google/protobuf/PrimitiveNonBoxingCollection.java \
java/core/src/main/java/com/google/protobuf/ProtobufArrayList.java \
java/core/src/main/java/com/google/protobuf/ProtocolMessageEnum.java \
java/core/src/main/java/com/google/protobuf/ProtocolStringList.java \
@@ -278,6 +288,7 @@ java_EXTRA_DIST=
java/core/src/test/java/com/google/protobuf/CodedOutputStreamTest.java \
java/core/src/test/java/com/google/protobuf/DeprecatedFieldTest.java \
java/core/src/test/java/com/google/protobuf/DescriptorsTest.java \
+ java/core/src/test/java/com/google/protobuf/DiscardUnknownFieldsTest.java \
java/core/src/test/java/com/google/protobuf/DoubleArrayListTest.java \
java/core/src/test/java/com/google/protobuf/DynamicMessageTest.java \
java/core/src/test/java/com/google/protobuf/EnumTest.java \
@@ -314,6 +325,7 @@ java_EXTRA_DIST=
java/core/src/test/java/com/google/protobuf/SingleFieldBuilderV3Test.java \
java/core/src/test/java/com/google/protobuf/SmallSortedMapTest.java \
java/core/src/test/java/com/google/protobuf/TestBadIdentifiers.java \
+ java/core/src/test/java/com/google/protobuf/TestBadIdentifiersLite.java \
java/core/src/test/java/com/google/protobuf/TestUtil.java \
java/core/src/test/java/com/google/protobuf/TestUtilLite.java \
java/core/src/test/java/com/google/protobuf/TextFormatParseInfoTreeTest.java \
@@ -326,6 +338,7 @@ java_EXTRA_DIST=
java/core/src/test/java/com/google/protobuf/WellKnownTypesTest.java \
java/core/src/test/java/com/google/protobuf/WireFormatTest.java \
java/core/src/test/proto/com/google/protobuf/any_test.proto \
+ java/core/src/test/proto/com/google/protobuf/deprecated_file.proto \
java/core/src/test/proto/com/google/protobuf/field_presence_test.proto \
java/core/src/test/proto/com/google/protobuf/lazy_fields_lite.proto \
java/core/src/test/proto/com/google/protobuf/lite_equals_and_hash.proto \
@@ -525,7 +538,9 @@ objectivec_EXTRA_DIST= \
objectivec/Tests/GPBDictionaryTests+String.m \
objectivec/Tests/GPBDictionaryTests+UInt32.m \
objectivec/Tests/GPBDictionaryTests+UInt64.m \
+ objectivec/Tests/GPBDictionaryTests.m \
objectivec/Tests/GPBDictionaryTests.pddm \
+ objectivec/Tests/GPBExtensionRegistryTest.m \
objectivec/Tests/GPBMessageTests+Merge.m \
objectivec/Tests/GPBMessageTests+Runtime.m \
objectivec/Tests/GPBMessageTests+Serialization.m \
@@ -543,15 +558,20 @@ objectivec_EXTRA_DIST= \
objectivec/Tests/GPBWireFormatTests.m \
objectivec/Tests/iOSTestHarness/AppDelegate.m \
objectivec/Tests/iOSTestHarness/en.lproj/InfoPlist.strings \
- objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/Contents.json \
- objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad6.png \
- objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad6_2x.png \
- objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad7.png \
- objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad7_2x.png \
- objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone6.png \
- objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone6_2x.png \
- objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone7_2x.png \
- objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone7_3x.png \
+ objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_20.png \
+ objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_29.png \
+ objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_40.png \
+ objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_58.png \
+ objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_60.png \
+ objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_76.png \
+ objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_80.png \
+ objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_87.png \
+ objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_120.png \
+ objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_152.png \
+ objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_167.png \
+ objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_180.png \
+ objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_1024.png \
+ objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/Contents.json \
objectivec/Tests/iOSTestHarness/Images.xcassets/LaunchImage.launchimage/Contents.json \
objectivec/Tests/iOSTestHarness/Info.plist \
objectivec/Tests/iOSTestHarness/LaunchScreen.xib \
@@ -576,88 +596,170 @@ objectivec_EXTRA_DIST= \
Protobuf.podspec
php_EXTRA_DIST= \
- php/src/phpdoc.dist.xml \
+ composer.json \
+ php/README.md \
+ php/composer.json \
+ php/ext/google/protobuf/array.c \
+ php/ext/google/protobuf/config.m4 \
+ php/ext/google/protobuf/def.c \
+ php/ext/google/protobuf/encode_decode.c \
+ php/ext/google/protobuf/map.c \
+ php/ext/google/protobuf/message.c \
+ php/ext/google/protobuf/package.xml \
+ php/ext/google/protobuf/protobuf.c \
+ php/ext/google/protobuf/protobuf.h \
+ php/ext/google/protobuf/storage.c \
+ php/ext/google/protobuf/type_check.c \
+ php/ext/google/protobuf/upb.c \
+ php/ext/google/protobuf/upb.h \
+ php/ext/google/protobuf/utf8.c \
+ php/ext/google/protobuf/utf8.h \
+ php/generate_descriptor_protos.sh \
+ php/phpunit.xml \
+ php/src/GPBMetadata/Google/Protobuf/Any.php \
+ php/src/GPBMetadata/Google/Protobuf/Api.php \
+ php/src/GPBMetadata/Google/Protobuf/Duration.php \
+ php/src/GPBMetadata/Google/Protobuf/FieldMask.php \
+ php/src/GPBMetadata/Google/Protobuf/GPBEmpty.php \
+ php/src/GPBMetadata/Google/Protobuf/Internal/Descriptor.php \
+ php/src/GPBMetadata/Google/Protobuf/SourceContext.php \
+ php/src/GPBMetadata/Google/Protobuf/Struct.php \
+ php/src/GPBMetadata/Google/Protobuf/Timestamp.php \
+ php/src/GPBMetadata/Google/Protobuf/Type.php \
+ php/src/GPBMetadata/Google/Protobuf/Wrappers.php \
+ php/src/Google/Protobuf/Any.php \
+ php/src/Google/Protobuf/Api.php \
+ php/src/Google/Protobuf/BoolValue.php \
+ php/src/Google/Protobuf/BytesValue.php \
+ php/src/Google/Protobuf/Descriptor.php \
+ php/src/Google/Protobuf/DescriptorPool.php \
+ php/src/Google/Protobuf/DoubleValue.php \
+ php/src/Google/Protobuf/Duration.php \
+ php/src/Google/Protobuf/Enum.php \
+ php/src/Google/Protobuf/EnumDescriptor.php \
+ php/src/Google/Protobuf/EnumValue.php \
+ php/src/Google/Protobuf/EnumValueDescriptor.php \
+ php/src/Google/Protobuf/Field.php \
+ php/src/Google/Protobuf/FieldDescriptor.php \
+ php/src/Google/Protobuf/FieldMask.php \
+ php/src/Google/Protobuf/Field_Cardinality.php \
+ php/src/Google/Protobuf/Field_Kind.php \
+ php/src/Google/Protobuf/FloatValue.php \
+ php/src/Google/Protobuf/GPBEmpty.php \
+ php/src/Google/Protobuf/Int32Value.php \
+ php/src/Google/Protobuf/Int64Value.php \
+ php/src/Google/Protobuf/Internal/CodedInputStream.php \
+ php/src/Google/Protobuf/Internal/CodedOutputStream.php \
+ php/src/Google/Protobuf/Internal/Descriptor.php \
php/src/Google/Protobuf/Internal/DescriptorPool.php \
- php/src/Google/Protobuf/Internal/GeneratedCodeInfo.php \
- php/src/Google/Protobuf/Internal/OneofField.php \
- php/src/Google/Protobuf/Internal/MessageOptions.php \
- php/src/Google/Protobuf/Internal/FileDescriptorProto.php \
- php/src/Google/Protobuf/Internal/MapEntry.php \
- php/src/Google/Protobuf/Internal/FieldDescriptorProto.php \
- php/src/Google/Protobuf/Internal/InputStream.php \
- php/src/Google/Protobuf/Internal/UninterpretedOption.php \
- php/src/Google/Protobuf/Internal/ServiceOptions.php \
- php/src/Google/Protobuf/Internal/MethodOptions_IdempotencyLevel.php \
- php/src/Google/Protobuf/Internal/ServiceDescriptorProto.php \
- php/src/Google/Protobuf/Internal/OneofDescriptorProto.php \
- php/src/Google/Protobuf/Internal/UninterpretedOption_NamePart.php \
- php/src/Google/Protobuf/Internal/OutputStream.php \
- php/src/Google/Protobuf/Internal/MessageBuilderContext.php \
- php/src/Google/Protobuf/Internal/EnumValueDescriptorProto.php \
- php/src/Google/Protobuf/Internal/FileOptions_OptimizeMode.php \
php/src/Google/Protobuf/Internal/DescriptorProto.php \
- php/src/Google/Protobuf/Internal/MapField.php \
- php/src/Google/Protobuf/Internal/MethodDescriptorProto.php \
php/src/Google/Protobuf/Internal/DescriptorProto_ExtensionRange.php \
php/src/Google/Protobuf/Internal/DescriptorProto_ReservedRange.php \
- php/src/Google/Protobuf/Internal/RepeatedField.php \
- php/src/Google/Protobuf/Internal/EnumValueOptions.php \
- php/src/Google/Protobuf/Internal/MethodOptions.php \
- php/src/Google/Protobuf/Internal/OneofOptions.php \
- php/src/Google/Protobuf/Internal/Message.php \
- php/src/Google/Protobuf/Internal/FileOptions.php \
- php/src/Google/Protobuf/Internal/FileDescriptorSet.php \
+ php/src/Google/Protobuf/Internal/EnumBuilderContext.php \
+ php/src/Google/Protobuf/Internal/EnumDescriptor.php \
php/src/Google/Protobuf/Internal/EnumDescriptorProto.php \
- php/src/Google/Protobuf/Internal/GPBWire.php \
+ php/src/Google/Protobuf/Internal/EnumDescriptorProto_EnumReservedRange.php \
+ php/src/Google/Protobuf/Internal/EnumOptions.php \
+ php/src/Google/Protobuf/Internal/EnumValueDescriptorProto.php \
+ php/src/Google/Protobuf/Internal/EnumValueOptions.php \
+ php/src/Google/Protobuf/Internal/ExtensionRangeOptions.php \
+ php/src/Google/Protobuf/Internal/FieldDescriptorProto_Label.php \
+ php/src/Google/Protobuf/Internal/FieldDescriptorProto.php \
+ php/src/Google/Protobuf/Internal/FieldDescriptor.php \
+ php/src/Google/Protobuf/Internal/FieldDescriptorProto.php \
php/src/Google/Protobuf/Internal/FieldDescriptorProto_Label.php \
- php/src/Google/Protobuf/Internal/FieldOptions.php \
- php/src/Google/Protobuf/Internal/GeneratedCodeInfo_Annotation.php \
php/src/Google/Protobuf/Internal/FieldDescriptorProto_Type.php \
- php/src/Google/Protobuf/Internal/GPBType.php \
+ php/src/Google/Protobuf/Internal/FieldOptions.php \
+ php/src/Google/Protobuf/Internal/FieldOptions_CType.php \
php/src/Google/Protobuf/Internal/FieldOptions_JSType.php \
- php/src/Google/Protobuf/Internal/SourceCodeInfo_Location.php \
- php/src/Google/Protobuf/Internal/SourceCodeInfo.php \
- php/src/Google/Protobuf/Internal/EnumOptions.php \
+ php/src/Google/Protobuf/Internal/FileDescriptor.php \
+ php/src/Google/Protobuf/Internal/FileDescriptorProto.php \
+ php/src/Google/Protobuf/Internal/FileDescriptorSet.php \
+ php/src/Google/Protobuf/Internal/FileOptions.php \
+ php/src/Google/Protobuf/Internal/FileOptions_OptimizeMode.php \
+ php/src/Google/Protobuf/Internal/GPBDecodeException.php \
+ php/src/Google/Protobuf/Internal/GPBJsonWire.php \
php/src/Google/Protobuf/Internal/GPBLabel.php \
- php/src/Google/Protobuf/Internal/EnumBuilderContext.php \
+ php/src/Google/Protobuf/Internal/GPBType.php \
php/src/Google/Protobuf/Internal/GPBUtil.php \
- php/src/Google/Protobuf/Internal/FieldOptions_CType.php \
- php/src/Google/Protobuf/descriptor.php \
- php/src/GPBMetadata/Google/Protobuf/Internal/Descriptor.php \
+ php/src/Google/Protobuf/Internal/GPBWire.php \
+ php/src/Google/Protobuf/Internal/GPBWireType.php \
+ php/src/Google/Protobuf/Internal/GeneratedCodeInfo.php \
+ php/src/Google/Protobuf/Internal/GeneratedCodeInfo_Annotation.php \
+ php/src/Google/Protobuf/Internal/GetPublicDescriptorTrait.php \
+ php/src/Google/Protobuf/Internal/HasPublicDescriptorTrait.php \
+ php/src/Google/Protobuf/Internal/MapEntry.php \
+ php/src/Google/Protobuf/Internal/MapField.php \
+ php/src/Google/Protobuf/Internal/MapFieldIter.php \
+ php/src/Google/Protobuf/Internal/Message.php \
+ php/src/Google/Protobuf/Internal/MessageBuilderContext.php \
+ php/src/Google/Protobuf/Internal/MessageOptions.php \
+ php/src/Google/Protobuf/Internal/MethodDescriptorProto.php \
+ php/src/Google/Protobuf/Internal/MethodOptions.php \
+ php/src/Google/Protobuf/Internal/MethodOptions_IdempotencyLevel.php \
+ php/src/Google/Protobuf/Internal/OneofDescriptor.php \
+ php/src/Google/Protobuf/Internal/OneofDescriptorProto.php \
+ php/src/Google/Protobuf/Internal/OneofField.php \
+ php/src/Google/Protobuf/Internal/OneofOptions.php \
+ php/src/Google/Protobuf/Internal/RawInputStream.php \
+ php/src/Google/Protobuf/Internal/RepeatedField.php \
+ php/src/Google/Protobuf/Internal/RepeatedFieldIter.php \
+ php/src/Google/Protobuf/Internal/ServiceDescriptorProto.php \
+ php/src/Google/Protobuf/Internal/ServiceOptions.php \
+ php/src/Google/Protobuf/Internal/SourceCodeInfo.php \
+ php/src/Google/Protobuf/Internal/SourceCodeInfo_Location.php \
+ php/src/Google/Protobuf/Internal/UninterpretedOption.php \
+ php/src/Google/Protobuf/Internal/UninterpretedOption_NamePart.php \
+ php/src/Google/Protobuf/ListValue.php \
+ php/src/Google/Protobuf/Method.php \
+ php/src/Google/Protobuf/Mixin.php \
+ php/src/Google/Protobuf/NullValue.php \
+ php/src/Google/Protobuf/OneofDescriptor.php \
+ php/src/Google/Protobuf/Option.php \
+ php/src/Google/Protobuf/SourceContext.php \
+ php/src/Google/Protobuf/StringValue.php \
+ php/src/Google/Protobuf/Struct.php \
+ php/src/Google/Protobuf/Syntax.php \
+ php/src/Google/Protobuf/Timestamp.php \
+ php/src/Google/Protobuf/Type.php \
+ php/src/Google/Protobuf/UInt32Value.php \
+ php/src/Google/Protobuf/UInt64Value.php \
+ php/src/Google/Protobuf/Value.php \
+ php/src/phpdoc.dist.xml \
+ php/tests/array_test.php \
php/tests/autoload.php \
+ php/tests/bootstrap_phpunit.php \
+ php/tests/compatibility_test.sh \
+ php/tests/descriptors_test.php \
php/tests/encode_decode_test.php \
- php/tests/test.sh \
php/tests/gdb_test.sh \
php/tests/generated_class_test.php \
- php/tests/array_test.php \
+ php/tests/generated_phpdoc_test.php \
+ php/tests/generated_service_test.php \
+ php/tests/map_field_test.php \
+ php/tests/memory_leak_test.php \
php/tests/php_implementation_test.php \
+ php/tests/proto/test.proto \
+ php/tests/proto/test_descriptors.proto \
+ php/tests/proto/test_empty_php_namespace.proto \
+ php/tests/proto/test_import_descriptor_proto.proto \
php/tests/proto/test_include.proto \
- php/tests/map_field_test.php \
- php/tests/test_base.php \
php/tests/proto/test_no_namespace.proto \
+ php/tests/proto/test_php_namespace.proto \
+ php/tests/proto/test_prefix.proto \
+ php/tests/proto/test_reserved_enum_lower.proto \
+ php/tests/proto/test_reserved_enum_upper.proto \
+ php/tests/proto/test_reserved_enum_value_lower.proto \
+ php/tests/proto/test_reserved_enum_value_upper.proto \
+ php/tests/proto/test_reserved_message_lower.proto \
+ php/tests/proto/test_reserved_message_upper.proto \
+ php/tests/proto/test_service.proto \
+ php/tests/proto/test_service_namespace.proto \
+ php/tests/test.sh \
+ php/tests/test_base.php \
php/tests/test_util.php \
- php/tests/proto/test.proto \
- php/tests/memory_leak_test.php \
- php/tests/well_known_test.php \
- php/README.md \
- php/ext/google/protobuf/utf8.h \
- php/ext/google/protobuf/message.c \
- php/ext/google/protobuf/utf8.c \
- php/ext/google/protobuf/package.xml \
- php/ext/google/protobuf/upb.h \
- php/ext/google/protobuf/array.c \
- php/ext/google/protobuf/encode_decode.c \
- php/ext/google/protobuf/protobuf.h \
- php/ext/google/protobuf/type_check.c \
- php/ext/google/protobuf/def.c \
- php/ext/google/protobuf/storage.c \
- php/ext/google/protobuf/map.c \
- php/ext/google/protobuf/config.m4 \
- php/ext/google/protobuf/upb.c \
- php/ext/google/protobuf/protobuf.c \
- php/phpunit.xml \
- php/composer.json \
- composer.json
+ php/tests/undefined_test.php \
+ php/tests/well_known_test.php
python_EXTRA_DIST= \
python/MANIFEST.in \
@@ -700,6 +802,7 @@ python_EXTRA_DIST= \
python/google/protobuf/internal/packed_field_test.proto \
python/google/protobuf/internal/proto_builder_test.py \
python/google/protobuf/internal/python_message.py \
+ python/google/protobuf/internal/python_protobuf.cc \
python/google/protobuf/internal/reflection_test.py \
python/google/protobuf/internal/service_reflection_test.py \
python/google/protobuf/internal/symbol_database_test.py \
@@ -719,6 +822,7 @@ python_EXTRA_DIST= \
python/google/protobuf/json_format.py \
python/google/protobuf/message.py \
python/google/protobuf/message_factory.py \
+ python/google/protobuf/python_protobuf.h \
python/google/protobuf/proto_builder.py \
python/google/protobuf/pyext/README \
python/google/protobuf/pyext/__init__.py \
@@ -742,7 +846,6 @@ python_EXTRA_DIST= \
python/google/protobuf/pyext/message_module.cc \
python/google/protobuf/pyext/proto2_api_test.proto \
python/google/protobuf/pyext/python.proto \
- python/google/protobuf/pyext/python_protobuf.h \
python/google/protobuf/pyext/repeated_composite_container.cc \
python/google/protobuf/pyext/repeated_composite_container.h \
python/google/protobuf/pyext/repeated_scalar_container.cc \
@@ -755,6 +858,7 @@ python_EXTRA_DIST= \
python/google/protobuf/symbol_database.py \
python/google/protobuf/text_encoding.py \
python/google/protobuf/text_format.py \
+ python/release.sh \
python/mox.py \
python/setup.cfg \
python/setup.py \
@@ -767,6 +871,15 @@ ruby_EXTRA_DIST= \
ruby/.gitignore \
ruby/README.md \
ruby/Rakefile \
+ ruby/compatibility_tests/v3.0.0/tests/test_import.proto \
+ ruby/compatibility_tests/v3.0.0/tests/stress.rb \
+ ruby/compatibility_tests/v3.0.0/tests/repeated_field_test.rb \
+ ruby/compatibility_tests/v3.0.0/tests/generated_code_test.rb \
+ ruby/compatibility_tests/v3.0.0/tests/generated_code.proto \
+ ruby/compatibility_tests/v3.0.0/tests/basic.rb \
+ ruby/compatibility_tests/v3.0.0/test.sh \
+ ruby/compatibility_tests/v3.0.0/Rakefile \
+ ruby/compatibility_tests/v3.0.0/README.md \
ruby/ext/google/protobuf_c/defs.c \
ruby/ext/google/protobuf_c/encode_decode.c \
ruby/ext/google/protobuf_c/extconf.rb \
@@ -778,6 +891,7 @@ ruby_EXTRA_DIST= \
ruby/ext/google/protobuf_c/storage.c \
ruby/ext/google/protobuf_c/upb.c \
ruby/ext/google/protobuf_c/upb.h \
+ ruby/ext/google/protobuf_c/wrap_memcpy.c \
ruby/google-protobuf.gemspec \
ruby/lib/google/protobuf/message_exts.rb \
ruby/lib/google/protobuf/repeated_field.rb \
@@ -803,6 +917,7 @@ ruby_EXTRA_DIST= \
ruby/src/main/java/google/ProtobufJavaService.java \
ruby/src/main/sentinel.proto \
ruby/tests/basic.rb \
+ ruby/tests/gc_test.rb \
ruby/tests/repeated_field_test.rb \
ruby/tests/stress.rb \
ruby/tests/generated_code.proto \
@@ -811,49 +926,101 @@ ruby_EXTRA_DIST= \
ruby/tests/well_known_types_test.rb \
ruby/travis-test.sh
-js_EXTRA_DIST= \
- js/README.md \
- js/binary/arith.js \
- js/binary/arith_test.js \
- js/binary/constants.js \
- js/binary/decoder.js \
- js/binary/decoder_test.js \
- js/binary/encoder.js \
- js/binary/proto_test.js \
- js/binary/reader.js \
- js/binary/reader_test.js \
- js/binary/utils.js \
- js/binary/utils_test.js \
- js/binary/writer.js \
- js/binary/writer_test.js \
- js/commonjs/export.js \
- js/commonjs/export_asserts.js \
- js/commonjs/export_testdeps.js \
- js/commonjs/import_test.js \
- js/commonjs/jasmine.json \
- js/commonjs/rewrite_tests_for_commonjs.js \
- js/commonjs/test6/test6.proto \
- js/commonjs/test7/test7.proto \
- js/data.proto \
- js/debug.js \
- js/debug_test.js \
- js/gulpfile.js \
- js/jasmine.json \
- js/map.js \
- js/maps_test.js \
- js/message.js \
- js/message_test.js \
- js/node_loader.js \
- js/package.json \
- js/proto3_test.js \
- js/proto3_test.proto \
- js/test.proto \
- js/test2.proto \
- js/test3.proto \
- js/test4.proto \
- js/test5.proto \
- js/test_bootstrap.js \
- js/testbinary.proto \
+js_EXTRA_DIST= \
+ js/README.md \
+ js/binary/arith.js \
+ js/binary/arith_test.js \
+ js/binary/constants.js \
+ js/binary/decoder.js \
+ js/binary/decoder_test.js \
+ js/binary/encoder.js \
+ js/binary/message_test.js \
+ js/binary/proto_test.js \
+ js/binary/reader.js \
+ js/binary/reader_test.js \
+ js/binary/utils.js \
+ js/binary/utils_test.js \
+ js/binary/writer.js \
+ js/binary/writer_test.js \
+ js/commonjs/export.js \
+ js/commonjs/export_asserts.js \
+ js/commonjs/export_testdeps.js \
+ js/commonjs/import_test.js \
+ js/commonjs/jasmine.json \
+ js/commonjs/rewrite_tests_for_commonjs.js \
+ js/commonjs/test6/test6.proto \
+ js/commonjs/test7/test7.proto \
+ js/compatibility_tests/v3.0.0/binary/arith_test.js \
+ js/compatibility_tests/v3.0.0/binary/decoder_test.js \
+ js/compatibility_tests/v3.0.0/binary/proto_test.js \
+ js/compatibility_tests/v3.0.0/binary/reader_test.js \
+ js/compatibility_tests/v3.0.0/binary/utils_test.js \
+ js/compatibility_tests/v3.0.0/binary/writer_test.js \
+ js/compatibility_tests/v3.0.0/commonjs/export_asserts.js \
+ js/compatibility_tests/v3.0.0/commonjs/export_testdeps.js \
+ js/compatibility_tests/v3.0.0/commonjs/import_test.js \
+ js/compatibility_tests/v3.0.0/commonjs/jasmine.json \
+ js/compatibility_tests/v3.0.0/commonjs/rewrite_tests_for_commonjs.js \
+ js/compatibility_tests/v3.0.0/commonjs/test6/test6.proto \
+ js/compatibility_tests/v3.0.0/commonjs/test7/test7.proto \
+ js/compatibility_tests/v3.0.0/data.proto \
+ js/compatibility_tests/v3.0.0/debug_test.js \
+ js/compatibility_tests/v3.0.0/jasmine1.json \
+ js/compatibility_tests/v3.0.0/jasmine2.json \
+ js/compatibility_tests/v3.0.0/jasmine3.json \
+ js/compatibility_tests/v3.0.0/message_test.js \
+ js/compatibility_tests/v3.0.0/proto3_test.js \
+ js/compatibility_tests/v3.0.0/proto3_test.proto \
+ js/compatibility_tests/v3.0.0/test2.proto \
+ js/compatibility_tests/v3.0.0/test3.proto \
+ js/compatibility_tests/v3.0.0/test4.proto \
+ js/compatibility_tests/v3.0.0/test5.proto \
+ js/compatibility_tests/v3.0.0/testbinary.proto \
+ js/compatibility_tests/v3.0.0/testempty.proto \
+ js/compatibility_tests/v3.0.0/test.proto \
+ js/compatibility_tests/v3.0.0/test.sh \
+ js/compatibility_tests/v3.1.0/testempty.proto \
+ js/compatibility_tests/v3.1.0/testbinary.proto \
+ js/compatibility_tests/v3.1.0/test5.proto \
+ js/compatibility_tests/v3.1.0/test4.proto \
+ js/compatibility_tests/v3.1.0/test3.proto \
+ js/compatibility_tests/v3.1.0/test2.proto \
+ js/compatibility_tests/v3.1.0/test.proto \
+ js/compatibility_tests/v3.1.0/proto3_test.proto \
+ js/compatibility_tests/v3.1.0/proto3_test.js \
+ js/compatibility_tests/v3.1.0/message_test.js \
+ js/compatibility_tests/v3.1.0/maps_test.js \
+ js/compatibility_tests/v3.1.0/debug_test.js \
+ js/compatibility_tests/v3.1.0/data.proto \
+ js/compatibility_tests/v3.1.0/commonjs/test7/test7.proto \
+ js/compatibility_tests/v3.1.0/commonjs/test6/test6.proto \
+ js/compatibility_tests/v3.1.0/binary/writer_test.js \
+ js/compatibility_tests/v3.1.0/binary/utils_test.js \
+ js/compatibility_tests/v3.1.0/binary/reader_test.js \
+ js/compatibility_tests/v3.1.0/binary/proto_test.js \
+ js/compatibility_tests/v3.1.0/binary/decoder_test.js \
+ js/compatibility_tests/v3.1.0/binary/arith_test.js \
+ js/data.proto \
+ js/debug.js \
+ js/debug_test.js \
+ js/gulpfile.js \
+ js/jasmine.json \
+ js/map.js \
+ js/maps_test.js \
+ js/message.js \
+ js/message_test.js \
+ js/node_loader.js \
+ js/package.json \
+ js/proto3_test.js \
+ js/proto3_test.proto \
+ js/test.proto \
+ js/test2.proto \
+ js/test3.proto \
+ js/test4.proto \
+ js/test5.proto \
+ js/test8.proto \
+ js/test_bootstrap.js \
+ js/testbinary.proto \
js/testempty.proto
all_EXTRA_DIST=$(csharp_EXTRA_DIST) $(java_EXTRA_DIST) $(javanano_EXTRA_DIST) $(objectivec_EXTRA_DIST) $(php_EXTRA_DIST) $(python_EXTRA_DIST) $(ruby_EXTRA_DIST) $(js_EXTRA_DIST)
@@ -879,32 +1046,40 @@ EXTRA_DIST = $(@DIST_LANG@_EXTRA_DIST) \
cmake/libprotoc.cmake \
cmake/protobuf-config-version.cmake.in \
cmake/protobuf-config.cmake.in \
+ cmake/protobuf-lite.pc.cmake \
cmake/protobuf-module.cmake.in \
cmake/protobuf-options.cmake \
+ cmake/protobuf.pc.cmake \
cmake/protoc.cmake \
cmake/tests.cmake \
editors/README.txt \
editors/proto.vim \
editors/protobuf-mode.el \
+ examples/AddPerson.java \
+ examples/BUILD \
examples/CMakeLists.txt \
- examples/README.txt \
+ examples/ListPeople.java \
examples/Makefile \
- examples/addressbook.proto \
+ examples/README.md \
+ examples/WORKSPACE \
examples/add_person.cc \
examples/add_person.go \
+ examples/add_person.py \
examples/add_person_test.go \
+ examples/addressbook.proto \
examples/list_people.cc \
examples/list_people.go \
- examples/AddPerson.java \
- examples/CMakeLists.txt \
- examples/ListPeople.java \
- examples/add_person.py \
examples/list_people.py \
examples/list_people_test.go \
protobuf.bzl \
+ python/release/wheel/build_wheel_manylinux.sh \
+ python/release/wheel/Dockerfile \
+ python/release/wheel/protobuf_optimized_pip.sh \
+ python/release/wheel/README.md \
six.BUILD \
util/python/BUILD
+
# Deletes all the files generated by autogen.sh.
MAINTAINERCLEANFILES = \
aclocal.m4 \
diff --git a/Protobuf.podspec b/Protobuf.podspec
index 217f6d20..d559d18a 100644
--- a/Protobuf.podspec
+++ b/Protobuf.podspec
@@ -5,10 +5,10 @@
# dependent projects use the :git notation to refer to the library.
Pod::Spec.new do |s|
s.name = 'Protobuf'
- s.version = '3.1.0'
+ s.version = '3.4.1'
s.summary = 'Protocol Buffers v.3 runtime library for Objective-C.'
s.homepage = 'https://github.com/google/protobuf'
- s.license = 'New BSD'
+ s.license = '3-Clause BSD License'
s.authors = { 'The Protocol Buffers contributors' => 'protobuf@googlegroups.com' }
s.cocoapods_version = '>= 1.0'
@@ -34,8 +34,9 @@ Pod::Spec.new do |s|
s.user_target_xcconfig = { 'GCC_PREPROCESSOR_DEFINITIONS' => '$(inherited) GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS=1' }
s.pod_target_xcconfig = { 'GCC_PREPROCESSOR_DEFINITIONS' => '$(inherited) GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS=1' }
- s.ios.deployment_target = '7.1'
+ s.ios.deployment_target = '7.0'
s.osx.deployment_target = '10.9'
+ s.tvos.deployment_target = '9.0'
s.watchos.deployment_target = '2.0'
s.requires_arc = false
end
diff --git a/README.md b/README.md
index 2c1bce1a..3a4e6ed2 100644
--- a/README.md
+++ b/README.md
@@ -37,7 +37,7 @@ as well as a set of standard .proto files distributed along with protobuf.
If you are looking for an old version that is not available in the release
page, check out the maven repo here:
- [http://repo1.maven.org/maven2/com/google/protobuf/protoc/](http://repo1.maven.org/maven2/com/google/protobuf/protoc/)
+ [https://repo1.maven.org/maven2/com/google/protobuf/protoc/](https://repo1.maven.org/maven2/com/google/protobuf/protoc/)
These pre-built binaries are only provided for released versions. If you want
to use the github master version at HEAD, or you need to modify protobuf code,
@@ -54,24 +54,35 @@ Protobuf supports several different programming languages. For each programming
language, you can find instructions in the corresponding source directory about
how to install protobuf runtime for that specific language:
-| Language | Source |
-|--------------------------------------|-------------------------------------------------------|
-| C++ (include C++ runtime and protoc) | [src](src) |
-| Java | [java](java) |
-| Python | [python](python) |
-| Objective-C | [objectivec](objectivec) |
-| C# | [csharp](csharp) |
-| JavaNano | [javanano](javanano) |
-| JavaScript | [js](js) |
-| Ruby | [ruby](ruby) |
-| Go | [golang/protobuf](https://github.com/golang/protobuf) |
-| PHP | [php](php) |
+| Language | Source |
+|--------------------------------------|-------------------------------------------------------------|
+| C++ (include C++ runtime and protoc) | [src](src) |
+| Java | [java](java) |
+| Python | [python](python) |
+| Objective-C | [objectivec](objectivec) |
+| C# | [csharp](csharp) |
+| JavaNano | [javanano](javanano) |
+| JavaScript | [js](js) |
+| Ruby | [ruby](ruby) |
+| Go | [golang/protobuf](https://github.com/golang/protobuf) |
+| PHP | [php](php) |
+| Dart | [dart-lang/protobuf](https://github.com/dart-lang/protobuf) |
+Quick Start
+-----------
-Usage
------
+The best way to learn how to use protobuf is to follow the tutorials in our
+developer guide:
+
+https://developers.google.com/protocol-buffers/docs/tutorials
+
+If you want to learn from code examples, take a look at the examples in the
+[examples](examples) directory.
+
+Documentation
+-------------
The complete documentation for Protocol Buffers is available via the
web at:
- https://developers.google.com/protocol-buffers/
+https://developers.google.com/protocol-buffers/
diff --git a/WORKSPACE b/WORKSPACE
index 2a49e372..1066a0e6 100644
--- a/WORKSPACE
+++ b/WORKSPACE
@@ -1,3 +1,5 @@
+workspace(name = "com_google_protobuf")
+
new_git_repository(
name = "googletest",
build_file = "gmock.BUILD",
diff --git a/appveyor.bat b/appveyor.bat
index 916f4434..ca88b25c 100644
--- a/appveyor.bat
+++ b/appveyor.bat
@@ -19,11 +19,15 @@ goto :EOF
:build_csharp
echo Building C#
cd csharp\src
+REM The platform environment variable is implicitly used by msbuild;
+REM we don't want it.
+set platform=
dotnet restore
-dotnet build -c %configuration% Google.Protobuf Google.Protobuf.Test Google.Protobuf.Conformance || goto error
+dotnet build -c %configuration% || goto error
echo Testing C#
-dotnet test -c %configuration% Google.Protobuf.Test || goto error
+dotnet run -c %configuration% -f netcoreapp1.0 -p Google.Protobuf.Test\Google.Protobuf.Test.csproj || goto error
+dotnet run -c %configuration% -f net451 -p Google.Protobuf.Test\Google.Protobuf.Test.csproj || goto error
goto :EOF
diff --git a/appveyor.yml b/appveyor.yml
index 08d087b6..8b440b63 100644
--- a/appveyor.yml
+++ b/appveyor.yml
@@ -14,6 +14,7 @@ environment:
UNICODE: ON
- language: csharp
+ image: Visual Studio 2017
# Our build scripts run tests automatically; we don't want AppVeyor
# to try to detect them itself.
@@ -29,8 +30,6 @@ install:
- del /Q release-1.7.0.zip
- rename googletest-release-1.7.0 gtest
- move gtest gmock
- - curl -L -o dotnetsdk.exe "https://go.microsoft.com/fwlink/?LinkID=809122"
- - dotnetsdk.exe /install /quiet /norestart
before_build:
- if %platform%==Win32 set generator=Visual Studio 12
diff --git a/autogen.sh b/autogen.sh
index 9f266425..9560aaf1 100755
--- a/autogen.sh
+++ b/autogen.sh
@@ -35,7 +35,9 @@ if test ! -e gmock; then
unzip -q release-1.7.0.zip
rm release-1.7.0.zip
mv googlemock-release-1.7.0 gmock
+fi
+if test ! -e gmock/gtest; then
curl $curlopts -L -O https://github.com/google/googletest/archive/release-1.7.0.zip
unzip -q release-1.7.0.zip
rm release-1.7.0.zip
diff --git a/cmake/CMakeLists.txt b/cmake/CMakeLists.txt
index df3b2012..2351392d 100644
--- a/cmake/CMakeLists.txt
+++ b/cmake/CMakeLists.txt
@@ -14,6 +14,7 @@ project(protobuf C CXX)
# Options
option(protobuf_BUILD_TESTS "Build tests" ON)
option(protobuf_BUILD_EXAMPLES "Build examples" OFF)
+option(protobuf_BUILD_PROTOC_BINARIES "Build libprotoc and protoc compiler" ON)
if (BUILD_SHARED_LIBS)
set(protobuf_BUILD_SHARED_LIBS_DEFAULT ON)
else (BUILD_SHARED_LIBS)
@@ -135,12 +136,31 @@ endif (protobuf_BUILD_SHARED_LIBS)
if (MSVC)
# Build with multiple processes
add_definitions(/MP)
- add_definitions(/wd4244 /wd4267 /wd4018 /wd4355 /wd4800 /wd4251 /wd4996 /wd4146 /wd4305)
+ # MSVC warning suppressions
+ add_definitions(
+ /wd4018 # 'expression' : signed/unsigned mismatch
+ /wd4065 # switch statement contains 'default' but no 'case' labels
+ /wd4146 # unary minus operator applied to unsigned type, result still unsigned
+ /wd4244 # 'conversion' conversion from 'type1' to 'type2', possible loss of data
+ /wd4251 # 'identifier' : class 'type' needs to have dll-interface to be used by clients of class 'type2'
+ /wd4267 # 'var' : conversion from 'size_t' to 'type', possible loss of data
+ /wd4305 # 'identifier' : truncation from 'type1' to 'type2'
+ /wd4307 # 'operator' : integral constant overflow
+ /wd4309 # 'conversion' : truncation of constant value
+ /wd4334 # 'operator' : result of 32-bit shift implicitly converted to 64 bits (was 64-bit shift intended?)
+ /wd4355 # 'this' : used in base member initializer list
+ /wd4506 # no definition for inline function 'function'
+ /wd4800 # 'type' : forcing value to bool 'true' or 'false' (performance warning)
+ /wd4996 # The compiler encountered a deprecated declaration.
+ )
# Allow big object
add_definitions(/bigobj)
string(REPLACE "/" "\\" PROTOBUF_SOURCE_WIN32_PATH ${protobuf_SOURCE_DIR})
string(REPLACE "/" "\\" PROTOBUF_BINARY_WIN32_PATH ${protobuf_BINARY_DIR})
configure_file(extract_includes.bat.in extract_includes.bat)
+
+ # Suppress linker warnings about files with no symbols defined.
+ set(CMAKE_STATIC_LINKER_FLAGS /ignore:4221)
endif (MSVC)
get_filename_component(protobuf_source_dir ${protobuf_SOURCE_DIR} PATH)
@@ -165,8 +185,10 @@ endif (protobuf_UNICODE)
include(libprotobuf-lite.cmake)
include(libprotobuf.cmake)
-include(libprotoc.cmake)
-include(protoc.cmake)
+if (protobuf_BUILD_PROTOC_BINARIES)
+ include(libprotoc.cmake)
+ include(protoc.cmake)
+endif (protobuf_BUILD_PROTOC_BINARIES)
if (protobuf_BUILD_TESTS)
include(tests.cmake)
diff --git a/cmake/extract_includes.bat.in b/cmake/extract_includes.bat.in
index 085071db..deb6de3b 100644
--- a/cmake/extract_includes.bat.in
+++ b/cmake/extract_includes.bat.in
@@ -14,115 +14,118 @@ mkdir include\google\protobuf\compiler\ruby
mkdir include\google\protobuf\io
mkdir include\google\protobuf\stubs
mkdir include\google\protobuf\util
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\any.h include\google\protobuf\any.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\any.pb.h include\google\protobuf\any.pb.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\api.pb.h include\google\protobuf\api.pb.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\arena.h include\google\protobuf\arena.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\arenastring.h include\google\protobuf\arenastring.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\code_generator.h include\google\protobuf\compiler\code_generator.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\command_line_interface.h include\google\protobuf\compiler\command_line_interface.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\cpp\cpp_generator.h include\google\protobuf\compiler\cpp\cpp_generator.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\csharp\csharp_generator.h include\google\protobuf\compiler\csharp\csharp_generator.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\csharp\csharp_names.h include\google\protobuf\compiler\csharp\csharp_names.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\importer.h include\google\protobuf\compiler\importer.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\java\java_generator.h include\google\protobuf\compiler\java\java_generator.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\java\java_names.h include\google\protobuf\compiler\java\java_names.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\javanano\javanano_generator.h include\google\protobuf\compiler\javanano\javanano_generator.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\js\js_generator.h include\google\protobuf\compiler\js\js_generator.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\js\well_known_types_embed.h include\google\protobuf\compiler\js\well_known_types_embed.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\objectivec\objectivec_generator.h include\google\protobuf\compiler\objectivec\objectivec_generator.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\objectivec\objectivec_helpers.h include\google\protobuf\compiler\objectivec\objectivec_helpers.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\parser.h include\google\protobuf\compiler\parser.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\php\php_generator.h include\google\protobuf\compiler\php\php_generator.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\plugin.h include\google\protobuf\compiler\plugin.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\plugin.pb.h include\google\protobuf\compiler\plugin.pb.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\python\python_generator.h include\google\protobuf\compiler\python\python_generator.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\ruby\ruby_generator.h include\google\protobuf\compiler\ruby\ruby_generator.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\descriptor.h include\google\protobuf\descriptor.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\descriptor.pb.h include\google\protobuf\descriptor.pb.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\descriptor_database.h include\google\protobuf\descriptor_database.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\duration.pb.h include\google\protobuf\duration.pb.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\dynamic_message.h include\google\protobuf\dynamic_message.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\empty.pb.h include\google\protobuf\empty.pb.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\extension_set.h include\google\protobuf\extension_set.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\field_mask.pb.h include\google\protobuf\field_mask.pb.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\generated_enum_reflection.h include\google\protobuf\generated_enum_reflection.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\generated_enum_util.h include\google\protobuf\generated_enum_util.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\generated_message_reflection.h include\google\protobuf\generated_message_reflection.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\generated_message_util.h include\google\protobuf\generated_message_util.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\has_bits.h include\google\protobuf\has_bits.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\io\coded_stream.h include\google\protobuf\io\coded_stream.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\io\gzip_stream.h include\google\protobuf\io\gzip_stream.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\io\printer.h include\google\protobuf\io\printer.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\io\strtod.h include\google\protobuf\io\strtod.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\io\tokenizer.h include\google\protobuf\io\tokenizer.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\io\zero_copy_stream.h include\google\protobuf\io\zero_copy_stream.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\io\zero_copy_stream_impl.h include\google\protobuf\io\zero_copy_stream_impl.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\io\zero_copy_stream_impl_lite.h include\google\protobuf\io\zero_copy_stream_impl_lite.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\map.h include\google\protobuf\map.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\map_entry.h include\google\protobuf\map_entry.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\map_entry_lite.h include\google\protobuf\map_entry_lite.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\map_field.h include\google\protobuf\map_field.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\map_field_inl.h include\google\protobuf\map_field_inl.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\map_field_lite.h include\google\protobuf\map_field_lite.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\map_type_handler.h include\google\protobuf\map_type_handler.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\message.h include\google\protobuf\message.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\message_lite.h include\google\protobuf\message_lite.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\metadata.h include\google\protobuf\metadata.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\reflection.h include\google\protobuf\reflection.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\reflection_ops.h include\google\protobuf\reflection_ops.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\repeated_field.h include\google\protobuf\repeated_field.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\service.h include\google\protobuf\service.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\source_context.pb.h include\google\protobuf\source_context.pb.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\struct.pb.h include\google\protobuf\struct.pb.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomic_sequence_num.h include\google\protobuf\stubs\atomic_sequence_num.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops.h include\google\protobuf\stubs\atomicops.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_arm64_gcc.h include\google\protobuf\stubs\atomicops_internals_arm64_gcc.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_arm_gcc.h include\google\protobuf\stubs\atomicops_internals_arm_gcc.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_arm_qnx.h include\google\protobuf\stubs\atomicops_internals_arm_qnx.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_atomicword_compat.h include\google\protobuf\stubs\atomicops_internals_atomicword_compat.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_generic_c11_atomic.h include\google\protobuf\stubs\atomicops_internals_generic_c11_atomic.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_generic_gcc.h include\google\protobuf\stubs\atomicops_internals_generic_gcc.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_macosx.h include\google\protobuf\stubs\atomicops_internals_macosx.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_mips_gcc.h include\google\protobuf\stubs\atomicops_internals_mips_gcc.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_power.h include\google\protobuf\stubs\atomicops_internals_power.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_ppc_gcc.h include\google\protobuf\stubs\atomicops_internals_ppc_gcc.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_solaris.h include\google\protobuf\stubs\atomicops_internals_solaris.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_tsan.h include\google\protobuf\stubs\atomicops_internals_tsan.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_x86_gcc.h include\google\protobuf\stubs\atomicops_internals_x86_gcc.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_x86_msvc.h include\google\protobuf\stubs\atomicops_internals_x86_msvc.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\bytestream.h include\google\protobuf\stubs\bytestream.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\callback.h include\google\protobuf\stubs\callback.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\casts.h include\google\protobuf\stubs\casts.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\common.h include\google\protobuf\stubs\common.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\fastmem.h include\google\protobuf\stubs\fastmem.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\hash.h include\google\protobuf\stubs\hash.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\logging.h include\google\protobuf\stubs\logging.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\macros.h include\google\protobuf\stubs\macros.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\mutex.h include\google\protobuf\stubs\mutex.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\once.h include\google\protobuf\stubs\once.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\platform_macros.h include\google\protobuf\stubs\platform_macros.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\port.h include\google\protobuf\stubs\port.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\scoped_ptr.h include\google\protobuf\stubs\scoped_ptr.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\shared_ptr.h include\google\protobuf\stubs\shared_ptr.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\singleton.h include\google\protobuf\stubs\singleton.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\status.h include\google\protobuf\stubs\status.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\stl_util.h include\google\protobuf\stubs\stl_util.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\stringpiece.h include\google\protobuf\stubs\stringpiece.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\template_util.h include\google\protobuf\stubs\template_util.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\type_traits.h include\google\protobuf\stubs\type_traits.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\text_format.h include\google\protobuf\text_format.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\timestamp.pb.h include\google\protobuf\timestamp.pb.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\type.pb.h include\google\protobuf\type.pb.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\unknown_field_set.h include\google\protobuf\unknown_field_set.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\util\field_comparator.h include\google\protobuf\util\field_comparator.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\util\field_mask_util.h include\google\protobuf\util\field_mask_util.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\util\json_util.h include\google\protobuf\util\json_util.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\util\message_differencer.h include\google\protobuf\util\message_differencer.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\util\time_util.h include\google\protobuf\util\time_util.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\util\type_resolver.h include\google\protobuf\util\type_resolver.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\util\type_resolver_util.h include\google\protobuf\util\type_resolver_util.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\wire_format.h include\google\protobuf\wire_format.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\wire_format_lite.h include\google\protobuf\wire_format_lite.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\wire_format_lite_inl.h include\google\protobuf\wire_format_lite_inl.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\wrappers.pb.h include\google\protobuf\wrappers.pb.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\any.h" include\google\protobuf\any.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\any.pb.h" include\google\protobuf\any.pb.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\api.pb.h" include\google\protobuf\api.pb.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\arena.h" include\google\protobuf\arena.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\arena_impl.h" include\google\protobuf\arena_impl.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\arenastring.h" include\google\protobuf\arenastring.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\code_generator.h" include\google\protobuf\compiler\code_generator.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\command_line_interface.h" include\google\protobuf\compiler\command_line_interface.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\cpp\cpp_generator.h" include\google\protobuf\compiler\cpp\cpp_generator.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\csharp\csharp_generator.h" include\google\protobuf\compiler\csharp\csharp_generator.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\csharp\csharp_names.h" include\google\protobuf\compiler\csharp\csharp_names.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\importer.h" include\google\protobuf\compiler\importer.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\java\java_generator.h" include\google\protobuf\compiler\java\java_generator.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\java\java_names.h" include\google\protobuf\compiler\java\java_names.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\javanano\javanano_generator.h" include\google\protobuf\compiler\javanano\javanano_generator.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\js\js_generator.h" include\google\protobuf\compiler\js\js_generator.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\js\well_known_types_embed.h" include\google\protobuf\compiler\js\well_known_types_embed.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\objectivec\objectivec_generator.h" include\google\protobuf\compiler\objectivec\objectivec_generator.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\objectivec\objectivec_helpers.h" include\google\protobuf\compiler\objectivec\objectivec_helpers.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\parser.h" include\google\protobuf\compiler\parser.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\php\php_generator.h" include\google\protobuf\compiler\php\php_generator.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\plugin.h" include\google\protobuf\compiler\plugin.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\plugin.pb.h" include\google\protobuf\compiler\plugin.pb.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\python\python_generator.h" include\google\protobuf\compiler\python\python_generator.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\ruby\ruby_generator.h" include\google\protobuf\compiler\ruby\ruby_generator.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\descriptor.h" include\google\protobuf\descriptor.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\descriptor.pb.h" include\google\protobuf\descriptor.pb.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\descriptor_database.h" include\google\protobuf\descriptor_database.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\duration.pb.h" include\google\protobuf\duration.pb.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\dynamic_message.h" include\google\protobuf\dynamic_message.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\empty.pb.h" include\google\protobuf\empty.pb.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\extension_set.h" include\google\protobuf\extension_set.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\field_mask.pb.h" include\google\protobuf\field_mask.pb.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\generated_enum_reflection.h" include\google\protobuf\generated_enum_reflection.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\generated_enum_util.h" include\google\protobuf\generated_enum_util.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\generated_message_reflection.h" include\google\protobuf\generated_message_reflection.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\generated_message_table_driven.h" include\google\protobuf\generated_message_table_driven.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\generated_message_util.h" include\google\protobuf\generated_message_util.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\has_bits.h" include\google\protobuf\has_bits.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\io\coded_stream.h" include\google\protobuf\io\coded_stream.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\io\gzip_stream.h" include\google\protobuf\io\gzip_stream.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\io\printer.h" include\google\protobuf\io\printer.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\io\strtod.h" include\google\protobuf\io\strtod.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\io\tokenizer.h" include\google\protobuf\io\tokenizer.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\io\zero_copy_stream.h" include\google\protobuf\io\zero_copy_stream.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\io\zero_copy_stream_impl.h" include\google\protobuf\io\zero_copy_stream_impl.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\io\zero_copy_stream_impl_lite.h" include\google\protobuf\io\zero_copy_stream_impl_lite.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\map.h" include\google\protobuf\map.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\map_entry.h" include\google\protobuf\map_entry.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\map_entry_lite.h" include\google\protobuf\map_entry_lite.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\map_field.h" include\google\protobuf\map_field.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\map_field_inl.h" include\google\protobuf\map_field_inl.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\map_field_lite.h" include\google\protobuf\map_field_lite.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\map_type_handler.h" include\google\protobuf\map_type_handler.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\message.h" include\google\protobuf\message.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\message_lite.h" include\google\protobuf\message_lite.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\metadata.h" include\google\protobuf\metadata.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\metadata_lite.h" include\google\protobuf\metadata_lite.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\reflection.h" include\google\protobuf\reflection.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\reflection_ops.h" include\google\protobuf\reflection_ops.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\repeated_field.h" include\google\protobuf\repeated_field.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\service.h" include\google\protobuf\service.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\source_context.pb.h" include\google\protobuf\source_context.pb.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\struct.pb.h" include\google\protobuf\struct.pb.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomic_sequence_num.h" include\google\protobuf\stubs\atomic_sequence_num.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops.h" include\google\protobuf\stubs\atomicops.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_arm64_gcc.h" include\google\protobuf\stubs\atomicops_internals_arm64_gcc.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_arm_gcc.h" include\google\protobuf\stubs\atomicops_internals_arm_gcc.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_arm_qnx.h" include\google\protobuf\stubs\atomicops_internals_arm_qnx.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_atomicword_compat.h" include\google\protobuf\stubs\atomicops_internals_atomicword_compat.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_generic_c11_atomic.h" include\google\protobuf\stubs\atomicops_internals_generic_c11_atomic.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_generic_gcc.h" include\google\protobuf\stubs\atomicops_internals_generic_gcc.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_mips_gcc.h" include\google\protobuf\stubs\atomicops_internals_mips_gcc.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_power.h" include\google\protobuf\stubs\atomicops_internals_power.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_ppc_gcc.h" include\google\protobuf\stubs\atomicops_internals_ppc_gcc.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_solaris.h" include\google\protobuf\stubs\atomicops_internals_solaris.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_tsan.h" include\google\protobuf\stubs\atomicops_internals_tsan.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_x86_gcc.h" include\google\protobuf\stubs\atomicops_internals_x86_gcc.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_x86_msvc.h" include\google\protobuf\stubs\atomicops_internals_x86_msvc.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\bytestream.h" include\google\protobuf\stubs\bytestream.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\callback.h" include\google\protobuf\stubs\callback.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\casts.h" include\google\protobuf\stubs\casts.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\common.h" include\google\protobuf\stubs\common.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\fastmem.h" include\google\protobuf\stubs\fastmem.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\hash.h" include\google\protobuf\stubs\hash.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\logging.h" include\google\protobuf\stubs\logging.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\macros.h" include\google\protobuf\stubs\macros.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\mutex.h" include\google\protobuf\stubs\mutex.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\once.h" include\google\protobuf\stubs\once.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\platform_macros.h" include\google\protobuf\stubs\platform_macros.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\port.h" include\google\protobuf\stubs\port.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\scoped_ptr.h" include\google\protobuf\stubs\scoped_ptr.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\shared_ptr.h" include\google\protobuf\stubs\shared_ptr.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\singleton.h" include\google\protobuf\stubs\singleton.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\status.h" include\google\protobuf\stubs\status.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\stl_util.h" include\google\protobuf\stubs\stl_util.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\stringpiece.h" include\google\protobuf\stubs\stringpiece.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\template_util.h" include\google\protobuf\stubs\template_util.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\type_traits.h" include\google\protobuf\stubs\type_traits.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\text_format.h" include\google\protobuf\text_format.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\timestamp.pb.h" include\google\protobuf\timestamp.pb.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\type.pb.h" include\google\protobuf\type.pb.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\unknown_field_set.h" include\google\protobuf\unknown_field_set.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\util\delimited_message_util.h" include\google\protobuf\util\delimited_message_util.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\util\field_comparator.h" include\google\protobuf\util\field_comparator.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\util\field_mask_util.h" include\google\protobuf\util\field_mask_util.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\util\json_util.h" include\google\protobuf\util\json_util.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\util\message_differencer.h" include\google\protobuf\util\message_differencer.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\util\time_util.h" include\google\protobuf\util\time_util.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\util\type_resolver.h" include\google\protobuf\util\type_resolver.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\util\type_resolver_util.h" include\google\protobuf\util\type_resolver_util.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\wire_format.h" include\google\protobuf\wire_format.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\wire_format_lite.h" include\google\protobuf\wire_format_lite.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\wire_format_lite_inl.h" include\google\protobuf\wire_format_lite_inl.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\wrappers.pb.h" include\google\protobuf\wrappers.pb.h
diff --git a/cmake/install.cmake b/cmake/install.cmake
index 73e31984..82036cb6 100644
--- a/cmake/install.cmake
+++ b/cmake/install.cmake
@@ -1,9 +1,16 @@
include(GNUInstallDirs)
-foreach(_library
- libprotobuf-lite
- libprotobuf
- libprotoc)
+configure_file(${CMAKE_CURRENT_SOURCE_DIR}/protobuf.pc.cmake
+ ${CMAKE_CURRENT_BINARY_DIR}/protobuf.pc @ONLY)
+configure_file(${CMAKE_CURRENT_SOURCE_DIR}/protobuf-lite.pc.cmake
+ ${CMAKE_CURRENT_BINARY_DIR}/protobuf-lite.pc @ONLY)
+
+set(_protobuf_libraries libprotobuf-lite libprotobuf)
+if (protobuf_BUILD_PROTOC_BINARIES)
+ list(APPEND _protobuf_libraries libprotoc)
+endif (protobuf_BUILD_PROTOC_BINARIES)
+
+foreach(_library ${_protobuf_libraries})
set_property(TARGET ${_library}
PROPERTY INTERFACE_INCLUDE_DIRECTORIES
$<BUILD_INTERFACE:${protobuf_source_dir}/src>
@@ -14,24 +21,22 @@ foreach(_library
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT ${_library})
endforeach()
-install(TARGETS protoc EXPORT protobuf-targets
- RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT protoc)
+if (protobuf_BUILD_PROTOC_BINARIES)
+ install(TARGETS protoc EXPORT protobuf-targets
+ RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT protoc)
+endif (protobuf_BUILD_PROTOC_BINARIES)
+
+install(FILES ${CMAKE_CURRENT_BINARY_DIR}/protobuf.pc ${CMAKE_CURRENT_BINARY_DIR}/protobuf-lite.pc DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig")
file(STRINGS extract_includes.bat.in _extract_strings
REGEX "^copy")
foreach(_extract_string ${_extract_strings})
- string(REPLACE "copy \${PROTOBUF_SOURCE_WIN32_PATH}\\" ""
- _extract_string ${_extract_string})
- string(REPLACE "\\" "/" _extract_string ${_extract_string})
- string(REGEX MATCH "^[^ ]+"
- _extract_from ${_extract_string})
- string(REGEX REPLACE "^${_extract_from} ([^$]+)" "\\1"
- _extract_to ${_extract_string})
- get_filename_component(_extract_from "${protobuf_SOURCE_DIR}/${_extract_from}" ABSOLUTE)
- get_filename_component(_extract_name ${_extract_to} NAME)
- get_filename_component(_extract_to ${_extract_to} PATH)
- string(REPLACE "include/" "${CMAKE_INSTALL_INCLUDEDIR}/"
- _extract_to "${_extract_to}")
+ string(REGEX REPLACE "^.* .+ include\\\\(.+)$" "\\1"
+ _header ${_extract_string})
+ string(REPLACE "\\" "/" _header ${_header})
+ get_filename_component(_extract_from "${protobuf_SOURCE_DIR}/../src/${_header}" ABSOLUTE)
+ get_filename_component(_extract_name ${_header} NAME)
+ get_filename_component(_extract_to "${CMAKE_INSTALL_INCLUDEDIR}/${_header}" PATH)
if(EXISTS "${_extract_from}")
install(FILES "${_extract_from}"
DESTINATION "${_extract_to}"
@@ -100,10 +105,18 @@ configure_file(protobuf-options.cmake
${CMAKE_INSTALL_CMAKEDIR}/protobuf-options.cmake @ONLY)
# Allows the build directory to be used as a find directory.
-export(TARGETS libprotobuf-lite libprotobuf libprotoc protoc
- NAMESPACE protobuf::
- FILE ${CMAKE_INSTALL_CMAKEDIR}/protobuf-targets.cmake
-)
+
+if (protobuf_BUILD_PROTOC_BINARIES)
+ export(TARGETS libprotobuf-lite libprotobuf libprotoc protoc
+ NAMESPACE protobuf::
+ FILE ${CMAKE_INSTALL_CMAKEDIR}/protobuf-targets.cmake
+ )
+else (protobuf_BUILD_PROTOC_BINARIES)
+ export(TARGETS libprotobuf-lite libprotobuf
+ NAMESPACE protobuf::
+ FILE ${CMAKE_INSTALL_CMAKEDIR}/protobuf-targets.cmake
+ )
+endif (protobuf_BUILD_PROTOC_BINARIES)
install(EXPORT protobuf-targets
DESTINATION "${CMAKE_INSTALL_CMAKEDIR}"
diff --git a/cmake/libprotobuf-lite.cmake b/cmake/libprotobuf-lite.cmake
index 036b0517..9e1fab0a 100644
--- a/cmake/libprotobuf-lite.cmake
+++ b/cmake/libprotobuf-lite.cmake
@@ -2,6 +2,7 @@ set(libprotobuf_lite_files
${protobuf_source_dir}/src/google/protobuf/arena.cc
${protobuf_source_dir}/src/google/protobuf/arenastring.cc
${protobuf_source_dir}/src/google/protobuf/extension_set.cc
+ ${protobuf_source_dir}/src/google/protobuf/generated_message_table_driven_lite.cc
${protobuf_source_dir}/src/google/protobuf/generated_message_util.cc
${protobuf_source_dir}/src/google/protobuf/io/coded_stream.cc
${protobuf_source_dir}/src/google/protobuf/io/zero_copy_stream.cc
@@ -13,6 +14,7 @@ set(libprotobuf_lite_files
${protobuf_source_dir}/src/google/protobuf/stubs/bytestream.cc
${protobuf_source_dir}/src/google/protobuf/stubs/common.cc
${protobuf_source_dir}/src/google/protobuf/stubs/int128.cc
+ ${protobuf_source_dir}/src/google/protobuf/stubs/io_win32.cc
${protobuf_source_dir}/src/google/protobuf/stubs/once.cc
${protobuf_source_dir}/src/google/protobuf/stubs/status.cc
${protobuf_source_dir}/src/google/protobuf/stubs/statusor.cc
@@ -24,8 +26,32 @@ set(libprotobuf_lite_files
${protobuf_source_dir}/src/google/protobuf/wire_format_lite.cc
)
+set(libprotobuf_lite_includes
+ ${protobuf_source_dir}/src/google/protobuf/arena.h
+ ${protobuf_source_dir}/src/google/protobuf/arenastring.h
+ ${protobuf_source_dir}/src/google/protobuf/extension_set.h
+ ${protobuf_source_dir}/src/google/protobuf/generated_message_util.h
+ ${protobuf_source_dir}/src/google/protobuf/io/coded_stream.h
+ ${protobuf_source_dir}/src/google/protobuf/io/zero_copy_stream.h
+ ${protobuf_source_dir}/src/google/protobuf/io/zero_copy_stream_impl_lite.h
+ ${protobuf_source_dir}/src/google/protobuf/message_lite.h
+ ${protobuf_source_dir}/src/google/protobuf/repeated_field.h
+ ${protobuf_source_dir}/src/google/protobuf/stubs/atomicops_internals_x86_msvc.h
+ ${protobuf_source_dir}/src/google/protobuf/stubs/bytestream.h
+ ${protobuf_source_dir}/src/google/protobuf/stubs/common.h
+ ${protobuf_source_dir}/src/google/protobuf/stubs/int128.h
+ ${protobuf_source_dir}/src/google/protobuf/stubs/once.h
+ ${protobuf_source_dir}/src/google/protobuf/stubs/status.h
+ ${protobuf_source_dir}/src/google/protobuf/stubs/statusor.h
+ ${protobuf_source_dir}/src/google/protobuf/stubs/stringpiece.h
+ ${protobuf_source_dir}/src/google/protobuf/stubs/stringprintf.h
+ ${protobuf_source_dir}/src/google/protobuf/stubs/strutil.h
+ ${protobuf_source_dir}/src/google/protobuf/stubs/time.h
+ ${protobuf_source_dir}/src/google/protobuf/wire_format_lite.h
+)
+
add_library(libprotobuf-lite ${protobuf_SHARED_OR_STATIC}
- ${libprotobuf_lite_files})
+ ${libprotobuf_lite_files} ${libprotobuf_lite_includes})
target_link_libraries(libprotobuf-lite ${CMAKE_THREAD_LIBS_INIT})
target_include_directories(libprotobuf-lite PUBLIC ${protobuf_source_dir}/src)
if(MSVC AND protobuf_BUILD_SHARED_LIBS)
diff --git a/cmake/libprotobuf.cmake b/cmake/libprotobuf.cmake
index 26e1f356..72db915b 100644
--- a/cmake/libprotobuf.cmake
+++ b/cmake/libprotobuf.cmake
@@ -13,6 +13,7 @@ set(libprotobuf_files
${protobuf_source_dir}/src/google/protobuf/extension_set_heavy.cc
${protobuf_source_dir}/src/google/protobuf/field_mask.pb.cc
${protobuf_source_dir}/src/google/protobuf/generated_message_reflection.cc
+ ${protobuf_source_dir}/src/google/protobuf/generated_message_table_driven.cc
${protobuf_source_dir}/src/google/protobuf/io/gzip_stream.cc
${protobuf_source_dir}/src/google/protobuf/io/printer.cc
${protobuf_source_dir}/src/google/protobuf/io/strtod.cc
@@ -30,6 +31,7 @@ set(libprotobuf_files
${protobuf_source_dir}/src/google/protobuf/timestamp.pb.cc
${protobuf_source_dir}/src/google/protobuf/type.pb.cc
${protobuf_source_dir}/src/google/protobuf/unknown_field_set.cc
+ ${protobuf_source_dir}/src/google/protobuf/util/delimited_message_util.cc
${protobuf_source_dir}/src/google/protobuf/util/field_comparator.cc
${protobuf_source_dir}/src/google/protobuf/util/field_mask_util.cc
${protobuf_source_dir}/src/google/protobuf/util/internal/datapiece.cc
@@ -54,8 +56,64 @@ set(libprotobuf_files
${protobuf_source_dir}/src/google/protobuf/wrappers.pb.cc
)
+set(libprotobuf_includes
+ ${protobuf_source_dir}/src/google/protobuf/any.h
+ ${protobuf_source_dir}/src/google/protobuf/any.pb.h
+ ${protobuf_source_dir}/src/google/protobuf/api.pb.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/importer.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/parser.h
+ ${protobuf_source_dir}/src/google/protobuf/descriptor.h
+ ${protobuf_source_dir}/src/google/protobuf/descriptor.pb.h
+ ${protobuf_source_dir}/src/google/protobuf/descriptor_database.h
+ ${protobuf_source_dir}/src/google/protobuf/duration.pb.h
+ ${protobuf_source_dir}/src/google/protobuf/dynamic_message.h
+ ${protobuf_source_dir}/src/google/protobuf/empty.pb.h
+ ${protobuf_source_dir}/src/google/protobuf/field_mask.pb.h
+ ${protobuf_source_dir}/src/google/protobuf/generated_message_reflection.h
+ ${protobuf_source_dir}/src/google/protobuf/io/gzip_stream.h
+ ${protobuf_source_dir}/src/google/protobuf/io/printer.h
+ ${protobuf_source_dir}/src/google/protobuf/io/strtod.h
+ ${protobuf_source_dir}/src/google/protobuf/io/tokenizer.h
+ ${protobuf_source_dir}/src/google/protobuf/io/zero_copy_stream_impl.h
+ ${protobuf_source_dir}/src/google/protobuf/map_field.h
+ ${protobuf_source_dir}/src/google/protobuf/message.h
+ ${protobuf_source_dir}/src/google/protobuf/reflection_ops.h
+ ${protobuf_source_dir}/src/google/protobuf/service.h
+ ${protobuf_source_dir}/src/google/protobuf/source_context.pb.h
+ ${protobuf_source_dir}/src/google/protobuf/struct.pb.h
+ ${protobuf_source_dir}/src/google/protobuf/stubs/mathlimits.h
+ ${protobuf_source_dir}/src/google/protobuf/stubs/substitute.h
+ ${protobuf_source_dir}/src/google/protobuf/text_format.h
+ ${protobuf_source_dir}/src/google/protobuf/timestamp.pb.h
+ ${protobuf_source_dir}/src/google/protobuf/type.pb.h
+ ${protobuf_source_dir}/src/google/protobuf/unknown_field_set.h
+ ${protobuf_source_dir}/src/google/protobuf/util/delimited_message_util.h
+ ${protobuf_source_dir}/src/google/protobuf/util/field_comparator.h
+ ${protobuf_source_dir}/src/google/protobuf/util/field_mask_util.h
+ ${protobuf_source_dir}/src/google/protobuf/util/internal/datapiece.h
+ ${protobuf_source_dir}/src/google/protobuf/util/internal/default_value_objectwriter.h
+ ${protobuf_source_dir}/src/google/protobuf/util/internal/error_listener.h
+ ${protobuf_source_dir}/src/google/protobuf/util/internal/field_mask_utility.h
+ ${protobuf_source_dir}/src/google/protobuf/util/internal/json_escaping.h
+ ${protobuf_source_dir}/src/google/protobuf/util/internal/json_objectwriter.h
+ ${protobuf_source_dir}/src/google/protobuf/util/internal/json_stream_parser.h
+ ${protobuf_source_dir}/src/google/protobuf/util/internal/object_writer.h
+ ${protobuf_source_dir}/src/google/protobuf/util/internal/proto_writer.h
+ ${protobuf_source_dir}/src/google/protobuf/util/internal/protostream_objectsource.h
+ ${protobuf_source_dir}/src/google/protobuf/util/internal/protostream_objectwriter.h
+ ${protobuf_source_dir}/src/google/protobuf/util/internal/type_info.h
+ ${protobuf_source_dir}/src/google/protobuf/util/internal/type_info_test_helper.h
+ ${protobuf_source_dir}/src/google/protobuf/util/internal/utility.h
+ ${protobuf_source_dir}/src/google/protobuf/util/json_util.h
+ ${protobuf_source_dir}/src/google/protobuf/util/message_differencer.h
+ ${protobuf_source_dir}/src/google/protobuf/util/time_util.h
+ ${protobuf_source_dir}/src/google/protobuf/util/type_resolver_util.h
+ ${protobuf_source_dir}/src/google/protobuf/wire_format.h
+ ${protobuf_source_dir}/src/google/protobuf/wrappers.pb.h
+)
+
add_library(libprotobuf ${protobuf_SHARED_OR_STATIC}
- ${libprotobuf_lite_files} ${libprotobuf_files})
+ ${libprotobuf_lite_files} ${libprotobuf_files} ${libprotobuf_includes})
target_link_libraries(libprotobuf ${CMAKE_THREAD_LIBS_INIT})
if(protobuf_WITH_ZLIB)
target_link_libraries(libprotobuf ${ZLIB_LIBRARIES})
diff --git a/cmake/libprotoc.cmake b/cmake/libprotoc.cmake
index 2d238449..107c1c52 100644
--- a/cmake/libprotoc.cmake
+++ b/cmake/libprotoc.cmake
@@ -11,6 +11,7 @@ set(libprotoc_files
${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_map_field.cc
${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_message.cc
${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_message_field.cc
+ ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.cc
${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_primitive_field.cc
${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_service.cc
${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_string_field.cc
@@ -94,8 +95,128 @@ set(libprotoc_files
${protobuf_source_dir}/src/google/protobuf/compiler/zip_writer.cc
)
+set(libprotoc_headers
+ ${protobuf_source_dir}/src/google/protobuf/compiler/code_generator.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/command_line_interface.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/importer.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/mock_code_generator.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/package_info.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/parser.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/plugin.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/plugin.pb.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/subprocess.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/zip_writer.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_enum.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_enum_field.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_extension.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_field.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_file.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_generator.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_helpers.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_map_field.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_message.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_message_field.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_options.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_primitive_field.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_service.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_string_field.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_unittest.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_doc_comment.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_enum.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_enum_field.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_field_base.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_generator.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_helpers.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_map_field.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_message.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_message_field.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_names.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_options.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_primitive_field.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_reflection_class.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_source_generator_base.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_wrapper_field.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_context.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_doc_comment.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_enum.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_enum_field.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_enum_field_lite.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_enum_lite.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_extension.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_extension_lite.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_field.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_file.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_generator.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_generator_factory.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_helpers.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_lazy_message_field.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_lazy_message_field_lite.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_map_field.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_map_field_lite.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_message.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_message_builder.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_message_builder_lite.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_message_field.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_message_field_lite.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_message_lite.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_names.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_name_resolver.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_options.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_primitive_field.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_primitive_field_lite.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_service.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_shared_code_generator.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_string_field.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_string_field_lite.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_enum.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_enum_field.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_extension.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_field.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_file.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_generator.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_helpers.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_map_field.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_message.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_message_field.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_params.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/javanano/javanano_primitive_field.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/js/js_generator.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/js/well_known_types_embed.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_enum.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_enum_field.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_extension.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_field.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_file.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_generator.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_helpers.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_map_field.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_message.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_message_field.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_oneof.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_primitive_field.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/php/php_generator.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/python/python_generator.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/ruby/ruby_generator.h
+ ${protobuf_source_dir}/src/google/protobuf/compiler/plugin.pb.h
+)
+
+set(js_well_known_types_sources
+ ${protobuf_source_dir}/src/google/protobuf/compiler/js/well_known_types/any.js
+ ${protobuf_source_dir}/src/google/protobuf/compiler/js/well_known_types/struct.js
+ ${protobuf_source_dir}/src/google/protobuf/compiler/js/well_known_types/timestamp.js
+)
+add_executable(js_embed ${protobuf_source_dir}/src/google/protobuf/compiler/js/embed.cc)
+add_custom_command(
+ OUTPUT ${protobuf_source_dir}/src/google/protobuf/compiler/js/well_known_types_embed.cc
+ DEPENDS js_embed ${js_well_known_types_sources}
+ COMMAND js_embed ${js_well_known_types_sources} > ${protobuf_source_dir}/src/google/protobuf/compiler/js/well_known_types_embed.cc
+)
+
add_library(libprotoc ${protobuf_SHARED_OR_STATIC}
- ${libprotoc_files})
+ ${libprotoc_files} ${libprotoc_headers})
target_link_libraries(libprotoc libprotobuf)
if(MSVC AND protobuf_BUILD_SHARED_LIBS)
target_compile_definitions(libprotoc
diff --git a/cmake/protobuf-config-version.cmake.in b/cmake/protobuf-config-version.cmake.in
index 0036c9ef..3fa01763 100644
--- a/cmake/protobuf-config-version.cmake.in
+++ b/cmake/protobuf-config-version.cmake.in
@@ -17,39 +17,41 @@ endif()
set(PACKAGE_VERSION_COMPATIBLE TRUE) #Assume true until shown otherwise
-if(NOT PACKAGE_FIND_VERSION_MAJOR EQUAL "@protobuf_VERSION_MAJOR@")
- set(PACKAGE_VERSION_COMPATIBLE FALSE)
-elseif(PACKAGE_FIND_VERSION VERSION_GREATER PACKAGE_VERSION)
- set(PACKAGE_VERSION_COMPATIBLE FALSE)
-elseif(PACKAGE_FIND_VERSION VERSION_EQUAL PACKAGE_VERSION)
- # Do not match prerelease versions to non-prerelease version requests.
- if(NOT "@protobuf_VERSION_PRERELEASE@" STREQUAL "" AND PACKAGE_FIND_VERSION_PRERELEASE STREQUAL "")
- message(AUTHOR_WARNING "To use this prerelease version of ${PACKAGE_FIND_NAME}, set ${PACKAGE_FIND_NAME}_FIND_VERSION_PRERELEASE to '@protobuf_VERSION_PRERELEASE@' or greater.")
+if(PACKAGE_FIND_VERSION) #Only perform version checks if one is given
+ if(NOT PACKAGE_FIND_VERSION_MAJOR EQUAL "@protobuf_VERSION_MAJOR@")
set(PACKAGE_VERSION_COMPATIBLE FALSE)
- endif()
-
- # Not robustly SemVer compliant, but protobuf never uses '.' separated prerelease identifiers.
- if(PACKAGE_FIND_VERSION_PRERELEASE STRGREATER "@protobuf_VERSION_PRERELEASE@")
+ elseif(PACKAGE_FIND_VERSION VERSION_GREATER PACKAGE_VERSION)
set(PACKAGE_VERSION_COMPATIBLE FALSE)
+ elseif(PACKAGE_FIND_VERSION VERSION_EQUAL PACKAGE_VERSION)
+ # Do not match prerelease versions to non-prerelease version requests.
+ if(NOT "@protobuf_VERSION_PRERELEASE@" STREQUAL "" AND PACKAGE_FIND_VERSION_PRERELEASE STREQUAL "")
+ message(AUTHOR_WARNING "To use this prerelease version of ${PACKAGE_FIND_NAME}, set ${PACKAGE_FIND_NAME}_FIND_VERSION_PRERELEASE to '@protobuf_VERSION_PRERELEASE@' or greater.")
+ set(PACKAGE_VERSION_COMPATIBLE FALSE)
+ endif()
+
+ # Not robustly SemVer compliant, but protobuf never uses '.' separated prerelease identifiers.
+ if(PACKAGE_FIND_VERSION_PRERELEASE STRGREATER "@protobuf_VERSION_PRERELEASE@")
+ set(PACKAGE_VERSION_COMPATIBLE FALSE)
+ endif()
endif()
endif()
# Check and save build options used to create this package
macro(_check_and_save_build_option OPTION VALUE)
if(DEFINED ${PACKAGE_FIND_NAME}_${OPTION} AND
- NOT ${PACKAGE_FIND_NAME}_${OPTION} EQUAL VALUE)
+ NOT ${PACKAGE_FIND_NAME}_${OPTION} STREQUAL ${VALUE})
set(PACKAGE_VERSION_UNSUITABLE TRUE)
endif()
- set(${PACKAGE_FIND_NAME}_${OPTION} ${VALUE})
+ set(${PACKAGE_FIND_NAME}_${OPTION} ${VALUE} PARENT_SCOPE)
endmacro()
_check_and_save_build_option(WITH_ZLIB @protobuf_WITH_ZLIB@)
_check_and_save_build_option(MSVC_STATIC_RUNTIME @protobuf_MSVC_STATIC_RUNTIME@)
_check_and_save_build_option(BUILD_SHARED_LIBS @protobuf_BUILD_SHARED_LIBS@)
# if the installed or the using project don't have CMAKE_SIZEOF_VOID_P set, ignore it:
-if(NOT "${CMAKE_SIZEOF_VOID_P}" STREQUAL "" AND NOT "@CMAKE_SIZEOF_VOID_P@" STREQUAL "")
+if(CMAKE_SIZEOF_VOID_P AND "@CMAKE_SIZEOF_VOID_P@")
# check that the installed version has the same 32/64bit-ness as the one which is currently searching:
- if(NOT CMAKE_SIZEOF_VOID_P STREQUAL "@CMAKE_SIZEOF_VOID_P@")
+ if(NOT CMAKE_SIZEOF_VOID_P EQUAL "@CMAKE_SIZEOF_VOID_P@")
math(EXPR installedBits "@CMAKE_SIZEOF_VOID_P@ * 8")
set(PACKAGE_VERSION "${PACKAGE_VERSION} (${installedBits}bit)")
set(PACKAGE_VERSION_UNSUITABLE TRUE)
diff --git a/cmake/protobuf-config.cmake.in b/cmake/protobuf-config.cmake.in
index a044fe5c..fd67edc3 100644
--- a/cmake/protobuf-config.cmake.in
+++ b/cmake/protobuf-config.cmake.in
@@ -7,6 +7,114 @@ include("${CMAKE_CURRENT_LIST_DIR}/protobuf-options.cmake")
# Imported targets
include("${CMAKE_CURRENT_LIST_DIR}/protobuf-targets.cmake")
+function(protobuf_generate)
+ include(CMakeParseArguments)
+
+ set(_options APPEND_PATH)
+ set(_singleargs LANGUAGE OUT_VAR EXPORT_MACRO)
+ if(COMMAND target_sources)
+ list(APPEND _singleargs TARGET)
+ endif()
+ set(_multiargs PROTOS IMPORT_DIRS GENERATE_EXTENSIONS)
+
+ cmake_parse_arguments(protobuf_generate "${_options}" "${_singleargs}" "${_multiargs}" "${ARGN}")
+
+ if(NOT protobuf_generate_PROTOS AND NOT protobuf_generate_TARGET)
+ message(SEND_ERROR "Error: protobuf_generate called without any targets or source files")
+ return()
+ endif()
+
+ if(NOT protobuf_generate_OUT_VAR AND NOT protobuf_generate_TARGET)
+ message(SEND_ERROR "Error: protobuf_generate called without a target or output variable")
+ return()
+ endif()
+
+ if(NOT protobuf_generate_LANGUAGE)
+ set(protobuf_generate_LANGUAGE cpp)
+ endif()
+ string(TOLOWER ${protobuf_generate_LANGUAGE} protobuf_generate_LANGUAGE)
+
+ if(protobuf_generate_EXPORT_MACRO AND protobuf_generate_LANGUAGE STREQUAL cpp)
+ set(_dll_export_decl "dllexport_decl=${protobuf_generate_EXPORT_MACRO}:")
+ endif()
+
+ if(NOT protobuf_GENERATE_EXTENSIONS)
+ if(protobuf_generate_LANGUAGE STREQUAL cpp)
+ set(protobuf_GENERATE_EXTENSIONS .pb.h .pb.cc)
+ elseif(protobuf_generate_LANGUAGE STREQUAL python)
+ set(protobuf_GENERATE_EXTENSIONS _pb2.py)
+ else()
+ message(SEND_ERROR "Error: protobuf_generate given unknown Language ${LANGUAGE}, please provide a value for GENERATE_EXTENSIONS")
+ return()
+ endif()
+ endif()
+
+ if(protobuf_generate_TARGET)
+ get_target_property(_source_list ${protobuf_generate_TARGET} SOURCES)
+ foreach(_file ${_source_list})
+ if(_file MATCHES "proto$")
+ list(APPEND protobuf_generate_PROTOS ${_file})
+ endif()
+ endforeach()
+ endif()
+
+ if(NOT protobuf_generate_PROTOS)
+ message(SEND_ERROR "Error: protobuf_generate could not find any .proto files")
+ return()
+ endif()
+
+ if(protobuf_generate_APPEND_PATH)
+ # Create an include path for each file specified
+ foreach(_file ${protobuf_generate_PROTOS})
+ get_filename_component(_abs_file ${_file} ABSOLUTE)
+ get_filename_component(_abs_path ${_abs_file} PATH)
+ list(FIND _protobuf_include_path ${_abs_path} _contains_already)
+ if(${_contains_already} EQUAL -1)
+ list(APPEND _protobuf_include_path -I ${_abs_path})
+ endif()
+ endforeach()
+ else()
+ set(_protobuf_include_path -I ${CMAKE_CURRENT_SOURCE_DIR})
+ endif()
+
+ foreach(DIR ${protobuf_generate_IMPORT_DIRS})
+ get_filename_component(ABS_PATH ${DIR} ABSOLUTE)
+ list(FIND _protobuf_include_path ${ABS_PATH} _contains_already)
+ if(${_contains_already} EQUAL -1)
+ list(APPEND _protobuf_include_path -I ${ABS_PATH})
+ endif()
+ endforeach()
+
+ set(_generated_srcs_all)
+ foreach(_proto ${protobuf_generate_PROTOS})
+ get_filename_component(_abs_file ${_proto} ABSOLUTE)
+ get_filename_component(_basename ${_proto} NAME_WE)
+
+ set(_generated_srcs)
+ foreach(_ext ${protobuf_GENERATE_EXTENSIONS})
+ list(APPEND _generated_srcs "${CMAKE_CURRENT_BINARY_DIR}/${_basename}${_ext}")
+ endforeach()
+ list(APPEND _generated_srcs_all ${_generated_srcs})
+
+ add_custom_command(
+ OUTPUT ${_generated_srcs}
+ COMMAND protobuf::protoc
+ ARGS --${protobuf_generate_LANGUAGE}_out ${_dll_export_decl}${CMAKE_CURRENT_BINARY_DIR} ${_protobuf_include_path} ${_abs_file}
+ DEPENDS ${ABS_FIL} protobuf::protoc
+ COMMENT "Running ${protobuf_generate_LANGUAGE} protocol buffer compiler on ${_proto}"
+ VERBATIM )
+ endforeach()
+
+ set_source_files_properties(${_generated_srcs_all} PROPERTIES GENERATED TRUE)
+ if(protobuf_generate_OUT_VAR)
+ set(${protobuf_generate_OUT_VAR} ${_generated_srcs_all} PARENT_SCOPE)
+ endif()
+ if(protobuf_generate_TARGET)
+ target_sources(${protobuf_generate_TARGET} PUBLIC ${_generated_srcs_all})
+ endif()
+
+endfunction()
+
# CMake FindProtobuf module compatible file
if(protobuf_MODULE_COMPATIBLE)
include("${CMAKE_CURRENT_LIST_DIR}/protobuf-module.cmake")
diff --git a/cmake/protobuf-lite.pc.cmake b/cmake/protobuf-lite.pc.cmake
new file mode 100644
index 00000000..cbe5426a
--- /dev/null
+++ b/cmake/protobuf-lite.pc.cmake
@@ -0,0 +1,11 @@
+prefix=@CMAKE_INSTALL_PREFIX@
+exec_prefix=@CMAKE_INSTALL_PREFIX@
+libdir=@CMAKE_INSTALL_FULL_LIBDIR@
+includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@
+
+Name: Protocol Buffers
+Description: Google's Data Interchange Format
+Version: @protobuf_VERSION@
+Libs: -L${libdir} -lprotobuf-lite @CMAKE_THREAD_LIBS_INIT@
+Cflags: -I${includedir} @CMAKE_THREAD_LIBS_INIT@
+Conflicts: protobuf
diff --git a/cmake/protobuf-module.cmake.in b/cmake/protobuf-module.cmake.in
index 614e4c04..74c54887 100644
--- a/cmake/protobuf-module.cmake.in
+++ b/cmake/protobuf-module.cmake.in
@@ -1,55 +1,35 @@
+# This file contains backwards compatibility patches for various legacy functions and variables
# Functions
function(PROTOBUF_GENERATE_CPP SRCS HDRS)
- if(NOT ARGN)
+ cmake_parse_arguments(protobuf_generate_cpp "" "EXPORT_MACRO" "" ${ARGN})
+
+ set(_proto_files "${protobuf_generate_cpp_UNPARSED_ARGUMENTS}")
+ if(NOT _proto_files)
message(SEND_ERROR "Error: PROTOBUF_GENERATE_CPP() called without any proto files")
return()
endif()
if(PROTOBUF_GENERATE_CPP_APPEND_PATH)
- # Create an include path for each file specified
- foreach(FIL ${ARGN})
- get_filename_component(ABS_FIL ${FIL} ABSOLUTE)
- get_filename_component(ABS_PATH ${ABS_FIL} PATH)
- list(FIND _protobuf_include_path ${ABS_PATH} _contains_already)
- if(${_contains_already} EQUAL -1)
- list(APPEND _protobuf_include_path -I ${ABS_PATH})
- endif()
- endforeach()
- else()
- set(_protobuf_include_path -I ${CMAKE_CURRENT_SOURCE_DIR})
+ set(_append_arg APPEND_PATH)
endif()
if(DEFINED Protobuf_IMPORT_DIRS)
- foreach(DIR ${Protobuf_IMPORT_DIRS})
- get_filename_component(ABS_PATH ${DIR} ABSOLUTE)
- list(FIND _protobuf_include_path ${ABS_PATH} _contains_already)
- if(${_contains_already} EQUAL -1)
- list(APPEND _protobuf_include_path -I ${ABS_PATH})
- endif()
- endforeach()
+ set(_import_arg IMPORT_DIRS ${Protobuf_IMPORT_DIRS})
endif()
+ set(_outvar)
+ protobuf_generate(${_append_arg} LANGUAGE cpp EXPORT_MACRO ${protobuf_generate_cpp_EXPORT_MACRO} OUT_VAR _outvar ${_import_arg} PROTOS ${_proto_files})
+
set(${SRCS})
set(${HDRS})
- foreach(FIL ${ARGN})
- get_filename_component(ABS_FIL ${FIL} ABSOLUTE)
- get_filename_component(FIL_WE ${FIL} NAME_WE)
-
- list(APPEND ${SRCS} "${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.pb.cc")
- list(APPEND ${HDRS} "${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.pb.h")
-
- add_custom_command(
- OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.pb.cc"
- "${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.pb.h"
- COMMAND ${Protobuf_PROTOC_EXECUTABLE}
- ARGS --cpp_out ${CMAKE_CURRENT_BINARY_DIR} ${_protobuf_include_path} ${ABS_FIL}
- DEPENDS ${ABS_FIL} ${Protobuf_PROTOC_EXECUTABLE}
- COMMENT "Running C++ protocol buffer compiler on ${FIL}"
- VERBATIM )
+ foreach(_file ${_outvar})
+ if(_file MATCHES "cc$")
+ list(APPEND ${SRCS} ${_file})
+ else()
+ list(APPEND ${HDRS} ${_file})
+ endif()
endforeach()
-
- set_source_files_properties(${${SRCS}} ${${HDRS}} PROPERTIES GENERATED TRUE)
set(${SRCS} ${${SRCS}} PARENT_SCOPE)
set(${HDRS} ${${HDRS}} PARENT_SCOPE)
endfunction()
@@ -61,44 +41,16 @@ function(PROTOBUF_GENERATE_PYTHON SRCS)
endif()
if(PROTOBUF_GENERATE_CPP_APPEND_PATH)
- # Create an include path for each file specified
- foreach(FIL ${ARGN})
- get_filename_component(ABS_FIL ${FIL} ABSOLUTE)
- get_filename_component(ABS_PATH ${ABS_FIL} PATH)
- list(FIND _protobuf_include_path ${ABS_PATH} _contains_already)
- if(${_contains_already} EQUAL -1)
- list(APPEND _protobuf_include_path -I ${ABS_PATH})
- endif()
- endforeach()
- else()
- set(_protobuf_include_path -I ${CMAKE_CURRENT_SOURCE_DIR})
+ set(_append_arg APPEND_PATH)
endif()
if(DEFINED Protobuf_IMPORT_DIRS)
- foreach(DIR ${Protobuf_IMPORT_DIRS})
- get_filename_component(ABS_PATH ${DIR} ABSOLUTE)
- list(FIND _protobuf_include_path ${ABS_PATH} _contains_already)
- if(${_contains_already} EQUAL -1)
- list(APPEND _protobuf_include_path -I ${ABS_PATH})
- endif()
- endforeach()
+ set(_import_arg IMPORT_DIRS ${Protobuf_IMPORT_DIRS})
endif()
- set(${SRCS})
- foreach(FIL ${ARGN})
- get_filename_component(ABS_FIL ${FIL} ABSOLUTE)
- get_filename_component(FIL_WE ${FIL} NAME_WE)
-
- list(APPEND ${SRCS} "${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}_pb2.py")
- add_custom_command(
- OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}_pb2.py"
- COMMAND ${Protobuf_PROTOC_EXECUTABLE} --python_out ${CMAKE_CURRENT_BINARY_DIR} ${_protobuf_include_path} ${ABS_FIL}
- DEPENDS ${ABS_FIL} ${Protobuf_PROTOC_EXECUTABLE}
- COMMENT "Running Python protocol buffer compiler on ${FIL}"
- VERBATIM )
- endforeach()
-
- set(${SRCS} ${${SRCS}} PARENT_SCOPE)
+ set(_outvar)
+ protobuf_generate(${_append_arg} LANGUAGE python OUT_VAR _outvar ${_import_arg} PROTOS ${ARGN})
+ set(${SRCS} ${_outvar} PARENT_SCOPE)
endfunction()
# Environment
@@ -198,6 +150,10 @@ if(NOT EXISTS "${Protobuf_PROTOC_EXECUTABLE}")
get_target_property(Protobuf_PROTOC_EXECUTABLE protobuf::protoc
IMPORTED_LOCATION_DEBUG)
endif()
+if(NOT EXISTS "${Protobuf_PROTOC_EXECUTABLE}")
+ get_target_property(Protobuf_PROTOC_EXECUTABLE protobuf::protoc
+ IMPORTED_LOCATION_NOCONFIG)
+endif()
# Version info variable
set(Protobuf_VERSION "@protobuf_VERSION@")
diff --git a/cmake/protobuf.pc.cmake b/cmake/protobuf.pc.cmake
new file mode 100644
index 00000000..d33e98cc
--- /dev/null
+++ b/cmake/protobuf.pc.cmake
@@ -0,0 +1,11 @@
+prefix=@CMAKE_INSTALL_PREFIX@
+exec_prefix=@CMAKE_INSTALL_PREFIX@
+libdir=@CMAKE_INSTALL_FULL_LIBDIR@
+includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@
+
+Name: Protocol Buffers
+Description: Google's Data Interchange Format
+Version: @protobuf_VERSION@
+Libs: -L${libdir} -lprotobuf @CMAKE_THREAD_LIBS_INIT@
+Cflags: -I${includedir} @CMAKE_THREAD_LIBS_INIT@
+Conflicts: protobuf-lite
diff --git a/cmake/tests.cmake b/cmake/tests.cmake
index 30214e7d..d4622c6b 100644
--- a/cmake/tests.cmake
+++ b/cmake/tests.cmake
@@ -17,6 +17,7 @@ add_library(gmock STATIC
${protobuf_source_dir}/gmock/src/gmock-all.cc
${protobuf_source_dir}/gmock/gtest/src/gtest-all.cc
)
+target_link_libraries(gmock ${CMAKE_THREAD_LIBS_INIT})
add_library(gmock_main STATIC ${protobuf_source_dir}/gmock/src/gmock_main.cc)
target_link_libraries(gmock_main gmock)
@@ -42,6 +43,9 @@ set(tests_protos
google/protobuf/unittest_empty.proto
google/protobuf/unittest_import.proto
google/protobuf/unittest_import_public.proto
+ google/protobuf/unittest_lazy_dependencies.proto
+ google/protobuf/unittest_lazy_dependencies_custom_option.proto
+ google/protobuf/unittest_lazy_dependencies_enum.proto
google/protobuf/unittest_lite_imports_nonlite.proto
google/protobuf/unittest_mset.proto
google/protobuf/unittest_mset_wire_format.proto
@@ -117,11 +121,14 @@ set(tests_files
${protobuf_source_dir}/src/google/protobuf/any_test.cc
${protobuf_source_dir}/src/google/protobuf/arena_unittest.cc
${protobuf_source_dir}/src/google/protobuf/arenastring_unittest.cc
+ ${protobuf_source_dir}/src/google/protobuf/compiler/annotation_test_util.cc
${protobuf_source_dir}/src/google/protobuf/compiler/command_line_interface_unittest.cc
${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc
+ ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_move_unittest.cc
${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc
${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_unittest.cc
${protobuf_source_dir}/src/google/protobuf/compiler/cpp/metadata_test.cc
+ ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_bootstrap_unittest.cc
${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_generator_unittest.cc
${protobuf_source_dir}/src/google/protobuf/compiler/importer_unittest.cc
${protobuf_source_dir}/src/google/protobuf/compiler/java/java_doc_comment_unittest.cc
@@ -155,6 +162,7 @@ set(tests_files
${protobuf_source_dir}/src/google/protobuf/stubs/bytestream_unittest.cc
${protobuf_source_dir}/src/google/protobuf/stubs/common_unittest.cc
${protobuf_source_dir}/src/google/protobuf/stubs/int128_unittest.cc
+ ${protobuf_source_dir}/src/google/protobuf/stubs/io_win32_unittest.cc
${protobuf_source_dir}/src/google/protobuf/stubs/once_unittest.cc
${protobuf_source_dir}/src/google/protobuf/stubs/status_test.cc
${protobuf_source_dir}/src/google/protobuf/stubs/statusor_test.cc
@@ -167,6 +175,7 @@ set(tests_files
${protobuf_source_dir}/src/google/protobuf/stubs/type_traits_unittest.cc
${protobuf_source_dir}/src/google/protobuf/text_format_unittest.cc
${protobuf_source_dir}/src/google/protobuf/unknown_field_set_unittest.cc
+ ${protobuf_source_dir}/src/google/protobuf/util/delimited_message_util_test.cc
${protobuf_source_dir}/src/google/protobuf/util/field_comparator_test.cc
${protobuf_source_dir}/src/google/protobuf/util/field_mask_util_test.cc
${protobuf_source_dir}/src/google/protobuf/util/internal/default_value_objectwriter_test.cc
@@ -204,7 +213,7 @@ set(lite_test_files
${protobuf_source_dir}/src/google/protobuf/lite_unittest.cc
)
add_executable(lite-test ${lite_test_files} ${common_lite_test_files} ${lite_test_proto_files})
-target_link_libraries(lite-test libprotobuf-lite)
+target_link_libraries(lite-test libprotobuf-lite gmock_main)
set(lite_arena_test_files
${protobuf_source_dir}/src/google/protobuf/lite_arena_unittest.cc
@@ -214,4 +223,5 @@ target_link_libraries(lite-arena-test libprotobuf-lite gmock_main)
add_custom_target(check
COMMAND tests
+ DEPENDS tests test_plugin
WORKING_DIRECTORY ${protobuf_source_dir})
diff --git a/composer.json b/composer.json
index 2833f0a2..2c64ad22 100644
--- a/composer.json
+++ b/composer.json
@@ -11,13 +11,13 @@
"require-dev": {
"phpunit/phpunit": ">=4.8.0"
},
+ "suggest": {
+ "ext-bcmath": "Need to support JSON deserialization"
+ },
"autoload": {
"psr-4": {
- "Google\\Protobuf\\Internal\\": "src/Google/Protobuf/Internal",
- "GPBMetadata\\Google\\Protobuf\\Internal\\": "src/GPBMetadata/Google/Protobuf/Internal"
- },
- "files": [
- "src/Google/Protobuf/descriptor.php"
- ]
+ "Google\\Protobuf\\": "php/src/Google/Protobuf",
+ "GPBMetadata\\Google\\Protobuf\\": "php/src/GPBMetadata/Google/Protobuf"
+ }
}
}
diff --git a/configure.ac b/configure.ac
index d1e913c6..ae15f5f8 100644
--- a/configure.ac
+++ b/configure.ac
@@ -17,7 +17,7 @@ AC_PREREQ(2.59)
# In the SVN trunk, the version should always be the next anticipated release
# version with the "-pre" suffix. (We used to use "-SNAPSHOT" but this pushed
# the size of one file name in the dist tarfile over the 99-char limit.)
-AC_INIT([Protocol Buffers],[3.1.0],[protobuf@googlegroups.com],[protobuf])
+AC_INIT([Protocol Buffers],[3.4.1],[protobuf@googlegroups.com],[protobuf])
AM_MAINTAINER_MODE([enable])
@@ -52,6 +52,16 @@ AC_ARG_WITH([zlib],
[include classes for streaming compressed data in and out @<:@default=check@:>@])],
[],[with_zlib=check])
+AC_ARG_WITH([zlib-include],
+ [AS_HELP_STRING([--with-zlib-include=PATH],
+ [zlib include directory])],
+ [CPPFLAGS="-I$withval $CPPFLAGS"])
+
+AC_ARG_WITH([zlib-lib],
+ [AS_HELP_STRING([--with-zlib-lib=PATH],
+ [zlib lib directory])],
+ [LDFLAGS="-L$withval $LDFLAGS"])
+
AC_ARG_WITH([protoc],
[AS_HELP_STRING([--with-protoc=COMMAND],
[use the given protoc command instead of building a new one when building tests (useful for cross-compiling)])],
@@ -60,6 +70,7 @@ AC_ARG_WITH([protoc],
# Checks for programs.
AC_PROG_CC
AC_PROG_CXX
+AC_PROG_CXX_FOR_BUILD
AC_LANG([C++])
ACX_USE_SYSTEM_EXTENSIONS
m4_ifdef([AM_PROG_AR], [AM_PROG_AR])
@@ -92,6 +103,25 @@ ACX_CHECK_SUNCC
# to the link
AC_PROG_LIBTOOL
+# Check whether the linker supports version scripts
+AC_MSG_CHECKING([whether the linker supports version scripts])
+save_LDFLAGS=$LDFLAGS
+LDFLAGS="$LDFLAGS -Wl,--version-script=conftest.map"
+cat > conftest.map <<EOF
+{
+ global:
+ main;
+ local:
+ *;
+};
+EOF
+AC_LINK_IFELSE(
+ [AC_LANG_SOURCE([int main() { return 0; }])],
+ [have_ld_version_script=yes; AC_MSG_RESULT(yes)],
+ [have_ld_version_script=no; AC_MSG_RESULT(no)])
+LDFLAGS=$save_LDFLAGS
+AM_CONDITIONAL([HAVE_LD_VERSION_SCRIPT], [test "$have_ld_version_script" == "yes"])
+
# Checks for header files.
AC_HEADER_STDC
AC_CHECK_HEADERS([fcntl.h inttypes.h limits.h stdlib.h unistd.h])
diff --git a/conformance/ConformanceJava.java b/conformance/ConformanceJava.java
index 7badf2a5..596d113a 100644
--- a/conformance/ConformanceJava.java
+++ b/conformance/ConformanceJava.java
@@ -1,12 +1,18 @@
import com.google.protobuf.ByteString;
+import com.google.protobuf.AbstractMessage;
+import com.google.protobuf.Parser;
import com.google.protobuf.CodedInputStream;
import com.google.protobuf.conformance.Conformance;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf_test_messages.proto3.TestMessagesProto3;
+import com.google.protobuf_test_messages.proto3.TestMessagesProto3.TestAllTypesProto3;
+import com.google.protobuf_test_messages.proto2.TestMessagesProto2;
+import com.google.protobuf_test_messages.proto2.TestMessagesProto2.TestAllTypesProto2;
+import com.google.protobuf.ExtensionRegistry;
import com.google.protobuf.util.JsonFormat;
import com.google.protobuf.util.JsonFormat.TypeRegistry;
-import java.io.IOException;
import java.nio.ByteBuffer;
+import java.util.ArrayList;
class ConformanceJava {
private int testCount = 0;
@@ -50,123 +56,100 @@ class ConformanceJava {
buf[3] = (byte)(val >> 24);
writeToStdout(buf);
}
+
+ private enum BinaryDecoderType {
+ BTYE_STRING_DECODER,
+ BYTE_ARRAY_DECODER,
+ ARRAY_BYTE_BUFFER_DECODER,
+ READONLY_ARRAY_BYTE_BUFFER_DECODER,
+ DIRECT_BYTE_BUFFER_DECODER,
+ READONLY_DIRECT_BYTE_BUFFER_DECODER,
+ INPUT_STREAM_DECODER;
+ }
- private enum BinaryDecoder {
- BYTE_STRING_DECODER() {
- @Override
- public TestMessagesProto3.TestAllTypes parse(ByteString bytes)
- throws InvalidProtocolBufferException {
- return TestMessagesProto3.TestAllTypes.parseFrom(bytes);
- }
- },
- BYTE_ARRAY_DECODER() {
- @Override
- public TestMessagesProto3.TestAllTypes parse(ByteString bytes)
- throws InvalidProtocolBufferException {
- return TestMessagesProto3.TestAllTypes.parseFrom(bytes.toByteArray());
- }
- },
- ARRAY_BYTE_BUFFER_DECODER() {
- @Override
- public TestMessagesProto3.TestAllTypes parse(ByteString bytes)
- throws InvalidProtocolBufferException {
- ByteBuffer buffer = ByteBuffer.allocate(bytes.size());
- bytes.copyTo(buffer);
- buffer.flip();
- try {
- return TestMessagesProto3.TestAllTypes.parseFrom(CodedInputStream.newInstance(buffer));
- } catch (InvalidProtocolBufferException e) {
- throw e;
- } catch (IOException e) {
- throw new RuntimeException(
- "ByteString based ByteBuffer should not throw IOException.", e);
- }
- }
- },
- READONLY_ARRAY_BYTE_BUFFER_DECODER() {
- @Override
- public TestMessagesProto3.TestAllTypes parse(ByteString bytes)
- throws InvalidProtocolBufferException {
- try {
- return TestMessagesProto3.TestAllTypes.parseFrom(
- CodedInputStream.newInstance(bytes.asReadOnlyByteBuffer()));
- } catch (InvalidProtocolBufferException e) {
- throw e;
- } catch (IOException e) {
- throw new RuntimeException(
- "ByteString based ByteBuffer should not throw IOException.", e);
+ private static class BinaryDecoder <MessageType extends AbstractMessage> {
+ public MessageType decode (ByteString bytes, BinaryDecoderType type,
+ Parser <MessageType> parser, ExtensionRegistry extensions)
+ throws InvalidProtocolBufferException {
+ switch (type) {
+ case BTYE_STRING_DECODER:
+ return parser.parseFrom(bytes, extensions);
+ case BYTE_ARRAY_DECODER:
+ return parser.parseFrom(bytes.toByteArray(), extensions);
+ case ARRAY_BYTE_BUFFER_DECODER: {
+ ByteBuffer buffer = ByteBuffer.allocate(bytes.size());
+ bytes.copyTo(buffer);
+ buffer.flip();
+ try {
+ return parser.parseFrom(CodedInputStream.newInstance(buffer), extensions);
+ } catch (InvalidProtocolBufferException e) {
+ throw e;
+ }
}
- }
- },
- DIRECT_BYTE_BUFFER_DECODER() {
- @Override
- public TestMessagesProto3.TestAllTypes parse(ByteString bytes)
- throws InvalidProtocolBufferException {
- ByteBuffer buffer = ByteBuffer.allocateDirect(bytes.size());
- bytes.copyTo(buffer);
- buffer.flip();
- try {
- return TestMessagesProto3.TestAllTypes.parseFrom(CodedInputStream.newInstance(buffer));
- } catch (InvalidProtocolBufferException e) {
- throw e;
- } catch (IOException e) {
- throw new RuntimeException(
- "ByteString based ByteBuffer should not throw IOException.", e);
+ case READONLY_ARRAY_BYTE_BUFFER_DECODER: {
+ try {
+ return parser.parseFrom(
+ CodedInputStream.newInstance(bytes.asReadOnlyByteBuffer()), extensions);
+ } catch (InvalidProtocolBufferException e) {
+ throw e;
+ }
+ }
+ case DIRECT_BYTE_BUFFER_DECODER: {
+ ByteBuffer buffer = ByteBuffer.allocateDirect(bytes.size());
+ bytes.copyTo(buffer);
+ buffer.flip();
+ try {
+ return parser.parseFrom(CodedInputStream.newInstance(buffer), extensions);
+ } catch (InvalidProtocolBufferException e) {
+ throw e;
+ }
}
- }
- },
- READONLY_DIRECT_BYTE_BUFFER_DECODER() {
- @Override
- public TestMessagesProto3.TestAllTypes parse(ByteString bytes)
- throws InvalidProtocolBufferException {
- ByteBuffer buffer = ByteBuffer.allocateDirect(bytes.size());
- bytes.copyTo(buffer);
- buffer.flip();
- try {
- return TestMessagesProto3.TestAllTypes.parseFrom(
- CodedInputStream.newInstance(buffer.asReadOnlyBuffer()));
- } catch (InvalidProtocolBufferException e) {
- throw e;
- } catch (IOException e) {
- throw new RuntimeException(
- "ByteString based ByteBuffer should not throw IOException.", e);
+ case READONLY_DIRECT_BYTE_BUFFER_DECODER: {
+ ByteBuffer buffer = ByteBuffer.allocateDirect(bytes.size());
+ bytes.copyTo(buffer);
+ buffer.flip();
+ try {
+ return parser.parseFrom(
+ CodedInputStream.newInstance(buffer.asReadOnlyBuffer()), extensions);
+ } catch (InvalidProtocolBufferException e) {
+ throw e;
+ }
}
- }
- },
- INPUT_STREAM_DECODER() {
- @Override
- public TestMessagesProto3.TestAllTypes parse(ByteString bytes)
- throws InvalidProtocolBufferException {
- try {
- return TestMessagesProto3.TestAllTypes.parseFrom(bytes.newInput());
- } catch (InvalidProtocolBufferException e) {
- throw e;
- } catch (IOException e) {
- throw new RuntimeException(
- "ByteString based InputStream should not throw IOException.", e);
+ case INPUT_STREAM_DECODER: {
+ try {
+ return parser.parseFrom(bytes.newInput(), extensions);
+ } catch (InvalidProtocolBufferException e) {
+ throw e;
+ }
}
+ default :
+ return null;
}
- };
-
- public abstract TestMessagesProto3.TestAllTypes parse(ByteString bytes)
- throws InvalidProtocolBufferException;
+ }
}
- private TestMessagesProto3.TestAllTypes parseBinary(ByteString bytes)
+ private <MessageType extends AbstractMessage> MessageType parseBinary(
+ ByteString bytes, Parser <MessageType> parser, ExtensionRegistry extensions)
throws InvalidProtocolBufferException {
- TestMessagesProto3.TestAllTypes[] messages =
- new TestMessagesProto3.TestAllTypes[BinaryDecoder.values().length];
- InvalidProtocolBufferException[] exceptions =
- new InvalidProtocolBufferException[BinaryDecoder.values().length];
+ ArrayList <MessageType> messages = new ArrayList <MessageType> ();
+ ArrayList <InvalidProtocolBufferException> exceptions =
+ new ArrayList <InvalidProtocolBufferException>();
+
+ for (int i = 0; i < BinaryDecoderType.values().length; i++) {
+ messages.add(null);
+ exceptions.add(null);
+ }
+ BinaryDecoder <MessageType> decoder = new BinaryDecoder <MessageType> ();
boolean hasMessage = false;
boolean hasException = false;
- for (int i = 0; i < BinaryDecoder.values().length; ++i) {
+ for (int i = 0; i < BinaryDecoderType.values().length; ++i) {
try {
- messages[i] = BinaryDecoder.values()[i].parse(bytes);
+ //= BinaryDecoderType.values()[i].parseProto3(bytes);
+ messages.set(i, decoder.decode(bytes, BinaryDecoderType.values()[i], parser, extensions));
hasMessage = true;
} catch (InvalidProtocolBufferException e) {
- exceptions[i] = e;
+ exceptions.set(i, e);
hasException = true;
}
}
@@ -174,9 +157,9 @@ class ConformanceJava {
if (hasMessage && hasException) {
StringBuilder sb =
new StringBuilder("Binary decoders disagreed on whether the payload was valid.\n");
- for (int i = 0; i < BinaryDecoder.values().length; ++i) {
- sb.append(BinaryDecoder.values()[i].name());
- if (messages[i] != null) {
+ for (int i = 0; i < BinaryDecoderType.values().length; ++i) {
+ sb.append(BinaryDecoderType.values()[i].name());
+ if (messages.get(i) != null) {
sb.append(" accepted the payload.\n");
} else {
sb.append(" rejected the payload.\n");
@@ -188,14 +171,14 @@ class ConformanceJava {
if (hasException) {
// We do not check if exceptions are equal. Different implementations may return different
// exception messages. Throw an arbitrary one out instead.
- throw exceptions[0];
+ throw exceptions.get(0);
}
// Fast path comparing all the messages with the first message, assuming equality being
// symmetric and transitive.
boolean allEqual = true;
- for (int i = 1; i < messages.length; ++i) {
- if (!messages[0].equals(messages[i])) {
+ for (int i = 1; i < messages.size(); ++i) {
+ if (!messages.get(0).equals(messages.get(i))) {
allEqual = false;
break;
}
@@ -204,12 +187,12 @@ class ConformanceJava {
// Slow path: compare and find out all unequal pairs.
if (!allEqual) {
StringBuilder sb = new StringBuilder();
- for (int i = 0; i < messages.length - 1; ++i) {
- for (int j = i + 1; j < messages.length; ++j) {
- if (!messages[i].equals(messages[j])) {
- sb.append(BinaryDecoder.values()[i].name())
+ for (int i = 0; i < messages.size() - 1; ++i) {
+ for (int j = i + 1; j < messages.size(); ++j) {
+ if (!messages.get(i).equals(messages.get(j))) {
+ sb.append(BinaryDecoderType.values()[i].name())
.append(" and ")
- .append(BinaryDecoder.values()[j].name())
+ .append(BinaryDecoderType.values()[j].name())
.append(" parsed the payload differently.\n");
}
}
@@ -217,24 +200,41 @@ class ConformanceJava {
throw new RuntimeException(sb.toString());
}
- return messages[0];
+ return messages.get(0);
}
private Conformance.ConformanceResponse doTest(Conformance.ConformanceRequest request) {
- TestMessagesProto3.TestAllTypes testMessage;
+ com.google.protobuf.AbstractMessage testMessage;
+ boolean isProto3 = request.getMessageType().equals("protobuf_test_messages.proto3.TestAllTypesProto3");
+ boolean isProto2 = request.getMessageType().equals("protobuf_test_messages.proto2.TestAllTypesProto2");
switch (request.getPayloadCase()) {
case PROTOBUF_PAYLOAD: {
- try {
- testMessage = parseBinary(request.getProtobufPayload());
- } catch (InvalidProtocolBufferException e) {
- return Conformance.ConformanceResponse.newBuilder().setParseError(e.getMessage()).build();
+ if (isProto3) {
+ try {
+ ExtensionRegistry extensions = ExtensionRegistry.newInstance();
+ TestMessagesProto3.registerAllExtensions(extensions);
+ testMessage = parseBinary(request.getProtobufPayload(), TestAllTypesProto3.parser(), extensions);
+ } catch (InvalidProtocolBufferException e) {
+ return Conformance.ConformanceResponse.newBuilder().setParseError(e.getMessage()).build();
+ }
+ } else if (isProto2) {
+ try {
+ ExtensionRegistry extensions = ExtensionRegistry.newInstance();
+ TestMessagesProto2.registerAllExtensions(extensions);
+ testMessage = parseBinary(request.getProtobufPayload(), TestAllTypesProto2.parser(), extensions);
+ } catch (InvalidProtocolBufferException e) {
+ return Conformance.ConformanceResponse.newBuilder().setParseError(e.getMessage()).build();
+ }
+ } else {
+ throw new RuntimeException("Protobuf request doesn't have specific payload type.");
}
break;
}
case JSON_PAYLOAD: {
try {
- TestMessagesProto3.TestAllTypes.Builder builder = TestMessagesProto3.TestAllTypes.newBuilder();
+ TestMessagesProto3.TestAllTypesProto3.Builder builder =
+ TestMessagesProto3.TestAllTypesProto3.newBuilder();
JsonFormat.parser().usingTypeRegistry(typeRegistry)
.merge(request.getJsonPayload(), builder);
testMessage = builder.build();
@@ -256,8 +256,10 @@ class ConformanceJava {
case UNSPECIFIED:
throw new RuntimeException("Unspecified output format.");
- case PROTOBUF:
- return Conformance.ConformanceResponse.newBuilder().setProtobufPayload(testMessage.toByteString()).build();
+ case PROTOBUF: {
+ ByteString MessageString = testMessage.toByteString();
+ return Conformance.ConformanceResponse.newBuilder().setProtobufPayload(MessageString).build();
+ }
case JSON:
try {
@@ -300,7 +302,7 @@ class ConformanceJava {
public void run() throws Exception {
typeRegistry = TypeRegistry.newBuilder().add(
- TestMessagesProto3.TestAllTypes.getDescriptor()).build();
+ TestMessagesProto3.TestAllTypesProto3.getDescriptor()).build();
while (doTestIo()) {
this.testCount++;
}
diff --git a/conformance/Makefile.am b/conformance/Makefile.am
index c2b58900..765f3588 100644
--- a/conformance/Makefile.am
+++ b/conformance/Makefile.am
@@ -4,6 +4,11 @@ conformance_protoc_inputs = \
conformance.proto \
$(top_srcdir)/src/google/protobuf/test_messages_proto3.proto
+# proto2 input files, should be separated with proto3, as we
+# can't generate proto2 files for ruby, php and objc
+conformance_proto2_protoc_inputs = \
+ $(top_srcdir)/src/google/protobuf/test_messages_proto2.proto
+
well_known_type_protoc_inputs = \
$(top_srcdir)/src/google/protobuf/any.proto \
$(top_srcdir)/src/google/protobuf/duration.proto \
@@ -21,6 +26,7 @@ other_language_protoc_outputs = \
conformance_pb2.py \
Conformance.pbobjc.h \
Conformance.pbobjc.m \
+ conformance_pb.js \
conformance_pb.rb \
com/google/protobuf/Any.java \
com/google/protobuf/AnyOrBuilder.java \
@@ -63,6 +69,7 @@ other_language_protoc_outputs = \
com/google/protobuf/ValueOrBuilder.java \
com/google/protobuf/WrappersProto.java \
com/google/protobuf_test_messages/proto3/TestMessagesProto3.java \
+ com/google/protobuf_test_messages/proto2/TestMessagesProto2.java \
google/protobuf/any.pb.cc \
google/protobuf/any.pb.h \
google/protobuf/any.rb \
@@ -79,12 +86,17 @@ other_language_protoc_outputs = \
google/protobuf/struct.pb.h \
google/protobuf/struct.rb \
google/protobuf/struct_pb2.py \
+ google/protobuf/TestMessagesProto2.pbobjc.h \
+ google/protobuf/TestMessagesProto2.pbobjc.m \
google/protobuf/TestMessagesProto3.pbobjc.h \
google/protobuf/TestMessagesProto3.pbobjc.m \
google/protobuf/test_messages_proto3.pb.cc \
google/protobuf/test_messages_proto3.pb.h \
+ google/protobuf/test_messages_proto2.pb.cc \
+ google/protobuf/test_messages_proto2.pb.h \
google/protobuf/test_messages_proto3_pb.rb \
google/protobuf/test_messages_proto3_pb2.py \
+ google/protobuf/test_messages_proto2_pb2.py \
google/protobuf/timestamp.pb.cc \
google/protobuf/timestamp.pb.h \
google/protobuf/timestamp.rb \
@@ -92,7 +104,40 @@ other_language_protoc_outputs = \
google/protobuf/wrappers.pb.cc \
google/protobuf/wrappers.pb.h \
google/protobuf/wrappers.rb \
- google/protobuf/wrappers_pb2.py
+ google/protobuf/wrappers_pb2.py \
+ Conformance/ConformanceRequest.php \
+ Conformance/ConformanceResponse.php \
+ Conformance/WireFormat.php \
+ GPBMetadata/Conformance.php \
+ GPBMetadata/Google/Protobuf/Any.php \
+ GPBMetadata/Google/Protobuf/Duration.php \
+ GPBMetadata/Google/Protobuf/FieldMask.php \
+ GPBMetadata/Google/Protobuf/Struct.php \
+ GPBMetadata/Google/Protobuf/TestMessagesProto3.php \
+ GPBMetadata/Google/Protobuf/Timestamp.php \
+ GPBMetadata/Google/Protobuf/Wrappers.php \
+ Google/Protobuf/Any.php \
+ Google/Protobuf/BoolValue.php \
+ Google/Protobuf/BytesValue.php \
+ Google/Protobuf/DoubleValue.php \
+ Google/Protobuf/Duration.php \
+ Google/Protobuf/FieldMask.php \
+ Google/Protobuf/FloatValue.php \
+ Google/Protobuf/Int32Value.php \
+ Google/Protobuf/Int64Value.php \
+ Google/Protobuf/ListValue.php \
+ Google/Protobuf/NullValue.php \
+ Google/Protobuf/StringValue.php \
+ Google/Protobuf/Struct.php \
+ Google/Protobuf/Timestamp.php \
+ Google/Protobuf/UInt32Value.php \
+ Google/Protobuf/UInt64Value.php \
+ Google/Protobuf/Value.php \
+ Protobuf_test_messages/Proto3/ForeignEnum.php \
+ Protobuf_test_messages/Proto3/ForeignMessage.php \
+ Protobuf_test_messages/Proto3/TestAllTypes_NestedEnum.php \
+ Protobuf_test_messages/Proto3/TestAllTypes_NestedMessage.php \
+ Protobuf_test_messages/Proto3/TestAllTypes.php
# lite/com/google/protobuf/Any.java \
# lite/com/google/protobuf/AnyOrBuilder.java \
# lite/com/google/protobuf/AnyProto.java \
@@ -146,21 +191,25 @@ EXTRA_DIST = \
conformance.proto \
conformance_python.py \
conformance_ruby.rb \
+ conformance_php.php \
failure_list_cpp.txt \
failure_list_csharp.txt \
failure_list_java.txt \
+ failure_list_js.txt \
failure_list_objc.txt \
failure_list_python.txt \
failure_list_python_cpp.txt \
failure_list_python-post26.txt \
- failure_list_ruby.txt
+ failure_list_ruby.txt \
+ failure_list_php.txt \
+ failure_list_php_c.txt
conformance_test_runner_LDADD = $(top_srcdir)/src/libprotobuf.la
conformance_test_runner_SOURCES = conformance_test.h conformance_test.cc \
conformance_test_runner.cc \
third_party/jsoncpp/json.h \
third_party/jsoncpp/jsoncpp.cpp
-nodist_conformance_test_runner_SOURCES = conformance.pb.cc google/protobuf/test_messages_proto3.pb.cc
+nodist_conformance_test_runner_SOURCES = conformance.pb.cc google/protobuf/test_messages_proto3.pb.cc google/protobuf/test_messages_proto2.pb.cc
conformance_test_runner_CPPFLAGS = -I$(top_srcdir)/src -I$(srcdir)
conformance_test_runner_CXXFLAGS = -std=c++11
# Explicit deps beacuse BUILT_SOURCES are only done before a "make all/check"
@@ -170,7 +219,7 @@ conformance_test_runner-conformance_test_runner.$(OBJEXT): conformance.pb.h
conformance_cpp_LDADD = $(top_srcdir)/src/libprotobuf.la
conformance_cpp_SOURCES = conformance_cpp.cc
-nodist_conformance_cpp_SOURCES = conformance.pb.cc google/protobuf/test_messages_proto3.pb.cc
+nodist_conformance_cpp_SOURCES = conformance.pb.cc google/protobuf/test_messages_proto3.pb.cc google/protobuf/test_messages_proto2.pb.cc
conformance_cpp_CPPFLAGS = -I$(top_srcdir)/src
# Explicit dep beacuse BUILT_SOURCES are only done before a "make all/check"
# so a direct "make test_cpp" could fail if parallel enough.
@@ -181,7 +230,7 @@ if OBJC_CONFORMANCE_TEST
bin_PROGRAMS += conformance-objc
conformance_objc_SOURCES = conformance_objc.m ../objectivec/GPBProtocolBuffers.m
-nodist_conformance_objc_SOURCES = Conformance.pbobjc.m google/protobuf/TestMessagesProto3.pbobjc.m
+nodist_conformance_objc_SOURCES = Conformance.pbobjc.m google/protobuf/TestMessagesProto2.pbobjc.m google/protobuf/TestMessagesProto3.pbobjc.m
# On travis, the build fails without the isysroot because whatever system
# headers are being found don't include generics support for
# NSArray/NSDictionary, the only guess is their image at one time had an odd
@@ -190,16 +239,24 @@ conformance_objc_CPPFLAGS = -I$(top_srcdir)/objectivec -isysroot `xcrun --sdk ma
conformance_objc_LDFLAGS = -framework Foundation
# Explicit dep beacuse BUILT_SOURCES are only done before a "make all/check"
# so a direct "make test_objc" could fail if parallel enough.
-conformance_objc-conformance_objc.$(OBJEXT): Conformance.pbobjc.h google/protobuf/TestMessagesProto3.pbobjc.h
+conformance_objc-conformance_objc.$(OBJEXT): Conformance.pbobjc.h google/protobuf/TestMessagesProto2.pbobjc.h google/protobuf/TestMessagesProto3.pbobjc.h
endif
+# JavaScript well-known types are expected to be in a directory called
+# google-protobuf, because they are usually in the google-protobuf npm
+# package. But we want to use the sources from our tree, so we recreate
+# that directory structure here.
+google-protobuf:
+ mkdir google-protobuf
+
if USE_EXTERNAL_PROTOC
# Some implementations include pre-generated versions of well-known types.
-protoc_middleman: $(conformance_protoc_inputs) $(well_known_type_protoc_inputs)
- $(PROTOC) -I$(srcdir) -I$(top_srcdir) --cpp_out=. --java_out=. --ruby_out=. --objc_out=. --python_out=. $(conformance_protoc_inputs)
- $(PROTOC) -I$(srcdir) -I$(top_srcdir) --cpp_out=. --java_out=. --ruby_out=. --python_out=. $(well_known_type_protoc_inputs)
+protoc_middleman: $(conformance_protoc_inputs) $(conformance_proto2_protoc_inputs) $(well_known_type_protoc_inputs) google-protobuf
+ $(PROTOC) -I$(srcdir) -I$(top_srcdir) --cpp_out=. --java_out=. --ruby_out=. --objc_out=. --python_out=. --php_out=. --js_out=import_style=commonjs,binary:. $(conformance_protoc_inputs)
+ $(PROTOC) -I$(srcdir) -I$(top_srcdir) --cpp_out=. --java_out=. --objc_out=. --python_out=. --js_out=import_style=commonjs,binary:. $(conformance_proto2_protoc_inputs)
+ $(PROTOC) -I$(srcdir) -I$(top_srcdir) --cpp_out=. --java_out=. --ruby_out=. --python_out=. --js_out=import_style=commonjs,binary:google-protobuf $(well_known_type_protoc_inputs)
## $(PROTOC) -I$(srcdir) -I$(top_srcdir) --java_out=lite:lite $(conformance_protoc_inputs) $(well_known_type_protoc_inputs)
touch protoc_middleman
@@ -208,9 +265,10 @@ else
# We have to cd to $(srcdir) before executing protoc because $(protoc_inputs) is
# relative to srcdir, which may not be the same as the current directory when
# building out-of-tree.
-protoc_middleman: $(top_srcdir)/src/protoc$(EXEEXT) $(conformance_protoc_inputs) $(well_known_type_protoc_inputs)
- oldpwd=`pwd` && ( cd $(srcdir) && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$(top_srcdir)/src --cpp_out=$$oldpwd --java_out=$$oldpwd --ruby_out=$$oldpwd --objc_out=$$oldpwd --python_out=$$oldpwd $(conformance_protoc_inputs) )
- oldpwd=`pwd` && ( cd $(srcdir) && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$(top_srcdir)/src --cpp_out=$$oldpwd --java_out=$$oldpwd --ruby_out=$$oldpwd --python_out=$$oldpwd $(well_known_type_protoc_inputs) )
+protoc_middleman: $(top_srcdir)/src/protoc$(EXEEXT) $(conformance_protoc_inputs) $(conformance_proto2_protoc_inputs) $(well_known_type_protoc_inputs) google-protobuf
+ oldpwd=`pwd` && ( cd $(srcdir) && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$(top_srcdir)/src --cpp_out=$$oldpwd --java_out=$$oldpwd --ruby_out=$$oldpwd --objc_out=$$oldpwd --python_out=$$oldpwd --php_out=$$oldpwd --js_out=import_style=commonjs,binary:$$oldpwd $(conformance_protoc_inputs) )
+ oldpwd=`pwd` && ( cd $(srcdir) && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$(top_srcdir)/src --cpp_out=$$oldpwd --java_out=$$oldpwd --objc_out=. --python_out=$$oldpwd --js_out=import_style=commonjs,binary:$$oldpwd $(conformance_proto2_protoc_inputs) )
+ oldpwd=`pwd` && ( cd $(srcdir) && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$(top_srcdir)/src --cpp_out=$$oldpwd --java_out=$$oldpwd --ruby_out=$$oldpwd --python_out=$$oldpwd --js_out=import_style=commonjs,binary:$$oldpwd/google-protobuf $(well_known_type_protoc_inputs) )
## @mkdir -p lite
## oldpwd=`pwd` && ( cd $(srcdir) && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$(top_srcdir)/src --java_out=lite:$$oldpwd/lite $(conformance_protoc_inputs) $(well_known_type_protoc_inputs) )
touch protoc_middleman
@@ -223,13 +281,13 @@ $(other_language_protoc_outputs): protoc_middleman
BUILT_SOURCES = $(protoc_outputs) $(other_language_protoc_outputs)
-CLEANFILES = $(protoc_outputs) protoc_middleman javac_middleman conformance-java javac_middleman_lite conformance-java-lite conformance-csharp $(other_language_protoc_outputs)
+CLEANFILES = $(protoc_outputs) protoc_middleman javac_middleman conformance-java javac_middleman_lite conformance-java-lite conformance-csharp conformance-php conformance-php-c $(other_language_protoc_outputs)
MAINTAINERCLEANFILES = \
Makefile.in
javac_middleman: ConformanceJava.java protoc_middleman $(other_language_protoc_outputs)
- jar=`ls ../java/util/target/*jar-with-dependencies.jar` && javac -classpath ../java/target/classes:$$jar ConformanceJava.java com/google/protobuf/conformance/Conformance.java com/google/protobuf_test_messages/proto3/TestMessagesProto3.java
+ jar=`ls ../java/util/target/*jar-with-dependencies.jar` && javac -classpath ../java/target/classes:$$jar ConformanceJava.java com/google/protobuf/conformance/Conformance.java com/google/protobuf_test_messages/proto3/TestMessagesProto3.java com/google/protobuf_test_messages/proto2/TestMessagesProto2.java
@touch javac_middleman
conformance-java: javac_middleman
@@ -257,6 +315,18 @@ conformance-csharp: $(other_language_protoc_outputs)
@echo 'dotnet ../csharp/src/Google.Protobuf.Conformance/bin/Release/netcoreapp1.0/Google.Protobuf.Conformance.dll "$$@"' >> conformance-csharp
@chmod +x conformance-csharp
+conformance-php:
+ @echo "Writing shortcut script conformance-php..."
+ @echo '#! /bin/sh' > conformance-php
+ @echo 'php -d auto_prepend_file=autoload.php ./conformance_php.php' >> conformance-php
+ @chmod +x conformance-php
+
+conformance-php-c:
+ @echo "Writing shortcut script conformance-php-c..."
+ @echo '#! /bin/sh' > conformance-php-c
+ @echo 'php -dextension=../php/ext/google/protobuf/modules/protobuf.so ./conformance_php.php' >> conformance-php-c
+ @chmod +x conformance-php-c
+
# Targets for actually running tests.
test_cpp: protoc_middleman conformance-test-runner conformance-cpp
./conformance-test-runner --enforce_recommended --failure_list failure_list_cpp.txt ./conformance-cpp
@@ -273,6 +343,15 @@ test_csharp: protoc_middleman conformance-test-runner conformance-csharp
test_ruby: protoc_middleman conformance-test-runner $(other_language_protoc_outputs)
RUBYLIB=../ruby/lib:. ./conformance-test-runner --enforce_recommended --failure_list failure_list_ruby.txt ./conformance_ruby.rb
+test_php: protoc_middleman conformance-test-runner conformance-php $(other_language_protoc_outputs)
+ ./conformance-test-runner --enforce_recommended --failure_list failure_list_php.txt ./conformance-php
+
+test_php_c: protoc_middleman conformance-test-runner conformance-php-c $(other_language_protoc_outputs)
+ ./conformance-test-runner --enforce_recommended --failure_list failure_list_php_c.txt ./conformance-php-c
+
+test_php_zts_c: protoc_middleman conformance-test-runner conformance-php-c $(other_language_protoc_outputs)
+ ./conformance-test-runner --enforce_recommended --failure_list failure_list_php_zts_c.txt ./conformance-php-c
+
# These depend on library paths being properly set up. The easiest way to
# run them is to just use "tox" from the python dir.
test_python: protoc_middleman conformance-test-runner
@@ -281,6 +360,9 @@ test_python: protoc_middleman conformance-test-runner
test_python_cpp: protoc_middleman conformance-test-runner
./conformance-test-runner --enforce_recommended --failure_list failure_list_python_cpp.txt ./conformance_python.py
+test_nodejs: protoc_middleman conformance-test-runner $(other_language_protoc_outputs)
+ NODE_PATH=../js:. ./conformance-test-runner --enforce_recommended --failure_list failure_list_js.txt ./conformance_nodejs.js
+
if OBJC_CONFORMANCE_TEST
test_objc: protoc_middleman conformance-test-runner conformance-objc
diff --git a/conformance/README.md b/conformance/README.md
index 9388055f..971fe8f6 100644
--- a/conformance/README.md
+++ b/conformance/README.md
@@ -19,11 +19,39 @@ directory to build `protoc`, since all the tests depend on it.
$ make
-Then to run the tests against the C++ implementation, run:
+Running the tests for C++
+-------------------------
+
+To run the tests against the C++ implementation, run:
$ cd conformance && make test_cpp
-More tests and languages will be added soon!
+Running the tests for JavaScript (Node.js)
+------------------------------------------
+
+To run the JavaScript tests against Node.js, make sure you have "node"
+on your path and then run:
+
+ $ cd conformance && make test_nodejs
+
+Running the tests for Ruby (MRI)
+--------------------------------
+
+To run the Ruby tests against MRI, first build the C extension:
+
+ $ cd ruby && rake
+
+Then run the tests like so:
+
+ $ cd conformance && make test_ruby
+
+Running the tests for other languages
+-------------------------------------
+
+Most of the languages in the Protobuf source tree are set up to run
+conformance tests. However some of them are more tricky to set up
+properly. See `tests.sh` in the base of the repository to see how
+Travis runs the tests.
Testing other Protocol Buffer implementations
---------------------------------------------
diff --git a/conformance/autoload.php b/conformance/autoload.php
new file mode 100644
index 00000000..0f49aecb
--- /dev/null
+++ b/conformance/autoload.php
@@ -0,0 +1,21 @@
+<?php
+
+define("GOOGLE_INTERNAL_NAMESPACE", "Google\\Protobuf\\Internal\\");
+define("GOOGLE_NAMESPACE", "Google\\Protobuf\\");
+define("GOOGLE_GPBMETADATA_NAMESPACE", "GPBMetadata\\Google\\Protobuf\\");
+
+function protobuf_autoloader_impl($class, $prefix) {
+ $length = strlen($prefix);
+ if ((substr($class, 0, $length) === $prefix)) {
+ $path = '../php/src/' . implode('/', array_map('ucwords', explode('\\', $class))) . '.php';
+ include_once $path;
+ }
+}
+
+function protobuf_autoloader($class) {
+ protobuf_autoloader_impl($class, GOOGLE_INTERNAL_NAMESPACE);
+ protobuf_autoloader_impl($class, GOOGLE_NAMESPACE);
+ protobuf_autoloader_impl($class, GOOGLE_GPBMETADATA_NAMESPACE);
+}
+
+spl_autoload_register('protobuf_autoloader');
diff --git a/conformance/conformance.proto b/conformance/conformance.proto
index 18e4b7bc..525140e9 100644
--- a/conformance/conformance.proto
+++ b/conformance/conformance.proto
@@ -77,6 +77,11 @@ message ConformanceRequest {
// Which format should the testee serialize its message to?
WireFormat requested_output_format = 3;
+
+ // The full name for the test message to use; for the moment, either:
+ // protobuf_test_messages.proto3.TestAllTypesProto3 or
+ // protobuf_test_messages.proto2.TestAllTypesProto2.
+ string message_type = 4;
}
// Represents a single test case's output.
diff --git a/conformance/conformance_cpp.cc b/conformance/conformance_cpp.cc
index b865cd93..9540b50e 100644
--- a/conformance/conformance_cpp.cc
+++ b/conformance/conformance_cpp.cc
@@ -34,6 +34,8 @@
#include "conformance.pb.h"
#include <google/protobuf/test_messages_proto3.pb.h>
+#include <google/protobuf/test_messages_proto2.pb.h>
+#include <google/protobuf/message.h>
#include <google/protobuf/util/json_util.h>
#include <google/protobuf/util/type_resolver_util.h>
@@ -41,13 +43,16 @@ using conformance::ConformanceRequest;
using conformance::ConformanceResponse;
using google::protobuf::Descriptor;
using google::protobuf::DescriptorPool;
+using google::protobuf::Message;
+using google::protobuf::MessageFactory;
using google::protobuf::internal::scoped_ptr;
using google::protobuf::util::BinaryToJsonString;
using google::protobuf::util::JsonToBinaryString;
using google::protobuf::util::NewTypeResolverForDescriptorPool;
using google::protobuf::util::Status;
using google::protobuf::util::TypeResolver;
-using protobuf_test_messages::proto3::TestAllTypes;
+using protobuf_test_messages::proto3::TestAllTypesProto3;
+using protobuf_test_messages::proto2::TestAllTypesProto2;
using std::string;
static const char kTypeUrlPrefix[] = "type.googleapis.com";
@@ -87,17 +92,24 @@ void CheckedWrite(int fd, const void *buf, size_t len) {
}
void DoTest(const ConformanceRequest& request, ConformanceResponse* response) {
- TestAllTypes test_message;
+ Message *test_message;
+ const Descriptor *descriptor = DescriptorPool::generated_pool()->FindMessageTypeByName(
+ request.message_type());
+ if (!descriptor) {
+ GOOGLE_LOG(FATAL) << "No such message type: " << request.message_type();
+ }
+ test_message = MessageFactory::generated_factory()->GetPrototype(descriptor)->New();
switch (request.payload_case()) {
- case ConformanceRequest::kProtobufPayload:
- if (!test_message.ParseFromString(request.protobuf_payload())) {
+ case ConformanceRequest::kProtobufPayload: {
+ if (!test_message->ParseFromString(request.protobuf_payload())) {
// Getting parse details would involve something like:
// http://stackoverflow.com/questions/22121922/how-can-i-get-more-details-about-errors-generated-during-protobuf-parsing-c
response->set_parse_error("Parse error (no more details available).");
return;
}
break;
+ }
case ConformanceRequest::kJsonPayload: {
string proto_binary;
@@ -109,7 +121,7 @@ void DoTest(const ConformanceRequest& request, ConformanceResponse* response) {
return;
}
- if (!test_message.ParseFromString(proto_binary)) {
+ if (!test_message->ParseFromString(proto_binary)) {
response->set_runtime_error(
"Parsing JSON generates invalid proto output.");
return;
@@ -127,14 +139,14 @@ void DoTest(const ConformanceRequest& request, ConformanceResponse* response) {
GOOGLE_LOG(FATAL) << "Unspecified output format";
break;
- case conformance::PROTOBUF:
- GOOGLE_CHECK(
- test_message.SerializeToString(response->mutable_protobuf_payload()));
+ case conformance::PROTOBUF: {
+ GOOGLE_CHECK(test_message->SerializeToString(response->mutable_protobuf_payload()));
break;
+ }
case conformance::JSON: {
string proto_binary;
- GOOGLE_CHECK(test_message.SerializeToString(&proto_binary));
+ GOOGLE_CHECK(test_message->SerializeToString(&proto_binary));
Status status = BinaryToJsonString(type_resolver, *type_url, proto_binary,
response->mutable_json_payload());
if (!status.ok()) {
@@ -197,7 +209,7 @@ bool DoTestIo() {
int main() {
type_resolver = NewTypeResolverForDescriptorPool(
kTypeUrlPrefix, DescriptorPool::generated_pool());
- type_url = new string(GetTypeUrl(TestAllTypes::descriptor()));
+ type_url = new string(GetTypeUrl(TestAllTypesProto3::descriptor()));
while (1) {
if (!DoTestIo()) {
fprintf(stderr, "conformance-cpp: received EOF from test runner "
diff --git a/conformance/conformance_nodejs.js b/conformance/conformance_nodejs.js
new file mode 100755
index 00000000..5d3955f7
--- /dev/null
+++ b/conformance/conformance_nodejs.js
@@ -0,0 +1,182 @@
+#!/usr/bin/env node
+
+/*
+ * 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.
+ */
+
+var conformance = require('conformance_pb');
+var test_messages_proto3 = require('google/protobuf/test_messages_proto3_pb');
+var test_messages_proto2 = require('google/protobuf/test_messages_proto2_pb');
+var fs = require('fs');
+
+var testCount = 0;
+
+function doTest(request) {
+ var testMessage;
+ var response = new conformance.ConformanceResponse();
+
+ try {
+ if (request.getRequestedOutputFormat() === conformance.WireFormat.JSON) {
+ response.setSkipped("JSON not supported.");
+ return response;
+ }
+
+ switch (request.getPayloadCase()) {
+ case conformance.ConformanceRequest.PayloadCase.PROTOBUF_PAYLOAD: {
+ if (request.getMessageType() == "protobuf_test_messages.proto3.TestAllTypesProto3") {
+ try {
+ testMessage = test_messages_proto3.TestAllTypesProto3.deserializeBinary(
+ request.getProtobufPayload());
+ } catch (err) {
+ response.setParseError(err.toString());
+ return response;
+ }
+ } else if (request.getMessageType() == "protobuf_test_messages.proto2.TestAllTypesProto2"){
+ try {
+ testMessage = test_messages_proto2.TestAllTypesProto2.deserializeBinary(
+ request.getProtobufPayload());
+ } catch (err) {
+ response.setParseError(err.toString());
+ return response;
+ }
+ } else {
+ throw "Protobuf request doesn\'t have specific payload type";
+ }
+ }
+
+ case conformance.ConformanceRequest.PayloadCase.JSON_PAYLOAD:
+ response.setSkipped("JSON not supported.");
+ return response;
+
+ case conformance.ConformanceRequest.PayloadCase.PAYLOAD_NOT_SET:
+ response.setRuntimeError("Request didn't have payload");
+ return response;
+ }
+
+ switch (request.getRequestedOutputFormat()) {
+ case conformance.WireFormat.UNSPECIFIED:
+ response.setRuntimeError("Unspecified output format");
+ return response;
+
+ case conformance.WireFormat.PROTOBUF:
+ response.setProtobufPayload(testMessage.serializeBinary());
+
+ case conformance.WireFormat.JSON:
+ response.setSkipped("JSON not supported.");
+ return response;
+
+ default:
+ throw "Request didn't have requested output format";
+ }
+ } catch (err) {
+ response.setRuntimeError(err.toString());
+ }
+
+ return response;
+}
+
+function onEof(totalRead) {
+ if (totalRead == 0) {
+ return undefined;
+ } else {
+ throw "conformance_nodejs: premature EOF on stdin.";
+ }
+}
+
+// Utility function to read a buffer of N bytes.
+function readBuffer(bytes) {
+ var buf = new Buffer(bytes);
+ var totalRead = 0;
+ while (totalRead < bytes) {
+ var read = 0;
+ try {
+ read = fs.readSync(process.stdin.fd, buf, totalRead, bytes - totalRead);
+ } catch (e) {
+ if (e.code == 'EOF') {
+ return onEof(totalRead)
+ } else if (e.code == 'EAGAIN') {
+ } else {
+ throw "conformance_nodejs: Error reading from stdin." + e;
+ }
+ }
+
+ totalRead += read;
+ }
+
+ return buf;
+}
+
+function writeBuffer(buffer) {
+ var totalWritten = 0;
+ while (totalWritten < buffer.length) {
+ totalWritten += fs.writeSync(
+ process.stdout.fd, buffer, totalWritten, buffer.length - totalWritten);
+ }
+}
+
+// Returns true if the test ran successfully, false on legitimate EOF.
+// If EOF is encountered in an unexpected place, raises IOError.
+function doTestIo() {
+ var lengthBuf = readBuffer(4);
+ if (!lengthBuf) {
+ return false;
+ }
+
+ var length = lengthBuf.readInt32LE(0);
+ var serializedRequest = readBuffer(length);
+ if (!serializedRequest) {
+ throw "conformance_nodejs: Failed to read request.";
+ }
+
+ serializedRequest = new Uint8Array(serializedRequest);
+ var request =
+ conformance.ConformanceRequest.deserializeBinary(serializedRequest);
+ var response = doTest(request);
+
+ var serializedResponse = response.serializeBinary();
+
+ lengthBuf = new Buffer(4);
+ lengthBuf.writeInt32LE(serializedResponse.length, 0);
+ writeBuffer(lengthBuf);
+ writeBuffer(new Buffer(serializedResponse));
+
+ testCount += 1
+
+ return true;
+}
+
+while (true) {
+ if (!doTestIo()) {
+ console.error('conformance_nodejs: received EOF from test runner ' +
+ "after " + testCount + " tests, exiting")
+ break;
+ }
+}
diff --git a/conformance/conformance_objc.m b/conformance/conformance_objc.m
index ef037f84..84a43811 100644
--- a/conformance/conformance_objc.m
+++ b/conformance/conformance_objc.m
@@ -31,6 +31,7 @@
#import <Foundation/Foundation.h>
#import "Conformance.pbobjc.h"
+#import "google/protobuf/TestMessagesProto2.pbobjc.h"
#import "google/protobuf/TestMessagesProto3.pbobjc.h"
static void Die(NSString *format, ...) __dead2;
@@ -63,7 +64,7 @@ static NSData *CheckedReadDataOfLength(NSFileHandle *handle, NSUInteger numBytes
static ConformanceResponse *DoTest(ConformanceRequest *request) {
ConformanceResponse *response = [ConformanceResponse message];
- TestAllTypes *testMessage = nil;
+ GPBMessage *testMessage = nil;
switch (request.payloadOneOfCase) {
case ConformanceRequest_Payload_OneOfCase_GPBUnsetOneOfCase:
@@ -71,9 +72,16 @@ static ConformanceResponse *DoTest(ConformanceRequest *request) {
break;
case ConformanceRequest_Payload_OneOfCase_ProtobufPayload: {
+ Class msgClass = nil;
+ if ([request.messageType isEqual:@"protobuf_test_messages.proto3.TestAllTypesProto3"]) {
+ msgClass = [Proto3TestAllTypesProto3 class];
+ } else if ([request.messageType isEqual:@"protobuf_test_messages.proto2.TestAllTypesProto2"]) {
+ msgClass = [TestAllTypesProto2 class];
+ } else {
+ Die(@"Protobuf request had an unknown message_type: %@", request.messageType);
+ }
NSError *error = nil;
- testMessage = [TestAllTypes parseFromData:request.protobufPayload
- error:&error];
+ testMessage = [msgClass parseFromData:request.protobufPayload error:&error];
if (!testMessage) {
response.parseError =
[NSString stringWithFormat:@"Parse error: %@", error];
diff --git a/conformance/conformance_php.php b/conformance/conformance_php.php
new file mode 100755
index 00000000..19f9a092
--- /dev/null
+++ b/conformance/conformance_php.php
@@ -0,0 +1,105 @@
+<?php
+
+require_once("Conformance/WireFormat.php");
+require_once("Conformance/ConformanceResponse.php");
+require_once("Conformance/ConformanceRequest.php");
+require_once("Protobuf_test_messages/Proto3/ForeignMessage.php");
+require_once("Protobuf_test_messages/Proto3/ForeignEnum.php");
+require_once("Protobuf_test_messages/Proto3/TestAllTypesProto3.php");
+require_once("Protobuf_test_messages/Proto3/TestAllTypesProto3_NestedMessage.php");
+require_once("Protobuf_test_messages/Proto3/TestAllTypesProto3_NestedEnum.php");
+
+require_once("GPBMetadata/Conformance.php");
+require_once("GPBMetadata/Google/Protobuf/TestMessagesProto3.php");
+
+use \Conformance\WireFormat;
+
+if (!ini_get("date.timezone")) {
+ ini_set("date.timezone", "UTC");
+}
+
+$test_count = 0;
+
+function doTest($request)
+{
+ $test_message = new \Protobuf_test_messages\Proto3\TestAllTypesProto3();
+ $response = new \Conformance\ConformanceResponse();
+ if ($request->getPayload() == "protobuf_payload") {
+ if ($request->getMessageType() == "protobuf_test_messages.proto3.TestAllTypesProto3") {
+ try {
+ $test_message->mergeFromString($request->getProtobufPayload());
+ } catch (Exception $e) {
+ $response->setParseError($e->getMessage());
+ return $response;
+ }
+ } elseif ($request->getMessageType() == "protobuf_test_messages.proto2.TestAllTypesProto2") {
+ $response->setSkipped("PHP doesn't support proto2");
+ return $response;
+ } else {
+ trigger_error("Protobuf request doesn't have specific payload type", E_USER_ERROR);
+ }
+ } elseif ($request->getPayload() == "json_payload") {
+ try {
+ $test_message->mergeFromJsonString($request->getJsonPayload());
+ } catch (Exception $e) {
+ $response->setParseError($e->getMessage());
+ return $response;
+ }
+ } else {
+ trigger_error("Request didn't have payload.", E_USER_ERROR);
+ }
+
+ if ($request->getRequestedOutputFormat() == WireFormat::UNSPECIFIED) {
+ trigger_error("Unspecified output format.", E_USER_ERROR);
+ } elseif ($request->getRequestedOutputFormat() == WireFormat::PROTOBUF) {
+ $response->setProtobufPayload($test_message->serializeToString());
+ } elseif ($request->getRequestedOutputFormat() == WireFormat::JSON) {
+ try {
+ $response->setJsonPayload($test_message->serializeToJsonString());
+ } catch (Exception $e) {
+ $response->setSerializeError($e->getMessage());
+ return $response;
+ }
+ }
+
+ return $response;
+}
+
+function doTestIO()
+{
+ $length_bytes = fread(STDIN, 4);
+ if (strlen($length_bytes) == 0) {
+ return false; # EOF
+ } elseif (strlen($length_bytes) != 4) {
+ fwrite(STDERR, "I/O error\n");
+ return false;
+ }
+
+ $length = unpack("V", $length_bytes)[1];
+ $serialized_request = fread(STDIN, $length);
+ if (strlen($serialized_request) != $length) {
+ trigger_error("I/O error", E_USER_ERROR);
+ }
+
+ $request = new \Conformance\ConformanceRequest();
+ $request->mergeFromString($serialized_request);
+
+ $response = doTest($request);
+
+ $serialized_response = $response->serializeToString();
+ fwrite(STDOUT, pack("V", strlen($serialized_response)));
+ fwrite(STDOUT, $serialized_response);
+
+ $GLOBALS['test_count'] += 1;
+
+ return true;
+}
+
+while(true){
+ if (!doTestIO()) {
+ fprintf(STDERR,
+ "conformance_php: received EOF from test runner " +
+ "after %d tests, exiting\n", $test_count);
+ exit;
+ }
+}
diff --git a/conformance/conformance_python.py b/conformance/conformance_python.py
index 7ace9b16..c5ba2467 100755
--- a/conformance/conformance_python.py
+++ b/conformance/conformance_python.py
@@ -38,9 +38,12 @@ See conformance.proto for more information.
import struct
import sys
import os
+from google.protobuf import descriptor
+from google.protobuf import descriptor_pool
from google.protobuf import json_format
from google.protobuf import message
from google.protobuf import test_messages_proto3_pb2
+from google.protobuf import test_messages_proto2_pb2
import conformance_pb2
sys.stdout = os.fdopen(sys.stdout.fileno(), 'wb', 0)
@@ -53,9 +56,17 @@ class ProtocolError(Exception):
pass
def do_test(request):
- test_message = test_messages_proto3_pb2.TestAllTypes()
+ isProto3 = (request.message_type == "protobuf_test_messages.proto3.TestAllTypesProto3")
+ isJson = (request.WhichOneof('payload') == 'json_payload')
+ isProto2 = (request.message_type == "protobuf_test_messages.proto2.TestAllTypesProto2")
+
+ if (not isProto3) and (not isJson) and (not isProto2):
+ raise ProtocolError("Protobuf request doesn't have specific payload type")
+
+ test_message = test_messages_proto2_pb2.TestAllTypesProto2() if isProto2 else \
+ test_messages_proto3_pb2.TestAllTypesProto3()
+
response = conformance_pb2.ConformanceResponse()
- test_message = test_messages_proto3_pb2.TestAllTypes()
try:
if request.WhichOneof('payload') == 'protobuf_payload':
@@ -63,8 +74,8 @@ def do_test(request):
test_message.ParseFromString(request.protobuf_payload)
except message.DecodeError as e:
response.parse_error = str(e)
- return response
-
+ return response
+
elif request.WhichOneof('payload') == 'json_payload':
try:
json_format.Parse(request.json_payload, test_message)
@@ -82,7 +93,7 @@ def do_test(request):
response.protobuf_payload = test_message.SerializeToString()
elif request.requested_output_format == conformance_pb2.JSON:
- try:
+ try:
response.json_payload = json_format.MessageToJson(test_message)
except Exception as e:
response.serialize_error = str(e)
diff --git a/conformance/conformance_ruby.rb b/conformance/conformance_ruby.rb
index b7b7cf1c..df63bf7c 100755
--- a/conformance/conformance_ruby.rb
+++ b/conformance/conformance_ruby.rb
@@ -37,23 +37,30 @@ $test_count = 0
$verbose = false
def do_test(request)
- test_message = ProtobufTestMessages::Proto3::TestAllTypes.new
+ test_message = ProtobufTestMessages::Proto3::TestAllTypesProto3.new
response = Conformance::ConformanceResponse.new
begin
case request.payload
when :protobuf_payload
- begin
- test_message = ProtobufTestMessages::Proto3::TestAllTypes.decode(
- request.protobuf_payload)
- rescue Google::Protobuf::ParseError => err
- response.parse_error = err.message.encode('utf-8')
+ if request.message_type.eql?('protobuf_test_messages.proto3.TestAllTypesProto3')
+ begin
+ test_message = ProtobufTestMessages::Proto3::TestAllTypesProto3.decode(
+ request.protobuf_payload)
+ rescue Google::Protobuf::ParseError => err
+ response.parse_error = err.message.encode('utf-8')
+ return response
+ end
+ elsif request.message_type.eql?('protobuf_test_messages.proto2.TestAllTypesProto2')
+ response.skipped = "Ruby doesn't support proto2"
return response
+ else
+ fail "Protobuf request doesn't have specific payload type"
end
when :json_payload
begin
- test_message = ProtobufTestMessages::Proto3::TestAllTypes.decode_json(
+ test_message = ProtobufTestMessages::Proto3::TestAllTypesProto3.decode_json(
request.json_payload)
rescue Google::Protobuf::ParseError => err
response.parse_error = err.message.encode('utf-8')
diff --git a/conformance/conformance_test.cc b/conformance/conformance_test.cc
index dd266d15..c54d4ccd 100644
--- a/conformance/conformance_test.cc
+++ b/conformance/conformance_test.cc
@@ -35,6 +35,7 @@
#include "conformance.pb.h"
#include "conformance_test.h"
#include <google/protobuf/test_messages_proto3.pb.h>
+#include <google/protobuf/test_messages_proto2.pb.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/stringprintf.h>
@@ -59,7 +60,8 @@ using google::protobuf::util::JsonToBinaryString;
using google::protobuf::util::MessageDifferencer;
using google::protobuf::util::NewTypeResolverForDescriptorPool;
using google::protobuf::util::Status;
-using protobuf_test_messages::proto3::TestAllTypes;
+using protobuf_test_messages::proto3::TestAllTypesProto3;
+using protobuf_test_messages::proto2::TestAllTypesProto2;
using std::string;
namespace {
@@ -109,13 +111,18 @@ string cat(const string& a, const string& b,
// The maximum number of bytes that it takes to encode a 64-bit varint.
#define VARINT_MAX_LEN 10
-size_t vencode64(uint64_t val, char *buf) {
+size_t vencode64(uint64_t val, int over_encoded_bytes, char *buf) {
if (val == 0) { buf[0] = 0; return 1; }
size_t i = 0;
while (val) {
uint8_t byte = val & 0x7fU;
val >>= 7;
- if (val) byte |= 0x80U;
+ if (val || over_encoded_bytes) byte |= 0x80U;
+ buf[i++] = byte;
+ }
+ while (over_encoded_bytes--) {
+ assert(i < 10);
+ uint8_t byte = over_encoded_bytes ? 0x80 : 0;
buf[i++] = byte;
}
return i;
@@ -123,7 +130,15 @@ size_t vencode64(uint64_t val, char *buf) {
string varint(uint64_t x) {
char buf[VARINT_MAX_LEN];
- size_t len = vencode64(x, buf);
+ size_t len = vencode64(x, 0, buf);
+ return string(buf, len);
+}
+
+// Encodes a varint that is |extra| bytes longer than it needs to be, but still
+// valid.
+string longvarint(uint64_t x, int extra) {
+ char buf[VARINT_MAX_LEN];
+ size_t len = vencode64(x, extra, buf);
return string(buf, len);
}
@@ -150,8 +165,10 @@ string submsg(uint32_t fn, const string& buf) {
#define UNKNOWN_FIELD 666
const FieldDescriptor* GetFieldForType(FieldDescriptor::Type type,
- bool repeated) {
- const Descriptor* d = TestAllTypes().GetDescriptor();
+ bool repeated, bool isProto3) {
+
+ const Descriptor* d = isProto3 ?
+ TestAllTypesProto3().GetDescriptor() : TestAllTypesProto2().GetDescriptor();
for (int i = 0; i < d->field_count(); i++) {
const FieldDescriptor* f = d->field(i);
if (f->type() == type && f->is_repeated() == repeated) {
@@ -258,24 +275,63 @@ void ConformanceTestSuite::RunTest(const string& test_name,
void ConformanceTestSuite::RunValidInputTest(
const string& test_name, ConformanceLevel level, const string& input,
WireFormat input_format, const string& equivalent_text_format,
- WireFormat requested_output) {
- TestAllTypes reference_message;
+ WireFormat requested_output, bool isProto3) {
+ auto newTestMessage = [&isProto3]() {
+ Message* newMessage;
+ if (isProto3) {
+ newMessage = new TestAllTypesProto3;
+ } else {
+ newMessage = new TestAllTypesProto2;
+ }
+ return newMessage;
+ };
+ Message* reference_message = newTestMessage();
GOOGLE_CHECK(
- TextFormat::ParseFromString(equivalent_text_format, &reference_message))
+ TextFormat::ParseFromString(equivalent_text_format, reference_message))
<< "Failed to parse data for test case: " << test_name
<< ", data: " << equivalent_text_format;
+ const string equivalent_wire_format = reference_message->SerializeAsString();
+ RunValidBinaryInputTest(test_name, level, input, input_format,
+ equivalent_wire_format, requested_output, isProto3);
+}
+
+void ConformanceTestSuite::RunValidBinaryInputTest(
+ const string& test_name, ConformanceLevel level, const string& input,
+ WireFormat input_format, const string& equivalent_wire_format,
+ WireFormat requested_output, bool isProto3) {
+ auto newTestMessage = [&isProto3]() {
+ Message* newMessage;
+ if (isProto3) {
+ newMessage = new TestAllTypesProto3;
+ } else {
+ newMessage = new TestAllTypesProto2;
+ }
+ return newMessage;
+ };
+ Message* reference_message = newTestMessage();
+ GOOGLE_CHECK(
+ reference_message->ParseFromString(equivalent_wire_format))
+ << "Failed to parse wire data for test case: " << test_name;
ConformanceRequest request;
ConformanceResponse response;
switch (input_format) {
- case conformance::PROTOBUF:
+ case conformance::PROTOBUF: {
request.set_protobuf_payload(input);
+ if (isProto3) {
+ request.set_message_type("protobuf_test_messages.proto3.TestAllTypesProto3");
+ } else {
+ request.set_message_type("protobuf_test_messages.proto2.TestAllTypesProto2");
+ }
break;
+ }
- case conformance::JSON:
+ case conformance::JSON: {
+ request.set_message_type("protobuf_test_messages.proto3.TestAllTypesProto3");
request.set_json_payload(input);
break;
+ }
default:
GOOGLE_LOG(FATAL) << "Unspecified input format";
@@ -285,7 +341,7 @@ void ConformanceTestSuite::RunValidInputTest(
RunTest(test_name, request, &response);
- TestAllTypes test_message;
+ Message *test_message = newTestMessage();
switch (response.result_case()) {
case ConformanceResponse::RESULT_NOT_SET:
@@ -321,10 +377,10 @@ void ConformanceTestSuite::RunValidInputTest(
return;
}
- if (!test_message.ParseFromString(binary_protobuf)) {
+ if (!test_message->ParseFromString(binary_protobuf)) {
ReportFailure(test_name, level, request, response,
- "INTERNAL ERROR: internal JSON->protobuf transcode "
- "yielded unparseable proto.");
+ "INTERNAL ERROR: internal JSON->protobuf transcode "
+ "yielded unparseable proto.");
return;
}
@@ -339,9 +395,9 @@ void ConformanceTestSuite::RunValidInputTest(
return;
}
- if (!test_message.ParseFromString(response.protobuf_payload())) {
+ if (!test_message->ParseFromString(response.protobuf_payload())) {
ReportFailure(test_name, level, request, response,
- "Protobuf output we received from test was unparseable.");
+ "Protobuf output we received from test was unparseable.");
return;
}
@@ -360,7 +416,9 @@ void ConformanceTestSuite::RunValidInputTest(
string differences;
differencer.ReportDifferencesToString(&differences);
- if (differencer.Compare(reference_message, test_message)) {
+ bool check;
+ check = differencer.Compare(*reference_message, *test_message);
+ if (check) {
ReportSuccess(test_name);
} else {
ReportFailure(test_name, level, request, response,
@@ -368,14 +426,19 @@ void ConformanceTestSuite::RunValidInputTest(
differences.c_str());
}
}
-
-// Expect that this precise protobuf will cause a parse error.
-void ConformanceTestSuite::ExpectParseFailureForProto(
- const string& proto, const string& test_name, ConformanceLevel level) {
+void ConformanceTestSuite::ExpectParseFailureForProtoWithProtoVersion (
+ const string& proto, const string& test_name, ConformanceLevel level,
+ bool isProto3) {
ConformanceRequest request;
ConformanceResponse response;
request.set_protobuf_payload(proto);
+ if (isProto3) {
+ request.set_message_type("protobuf_test_messages.proto3.TestAllTypesProto3");
+ } else {
+ request.set_message_type("protobuf_test_messages.proto2.TestAllTypesProto2");
+ }
string effective_test_name = ConformanceLevelToString(level) +
+ (isProto3 ? ".Proto3" : ".Proto2") +
".ProtobufInput." + test_name;
// We don't expect output, but if the program erroneously accepts the protobuf
@@ -393,6 +456,13 @@ void ConformanceTestSuite::ExpectParseFailureForProto(
}
}
+// Expect that this precise protobuf will cause a parse error.
+void ConformanceTestSuite::ExpectParseFailureForProto(
+ const string& proto, const string& test_name, ConformanceLevel level) {
+ ExpectParseFailureForProtoWithProtoVersion(proto, test_name, level, true);
+ ExpectParseFailureForProtoWithProtoVersion(proto, test_name, level, false);
+}
+
// Expect that this protobuf will cause a parse error, even if it is followed
// by valid protobuf data. We can try running this twice: once with this
// data verbatim and once with this data followed by some valid data.
@@ -407,41 +477,61 @@ void ConformanceTestSuite::RunValidJsonTest(
const string& test_name, ConformanceLevel level, const string& input_json,
const string& equivalent_text_format) {
RunValidInputTest(
- ConformanceLevelToString(level) + ".JsonInput." + test_name +
+ ConformanceLevelToString(level) + ".Proto3.JsonInput." + test_name +
".ProtobufOutput", level, input_json, conformance::JSON,
- equivalent_text_format, conformance::PROTOBUF);
+ equivalent_text_format, conformance::PROTOBUF, true);
RunValidInputTest(
- ConformanceLevelToString(level) + ".JsonInput." + test_name +
+ ConformanceLevelToString(level) + ".Proto3.JsonInput." + test_name +
".JsonOutput", level, input_json, conformance::JSON,
- equivalent_text_format, conformance::JSON);
+ equivalent_text_format, conformance::JSON, true);
}
void ConformanceTestSuite::RunValidJsonTestWithProtobufInput(
- const string& test_name, ConformanceLevel level, const TestAllTypes& input,
+ const string& test_name, ConformanceLevel level, const TestAllTypesProto3& input,
const string& equivalent_text_format) {
RunValidInputTest(
- ConformanceLevelToString(level) + ".ProtobufInput." + test_name +
+ ConformanceLevelToString(level) + ".Proto3" + ".ProtobufInput." + test_name +
".JsonOutput", level, input.SerializeAsString(), conformance::PROTOBUF,
- equivalent_text_format, conformance::JSON);
+ equivalent_text_format, conformance::JSON, true);
}
void ConformanceTestSuite::RunValidProtobufTest(
const string& test_name, ConformanceLevel level,
- const string& input_protobuf, const string& equivalent_text_format) {
+ const string& input_protobuf, const string& equivalent_text_format,
+ bool isProto3) {
+ string rname = ".Proto3";
+ if (!isProto3) {
+ rname = ".Proto2";
+ }
RunValidInputTest(
- ConformanceLevelToString(level) + ".ProtobufInput." + test_name +
+ ConformanceLevelToString(level) + rname + ".ProtobufInput." + test_name +
".ProtobufOutput", level, input_protobuf, conformance::PROTOBUF,
- equivalent_text_format, conformance::PROTOBUF);
- RunValidInputTest(
- ConformanceLevelToString(level) + ".ProtobufInput." + test_name +
- ".JsonOutput", level, input_protobuf, conformance::PROTOBUF,
- equivalent_text_format, conformance::JSON);
+ equivalent_text_format, conformance::PROTOBUF, isProto3);
+ if (isProto3) {
+ RunValidInputTest(
+ ConformanceLevelToString(level) + rname + ".ProtobufInput." + test_name +
+ ".JsonOutput", level, input_protobuf, conformance::PROTOBUF,
+ equivalent_text_format, conformance::JSON, isProto3);
+ }
+}
+
+void ConformanceTestSuite::RunValidBinaryProtobufTest(
+ const string& test_name, ConformanceLevel level,
+ const string& input_protobuf, bool isProto3) {
+ string rname = ".Proto3";
+ if (!isProto3) {
+ rname = ".Proto2";
+ }
+ RunValidBinaryInputTest(
+ ConformanceLevelToString(level) + rname + ".ProtobufInput." + test_name +
+ ".ProtobufOutput", level, input_protobuf, conformance::PROTOBUF,
+ input_protobuf, conformance::PROTOBUF, isProto3);
}
void ConformanceTestSuite::RunValidProtobufTestWithMessage(
- const string& test_name, ConformanceLevel level, const TestAllTypes& input,
- const string& equivalent_text_format) {
- RunValidProtobufTest(test_name, level, input.SerializeAsString(), equivalent_text_format);
+ const string& test_name, ConformanceLevel level, const Message *input,
+ const string& equivalent_text_format, bool isProto3) {
+ RunValidProtobufTest(test_name, level, input->SerializeAsString(), equivalent_text_format, isProto3);
}
// According to proto3 JSON specification, JSON serializers follow more strict
@@ -456,9 +546,10 @@ void ConformanceTestSuite::RunValidJsonTestWithValidator(
ConformanceResponse response;
request.set_json_payload(input_json);
request.set_requested_output_format(conformance::JSON);
+ request.set_message_type("protobuf_test_messages.proto3.TestAllTypesProto3");
string effective_test_name = ConformanceLevelToString(level) +
- ".JsonInput." + test_name + ".Validator";
+ ".Proto3.JsonInput." + test_name + ".Validator";
RunTest(effective_test_name, request, &response);
@@ -494,8 +585,9 @@ void ConformanceTestSuite::ExpectParseFailureForJson(
ConformanceRequest request;
ConformanceResponse response;
request.set_json_payload(input_json);
+ request.set_message_type("protobuf_test_messages.proto3.TestAllTypesProto3");
string effective_test_name =
- ConformanceLevelToString(level) + ".JsonInput." + test_name;
+ ConformanceLevelToString(level) + ".Proto3.JsonInput." + test_name;
// We don't expect output, but if the program erroneously accepts the protobuf
// we let it send its response as this. We must not leave it unspecified.
@@ -514,7 +606,7 @@ void ConformanceTestSuite::ExpectParseFailureForJson(
void ConformanceTestSuite::ExpectSerializeFailureForJson(
const string& test_name, ConformanceLevel level, const string& text_format) {
- TestAllTypes payload_message;
+ TestAllTypesProto3 payload_message;
GOOGLE_CHECK(
TextFormat::ParseFromString(text_format, &payload_message))
<< "Failed to parse: " << text_format;
@@ -522,6 +614,7 @@ void ConformanceTestSuite::ExpectSerializeFailureForJson(
ConformanceRequest request;
ConformanceResponse response;
request.set_protobuf_payload(payload_message.SerializeAsString());
+ request.set_message_type("protobuf_test_messages.proto3.TestAllTypesProto3");
string effective_test_name =
ConformanceLevelToString(level) + "." + test_name + ".JsonOutput";
request.set_requested_output_format(conformance::JSON);
@@ -537,6 +630,7 @@ void ConformanceTestSuite::ExpectSerializeFailureForJson(
}
}
+//TODO: proto2?
void ConformanceTestSuite::TestPrematureEOFForType(FieldDescriptor::Type type) {
// Incomplete values for each wire type.
static const string incompletes[6] = {
@@ -548,8 +642,8 @@ void ConformanceTestSuite::TestPrematureEOFForType(FieldDescriptor::Type type) {
string("abc") // 32BIT
};
- const FieldDescriptor* field = GetFieldForType(type, false);
- const FieldDescriptor* rep_field = GetFieldForType(type, true);
+ const FieldDescriptor* field = GetFieldForType(type, false, true);
+ const FieldDescriptor* rep_field = GetFieldForType(type, true, true);
WireFormatLite::WireType wire_type = WireFormatLite::WireTypeForFieldType(
static_cast<WireFormatLite::FieldType>(type));
const string& incomplete = incompletes[wire_type];
@@ -627,33 +721,36 @@ void ConformanceTestSuite::TestPrematureEOFForType(FieldDescriptor::Type type) {
void ConformanceTestSuite::TestValidDataForType(
FieldDescriptor::Type type,
std::vector<std::pair<std::string, std::string>> values) {
- const string type_name =
- UpperCase(string(".") + FieldDescriptor::TypeName(type));
- WireFormatLite::WireType wire_type = WireFormatLite::WireTypeForFieldType(
- static_cast<WireFormatLite::FieldType>(type));
- const FieldDescriptor* field = GetFieldForType(type, false);
- const FieldDescriptor* rep_field = GetFieldForType(type, true);
-
- RunValidProtobufTest("ValidDataScalar" + type_name, REQUIRED,
- cat(tag(field->number(), wire_type), values[0].first),
- field->name() + ": " + values[0].second);
-
- string proto;
- string text = field->name() + ": " + values.back().second;
- for (size_t i = 0; i < values.size(); i++) {
- proto += cat(tag(field->number(), wire_type), values[i].first);
- }
- RunValidProtobufTest("RepeatedScalarSelectsLast" + type_name, REQUIRED,
- proto, text);
+ for (int isProto3 = 0; isProto3 < 2; isProto3++) {
+ const string type_name =
+ UpperCase(string(".") + FieldDescriptor::TypeName(type));
+ WireFormatLite::WireType wire_type = WireFormatLite::WireTypeForFieldType(
+ static_cast<WireFormatLite::FieldType>(type));
+ const FieldDescriptor* field = GetFieldForType(type, false, isProto3);
+ const FieldDescriptor* rep_field = GetFieldForType(type, true, isProto3);
+
+ RunValidProtobufTest("ValidDataScalar" + type_name, REQUIRED,
+ cat(tag(field->number(), wire_type), values[0].first),
+ field->name() + ": " + values[0].second, isProto3);
+
+ string proto;
+ string text = field->name() + ": " + values.back().second;
+ for (size_t i = 0; i < values.size(); i++) {
+ proto += cat(tag(field->number(), wire_type), values[i].first);
+ }
+ RunValidProtobufTest("RepeatedScalarSelectsLast" + type_name, REQUIRED,
+ proto, text, isProto3);
- proto.clear();
- text.clear();
+ proto.clear();
+ text.clear();
- for (size_t i = 0; i < values.size(); i++) {
- proto += cat(tag(rep_field->number(), wire_type), values[i].first);
- text += rep_field->name() + ": " + values[i].second + " ";
+ for (size_t i = 0; i < values.size(); i++) {
+ proto += cat(tag(rep_field->number(), wire_type), values[i].first);
+ text += rep_field->name() + ": " + values[i].second + " ";
+ }
+ RunValidProtobufTest("ValidDataRepeated" + type_name, REQUIRED,
+ proto, text, isProto3);
}
- RunValidProtobufTest("ValidDataRepeated" + type_name, REQUIRED, proto, text);
}
void ConformanceTestSuite::SetFailureList(const string& filename,
@@ -664,7 +761,7 @@ void ConformanceTestSuite::SetFailureList(const string& filename,
std::inserter(expected_to_fail_, expected_to_fail_.end()));
}
-bool ConformanceTestSuite::CheckSetEmpty(const set<string>& set_to_check,
+bool ConformanceTestSuite::CheckSetEmpty(const std::set<string>& set_to_check,
const std::string& write_to_file,
const std::string& msg) {
if (set_to_check.empty()) {
@@ -672,7 +769,7 @@ bool ConformanceTestSuite::CheckSetEmpty(const set<string>& set_to_check,
} else {
StringAppendF(&output_, "\n");
StringAppendF(&output_, "%s\n\n", msg.c_str());
- for (set<string>::const_iterator iter = set_to_check.begin();
+ for (std::set<string>::const_iterator iter = set_to_check.begin();
iter != set_to_check.end(); ++iter) {
StringAppendF(&output_, " %s\n", iter->c_str());
}
@@ -681,7 +778,7 @@ bool ConformanceTestSuite::CheckSetEmpty(const set<string>& set_to_check,
if (!write_to_file.empty()) {
std::ofstream os(write_to_file);
if (os) {
- for (set<string>::const_iterator iter = set_to_check.begin();
+ for (std::set<string>::const_iterator iter = set_to_check.begin();
iter != set_to_check.end(); ++iter) {
os << *iter << "\n";
}
@@ -695,6 +792,68 @@ bool ConformanceTestSuite::CheckSetEmpty(const set<string>& set_to_check,
}
}
+// TODO: proto2?
+void ConformanceTestSuite::TestIllegalTags() {
+ // field num 0 is illegal
+ string nullfield[] = {
+ "\1DEADBEEF",
+ "\2\1\1",
+ "\3\4",
+ "\5DEAD"
+ };
+ for (int i = 0; i < 4; i++) {
+ string name = "IllegalZeroFieldNum_Case_0";
+ name.back() += i;
+ ExpectParseFailureForProto(nullfield[i], name, REQUIRED);
+ }
+}
+template <class MessageType>
+void ConformanceTestSuite::TestOneofMessage (MessageType &message,
+ bool isProto3) {
+ message.set_oneof_uint32(0);
+ RunValidProtobufTestWithMessage(
+ "OneofZeroUint32", RECOMMENDED, &message, "oneof_uint32: 0", isProto3);
+ message.mutable_oneof_nested_message()->set_a(0);
+ RunValidProtobufTestWithMessage(
+ "OneofZeroMessage", RECOMMENDED, &message,
+ isProto3 ? "oneof_nested_message: {}" : "oneof_nested_message: {a: 0}",
+ isProto3);
+ message.mutable_oneof_nested_message()->set_a(1);
+ RunValidProtobufTestWithMessage(
+ "OneofZeroMessageSetTwice", RECOMMENDED, &message,
+ "oneof_nested_message: {a: 1}",
+ isProto3);
+ message.set_oneof_string("");
+ RunValidProtobufTestWithMessage(
+ "OneofZeroString", RECOMMENDED, &message, "oneof_string: \"\"", isProto3);
+ message.set_oneof_bytes("");
+ RunValidProtobufTestWithMessage(
+ "OneofZeroBytes", RECOMMENDED, &message, "oneof_bytes: \"\"", isProto3);
+ message.set_oneof_bool(false);
+ RunValidProtobufTestWithMessage(
+ "OneofZeroBool", RECOMMENDED, &message, "oneof_bool: false", isProto3);
+ message.set_oneof_uint64(0);
+ RunValidProtobufTestWithMessage(
+ "OneofZeroUint64", RECOMMENDED, &message, "oneof_uint64: 0", isProto3);
+ message.set_oneof_float(0.0f);
+ RunValidProtobufTestWithMessage(
+ "OneofZeroFloat", RECOMMENDED, &message, "oneof_float: 0", isProto3);
+ message.set_oneof_double(0.0);
+ RunValidProtobufTestWithMessage(
+ "OneofZeroDouble", RECOMMENDED, &message, "oneof_double: 0", isProto3);
+ message.set_oneof_enum(MessageType::FOO);
+ RunValidProtobufTestWithMessage(
+ "OneofZeroEnum", RECOMMENDED, &message, "oneof_enum: FOO", isProto3);
+}
+
+template <class MessageType>
+void ConformanceTestSuite::TestUnknownMessage(MessageType& message,
+ bool isProto3) {
+ message.ParseFromString("\xA8\x1F\x01");
+ RunValidBinaryProtobufTest("UnknownVarint", REQUIRED,
+ message.SerializeAsString(), isProto3);
+}
+
bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
std::string* output) {
runner_ = runner;
@@ -706,7 +865,7 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
unexpected_succeeding_tests_.clear();
type_resolver_.reset(NewTypeResolverForDescriptorPool(
kTypeUrlPrefix, DescriptorPool::generated_pool()));
- type_url_ = GetTypeUrl(TestAllTypes::descriptor());
+ type_url_ = GetTypeUrl(TestAllTypesProto3::descriptor());
output_ = "\nCONFORMANCE TEST BEGIN ====================================\n\n";
@@ -715,6 +874,8 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
TestPrematureEOFForType(static_cast<FieldDescriptor::Type>(i));
}
+ TestIllegalTags();
+
int64 kInt64Min = -9223372036854775808ULL;
int64 kInt64Max = 9223372036854775807ULL;
uint64 kUint64Max = 18446744073709551615ULL;
@@ -729,6 +890,7 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
});
TestValidDataForType(FieldDescriptor::TYPE_FLOAT, {
{flt(0.1), "0.1"},
+ {flt(1.00000075e-36), "1.00000075e-36"},
{flt(3.402823e+38), "3.402823e+38"}, // 3.40282347e+38
{flt(1.17549435e-38f), "1.17549435e-38"}
});
@@ -744,13 +906,23 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
});
TestValidDataForType(FieldDescriptor::TYPE_INT32, {
{varint(12345), "12345"},
+ {longvarint(12345, 2), "12345"},
+ {longvarint(12345, 7), "12345"},
{varint(kInt32Max), std::to_string(kInt32Max)},
{varint(kInt32Min), std::to_string(kInt32Min)},
+ {varint(1LL << 33), std::to_string(static_cast<int32>(1LL << 33))},
+ {varint((1LL << 33) - 1),
+ std::to_string(static_cast<int32>((1LL << 33) - 1))},
});
TestValidDataForType(FieldDescriptor::TYPE_UINT32, {
{varint(12345), "12345"},
+ {longvarint(12345, 2), "12345"},
+ {longvarint(12345, 7), "12345"},
{varint(kUint32Max), std::to_string(kUint32Max)}, // UINT32_MAX
- {varint(0), "0"}
+ {varint(0), "0"},
+ {varint(1LL << 33), std::to_string(static_cast<uint32>(1LL << 33))},
+ {varint((1LL << 33) - 1),
+ std::to_string(static_cast<uint32>((1LL << 33) - 1))},
});
TestValidDataForType(FieldDescriptor::TYPE_FIXED64, {
{u64(12345), "12345"},
@@ -1192,7 +1364,7 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
"Int32FieldNegativeWithLeadingZero", REQUIRED,
R"({"optionalInt32": -01})");
// String values must follow the same syntax rule. Specifically leading
- // or traling spaces are not allowed.
+ // or trailing spaces are not allowed.
ExpectParseFailureForJson(
"Int32FieldLeadingSpace", REQUIRED,
R"({"optionalInt32": " 1"})");
@@ -1289,7 +1461,7 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
"optional_float: -inf");
// Non-cannonical Nan will be correctly normalized.
{
- TestAllTypes message;
+ TestAllTypesProto3 message;
// IEEE floating-point standard 32-bit quiet NaN:
// 0111 1111 1xxx xxxx xxxx xxxx xxxx xxxx
message.set_optional_float(
@@ -1361,7 +1533,7 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
"optional_double: -inf");
// Non-cannonical Nan will be correctly normalized.
{
- TestAllTypes message;
+ TestAllTypesProto3 message;
message.set_optional_double(
WireFormatLite::DecodeDouble(0x7FFA123456789ABCLL));
RunValidJsonTestWithProtobufInput(
@@ -1476,9 +1648,10 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
"BytesField", REQUIRED,
R"({"optionalBytes": "AQI="})",
R"(optional_bytes: "\x01\x02")");
- ExpectParseFailureForJson(
- "BytesFieldInvalidBase64Characters", REQUIRED,
- R"({"optionalBytes": "-_=="})");
+ RunValidJsonTest(
+ "BytesFieldBase64Url", RECOMMENDED,
+ R"({"optionalBytes": "-_"})",
+ R"(optional_bytes: "\xfb")");
// Message fields.
RunValidJsonTest(
@@ -1491,36 +1664,10 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
"OneofFieldDuplicate", REQUIRED,
R"({"oneofUint32": 1, "oneofString": "test"})");
// Ensure zero values for oneof make it out/backs.
- {
- TestAllTypes message;
- message.set_oneof_uint32(0);
- RunValidProtobufTestWithMessage(
- "OneofZeroUint32", RECOMMENDED, message, "oneof_uint32: 0");
- message.mutable_oneof_nested_message()->set_a(0);
- RunValidProtobufTestWithMessage(
- "OneofZeroMessage", RECOMMENDED, message, "oneof_nested_message: {}");
- message.set_oneof_string("");
- RunValidProtobufTestWithMessage(
- "OneofZeroString", RECOMMENDED, message, "oneof_string: \"\"");
- message.set_oneof_bytes("");
- RunValidProtobufTestWithMessage(
- "OneofZeroBytes", RECOMMENDED, message, "oneof_bytes: \"\"");
- message.set_oneof_bool(false);
- RunValidProtobufTestWithMessage(
- "OneofZeroBool", RECOMMENDED, message, "oneof_bool: false");
- message.set_oneof_uint64(0);
- RunValidProtobufTestWithMessage(
- "OneofZeroUint64", RECOMMENDED, message, "oneof_uint64: 0");
- message.set_oneof_float(0.0f);
- RunValidProtobufTestWithMessage(
- "OneofZeroFloat", RECOMMENDED, message, "oneof_float: 0");
- message.set_oneof_double(0.0);
- RunValidProtobufTestWithMessage(
- "OneofZeroDouble", RECOMMENDED, message, "oneof_double: 0");
- message.set_oneof_enum(TestAllTypes::FOO);
- RunValidProtobufTestWithMessage(
- "OneofZeroEnum", RECOMMENDED, message, "oneof_enum: FOO");
- }
+ TestAllTypesProto3 messageProto3;
+ TestAllTypesProto2 messageProto2;
+ TestOneofMessage(messageProto3, true);
+ TestOneofMessage(messageProto2, false);
RunValidJsonTest(
"OneofZeroUint32", RECOMMENDED,
R"({"oneofUint32": 0})", "oneof_uint32: 0");
@@ -1743,6 +1890,14 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
"StringFieldSingleQuoteBoth", RECOMMENDED,
R"({'optionalString': 'Hello world!'})");
+ // Unknown fields.
+ {
+ TestAllTypesProto3 messageProto3;
+ TestAllTypesProto2 messageProto2;
+ TestUnknownMessage(messageProto3, true);
+ TestUnknownMessage(messageProto2, false);
+ }
+
// Wrapper types.
RunValidJsonTest(
"OptionalBoolWrapper", REQUIRED,
@@ -1891,6 +2046,10 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
R"({"repeatedDuration": ["1.5s", "-1.5s"]})",
"repeated_duration: {seconds: 1 nanos: 500000000}"
"repeated_duration: {seconds: -1 nanos: -500000000}");
+ RunValidJsonTest(
+ "DurationNull", REQUIRED,
+ R"({"optionalDuration": null})",
+ "");
ExpectParseFailureForJson(
"DurationMissingS", REQUIRED,
@@ -1960,6 +2119,10 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
"TimestampWithNegativeOffset", REQUIRED,
R"({"optionalTimestamp": "1969-12-31T16:00:00-08:00"})",
"optional_timestamp: {seconds: 0}");
+ RunValidJsonTest(
+ "TimestampNull", REQUIRED,
+ R"({"optionalTimestamp": null})",
+ "");
ExpectParseFailureForJson(
"TimestampJsonInputTooSmall", REQUIRED,
@@ -2162,13 +2325,13 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
"Any", REQUIRED,
R"({
"optionalAny": {
- "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypes",
+ "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3",
"optionalInt32": 12345
}
})",
R"(
optional_any: {
- [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypes] {
+ [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] {
optional_int32: 12345
}
}
@@ -2179,7 +2342,7 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
"optionalAny": {
"@type": "type.googleapis.com/google.protobuf.Any",
"value": {
- "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypes",
+ "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3",
"optionalInt32": 12345
}
}
@@ -2187,7 +2350,7 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
R"(
optional_any: {
[type.googleapis.com/google.protobuf.Any] {
- [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypes] {
+ [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] {
optional_int32: 12345
}
}
@@ -2199,12 +2362,12 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
R"({
"optionalAny": {
"optionalInt32": 12345,
- "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypes"
+ "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3"
}
})",
R"(
optional_any: {
- [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypes] {
+ [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] {
optional_int32: 12345
}
}
diff --git a/conformance/conformance_test.h b/conformance/conformance_test.h
index 5f05a25b..4882412c 100644
--- a/conformance/conformance_test.h
+++ b/conformance/conformance_test.h
@@ -53,7 +53,7 @@ class ConformanceResponse;
namespace protobuf_test_messages {
namespace proto3 {
-class TestAllTypes;
+class TestAllTypesProto3;
} // namespace proto3
} // namespace protobuf_test_messages
@@ -165,7 +165,15 @@ class ConformanceTestSuite {
const string& input,
conformance::WireFormat input_format,
const string& equivalent_text_format,
- conformance::WireFormat requested_output);
+ conformance::WireFormat requested_output,
+ bool isProto3);
+ void RunValidBinaryInputTest(const string& test_name,
+ ConformanceLevel level,
+ const string& input,
+ conformance::WireFormat input_format,
+ const string& equivalent_wire_format,
+ conformance::WireFormat requested_output,
+ bool isProto3);
void RunValidJsonTest(const string& test_name,
ConformanceLevel level,
const string& input_json,
@@ -173,15 +181,21 @@ class ConformanceTestSuite {
void RunValidJsonTestWithProtobufInput(
const string& test_name,
ConformanceLevel level,
- const protobuf_test_messages::proto3::TestAllTypes& input,
+ const protobuf_test_messages::proto3::TestAllTypesProto3& input,
const string& equivalent_text_format);
void RunValidProtobufTest(const string& test_name, ConformanceLevel level,
const string& input_protobuf,
- const string& equivalent_text_format);
+ const string& equivalent_text_format,
+ bool isProto3);
+ void RunValidBinaryProtobufTest(const string& test_name,
+ ConformanceLevel level,
+ const string& input_protobuf,
+ bool isProto3);
void RunValidProtobufTestWithMessage(
const string& test_name, ConformanceLevel level,
- const protobuf_test_messages::proto3::TestAllTypes& input,
- const string& equivalent_text_format);
+ const Message *input,
+ const string& equivalent_text_format,
+ bool isProto3);
typedef std::function<bool(const Json::Value&)> Validator;
void RunValidJsonTestWithValidator(const string& test_name,
@@ -194,6 +208,10 @@ class ConformanceTestSuite {
void ExpectSerializeFailureForJson(const string& test_name,
ConformanceLevel level,
const string& text_format);
+ void ExpectParseFailureForProtoWithProtoVersion (const string& proto,
+ const string& test_name,
+ ConformanceLevel level,
+ bool isProto3);
void ExpectParseFailureForProto(const std::string& proto,
const std::string& test_name,
ConformanceLevel level);
@@ -201,10 +219,17 @@ class ConformanceTestSuite {
const std::string& test_name,
ConformanceLevel level);
void TestPrematureEOFForType(google::protobuf::FieldDescriptor::Type type);
+ void TestIllegalTags();
+ template <class MessageType>
+ void TestOneofMessage (MessageType &message,
+ bool isProto3);
+ template <class MessageType>
+ void TestUnknownMessage (MessageType &message,
+ bool isProto3);
void TestValidDataForType(
google::protobuf::FieldDescriptor::Type,
std::vector<std::pair<std::string, std::string>> values);
- bool CheckSetEmpty(const set<string>& set_to_check,
+ bool CheckSetEmpty(const std::set<string>& set_to_check,
const std::string& write_to_file, const std::string& msg);
ConformanceTestRunner* runner_;
int successes_;
diff --git a/conformance/failure_list_cpp.txt b/conformance/failure_list_cpp.txt
index 8cfd74da..8c328890 100644
--- a/conformance/failure_list_cpp.txt
+++ b/conformance/failure_list_cpp.txt
@@ -10,37 +10,48 @@
Recommended.FieldMaskNumbersDontRoundTrip.JsonOutput
Recommended.FieldMaskPathsDontRoundTrip.JsonOutput
Recommended.FieldMaskTooManyUnderscore.JsonOutput
-Recommended.JsonInput.BoolFieldDoubleQuotedFalse
-Recommended.JsonInput.BoolFieldDoubleQuotedTrue
-Recommended.JsonInput.FieldMaskInvalidCharacter
-Recommended.JsonInput.FieldNameDuplicate
-Recommended.JsonInput.FieldNameDuplicateDifferentCasing1
-Recommended.JsonInput.FieldNameDuplicateDifferentCasing2
-Recommended.JsonInput.FieldNameNotQuoted
-Recommended.JsonInput.MapFieldValueIsNull
-Recommended.JsonInput.RepeatedFieldMessageElementIsNull
-Recommended.JsonInput.RepeatedFieldPrimitiveElementIsNull
-Recommended.JsonInput.RepeatedFieldTrailingComma
-Recommended.JsonInput.RepeatedFieldTrailingCommaWithNewlines
-Recommended.JsonInput.RepeatedFieldTrailingCommaWithSpace
-Recommended.JsonInput.RepeatedFieldTrailingCommaWithSpaceCommaSpace
-Recommended.JsonInput.StringFieldSingleQuoteBoth
-Recommended.JsonInput.StringFieldSingleQuoteKey
-Recommended.JsonInput.StringFieldSingleQuoteValue
-Recommended.JsonInput.StringFieldUppercaseEscapeLetter
-Recommended.JsonInput.TrailingCommaInAnObject
-Recommended.JsonInput.TrailingCommaInAnObjectWithNewlines
-Recommended.JsonInput.TrailingCommaInAnObjectWithSpace
-Recommended.JsonInput.TrailingCommaInAnObjectWithSpaceCommaSpace
-Required.ProtobufInput.PrematureEofBeforeKnownRepeatedValue.MESSAGE
-Required.ProtobufInput.PrematureEofInDelimitedDataForKnownNonRepeatedValue.MESSAGE
-Required.ProtobufInput.PrematureEofInDelimitedDataForKnownRepeatedValue.MESSAGE
-Required.ProtobufInput.PrematureEofInPackedField.BOOL
-Required.ProtobufInput.PrematureEofInPackedField.ENUM
-Required.ProtobufInput.PrematureEofInPackedField.INT32
-Required.ProtobufInput.PrematureEofInPackedField.INT64
-Required.ProtobufInput.PrematureEofInPackedField.SINT32
-Required.ProtobufInput.PrematureEofInPackedField.SINT64
-Required.ProtobufInput.PrematureEofInPackedField.UINT32
-Required.ProtobufInput.PrematureEofInPackedField.UINT64
-Required.ProtobufInput.PrematureEofInsideKnownRepeatedValue.MESSAGE
+Recommended.Proto3.JsonInput.BoolFieldDoubleQuotedFalse
+Recommended.Proto3.JsonInput.BoolFieldDoubleQuotedTrue
+Recommended.Proto3.JsonInput.BytesFieldBase64Url.JsonOutput
+Recommended.Proto3.JsonInput.BytesFieldBase64Url.ProtobufOutput
+Recommended.Proto3.JsonInput.FieldMaskInvalidCharacter
+Recommended.Proto3.JsonInput.FieldNameDuplicate
+Recommended.Proto3.JsonInput.FieldNameDuplicateDifferentCasing1
+Recommended.Proto3.JsonInput.FieldNameDuplicateDifferentCasing2
+Recommended.Proto3.JsonInput.FieldNameNotQuoted
+Recommended.Proto3.JsonInput.MapFieldValueIsNull
+Recommended.Proto3.JsonInput.RepeatedFieldMessageElementIsNull
+Recommended.Proto3.JsonInput.RepeatedFieldPrimitiveElementIsNull
+Recommended.Proto3.JsonInput.RepeatedFieldTrailingComma
+Recommended.Proto3.JsonInput.RepeatedFieldTrailingCommaWithNewlines
+Recommended.Proto3.JsonInput.RepeatedFieldTrailingCommaWithSpace
+Recommended.Proto3.JsonInput.RepeatedFieldTrailingCommaWithSpaceCommaSpace
+Recommended.Proto3.JsonInput.StringFieldSingleQuoteBoth
+Recommended.Proto3.JsonInput.StringFieldSingleQuoteKey
+Recommended.Proto3.JsonInput.StringFieldSingleQuoteValue
+Recommended.Proto3.JsonInput.StringFieldUppercaseEscapeLetter
+Recommended.Proto3.JsonInput.TrailingCommaInAnObject
+Recommended.Proto3.JsonInput.TrailingCommaInAnObjectWithNewlines
+Recommended.Proto3.JsonInput.TrailingCommaInAnObjectWithSpace
+Recommended.Proto3.JsonInput.TrailingCommaInAnObjectWithSpaceCommaSpace
+Required.Proto3.ProtobufInput.PrematureEofInDelimitedDataForKnownNonRepeatedValue.MESSAGE
+Required.Proto3.ProtobufInput.PrematureEofInDelimitedDataForKnownRepeatedValue.MESSAGE
+Required.Proto3.ProtobufInput.PrematureEofInPackedField.BOOL
+Required.Proto3.ProtobufInput.PrematureEofInPackedField.ENUM
+Required.Proto3.ProtobufInput.PrematureEofInPackedField.INT32
+Required.Proto3.ProtobufInput.PrematureEofInPackedField.INT64
+Required.Proto3.ProtobufInput.PrematureEofInPackedField.SINT32
+Required.Proto3.ProtobufInput.PrematureEofInPackedField.SINT64
+Required.Proto3.ProtobufInput.PrematureEofInPackedField.UINT32
+Required.Proto3.ProtobufInput.PrematureEofInPackedField.UINT64
+Required.Proto2.ProtobufInput.PrematureEofInDelimitedDataForKnownNonRepeatedValue.MESSAGE
+Required.Proto2.ProtobufInput.PrematureEofInDelimitedDataForKnownRepeatedValue.MESSAGE
+Required.Proto2.ProtobufInput.PrematureEofInPackedField.BOOL
+Required.Proto2.ProtobufInput.PrematureEofInPackedField.ENUM
+Required.Proto2.ProtobufInput.PrematureEofInPackedField.INT32
+Required.Proto2.ProtobufInput.PrematureEofInPackedField.INT64
+Required.Proto2.ProtobufInput.PrematureEofInPackedField.SINT32
+Required.Proto2.ProtobufInput.PrematureEofInPackedField.SINT64
+Required.Proto2.ProtobufInput.PrematureEofInPackedField.UINT32
+Required.Proto2.ProtobufInput.PrematureEofInPackedField.UINT64
+
diff --git a/conformance/failure_list_csharp.txt b/conformance/failure_list_csharp.txt
index e69de29b..cd84e693 100644
--- a/conformance/failure_list_csharp.txt
+++ b/conformance/failure_list_csharp.txt
@@ -0,0 +1,3 @@
+Recommended.Proto3.JsonInput.BytesFieldBase64Url.JsonOutput
+Recommended.Proto3.JsonInput.BytesFieldBase64Url.ProtobufOutput
+Required.Proto3.ProtobufInput.UnknownVarint.ProtobufOutput
diff --git a/conformance/failure_list_java.txt b/conformance/failure_list_java.txt
index 632940ef..5116c569 100644
--- a/conformance/failure_list_java.txt
+++ b/conformance/failure_list_java.txt
@@ -7,39 +7,41 @@
Recommended.FieldMaskNumbersDontRoundTrip.JsonOutput
Recommended.FieldMaskPathsDontRoundTrip.JsonOutput
Recommended.FieldMaskTooManyUnderscore.JsonOutput
-Recommended.JsonInput.BoolFieldAllCapitalFalse
-Recommended.JsonInput.BoolFieldAllCapitalTrue
-Recommended.JsonInput.BoolFieldCamelCaseFalse
-Recommended.JsonInput.BoolFieldCamelCaseTrue
-Recommended.JsonInput.BoolFieldDoubleQuotedFalse
-Recommended.JsonInput.BoolFieldDoubleQuotedTrue
-Recommended.JsonInput.BoolMapFieldKeyNotQuoted
-Recommended.JsonInput.DoubleFieldInfinityNotQuoted
-Recommended.JsonInput.DoubleFieldNanNotQuoted
-Recommended.JsonInput.DoubleFieldNegativeInfinityNotQuoted
-Recommended.JsonInput.FieldMaskInvalidCharacter
-Recommended.JsonInput.FieldNameDuplicate
-Recommended.JsonInput.FieldNameNotQuoted
-Recommended.JsonInput.FloatFieldInfinityNotQuoted
-Recommended.JsonInput.FloatFieldNanNotQuoted
-Recommended.JsonInput.FloatFieldNegativeInfinityNotQuoted
-Recommended.JsonInput.Int32MapFieldKeyNotQuoted
-Recommended.JsonInput.Int64MapFieldKeyNotQuoted
-Recommended.JsonInput.JsonWithComments
-Recommended.JsonInput.StringFieldSingleQuoteBoth
-Recommended.JsonInput.StringFieldSingleQuoteKey
-Recommended.JsonInput.StringFieldSingleQuoteValue
-Recommended.JsonInput.StringFieldSurrogateInWrongOrder
-Recommended.JsonInput.StringFieldUnpairedHighSurrogate
-Recommended.JsonInput.StringFieldUnpairedLowSurrogate
-Recommended.JsonInput.Uint32MapFieldKeyNotQuoted
-Recommended.JsonInput.Uint64MapFieldKeyNotQuoted
-Required.JsonInput.EnumFieldNotQuoted
-Required.JsonInput.Int32FieldLeadingZero
-Required.JsonInput.Int32FieldNegativeWithLeadingZero
-Required.JsonInput.Int32FieldPlusSign
-Required.JsonInput.RepeatedFieldWrongElementTypeExpectingStringsGotBool
-Required.JsonInput.RepeatedFieldWrongElementTypeExpectingStringsGotInt
-Required.JsonInput.StringFieldNotAString
-Required.ProtobufInput.PrematureEofInDelimitedDataForKnownNonRepeatedValue.MESSAGE
-Required.ProtobufInput.PrematureEofInDelimitedDataForKnownRepeatedValue.MESSAGE
+Recommended.Proto3.JsonInput.BoolFieldAllCapitalFalse
+Recommended.Proto3.JsonInput.BoolFieldAllCapitalTrue
+Recommended.Proto3.JsonInput.BoolFieldCamelCaseFalse
+Recommended.Proto3.JsonInput.BoolFieldCamelCaseTrue
+Recommended.Proto3.JsonInput.BoolFieldDoubleQuotedFalse
+Recommended.Proto3.JsonInput.BoolFieldDoubleQuotedTrue
+Recommended.Proto3.JsonInput.BoolMapFieldKeyNotQuoted
+Recommended.Proto3.JsonInput.DoubleFieldInfinityNotQuoted
+Recommended.Proto3.JsonInput.DoubleFieldNanNotQuoted
+Recommended.Proto3.JsonInput.DoubleFieldNegativeInfinityNotQuoted
+Recommended.Proto3.JsonInput.FieldMaskInvalidCharacter
+Recommended.Proto3.JsonInput.FieldNameDuplicate
+Recommended.Proto3.JsonInput.FieldNameNotQuoted
+Recommended.Proto3.JsonInput.FloatFieldInfinityNotQuoted
+Recommended.Proto3.JsonInput.FloatFieldNanNotQuoted
+Recommended.Proto3.JsonInput.FloatFieldNegativeInfinityNotQuoted
+Recommended.Proto3.JsonInput.Int32MapFieldKeyNotQuoted
+Recommended.Proto3.JsonInput.Int64MapFieldKeyNotQuoted
+Recommended.Proto3.JsonInput.JsonWithComments
+Recommended.Proto3.JsonInput.StringFieldSingleQuoteBoth
+Recommended.Proto3.JsonInput.StringFieldSingleQuoteKey
+Recommended.Proto3.JsonInput.StringFieldSingleQuoteValue
+Recommended.Proto3.JsonInput.StringFieldSurrogateInWrongOrder
+Recommended.Proto3.JsonInput.StringFieldUnpairedHighSurrogate
+Recommended.Proto3.JsonInput.StringFieldUnpairedLowSurrogate
+Recommended.Proto3.JsonInput.Uint32MapFieldKeyNotQuoted
+Recommended.Proto3.JsonInput.Uint64MapFieldKeyNotQuoted
+Required.Proto3.JsonInput.EnumFieldNotQuoted
+Required.Proto3.JsonInput.Int32FieldLeadingZero
+Required.Proto3.JsonInput.Int32FieldNegativeWithLeadingZero
+Required.Proto3.JsonInput.Int32FieldPlusSign
+Required.Proto3.JsonInput.RepeatedFieldWrongElementTypeExpectingStringsGotBool
+Required.Proto3.JsonInput.RepeatedFieldWrongElementTypeExpectingStringsGotInt
+Required.Proto3.JsonInput.StringFieldNotAString
+Required.Proto3.ProtobufInput.PrematureEofInDelimitedDataForKnownNonRepeatedValue.MESSAGE
+Required.Proto3.ProtobufInput.PrematureEofInDelimitedDataForKnownRepeatedValue.MESSAGE
+Required.Proto2.ProtobufInput.PrematureEofInDelimitedDataForKnownNonRepeatedValue.MESSAGE
+Required.Proto2.ProtobufInput.PrematureEofInDelimitedDataForKnownRepeatedValue.MESSAGE \ No newline at end of file
diff --git a/conformance/failure_list_js.txt b/conformance/failure_list_js.txt
new file mode 100644
index 00000000..f8f6a578
--- /dev/null
+++ b/conformance/failure_list_js.txt
@@ -0,0 +1,13 @@
+Required.Proto3.ProtobufInput.ValidDataRepeated.BOOL.ProtobufOutput
+Required.Proto3.ProtobufInput.ValidDataRepeated.DOUBLE.ProtobufOutput
+Required.Proto3.ProtobufInput.ValidDataRepeated.FIXED32.ProtobufOutput
+Required.Proto3.ProtobufInput.ValidDataRepeated.FIXED64.ProtobufOutput
+Required.Proto3.ProtobufInput.ValidDataRepeated.FLOAT.ProtobufOutput
+Required.Proto3.ProtobufInput.ValidDataRepeated.INT32.ProtobufOutput
+Required.Proto3.ProtobufInput.ValidDataRepeated.INT64.ProtobufOutput
+Required.Proto3.ProtobufInput.ValidDataRepeated.SFIXED32.ProtobufOutput
+Required.Proto3.ProtobufInput.ValidDataRepeated.SFIXED64.ProtobufOutput
+Required.Proto3.ProtobufInput.ValidDataRepeated.SINT32.ProtobufOutput
+Required.Proto3.ProtobufInput.ValidDataRepeated.SINT64.ProtobufOutput
+Required.Proto3.ProtobufInput.ValidDataRepeated.UINT32.ProtobufOutput
+Required.Proto3.ProtobufInput.ValidDataRepeated.UINT64.ProtobufOutput
diff --git a/conformance/failure_list_objc.txt b/conformance/failure_list_objc.txt
index dd538c10..e34501ea 100644
--- a/conformance/failure_list_objc.txt
+++ b/conformance/failure_list_objc.txt
@@ -1,4 +1,2 @@
-# All tests currently passing.
-#
# JSON input or output tests are skipped (in conformance_objc.m) as mobile
# platforms don't support JSON wire format to avoid code bloat.
diff --git a/conformance/failure_list_php.txt b/conformance/failure_list_php.txt
new file mode 100644
index 00000000..0d234112
--- /dev/null
+++ b/conformance/failure_list_php.txt
@@ -0,0 +1,20 @@
+Recommended.FieldMaskNumbersDontRoundTrip.JsonOutput
+Recommended.FieldMaskPathsDontRoundTrip.JsonOutput
+Recommended.FieldMaskTooManyUnderscore.JsonOutput
+Recommended.Proto3.JsonInput.BytesFieldBase64Url.JsonOutput
+Recommended.Proto3.JsonInput.BytesFieldBase64Url.ProtobufOutput
+Recommended.Proto3.JsonInput.DurationHas3FractionalDigits.Validator
+Recommended.Proto3.JsonInput.DurationHas6FractionalDigits.Validator
+Recommended.Proto3.JsonInput.DurationHas9FractionalDigits.Validator
+Recommended.Proto3.JsonInput.DurationHasZeroFractionalDigit.Validator
+Recommended.Proto3.JsonInput.FieldMaskInvalidCharacter
+Required.Proto3.JsonInput.FloatFieldTooLarge
+Required.Proto3.JsonInput.FloatFieldTooSmall
+Required.Proto3.JsonInput.DoubleFieldTooSmall
+Required.Proto3.JsonInput.Int32FieldNotInteger
+Required.Proto3.JsonInput.Int64FieldNotInteger
+Required.Proto3.JsonInput.Uint32FieldNotInteger
+Required.Proto3.JsonInput.Uint64FieldNotInteger
+Required.Proto3.JsonInput.Int32FieldLeadingSpace
+Required.Proto3.JsonInput.OneofFieldDuplicate
+Required.Proto3.ProtobufInput.ValidDataRepeated.FLOAT.JsonOutput
diff --git a/conformance/failure_list_php_c.txt b/conformance/failure_list_php_c.txt
new file mode 100644
index 00000000..088708e9
--- /dev/null
+++ b/conformance/failure_list_php_c.txt
@@ -0,0 +1,182 @@
+Recommended.FieldMaskNumbersDontRoundTrip.JsonOutput
+Recommended.FieldMaskPathsDontRoundTrip.JsonOutput
+Recommended.FieldMaskTooManyUnderscore.JsonOutput
+Recommended.Proto3.JsonInput.BoolFieldIntegerOne
+Recommended.Proto3.JsonInput.BoolFieldIntegerZero
+Recommended.Proto3.JsonInput.DurationHas3FractionalDigits.Validator
+Recommended.Proto3.JsonInput.DurationHas6FractionalDigits.Validator
+Recommended.Proto3.JsonInput.DurationHas9FractionalDigits.Validator
+Recommended.Proto3.JsonInput.DurationHasZeroFractionalDigit.Validator
+Recommended.Proto3.JsonInput.Int64FieldBeString.Validator
+Recommended.Proto3.JsonInput.MapFieldValueIsNull
+Recommended.Proto3.JsonInput.OneofZeroBytes.JsonOutput
+Recommended.Proto3.JsonInput.OneofZeroBytes.ProtobufOutput
+Recommended.Proto3.JsonInput.OneofZeroString.JsonOutput
+Recommended.Proto3.JsonInput.OneofZeroString.ProtobufOutput
+Recommended.Proto3.JsonInput.RepeatedFieldMessageElementIsNull
+Recommended.Proto3.JsonInput.RepeatedFieldPrimitiveElementIsNull
+Recommended.Proto3.JsonInput.StringEndsWithEscapeChar
+Recommended.Proto3.JsonInput.StringFieldSurrogateInWrongOrder
+Recommended.Proto3.JsonInput.StringFieldUnpairedHighSurrogate
+Recommended.Proto3.JsonInput.StringFieldUnpairedLowSurrogate
+Recommended.Proto3.JsonInput.Uint64FieldBeString.Validator
+Recommended.Proto3.ProtobufInput.OneofZeroBytes.JsonOutput
+Recommended.Proto3.ProtobufInput.OneofZeroBytes.ProtobufOutput
+Recommended.Proto3.ProtobufInput.OneofZeroString.JsonOutput
+Recommended.Proto3.ProtobufInput.OneofZeroString.ProtobufOutput
+Required.DurationProtoInputTooLarge.JsonOutput
+Required.DurationProtoInputTooSmall.JsonOutput
+Required.Proto3.JsonInput.Any.JsonOutput
+Required.Proto3.JsonInput.Any.ProtobufOutput
+Required.Proto3.JsonInput.AnyNested.JsonOutput
+Required.Proto3.JsonInput.AnyNested.ProtobufOutput
+Required.Proto3.JsonInput.AnyUnorderedTypeTag.JsonOutput
+Required.Proto3.JsonInput.AnyUnorderedTypeTag.ProtobufOutput
+Required.Proto3.JsonInput.AnyWithDuration.JsonOutput
+Required.Proto3.JsonInput.AnyWithDuration.ProtobufOutput
+Required.Proto3.JsonInput.AnyWithFieldMask.JsonOutput
+Required.Proto3.JsonInput.AnyWithFieldMask.ProtobufOutput
+Required.Proto3.JsonInput.AnyWithInt32ValueWrapper.JsonOutput
+Required.Proto3.JsonInput.AnyWithInt32ValueWrapper.ProtobufOutput
+Required.Proto3.JsonInput.AnyWithStruct.JsonOutput
+Required.Proto3.JsonInput.AnyWithStruct.ProtobufOutput
+Required.Proto3.JsonInput.AnyWithTimestamp.JsonOutput
+Required.Proto3.JsonInput.AnyWithTimestamp.ProtobufOutput
+Required.Proto3.JsonInput.AnyWithValueForInteger.JsonOutput
+Required.Proto3.JsonInput.AnyWithValueForInteger.ProtobufOutput
+Required.Proto3.JsonInput.AnyWithValueForJsonObject.JsonOutput
+Required.Proto3.JsonInput.AnyWithValueForJsonObject.ProtobufOutput
+Required.Proto3.JsonInput.BoolMapField.JsonOutput
+Required.Proto3.JsonInput.DoubleFieldInfinity.JsonOutput
+Required.Proto3.JsonInput.DoubleFieldInfinity.ProtobufOutput
+Required.Proto3.JsonInput.DoubleFieldMaxNegativeValue.JsonOutput
+Required.Proto3.JsonInput.DoubleFieldMaxNegativeValue.ProtobufOutput
+Required.Proto3.JsonInput.DoubleFieldMaxPositiveValue.JsonOutput
+Required.Proto3.JsonInput.DoubleFieldMaxPositiveValue.ProtobufOutput
+Required.Proto3.JsonInput.DoubleFieldMinNegativeValue.JsonOutput
+Required.Proto3.JsonInput.DoubleFieldMinNegativeValue.ProtobufOutput
+Required.Proto3.JsonInput.DoubleFieldMinPositiveValue.JsonOutput
+Required.Proto3.JsonInput.DoubleFieldMinPositiveValue.ProtobufOutput
+Required.Proto3.JsonInput.DoubleFieldNan.JsonOutput
+Required.Proto3.JsonInput.DoubleFieldNan.ProtobufOutput
+Required.Proto3.JsonInput.DoubleFieldNegativeInfinity.JsonOutput
+Required.Proto3.JsonInput.DoubleFieldNegativeInfinity.ProtobufOutput
+Required.Proto3.JsonInput.DoubleFieldQuotedValue.JsonOutput
+Required.Proto3.JsonInput.DoubleFieldQuotedValue.ProtobufOutput
+Required.Proto3.JsonInput.DurationMaxValue.JsonOutput
+Required.Proto3.JsonInput.DurationMaxValue.ProtobufOutput
+Required.Proto3.JsonInput.DurationMinValue.JsonOutput
+Required.Proto3.JsonInput.DurationMinValue.ProtobufOutput
+Required.Proto3.JsonInput.DurationRepeatedValue.JsonOutput
+Required.Proto3.JsonInput.DurationRepeatedValue.ProtobufOutput
+Required.Proto3.JsonInput.EnumFieldNumericValueNonZero.JsonOutput
+Required.Proto3.JsonInput.EnumFieldNumericValueNonZero.ProtobufOutput
+Required.Proto3.JsonInput.EnumFieldNumericValueZero.JsonOutput
+Required.Proto3.JsonInput.EnumFieldNumericValueZero.ProtobufOutput
+Required.Proto3.JsonInput.EnumFieldUnknownValue.Validator
+Required.Proto3.JsonInput.FieldMask.JsonOutput
+Required.Proto3.JsonInput.FieldMask.ProtobufOutput
+Required.Proto3.JsonInput.FloatFieldInfinity.JsonOutput
+Required.Proto3.JsonInput.FloatFieldInfinity.ProtobufOutput
+Required.Proto3.JsonInput.FloatFieldNan.JsonOutput
+Required.Proto3.JsonInput.FloatFieldNan.ProtobufOutput
+Required.Proto3.JsonInput.FloatFieldNegativeInfinity.JsonOutput
+Required.Proto3.JsonInput.FloatFieldNegativeInfinity.ProtobufOutput
+Required.Proto3.JsonInput.FloatFieldQuotedValue.JsonOutput
+Required.Proto3.JsonInput.FloatFieldQuotedValue.ProtobufOutput
+Required.Proto3.JsonInput.FloatFieldTooLarge
+Required.Proto3.JsonInput.FloatFieldTooSmall
+Required.Proto3.JsonInput.Int32FieldExponentialFormat.JsonOutput
+Required.Proto3.JsonInput.Int32FieldExponentialFormat.ProtobufOutput
+Required.Proto3.JsonInput.Int32FieldFloatTrailingZero.JsonOutput
+Required.Proto3.JsonInput.Int32FieldFloatTrailingZero.ProtobufOutput
+Required.Proto3.JsonInput.Int32FieldMaxFloatValue.JsonOutput
+Required.Proto3.JsonInput.Int32FieldMaxFloatValue.ProtobufOutput
+Required.Proto3.JsonInput.Int32FieldMinFloatValue.JsonOutput
+Required.Proto3.JsonInput.Int32FieldMinFloatValue.ProtobufOutput
+Required.Proto3.JsonInput.Int32FieldStringValue.JsonOutput
+Required.Proto3.JsonInput.Int32FieldStringValue.ProtobufOutput
+Required.Proto3.JsonInput.Int32FieldStringValueEscaped.JsonOutput
+Required.Proto3.JsonInput.Int32FieldStringValueEscaped.ProtobufOutput
+Required.Proto3.JsonInput.Int64FieldMaxValue.JsonOutput
+Required.Proto3.JsonInput.Int64FieldMaxValue.ProtobufOutput
+Required.Proto3.JsonInput.Int64FieldMinValue.JsonOutput
+Required.Proto3.JsonInput.Int64FieldMinValue.ProtobufOutput
+Required.Proto3.JsonInput.MessageField.JsonOutput
+Required.Proto3.JsonInput.MessageField.ProtobufOutput
+Required.Proto3.JsonInput.OptionalBoolWrapper.JsonOutput
+Required.Proto3.JsonInput.OptionalBoolWrapper.ProtobufOutput
+Required.Proto3.JsonInput.OptionalBytesWrapper.JsonOutput
+Required.Proto3.JsonInput.OptionalBytesWrapper.ProtobufOutput
+Required.Proto3.JsonInput.OptionalDoubleWrapper.JsonOutput
+Required.Proto3.JsonInput.OptionalDoubleWrapper.ProtobufOutput
+Required.Proto3.JsonInput.OptionalFloatWrapper.JsonOutput
+Required.Proto3.JsonInput.OptionalFloatWrapper.ProtobufOutput
+Required.Proto3.JsonInput.OptionalInt32Wrapper.JsonOutput
+Required.Proto3.JsonInput.OptionalInt32Wrapper.ProtobufOutput
+Required.Proto3.JsonInput.OptionalInt64Wrapper.JsonOutput
+Required.Proto3.JsonInput.OptionalInt64Wrapper.ProtobufOutput
+Required.Proto3.JsonInput.OptionalStringWrapper.JsonOutput
+Required.Proto3.JsonInput.OptionalStringWrapper.ProtobufOutput
+Required.Proto3.JsonInput.OptionalUint32Wrapper.JsonOutput
+Required.Proto3.JsonInput.OptionalUint32Wrapper.ProtobufOutput
+Required.Proto3.JsonInput.OptionalUint64Wrapper.JsonOutput
+Required.Proto3.JsonInput.OptionalUint64Wrapper.ProtobufOutput
+Required.Proto3.JsonInput.OptionalWrapperTypesWithNonDefaultValue.JsonOutput
+Required.Proto3.JsonInput.OptionalWrapperTypesWithNonDefaultValue.ProtobufOutput
+Required.Proto3.JsonInput.RepeatedBoolWrapper.JsonOutput
+Required.Proto3.JsonInput.RepeatedBoolWrapper.ProtobufOutput
+Required.Proto3.JsonInput.RepeatedBytesWrapper.JsonOutput
+Required.Proto3.JsonInput.RepeatedBytesWrapper.ProtobufOutput
+Required.Proto3.JsonInput.RepeatedDoubleWrapper.JsonOutput
+Required.Proto3.JsonInput.RepeatedDoubleWrapper.ProtobufOutput
+Required.Proto3.JsonInput.RepeatedFieldWrongElementTypeExpectingMessagesGotInt
+Required.Proto3.JsonInput.RepeatedFieldWrongElementTypeExpectingStringsGotInt
+Required.Proto3.JsonInput.RepeatedFloatWrapper.JsonOutput
+Required.Proto3.JsonInput.RepeatedFloatWrapper.ProtobufOutput
+Required.Proto3.JsonInput.RepeatedInt32Wrapper.JsonOutput
+Required.Proto3.JsonInput.RepeatedInt32Wrapper.ProtobufOutput
+Required.Proto3.JsonInput.RepeatedInt64Wrapper.JsonOutput
+Required.Proto3.JsonInput.RepeatedInt64Wrapper.ProtobufOutput
+Required.Proto3.JsonInput.RepeatedStringWrapper.JsonOutput
+Required.Proto3.JsonInput.RepeatedStringWrapper.ProtobufOutput
+Required.Proto3.JsonInput.RepeatedUint32Wrapper.JsonOutput
+Required.Proto3.JsonInput.RepeatedUint32Wrapper.ProtobufOutput
+Required.Proto3.JsonInput.RepeatedUint64Wrapper.JsonOutput
+Required.Proto3.JsonInput.RepeatedUint64Wrapper.ProtobufOutput
+Required.Proto3.JsonInput.StringFieldEscape.JsonOutput
+Required.Proto3.JsonInput.StringFieldEscape.ProtobufOutput
+Required.Proto3.JsonInput.StringFieldNotAString
+Required.Proto3.JsonInput.StringFieldSurrogatePair.JsonOutput
+Required.Proto3.JsonInput.StringFieldSurrogatePair.ProtobufOutput
+Required.Proto3.JsonInput.StringFieldUnicodeEscape.JsonOutput
+Required.Proto3.JsonInput.StringFieldUnicodeEscape.ProtobufOutput
+Required.Proto3.JsonInput.StringFieldUnicodeEscapeWithLowercaseHexLetters.JsonOutput
+Required.Proto3.JsonInput.StringFieldUnicodeEscapeWithLowercaseHexLetters.ProtobufOutput
+Required.Proto3.JsonInput.Struct.JsonOutput
+Required.Proto3.JsonInput.Struct.ProtobufOutput
+Required.Proto3.JsonInput.Uint32FieldMaxFloatValue.JsonOutput
+Required.Proto3.JsonInput.Uint32FieldMaxFloatValue.ProtobufOutput
+Required.Proto3.JsonInput.Uint64FieldMaxValue.JsonOutput
+Required.Proto3.JsonInput.Uint64FieldMaxValue.ProtobufOutput
+Required.Proto3.JsonInput.ValueAcceptBool.JsonOutput
+Required.Proto3.JsonInput.ValueAcceptBool.ProtobufOutput
+Required.Proto3.JsonInput.ValueAcceptFloat.JsonOutput
+Required.Proto3.JsonInput.ValueAcceptFloat.ProtobufOutput
+Required.Proto3.JsonInput.ValueAcceptInteger.JsonOutput
+Required.Proto3.JsonInput.ValueAcceptInteger.ProtobufOutput
+Required.Proto3.JsonInput.ValueAcceptList.JsonOutput
+Required.Proto3.JsonInput.ValueAcceptList.ProtobufOutput
+Required.Proto3.JsonInput.ValueAcceptNull.JsonOutput
+Required.Proto3.JsonInput.ValueAcceptNull.ProtobufOutput
+Required.Proto3.JsonInput.ValueAcceptObject.JsonOutput
+Required.Proto3.JsonInput.ValueAcceptObject.ProtobufOutput
+Required.Proto3.JsonInput.ValueAcceptString.JsonOutput
+Required.Proto3.JsonInput.ValueAcceptString.ProtobufOutput
+Required.Proto3.ProtobufInput.DoubleFieldNormalizeQuietNan.JsonOutput
+Required.Proto3.ProtobufInput.DoubleFieldNormalizeSignalingNan.JsonOutput
+Required.Proto3.ProtobufInput.FloatFieldNormalizeQuietNan.JsonOutput
+Required.Proto3.ProtobufInput.FloatFieldNormalizeSignalingNan.JsonOutput
+Required.Proto3.ProtobufInput.ValidDataRepeated.FLOAT.JsonOutput
+Required.TimestampProtoInputTooLarge.JsonOutput
+Required.TimestampProtoInputTooSmall.JsonOutput
diff --git a/conformance/failure_list_php_zts_c.txt b/conformance/failure_list_php_zts_c.txt
new file mode 100644
index 00000000..d9a8fe36
--- /dev/null
+++ b/conformance/failure_list_php_zts_c.txt
@@ -0,0 +1,225 @@
+Recommended.FieldMaskNumbersDontRoundTrip.JsonOutput
+Recommended.FieldMaskPathsDontRoundTrip.JsonOutput
+Recommended.FieldMaskTooManyUnderscore.JsonOutput
+Recommended.JsonInput.BoolFieldIntegerOne
+Recommended.JsonInput.BoolFieldIntegerZero
+Recommended.JsonInput.DurationHas3FractionalDigits.Validator
+Recommended.JsonInput.DurationHas6FractionalDigits.Validator
+Recommended.JsonInput.DurationHas9FractionalDigits.Validator
+Recommended.JsonInput.DurationHasZeroFractionalDigit.Validator
+Recommended.JsonInput.Int64FieldBeString.Validator
+Recommended.JsonInput.OneofZeroBytes.JsonOutput
+Recommended.JsonInput.OneofZeroBytes.ProtobufOutput
+Recommended.JsonInput.OneofZeroDouble.JsonOutput
+Recommended.JsonInput.OneofZeroDouble.ProtobufOutput
+Recommended.JsonInput.OneofZeroFloat.JsonOutput
+Recommended.JsonInput.OneofZeroFloat.ProtobufOutput
+Recommended.JsonInput.OneofZeroString.JsonOutput
+Recommended.JsonInput.OneofZeroString.ProtobufOutput
+Recommended.JsonInput.OneofZeroUint32.JsonOutput
+Recommended.JsonInput.OneofZeroUint32.ProtobufOutput
+Recommended.JsonInput.OneofZeroUint64.JsonOutput
+Recommended.JsonInput.OneofZeroUint64.ProtobufOutput
+Recommended.JsonInput.StringEndsWithEscapeChar
+Recommended.JsonInput.StringFieldSurrogateInWrongOrder
+Recommended.JsonInput.StringFieldUnpairedHighSurrogate
+Recommended.JsonInput.StringFieldUnpairedLowSurrogate
+Recommended.JsonInput.TimestampHas3FractionalDigits.Validator
+Recommended.JsonInput.TimestampHas6FractionalDigits.Validator
+Recommended.JsonInput.TimestampHas9FractionalDigits.Validator
+Recommended.JsonInput.TimestampHasZeroFractionalDigit.Validator
+Recommended.JsonInput.TimestampZeroNormalized.Validator
+Recommended.JsonInput.Uint64FieldBeString.Validator
+Recommended.ProtobufInput.OneofZeroBytes.JsonOutput
+Recommended.ProtobufInput.OneofZeroBytes.ProtobufOutput
+Recommended.ProtobufInput.OneofZeroString.JsonOutput
+Recommended.ProtobufInput.OneofZeroString.ProtobufOutput
+Required.DurationProtoInputTooLarge.JsonOutput
+Required.DurationProtoInputTooSmall.JsonOutput
+Required.JsonInput.AllFieldAcceptNull.ProtobufOutput
+Required.JsonInput.Any.JsonOutput
+Required.JsonInput.Any.ProtobufOutput
+Required.JsonInput.AnyNested.JsonOutput
+Required.JsonInput.AnyNested.ProtobufOutput
+Required.JsonInput.AnyUnorderedTypeTag.JsonOutput
+Required.JsonInput.AnyUnorderedTypeTag.ProtobufOutput
+Required.JsonInput.AnyWithDuration.JsonOutput
+Required.JsonInput.AnyWithDuration.ProtobufOutput
+Required.JsonInput.AnyWithFieldMask.JsonOutput
+Required.JsonInput.AnyWithFieldMask.ProtobufOutput
+Required.JsonInput.AnyWithInt32ValueWrapper.JsonOutput
+Required.JsonInput.AnyWithInt32ValueWrapper.ProtobufOutput
+Required.JsonInput.AnyWithStruct.JsonOutput
+Required.JsonInput.AnyWithStruct.ProtobufOutput
+Required.JsonInput.AnyWithTimestamp.JsonOutput
+Required.JsonInput.AnyWithTimestamp.ProtobufOutput
+Required.JsonInput.AnyWithValueForInteger.JsonOutput
+Required.JsonInput.AnyWithValueForInteger.ProtobufOutput
+Required.JsonInput.AnyWithValueForJsonObject.JsonOutput
+Required.JsonInput.AnyWithValueForJsonObject.ProtobufOutput
+Required.JsonInput.BoolFieldFalse.ProtobufOutput
+Required.JsonInput.BoolMapField.JsonOutput
+Required.JsonInput.DoubleFieldInfinity.JsonOutput
+Required.JsonInput.DoubleFieldInfinity.ProtobufOutput
+Required.JsonInput.DoubleFieldMaxNegativeValue.JsonOutput
+Required.JsonInput.DoubleFieldMaxNegativeValue.ProtobufOutput
+Required.JsonInput.DoubleFieldMaxPositiveValue.JsonOutput
+Required.JsonInput.DoubleFieldMaxPositiveValue.ProtobufOutput
+Required.JsonInput.DoubleFieldMinNegativeValue.JsonOutput
+Required.JsonInput.DoubleFieldMinNegativeValue.ProtobufOutput
+Required.JsonInput.DoubleFieldMinPositiveValue.JsonOutput
+Required.JsonInput.DoubleFieldMinPositiveValue.ProtobufOutput
+Required.JsonInput.DoubleFieldNan.JsonOutput
+Required.JsonInput.DoubleFieldNan.ProtobufOutput
+Required.JsonInput.DoubleFieldNegativeInfinity.JsonOutput
+Required.JsonInput.DoubleFieldNegativeInfinity.ProtobufOutput
+Required.JsonInput.DoubleFieldQuotedValue.JsonOutput
+Required.JsonInput.DoubleFieldQuotedValue.ProtobufOutput
+Required.JsonInput.DurationMaxValue.JsonOutput
+Required.JsonInput.DurationMaxValue.ProtobufOutput
+Required.JsonInput.DurationMinValue.JsonOutput
+Required.JsonInput.DurationMinValue.ProtobufOutput
+Required.JsonInput.DurationRepeatedValue.JsonOutput
+Required.JsonInput.DurationRepeatedValue.ProtobufOutput
+Required.JsonInput.EnumField.ProtobufOutput
+Required.JsonInput.EnumFieldNumericValueNonZero.JsonOutput
+Required.JsonInput.EnumFieldNumericValueNonZero.ProtobufOutput
+Required.JsonInput.EnumFieldNumericValueZero.JsonOutput
+Required.JsonInput.EnumFieldNumericValueZero.ProtobufOutput
+Required.JsonInput.EnumFieldUnknownValue.Validator
+Required.JsonInput.FieldMask.JsonOutput
+Required.JsonInput.FieldMask.ProtobufOutput
+Required.JsonInput.FloatFieldInfinity.JsonOutput
+Required.JsonInput.FloatFieldInfinity.ProtobufOutput
+Required.JsonInput.FloatFieldNan.JsonOutput
+Required.JsonInput.FloatFieldNan.ProtobufOutput
+Required.JsonInput.FloatFieldNegativeInfinity.JsonOutput
+Required.JsonInput.FloatFieldNegativeInfinity.ProtobufOutput
+Required.JsonInput.FloatFieldQuotedValue.JsonOutput
+Required.JsonInput.FloatFieldQuotedValue.ProtobufOutput
+Required.JsonInput.FloatFieldTooLarge
+Required.JsonInput.FloatFieldTooSmall
+Required.JsonInput.Int32FieldExponentialFormat.JsonOutput
+Required.JsonInput.Int32FieldExponentialFormat.ProtobufOutput
+Required.JsonInput.Int32FieldFloatTrailingZero.JsonOutput
+Required.JsonInput.Int32FieldFloatTrailingZero.ProtobufOutput
+Required.JsonInput.Int32FieldMaxFloatValue.JsonOutput
+Required.JsonInput.Int32FieldMaxFloatValue.ProtobufOutput
+Required.JsonInput.Int32FieldMinFloatValue.JsonOutput
+Required.JsonInput.Int32FieldMinFloatValue.ProtobufOutput
+Required.JsonInput.Int32FieldStringValue.JsonOutput
+Required.JsonInput.Int32FieldStringValue.ProtobufOutput
+Required.JsonInput.Int32FieldStringValueEscaped.JsonOutput
+Required.JsonInput.Int32FieldStringValueEscaped.ProtobufOutput
+Required.JsonInput.Int32MapEscapedKey.JsonOutput
+Required.JsonInput.Int32MapEscapedKey.ProtobufOutput
+Required.JsonInput.Int32MapField.JsonOutput
+Required.JsonInput.Int32MapField.ProtobufOutput
+Required.JsonInput.Int64FieldMaxValue.JsonOutput
+Required.JsonInput.Int64FieldMaxValue.ProtobufOutput
+Required.JsonInput.Int64FieldMinValue.JsonOutput
+Required.JsonInput.Int64FieldMinValue.ProtobufOutput
+Required.JsonInput.Int64MapEscapedKey.JsonOutput
+Required.JsonInput.Int64MapEscapedKey.ProtobufOutput
+Required.JsonInput.Int64MapField.JsonOutput
+Required.JsonInput.Int64MapField.ProtobufOutput
+Required.JsonInput.MessageField.JsonOutput
+Required.JsonInput.MessageField.ProtobufOutput
+Required.JsonInput.MessageMapField.JsonOutput
+Required.JsonInput.MessageMapField.ProtobufOutput
+Required.JsonInput.MessageRepeatedField.JsonOutput
+Required.JsonInput.MessageRepeatedField.ProtobufOutput
+Required.JsonInput.OptionalBoolWrapper.JsonOutput
+Required.JsonInput.OptionalBoolWrapper.ProtobufOutput
+Required.JsonInput.OptionalBytesWrapper.JsonOutput
+Required.JsonInput.OptionalBytesWrapper.ProtobufOutput
+Required.JsonInput.OptionalDoubleWrapper.JsonOutput
+Required.JsonInput.OptionalDoubleWrapper.ProtobufOutput
+Required.JsonInput.OptionalFloatWrapper.JsonOutput
+Required.JsonInput.OptionalFloatWrapper.ProtobufOutput
+Required.JsonInput.OptionalInt32Wrapper.JsonOutput
+Required.JsonInput.OptionalInt32Wrapper.ProtobufOutput
+Required.JsonInput.OptionalInt64Wrapper.JsonOutput
+Required.JsonInput.OptionalInt64Wrapper.ProtobufOutput
+Required.JsonInput.OptionalStringWrapper.JsonOutput
+Required.JsonInput.OptionalStringWrapper.ProtobufOutput
+Required.JsonInput.OptionalUint32Wrapper.JsonOutput
+Required.JsonInput.OptionalUint32Wrapper.ProtobufOutput
+Required.JsonInput.OptionalUint64Wrapper.JsonOutput
+Required.JsonInput.OptionalUint64Wrapper.ProtobufOutput
+Required.JsonInput.OptionalWrapperTypesWithNonDefaultValue.JsonOutput
+Required.JsonInput.OptionalWrapperTypesWithNonDefaultValue.ProtobufOutput
+Required.JsonInput.PrimitiveRepeatedField.JsonOutput
+Required.JsonInput.PrimitiveRepeatedField.ProtobufOutput
+Required.JsonInput.RepeatedBoolWrapper.JsonOutput
+Required.JsonInput.RepeatedBoolWrapper.ProtobufOutput
+Required.JsonInput.RepeatedBytesWrapper.JsonOutput
+Required.JsonInput.RepeatedBytesWrapper.ProtobufOutput
+Required.JsonInput.RepeatedDoubleWrapper.JsonOutput
+Required.JsonInput.RepeatedDoubleWrapper.ProtobufOutput
+Required.JsonInput.RepeatedFieldWrongElementTypeExpectingStringsGotInt
+Required.JsonInput.RepeatedFloatWrapper.JsonOutput
+Required.JsonInput.RepeatedFloatWrapper.ProtobufOutput
+Required.JsonInput.RepeatedInt32Wrapper.JsonOutput
+Required.JsonInput.RepeatedInt32Wrapper.ProtobufOutput
+Required.JsonInput.RepeatedInt64Wrapper.JsonOutput
+Required.JsonInput.RepeatedInt64Wrapper.ProtobufOutput
+Required.JsonInput.RepeatedStringWrapper.JsonOutput
+Required.JsonInput.RepeatedStringWrapper.ProtobufOutput
+Required.JsonInput.RepeatedUint32Wrapper.JsonOutput
+Required.JsonInput.RepeatedUint32Wrapper.ProtobufOutput
+Required.JsonInput.RepeatedUint64Wrapper.JsonOutput
+Required.JsonInput.RepeatedUint64Wrapper.ProtobufOutput
+Required.JsonInput.StringFieldEscape.JsonOutput
+Required.JsonInput.StringFieldEscape.ProtobufOutput
+Required.JsonInput.StringFieldNotAString
+Required.JsonInput.StringFieldSurrogatePair.JsonOutput
+Required.JsonInput.StringFieldSurrogatePair.ProtobufOutput
+Required.JsonInput.StringFieldUnicodeEscape.JsonOutput
+Required.JsonInput.StringFieldUnicodeEscape.ProtobufOutput
+Required.JsonInput.StringFieldUnicodeEscapeWithLowercaseHexLetters.JsonOutput
+Required.JsonInput.StringFieldUnicodeEscapeWithLowercaseHexLetters.ProtobufOutput
+Required.JsonInput.Struct.JsonOutput
+Required.JsonInput.Struct.ProtobufOutput
+Required.JsonInput.TimestampMaxValue.JsonOutput
+Required.JsonInput.TimestampMaxValue.ProtobufOutput
+Required.JsonInput.TimestampMinValue.JsonOutput
+Required.JsonInput.TimestampMinValue.ProtobufOutput
+Required.JsonInput.TimestampRepeatedValue.JsonOutput
+Required.JsonInput.TimestampRepeatedValue.ProtobufOutput
+Required.JsonInput.TimestampWithNegativeOffset.JsonOutput
+Required.JsonInput.TimestampWithNegativeOffset.ProtobufOutput
+Required.JsonInput.TimestampWithPositiveOffset.JsonOutput
+Required.JsonInput.TimestampWithPositiveOffset.ProtobufOutput
+Required.JsonInput.Uint32FieldMaxFloatValue.JsonOutput
+Required.JsonInput.Uint32FieldMaxFloatValue.ProtobufOutput
+Required.JsonInput.Uint32MapField.JsonOutput
+Required.JsonInput.Uint32MapField.ProtobufOutput
+Required.JsonInput.Uint64FieldMaxValue.JsonOutput
+Required.JsonInput.Uint64FieldMaxValue.ProtobufOutput
+Required.JsonInput.Uint64MapField.JsonOutput
+Required.JsonInput.Uint64MapField.ProtobufOutput
+Required.JsonInput.ValueAcceptBool.JsonOutput
+Required.JsonInput.ValueAcceptBool.ProtobufOutput
+Required.JsonInput.ValueAcceptFloat.JsonOutput
+Required.JsonInput.ValueAcceptFloat.ProtobufOutput
+Required.JsonInput.ValueAcceptInteger.JsonOutput
+Required.JsonInput.ValueAcceptInteger.ProtobufOutput
+Required.JsonInput.ValueAcceptList.JsonOutput
+Required.JsonInput.ValueAcceptList.ProtobufOutput
+Required.JsonInput.ValueAcceptNull.JsonOutput
+Required.JsonInput.ValueAcceptNull.ProtobufOutput
+Required.JsonInput.ValueAcceptObject.JsonOutput
+Required.JsonInput.ValueAcceptObject.ProtobufOutput
+Required.JsonInput.ValueAcceptString.JsonOutput
+Required.JsonInput.ValueAcceptString.ProtobufOutput
+Required.JsonInput.WrapperTypesWithNullValue.ProtobufOutput
+Required.ProtobufInput.DoubleFieldNormalizeQuietNan.JsonOutput
+Required.ProtobufInput.DoubleFieldNormalizeSignalingNan.JsonOutput
+Required.ProtobufInput.FloatFieldNormalizeQuietNan.JsonOutput
+Required.ProtobufInput.FloatFieldNormalizeSignalingNan.JsonOutput
+Required.ProtobufInput.RepeatedScalarSelectsLast.FIXED32.ProtobufOutput
+Required.ProtobufInput.RepeatedScalarSelectsLast.FIXED64.ProtobufOutput
+Required.ProtobufInput.RepeatedScalarSelectsLast.UINT64.ProtobufOutput
+Required.TimestampProtoInputTooLarge.JsonOutput
+Required.TimestampProtoInputTooSmall.JsonOutput
diff --git a/conformance/failure_list_python.txt b/conformance/failure_list_python.txt
index 9d556a03..e3ce7af7 100644
--- a/conformance/failure_list_python.txt
+++ b/conformance/failure_list_python.txt
@@ -1,13 +1,21 @@
-Recommended.JsonInput.DoubleFieldInfinityNotQuoted
-Recommended.JsonInput.DoubleFieldNanNotQuoted
-Recommended.JsonInput.DoubleFieldNegativeInfinityNotQuoted
-Recommended.JsonInput.FloatFieldInfinityNotQuoted
-Recommended.JsonInput.FloatFieldNanNotQuoted
-Recommended.JsonInput.FloatFieldNegativeInfinityNotQuoted
-Required.JsonInput.BytesFieldInvalidBase64Characters
-Required.JsonInput.DoubleFieldTooSmall
-Required.JsonInput.EnumFieldUnknownValue.Validator
-Required.JsonInput.FloatFieldTooLarge
-Required.JsonInput.FloatFieldTooSmall
-Required.JsonInput.RepeatedFieldWrongElementTypeExpectingIntegersGotBool
-Required.JsonInput.TimestampJsonInputLowercaseT
+Recommended.Proto3.JsonInput.BytesFieldBase64Url.JsonOutput
+Recommended.Proto3.JsonInput.BytesFieldBase64Url.ProtobufOutput
+Recommended.Proto3.JsonInput.DoubleFieldInfinityNotQuoted
+Recommended.Proto3.JsonInput.DoubleFieldNanNotQuoted
+Recommended.Proto3.JsonInput.DoubleFieldNegativeInfinityNotQuoted
+Recommended.Proto3.JsonInput.FloatFieldInfinityNotQuoted
+Recommended.Proto3.JsonInput.FloatFieldNanNotQuoted
+Recommended.Proto3.JsonInput.FloatFieldNegativeInfinityNotQuoted
+Required.Proto3.JsonInput.DoubleFieldTooSmall
+Required.Proto3.JsonInput.FloatFieldTooLarge
+Required.Proto3.JsonInput.FloatFieldTooSmall
+Required.Proto3.JsonInput.RepeatedFieldWrongElementTypeExpectingIntegersGotBool
+Required.Proto3.JsonInput.TimestampJsonInputLowercaseT
+Required.Proto2.ProtobufInput.IllegalZeroFieldNum_Case_0
+Required.Proto2.ProtobufInput.IllegalZeroFieldNum_Case_1
+Required.Proto2.ProtobufInput.IllegalZeroFieldNum_Case_2
+Required.Proto2.ProtobufInput.IllegalZeroFieldNum_Case_3
+Required.Proto3.ProtobufInput.IllegalZeroFieldNum_Case_0
+Required.Proto3.ProtobufInput.IllegalZeroFieldNum_Case_1
+Required.Proto3.ProtobufInput.IllegalZeroFieldNum_Case_2
+Required.Proto3.ProtobufInput.IllegalZeroFieldNum_Case_3
diff --git a/conformance/failure_list_python_cpp.txt b/conformance/failure_list_python_cpp.txt
index 92404d2f..a498ad1a 100644
--- a/conformance/failure_list_python_cpp.txt
+++ b/conformance/failure_list_python_cpp.txt
@@ -7,32 +7,48 @@
# TODO(haberman): insert links to corresponding bugs tracking the issue.
# Should we use GitHub issues or the Google-internal bug tracker?
-Recommended.JsonInput.DoubleFieldInfinityNotQuoted
-Recommended.JsonInput.DoubleFieldNanNotQuoted
-Recommended.JsonInput.DoubleFieldNegativeInfinityNotQuoted
-Recommended.JsonInput.FloatFieldInfinityNotQuoted
-Recommended.JsonInput.FloatFieldNanNotQuoted
-Recommended.JsonInput.FloatFieldNegativeInfinityNotQuoted
-Required.JsonInput.BytesFieldInvalidBase64Characters
-Required.JsonInput.DoubleFieldTooSmall
-Required.JsonInput.EnumFieldUnknownValue.Validator
-Required.JsonInput.FloatFieldTooLarge
-Required.JsonInput.FloatFieldTooSmall
-Required.JsonInput.RepeatedFieldWrongElementTypeExpectingIntegersGotBool
-Required.JsonInput.TimestampJsonInputLowercaseT
-Required.ProtobufInput.PrematureEofInDelimitedDataForKnownNonRepeatedValue.MESSAGE
-Required.ProtobufInput.PrematureEofInDelimitedDataForKnownRepeatedValue.MESSAGE
-Required.ProtobufInput.PrematureEofInPackedField.BOOL
-Required.ProtobufInput.PrematureEofInPackedField.DOUBLE
-Required.ProtobufInput.PrematureEofInPackedField.ENUM
-Required.ProtobufInput.PrematureEofInPackedField.FIXED32
-Required.ProtobufInput.PrematureEofInPackedField.FIXED64
-Required.ProtobufInput.PrematureEofInPackedField.FLOAT
-Required.ProtobufInput.PrematureEofInPackedField.INT32
-Required.ProtobufInput.PrematureEofInPackedField.INT64
-Required.ProtobufInput.PrematureEofInPackedField.SFIXED32
-Required.ProtobufInput.PrematureEofInPackedField.SFIXED64
-Required.ProtobufInput.PrematureEofInPackedField.SINT32
-Required.ProtobufInput.PrematureEofInPackedField.SINT64
-Required.ProtobufInput.PrematureEofInPackedField.UINT32
-Required.ProtobufInput.PrematureEofInPackedField.UINT64
+Recommended.Proto3.JsonInput.BytesFieldBase64Url.JsonOutput
+Recommended.Proto3.JsonInput.BytesFieldBase64Url.ProtobufOutput
+Recommended.Proto3.JsonInput.DoubleFieldInfinityNotQuoted
+Recommended.Proto3.JsonInput.DoubleFieldNanNotQuoted
+Recommended.Proto3.JsonInput.DoubleFieldNegativeInfinityNotQuoted
+Recommended.Proto3.JsonInput.FloatFieldInfinityNotQuoted
+Recommended.Proto3.JsonInput.FloatFieldNanNotQuoted
+Recommended.Proto3.JsonInput.FloatFieldNegativeInfinityNotQuoted
+Required.Proto3.JsonInput.DoubleFieldTooSmall
+Required.Proto3.JsonInput.FloatFieldTooLarge
+Required.Proto3.JsonInput.FloatFieldTooSmall
+Required.Proto3.JsonInput.RepeatedFieldWrongElementTypeExpectingIntegersGotBool
+Required.Proto3.JsonInput.TimestampJsonInputLowercaseT
+Required.Proto3.ProtobufInput.PrematureEofInDelimitedDataForKnownNonRepeatedValue.MESSAGE
+Required.Proto3.ProtobufInput.PrematureEofInDelimitedDataForKnownRepeatedValue.MESSAGE
+Required.Proto3.ProtobufInput.PrematureEofInPackedField.BOOL
+Required.Proto3.ProtobufInput.PrematureEofInPackedField.DOUBLE
+Required.Proto3.ProtobufInput.PrematureEofInPackedField.ENUM
+Required.Proto3.ProtobufInput.PrematureEofInPackedField.FIXED32
+Required.Proto3.ProtobufInput.PrematureEofInPackedField.FIXED64
+Required.Proto3.ProtobufInput.PrematureEofInPackedField.FLOAT
+Required.Proto3.ProtobufInput.PrematureEofInPackedField.INT32
+Required.Proto3.ProtobufInput.PrematureEofInPackedField.INT64
+Required.Proto3.ProtobufInput.PrematureEofInPackedField.SFIXED32
+Required.Proto3.ProtobufInput.PrematureEofInPackedField.SFIXED64
+Required.Proto3.ProtobufInput.PrematureEofInPackedField.SINT32
+Required.Proto3.ProtobufInput.PrematureEofInPackedField.SINT64
+Required.Proto3.ProtobufInput.PrematureEofInPackedField.UINT32
+Required.Proto3.ProtobufInput.PrematureEofInPackedField.UINT64
+Required.Proto2.ProtobufInput.PrematureEofInDelimitedDataForKnownNonRepeatedValue.MESSAGE
+Required.Proto2.ProtobufInput.PrematureEofInDelimitedDataForKnownRepeatedValue.MESSAGE
+Required.Proto2.ProtobufInput.PrematureEofInPackedField.BOOL
+Required.Proto2.ProtobufInput.PrematureEofInPackedField.DOUBLE
+Required.Proto2.ProtobufInput.PrematureEofInPackedField.ENUM
+Required.Proto2.ProtobufInput.PrematureEofInPackedField.FIXED32
+Required.Proto2.ProtobufInput.PrematureEofInPackedField.FIXED64
+Required.Proto2.ProtobufInput.PrematureEofInPackedField.FLOAT
+Required.Proto2.ProtobufInput.PrematureEofInPackedField.INT32
+Required.Proto2.ProtobufInput.PrematureEofInPackedField.INT64
+Required.Proto2.ProtobufInput.PrematureEofInPackedField.SFIXED32
+Required.Proto2.ProtobufInput.PrematureEofInPackedField.SFIXED64
+Required.Proto2.ProtobufInput.PrematureEofInPackedField.SINT32
+Required.Proto2.ProtobufInput.PrematureEofInPackedField.SINT64
+Required.Proto2.ProtobufInput.PrematureEofInPackedField.UINT32
+Required.Proto2.ProtobufInput.PrematureEofInPackedField.UINT64
diff --git a/conformance/failure_list_ruby.txt b/conformance/failure_list_ruby.txt
index 1de6c439..1bab1359 100644
--- a/conformance/failure_list_ruby.txt
+++ b/conformance/failure_list_ruby.txt
@@ -1,203 +1,135 @@
Recommended.FieldMaskNumbersDontRoundTrip.JsonOutput
Recommended.FieldMaskPathsDontRoundTrip.JsonOutput
Recommended.FieldMaskTooManyUnderscore.JsonOutput
-Recommended.JsonInput.BoolFieldIntegerOne
-Recommended.JsonInput.BoolFieldIntegerZero
-Recommended.JsonInput.DurationHas3FractionalDigits.Validator
-Recommended.JsonInput.DurationHas6FractionalDigits.Validator
-Recommended.JsonInput.DurationHas9FractionalDigits.Validator
-Recommended.JsonInput.DurationHasZeroFractionalDigit.Validator
-Recommended.JsonInput.Int64FieldBeString.Validator
-Recommended.JsonInput.OneofZeroDouble.JsonOutput
-Recommended.JsonInput.OneofZeroDouble.ProtobufOutput
-Recommended.JsonInput.OneofZeroFloat.JsonOutput
-Recommended.JsonInput.OneofZeroFloat.ProtobufOutput
-Recommended.JsonInput.OneofZeroUint32.JsonOutput
-Recommended.JsonInput.OneofZeroUint32.ProtobufOutput
-Recommended.JsonInput.OneofZeroUint64.JsonOutput
-Recommended.JsonInput.OneofZeroUint64.ProtobufOutput
-Recommended.JsonInput.StringEndsWithEscapeChar
-Recommended.JsonInput.StringFieldSurrogateInWrongOrder
-Recommended.JsonInput.StringFieldUnpairedHighSurrogate
-Recommended.JsonInput.StringFieldUnpairedLowSurrogate
-Recommended.JsonInput.TimestampHas3FractionalDigits.Validator
-Recommended.JsonInput.TimestampHas6FractionalDigits.Validator
-Recommended.JsonInput.TimestampHas9FractionalDigits.Validator
-Recommended.JsonInput.TimestampHasZeroFractionalDigit.Validator
-Recommended.JsonInput.TimestampZeroNormalized.Validator
-Recommended.JsonInput.Uint64FieldBeString.Validator
+Recommended.Proto3.JsonInput.BytesFieldBase64Url.JsonOutput
+Recommended.Proto3.JsonInput.BytesFieldBase64Url.ProtobufOutput
+Recommended.Proto3.JsonInput.DurationHas3FractionalDigits.Validator
+Recommended.Proto3.JsonInput.DurationHas6FractionalDigits.Validator
+Recommended.Proto3.JsonInput.DurationHas9FractionalDigits.Validator
+Recommended.Proto3.JsonInput.DurationHasZeroFractionalDigit.Validator
+Recommended.Proto3.JsonInput.Int64FieldBeString.Validator
+Recommended.Proto3.JsonInput.MapFieldValueIsNull
+Recommended.Proto3.JsonInput.RepeatedFieldMessageElementIsNull
+Recommended.Proto3.JsonInput.RepeatedFieldPrimitiveElementIsNull
+Recommended.Proto3.JsonInput.StringEndsWithEscapeChar
+Recommended.Proto3.JsonInput.StringFieldSurrogateInWrongOrder
+Recommended.Proto3.JsonInput.StringFieldUnpairedHighSurrogate
+Recommended.Proto3.JsonInput.StringFieldUnpairedLowSurrogate
+Recommended.Proto3.JsonInput.TimestampHas3FractionalDigits.Validator
+Recommended.Proto3.JsonInput.TimestampHas6FractionalDigits.Validator
+Recommended.Proto3.JsonInput.TimestampHas9FractionalDigits.Validator
+Recommended.Proto3.JsonInput.TimestampHasZeroFractionalDigit.Validator
+Recommended.Proto3.JsonInput.TimestampZeroNormalized.Validator
+Recommended.Proto3.JsonInput.Uint64FieldBeString.Validator
Required.DurationProtoInputTooLarge.JsonOutput
Required.DurationProtoInputTooSmall.JsonOutput
-Required.JsonInput.Any.JsonOutput
-Required.JsonInput.Any.ProtobufOutput
-Required.JsonInput.AnyNested.JsonOutput
-Required.JsonInput.AnyNested.ProtobufOutput
-Required.JsonInput.AnyUnorderedTypeTag.JsonOutput
-Required.JsonInput.AnyUnorderedTypeTag.ProtobufOutput
-Required.JsonInput.AnyWithDuration.JsonOutput
-Required.JsonInput.AnyWithDuration.ProtobufOutput
-Required.JsonInput.AnyWithFieldMask.JsonOutput
-Required.JsonInput.AnyWithFieldMask.ProtobufOutput
-Required.JsonInput.AnyWithInt32ValueWrapper.JsonOutput
-Required.JsonInput.AnyWithInt32ValueWrapper.ProtobufOutput
-Required.JsonInput.AnyWithStruct.JsonOutput
-Required.JsonInput.AnyWithStruct.ProtobufOutput
-Required.JsonInput.AnyWithTimestamp.JsonOutput
-Required.JsonInput.AnyWithTimestamp.ProtobufOutput
-Required.JsonInput.AnyWithValueForInteger.JsonOutput
-Required.JsonInput.AnyWithValueForInteger.ProtobufOutput
-Required.JsonInput.AnyWithValueForJsonObject.JsonOutput
-Required.JsonInput.AnyWithValueForJsonObject.ProtobufOutput
-Required.JsonInput.DoubleFieldInfinity.JsonOutput
-Required.JsonInput.DoubleFieldInfinity.ProtobufOutput
-Required.JsonInput.DoubleFieldMaxNegativeValue.JsonOutput
-Required.JsonInput.DoubleFieldMaxNegativeValue.ProtobufOutput
-Required.JsonInput.DoubleFieldMaxPositiveValue.JsonOutput
-Required.JsonInput.DoubleFieldMaxPositiveValue.ProtobufOutput
-Required.JsonInput.DoubleFieldMinNegativeValue.JsonOutput
-Required.JsonInput.DoubleFieldMinNegativeValue.ProtobufOutput
-Required.JsonInput.DoubleFieldMinPositiveValue.JsonOutput
-Required.JsonInput.DoubleFieldMinPositiveValue.ProtobufOutput
-Required.JsonInput.DoubleFieldNan.JsonOutput
-Required.JsonInput.DoubleFieldNan.ProtobufOutput
-Required.JsonInput.DoubleFieldNegativeInfinity.JsonOutput
-Required.JsonInput.DoubleFieldNegativeInfinity.ProtobufOutput
-Required.JsonInput.DoubleFieldQuotedValue.JsonOutput
-Required.JsonInput.DoubleFieldQuotedValue.ProtobufOutput
-Required.JsonInput.DurationMaxValue.JsonOutput
-Required.JsonInput.DurationMaxValue.ProtobufOutput
-Required.JsonInput.DurationMinValue.JsonOutput
-Required.JsonInput.DurationMinValue.ProtobufOutput
-Required.JsonInput.DurationRepeatedValue.JsonOutput
-Required.JsonInput.DurationRepeatedValue.ProtobufOutput
-Required.JsonInput.EnumFieldNumericValueNonZero.JsonOutput
-Required.JsonInput.EnumFieldNumericValueNonZero.ProtobufOutput
-Required.JsonInput.EnumFieldNumericValueZero.JsonOutput
-Required.JsonInput.EnumFieldNumericValueZero.ProtobufOutput
-Required.JsonInput.EnumFieldUnknownValue.Validator
-Required.JsonInput.FieldMask.JsonOutput
-Required.JsonInput.FieldMask.ProtobufOutput
-Required.JsonInput.FloatFieldInfinity.JsonOutput
-Required.JsonInput.FloatFieldInfinity.ProtobufOutput
-Required.JsonInput.FloatFieldNan.JsonOutput
-Required.JsonInput.FloatFieldNan.ProtobufOutput
-Required.JsonInput.FloatFieldNegativeInfinity.JsonOutput
-Required.JsonInput.FloatFieldNegativeInfinity.ProtobufOutput
-Required.JsonInput.FloatFieldQuotedValue.JsonOutput
-Required.JsonInput.FloatFieldQuotedValue.ProtobufOutput
-Required.JsonInput.FloatFieldTooLarge
-Required.JsonInput.FloatFieldTooSmall
-Required.JsonInput.Int32FieldExponentialFormat.JsonOutput
-Required.JsonInput.Int32FieldExponentialFormat.ProtobufOutput
-Required.JsonInput.Int32FieldFloatTrailingZero.JsonOutput
-Required.JsonInput.Int32FieldFloatTrailingZero.ProtobufOutput
-Required.JsonInput.Int32FieldMaxFloatValue.JsonOutput
-Required.JsonInput.Int32FieldMaxFloatValue.ProtobufOutput
-Required.JsonInput.Int32FieldMinFloatValue.JsonOutput
-Required.JsonInput.Int32FieldMinFloatValue.ProtobufOutput
-Required.JsonInput.Int32FieldStringValue.JsonOutput
-Required.JsonInput.Int32FieldStringValue.ProtobufOutput
-Required.JsonInput.Int32FieldStringValueEscaped.JsonOutput
-Required.JsonInput.Int32FieldStringValueEscaped.ProtobufOutput
-Required.JsonInput.Int32MapEscapedKey.JsonOutput
-Required.JsonInput.Int32MapEscapedKey.ProtobufOutput
-Required.JsonInput.Int32MapField.JsonOutput
-Required.JsonInput.Int32MapField.ProtobufOutput
-Required.JsonInput.Int64FieldMaxValue.JsonOutput
-Required.JsonInput.Int64FieldMaxValue.ProtobufOutput
-Required.JsonInput.Int64FieldMinValue.JsonOutput
-Required.JsonInput.Int64FieldMinValue.ProtobufOutput
-Required.JsonInput.Int64MapEscapedKey.JsonOutput
-Required.JsonInput.Int64MapEscapedKey.ProtobufOutput
-Required.JsonInput.Int64MapField.JsonOutput
-Required.JsonInput.Int64MapField.ProtobufOutput
-Required.JsonInput.MessageField.JsonOutput
-Required.JsonInput.MessageField.ProtobufOutput
-Required.JsonInput.MessageMapField.JsonOutput
-Required.JsonInput.MessageMapField.ProtobufOutput
-Required.JsonInput.MessageRepeatedField.JsonOutput
-Required.JsonInput.MessageRepeatedField.ProtobufOutput
-Required.JsonInput.OptionalBoolWrapper.JsonOutput
-Required.JsonInput.OptionalBoolWrapper.ProtobufOutput
-Required.JsonInput.OptionalBytesWrapper.JsonOutput
-Required.JsonInput.OptionalBytesWrapper.ProtobufOutput
-Required.JsonInput.OptionalDoubleWrapper.JsonOutput
-Required.JsonInput.OptionalDoubleWrapper.ProtobufOutput
-Required.JsonInput.OptionalFloatWrapper.JsonOutput
-Required.JsonInput.OptionalFloatWrapper.ProtobufOutput
-Required.JsonInput.OptionalInt32Wrapper.JsonOutput
-Required.JsonInput.OptionalInt32Wrapper.ProtobufOutput
-Required.JsonInput.OptionalInt64Wrapper.JsonOutput
-Required.JsonInput.OptionalInt64Wrapper.ProtobufOutput
-Required.JsonInput.OptionalStringWrapper.JsonOutput
-Required.JsonInput.OptionalStringWrapper.ProtobufOutput
-Required.JsonInput.OptionalUint32Wrapper.JsonOutput
-Required.JsonInput.OptionalUint32Wrapper.ProtobufOutput
-Required.JsonInput.OptionalUint64Wrapper.JsonOutput
-Required.JsonInput.OptionalUint64Wrapper.ProtobufOutput
-Required.JsonInput.OptionalWrapperTypesWithNonDefaultValue.JsonOutput
-Required.JsonInput.OptionalWrapperTypesWithNonDefaultValue.ProtobufOutput
-Required.JsonInput.PrimitiveRepeatedField.JsonOutput
-Required.JsonInput.PrimitiveRepeatedField.ProtobufOutput
-Required.JsonInput.RepeatedBoolWrapper.JsonOutput
-Required.JsonInput.RepeatedBoolWrapper.ProtobufOutput
-Required.JsonInput.RepeatedBytesWrapper.JsonOutput
-Required.JsonInput.RepeatedBytesWrapper.ProtobufOutput
-Required.JsonInput.RepeatedDoubleWrapper.JsonOutput
-Required.JsonInput.RepeatedDoubleWrapper.ProtobufOutput
-Required.JsonInput.RepeatedFieldWrongElementTypeExpectingStringsGotInt
-Required.JsonInput.RepeatedFloatWrapper.JsonOutput
-Required.JsonInput.RepeatedFloatWrapper.ProtobufOutput
-Required.JsonInput.RepeatedInt32Wrapper.JsonOutput
-Required.JsonInput.RepeatedInt32Wrapper.ProtobufOutput
-Required.JsonInput.RepeatedInt64Wrapper.JsonOutput
-Required.JsonInput.RepeatedInt64Wrapper.ProtobufOutput
-Required.JsonInput.RepeatedStringWrapper.JsonOutput
-Required.JsonInput.RepeatedStringWrapper.ProtobufOutput
-Required.JsonInput.RepeatedUint32Wrapper.JsonOutput
-Required.JsonInput.RepeatedUint32Wrapper.ProtobufOutput
-Required.JsonInput.RepeatedUint64Wrapper.JsonOutput
-Required.JsonInput.RepeatedUint64Wrapper.ProtobufOutput
-Required.JsonInput.StringFieldNotAString
-Required.JsonInput.StringFieldSurrogatePair.JsonOutput
-Required.JsonInput.StringFieldSurrogatePair.ProtobufOutput
-Required.JsonInput.Struct.JsonOutput
-Required.JsonInput.Struct.ProtobufOutput
-Required.JsonInput.TimestampMaxValue.JsonOutput
-Required.JsonInput.TimestampMaxValue.ProtobufOutput
-Required.JsonInput.TimestampMinValue.JsonOutput
-Required.JsonInput.TimestampMinValue.ProtobufOutput
-Required.JsonInput.TimestampRepeatedValue.JsonOutput
-Required.JsonInput.TimestampRepeatedValue.ProtobufOutput
-Required.JsonInput.TimestampWithNegativeOffset.JsonOutput
-Required.JsonInput.TimestampWithNegativeOffset.ProtobufOutput
-Required.JsonInput.TimestampWithPositiveOffset.JsonOutput
-Required.JsonInput.TimestampWithPositiveOffset.ProtobufOutput
-Required.JsonInput.Uint32FieldMaxFloatValue.JsonOutput
-Required.JsonInput.Uint32FieldMaxFloatValue.ProtobufOutput
-Required.JsonInput.Uint32MapField.JsonOutput
-Required.JsonInput.Uint32MapField.ProtobufOutput
-Required.JsonInput.Uint64FieldMaxValue.JsonOutput
-Required.JsonInput.Uint64FieldMaxValue.ProtobufOutput
-Required.JsonInput.Uint64MapField.JsonOutput
-Required.JsonInput.Uint64MapField.ProtobufOutput
-Required.JsonInput.ValueAcceptBool.JsonOutput
-Required.JsonInput.ValueAcceptBool.ProtobufOutput
-Required.JsonInput.ValueAcceptFloat.JsonOutput
-Required.JsonInput.ValueAcceptFloat.ProtobufOutput
-Required.JsonInput.ValueAcceptInteger.JsonOutput
-Required.JsonInput.ValueAcceptInteger.ProtobufOutput
-Required.JsonInput.ValueAcceptList.JsonOutput
-Required.JsonInput.ValueAcceptList.ProtobufOutput
-Required.JsonInput.ValueAcceptNull.JsonOutput
-Required.JsonInput.ValueAcceptNull.ProtobufOutput
-Required.JsonInput.ValueAcceptObject.JsonOutput
-Required.JsonInput.ValueAcceptObject.ProtobufOutput
-Required.JsonInput.ValueAcceptString.JsonOutput
-Required.JsonInput.ValueAcceptString.ProtobufOutput
-Required.ProtobufInput.DoubleFieldNormalizeQuietNan.JsonOutput
-Required.ProtobufInput.DoubleFieldNormalizeSignalingNan.JsonOutput
-Required.ProtobufInput.FloatFieldNormalizeQuietNan.JsonOutput
-Required.ProtobufInput.FloatFieldNormalizeSignalingNan.JsonOutput
+Required.Proto3.JsonInput.Any.JsonOutput
+Required.Proto3.JsonInput.Any.ProtobufOutput
+Required.Proto3.JsonInput.AnyNested.JsonOutput
+Required.Proto3.JsonInput.AnyNested.ProtobufOutput
+Required.Proto3.JsonInput.AnyUnorderedTypeTag.JsonOutput
+Required.Proto3.JsonInput.AnyUnorderedTypeTag.ProtobufOutput
+Required.Proto3.JsonInput.AnyWithDuration.JsonOutput
+Required.Proto3.JsonInput.AnyWithDuration.ProtobufOutput
+Required.Proto3.JsonInput.AnyWithFieldMask.JsonOutput
+Required.Proto3.JsonInput.AnyWithFieldMask.ProtobufOutput
+Required.Proto3.JsonInput.AnyWithInt32ValueWrapper.JsonOutput
+Required.Proto3.JsonInput.AnyWithInt32ValueWrapper.ProtobufOutput
+Required.Proto3.JsonInput.AnyWithStruct.JsonOutput
+Required.Proto3.JsonInput.AnyWithStruct.ProtobufOutput
+Required.Proto3.JsonInput.AnyWithTimestamp.JsonOutput
+Required.Proto3.JsonInput.AnyWithTimestamp.ProtobufOutput
+Required.Proto3.JsonInput.AnyWithValueForInteger.JsonOutput
+Required.Proto3.JsonInput.AnyWithValueForInteger.ProtobufOutput
+Required.Proto3.JsonInput.AnyWithValueForJsonObject.JsonOutput
+Required.Proto3.JsonInput.AnyWithValueForJsonObject.ProtobufOutput
+Required.Proto3.JsonInput.DoubleFieldMaxNegativeValue.JsonOutput
+Required.Proto3.JsonInput.DoubleFieldMaxNegativeValue.ProtobufOutput
+Required.Proto3.JsonInput.DoubleFieldMinPositiveValue.JsonOutput
+Required.Proto3.JsonInput.DoubleFieldMinPositiveValue.ProtobufOutput
+Required.Proto3.JsonInput.DoubleFieldNan.JsonOutput
+Required.Proto3.JsonInput.DurationMaxValue.JsonOutput
+Required.Proto3.JsonInput.DurationMaxValue.ProtobufOutput
+Required.Proto3.JsonInput.DurationMinValue.JsonOutput
+Required.Proto3.JsonInput.DurationMinValue.ProtobufOutput
+Required.Proto3.JsonInput.DurationRepeatedValue.JsonOutput
+Required.Proto3.JsonInput.DurationRepeatedValue.ProtobufOutput
+Required.Proto3.JsonInput.FieldMask.JsonOutput
+Required.Proto3.JsonInput.FieldMask.ProtobufOutput
+Required.Proto3.JsonInput.FloatFieldInfinity.JsonOutput
+Required.Proto3.JsonInput.FloatFieldNan.JsonOutput
+Required.Proto3.JsonInput.FloatFieldNegativeInfinity.JsonOutput
+Required.Proto3.JsonInput.OneofFieldDuplicate
+Required.Proto3.JsonInput.OptionalBoolWrapper.JsonOutput
+Required.Proto3.JsonInput.OptionalBoolWrapper.ProtobufOutput
+Required.Proto3.JsonInput.OptionalBytesWrapper.JsonOutput
+Required.Proto3.JsonInput.OptionalBytesWrapper.ProtobufOutput
+Required.Proto3.JsonInput.OptionalDoubleWrapper.JsonOutput
+Required.Proto3.JsonInput.OptionalDoubleWrapper.ProtobufOutput
+Required.Proto3.JsonInput.OptionalFloatWrapper.JsonOutput
+Required.Proto3.JsonInput.OptionalFloatWrapper.ProtobufOutput
+Required.Proto3.JsonInput.OptionalInt32Wrapper.JsonOutput
+Required.Proto3.JsonInput.OptionalInt32Wrapper.ProtobufOutput
+Required.Proto3.JsonInput.OptionalInt64Wrapper.JsonOutput
+Required.Proto3.JsonInput.OptionalInt64Wrapper.ProtobufOutput
+Required.Proto3.JsonInput.OptionalStringWrapper.JsonOutput
+Required.Proto3.JsonInput.OptionalStringWrapper.ProtobufOutput
+Required.Proto3.JsonInput.OptionalUint32Wrapper.JsonOutput
+Required.Proto3.JsonInput.OptionalUint32Wrapper.ProtobufOutput
+Required.Proto3.JsonInput.OptionalUint64Wrapper.JsonOutput
+Required.Proto3.JsonInput.OptionalUint64Wrapper.ProtobufOutput
+Required.Proto3.JsonInput.OptionalWrapperTypesWithNonDefaultValue.JsonOutput
+Required.Proto3.JsonInput.OptionalWrapperTypesWithNonDefaultValue.ProtobufOutput
+Required.Proto3.JsonInput.RepeatedBoolWrapper.JsonOutput
+Required.Proto3.JsonInput.RepeatedBoolWrapper.ProtobufOutput
+Required.Proto3.JsonInput.RepeatedBytesWrapper.JsonOutput
+Required.Proto3.JsonInput.RepeatedBytesWrapper.ProtobufOutput
+Required.Proto3.JsonInput.RepeatedDoubleWrapper.JsonOutput
+Required.Proto3.JsonInput.RepeatedDoubleWrapper.ProtobufOutput
+Required.Proto3.JsonInput.RepeatedFloatWrapper.JsonOutput
+Required.Proto3.JsonInput.RepeatedFloatWrapper.ProtobufOutput
+Required.Proto3.JsonInput.RepeatedInt32Wrapper.JsonOutput
+Required.Proto3.JsonInput.RepeatedInt32Wrapper.ProtobufOutput
+Required.Proto3.JsonInput.RepeatedInt64Wrapper.JsonOutput
+Required.Proto3.JsonInput.RepeatedInt64Wrapper.ProtobufOutput
+Required.Proto3.JsonInput.RepeatedStringWrapper.JsonOutput
+Required.Proto3.JsonInput.RepeatedStringWrapper.ProtobufOutput
+Required.Proto3.JsonInput.RepeatedUint32Wrapper.JsonOutput
+Required.Proto3.JsonInput.RepeatedUint32Wrapper.ProtobufOutput
+Required.Proto3.JsonInput.RepeatedUint64Wrapper.JsonOutput
+Required.Proto3.JsonInput.RepeatedUint64Wrapper.ProtobufOutput
+Required.Proto3.JsonInput.StringFieldSurrogatePair.JsonOutput
+Required.Proto3.JsonInput.StringFieldSurrogatePair.ProtobufOutput
+Required.Proto3.JsonInput.Struct.JsonOutput
+Required.Proto3.JsonInput.Struct.ProtobufOutput
+Required.Proto3.JsonInput.TimestampMaxValue.JsonOutput
+Required.Proto3.JsonInput.TimestampMaxValue.ProtobufOutput
+Required.Proto3.JsonInput.TimestampMinValue.JsonOutput
+Required.Proto3.JsonInput.TimestampMinValue.ProtobufOutput
+Required.Proto3.JsonInput.TimestampRepeatedValue.JsonOutput
+Required.Proto3.JsonInput.TimestampRepeatedValue.ProtobufOutput
+Required.Proto3.JsonInput.TimestampWithNegativeOffset.JsonOutput
+Required.Proto3.JsonInput.TimestampWithNegativeOffset.ProtobufOutput
+Required.Proto3.JsonInput.TimestampWithPositiveOffset.JsonOutput
+Required.Proto3.JsonInput.TimestampWithPositiveOffset.ProtobufOutput
+Required.Proto3.JsonInput.ValueAcceptBool.JsonOutput
+Required.Proto3.JsonInput.ValueAcceptBool.ProtobufOutput
+Required.Proto3.JsonInput.ValueAcceptFloat.JsonOutput
+Required.Proto3.JsonInput.ValueAcceptFloat.ProtobufOutput
+Required.Proto3.JsonInput.ValueAcceptInteger.JsonOutput
+Required.Proto3.JsonInput.ValueAcceptInteger.ProtobufOutput
+Required.Proto3.JsonInput.ValueAcceptList.JsonOutput
+Required.Proto3.JsonInput.ValueAcceptList.ProtobufOutput
+Required.Proto3.JsonInput.ValueAcceptNull.JsonOutput
+Required.Proto3.JsonInput.ValueAcceptNull.ProtobufOutput
+Required.Proto3.JsonInput.ValueAcceptObject.JsonOutput
+Required.Proto3.JsonInput.ValueAcceptObject.ProtobufOutput
+Required.Proto3.JsonInput.ValueAcceptString.JsonOutput
+Required.Proto3.JsonInput.ValueAcceptString.ProtobufOutput
+Required.Proto3.ProtobufInput.DoubleFieldNormalizeQuietNan.JsonOutput
+Required.Proto3.ProtobufInput.DoubleFieldNormalizeSignalingNan.JsonOutput
+Required.Proto3.ProtobufInput.FloatFieldNormalizeQuietNan.JsonOutput
+Required.Proto3.ProtobufInput.FloatFieldNormalizeSignalingNan.JsonOutput
+Required.Proto3.ProtobufInput.ValidDataRepeated.FLOAT.JsonOutput
Required.TimestampProtoInputTooLarge.JsonOutput
Required.TimestampProtoInputTooSmall.JsonOutput
diff --git a/conformance/update_failure_list.py b/conformance/update_failure_list.py
index 69f210e3..ad42ed3c 100755
--- a/conformance/update_failure_list.py
+++ b/conformance/update_failure_list.py
@@ -35,7 +35,6 @@ This is sort of like comm(1), except it recognizes comments and ignores them.
"""
import argparse
-import fileinput
parser = argparse.ArgumentParser(
description='Adds/removes failures from the failure list.')
@@ -57,12 +56,13 @@ for remove_file in (args.remove_list or []):
with open(remove_file) as f:
for line in f:
if line in add_set:
- raise "Asked to both add and remove test: " + line
+ raise Exception("Asked to both add and remove test: " + line)
remove_set.add(line.strip())
add_list = sorted(add_set, reverse=True)
-existing_list = file(args.filename).read()
+with open(args.filename) as in_file:
+ existing_list = in_file.read()
with open(args.filename, "w") as f:
for line in existing_list.splitlines(True):
diff --git a/csharp/Google.Protobuf.Tools.nuspec b/csharp/Google.Protobuf.Tools.nuspec
index d079c683..5b38241a 100644
--- a/csharp/Google.Protobuf.Tools.nuspec
+++ b/csharp/Google.Protobuf.Tools.nuspec
@@ -5,7 +5,7 @@
<title>Google Protocol Buffers tools</title>
<summary>Tools for Protocol Buffers - Google's data interchange format.</summary>
<description>See project site for more info.</description>
- <version>3.1.0</version>
+ <version>3.4.1</version>
<authors>Google Inc.</authors>
<owners>protobuf-packages</owners>
<licenseUrl>https://github.com/google/protobuf/blob/master/LICENSE</licenseUrl>
diff --git a/csharp/README.md b/csharp/README.md
index ed5c7be7..c1d12419 100644
--- a/csharp/README.md
+++ b/csharp/README.md
@@ -31,16 +31,41 @@ which only uses features from C# 3 and earlier.
Building
========
-Open the `src/Google.Protobuf.sln` solution in Visual Studio 2015 or
-later. You should be able to run the NUnit test from Test Explorer
-(you might need to install NUnit Visual Studio add-in).
+Open the `src/Google.Protobuf.sln` solution in Visual Studio 2017 or
+later.
Although *users* of this project are only expected to have Visual
Studio 2012 or later, *developers* of the library are required to
-have Visual Studio 2015 or later, as the library uses C# 6 features
-in its implementation. These features have no impact when using the
-compiled code - they're only relevant when building the
-`Google.Protobuf` assembly.
+have Visual Studio 2017 or later, as the library uses C# 6 features
+in its implementation, as well as the new Visual Studio 2017 csproj
+format. These features have no impact when using the compiled code -
+they're only relevant when building the `Google.Protobuf` assembly.
+
+Testing
+=======
+
+The unit tests use [NUnit 3](https://github.com/nunit/nunit). NUnit doesn't yet
+support `dotnet test`, so for now the test project is a console application
+using NUnitLite. Simply run `Google.Protobuf.Test.exe` to run the unit tests
+directly, or else use `dotnet run`.
+
+.NET 3.5
+========
+
+We don't officially support .NET 3.5. However, there has been some effort
+to make enabling .NET 3.5 support relatively painless in case you require it.
+There's no guarantee that this will continue in the future, so rely on .NET
+3.5 support at your peril.
+
+To enable .NET 3.5 support, you must edit the `TargetFrameworks` elements of
+[src/Google.Protobuf/Google.Protobuf.csproj](src/Google.Protobuf/Google.Protobuf.csproj)
+(and [src/Google.Protobuf.Test/Google.Protobuf.Test.csproj](src/Google.Protobuf.Test/Google.Protobuf.Test.csproj)
+if you want to run the unit tests):
+
+Open the .csproj file in a text editor and simply add `net35` to the list of
+target frameworks, noting that the `TargetFrameworks` element appears twice in
+the file (once in the first `PropertyGroup` element, and again in the second
+`PropertyGroup` element, i.e., the one with the conditional).
History of C# protobufs
=======================
diff --git a/csharp/build_packages.bat b/csharp/build_packages.bat
index 37732e7c..d7205659 100644
--- a/csharp/build_packages.bat
+++ b/csharp/build_packages.bat
@@ -1,7 +1,7 @@
@rem Builds Google.Protobuf NuGet packages
-dotnet restore src
-dotnet pack -c Release src\Google.Protobuf || goto :error
+dotnet restore src/Google.Protobuf.sln
+dotnet pack -c Release src/Google.Protobuf.sln || goto :error
goto :EOF
diff --git a/csharp/buildall.sh b/csharp/buildall.sh
index cab32229..dd4b463d 100755
--- a/csharp/buildall.sh
+++ b/csharp/buildall.sh
@@ -6,11 +6,12 @@ SRC=$(dirname $0)/src
set -ex
echo Building relevant projects.
-dotnet build -c $CONFIG $SRC/Google.Protobuf $SRC/Google.Protobuf.Test $SRC/Google.Protobuf.Conformance
+dotnet restore $SRC/Google.Protobuf.sln
+dotnet build -c $CONFIG $SRC/Google.Protobuf.sln
echo Running tests.
# Only test netcoreapp1.0, which uses the .NET Core runtime.
# If we want to test the .NET 4.5 version separately, we could
# run Mono explicitly. However, we don't have any differences between
# the .NET 4.5 and netstandard1.0 assemblies.
-dotnet test -c $CONFIG -f netcoreapp1.0 $SRC/Google.Protobuf.Test
+dotnet run -c $CONFIG -f netcoreapp1.0 -p $SRC/Google.Protobuf.Test/Google.Protobuf.Test.csproj
diff --git a/csharp/compatibility_tests/v3.0.0/protos/csharp/protos/unittest_issues.proto b/csharp/compatibility_tests/v3.0.0/protos/csharp/protos/unittest_issues.proto
new file mode 100644
index 00000000..6c9f7634
--- /dev/null
+++ b/csharp/compatibility_tests/v3.0.0/protos/csharp/protos/unittest_issues.proto
@@ -0,0 +1,126 @@
+syntax = "proto3";
+
+// These proto descriptors have at one time been reported as an issue or defect.
+// They are kept here to replicate the issue, and continue to verify the fix.
+
+// Issue: Non-"Google.Protobuffers" namespace will ensure that protobuffer library types are qualified
+option csharp_namespace = "UnitTest.Issues.TestProtos";
+
+package unittest_issues;
+option optimize_for = SPEED;
+
+// Issue 307: when generating doubly-nested types, any references
+// should be of the form A.Types.B.Types.C.
+message Issue307 {
+ message NestedOnce {
+ message NestedTwice {
+ }
+ }
+}
+
+// Old issue 13: http://code.google.com/p/protobuf-csharp-port/issues/detail?id=13
+// New issue 309: https://github.com/google/protobuf/issues/309
+
+// message A {
+// optional int32 _A = 1;
+// }
+
+// message B {
+// optional int32 B_ = 1;
+// }
+
+//message AB {
+// optional int32 a_b = 1;
+//}
+
+// Similar issue with numeric names
+// Java code failed too, so probably best for this to be a restriction.
+// See https://github.com/google/protobuf/issues/308
+// message NumberField {
+// optional int32 _01 = 1;
+// }
+
+// issue 19 - negative enum values
+
+enum NegativeEnum {
+ NEGATIVE_ENUM_ZERO = 0;
+ FiveBelow = -5;
+ MinusOne = -1;
+}
+
+message NegativeEnumMessage {
+ NegativeEnum value = 1;
+ repeated NegativeEnum values = 2 [packed = false];
+ repeated NegativeEnum packed_values = 3 [packed=true];
+}
+
+// Issue 21: http://code.google.com/p/protobuf-csharp-port/issues/detail?id=21
+// Decorate fields with [deprecated=true] as [System.Obsolete]
+
+message DeprecatedChild {
+}
+
+enum DeprecatedEnum {
+ DEPRECATED_ZERO = 0;
+ one = 1;
+}
+
+message DeprecatedFieldsMessage {
+ int32 PrimitiveValue = 1 [deprecated = true];
+ repeated int32 PrimitiveArray = 2 [deprecated = true];
+
+ DeprecatedChild MessageValue = 3 [deprecated = true];
+ repeated DeprecatedChild MessageArray = 4 [deprecated = true];
+
+ DeprecatedEnum EnumValue = 5 [deprecated = true];
+ repeated DeprecatedEnum EnumArray = 6 [deprecated = true];
+}
+
+// Issue 45: http://code.google.com/p/protobuf-csharp-port/issues/detail?id=45
+message ItemField {
+ int32 item = 1;
+}
+
+message ReservedNames {
+ // Force a nested type called Types
+ message SomeNestedType {
+ }
+
+ int32 types = 1;
+ int32 descriptor = 2;
+}
+
+message TestJsonFieldOrdering {
+ // These fields are deliberately not declared in numeric
+ // order, and the oneof fields aren't contiguous either.
+ // This allows for reasonably robust tests of JSON output
+ // ordering.
+ // TestFieldOrderings in unittest_proto3.proto is similar,
+ // but doesn't include oneofs.
+ // TODO: Consider adding oneofs to TestFieldOrderings, although
+ // that will require fixing other tests in multiple platforms.
+ // Alternatively, consider just adding this to
+ // unittest_proto3.proto if multiple platforms want it.
+
+ int32 plain_int32 = 4;
+
+ oneof o1 {
+ string o1_string = 2;
+ int32 o1_int32 = 5;
+ }
+
+ string plain_string = 1;
+
+ oneof o2 {
+ int32 o2_int32 = 6;
+ string o2_string = 3;
+ }
+
+}
+
+message TestJsonName {
+ // Message for testing the effects for of the json_name option
+ string name = 1;
+ string description = 2 [json_name = "desc"];
+ string guid = 3 [json_name = "exid"];
+}
diff --git a/src/google/protobuf/map_unittest_proto3.proto b/csharp/compatibility_tests/v3.0.0/protos/src/google/protobuf/map_unittest_proto3.proto
index 16be2773..16be2773 100644
--- a/src/google/protobuf/map_unittest_proto3.proto
+++ b/csharp/compatibility_tests/v3.0.0/protos/src/google/protobuf/map_unittest_proto3.proto
diff --git a/src/google/protobuf/unittest_import_proto3.proto b/csharp/compatibility_tests/v3.0.0/protos/src/google/protobuf/unittest_import_proto3.proto
index 59673eaf..59673eaf 100644
--- a/src/google/protobuf/unittest_import_proto3.proto
+++ b/csharp/compatibility_tests/v3.0.0/protos/src/google/protobuf/unittest_import_proto3.proto
diff --git a/src/google/protobuf/unittest_import_public_proto3.proto b/csharp/compatibility_tests/v3.0.0/protos/src/google/protobuf/unittest_import_public_proto3.proto
index d6f11e28..d6f11e28 100644
--- a/src/google/protobuf/unittest_import_public_proto3.proto
+++ b/csharp/compatibility_tests/v3.0.0/protos/src/google/protobuf/unittest_import_public_proto3.proto
diff --git a/csharp/compatibility_tests/v3.0.0/protos/src/google/protobuf/unittest_proto3.proto b/csharp/compatibility_tests/v3.0.0/protos/src/google/protobuf/unittest_proto3.proto
new file mode 100644
index 00000000..f59d2178
--- /dev/null
+++ b/csharp/compatibility_tests/v3.0.0/protos/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 {}
+
diff --git a/csharp/compatibility_tests/v3.0.0/protos/src/google/protobuf/unittest_well_known_types.proto b/csharp/compatibility_tests/v3.0.0/protos/src/google/protobuf/unittest_well_known_types.proto
new file mode 100644
index 00000000..c9075244
--- /dev/null
+++ b/csharp/compatibility_tests/v3.0.0/protos/src/google/protobuf/unittest_well_known_types.proto
@@ -0,0 +1,114 @@
+syntax = "proto3";
+
+package protobuf_unittest;
+
+option csharp_namespace = "Google.Protobuf.TestProtos";
+option java_multiple_files = true;
+option java_package = "com.google.protobuf.test";
+
+import "google/protobuf/any.proto";
+import "google/protobuf/api.proto";
+import "google/protobuf/duration.proto";
+import "google/protobuf/empty.proto";
+import "google/protobuf/field_mask.proto";
+import "google/protobuf/source_context.proto";
+import "google/protobuf/struct.proto";
+import "google/protobuf/timestamp.proto";
+import "google/protobuf/type.proto";
+import "google/protobuf/wrappers.proto";
+
+// Test that we can include all well-known types.
+// Each wrapper type is included separately, as languages
+// map handle different wrappers in different ways.
+message TestWellKnownTypes {
+ google.protobuf.Any any_field = 1;
+ google.protobuf.Api api_field = 2;
+ google.protobuf.Duration duration_field = 3;
+ google.protobuf.Empty empty_field = 4;
+ google.protobuf.FieldMask field_mask_field = 5;
+ google.protobuf.SourceContext source_context_field = 6;
+ google.protobuf.Struct struct_field = 7;
+ google.protobuf.Timestamp timestamp_field = 8;
+ google.protobuf.Type type_field = 9;
+ google.protobuf.DoubleValue double_field = 10;
+ google.protobuf.FloatValue float_field = 11;
+ google.protobuf.Int64Value int64_field = 12;
+ google.protobuf.UInt64Value uint64_field = 13;
+ google.protobuf.Int32Value int32_field = 14;
+ google.protobuf.UInt32Value uint32_field = 15;
+ google.protobuf.BoolValue bool_field = 16;
+ google.protobuf.StringValue string_field = 17;
+ google.protobuf.BytesValue bytes_field = 18;
+ // Part of struct, but useful to be able to test separately
+ google.protobuf.Value value_field = 19;
+}
+
+// A repeated field for each well-known type.
+message RepeatedWellKnownTypes {
+ repeated google.protobuf.Any any_field = 1;
+ repeated google.protobuf.Api api_field = 2;
+ repeated google.protobuf.Duration duration_field = 3;
+ repeated google.protobuf.Empty empty_field = 4;
+ repeated google.protobuf.FieldMask field_mask_field = 5;
+ repeated google.protobuf.SourceContext source_context_field = 6;
+ repeated google.protobuf.Struct struct_field = 7;
+ repeated google.protobuf.Timestamp timestamp_field = 8;
+ repeated google.protobuf.Type type_field = 9;
+ // These don't actually make a lot of sense, but they're not prohibited...
+ repeated google.protobuf.DoubleValue double_field = 10;
+ repeated google.protobuf.FloatValue float_field = 11;
+ repeated google.protobuf.Int64Value int64_field = 12;
+ repeated google.protobuf.UInt64Value uint64_field = 13;
+ repeated google.protobuf.Int32Value int32_field = 14;
+ repeated google.protobuf.UInt32Value uint32_field = 15;
+ repeated google.protobuf.BoolValue bool_field = 16;
+ repeated google.protobuf.StringValue string_field = 17;
+ repeated google.protobuf.BytesValue bytes_field = 18;
+}
+
+message OneofWellKnownTypes {
+ oneof oneof_field {
+ google.protobuf.Any any_field = 1;
+ google.protobuf.Api api_field = 2;
+ google.protobuf.Duration duration_field = 3;
+ google.protobuf.Empty empty_field = 4;
+ google.protobuf.FieldMask field_mask_field = 5;
+ google.protobuf.SourceContext source_context_field = 6;
+ google.protobuf.Struct struct_field = 7;
+ google.protobuf.Timestamp timestamp_field = 8;
+ google.protobuf.Type type_field = 9;
+ google.protobuf.DoubleValue double_field = 10;
+ google.protobuf.FloatValue float_field = 11;
+ google.protobuf.Int64Value int64_field = 12;
+ google.protobuf.UInt64Value uint64_field = 13;
+ google.protobuf.Int32Value int32_field = 14;
+ google.protobuf.UInt32Value uint32_field = 15;
+ google.protobuf.BoolValue bool_field = 16;
+ google.protobuf.StringValue string_field = 17;
+ google.protobuf.BytesValue bytes_field = 18;
+ }
+}
+
+// A map field for each well-known type. We only
+// need to worry about the value part of the map being the
+// well-known types, as messages can't be map keys.
+message MapWellKnownTypes {
+ map<int32,google.protobuf.Any> any_field = 1;
+ map<int32,google.protobuf.Api> api_field = 2;
+ map<int32,google.protobuf.Duration> duration_field = 3;
+ map<int32,google.protobuf.Empty> empty_field = 4;
+ map<int32,google.protobuf.FieldMask> field_mask_field = 5;
+ map<int32,google.protobuf.SourceContext> source_context_field = 6;
+ map<int32,google.protobuf.Struct> struct_field = 7;
+ map<int32,google.protobuf.Timestamp> timestamp_field = 8;
+ map<int32,google.protobuf.Type> type_field = 9;
+ map<int32,google.protobuf.DoubleValue> double_field = 10;
+ map<int32,google.protobuf.FloatValue> float_field = 11;
+ map<int32,google.protobuf.Int64Value> int64_field = 12;
+ map<int32,google.protobuf.UInt64Value> uint64_field = 13;
+ map<int32,google.protobuf.Int32Value> int32_field = 14;
+ map<int32,google.protobuf.UInt32Value> uint32_field = 15;
+ map<int32,google.protobuf.BoolValue> bool_field = 16;
+ map<int32,google.protobuf.StringValue> string_field = 17;
+ map<int32,google.protobuf.BytesValue> bytes_field = 18;
+}
diff --git a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/ByteStringTest.cs b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/ByteStringTest.cs
new file mode 100644
index 00000000..685e130a
--- /dev/null
+++ b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/ByteStringTest.cs
@@ -0,0 +1,171 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+using System;
+using System.Text;
+using NUnit.Framework;
+
+namespace Google.Protobuf
+{
+ public class ByteStringTest
+ {
+ [Test]
+ public void Equality()
+ {
+ ByteString b1 = ByteString.CopyFrom(1, 2, 3);
+ ByteString b2 = ByteString.CopyFrom(1, 2, 3);
+ ByteString b3 = ByteString.CopyFrom(1, 2, 4);
+ ByteString b4 = ByteString.CopyFrom(1, 2, 3, 4);
+ EqualityTester.AssertEquality(b1, b1);
+ EqualityTester.AssertEquality(b1, b2);
+ EqualityTester.AssertInequality(b1, b3);
+ EqualityTester.AssertInequality(b1, b4);
+ EqualityTester.AssertInequality(b1, null);
+#pragma warning disable 1718 // Deliberately calling ==(b1, b1) and !=(b1, b1)
+ Assert.IsTrue(b1 == b1);
+ Assert.IsTrue(b1 == b2);
+ Assert.IsFalse(b1 == b3);
+ Assert.IsFalse(b1 == b4);
+ Assert.IsFalse(b1 == null);
+ Assert.IsTrue((ByteString) null == null);
+ Assert.IsFalse(b1 != b1);
+ Assert.IsFalse(b1 != b2);
+#pragma warning disable 1718
+ Assert.IsTrue(b1 != b3);
+ Assert.IsTrue(b1 != b4);
+ Assert.IsTrue(b1 != null);
+ Assert.IsFalse((ByteString) null != null);
+ }
+
+ [Test]
+ public void EmptyByteStringHasZeroSize()
+ {
+ Assert.AreEqual(0, ByteString.Empty.Length);
+ }
+
+ [Test]
+ public void CopyFromStringWithExplicitEncoding()
+ {
+ ByteString bs = ByteString.CopyFrom("AB", Encoding.Unicode);
+ Assert.AreEqual(4, bs.Length);
+ Assert.AreEqual(65, bs[0]);
+ Assert.AreEqual(0, bs[1]);
+ Assert.AreEqual(66, bs[2]);
+ Assert.AreEqual(0, bs[3]);
+ }
+
+ [Test]
+ public void IsEmptyWhenEmpty()
+ {
+ Assert.IsTrue(ByteString.CopyFromUtf8("").IsEmpty);
+ }
+
+ [Test]
+ public void IsEmptyWhenNotEmpty()
+ {
+ Assert.IsFalse(ByteString.CopyFromUtf8("X").IsEmpty);
+ }
+
+ [Test]
+ public void CopyFromByteArrayCopiesContents()
+ {
+ byte[] data = new byte[1];
+ data[0] = 10;
+ ByteString bs = ByteString.CopyFrom(data);
+ Assert.AreEqual(10, bs[0]);
+ data[0] = 5;
+ Assert.AreEqual(10, bs[0]);
+ }
+
+ [Test]
+ public void ToByteArrayCopiesContents()
+ {
+ ByteString bs = ByteString.CopyFromUtf8("Hello");
+ byte[] data = bs.ToByteArray();
+ Assert.AreEqual((byte)'H', data[0]);
+ Assert.AreEqual((byte)'H', bs[0]);
+ data[0] = 0;
+ Assert.AreEqual(0, data[0]);
+ Assert.AreEqual((byte)'H', bs[0]);
+ }
+
+ [Test]
+ public void CopyFromUtf8UsesUtf8()
+ {
+ ByteString bs = ByteString.CopyFromUtf8("\u20ac");
+ Assert.AreEqual(3, bs.Length);
+ Assert.AreEqual(0xe2, bs[0]);
+ Assert.AreEqual(0x82, bs[1]);
+ Assert.AreEqual(0xac, bs[2]);
+ }
+
+ [Test]
+ public void CopyFromPortion()
+ {
+ byte[] data = new byte[] {0, 1, 2, 3, 4, 5, 6};
+ ByteString bs = ByteString.CopyFrom(data, 2, 3);
+ Assert.AreEqual(3, bs.Length);
+ Assert.AreEqual(2, bs[0]);
+ Assert.AreEqual(3, bs[1]);
+ }
+
+ [Test]
+ public void ToStringUtf8()
+ {
+ ByteString bs = ByteString.CopyFromUtf8("\u20ac");
+ Assert.AreEqual("\u20ac", bs.ToStringUtf8());
+ }
+
+ [Test]
+ public void ToStringWithExplicitEncoding()
+ {
+ ByteString bs = ByteString.CopyFrom("\u20ac", Encoding.Unicode);
+ Assert.AreEqual("\u20ac", bs.ToString(Encoding.Unicode));
+ }
+
+ [Test]
+ public void FromBase64_WithText()
+ {
+ byte[] data = new byte[] {0, 1, 2, 3, 4, 5, 6};
+ string base64 = Convert.ToBase64String(data);
+ ByteString bs = ByteString.FromBase64(base64);
+ Assert.AreEqual(data, bs.ToByteArray());
+ }
+
+ [Test]
+ public void FromBase64_Empty()
+ {
+ // Optimization which also fixes issue 61.
+ Assert.AreSame(ByteString.Empty, ByteString.FromBase64(""));
+ }
+ }
+} \ No newline at end of file
diff --git a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/CodedInputStreamExtensions.cs b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/CodedInputStreamExtensions.cs
new file mode 100644
index 00000000..23af2887
--- /dev/null
+++ b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/CodedInputStreamExtensions.cs
@@ -0,0 +1,53 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2015 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+using NUnit.Framework;
+
+namespace Google.Protobuf
+{
+ internal static class CodedInputStreamExtensions
+ {
+ public static void AssertNextTag(this CodedInputStream input, uint expectedTag)
+ {
+ uint tag = input.ReadTag();
+ Assert.AreEqual(expectedTag, tag);
+ }
+
+ public static T ReadMessage<T>(this CodedInputStream stream, MessageParser<T> parser)
+ where T : IMessage<T>
+ {
+ var message = parser.CreateTemplate();
+ stream.ReadMessage(message);
+ return message;
+ }
+ }
+}
diff --git a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/CodedInputStreamTest.cs b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/CodedInputStreamTest.cs
new file mode 100644
index 00000000..ff44895c
--- /dev/null
+++ b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/CodedInputStreamTest.cs
@@ -0,0 +1,598 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+using System;
+using System.IO;
+using Google.Protobuf.TestProtos;
+using NUnit.Framework;
+
+namespace Google.Protobuf
+{
+ public class CodedInputStreamTest
+ {
+ /// <summary>
+ /// Helper to construct a byte array from a bunch of bytes. The inputs are
+ /// actually ints so that I can use hex notation and not get stupid errors
+ /// about precision.
+ /// </summary>
+ private static byte[] Bytes(params int[] bytesAsInts)
+ {
+ byte[] bytes = new byte[bytesAsInts.Length];
+ for (int i = 0; i < bytesAsInts.Length; i++)
+ {
+ bytes[i] = (byte) bytesAsInts[i];
+ }
+ return bytes;
+ }
+
+ /// <summary>
+ /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64()
+ /// </summary>
+ private static void AssertReadVarint(byte[] data, ulong value)
+ {
+ CodedInputStream input = new CodedInputStream(data);
+ Assert.AreEqual((uint) value, input.ReadRawVarint32());
+
+ input = new CodedInputStream(data);
+ Assert.AreEqual(value, input.ReadRawVarint64());
+ Assert.IsTrue(input.IsAtEnd);
+
+ // Try different block sizes.
+ for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2)
+ {
+ input = new CodedInputStream(new SmallBlockInputStream(data, bufferSize));
+ Assert.AreEqual((uint) value, input.ReadRawVarint32());
+
+ input = new CodedInputStream(new SmallBlockInputStream(data, bufferSize));
+ Assert.AreEqual(value, input.ReadRawVarint64());
+ Assert.IsTrue(input.IsAtEnd);
+ }
+
+ // Try reading directly from a MemoryStream. We want to verify that it
+ // doesn't read past the end of the input, so write an extra byte - this
+ // lets us test the position at the end.
+ MemoryStream memoryStream = new MemoryStream();
+ memoryStream.Write(data, 0, data.Length);
+ memoryStream.WriteByte(0);
+ memoryStream.Position = 0;
+ Assert.AreEqual((uint) value, CodedInputStream.ReadRawVarint32(memoryStream));
+ Assert.AreEqual(data.Length, memoryStream.Position);
+ }
+
+ /// <summary>
+ /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() and
+ /// expects them to fail with an InvalidProtocolBufferException whose
+ /// description matches the given one.
+ /// </summary>
+ private static void AssertReadVarintFailure(InvalidProtocolBufferException expected, byte[] data)
+ {
+ CodedInputStream input = new CodedInputStream(data);
+ var exception = Assert.Throws<InvalidProtocolBufferException>(() => input.ReadRawVarint32());
+ Assert.AreEqual(expected.Message, exception.Message);
+
+ input = new CodedInputStream(data);
+ exception = Assert.Throws<InvalidProtocolBufferException>(() => input.ReadRawVarint64());
+ Assert.AreEqual(expected.Message, exception.Message);
+
+ // Make sure we get the same error when reading directly from a Stream.
+ exception = Assert.Throws<InvalidProtocolBufferException>(() => CodedInputStream.ReadRawVarint32(new MemoryStream(data)));
+ Assert.AreEqual(expected.Message, exception.Message);
+ }
+
+ [Test]
+ public void ReadVarint()
+ {
+ AssertReadVarint(Bytes(0x00), 0);
+ AssertReadVarint(Bytes(0x01), 1);
+ AssertReadVarint(Bytes(0x7f), 127);
+ // 14882
+ AssertReadVarint(Bytes(0xa2, 0x74), (0x22 << 0) | (0x74 << 7));
+ // 2961488830
+ AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x0b),
+ (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
+ (0x0bL << 28));
+
+ // 64-bit
+ // 7256456126
+ AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x1b),
+ (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
+ (0x1bL << 28));
+ // 41256202580718336
+ AssertReadVarint(Bytes(0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49),
+ (0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) |
+ (0x43L << 28) | (0x49L << 35) | (0x24L << 42) | (0x49L << 49));
+ // 11964378330978735131
+ AssertReadVarint(Bytes(0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01),
+ (0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) |
+ (0x3bUL << 28) | (0x56UL << 35) | (0x00UL << 42) |
+ (0x05UL << 49) | (0x26UL << 56) | (0x01UL << 63));
+
+ // Failures
+ AssertReadVarintFailure(
+ InvalidProtocolBufferException.MalformedVarint(),
+ Bytes(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,
+ 0x00));
+ AssertReadVarintFailure(
+ InvalidProtocolBufferException.TruncatedMessage(),
+ Bytes(0x80));
+ }
+
+ /// <summary>
+ /// Parses the given bytes using ReadRawLittleEndian32() and checks
+ /// that the result matches the given value.
+ /// </summary>
+ private static void AssertReadLittleEndian32(byte[] data, uint value)
+ {
+ CodedInputStream input = new CodedInputStream(data);
+ Assert.AreEqual(value, input.ReadRawLittleEndian32());
+ Assert.IsTrue(input.IsAtEnd);
+
+ // Try different block sizes.
+ for (int blockSize = 1; blockSize <= 16; blockSize *= 2)
+ {
+ input = new CodedInputStream(
+ new SmallBlockInputStream(data, blockSize));
+ Assert.AreEqual(value, input.ReadRawLittleEndian32());
+ Assert.IsTrue(input.IsAtEnd);
+ }
+ }
+
+ /// <summary>
+ /// Parses the given bytes using ReadRawLittleEndian64() and checks
+ /// that the result matches the given value.
+ /// </summary>
+ private static void AssertReadLittleEndian64(byte[] data, ulong value)
+ {
+ CodedInputStream input = new CodedInputStream(data);
+ Assert.AreEqual(value, input.ReadRawLittleEndian64());
+ Assert.IsTrue(input.IsAtEnd);
+
+ // Try different block sizes.
+ for (int blockSize = 1; blockSize <= 16; blockSize *= 2)
+ {
+ input = new CodedInputStream(
+ new SmallBlockInputStream(data, blockSize));
+ Assert.AreEqual(value, input.ReadRawLittleEndian64());
+ Assert.IsTrue(input.IsAtEnd);
+ }
+ }
+
+ [Test]
+ public void ReadLittleEndian()
+ {
+ AssertReadLittleEndian32(Bytes(0x78, 0x56, 0x34, 0x12), 0x12345678);
+ AssertReadLittleEndian32(Bytes(0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef0);
+
+ AssertReadLittleEndian64(Bytes(0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12),
+ 0x123456789abcdef0L);
+ AssertReadLittleEndian64(
+ Bytes(0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef012345678UL);
+ }
+
+ [Test]
+ public void DecodeZigZag32()
+ {
+ Assert.AreEqual(0, CodedInputStream.DecodeZigZag32(0));
+ Assert.AreEqual(-1, CodedInputStream.DecodeZigZag32(1));
+ Assert.AreEqual(1, CodedInputStream.DecodeZigZag32(2));
+ Assert.AreEqual(-2, CodedInputStream.DecodeZigZag32(3));
+ Assert.AreEqual(0x3FFFFFFF, CodedInputStream.DecodeZigZag32(0x7FFFFFFE));
+ Assert.AreEqual(unchecked((int) 0xC0000000), CodedInputStream.DecodeZigZag32(0x7FFFFFFF));
+ Assert.AreEqual(0x7FFFFFFF, CodedInputStream.DecodeZigZag32(0xFFFFFFFE));
+ Assert.AreEqual(unchecked((int) 0x80000000), CodedInputStream.DecodeZigZag32(0xFFFFFFFF));
+ }
+
+ [Test]
+ public void DecodeZigZag64()
+ {
+ Assert.AreEqual(0, CodedInputStream.DecodeZigZag64(0));
+ Assert.AreEqual(-1, CodedInputStream.DecodeZigZag64(1));
+ Assert.AreEqual(1, CodedInputStream.DecodeZigZag64(2));
+ Assert.AreEqual(-2, CodedInputStream.DecodeZigZag64(3));
+ Assert.AreEqual(0x000000003FFFFFFFL, CodedInputStream.DecodeZigZag64(0x000000007FFFFFFEL));
+ Assert.AreEqual(unchecked((long) 0xFFFFFFFFC0000000L), CodedInputStream.DecodeZigZag64(0x000000007FFFFFFFL));
+ Assert.AreEqual(0x000000007FFFFFFFL, CodedInputStream.DecodeZigZag64(0x00000000FFFFFFFEL));
+ Assert.AreEqual(unchecked((long) 0xFFFFFFFF80000000L), CodedInputStream.DecodeZigZag64(0x00000000FFFFFFFFL));
+ Assert.AreEqual(0x7FFFFFFFFFFFFFFFL, CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFEL));
+ Assert.AreEqual(unchecked((long) 0x8000000000000000L), CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFFL));
+ }
+
+ [Test]
+ public void ReadWholeMessage_VaryingBlockSizes()
+ {
+ TestAllTypes message = SampleMessages.CreateFullTestAllTypes();
+
+ byte[] rawBytes = message.ToByteArray();
+ Assert.AreEqual(rawBytes.Length, message.CalculateSize());
+ TestAllTypes message2 = TestAllTypes.Parser.ParseFrom(rawBytes);
+ Assert.AreEqual(message, message2);
+
+ // Try different block sizes.
+ for (int blockSize = 1; blockSize < 256; blockSize *= 2)
+ {
+ message2 = TestAllTypes.Parser.ParseFrom(new SmallBlockInputStream(rawBytes, blockSize));
+ Assert.AreEqual(message, message2);
+ }
+ }
+
+ [Test]
+ public void ReadHugeBlob()
+ {
+ // Allocate and initialize a 1MB blob.
+ byte[] blob = new byte[1 << 20];
+ for (int i = 0; i < blob.Length; i++)
+ {
+ blob[i] = (byte) i;
+ }
+
+ // Make a message containing it.
+ var message = new TestAllTypes { SingleBytes = ByteString.CopyFrom(blob) };
+
+ // Serialize and parse it. Make sure to parse from an InputStream, not
+ // directly from a ByteString, so that CodedInputStream uses buffered
+ // reading.
+ TestAllTypes message2 = TestAllTypes.Parser.ParseFrom(message.ToByteString());
+
+ Assert.AreEqual(message, message2);
+ }
+
+ [Test]
+ public void ReadMaliciouslyLargeBlob()
+ {
+ MemoryStream ms = new MemoryStream();
+ CodedOutputStream output = new CodedOutputStream(ms);
+
+ uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
+ output.WriteRawVarint32(tag);
+ output.WriteRawVarint32(0x7FFFFFFF);
+ output.WriteRawBytes(new byte[32]); // Pad with a few random bytes.
+ output.Flush();
+ ms.Position = 0;
+
+ CodedInputStream input = new CodedInputStream(ms);
+ Assert.AreEqual(tag, input.ReadTag());
+
+ Assert.Throws<InvalidProtocolBufferException>(() => input.ReadBytes());
+ }
+
+ internal static TestRecursiveMessage MakeRecursiveMessage(int depth)
+ {
+ if (depth == 0)
+ {
+ return new TestRecursiveMessage { I = 5 };
+ }
+ else
+ {
+ return new TestRecursiveMessage { A = MakeRecursiveMessage(depth - 1) };
+ }
+ }
+
+ internal static void AssertMessageDepth(TestRecursiveMessage message, int depth)
+ {
+ if (depth == 0)
+ {
+ Assert.IsNull(message.A);
+ Assert.AreEqual(5, message.I);
+ }
+ else
+ {
+ Assert.IsNotNull(message.A);
+ AssertMessageDepth(message.A, depth - 1);
+ }
+ }
+
+ [Test]
+ public void MaliciousRecursion()
+ {
+ ByteString data64 = MakeRecursiveMessage(64).ToByteString();
+ ByteString data65 = MakeRecursiveMessage(65).ToByteString();
+
+ AssertMessageDepth(TestRecursiveMessage.Parser.ParseFrom(data64), 64);
+
+ Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.Parser.ParseFrom(data65));
+
+ CodedInputStream input = CodedInputStream.CreateWithLimits(new MemoryStream(data64.ToByteArray()), 1000000, 63);
+ Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.Parser.ParseFrom(input));
+ }
+
+ [Test]
+ public void SizeLimit()
+ {
+ // Have to use a Stream rather than ByteString.CreateCodedInput as SizeLimit doesn't
+ // apply to the latter case.
+ MemoryStream ms = new MemoryStream(SampleMessages.CreateFullTestAllTypes().ToByteArray());
+ CodedInputStream input = CodedInputStream.CreateWithLimits(ms, 16, 100);
+ Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseFrom(input));
+ }
+
+ /// <summary>
+ /// Tests that if we read an string that contains invalid UTF-8, no exception
+ /// is thrown. Instead, the invalid bytes are replaced with the Unicode
+ /// "replacement character" U+FFFD.
+ /// </summary>
+ [Test]
+ public void ReadInvalidUtf8()
+ {
+ MemoryStream ms = new MemoryStream();
+ CodedOutputStream output = new CodedOutputStream(ms);
+
+ uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
+ output.WriteRawVarint32(tag);
+ output.WriteRawVarint32(1);
+ output.WriteRawBytes(new byte[] {0x80});
+ output.Flush();
+ ms.Position = 0;
+
+ CodedInputStream input = new CodedInputStream(ms);
+
+ Assert.AreEqual(tag, input.ReadTag());
+ string text = input.ReadString();
+ Assert.AreEqual('\ufffd', text[0]);
+ }
+
+ /// <summary>
+ /// A stream which limits the number of bytes it reads at a time.
+ /// We use this to make sure that CodedInputStream doesn't screw up when
+ /// reading in small blocks.
+ /// </summary>
+ private sealed class SmallBlockInputStream : MemoryStream
+ {
+ private readonly int blockSize;
+
+ public SmallBlockInputStream(byte[] data, int blockSize)
+ : base(data)
+ {
+ this.blockSize = blockSize;
+ }
+
+ public override int Read(byte[] buffer, int offset, int count)
+ {
+ return base.Read(buffer, offset, Math.Min(count, blockSize));
+ }
+ }
+
+ [Test]
+ public void TestNegativeEnum()
+ {
+ byte[] bytes = { 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01 };
+ CodedInputStream input = new CodedInputStream(bytes);
+ Assert.AreEqual((int)SampleEnum.NegativeValue, input.ReadEnum());
+ Assert.IsTrue(input.IsAtEnd);
+ }
+
+ //Issue 71: CodedInputStream.ReadBytes go to slow path unnecessarily
+ [Test]
+ public void TestSlowPathAvoidance()
+ {
+ using (var ms = new MemoryStream())
+ {
+ CodedOutputStream output = new CodedOutputStream(ms);
+ output.WriteTag(1, WireFormat.WireType.LengthDelimited);
+ output.WriteBytes(ByteString.CopyFrom(new byte[100]));
+ output.WriteTag(2, WireFormat.WireType.LengthDelimited);
+ output.WriteBytes(ByteString.CopyFrom(new byte[100]));
+ output.Flush();
+
+ ms.Position = 0;
+ CodedInputStream input = new CodedInputStream(ms, new byte[ms.Length / 2], 0, 0, false);
+
+ uint tag = input.ReadTag();
+ Assert.AreEqual(1, WireFormat.GetTagFieldNumber(tag));
+ Assert.AreEqual(100, input.ReadBytes().Length);
+
+ tag = input.ReadTag();
+ Assert.AreEqual(2, WireFormat.GetTagFieldNumber(tag));
+ Assert.AreEqual(100, input.ReadBytes().Length);
+ }
+ }
+
+ [Test]
+ public void Tag0Throws()
+ {
+ var input = new CodedInputStream(new byte[] { 0 });
+ Assert.Throws<InvalidProtocolBufferException>(() => input.ReadTag());
+ }
+
+ [Test]
+ public void SkipGroup()
+ {
+ // Create an output stream with a group in:
+ // Field 1: string "field 1"
+ // Field 2: group containing:
+ // Field 1: fixed int32 value 100
+ // Field 2: string "ignore me"
+ // Field 3: nested group containing
+ // Field 1: fixed int64 value 1000
+ // Field 3: string "field 3"
+ var stream = new MemoryStream();
+ var output = new CodedOutputStream(stream);
+ output.WriteTag(1, WireFormat.WireType.LengthDelimited);
+ output.WriteString("field 1");
+
+ // The outer group...
+ output.WriteTag(2, WireFormat.WireType.StartGroup);
+ output.WriteTag(1, WireFormat.WireType.Fixed32);
+ output.WriteFixed32(100);
+ output.WriteTag(2, WireFormat.WireType.LengthDelimited);
+ output.WriteString("ignore me");
+ // The nested group...
+ output.WriteTag(3, WireFormat.WireType.StartGroup);
+ output.WriteTag(1, WireFormat.WireType.Fixed64);
+ output.WriteFixed64(1000);
+ // Note: Not sure the field number is relevant for end group...
+ output.WriteTag(3, WireFormat.WireType.EndGroup);
+
+ // End the outer group
+ output.WriteTag(2, WireFormat.WireType.EndGroup);
+
+ output.WriteTag(3, WireFormat.WireType.LengthDelimited);
+ output.WriteString("field 3");
+ output.Flush();
+ stream.Position = 0;
+
+ // Now act like a generated client
+ var input = new CodedInputStream(stream);
+ Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited), input.ReadTag());
+ Assert.AreEqual("field 1", input.ReadString());
+ Assert.AreEqual(WireFormat.MakeTag(2, WireFormat.WireType.StartGroup), input.ReadTag());
+ input.SkipLastField(); // Should consume the whole group, including the nested one.
+ Assert.AreEqual(WireFormat.MakeTag(3, WireFormat.WireType.LengthDelimited), input.ReadTag());
+ Assert.AreEqual("field 3", input.ReadString());
+ }
+
+ [Test]
+ public void SkipGroup_WrongEndGroupTag()
+ {
+ // Create an output stream with:
+ // Field 1: string "field 1"
+ // Start group 2
+ // Field 3: fixed int32
+ // End group 4 (should give an error)
+ var stream = new MemoryStream();
+ var output = new CodedOutputStream(stream);
+ output.WriteTag(1, WireFormat.WireType.LengthDelimited);
+ output.WriteString("field 1");
+
+ // The outer group...
+ output.WriteTag(2, WireFormat.WireType.StartGroup);
+ output.WriteTag(3, WireFormat.WireType.Fixed32);
+ output.WriteFixed32(100);
+ output.WriteTag(4, WireFormat.WireType.EndGroup);
+ output.Flush();
+ stream.Position = 0;
+
+ // Now act like a generated client
+ var input = new CodedInputStream(stream);
+ Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited), input.ReadTag());
+ Assert.AreEqual("field 1", input.ReadString());
+ Assert.AreEqual(WireFormat.MakeTag(2, WireFormat.WireType.StartGroup), input.ReadTag());
+ Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField);
+ }
+
+ [Test]
+ public void RogueEndGroupTag()
+ {
+ // If we have an end-group tag without a leading start-group tag, generated
+ // code will just call SkipLastField... so that should fail.
+
+ var stream = new MemoryStream();
+ var output = new CodedOutputStream(stream);
+ output.WriteTag(1, WireFormat.WireType.EndGroup);
+ output.Flush();
+ stream.Position = 0;
+
+ var input = new CodedInputStream(stream);
+ Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.EndGroup), input.ReadTag());
+ Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField);
+ }
+
+ [Test]
+ public void EndOfStreamReachedWhileSkippingGroup()
+ {
+ var stream = new MemoryStream();
+ var output = new CodedOutputStream(stream);
+ output.WriteTag(1, WireFormat.WireType.StartGroup);
+ output.WriteTag(2, WireFormat.WireType.StartGroup);
+ output.WriteTag(2, WireFormat.WireType.EndGroup);
+
+ output.Flush();
+ stream.Position = 0;
+
+ // Now act like a generated client
+ var input = new CodedInputStream(stream);
+ input.ReadTag();
+ Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField);
+ }
+
+ [Test]
+ public void RecursionLimitAppliedWhileSkippingGroup()
+ {
+ var stream = new MemoryStream();
+ var output = new CodedOutputStream(stream);
+ for (int i = 0; i < CodedInputStream.DefaultRecursionLimit + 1; i++)
+ {
+ output.WriteTag(1, WireFormat.WireType.StartGroup);
+ }
+ for (int i = 0; i < CodedInputStream.DefaultRecursionLimit + 1; i++)
+ {
+ output.WriteTag(1, WireFormat.WireType.EndGroup);
+ }
+ output.Flush();
+ stream.Position = 0;
+
+ // Now act like a generated client
+ var input = new CodedInputStream(stream);
+ Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.StartGroup), input.ReadTag());
+ Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField);
+ }
+
+ [Test]
+ public void Construction_Invalid()
+ {
+ Assert.Throws<ArgumentNullException>(() => new CodedInputStream((byte[]) null));
+ Assert.Throws<ArgumentNullException>(() => new CodedInputStream(null, 0, 0));
+ Assert.Throws<ArgumentNullException>(() => new CodedInputStream((Stream) null));
+ Assert.Throws<ArgumentOutOfRangeException>(() => new CodedInputStream(new byte[10], 100, 0));
+ Assert.Throws<ArgumentOutOfRangeException>(() => new CodedInputStream(new byte[10], 5, 10));
+ }
+
+ [Test]
+ public void CreateWithLimits_InvalidLimits()
+ {
+ var stream = new MemoryStream();
+ Assert.Throws<ArgumentOutOfRangeException>(() => CodedInputStream.CreateWithLimits(stream, 0, 1));
+ Assert.Throws<ArgumentOutOfRangeException>(() => CodedInputStream.CreateWithLimits(stream, 1, 0));
+ }
+
+ [Test]
+ public void Dispose_DisposesUnderlyingStream()
+ {
+ var memoryStream = new MemoryStream();
+ Assert.IsTrue(memoryStream.CanRead);
+ using (var cis = new CodedInputStream(memoryStream))
+ {
+ }
+ Assert.IsFalse(memoryStream.CanRead); // Disposed
+ }
+
+ [Test]
+ public void Dispose_WithLeaveOpen()
+ {
+ var memoryStream = new MemoryStream();
+ Assert.IsTrue(memoryStream.CanRead);
+ using (var cis = new CodedInputStream(memoryStream, true))
+ {
+ }
+ Assert.IsTrue(memoryStream.CanRead); // We left the stream open
+ }
+ }
+} \ No newline at end of file
diff --git a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/CodedOutputStreamTest.cs b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/CodedOutputStreamTest.cs
new file mode 100644
index 00000000..01bd3218
--- /dev/null
+++ b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/CodedOutputStreamTest.cs
@@ -0,0 +1,419 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+using System;
+using System.IO;
+using Google.Protobuf.TestProtos;
+using NUnit.Framework;
+
+namespace Google.Protobuf
+{
+ public class CodedOutputStreamTest
+ {
+ /// <summary>
+ /// Writes the given value using WriteRawVarint32() and WriteRawVarint64() and
+ /// checks that the result matches the given bytes
+ /// </summary>
+ private static void AssertWriteVarint(byte[] data, ulong value)
+ {
+ // Only do 32-bit write if the value fits in 32 bits.
+ if ((value >> 32) == 0)
+ {
+ MemoryStream rawOutput = new MemoryStream();
+ CodedOutputStream output = new CodedOutputStream(rawOutput);
+ output.WriteRawVarint32((uint) value);
+ output.Flush();
+ Assert.AreEqual(data, rawOutput.ToArray());
+ // Also try computing size.
+ Assert.AreEqual(data.Length, CodedOutputStream.ComputeRawVarint32Size((uint) value));
+ }
+
+ {
+ MemoryStream rawOutput = new MemoryStream();
+ CodedOutputStream output = new CodedOutputStream(rawOutput);
+ output.WriteRawVarint64(value);
+ output.Flush();
+ Assert.AreEqual(data, rawOutput.ToArray());
+
+ // Also try computing size.
+ Assert.AreEqual(data.Length, CodedOutputStream.ComputeRawVarint64Size(value));
+ }
+
+ // Try different buffer sizes.
+ for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2)
+ {
+ // Only do 32-bit write if the value fits in 32 bits.
+ if ((value >> 32) == 0)
+ {
+ MemoryStream rawOutput = new MemoryStream();
+ CodedOutputStream output =
+ new CodedOutputStream(rawOutput, bufferSize);
+ output.WriteRawVarint32((uint) value);
+ output.Flush();
+ Assert.AreEqual(data, rawOutput.ToArray());
+ }
+
+ {
+ MemoryStream rawOutput = new MemoryStream();
+ CodedOutputStream output = new CodedOutputStream(rawOutput, bufferSize);
+ output.WriteRawVarint64(value);
+ output.Flush();
+ Assert.AreEqual(data, rawOutput.ToArray());
+ }
+ }
+ }
+
+ /// <summary>
+ /// Tests WriteRawVarint32() and WriteRawVarint64()
+ /// </summary>
+ [Test]
+ public void WriteVarint()
+ {
+ AssertWriteVarint(new byte[] {0x00}, 0);
+ AssertWriteVarint(new byte[] {0x01}, 1);
+ AssertWriteVarint(new byte[] {0x7f}, 127);
+ // 14882
+ AssertWriteVarint(new byte[] {0xa2, 0x74}, (0x22 << 0) | (0x74 << 7));
+ // 2961488830
+ AssertWriteVarint(new byte[] {0xbe, 0xf7, 0x92, 0x84, 0x0b},
+ (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
+ (0x0bL << 28));
+
+ // 64-bit
+ // 7256456126
+ AssertWriteVarint(new byte[] {0xbe, 0xf7, 0x92, 0x84, 0x1b},
+ (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
+ (0x1bL << 28));
+ // 41256202580718336
+ AssertWriteVarint(
+ new byte[] {0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49},
+ (0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) |
+ (0x43UL << 28) | (0x49L << 35) | (0x24UL << 42) | (0x49UL << 49));
+ // 11964378330978735131
+ AssertWriteVarint(
+ new byte[] {0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01},
+ unchecked((ulong)
+ ((0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) |
+ (0x3bL << 28) | (0x56L << 35) | (0x00L << 42) |
+ (0x05L << 49) | (0x26L << 56) | (0x01L << 63))));
+ }
+
+ /// <summary>
+ /// Parses the given bytes using WriteRawLittleEndian32() and checks
+ /// that the result matches the given value.
+ /// </summary>
+ private static void AssertWriteLittleEndian32(byte[] data, uint value)
+ {
+ MemoryStream rawOutput = new MemoryStream();
+ CodedOutputStream output = new CodedOutputStream(rawOutput);
+ output.WriteRawLittleEndian32(value);
+ output.Flush();
+ Assert.AreEqual(data, rawOutput.ToArray());
+
+ // Try different buffer sizes.
+ for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2)
+ {
+ rawOutput = new MemoryStream();
+ output = new CodedOutputStream(rawOutput, bufferSize);
+ output.WriteRawLittleEndian32(value);
+ output.Flush();
+ Assert.AreEqual(data, rawOutput.ToArray());
+ }
+ }
+
+ /// <summary>
+ /// Parses the given bytes using WriteRawLittleEndian64() and checks
+ /// that the result matches the given value.
+ /// </summary>
+ private static void AssertWriteLittleEndian64(byte[] data, ulong value)
+ {
+ MemoryStream rawOutput = new MemoryStream();
+ CodedOutputStream output = new CodedOutputStream(rawOutput);
+ output.WriteRawLittleEndian64(value);
+ output.Flush();
+ Assert.AreEqual(data, rawOutput.ToArray());
+
+ // Try different block sizes.
+ for (int blockSize = 1; blockSize <= 16; blockSize *= 2)
+ {
+ rawOutput = new MemoryStream();
+ output = new CodedOutputStream(rawOutput, blockSize);
+ output.WriteRawLittleEndian64(value);
+ output.Flush();
+ Assert.AreEqual(data, rawOutput.ToArray());
+ }
+ }
+
+ /// <summary>
+ /// Tests writeRawLittleEndian32() and writeRawLittleEndian64().
+ /// </summary>
+ [Test]
+ public void WriteLittleEndian()
+ {
+ AssertWriteLittleEndian32(new byte[] {0x78, 0x56, 0x34, 0x12}, 0x12345678);
+ AssertWriteLittleEndian32(new byte[] {0xf0, 0xde, 0xbc, 0x9a}, 0x9abcdef0);
+
+ AssertWriteLittleEndian64(
+ new byte[] {0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12},
+ 0x123456789abcdef0L);
+ AssertWriteLittleEndian64(
+ new byte[] {0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a},
+ 0x9abcdef012345678UL);
+ }
+
+ [Test]
+ public void WriteWholeMessage_VaryingBlockSizes()
+ {
+ TestAllTypes message = SampleMessages.CreateFullTestAllTypes();
+
+ byte[] rawBytes = message.ToByteArray();
+
+ // Try different block sizes.
+ for (int blockSize = 1; blockSize < 256; blockSize *= 2)
+ {
+ MemoryStream rawOutput = new MemoryStream();
+ CodedOutputStream output = new CodedOutputStream(rawOutput, blockSize);
+ message.WriteTo(output);
+ output.Flush();
+ Assert.AreEqual(rawBytes, rawOutput.ToArray());
+ }
+ }
+
+ [Test]
+ public void EncodeZigZag32()
+ {
+ Assert.AreEqual(0u, CodedOutputStream.EncodeZigZag32(0));
+ Assert.AreEqual(1u, CodedOutputStream.EncodeZigZag32(-1));
+ Assert.AreEqual(2u, CodedOutputStream.EncodeZigZag32(1));
+ Assert.AreEqual(3u, CodedOutputStream.EncodeZigZag32(-2));
+ Assert.AreEqual(0x7FFFFFFEu, CodedOutputStream.EncodeZigZag32(0x3FFFFFFF));
+ Assert.AreEqual(0x7FFFFFFFu, CodedOutputStream.EncodeZigZag32(unchecked((int) 0xC0000000)));
+ Assert.AreEqual(0xFFFFFFFEu, CodedOutputStream.EncodeZigZag32(0x7FFFFFFF));
+ Assert.AreEqual(0xFFFFFFFFu, CodedOutputStream.EncodeZigZag32(unchecked((int) 0x80000000)));
+ }
+
+ [Test]
+ public void EncodeZigZag64()
+ {
+ Assert.AreEqual(0u, CodedOutputStream.EncodeZigZag64(0));
+ Assert.AreEqual(1u, CodedOutputStream.EncodeZigZag64(-1));
+ Assert.AreEqual(2u, CodedOutputStream.EncodeZigZag64(1));
+ Assert.AreEqual(3u, CodedOutputStream.EncodeZigZag64(-2));
+ Assert.AreEqual(0x000000007FFFFFFEuL,
+ CodedOutputStream.EncodeZigZag64(unchecked((long) 0x000000003FFFFFFFUL)));
+ Assert.AreEqual(0x000000007FFFFFFFuL,
+ CodedOutputStream.EncodeZigZag64(unchecked((long) 0xFFFFFFFFC0000000UL)));
+ Assert.AreEqual(0x00000000FFFFFFFEuL,
+ CodedOutputStream.EncodeZigZag64(unchecked((long) 0x000000007FFFFFFFUL)));
+ Assert.AreEqual(0x00000000FFFFFFFFuL,
+ CodedOutputStream.EncodeZigZag64(unchecked((long) 0xFFFFFFFF80000000UL)));
+ Assert.AreEqual(0xFFFFFFFFFFFFFFFEL,
+ CodedOutputStream.EncodeZigZag64(unchecked((long) 0x7FFFFFFFFFFFFFFFUL)));
+ Assert.AreEqual(0xFFFFFFFFFFFFFFFFL,
+ CodedOutputStream.EncodeZigZag64(unchecked((long) 0x8000000000000000UL)));
+ }
+
+ [Test]
+ public void RoundTripZigZag32()
+ {
+ // Some easier-to-verify round-trip tests. The inputs (other than 0, 1, -1)
+ // were chosen semi-randomly via keyboard bashing.
+ Assert.AreEqual(0, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(0)));
+ Assert.AreEqual(1, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(1)));
+ Assert.AreEqual(-1, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(-1)));
+ Assert.AreEqual(14927, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(14927)));
+ Assert.AreEqual(-3612, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(-3612)));
+ }
+
+ [Test]
+ public void RoundTripZigZag64()
+ {
+ Assert.AreEqual(0, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(0)));
+ Assert.AreEqual(1, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(1)));
+ Assert.AreEqual(-1, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(-1)));
+ Assert.AreEqual(14927, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(14927)));
+ Assert.AreEqual(-3612, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(-3612)));
+
+ Assert.AreEqual(856912304801416L,
+ CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(856912304801416L)));
+ Assert.AreEqual(-75123905439571256L,
+ CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(-75123905439571256L)));
+ }
+
+ [Test]
+ public void TestNegativeEnumNoTag()
+ {
+ Assert.AreEqual(10, CodedOutputStream.ComputeInt32Size(-2));
+ Assert.AreEqual(10, CodedOutputStream.ComputeEnumSize((int) SampleEnum.NegativeValue));
+
+ byte[] bytes = new byte[10];
+ CodedOutputStream output = new CodedOutputStream(bytes);
+ output.WriteEnum((int) SampleEnum.NegativeValue);
+
+ Assert.AreEqual(0, output.SpaceLeft);
+ Assert.AreEqual("FE-FF-FF-FF-FF-FF-FF-FF-FF-01", BitConverter.ToString(bytes));
+ }
+
+ [Test]
+ public void TestCodedInputOutputPosition()
+ {
+ byte[] content = new byte[110];
+ for (int i = 0; i < content.Length; i++)
+ content[i] = (byte)i;
+
+ byte[] child = new byte[120];
+ {
+ MemoryStream ms = new MemoryStream(child);
+ CodedOutputStream cout = new CodedOutputStream(ms, 20);
+ // Field 11: numeric value: 500
+ cout.WriteTag(11, WireFormat.WireType.Varint);
+ Assert.AreEqual(1, cout.Position);
+ cout.WriteInt32(500);
+ Assert.AreEqual(3, cout.Position);
+ //Field 12: length delimited 120 bytes
+ cout.WriteTag(12, WireFormat.WireType.LengthDelimited);
+ Assert.AreEqual(4, cout.Position);
+ cout.WriteBytes(ByteString.CopyFrom(content));
+ Assert.AreEqual(115, cout.Position);
+ // Field 13: fixed numeric value: 501
+ cout.WriteTag(13, WireFormat.WireType.Fixed32);
+ Assert.AreEqual(116, cout.Position);
+ cout.WriteSFixed32(501);
+ Assert.AreEqual(120, cout.Position);
+ cout.Flush();
+ }
+
+ byte[] bytes = new byte[130];
+ {
+ CodedOutputStream cout = new CodedOutputStream(bytes);
+ // Field 1: numeric value: 500
+ cout.WriteTag(1, WireFormat.WireType.Varint);
+ Assert.AreEqual(1, cout.Position);
+ cout.WriteInt32(500);
+ Assert.AreEqual(3, cout.Position);
+ //Field 2: length delimited 120 bytes
+ cout.WriteTag(2, WireFormat.WireType.LengthDelimited);
+ Assert.AreEqual(4, cout.Position);
+ cout.WriteBytes(ByteString.CopyFrom(child));
+ Assert.AreEqual(125, cout.Position);
+ // Field 3: fixed numeric value: 500
+ cout.WriteTag(3, WireFormat.WireType.Fixed32);
+ Assert.AreEqual(126, cout.Position);
+ cout.WriteSFixed32(501);
+ Assert.AreEqual(130, cout.Position);
+ cout.Flush();
+ }
+ // Now test Input stream:
+ {
+ CodedInputStream cin = new CodedInputStream(new MemoryStream(bytes), new byte[50], 0, 0, false);
+ Assert.AreEqual(0, cin.Position);
+ // Field 1:
+ uint tag = cin.ReadTag();
+ Assert.AreEqual(1, tag >> 3);
+ Assert.AreEqual(1, cin.Position);
+ Assert.AreEqual(500, cin.ReadInt32());
+ Assert.AreEqual(3, cin.Position);
+ //Field 2:
+ tag = cin.ReadTag();
+ Assert.AreEqual(2, tag >> 3);
+ Assert.AreEqual(4, cin.Position);
+ int childlen = cin.ReadLength();
+ Assert.AreEqual(120, childlen);
+ Assert.AreEqual(5, cin.Position);
+ int oldlimit = cin.PushLimit((int)childlen);
+ Assert.AreEqual(5, cin.Position);
+ // Now we are reading child message
+ {
+ // Field 11: numeric value: 500
+ tag = cin.ReadTag();
+ Assert.AreEqual(11, tag >> 3);
+ Assert.AreEqual(6, cin.Position);
+ Assert.AreEqual(500, cin.ReadInt32());
+ Assert.AreEqual(8, cin.Position);
+ //Field 12: length delimited 120 bytes
+ tag = cin.ReadTag();
+ Assert.AreEqual(12, tag >> 3);
+ Assert.AreEqual(9, cin.Position);
+ ByteString bstr = cin.ReadBytes();
+ Assert.AreEqual(110, bstr.Length);
+ Assert.AreEqual((byte) 109, bstr[109]);
+ Assert.AreEqual(120, cin.Position);
+ // Field 13: fixed numeric value: 501
+ tag = cin.ReadTag();
+ Assert.AreEqual(13, tag >> 3);
+ // ROK - Previously broken here, this returned 126 failing to account for bufferSizeAfterLimit
+ Assert.AreEqual(121, cin.Position);
+ Assert.AreEqual(501, cin.ReadSFixed32());
+ Assert.AreEqual(125, cin.Position);
+ Assert.IsTrue(cin.IsAtEnd);
+ }
+ cin.PopLimit(oldlimit);
+ Assert.AreEqual(125, cin.Position);
+ // Field 3: fixed numeric value: 501
+ tag = cin.ReadTag();
+ Assert.AreEqual(3, tag >> 3);
+ Assert.AreEqual(126, cin.Position);
+ Assert.AreEqual(501, cin.ReadSFixed32());
+ Assert.AreEqual(130, cin.Position);
+ Assert.IsTrue(cin.IsAtEnd);
+ }
+ }
+
+ [Test]
+ public void Dispose_DisposesUnderlyingStream()
+ {
+ var memoryStream = new MemoryStream();
+ Assert.IsTrue(memoryStream.CanWrite);
+ using (var cos = new CodedOutputStream(memoryStream))
+ {
+ cos.WriteRawByte(0);
+ Assert.AreEqual(0, memoryStream.Position); // Not flushed yet
+ }
+ Assert.AreEqual(1, memoryStream.ToArray().Length); // Flushed data from CodedOutputStream to MemoryStream
+ Assert.IsFalse(memoryStream.CanWrite); // Disposed
+ }
+
+ [Test]
+ public void Dispose_WithLeaveOpen()
+ {
+ var memoryStream = new MemoryStream();
+ Assert.IsTrue(memoryStream.CanWrite);
+ using (var cos = new CodedOutputStream(memoryStream, true))
+ {
+ cos.WriteRawByte(0);
+ Assert.AreEqual(0, memoryStream.Position); // Not flushed yet
+ }
+ Assert.AreEqual(1, memoryStream.Position); // Flushed data from CodedOutputStream to MemoryStream
+ Assert.IsTrue(memoryStream.CanWrite); // We left the stream open
+ }
+ }
+} \ No newline at end of file
diff --git a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Collections/MapFieldTest.cs b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Collections/MapFieldTest.cs
new file mode 100644
index 00000000..9c845907
--- /dev/null
+++ b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Collections/MapFieldTest.cs
@@ -0,0 +1,532 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2015 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+using System;
+using System.Collections.Generic;
+using Google.Protobuf.TestProtos;
+using NUnit.Framework;
+using System.Collections;
+using System.Linq;
+
+namespace Google.Protobuf.Collections
+{
+ /// <summary>
+ /// Tests for MapField which aren't reliant on the encoded format -
+ /// tests for serialization/deserialization are part of GeneratedMessageTest.
+ /// </summary>
+ public class MapFieldTest
+ {
+ [Test]
+ public void Clone_ClonesMessages()
+ {
+ var message = new ForeignMessage { C = 20 };
+ var map = new MapField<string, ForeignMessage> { { "x", message } };
+ var clone = map.Clone();
+ map["x"].C = 30;
+ Assert.AreEqual(20, clone["x"].C);
+ }
+
+ [Test]
+ public void NullValuesProhibited()
+ {
+ TestNullValues<int?>(0);
+ TestNullValues("");
+ TestNullValues(new TestAllTypes());
+ }
+
+ private void TestNullValues<T>(T nonNullValue)
+ {
+ var map = new MapField<int, T>();
+ var nullValue = (T) (object) null;
+ Assert.Throws<ArgumentNullException>(() => map.Add(0, nullValue));
+ Assert.Throws<ArgumentNullException>(() => map[0] = nullValue);
+ map.Add(1, nonNullValue);
+ map[1] = nonNullValue;
+ }
+
+ [Test]
+ public void Add_ForbidsNullKeys()
+ {
+ var map = new MapField<string, ForeignMessage>();
+ Assert.Throws<ArgumentNullException>(() => map.Add(null, new ForeignMessage()));
+ }
+
+ [Test]
+ public void Indexer_ForbidsNullKeys()
+ {
+ var map = new MapField<string, ForeignMessage>();
+ Assert.Throws<ArgumentNullException>(() => map[null] = new ForeignMessage());
+ }
+
+ [Test]
+ public void AddPreservesInsertionOrder()
+ {
+ var map = new MapField<string, string>();
+ map.Add("a", "v1");
+ map.Add("b", "v2");
+ map.Add("c", "v3");
+ map.Remove("b");
+ map.Add("d", "v4");
+ CollectionAssert.AreEqual(new[] { "a", "c", "d" }, map.Keys);
+ CollectionAssert.AreEqual(new[] { "v1", "v3", "v4" }, map.Values);
+ }
+
+ [Test]
+ public void EqualityIsOrderInsensitive()
+ {
+ var map1 = new MapField<string, string>();
+ map1.Add("a", "v1");
+ map1.Add("b", "v2");
+
+ var map2 = new MapField<string, string>();
+ map2.Add("b", "v2");
+ map2.Add("a", "v1");
+
+ EqualityTester.AssertEquality(map1, map2);
+ }
+
+ [Test]
+ public void EqualityIsKeySensitive()
+ {
+ var map1 = new MapField<string, string>();
+ map1.Add("first key", "v1");
+ map1.Add("second key", "v2");
+
+ var map2 = new MapField<string, string>();
+ map2.Add("third key", "v1");
+ map2.Add("fourth key", "v2");
+
+ EqualityTester.AssertInequality(map1, map2);
+ }
+
+ [Test]
+ public void Equality_Simple()
+ {
+ var map = new MapField<string, string>();
+ EqualityTester.AssertEquality(map, map);
+ EqualityTester.AssertInequality(map, null);
+ Assert.IsFalse(map.Equals(new object()));
+ }
+
+ [Test]
+ public void EqualityIsValueSensitive()
+ {
+ // Note: Without some care, it's a little easier than one might
+ // hope to see hash collisions, but only in some environments...
+ var map1 = new MapField<string, string>();
+ map1.Add("a", "first value");
+ map1.Add("b", "second value");
+
+ var map2 = new MapField<string, string>();
+ map2.Add("a", "third value");
+ map2.Add("b", "fourth value");
+
+ EqualityTester.AssertInequality(map1, map2);
+ }
+
+ [Test]
+ public void Add_Dictionary()
+ {
+ var map1 = new MapField<string, string>
+ {
+ { "x", "y" },
+ { "a", "b" }
+ };
+ var map2 = new MapField<string, string>
+ {
+ { "before", "" },
+ map1,
+ { "after", "" }
+ };
+ var expected = new MapField<string, string>
+ {
+ { "before", "" },
+ { "x", "y" },
+ { "a", "b" },
+ { "after", "" }
+ };
+ Assert.AreEqual(expected, map2);
+ CollectionAssert.AreEqual(new[] { "before", "x", "a", "after" }, map2.Keys);
+ }
+
+ // General IDictionary<TKey, TValue> behavior tests
+ [Test]
+ public void Add_KeyAlreadyExists()
+ {
+ var map = new MapField<string, string>();
+ map.Add("foo", "bar");
+ Assert.Throws<ArgumentException>(() => map.Add("foo", "baz"));
+ }
+
+ [Test]
+ public void Add_Pair()
+ {
+ var map = new MapField<string, string>();
+ ICollection<KeyValuePair<string, string>> collection = map;
+ collection.Add(NewKeyValuePair("x", "y"));
+ Assert.AreEqual("y", map["x"]);
+ Assert.Throws<ArgumentException>(() => collection.Add(NewKeyValuePair("x", "z")));
+ }
+
+ [Test]
+ public void Contains_Pair()
+ {
+ var map = new MapField<string, string> { { "x", "y" } };
+ ICollection<KeyValuePair<string, string>> collection = map;
+ Assert.IsTrue(collection.Contains(NewKeyValuePair("x", "y")));
+ Assert.IsFalse(collection.Contains(NewKeyValuePair("x", "z")));
+ Assert.IsFalse(collection.Contains(NewKeyValuePair("z", "y")));
+ }
+
+ [Test]
+ public void Remove_Key()
+ {
+ var map = new MapField<string, string>();
+ map.Add("foo", "bar");
+ Assert.AreEqual(1, map.Count);
+ Assert.IsFalse(map.Remove("missing"));
+ Assert.AreEqual(1, map.Count);
+ Assert.IsTrue(map.Remove("foo"));
+ Assert.AreEqual(0, map.Count);
+ Assert.Throws<ArgumentNullException>(() => map.Remove(null));
+ }
+
+ [Test]
+ public void Remove_Pair()
+ {
+ var map = new MapField<string, string>();
+ map.Add("foo", "bar");
+ ICollection<KeyValuePair<string, string>> collection = map;
+ Assert.AreEqual(1, map.Count);
+ Assert.IsFalse(collection.Remove(NewKeyValuePair("wrong key", "bar")));
+ Assert.AreEqual(1, map.Count);
+ Assert.IsFalse(collection.Remove(NewKeyValuePair("foo", "wrong value")));
+ Assert.AreEqual(1, map.Count);
+ Assert.IsTrue(collection.Remove(NewKeyValuePair("foo", "bar")));
+ Assert.AreEqual(0, map.Count);
+ Assert.Throws<ArgumentException>(() => collection.Remove(new KeyValuePair<string, string>(null, "")));
+ }
+
+ [Test]
+ public void CopyTo_Pair()
+ {
+ var map = new MapField<string, string>();
+ map.Add("foo", "bar");
+ ICollection<KeyValuePair<string, string>> collection = map;
+ KeyValuePair<string, string>[] array = new KeyValuePair<string, string>[3];
+ collection.CopyTo(array, 1);
+ Assert.AreEqual(NewKeyValuePair("foo", "bar"), array[1]);
+ }
+
+ [Test]
+ public void Clear()
+ {
+ var map = new MapField<string, string> { { "x", "y" } };
+ Assert.AreEqual(1, map.Count);
+ map.Clear();
+ Assert.AreEqual(0, map.Count);
+ map.Add("x", "y");
+ Assert.AreEqual(1, map.Count);
+ }
+
+ [Test]
+ public void Indexer_Get()
+ {
+ var map = new MapField<string, string> { { "x", "y" } };
+ Assert.AreEqual("y", map["x"]);
+ Assert.Throws<KeyNotFoundException>(() => { var ignored = map["z"]; });
+ }
+
+ [Test]
+ public void Indexer_Set()
+ {
+ var map = new MapField<string, string>();
+ map["x"] = "y";
+ Assert.AreEqual("y", map["x"]);
+ map["x"] = "z"; // This won't throw, unlike Add.
+ Assert.AreEqual("z", map["x"]);
+ }
+
+ [Test]
+ public void GetEnumerator_NonGeneric()
+ {
+ IEnumerable map = new MapField<string, string> { { "x", "y" } };
+ CollectionAssert.AreEqual(new[] { new KeyValuePair<string, string>("x", "y") },
+ map.Cast<object>().ToList());
+ }
+
+ // Test for the explicitly-implemented non-generic IDictionary interface
+ [Test]
+ public void IDictionary_GetEnumerator()
+ {
+ IDictionary map = new MapField<string, string> { { "x", "y" } };
+ var enumerator = map.GetEnumerator();
+
+ // Commented assertions show an ideal situation - it looks like
+ // the LinkedList enumerator doesn't throw when you ask for the current entry
+ // at an inappropriate time; fixing this would be more work than it's worth.
+ // Assert.Throws<InvalidOperationException>(() => enumerator.Current.GetHashCode());
+ Assert.IsTrue(enumerator.MoveNext());
+ Assert.AreEqual("x", enumerator.Key);
+ Assert.AreEqual("y", enumerator.Value);
+ Assert.AreEqual(new DictionaryEntry("x", "y"), enumerator.Current);
+ Assert.AreEqual(new DictionaryEntry("x", "y"), enumerator.Entry);
+ Assert.IsFalse(enumerator.MoveNext());
+ // Assert.Throws<InvalidOperationException>(() => enumerator.Current.GetHashCode());
+ enumerator.Reset();
+ // Assert.Throws<InvalidOperationException>(() => enumerator.Current.GetHashCode());
+ Assert.IsTrue(enumerator.MoveNext());
+ Assert.AreEqual("x", enumerator.Key); // Assume the rest are okay
+ }
+
+ [Test]
+ public void IDictionary_Add()
+ {
+ var map = new MapField<string, string> { { "x", "y" } };
+ IDictionary dictionary = map;
+ dictionary.Add("a", "b");
+ Assert.AreEqual("b", map["a"]);
+ Assert.Throws<ArgumentException>(() => dictionary.Add("a", "duplicate"));
+ Assert.Throws<InvalidCastException>(() => dictionary.Add(new object(), "key is bad"));
+ Assert.Throws<InvalidCastException>(() => dictionary.Add("value is bad", new object()));
+ }
+
+ [Test]
+ public void IDictionary_Contains()
+ {
+ var map = new MapField<string, string> { { "x", "y" } };
+ IDictionary dictionary = map;
+
+ Assert.IsFalse(dictionary.Contains("a"));
+ Assert.IsFalse(dictionary.Contains(5));
+ // Surprising, but IDictionary.Contains is only about keys.
+ Assert.IsFalse(dictionary.Contains(new DictionaryEntry("x", "y")));
+ Assert.IsTrue(dictionary.Contains("x"));
+ }
+
+ [Test]
+ public void IDictionary_Remove()
+ {
+ var map = new MapField<string, string> { { "x", "y" } };
+ IDictionary dictionary = map;
+ dictionary.Remove("a");
+ Assert.AreEqual(1, dictionary.Count);
+ dictionary.Remove(5);
+ Assert.AreEqual(1, dictionary.Count);
+ dictionary.Remove(new DictionaryEntry("x", "y"));
+ Assert.AreEqual(1, dictionary.Count);
+ dictionary.Remove("x");
+ Assert.AreEqual(0, dictionary.Count);
+ Assert.Throws<ArgumentNullException>(() => dictionary.Remove(null));
+ }
+
+ [Test]
+ public void IDictionary_CopyTo()
+ {
+ var map = new MapField<string, string> { { "x", "y" } };
+ IDictionary dictionary = map;
+ var array = new DictionaryEntry[3];
+ dictionary.CopyTo(array, 1);
+ CollectionAssert.AreEqual(new[] { default(DictionaryEntry), new DictionaryEntry("x", "y"), default(DictionaryEntry) },
+ array);
+ var objectArray = new object[3];
+ dictionary.CopyTo(objectArray, 1);
+ CollectionAssert.AreEqual(new object[] { null, new DictionaryEntry("x", "y"), null },
+ objectArray);
+ }
+
+ [Test]
+ public void IDictionary_IsFixedSize()
+ {
+ var map = new MapField<string, string> { { "x", "y" } };
+ IDictionary dictionary = map;
+ Assert.IsFalse(dictionary.IsFixedSize);
+ }
+
+ [Test]
+ public void IDictionary_Keys()
+ {
+ IDictionary dictionary = new MapField<string, string> { { "x", "y" } };
+ CollectionAssert.AreEqual(new[] { "x" }, dictionary.Keys);
+ }
+
+ [Test]
+ public void IDictionary_Values()
+ {
+ IDictionary dictionary = new MapField<string, string> { { "x", "y" } };
+ CollectionAssert.AreEqual(new[] { "y" }, dictionary.Values);
+ }
+
+ [Test]
+ public void IDictionary_IsSynchronized()
+ {
+ IDictionary dictionary = new MapField<string, string> { { "x", "y" } };
+ Assert.IsFalse(dictionary.IsSynchronized);
+ }
+
+ [Test]
+ public void IDictionary_SyncRoot()
+ {
+ IDictionary dictionary = new MapField<string, string> { { "x", "y" } };
+ Assert.AreSame(dictionary, dictionary.SyncRoot);
+ }
+
+ [Test]
+ public void IDictionary_Indexer_Get()
+ {
+ IDictionary dictionary = new MapField<string, string> { { "x", "y" } };
+ Assert.AreEqual("y", dictionary["x"]);
+ Assert.IsNull(dictionary["a"]);
+ Assert.IsNull(dictionary[5]);
+ Assert.Throws<ArgumentNullException>(() => dictionary[null].GetHashCode());
+ }
+
+ [Test]
+ public void IDictionary_Indexer_Set()
+ {
+ var map = new MapField<string, string> { { "x", "y" } };
+ IDictionary dictionary = map;
+ map["a"] = "b";
+ Assert.AreEqual("b", map["a"]);
+ map["a"] = "c";
+ Assert.AreEqual("c", map["a"]);
+ Assert.Throws<InvalidCastException>(() => dictionary[5] = "x");
+ Assert.Throws<InvalidCastException>(() => dictionary["x"] = 5);
+ Assert.Throws<ArgumentNullException>(() => dictionary[null] = "z");
+ Assert.Throws<ArgumentNullException>(() => dictionary["x"] = null);
+ }
+
+ [Test]
+ public void KeysReturnsLiveView()
+ {
+ var map = new MapField<string, string>();
+ var keys = map.Keys;
+ CollectionAssert.AreEqual(new string[0], keys);
+ map["foo"] = "bar";
+ map["x"] = "y";
+ CollectionAssert.AreEqual(new[] { "foo", "x" }, keys);
+ }
+
+ [Test]
+ public void ValuesReturnsLiveView()
+ {
+ var map = new MapField<string, string>();
+ var values = map.Values;
+ CollectionAssert.AreEqual(new string[0], values);
+ map["foo"] = "bar";
+ map["x"] = "y";
+ CollectionAssert.AreEqual(new[] { "bar", "y" }, values);
+ }
+
+ // Just test keys - we know the implementation is the same for values
+ [Test]
+ public void ViewsAreReadOnly()
+ {
+ var map = new MapField<string, string>();
+ var keys = map.Keys;
+ Assert.IsTrue(keys.IsReadOnly);
+ Assert.Throws<NotSupportedException>(() => keys.Clear());
+ Assert.Throws<NotSupportedException>(() => keys.Remove("a"));
+ Assert.Throws<NotSupportedException>(() => keys.Add("a"));
+ }
+
+ // Just test keys - we know the implementation is the same for values
+ [Test]
+ public void ViewCopyTo()
+ {
+ var map = new MapField<string, string> { { "foo", "bar" }, { "x", "y" } };
+ var keys = map.Keys;
+ var array = new string[4];
+ Assert.Throws<ArgumentException>(() => keys.CopyTo(array, 3));
+ Assert.Throws<ArgumentOutOfRangeException>(() => keys.CopyTo(array, -1));
+ keys.CopyTo(array, 1);
+ CollectionAssert.AreEqual(new[] { null, "foo", "x", null }, array);
+ }
+
+ // Just test keys - we know the implementation is the same for values
+ [Test]
+ public void NonGenericViewCopyTo()
+ {
+ IDictionary map = new MapField<string, string> { { "foo", "bar" }, { "x", "y" } };
+ ICollection keys = map.Keys;
+ // Note the use of the Array type here rather than string[]
+ Array array = new string[4];
+ Assert.Throws<ArgumentException>(() => keys.CopyTo(array, 3));
+ Assert.Throws<ArgumentOutOfRangeException>(() => keys.CopyTo(array, -1));
+ keys.CopyTo(array, 1);
+ CollectionAssert.AreEqual(new[] { null, "foo", "x", null }, array);
+ }
+
+ [Test]
+ public void KeysContains()
+ {
+ var map = new MapField<string, string> { { "foo", "bar" }, { "x", "y" } };
+ var keys = map.Keys;
+ Assert.IsTrue(keys.Contains("foo"));
+ Assert.IsFalse(keys.Contains("bar")); // It's a value!
+ Assert.IsFalse(keys.Contains("1"));
+ // Keys can't be null, so we should prevent contains check
+ Assert.Throws<ArgumentNullException>(() => keys.Contains(null));
+ }
+
+ [Test]
+ public void ValuesContains()
+ {
+ var map = new MapField<string, string> { { "foo", "bar" }, { "x", "y" } };
+ var values = map.Values;
+ Assert.IsTrue(values.Contains("bar"));
+ Assert.IsFalse(values.Contains("foo")); // It's a key!
+ Assert.IsFalse(values.Contains("1"));
+ // Values can be null, so this makes sense
+ Assert.IsFalse(values.Contains(null));
+ }
+
+ [Test]
+ public void ToString_StringToString()
+ {
+ var map = new MapField<string, string> { { "foo", "bar" }, { "x", "y" } };
+ Assert.AreEqual("{ \"foo\": \"bar\", \"x\": \"y\" }", map.ToString());
+ }
+
+ [Test]
+ public void ToString_UnsupportedKeyType()
+ {
+ var map = new MapField<byte, string> { { 10, "foo" } };
+ Assert.Throws<ArgumentException>(() => map.ToString());
+ }
+
+ private static KeyValuePair<TKey, TValue> NewKeyValuePair<TKey, TValue>(TKey key, TValue value)
+ {
+ return new KeyValuePair<TKey, TValue>(key, value);
+ }
+ }
+}
diff --git a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Collections/RepeatedFieldTest.cs b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Collections/RepeatedFieldTest.cs
new file mode 100644
index 00000000..6852f75f
--- /dev/null
+++ b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Collections/RepeatedFieldTest.cs
@@ -0,0 +1,746 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2015 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Text;
+using Google.Protobuf.TestProtos;
+using Google.Protobuf.WellKnownTypes;
+using NUnit.Framework;
+
+namespace Google.Protobuf.Collections
+{
+ public class RepeatedFieldTest
+ {
+ [Test]
+ public void NullValuesRejected()
+ {
+ var list = new RepeatedField<string>();
+ Assert.Throws<ArgumentNullException>(() => list.Add((string)null));
+ Assert.Throws<ArgumentNullException>(() => list.Add((IEnumerable<string>)null));
+ Assert.Throws<ArgumentNullException>(() => list.Add((RepeatedField<string>)null));
+ Assert.Throws<ArgumentNullException>(() => list.Contains(null));
+ Assert.Throws<ArgumentNullException>(() => list.IndexOf(null));
+ }
+
+ [Test]
+ public void Add_SingleItem()
+ {
+ var list = new RepeatedField<string>();
+ list.Add("foo");
+ Assert.AreEqual(1, list.Count);
+ Assert.AreEqual("foo", list[0]);
+ }
+
+ [Test]
+ public void Add_Sequence()
+ {
+ var list = new RepeatedField<string>();
+ list.Add(new[] { "foo", "bar" });
+ Assert.AreEqual(2, list.Count);
+ Assert.AreEqual("foo", list[0]);
+ Assert.AreEqual("bar", list[1]);
+ }
+
+ [Test]
+ public void AddRange_SlowPath()
+ {
+ var list = new RepeatedField<string>();
+ list.AddRange(new[] { "foo", "bar" }.Select(x => x));
+ Assert.AreEqual(2, list.Count);
+ Assert.AreEqual("foo", list[0]);
+ Assert.AreEqual("bar", list[1]);
+ }
+
+ [Test]
+ public void AddRange_SlowPath_NullsProhibited_ReferenceType()
+ {
+ var list = new RepeatedField<string>();
+ // It's okay for this to throw ArgumentNullException if necessary.
+ // It's not ideal, but not awful.
+ Assert.Catch<ArgumentException>(() => list.AddRange(new[] { "foo", null }.Select(x => x)));
+ }
+
+ [Test]
+ public void AddRange_SlowPath_NullsProhibited_NullableValueType()
+ {
+ var list = new RepeatedField<int?>();
+ // It's okay for this to throw ArgumentNullException if necessary.
+ // It's not ideal, but not awful.
+ Assert.Catch<ArgumentException>(() => list.AddRange(new[] { 20, (int?)null }.Select(x => x)));
+ }
+
+ [Test]
+ public void AddRange_Optimized_NonNullableValueType()
+ {
+ var list = new RepeatedField<int>();
+ list.AddRange(new List<int> { 20, 30 });
+ Assert.AreEqual(2, list.Count);
+ Assert.AreEqual(20, list[0]);
+ Assert.AreEqual(30, list[1]);
+ }
+
+ [Test]
+ public void AddRange_Optimized_ReferenceType()
+ {
+ var list = new RepeatedField<string>();
+ list.AddRange(new List<string> { "foo", "bar" });
+ Assert.AreEqual(2, list.Count);
+ Assert.AreEqual("foo", list[0]);
+ Assert.AreEqual("bar", list[1]);
+ }
+
+ [Test]
+ public void AddRange_Optimized_NullableValueType()
+ {
+ var list = new RepeatedField<int?>();
+ list.AddRange(new List<int?> { 20, 30 });
+ Assert.AreEqual(2, list.Count);
+ Assert.AreEqual((int?) 20, list[0]);
+ Assert.AreEqual((int?) 30, list[1]);
+ }
+
+ [Test]
+ public void AddRange_Optimized_NullsProhibited_ReferenceType()
+ {
+ // We don't just trust that a collection with a nullable element type doesn't contain nulls
+ var list = new RepeatedField<string>();
+ // It's okay for this to throw ArgumentNullException if necessary.
+ // It's not ideal, but not awful.
+ Assert.Catch<ArgumentException>(() => list.AddRange(new List<string> { "foo", null }));
+ }
+
+ [Test]
+ public void AddRange_Optimized_NullsProhibited_NullableValueType()
+ {
+ // We don't just trust that a collection with a nullable element type doesn't contain nulls
+ var list = new RepeatedField<int?>();
+ // It's okay for this to throw ArgumentNullException if necessary.
+ // It's not ideal, but not awful.
+ Assert.Catch<ArgumentException>(() => list.AddRange(new List<int?> { 20, null }));
+ }
+
+ [Test]
+ public void AddRange_AlreadyNotEmpty()
+ {
+ var list = new RepeatedField<int> { 1, 2, 3 };
+ list.AddRange(new List<int> { 4, 5, 6 });
+ CollectionAssert.AreEqual(new[] { 1, 2, 3, 4, 5, 6 }, list);
+ }
+
+ [Test]
+ public void AddRange_RepeatedField()
+ {
+ var list = new RepeatedField<string> { "original" };
+ list.AddRange(new RepeatedField<string> { "foo", "bar" });
+ Assert.AreEqual(3, list.Count);
+ Assert.AreEqual("original", list[0]);
+ Assert.AreEqual("foo", list[1]);
+ Assert.AreEqual("bar", list[2]);
+ }
+
+ [Test]
+ public void RemoveAt_Valid()
+ {
+ var list = new RepeatedField<string> { "first", "second", "third" };
+ list.RemoveAt(1);
+ CollectionAssert.AreEqual(new[] { "first", "third" }, list);
+ // Just check that these don't throw...
+ list.RemoveAt(list.Count - 1); // Now the count will be 1...
+ list.RemoveAt(0);
+ Assert.AreEqual(0, list.Count);
+ }
+
+ [Test]
+ public void RemoveAt_Invalid()
+ {
+ var list = new RepeatedField<string> { "first", "second", "third" };
+ Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(-1));
+ Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(3));
+ }
+
+ [Test]
+ public void Insert_Valid()
+ {
+ var list = new RepeatedField<string> { "first", "second" };
+ list.Insert(1, "middle");
+ CollectionAssert.AreEqual(new[] { "first", "middle", "second" }, list);
+ list.Insert(3, "end");
+ CollectionAssert.AreEqual(new[] { "first", "middle", "second", "end" }, list);
+ list.Insert(0, "start");
+ CollectionAssert.AreEqual(new[] { "start", "first", "middle", "second", "end" }, list);
+ }
+
+ [Test]
+ public void Insert_Invalid()
+ {
+ var list = new RepeatedField<string> { "first", "second" };
+ Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(-1, "foo"));
+ Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(3, "foo"));
+ Assert.Throws<ArgumentNullException>(() => list.Insert(0, null));
+ }
+
+ [Test]
+ public void Equals_RepeatedField()
+ {
+ var list = new RepeatedField<string> { "first", "second" };
+ Assert.IsFalse(list.Equals((RepeatedField<string>) null));
+ Assert.IsTrue(list.Equals(list));
+ Assert.IsFalse(list.Equals(new RepeatedField<string> { "first", "third" }));
+ Assert.IsFalse(list.Equals(new RepeatedField<string> { "first" }));
+ Assert.IsTrue(list.Equals(new RepeatedField<string> { "first", "second" }));
+ }
+
+ [Test]
+ public void Equals_Object()
+ {
+ var list = new RepeatedField<string> { "first", "second" };
+ Assert.IsFalse(list.Equals((object) null));
+ Assert.IsTrue(list.Equals((object) list));
+ Assert.IsFalse(list.Equals((object) new RepeatedField<string> { "first", "third" }));
+ Assert.IsFalse(list.Equals((object) new RepeatedField<string> { "first" }));
+ Assert.IsTrue(list.Equals((object) new RepeatedField<string> { "first", "second" }));
+ Assert.IsFalse(list.Equals(new object()));
+ }
+
+ [Test]
+ public void GetEnumerator_GenericInterface()
+ {
+ IEnumerable<string> list = new RepeatedField<string> { "first", "second" };
+ // Select gets rid of the optimizations in ToList...
+ CollectionAssert.AreEqual(new[] { "first", "second" }, list.Select(x => x).ToList());
+ }
+
+ [Test]
+ public void GetEnumerator_NonGenericInterface()
+ {
+ IEnumerable list = new RepeatedField<string> { "first", "second" };
+ CollectionAssert.AreEqual(new[] { "first", "second" }, list.Cast<object>().ToList());
+ }
+
+ [Test]
+ public void CopyTo()
+ {
+ var list = new RepeatedField<string> { "first", "second" };
+ string[] stringArray = new string[4];
+ list.CopyTo(stringArray, 1);
+ CollectionAssert.AreEqual(new[] { null, "first", "second", null }, stringArray);
+ }
+
+ [Test]
+ public void Indexer_Get()
+ {
+ var list = new RepeatedField<string> { "first", "second" };
+ Assert.AreEqual("first", list[0]);
+ Assert.AreEqual("second", list[1]);
+ Assert.Throws<ArgumentOutOfRangeException>(() => list[-1].GetHashCode());
+ Assert.Throws<ArgumentOutOfRangeException>(() => list[2].GetHashCode());
+ }
+
+ [Test]
+ public void Indexer_Set()
+ {
+ var list = new RepeatedField<string> { "first", "second" };
+ list[0] = "changed";
+ Assert.AreEqual("changed", list[0]);
+ Assert.Throws<ArgumentNullException>(() => list[0] = null);
+ Assert.Throws<ArgumentOutOfRangeException>(() => list[-1] = "bad");
+ Assert.Throws<ArgumentOutOfRangeException>(() => list[2] = "bad");
+ }
+
+ [Test]
+ public void Clone_ReturnsMutable()
+ {
+ var list = new RepeatedField<int> { 0 };
+ var clone = list.Clone();
+ clone[0] = 1;
+ }
+
+ [Test]
+ public void Enumerator()
+ {
+ var list = new RepeatedField<string> { "first", "second" };
+ using (var enumerator = list.GetEnumerator())
+ {
+ Assert.IsTrue(enumerator.MoveNext());
+ Assert.AreEqual("first", enumerator.Current);
+ Assert.IsTrue(enumerator.MoveNext());
+ Assert.AreEqual("second", enumerator.Current);
+ Assert.IsFalse(enumerator.MoveNext());
+ Assert.IsFalse(enumerator.MoveNext());
+ }
+ }
+
+ [Test]
+ public void AddEntriesFrom_PackedInt32()
+ {
+ uint packedTag = WireFormat.MakeTag(10, WireFormat.WireType.LengthDelimited);
+ var stream = new MemoryStream();
+ var output = new CodedOutputStream(stream);
+ var length = CodedOutputStream.ComputeInt32Size(10)
+ + CodedOutputStream.ComputeInt32Size(999)
+ + CodedOutputStream.ComputeInt32Size(-1000);
+ output.WriteTag(packedTag);
+ output.WriteRawVarint32((uint) length);
+ output.WriteInt32(10);
+ output.WriteInt32(999);
+ output.WriteInt32(-1000);
+ output.Flush();
+ stream.Position = 0;
+
+ // Deliberately "expecting" a non-packed tag, but we detect that the data is
+ // actually packed.
+ uint nonPackedTag = WireFormat.MakeTag(10, WireFormat.WireType.LengthDelimited);
+ var field = new RepeatedField<int>();
+ var input = new CodedInputStream(stream);
+ input.AssertNextTag(packedTag);
+ field.AddEntriesFrom(input, FieldCodec.ForInt32(nonPackedTag));
+ CollectionAssert.AreEqual(new[] { 10, 999, -1000 }, field);
+ Assert.IsTrue(input.IsAtEnd);
+ }
+
+ [Test]
+ public void AddEntriesFrom_NonPackedInt32()
+ {
+ uint nonPackedTag = WireFormat.MakeTag(10, WireFormat.WireType.Varint);
+ var stream = new MemoryStream();
+ var output = new CodedOutputStream(stream);
+ output.WriteTag(nonPackedTag);
+ output.WriteInt32(10);
+ output.WriteTag(nonPackedTag);
+ output.WriteInt32(999);
+ output.WriteTag(nonPackedTag);
+ output.WriteInt32(-1000); // Just for variety...
+ output.Flush();
+ stream.Position = 0;
+
+ // Deliberately "expecting" a packed tag, but we detect that the data is
+ // actually not packed.
+ uint packedTag = WireFormat.MakeTag(10, WireFormat.WireType.LengthDelimited);
+ var field = new RepeatedField<int>();
+ var input = new CodedInputStream(stream);
+ input.AssertNextTag(nonPackedTag);
+ field.AddEntriesFrom(input, FieldCodec.ForInt32(packedTag));
+ CollectionAssert.AreEqual(new[] { 10, 999, -1000 }, field);
+ Assert.IsTrue(input.IsAtEnd);
+ }
+
+ [Test]
+ public void AddEntriesFrom_String()
+ {
+ uint tag = WireFormat.MakeTag(10, WireFormat.WireType.LengthDelimited);
+ var stream = new MemoryStream();
+ var output = new CodedOutputStream(stream);
+ output.WriteTag(tag);
+ output.WriteString("Foo");
+ output.WriteTag(tag);
+ output.WriteString("");
+ output.WriteTag(tag);
+ output.WriteString("Bar");
+ output.Flush();
+ stream.Position = 0;
+
+ var field = new RepeatedField<string>();
+ var input = new CodedInputStream(stream);
+ input.AssertNextTag(tag);
+ field.AddEntriesFrom(input, FieldCodec.ForString(tag));
+ CollectionAssert.AreEqual(new[] { "Foo", "", "Bar" }, field);
+ Assert.IsTrue(input.IsAtEnd);
+ }
+
+ [Test]
+ public void AddEntriesFrom_Message()
+ {
+ var message1 = new ForeignMessage { C = 2000 };
+ var message2 = new ForeignMessage { C = -250 };
+
+ uint tag = WireFormat.MakeTag(10, WireFormat.WireType.LengthDelimited);
+ var stream = new MemoryStream();
+ var output = new CodedOutputStream(stream);
+ output.WriteTag(tag);
+ output.WriteMessage(message1);
+ output.WriteTag(tag);
+ output.WriteMessage(message2);
+ output.Flush();
+ stream.Position = 0;
+
+ var field = new RepeatedField<ForeignMessage>();
+ var input = new CodedInputStream(stream);
+ input.AssertNextTag(tag);
+ field.AddEntriesFrom(input, FieldCodec.ForMessage(tag, ForeignMessage.Parser));
+ CollectionAssert.AreEqual(new[] { message1, message2}, field);
+ Assert.IsTrue(input.IsAtEnd);
+ }
+
+ [Test]
+ public void WriteTo_PackedInt32()
+ {
+ uint tag = WireFormat.MakeTag(10, WireFormat.WireType.LengthDelimited);
+ var field = new RepeatedField<int> { 10, 1000, 1000000 };
+ var stream = new MemoryStream();
+ var output = new CodedOutputStream(stream);
+ field.WriteTo(output, FieldCodec.ForInt32(tag));
+ output.Flush();
+ stream.Position = 0;
+
+ var input = new CodedInputStream(stream);
+ input.AssertNextTag(tag);
+ var length = input.ReadLength();
+ Assert.AreEqual(10, input.ReadInt32());
+ Assert.AreEqual(1000, input.ReadInt32());
+ Assert.AreEqual(1000000, input.ReadInt32());
+ Assert.IsTrue(input.IsAtEnd);
+ Assert.AreEqual(1 + CodedOutputStream.ComputeLengthSize(length) + length, stream.Length);
+ }
+
+ [Test]
+ public void WriteTo_NonPackedInt32()
+ {
+ uint tag = WireFormat.MakeTag(10, WireFormat.WireType.Varint);
+ var field = new RepeatedField<int> { 10, 1000, 1000000};
+ var stream = new MemoryStream();
+ var output = new CodedOutputStream(stream);
+ field.WriteTo(output, FieldCodec.ForInt32(tag));
+ output.Flush();
+ stream.Position = 0;
+
+ var input = new CodedInputStream(stream);
+ input.AssertNextTag(tag);
+ Assert.AreEqual(10, input.ReadInt32());
+ input.AssertNextTag(tag);
+ Assert.AreEqual(1000, input.ReadInt32());
+ input.AssertNextTag(tag);
+ Assert.AreEqual(1000000, input.ReadInt32());
+ Assert.IsTrue(input.IsAtEnd);
+ }
+
+ [Test]
+ public void WriteTo_String()
+ {
+ uint tag = WireFormat.MakeTag(10, WireFormat.WireType.LengthDelimited);
+ var field = new RepeatedField<string> { "Foo", "", "Bar" };
+ var stream = new MemoryStream();
+ var output = new CodedOutputStream(stream);
+ field.WriteTo(output, FieldCodec.ForString(tag));
+ output.Flush();
+ stream.Position = 0;
+
+ var input = new CodedInputStream(stream);
+ input.AssertNextTag(tag);
+ Assert.AreEqual("Foo", input.ReadString());
+ input.AssertNextTag(tag);
+ Assert.AreEqual("", input.ReadString());
+ input.AssertNextTag(tag);
+ Assert.AreEqual("Bar", input.ReadString());
+ Assert.IsTrue(input.IsAtEnd);
+ }
+
+ [Test]
+ public void WriteTo_Message()
+ {
+ var message1 = new ForeignMessage { C = 20 };
+ var message2 = new ForeignMessage { C = 25 };
+ uint tag = WireFormat.MakeTag(10, WireFormat.WireType.LengthDelimited);
+ var field = new RepeatedField<ForeignMessage> { message1, message2 };
+ var stream = new MemoryStream();
+ var output = new CodedOutputStream(stream);
+ field.WriteTo(output, FieldCodec.ForMessage(tag, ForeignMessage.Parser));
+ output.Flush();
+ stream.Position = 0;
+
+ var input = new CodedInputStream(stream);
+ input.AssertNextTag(tag);
+ Assert.AreEqual(message1, input.ReadMessage(ForeignMessage.Parser));
+ input.AssertNextTag(tag);
+ Assert.AreEqual(message2, input.ReadMessage(ForeignMessage.Parser));
+ Assert.IsTrue(input.IsAtEnd);
+ }
+
+ [Test]
+ public void CalculateSize_VariableSizeNonPacked()
+ {
+ var list = new RepeatedField<int> { 1, 500, 1 };
+ var tag = WireFormat.MakeTag(1, WireFormat.WireType.Varint);
+ // 2 bytes for the first entry, 3 bytes for the second, 2 bytes for the third
+ Assert.AreEqual(7, list.CalculateSize(FieldCodec.ForInt32(tag)));
+ }
+
+ [Test]
+ public void CalculateSize_FixedSizeNonPacked()
+ {
+ var list = new RepeatedField<int> { 1, 500, 1 };
+ var tag = WireFormat.MakeTag(1, WireFormat.WireType.Fixed32);
+ // 5 bytes for the each entry
+ Assert.AreEqual(15, list.CalculateSize(FieldCodec.ForSFixed32(tag)));
+ }
+
+ [Test]
+ public void CalculateSize_VariableSizePacked()
+ {
+ var list = new RepeatedField<int> { 1, 500, 1};
+ var tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
+ // 1 byte for the tag, 1 byte for the length,
+ // 1 byte for the first entry, 2 bytes for the second, 1 byte for the third
+ Assert.AreEqual(6, list.CalculateSize(FieldCodec.ForInt32(tag)));
+ }
+
+ [Test]
+ public void CalculateSize_FixedSizePacked()
+ {
+ var list = new RepeatedField<int> { 1, 500, 1 };
+ var tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
+ // 1 byte for the tag, 1 byte for the length, 4 bytes per entry
+ Assert.AreEqual(14, list.CalculateSize(FieldCodec.ForSFixed32(tag)));
+ }
+
+ [Test]
+ public void TestNegativeEnumArray()
+ {
+ int arraySize = 1 + 1 + (11 * 5);
+ int msgSize = arraySize;
+ byte[] bytes = new byte[msgSize];
+ CodedOutputStream output = new CodedOutputStream(bytes);
+ uint tag = WireFormat.MakeTag(8, WireFormat.WireType.Varint);
+ for (int i = 0; i >= -5; i--)
+ {
+ output.WriteTag(tag);
+ output.WriteEnum(i);
+ }
+
+ Assert.AreEqual(0, output.SpaceLeft);
+
+ CodedInputStream input = new CodedInputStream(bytes);
+ tag = input.ReadTag();
+
+ RepeatedField<SampleEnum> values = new RepeatedField<SampleEnum>();
+ values.AddEntriesFrom(input, FieldCodec.ForEnum(tag, x => (int)x, x => (SampleEnum)x));
+
+ Assert.AreEqual(6, values.Count);
+ Assert.AreEqual(SampleEnum.None, values[0]);
+ Assert.AreEqual(((SampleEnum)(-1)), values[1]);
+ Assert.AreEqual(SampleEnum.NegativeValue, values[2]);
+ Assert.AreEqual(((SampleEnum)(-3)), values[3]);
+ Assert.AreEqual(((SampleEnum)(-4)), values[4]);
+ Assert.AreEqual(((SampleEnum)(-5)), values[5]);
+ }
+
+
+ [Test]
+ public void TestNegativeEnumPackedArray()
+ {
+ int arraySize = 1 + (10 * 5);
+ int msgSize = 1 + 1 + arraySize;
+ byte[] bytes = new byte[msgSize];
+ CodedOutputStream output = new CodedOutputStream(bytes);
+ // Length-delimited to show we want the packed representation
+ uint tag = WireFormat.MakeTag(8, WireFormat.WireType.LengthDelimited);
+ output.WriteTag(tag);
+ int size = 0;
+ for (int i = 0; i >= -5; i--)
+ {
+ size += CodedOutputStream.ComputeEnumSize(i);
+ }
+ output.WriteRawVarint32((uint)size);
+ for (int i = 0; i >= -5; i--)
+ {
+ output.WriteEnum(i);
+ }
+ Assert.AreEqual(0, output.SpaceLeft);
+
+ CodedInputStream input = new CodedInputStream(bytes);
+ tag = input.ReadTag();
+
+ RepeatedField<SampleEnum> values = new RepeatedField<SampleEnum>();
+ values.AddEntriesFrom(input, FieldCodec.ForEnum(tag, x => (int)x, x => (SampleEnum)x));
+
+ Assert.AreEqual(6, values.Count);
+ Assert.AreEqual(SampleEnum.None, values[0]);
+ Assert.AreEqual(((SampleEnum)(-1)), values[1]);
+ Assert.AreEqual(SampleEnum.NegativeValue, values[2]);
+ Assert.AreEqual(((SampleEnum)(-3)), values[3]);
+ Assert.AreEqual(((SampleEnum)(-4)), values[4]);
+ Assert.AreEqual(((SampleEnum)(-5)), values[5]);
+ }
+
+ // Fairly perfunctory tests for the non-generic IList implementation
+ [Test]
+ public void IList_Indexer()
+ {
+ var field = new RepeatedField<string> { "first", "second" };
+ IList list = field;
+ Assert.AreEqual("first", list[0]);
+ list[1] = "changed";
+ Assert.AreEqual("changed", field[1]);
+ }
+
+ [Test]
+ public void IList_Contains()
+ {
+ IList list = new RepeatedField<string> { "first", "second" };
+ Assert.IsTrue(list.Contains("second"));
+ Assert.IsFalse(list.Contains("third"));
+ Assert.IsFalse(list.Contains(new object()));
+ }
+
+ [Test]
+ public void IList_Add()
+ {
+ IList list = new RepeatedField<string> { "first", "second" };
+ list.Add("third");
+ CollectionAssert.AreEqual(new[] { "first", "second", "third" }, list);
+ }
+
+ [Test]
+ public void IList_Remove()
+ {
+ IList list = new RepeatedField<string> { "first", "second" };
+ list.Remove("third"); // No-op, no exception
+ list.Remove(new object()); // No-op, no exception
+ list.Remove("first");
+ CollectionAssert.AreEqual(new[] { "second" }, list);
+ }
+
+ [Test]
+ public void IList_IsFixedSize()
+ {
+ var field = new RepeatedField<string> { "first", "second" };
+ IList list = field;
+ Assert.IsFalse(list.IsFixedSize);
+ }
+
+ [Test]
+ public void IList_IndexOf()
+ {
+ IList list = new RepeatedField<string> { "first", "second" };
+ Assert.AreEqual(1, list.IndexOf("second"));
+ Assert.AreEqual(-1, list.IndexOf("third"));
+ Assert.AreEqual(-1, list.IndexOf(new object()));
+ }
+
+ [Test]
+ public void IList_SyncRoot()
+ {
+ IList list = new RepeatedField<string> { "first", "second" };
+ Assert.AreSame(list, list.SyncRoot);
+ }
+
+ [Test]
+ public void IList_CopyTo()
+ {
+ IList list = new RepeatedField<string> { "first", "second" };
+ string[] stringArray = new string[4];
+ list.CopyTo(stringArray, 1);
+ CollectionAssert.AreEqual(new[] { null, "first", "second", null }, stringArray);
+
+ object[] objectArray = new object[4];
+ list.CopyTo(objectArray, 1);
+ CollectionAssert.AreEqual(new[] { null, "first", "second", null }, objectArray);
+
+ Assert.Throws<ArrayTypeMismatchException>(() => list.CopyTo(new StringBuilder[4], 1));
+ Assert.Throws<ArrayTypeMismatchException>(() => list.CopyTo(new int[4], 1));
+ }
+
+ [Test]
+ public void IList_IsSynchronized()
+ {
+ IList list = new RepeatedField<string> { "first", "second" };
+ Assert.IsFalse(list.IsSynchronized);
+ }
+
+ [Test]
+ public void IList_Insert()
+ {
+ IList list = new RepeatedField<string> { "first", "second" };
+ list.Insert(1, "middle");
+ CollectionAssert.AreEqual(new[] { "first", "middle", "second" }, list);
+ }
+
+ [Test]
+ public void ToString_Integers()
+ {
+ var list = new RepeatedField<int> { 5, 10, 20 };
+ var text = list.ToString();
+ Assert.AreEqual("[ 5, 10, 20 ]", text);
+ }
+
+ [Test]
+ public void ToString_Strings()
+ {
+ var list = new RepeatedField<string> { "x", "y", "z" };
+ var text = list.ToString();
+ Assert.AreEqual("[ \"x\", \"y\", \"z\" ]", text);
+ }
+
+ [Test]
+ public void ToString_Messages()
+ {
+ var list = new RepeatedField<TestAllTypes> { new TestAllTypes { SingleDouble = 1.5 }, new TestAllTypes { SingleInt32 = 10 } };
+ var text = list.ToString();
+ Assert.AreEqual("[ { \"singleDouble\": 1.5 }, { \"singleInt32\": 10 } ]", text);
+ }
+
+ [Test]
+ public void ToString_Empty()
+ {
+ var list = new RepeatedField<TestAllTypes> { };
+ var text = list.ToString();
+ Assert.AreEqual("[ ]", text);
+ }
+
+ [Test]
+ public void ToString_InvalidElementType()
+ {
+ var list = new RepeatedField<decimal> { 15m };
+ Assert.Throws<ArgumentException>(() => list.ToString());
+ }
+
+ [Test]
+ public void ToString_Timestamp()
+ {
+ var list = new RepeatedField<Timestamp> { Timestamp.FromDateTime(new DateTime(2015, 10, 1, 12, 34, 56, DateTimeKind.Utc)) };
+ var text = list.ToString();
+ Assert.AreEqual("[ \"2015-10-01T12:34:56Z\" ]", text);
+ }
+
+ [Test]
+ public void ToString_Struct()
+ {
+ var message = new Struct { Fields = { { "foo", new Value { NumberValue = 20 } } } };
+ var list = new RepeatedField<Struct> { message };
+ var text = list.ToString();
+ Assert.AreEqual(text, "[ { \"foo\": 20 } ]", message.ToString());
+ }
+ }
+}
diff --git a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Compatibility/PropertyInfoExtensionsTest.cs b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Compatibility/PropertyInfoExtensionsTest.cs
new file mode 100644
index 00000000..df23a09c
--- /dev/null
+++ b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Compatibility/PropertyInfoExtensionsTest.cs
@@ -0,0 +1,98 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2015 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+using NUnit.Framework;
+using System.Reflection;
+
+namespace Google.Protobuf.Compatibility
+{
+ public class PropertyInfoExtensionsTest
+ {
+ public string PublicReadWrite { get; set; }
+ private string PrivateReadWrite { get; set; }
+ public string PublicReadPrivateWrite { get; private set; }
+ public string PrivateReadPublicWrite { private get; set; }
+ public string PublicReadOnly { get { return null; } }
+ private string PrivateReadOnly { get { return null; } }
+ public string PublicWriteOnly { set { } }
+ private string PrivateWriteOnly { set { } }
+
+ [Test]
+ [TestCase("PublicReadWrite")]
+ [TestCase("PublicReadPrivateWrite")]
+ [TestCase("PublicReadOnly")]
+ public void GetGetMethod_Success(string name)
+ {
+ var propertyInfo = typeof(PropertyInfoExtensionsTest)
+ .GetProperty(name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
+ Assert.IsNotNull(PropertyInfoExtensions.GetGetMethod(propertyInfo));
+ }
+
+ [Test]
+ [TestCase("PrivateReadWrite")]
+ [TestCase("PrivateReadPublicWrite")]
+ [TestCase("PrivateReadOnly")]
+ [TestCase("PublicWriteOnly")]
+ [TestCase("PrivateWriteOnly")]
+ public void GetGetMethod_NoAccessibleGetter(string name)
+ {
+ var propertyInfo = typeof(PropertyInfoExtensionsTest)
+ .GetProperty(name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
+ Assert.IsNull(PropertyInfoExtensions.GetGetMethod(propertyInfo));
+ }
+
+ [Test]
+ [TestCase("PublicReadWrite")]
+ [TestCase("PrivateReadPublicWrite")]
+ [TestCase("PublicWriteOnly")]
+ public void GetSetMethod_Success(string name)
+ {
+ var propertyInfo = typeof(PropertyInfoExtensionsTest)
+ .GetProperty(name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
+ Assert.IsNotNull(PropertyInfoExtensions.GetSetMethod(propertyInfo));
+ }
+
+ [Test]
+ [TestCase("PublicReadPrivateWrite")]
+ [TestCase("PrivateReadWrite")]
+ [TestCase("PrivateReadOnly")]
+ [TestCase("PublicReadOnly")]
+ [TestCase("PrivateWriteOnly")]
+ public void GetSetMethod_NoAccessibleGetter(string name)
+ {
+ var propertyInfo = typeof(PropertyInfoExtensionsTest)
+ .GetProperty(name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
+ Assert.IsNull(PropertyInfoExtensions.GetSetMethod(propertyInfo));
+ }
+ }
+
+}
diff --git a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Compatibility/TypeExtensionsTest.cs b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Compatibility/TypeExtensionsTest.cs
new file mode 100644
index 00000000..f430b06b
--- /dev/null
+++ b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Compatibility/TypeExtensionsTest.cs
@@ -0,0 +1,117 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2015 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+using NUnit.Framework;
+using System;
+using System.Collections.Generic;
+using System.Reflection;
+
+#if !DOTNET35
+namespace Google.Protobuf.Compatibility
+{
+ public class TypeExtensionsTest
+ {
+ public class DerivedList : List<string> { }
+ public string PublicProperty { get; set; }
+ private string PrivateProperty { get; set; }
+
+ public void PublicMethod()
+ {
+ }
+
+ private void PrivateMethod()
+ {
+ }
+
+ [Test]
+ [TestCase(typeof(object), typeof(string), true)]
+ [TestCase(typeof(object), typeof(int), true)]
+ [TestCase(typeof(string), typeof(string), true)]
+ [TestCase(typeof(string), typeof(object), false)]
+ [TestCase(typeof(string), typeof(int), false)]
+ [TestCase(typeof(int), typeof(int), true)]
+ [TestCase(typeof(ValueType), typeof(int), true)]
+ [TestCase(typeof(long), typeof(int), false)] //
+ public void IsAssignableFrom(Type target, Type argument, bool expected)
+ {
+ Assert.AreEqual(expected, TypeExtensions.IsAssignableFrom(target, argument));
+ }
+
+ [Test]
+ [TestCase(typeof(DerivedList), "Count")] // Go up the type hierarchy
+ [TestCase(typeof(List<string>), "Count")]
+ [TestCase(typeof(List<>), "Count")]
+ [TestCase(typeof(TypeExtensionsTest), "PublicProperty")]
+ public void GetProperty_Success(Type type, string name)
+ {
+ var property = TypeExtensions.GetProperty(type, name);
+ Assert.IsNotNull(property);
+ Assert.AreEqual(name, property.Name);
+ }
+
+ [Test]
+ [TestCase(typeof(TypeExtensionsTest), "PrivateProperty")]
+ [TestCase(typeof(TypeExtensionsTest), "Garbage")]
+ public void GetProperty_NoSuchProperty(Type type, string name)
+ {
+ var property = TypeExtensions.GetProperty(type, name);
+ Assert.IsNull(property);
+ }
+
+ [Test]
+ [TestCase(typeof(DerivedList), "RemoveAt")] // Go up the type hierarchy
+ [TestCase(typeof(List<>), "RemoveAt")]
+ [TestCase(typeof(TypeExtensionsTest), "PublicMethod")]
+ public void GetMethod_Success(Type type, string name)
+ {
+ var method = TypeExtensions.GetMethod(type, name);
+ Assert.IsNotNull(method);
+ Assert.AreEqual(name, method.Name);
+ }
+
+ [Test]
+ [TestCase(typeof(TypeExtensionsTest), "PrivateMethod")]
+ [TestCase(typeof(TypeExtensionsTest), "GarbageMethod")]
+ public void GetMethod_NoSuchMethod(Type type, string name)
+ {
+ var method = TypeExtensions.GetMethod(type, name);
+ Assert.IsNull(method);
+ }
+
+ [Test]
+ [TestCase(typeof(List<string>), "IndexOf")]
+ public void GetMethod_Ambiguous(Type type, string name)
+ {
+ Assert.Throws<AmbiguousMatchException>(() => TypeExtensions.GetMethod(type, name));
+ }
+ }
+}
+#endif
diff --git a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/DeprecatedMemberTest.cs b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/DeprecatedMemberTest.cs
new file mode 100644
index 00000000..34d5b9f9
--- /dev/null
+++ b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/DeprecatedMemberTest.cs
@@ -0,0 +1,55 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2015 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+using System;
+using System.Reflection;
+using Google.Protobuf.TestProtos;
+using NUnit.Framework;
+
+namespace Google.Protobuf
+{
+ public class DeprecatedMemberTest
+ {
+ private static void AssertIsDeprecated(MemberInfo member)
+ {
+ Assert.NotNull(member);
+ Assert.IsTrue(member.IsDefined(typeof(ObsoleteAttribute), false), "Member not obsolete: " + member);
+ }
+
+ [Test]
+ public void TestDepreatedPrimitiveValue()
+ {
+ AssertIsDeprecated(typeof(TestDeprecatedFields).GetProperty("DeprecatedInt32"));
+ }
+
+ }
+}
diff --git a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/EqualityTester.cs b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/EqualityTester.cs
new file mode 100644
index 00000000..a669baba
--- /dev/null
+++ b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/EqualityTester.cs
@@ -0,0 +1,64 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2015 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+using System;
+using NUnit.Framework;
+
+namespace Google.Protobuf
+{
+ /// <summary>
+ /// Helper methods when testing equality. NUnit's Assert.AreEqual and
+ /// Assert.AreNotEqual methods try to be clever with collections, which can
+ /// be annoying...
+ /// </summary>
+ internal static class EqualityTester
+ {
+ public static void AssertEquality<T>(T first, T second) where T : IEquatable<T>
+ {
+ Assert.IsTrue(first.Equals(second));
+ Assert.IsTrue(first.Equals((object) second));
+ Assert.AreEqual(first.GetHashCode(), second.GetHashCode());
+ }
+
+ public static void AssertInequality<T>(T first, T second) where T : IEquatable<T>
+ {
+ Assert.IsFalse(first.Equals(second));
+ Assert.IsFalse(first.Equals((object) second));
+ // While this isn't a requirement, the chances of this test failing due to
+ // coincidence rather than a bug are very small.
+ if (first != null && second != null)
+ {
+ Assert.AreNotEqual(first.GetHashCode(), second.GetHashCode());
+ }
+ }
+ }
+}
diff --git a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/FieldCodecTest.cs b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/FieldCodecTest.cs
new file mode 100644
index 00000000..0e2bad59
--- /dev/null
+++ b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/FieldCodecTest.cs
@@ -0,0 +1,196 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2015 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+using System.Collections.Generic;
+using System.IO;
+using System.Reflection;
+using Google.Protobuf.TestProtos;
+using NUnit.Framework;
+
+namespace Google.Protobuf
+{
+ public class FieldCodecTest
+ {
+#pragma warning disable 0414 // Used by tests via reflection - do not remove!
+ private static readonly List<ICodecTestData> Codecs = new List<ICodecTestData>
+ {
+ new FieldCodecTestData<bool>(FieldCodec.ForBool(100), true, "Bool"),
+ new FieldCodecTestData<string>(FieldCodec.ForString(100), "sample", "String"),
+ new FieldCodecTestData<ByteString>(FieldCodec.ForBytes(100), ByteString.CopyFrom(1, 2, 3), "Bytes"),
+ new FieldCodecTestData<int>(FieldCodec.ForInt32(100), -1000, "Int32"),
+ new FieldCodecTestData<int>(FieldCodec.ForSInt32(100), -1000, "SInt32"),
+ new FieldCodecTestData<int>(FieldCodec.ForSFixed32(100), -1000, "SFixed32"),
+ new FieldCodecTestData<uint>(FieldCodec.ForUInt32(100), 1234, "UInt32"),
+ new FieldCodecTestData<uint>(FieldCodec.ForFixed32(100), 1234, "Fixed32"),
+ new FieldCodecTestData<long>(FieldCodec.ForInt64(100), -1000, "Int64"),
+ new FieldCodecTestData<long>(FieldCodec.ForSInt64(100), -1000, "SInt64"),
+ new FieldCodecTestData<long>(FieldCodec.ForSFixed64(100), -1000, "SFixed64"),
+ new FieldCodecTestData<ulong>(FieldCodec.ForUInt64(100), 1234, "UInt64"),
+ new FieldCodecTestData<ulong>(FieldCodec.ForFixed64(100), 1234, "Fixed64"),
+ new FieldCodecTestData<float>(FieldCodec.ForFloat(100), 1234.5f, "Float"),
+ new FieldCodecTestData<double>(FieldCodec.ForDouble(100), 1234567890.5d, "Double"),
+ new FieldCodecTestData<ForeignEnum>(
+ FieldCodec.ForEnum(100, t => (int) t, t => (ForeignEnum) t), ForeignEnum.ForeignBaz, "Enum"),
+ new FieldCodecTestData<ForeignMessage>(
+ FieldCodec.ForMessage(100, ForeignMessage.Parser), new ForeignMessage { C = 10 }, "Message"),
+ };
+#pragma warning restore 0414
+
+ [Test, TestCaseSource("Codecs")]
+ public void RoundTripWithTag(ICodecTestData codec)
+ {
+ codec.TestRoundTripWithTag();
+ }
+
+ [Test, TestCaseSource("Codecs")]
+ public void RoundTripRaw(ICodecTestData codec)
+ {
+ codec.TestRoundTripRaw();
+ }
+
+ [Test, TestCaseSource("Codecs")]
+ public void CalculateSize(ICodecTestData codec)
+ {
+ codec.TestCalculateSizeWithTag();
+ }
+
+ [Test, TestCaseSource("Codecs")]
+ public void DefaultValue(ICodecTestData codec)
+ {
+ codec.TestDefaultValue();
+ }
+
+ [Test, TestCaseSource("Codecs")]
+ public void FixedSize(ICodecTestData codec)
+ {
+ codec.TestFixedSize();
+ }
+
+ // This is ugly, but it means we can have a non-generic interface.
+ // It feels like NUnit should support this better, but I don't know
+ // of any better ways right now.
+ public interface ICodecTestData
+ {
+ void TestRoundTripRaw();
+ void TestRoundTripWithTag();
+ void TestCalculateSizeWithTag();
+ void TestDefaultValue();
+ void TestFixedSize();
+ }
+
+ public class FieldCodecTestData<T> : ICodecTestData
+ {
+ private readonly FieldCodec<T> codec;
+ private readonly T sampleValue;
+ private readonly string name;
+
+ public FieldCodecTestData(FieldCodec<T> codec, T sampleValue, string name)
+ {
+ this.codec = codec;
+ this.sampleValue = sampleValue;
+ this.name = name;
+ }
+
+ public void TestRoundTripRaw()
+ {
+ var stream = new MemoryStream();
+ var codedOutput = new CodedOutputStream(stream);
+ codec.ValueWriter(codedOutput, sampleValue);
+ codedOutput.Flush();
+ stream.Position = 0;
+ var codedInput = new CodedInputStream(stream);
+ Assert.AreEqual(sampleValue, codec.ValueReader(codedInput));
+ Assert.IsTrue(codedInput.IsAtEnd);
+ }
+
+ public void TestRoundTripWithTag()
+ {
+ var stream = new MemoryStream();
+ var codedOutput = new CodedOutputStream(stream);
+ codec.WriteTagAndValue(codedOutput, sampleValue);
+ codedOutput.Flush();
+ stream.Position = 0;
+ var codedInput = new CodedInputStream(stream);
+ codedInput.AssertNextTag(codec.Tag);
+ Assert.AreEqual(sampleValue, codec.Read(codedInput));
+ Assert.IsTrue(codedInput.IsAtEnd);
+ }
+
+ public void TestCalculateSizeWithTag()
+ {
+ var stream = new MemoryStream();
+ var codedOutput = new CodedOutputStream(stream);
+ codec.WriteTagAndValue(codedOutput, sampleValue);
+ codedOutput.Flush();
+ Assert.AreEqual(stream.Position, codec.CalculateSizeWithTag(sampleValue));
+ }
+
+ public void TestDefaultValue()
+ {
+ // WriteTagAndValue ignores default values
+ var stream = new MemoryStream();
+ var codedOutput = new CodedOutputStream(stream);
+ codec.WriteTagAndValue(codedOutput, codec.DefaultValue);
+ codedOutput.Flush();
+ Assert.AreEqual(0, stream.Position);
+ Assert.AreEqual(0, codec.CalculateSizeWithTag(codec.DefaultValue));
+ if (typeof(T).GetTypeInfo().IsValueType)
+ {
+ Assert.AreEqual(default(T), codec.DefaultValue);
+ }
+
+ // The plain ValueWriter/ValueReader delegates don't.
+ if (codec.DefaultValue != null) // This part isn't appropriate for message types.
+ {
+ codedOutput = new CodedOutputStream(stream);
+ codec.ValueWriter(codedOutput, codec.DefaultValue);
+ codedOutput.Flush();
+ Assert.AreNotEqual(0, stream.Position);
+ Assert.AreEqual(stream.Position, codec.ValueSizeCalculator(codec.DefaultValue));
+ stream.Position = 0;
+ var codedInput = new CodedInputStream(stream);
+ Assert.AreEqual(codec.DefaultValue, codec.ValueReader(codedInput));
+ }
+ }
+
+ public void TestFixedSize()
+ {
+ Assert.AreEqual(name.Contains("Fixed"), codec.FixedSize != 0);
+ }
+
+ public override string ToString()
+ {
+ return name;
+ }
+ }
+ }
+}
diff --git a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/GeneratedMessageTest.cs b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/GeneratedMessageTest.cs
new file mode 100644
index 00000000..8b153d69
--- /dev/null
+++ b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/GeneratedMessageTest.cs
@@ -0,0 +1,723 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2015 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+using System;
+using System.IO;
+using Google.Protobuf.TestProtos;
+using NUnit.Framework;
+using System.Collections;
+using System.Collections.Generic;
+using System.Linq;
+using Google.Protobuf.WellKnownTypes;
+
+namespace Google.Protobuf
+{
+ /// <summary>
+ /// Tests around the generated TestAllTypes message.
+ /// </summary>
+ public class GeneratedMessageTest
+ {
+ [Test]
+ public void EmptyMessageFieldDistinctFromMissingMessageField()
+ {
+ // This demonstrates what we're really interested in...
+ var message1 = new TestAllTypes { SingleForeignMessage = new ForeignMessage() };
+ var message2 = new TestAllTypes(); // SingleForeignMessage is null
+ EqualityTester.AssertInequality(message1, message2);
+ }
+
+ [Test]
+ public void DefaultValues()
+ {
+ // Single fields
+ var message = new TestAllTypes();
+ Assert.AreEqual(false, message.SingleBool);
+ Assert.AreEqual(ByteString.Empty, message.SingleBytes);
+ Assert.AreEqual(0.0, message.SingleDouble);
+ Assert.AreEqual(0, message.SingleFixed32);
+ Assert.AreEqual(0L, message.SingleFixed64);
+ Assert.AreEqual(0.0f, message.SingleFloat);
+ Assert.AreEqual(ForeignEnum.ForeignUnspecified, message.SingleForeignEnum);
+ Assert.IsNull(message.SingleForeignMessage);
+ Assert.AreEqual(ImportEnum.Unspecified, message.SingleImportEnum);
+ Assert.IsNull(message.SingleImportMessage);
+ Assert.AreEqual(0, message.SingleInt32);
+ Assert.AreEqual(0L, message.SingleInt64);
+ Assert.AreEqual(TestAllTypes.Types.NestedEnum.Unspecified, message.SingleNestedEnum);
+ Assert.IsNull(message.SingleNestedMessage);
+ Assert.IsNull(message.SinglePublicImportMessage);
+ Assert.AreEqual(0, message.SingleSfixed32);
+ Assert.AreEqual(0L, message.SingleSfixed64);
+ Assert.AreEqual(0, message.SingleSint32);
+ Assert.AreEqual(0L, message.SingleSint64);
+ Assert.AreEqual("", message.SingleString);
+ Assert.AreEqual(0U, message.SingleUint32);
+ Assert.AreEqual(0UL, message.SingleUint64);
+
+ // Repeated fields
+ Assert.AreEqual(0, message.RepeatedBool.Count);
+ Assert.AreEqual(0, message.RepeatedBytes.Count);
+ Assert.AreEqual(0, message.RepeatedDouble.Count);
+ Assert.AreEqual(0, message.RepeatedFixed32.Count);
+ Assert.AreEqual(0, message.RepeatedFixed64.Count);
+ Assert.AreEqual(0, message.RepeatedFloat.Count);
+ Assert.AreEqual(0, message.RepeatedForeignEnum.Count);
+ Assert.AreEqual(0, message.RepeatedForeignMessage.Count);
+ Assert.AreEqual(0, message.RepeatedImportEnum.Count);
+ Assert.AreEqual(0, message.RepeatedImportMessage.Count);
+ Assert.AreEqual(0, message.RepeatedNestedEnum.Count);
+ Assert.AreEqual(0, message.RepeatedNestedMessage.Count);
+ Assert.AreEqual(0, message.RepeatedPublicImportMessage.Count);
+ Assert.AreEqual(0, message.RepeatedSfixed32.Count);
+ Assert.AreEqual(0, message.RepeatedSfixed64.Count);
+ Assert.AreEqual(0, message.RepeatedSint32.Count);
+ Assert.AreEqual(0, message.RepeatedSint64.Count);
+ Assert.AreEqual(0, message.RepeatedString.Count);
+ Assert.AreEqual(0, message.RepeatedUint32.Count);
+ Assert.AreEqual(0, message.RepeatedUint64.Count);
+
+ // Oneof fields
+ Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.None, message.OneofFieldCase);
+ Assert.AreEqual(0, message.OneofUint32);
+ Assert.AreEqual("", message.OneofString);
+ Assert.AreEqual(ByteString.Empty, message.OneofBytes);
+ Assert.IsNull(message.OneofNestedMessage);
+ }
+
+ [Test]
+ public void NullStringAndBytesRejected()
+ {
+ var message = new TestAllTypes();
+ Assert.Throws<ArgumentNullException>(() => message.SingleString = null);
+ Assert.Throws<ArgumentNullException>(() => message.OneofString = null);
+ Assert.Throws<ArgumentNullException>(() => message.SingleBytes = null);
+ Assert.Throws<ArgumentNullException>(() => message.OneofBytes = null);
+ }
+
+ [Test]
+ public void RoundTrip_Empty()
+ {
+ var message = new TestAllTypes();
+ // Without setting any values, there's nothing to write.
+ byte[] bytes = message.ToByteArray();
+ Assert.AreEqual(0, bytes.Length);
+ TestAllTypes parsed = TestAllTypes.Parser.ParseFrom(bytes);
+ Assert.AreEqual(message, parsed);
+ }
+
+ [Test]
+ public void RoundTrip_SingleValues()
+ {
+ var message = new TestAllTypes
+ {
+ SingleBool = true,
+ SingleBytes = ByteString.CopyFrom(1, 2, 3, 4),
+ SingleDouble = 23.5,
+ SingleFixed32 = 23,
+ SingleFixed64 = 1234567890123,
+ SingleFloat = 12.25f,
+ SingleForeignEnum = ForeignEnum.ForeignBar,
+ SingleForeignMessage = new ForeignMessage { C = 10 },
+ SingleImportEnum = ImportEnum.ImportBaz,
+ SingleImportMessage = new ImportMessage { D = 20 },
+ SingleInt32 = 100,
+ SingleInt64 = 3210987654321,
+ SingleNestedEnum = TestAllTypes.Types.NestedEnum.Foo,
+ SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 35 },
+ SinglePublicImportMessage = new PublicImportMessage { E = 54 },
+ SingleSfixed32 = -123,
+ SingleSfixed64 = -12345678901234,
+ SingleSint32 = -456,
+ SingleSint64 = -12345678901235,
+ SingleString = "test",
+ SingleUint32 = uint.MaxValue,
+ SingleUint64 = ulong.MaxValue
+ };
+
+ byte[] bytes = message.ToByteArray();
+ TestAllTypes parsed = TestAllTypes.Parser.ParseFrom(bytes);
+ Assert.AreEqual(message, parsed);
+ }
+
+ [Test]
+ public void RoundTrip_RepeatedValues()
+ {
+ var message = new TestAllTypes
+ {
+ RepeatedBool = { true, false },
+ RepeatedBytes = { ByteString.CopyFrom(1, 2, 3, 4), ByteString.CopyFrom(5, 6) },
+ RepeatedDouble = { -12.25, 23.5 },
+ RepeatedFixed32 = { uint.MaxValue, 23 },
+ RepeatedFixed64 = { ulong.MaxValue, 1234567890123 },
+ RepeatedFloat = { 100f, 12.25f },
+ RepeatedForeignEnum = { ForeignEnum.ForeignFoo, ForeignEnum.ForeignBar },
+ RepeatedForeignMessage = { new ForeignMessage(), new ForeignMessage { C = 10 } },
+ RepeatedImportEnum = { ImportEnum.ImportBaz, ImportEnum.Unspecified },
+ RepeatedImportMessage = { new ImportMessage { D = 20 }, new ImportMessage { D = 25 } },
+ RepeatedInt32 = { 100, 200 },
+ RepeatedInt64 = { 3210987654321, long.MaxValue },
+ RepeatedNestedEnum = { TestAllTypes.Types.NestedEnum.Foo, TestAllTypes.Types.NestedEnum.Neg },
+ RepeatedNestedMessage = { new TestAllTypes.Types.NestedMessage { Bb = 35 }, new TestAllTypes.Types.NestedMessage { Bb = 10 } },
+ RepeatedPublicImportMessage = { new PublicImportMessage { E = 54 }, new PublicImportMessage { E = -1 } },
+ RepeatedSfixed32 = { -123, 123 },
+ RepeatedSfixed64 = { -12345678901234, 12345678901234 },
+ RepeatedSint32 = { -456, 100 },
+ RepeatedSint64 = { -12345678901235, 123 },
+ RepeatedString = { "foo", "bar" },
+ RepeatedUint32 = { uint.MaxValue, uint.MinValue },
+ RepeatedUint64 = { ulong.MaxValue, uint.MinValue }
+ };
+
+ byte[] bytes = message.ToByteArray();
+ TestAllTypes parsed = TestAllTypes.Parser.ParseFrom(bytes);
+ Assert.AreEqual(message, parsed);
+ }
+
+ // Note that not every map within map_unittest_proto3 is used. They all go through very
+ // similar code paths. The fact that all maps are present is validation that we have codecs
+ // for every type.
+ [Test]
+ public void RoundTrip_Maps()
+ {
+ var message = new TestMap
+ {
+ MapBoolBool = {
+ { false, true },
+ { true, false }
+ },
+ MapInt32Bytes = {
+ { 5, ByteString.CopyFrom(6, 7, 8) },
+ { 25, ByteString.CopyFrom(1, 2, 3, 4, 5) },
+ { 10, ByteString.Empty }
+ },
+ MapInt32ForeignMessage = {
+ { 0, new ForeignMessage { C = 10 } },
+ { 5, new ForeignMessage() },
+ },
+ MapInt32Enum = {
+ { 1, MapEnum.Bar },
+ { 2000, MapEnum.Foo }
+ }
+ };
+
+ byte[] bytes = message.ToByteArray();
+ TestMap parsed = TestMap.Parser.ParseFrom(bytes);
+ Assert.AreEqual(message, parsed);
+ }
+
+ [Test]
+ public void MapWithEmptyEntry()
+ {
+ var message = new TestMap
+ {
+ MapInt32Bytes = { { 0, ByteString.Empty } }
+ };
+
+ byte[] bytes = message.ToByteArray();
+ Assert.AreEqual(2, bytes.Length); // Tag for field entry (1 byte), length of entry (0; 1 byte)
+
+ var parsed = TestMap.Parser.ParseFrom(bytes);
+ Assert.AreEqual(1, parsed.MapInt32Bytes.Count);
+ Assert.AreEqual(ByteString.Empty, parsed.MapInt32Bytes[0]);
+ }
+
+ [Test]
+ public void MapWithOnlyValue()
+ {
+ // Hand-craft the stream to contain a single entry with just a value.
+ var memoryStream = new MemoryStream();
+ var output = new CodedOutputStream(memoryStream);
+ output.WriteTag(TestMap.MapInt32ForeignMessageFieldNumber, WireFormat.WireType.LengthDelimited);
+ var nestedMessage = new ForeignMessage { C = 20 };
+ // Size of the entry (tag, size written by WriteMessage, data written by WriteMessage)
+ output.WriteLength(2 + nestedMessage.CalculateSize());
+ output.WriteTag(2, WireFormat.WireType.LengthDelimited);
+ output.WriteMessage(nestedMessage);
+ output.Flush();
+
+ var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray());
+ Assert.AreEqual(nestedMessage, parsed.MapInt32ForeignMessage[0]);
+ }
+
+ [Test]
+ public void MapWithOnlyKey_PrimitiveValue()
+ {
+ // Hand-craft the stream to contain a single entry with just a key.
+ var memoryStream = new MemoryStream();
+ var output = new CodedOutputStream(memoryStream);
+ output.WriteTag(TestMap.MapInt32DoubleFieldNumber, WireFormat.WireType.LengthDelimited);
+ int key = 10;
+ output.WriteLength(1 + CodedOutputStream.ComputeInt32Size(key));
+ output.WriteTag(1, WireFormat.WireType.Varint);
+ output.WriteInt32(key);
+ output.Flush();
+
+ var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray());
+ Assert.AreEqual(0.0, parsed.MapInt32Double[key]);
+ }
+
+ [Test]
+ public void MapWithOnlyKey_MessageValue()
+ {
+ // Hand-craft the stream to contain a single entry with just a key.
+ var memoryStream = new MemoryStream();
+ var output = new CodedOutputStream(memoryStream);
+ output.WriteTag(TestMap.MapInt32ForeignMessageFieldNumber, WireFormat.WireType.LengthDelimited);
+ int key = 10;
+ output.WriteLength(1 + CodedOutputStream.ComputeInt32Size(key));
+ output.WriteTag(1, WireFormat.WireType.Varint);
+ output.WriteInt32(key);
+ output.Flush();
+
+ var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray());
+ Assert.AreEqual(new ForeignMessage(), parsed.MapInt32ForeignMessage[key]);
+ }
+
+ [Test]
+ public void MapIgnoresExtraFieldsWithinEntryMessages()
+ {
+ // Hand-craft the stream to contain a single entry with three fields
+ var memoryStream = new MemoryStream();
+ var output = new CodedOutputStream(memoryStream);
+
+ output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited);
+
+ var key = 10; // Field 1
+ var value = 20; // Field 2
+ var extra = 30; // Field 3
+
+ // Each field can be represented in a single byte, with a single byte tag.
+ // Total message size: 6 bytes.
+ output.WriteLength(6);
+ output.WriteTag(1, WireFormat.WireType.Varint);
+ output.WriteInt32(key);
+ output.WriteTag(2, WireFormat.WireType.Varint);
+ output.WriteInt32(value);
+ output.WriteTag(3, WireFormat.WireType.Varint);
+ output.WriteInt32(extra);
+ output.Flush();
+
+ var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray());
+ Assert.AreEqual(value, parsed.MapInt32Int32[key]);
+ }
+
+ [Test]
+ public void MapFieldOrderIsIrrelevant()
+ {
+ var memoryStream = new MemoryStream();
+ var output = new CodedOutputStream(memoryStream);
+
+ output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited);
+
+ var key = 10;
+ var value = 20;
+
+ // Each field can be represented in a single byte, with a single byte tag.
+ // Total message size: 4 bytes.
+ output.WriteLength(4);
+ output.WriteTag(2, WireFormat.WireType.Varint);
+ output.WriteInt32(value);
+ output.WriteTag(1, WireFormat.WireType.Varint);
+ output.WriteInt32(key);
+ output.Flush();
+
+ var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray());
+ Assert.AreEqual(value, parsed.MapInt32Int32[key]);
+ }
+
+ [Test]
+ public void MapNonContiguousEntries()
+ {
+ var memoryStream = new MemoryStream();
+ var output = new CodedOutputStream(memoryStream);
+
+ // Message structure:
+ // Entry for MapInt32Int32
+ // Entry for MapStringString
+ // Entry for MapInt32Int32
+
+ // First entry
+ var key1 = 10;
+ var value1 = 20;
+ output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited);
+ output.WriteLength(4);
+ output.WriteTag(1, WireFormat.WireType.Varint);
+ output.WriteInt32(key1);
+ output.WriteTag(2, WireFormat.WireType.Varint);
+ output.WriteInt32(value1);
+
+ // Second entry
+ var key2 = "a";
+ var value2 = "b";
+ output.WriteTag(TestMap.MapStringStringFieldNumber, WireFormat.WireType.LengthDelimited);
+ output.WriteLength(6); // 3 bytes per entry: tag, size, character
+ output.WriteTag(1, WireFormat.WireType.LengthDelimited);
+ output.WriteString(key2);
+ output.WriteTag(2, WireFormat.WireType.LengthDelimited);
+ output.WriteString(value2);
+
+ // Third entry
+ var key3 = 15;
+ var value3 = 25;
+ output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited);
+ output.WriteLength(4);
+ output.WriteTag(1, WireFormat.WireType.Varint);
+ output.WriteInt32(key3);
+ output.WriteTag(2, WireFormat.WireType.Varint);
+ output.WriteInt32(value3);
+
+ output.Flush();
+ var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray());
+ var expected = new TestMap
+ {
+ MapInt32Int32 = { { key1, value1 }, { key3, value3 } },
+ MapStringString = { { key2, value2 } }
+ };
+ Assert.AreEqual(expected, parsed);
+ }
+
+ [Test]
+ public void DuplicateKeys_LastEntryWins()
+ {
+ var memoryStream = new MemoryStream();
+ var output = new CodedOutputStream(memoryStream);
+
+ var key = 10;
+ var value1 = 20;
+ var value2 = 30;
+
+ // First entry
+ output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited);
+ output.WriteLength(4);
+ output.WriteTag(1, WireFormat.WireType.Varint);
+ output.WriteInt32(key);
+ output.WriteTag(2, WireFormat.WireType.Varint);
+ output.WriteInt32(value1);
+
+ // Second entry - same key, different value
+ output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited);
+ output.WriteLength(4);
+ output.WriteTag(1, WireFormat.WireType.Varint);
+ output.WriteInt32(key);
+ output.WriteTag(2, WireFormat.WireType.Varint);
+ output.WriteInt32(value2);
+ output.Flush();
+
+ var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray());
+ Assert.AreEqual(value2, parsed.MapInt32Int32[key]);
+ }
+
+ [Test]
+ public void CloneSingleNonMessageValues()
+ {
+ var original = new TestAllTypes
+ {
+ SingleBool = true,
+ SingleBytes = ByteString.CopyFrom(1, 2, 3, 4),
+ SingleDouble = 23.5,
+ SingleFixed32 = 23,
+ SingleFixed64 = 1234567890123,
+ SingleFloat = 12.25f,
+ SingleInt32 = 100,
+ SingleInt64 = 3210987654321,
+ SingleNestedEnum = TestAllTypes.Types.NestedEnum.Foo,
+ SingleSfixed32 = -123,
+ SingleSfixed64 = -12345678901234,
+ SingleSint32 = -456,
+ SingleSint64 = -12345678901235,
+ SingleString = "test",
+ SingleUint32 = uint.MaxValue,
+ SingleUint64 = ulong.MaxValue
+ };
+ var clone = original.Clone();
+ Assert.AreNotSame(original, clone);
+ Assert.AreEqual(original, clone);
+ // Just as a single example
+ clone.SingleInt32 = 150;
+ Assert.AreNotEqual(original, clone);
+ }
+
+ [Test]
+ public void CloneRepeatedNonMessageValues()
+ {
+ var original = new TestAllTypes
+ {
+ RepeatedBool = { true, false },
+ RepeatedBytes = { ByteString.CopyFrom(1, 2, 3, 4), ByteString.CopyFrom(5, 6) },
+ RepeatedDouble = { -12.25, 23.5 },
+ RepeatedFixed32 = { uint.MaxValue, 23 },
+ RepeatedFixed64 = { ulong.MaxValue, 1234567890123 },
+ RepeatedFloat = { 100f, 12.25f },
+ RepeatedInt32 = { 100, 200 },
+ RepeatedInt64 = { 3210987654321, long.MaxValue },
+ RepeatedNestedEnum = { TestAllTypes.Types.NestedEnum.Foo, TestAllTypes.Types.NestedEnum.Neg },
+ RepeatedSfixed32 = { -123, 123 },
+ RepeatedSfixed64 = { -12345678901234, 12345678901234 },
+ RepeatedSint32 = { -456, 100 },
+ RepeatedSint64 = { -12345678901235, 123 },
+ RepeatedString = { "foo", "bar" },
+ RepeatedUint32 = { uint.MaxValue, uint.MinValue },
+ RepeatedUint64 = { ulong.MaxValue, uint.MinValue }
+ };
+
+ var clone = original.Clone();
+ Assert.AreNotSame(original, clone);
+ Assert.AreEqual(original, clone);
+ // Just as a single example
+ clone.RepeatedDouble.Add(25.5);
+ Assert.AreNotEqual(original, clone);
+ }
+
+ [Test]
+ public void CloneSingleMessageField()
+ {
+ var original = new TestAllTypes
+ {
+ SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 20 }
+ };
+
+ var clone = original.Clone();
+ Assert.AreNotSame(original, clone);
+ Assert.AreNotSame(original.SingleNestedMessage, clone.SingleNestedMessage);
+ Assert.AreEqual(original, clone);
+
+ clone.SingleNestedMessage.Bb = 30;
+ Assert.AreNotEqual(original, clone);
+ }
+
+ [Test]
+ public void CloneRepeatedMessageField()
+ {
+ var original = new TestAllTypes
+ {
+ RepeatedNestedMessage = { new TestAllTypes.Types.NestedMessage { Bb = 20 } }
+ };
+
+ var clone = original.Clone();
+ Assert.AreNotSame(original, clone);
+ Assert.AreNotSame(original.RepeatedNestedMessage, clone.RepeatedNestedMessage);
+ Assert.AreNotSame(original.RepeatedNestedMessage[0], clone.RepeatedNestedMessage[0]);
+ Assert.AreEqual(original, clone);
+
+ clone.RepeatedNestedMessage[0].Bb = 30;
+ Assert.AreNotEqual(original, clone);
+ }
+
+ [Test]
+ public void CloneOneofField()
+ {
+ var original = new TestAllTypes
+ {
+ OneofNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 20 }
+ };
+
+ var clone = original.Clone();
+ Assert.AreNotSame(original, clone);
+ Assert.AreEqual(original, clone);
+
+ // We should have cloned the message
+ original.OneofNestedMessage.Bb = 30;
+ Assert.AreNotEqual(original, clone);
+ }
+
+ [Test]
+ public void OneofProperties()
+ {
+ // Switch the oneof case between each of the different options, and check everything behaves
+ // as expected in each case.
+ var message = new TestAllTypes();
+ Assert.AreEqual("", message.OneofString);
+ Assert.AreEqual(0, message.OneofUint32);
+ Assert.AreEqual(ByteString.Empty, message.OneofBytes);
+ Assert.IsNull(message.OneofNestedMessage);
+ Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.None, message.OneofFieldCase);
+
+ message.OneofString = "sample";
+ Assert.AreEqual("sample", message.OneofString);
+ Assert.AreEqual(0, message.OneofUint32);
+ Assert.AreEqual(ByteString.Empty, message.OneofBytes);
+ Assert.IsNull(message.OneofNestedMessage);
+ Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofString, message.OneofFieldCase);
+
+ var bytes = ByteString.CopyFrom(1, 2, 3);
+ message.OneofBytes = bytes;
+ Assert.AreEqual("", message.OneofString);
+ Assert.AreEqual(0, message.OneofUint32);
+ Assert.AreEqual(bytes, message.OneofBytes);
+ Assert.IsNull(message.OneofNestedMessage);
+ Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofBytes, message.OneofFieldCase);
+
+ message.OneofUint32 = 20;
+ Assert.AreEqual("", message.OneofString);
+ Assert.AreEqual(20, message.OneofUint32);
+ Assert.AreEqual(ByteString.Empty, message.OneofBytes);
+ Assert.IsNull(message.OneofNestedMessage);
+ Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofUint32, message.OneofFieldCase);
+
+ var nestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 25 };
+ message.OneofNestedMessage = nestedMessage;
+ Assert.AreEqual("", message.OneofString);
+ Assert.AreEqual(0, message.OneofUint32);
+ Assert.AreEqual(ByteString.Empty, message.OneofBytes);
+ Assert.AreEqual(nestedMessage, message.OneofNestedMessage);
+ Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofNestedMessage, message.OneofFieldCase);
+
+ message.ClearOneofField();
+ Assert.AreEqual("", message.OneofString);
+ Assert.AreEqual(0, message.OneofUint32);
+ Assert.AreEqual(ByteString.Empty, message.OneofBytes);
+ Assert.IsNull(message.OneofNestedMessage);
+ Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.None, message.OneofFieldCase);
+ }
+
+ [Test]
+ public void Oneof_DefaultValuesNotEqual()
+ {
+ var message1 = new TestAllTypes { OneofString = "" };
+ var message2 = new TestAllTypes { OneofUint32 = 0 };
+ Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofString, message1.OneofFieldCase);
+ Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofUint32, message2.OneofFieldCase);
+ Assert.AreNotEqual(message1, message2);
+ }
+
+ [Test]
+ public void OneofSerialization_NonDefaultValue()
+ {
+ var message = new TestAllTypes();
+ message.OneofString = "this would take a bit of space";
+ message.OneofUint32 = 10;
+ var bytes = message.ToByteArray();
+ Assert.AreEqual(3, bytes.Length); // 2 bytes for the tag + 1 for the value - no string!
+
+ var message2 = TestAllTypes.Parser.ParseFrom(bytes);
+ Assert.AreEqual(message, message2);
+ Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofUint32, message2.OneofFieldCase);
+ }
+
+ [Test]
+ public void OneofSerialization_DefaultValue()
+ {
+ var message = new TestAllTypes();
+ message.OneofString = "this would take a bit of space";
+ message.OneofUint32 = 0; // This is the default value for UInt32; normally wouldn't be serialized
+ var bytes = message.ToByteArray();
+ Assert.AreEqual(3, bytes.Length); // 2 bytes for the tag + 1 for the value - it's still serialized
+
+ var message2 = TestAllTypes.Parser.ParseFrom(bytes);
+ Assert.AreEqual(message, message2);
+ Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofUint32, message2.OneofFieldCase);
+ }
+
+ [Test]
+ public void IgnoreUnknownFields_RealDataStillRead()
+ {
+ var message = SampleMessages.CreateFullTestAllTypes();
+ var stream = new MemoryStream();
+ var output = new CodedOutputStream(stream);
+ var unusedFieldNumber = 23456;
+ Assert.IsFalse(TestAllTypes.Descriptor.Fields.InDeclarationOrder().Select(x => x.FieldNumber).Contains(unusedFieldNumber));
+ output.WriteTag(unusedFieldNumber, WireFormat.WireType.LengthDelimited);
+ output.WriteString("ignore me");
+ message.WriteTo(output);
+ output.Flush();
+
+ stream.Position = 0;
+ var parsed = TestAllTypes.Parser.ParseFrom(stream);
+ Assert.AreEqual(message, parsed);
+ }
+
+ [Test]
+ public void IgnoreUnknownFields_AllTypes()
+ {
+ // Simple way of ensuring we can skip all kinds of fields.
+ var data = SampleMessages.CreateFullTestAllTypes().ToByteArray();
+ var empty = Empty.Parser.ParseFrom(data);
+ Assert.AreEqual(new Empty(), empty);
+ }
+
+ // This was originally seen as a conformance test failure.
+ [Test]
+ public void TruncatedMessageFieldThrows()
+ {
+ // 130, 3 is the message tag
+ // 1 is the data length - but there's no data.
+ var data = new byte[] { 130, 3, 1 };
+ Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseFrom(data));
+ }
+
+ /// <summary>
+ /// Demonstrates current behaviour with an extraneous end group tag - see issue 688
+ /// for details; we may want to change this.
+ /// </summary>
+ [Test]
+ public void ExtraEndGroupThrows()
+ {
+ var message = SampleMessages.CreateFullTestAllTypes();
+ var stream = new MemoryStream();
+ var output = new CodedOutputStream(stream);
+
+ output.WriteTag(TestAllTypes.SingleFixed32FieldNumber, WireFormat.WireType.Fixed32);
+ output.WriteFixed32(123);
+ output.WriteTag(100, WireFormat.WireType.EndGroup);
+
+ output.Flush();
+
+ stream.Position = 0;
+ Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseFrom(stream));
+ }
+
+ [Test]
+ public void CustomDiagnosticMessage_DirectToStringCall()
+ {
+ var message = new ForeignMessage { C = 31 };
+ Assert.AreEqual("{ \"c\": 31, \"@cInHex\": \"1f\" }", message.ToString());
+ Assert.AreEqual("{ \"c\": 31 }", JsonFormatter.Default.Format(message));
+ }
+
+ [Test]
+ public void CustomDiagnosticMessage_Nested()
+ {
+ var message = new TestAllTypes { SingleForeignMessage = new ForeignMessage { C = 16 } };
+ Assert.AreEqual("{ \"singleForeignMessage\": { \"c\": 16, \"@cInHex\": \"10\" } }", message.ToString());
+ Assert.AreEqual("{ \"singleForeignMessage\": { \"c\": 16 } }", JsonFormatter.Default.Format(message));
+ }
+
+ [Test]
+ public void CustomDiagnosticMessage_DirectToTextWriterCall()
+ {
+ var message = new ForeignMessage { C = 31 };
+ var writer = new StringWriter();
+ JsonFormatter.Default.Format(message, writer);
+ Assert.AreEqual("{ \"c\": 31 }", writer.ToString());
+ }
+ }
+} \ No newline at end of file
diff --git a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Google.Protobuf.Test.csproj b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Google.Protobuf.Test.csproj
new file mode 100644
index 00000000..06d07b9f
--- /dev/null
+++ b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Google.Protobuf.Test.csproj
@@ -0,0 +1,30 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <PropertyGroup>
+ <OutputType>Exe</OutputType>
+ <TargetFrameworks>net451;netcoreapp1.0</TargetFrameworks>
+ <AssemblyOriginatorKeyFile>../../keys/Google.Protobuf.snk</AssemblyOriginatorKeyFile>
+ <SignAssembly>true</SignAssembly>
+ <PublicSign Condition=" '$(OS)' != 'Windows_NT' ">true</PublicSign>
+ <IsPackable>False</IsPackable>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="..\Google.Protobuf\Google.Protobuf.csproj" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <PackageReference Include="NUnit" Version="3.6.1" />
+ <PackageReference Include="NUnitLite" Version="3.6.1" />
+ </ItemGroup>
+
+ <!--
+ - Override target frameworks on non-Windows to just .NET Core
+ - Doing this conditionally in the initial PropertyGroup confuses
+ - Visual Studio.
+ -->
+ <PropertyGroup Condition="'$(OS)' != 'Windows_NT'">
+ <TargetFrameworks>netcoreapp1.0</TargetFrameworks>
+ </PropertyGroup>
+
+</Project>
diff --git a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/IssuesTest.cs b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/IssuesTest.cs
new file mode 100644
index 00000000..a38d6b08
--- /dev/null
+++ b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/IssuesTest.cs
@@ -0,0 +1,82 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+using Google.Protobuf.Reflection;
+using UnitTest.Issues.TestProtos;
+using NUnit.Framework;
+
+
+namespace Google.Protobuf
+{
+ /// <summary>
+ /// Tests for issues which aren't easily compartmentalized into other unit tests.
+ /// </summary>
+ public class IssuesTest
+ {
+ // Issue 45
+ [Test]
+ public void FieldCalledItem()
+ {
+ ItemField message = new ItemField { Item = 3 };
+ FieldDescriptor field = ItemField.Descriptor.FindFieldByName("item");
+ Assert.NotNull(field);
+ Assert.AreEqual(3, (int)field.Accessor.GetValue(message));
+ }
+
+ [Test]
+ public void ReservedNames()
+ {
+ var message = new ReservedNames { Types_ = 10, Descriptor_ = 20 };
+ // Underscores aren't reflected in the JSON.
+ Assert.AreEqual("{ \"types\": 10, \"descriptor\": 20 }", message.ToString());
+ }
+
+ [Test]
+ public void JsonNameParseTest()
+ {
+ var settings = new JsonParser.Settings(10, TypeRegistry.FromFiles(UnittestIssuesReflection.Descriptor));
+ var parser = new JsonParser(settings);
+
+ // It is safe to use either original field name or explicitly specified json_name
+ Assert.AreEqual(new TestJsonName { Name = "test", Description = "test2", Guid = "test3" },
+ parser.Parse<TestJsonName>("{ \"name\": \"test\", \"desc\": \"test2\", \"guid\": \"test3\" }"));
+ }
+
+ [Test]
+ public void JsonNameFormatTest()
+ {
+ var message = new TestJsonName { Name = "test", Description = "test2", Guid = "test3" };
+ Assert.AreEqual("{ \"name\": \"test\", \"desc\": \"test2\", \"exid\": \"test3\" }",
+ JsonFormatter.Default.Format(message));
+ }
+ }
+}
diff --git a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/JsonParserTest.cs b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/JsonParserTest.cs
new file mode 100644
index 00000000..f595455a
--- /dev/null
+++ b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/JsonParserTest.cs
@@ -0,0 +1,939 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+using Google.Protobuf.Reflection;
+using Google.Protobuf.TestProtos;
+using Google.Protobuf.WellKnownTypes;
+using NUnit.Framework;
+using System;
+
+namespace Google.Protobuf
+{
+ /// <summary>
+ /// Unit tests for JSON parsing.
+ /// </summary>
+ public class JsonParserTest
+ {
+ // Sanity smoke test
+ [Test]
+ public void AllTypesRoundtrip()
+ {
+ AssertRoundtrip(SampleMessages.CreateFullTestAllTypes());
+ }
+
+ [Test]
+ public void Maps()
+ {
+ AssertRoundtrip(new TestMap { MapStringString = { { "with spaces", "bar" }, { "a", "b" } } });
+ AssertRoundtrip(new TestMap { MapInt32Int32 = { { 0, 1 }, { 2, 3 } } });
+ AssertRoundtrip(new TestMap { MapBoolBool = { { false, true }, { true, false } } });
+ }
+
+ [Test]
+ [TestCase(" 1 ")]
+ [TestCase("+1")]
+ [TestCase("1,000")]
+ [TestCase("1.5")]
+ public void IntegerMapKeysAreStrict(string keyText)
+ {
+ // Test that integer parsing is strict. We assume that if this is correct for int32,
+ // it's correct for other numeric key types.
+ var json = "{ \"mapInt32Int32\": { \"" + keyText + "\" : \"1\" } }";
+ Assert.Throws<InvalidProtocolBufferException>(() => JsonParser.Default.Parse<TestMap>(json));
+ }
+
+ [Test]
+ public void OriginalFieldNameAccepted()
+ {
+ var json = "{ \"single_int32\": 10 }";
+ var expected = new TestAllTypes { SingleInt32 = 10 };
+ Assert.AreEqual(expected, TestAllTypes.Parser.ParseJson(json));
+ }
+
+ [Test]
+ public void SourceContextRoundtrip()
+ {
+ AssertRoundtrip(new SourceContext { FileName = "foo.proto" });
+ }
+
+ [Test]
+ public void SingularWrappers_DefaultNonNullValues()
+ {
+ var message = new TestWellKnownTypes
+ {
+ StringField = "",
+ BytesField = ByteString.Empty,
+ BoolField = false,
+ FloatField = 0f,
+ DoubleField = 0d,
+ Int32Field = 0,
+ Int64Field = 0,
+ Uint32Field = 0,
+ Uint64Field = 0
+ };
+ AssertRoundtrip(message);
+ }
+
+ [Test]
+ public void SingularWrappers_NonDefaultValues()
+ {
+ var message = new TestWellKnownTypes
+ {
+ StringField = "x",
+ BytesField = ByteString.CopyFrom(1, 2, 3),
+ BoolField = true,
+ FloatField = 12.5f,
+ DoubleField = 12.25d,
+ Int32Field = 1,
+ Int64Field = 2,
+ Uint32Field = 3,
+ Uint64Field = 4
+ };
+ AssertRoundtrip(message);
+ }
+
+ [Test]
+ public void SingularWrappers_ExplicitNulls()
+ {
+ // When we parse the "valueField": null part, we remember it... basically, it's one case
+ // where explicit default values don't fully roundtrip.
+ var message = new TestWellKnownTypes { ValueField = Value.ForNull() };
+ var json = new JsonFormatter(new JsonFormatter.Settings(true)).Format(message);
+ var parsed = JsonParser.Default.Parse<TestWellKnownTypes>(json);
+ Assert.AreEqual(message, parsed);
+ }
+
+ [Test]
+ [TestCase(typeof(BoolValue), "true", true)]
+ [TestCase(typeof(Int32Value), "32", 32)]
+ [TestCase(typeof(Int64Value), "32", 32L)]
+ [TestCase(typeof(Int64Value), "\"32\"", 32L)]
+ [TestCase(typeof(UInt32Value), "32", 32U)]
+ [TestCase(typeof(UInt64Value), "\"32\"", 32UL)]
+ [TestCase(typeof(UInt64Value), "32", 32UL)]
+ [TestCase(typeof(StringValue), "\"foo\"", "foo")]
+ [TestCase(typeof(FloatValue), "1.5", 1.5f)]
+ [TestCase(typeof(DoubleValue), "1.5", 1.5d)]
+ public void Wrappers_Standalone(System.Type wrapperType, string json, object expectedValue)
+ {
+ IMessage parsed = (IMessage)Activator.CreateInstance(wrapperType);
+ IMessage expected = (IMessage)Activator.CreateInstance(wrapperType);
+ JsonParser.Default.Merge(parsed, "null");
+ Assert.AreEqual(expected, parsed);
+
+ JsonParser.Default.Merge(parsed, json);
+ expected.Descriptor.Fields[WrappersReflection.WrapperValueFieldNumber].Accessor.SetValue(expected, expectedValue);
+ Assert.AreEqual(expected, parsed);
+ }
+
+ [Test]
+ public void ExplicitNullValue()
+ {
+ string json = "{\"valueField\": null}";
+ var message = JsonParser.Default.Parse<TestWellKnownTypes>(json);
+ Assert.AreEqual(new TestWellKnownTypes { ValueField = Value.ForNull() }, message);
+ }
+
+ [Test]
+ public void BytesWrapper_Standalone()
+ {
+ ByteString data = ByteString.CopyFrom(1, 2, 3);
+ // Can't do this with attributes...
+ var parsed = JsonParser.Default.Parse<BytesValue>(WrapInQuotes(data.ToBase64()));
+ var expected = new BytesValue { Value = data };
+ Assert.AreEqual(expected, parsed);
+ }
+
+ [Test]
+ public void RepeatedWrappers()
+ {
+ var message = new RepeatedWellKnownTypes
+ {
+ BoolField = { true, false },
+ BytesField = { ByteString.CopyFrom(1, 2, 3), ByteString.CopyFrom(4, 5, 6), ByteString.Empty },
+ DoubleField = { 12.5, -1.5, 0d },
+ FloatField = { 123.25f, -20f, 0f },
+ Int32Field = { int.MaxValue, int.MinValue, 0 },
+ Int64Field = { long.MaxValue, long.MinValue, 0L },
+ StringField = { "First", "Second", "" },
+ Uint32Field = { uint.MaxValue, uint.MinValue, 0U },
+ Uint64Field = { ulong.MaxValue, ulong.MinValue, 0UL },
+ };
+ AssertRoundtrip(message);
+ }
+
+ [Test]
+ public void RepeatedField_NullElementProhibited()
+ {
+ string json = "{ \"repeated_foreign_message\": [null] }";
+ Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json));
+ }
+
+ [Test]
+ public void RepeatedField_NullOverallValueAllowed()
+ {
+ string json = "{ \"repeated_foreign_message\": null }";
+ Assert.AreEqual(new TestAllTypes(), TestAllTypes.Parser.ParseJson(json));
+ }
+
+ [Test]
+ [TestCase("{ \"mapInt32Int32\": { \"10\": null }")]
+ [TestCase("{ \"mapStringString\": { \"abc\": null }")]
+ [TestCase("{ \"mapInt32ForeignMessage\": { \"10\": null }")]
+ public void MapField_NullValueProhibited(string json)
+ {
+ Assert.Throws<InvalidProtocolBufferException>(() => TestMap.Parser.ParseJson(json));
+ }
+
+ [Test]
+ public void MapField_NullOverallValueAllowed()
+ {
+ string json = "{ \"mapInt32Int32\": null }";
+ Assert.AreEqual(new TestMap(), TestMap.Parser.ParseJson(json));
+ }
+
+ [Test]
+ public void IndividualWrapperTypes()
+ {
+ Assert.AreEqual(new StringValue { Value = "foo" }, StringValue.Parser.ParseJson("\"foo\""));
+ Assert.AreEqual(new Int32Value { Value = 1 }, Int32Value.Parser.ParseJson("1"));
+ // Can parse strings directly too
+ Assert.AreEqual(new Int32Value { Value = 1 }, Int32Value.Parser.ParseJson("\"1\""));
+ }
+
+ private static void AssertRoundtrip<T>(T message) where T : IMessage<T>, new()
+ {
+ var clone = message.Clone();
+ var json = JsonFormatter.Default.Format(message);
+ var parsed = JsonParser.Default.Parse<T>(json);
+ Assert.AreEqual(clone, parsed);
+ }
+
+ [Test]
+ [TestCase("0", 0)]
+ [TestCase("-0", 0)] // Not entirely clear whether we intend to allow this...
+ [TestCase("1", 1)]
+ [TestCase("-1", -1)]
+ [TestCase("2147483647", 2147483647)]
+ [TestCase("-2147483648", -2147483648)]
+ public void StringToInt32_Valid(string jsonValue, int expectedParsedValue)
+ {
+ string json = "{ \"singleInt32\": \"" + jsonValue + "\"}";
+ var parsed = TestAllTypes.Parser.ParseJson(json);
+ Assert.AreEqual(expectedParsedValue, parsed.SingleInt32);
+ }
+
+ [Test]
+ [TestCase("+0")]
+ [TestCase(" 1")]
+ [TestCase("1 ")]
+ [TestCase("00")]
+ [TestCase("-00")]
+ [TestCase("--1")]
+ [TestCase("+1")]
+ [TestCase("1.5")]
+ [TestCase("1e10")]
+ [TestCase("2147483648")]
+ [TestCase("-2147483649")]
+ public void StringToInt32_Invalid(string jsonValue)
+ {
+ string json = "{ \"singleInt32\": \"" + jsonValue + "\"}";
+ Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json));
+ }
+
+ [Test]
+ [TestCase("0", 0U)]
+ [TestCase("1", 1U)]
+ [TestCase("4294967295", 4294967295U)]
+ public void StringToUInt32_Valid(string jsonValue, uint expectedParsedValue)
+ {
+ string json = "{ \"singleUint32\": \"" + jsonValue + "\"}";
+ var parsed = TestAllTypes.Parser.ParseJson(json);
+ Assert.AreEqual(expectedParsedValue, parsed.SingleUint32);
+ }
+
+ // Assume that anything non-bounds-related is covered in the Int32 case
+ [Test]
+ [TestCase("-1")]
+ [TestCase("4294967296")]
+ public void StringToUInt32_Invalid(string jsonValue)
+ {
+ string json = "{ \"singleUint32\": \"" + jsonValue + "\"}";
+ Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json));
+ }
+
+ [Test]
+ [TestCase("0", 0L)]
+ [TestCase("1", 1L)]
+ [TestCase("-1", -1L)]
+ [TestCase("9223372036854775807", 9223372036854775807)]
+ [TestCase("-9223372036854775808", -9223372036854775808)]
+ public void StringToInt64_Valid(string jsonValue, long expectedParsedValue)
+ {
+ string json = "{ \"singleInt64\": \"" + jsonValue + "\"}";
+ var parsed = TestAllTypes.Parser.ParseJson(json);
+ Assert.AreEqual(expectedParsedValue, parsed.SingleInt64);
+ }
+
+ // Assume that anything non-bounds-related is covered in the Int32 case
+ [Test]
+ [TestCase("-9223372036854775809")]
+ [TestCase("9223372036854775808")]
+ public void StringToInt64_Invalid(string jsonValue)
+ {
+ string json = "{ \"singleInt64\": \"" + jsonValue + "\"}";
+ Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json));
+ }
+
+ [Test]
+ [TestCase("0", 0UL)]
+ [TestCase("1", 1UL)]
+ [TestCase("18446744073709551615", 18446744073709551615)]
+ public void StringToUInt64_Valid(string jsonValue, ulong expectedParsedValue)
+ {
+ string json = "{ \"singleUint64\": \"" + jsonValue + "\"}";
+ var parsed = TestAllTypes.Parser.ParseJson(json);
+ Assert.AreEqual(expectedParsedValue, parsed.SingleUint64);
+ }
+
+ // Assume that anything non-bounds-related is covered in the Int32 case
+ [Test]
+ [TestCase("-1")]
+ [TestCase("18446744073709551616")]
+ public void StringToUInt64_Invalid(string jsonValue)
+ {
+ string json = "{ \"singleUint64\": \"" + jsonValue + "\"}";
+ Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json));
+ }
+
+ [Test]
+ [TestCase("0", 0d)]
+ [TestCase("1", 1d)]
+ [TestCase("1.000000", 1d)]
+ [TestCase("1.0000000000000000000000001", 1d)] // We don't notice that we haven't preserved the exact value
+ [TestCase("-1", -1d)]
+ [TestCase("1e1", 10d)]
+ [TestCase("1e01", 10d)] // Leading decimals are allowed in exponents
+ [TestCase("1E1", 10d)] // Either case is fine
+ [TestCase("-1e1", -10d)]
+ [TestCase("1.5e1", 15d)]
+ [TestCase("-1.5e1", -15d)]
+ [TestCase("15e-1", 1.5d)]
+ [TestCase("-15e-1", -1.5d)]
+ [TestCase("1.79769e308", 1.79769e308)]
+ [TestCase("-1.79769e308", -1.79769e308)]
+ [TestCase("Infinity", double.PositiveInfinity)]
+ [TestCase("-Infinity", double.NegativeInfinity)]
+ [TestCase("NaN", double.NaN)]
+ public void StringToDouble_Valid(string jsonValue, double expectedParsedValue)
+ {
+ string json = "{ \"singleDouble\": \"" + jsonValue + "\"}";
+ var parsed = TestAllTypes.Parser.ParseJson(json);
+ Assert.AreEqual(expectedParsedValue, parsed.SingleDouble);
+ }
+
+ [Test]
+ [TestCase("1.7977e308")]
+ [TestCase("-1.7977e308")]
+ [TestCase("1e309")]
+ [TestCase("1,0")]
+ [TestCase("1.0.0")]
+ [TestCase("+1")]
+ [TestCase("00")]
+ [TestCase("01")]
+ [TestCase("-00")]
+ [TestCase("-01")]
+ [TestCase("--1")]
+ [TestCase(" Infinity")]
+ [TestCase(" -Infinity")]
+ [TestCase("NaN ")]
+ [TestCase("Infinity ")]
+ [TestCase("-Infinity ")]
+ [TestCase(" NaN")]
+ [TestCase("INFINITY")]
+ [TestCase("nan")]
+ [TestCase("\u00BD")] // 1/2 as a single Unicode character. Just sanity checking...
+ public void StringToDouble_Invalid(string jsonValue)
+ {
+ string json = "{ \"singleDouble\": \"" + jsonValue + "\"}";
+ Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json));
+ }
+
+ [Test]
+ [TestCase("0", 0f)]
+ [TestCase("1", 1f)]
+ [TestCase("1.000000", 1f)]
+ [TestCase("-1", -1f)]
+ [TestCase("3.402823e38", 3.402823e38f)]
+ [TestCase("-3.402823e38", -3.402823e38f)]
+ [TestCase("1.5e1", 15f)]
+ [TestCase("15e-1", 1.5f)]
+ public void StringToFloat_Valid(string jsonValue, float expectedParsedValue)
+ {
+ string json = "{ \"singleFloat\": \"" + jsonValue + "\"}";
+ var parsed = TestAllTypes.Parser.ParseJson(json);
+ Assert.AreEqual(expectedParsedValue, parsed.SingleFloat);
+ }
+
+ [Test]
+ [TestCase("3.402824e38")]
+ [TestCase("-3.402824e38")]
+ [TestCase("1,0")]
+ [TestCase("1.0.0")]
+ [TestCase("+1")]
+ [TestCase("00")]
+ [TestCase("--1")]
+ public void StringToFloat_Invalid(string jsonValue)
+ {
+ string json = "{ \"singleFloat\": \"" + jsonValue + "\"}";
+ Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json));
+ }
+
+ [Test]
+ [TestCase("0", 0)]
+ [TestCase("-0", 0)] // Not entirely clear whether we intend to allow this...
+ [TestCase("1", 1)]
+ [TestCase("-1", -1)]
+ [TestCase("2147483647", 2147483647)]
+ [TestCase("-2147483648", -2147483648)]
+ [TestCase("1e1", 10)]
+ [TestCase("-1e1", -10)]
+ [TestCase("10.00", 10)]
+ [TestCase("-10.00", -10)]
+ public void NumberToInt32_Valid(string jsonValue, int expectedParsedValue)
+ {
+ string json = "{ \"singleInt32\": " + jsonValue + "}";
+ var parsed = TestAllTypes.Parser.ParseJson(json);
+ Assert.AreEqual(expectedParsedValue, parsed.SingleInt32);
+ }
+
+ [Test]
+ [TestCase("+0", typeof(InvalidJsonException))]
+ [TestCase("00", typeof(InvalidJsonException))]
+ [TestCase("-00", typeof(InvalidJsonException))]
+ [TestCase("--1", typeof(InvalidJsonException))]
+ [TestCase("+1", typeof(InvalidJsonException))]
+ [TestCase("1.5", typeof(InvalidProtocolBufferException))]
+ // Value is out of range
+ [TestCase("1e10", typeof(InvalidProtocolBufferException))]
+ [TestCase("2147483648", typeof(InvalidProtocolBufferException))]
+ [TestCase("-2147483649", typeof(InvalidProtocolBufferException))]
+ public void NumberToInt32_Invalid(string jsonValue, System.Type expectedExceptionType)
+ {
+ string json = "{ \"singleInt32\": " + jsonValue + "}";
+ Assert.Throws(expectedExceptionType, () => TestAllTypes.Parser.ParseJson(json));
+ }
+
+ [Test]
+ [TestCase("0", 0U)]
+ [TestCase("1", 1U)]
+ [TestCase("4294967295", 4294967295U)]
+ public void NumberToUInt32_Valid(string jsonValue, uint expectedParsedValue)
+ {
+ string json = "{ \"singleUint32\": " + jsonValue + "}";
+ var parsed = TestAllTypes.Parser.ParseJson(json);
+ Assert.AreEqual(expectedParsedValue, parsed.SingleUint32);
+ }
+
+ // Assume that anything non-bounds-related is covered in the Int32 case
+ [Test]
+ [TestCase("-1")]
+ [TestCase("4294967296")]
+ public void NumberToUInt32_Invalid(string jsonValue)
+ {
+ string json = "{ \"singleUint32\": " + jsonValue + "}";
+ Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json));
+ }
+
+ [Test]
+ [TestCase("0", 0L)]
+ [TestCase("1", 1L)]
+ [TestCase("-1", -1L)]
+ // long.MaxValue isn't actually representable as a double. This string value is the highest
+ // representable value which isn't greater than long.MaxValue.
+ [TestCase("9223372036854774784", 9223372036854774784)]
+ [TestCase("-9223372036854775808", -9223372036854775808)]
+ public void NumberToInt64_Valid(string jsonValue, long expectedParsedValue)
+ {
+ string json = "{ \"singleInt64\": " + jsonValue + "}";
+ var parsed = TestAllTypes.Parser.ParseJson(json);
+ Assert.AreEqual(expectedParsedValue, parsed.SingleInt64);
+ }
+
+ // Assume that anything non-bounds-related is covered in the Int32 case
+ [Test]
+ [TestCase("9223372036854775808")]
+ // Theoretical bound would be -9223372036854775809, but when that is parsed to a double
+ // we end up with the exact value of long.MinValue due to lack of precision. The value here
+ // is the "next double down".
+ [TestCase("-9223372036854780000")]
+ public void NumberToInt64_Invalid(string jsonValue)
+ {
+ string json = "{ \"singleInt64\": " + jsonValue + "}";
+ Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json));
+ }
+
+ [Test]
+ [TestCase("0", 0UL)]
+ [TestCase("1", 1UL)]
+ // ulong.MaxValue isn't representable as a double. This value is the largest double within
+ // the range of ulong.
+ [TestCase("18446744073709549568", 18446744073709549568UL)]
+ public void NumberToUInt64_Valid(string jsonValue, ulong expectedParsedValue)
+ {
+ string json = "{ \"singleUint64\": " + jsonValue + "}";
+ var parsed = TestAllTypes.Parser.ParseJson(json);
+ Assert.AreEqual(expectedParsedValue, parsed.SingleUint64);
+ }
+
+ // Assume that anything non-bounds-related is covered in the Int32 case
+ [Test]
+ [TestCase("-1")]
+ [TestCase("18446744073709551616")]
+ public void NumberToUInt64_Invalid(string jsonValue)
+ {
+ string json = "{ \"singleUint64\": " + jsonValue + "}";
+ Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json));
+ }
+
+ [Test]
+ [TestCase("0", 0d)]
+ [TestCase("1", 1d)]
+ [TestCase("1.000000", 1d)]
+ [TestCase("1.0000000000000000000000001", 1d)] // We don't notice that we haven't preserved the exact value
+ [TestCase("-1", -1d)]
+ [TestCase("1e1", 10d)]
+ [TestCase("1e01", 10d)] // Leading decimals are allowed in exponents
+ [TestCase("1E1", 10d)] // Either case is fine
+ [TestCase("-1e1", -10d)]
+ [TestCase("1.5e1", 15d)]
+ [TestCase("-1.5e1", -15d)]
+ [TestCase("15e-1", 1.5d)]
+ [TestCase("-15e-1", -1.5d)]
+ [TestCase("1.79769e308", 1.79769e308)]
+ [TestCase("-1.79769e308", -1.79769e308)]
+ public void NumberToDouble_Valid(string jsonValue, double expectedParsedValue)
+ {
+ string json = "{ \"singleDouble\": " + jsonValue + "}";
+ var parsed = TestAllTypes.Parser.ParseJson(json);
+ Assert.AreEqual(expectedParsedValue, parsed.SingleDouble);
+ }
+
+ [Test]
+ [TestCase("1.7977e308")]
+ [TestCase("-1.7977e308")]
+ [TestCase("1e309")]
+ [TestCase("1,0")]
+ [TestCase("1.0.0")]
+ [TestCase("+1")]
+ [TestCase("00")]
+ [TestCase("--1")]
+ [TestCase("\u00BD")] // 1/2 as a single Unicode character. Just sanity checking...
+ public void NumberToDouble_Invalid(string jsonValue)
+ {
+ string json = "{ \"singleDouble\": " + jsonValue + "}";
+ Assert.Throws<InvalidJsonException>(() => TestAllTypes.Parser.ParseJson(json));
+ }
+
+ [Test]
+ [TestCase("0", 0f)]
+ [TestCase("1", 1f)]
+ [TestCase("1.000000", 1f)]
+ [TestCase("-1", -1f)]
+ [TestCase("3.402823e38", 3.402823e38f)]
+ [TestCase("-3.402823e38", -3.402823e38f)]
+ [TestCase("1.5e1", 15f)]
+ [TestCase("15e-1", 1.5f)]
+ public void NumberToFloat_Valid(string jsonValue, float expectedParsedValue)
+ {
+ string json = "{ \"singleFloat\": " + jsonValue + "}";
+ var parsed = TestAllTypes.Parser.ParseJson(json);
+ Assert.AreEqual(expectedParsedValue, parsed.SingleFloat);
+ }
+
+ [Test]
+ [TestCase("3.402824e38", typeof(InvalidProtocolBufferException))]
+ [TestCase("-3.402824e38", typeof(InvalidProtocolBufferException))]
+ [TestCase("1,0", typeof(InvalidJsonException))]
+ [TestCase("1.0.0", typeof(InvalidJsonException))]
+ [TestCase("+1", typeof(InvalidJsonException))]
+ [TestCase("00", typeof(InvalidJsonException))]
+ [TestCase("--1", typeof(InvalidJsonException))]
+ public void NumberToFloat_Invalid(string jsonValue, System.Type expectedExceptionType)
+ {
+ string json = "{ \"singleFloat\": " + jsonValue + "}";
+ Assert.Throws(expectedExceptionType, () => TestAllTypes.Parser.ParseJson(json));
+ }
+
+ // The simplest way of testing that the value has parsed correctly is to reformat it,
+ // as we trust the formatting. In many cases that will give the same result as the input,
+ // so in those cases we accept an expectedFormatted value of null. Sometimes the results
+ // will be different though, due to a different number of digits being provided.
+ [Test]
+ // Z offset
+ [TestCase("2015-10-09T14:46:23.123456789Z", null)]
+ [TestCase("2015-10-09T14:46:23.123456Z", null)]
+ [TestCase("2015-10-09T14:46:23.123Z", null)]
+ [TestCase("2015-10-09T14:46:23Z", null)]
+ [TestCase("2015-10-09T14:46:23.123456000Z", "2015-10-09T14:46:23.123456Z")]
+ [TestCase("2015-10-09T14:46:23.1234560Z", "2015-10-09T14:46:23.123456Z")]
+ [TestCase("2015-10-09T14:46:23.123000000Z", "2015-10-09T14:46:23.123Z")]
+ [TestCase("2015-10-09T14:46:23.1230Z", "2015-10-09T14:46:23.123Z")]
+ [TestCase("2015-10-09T14:46:23.00Z", "2015-10-09T14:46:23Z")]
+
+ // +00:00 offset
+ [TestCase("2015-10-09T14:46:23.123456789+00:00", "2015-10-09T14:46:23.123456789Z")]
+ [TestCase("2015-10-09T14:46:23.123456+00:00", "2015-10-09T14:46:23.123456Z")]
+ [TestCase("2015-10-09T14:46:23.123+00:00", "2015-10-09T14:46:23.123Z")]
+ [TestCase("2015-10-09T14:46:23+00:00", "2015-10-09T14:46:23Z")]
+ [TestCase("2015-10-09T14:46:23.123456000+00:00", "2015-10-09T14:46:23.123456Z")]
+ [TestCase("2015-10-09T14:46:23.1234560+00:00", "2015-10-09T14:46:23.123456Z")]
+ [TestCase("2015-10-09T14:46:23.123000000+00:00", "2015-10-09T14:46:23.123Z")]
+ [TestCase("2015-10-09T14:46:23.1230+00:00", "2015-10-09T14:46:23.123Z")]
+ [TestCase("2015-10-09T14:46:23.00+00:00", "2015-10-09T14:46:23Z")]
+
+ // Other offsets (assume by now that the subsecond handling is okay)
+ [TestCase("2015-10-09T15:46:23.123456789+01:00", "2015-10-09T14:46:23.123456789Z")]
+ [TestCase("2015-10-09T13:46:23.123456789-01:00", "2015-10-09T14:46:23.123456789Z")]
+ [TestCase("2015-10-09T15:16:23.123456789+00:30", "2015-10-09T14:46:23.123456789Z")]
+ [TestCase("2015-10-09T14:16:23.123456789-00:30", "2015-10-09T14:46:23.123456789Z")]
+ [TestCase("2015-10-09T16:31:23.123456789+01:45", "2015-10-09T14:46:23.123456789Z")]
+ [TestCase("2015-10-09T13:01:23.123456789-01:45", "2015-10-09T14:46:23.123456789Z")]
+ [TestCase("2015-10-10T08:46:23.123456789+18:00", "2015-10-09T14:46:23.123456789Z")]
+ [TestCase("2015-10-08T20:46:23.123456789-18:00", "2015-10-09T14:46:23.123456789Z")]
+
+ // Leap years and min/max
+ [TestCase("2016-02-29T14:46:23.123456789Z", null)]
+ [TestCase("2000-02-29T14:46:23.123456789Z", null)]
+ [TestCase("0001-01-01T00:00:00Z", null)]
+ [TestCase("9999-12-31T23:59:59.999999999Z", null)]
+ public void Timestamp_Valid(string jsonValue, string expectedFormatted)
+ {
+ expectedFormatted = expectedFormatted ?? jsonValue;
+ string json = WrapInQuotes(jsonValue);
+ var parsed = Timestamp.Parser.ParseJson(json);
+ Assert.AreEqual(WrapInQuotes(expectedFormatted), parsed.ToString());
+ }
+
+ [Test]
+ [TestCase("2015-10-09 14:46:23.123456789Z", Description = "No T between date and time")]
+ [TestCase("2015/10/09T14:46:23.123456789Z", Description = "Wrong date separators")]
+ [TestCase("2015-10-09T14.46.23.123456789Z", Description = "Wrong time separators")]
+ [TestCase("2015-10-09T14:46:23,123456789Z", Description = "Wrong fractional second separators (valid ISO-8601 though)")]
+ [TestCase(" 2015-10-09T14:46:23.123456789Z", Description = "Whitespace at start")]
+ [TestCase("2015-10-09T14:46:23.123456789Z ", Description = "Whitespace at end")]
+ [TestCase("2015-10-09T14:46:23.1234567890", Description = "Too many digits")]
+ [TestCase("2015-10-09T14:46:23.123456789", Description = "No offset")]
+ [TestCase("2015-13-09T14:46:23.123456789Z", Description = "Invalid month")]
+ [TestCase("2015-10-32T14:46:23.123456789Z", Description = "Invalid day")]
+ [TestCase("2015-10-09T24:00:00.000000000Z", Description = "Invalid hour (valid ISO-8601 though)")]
+ [TestCase("2015-10-09T14:60:23.123456789Z", Description = "Invalid minutes")]
+ [TestCase("2015-10-09T14:46:60.123456789Z", Description = "Invalid seconds")]
+ [TestCase("2015-10-09T14:46:23.123456789+18:01", Description = "Offset too large (positive)")]
+ [TestCase("2015-10-09T14:46:23.123456789-18:01", Description = "Offset too large (negative)")]
+ [TestCase("2015-10-09T14:46:23.123456789-00:00", Description = "Local offset (-00:00) makes no sense here")]
+ [TestCase("0001-01-01T00:00:00+00:01", Description = "Value before earliest when offset applied")]
+ [TestCase("9999-12-31T23:59:59.999999999-00:01", Description = "Value after latest when offset applied")]
+ [TestCase("2100-02-29T14:46:23.123456789Z", Description = "Feb 29th on a non-leap-year")]
+ public void Timestamp_Invalid(string jsonValue)
+ {
+ string json = WrapInQuotes(jsonValue);
+ Assert.Throws<InvalidProtocolBufferException>(() => Timestamp.Parser.ParseJson(json));
+ }
+
+ [Test]
+ public void StructValue_Null()
+ {
+ Assert.AreEqual(new Value { NullValue = 0 }, Value.Parser.ParseJson("null"));
+ }
+
+ [Test]
+ public void StructValue_String()
+ {
+ Assert.AreEqual(new Value { StringValue = "hi" }, Value.Parser.ParseJson("\"hi\""));
+ }
+
+ [Test]
+ public void StructValue_Bool()
+ {
+ Assert.AreEqual(new Value { BoolValue = true }, Value.Parser.ParseJson("true"));
+ Assert.AreEqual(new Value { BoolValue = false }, Value.Parser.ParseJson("false"));
+ }
+
+ [Test]
+ public void StructValue_List()
+ {
+ Assert.AreEqual(Value.ForList(Value.ForNumber(1), Value.ForString("x")), Value.Parser.ParseJson("[1, \"x\"]"));
+ }
+
+ [Test]
+ public void ParseListValue()
+ {
+ Assert.AreEqual(new ListValue { Values = { Value.ForNumber(1), Value.ForString("x") } }, ListValue.Parser.ParseJson("[1, \"x\"]"));
+ }
+
+ [Test]
+ public void StructValue_Struct()
+ {
+ Assert.AreEqual(
+ Value.ForStruct(new Struct { Fields = { { "x", Value.ForNumber(1) }, { "y", Value.ForString("z") } } }),
+ Value.Parser.ParseJson("{ \"x\": 1, \"y\": \"z\" }"));
+ }
+
+ [Test]
+ public void ParseStruct()
+ {
+ Assert.AreEqual(new Struct { Fields = { { "x", Value.ForNumber(1) }, { "y", Value.ForString("z") } } },
+ Struct.Parser.ParseJson("{ \"x\": 1, \"y\": \"z\" }"));
+ }
+
+ // TODO for duration parsing: upper and lower bounds.
+ // +/- 315576000000 seconds
+
+ [Test]
+ [TestCase("1.123456789s", null)]
+ [TestCase("1.123456s", null)]
+ [TestCase("1.123s", null)]
+ [TestCase("1.12300s", "1.123s")]
+ [TestCase("1.12345s", "1.123450s")]
+ [TestCase("1s", null)]
+ [TestCase("-1.123456789s", null)]
+ [TestCase("-1.123456s", null)]
+ [TestCase("-1.123s", null)]
+ [TestCase("-1s", null)]
+ [TestCase("0.123s", null)]
+ [TestCase("-0.123s", null)]
+ [TestCase("123456.123s", null)]
+ [TestCase("-123456.123s", null)]
+ // Upper and lower bounds
+ [TestCase("315576000000s", null)]
+ [TestCase("-315576000000s", null)]
+ public void Duration_Valid(string jsonValue, string expectedFormatted)
+ {
+ expectedFormatted = expectedFormatted ?? jsonValue;
+ string json = WrapInQuotes(jsonValue);
+ var parsed = Duration.Parser.ParseJson(json);
+ Assert.AreEqual(WrapInQuotes(expectedFormatted), parsed.ToString());
+ }
+
+ // The simplest way of testing that the value has parsed correctly is to reformat it,
+ // as we trust the formatting. In many cases that will give the same result as the input,
+ // so in those cases we accept an expectedFormatted value of null. Sometimes the results
+ // will be different though, due to a different number of digits being provided.
+ [Test]
+ [TestCase("1.1234567890s", Description = "Too many digits")]
+ [TestCase("1.123456789", Description = "No suffix")]
+ [TestCase("1.123456789ss", Description = "Too much suffix")]
+ [TestCase("1.123456789S", Description = "Upper case suffix")]
+ [TestCase("+1.123456789s", Description = "Leading +")]
+ [TestCase(".123456789s", Description = "No integer before the fraction")]
+ [TestCase("1,123456789s", Description = "Comma as decimal separator")]
+ [TestCase("1x1.123456789s", Description = "Non-digit in integer part")]
+ [TestCase("1.1x3456789s", Description = "Non-digit in fractional part")]
+ [TestCase(" 1.123456789s", Description = "Whitespace before fraction")]
+ [TestCase("1.123456789s ", Description = "Whitespace after value")]
+ [TestCase("01.123456789s", Description = "Leading zero (positive)")]
+ [TestCase("-01.123456789s", Description = "Leading zero (negative)")]
+ [TestCase("--0.123456789s", Description = "Double minus sign")]
+ // Violate upper/lower bounds in various ways
+ [TestCase("315576000001s", Description = "Integer part too large")]
+ [TestCase("3155760000000s", Description = "Integer part too long (positive)")]
+ [TestCase("-3155760000000s", Description = "Integer part too long (negative)")]
+ public void Duration_Invalid(string jsonValue)
+ {
+ string json = WrapInQuotes(jsonValue);
+ Assert.Throws<InvalidProtocolBufferException>(() => Duration.Parser.ParseJson(json));
+ }
+
+ // Not as many tests for field masks as I'd like; more to be added when we have more
+ // detailed specifications.
+
+ [Test]
+ [TestCase("")]
+ [TestCase("foo", "foo")]
+ [TestCase("foo,bar", "foo", "bar")]
+ [TestCase("foo.bar", "foo.bar")]
+ [TestCase("fooBar", "foo_bar")]
+ [TestCase("fooBar.bazQux", "foo_bar.baz_qux")]
+ public void FieldMask_Valid(string jsonValue, params string[] expectedPaths)
+ {
+ string json = WrapInQuotes(jsonValue);
+ var parsed = FieldMask.Parser.ParseJson(json);
+ CollectionAssert.AreEqual(expectedPaths, parsed.Paths);
+ }
+
+ [Test]
+ [TestCase("foo_bar")]
+ public void FieldMask_Invalid(string jsonValue)
+ {
+ string json = WrapInQuotes(jsonValue);
+ Assert.Throws<InvalidProtocolBufferException>(() => FieldMask.Parser.ParseJson(json));
+ }
+
+ [Test]
+ public void Any_RegularMessage()
+ {
+ var registry = TypeRegistry.FromMessages(TestAllTypes.Descriptor);
+ var formatter = new JsonFormatter(new JsonFormatter.Settings(false, TypeRegistry.FromMessages(TestAllTypes.Descriptor)));
+ var message = new TestAllTypes { SingleInt32 = 10, SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 20 } };
+ var original = Any.Pack(message);
+ var json = formatter.Format(original); // This is tested in JsonFormatterTest
+ var parser = new JsonParser(new JsonParser.Settings(10, registry));
+ Assert.AreEqual(original, parser.Parse<Any>(json));
+ string valueFirstJson = "{ \"singleInt32\": 10, \"singleNestedMessage\": { \"bb\": 20 }, \"@type\": \"type.googleapis.com/protobuf_unittest.TestAllTypes\" }";
+ Assert.AreEqual(original, parser.Parse<Any>(valueFirstJson));
+ }
+
+ [Test]
+ public void Any_CustomPrefix()
+ {
+ var registry = TypeRegistry.FromMessages(TestAllTypes.Descriptor);
+ var message = new TestAllTypes { SingleInt32 = 10 };
+ var original = Any.Pack(message, "custom.prefix/middle-part");
+ var parser = new JsonParser(new JsonParser.Settings(10, registry));
+ string json = "{ \"@type\": \"custom.prefix/middle-part/protobuf_unittest.TestAllTypes\", \"singleInt32\": 10 }";
+ Assert.AreEqual(original, parser.Parse<Any>(json));
+ }
+
+ [Test]
+ public void Any_UnknownType()
+ {
+ string json = "{ \"@type\": \"type.googleapis.com/bogus\" }";
+ Assert.Throws<InvalidOperationException>(() => Any.Parser.ParseJson(json));
+ }
+
+ [Test]
+ public void Any_NoTypeUrl()
+ {
+ string json = "{ \"foo\": \"bar\" }";
+ Assert.Throws<InvalidProtocolBufferException>(() => Any.Parser.ParseJson(json));
+ }
+
+ [Test]
+ public void Any_WellKnownType()
+ {
+ var registry = TypeRegistry.FromMessages(Timestamp.Descriptor);
+ var formatter = new JsonFormatter(new JsonFormatter.Settings(false, registry));
+ var timestamp = new DateTime(1673, 6, 19, 12, 34, 56, DateTimeKind.Utc).ToTimestamp();
+ var original = Any.Pack(timestamp);
+ var json = formatter.Format(original); // This is tested in JsonFormatterTest
+ var parser = new JsonParser(new JsonParser.Settings(10, registry));
+ Assert.AreEqual(original, parser.Parse<Any>(json));
+ string valueFirstJson = "{ \"value\": \"1673-06-19T12:34:56Z\", \"@type\": \"type.googleapis.com/google.protobuf.Timestamp\" }";
+ Assert.AreEqual(original, parser.Parse<Any>(valueFirstJson));
+ }
+
+ [Test]
+ public void Any_Nested()
+ {
+ var registry = TypeRegistry.FromMessages(TestWellKnownTypes.Descriptor, TestAllTypes.Descriptor);
+ var formatter = new JsonFormatter(new JsonFormatter.Settings(false, registry));
+ var parser = new JsonParser(new JsonParser.Settings(10, registry));
+ var doubleNestedMessage = new TestAllTypes { SingleInt32 = 20 };
+ var nestedMessage = Any.Pack(doubleNestedMessage);
+ var message = new TestWellKnownTypes { AnyField = Any.Pack(nestedMessage) };
+ var json = formatter.Format(message);
+ // Use the descriptor-based parser just for a change.
+ Assert.AreEqual(message, parser.Parse(json, TestWellKnownTypes.Descriptor));
+ }
+
+ [Test]
+ public void DataAfterObject()
+ {
+ string json = "{} 10";
+ Assert.Throws<InvalidJsonException>(() => TestAllTypes.Parser.ParseJson(json));
+ }
+
+ /// <summary>
+ /// JSON equivalent to <see cref="CodedInputStreamTest.MaliciousRecursion"/>
+ /// </summary>
+ [Test]
+ public void MaliciousRecursion()
+ {
+ string data64 = CodedInputStreamTest.MakeRecursiveMessage(64).ToString();
+ string data65 = CodedInputStreamTest.MakeRecursiveMessage(65).ToString();
+
+ var parser64 = new JsonParser(new JsonParser.Settings(64));
+ CodedInputStreamTest.AssertMessageDepth(parser64.Parse<TestRecursiveMessage>(data64), 64);
+ Assert.Throws<InvalidProtocolBufferException>(() => parser64.Parse<TestRecursiveMessage>(data65));
+
+ var parser63 = new JsonParser(new JsonParser.Settings(63));
+ Assert.Throws<InvalidProtocolBufferException>(() => parser63.Parse<TestRecursiveMessage>(data64));
+ }
+
+ [Test]
+ [TestCase("AQI")]
+ [TestCase("_-==")]
+ public void Bytes_InvalidBase64(string badBase64)
+ {
+ string json = "{ \"singleBytes\": \"" + badBase64 + "\" }";
+ Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json));
+ }
+
+ [Test]
+ [TestCase("\"FOREIGN_BAR\"", ForeignEnum.ForeignBar)]
+ [TestCase("5", ForeignEnum.ForeignBar)]
+ [TestCase("100", (ForeignEnum)100)]
+ public void EnumValid(string value, ForeignEnum expectedValue)
+ {
+ string json = "{ \"singleForeignEnum\": " + value + " }";
+ var parsed = TestAllTypes.Parser.ParseJson(json);
+ Assert.AreEqual(new TestAllTypes { SingleForeignEnum = expectedValue }, parsed);
+ }
+
+ [Test]
+ [TestCase("\"NOT_A_VALID_VALUE\"")]
+ [TestCase("5.5")]
+ public void Enum_Invalid(string value)
+ {
+ string json = "{ \"singleForeignEnum\": " + value + " }";
+ Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json));
+ }
+
+ [Test]
+ public void OneofDuplicate_Invalid()
+ {
+ string json = "{ \"oneofString\": \"x\", \"oneofUint32\": 10 }";
+ Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json));
+ }
+
+ /// <summary>
+ /// Various tests use strings which have quotes round them for parsing or as the result
+ /// of formatting, but without those quotes being specified in the tests (for the sake of readability).
+ /// This method simply returns the input, wrapped in double quotes.
+ /// </summary>
+ internal static string WrapInQuotes(string text)
+ {
+ return '"' + text + '"';
+ }
+ }
+} \ No newline at end of file
diff --git a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/JsonTokenizerTest.cs b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/JsonTokenizerTest.cs
new file mode 100644
index 00000000..527ab336
--- /dev/null
+++ b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/JsonTokenizerTest.cs
@@ -0,0 +1,408 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+using NUnit.Framework;
+using System;
+using System.IO;
+
+namespace Google.Protobuf
+{
+ public class JsonTokenizerTest
+ {
+ [Test]
+ public void EmptyObjectValue()
+ {
+ AssertTokens("{}", JsonToken.StartObject, JsonToken.EndObject);
+ }
+
+ [Test]
+ public void EmptyArrayValue()
+ {
+ AssertTokens("[]", JsonToken.StartArray, JsonToken.EndArray);
+ }
+
+ [Test]
+ [TestCase("foo", "foo")]
+ [TestCase("tab\\t", "tab\t")]
+ [TestCase("line\\nfeed", "line\nfeed")]
+ [TestCase("carriage\\rreturn", "carriage\rreturn")]
+ [TestCase("back\\bspace", "back\bspace")]
+ [TestCase("form\\ffeed", "form\ffeed")]
+ [TestCase("escaped\\/slash", "escaped/slash")]
+ [TestCase("escaped\\\\backslash", "escaped\\backslash")]
+ [TestCase("escaped\\\"quote", "escaped\"quote")]
+ [TestCase("foo {}[] bar", "foo {}[] bar")]
+ [TestCase("foo\\u09aFbar", "foo\u09afbar")] // Digits, upper hex, lower hex
+ [TestCase("ab\ud800\udc00cd", "ab\ud800\udc00cd")]
+ [TestCase("ab\\ud800\\udc00cd", "ab\ud800\udc00cd")]
+ public void StringValue(string json, string expectedValue)
+ {
+ AssertTokensNoReplacement("\"" + json + "\"", JsonToken.Value(expectedValue));
+ }
+
+ // Valid surrogate pairs, with mixed escaping. These test cases can't be expressed
+ // using TestCase as they have no valid UTF-8 representation.
+ // It's unclear exactly how we should handle a mixture of escaped or not: that can't
+ // come from UTF-8 text, but could come from a .NET string. For the moment,
+ // treat it as valid in the obvious way.
+ [Test]
+ public void MixedSurrogatePairs()
+ {
+ string expected = "\ud800\udc00";
+ AssertTokens("'\\ud800\udc00'", JsonToken.Value(expected));
+ AssertTokens("'\ud800\\udc00'", JsonToken.Value(expected));
+ }
+
+ [Test]
+ public void ObjectDepth()
+ {
+ string json = "{ \"foo\": { \"x\": 1, \"y\": [ 0 ] } }";
+ var tokenizer = JsonTokenizer.FromTextReader(new StringReader(json));
+ // If we had more tests like this, I'd introduce a helper method... but for one test, it's not worth it.
+ Assert.AreEqual(0, tokenizer.ObjectDepth);
+ Assert.AreEqual(JsonToken.StartObject, tokenizer.Next());
+ Assert.AreEqual(1, tokenizer.ObjectDepth);
+ Assert.AreEqual(JsonToken.Name("foo"), tokenizer.Next());
+ Assert.AreEqual(1, tokenizer.ObjectDepth);
+ Assert.AreEqual(JsonToken.StartObject, tokenizer.Next());
+ Assert.AreEqual(2, tokenizer.ObjectDepth);
+ Assert.AreEqual(JsonToken.Name("x"), tokenizer.Next());
+ Assert.AreEqual(2, tokenizer.ObjectDepth);
+ Assert.AreEqual(JsonToken.Value(1), tokenizer.Next());
+ Assert.AreEqual(2, tokenizer.ObjectDepth);
+ Assert.AreEqual(JsonToken.Name("y"), tokenizer.Next());
+ Assert.AreEqual(2, tokenizer.ObjectDepth);
+ Assert.AreEqual(JsonToken.StartArray, tokenizer.Next());
+ Assert.AreEqual(2, tokenizer.ObjectDepth); // Depth hasn't changed in array
+ Assert.AreEqual(JsonToken.Value(0), tokenizer.Next());
+ Assert.AreEqual(2, tokenizer.ObjectDepth);
+ Assert.AreEqual(JsonToken.EndArray, tokenizer.Next());
+ Assert.AreEqual(2, tokenizer.ObjectDepth);
+ Assert.AreEqual(JsonToken.EndObject, tokenizer.Next());
+ Assert.AreEqual(1, tokenizer.ObjectDepth);
+ Assert.AreEqual(JsonToken.EndObject, tokenizer.Next());
+ Assert.AreEqual(0, tokenizer.ObjectDepth);
+ Assert.AreEqual(JsonToken.EndDocument, tokenizer.Next());
+ Assert.AreEqual(0, tokenizer.ObjectDepth);
+ }
+
+ [Test]
+ public void ObjectDepth_WithPushBack()
+ {
+ string json = "{}";
+ var tokenizer = JsonTokenizer.FromTextReader(new StringReader(json));
+ Assert.AreEqual(0, tokenizer.ObjectDepth);
+ var token = tokenizer.Next();
+ Assert.AreEqual(1, tokenizer.ObjectDepth);
+ // When we push back a "start object", we should effectively be back to the previous depth.
+ tokenizer.PushBack(token);
+ Assert.AreEqual(0, tokenizer.ObjectDepth);
+ // Read the same token again, and get back to depth 1
+ token = tokenizer.Next();
+ Assert.AreEqual(1, tokenizer.ObjectDepth);
+
+ // Now the same in reverse, with EndObject
+ token = tokenizer.Next();
+ Assert.AreEqual(0, tokenizer.ObjectDepth);
+ tokenizer.PushBack(token);
+ Assert.AreEqual(1, tokenizer.ObjectDepth);
+ tokenizer.Next();
+ Assert.AreEqual(0, tokenizer.ObjectDepth);
+ }
+
+ [Test]
+ [TestCase("embedded tab\t")]
+ [TestCase("embedded CR\r")]
+ [TestCase("embedded LF\n")]
+ [TestCase("embedded bell\u0007")]
+ [TestCase("bad escape\\a")]
+ [TestCase("incomplete escape\\")]
+ [TestCase("incomplete Unicode escape\\u000")]
+ [TestCase("invalid Unicode escape\\u000H")]
+ // Surrogate pair handling, both in raw .NET strings and escaped. We only need
+ // to detect this in strings, as non-ASCII characters anywhere other than in strings
+ // will already lead to parsing errors.
+ [TestCase("\\ud800")]
+ [TestCase("\\udc00")]
+ [TestCase("\\ud800x")]
+ [TestCase("\\udc00x")]
+ [TestCase("\\udc00\\ud800y")]
+ public void InvalidStringValue(string json)
+ {
+ AssertThrowsAfter("\"" + json + "\"");
+ }
+
+ // Tests for invalid strings that can't be expressed in attributes,
+ // as the constants can't be expressed as UTF-8 strings.
+ [Test]
+ public void InvalidSurrogatePairs()
+ {
+ AssertThrowsAfter("\"\ud800x\"");
+ AssertThrowsAfter("\"\udc00y\"");
+ AssertThrowsAfter("\"\udc00\ud800y\"");
+ }
+
+ [Test]
+ [TestCase("0", 0)]
+ [TestCase("-0", 0)] // We don't distinguish between positive and negative 0
+ [TestCase("1", 1)]
+ [TestCase("-1", -1)]
+ // From here on, assume leading sign is okay...
+ [TestCase("1.125", 1.125)]
+ [TestCase("1.0", 1)]
+ [TestCase("1e5", 100000)]
+ [TestCase("1e000000", 1)] // Weird, but not prohibited by the spec
+ [TestCase("1E5", 100000)]
+ [TestCase("1e+5", 100000)]
+ [TestCase("1E-5", 0.00001)]
+ [TestCase("123E-2", 1.23)]
+ [TestCase("123.45E3", 123450)]
+ [TestCase(" 1 ", 1)]
+ public void NumberValue(string json, double expectedValue)
+ {
+ AssertTokens(json, JsonToken.Value(expectedValue));
+ }
+
+ [Test]
+ [TestCase("00")]
+ [TestCase(".5")]
+ [TestCase("1.")]
+ [TestCase("1e")]
+ [TestCase("1e-")]
+ [TestCase("--")]
+ [TestCase("--1")]
+ [TestCase("-1.7977e308")]
+ [TestCase("1.7977e308")]
+ public void InvalidNumberValue(string json)
+ {
+ AssertThrowsAfter(json);
+ }
+
+ [Test]
+ [TestCase("nul")]
+ [TestCase("nothing")]
+ [TestCase("truth")]
+ [TestCase("fALSEhood")]
+ public void InvalidLiterals(string json)
+ {
+ AssertThrowsAfter(json);
+ }
+
+ [Test]
+ public void NullValue()
+ {
+ AssertTokens("null", JsonToken.Null);
+ }
+
+ [Test]
+ public void TrueValue()
+ {
+ AssertTokens("true", JsonToken.True);
+ }
+
+ [Test]
+ public void FalseValue()
+ {
+ AssertTokens("false", JsonToken.False);
+ }
+
+ [Test]
+ public void SimpleObject()
+ {
+ AssertTokens("{'x': 'y'}",
+ JsonToken.StartObject, JsonToken.Name("x"), JsonToken.Value("y"), JsonToken.EndObject);
+ }
+
+ [Test]
+ [TestCase("[10, 20", 3)]
+ [TestCase("[10,", 2)]
+ [TestCase("[10:20]", 2)]
+ [TestCase("[", 1)]
+ [TestCase("[,", 1)]
+ [TestCase("{", 1)]
+ [TestCase("{,", 1)]
+ [TestCase("{[", 1)]
+ [TestCase("{{", 1)]
+ [TestCase("{0", 1)]
+ [TestCase("{null", 1)]
+ [TestCase("{false", 1)]
+ [TestCase("{true", 1)]
+ [TestCase("}", 0)]
+ [TestCase("]", 0)]
+ [TestCase(",", 0)]
+ [TestCase("'foo' 'bar'", 1)]
+ [TestCase(":", 0)]
+ [TestCase("'foo", 0)] // Incomplete string
+ [TestCase("{ 'foo' }", 2)]
+ [TestCase("{ x:1", 1)] // Property names must be quoted
+ [TestCase("{]", 1)]
+ [TestCase("[}", 1)]
+ [TestCase("[1,", 2)]
+ [TestCase("{'x':0]", 3)]
+ [TestCase("{ 'foo': }", 2)]
+ [TestCase("{ 'foo':'bar', }", 3)]
+ public void InvalidStructure(string json, int expectedValidTokens)
+ {
+ // Note: we don't test that the earlier tokens are exactly as expected,
+ // partly because that's hard to parameterize.
+ var reader = new StringReader(json.Replace('\'', '"'));
+ var tokenizer = JsonTokenizer.FromTextReader(reader);
+ for (int i = 0; i < expectedValidTokens; i++)
+ {
+ Assert.IsNotNull(tokenizer.Next());
+ }
+ Assert.Throws<InvalidJsonException>(() => tokenizer.Next());
+ }
+
+ [Test]
+ public void ArrayMixedType()
+ {
+ AssertTokens("[1, 'foo', null, false, true, [2], {'x':'y' }]",
+ JsonToken.StartArray,
+ JsonToken.Value(1),
+ JsonToken.Value("foo"),
+ JsonToken.Null,
+ JsonToken.False,
+ JsonToken.True,
+ JsonToken.StartArray,
+ JsonToken.Value(2),
+ JsonToken.EndArray,
+ JsonToken.StartObject,
+ JsonToken.Name("x"),
+ JsonToken.Value("y"),
+ JsonToken.EndObject,
+ JsonToken.EndArray);
+ }
+
+ [Test]
+ public void ObjectMixedType()
+ {
+ AssertTokens(@"{'a': 1, 'b': 'bar', 'c': null, 'd': false, 'e': true,
+ 'f': [2], 'g': {'x':'y' }}",
+ JsonToken.StartObject,
+ JsonToken.Name("a"),
+ JsonToken.Value(1),
+ JsonToken.Name("b"),
+ JsonToken.Value("bar"),
+ JsonToken.Name("c"),
+ JsonToken.Null,
+ JsonToken.Name("d"),
+ JsonToken.False,
+ JsonToken.Name("e"),
+ JsonToken.True,
+ JsonToken.Name("f"),
+ JsonToken.StartArray,
+ JsonToken.Value(2),
+ JsonToken.EndArray,
+ JsonToken.Name("g"),
+ JsonToken.StartObject,
+ JsonToken.Name("x"),
+ JsonToken.Value("y"),
+ JsonToken.EndObject,
+ JsonToken.EndObject);
+ }
+
+ [Test]
+ public void NextAfterEndDocumentThrows()
+ {
+ var tokenizer = JsonTokenizer.FromTextReader(new StringReader("null"));
+ Assert.AreEqual(JsonToken.Null, tokenizer.Next());
+ Assert.AreEqual(JsonToken.EndDocument, tokenizer.Next());
+ Assert.Throws<InvalidOperationException>(() => tokenizer.Next());
+ }
+
+ [Test]
+ public void CanPushBackEndDocument()
+ {
+ var tokenizer = JsonTokenizer.FromTextReader(new StringReader("null"));
+ Assert.AreEqual(JsonToken.Null, tokenizer.Next());
+ Assert.AreEqual(JsonToken.EndDocument, tokenizer.Next());
+ tokenizer.PushBack(JsonToken.EndDocument);
+ Assert.AreEqual(JsonToken.EndDocument, tokenizer.Next());
+ Assert.Throws<InvalidOperationException>(() => tokenizer.Next());
+ }
+
+ /// <summary>
+ /// Asserts that the specified JSON is tokenized into the given sequence of tokens.
+ /// All apostrophes are first converted to double quotes, allowing any tests
+ /// that don't need to check actual apostrophe handling to use apostrophes in the JSON, avoiding
+ /// messy string literal escaping. The "end document" token is not specified in the list of
+ /// expected tokens, but is implicit.
+ /// </summary>
+ private static void AssertTokens(string json, params JsonToken[] expectedTokens)
+ {
+ AssertTokensNoReplacement(json.Replace('\'', '"'), expectedTokens);
+ }
+
+ /// <summary>
+ /// Asserts that the specified JSON is tokenized into the given sequence of tokens.
+ /// Unlike <see cref="AssertTokens(string, JsonToken[])"/>, this does not perform any character
+ /// replacement on the specified JSON, and should be used when the text contains apostrophes which
+ /// are expected to be used *as* apostrophes. The "end document" token is not specified in the list of
+ /// expected tokens, but is implicit.
+ /// </summary>
+ private static void AssertTokensNoReplacement(string json, params JsonToken[] expectedTokens)
+ {
+ var reader = new StringReader(json);
+ var tokenizer = JsonTokenizer.FromTextReader(reader);
+ for (int i = 0; i < expectedTokens.Length; i++)
+ {
+ var actualToken = tokenizer.Next();
+ if (actualToken == JsonToken.EndDocument)
+ {
+ Assert.Fail("Expected {0} but reached end of token stream", expectedTokens[i]);
+ }
+ Assert.AreEqual(expectedTokens[i], actualToken);
+ }
+ var finalToken = tokenizer.Next();
+ if (finalToken != JsonToken.EndDocument)
+ {
+ Assert.Fail("Expected token stream to be exhausted; received {0}", finalToken);
+ }
+ }
+
+ private static void AssertThrowsAfter(string json, params JsonToken[] expectedTokens)
+ {
+ var reader = new StringReader(json);
+ var tokenizer = JsonTokenizer.FromTextReader(reader);
+ for (int i = 0; i < expectedTokens.Length; i++)
+ {
+ var actualToken = tokenizer.Next();
+ if (actualToken == JsonToken.EndDocument)
+ {
+ Assert.Fail("Expected {0} but reached end of document", expectedTokens[i]);
+ }
+ Assert.AreEqual(expectedTokens[i], actualToken);
+ }
+ Assert.Throws<InvalidJsonException>(() => tokenizer.Next());
+ }
+ }
+}
diff --git a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Program.cs b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Program.cs
new file mode 100644
index 00000000..9078e59b
--- /dev/null
+++ b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Program.cs
@@ -0,0 +1,47 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2017 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+using NUnitLite;
+using System.Reflection;
+
+// Note: this file wasn't in the actual 3.0, but is required due to build
+// system changes
+
+namespace Google.Protobuf.Test
+{
+ class Program
+ {
+ public static int Main(string[] args)
+ {
+ return new AutoRun(typeof(Program).GetTypeInfo().Assembly).Execute(args);
+ }
+ }
+} \ No newline at end of file
diff --git a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Reflection/DescriptorsTest.cs b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Reflection/DescriptorsTest.cs
new file mode 100644
index 00000000..52d5a676
--- /dev/null
+++ b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Reflection/DescriptorsTest.cs
@@ -0,0 +1,259 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+using System.Linq;
+using Google.Protobuf.TestProtos;
+using NUnit.Framework;
+using UnitTest.Issues.TestProtos;
+
+namespace Google.Protobuf.Reflection
+{
+ /// <summary>
+ /// Tests for descriptors. (Not in its own namespace or broken up into individual classes as the
+ /// size doesn't warrant it. On the other hand, this makes me feel a bit dirty...)
+ /// </summary>
+ public class DescriptorsTest
+ {
+ [Test]
+ public void FileDescriptor()
+ {
+ FileDescriptor file = UnittestProto3Reflection.Descriptor;
+
+ Assert.AreEqual("google/protobuf/unittest_proto3.proto", file.Name);
+ Assert.AreEqual("protobuf_unittest", file.Package);
+
+ Assert.AreEqual("UnittestProto", file.Proto.Options.JavaOuterClassname);
+ 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, UnittestImportProto3Reflection.Descriptor.PublicDependencies.Count);
+ Assert.AreEqual(UnittestImportPublicProto3Reflection.Descriptor, UnittestImportProto3Reflection.Descriptor.PublicDependencies[0]);
+
+ Assert.AreEqual(1, file.Dependencies.Count);
+ Assert.AreEqual(UnittestImportProto3Reflection.Descriptor, file.Dependencies[0]);
+
+ MessageDescriptor messageType = TestAllTypes.Descriptor;
+ Assert.AreSame(typeof(TestAllTypes), messageType.ClrType);
+ Assert.AreSame(TestAllTypes.Parser, messageType.Parser);
+ Assert.AreEqual(messageType, file.MessageTypes[0]);
+ Assert.AreEqual(messageType, file.FindTypeByName<MessageDescriptor>("TestAllTypes"));
+ Assert.Null(file.FindTypeByName<MessageDescriptor>("NoSuchType"));
+ Assert.Null(file.FindTypeByName<MessageDescriptor>("protobuf_unittest.TestAllTypes"));
+ for (int i = 0; i < file.MessageTypes.Count; i++)
+ {
+ Assert.AreEqual(i, file.MessageTypes[i].Index);
+ }
+
+ Assert.AreEqual(file.EnumTypes[0], file.FindTypeByName<EnumDescriptor>("ForeignEnum"));
+ Assert.Null(file.FindTypeByName<EnumDescriptor>("NoSuchType"));
+ Assert.Null(file.FindTypeByName<EnumDescriptor>("protobuf_unittest.ForeignEnum"));
+ Assert.AreEqual(1, UnittestImportProto3Reflection.Descriptor.EnumTypes.Count);
+ Assert.AreEqual("ImportEnum", UnittestImportProto3Reflection.Descriptor.EnumTypes[0].Name);
+ for (int i = 0; i < file.EnumTypes.Count; i++)
+ {
+ Assert.AreEqual(i, file.EnumTypes[i].Index);
+ }
+
+ Assert.AreEqual(10, file.SerializedData[0]);
+ }
+
+ [Test]
+ public void MessageDescriptor()
+ {
+ MessageDescriptor messageType = TestAllTypes.Descriptor;
+ MessageDescriptor nestedType = TestAllTypes.Types.NestedMessage.Descriptor;
+
+ Assert.AreEqual("TestAllTypes", messageType.Name);
+ Assert.AreEqual("protobuf_unittest.TestAllTypes", messageType.FullName);
+ Assert.AreEqual(UnittestProto3Reflection.Descriptor, messageType.File);
+ Assert.IsNull(messageType.ContainingType);
+ Assert.IsNull(messageType.Proto.Options);
+
+ Assert.AreEqual("TestAllTypes", messageType.Name);
+
+ Assert.AreEqual("NestedMessage", nestedType.Name);
+ Assert.AreEqual("protobuf_unittest.TestAllTypes.NestedMessage", nestedType.FullName);
+ Assert.AreEqual(UnittestProto3Reflection.Descriptor, nestedType.File);
+ Assert.AreEqual(messageType, nestedType.ContainingType);
+
+ FieldDescriptor field = messageType.Fields.InDeclarationOrder()[0];
+ Assert.AreEqual("single_int32", field.Name);
+ Assert.AreEqual(field, messageType.FindDescriptor<FieldDescriptor>("single_int32"));
+ Assert.Null(messageType.FindDescriptor<FieldDescriptor>("no_such_field"));
+ Assert.AreEqual(field, messageType.FindFieldByNumber(1));
+ Assert.Null(messageType.FindFieldByNumber(571283));
+ var fieldsInDeclarationOrder = messageType.Fields.InDeclarationOrder();
+ for (int i = 0; i < fieldsInDeclarationOrder.Count; i++)
+ {
+ Assert.AreEqual(i, fieldsInDeclarationOrder[i].Index);
+ }
+
+ Assert.AreEqual(nestedType, messageType.NestedTypes[0]);
+ Assert.AreEqual(nestedType, messageType.FindDescriptor<MessageDescriptor>("NestedMessage"));
+ Assert.Null(messageType.FindDescriptor<MessageDescriptor>("NoSuchType"));
+ for (int i = 0; i < messageType.NestedTypes.Count; i++)
+ {
+ Assert.AreEqual(i, messageType.NestedTypes[i].Index);
+ }
+
+ Assert.AreEqual(messageType.EnumTypes[0], messageType.FindDescriptor<EnumDescriptor>("NestedEnum"));
+ Assert.Null(messageType.FindDescriptor<EnumDescriptor>("NoSuchType"));
+ for (int i = 0; i < messageType.EnumTypes.Count; i++)
+ {
+ Assert.AreEqual(i, messageType.EnumTypes[i].Index);
+ }
+ }
+
+ [Test]
+ public void FieldDescriptor()
+ {
+ MessageDescriptor messageType = TestAllTypes.Descriptor;
+ FieldDescriptor primitiveField = messageType.FindDescriptor<FieldDescriptor>("single_int32");
+ FieldDescriptor enumField = messageType.FindDescriptor<FieldDescriptor>("single_nested_enum");
+ FieldDescriptor messageField = messageType.FindDescriptor<FieldDescriptor>("single_foreign_message");
+
+ 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(UnittestProto3Reflection.Descriptor, primitiveField.File);
+ Assert.AreEqual(FieldType.Int32, primitiveField.FieldType);
+ Assert.IsNull(primitiveField.Proto.Options);
+
+ Assert.AreEqual("single_nested_enum", enumField.Name);
+ Assert.AreEqual(FieldType.Enum, enumField.FieldType);
+ // Assert.AreEqual(TestAllTypes.Types.NestedEnum.DescriptorProtoFile, enumField.EnumType);
+
+ Assert.AreEqual("single_foreign_message", messageField.Name);
+ Assert.AreEqual(FieldType.Message, messageField.FieldType);
+ Assert.AreEqual(ForeignMessage.Descriptor, messageField.MessageType);
+ }
+
+ [Test]
+ public void FieldDescriptorLabel()
+ {
+ FieldDescriptor singleField =
+ TestAllTypes.Descriptor.FindDescriptor<FieldDescriptor>("single_int32");
+ FieldDescriptor repeatedField =
+ TestAllTypes.Descriptor.FindDescriptor<FieldDescriptor>("repeated_int32");
+
+ Assert.IsFalse(singleField.IsRepeated);
+ Assert.IsTrue(repeatedField.IsRepeated);
+ }
+
+ [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 = UnittestProto3Reflection.Descriptor.FindTypeByName<EnumDescriptor>("ForeignEnum");
+ EnumDescriptor nestedType = TestAllTypes.Descriptor.FindDescriptor<EnumDescriptor>("NestedEnum");
+
+ Assert.AreEqual("ForeignEnum", enumType.Name);
+ Assert.AreEqual("protobuf_unittest.ForeignEnum", enumType.FullName);
+ Assert.AreEqual(UnittestProto3Reflection.Descriptor, enumType.File);
+ Assert.Null(enumType.ContainingType);
+ Assert.Null(enumType.Proto.Options);
+
+ Assert.AreEqual("NestedEnum", nestedType.Name);
+ Assert.AreEqual("protobuf_unittest.TestAllTypes.NestedEnum",
+ nestedType.FullName);
+ Assert.AreEqual(UnittestProto3Reflection.Descriptor, nestedType.File);
+ Assert.AreEqual(TestAllTypes.Descriptor, nestedType.ContainingType);
+
+ EnumValueDescriptor value = enumType.FindValueByName("FOREIGN_FOO");
+ Assert.AreEqual(value, enumType.Values[1]);
+ Assert.AreEqual("FOREIGN_FOO", value.Name);
+ Assert.AreEqual(4, value.Number);
+ Assert.AreEqual((int) ForeignEnum.ForeignFoo, value.Number);
+ Assert.AreEqual(value, enumType.FindValueByNumber(4));
+ Assert.Null(enumType.FindValueByName("NO_SUCH_VALUE"));
+ for (int i = 0; i < enumType.Values.Count; i++)
+ {
+ Assert.AreEqual(i, enumType.Values[i].Index);
+ }
+ }
+
+ [Test]
+ public void OneofDescriptor()
+ {
+ OneofDescriptor descriptor = TestAllTypes.Descriptor.FindDescriptor<OneofDescriptor>("oneof_field");
+ Assert.AreEqual("oneof_field", descriptor.Name);
+ Assert.AreEqual("protobuf_unittest.TestAllTypes.oneof_field", descriptor.FullName);
+
+ var expectedFields = new[] {
+ TestAllTypes.OneofBytesFieldNumber,
+ TestAllTypes.OneofNestedMessageFieldNumber,
+ TestAllTypes.OneofStringFieldNumber,
+ TestAllTypes.OneofUint32FieldNumber }
+ .Select(fieldNumber => TestAllTypes.Descriptor.FindFieldByNumber(fieldNumber))
+ .ToList();
+ foreach (var field in expectedFields)
+ {
+ Assert.AreSame(descriptor, field.ContainingOneof);
+ }
+
+ CollectionAssert.AreEquivalent(expectedFields, descriptor.Fields);
+ }
+
+ [Test]
+ public void MapEntryMessageDescriptor()
+ {
+ var descriptor = MapWellKnownTypes.Descriptor.NestedTypes[0];
+ Assert.IsNull(descriptor.Parser);
+ Assert.IsNull(descriptor.ClrType);
+ Assert.IsNull(descriptor.Fields[1].Accessor);
+ }
+
+ // From TestFieldOrdering:
+ // string my_string = 11;
+ // int64 my_int = 1;
+ // float my_float = 101;
+ // NestedMessage single_nested_message = 200;
+ [Test]
+ public void FieldListOrderings()
+ {
+ var fields = TestFieldOrderings.Descriptor.Fields;
+ Assert.AreEqual(new[] { 11, 1, 101, 200 }, fields.InDeclarationOrder().Select(x => x.FieldNumber));
+ Assert.AreEqual(new[] { 1, 11, 101, 200 }, fields.InFieldNumberOrder().Select(x => x.FieldNumber));
+ }
+
+
+ [Test]
+ public void DescriptorProtoFileDescriptor()
+ {
+ var descriptor = Google.Protobuf.Reflection.FileDescriptor.DescriptorProtoFileDescriptor;
+ Assert.AreEqual("google/protobuf/descriptor.proto", descriptor.Name);
+ }
+ }
+}
diff --git a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Reflection/FieldAccessTest.cs b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Reflection/FieldAccessTest.cs
new file mode 100644
index 00000000..a488af30
--- /dev/null
+++ b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Reflection/FieldAccessTest.cs
@@ -0,0 +1,218 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2015 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+using Google.Protobuf.TestProtos;
+using NUnit.Framework;
+using System;
+using System.Collections;
+using System.Collections.Generic;
+
+namespace Google.Protobuf.Reflection
+{
+ public class FieldAccessTest
+ {
+ [Test]
+ public void GetValue()
+ {
+ var message = SampleMessages.CreateFullTestAllTypes();
+ var fields = TestAllTypes.Descriptor.Fields;
+ Assert.AreEqual(message.SingleBool, fields[TestAllTypes.SingleBoolFieldNumber].Accessor.GetValue(message));
+ Assert.AreEqual(message.SingleBytes, fields[TestAllTypes.SingleBytesFieldNumber].Accessor.GetValue(message));
+ Assert.AreEqual(message.SingleDouble, fields[TestAllTypes.SingleDoubleFieldNumber].Accessor.GetValue(message));
+ Assert.AreEqual(message.SingleFixed32, fields[TestAllTypes.SingleFixed32FieldNumber].Accessor.GetValue(message));
+ Assert.AreEqual(message.SingleFixed64, fields[TestAllTypes.SingleFixed64FieldNumber].Accessor.GetValue(message));
+ Assert.AreEqual(message.SingleFloat, fields[TestAllTypes.SingleFloatFieldNumber].Accessor.GetValue(message));
+ Assert.AreEqual(message.SingleForeignEnum, fields[TestAllTypes.SingleForeignEnumFieldNumber].Accessor.GetValue(message));
+ Assert.AreEqual(message.SingleForeignMessage, fields[TestAllTypes.SingleForeignMessageFieldNumber].Accessor.GetValue(message));
+ Assert.AreEqual(message.SingleImportEnum, fields[TestAllTypes.SingleImportEnumFieldNumber].Accessor.GetValue(message));
+ Assert.AreEqual(message.SingleImportMessage, fields[TestAllTypes.SingleImportMessageFieldNumber].Accessor.GetValue(message));
+ Assert.AreEqual(message.SingleInt32, fields[TestAllTypes.SingleInt32FieldNumber].Accessor.GetValue(message));
+ Assert.AreEqual(message.SingleInt64, fields[TestAllTypes.SingleInt64FieldNumber].Accessor.GetValue(message));
+ Assert.AreEqual(message.SingleNestedEnum, fields[TestAllTypes.SingleNestedEnumFieldNumber].Accessor.GetValue(message));
+ Assert.AreEqual(message.SingleNestedMessage, fields[TestAllTypes.SingleNestedMessageFieldNumber].Accessor.GetValue(message));
+ Assert.AreEqual(message.SinglePublicImportMessage, fields[TestAllTypes.SinglePublicImportMessageFieldNumber].Accessor.GetValue(message));
+ Assert.AreEqual(message.SingleSint32, fields[TestAllTypes.SingleSint32FieldNumber].Accessor.GetValue(message));
+ Assert.AreEqual(message.SingleSint64, fields[TestAllTypes.SingleSint64FieldNumber].Accessor.GetValue(message));
+ Assert.AreEqual(message.SingleString, fields[TestAllTypes.SingleStringFieldNumber].Accessor.GetValue(message));
+ Assert.AreEqual(message.SingleSfixed32, fields[TestAllTypes.SingleSfixed32FieldNumber].Accessor.GetValue(message));
+ Assert.AreEqual(message.SingleSfixed64, fields[TestAllTypes.SingleSfixed64FieldNumber].Accessor.GetValue(message));
+ Assert.AreEqual(message.SingleUint32, fields[TestAllTypes.SingleUint32FieldNumber].Accessor.GetValue(message));
+ Assert.AreEqual(message.SingleUint64, fields[TestAllTypes.SingleUint64FieldNumber].Accessor.GetValue(message));
+ Assert.AreEqual(message.OneofBytes, fields[TestAllTypes.OneofBytesFieldNumber].Accessor.GetValue(message));
+ Assert.AreEqual(message.OneofString, fields[TestAllTypes.OneofStringFieldNumber].Accessor.GetValue(message));
+ Assert.AreEqual(message.OneofNestedMessage, fields[TestAllTypes.OneofNestedMessageFieldNumber].Accessor.GetValue(message));
+ Assert.AreEqual(message.OneofUint32, fields[TestAllTypes.OneofUint32FieldNumber].Accessor.GetValue(message));
+
+ // Just one example for repeated fields - they're all just returning the list
+ var list = (IList) fields[TestAllTypes.RepeatedInt32FieldNumber].Accessor.GetValue(message);
+ Assert.AreEqual(message.RepeatedInt32, list);
+ Assert.AreEqual(message.RepeatedInt32[0], list[0]); // Just in case there was any doubt...
+
+ // Just a single map field, for the same reason
+ var mapMessage = new TestMap { MapStringString = { { "key1", "value1" }, { "key2", "value2" } } };
+ fields = TestMap.Descriptor.Fields;
+ var dictionary = (IDictionary) fields[TestMap.MapStringStringFieldNumber].Accessor.GetValue(mapMessage);
+ Assert.AreEqual(mapMessage.MapStringString, dictionary);
+ Assert.AreEqual("value1", dictionary["key1"]);
+ }
+
+ [Test]
+ public void Clear()
+ {
+ var message = SampleMessages.CreateFullTestAllTypes();
+ var fields = TestAllTypes.Descriptor.Fields;
+ fields[TestAllTypes.SingleBoolFieldNumber].Accessor.Clear(message);
+ fields[TestAllTypes.SingleInt32FieldNumber].Accessor.Clear(message);
+ fields[TestAllTypes.SingleStringFieldNumber].Accessor.Clear(message);
+ fields[TestAllTypes.SingleBytesFieldNumber].Accessor.Clear(message);
+ fields[TestAllTypes.SingleForeignEnumFieldNumber].Accessor.Clear(message);
+ fields[TestAllTypes.SingleForeignMessageFieldNumber].Accessor.Clear(message);
+ fields[TestAllTypes.RepeatedDoubleFieldNumber].Accessor.Clear(message);
+
+ var expected = new TestAllTypes(SampleMessages.CreateFullTestAllTypes())
+ {
+ SingleBool = false,
+ SingleInt32 = 0,
+ SingleString = "",
+ SingleBytes = ByteString.Empty,
+ SingleForeignEnum = 0,
+ SingleForeignMessage = null,
+ };
+ expected.RepeatedDouble.Clear();
+
+ Assert.AreEqual(expected, message);
+
+ // Separately, maps.
+ var mapMessage = new TestMap { MapStringString = { { "key1", "value1" }, { "key2", "value2" } } };
+ fields = TestMap.Descriptor.Fields;
+ fields[TestMap.MapStringStringFieldNumber].Accessor.Clear(mapMessage);
+ Assert.AreEqual(0, mapMessage.MapStringString.Count);
+ }
+
+ [Test]
+ public void SetValue_SingleFields()
+ {
+ // Just a sample (primitives, messages, enums, strings, byte strings)
+ var message = SampleMessages.CreateFullTestAllTypes();
+ var fields = TestAllTypes.Descriptor.Fields;
+ fields[TestAllTypes.SingleBoolFieldNumber].Accessor.SetValue(message, false);
+ fields[TestAllTypes.SingleInt32FieldNumber].Accessor.SetValue(message, 500);
+ fields[TestAllTypes.SingleStringFieldNumber].Accessor.SetValue(message, "It's a string");
+ fields[TestAllTypes.SingleBytesFieldNumber].Accessor.SetValue(message, ByteString.CopyFrom(99, 98, 97));
+ fields[TestAllTypes.SingleForeignEnumFieldNumber].Accessor.SetValue(message, ForeignEnum.ForeignFoo);
+ fields[TestAllTypes.SingleForeignMessageFieldNumber].Accessor.SetValue(message, new ForeignMessage { C = 12345 });
+ fields[TestAllTypes.SingleDoubleFieldNumber].Accessor.SetValue(message, 20150701.5);
+
+ var expected = new TestAllTypes(SampleMessages.CreateFullTestAllTypes())
+ {
+ SingleBool = false,
+ SingleInt32 = 500,
+ SingleString = "It's a string",
+ SingleBytes = ByteString.CopyFrom(99, 98, 97),
+ SingleForeignEnum = ForeignEnum.ForeignFoo,
+ SingleForeignMessage = new ForeignMessage { C = 12345 },
+ SingleDouble = 20150701.5
+ };
+
+ Assert.AreEqual(expected, message);
+ }
+
+ [Test]
+ public void SetValue_SingleFields_WrongType()
+ {
+ IMessage message = SampleMessages.CreateFullTestAllTypes();
+ var fields = message.Descriptor.Fields;
+ Assert.Throws<InvalidCastException>(() => fields[TestAllTypes.SingleBoolFieldNumber].Accessor.SetValue(message, "This isn't a bool"));
+ }
+
+ [Test]
+ public void SetValue_MapFields()
+ {
+ IMessage message = new TestMap();
+ var fields = message.Descriptor.Fields;
+ Assert.Throws<InvalidOperationException>(() => fields[TestMap.MapStringStringFieldNumber].Accessor.SetValue(message, new Dictionary<string, string>()));
+ }
+
+ [Test]
+ public void SetValue_RepeatedFields()
+ {
+ IMessage message = SampleMessages.CreateFullTestAllTypes();
+ var fields = message.Descriptor.Fields;
+ Assert.Throws<InvalidOperationException>(() => fields[TestAllTypes.RepeatedDoubleFieldNumber].Accessor.SetValue(message, new double[10]));
+ }
+
+ [Test]
+ public void GetValue_IncorrectType()
+ {
+ IMessage message = SampleMessages.CreateFullTestAllTypes();
+ var fields = message.Descriptor.Fields;
+ Assert.Throws<InvalidCastException>(() => fields[TestAllTypes.SingleBoolFieldNumber].Accessor.GetValue(new TestMap()));
+ }
+
+ [Test]
+ public void Oneof()
+ {
+ var message = new TestAllTypes();
+ var descriptor = TestAllTypes.Descriptor;
+ Assert.AreEqual(1, descriptor.Oneofs.Count);
+ var oneof = descriptor.Oneofs[0];
+ Assert.AreEqual("oneof_field", oneof.Name);
+ Assert.IsNull(oneof.Accessor.GetCaseFieldDescriptor(message));
+
+ message.OneofString = "foo";
+ Assert.AreSame(descriptor.Fields[TestAllTypes.OneofStringFieldNumber], oneof.Accessor.GetCaseFieldDescriptor(message));
+
+ message.OneofUint32 = 10;
+ Assert.AreSame(descriptor.Fields[TestAllTypes.OneofUint32FieldNumber], oneof.Accessor.GetCaseFieldDescriptor(message));
+
+ oneof.Accessor.Clear(message);
+ Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.None, message.OneofFieldCase);
+ }
+
+ [Test]
+ public void FieldDescriptor_ByName()
+ {
+ var descriptor = TestAllTypes.Descriptor;
+ Assert.AreSame(
+ descriptor.Fields[TestAllTypes.SingleBoolFieldNumber],
+ descriptor.Fields["single_bool"]);
+ }
+
+ [Test]
+ public void FieldDescriptor_NotFound()
+ {
+ var descriptor = TestAllTypes.Descriptor;
+ Assert.Throws<KeyNotFoundException>(() => descriptor.Fields[999999].ToString());
+ Assert.Throws<KeyNotFoundException>(() => descriptor.Fields["not found"].ToString());
+ }
+ }
+}
diff --git a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Reflection/TypeRegistryTest.cs b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Reflection/TypeRegistryTest.cs
new file mode 100644
index 00000000..5be7ca23
--- /dev/null
+++ b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Reflection/TypeRegistryTest.cs
@@ -0,0 +1,94 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2015 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+using Google.Protobuf.TestProtos;
+using Google.Protobuf.WellKnownTypes;
+using NUnit.Framework;
+
+namespace Google.Protobuf.Reflection
+{
+ public class TypeRegistryTest
+ {
+ // Most of our tests use messages. Simple test that we really can use files...
+ [Test]
+ public void CreateWithFileDescriptor()
+ {
+ var registry = TypeRegistry.FromFiles(DurationReflection.Descriptor, StructReflection.Descriptor);
+ AssertDescriptorPresent(registry, Duration.Descriptor);
+ AssertDescriptorPresent(registry, ListValue.Descriptor);
+ AssertDescriptorAbsent(registry, Timestamp.Descriptor);
+ }
+
+ [Test]
+ public void TypesFromSameFile()
+ {
+ // Just for kicks, let's start with a nested type
+ var registry = TypeRegistry.FromMessages(TestAllTypes.Types.NestedMessage.Descriptor);
+ // Top-level...
+ AssertDescriptorPresent(registry, TestFieldOrderings.Descriptor);
+ // ... and nested (not the same as the original NestedMessage!)
+ AssertDescriptorPresent(registry, TestFieldOrderings.Types.NestedMessage.Descriptor);
+ }
+
+ [Test]
+ public void DependenciesAreIncluded()
+ {
+ var registry = TypeRegistry.FromMessages(TestAllTypes.Descriptor);
+ // Direct dependencies
+ AssertDescriptorPresent(registry, ImportMessage.Descriptor);
+ // Public dependencies
+ AssertDescriptorPresent(registry, PublicImportMessage.Descriptor);
+ }
+
+ [Test]
+ public void DuplicateFiles()
+ {
+ // Duplicates via dependencies and simply via repetition
+ var registry = TypeRegistry.FromFiles(
+ UnittestProto3Reflection.Descriptor, UnittestImportProto3Reflection.Descriptor,
+ TimestampReflection.Descriptor, TimestampReflection.Descriptor);
+ AssertDescriptorPresent(registry, TestAllTypes.Descriptor);
+ AssertDescriptorPresent(registry, ImportMessage.Descriptor);
+ AssertDescriptorPresent(registry, Timestamp.Descriptor);
+ }
+
+ private static void AssertDescriptorPresent(TypeRegistry registry, MessageDescriptor descriptor)
+ {
+ Assert.AreSame(descriptor, registry.Find(descriptor.FullName));
+ }
+
+ private static void AssertDescriptorAbsent(TypeRegistry registry, MessageDescriptor descriptor)
+ {
+ Assert.IsNull(registry.Find(descriptor.FullName));
+ }
+ }
+}
diff --git a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/SampleEnum.cs b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/SampleEnum.cs
new file mode 100644
index 00000000..77447afa
--- /dev/null
+++ b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/SampleEnum.cs
@@ -0,0 +1,42 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2015 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+namespace Google.Protobuf
+{
+ // Just a sample enum with positive and negative values to be used in tests.
+ internal enum SampleEnum
+ {
+ NegativeValue = -2,
+ None = 0,
+ PositiveValue = 3
+ }
+}
diff --git a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/SampleMessages.cs b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/SampleMessages.cs
new file mode 100644
index 00000000..ffa4e2a7
--- /dev/null
+++ b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/SampleMessages.cs
@@ -0,0 +1,99 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2015 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+using System;
+using Google.Protobuf.TestProtos;
+
+namespace Google.Protobuf
+{
+ /// <summary>
+ /// Helper methods to create sample instances of types generated from unit test messages.
+ /// </summary>
+ public class SampleMessages
+ {
+ /// <summary>
+ /// Creates a new sample TestAllTypes message with all fields populated.
+ /// The "oneof" field is populated with the string property (OneofString).
+ /// </summary>
+ public static TestAllTypes CreateFullTestAllTypes()
+ {
+ return new TestAllTypes
+ {
+ SingleBool = true,
+ SingleBytes = ByteString.CopyFrom(1, 2, 3, 4),
+ SingleDouble = 23.5,
+ SingleFixed32 = 23,
+ SingleFixed64 = 1234567890123,
+ SingleFloat = 12.25f,
+ SingleForeignEnum = ForeignEnum.ForeignBar,
+ SingleForeignMessage = new ForeignMessage { C = 10 },
+ SingleImportEnum = ImportEnum.ImportBaz,
+ 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 = UInt32.MaxValue,
+ SingleUint64 = UInt64.MaxValue,
+ RepeatedBool = { true, false },
+ RepeatedBytes = { ByteString.CopyFrom(1, 2, 3, 4), ByteString.CopyFrom(5, 6), ByteString.CopyFrom(new byte[1000]) },
+ RepeatedDouble = { -12.25, 23.5 },
+ RepeatedFixed32 = { UInt32.MaxValue, 23 },
+ RepeatedFixed64 = { UInt64.MaxValue, 1234567890123 },
+ RepeatedFloat = { 100f, 12.25f },
+ RepeatedForeignEnum = { ForeignEnum.ForeignFoo, ForeignEnum.ForeignBar },
+ RepeatedForeignMessage = { new ForeignMessage(), new ForeignMessage { C = 10 } },
+ RepeatedImportEnum = { ImportEnum.ImportBaz, ImportEnum.Unspecified },
+ RepeatedImportMessage = { new ImportMessage { D = 20 }, new ImportMessage { D = 25 } },
+ RepeatedInt32 = { 100, 200 },
+ RepeatedInt64 = { 3210987654321, Int64.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 = { UInt32.MaxValue, UInt32.MinValue },
+ RepeatedUint64 = { UInt64.MaxValue, UInt32.MinValue },
+ OneofString = "Oneof string"
+ };
+ }
+ }
+} \ No newline at end of file
diff --git a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/TestCornerCases.cs b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/TestCornerCases.cs
new file mode 100644
index 00000000..248f5fa9
--- /dev/null
+++ b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/TestCornerCases.cs
@@ -0,0 +1,62 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+using UnitTest.Issues.TestProtos;
+using NUnit.Framework;
+
+namespace Google.Protobuf
+{
+ public class TestCornerCases
+ {
+ [Test]
+ public void TestRoundTripNegativeEnums()
+ {
+ NegativeEnumMessage msg = new NegativeEnumMessage
+ {
+ Value = NegativeEnum.MinusOne,
+ Values = { NegativeEnum.Zero, NegativeEnum.MinusOne, NegativeEnum.FiveBelow },
+ PackedValues = { NegativeEnum.Zero, NegativeEnum.MinusOne, NegativeEnum.FiveBelow }
+ };
+
+ Assert.AreEqual(58, msg.CalculateSize());
+
+ byte[] bytes = new byte[58];
+ CodedOutputStream output = new CodedOutputStream(bytes);
+
+ msg.WriteTo(output);
+ Assert.AreEqual(0, output.SpaceLeft);
+
+ NegativeEnumMessage copy = NegativeEnumMessage.Parser.ParseFrom(bytes);
+ Assert.AreEqual(msg, copy);
+ }
+ }
+}
diff --git a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/TestProtos/ForeignMessagePartial.cs b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/TestProtos/ForeignMessagePartial.cs
new file mode 100644
index 00000000..5663a699
--- /dev/null
+++ b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/TestProtos/ForeignMessagePartial.cs
@@ -0,0 +1,45 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2016 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+namespace Google.Protobuf.TestProtos
+{
+ /// <summary>
+ /// A message with custom diagnostics (to test that they work).
+ /// </summary>
+ public partial class ForeignMessage : ICustomDiagnosticMessage
+ {
+ public string ToDiagnosticString()
+ {
+ return $"{{ \"c\": {C}, \"@cInHex\": \"{C:x}\" }}";
+ }
+ }
+}
diff --git a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/WellKnownTypes/AnyTest.cs b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/WellKnownTypes/AnyTest.cs
new file mode 100644
index 00000000..4aecc998
--- /dev/null
+++ b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/WellKnownTypes/AnyTest.cs
@@ -0,0 +1,116 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2015 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+using Google.Protobuf.TestProtos;
+using NUnit.Framework;
+
+namespace Google.Protobuf.WellKnownTypes
+{
+ public class AnyTest
+ {
+ [Test]
+ public void Pack()
+ {
+ var message = SampleMessages.CreateFullTestAllTypes();
+ var any = Any.Pack(message);
+ Assert.AreEqual("type.googleapis.com/protobuf_unittest.TestAllTypes", any.TypeUrl);
+ Assert.AreEqual(message.CalculateSize(), any.Value.Length);
+ }
+
+ [Test]
+ public void Pack_WithCustomPrefix()
+ {
+ var message = SampleMessages.CreateFullTestAllTypes();
+ var any = Any.Pack(message, "foo.bar/baz");
+ Assert.AreEqual("foo.bar/baz/protobuf_unittest.TestAllTypes", any.TypeUrl);
+ Assert.AreEqual(message.CalculateSize(), any.Value.Length);
+ }
+
+ [Test]
+ public void Pack_WithCustomPrefixTrailingSlash()
+ {
+ var message = SampleMessages.CreateFullTestAllTypes();
+ var any = Any.Pack(message, "foo.bar/baz/");
+ Assert.AreEqual("foo.bar/baz/protobuf_unittest.TestAllTypes", any.TypeUrl);
+ Assert.AreEqual(message.CalculateSize(), any.Value.Length);
+ }
+
+ [Test]
+ public void Unpack_WrongType()
+ {
+ var message = SampleMessages.CreateFullTestAllTypes();
+ var any = Any.Pack(message);
+ Assert.Throws<InvalidProtocolBufferException>(() => any.Unpack<TestOneof>());
+ }
+
+ [Test]
+ public void Unpack_Success()
+ {
+ var message = SampleMessages.CreateFullTestAllTypes();
+ var any = Any.Pack(message);
+ var unpacked = any.Unpack<TestAllTypes>();
+ Assert.AreEqual(message, unpacked);
+ }
+
+ [Test]
+ public void Unpack_CustomPrefix_Success()
+ {
+ var message = SampleMessages.CreateFullTestAllTypes();
+ var any = Any.Pack(message, "foo.bar/baz");
+ var unpacked = any.Unpack<TestAllTypes>();
+ Assert.AreEqual(message, unpacked);
+ }
+
+ [Test]
+ public void ToString_WithValues()
+ {
+ var message = SampleMessages.CreateFullTestAllTypes();
+ var any = Any.Pack(message);
+ var text = any.ToString();
+ Assert.That(text, Does.Contain("\"@value\": \"" + message.ToByteString().ToBase64() + "\""));
+ }
+
+ [Test]
+ public void ToString_Empty()
+ {
+ var any = new Any();
+ Assert.AreEqual("{ \"@type\": \"\", \"@value\": \"\" }", any.ToString());
+ }
+
+ [Test]
+ public void ToString_MessageContainingAny()
+ {
+ var message = new TestWellKnownTypes { AnyField = new Any() };
+ Assert.AreEqual("{ \"anyField\": { \"@type\": \"\", \"@value\": \"\" } }", message.ToString());
+ }
+ }
+}
diff --git a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/WellKnownTypes/DurationTest.cs b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/WellKnownTypes/DurationTest.cs
new file mode 100644
index 00000000..141faf80
--- /dev/null
+++ b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/WellKnownTypes/DurationTest.cs
@@ -0,0 +1,132 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2015 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+using NUnit.Framework;
+using System;
+
+namespace Google.Protobuf.WellKnownTypes
+{
+ public class DurationTest
+ {
+ [Test]
+ public void ToTimeSpan()
+ {
+ Assert.AreEqual(TimeSpan.FromSeconds(1), new Duration { Seconds = 1 }.ToTimeSpan());
+ Assert.AreEqual(TimeSpan.FromSeconds(-1), new Duration { Seconds = -1 }.ToTimeSpan());
+ Assert.AreEqual(TimeSpan.FromMilliseconds(1), new Duration { Nanos = 1000000 }.ToTimeSpan());
+ Assert.AreEqual(TimeSpan.FromMilliseconds(-1), new Duration { Nanos = -1000000 }.ToTimeSpan());
+ Assert.AreEqual(TimeSpan.FromTicks(1), new Duration { Nanos = 100 }.ToTimeSpan());
+ Assert.AreEqual(TimeSpan.FromTicks(-1), new Duration { Nanos = -100 }.ToTimeSpan());
+
+ // Rounding is towards 0
+ Assert.AreEqual(TimeSpan.FromTicks(2), new Duration { Nanos = 250 }.ToTimeSpan());
+ Assert.AreEqual(TimeSpan.FromTicks(-2), new Duration { Nanos = -250 }.ToTimeSpan());
+ }
+
+ [Test]
+ public void Addition()
+ {
+ Assert.AreEqual(new Duration { Seconds = 2, Nanos = 100000000 },
+ new Duration { Seconds = 1, Nanos = 600000000 } + new Duration { Nanos = 500000000 });
+ Assert.AreEqual(new Duration { Seconds = -2, Nanos = -100000000 },
+ new Duration { Seconds = -1, Nanos = -600000000 } + new Duration { Nanos = -500000000 });
+ Assert.AreEqual(new Duration { Seconds = 1, Nanos = 100000000 },
+ new Duration { Seconds = 1, Nanos = 600000000 } + new Duration { Nanos = -500000000 });
+
+ // Non-normalized durations, or non-normalized intermediate results
+ Assert.AreEqual(new Duration { Seconds = 1 },
+ new Duration { Seconds = 1, Nanos = -500000000 } + new Duration { Nanos = 500000000 });
+
+ Assert.AreEqual(new Duration { Nanos = -900000000 },
+ new Duration { Seconds = -1, Nanos = -100000000 } + new Duration { Nanos = 200000000 });
+ Assert.AreEqual(new Duration { Nanos = 900000000 },
+ new Duration { Seconds = 1, Nanos = 100000000 } + new Duration { Nanos = -200000000 });
+ }
+
+ [Test]
+ public void Subtraction()
+ {
+ Assert.AreEqual(new Duration { Seconds = 1, Nanos = 100000000 },
+ new Duration { Seconds = 1, Nanos = 600000000 } - new Duration { Nanos = 500000000 });
+ Assert.AreEqual(new Duration { Seconds = -1, Nanos = -100000000 },
+ new Duration { Seconds = -1, Nanos = -600000000 } - new Duration { Nanos = -500000000 });
+ Assert.AreEqual(new Duration { Seconds = 2, Nanos = 100000000 },
+ new Duration { Seconds = 1, Nanos = 600000000 } - new Duration { Nanos = -500000000 });
+
+ // Non-normalized durations
+ Assert.AreEqual(new Duration(),
+ new Duration { Seconds = 1, Nanos = -500000000 } - new Duration { Nanos = 500000000 });
+ Assert.AreEqual(new Duration { Seconds = 1 },
+ new Duration { Nanos = 2000000000 } - new Duration { Nanos = 1000000000 });
+ }
+
+ [Test]
+ public void FromTimeSpan()
+ {
+ Assert.AreEqual(new Duration { Seconds = 1 }, Duration.FromTimeSpan(TimeSpan.FromSeconds(1)));
+ Assert.AreEqual(new Duration { Nanos = Duration.NanosecondsPerTick }, Duration.FromTimeSpan(TimeSpan.FromTicks(1)));
+ }
+
+ [Test]
+ [TestCase(0, Duration.MaxNanoseconds + 1)]
+ [TestCase(0, Duration.MinNanoseconds - 1)]
+ [TestCase(Duration.MinSeconds - 1, 0)]
+ [TestCase(Duration.MaxSeconds + 1, 0)]
+ [TestCase(1, -1)]
+ [TestCase(-1, 1)]
+ public void ToTimeSpan_Invalid(long seconds, int nanoseconds)
+ {
+ var duration = new Duration { Seconds = seconds, Nanos = nanoseconds };
+ Assert.Throws<InvalidOperationException>(() => duration.ToTimeSpan());
+ }
+
+ [Test]
+ [TestCase(0, Duration.MaxNanoseconds)]
+ [TestCase(0, Duration.MinNanoseconds)]
+ [TestCase(Duration.MinSeconds, Duration.MinNanoseconds)]
+ [TestCase(Duration.MaxSeconds, Duration.MaxNanoseconds)]
+ public void ToTimeSpan_Valid(long seconds, int nanoseconds)
+ {
+ // Only testing that these values don't throw, unlike their similar tests in ToTimeSpan_Invalid
+ var duration = new Duration { Seconds = seconds, Nanos = nanoseconds };
+ duration.ToTimeSpan();
+ }
+
+ [Test]
+ public void ToString_NonNormalized()
+ {
+ // Just a single example should be sufficient...
+ var duration = new Duration { Seconds = 1, Nanos = -1 };
+ Assert.AreEqual("{ \"@warning\": \"Invalid Duration\", \"seconds\": \"1\", \"nanos\": -1 }", duration.ToString());
+ }
+ }
+}
diff --git a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/WellKnownTypes/FieldMaskTest.cs b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/WellKnownTypes/FieldMaskTest.cs
new file mode 100644
index 00000000..1d9908b4
--- /dev/null
+++ b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/WellKnownTypes/FieldMaskTest.cs
@@ -0,0 +1,62 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2016 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+
+using NUnit.Framework;
+
+namespace Google.Protobuf.WellKnownTypes
+{
+ public class FieldMaskTest
+ {
+ [Test]
+ [TestCase("foo__bar")]
+ [TestCase("foo_3_ar")]
+ [TestCase("fooBar")]
+ public void ToString_Invalid(string input)
+ {
+ var mask = new FieldMask { Paths = { input } };
+ var text = mask.ToString();
+ // More specific test below
+ Assert.That(text, Does.Contain("@warning"));
+ Assert.That(text, Does.Contain(input));
+ }
+
+ [Test]
+ public void ToString_Invalid_Precise()
+ {
+ var mask = new FieldMask { Paths = { "x", "foo__bar", @"x\y" } };
+ Assert.AreEqual(
+ "{ \"@warning\": \"Invalid FieldMask\", \"paths\": [ \"x\", \"foo__bar\", \"x\\\\y\" ] }",
+ mask.ToString());
+ }
+ }
+}
diff --git a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/WellKnownTypes/TimestampTest.cs b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/WellKnownTypes/TimestampTest.cs
new file mode 100644
index 00000000..9ecd24c6
--- /dev/null
+++ b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/WellKnownTypes/TimestampTest.cs
@@ -0,0 +1,115 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2015 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+using NUnit.Framework;
+using System;
+
+namespace Google.Protobuf.WellKnownTypes
+{
+ public class TimestampTest
+ {
+ [Test]
+ public void FromAndToDateTime()
+ {
+ DateTime utcMin = DateTime.SpecifyKind(DateTime.MinValue, DateTimeKind.Utc);
+ DateTime utcMax = DateTime.SpecifyKind(DateTime.MaxValue, DateTimeKind.Utc);
+ AssertRoundtrip(new Timestamp { Seconds = -62135596800 }, utcMin);
+ AssertRoundtrip(new Timestamp { Seconds = 253402300799, Nanos = 999999900 }, utcMax);
+ AssertRoundtrip(new Timestamp(), new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc));
+ AssertRoundtrip(new Timestamp { Nanos = 1000000}, new DateTime(1970, 1, 1, 0, 0, 0, 1, DateTimeKind.Utc));
+ AssertRoundtrip(new Timestamp { Seconds = -1, Nanos = 999000000 }, new DateTime(1969, 12, 31, 23, 59, 59, 999, DateTimeKind.Utc));
+ AssertRoundtrip(new Timestamp { Seconds = 3600 }, new DateTime(1970, 1, 1, 1, 0, 0, DateTimeKind.Utc));
+ AssertRoundtrip(new Timestamp { Seconds = -3600 }, new DateTime(1969, 12, 31, 23, 0, 0, DateTimeKind.Utc));
+ }
+
+ [Test]
+ public void ToDateTimeTruncation()
+ {
+ var t1 = new Timestamp { Seconds = 1, Nanos = 1000000 + Duration.NanosecondsPerTick - 1 };
+ Assert.AreEqual(new DateTime(1970, 1, 1, 0, 0, 1, DateTimeKind.Utc).AddMilliseconds(1), t1.ToDateTime());
+
+ var t2 = new Timestamp { Seconds = -1, Nanos = 1000000 + Duration.NanosecondsPerTick - 1 };
+ Assert.AreEqual(new DateTime(1969, 12, 31, 23, 59, 59).AddMilliseconds(1), t2.ToDateTime());
+ }
+
+ [Test]
+ [TestCase(Timestamp.UnixSecondsAtBclMinValue - 1, Timestamp.MaxNanos)]
+ [TestCase(Timestamp.UnixSecondsAtBclMaxValue + 1, 0)]
+ [TestCase(0, -1)]
+ [TestCase(0, Timestamp.MaxNanos + 1)]
+ public void ToDateTime_OutOfRange(long seconds, int nanoseconds)
+ {
+ var value = new Timestamp { Seconds = seconds, Nanos = nanoseconds };
+ Assert.Throws<InvalidOperationException>(() => value.ToDateTime());
+ }
+
+ // 1ns larger or smaller than the above values
+ [Test]
+ [TestCase(Timestamp.UnixSecondsAtBclMinValue, 0)]
+ [TestCase(Timestamp.UnixSecondsAtBclMaxValue, Timestamp.MaxNanos)]
+ [TestCase(0, 0)]
+ [TestCase(0, Timestamp.MaxNanos)]
+ public void ToDateTime_ValidBoundaries(long seconds, int nanoseconds)
+ {
+ var value = new Timestamp { Seconds = seconds, Nanos = nanoseconds };
+ value.ToDateTime();
+ }
+
+ private static void AssertRoundtrip(Timestamp timestamp, DateTime dateTime)
+ {
+ Assert.AreEqual(timestamp, Timestamp.FromDateTime(dateTime));
+ Assert.AreEqual(dateTime, timestamp.ToDateTime());
+ Assert.AreEqual(DateTimeKind.Utc, timestamp.ToDateTime().Kind);
+ }
+
+ [Test]
+ public void Arithmetic()
+ {
+ Timestamp t1 = new Timestamp { Seconds = 10000, Nanos = 5000 };
+ Timestamp t2 = new Timestamp { Seconds = 8000, Nanos = 10000 };
+ Duration difference = new Duration { Seconds = 1999, Nanos = Duration.NanosecondsPerSecond - 5000 };
+ Assert.AreEqual(difference, t1 - t2);
+ Assert.AreEqual(-difference, t2 - t1);
+
+ Assert.AreEqual(t1, t2 + difference);
+ Assert.AreEqual(t2, t1 - difference);
+ }
+
+ [Test]
+ public void ToString_NonNormalized()
+ {
+ // Just a single example should be sufficient...
+ var duration = new Timestamp { Seconds = 1, Nanos = -1 };
+ Assert.AreEqual("{ \"@warning\": \"Invalid Timestamp\", \"seconds\": \"1\", \"nanos\": -1 }", duration.ToString());
+ }
+ }
+}
diff --git a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/WellKnownTypes/WrappersTest.cs b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/WellKnownTypes/WrappersTest.cs
new file mode 100644
index 00000000..5b7185dc
--- /dev/null
+++ b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/WellKnownTypes/WrappersTest.cs
@@ -0,0 +1,421 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2015 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+using System;
+using Google.Protobuf.TestProtos;
+using NUnit.Framework;
+using System.Collections;
+using System.IO;
+
+namespace Google.Protobuf.WellKnownTypes
+{
+ public class WrappersTest
+ {
+ [Test]
+ public void NullIsDefault()
+ {
+ var message = new TestWellKnownTypes();
+ Assert.IsNull(message.StringField);
+ Assert.IsNull(message.BytesField);
+ Assert.IsNull(message.BoolField);
+ Assert.IsNull(message.FloatField);
+ Assert.IsNull(message.DoubleField);
+ Assert.IsNull(message.Int32Field);
+ Assert.IsNull(message.Int64Field);
+ Assert.IsNull(message.Uint32Field);
+ Assert.IsNull(message.Uint64Field);
+ }
+
+ [Test]
+ public void NonDefaultSingleValues()
+ {
+ var message = new TestWellKnownTypes
+ {
+ StringField = "x",
+ BytesField = ByteString.CopyFrom(1, 2, 3),
+ BoolField = true,
+ FloatField = 12.5f,
+ DoubleField = 12.25d,
+ Int32Field = 1,
+ Int64Field = 2,
+ Uint32Field = 3,
+ Uint64Field = 4
+ };
+
+ var bytes = message.ToByteArray();
+ var parsed = TestWellKnownTypes.Parser.ParseFrom(bytes);
+
+ Assert.AreEqual("x", parsed.StringField);
+ Assert.AreEqual(ByteString.CopyFrom(1, 2, 3), parsed.BytesField);
+ Assert.AreEqual(true, parsed.BoolField);
+ Assert.AreEqual(12.5f, parsed.FloatField);
+ Assert.AreEqual(12.25d, parsed.DoubleField);
+ Assert.AreEqual(1, parsed.Int32Field);
+ Assert.AreEqual(2L, parsed.Int64Field);
+ Assert.AreEqual(3U, parsed.Uint32Field);
+ Assert.AreEqual(4UL, parsed.Uint64Field);
+ }
+
+ [Test]
+ public void NonNullDefaultIsPreservedThroughSerialization()
+ {
+ var message = new TestWellKnownTypes
+ {
+ StringField = "",
+ BytesField = ByteString.Empty,
+ BoolField = false,
+ FloatField = 0f,
+ DoubleField = 0d,
+ Int32Field = 0,
+ Int64Field = 0,
+ Uint32Field = 0,
+ Uint64Field = 0
+ };
+
+ var bytes = message.ToByteArray();
+ var parsed = TestWellKnownTypes.Parser.ParseFrom(bytes);
+
+ Assert.AreEqual("", parsed.StringField);
+ Assert.AreEqual(ByteString.Empty, parsed.BytesField);
+ Assert.AreEqual(false, parsed.BoolField);
+ Assert.AreEqual(0f, parsed.FloatField);
+ Assert.AreEqual(0d, parsed.DoubleField);
+ Assert.AreEqual(0, parsed.Int32Field);
+ Assert.AreEqual(0L, parsed.Int64Field);
+ Assert.AreEqual(0U, parsed.Uint32Field);
+ Assert.AreEqual(0UL, parsed.Uint64Field);
+ }
+
+ [Test]
+ public void RepeatedWrappersProhibitNullItems()
+ {
+ var message = new RepeatedWellKnownTypes();
+ Assert.Throws<ArgumentNullException>(() => message.BoolField.Add((bool?) null));
+ Assert.Throws<ArgumentNullException>(() => message.Int32Field.Add((int?) null));
+ Assert.Throws<ArgumentNullException>(() => message.StringField.Add((string) null));
+ Assert.Throws<ArgumentNullException>(() => message.BytesField.Add((ByteString) null));
+ }
+
+ [Test]
+ public void RepeatedWrappersSerializeDeserialize()
+ {
+ var message = new RepeatedWellKnownTypes
+ {
+ BoolField = { true, false },
+ BytesField = { ByteString.CopyFrom(1, 2, 3), ByteString.CopyFrom(4, 5, 6), ByteString.Empty },
+ DoubleField = { 12.5, -1.5, 0d },
+ FloatField = { 123.25f, -20f, 0f },
+ Int32Field = { int.MaxValue, int.MinValue, 0 },
+ Int64Field = { long.MaxValue, long.MinValue, 0L },
+ StringField = { "First", "Second", "" },
+ Uint32Field = { uint.MaxValue, uint.MinValue, 0U },
+ Uint64Field = { ulong.MaxValue, ulong.MinValue, 0UL },
+ };
+ var bytes = message.ToByteArray();
+ var parsed = RepeatedWellKnownTypes.Parser.ParseFrom(bytes);
+
+ Assert.AreEqual(message, parsed);
+ // Just to test a single value for sanity...
+ Assert.AreEqual("Second", message.StringField[1]);
+ }
+
+ [Test]
+ public void RepeatedWrappersBinaryFormat()
+ {
+ // At one point we accidentally used a packed format for repeated wrappers, which is wrong (and weird).
+ // This test is just to prove that we use the right format.
+
+ var rawOutput = new MemoryStream();
+ var output = new CodedOutputStream(rawOutput);
+ // Write a value of 5
+ output.WriteTag(RepeatedWellKnownTypes.Int32FieldFieldNumber, WireFormat.WireType.LengthDelimited);
+ output.WriteLength(2);
+ output.WriteTag(WrappersReflection.WrapperValueFieldNumber, WireFormat.WireType.Varint);
+ output.WriteInt32(5);
+ // Write a value of 0 (empty message)
+ output.WriteTag(RepeatedWellKnownTypes.Int32FieldFieldNumber, WireFormat.WireType.LengthDelimited);
+ output.WriteLength(0);
+ output.Flush();
+ var expectedBytes = rawOutput.ToArray();
+
+ var message = new RepeatedWellKnownTypes { Int32Field = { 5, 0 } };
+ var actualBytes = message.ToByteArray();
+ Assert.AreEqual(expectedBytes, actualBytes);
+ }
+
+ [Test]
+ public void MapWrappersSerializeDeserialize()
+ {
+ // Note: no null values here, as they are prohibited in map fields
+ // (despite being representable).
+ var message = new MapWellKnownTypes
+ {
+ BoolField = { { 10, false }, { 20, true } },
+ BytesField = {
+ { -1, ByteString.CopyFrom(1, 2, 3) },
+ { 10, ByteString.CopyFrom(4, 5, 6) },
+ { 1000, ByteString.Empty },
+ },
+ DoubleField = { { 1, 12.5 }, { 10, -1.5 }, { 20, 0d } },
+ FloatField = { { 2, 123.25f }, { 3, -20f }, { 4, 0f } },
+ Int32Field = { { 5, int.MaxValue }, { 6, int.MinValue }, { 7, 0 } },
+ Int64Field = { { 8, long.MaxValue }, { 9, long.MinValue }, { 10, 0L } },
+ StringField = { { 11, "First" }, { 12, "Second" }, { 13, "" } },
+ Uint32Field = { { 15, uint.MaxValue }, { 16, uint.MinValue }, { 17, 0U } },
+ Uint64Field = { { 18, ulong.MaxValue }, { 19, ulong.MinValue }, { 20, 0UL } },
+ };
+
+ var bytes = message.ToByteArray();
+ var parsed = MapWellKnownTypes.Parser.ParseFrom(bytes);
+
+ Assert.AreEqual(message, parsed);
+ // Just to test a single value for sanity...
+ Assert.AreEqual("Second", message.StringField[12]);
+ }
+
+ [Test]
+ public void Reflection_SingleValues()
+ {
+ var message = new TestWellKnownTypes
+ {
+ StringField = "x",
+ BytesField = ByteString.CopyFrom(1, 2, 3),
+ BoolField = true,
+ FloatField = 12.5f,
+ DoubleField = 12.25d,
+ Int32Field = 1,
+ Int64Field = 2,
+ Uint32Field = 3,
+ Uint64Field = 4
+ };
+ var fields = TestWellKnownTypes.Descriptor.Fields;
+
+ Assert.AreEqual("x", fields[TestWellKnownTypes.StringFieldFieldNumber].Accessor.GetValue(message));
+ Assert.AreEqual(ByteString.CopyFrom(1, 2, 3), fields[TestWellKnownTypes.BytesFieldFieldNumber].Accessor.GetValue(message));
+ Assert.AreEqual(true, fields[TestWellKnownTypes.BoolFieldFieldNumber].Accessor.GetValue(message));
+ Assert.AreEqual(12.5f, fields[TestWellKnownTypes.FloatFieldFieldNumber].Accessor.GetValue(message));
+ Assert.AreEqual(12.25d, fields[TestWellKnownTypes.DoubleFieldFieldNumber].Accessor.GetValue(message));
+ Assert.AreEqual(1, fields[TestWellKnownTypes.Int32FieldFieldNumber].Accessor.GetValue(message));
+ Assert.AreEqual(2L, fields[TestWellKnownTypes.Int64FieldFieldNumber].Accessor.GetValue(message));
+ Assert.AreEqual(3U, fields[TestWellKnownTypes.Uint32FieldFieldNumber].Accessor.GetValue(message));
+ Assert.AreEqual(4UL, fields[TestWellKnownTypes.Uint64FieldFieldNumber].Accessor.GetValue(message));
+
+ // And a couple of null fields...
+ message.StringField = null;
+ message.FloatField = null;
+ Assert.IsNull(fields[TestWellKnownTypes.StringFieldFieldNumber].Accessor.GetValue(message));
+ Assert.IsNull(fields[TestWellKnownTypes.FloatFieldFieldNumber].Accessor.GetValue(message));
+ }
+
+ [Test]
+ public void Reflection_RepeatedFields()
+ {
+ // Just a single example... note that we can't have a null value here
+ var message = new RepeatedWellKnownTypes { Int32Field = { 1, 2 } };
+ var fields = RepeatedWellKnownTypes.Descriptor.Fields;
+ var list = (IList) fields[RepeatedWellKnownTypes.Int32FieldFieldNumber].Accessor.GetValue(message);
+ CollectionAssert.AreEqual(new[] { 1, 2 }, list);
+ }
+
+ [Test]
+ public void Reflection_MapFields()
+ {
+ // Just a single example... note that we can't have a null value here despite the value type being int?
+ var message = new MapWellKnownTypes { Int32Field = { { 1, 2 } } };
+ var fields = MapWellKnownTypes.Descriptor.Fields;
+ var dictionary = (IDictionary) fields[MapWellKnownTypes.Int32FieldFieldNumber].Accessor.GetValue(message);
+ Assert.AreEqual(2, dictionary[1]);
+ }
+
+ [Test]
+ public void Oneof()
+ {
+ var message = new OneofWellKnownTypes { EmptyField = new Empty() };
+ // Start off with a non-wrapper
+ Assert.AreEqual(OneofWellKnownTypes.OneofFieldOneofCase.EmptyField, message.OneofFieldCase);
+ AssertOneofRoundTrip(message);
+
+ message.StringField = "foo";
+ Assert.AreEqual(OneofWellKnownTypes.OneofFieldOneofCase.StringField, message.OneofFieldCase);
+ AssertOneofRoundTrip(message);
+
+ message.StringField = "foo";
+ Assert.AreEqual(OneofWellKnownTypes.OneofFieldOneofCase.StringField, message.OneofFieldCase);
+ AssertOneofRoundTrip(message);
+
+ message.DoubleField = 0.0f;
+ Assert.AreEqual(OneofWellKnownTypes.OneofFieldOneofCase.DoubleField, message.OneofFieldCase);
+ AssertOneofRoundTrip(message);
+
+ message.DoubleField = 1.0f;
+ Assert.AreEqual(OneofWellKnownTypes.OneofFieldOneofCase.DoubleField, message.OneofFieldCase);
+ AssertOneofRoundTrip(message);
+
+ message.ClearOneofField();
+ Assert.AreEqual(OneofWellKnownTypes.OneofFieldOneofCase.None, message.OneofFieldCase);
+ AssertOneofRoundTrip(message);
+ }
+
+ private void AssertOneofRoundTrip(OneofWellKnownTypes message)
+ {
+ // Normal roundtrip, but explicitly checking the case...
+ var bytes = message.ToByteArray();
+ var parsed = OneofWellKnownTypes.Parser.ParseFrom(bytes);
+ Assert.AreEqual(message, parsed);
+ Assert.AreEqual(message.OneofFieldCase, parsed.OneofFieldCase);
+ }
+
+ [Test]
+ [TestCase("x", "y", "y")]
+ [TestCase("x", "", "x")]
+ [TestCase("x", null, "x")]
+ [TestCase("", "y", "y")]
+ [TestCase("", "", "")]
+ [TestCase("", null, "")]
+ [TestCase(null, "y", "y")]
+ [TestCase(null, "", "")]
+ [TestCase(null, null, null)]
+ public void Merging(string original, string merged, string expected)
+ {
+ var originalMessage = new TestWellKnownTypes { StringField = original };
+ var mergingMessage = new TestWellKnownTypes { StringField = merged };
+ originalMessage.MergeFrom(mergingMessage);
+ Assert.AreEqual(expected, originalMessage.StringField);
+
+ // Try it using MergeFrom(CodedInputStream) too...
+ originalMessage = new TestWellKnownTypes { StringField = original };
+ originalMessage.MergeFrom(mergingMessage.ToByteArray());
+ Assert.AreEqual(expected, originalMessage.StringField);
+ }
+
+ // Merging is odd with wrapper types, due to the way that default values aren't emitted in
+ // the binary stream. In fact we cheat a little bit - a message with an explicitly present default
+ // value will have that default value ignored. See issue 615. Fixing this would require significant upheaval to
+ // the FieldCodec side of things.
+ [Test]
+ public void MergingStreamExplicitValue()
+ {
+ var message = new TestWellKnownTypes { Int32Field = 5 };
+
+ // Create a byte array which has the data of an Int32Value explicitly containing a value of 0.
+ // This wouldn't normally happen.
+ byte[] bytes;
+ var wrapperTag = WireFormat.MakeTag(TestWellKnownTypes.Int32FieldFieldNumber, WireFormat.WireType.LengthDelimited);
+ var valueTag = WireFormat.MakeTag(Int32Value.ValueFieldNumber, WireFormat.WireType.Varint);
+ using (var stream = new MemoryStream())
+ {
+ var coded = new CodedOutputStream(stream);
+ coded.WriteTag(wrapperTag);
+ coded.WriteLength(2); // valueTag + a value 0, each one byte
+ coded.WriteTag(valueTag);
+ coded.WriteInt32(0);
+ coded.Flush();
+ bytes = stream.ToArray();
+ }
+
+ message.MergeFrom(bytes);
+ // A normal implementation would have 0 now, as the explicit default would have been overwritten the 5.
+ // With the FieldCodec for Nullable<int>, we can't tell the difference between an implicit 0 and an explicit 0.
+ Assert.AreEqual(5, message.Int32Field);
+ }
+
+ [Test]
+ public void MergingStreamNoValue()
+ {
+ var message = new TestWellKnownTypes { Int32Field = 5 };
+
+ // Create a byte array which an Int32 field, but with no value.
+ var bytes = new TestWellKnownTypes { Int32Field = 0 }.ToByteArray();
+ Assert.AreEqual(2, bytes.Length); // The tag for Int32Field is a single byte, then a byte indicating a 0-length message.
+ message.MergeFrom(bytes);
+
+ // The "implicit" 0 did *not* overwrite the value.
+ // (This is the correct behaviour.)
+ Assert.AreEqual(5, message.Int32Field);
+ }
+
+ // All permutations of origin/merging value being null, zero (default) or non-default.
+ // As this is the in-memory version, we don't need to worry about the difference between implicit and explicit 0.
+ [Test]
+ [TestCase(null, null, null)]
+ [TestCase(null, 0, 0)]
+ [TestCase(null, 5, 5)]
+ [TestCase(0, null, 0)]
+ [TestCase(0, 0, 0)]
+ [TestCase(0, 5, 5)]
+ [TestCase(5, null, 5)]
+ [TestCase(5, 0, 5)]
+ [TestCase(5, 10, 10)]
+ public void MergingMessageWithZero(int? originValue, int? mergingValue, int? expectedResult)
+ {
+ // This differs from the MergingStreamCornerCase because when we merge message *objects*,
+ // we ignore default values from the "source".
+ var message1 = new TestWellKnownTypes { Int32Field = originValue };
+ var message2 = new TestWellKnownTypes { Int32Field = mergingValue };
+ message1.MergeFrom(message2);
+ Assert.AreEqual(expectedResult, message1.Int32Field);
+ }
+
+ [Test]
+ public void UnknownFieldInWrapper()
+ {
+ var stream = new MemoryStream();
+ var output = new CodedOutputStream(stream);
+ var wrapperTag = WireFormat.MakeTag(TestWellKnownTypes.Int32FieldFieldNumber, WireFormat.WireType.LengthDelimited);
+ var unknownTag = WireFormat.MakeTag(15, WireFormat.WireType.Varint);
+ var valueTag = WireFormat.MakeTag(Int32Value.ValueFieldNumber, WireFormat.WireType.Varint);
+
+ output.WriteTag(wrapperTag);
+ output.WriteLength(4); // unknownTag + value 5 + valueType + value 6, each 1 byte
+ output.WriteTag(unknownTag);
+ output.WriteInt32((int) valueTag); // Sneakily "pretend" it's a tag when it's really a value
+ output.WriteTag(valueTag);
+ output.WriteInt32(6);
+
+ output.Flush();
+ stream.Position = 0;
+
+ var message = TestWellKnownTypes.Parser.ParseFrom(stream);
+ Assert.AreEqual(6, message.Int32Field);
+ }
+
+ [Test]
+ public void ClearWithReflection()
+ {
+ // String and Bytes are the tricky ones here, as the CLR type of the property
+ // is the same between the wrapper and non-wrapper types.
+ var message = new TestWellKnownTypes { StringField = "foo" };
+ TestWellKnownTypes.Descriptor.Fields[TestWellKnownTypes.StringFieldFieldNumber].Accessor.Clear(message);
+ Assert.IsNull(message.StringField);
+ }
+ }
+}
diff --git a/csharp/compatibility_tests/v3.0.0/test.sh b/csharp/compatibility_tests/v3.0.0/test.sh
new file mode 100755
index 00000000..54d28dfc
--- /dev/null
+++ b/csharp/compatibility_tests/v3.0.0/test.sh
@@ -0,0 +1,104 @@
+#!/bin/bash
+
+function run_test() {
+ # Generate test proto files.
+ ./protoc_1 -Iprotos/src -I../../../src/ --csharp_out=src/Google.Protobuf.Test \
+ --csharp_opt=base_namespace=Google.Protobuf \
+ protos/src/google/protobuf/unittest_import_proto3.proto \
+ protos/src/google/protobuf/unittest_import_public_proto3.proto \
+ protos/src/google/protobuf/unittest_well_known_types.proto
+
+ ./protoc_1 -Iprotos/csharp --csharp_out=src/Google.Protobuf.Test \
+ --csharp_opt=base_namespace=UnitTest.Issues \
+ protos/csharp/protos/unittest_issues.proto
+
+ ./protoc_2 -Iprotos/src --csharp_out=src/Google.Protobuf.Test \
+ --csharp_opt=base_namespace=Google.Protobuf \
+ protos/src/google/protobuf/unittest_proto3.proto \
+ protos/src/google/protobuf/map_unittest_proto3.proto
+
+ # Build and test.
+ dotnet restore src/Google.Protobuf/Google.Protobuf.csproj
+ dotnet restore src/Google.Protobuf.Test/Google.Protobuf.Test.csproj
+ dotnet build -c Release src/Google.Protobuf/Google.Protobuf.csproj
+ dotnet build -c Release src/Google.Protobuf.Test/Google.Protobuf.Test.csproj
+ dotnet run -c Release -f netcoreapp1.0 -p src/Google.Protobuf.Test/Google.Protobuf.Test.csproj
+}
+
+set -ex
+
+# Change to the script's directory.
+cd $(dirname $0)
+
+# Version of the tests (i.e., the version of protobuf from where we extracted
+# these tests).
+TEST_VERSION=3.0.0
+
+# The old version of protobuf that we are testing compatibility against. This
+# is usually the same as TEST_VERSION (i.e., we use the tests extracted from
+# that version to test compatibility of the newest runtime against it), but it
+# is also possible to use this same test set to test the compatibiilty of the
+# latest version against other versions.
+case "$1" in
+ ""|3.0.0)
+ OLD_VERSION=3.0.0
+ OLD_VERSION_PROTOC=http://repo1.maven.org/maven2/com/google/protobuf/protoc/3.0.0/protoc-3.0.0-linux-x86_64.exe
+ ;;
+ 3.0.2)
+ OLD_VERSION=3.0.2
+ OLD_VERSION_PROTOC=http://repo1.maven.org/maven2/com/google/protobuf/protoc/3.0.2/protoc-3.0.2-linux-x86_64.exe
+ ;;
+ 3.1.0)
+ OLD_VERSION=3.1.0
+ OLD_VERSION_PROTOC=http://repo1.maven.org/maven2/com/google/protobuf/protoc/3.1.0/protoc-3.1.0-linux-x86_64.exe
+ ;;
+ *)
+ echo "[ERROR]: Unknown version number: $1"
+ exit 1
+ ;;
+esac
+
+echo "Running compatibility tests with $OLD_VERSION"
+
+# Check protoc
+[ -f ../../../src/protoc ] || {
+ echo "[ERROR]: Please build protoc first."
+ exit 1
+}
+
+# Download old version protoc compiler (for linux).
+wget $OLD_VERSION_PROTOC -O old_protoc
+chmod +x old_protoc
+
+# Test source compatibility. In these tests we recompile everything against
+# the new runtime (including old version generated code).
+# Copy the new runtime and keys.
+cp ../../src/Google.Protobuf src/Google.Protobuf -r
+cp ../../keys . -r
+
+# Test A.1:
+# proto set 1: use old version
+# proto set 2 which may import protos in set 1: use old version
+cp old_protoc protoc_1
+cp old_protoc protoc_2
+run_test
+
+# Test A.2:
+# proto set 1: use new version
+# proto set 2 which may import protos in set 1: use old version
+cp ../../../src/protoc protoc_1
+cp old_protoc protoc_2
+run_test
+
+# Test A.3:
+# proto set 1: use old version
+# proto set 2 which may import protos in set 1: use new version
+cp old_protoc protoc_1
+cp ../../../src/protoc protoc_2
+run_test
+
+rm protoc_1
+rm protoc_2
+rm old_protoc
+rm keys -r
+rm src/Google.Protobuf -r
diff --git a/csharp/generate_protos.sh b/csharp/generate_protos.sh
index 7cbcf436..5c748e35 100755
--- a/csharp/generate_protos.sh
+++ b/csharp/generate_protos.sh
@@ -3,7 +3,7 @@
# You first need to make sure protoc has been built (see instructions on
# building protoc in root of this repository)
-set -ex
+set -e
# cd to repository root
pushd $(dirname $0)/..
@@ -40,27 +40,20 @@ $PROTOC -Isrc --csharp_out=csharp/src/Google.Protobuf \
src/google/protobuf/type.proto \
src/google/protobuf/wrappers.proto
-# Test protos where the namespace matches the target location
-$PROTOC -Isrc --csharp_out=csharp/src/Google.Protobuf.Test \
- --csharp_opt=base_namespace=Google.Protobuf \
- src/google/protobuf/map_unittest_proto3.proto \
- src/google/protobuf/unittest_proto3.proto \
- src/google/protobuf/unittest_import_proto3.proto \
- src/google/protobuf/unittest_import_public_proto3.proto \
- src/google/protobuf/unittest_well_known_types.proto
-
-# Different base namespace to the protos above
-$PROTOC -Icsharp/protos --csharp_out=csharp/src/Google.Protobuf.Test \
- --csharp_opt=base_namespace=UnitTest.Issues \
- csharp/protos/unittest_issues.proto
-
-# Don't specify a base namespace at all; we just want to make sure the
-# results end up in TestProtos.
-$PROTOC -Isrc --csharp_out=csharp/src/Google.Protobuf.Test/TestProtos \
+# Test protos
+$PROTOC -Isrc -Icsharp/protos \
+ --csharp_out=csharp/src/Google.Protobuf.Test/TestProtos \
+ csharp/protos/map_unittest_proto3.proto \
+ csharp/protos/unittest_issues.proto \
+ csharp/protos/unittest_custom_options_proto3.proto \
+ csharp/protos/unittest_proto3.proto \
+ csharp/protos/unittest_import_proto3.proto \
+ csharp/protos/unittest_import_public_proto3.proto \
+ src/google/protobuf/unittest_well_known_types.proto \
src/google/protobuf/test_messages_proto3.proto
# AddressBook sample protos
-$PROTOC -Iexamples --csharp_out=csharp/src/AddressBook \
+$PROTOC -Iexamples -Isrc --csharp_out=csharp/src/AddressBook \
examples/addressbook.proto
$PROTOC -Iconformance -Isrc --csharp_out=csharp/src/Google.Protobuf.Conformance \
diff --git a/csharp/global.json b/csharp/global.json
new file mode 100644
index 00000000..3622b564
--- /dev/null
+++ b/csharp/global.json
@@ -0,0 +1,5 @@
+{
+ "sdk": {
+ "version": "1.0.0"
+ }
+}
diff --git a/csharp/protos/README.md b/csharp/protos/README.md
new file mode 100644
index 00000000..bdd66fcf
--- /dev/null
+++ b/csharp/protos/README.md
@@ -0,0 +1,3 @@
+This directory contains unit test protos adapted from those in
+src/google/protobuf, and C#-specific test protos for regression
+tests against bugs found in the C# codegen or library.
diff --git a/csharp/protos/map_unittest_proto3.proto b/csharp/protos/map_unittest_proto3.proto
new file mode 100644
index 00000000..e43e858b
--- /dev/null
+++ b/csharp/protos/map_unittest_proto3.proto
@@ -0,0 +1,116 @@
+// 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.
+
+// This file is mostly equivalent to map_unittest.proto, but imports
+// unittest_proto3.proto instead of unittest.proto, so that it only
+// uses proto3 messages. This makes it suitable for testing
+// implementations which only support proto3.
+// The TestRequiredMessageMap message has been removed as there are no
+// required fields in proto3.
+syntax = "proto3";
+
+option csharp_namespace = "Google.Protobuf.TestProtos";
+
+import "unittest_proto3.proto";
+
+package protobuf_unittest3;
+
+// Tests maps.
+message TestMap {
+ map<int32 , int32 > map_int32_int32 = 1;
+ map<int64 , int64 > map_int64_int64 = 2;
+ map<uint32 , uint32 > map_uint32_uint32 = 3;
+ map<uint64 , uint64 > map_uint64_uint64 = 4;
+ map<sint32 , sint32 > map_sint32_sint32 = 5;
+ map<sint64 , sint64 > map_sint64_sint64 = 6;
+ map<fixed32 , fixed32 > map_fixed32_fixed32 = 7;
+ map<fixed64 , fixed64 > map_fixed64_fixed64 = 8;
+ map<sfixed32, sfixed32> map_sfixed32_sfixed32 = 9;
+ map<sfixed64, sfixed64> map_sfixed64_sfixed64 = 10;
+ map<int32 , float > map_int32_float = 11;
+ map<int32 , double > map_int32_double = 12;
+ map<bool , bool > map_bool_bool = 13;
+ map<string , string > map_string_string = 14;
+ map<int32 , bytes > map_int32_bytes = 15;
+ map<int32 , MapEnum > map_int32_enum = 16;
+ map<int32 , ForeignMessage> map_int32_foreign_message = 17;
+}
+
+message TestMapSubmessage {
+ TestMap test_map = 1;
+}
+
+message TestMessageMap {
+ map<int32, TestAllTypes> map_int32_message = 1;
+}
+
+// Two map fields share the same entry default instance.
+message TestSameTypeMap {
+ map<int32, int32> map1 = 1;
+ map<int32, int32> map2 = 2;
+}
+
+enum MapEnum {
+ MAP_ENUM_FOO = 0;
+ MAP_ENUM_BAR = 1;
+ MAP_ENUM_BAZ = 2;
+}
+
+message TestArenaMap {
+ map<int32 , int32 > map_int32_int32 = 1;
+ map<int64 , int64 > map_int64_int64 = 2;
+ map<uint32 , uint32 > map_uint32_uint32 = 3;
+ map<uint64 , uint64 > map_uint64_uint64 = 4;
+ map<sint32 , sint32 > map_sint32_sint32 = 5;
+ map<sint64 , sint64 > map_sint64_sint64 = 6;
+ map<fixed32 , fixed32 > map_fixed32_fixed32 = 7;
+ map<fixed64 , fixed64 > map_fixed64_fixed64 = 8;
+ map<sfixed32, sfixed32> map_sfixed32_sfixed32 = 9;
+ map<sfixed64, sfixed64> map_sfixed64_sfixed64 = 10;
+ map<int32 , float > map_int32_float = 11;
+ map<int32 , double > map_int32_double = 12;
+ map<bool , bool > map_bool_bool = 13;
+ map<int32 , MapEnum > map_int32_enum = 14;
+ map<int32 , ForeignMessage> map_int32_foreign_message = 15;
+}
+
+// Previously, message containing enum called Type cannot be used as value of
+// map field.
+message MessageContainingEnumCalledType {
+ enum Type {
+ TYPE_FOO = 0;
+ }
+ map<int32, MessageContainingEnumCalledType> type = 1;
+}
+
+// Previously, message cannot contain map field called "entry".
+message MessageContainingMapCalledEntry {
+ map<int32, int32> entry = 1;
+}
diff --git a/csharp/protos/unittest_custom_options_proto3.proto b/csharp/protos/unittest_custom_options_proto3.proto
new file mode 100644
index 00000000..87bd0f7a
--- /dev/null
+++ b/csharp/protos/unittest_custom_options_proto3.proto
@@ -0,0 +1,336 @@
+// 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: benjy@google.com (Benjy Weinberger)
+// Based on original Protocol Buffers design by
+// Sanjay Ghemawat, Jeff Dean, and others.
+//
+// A proto file used to test the "custom options" feature of google.protobuf.
+
+// This file is based on unittest_custom_options.proto in
+// src/google/protobuf, but is modified for proto3. It could
+// potentially be moved into src/google/protobuf, but currently C#
+// is the only language that really needs it, as we don't support
+// proto2 syntax. It's cut down significantly as proto3 only supports
+// extensions for options.
+
+
+syntax = "proto3";
+
+// A custom file option (defined below).
+option (file_opt1) = 9876543210;
+
+import "google/protobuf/descriptor.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.
+package protobuf_unittest;
+option csharp_namespace = "UnitTest.Issues.TestProtos";
+
+// Some simple test custom options of various types.
+
+extend google.protobuf.FileOptions {
+ uint64 file_opt1 = 7736974;
+}
+
+extend google.protobuf.MessageOptions {
+ int32 message_opt1 = 7739036;
+}
+
+extend google.protobuf.FieldOptions {
+ fixed64 field_opt1 = 7740936;
+}
+
+extend google.protobuf.OneofOptions {
+ int32 oneof_opt1 = 7740111;
+}
+
+extend google.protobuf.EnumOptions {
+ sfixed32 enum_opt1 = 7753576;
+}
+
+extend google.protobuf.EnumValueOptions {
+ int32 enum_value_opt1 = 1560678;
+}
+
+extend google.protobuf.ServiceOptions {
+ sint64 service_opt1 = 7887650;
+}
+
+enum MethodOpt1 {
+ METHODOPT1_UNSPECIFIED = 0;
+ METHODOPT1_VAL1 = 1;
+ METHODOPT1_VAL2 = 2;
+}
+
+extend google.protobuf.MethodOptions {
+ MethodOpt1 method_opt1 = 7890860;
+}
+
+// A test message with custom options at all possible locations (and also some
+// regular options, to make sure they interact nicely).
+message TestMessageWithCustomOptions {
+ option message_set_wire_format = false;
+
+ option (message_opt1) = -56;
+
+ string field1 = 1 [ctype=CORD,
+ (field_opt1)=8765432109];
+
+ oneof AnOneof {
+ option (oneof_opt1) = -99;
+ int32 oneof_field = 2;
+ }
+
+ enum AnEnum {
+ option (enum_opt1) = -789;
+ ANENUM_UNSPECIFIED = 0;
+ ANENUM_VAL1 = 1;
+ ANENUM_VAL2 = 2 [(enum_value_opt1) = 123];
+ }
+}
+
+
+// A test RPC service with custom options at all possible locations (and also
+// some regular options, to make sure they interact nicely).
+message CustomOptionFooRequest {
+}
+
+message CustomOptionFooResponse {
+}
+
+message CustomOptionFooClientMessage {
+}
+
+message CustomOptionFooServerMessage {
+}
+
+service TestServiceWithCustomOptions {
+ option (service_opt1) = -9876543210;
+
+ rpc Foo(CustomOptionFooRequest) returns (CustomOptionFooResponse) {
+ option (method_opt1) = METHODOPT1_VAL2;
+ }
+}
+
+
+
+// Options of every possible field type, so we can test them all exhaustively.
+
+message DummyMessageContainingEnum {
+ enum TestEnumType {
+ TEST_OPTION_ENUM_UNSPECIFIED = 0;
+ TEST_OPTION_ENUM_TYPE1 = 22;
+ TEST_OPTION_ENUM_TYPE2 = -23;
+ }
+}
+
+message DummyMessageInvalidAsOptionType {
+}
+
+extend google.protobuf.MessageOptions {
+ bool bool_opt = 7706090;
+ int32 int32_opt = 7705709;
+ int64 int64_opt = 7705542;
+ uint32 uint32_opt = 7704880;
+ uint64 uint64_opt = 7702367;
+ sint32 sint32_opt = 7701568;
+ sint64 sint64_opt = 7700863;
+ fixed32 fixed32_opt = 7700307;
+ fixed64 fixed64_opt = 7700194;
+ sfixed32 sfixed32_opt = 7698645;
+ sfixed64 sfixed64_opt = 7685475;
+ float float_opt = 7675390;
+ double double_opt = 7673293;
+ string string_opt = 7673285;
+ bytes bytes_opt = 7673238;
+ DummyMessageContainingEnum.TestEnumType enum_opt = 7673233;
+ DummyMessageInvalidAsOptionType message_type_opt = 7665967;
+}
+
+message CustomOptionMinIntegerValues {
+ option (bool_opt) = false;
+ option (int32_opt) = -0x80000000;
+ option (int64_opt) = -0x8000000000000000;
+ option (uint32_opt) = 0;
+ option (uint64_opt) = 0;
+ option (sint32_opt) = -0x80000000;
+ option (sint64_opt) = -0x8000000000000000;
+ option (fixed32_opt) = 0;
+ option (fixed64_opt) = 0;
+ option (sfixed32_opt) = -0x80000000;
+ option (sfixed64_opt) = -0x8000000000000000;
+}
+
+message CustomOptionMaxIntegerValues {
+ option (bool_opt) = true;
+ option (int32_opt) = 0x7FFFFFFF;
+ option (int64_opt) = 0x7FFFFFFFFFFFFFFF;
+ option (uint32_opt) = 0xFFFFFFFF;
+ option (uint64_opt) = 0xFFFFFFFFFFFFFFFF;
+ option (sint32_opt) = 0x7FFFFFFF;
+ option (sint64_opt) = 0x7FFFFFFFFFFFFFFF;
+ option (fixed32_opt) = 0xFFFFFFFF;
+ option (fixed64_opt) = 0xFFFFFFFFFFFFFFFF;
+ option (sfixed32_opt) = 0x7FFFFFFF;
+ option (sfixed64_opt) = 0x7FFFFFFFFFFFFFFF;
+}
+
+message CustomOptionOtherValues {
+ option (int32_opt) = -100; // To test sign-extension.
+ option (float_opt) = 12.3456789;
+ option (double_opt) = 1.234567890123456789;
+ option (string_opt) = "Hello, \"World\"";
+ option (bytes_opt) = "Hello\0World";
+ option (enum_opt) = TEST_OPTION_ENUM_TYPE2;
+}
+
+message SettingRealsFromPositiveInts {
+ option (float_opt) = 12;
+ option (double_opt) = 154;
+}
+
+message SettingRealsFromNegativeInts {
+ option (float_opt) = -12;
+ option (double_opt) = -154;
+}
+
+// Options of complex message types, themselves combined and extended in
+// various ways.
+
+message ComplexOptionType1 {
+ int32 foo = 1;
+ int32 foo2 = 2;
+ int32 foo3 = 3;
+ repeated int32 foo4 = 4;
+}
+
+message ComplexOptionType2 {
+ ComplexOptionType1 bar = 1;
+ int32 baz = 2;
+
+ message ComplexOptionType4 {
+ int32 waldo = 1;
+
+ extend google.protobuf.MessageOptions {
+ ComplexOptionType4 complex_opt4 = 7633546;
+ }
+ }
+
+ ComplexOptionType4 fred = 3;
+ repeated ComplexOptionType4 barney = 4;
+}
+
+message ComplexOptionType3 {
+ int32 qux = 1;
+}
+
+extend google.protobuf.MessageOptions {
+ protobuf_unittest.ComplexOptionType1 complex_opt1 = 7646756;
+ ComplexOptionType2 complex_opt2 = 7636949;
+ ComplexOptionType3 complex_opt3 = 7636463;
+}
+
+// Note that we try various different ways of naming the same extension.
+message VariousComplexOptions {
+ option (.protobuf_unittest.complex_opt1).foo = 42;
+ option (protobuf_unittest.complex_opt1).foo4 = 99;
+ option (protobuf_unittest.complex_opt1).foo4 = 88;
+ option (complex_opt2).baz = 987;
+ option (complex_opt2).bar.foo = 743;
+ option (ComplexOptionType2.ComplexOptionType4.complex_opt4).waldo = 1971;
+ option (complex_opt2).fred.waldo = 321;
+ option (complex_opt2).barney = { waldo: 101 };
+ option (complex_opt2).barney = { waldo: 212 };
+ option (protobuf_unittest.complex_opt3).qux = 9;
+}
+
+// ------------------------------------------------------
+// Definitions for testing aggregate option parsing.
+// See descriptor_unittest.cc.
+
+// A helper type used to test aggregate option parsing
+message Aggregate {
+ int32 i = 1;
+ string s = 2;
+
+ // A nested object
+ Aggregate sub = 3;
+}
+
+// Allow Aggregate to be used as an option at all possible locations
+// in the .proto grammer.
+extend google.protobuf.FileOptions { Aggregate fileopt = 15478479; }
+extend google.protobuf.MessageOptions { Aggregate msgopt = 15480088; }
+extend google.protobuf.FieldOptions { Aggregate fieldopt = 15481374; }
+extend google.protobuf.EnumOptions { Aggregate enumopt = 15483218; }
+extend google.protobuf.EnumValueOptions { Aggregate enumvalopt = 15486921; }
+extend google.protobuf.ServiceOptions { Aggregate serviceopt = 15497145; }
+extend google.protobuf.MethodOptions { Aggregate methodopt = 15512713; }
+
+// Try using AggregateOption at different points in the proto grammar
+option (fileopt) = {
+ s: 'FileAnnotation'
+ // Also test the handling of comments
+ /* of both types */ i: 100
+
+ sub { s: 'NestedFileAnnotation' }
+};
+
+message AggregateMessage {
+ option (msgopt) = { i:101 s:'MessageAnnotation' };
+ int32 fieldname = 1 [(fieldopt) = { s:'FieldAnnotation' }];
+}
+
+service AggregateService {
+ option (serviceopt) = { s:'ServiceAnnotation' };
+ rpc Method (AggregateMessage) returns (AggregateMessage) {
+ option (methodopt) = { s:'MethodAnnotation' };
+ }
+}
+
+enum AggregateEnum {
+ option (enumopt) = { s:'EnumAnnotation' };
+ UNSPECIFIED = 0;
+ VALUE = 1 [(enumvalopt) = { s:'EnumValueAnnotation' }];
+}
+
+// Test custom options for nested type.
+message NestedOptionType {
+ message NestedMessage {
+ option (message_opt1) = 1001;
+ int32 nested_field = 1 [(field_opt1) = 1002];
+ }
+ enum NestedEnum {
+ UNSPECIFIED = 0;
+ option (enum_opt1) = 1003;
+ NESTED_ENUM_VALUE = 1 [(enum_value_opt1) = 1004];
+ }
+}
diff --git a/csharp/protos/unittest_import_proto3.proto b/csharp/protos/unittest_import_proto3.proto
new file mode 100644
index 00000000..2e666822
--- /dev/null
+++ b/csharp/protos/unittest_import_proto3.proto
@@ -0,0 +1,56 @@
+// 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";
+
+package protobuf_unittest_import;
+
+option csharp_namespace = "Google.Protobuf.TestProtos";
+
+// Test public import
+import public "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/arena_nc.cc b/csharp/protos/unittest_import_public_proto3.proto
index f2f08427..88c20799 100644
--- a/src/google/protobuf/arena_nc.cc
+++ b/csharp/protos/unittest_import_public_proto3.proto
@@ -28,18 +28,14 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-// Negative compilation test for arena usage.
+// Author: liujisi@google.com (Pherl Liu)
-#include <google/protobuf/arena.h>
-#include <google/protobuf/unittest.pb.h>
+syntax = "proto3";
-#ifdef TEST_ARENA_PRIVATE_CONSTRUCTOR
+package protobuf_unittest_import;
-namespace google {
-void ArenaPrivateConstructor() {
- google::protobuf::Arena arena;
- protobuf_unittest::TestAllTypes message(&arena);
-}
+option csharp_namespace = "Google.Protobuf.TestProtos";
-#endif
-} // namespace google
+message PublicImportMessage {
+ int32 e = 1;
+}
diff --git a/csharp/protos/unittest_issues.proto b/csharp/protos/unittest_issues.proto
index 6c9f7634..0d8793e1 100644
--- a/csharp/protos/unittest_issues.proto
+++ b/csharp/protos/unittest_issues.proto
@@ -7,7 +7,6 @@ syntax = "proto3";
option csharp_namespace = "UnitTest.Issues.TestProtos";
package unittest_issues;
-option optimize_for = SPEED;
// Issue 307: when generating doubly-nested types, any references
// should be of the form A.Types.B.Types.C.
@@ -124,3 +123,18 @@ message TestJsonName {
string description = 2 [json_name = "desc"];
string guid = 3 [json_name = "exid"];
}
+
+// Issue 3200: When merging two messages which use the same
+// oneof case, which is itself a message type, the submessages should
+// be merged.
+message OneofMerging {
+ message Nested {
+ int32 x = 1;
+ int32 y = 2;
+ }
+
+ oneof value {
+ string text = 1;
+ Nested nested = 2;
+ }
+} \ No newline at end of file
diff --git a/csharp/protos/unittest_proto3.proto b/csharp/protos/unittest_proto3.proto
new file mode 100644
index 00000000..d22265cc
--- /dev/null
+++ b/csharp/protos/unittest_proto3.proto
@@ -0,0 +1,379 @@
+// 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";
+
+option csharp_namespace = "Google.Protobuf.TestProtos";
+
+// Only present so we can test that we can read it (as an example
+// of a non-C# option)
+option java_outer_classname = "UnittestProto";
+
+import "unittest_import_proto3.proto";
+
+package protobuf_unittest3;
+
+// 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;
+}
+
+message TestEnumAllowAlias {
+ TestEnumWithDupValue value = 1;
+}
+
+// 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 {}
+
diff --git a/csharp/src/AddressBook/AddressBook.csproj b/csharp/src/AddressBook/AddressBook.csproj
new file mode 100644
index 00000000..6edfdcab
--- /dev/null
+++ b/csharp/src/AddressBook/AddressBook.csproj
@@ -0,0 +1,14 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <PropertyGroup>
+ <TargetFramework>netcoreapp1.0</TargetFramework>
+ <OutputType>Exe</OutputType>
+ <StartupObject>Google.Protobuf.Examples.AddressBook.Program</StartupObject>
+ <IsPackable>False</IsPackable>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="..\Google.Protobuf\Google.Protobuf.csproj" />
+ </ItemGroup>
+
+</Project>
diff --git a/csharp/src/AddressBook/AddressBook.xproj b/csharp/src/AddressBook/AddressBook.xproj
deleted file mode 100644
index 4c9925e8..00000000
--- a/csharp/src/AddressBook/AddressBook.xproj
+++ /dev/null
@@ -1,19 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
- <PropertyGroup>
- <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">14.0</VisualStudioVersion>
- <VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
- </PropertyGroup>
- <Import Project="$(VSToolsPath)\DotNet\Microsoft.DotNet.Props" Condition="'$(VSToolsPath)' != ''" />
- <PropertyGroup Label="Globals">
- <ProjectGuid>afb63919-1e05-43b4-802a-8fb8c9b2f463</ProjectGuid>
- <RootNamespace>AddressBook</RootNamespace>
- <BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">.\obj</BaseIntermediateOutputPath>
- <OutputPath Condition="'$(OutputPath)'=='' ">.\bin\</OutputPath>
- </PropertyGroup>
-
- <PropertyGroup>
- <SchemaVersion>2.0</SchemaVersion>
- </PropertyGroup>
- <Import Project="$(VSToolsPath)\DotNet\Microsoft.DotNet.targets" Condition="'$(VSToolsPath)' != ''" />
-</Project> \ No newline at end of file
diff --git a/csharp/src/AddressBook/Addressbook.cs b/csharp/src/AddressBook/Addressbook.cs
index 75ed071b..e595e58b 100644
--- a/csharp/src/AddressBook/Addressbook.cs
+++ b/csharp/src/AddressBook/Addressbook.cs
@@ -22,19 +22,21 @@ namespace Google.Protobuf.Examples.AddressBook {
static AddressbookReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
- "ChFhZGRyZXNzYm9vay5wcm90bxIIdHV0b3JpYWwi1QEKBlBlcnNvbhIMCgRu",
- "YW1lGAEgASgJEgoKAmlkGAIgASgFEg0KBWVtYWlsGAMgASgJEiwKBnBob25l",
- "cxgEIAMoCzIcLnR1dG9yaWFsLlBlcnNvbi5QaG9uZU51bWJlchpHCgtQaG9u",
- "ZU51bWJlchIOCgZudW1iZXIYASABKAkSKAoEdHlwZRgCIAEoDjIaLnR1dG9y",
- "aWFsLlBlcnNvbi5QaG9uZVR5cGUiKwoJUGhvbmVUeXBlEgoKBk1PQklMRRAA",
- "EggKBEhPTUUQARIICgRXT1JLEAIiLwoLQWRkcmVzc0Jvb2sSIAoGcGVvcGxl",
- "GAEgAygLMhAudHV0b3JpYWwuUGVyc29uQlAKFGNvbS5leGFtcGxlLnR1dG9y",
- "aWFsQhFBZGRyZXNzQm9va1Byb3Rvc6oCJEdvb2dsZS5Qcm90b2J1Zi5FeGFt",
- "cGxlcy5BZGRyZXNzQm9va2IGcHJvdG8z"));
+ "ChFhZGRyZXNzYm9vay5wcm90bxIIdHV0b3JpYWwaH2dvb2dsZS9wcm90b2J1",
+ "Zi90aW1lc3RhbXAucHJvdG8ihwIKBlBlcnNvbhIMCgRuYW1lGAEgASgJEgoK",
+ "AmlkGAIgASgFEg0KBWVtYWlsGAMgASgJEiwKBnBob25lcxgEIAMoCzIcLnR1",
+ "dG9yaWFsLlBlcnNvbi5QaG9uZU51bWJlchIwCgxsYXN0X3VwZGF0ZWQYBSAB",
+ "KAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wGkcKC1Bob25lTnVtYmVy",
+ "Eg4KBm51bWJlchgBIAEoCRIoCgR0eXBlGAIgASgOMhoudHV0b3JpYWwuUGVy",
+ "c29uLlBob25lVHlwZSIrCglQaG9uZVR5cGUSCgoGTU9CSUxFEAASCAoESE9N",
+ "RRABEggKBFdPUksQAiIvCgtBZGRyZXNzQm9vaxIgCgZwZW9wbGUYASADKAsy",
+ "EC50dXRvcmlhbC5QZXJzb25CUAoUY29tLmV4YW1wbGUudHV0b3JpYWxCEUFk",
+ "ZHJlc3NCb29rUHJvdG9zqgIkR29vZ2xlLlByb3RvYnVmLkV4YW1wbGVzLkFk",
+ "ZHJlc3NCb29rYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
- new pbr::FileDescriptor[] { },
+ new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
- new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Examples.AddressBook.Person), global::Google.Protobuf.Examples.AddressBook.Person.Parser, new[]{ "Name", "Id", "Email", "Phones" }, null, new[]{ typeof(global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneType) }, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneNumber), global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneNumber.Parser, new[]{ "Number", "Type" }, null, null, null)}),
+ new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Examples.AddressBook.Person), global::Google.Protobuf.Examples.AddressBook.Person.Parser, new[]{ "Name", "Id", "Email", "Phones", "LastUpdated" }, null, new[]{ typeof(global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneType) }, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneNumber), global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneNumber.Parser, new[]{ "Number", "Type" }, null, null, null)}),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Examples.AddressBook.AddressBook), global::Google.Protobuf.Examples.AddressBook.AddressBook.Parser, new[]{ "People" }, null, null, null)
}));
}
@@ -73,6 +75,7 @@ namespace Google.Protobuf.Examples.AddressBook {
id_ = other.id_;
email_ = other.email_;
phones_ = other.phones_.Clone();
+ LastUpdated = other.lastUpdated_ != null ? other.LastUpdated.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -126,6 +129,17 @@ namespace Google.Protobuf.Examples.AddressBook {
get { return phones_; }
}
+ /// <summary>Field number for the "last_updated" field.</summary>
+ public const int LastUpdatedFieldNumber = 5;
+ private global::Google.Protobuf.WellKnownTypes.Timestamp lastUpdated_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public global::Google.Protobuf.WellKnownTypes.Timestamp LastUpdated {
+ get { return lastUpdated_; }
+ set {
+ lastUpdated_ = value;
+ }
+ }
+
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Person);
@@ -143,6 +157,7 @@ namespace Google.Protobuf.Examples.AddressBook {
if (Id != other.Id) return false;
if (Email != other.Email) return false;
if(!phones_.Equals(other.phones_)) return false;
+ if (!object.Equals(LastUpdated, other.LastUpdated)) return false;
return true;
}
@@ -153,6 +168,7 @@ namespace Google.Protobuf.Examples.AddressBook {
if (Id != 0) hash ^= Id.GetHashCode();
if (Email.Length != 0) hash ^= Email.GetHashCode();
hash ^= phones_.GetHashCode();
+ if (lastUpdated_ != null) hash ^= LastUpdated.GetHashCode();
return hash;
}
@@ -176,6 +192,10 @@ namespace Google.Protobuf.Examples.AddressBook {
output.WriteString(Email);
}
phones_.WriteTo(output, _repeated_phones_codec);
+ if (lastUpdated_ != null) {
+ output.WriteRawTag(42);
+ output.WriteMessage(LastUpdated);
+ }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -191,6 +211,9 @@ namespace Google.Protobuf.Examples.AddressBook {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Email);
}
size += phones_.CalculateSize(_repeated_phones_codec);
+ if (lastUpdated_ != null) {
+ size += 1 + pb::CodedOutputStream.ComputeMessageSize(LastUpdated);
+ }
return size;
}
@@ -209,6 +232,12 @@ namespace Google.Protobuf.Examples.AddressBook {
Email = other.Email;
}
phones_.Add(other.phones_);
+ if (other.lastUpdated_ != null) {
+ if (lastUpdated_ == null) {
+ lastUpdated_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
+ }
+ LastUpdated.MergeFrom(other.LastUpdated);
+ }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -235,6 +264,13 @@ namespace Google.Protobuf.Examples.AddressBook {
phones_.AddEntriesFrom(input, _repeated_phones_codec);
break;
}
+ case 42: {
+ if (lastUpdated_ == null) {
+ lastUpdated_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
+ }
+ input.ReadMessage(lastUpdated_);
+ break;
+ }
}
}
}
diff --git a/csharp/src/AddressBook/project.json b/csharp/src/AddressBook/project.json
deleted file mode 100644
index c500bdc2..00000000
--- a/csharp/src/AddressBook/project.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "buildOptions": {
- "debugType": "portable",
- "emitEntryPoint": true,
- "additionalArguments": [ "/main:Google.Protobuf.Examples.AddressBook.Program" ]
- },
- "dependencies": {
- "Google.Protobuf": { "target": "project" }
- },
- "frameworks": {
- "netcoreapp1.0": {
- "dependencies": {
- "Microsoft.NETCore.App": {
- "type": "platform",
- "version": "1.0.0"
- }
- }
- }
- }
-}
diff --git a/csharp/src/Google.Protobuf.Conformance/Conformance.cs b/csharp/src/Google.Protobuf.Conformance/Conformance.cs
index 1a835aef..394607b9 100644
--- a/csharp/src/Google.Protobuf.Conformance/Conformance.cs
+++ b/csharp/src/Google.Protobuf.Conformance/Conformance.cs
@@ -22,21 +22,21 @@ namespace Conformance {
static ConformanceReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
- "ChFjb25mb3JtYW5jZS5wcm90bxILY29uZm9ybWFuY2UijQEKEkNvbmZvcm1h",
+ "ChFjb25mb3JtYW5jZS5wcm90bxILY29uZm9ybWFuY2UiowEKEkNvbmZvcm1h",
"bmNlUmVxdWVzdBIaChBwcm90b2J1Zl9wYXlsb2FkGAEgASgMSAASFgoManNv",
"bl9wYXlsb2FkGAIgASgJSAASOAoXcmVxdWVzdGVkX291dHB1dF9mb3JtYXQY",
- "AyABKA4yFy5jb25mb3JtYW5jZS5XaXJlRm9ybWF0QgkKB3BheWxvYWQisQEK",
- "E0NvbmZvcm1hbmNlUmVzcG9uc2USFQoLcGFyc2VfZXJyb3IYASABKAlIABIZ",
- "Cg9zZXJpYWxpemVfZXJyb3IYBiABKAlIABIXCg1ydW50aW1lX2Vycm9yGAIg",
- "ASgJSAASGgoQcHJvdG9idWZfcGF5bG9hZBgDIAEoDEgAEhYKDGpzb25fcGF5",
- "bG9hZBgEIAEoCUgAEhEKB3NraXBwZWQYBSABKAlIAEIICgZyZXN1bHQqNQoK",
- "V2lyZUZvcm1hdBIPCgtVTlNQRUNJRklFRBAAEgwKCFBST1RPQlVGEAESCAoE",
- "SlNPThACQiEKH2NvbS5nb29nbGUucHJvdG9idWYuY29uZm9ybWFuY2ViBnBy",
- "b3RvMw=="));
+ "AyABKA4yFy5jb25mb3JtYW5jZS5XaXJlRm9ybWF0EhQKDG1lc3NhZ2VfdHlw",
+ "ZRgEIAEoCUIJCgdwYXlsb2FkIrEBChNDb25mb3JtYW5jZVJlc3BvbnNlEhUK",
+ "C3BhcnNlX2Vycm9yGAEgASgJSAASGQoPc2VyaWFsaXplX2Vycm9yGAYgASgJ",
+ "SAASFwoNcnVudGltZV9lcnJvchgCIAEoCUgAEhoKEHByb3RvYnVmX3BheWxv",
+ "YWQYAyABKAxIABIWCgxqc29uX3BheWxvYWQYBCABKAlIABIRCgdza2lwcGVk",
+ "GAUgASgJSABCCAoGcmVzdWx0KjUKCldpcmVGb3JtYXQSDwoLVU5TUEVDSUZJ",
+ "RUQQABIMCghQUk9UT0JVRhABEggKBEpTT04QAkIhCh9jb20uZ29vZ2xlLnBy",
+ "b3RvYnVmLmNvbmZvcm1hbmNlYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(new[] {typeof(global::Conformance.WireFormat), }, new pbr::GeneratedClrTypeInfo[] {
- new pbr::GeneratedClrTypeInfo(typeof(global::Conformance.ConformanceRequest), global::Conformance.ConformanceRequest.Parser, new[]{ "ProtobufPayload", "JsonPayload", "RequestedOutputFormat" }, new[]{ "Payload" }, null, null),
+ new pbr::GeneratedClrTypeInfo(typeof(global::Conformance.ConformanceRequest), global::Conformance.ConformanceRequest.Parser, new[]{ "ProtobufPayload", "JsonPayload", "RequestedOutputFormat", "MessageType" }, new[]{ "Payload" }, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Conformance.ConformanceResponse), global::Conformance.ConformanceResponse.Parser, new[]{ "ParseError", "SerializeError", "RuntimeError", "ProtobufPayload", "JsonPayload", "Skipped" }, new[]{ "Result" }, null, null)
}));
}
@@ -85,6 +85,7 @@ namespace Conformance {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ConformanceRequest(ConformanceRequest other) : this() {
requestedOutputFormat_ = other.requestedOutputFormat_;
+ messageType_ = other.messageType_;
switch (other.PayloadCase) {
case PayloadOneofCase.ProtobufPayload:
ProtobufPayload = other.ProtobufPayload;
@@ -137,6 +138,22 @@ namespace Conformance {
}
}
+ /// <summary>Field number for the "message_type" field.</summary>
+ public const int MessageTypeFieldNumber = 4;
+ private string messageType_ = "";
+ /// <summary>
+ /// The full name for the test message to use; for the moment, either:
+ /// protobuf_test_messages.proto3.TestAllTypesProto3 or
+ /// protobuf_test_messages.proto2.TestAllTypesProto2.
+ /// </summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public string MessageType {
+ get { return messageType_; }
+ set {
+ messageType_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
+ }
+ }
+
private object payload_;
/// <summary>Enum of possible cases for the "payload" oneof.</summary>
public enum PayloadOneofCase {
@@ -172,6 +189,7 @@ namespace Conformance {
if (ProtobufPayload != other.ProtobufPayload) return false;
if (JsonPayload != other.JsonPayload) return false;
if (RequestedOutputFormat != other.RequestedOutputFormat) return false;
+ if (MessageType != other.MessageType) return false;
if (PayloadCase != other.PayloadCase) return false;
return true;
}
@@ -182,6 +200,7 @@ namespace Conformance {
if (payloadCase_ == PayloadOneofCase.ProtobufPayload) hash ^= ProtobufPayload.GetHashCode();
if (payloadCase_ == PayloadOneofCase.JsonPayload) hash ^= JsonPayload.GetHashCode();
if (RequestedOutputFormat != 0) hash ^= RequestedOutputFormat.GetHashCode();
+ if (MessageType.Length != 0) hash ^= MessageType.GetHashCode();
hash ^= (int) payloadCase_;
return hash;
}
@@ -205,6 +224,10 @@ namespace Conformance {
output.WriteRawTag(24);
output.WriteEnum((int) RequestedOutputFormat);
}
+ if (MessageType.Length != 0) {
+ output.WriteRawTag(34);
+ output.WriteString(MessageType);
+ }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -219,6 +242,9 @@ namespace Conformance {
if (RequestedOutputFormat != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) RequestedOutputFormat);
}
+ if (MessageType.Length != 0) {
+ size += 1 + pb::CodedOutputStream.ComputeStringSize(MessageType);
+ }
return size;
}
@@ -230,6 +256,9 @@ namespace Conformance {
if (other.RequestedOutputFormat != 0) {
RequestedOutputFormat = other.RequestedOutputFormat;
}
+ if (other.MessageType.Length != 0) {
+ MessageType = other.MessageType;
+ }
switch (other.PayloadCase) {
case PayloadOneofCase.ProtobufPayload:
ProtobufPayload = other.ProtobufPayload;
@@ -261,6 +290,10 @@ namespace Conformance {
requestedOutputFormat_ = (global::Conformance.WireFormat) input.ReadEnum();
break;
}
+ case 34: {
+ MessageType = input.ReadString();
+ break;
+ }
}
}
}
diff --git a/csharp/src/Google.Protobuf.Conformance/Google.Protobuf.Conformance.csproj b/csharp/src/Google.Protobuf.Conformance/Google.Protobuf.Conformance.csproj
new file mode 100644
index 00000000..b654c0b2
--- /dev/null
+++ b/csharp/src/Google.Protobuf.Conformance/Google.Protobuf.Conformance.csproj
@@ -0,0 +1,14 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <PropertyGroup>
+ <TargetFramework>netcoreapp1.0</TargetFramework>
+ <OutputType>Exe</OutputType>
+ <IsPackable>False</IsPackable>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="..\Google.Protobuf\Google.Protobuf.csproj" />
+ <ProjectReference Include="..\Google.Protobuf.Test\Google.Protobuf.Test.csproj" />
+ </ItemGroup>
+
+</Project>
diff --git a/csharp/src/Google.Protobuf.Conformance/Google.Protobuf.Conformance.xproj b/csharp/src/Google.Protobuf.Conformance/Google.Protobuf.Conformance.xproj
deleted file mode 100644
index 99ff1465..00000000
--- a/csharp/src/Google.Protobuf.Conformance/Google.Protobuf.Conformance.xproj
+++ /dev/null
@@ -1,19 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
- <PropertyGroup>
- <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">14.0</VisualStudioVersion>
- <VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
- </PropertyGroup>
- <Import Project="$(VSToolsPath)\DotNet\Microsoft.DotNet.Props" Condition="'$(VSToolsPath)' != ''" />
- <PropertyGroup Label="Globals">
- <ProjectGuid>dddc055b-e185-4181-bab0-072f0f984569</ProjectGuid>
- <RootNamespace>Google.Protobuf.Conformance</RootNamespace>
- <BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">.\obj</BaseIntermediateOutputPath>
- <OutputPath Condition="'$(OutputPath)'=='' ">.\bin\</OutputPath>
- </PropertyGroup>
-
- <PropertyGroup>
- <SchemaVersion>2.0</SchemaVersion>
- </PropertyGroup>
- <Import Project="$(VSToolsPath)\DotNet\Microsoft.DotNet.targets" Condition="'$(VSToolsPath)' != ''" />
-</Project> \ No newline at end of file
diff --git a/csharp/src/Google.Protobuf.Conformance/Program.cs b/csharp/src/Google.Protobuf.Conformance/Program.cs
index 00ee64f8..96dc354e 100644
--- a/csharp/src/Google.Protobuf.Conformance/Program.cs
+++ b/csharp/src/Google.Protobuf.Conformance/Program.cs
@@ -48,7 +48,7 @@ namespace Google.Protobuf.Conformance
// This way we get the binary streams instead of readers/writers.
var input = new BinaryReader(Console.OpenStandardInput());
var output = new BinaryWriter(Console.OpenStandardOutput());
- var typeRegistry = TypeRegistry.FromMessages(ProtobufTestMessages.Proto3.TestAllTypes.Descriptor);
+ var typeRegistry = TypeRegistry.FromMessages(ProtobufTestMessages.Proto3.TestAllTypesProto3.Descriptor);
int count = 0;
while (RunTest(input, output, typeRegistry))
@@ -81,18 +81,31 @@ namespace Google.Protobuf.Conformance
private static ConformanceResponse PerformRequest(ConformanceRequest request, TypeRegistry typeRegistry)
{
- ProtobufTestMessages.Proto3.TestAllTypes message;
+ ProtobufTestMessages.Proto3.TestAllTypesProto3 message;
try
{
switch (request.PayloadCase)
{
case ConformanceRequest.PayloadOneofCase.JsonPayload:
var parser = new JsonParser(new JsonParser.Settings(20, typeRegistry));
- message = parser.Parse<ProtobufTestMessages.Proto3.TestAllTypes>(request.JsonPayload);
+ message = parser.Parse<ProtobufTestMessages.Proto3.TestAllTypesProto3>(request.JsonPayload);
break;
- case ConformanceRequest.PayloadOneofCase.ProtobufPayload:
- message = ProtobufTestMessages.Proto3.TestAllTypes.Parser.ParseFrom(request.ProtobufPayload);
+ case ConformanceRequest.PayloadOneofCase.ProtobufPayload:
+ {
+ if (request.MessageType.Equals("protobuf_test_messages.proto3.TestAllTypesProto3"))
+ {
+ message = ProtobufTestMessages.Proto3.TestAllTypesProto3.Parser.ParseFrom(request.ProtobufPayload);
+ }
+ else if (request.MessageType.Equals("protobuf_test_messages.proto2.TestAllTypesProto2"))
+ {
+ return new ConformanceResponse { Skipped = "CSharp doesn't support proto2" };
+ }
+ else
+ {
+ throw new Exception(" Protobuf request doesn't have specific payload type");
+ }
break;
+ }
default:
throw new Exception("Unsupported request payload: " + request.PayloadCase);
}
diff --git a/csharp/src/Google.Protobuf.Conformance/project.json b/csharp/src/Google.Protobuf.Conformance/project.json
deleted file mode 100644
index 4cf05231..00000000
--- a/csharp/src/Google.Protobuf.Conformance/project.json
+++ /dev/null
@@ -1,21 +0,0 @@
-{
- "buildOptions": {
- "debugType": "portable",
- "emitEntryPoint": true
- },
- "dependencies": {
- "Google.Protobuf": { "target": "project" },
- "Google.Protobuf.Test": { "target": "project" }
- },
- "frameworks": {
- "netcoreapp1.0": {
- "imports": [ "dnxcore50", "netcoreapp1.0", "portable-net45+win8" ],
- "dependencies": {
- "Microsoft.NETCore.App": {
- "type": "platform",
- "version": "1.0.0"
- }
- }
- }
- }
-}
diff --git a/csharp/src/Google.Protobuf.JsonDump/Google.Protobuf.JsonDump.csproj b/csharp/src/Google.Protobuf.JsonDump/Google.Protobuf.JsonDump.csproj
new file mode 100644
index 00000000..4eda641a
--- /dev/null
+++ b/csharp/src/Google.Protobuf.JsonDump/Google.Protobuf.JsonDump.csproj
@@ -0,0 +1,13 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <PropertyGroup>
+ <TargetFramework>netcoreapp1.0</TargetFramework>
+ <OutputType>Exe</OutputType>
+ <IsPackable>False</IsPackable>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="..\Google.Protobuf\Google.Protobuf.csproj" />
+ </ItemGroup>
+
+</Project>
diff --git a/csharp/src/Google.Protobuf.JsonDump/Google.Protobuf.JsonDump.xproj b/csharp/src/Google.Protobuf.JsonDump/Google.Protobuf.JsonDump.xproj
deleted file mode 100644
index 27095be5..00000000
--- a/csharp/src/Google.Protobuf.JsonDump/Google.Protobuf.JsonDump.xproj
+++ /dev/null
@@ -1,19 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
- <PropertyGroup>
- <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">14.0</VisualStudioVersion>
- <VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
- </PropertyGroup>
- <Import Project="$(VSToolsPath)\DotNet\Microsoft.DotNet.Props" Condition="'$(VSToolsPath)' != ''" />
- <PropertyGroup Label="Globals">
- <ProjectGuid>9695e08f-9829-497d-b95c-b38f28d48690</ProjectGuid>
- <RootNamespace>Google.Protobuf.JsonDump</RootNamespace>
- <BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">.\obj</BaseIntermediateOutputPath>
- <OutputPath Condition="'$(OutputPath)'=='' ">.\bin\</OutputPath>
- </PropertyGroup>
-
- <PropertyGroup>
- <SchemaVersion>2.0</SchemaVersion>
- </PropertyGroup>
- <Import Project="$(VSToolsPath)\DotNet\Microsoft.DotNet.targets" Condition="'$(VSToolsPath)' != ''" />
-</Project> \ No newline at end of file
diff --git a/csharp/src/Google.Protobuf.JsonDump/project.json b/csharp/src/Google.Protobuf.JsonDump/project.json
deleted file mode 100644
index 84b23c45..00000000
--- a/csharp/src/Google.Protobuf.JsonDump/project.json
+++ /dev/null
@@ -1,19 +0,0 @@
-{
- "buildOptions": {
- "debugType": "portable",
- "emitEntryPoint": true
- },
- "dependencies": {
- "Google.Protobuf": { "target": "project" }
- },
- "frameworks": {
- "netcoreapp1.0": {
- "dependencies": {
- "Microsoft.NETCore.App": {
- "type": "platform",
- "version": "1.0.0"
- }
- }
- }
- }
-}
diff --git a/csharp/src/Google.Protobuf.Test/ByteStringTest.cs b/csharp/src/Google.Protobuf.Test/ByteStringTest.cs
index ff2444a3..afdd491f 100644..100755
--- a/csharp/src/Google.Protobuf.Test/ByteStringTest.cs
+++ b/csharp/src/Google.Protobuf.Test/ByteStringTest.cs
@@ -33,6 +33,10 @@
using System;
using System.Text;
using NUnit.Framework;
+using System.IO;
+#if !NET35
+using System.Threading.Tasks;
+#endif
namespace Google.Protobuf
{
@@ -169,6 +173,56 @@ namespace Google.Protobuf
}
[Test]
+ public void FromStream_Seekable()
+ {
+ var stream = new MemoryStream(new byte[] { 1, 2, 3, 4, 5 });
+ // Consume the first byte, just to test that it's "from current position"
+ stream.ReadByte();
+ var actual = ByteString.FromStream(stream);
+ ByteString expected = ByteString.CopyFrom(2, 3, 4, 5);
+ Assert.AreEqual(expected, actual, $"{expected.ToBase64()} != {actual.ToBase64()}");
+ }
+
+ [Test]
+ public void FromStream_NotSeekable()
+ {
+ var stream = new MemoryStream(new byte[] { 1, 2, 3, 4, 5 });
+ // Consume the first byte, just to test that it's "from current position"
+ stream.ReadByte();
+ // Wrap the original stream in LimitedInputStream, which has CanSeek=false
+ var limitedStream = new LimitedInputStream(stream, 3);
+ var actual = ByteString.FromStream(limitedStream);
+ ByteString expected = ByteString.CopyFrom(2, 3, 4);
+ Assert.AreEqual(expected, actual, $"{expected.ToBase64()} != {actual.ToBase64()}");
+ }
+
+#if !NET35
+ [Test]
+ public async Task FromStreamAsync_Seekable()
+ {
+ var stream = new MemoryStream(new byte[] { 1, 2, 3, 4, 5 });
+ // Consume the first byte, just to test that it's "from current position"
+ stream.ReadByte();
+ var actual = await ByteString.FromStreamAsync(stream);
+ ByteString expected = ByteString.CopyFrom(2, 3, 4, 5);
+ Assert.AreEqual(expected, actual, $"{expected.ToBase64()} != {actual.ToBase64()}");
+ }
+
+ [Test]
+ public async Task FromStreamAsync_NotSeekable()
+ {
+ var stream = new MemoryStream(new byte[] { 1, 2, 3, 4, 5 });
+ // Consume the first byte, just to test that it's "from current position"
+ stream.ReadByte();
+ // Wrap the original stream in LimitedInputStream, which has CanSeek=false
+ var limitedStream = new LimitedInputStream(stream, 3);
+ var actual = await ByteString.FromStreamAsync(limitedStream);
+ ByteString expected = ByteString.CopyFrom(2, 3, 4);
+ Assert.AreEqual(expected, actual, $"{expected.ToBase64()} != {actual.ToBase64()}");
+ }
+#endif
+
+ [Test]
public void GetHashCode_Regression()
{
// We used to have an awful hash algorithm where only the last four
@@ -179,6 +233,5 @@ namespace Google.Protobuf
ByteString b2 = ByteString.CopyFrom(200, 1, 2, 3, 4);
Assert.AreNotEqual(b1.GetHashCode(), b2.GetHashCode());
}
-
}
} \ No newline at end of file
diff --git a/csharp/src/Google.Protobuf.Test/CodedInputStreamTest.cs b/csharp/src/Google.Protobuf.Test/CodedInputStreamTest.cs
index c0a9ffd1..e7c6b805 100644
--- a/csharp/src/Google.Protobuf.Test/CodedInputStreamTest.cs
+++ b/csharp/src/Google.Protobuf.Test/CodedInputStreamTest.cs
@@ -284,6 +284,20 @@ namespace Google.Protobuf
Assert.Throws<InvalidProtocolBufferException>(() => input.ReadBytes());
}
+ // Representations of a tag for field 0 with various wire types
+ [Test]
+ [TestCase(0)]
+ [TestCase(1)]
+ [TestCase(2)]
+ [TestCase(3)]
+ [TestCase(4)]
+ [TestCase(5)]
+ public void ReadTag_ZeroFieldRejected(byte tag)
+ {
+ CodedInputStream cis = new CodedInputStream(new byte[] { tag });
+ Assert.Throws<InvalidProtocolBufferException>(() => cis.ReadTag());
+ }
+
internal static TestRecursiveMessage MakeRecursiveMessage(int depth)
{
if (depth == 0)
@@ -403,7 +417,7 @@ namespace Google.Protobuf
output.Flush();
ms.Position = 0;
- CodedInputStream input = new CodedInputStream(ms, new byte[ms.Length / 2], 0, 0);
+ CodedInputStream input = new CodedInputStream(ms, new byte[ms.Length / 2], 0, 0, false);
uint tag = input.ReadTag();
Assert.AreEqual(1, WireFormat.GetTagFieldNumber(tag));
@@ -594,5 +608,12 @@ namespace Google.Protobuf
}
Assert.IsTrue(memoryStream.CanRead); // We left the stream open
}
+
+ [Test]
+ public void Dispose_FromByteArray()
+ {
+ var stream = new CodedInputStream(new byte[10]);
+ stream.Dispose();
+ }
}
} \ No newline at end of file
diff --git a/csharp/src/Google.Protobuf.Test/CodedOutputStreamTest.cs b/csharp/src/Google.Protobuf.Test/CodedOutputStreamTest.cs
index 48bf6d60..98cabd55 100644
--- a/csharp/src/Google.Protobuf.Test/CodedOutputStreamTest.cs
+++ b/csharp/src/Google.Protobuf.Test/CodedOutputStreamTest.cs
@@ -334,7 +334,7 @@ namespace Google.Protobuf
}
// Now test Input stream:
{
- CodedInputStream cin = new CodedInputStream(new MemoryStream(bytes), new byte[50], 0, 0);
+ CodedInputStream cin = new CodedInputStream(new MemoryStream(bytes), new byte[50], 0, 0, false);
Assert.AreEqual(0, cin.Position);
// Field 1:
uint tag = cin.ReadTag();
@@ -415,5 +415,12 @@ namespace Google.Protobuf
Assert.AreEqual(1, memoryStream.Position); // Flushed data from CodedOutputStream to MemoryStream
Assert.IsTrue(memoryStream.CanWrite); // We left the stream open
}
+
+ [Test]
+ public void Dispose_FromByteArray()
+ {
+ var stream = new CodedOutputStream(new byte[10]);
+ stream.Dispose();
+ }
}
} \ No newline at end of file
diff --git a/csharp/src/Google.Protobuf.Test/Collections/MapFieldTest.cs b/csharp/src/Google.Protobuf.Test/Collections/MapFieldTest.cs
index 9c845907..68b4de45 100644
--- a/csharp/src/Google.Protobuf.Test/Collections/MapFieldTest.cs
+++ b/csharp/src/Google.Protobuf.Test/Collections/MapFieldTest.cs
@@ -499,6 +499,14 @@ namespace Google.Protobuf.Collections
}
[Test]
+ public void KeysCopyTo()
+ {
+ var map = new MapField<string, string> { { "foo", "bar" }, { "x", "y" } };
+ var keys = map.Keys.ToArray(); // Uses CopyTo internally
+ CollectionAssert.AreEquivalent(new[] { "foo", "x" }, keys);
+ }
+
+ [Test]
public void ValuesContains()
{
var map = new MapField<string, string> { { "foo", "bar" }, { "x", "y" } };
@@ -511,6 +519,14 @@ namespace Google.Protobuf.Collections
}
[Test]
+ public void ValuesCopyTo()
+ {
+ var map = new MapField<string, string> { { "foo", "bar" }, { "x", "y" } };
+ var values = map.Values.ToArray(); // Uses CopyTo internally
+ CollectionAssert.AreEquivalent(new[] { "bar", "y" }, values);
+ }
+
+ [Test]
public void ToString_StringToString()
{
var map = new MapField<string, string> { { "foo", "bar" }, { "x", "y" } };
@@ -524,6 +540,22 @@ namespace Google.Protobuf.Collections
Assert.Throws<ArgumentException>(() => map.ToString());
}
+#if !NET35
+ [Test]
+ public void IDictionaryKeys_Equals_IReadOnlyDictionaryKeys()
+ {
+ var map = new MapField<string, string> { { "foo", "bar" }, { "x", "y" } };
+ CollectionAssert.AreEquivalent(((IDictionary<string, string>)map).Keys, ((IReadOnlyDictionary<string, string>)map).Keys);
+ }
+
+ [Test]
+ public void IDictionaryValues_Equals_IReadOnlyDictionaryValues()
+ {
+ var map = new MapField<string, string> { { "foo", "bar" }, { "x", "y" } };
+ CollectionAssert.AreEquivalent(((IDictionary<string, string>)map).Values, ((IReadOnlyDictionary<string, string>)map).Values);
+ }
+#endif
+
private static KeyValuePair<TKey, TValue> NewKeyValuePair<TKey, TValue>(TKey key, TValue value)
{
return new KeyValuePair<TKey, TValue>(key, value);
diff --git a/csharp/src/Google.Protobuf.Test/Compatibility/StreamExtensionsTest.cs b/csharp/src/Google.Protobuf.Test/Compatibility/StreamExtensionsTest.cs
new file mode 100755
index 00000000..48c0725f
--- /dev/null
+++ b/csharp/src/Google.Protobuf.Test/Compatibility/StreamExtensionsTest.cs
@@ -0,0 +1,67 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2015 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+#if NET35
+using System;
+using System.IO;
+using NUnit.Framework;
+using Google.Protobuf.Compatibility;
+
+namespace Google.Protobuf.Test.Compatibility
+{
+ public class StreamExtensionsTest
+ {
+ [Test]
+ public void CopyToNullArgument()
+ {
+ var memoryStream = new MemoryStream();
+ Assert.Throws<ArgumentNullException>(() => memoryStream.CopyTo(null));
+ }
+
+ [Test]
+ public void CopyToTest()
+ {
+ byte[] bytesToStream = new byte[] { 0x31, 0x08, 0xFF, 0x00 };
+ Stream source = new MemoryStream(bytesToStream);
+ Stream destination = new MemoryStream((int)source.Length);
+ source.CopyTo(destination);
+ destination.Seek(0, SeekOrigin.Begin);
+
+ Assert.AreEqual(0x31, destination.ReadByte());
+ Assert.AreEqual(0x08, destination.ReadByte());
+ Assert.AreEqual(0xFF, destination.ReadByte());
+ Assert.AreEqual(0x00, destination.ReadByte());
+ Assert.AreEqual(-1, destination.ReadByte());
+ }
+ }
+}
+#endif
diff --git a/csharp/src/Google.Protobuf.Test/Compatibility/TypeExtensionsTest.cs b/csharp/src/Google.Protobuf.Test/Compatibility/TypeExtensionsTest.cs
index f430b06b..abbe3c95 100644..100755
--- a/csharp/src/Google.Protobuf.Test/Compatibility/TypeExtensionsTest.cs
+++ b/csharp/src/Google.Protobuf.Test/Compatibility/TypeExtensionsTest.cs
@@ -34,7 +34,7 @@ using System;
using System.Collections.Generic;
using System.Reflection;
-#if !DOTNET35
+#if !NET35
namespace Google.Protobuf.Compatibility
{
public class TypeExtensionsTest
diff --git a/csharp/src/Google.Protobuf.Test/FieldCodecTest.cs b/csharp/src/Google.Protobuf.Test/FieldCodecTest.cs
index 0e2bad59..77641163 100644..100755
--- a/csharp/src/Google.Protobuf.Test/FieldCodecTest.cs
+++ b/csharp/src/Google.Protobuf.Test/FieldCodecTest.cs
@@ -158,7 +158,9 @@ namespace Google.Protobuf
{
// WriteTagAndValue ignores default values
var stream = new MemoryStream();
- var codedOutput = new CodedOutputStream(stream);
+ CodedOutputStream codedOutput;
+#if !NET35
+ codedOutput = new CodedOutputStream(stream);
codec.WriteTagAndValue(codedOutput, codec.DefaultValue);
codedOutput.Flush();
Assert.AreEqual(0, stream.Position);
@@ -167,6 +169,7 @@ namespace Google.Protobuf
{
Assert.AreEqual(default(T), codec.DefaultValue);
}
+#endif
// The plain ValueWriter/ValueReader delegates don't.
if (codec.DefaultValue != null) // This part isn't appropriate for message types.
diff --git a/csharp/src/Google.Protobuf.Test/Google.Protobuf.Test.csproj b/csharp/src/Google.Protobuf.Test/Google.Protobuf.Test.csproj
new file mode 100644
index 00000000..06d07b9f
--- /dev/null
+++ b/csharp/src/Google.Protobuf.Test/Google.Protobuf.Test.csproj
@@ -0,0 +1,30 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <PropertyGroup>
+ <OutputType>Exe</OutputType>
+ <TargetFrameworks>net451;netcoreapp1.0</TargetFrameworks>
+ <AssemblyOriginatorKeyFile>../../keys/Google.Protobuf.snk</AssemblyOriginatorKeyFile>
+ <SignAssembly>true</SignAssembly>
+ <PublicSign Condition=" '$(OS)' != 'Windows_NT' ">true</PublicSign>
+ <IsPackable>False</IsPackable>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="..\Google.Protobuf\Google.Protobuf.csproj" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <PackageReference Include="NUnit" Version="3.6.1" />
+ <PackageReference Include="NUnitLite" Version="3.6.1" />
+ </ItemGroup>
+
+ <!--
+ - Override target frameworks on non-Windows to just .NET Core
+ - Doing this conditionally in the initial PropertyGroup confuses
+ - Visual Studio.
+ -->
+ <PropertyGroup Condition="'$(OS)' != 'Windows_NT'">
+ <TargetFrameworks>netcoreapp1.0</TargetFrameworks>
+ </PropertyGroup>
+
+</Project>
diff --git a/csharp/src/Google.Protobuf.Test/Google.Protobuf.Test.xproj b/csharp/src/Google.Protobuf.Test/Google.Protobuf.Test.xproj
deleted file mode 100644
index 6370441e..00000000
--- a/csharp/src/Google.Protobuf.Test/Google.Protobuf.Test.xproj
+++ /dev/null
@@ -1,21 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
- <PropertyGroup>
- <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">14.0</VisualStudioVersion>
- <VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
- </PropertyGroup>
- <Import Project="$(VSToolsPath)\DotNet\Microsoft.DotNet.Props" Condition="'$(VSToolsPath)' != ''" />
- <PropertyGroup Label="Globals">
- <ProjectGuid>580eb013-d3c7-4578-b845-015f4a3b0591</ProjectGuid>
- <RootNamespace>Google.Protobuf.Test</RootNamespace>
- <BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">.\obj</BaseIntermediateOutputPath>
- <OutputPath Condition="'$(OutputPath)'=='' ">.\bin\</OutputPath>
- </PropertyGroup>
- <PropertyGroup>
- <SchemaVersion>2.0</SchemaVersion>
- </PropertyGroup>
- <ItemGroup>
- <Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" />
- </ItemGroup>
- <Import Project="$(VSToolsPath)\DotNet\Microsoft.DotNet.targets" Condition="'$(VSToolsPath)' != ''" />
-</Project> \ No newline at end of file
diff --git a/csharp/src/Google.Protobuf.Test/IssuesTest.cs b/csharp/src/Google.Protobuf.Test/IssuesTest.cs
index a38d6b08..2caf80a9 100644
--- a/csharp/src/Google.Protobuf.Test/IssuesTest.cs
+++ b/csharp/src/Google.Protobuf.Test/IssuesTest.cs
@@ -33,7 +33,7 @@
using Google.Protobuf.Reflection;
using UnitTest.Issues.TestProtos;
using NUnit.Framework;
-
+using static UnitTest.Issues.TestProtos.OneofMerging.Types;
namespace Google.Protobuf
{
@@ -78,5 +78,17 @@ namespace Google.Protobuf
Assert.AreEqual("{ \"name\": \"test\", \"desc\": \"test2\", \"exid\": \"test3\" }",
JsonFormatter.Default.Format(message));
}
+
+ [Test]
+ public void OneofMerging()
+ {
+ var message1 = new OneofMerging { Nested = new Nested { X = 10 } };
+ var message2 = new OneofMerging { Nested = new Nested { Y = 20 } };
+ var expected = new OneofMerging { Nested = new Nested { X = 10, Y = 20 } };
+
+ var merged = message1.Clone();
+ merged.MergeFrom(message2);
+ Assert.AreEqual(expected, merged);
+ }
}
}
diff --git a/csharp/src/Google.Protobuf.Test/JsonFormatterTest.cs b/csharp/src/Google.Protobuf.Test/JsonFormatterTest.cs
index 302f8143..1c7a8cdf 100644
--- a/csharp/src/Google.Protobuf.Test/JsonFormatterTest.cs
+++ b/csharp/src/Google.Protobuf.Test/JsonFormatterTest.cs
@@ -52,7 +52,7 @@ namespace Google.Protobuf
[Test]
public void DefaultValues_WhenOmitted()
{
- var formatter = new JsonFormatter(new JsonFormatter.Settings(formatDefaultValues: false));
+ var formatter = JsonFormatter.Default;
AssertJson("{ }", formatter.Format(new ForeignMessage()));
AssertJson("{ }", formatter.Format(new TestAllTypes()));
@@ -62,11 +62,40 @@ namespace Google.Protobuf
[Test]
public void DefaultValues_WhenIncluded()
{
- var formatter = new JsonFormatter(new JsonFormatter.Settings(formatDefaultValues: true));
+ var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true));
AssertJson("{ 'c': 0 }", formatter.Format(new ForeignMessage()));
}
[Test]
+ public void EnumAllowAlias()
+ {
+ var message = new TestEnumAllowAlias
+ {
+ Value = TestEnumWithDupValue.Foo2,
+ };
+ var actualText = JsonFormatter.Default.Format(message);
+ var expectedText = "{ 'value': 'FOO1' }";
+ AssertJson(expectedText, actualText);
+ }
+
+ [Test]
+ public void EnumAsInt()
+ {
+ var message = new TestAllTypes
+ {
+ SingleForeignEnum = ForeignEnum.ForeignBar,
+ RepeatedForeignEnum = { ForeignEnum.ForeignBaz, (ForeignEnum) 100, ForeignEnum.ForeignFoo }
+ };
+ var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatEnumsAsIntegers(true));
+ var actualText = formatter.Format(message);
+ var expectedText = "{ " +
+ "'singleForeignEnum': 5, " +
+ "'repeatedForeignEnum': [ 6, 100, 4 ]" +
+ " }";
+ AssertJson(expectedText, actualText);
+ }
+
+ [Test]
public void AllSingleFields()
{
var message = new TestAllTypes
@@ -254,9 +283,9 @@ namespace Google.Protobuf
}
// We should get the same result both with and without "format default values".
- var formatter = new JsonFormatter(new JsonFormatter.Settings(false));
+ var formatter = JsonFormatter.Default;
AssertJson(expectedJson, formatter.Format(message));
- formatter = new JsonFormatter(new JsonFormatter.Settings(true));
+ formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true));
AssertJson(expectedJson, formatter.Format(message));
}
@@ -288,7 +317,7 @@ namespace Google.Protobuf
{
// The actual JSON here is very large because there are lots of fields. Just test a couple of them.
var message = new TestWellKnownTypes { Int32Field = 10 };
- var formatter = new JsonFormatter(new JsonFormatter.Settings(true));
+ var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true));
var actualJson = formatter.Format(message);
Assert.IsTrue(actualJson.Contains("\"int64Field\": null"));
Assert.IsFalse(actualJson.Contains("\"int32Field\": null"));
@@ -297,7 +326,7 @@ namespace Google.Protobuf
[Test]
public void OutputIsInNumericFieldOrder_NoDefaults()
{
- var formatter = new JsonFormatter(new JsonFormatter.Settings(false));
+ var formatter = JsonFormatter.Default;
var message = new TestJsonFieldOrdering { PlainString = "p1", PlainInt32 = 2 };
AssertJson("{ 'plainString': 'p1', 'plainInt32': 2 }", formatter.Format(message));
message = new TestJsonFieldOrdering { O1Int32 = 5, O2String = "o2", PlainInt32 = 10, PlainString = "plain" };
@@ -309,7 +338,7 @@ namespace Google.Protobuf
[Test]
public void OutputIsInNumericFieldOrder_WithDefaults()
{
- var formatter = new JsonFormatter(new JsonFormatter.Settings(true));
+ var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true));
var message = new TestJsonFieldOrdering();
AssertJson("{ 'plainString': '', 'plainInt32': 0 }", formatter.Format(message));
message = new TestJsonFieldOrdering { O1Int32 = 5, O2String = "o2", PlainInt32 = 10, PlainString = "plain" };
@@ -473,7 +502,7 @@ namespace Google.Protobuf
[Test]
public void AnyWellKnownType()
{
- var formatter = new JsonFormatter(new JsonFormatter.Settings(false, TypeRegistry.FromMessages(Timestamp.Descriptor)));
+ var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithTypeRegistry(TypeRegistry.FromMessages(Timestamp.Descriptor)));
var timestamp = new DateTime(1673, 6, 19, 12, 34, 56, DateTimeKind.Utc).ToTimestamp();
var any = Any.Pack(timestamp);
AssertJson("{ '@type': 'type.googleapis.com/google.protobuf.Timestamp', 'value': '1673-06-19T12:34:56Z' }", formatter.Format(any));
@@ -482,32 +511,32 @@ namespace Google.Protobuf
[Test]
public void AnyMessageType()
{
- var formatter = new JsonFormatter(new JsonFormatter.Settings(false, TypeRegistry.FromMessages(TestAllTypes.Descriptor)));
+ var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithTypeRegistry(TypeRegistry.FromMessages(TestAllTypes.Descriptor)));
var message = new TestAllTypes { SingleInt32 = 10, SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 20 } };
var any = Any.Pack(message);
- AssertJson("{ '@type': 'type.googleapis.com/protobuf_unittest.TestAllTypes', 'singleInt32': 10, 'singleNestedMessage': { 'bb': 20 } }", formatter.Format(any));
+ AssertJson("{ '@type': 'type.googleapis.com/protobuf_unittest3.TestAllTypes', 'singleInt32': 10, 'singleNestedMessage': { 'bb': 20 } }", formatter.Format(any));
}
[Test]
public void AnyMessageType_CustomPrefix()
{
- var formatter = new JsonFormatter(new JsonFormatter.Settings(false, TypeRegistry.FromMessages(TestAllTypes.Descriptor)));
+ var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithTypeRegistry(TypeRegistry.FromMessages(TestAllTypes.Descriptor)));
var message = new TestAllTypes { SingleInt32 = 10 };
var any = Any.Pack(message, "foo.bar/baz");
- AssertJson("{ '@type': 'foo.bar/baz/protobuf_unittest.TestAllTypes', 'singleInt32': 10 }", formatter.Format(any));
+ AssertJson("{ '@type': 'foo.bar/baz/protobuf_unittest3.TestAllTypes', 'singleInt32': 10 }", formatter.Format(any));
}
[Test]
public void AnyNested()
{
var registry = TypeRegistry.FromMessages(TestWellKnownTypes.Descriptor, TestAllTypes.Descriptor);
- var formatter = new JsonFormatter(new JsonFormatter.Settings(false, registry));
+ var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithTypeRegistry(registry));
// Nest an Any as the value of an Any.
var doubleNestedMessage = new TestAllTypes { SingleInt32 = 20 };
var nestedMessage = Any.Pack(doubleNestedMessage);
var message = new TestWellKnownTypes { AnyField = Any.Pack(nestedMessage) };
- AssertJson("{ 'anyField': { '@type': 'type.googleapis.com/google.protobuf.Any', 'value': { '@type': 'type.googleapis.com/protobuf_unittest.TestAllTypes', 'singleInt32': 20 } } }",
+ AssertJson("{ 'anyField': { '@type': 'type.googleapis.com/google.protobuf.Any', 'value': { '@type': 'type.googleapis.com/protobuf_unittest3.TestAllTypes', 'singleInt32': 20 } } }",
formatter.Format(message));
}
diff --git a/csharp/src/Google.Protobuf.Test/JsonParserTest.cs b/csharp/src/Google.Protobuf.Test/JsonParserTest.cs
index f595455a..329ae9be 100644
--- a/csharp/src/Google.Protobuf.Test/JsonParserTest.cs
+++ b/csharp/src/Google.Protobuf.Test/JsonParserTest.cs
@@ -809,7 +809,7 @@ namespace Google.Protobuf
var json = formatter.Format(original); // This is tested in JsonFormatterTest
var parser = new JsonParser(new JsonParser.Settings(10, registry));
Assert.AreEqual(original, parser.Parse<Any>(json));
- string valueFirstJson = "{ \"singleInt32\": 10, \"singleNestedMessage\": { \"bb\": 20 }, \"@type\": \"type.googleapis.com/protobuf_unittest.TestAllTypes\" }";
+ string valueFirstJson = "{ \"singleInt32\": 10, \"singleNestedMessage\": { \"bb\": 20 }, \"@type\": \"type.googleapis.com/protobuf_unittest3.TestAllTypes\" }";
Assert.AreEqual(original, parser.Parse<Any>(valueFirstJson));
}
@@ -820,7 +820,7 @@ namespace Google.Protobuf
var message = new TestAllTypes { SingleInt32 = 10 };
var original = Any.Pack(message, "custom.prefix/middle-part");
var parser = new JsonParser(new JsonParser.Settings(10, registry));
- string json = "{ \"@type\": \"custom.prefix/middle-part/protobuf_unittest.TestAllTypes\", \"singleInt32\": 10 }";
+ string json = "{ \"@type\": \"custom.prefix/middle-part/protobuf_unittest3.TestAllTypes\", \"singleInt32\": 10 }";
Assert.AreEqual(original, parser.Parse<Any>(json));
}
@@ -926,6 +926,27 @@ namespace Google.Protobuf
Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json));
}
+ [Test]
+ public void UnknownField_NotIgnored()
+ {
+ string json = "{ \"unknownField\": 10, \"singleString\": \"x\" }";
+ Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json));
+ }
+
+ [Test]
+ [TestCase("5")]
+ [TestCase("\"text\"")]
+ [TestCase("[0, 1, 2]")]
+ [TestCase("{ \"a\": { \"b\": 10 } }")]
+ public void UnknownField_Ignored(string value)
+ {
+ var parser = new JsonParser(JsonParser.Settings.Default.WithIgnoreUnknownFields(true));
+ string json = "{ \"unknownField\": " + value + ", \"singleString\": \"x\" }";
+ var actual = parser.Parse<TestAllTypes>(json);
+ var expected = new TestAllTypes { SingleString = "x" };
+ Assert.AreEqual(expected, actual);
+ }
+
/// <summary>
/// Various tests use strings which have quotes round them for parsing or as the result
/// of formatting, but without those quotes being specified in the tests (for the sake of readability).
diff --git a/csharp/src/Google.Protobuf.Test/JsonTokenizerTest.cs b/csharp/src/Google.Protobuf.Test/JsonTokenizerTest.cs
index 527ab336..33d35036 100644
--- a/csharp/src/Google.Protobuf.Test/JsonTokenizerTest.cs
+++ b/csharp/src/Google.Protobuf.Test/JsonTokenizerTest.cs
@@ -349,6 +349,22 @@ namespace Google.Protobuf
Assert.AreEqual(JsonToken.EndDocument, tokenizer.Next());
Assert.Throws<InvalidOperationException>(() => tokenizer.Next());
}
+
+ [Test]
+ [TestCase("{ 'skip': 0, 'next': 1")]
+ [TestCase("{ 'skip': [0, 1, 2], 'next': 1")]
+ [TestCase("{ 'skip': 'x', 'next': 1")]
+ [TestCase("{ 'skip': ['x', 'y'], 'next': 1")]
+ [TestCase("{ 'skip': {'a': 0}, 'next': 1")]
+ [TestCase("{ 'skip': {'a': [0, {'b':[]}]}, 'next': 1")]
+ public void SkipValue(string json)
+ {
+ var tokenizer = JsonTokenizer.FromTextReader(new StringReader(json.Replace('\'', '"')));
+ Assert.AreEqual(JsonToken.StartObject, tokenizer.Next());
+ Assert.AreEqual("skip", tokenizer.Next().StringValue);
+ tokenizer.SkipValue();
+ Assert.AreEqual("next", tokenizer.Next().StringValue);
+ }
/// <summary>
/// Asserts that the specified JSON is tokenized into the given sequence of tokens.
diff --git a/csharp/src/Google.Protobuf.Test/Program.cs b/csharp/src/Google.Protobuf.Test/Program.cs
new file mode 100755
index 00000000..954c02b5
--- /dev/null
+++ b/csharp/src/Google.Protobuf.Test/Program.cs
@@ -0,0 +1,48 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2017 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+using NUnitLite;
+using System.Reflection;
+
+namespace Google.Protobuf.Test
+{
+ class Program
+ {
+ public static int Main(string[] args)
+ {
+ #if NET35
+ return new AutoRun(typeof(Program).Assembly).Execute(args);
+ #else
+ return new AutoRun(typeof(Program).GetTypeInfo().Assembly).Execute(args);
+ #endif
+ }
+ }
+} \ No newline at end of file
diff --git a/csharp/src/Google.Protobuf.Test/Reflection/CustomOptionsTest.cs b/csharp/src/Google.Protobuf.Test/Reflection/CustomOptionsTest.cs
new file mode 100644
index 00000000..68b4d6af
--- /dev/null
+++ b/csharp/src/Google.Protobuf.Test/Reflection/CustomOptionsTest.cs
@@ -0,0 +1,271 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2017 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+using Google.Protobuf.Reflection;
+using Google.Protobuf.WellKnownTypes;
+using NUnit.Framework;
+using System.IO;
+using System.Linq;
+using UnitTest.Issues.TestProtos;
+using static Google.Protobuf.WireFormat;
+using static UnitTest.Issues.TestProtos.ComplexOptionType2.Types;
+using static UnitTest.Issues.TestProtos.DummyMessageContainingEnum.Types;
+using static Google.Protobuf.Test.Reflection.CustomOptionNumber;
+
+namespace Google.Protobuf.Test.Reflection
+{
+ // Internal enum to allow us to use "using static" for convenience.
+ // These are the options defined in unittest_custom_options_proto3.proto
+ internal enum CustomOptionNumber
+ {
+ FileOpt1 = 7736974,
+ MessageOpt1 = 7739036,
+ FieldOpt1 = 7740936,
+ OneofOpt1 = 7740111,
+ EnumOpt1 = 7753576,
+ EnumValueOpt1 = 1560678,
+ ServiceOpt1 = 7887650,
+ MethodOpt1 = 7890860,
+
+ // All message options...
+ BoolOpt = 7706090,
+ Int32Opt = 7705709,
+ Int64Opt = 7705542,
+ UInt32Opt = 7704880,
+ UInt64Opt = 7702367,
+ SInt32Opt = 7701568,
+ SInt64Opt = 7700863,
+ Fixed32Opt = 7700307,
+ Fixed64Opt = 7700194,
+ SFixed32Opt = 7698645,
+ SFixed64Opt = 7685475,
+ FloatOpt = 7675390,
+ DoubleOpt = 7673293,
+ StringOpt = 7673285,
+ BytesOpt = 7673238,
+ EnumOpt = 7673233,
+ MessageTypeOpt = 7665967,
+
+ // Miscellaneous
+ ComplexOpt4 = 7633546,
+ ComplexOpt1 = 7646756,
+ ComplexOpt2 = 7636949,
+ ComplexOpt3 = 7636463,
+
+ // Aggregates
+ AggregateFileOpt = 15478479,
+ AggregateMsgOpt = 15480088,
+ AggregateFieldOpt = 15481374,
+ AggregateEnumOpt = 15483218,
+ AggregateEnumValueOpt = 15486921,
+ AggregateServiceOpt = 15497145,
+ AggregateMethodOpt = 15512713,
+ }
+
+ /// <summary>
+ /// The majority of the testing here is done via parsed descriptors. That's simpler to
+ /// achieve (and more important) than constructing a CodedInputStream manually.
+ /// </summary>
+ public class CustomOptionsTest
+ {
+ delegate bool OptionFetcher<T>(int field, out T value);
+
+ [Test]
+ public void EmptyOptionsIsShared()
+ {
+ var structOptions = Struct.Descriptor.CustomOptions;
+ var timestampOptions = Struct.Descriptor.CustomOptions;
+ Assert.AreSame(structOptions, timestampOptions);
+ }
+
+ [Test]
+ public void SimpleIntegerTest()
+ {
+ var stream = new MemoryStream();
+ var output = new CodedOutputStream(stream);
+ output.WriteTag(MakeTag(1, WireType.Varint));
+ output.WriteInt32(1234567);
+ output.Flush();
+ stream.Position = 0;
+ var input = new CodedInputStream(stream);
+ input.ReadTag();
+
+ var options = CustomOptions.Empty;
+ options = options.ReadOrSkipUnknownField(input);
+
+ int intValue;
+ Assert.True(options.TryGetInt32(1, out intValue));
+ Assert.AreEqual(1234567, intValue);
+
+ string stringValue;
+ // No ByteString stored values
+ Assert.False(options.TryGetString(1, out stringValue));
+ // Nothing stored for field 2
+ Assert.False(options.TryGetInt32(2, out intValue));
+ }
+
+ [Test]
+ public void SimpleStringTest()
+ {
+ var stream = new MemoryStream();
+ var output = new CodedOutputStream(stream);
+ output.WriteTag(MakeTag(1, WireType.LengthDelimited));
+ output.WriteString("value");
+ output.Flush();
+ stream.Position = 0;
+ var input = new CodedInputStream(stream);
+ input.ReadTag();
+
+ var options = CustomOptions.Empty;
+ options = options.ReadOrSkipUnknownField(input);
+
+ string stringValue;
+ Assert.True(options.TryGetString(1, out stringValue));
+ Assert.AreEqual("value", stringValue);
+
+ int intValue;
+ // No numeric stored values
+ Assert.False(options.TryGetInt32(1, out intValue));
+ // Nothing stored for field 2
+ Assert.False(options.TryGetString(2, out stringValue));
+ }
+
+ [Test]
+ public void ScalarOptions()
+ {
+ var options = CustomOptionOtherValues.Descriptor.CustomOptions;
+ AssertOption(-100, options.TryGetInt32, Int32Opt);
+ AssertOption(12.3456789f, options.TryGetFloat, FloatOpt);
+ AssertOption(1.234567890123456789d, options.TryGetDouble, DoubleOpt);
+ AssertOption("Hello, \"World\"", options.TryGetString, StringOpt);
+ AssertOption(ByteString.CopyFromUtf8("Hello\0World"), options.TryGetBytes, BytesOpt);
+ AssertOption((int) TestEnumType.TestOptionEnumType2, options.TryGetInt32, EnumOpt);
+ }
+
+ [Test]
+ public void MessageOptions()
+ {
+ var options = VariousComplexOptions.Descriptor.CustomOptions;
+ AssertOption(new ComplexOptionType1 { Foo = 42, Foo4 = { 99, 88 } }, options.TryGetMessage, ComplexOpt1);
+ AssertOption(new ComplexOptionType2
+ {
+ Baz = 987, Bar = new ComplexOptionType1 { Foo = 743 },
+ Fred = new ComplexOptionType4 { Waldo = 321 },
+ Barney = { new ComplexOptionType4 { Waldo = 101 }, new ComplexOptionType4 { Waldo = 212 } }
+ },
+ options.TryGetMessage, ComplexOpt2);
+ AssertOption(new ComplexOptionType3 { Qux = 9 }, options.TryGetMessage, ComplexOpt3);
+ }
+
+ [Test]
+ public void OptionLocations()
+ {
+ var fileOptions = UnittestCustomOptionsProto3Reflection.Descriptor.CustomOptions;
+ AssertOption(9876543210UL, fileOptions.TryGetUInt64, FileOpt1);
+
+ var messageOptions = TestMessageWithCustomOptions.Descriptor.CustomOptions;
+ AssertOption(-56, messageOptions.TryGetInt32, MessageOpt1);
+
+ var fieldOptions = TestMessageWithCustomOptions.Descriptor.Fields["field1"] .CustomOptions;
+ AssertOption(8765432109UL, fieldOptions.TryGetFixed64, FieldOpt1);
+
+ var oneofOptions = TestMessageWithCustomOptions.Descriptor.Oneofs[0].CustomOptions;
+ AssertOption(-99, oneofOptions.TryGetInt32, OneofOpt1);
+
+ var enumOptions = TestMessageWithCustomOptions.Descriptor.EnumTypes[0].CustomOptions;
+ AssertOption(-789, enumOptions.TryGetSFixed32, EnumOpt1);
+
+ var enumValueOptions = TestMessageWithCustomOptions.Descriptor.EnumTypes[0].FindValueByNumber(2).CustomOptions;
+ AssertOption(123, enumValueOptions.TryGetInt32, EnumValueOpt1);
+
+ var service = UnittestCustomOptionsProto3Reflection.Descriptor.Services
+ .Single(s => s.Name == "TestServiceWithCustomOptions");
+ var serviceOptions = service.CustomOptions;
+ AssertOption(-9876543210, serviceOptions.TryGetSInt64, ServiceOpt1);
+
+ var methodOptions = service.Methods[0].CustomOptions;
+ AssertOption((int) UnitTest.Issues.TestProtos.MethodOpt1.Val2, methodOptions.TryGetInt32, CustomOptionNumber.MethodOpt1);
+ }
+
+ [Test]
+ public void MinValues()
+ {
+ var options = CustomOptionMinIntegerValues.Descriptor.CustomOptions;
+ AssertOption(false, options.TryGetBool, BoolOpt);
+ AssertOption(int.MinValue, options.TryGetInt32, Int32Opt);
+ AssertOption(long.MinValue, options.TryGetInt64, Int64Opt);
+ AssertOption(uint.MinValue, options.TryGetUInt32, UInt32Opt);
+ AssertOption(ulong.MinValue, options.TryGetUInt64, UInt64Opt);
+ AssertOption(int.MinValue, options.TryGetSInt32, SInt32Opt);
+ AssertOption(long.MinValue, options.TryGetSInt64, SInt64Opt);
+ AssertOption(uint.MinValue, options.TryGetUInt32, Fixed32Opt);
+ AssertOption(ulong.MinValue, options.TryGetUInt64, Fixed64Opt);
+ AssertOption(int.MinValue, options.TryGetInt32, SFixed32Opt);
+ AssertOption(long.MinValue, options.TryGetInt64, SFixed64Opt);
+ }
+
+ [Test]
+ public void MaxValues()
+ {
+ var options = CustomOptionMaxIntegerValues.Descriptor.CustomOptions;
+ AssertOption(true, options.TryGetBool, BoolOpt);
+ AssertOption(int.MaxValue, options.TryGetInt32, Int32Opt);
+ AssertOption(long.MaxValue, options.TryGetInt64, Int64Opt);
+ AssertOption(uint.MaxValue, options.TryGetUInt32, UInt32Opt);
+ AssertOption(ulong.MaxValue, options.TryGetUInt64, UInt64Opt);
+ AssertOption(int.MaxValue, options.TryGetSInt32, SInt32Opt);
+ AssertOption(long.MaxValue, options.TryGetSInt64, SInt64Opt);
+ AssertOption(uint.MaxValue, options.TryGetFixed32, Fixed32Opt);
+ AssertOption(ulong.MaxValue, options.TryGetFixed64, Fixed64Opt);
+ AssertOption(int.MaxValue, options.TryGetSFixed32, SFixed32Opt);
+ AssertOption(long.MaxValue, options.TryGetSFixed64, SFixed64Opt);
+ }
+
+ [Test]
+ public void AggregateOptions()
+ {
+ // Just two examples
+ var messageOptions = AggregateMessage.Descriptor.CustomOptions;
+ AssertOption(new Aggregate { I = 101, S = "MessageAnnotation" }, messageOptions.TryGetMessage, AggregateMsgOpt);
+
+ var fieldOptions = AggregateMessage.Descriptor.Fields["fieldname"].CustomOptions;
+ AssertOption(new Aggregate { S = "FieldAnnotation" }, fieldOptions.TryGetMessage, AggregateFieldOpt);
+ }
+
+ private void AssertOption<T>(T expected, OptionFetcher<T> fetcher, CustomOptionNumber field)
+ {
+ T actual;
+ Assert.IsTrue(fetcher((int) field, out actual));
+ Assert.AreEqual(expected, actual);
+ }
+ }
+}
diff --git a/csharp/src/Google.Protobuf.Test/Reflection/DescriptorsTest.cs b/csharp/src/Google.Protobuf.Test/Reflection/DescriptorsTest.cs
index 52d5a676..29a376e0 100644
--- a/csharp/src/Google.Protobuf.Test/Reflection/DescriptorsTest.cs
+++ b/csharp/src/Google.Protobuf.Test/Reflection/DescriptorsTest.cs
@@ -48,13 +48,13 @@ namespace Google.Protobuf.Reflection
{
FileDescriptor file = UnittestProto3Reflection.Descriptor;
- Assert.AreEqual("google/protobuf/unittest_proto3.proto", file.Name);
- Assert.AreEqual("protobuf_unittest", file.Package);
+ Assert.AreEqual("unittest_proto3.proto", file.Name);
+ Assert.AreEqual("protobuf_unittest3", file.Package);
Assert.AreEqual("UnittestProto", file.Proto.Options.JavaOuterClassname);
- Assert.AreEqual("google/protobuf/unittest_proto3.proto", file.Proto.Name);
+ Assert.AreEqual("unittest_proto3.proto", file.Proto.Name);
- // unittest.proto doesn't have any public imports, but unittest_import.proto does.
+ // unittest_proto3.proto doesn't have any public imports, but unittest_import_proto3.proto does.
Assert.AreEqual(0, file.PublicDependencies.Count);
Assert.AreEqual(1, UnittestImportProto3Reflection.Descriptor.PublicDependencies.Count);
Assert.AreEqual(UnittestImportPublicProto3Reflection.Descriptor, UnittestImportProto3Reflection.Descriptor.PublicDependencies[0]);
@@ -68,7 +68,7 @@ namespace Google.Protobuf.Reflection
Assert.AreEqual(messageType, file.MessageTypes[0]);
Assert.AreEqual(messageType, file.FindTypeByName<MessageDescriptor>("TestAllTypes"));
Assert.Null(file.FindTypeByName<MessageDescriptor>("NoSuchType"));
- Assert.Null(file.FindTypeByName<MessageDescriptor>("protobuf_unittest.TestAllTypes"));
+ Assert.Null(file.FindTypeByName<MessageDescriptor>("protobuf_unittest3.TestAllTypes"));
for (int i = 0; i < file.MessageTypes.Count; i++)
{
Assert.AreEqual(i, file.MessageTypes[i].Index);
@@ -76,7 +76,7 @@ namespace Google.Protobuf.Reflection
Assert.AreEqual(file.EnumTypes[0], file.FindTypeByName<EnumDescriptor>("ForeignEnum"));
Assert.Null(file.FindTypeByName<EnumDescriptor>("NoSuchType"));
- Assert.Null(file.FindTypeByName<EnumDescriptor>("protobuf_unittest.ForeignEnum"));
+ Assert.Null(file.FindTypeByName<EnumDescriptor>("protobuf_unittest3.ForeignEnum"));
Assert.AreEqual(1, UnittestImportProto3Reflection.Descriptor.EnumTypes.Count);
Assert.AreEqual("ImportEnum", UnittestImportProto3Reflection.Descriptor.EnumTypes[0].Name);
for (int i = 0; i < file.EnumTypes.Count; i++)
@@ -88,13 +88,23 @@ namespace Google.Protobuf.Reflection
}
[Test]
+ public void FileDescriptor_NonRootPath()
+ {
+ // unittest_proto3.proto used to be in google/protobuf. Now it's in the C#-specific location,
+ // let's test something that's still in a directory.
+ FileDescriptor file = UnittestWellKnownTypesReflection.Descriptor;
+ Assert.AreEqual("google/protobuf/unittest_well_known_types.proto", file.Name);
+ Assert.AreEqual("protobuf_unittest", file.Package);
+ }
+
+ [Test]
public void MessageDescriptor()
{
MessageDescriptor messageType = TestAllTypes.Descriptor;
MessageDescriptor nestedType = TestAllTypes.Types.NestedMessage.Descriptor;
Assert.AreEqual("TestAllTypes", messageType.Name);
- Assert.AreEqual("protobuf_unittest.TestAllTypes", messageType.FullName);
+ Assert.AreEqual("protobuf_unittest3.TestAllTypes", messageType.FullName);
Assert.AreEqual(UnittestProto3Reflection.Descriptor, messageType.File);
Assert.IsNull(messageType.ContainingType);
Assert.IsNull(messageType.Proto.Options);
@@ -102,7 +112,7 @@ namespace Google.Protobuf.Reflection
Assert.AreEqual("TestAllTypes", messageType.Name);
Assert.AreEqual("NestedMessage", nestedType.Name);
- Assert.AreEqual("protobuf_unittest.TestAllTypes.NestedMessage", nestedType.FullName);
+ Assert.AreEqual("protobuf_unittest3.TestAllTypes.NestedMessage", nestedType.FullName);
Assert.AreEqual(UnittestProto3Reflection.Descriptor, nestedType.File);
Assert.AreEqual(messageType, nestedType.ContainingType);
@@ -143,7 +153,7 @@ namespace Google.Protobuf.Reflection
FieldDescriptor messageField = messageType.FindDescriptor<FieldDescriptor>("single_foreign_message");
Assert.AreEqual("single_int32", primitiveField.Name);
- Assert.AreEqual("protobuf_unittest.TestAllTypes.single_int32",
+ Assert.AreEqual("protobuf_unittest3.TestAllTypes.single_int32",
primitiveField.FullName);
Assert.AreEqual(1, primitiveField.FieldNumber);
Assert.AreEqual(messageType, primitiveField.ContainingType);
@@ -180,13 +190,13 @@ namespace Google.Protobuf.Reflection
EnumDescriptor nestedType = TestAllTypes.Descriptor.FindDescriptor<EnumDescriptor>("NestedEnum");
Assert.AreEqual("ForeignEnum", enumType.Name);
- Assert.AreEqual("protobuf_unittest.ForeignEnum", enumType.FullName);
+ Assert.AreEqual("protobuf_unittest3.ForeignEnum", enumType.FullName);
Assert.AreEqual(UnittestProto3Reflection.Descriptor, enumType.File);
Assert.Null(enumType.ContainingType);
Assert.Null(enumType.Proto.Options);
Assert.AreEqual("NestedEnum", nestedType.Name);
- Assert.AreEqual("protobuf_unittest.TestAllTypes.NestedEnum",
+ Assert.AreEqual("protobuf_unittest3.TestAllTypes.NestedEnum",
nestedType.FullName);
Assert.AreEqual(UnittestProto3Reflection.Descriptor, nestedType.File);
Assert.AreEqual(TestAllTypes.Descriptor, nestedType.ContainingType);
@@ -209,7 +219,7 @@ namespace Google.Protobuf.Reflection
{
OneofDescriptor descriptor = TestAllTypes.Descriptor.FindDescriptor<OneofDescriptor>("oneof_field");
Assert.AreEqual("oneof_field", descriptor.Name);
- Assert.AreEqual("protobuf_unittest.TestAllTypes.oneof_field", descriptor.FullName);
+ Assert.AreEqual("protobuf_unittest3.TestAllTypes.oneof_field", descriptor.FullName);
var expectedFields = new[] {
TestAllTypes.OneofBytesFieldNumber,
diff --git a/csharp/src/Google.Protobuf.Test/TestProtos/MapUnittestProto3.cs b/csharp/src/Google.Protobuf.Test/TestProtos/MapUnittestProto3.cs
index 9c0518a3..bb946046 100644
--- a/csharp/src/Google.Protobuf.Test/TestProtos/MapUnittestProto3.cs
+++ b/csharp/src/Google.Protobuf.Test/TestProtos/MapUnittestProto3.cs
@@ -1,5 +1,5 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
-// source: google/protobuf/map_unittest_proto3.proto
+// source: map_unittest_proto3.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
@@ -9,11 +9,11 @@ using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Protobuf.TestProtos {
- /// <summary>Holder for reflection information generated from google/protobuf/map_unittest_proto3.proto</summary>
+ /// <summary>Holder for reflection information generated from map_unittest_proto3.proto</summary>
public static partial class MapUnittestProto3Reflection {
#region Descriptor
- /// <summary>File descriptor for google/protobuf/map_unittest_proto3.proto</summary>
+ /// <summary>File descriptor for map_unittest_proto3.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
@@ -22,130 +22,130 @@ namespace Google.Protobuf.TestProtos {
static MapUnittestProto3Reflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
- "Cilnb29nbGUvcHJvdG9idWYvbWFwX3VuaXR0ZXN0X3Byb3RvMy5wcm90bxIR",
- "cHJvdG9idWZfdW5pdHRlc3QaJWdvb2dsZS9wcm90b2J1Zi91bml0dGVzdF9w",
- "cm90bzMucHJvdG8ilhIKB1Rlc3RNYXASRgoPbWFwX2ludDMyX2ludDMyGAEg",
- "AygLMi0ucHJvdG9idWZfdW5pdHRlc3QuVGVzdE1hcC5NYXBJbnQzMkludDMy",
- "RW50cnkSRgoPbWFwX2ludDY0X2ludDY0GAIgAygLMi0ucHJvdG9idWZfdW5p",
- "dHRlc3QuVGVzdE1hcC5NYXBJbnQ2NEludDY0RW50cnkSSgoRbWFwX3VpbnQz",
- "Ml91aW50MzIYAyADKAsyLy5wcm90b2J1Zl91bml0dGVzdC5UZXN0TWFwLk1h",
- "cFVpbnQzMlVpbnQzMkVudHJ5EkoKEW1hcF91aW50NjRfdWludDY0GAQgAygL",
- "Mi8ucHJvdG9idWZfdW5pdHRlc3QuVGVzdE1hcC5NYXBVaW50NjRVaW50NjRF",
- "bnRyeRJKChFtYXBfc2ludDMyX3NpbnQzMhgFIAMoCzIvLnByb3RvYnVmX3Vu",
- "aXR0ZXN0LlRlc3RNYXAuTWFwU2ludDMyU2ludDMyRW50cnkSSgoRbWFwX3Np",
- "bnQ2NF9zaW50NjQYBiADKAsyLy5wcm90b2J1Zl91bml0dGVzdC5UZXN0TWFw",
- "Lk1hcFNpbnQ2NFNpbnQ2NEVudHJ5Ek4KE21hcF9maXhlZDMyX2ZpeGVkMzIY",
- "ByADKAsyMS5wcm90b2J1Zl91bml0dGVzdC5UZXN0TWFwLk1hcEZpeGVkMzJG",
- "aXhlZDMyRW50cnkSTgoTbWFwX2ZpeGVkNjRfZml4ZWQ2NBgIIAMoCzIxLnBy",
- "b3RvYnVmX3VuaXR0ZXN0LlRlc3RNYXAuTWFwRml4ZWQ2NEZpeGVkNjRFbnRy",
- "eRJSChVtYXBfc2ZpeGVkMzJfc2ZpeGVkMzIYCSADKAsyMy5wcm90b2J1Zl91",
- "bml0dGVzdC5UZXN0TWFwLk1hcFNmaXhlZDMyU2ZpeGVkMzJFbnRyeRJSChVt",
- "YXBfc2ZpeGVkNjRfc2ZpeGVkNjQYCiADKAsyMy5wcm90b2J1Zl91bml0dGVz",
- "dC5UZXN0TWFwLk1hcFNmaXhlZDY0U2ZpeGVkNjRFbnRyeRJGCg9tYXBfaW50",
- "MzJfZmxvYXQYCyADKAsyLS5wcm90b2J1Zl91bml0dGVzdC5UZXN0TWFwLk1h",
- "cEludDMyRmxvYXRFbnRyeRJIChBtYXBfaW50MzJfZG91YmxlGAwgAygLMi4u",
- "cHJvdG9idWZfdW5pdHRlc3QuVGVzdE1hcC5NYXBJbnQzMkRvdWJsZUVudHJ5",
- "EkIKDW1hcF9ib29sX2Jvb2wYDSADKAsyKy5wcm90b2J1Zl91bml0dGVzdC5U",
- "ZXN0TWFwLk1hcEJvb2xCb29sRW50cnkSSgoRbWFwX3N0cmluZ19zdHJpbmcY",
- "DiADKAsyLy5wcm90b2J1Zl91bml0dGVzdC5UZXN0TWFwLk1hcFN0cmluZ1N0",
- "cmluZ0VudHJ5EkYKD21hcF9pbnQzMl9ieXRlcxgPIAMoCzItLnByb3RvYnVm",
- "X3VuaXR0ZXN0LlRlc3RNYXAuTWFwSW50MzJCeXRlc0VudHJ5EkQKDm1hcF9p",
- "bnQzMl9lbnVtGBAgAygLMiwucHJvdG9idWZfdW5pdHRlc3QuVGVzdE1hcC5N",
- "YXBJbnQzMkVudW1FbnRyeRJZChltYXBfaW50MzJfZm9yZWlnbl9tZXNzYWdl",
- "GBEgAygLMjYucHJvdG9idWZfdW5pdHRlc3QuVGVzdE1hcC5NYXBJbnQzMkZv",
- "cmVpZ25NZXNzYWdlRW50cnkaNAoSTWFwSW50MzJJbnQzMkVudHJ5EgsKA2tl",
- "eRgBIAEoBRINCgV2YWx1ZRgCIAEoBToCOAEaNAoSTWFwSW50NjRJbnQ2NEVu",
- "dHJ5EgsKA2tleRgBIAEoAxINCgV2YWx1ZRgCIAEoAzoCOAEaNgoUTWFwVWlu",
- "dDMyVWludDMyRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4",
- "ARo2ChRNYXBVaW50NjRVaW50NjRFbnRyeRILCgNrZXkYASABKAQSDQoFdmFs",
- "dWUYAiABKAQ6AjgBGjYKFE1hcFNpbnQzMlNpbnQzMkVudHJ5EgsKA2tleRgB",
- "IAEoERINCgV2YWx1ZRgCIAEoEToCOAEaNgoUTWFwU2ludDY0U2ludDY0RW50",
- "cnkSCwoDa2V5GAEgASgSEg0KBXZhbHVlGAIgASgSOgI4ARo4ChZNYXBGaXhl",
- "ZDMyRml4ZWQzMkVudHJ5EgsKA2tleRgBIAEoBxINCgV2YWx1ZRgCIAEoBzoC",
- "OAEaOAoWTWFwRml4ZWQ2NEZpeGVkNjRFbnRyeRILCgNrZXkYASABKAYSDQoF",
- "dmFsdWUYAiABKAY6AjgBGjoKGE1hcFNmaXhlZDMyU2ZpeGVkMzJFbnRyeRIL",
- "CgNrZXkYASABKA8SDQoFdmFsdWUYAiABKA86AjgBGjoKGE1hcFNmaXhlZDY0",
- "U2ZpeGVkNjRFbnRyeRILCgNrZXkYASABKBASDQoFdmFsdWUYAiABKBA6AjgB",
- "GjQKEk1hcEludDMyRmxvYXRFbnRyeRILCgNrZXkYASABKAUSDQoFdmFsdWUY",
- "AiABKAI6AjgBGjUKE01hcEludDMyRG91YmxlRW50cnkSCwoDa2V5GAEgASgF",
- "Eg0KBXZhbHVlGAIgASgBOgI4ARoyChBNYXBCb29sQm9vbEVudHJ5EgsKA2tl",
- "eRgBIAEoCBINCgV2YWx1ZRgCIAEoCDoCOAEaNgoUTWFwU3RyaW5nU3RyaW5n",
- "RW50cnkSCwoDa2V5GAEgASgJEg0KBXZhbHVlGAIgASgJOgI4ARo0ChJNYXBJ",
- "bnQzMkJ5dGVzRW50cnkSCwoDa2V5GAEgASgFEg0KBXZhbHVlGAIgASgMOgI4",
- "ARpPChFNYXBJbnQzMkVudW1FbnRyeRILCgNrZXkYASABKAUSKQoFdmFsdWUY",
- "AiABKA4yGi5wcm90b2J1Zl91bml0dGVzdC5NYXBFbnVtOgI4ARpgChtNYXBJ",
- "bnQzMkZvcmVpZ25NZXNzYWdlRW50cnkSCwoDa2V5GAEgASgFEjAKBXZhbHVl",
- "GAIgASgLMiEucHJvdG9idWZfdW5pdHRlc3QuRm9yZWlnbk1lc3NhZ2U6AjgB",
- "IkEKEVRlc3RNYXBTdWJtZXNzYWdlEiwKCHRlc3RfbWFwGAEgASgLMhoucHJv",
- "dG9idWZfdW5pdHRlc3QuVGVzdE1hcCK8AQoOVGVzdE1lc3NhZ2VNYXASUQoR",
- "bWFwX2ludDMyX21lc3NhZ2UYASADKAsyNi5wcm90b2J1Zl91bml0dGVzdC5U",
- "ZXN0TWVzc2FnZU1hcC5NYXBJbnQzMk1lc3NhZ2VFbnRyeRpXChRNYXBJbnQz",
- "Mk1lc3NhZ2VFbnRyeRILCgNrZXkYASABKAUSLgoFdmFsdWUYAiABKAsyHy5w",
- "cm90b2J1Zl91bml0dGVzdC5UZXN0QWxsVHlwZXM6AjgBIuMBCg9UZXN0U2Ft",
- "ZVR5cGVNYXASOgoEbWFwMRgBIAMoCzIsLnByb3RvYnVmX3VuaXR0ZXN0LlRl",
- "c3RTYW1lVHlwZU1hcC5NYXAxRW50cnkSOgoEbWFwMhgCIAMoCzIsLnByb3Rv",
- "YnVmX3VuaXR0ZXN0LlRlc3RTYW1lVHlwZU1hcC5NYXAyRW50cnkaKwoJTWFw",
- "MUVudHJ5EgsKA2tleRgBIAEoBRINCgV2YWx1ZRgCIAEoBToCOAEaKwoJTWFw",
- "MkVudHJ5EgsKA2tleRgBIAEoBRINCgV2YWx1ZRgCIAEoBToCOAEi5BAKDFRl",
- "c3RBcmVuYU1hcBJLCg9tYXBfaW50MzJfaW50MzIYASADKAsyMi5wcm90b2J1",
- "Zl91bml0dGVzdC5UZXN0QXJlbmFNYXAuTWFwSW50MzJJbnQzMkVudHJ5EksK",
- "D21hcF9pbnQ2NF9pbnQ2NBgCIAMoCzIyLnByb3RvYnVmX3VuaXR0ZXN0LlRl",
- "c3RBcmVuYU1hcC5NYXBJbnQ2NEludDY0RW50cnkSTwoRbWFwX3VpbnQzMl91",
- "aW50MzIYAyADKAsyNC5wcm90b2J1Zl91bml0dGVzdC5UZXN0QXJlbmFNYXAu",
- "TWFwVWludDMyVWludDMyRW50cnkSTwoRbWFwX3VpbnQ2NF91aW50NjQYBCAD",
- "KAsyNC5wcm90b2J1Zl91bml0dGVzdC5UZXN0QXJlbmFNYXAuTWFwVWludDY0",
- "VWludDY0RW50cnkSTwoRbWFwX3NpbnQzMl9zaW50MzIYBSADKAsyNC5wcm90",
- "b2J1Zl91bml0dGVzdC5UZXN0QXJlbmFNYXAuTWFwU2ludDMyU2ludDMyRW50",
- "cnkSTwoRbWFwX3NpbnQ2NF9zaW50NjQYBiADKAsyNC5wcm90b2J1Zl91bml0",
- "dGVzdC5UZXN0QXJlbmFNYXAuTWFwU2ludDY0U2ludDY0RW50cnkSUwoTbWFw",
- "X2ZpeGVkMzJfZml4ZWQzMhgHIAMoCzI2LnByb3RvYnVmX3VuaXR0ZXN0LlRl",
- "c3RBcmVuYU1hcC5NYXBGaXhlZDMyRml4ZWQzMkVudHJ5ElMKE21hcF9maXhl",
- "ZDY0X2ZpeGVkNjQYCCADKAsyNi5wcm90b2J1Zl91bml0dGVzdC5UZXN0QXJl",
- "bmFNYXAuTWFwRml4ZWQ2NEZpeGVkNjRFbnRyeRJXChVtYXBfc2ZpeGVkMzJf",
- "c2ZpeGVkMzIYCSADKAsyOC5wcm90b2J1Zl91bml0dGVzdC5UZXN0QXJlbmFN",
- "YXAuTWFwU2ZpeGVkMzJTZml4ZWQzMkVudHJ5ElcKFW1hcF9zZml4ZWQ2NF9z",
- "Zml4ZWQ2NBgKIAMoCzI4LnByb3RvYnVmX3VuaXR0ZXN0LlRlc3RBcmVuYU1h",
- "cC5NYXBTZml4ZWQ2NFNmaXhlZDY0RW50cnkSSwoPbWFwX2ludDMyX2Zsb2F0",
- "GAsgAygLMjIucHJvdG9idWZfdW5pdHRlc3QuVGVzdEFyZW5hTWFwLk1hcElu",
- "dDMyRmxvYXRFbnRyeRJNChBtYXBfaW50MzJfZG91YmxlGAwgAygLMjMucHJv",
- "dG9idWZfdW5pdHRlc3QuVGVzdEFyZW5hTWFwLk1hcEludDMyRG91YmxlRW50",
- "cnkSRwoNbWFwX2Jvb2xfYm9vbBgNIAMoCzIwLnByb3RvYnVmX3VuaXR0ZXN0",
- "LlRlc3RBcmVuYU1hcC5NYXBCb29sQm9vbEVudHJ5EkkKDm1hcF9pbnQzMl9l",
- "bnVtGA4gAygLMjEucHJvdG9idWZfdW5pdHRlc3QuVGVzdEFyZW5hTWFwLk1h",
- "cEludDMyRW51bUVudHJ5El4KGW1hcF9pbnQzMl9mb3JlaWduX21lc3NhZ2UY",
- "DyADKAsyOy5wcm90b2J1Zl91bml0dGVzdC5UZXN0QXJlbmFNYXAuTWFwSW50",
- "MzJGb3JlaWduTWVzc2FnZUVudHJ5GjQKEk1hcEludDMySW50MzJFbnRyeRIL",
- "CgNrZXkYASABKAUSDQoFdmFsdWUYAiABKAU6AjgBGjQKEk1hcEludDY0SW50",
- "NjRFbnRyeRILCgNrZXkYASABKAMSDQoFdmFsdWUYAiABKAM6AjgBGjYKFE1h",
- "cFVpbnQzMlVpbnQzMkVudHJ5EgsKA2tleRgBIAEoDRINCgV2YWx1ZRgCIAEo",
- "DToCOAEaNgoUTWFwVWludDY0VWludDY0RW50cnkSCwoDa2V5GAEgASgEEg0K",
- "BXZhbHVlGAIgASgEOgI4ARo2ChRNYXBTaW50MzJTaW50MzJFbnRyeRILCgNr",
- "ZXkYASABKBESDQoFdmFsdWUYAiABKBE6AjgBGjYKFE1hcFNpbnQ2NFNpbnQ2",
- "NEVudHJ5EgsKA2tleRgBIAEoEhINCgV2YWx1ZRgCIAEoEjoCOAEaOAoWTWFw",
- "Rml4ZWQzMkZpeGVkMzJFbnRyeRILCgNrZXkYASABKAcSDQoFdmFsdWUYAiAB",
- "KAc6AjgBGjgKFk1hcEZpeGVkNjRGaXhlZDY0RW50cnkSCwoDa2V5GAEgASgG",
- "Eg0KBXZhbHVlGAIgASgGOgI4ARo6ChhNYXBTZml4ZWQzMlNmaXhlZDMyRW50",
- "cnkSCwoDa2V5GAEgASgPEg0KBXZhbHVlGAIgASgPOgI4ARo6ChhNYXBTZml4",
- "ZWQ2NFNmaXhlZDY0RW50cnkSCwoDa2V5GAEgASgQEg0KBXZhbHVlGAIgASgQ",
- "OgI4ARo0ChJNYXBJbnQzMkZsb2F0RW50cnkSCwoDa2V5GAEgASgFEg0KBXZh",
- "bHVlGAIgASgCOgI4ARo1ChNNYXBJbnQzMkRvdWJsZUVudHJ5EgsKA2tleRgB",
- "IAEoBRINCgV2YWx1ZRgCIAEoAToCOAEaMgoQTWFwQm9vbEJvb2xFbnRyeRIL",
- "CgNrZXkYASABKAgSDQoFdmFsdWUYAiABKAg6AjgBGk8KEU1hcEludDMyRW51",
- "bUVudHJ5EgsKA2tleRgBIAEoBRIpCgV2YWx1ZRgCIAEoDjIaLnByb3RvYnVm",
- "X3VuaXR0ZXN0Lk1hcEVudW06AjgBGmAKG01hcEludDMyRm9yZWlnbk1lc3Nh",
- "Z2VFbnRyeRILCgNrZXkYASABKAUSMAoFdmFsdWUYAiABKAsyIS5wcm90b2J1",
- "Zl91bml0dGVzdC5Gb3JlaWduTWVzc2FnZToCOAEi5AEKH01lc3NhZ2VDb250",
- "YWluaW5nRW51bUNhbGxlZFR5cGUSSgoEdHlwZRgBIAMoCzI8LnByb3RvYnVm",
- "X3VuaXR0ZXN0Lk1lc3NhZ2VDb250YWluaW5nRW51bUNhbGxlZFR5cGUuVHlw",
- "ZUVudHJ5Gl8KCVR5cGVFbnRyeRILCgNrZXkYASABKAUSQQoFdmFsdWUYAiAB",
- "KAsyMi5wcm90b2J1Zl91bml0dGVzdC5NZXNzYWdlQ29udGFpbmluZ0VudW1D",
- "YWxsZWRUeXBlOgI4ASIUCgRUeXBlEgwKCFRZUEVfRk9PEAAinQEKH01lc3Nh",
- "Z2VDb250YWluaW5nTWFwQ2FsbGVkRW50cnkSTAoFZW50cnkYASADKAsyPS5w",
- "cm90b2J1Zl91bml0dGVzdC5NZXNzYWdlQ29udGFpbmluZ01hcENhbGxlZEVu",
- "dHJ5LkVudHJ5RW50cnkaLAoKRW50cnlFbnRyeRILCgNrZXkYASABKAUSDQoF",
- "dmFsdWUYAiABKAU6AjgBKj8KB01hcEVudW0SEAoMTUFQX0VOVU1fRk9PEAAS",
- "EAoMTUFQX0VOVU1fQkFSEAESEAoMTUFQX0VOVU1fQkFaEAJCIPgBAaoCGkdv",
- "b2dsZS5Qcm90b2J1Zi5UZXN0UHJvdG9zYgZwcm90bzM="));
+ "ChltYXBfdW5pdHRlc3RfcHJvdG8zLnByb3RvEhJwcm90b2J1Zl91bml0dGVz",
+ "dDMaFXVuaXR0ZXN0X3Byb3RvMy5wcm90byKpEgoHVGVzdE1hcBJHCg9tYXBf",
+ "aW50MzJfaW50MzIYASADKAsyLi5wcm90b2J1Zl91bml0dGVzdDMuVGVzdE1h",
+ "cC5NYXBJbnQzMkludDMyRW50cnkSRwoPbWFwX2ludDY0X2ludDY0GAIgAygL",
+ "Mi4ucHJvdG9idWZfdW5pdHRlc3QzLlRlc3RNYXAuTWFwSW50NjRJbnQ2NEVu",
+ "dHJ5EksKEW1hcF91aW50MzJfdWludDMyGAMgAygLMjAucHJvdG9idWZfdW5p",
+ "dHRlc3QzLlRlc3RNYXAuTWFwVWludDMyVWludDMyRW50cnkSSwoRbWFwX3Vp",
+ "bnQ2NF91aW50NjQYBCADKAsyMC5wcm90b2J1Zl91bml0dGVzdDMuVGVzdE1h",
+ "cC5NYXBVaW50NjRVaW50NjRFbnRyeRJLChFtYXBfc2ludDMyX3NpbnQzMhgF",
+ "IAMoCzIwLnByb3RvYnVmX3VuaXR0ZXN0My5UZXN0TWFwLk1hcFNpbnQzMlNp",
+ "bnQzMkVudHJ5EksKEW1hcF9zaW50NjRfc2ludDY0GAYgAygLMjAucHJvdG9i",
+ "dWZfdW5pdHRlc3QzLlRlc3RNYXAuTWFwU2ludDY0U2ludDY0RW50cnkSTwoT",
+ "bWFwX2ZpeGVkMzJfZml4ZWQzMhgHIAMoCzIyLnByb3RvYnVmX3VuaXR0ZXN0",
+ "My5UZXN0TWFwLk1hcEZpeGVkMzJGaXhlZDMyRW50cnkSTwoTbWFwX2ZpeGVk",
+ "NjRfZml4ZWQ2NBgIIAMoCzIyLnByb3RvYnVmX3VuaXR0ZXN0My5UZXN0TWFw",
+ "Lk1hcEZpeGVkNjRGaXhlZDY0RW50cnkSUwoVbWFwX3NmaXhlZDMyX3NmaXhl",
+ "ZDMyGAkgAygLMjQucHJvdG9idWZfdW5pdHRlc3QzLlRlc3RNYXAuTWFwU2Zp",
+ "eGVkMzJTZml4ZWQzMkVudHJ5ElMKFW1hcF9zZml4ZWQ2NF9zZml4ZWQ2NBgK",
+ "IAMoCzI0LnByb3RvYnVmX3VuaXR0ZXN0My5UZXN0TWFwLk1hcFNmaXhlZDY0",
+ "U2ZpeGVkNjRFbnRyeRJHCg9tYXBfaW50MzJfZmxvYXQYCyADKAsyLi5wcm90",
+ "b2J1Zl91bml0dGVzdDMuVGVzdE1hcC5NYXBJbnQzMkZsb2F0RW50cnkSSQoQ",
+ "bWFwX2ludDMyX2RvdWJsZRgMIAMoCzIvLnByb3RvYnVmX3VuaXR0ZXN0My5U",
+ "ZXN0TWFwLk1hcEludDMyRG91YmxlRW50cnkSQwoNbWFwX2Jvb2xfYm9vbBgN",
+ "IAMoCzIsLnByb3RvYnVmX3VuaXR0ZXN0My5UZXN0TWFwLk1hcEJvb2xCb29s",
+ "RW50cnkSSwoRbWFwX3N0cmluZ19zdHJpbmcYDiADKAsyMC5wcm90b2J1Zl91",
+ "bml0dGVzdDMuVGVzdE1hcC5NYXBTdHJpbmdTdHJpbmdFbnRyeRJHCg9tYXBf",
+ "aW50MzJfYnl0ZXMYDyADKAsyLi5wcm90b2J1Zl91bml0dGVzdDMuVGVzdE1h",
+ "cC5NYXBJbnQzMkJ5dGVzRW50cnkSRQoObWFwX2ludDMyX2VudW0YECADKAsy",
+ "LS5wcm90b2J1Zl91bml0dGVzdDMuVGVzdE1hcC5NYXBJbnQzMkVudW1FbnRy",
+ "eRJaChltYXBfaW50MzJfZm9yZWlnbl9tZXNzYWdlGBEgAygLMjcucHJvdG9i",
+ "dWZfdW5pdHRlc3QzLlRlc3RNYXAuTWFwSW50MzJGb3JlaWduTWVzc2FnZUVu",
+ "dHJ5GjQKEk1hcEludDMySW50MzJFbnRyeRILCgNrZXkYASABKAUSDQoFdmFs",
+ "dWUYAiABKAU6AjgBGjQKEk1hcEludDY0SW50NjRFbnRyeRILCgNrZXkYASAB",
+ "KAMSDQoFdmFsdWUYAiABKAM6AjgBGjYKFE1hcFVpbnQzMlVpbnQzMkVudHJ5",
+ "EgsKA2tleRgBIAEoDRINCgV2YWx1ZRgCIAEoDToCOAEaNgoUTWFwVWludDY0",
+ "VWludDY0RW50cnkSCwoDa2V5GAEgASgEEg0KBXZhbHVlGAIgASgEOgI4ARo2",
+ "ChRNYXBTaW50MzJTaW50MzJFbnRyeRILCgNrZXkYASABKBESDQoFdmFsdWUY",
+ "AiABKBE6AjgBGjYKFE1hcFNpbnQ2NFNpbnQ2NEVudHJ5EgsKA2tleRgBIAEo",
+ "EhINCgV2YWx1ZRgCIAEoEjoCOAEaOAoWTWFwRml4ZWQzMkZpeGVkMzJFbnRy",
+ "eRILCgNrZXkYASABKAcSDQoFdmFsdWUYAiABKAc6AjgBGjgKFk1hcEZpeGVk",
+ "NjRGaXhlZDY0RW50cnkSCwoDa2V5GAEgASgGEg0KBXZhbHVlGAIgASgGOgI4",
+ "ARo6ChhNYXBTZml4ZWQzMlNmaXhlZDMyRW50cnkSCwoDa2V5GAEgASgPEg0K",
+ "BXZhbHVlGAIgASgPOgI4ARo6ChhNYXBTZml4ZWQ2NFNmaXhlZDY0RW50cnkS",
+ "CwoDa2V5GAEgASgQEg0KBXZhbHVlGAIgASgQOgI4ARo0ChJNYXBJbnQzMkZs",
+ "b2F0RW50cnkSCwoDa2V5GAEgASgFEg0KBXZhbHVlGAIgASgCOgI4ARo1ChNN",
+ "YXBJbnQzMkRvdWJsZUVudHJ5EgsKA2tleRgBIAEoBRINCgV2YWx1ZRgCIAEo",
+ "AToCOAEaMgoQTWFwQm9vbEJvb2xFbnRyeRILCgNrZXkYASABKAgSDQoFdmFs",
+ "dWUYAiABKAg6AjgBGjYKFE1hcFN0cmluZ1N0cmluZ0VudHJ5EgsKA2tleRgB",
+ "IAEoCRINCgV2YWx1ZRgCIAEoCToCOAEaNAoSTWFwSW50MzJCeXRlc0VudHJ5",
+ "EgsKA2tleRgBIAEoBRINCgV2YWx1ZRgCIAEoDDoCOAEaUAoRTWFwSW50MzJF",
+ "bnVtRW50cnkSCwoDa2V5GAEgASgFEioKBXZhbHVlGAIgASgOMhsucHJvdG9i",
+ "dWZfdW5pdHRlc3QzLk1hcEVudW06AjgBGmEKG01hcEludDMyRm9yZWlnbk1l",
+ "c3NhZ2VFbnRyeRILCgNrZXkYASABKAUSMQoFdmFsdWUYAiABKAsyIi5wcm90",
+ "b2J1Zl91bml0dGVzdDMuRm9yZWlnbk1lc3NhZ2U6AjgBIkIKEVRlc3RNYXBT",
+ "dWJtZXNzYWdlEi0KCHRlc3RfbWFwGAEgASgLMhsucHJvdG9idWZfdW5pdHRl",
+ "c3QzLlRlc3RNYXAivgEKDlRlc3RNZXNzYWdlTWFwElIKEW1hcF9pbnQzMl9t",
+ "ZXNzYWdlGAEgAygLMjcucHJvdG9idWZfdW5pdHRlc3QzLlRlc3RNZXNzYWdl",
+ "TWFwLk1hcEludDMyTWVzc2FnZUVudHJ5GlgKFE1hcEludDMyTWVzc2FnZUVu",
+ "dHJ5EgsKA2tleRgBIAEoBRIvCgV2YWx1ZRgCIAEoCzIgLnByb3RvYnVmX3Vu",
+ "aXR0ZXN0My5UZXN0QWxsVHlwZXM6AjgBIuUBCg9UZXN0U2FtZVR5cGVNYXAS",
+ "OwoEbWFwMRgBIAMoCzItLnByb3RvYnVmX3VuaXR0ZXN0My5UZXN0U2FtZVR5",
+ "cGVNYXAuTWFwMUVudHJ5EjsKBG1hcDIYAiADKAsyLS5wcm90b2J1Zl91bml0",
+ "dGVzdDMuVGVzdFNhbWVUeXBlTWFwLk1hcDJFbnRyeRorCglNYXAxRW50cnkS",
+ "CwoDa2V5GAEgASgFEg0KBXZhbHVlGAIgASgFOgI4ARorCglNYXAyRW50cnkS",
+ "CwoDa2V5GAEgASgFEg0KBXZhbHVlGAIgASgFOgI4ASL1EAoMVGVzdEFyZW5h",
+ "TWFwEkwKD21hcF9pbnQzMl9pbnQzMhgBIAMoCzIzLnByb3RvYnVmX3VuaXR0",
+ "ZXN0My5UZXN0QXJlbmFNYXAuTWFwSW50MzJJbnQzMkVudHJ5EkwKD21hcF9p",
+ "bnQ2NF9pbnQ2NBgCIAMoCzIzLnByb3RvYnVmX3VuaXR0ZXN0My5UZXN0QXJl",
+ "bmFNYXAuTWFwSW50NjRJbnQ2NEVudHJ5ElAKEW1hcF91aW50MzJfdWludDMy",
+ "GAMgAygLMjUucHJvdG9idWZfdW5pdHRlc3QzLlRlc3RBcmVuYU1hcC5NYXBV",
+ "aW50MzJVaW50MzJFbnRyeRJQChFtYXBfdWludDY0X3VpbnQ2NBgEIAMoCzI1",
+ "LnByb3RvYnVmX3VuaXR0ZXN0My5UZXN0QXJlbmFNYXAuTWFwVWludDY0VWlu",
+ "dDY0RW50cnkSUAoRbWFwX3NpbnQzMl9zaW50MzIYBSADKAsyNS5wcm90b2J1",
+ "Zl91bml0dGVzdDMuVGVzdEFyZW5hTWFwLk1hcFNpbnQzMlNpbnQzMkVudHJ5",
+ "ElAKEW1hcF9zaW50NjRfc2ludDY0GAYgAygLMjUucHJvdG9idWZfdW5pdHRl",
+ "c3QzLlRlc3RBcmVuYU1hcC5NYXBTaW50NjRTaW50NjRFbnRyeRJUChNtYXBf",
+ "Zml4ZWQzMl9maXhlZDMyGAcgAygLMjcucHJvdG9idWZfdW5pdHRlc3QzLlRl",
+ "c3RBcmVuYU1hcC5NYXBGaXhlZDMyRml4ZWQzMkVudHJ5ElQKE21hcF9maXhl",
+ "ZDY0X2ZpeGVkNjQYCCADKAsyNy5wcm90b2J1Zl91bml0dGVzdDMuVGVzdEFy",
+ "ZW5hTWFwLk1hcEZpeGVkNjRGaXhlZDY0RW50cnkSWAoVbWFwX3NmaXhlZDMy",
+ "X3NmaXhlZDMyGAkgAygLMjkucHJvdG9idWZfdW5pdHRlc3QzLlRlc3RBcmVu",
+ "YU1hcC5NYXBTZml4ZWQzMlNmaXhlZDMyRW50cnkSWAoVbWFwX3NmaXhlZDY0",
+ "X3NmaXhlZDY0GAogAygLMjkucHJvdG9idWZfdW5pdHRlc3QzLlRlc3RBcmVu",
+ "YU1hcC5NYXBTZml4ZWQ2NFNmaXhlZDY0RW50cnkSTAoPbWFwX2ludDMyX2Zs",
+ "b2F0GAsgAygLMjMucHJvdG9idWZfdW5pdHRlc3QzLlRlc3RBcmVuYU1hcC5N",
+ "YXBJbnQzMkZsb2F0RW50cnkSTgoQbWFwX2ludDMyX2RvdWJsZRgMIAMoCzI0",
+ "LnByb3RvYnVmX3VuaXR0ZXN0My5UZXN0QXJlbmFNYXAuTWFwSW50MzJEb3Vi",
+ "bGVFbnRyeRJICg1tYXBfYm9vbF9ib29sGA0gAygLMjEucHJvdG9idWZfdW5p",
+ "dHRlc3QzLlRlc3RBcmVuYU1hcC5NYXBCb29sQm9vbEVudHJ5EkoKDm1hcF9p",
+ "bnQzMl9lbnVtGA4gAygLMjIucHJvdG9idWZfdW5pdHRlc3QzLlRlc3RBcmVu",
+ "YU1hcC5NYXBJbnQzMkVudW1FbnRyeRJfChltYXBfaW50MzJfZm9yZWlnbl9t",
+ "ZXNzYWdlGA8gAygLMjwucHJvdG9idWZfdW5pdHRlc3QzLlRlc3RBcmVuYU1h",
+ "cC5NYXBJbnQzMkZvcmVpZ25NZXNzYWdlRW50cnkaNAoSTWFwSW50MzJJbnQz",
+ "MkVudHJ5EgsKA2tleRgBIAEoBRINCgV2YWx1ZRgCIAEoBToCOAEaNAoSTWFw",
+ "SW50NjRJbnQ2NEVudHJ5EgsKA2tleRgBIAEoAxINCgV2YWx1ZRgCIAEoAzoC",
+ "OAEaNgoUTWFwVWludDMyVWludDMyRW50cnkSCwoDa2V5GAEgASgNEg0KBXZh",
+ "bHVlGAIgASgNOgI4ARo2ChRNYXBVaW50NjRVaW50NjRFbnRyeRILCgNrZXkY",
+ "ASABKAQSDQoFdmFsdWUYAiABKAQ6AjgBGjYKFE1hcFNpbnQzMlNpbnQzMkVu",
+ "dHJ5EgsKA2tleRgBIAEoERINCgV2YWx1ZRgCIAEoEToCOAEaNgoUTWFwU2lu",
+ "dDY0U2ludDY0RW50cnkSCwoDa2V5GAEgASgSEg0KBXZhbHVlGAIgASgSOgI4",
+ "ARo4ChZNYXBGaXhlZDMyRml4ZWQzMkVudHJ5EgsKA2tleRgBIAEoBxINCgV2",
+ "YWx1ZRgCIAEoBzoCOAEaOAoWTWFwRml4ZWQ2NEZpeGVkNjRFbnRyeRILCgNr",
+ "ZXkYASABKAYSDQoFdmFsdWUYAiABKAY6AjgBGjoKGE1hcFNmaXhlZDMyU2Zp",
+ "eGVkMzJFbnRyeRILCgNrZXkYASABKA8SDQoFdmFsdWUYAiABKA86AjgBGjoK",
+ "GE1hcFNmaXhlZDY0U2ZpeGVkNjRFbnRyeRILCgNrZXkYASABKBASDQoFdmFs",
+ "dWUYAiABKBA6AjgBGjQKEk1hcEludDMyRmxvYXRFbnRyeRILCgNrZXkYASAB",
+ "KAUSDQoFdmFsdWUYAiABKAI6AjgBGjUKE01hcEludDMyRG91YmxlRW50cnkS",
+ "CwoDa2V5GAEgASgFEg0KBXZhbHVlGAIgASgBOgI4ARoyChBNYXBCb29sQm9v",
+ "bEVudHJ5EgsKA2tleRgBIAEoCBINCgV2YWx1ZRgCIAEoCDoCOAEaUAoRTWFw",
+ "SW50MzJFbnVtRW50cnkSCwoDa2V5GAEgASgFEioKBXZhbHVlGAIgASgOMhsu",
+ "cHJvdG9idWZfdW5pdHRlc3QzLk1hcEVudW06AjgBGmEKG01hcEludDMyRm9y",
+ "ZWlnbk1lc3NhZ2VFbnRyeRILCgNrZXkYASABKAUSMQoFdmFsdWUYAiABKAsy",
+ "Ii5wcm90b2J1Zl91bml0dGVzdDMuRm9yZWlnbk1lc3NhZ2U6AjgBIuYBCh9N",
+ "ZXNzYWdlQ29udGFpbmluZ0VudW1DYWxsZWRUeXBlEksKBHR5cGUYASADKAsy",
+ "PS5wcm90b2J1Zl91bml0dGVzdDMuTWVzc2FnZUNvbnRhaW5pbmdFbnVtQ2Fs",
+ "bGVkVHlwZS5UeXBlRW50cnkaYAoJVHlwZUVudHJ5EgsKA2tleRgBIAEoBRJC",
+ "CgV2YWx1ZRgCIAEoCzIzLnByb3RvYnVmX3VuaXR0ZXN0My5NZXNzYWdlQ29u",
+ "dGFpbmluZ0VudW1DYWxsZWRUeXBlOgI4ASIUCgRUeXBlEgwKCFRZUEVfRk9P",
+ "EAAingEKH01lc3NhZ2VDb250YWluaW5nTWFwQ2FsbGVkRW50cnkSTQoFZW50",
+ "cnkYASADKAsyPi5wcm90b2J1Zl91bml0dGVzdDMuTWVzc2FnZUNvbnRhaW5p",
+ "bmdNYXBDYWxsZWRFbnRyeS5FbnRyeUVudHJ5GiwKCkVudHJ5RW50cnkSCwoD",
+ "a2V5GAEgASgFEg0KBXZhbHVlGAIgASgFOgI4ASo/CgdNYXBFbnVtEhAKDE1B",
+ "UF9FTlVNX0ZPTxAAEhAKDE1BUF9FTlVNX0JBUhABEhAKDE1BUF9FTlVNX0JB",
+ "WhACQh2qAhpHb29nbGUuUHJvdG9idWYuVGVzdFByb3Rvc2IGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(new[] {typeof(global::Google.Protobuf.TestProtos.MapEnum), }, new pbr::GeneratedClrTypeInfo[] {
diff --git a/csharp/src/Google.Protobuf.Test/TestProtos/TestMessagesProto3.cs b/csharp/src/Google.Protobuf.Test/TestProtos/TestMessagesProto3.cs
index fbeb512a..45850bb0 100644
--- a/csharp/src/Google.Protobuf.Test/TestProtos/TestMessagesProto3.cs
+++ b/csharp/src/Google.Protobuf.Test/TestProtos/TestMessagesProto3.cs
@@ -27,180 +27,184 @@ namespace ProtobufTestMessages.Proto3 {
"dWYvYW55LnByb3RvGh5nb29nbGUvcHJvdG9idWYvZHVyYXRpb24ucHJvdG8a",
"IGdvb2dsZS9wcm90b2J1Zi9maWVsZF9tYXNrLnByb3RvGhxnb29nbGUvcHJv",
"dG9idWYvc3RydWN0LnByb3RvGh9nb29nbGUvcHJvdG9idWYvdGltZXN0YW1w",
- "LnByb3RvGh5nb29nbGUvcHJvdG9idWYvd3JhcHBlcnMucHJvdG8i+DkKDFRl",
- "c3RBbGxUeXBlcxIWCg5vcHRpb25hbF9pbnQzMhgBIAEoBRIWCg5vcHRpb25h",
- "bF9pbnQ2NBgCIAEoAxIXCg9vcHRpb25hbF91aW50MzIYAyABKA0SFwoPb3B0",
- "aW9uYWxfdWludDY0GAQgASgEEhcKD29wdGlvbmFsX3NpbnQzMhgFIAEoERIX",
- "Cg9vcHRpb25hbF9zaW50NjQYBiABKBISGAoQb3B0aW9uYWxfZml4ZWQzMhgH",
- "IAEoBxIYChBvcHRpb25hbF9maXhlZDY0GAggASgGEhkKEW9wdGlvbmFsX3Nm",
- "aXhlZDMyGAkgASgPEhkKEW9wdGlvbmFsX3NmaXhlZDY0GAogASgQEhYKDm9w",
- "dGlvbmFsX2Zsb2F0GAsgASgCEhcKD29wdGlvbmFsX2RvdWJsZRgMIAEoARIV",
- "Cg1vcHRpb25hbF9ib29sGA0gASgIEhcKD29wdGlvbmFsX3N0cmluZxgOIAEo",
- "CRIWCg5vcHRpb25hbF9ieXRlcxgPIAEoDBJaChdvcHRpb25hbF9uZXN0ZWRf",
- "bWVzc2FnZRgSIAEoCzI5LnByb3RvYnVmX3Rlc3RfbWVzc2FnZXMucHJvdG8z",
- "LlRlc3RBbGxUeXBlcy5OZXN0ZWRNZXNzYWdlEk8KGG9wdGlvbmFsX2ZvcmVp",
- "Z25fbWVzc2FnZRgTIAEoCzItLnByb3RvYnVmX3Rlc3RfbWVzc2FnZXMucHJv",
- "dG8zLkZvcmVpZ25NZXNzYWdlElQKFG9wdGlvbmFsX25lc3RlZF9lbnVtGBUg",
- "ASgOMjYucHJvdG9idWZfdGVzdF9tZXNzYWdlcy5wcm90bzMuVGVzdEFsbFR5",
- "cGVzLk5lc3RlZEVudW0SSQoVb3B0aW9uYWxfZm9yZWlnbl9lbnVtGBYgASgO",
- "MioucHJvdG9idWZfdGVzdF9tZXNzYWdlcy5wcm90bzMuRm9yZWlnbkVudW0S",
- "IQoVb3B0aW9uYWxfc3RyaW5nX3BpZWNlGBggASgJQgIIAhIZCg1vcHRpb25h",
- "bF9jb3JkGBkgASgJQgIIARJGChFyZWN1cnNpdmVfbWVzc2FnZRgbIAEoCzIr",
- "LnByb3RvYnVmX3Rlc3RfbWVzc2FnZXMucHJvdG8zLlRlc3RBbGxUeXBlcxIW",
- "Cg5yZXBlYXRlZF9pbnQzMhgfIAMoBRIWCg5yZXBlYXRlZF9pbnQ2NBggIAMo",
- "AxIXCg9yZXBlYXRlZF91aW50MzIYISADKA0SFwoPcmVwZWF0ZWRfdWludDY0",
- "GCIgAygEEhcKD3JlcGVhdGVkX3NpbnQzMhgjIAMoERIXCg9yZXBlYXRlZF9z",
- "aW50NjQYJCADKBISGAoQcmVwZWF0ZWRfZml4ZWQzMhglIAMoBxIYChByZXBl",
- "YXRlZF9maXhlZDY0GCYgAygGEhkKEXJlcGVhdGVkX3NmaXhlZDMyGCcgAygP",
- "EhkKEXJlcGVhdGVkX3NmaXhlZDY0GCggAygQEhYKDnJlcGVhdGVkX2Zsb2F0",
- "GCkgAygCEhcKD3JlcGVhdGVkX2RvdWJsZRgqIAMoARIVCg1yZXBlYXRlZF9i",
- "b29sGCsgAygIEhcKD3JlcGVhdGVkX3N0cmluZxgsIAMoCRIWCg5yZXBlYXRl",
- "ZF9ieXRlcxgtIAMoDBJaChdyZXBlYXRlZF9uZXN0ZWRfbWVzc2FnZRgwIAMo",
- "CzI5LnByb3RvYnVmX3Rlc3RfbWVzc2FnZXMucHJvdG8zLlRlc3RBbGxUeXBl",
- "cy5OZXN0ZWRNZXNzYWdlEk8KGHJlcGVhdGVkX2ZvcmVpZ25fbWVzc2FnZRgx",
- "IAMoCzItLnByb3RvYnVmX3Rlc3RfbWVzc2FnZXMucHJvdG8zLkZvcmVpZ25N",
- "ZXNzYWdlElQKFHJlcGVhdGVkX25lc3RlZF9lbnVtGDMgAygOMjYucHJvdG9i",
- "dWZfdGVzdF9tZXNzYWdlcy5wcm90bzMuVGVzdEFsbFR5cGVzLk5lc3RlZEVu",
- "dW0SSQoVcmVwZWF0ZWRfZm9yZWlnbl9lbnVtGDQgAygOMioucHJvdG9idWZf",
- "dGVzdF9tZXNzYWdlcy5wcm90bzMuRm9yZWlnbkVudW0SIQoVcmVwZWF0ZWRf",
- "c3RyaW5nX3BpZWNlGDYgAygJQgIIAhIZCg1yZXBlYXRlZF9jb3JkGDcgAygJ",
- "QgIIARJXCg9tYXBfaW50MzJfaW50MzIYOCADKAsyPi5wcm90b2J1Zl90ZXN0",
- "X21lc3NhZ2VzLnByb3RvMy5UZXN0QWxsVHlwZXMuTWFwSW50MzJJbnQzMkVu",
- "dHJ5ElcKD21hcF9pbnQ2NF9pbnQ2NBg5IAMoCzI+LnByb3RvYnVmX3Rlc3Rf",
- "bWVzc2FnZXMucHJvdG8zLlRlc3RBbGxUeXBlcy5NYXBJbnQ2NEludDY0RW50",
- "cnkSWwoRbWFwX3VpbnQzMl91aW50MzIYOiADKAsyQC5wcm90b2J1Zl90ZXN0",
- "X21lc3NhZ2VzLnByb3RvMy5UZXN0QWxsVHlwZXMuTWFwVWludDMyVWludDMy",
- "RW50cnkSWwoRbWFwX3VpbnQ2NF91aW50NjQYOyADKAsyQC5wcm90b2J1Zl90",
- "ZXN0X21lc3NhZ2VzLnByb3RvMy5UZXN0QWxsVHlwZXMuTWFwVWludDY0VWlu",
- "dDY0RW50cnkSWwoRbWFwX3NpbnQzMl9zaW50MzIYPCADKAsyQC5wcm90b2J1",
- "Zl90ZXN0X21lc3NhZ2VzLnByb3RvMy5UZXN0QWxsVHlwZXMuTWFwU2ludDMy",
- "U2ludDMyRW50cnkSWwoRbWFwX3NpbnQ2NF9zaW50NjQYPSADKAsyQC5wcm90",
- "b2J1Zl90ZXN0X21lc3NhZ2VzLnByb3RvMy5UZXN0QWxsVHlwZXMuTWFwU2lu",
- "dDY0U2ludDY0RW50cnkSXwoTbWFwX2ZpeGVkMzJfZml4ZWQzMhg+IAMoCzJC",
- "LnByb3RvYnVmX3Rlc3RfbWVzc2FnZXMucHJvdG8zLlRlc3RBbGxUeXBlcy5N",
- "YXBGaXhlZDMyRml4ZWQzMkVudHJ5El8KE21hcF9maXhlZDY0X2ZpeGVkNjQY",
- "PyADKAsyQi5wcm90b2J1Zl90ZXN0X21lc3NhZ2VzLnByb3RvMy5UZXN0QWxs",
- "VHlwZXMuTWFwRml4ZWQ2NEZpeGVkNjRFbnRyeRJjChVtYXBfc2ZpeGVkMzJf",
- "c2ZpeGVkMzIYQCADKAsyRC5wcm90b2J1Zl90ZXN0X21lc3NhZ2VzLnByb3Rv",
- "My5UZXN0QWxsVHlwZXMuTWFwU2ZpeGVkMzJTZml4ZWQzMkVudHJ5EmMKFW1h",
- "cF9zZml4ZWQ2NF9zZml4ZWQ2NBhBIAMoCzJELnByb3RvYnVmX3Rlc3RfbWVz",
- "c2FnZXMucHJvdG8zLlRlc3RBbGxUeXBlcy5NYXBTZml4ZWQ2NFNmaXhlZDY0",
- "RW50cnkSVwoPbWFwX2ludDMyX2Zsb2F0GEIgAygLMj4ucHJvdG9idWZfdGVz",
- "dF9tZXNzYWdlcy5wcm90bzMuVGVzdEFsbFR5cGVzLk1hcEludDMyRmxvYXRF",
- "bnRyeRJZChBtYXBfaW50MzJfZG91YmxlGEMgAygLMj8ucHJvdG9idWZfdGVz",
- "dF9tZXNzYWdlcy5wcm90bzMuVGVzdEFsbFR5cGVzLk1hcEludDMyRG91Ymxl",
- "RW50cnkSUwoNbWFwX2Jvb2xfYm9vbBhEIAMoCzI8LnByb3RvYnVmX3Rlc3Rf",
- "bWVzc2FnZXMucHJvdG8zLlRlc3RBbGxUeXBlcy5NYXBCb29sQm9vbEVudHJ5",
- "ElsKEW1hcF9zdHJpbmdfc3RyaW5nGEUgAygLMkAucHJvdG9idWZfdGVzdF9t",
- "ZXNzYWdlcy5wcm90bzMuVGVzdEFsbFR5cGVzLk1hcFN0cmluZ1N0cmluZ0Vu",
- "dHJ5ElkKEG1hcF9zdHJpbmdfYnl0ZXMYRiADKAsyPy5wcm90b2J1Zl90ZXN0",
- "X21lc3NhZ2VzLnByb3RvMy5UZXN0QWxsVHlwZXMuTWFwU3RyaW5nQnl0ZXNF",
- "bnRyeRJqChltYXBfc3RyaW5nX25lc3RlZF9tZXNzYWdlGEcgAygLMkcucHJv",
- "dG9idWZfdGVzdF9tZXNzYWdlcy5wcm90bzMuVGVzdEFsbFR5cGVzLk1hcFN0",
- "cmluZ05lc3RlZE1lc3NhZ2VFbnRyeRJsChptYXBfc3RyaW5nX2ZvcmVpZ25f",
- "bWVzc2FnZRhIIAMoCzJILnByb3RvYnVmX3Rlc3RfbWVzc2FnZXMucHJvdG8z",
- "LlRlc3RBbGxUeXBlcy5NYXBTdHJpbmdGb3JlaWduTWVzc2FnZUVudHJ5EmQK",
- "Fm1hcF9zdHJpbmdfbmVzdGVkX2VudW0YSSADKAsyRC5wcm90b2J1Zl90ZXN0",
- "X21lc3NhZ2VzLnByb3RvMy5UZXN0QWxsVHlwZXMuTWFwU3RyaW5nTmVzdGVk",
- "RW51bUVudHJ5EmYKF21hcF9zdHJpbmdfZm9yZWlnbl9lbnVtGEogAygLMkUu",
- "cHJvdG9idWZfdGVzdF9tZXNzYWdlcy5wcm90bzMuVGVzdEFsbFR5cGVzLk1h",
- "cFN0cmluZ0ZvcmVpZ25FbnVtRW50cnkSFgoMb25lb2ZfdWludDMyGG8gASgN",
- "SAASWQoUb25lb2ZfbmVzdGVkX21lc3NhZ2UYcCABKAsyOS5wcm90b2J1Zl90",
- "ZXN0X21lc3NhZ2VzLnByb3RvMy5UZXN0QWxsVHlwZXMuTmVzdGVkTWVzc2Fn",
- "ZUgAEhYKDG9uZW9mX3N0cmluZxhxIAEoCUgAEhUKC29uZW9mX2J5dGVzGHIg",
- "ASgMSAASFAoKb25lb2ZfYm9vbBhzIAEoCEgAEhYKDG9uZW9mX3VpbnQ2NBh0",
- "IAEoBEgAEhUKC29uZW9mX2Zsb2F0GHUgASgCSAASFgoMb25lb2ZfZG91Ymxl",
- "GHYgASgBSAASTAoKb25lb2ZfZW51bRh3IAEoDjI2LnByb3RvYnVmX3Rlc3Rf",
- "bWVzc2FnZXMucHJvdG8zLlRlc3RBbGxUeXBlcy5OZXN0ZWRFbnVtSAASOgoV",
- "b3B0aW9uYWxfYm9vbF93cmFwcGVyGMkBIAEoCzIaLmdvb2dsZS5wcm90b2J1",
- "Zi5Cb29sVmFsdWUSPAoWb3B0aW9uYWxfaW50MzJfd3JhcHBlchjKASABKAsy",
- "Gy5nb29nbGUucHJvdG9idWYuSW50MzJWYWx1ZRI8ChZvcHRpb25hbF9pbnQ2",
- "NF93cmFwcGVyGMsBIAEoCzIbLmdvb2dsZS5wcm90b2J1Zi5JbnQ2NFZhbHVl",
- "Ej4KF29wdGlvbmFsX3VpbnQzMl93cmFwcGVyGMwBIAEoCzIcLmdvb2dsZS5w",
- "cm90b2J1Zi5VSW50MzJWYWx1ZRI+ChdvcHRpb25hbF91aW50NjRfd3JhcHBl",
- "chjNASABKAsyHC5nb29nbGUucHJvdG9idWYuVUludDY0VmFsdWUSPAoWb3B0",
- "aW9uYWxfZmxvYXRfd3JhcHBlchjOASABKAsyGy5nb29nbGUucHJvdG9idWYu",
- "RmxvYXRWYWx1ZRI+ChdvcHRpb25hbF9kb3VibGVfd3JhcHBlchjPASABKAsy",
- "HC5nb29nbGUucHJvdG9idWYuRG91YmxlVmFsdWUSPgoXb3B0aW9uYWxfc3Ry",
- "aW5nX3dyYXBwZXIY0AEgASgLMhwuZ29vZ2xlLnByb3RvYnVmLlN0cmluZ1Zh",
- "bHVlEjwKFm9wdGlvbmFsX2J5dGVzX3dyYXBwZXIY0QEgASgLMhsuZ29vZ2xl",
- "LnByb3RvYnVmLkJ5dGVzVmFsdWUSOgoVcmVwZWF0ZWRfYm9vbF93cmFwcGVy",
- "GNMBIAMoCzIaLmdvb2dsZS5wcm90b2J1Zi5Cb29sVmFsdWUSPAoWcmVwZWF0",
- "ZWRfaW50MzJfd3JhcHBlchjUASADKAsyGy5nb29nbGUucHJvdG9idWYuSW50",
- "MzJWYWx1ZRI8ChZyZXBlYXRlZF9pbnQ2NF93cmFwcGVyGNUBIAMoCzIbLmdv",
- "b2dsZS5wcm90b2J1Zi5JbnQ2NFZhbHVlEj4KF3JlcGVhdGVkX3VpbnQzMl93",
- "cmFwcGVyGNYBIAMoCzIcLmdvb2dsZS5wcm90b2J1Zi5VSW50MzJWYWx1ZRI+",
- "ChdyZXBlYXRlZF91aW50NjRfd3JhcHBlchjXASADKAsyHC5nb29nbGUucHJv",
- "dG9idWYuVUludDY0VmFsdWUSPAoWcmVwZWF0ZWRfZmxvYXRfd3JhcHBlchjY",
- "ASADKAsyGy5nb29nbGUucHJvdG9idWYuRmxvYXRWYWx1ZRI+ChdyZXBlYXRl",
- "ZF9kb3VibGVfd3JhcHBlchjZASADKAsyHC5nb29nbGUucHJvdG9idWYuRG91",
- "YmxlVmFsdWUSPgoXcmVwZWF0ZWRfc3RyaW5nX3dyYXBwZXIY2gEgAygLMhwu",
- "Z29vZ2xlLnByb3RvYnVmLlN0cmluZ1ZhbHVlEjwKFnJlcGVhdGVkX2J5dGVz",
- "X3dyYXBwZXIY2wEgAygLMhsuZ29vZ2xlLnByb3RvYnVmLkJ5dGVzVmFsdWUS",
- "NQoRb3B0aW9uYWxfZHVyYXRpb24YrQIgASgLMhkuZ29vZ2xlLnByb3RvYnVm",
- "LkR1cmF0aW9uEjcKEm9wdGlvbmFsX3RpbWVzdGFtcBiuAiABKAsyGi5nb29n",
- "bGUucHJvdG9idWYuVGltZXN0YW1wEjgKE29wdGlvbmFsX2ZpZWxkX21hc2sY",
- "rwIgASgLMhouZ29vZ2xlLnByb3RvYnVmLkZpZWxkTWFzaxIxCg9vcHRpb25h",
- "bF9zdHJ1Y3QYsAIgASgLMhcuZ29vZ2xlLnByb3RvYnVmLlN0cnVjdBIrCgxv",
- "cHRpb25hbF9hbnkYsQIgASgLMhQuZ29vZ2xlLnByb3RvYnVmLkFueRIvCg5v",
- "cHRpb25hbF92YWx1ZRiyAiABKAsyFi5nb29nbGUucHJvdG9idWYuVmFsdWUS",
- "NQoRcmVwZWF0ZWRfZHVyYXRpb24YtwIgAygLMhkuZ29vZ2xlLnByb3RvYnVm",
- "LkR1cmF0aW9uEjcKEnJlcGVhdGVkX3RpbWVzdGFtcBi4AiADKAsyGi5nb29n",
- "bGUucHJvdG9idWYuVGltZXN0YW1wEjcKEnJlcGVhdGVkX2ZpZWxkbWFzaxi5",
- "AiADKAsyGi5nb29nbGUucHJvdG9idWYuRmllbGRNYXNrEjEKD3JlcGVhdGVk",
- "X3N0cnVjdBjEAiADKAsyFy5nb29nbGUucHJvdG9idWYuU3RydWN0EisKDHJl",
- "cGVhdGVkX2FueRi7AiADKAsyFC5nb29nbGUucHJvdG9idWYuQW55Ei8KDnJl",
- "cGVhdGVkX3ZhbHVlGLwCIAMoCzIWLmdvb2dsZS5wcm90b2J1Zi5WYWx1ZRIT",
- "CgpmaWVsZG5hbWUxGJEDIAEoBRIUCgtmaWVsZF9uYW1lMhiSAyABKAUSFQoM",
- "X2ZpZWxkX25hbWUzGJMDIAEoBRIWCg1maWVsZF9fbmFtZTRfGJQDIAEoBRIU",
- "CgtmaWVsZDBuYW1lNRiVAyABKAUSFgoNZmllbGRfMF9uYW1lNhiWAyABKAUS",
- "EwoKZmllbGROYW1lNxiXAyABKAUSEwoKRmllbGROYW1lOBiYAyABKAUSFAoL",
- "ZmllbGRfTmFtZTkYmQMgASgFEhUKDEZpZWxkX05hbWUxMBiaAyABKAUSFQoM",
- "RklFTERfTkFNRTExGJsDIAEoBRIVCgxGSUVMRF9uYW1lMTIYnAMgASgFEhcK",
- "Dl9fZmllbGRfbmFtZTEzGJ0DIAEoBRIXCg5fX0ZpZWxkX25hbWUxNBieAyAB",
- "KAUSFgoNZmllbGRfX25hbWUxNRifAyABKAUSFgoNZmllbGRfX05hbWUxNhig",
- "AyABKAUSFwoOZmllbGRfbmFtZTE3X18YoQMgASgFEhcKDkZpZWxkX25hbWUx",
- "OF9fGKIDIAEoBRpcCg1OZXN0ZWRNZXNzYWdlEgkKAWEYASABKAUSQAoLY29y",
- "ZWN1cnNpdmUYAiABKAsyKy5wcm90b2J1Zl90ZXN0X21lc3NhZ2VzLnByb3Rv",
- "My5UZXN0QWxsVHlwZXMaNAoSTWFwSW50MzJJbnQzMkVudHJ5EgsKA2tleRgB",
- "IAEoBRINCgV2YWx1ZRgCIAEoBToCOAEaNAoSTWFwSW50NjRJbnQ2NEVudHJ5",
- "EgsKA2tleRgBIAEoAxINCgV2YWx1ZRgCIAEoAzoCOAEaNgoUTWFwVWludDMy",
- "VWludDMyRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARo2",
- "ChRNYXBVaW50NjRVaW50NjRFbnRyeRILCgNrZXkYASABKAQSDQoFdmFsdWUY",
- "AiABKAQ6AjgBGjYKFE1hcFNpbnQzMlNpbnQzMkVudHJ5EgsKA2tleRgBIAEo",
- "ERINCgV2YWx1ZRgCIAEoEToCOAEaNgoUTWFwU2ludDY0U2ludDY0RW50cnkS",
- "CwoDa2V5GAEgASgSEg0KBXZhbHVlGAIgASgSOgI4ARo4ChZNYXBGaXhlZDMy",
- "Rml4ZWQzMkVudHJ5EgsKA2tleRgBIAEoBxINCgV2YWx1ZRgCIAEoBzoCOAEa",
- "OAoWTWFwRml4ZWQ2NEZpeGVkNjRFbnRyeRILCgNrZXkYASABKAYSDQoFdmFs",
- "dWUYAiABKAY6AjgBGjoKGE1hcFNmaXhlZDMyU2ZpeGVkMzJFbnRyeRILCgNr",
- "ZXkYASABKA8SDQoFdmFsdWUYAiABKA86AjgBGjoKGE1hcFNmaXhlZDY0U2Zp",
- "eGVkNjRFbnRyeRILCgNrZXkYASABKBASDQoFdmFsdWUYAiABKBA6AjgBGjQK",
- "Ek1hcEludDMyRmxvYXRFbnRyeRILCgNrZXkYASABKAUSDQoFdmFsdWUYAiAB",
- "KAI6AjgBGjUKE01hcEludDMyRG91YmxlRW50cnkSCwoDa2V5GAEgASgFEg0K",
- "BXZhbHVlGAIgASgBOgI4ARoyChBNYXBCb29sQm9vbEVudHJ5EgsKA2tleRgB",
- "IAEoCBINCgV2YWx1ZRgCIAEoCDoCOAEaNgoUTWFwU3RyaW5nU3RyaW5nRW50",
- "cnkSCwoDa2V5GAEgASgJEg0KBXZhbHVlGAIgASgJOgI4ARo1ChNNYXBTdHJp",
- "bmdCeXRlc0VudHJ5EgsKA2tleRgBIAEoCRINCgV2YWx1ZRgCIAEoDDoCOAEa",
- "eAobTWFwU3RyaW5nTmVzdGVkTWVzc2FnZUVudHJ5EgsKA2tleRgBIAEoCRJI",
- "CgV2YWx1ZRgCIAEoCzI5LnByb3RvYnVmX3Rlc3RfbWVzc2FnZXMucHJvdG8z",
- "LlRlc3RBbGxUeXBlcy5OZXN0ZWRNZXNzYWdlOgI4ARptChxNYXBTdHJpbmdG",
- "b3JlaWduTWVzc2FnZUVudHJ5EgsKA2tleRgBIAEoCRI8CgV2YWx1ZRgCIAEo",
- "CzItLnByb3RvYnVmX3Rlc3RfbWVzc2FnZXMucHJvdG8zLkZvcmVpZ25NZXNz",
- "YWdlOgI4ARpyChhNYXBTdHJpbmdOZXN0ZWRFbnVtRW50cnkSCwoDa2V5GAEg",
- "ASgJEkUKBXZhbHVlGAIgASgOMjYucHJvdG9idWZfdGVzdF9tZXNzYWdlcy5w",
- "cm90bzMuVGVzdEFsbFR5cGVzLk5lc3RlZEVudW06AjgBGmcKGU1hcFN0cmlu",
+ "LnByb3RvGh5nb29nbGUvcHJvdG9idWYvd3JhcHBlcnMucHJvdG8itDsKElRl",
+ "c3RBbGxUeXBlc1Byb3RvMxIWCg5vcHRpb25hbF9pbnQzMhgBIAEoBRIWCg5v",
+ "cHRpb25hbF9pbnQ2NBgCIAEoAxIXCg9vcHRpb25hbF91aW50MzIYAyABKA0S",
+ "FwoPb3B0aW9uYWxfdWludDY0GAQgASgEEhcKD29wdGlvbmFsX3NpbnQzMhgF",
+ "IAEoERIXCg9vcHRpb25hbF9zaW50NjQYBiABKBISGAoQb3B0aW9uYWxfZml4",
+ "ZWQzMhgHIAEoBxIYChBvcHRpb25hbF9maXhlZDY0GAggASgGEhkKEW9wdGlv",
+ "bmFsX3NmaXhlZDMyGAkgASgPEhkKEW9wdGlvbmFsX3NmaXhlZDY0GAogASgQ",
+ "EhYKDm9wdGlvbmFsX2Zsb2F0GAsgASgCEhcKD29wdGlvbmFsX2RvdWJsZRgM",
+ "IAEoARIVCg1vcHRpb25hbF9ib29sGA0gASgIEhcKD29wdGlvbmFsX3N0cmlu",
+ "ZxgOIAEoCRIWCg5vcHRpb25hbF9ieXRlcxgPIAEoDBJgChdvcHRpb25hbF9u",
+ "ZXN0ZWRfbWVzc2FnZRgSIAEoCzI/LnByb3RvYnVmX3Rlc3RfbWVzc2FnZXMu",
+ "cHJvdG8zLlRlc3RBbGxUeXBlc1Byb3RvMy5OZXN0ZWRNZXNzYWdlEk8KGG9w",
+ "dGlvbmFsX2ZvcmVpZ25fbWVzc2FnZRgTIAEoCzItLnByb3RvYnVmX3Rlc3Rf",
+ "bWVzc2FnZXMucHJvdG8zLkZvcmVpZ25NZXNzYWdlEloKFG9wdGlvbmFsX25l",
+ "c3RlZF9lbnVtGBUgASgOMjwucHJvdG9idWZfdGVzdF9tZXNzYWdlcy5wcm90",
+ "bzMuVGVzdEFsbFR5cGVzUHJvdG8zLk5lc3RlZEVudW0SSQoVb3B0aW9uYWxf",
+ "Zm9yZWlnbl9lbnVtGBYgASgOMioucHJvdG9idWZfdGVzdF9tZXNzYWdlcy5w",
+ "cm90bzMuRm9yZWlnbkVudW0SIQoVb3B0aW9uYWxfc3RyaW5nX3BpZWNlGBgg",
+ "ASgJQgIIAhIZCg1vcHRpb25hbF9jb3JkGBkgASgJQgIIARJMChFyZWN1cnNp",
+ "dmVfbWVzc2FnZRgbIAEoCzIxLnByb3RvYnVmX3Rlc3RfbWVzc2FnZXMucHJv",
+ "dG8zLlRlc3RBbGxUeXBlc1Byb3RvMxIWCg5yZXBlYXRlZF9pbnQzMhgfIAMo",
+ "BRIWCg5yZXBlYXRlZF9pbnQ2NBggIAMoAxIXCg9yZXBlYXRlZF91aW50MzIY",
+ "ISADKA0SFwoPcmVwZWF0ZWRfdWludDY0GCIgAygEEhcKD3JlcGVhdGVkX3Np",
+ "bnQzMhgjIAMoERIXCg9yZXBlYXRlZF9zaW50NjQYJCADKBISGAoQcmVwZWF0",
+ "ZWRfZml4ZWQzMhglIAMoBxIYChByZXBlYXRlZF9maXhlZDY0GCYgAygGEhkK",
+ "EXJlcGVhdGVkX3NmaXhlZDMyGCcgAygPEhkKEXJlcGVhdGVkX3NmaXhlZDY0",
+ "GCggAygQEhYKDnJlcGVhdGVkX2Zsb2F0GCkgAygCEhcKD3JlcGVhdGVkX2Rv",
+ "dWJsZRgqIAMoARIVCg1yZXBlYXRlZF9ib29sGCsgAygIEhcKD3JlcGVhdGVk",
+ "X3N0cmluZxgsIAMoCRIWCg5yZXBlYXRlZF9ieXRlcxgtIAMoDBJgChdyZXBl",
+ "YXRlZF9uZXN0ZWRfbWVzc2FnZRgwIAMoCzI/LnByb3RvYnVmX3Rlc3RfbWVz",
+ "c2FnZXMucHJvdG8zLlRlc3RBbGxUeXBlc1Byb3RvMy5OZXN0ZWRNZXNzYWdl",
+ "Ek8KGHJlcGVhdGVkX2ZvcmVpZ25fbWVzc2FnZRgxIAMoCzItLnByb3RvYnVm",
+ "X3Rlc3RfbWVzc2FnZXMucHJvdG8zLkZvcmVpZ25NZXNzYWdlEloKFHJlcGVh",
+ "dGVkX25lc3RlZF9lbnVtGDMgAygOMjwucHJvdG9idWZfdGVzdF9tZXNzYWdl",
+ "cy5wcm90bzMuVGVzdEFsbFR5cGVzUHJvdG8zLk5lc3RlZEVudW0SSQoVcmVw",
+ "ZWF0ZWRfZm9yZWlnbl9lbnVtGDQgAygOMioucHJvdG9idWZfdGVzdF9tZXNz",
+ "YWdlcy5wcm90bzMuRm9yZWlnbkVudW0SIQoVcmVwZWF0ZWRfc3RyaW5nX3Bp",
+ "ZWNlGDYgAygJQgIIAhIZCg1yZXBlYXRlZF9jb3JkGDcgAygJQgIIARJdCg9t",
+ "YXBfaW50MzJfaW50MzIYOCADKAsyRC5wcm90b2J1Zl90ZXN0X21lc3NhZ2Vz",
+ "LnByb3RvMy5UZXN0QWxsVHlwZXNQcm90bzMuTWFwSW50MzJJbnQzMkVudHJ5",
+ "El0KD21hcF9pbnQ2NF9pbnQ2NBg5IAMoCzJELnByb3RvYnVmX3Rlc3RfbWVz",
+ "c2FnZXMucHJvdG8zLlRlc3RBbGxUeXBlc1Byb3RvMy5NYXBJbnQ2NEludDY0",
+ "RW50cnkSYQoRbWFwX3VpbnQzMl91aW50MzIYOiADKAsyRi5wcm90b2J1Zl90",
+ "ZXN0X21lc3NhZ2VzLnByb3RvMy5UZXN0QWxsVHlwZXNQcm90bzMuTWFwVWlu",
+ "dDMyVWludDMyRW50cnkSYQoRbWFwX3VpbnQ2NF91aW50NjQYOyADKAsyRi5w",
+ "cm90b2J1Zl90ZXN0X21lc3NhZ2VzLnByb3RvMy5UZXN0QWxsVHlwZXNQcm90",
+ "bzMuTWFwVWludDY0VWludDY0RW50cnkSYQoRbWFwX3NpbnQzMl9zaW50MzIY",
+ "PCADKAsyRi5wcm90b2J1Zl90ZXN0X21lc3NhZ2VzLnByb3RvMy5UZXN0QWxs",
+ "VHlwZXNQcm90bzMuTWFwU2ludDMyU2ludDMyRW50cnkSYQoRbWFwX3NpbnQ2",
+ "NF9zaW50NjQYPSADKAsyRi5wcm90b2J1Zl90ZXN0X21lc3NhZ2VzLnByb3Rv",
+ "My5UZXN0QWxsVHlwZXNQcm90bzMuTWFwU2ludDY0U2ludDY0RW50cnkSZQoT",
+ "bWFwX2ZpeGVkMzJfZml4ZWQzMhg+IAMoCzJILnByb3RvYnVmX3Rlc3RfbWVz",
+ "c2FnZXMucHJvdG8zLlRlc3RBbGxUeXBlc1Byb3RvMy5NYXBGaXhlZDMyRml4",
+ "ZWQzMkVudHJ5EmUKE21hcF9maXhlZDY0X2ZpeGVkNjQYPyADKAsySC5wcm90",
+ "b2J1Zl90ZXN0X21lc3NhZ2VzLnByb3RvMy5UZXN0QWxsVHlwZXNQcm90bzMu",
+ "TWFwRml4ZWQ2NEZpeGVkNjRFbnRyeRJpChVtYXBfc2ZpeGVkMzJfc2ZpeGVk",
+ "MzIYQCADKAsySi5wcm90b2J1Zl90ZXN0X21lc3NhZ2VzLnByb3RvMy5UZXN0",
+ "QWxsVHlwZXNQcm90bzMuTWFwU2ZpeGVkMzJTZml4ZWQzMkVudHJ5EmkKFW1h",
+ "cF9zZml4ZWQ2NF9zZml4ZWQ2NBhBIAMoCzJKLnByb3RvYnVmX3Rlc3RfbWVz",
+ "c2FnZXMucHJvdG8zLlRlc3RBbGxUeXBlc1Byb3RvMy5NYXBTZml4ZWQ2NFNm",
+ "aXhlZDY0RW50cnkSXQoPbWFwX2ludDMyX2Zsb2F0GEIgAygLMkQucHJvdG9i",
+ "dWZfdGVzdF9tZXNzYWdlcy5wcm90bzMuVGVzdEFsbFR5cGVzUHJvdG8zLk1h",
+ "cEludDMyRmxvYXRFbnRyeRJfChBtYXBfaW50MzJfZG91YmxlGEMgAygLMkUu",
+ "cHJvdG9idWZfdGVzdF9tZXNzYWdlcy5wcm90bzMuVGVzdEFsbFR5cGVzUHJv",
+ "dG8zLk1hcEludDMyRG91YmxlRW50cnkSWQoNbWFwX2Jvb2xfYm9vbBhEIAMo",
+ "CzJCLnByb3RvYnVmX3Rlc3RfbWVzc2FnZXMucHJvdG8zLlRlc3RBbGxUeXBl",
+ "c1Byb3RvMy5NYXBCb29sQm9vbEVudHJ5EmEKEW1hcF9zdHJpbmdfc3RyaW5n",
+ "GEUgAygLMkYucHJvdG9idWZfdGVzdF9tZXNzYWdlcy5wcm90bzMuVGVzdEFs",
+ "bFR5cGVzUHJvdG8zLk1hcFN0cmluZ1N0cmluZ0VudHJ5El8KEG1hcF9zdHJp",
+ "bmdfYnl0ZXMYRiADKAsyRS5wcm90b2J1Zl90ZXN0X21lc3NhZ2VzLnByb3Rv",
+ "My5UZXN0QWxsVHlwZXNQcm90bzMuTWFwU3RyaW5nQnl0ZXNFbnRyeRJwChlt",
+ "YXBfc3RyaW5nX25lc3RlZF9tZXNzYWdlGEcgAygLMk0ucHJvdG9idWZfdGVz",
+ "dF9tZXNzYWdlcy5wcm90bzMuVGVzdEFsbFR5cGVzUHJvdG8zLk1hcFN0cmlu",
+ "Z05lc3RlZE1lc3NhZ2VFbnRyeRJyChptYXBfc3RyaW5nX2ZvcmVpZ25fbWVz",
+ "c2FnZRhIIAMoCzJOLnByb3RvYnVmX3Rlc3RfbWVzc2FnZXMucHJvdG8zLlRl",
+ "c3RBbGxUeXBlc1Byb3RvMy5NYXBTdHJpbmdGb3JlaWduTWVzc2FnZUVudHJ5",
+ "EmoKFm1hcF9zdHJpbmdfbmVzdGVkX2VudW0YSSADKAsySi5wcm90b2J1Zl90",
+ "ZXN0X21lc3NhZ2VzLnByb3RvMy5UZXN0QWxsVHlwZXNQcm90bzMuTWFwU3Ry",
+ "aW5nTmVzdGVkRW51bUVudHJ5EmwKF21hcF9zdHJpbmdfZm9yZWlnbl9lbnVt",
+ "GEogAygLMksucHJvdG9idWZfdGVzdF9tZXNzYWdlcy5wcm90bzMuVGVzdEFs",
+ "bFR5cGVzUHJvdG8zLk1hcFN0cmluZ0ZvcmVpZ25FbnVtRW50cnkSFgoMb25l",
+ "b2ZfdWludDMyGG8gASgNSAASXwoUb25lb2ZfbmVzdGVkX21lc3NhZ2UYcCAB",
+ "KAsyPy5wcm90b2J1Zl90ZXN0X21lc3NhZ2VzLnByb3RvMy5UZXN0QWxsVHlw",
+ "ZXNQcm90bzMuTmVzdGVkTWVzc2FnZUgAEhYKDG9uZW9mX3N0cmluZxhxIAEo",
+ "CUgAEhUKC29uZW9mX2J5dGVzGHIgASgMSAASFAoKb25lb2ZfYm9vbBhzIAEo",
+ "CEgAEhYKDG9uZW9mX3VpbnQ2NBh0IAEoBEgAEhUKC29uZW9mX2Zsb2F0GHUg",
+ "ASgCSAASFgoMb25lb2ZfZG91YmxlGHYgASgBSAASUgoKb25lb2ZfZW51bRh3",
+ "IAEoDjI8LnByb3RvYnVmX3Rlc3RfbWVzc2FnZXMucHJvdG8zLlRlc3RBbGxU",
+ "eXBlc1Byb3RvMy5OZXN0ZWRFbnVtSAASOgoVb3B0aW9uYWxfYm9vbF93cmFw",
+ "cGVyGMkBIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5Cb29sVmFsdWUSPAoWb3B0",
+ "aW9uYWxfaW50MzJfd3JhcHBlchjKASABKAsyGy5nb29nbGUucHJvdG9idWYu",
+ "SW50MzJWYWx1ZRI8ChZvcHRpb25hbF9pbnQ2NF93cmFwcGVyGMsBIAEoCzIb",
+ "Lmdvb2dsZS5wcm90b2J1Zi5JbnQ2NFZhbHVlEj4KF29wdGlvbmFsX3VpbnQz",
+ "Ml93cmFwcGVyGMwBIAEoCzIcLmdvb2dsZS5wcm90b2J1Zi5VSW50MzJWYWx1",
+ "ZRI+ChdvcHRpb25hbF91aW50NjRfd3JhcHBlchjNASABKAsyHC5nb29nbGUu",
+ "cHJvdG9idWYuVUludDY0VmFsdWUSPAoWb3B0aW9uYWxfZmxvYXRfd3JhcHBl",
+ "chjOASABKAsyGy5nb29nbGUucHJvdG9idWYuRmxvYXRWYWx1ZRI+ChdvcHRp",
+ "b25hbF9kb3VibGVfd3JhcHBlchjPASABKAsyHC5nb29nbGUucHJvdG9idWYu",
+ "RG91YmxlVmFsdWUSPgoXb3B0aW9uYWxfc3RyaW5nX3dyYXBwZXIY0AEgASgL",
+ "MhwuZ29vZ2xlLnByb3RvYnVmLlN0cmluZ1ZhbHVlEjwKFm9wdGlvbmFsX2J5",
+ "dGVzX3dyYXBwZXIY0QEgASgLMhsuZ29vZ2xlLnByb3RvYnVmLkJ5dGVzVmFs",
+ "dWUSOgoVcmVwZWF0ZWRfYm9vbF93cmFwcGVyGNMBIAMoCzIaLmdvb2dsZS5w",
+ "cm90b2J1Zi5Cb29sVmFsdWUSPAoWcmVwZWF0ZWRfaW50MzJfd3JhcHBlchjU",
+ "ASADKAsyGy5nb29nbGUucHJvdG9idWYuSW50MzJWYWx1ZRI8ChZyZXBlYXRl",
+ "ZF9pbnQ2NF93cmFwcGVyGNUBIAMoCzIbLmdvb2dsZS5wcm90b2J1Zi5JbnQ2",
+ "NFZhbHVlEj4KF3JlcGVhdGVkX3VpbnQzMl93cmFwcGVyGNYBIAMoCzIcLmdv",
+ "b2dsZS5wcm90b2J1Zi5VSW50MzJWYWx1ZRI+ChdyZXBlYXRlZF91aW50NjRf",
+ "d3JhcHBlchjXASADKAsyHC5nb29nbGUucHJvdG9idWYuVUludDY0VmFsdWUS",
+ "PAoWcmVwZWF0ZWRfZmxvYXRfd3JhcHBlchjYASADKAsyGy5nb29nbGUucHJv",
+ "dG9idWYuRmxvYXRWYWx1ZRI+ChdyZXBlYXRlZF9kb3VibGVfd3JhcHBlchjZ",
+ "ASADKAsyHC5nb29nbGUucHJvdG9idWYuRG91YmxlVmFsdWUSPgoXcmVwZWF0",
+ "ZWRfc3RyaW5nX3dyYXBwZXIY2gEgAygLMhwuZ29vZ2xlLnByb3RvYnVmLlN0",
+ "cmluZ1ZhbHVlEjwKFnJlcGVhdGVkX2J5dGVzX3dyYXBwZXIY2wEgAygLMhsu",
+ "Z29vZ2xlLnByb3RvYnVmLkJ5dGVzVmFsdWUSNQoRb3B0aW9uYWxfZHVyYXRp",
+ "b24YrQIgASgLMhkuZ29vZ2xlLnByb3RvYnVmLkR1cmF0aW9uEjcKEm9wdGlv",
+ "bmFsX3RpbWVzdGFtcBiuAiABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0",
+ "YW1wEjgKE29wdGlvbmFsX2ZpZWxkX21hc2sYrwIgASgLMhouZ29vZ2xlLnBy",
+ "b3RvYnVmLkZpZWxkTWFzaxIxCg9vcHRpb25hbF9zdHJ1Y3QYsAIgASgLMhcu",
+ "Z29vZ2xlLnByb3RvYnVmLlN0cnVjdBIrCgxvcHRpb25hbF9hbnkYsQIgASgL",
+ "MhQuZ29vZ2xlLnByb3RvYnVmLkFueRIvCg5vcHRpb25hbF92YWx1ZRiyAiAB",
+ "KAsyFi5nb29nbGUucHJvdG9idWYuVmFsdWUSNQoRcmVwZWF0ZWRfZHVyYXRp",
+ "b24YtwIgAygLMhkuZ29vZ2xlLnByb3RvYnVmLkR1cmF0aW9uEjcKEnJlcGVh",
+ "dGVkX3RpbWVzdGFtcBi4AiADKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0",
+ "YW1wEjcKEnJlcGVhdGVkX2ZpZWxkbWFzaxi5AiADKAsyGi5nb29nbGUucHJv",
+ "dG9idWYuRmllbGRNYXNrEjEKD3JlcGVhdGVkX3N0cnVjdBjEAiADKAsyFy5n",
+ "b29nbGUucHJvdG9idWYuU3RydWN0EisKDHJlcGVhdGVkX2FueRi7AiADKAsy",
+ "FC5nb29nbGUucHJvdG9idWYuQW55Ei8KDnJlcGVhdGVkX3ZhbHVlGLwCIAMo",
+ "CzIWLmdvb2dsZS5wcm90b2J1Zi5WYWx1ZRITCgpmaWVsZG5hbWUxGJEDIAEo",
+ "BRIUCgtmaWVsZF9uYW1lMhiSAyABKAUSFQoMX2ZpZWxkX25hbWUzGJMDIAEo",
+ "BRIWCg1maWVsZF9fbmFtZTRfGJQDIAEoBRIUCgtmaWVsZDBuYW1lNRiVAyAB",
+ "KAUSFgoNZmllbGRfMF9uYW1lNhiWAyABKAUSEwoKZmllbGROYW1lNxiXAyAB",
+ "KAUSEwoKRmllbGROYW1lOBiYAyABKAUSFAoLZmllbGRfTmFtZTkYmQMgASgF",
+ "EhUKDEZpZWxkX05hbWUxMBiaAyABKAUSFQoMRklFTERfTkFNRTExGJsDIAEo",
+ "BRIVCgxGSUVMRF9uYW1lMTIYnAMgASgFEhcKDl9fZmllbGRfbmFtZTEzGJ0D",
+ "IAEoBRIXCg5fX0ZpZWxkX25hbWUxNBieAyABKAUSFgoNZmllbGRfX25hbWUx",
+ "NRifAyABKAUSFgoNZmllbGRfX05hbWUxNhigAyABKAUSFwoOZmllbGRfbmFt",
+ "ZTE3X18YoQMgASgFEhcKDkZpZWxkX25hbWUxOF9fGKIDIAEoBRpiCg1OZXN0",
+ "ZWRNZXNzYWdlEgkKAWEYASABKAUSRgoLY29yZWN1cnNpdmUYAiABKAsyMS5w",
+ "cm90b2J1Zl90ZXN0X21lc3NhZ2VzLnByb3RvMy5UZXN0QWxsVHlwZXNQcm90",
+ "bzMaNAoSTWFwSW50MzJJbnQzMkVudHJ5EgsKA2tleRgBIAEoBRINCgV2YWx1",
+ "ZRgCIAEoBToCOAEaNAoSTWFwSW50NjRJbnQ2NEVudHJ5EgsKA2tleRgBIAEo",
+ "AxINCgV2YWx1ZRgCIAEoAzoCOAEaNgoUTWFwVWludDMyVWludDMyRW50cnkS",
+ "CwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARo2ChRNYXBVaW50NjRV",
+ "aW50NjRFbnRyeRILCgNrZXkYASABKAQSDQoFdmFsdWUYAiABKAQ6AjgBGjYK",
+ "FE1hcFNpbnQzMlNpbnQzMkVudHJ5EgsKA2tleRgBIAEoERINCgV2YWx1ZRgC",
+ "IAEoEToCOAEaNgoUTWFwU2ludDY0U2ludDY0RW50cnkSCwoDa2V5GAEgASgS",
+ "Eg0KBXZhbHVlGAIgASgSOgI4ARo4ChZNYXBGaXhlZDMyRml4ZWQzMkVudHJ5",
+ "EgsKA2tleRgBIAEoBxINCgV2YWx1ZRgCIAEoBzoCOAEaOAoWTWFwRml4ZWQ2",
+ "NEZpeGVkNjRFbnRyeRILCgNrZXkYASABKAYSDQoFdmFsdWUYAiABKAY6AjgB",
+ "GjoKGE1hcFNmaXhlZDMyU2ZpeGVkMzJFbnRyeRILCgNrZXkYASABKA8SDQoF",
+ "dmFsdWUYAiABKA86AjgBGjoKGE1hcFNmaXhlZDY0U2ZpeGVkNjRFbnRyeRIL",
+ "CgNrZXkYASABKBASDQoFdmFsdWUYAiABKBA6AjgBGjQKEk1hcEludDMyRmxv",
+ "YXRFbnRyeRILCgNrZXkYASABKAUSDQoFdmFsdWUYAiABKAI6AjgBGjUKE01h",
+ "cEludDMyRG91YmxlRW50cnkSCwoDa2V5GAEgASgFEg0KBXZhbHVlGAIgASgB",
+ "OgI4ARoyChBNYXBCb29sQm9vbEVudHJ5EgsKA2tleRgBIAEoCBINCgV2YWx1",
+ "ZRgCIAEoCDoCOAEaNgoUTWFwU3RyaW5nU3RyaW5nRW50cnkSCwoDa2V5GAEg",
+ "ASgJEg0KBXZhbHVlGAIgASgJOgI4ARo1ChNNYXBTdHJpbmdCeXRlc0VudHJ5",
+ "EgsKA2tleRgBIAEoCRINCgV2YWx1ZRgCIAEoDDoCOAEafgobTWFwU3RyaW5n",
+ "TmVzdGVkTWVzc2FnZUVudHJ5EgsKA2tleRgBIAEoCRJOCgV2YWx1ZRgCIAEo",
+ "CzI/LnByb3RvYnVmX3Rlc3RfbWVzc2FnZXMucHJvdG8zLlRlc3RBbGxUeXBl",
+ "c1Byb3RvMy5OZXN0ZWRNZXNzYWdlOgI4ARptChxNYXBTdHJpbmdGb3JlaWdu",
+ "TWVzc2FnZUVudHJ5EgsKA2tleRgBIAEoCRI8CgV2YWx1ZRgCIAEoCzItLnBy",
+ "b3RvYnVmX3Rlc3RfbWVzc2FnZXMucHJvdG8zLkZvcmVpZ25NZXNzYWdlOgI4",
+ "ARp4ChhNYXBTdHJpbmdOZXN0ZWRFbnVtRW50cnkSCwoDa2V5GAEgASgJEksK",
+ "BXZhbHVlGAIgASgOMjwucHJvdG9idWZfdGVzdF9tZXNzYWdlcy5wcm90bzMu",
+ "VGVzdEFsbFR5cGVzUHJvdG8zLk5lc3RlZEVudW06AjgBGmcKGU1hcFN0cmlu",
"Z0ZvcmVpZ25FbnVtRW50cnkSCwoDa2V5GAEgASgJEjkKBXZhbHVlGAIgASgO",
"MioucHJvdG9idWZfdGVzdF9tZXNzYWdlcy5wcm90bzMuRm9yZWlnbkVudW06",
"AjgBIjkKCk5lc3RlZEVudW0SBwoDRk9PEAASBwoDQkFSEAESBwoDQkFaEAIS",
- "EAoDTkVHEP///////////wFCDQoLb25lb2ZfZmllbGQiGwoORm9yZWlnbk1l",
- "c3NhZ2USCQoBYxgBIAEoBSpACgtGb3JlaWduRW51bRIPCgtGT1JFSUdOX0ZP",
- "TxAAEg8KC0ZPUkVJR05fQkFSEAESDwoLRk9SRUlHTl9CQVoQAkIvCihjb20u",
- "Z29vZ2xlLnByb3RvYnVmX3Rlc3RfbWVzc2FnZXMucHJvdG8zSAH4AQFiBnBy",
- "b3RvMw=="));
+ "EAoDTkVHEP///////////wFCDQoLb25lb2ZfZmllbGRKBgj1AxD/AyIbCg5G",
+ "b3JlaWduTWVzc2FnZRIJCgFjGAEgASgFKkAKC0ZvcmVpZ25FbnVtEg8KC0ZP",
+ "UkVJR05fRk9PEAASDwoLRk9SRUlHTl9CQVIQARIPCgtGT1JFSUdOX0JBWhAC",
+ "QjgKKGNvbS5nb29nbGUucHJvdG9idWZfdGVzdF9tZXNzYWdlcy5wcm90bzNI",
+ "AfgBAaICBlByb3RvM2IGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.AnyReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.DurationReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.FieldMaskReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.StructReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.WrappersReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(new[] {typeof(global::ProtobufTestMessages.Proto3.ForeignEnum), }, new pbr::GeneratedClrTypeInfo[] {
- new pbr::GeneratedClrTypeInfo(typeof(global::ProtobufTestMessages.Proto3.TestAllTypes), global::ProtobufTestMessages.Proto3.TestAllTypes.Parser, new[]{ "OptionalInt32", "OptionalInt64", "OptionalUint32", "OptionalUint64", "OptionalSint32", "OptionalSint64", "OptionalFixed32", "OptionalFixed64", "OptionalSfixed32", "OptionalSfixed64", "OptionalFloat", "OptionalDouble", "OptionalBool", "OptionalString", "OptionalBytes", "OptionalNestedMessage", "OptionalForeignMessage", "OptionalNestedEnum", "OptionalForeignEnum", "OptionalStringPiece", "OptionalCord", "RecursiveMessage", "RepeatedInt32", "RepeatedInt64", "RepeatedUint32", "RepeatedUint64", "RepeatedSint32", "RepeatedSint64", "RepeatedFixed32", "RepeatedFixed64", "RepeatedSfixed32", "RepeatedSfixed64", "RepeatedFloat", "RepeatedDouble", "RepeatedBool", "RepeatedString", "RepeatedBytes", "RepeatedNestedMessage", "RepeatedForeignMessage", "RepeatedNestedEnum", "RepeatedForeignEnum", "RepeatedStringPiece", "RepeatedCord", "MapInt32Int32", "MapInt64Int64", "MapUint32Uint32", "MapUint64Uint64", "MapSint32Sint32", "MapSint64Sint64", "MapFixed32Fixed32", "MapFixed64Fixed64", "MapSfixed32Sfixed32", "MapSfixed64Sfixed64", "MapInt32Float", "MapInt32Double", "MapBoolBool", "MapStringString", "MapStringBytes", "MapStringNestedMessage", "MapStringForeignMessage", "MapStringNestedEnum", "MapStringForeignEnum", "OneofUint32", "OneofNestedMessage", "OneofString", "OneofBytes", "OneofBool", "OneofUint64", "OneofFloat", "OneofDouble", "OneofEnum", "OptionalBoolWrapper", "OptionalInt32Wrapper", "OptionalInt64Wrapper", "OptionalUint32Wrapper", "OptionalUint64Wrapper", "OptionalFloatWrapper", "OptionalDoubleWrapper", "OptionalStringWrapper", "OptionalBytesWrapper", "RepeatedBoolWrapper", "RepeatedInt32Wrapper", "RepeatedInt64Wrapper", "RepeatedUint32Wrapper", "RepeatedUint64Wrapper", "RepeatedFloatWrapper", "RepeatedDoubleWrapper", "RepeatedStringWrapper", "RepeatedBytesWrapper", "OptionalDuration", "OptionalTimestamp", "OptionalFieldMask", "OptionalStruct", "OptionalAny", "OptionalValue", "RepeatedDuration", "RepeatedTimestamp", "RepeatedFieldmask", "RepeatedStruct", "RepeatedAny", "RepeatedValue", "Fieldname1", "FieldName2", "FieldName3", "FieldName4", "Field0Name5", "Field0Name6", "FieldName7", "FieldName8", "FieldName9", "FieldName10", "FIELDNAME11", "FIELDName12", "FieldName13", "FieldName14", "FieldName15", "FieldName16", "FieldName17", "FieldName18" }, new[]{ "OneofField" }, new[]{ typeof(global::ProtobufTestMessages.Proto3.TestAllTypes.Types.NestedEnum) }, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::ProtobufTestMessages.Proto3.TestAllTypes.Types.NestedMessage), global::ProtobufTestMessages.Proto3.TestAllTypes.Types.NestedMessage.Parser, new[]{ "A", "Corecursive" }, null, null, null),
+ new pbr::GeneratedClrTypeInfo(typeof(global::ProtobufTestMessages.Proto3.TestAllTypesProto3), global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Parser, new[]{ "OptionalInt32", "OptionalInt64", "OptionalUint32", "OptionalUint64", "OptionalSint32", "OptionalSint64", "OptionalFixed32", "OptionalFixed64", "OptionalSfixed32", "OptionalSfixed64", "OptionalFloat", "OptionalDouble", "OptionalBool", "OptionalString", "OptionalBytes", "OptionalNestedMessage", "OptionalForeignMessage", "OptionalNestedEnum", "OptionalForeignEnum", "OptionalStringPiece", "OptionalCord", "RecursiveMessage", "RepeatedInt32", "RepeatedInt64", "RepeatedUint32", "RepeatedUint64", "RepeatedSint32", "RepeatedSint64", "RepeatedFixed32", "RepeatedFixed64", "RepeatedSfixed32", "RepeatedSfixed64", "RepeatedFloat", "RepeatedDouble", "RepeatedBool", "RepeatedString", "RepeatedBytes", "RepeatedNestedMessage", "RepeatedForeignMessage", "RepeatedNestedEnum", "RepeatedForeignEnum", "RepeatedStringPiece", "RepeatedCord", "MapInt32Int32", "MapInt64Int64", "MapUint32Uint32", "MapUint64Uint64", "MapSint32Sint32", "MapSint64Sint64", "MapFixed32Fixed32", "MapFixed64Fixed64", "MapSfixed32Sfixed32", "MapSfixed64Sfixed64", "MapInt32Float", "MapInt32Double", "MapBoolBool", "MapStringString", "MapStringBytes", "MapStringNestedMessage", "MapStringForeignMessage", "MapStringNestedEnum", "MapStringForeignEnum", "OneofUint32", "OneofNestedMessage", "OneofString", "OneofBytes", "OneofBool", "OneofUint64", "OneofFloat", "OneofDouble", "OneofEnum", "OptionalBoolWrapper", "OptionalInt32Wrapper", "OptionalInt64Wrapper", "OptionalUint32Wrapper", "OptionalUint64Wrapper", "OptionalFloatWrapper", "OptionalDoubleWrapper", "OptionalStringWrapper", "OptionalBytesWrapper", "RepeatedBoolWrapper", "RepeatedInt32Wrapper", "RepeatedInt64Wrapper", "RepeatedUint32Wrapper", "RepeatedUint64Wrapper", "RepeatedFloatWrapper", "RepeatedDoubleWrapper", "RepeatedStringWrapper", "RepeatedBytesWrapper", "OptionalDuration", "OptionalTimestamp", "OptionalFieldMask", "OptionalStruct", "OptionalAny", "OptionalValue", "RepeatedDuration", "RepeatedTimestamp", "RepeatedFieldmask", "RepeatedStruct", "RepeatedAny", "RepeatedValue", "Fieldname1", "FieldName2", "FieldName3", "FieldName4", "Field0Name5", "Field0Name6", "FieldName7", "FieldName8", "FieldName9", "FieldName10", "FIELDNAME11", "FIELDName12", "FieldName13", "FieldName14", "FieldName15", "FieldName16", "FieldName17", "FieldName18" }, new[]{ "OneofField" }, new[]{ typeof(global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Types.NestedEnum) }, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Types.NestedMessage), global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Types.NestedMessage.Parser, new[]{ "A", "Corecursive" }, null, null, null),
null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, }),
new pbr::GeneratedClrTypeInfo(typeof(global::ProtobufTestMessages.Proto3.ForeignMessage), global::ProtobufTestMessages.Proto3.ForeignMessage.Parser, new[]{ "C" }, null, null, null)
}));
@@ -227,10 +231,10 @@ namespace ProtobufTestMessages.Proto3 {
/// could trigger bugs that occur in any message type in this file. We verify
/// this stays true in a unit test.
/// </summary>
- public sealed partial class TestAllTypes : pb::IMessage<TestAllTypes> {
- private static readonly pb::MessageParser<TestAllTypes> _parser = new pb::MessageParser<TestAllTypes>(() => new TestAllTypes());
+ public sealed partial class TestAllTypesProto3 : pb::IMessage<TestAllTypesProto3> {
+ private static readonly pb::MessageParser<TestAllTypesProto3> _parser = new pb::MessageParser<TestAllTypesProto3>(() => new TestAllTypesProto3());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public static pb::MessageParser<TestAllTypes> Parser { get { return _parser; } }
+ public static pb::MessageParser<TestAllTypesProto3> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
@@ -243,14 +247,14 @@ namespace ProtobufTestMessages.Proto3 {
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public TestAllTypes() {
+ public TestAllTypesProto3() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public TestAllTypes(TestAllTypes other) : this() {
+ public TestAllTypesProto3(TestAllTypesProto3 other) : this() {
optionalInt32_ = other.optionalInt32_;
optionalInt64_ = other.optionalInt64_;
optionalUint32_ = other.optionalUint32_;
@@ -394,8 +398,8 @@ namespace ProtobufTestMessages.Proto3 {
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public TestAllTypes Clone() {
- return new TestAllTypes(this);
+ public TestAllTypesProto3 Clone() {
+ return new TestAllTypesProto3(this);
}
/// <summary>Field number for the "optional_int32" field.</summary>
@@ -568,9 +572,9 @@ namespace ProtobufTestMessages.Proto3 {
/// <summary>Field number for the "optional_nested_message" field.</summary>
public const int OptionalNestedMessageFieldNumber = 18;
- private global::ProtobufTestMessages.Proto3.TestAllTypes.Types.NestedMessage optionalNestedMessage_;
+ private global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Types.NestedMessage optionalNestedMessage_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public global::ProtobufTestMessages.Proto3.TestAllTypes.Types.NestedMessage OptionalNestedMessage {
+ public global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Types.NestedMessage OptionalNestedMessage {
get { return optionalNestedMessage_; }
set {
optionalNestedMessage_ = value;
@@ -590,9 +594,9 @@ namespace ProtobufTestMessages.Proto3 {
/// <summary>Field number for the "optional_nested_enum" field.</summary>
public const int OptionalNestedEnumFieldNumber = 21;
- private global::ProtobufTestMessages.Proto3.TestAllTypes.Types.NestedEnum optionalNestedEnum_ = 0;
+ private global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Types.NestedEnum optionalNestedEnum_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public global::ProtobufTestMessages.Proto3.TestAllTypes.Types.NestedEnum OptionalNestedEnum {
+ public global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Types.NestedEnum OptionalNestedEnum {
get { return optionalNestedEnum_; }
set {
optionalNestedEnum_ = value;
@@ -634,9 +638,9 @@ namespace ProtobufTestMessages.Proto3 {
/// <summary>Field number for the "recursive_message" field.</summary>
public const int RecursiveMessageFieldNumber = 27;
- private global::ProtobufTestMessages.Proto3.TestAllTypes recursiveMessage_;
+ private global::ProtobufTestMessages.Proto3.TestAllTypesProto3 recursiveMessage_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public global::ProtobufTestMessages.Proto3.TestAllTypes RecursiveMessage {
+ public global::ProtobufTestMessages.Proto3.TestAllTypesProto3 RecursiveMessage {
get { return recursiveMessage_; }
set {
recursiveMessage_ = value;
@@ -798,11 +802,11 @@ namespace ProtobufTestMessages.Proto3 {
/// <summary>Field number for the "repeated_nested_message" field.</summary>
public const int RepeatedNestedMessageFieldNumber = 48;
- private static readonly pb::FieldCodec<global::ProtobufTestMessages.Proto3.TestAllTypes.Types.NestedMessage> _repeated_repeatedNestedMessage_codec
- = pb::FieldCodec.ForMessage(386, global::ProtobufTestMessages.Proto3.TestAllTypes.Types.NestedMessage.Parser);
- private readonly pbc::RepeatedField<global::ProtobufTestMessages.Proto3.TestAllTypes.Types.NestedMessage> repeatedNestedMessage_ = new pbc::RepeatedField<global::ProtobufTestMessages.Proto3.TestAllTypes.Types.NestedMessage>();
+ private static readonly pb::FieldCodec<global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Types.NestedMessage> _repeated_repeatedNestedMessage_codec
+ = pb::FieldCodec.ForMessage(386, global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Types.NestedMessage.Parser);
+ private readonly pbc::RepeatedField<global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Types.NestedMessage> repeatedNestedMessage_ = new pbc::RepeatedField<global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Types.NestedMessage>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public pbc::RepeatedField<global::ProtobufTestMessages.Proto3.TestAllTypes.Types.NestedMessage> RepeatedNestedMessage {
+ public pbc::RepeatedField<global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Types.NestedMessage> RepeatedNestedMessage {
get { return repeatedNestedMessage_; }
}
@@ -818,11 +822,11 @@ namespace ProtobufTestMessages.Proto3 {
/// <summary>Field number for the "repeated_nested_enum" field.</summary>
public const int RepeatedNestedEnumFieldNumber = 51;
- private static readonly pb::FieldCodec<global::ProtobufTestMessages.Proto3.TestAllTypes.Types.NestedEnum> _repeated_repeatedNestedEnum_codec
- = pb::FieldCodec.ForEnum(410, x => (int) x, x => (global::ProtobufTestMessages.Proto3.TestAllTypes.Types.NestedEnum) x);
- private readonly pbc::RepeatedField<global::ProtobufTestMessages.Proto3.TestAllTypes.Types.NestedEnum> repeatedNestedEnum_ = new pbc::RepeatedField<global::ProtobufTestMessages.Proto3.TestAllTypes.Types.NestedEnum>();
+ private static readonly pb::FieldCodec<global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Types.NestedEnum> _repeated_repeatedNestedEnum_codec
+ = pb::FieldCodec.ForEnum(410, x => (int) x, x => (global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Types.NestedEnum) x);
+ private readonly pbc::RepeatedField<global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Types.NestedEnum> repeatedNestedEnum_ = new pbc::RepeatedField<global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Types.NestedEnum>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public pbc::RepeatedField<global::ProtobufTestMessages.Proto3.TestAllTypes.Types.NestedEnum> RepeatedNestedEnum {
+ public pbc::RepeatedField<global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Types.NestedEnum> RepeatedNestedEnum {
get { return repeatedNestedEnum_; }
}
@@ -1011,11 +1015,11 @@ namespace ProtobufTestMessages.Proto3 {
/// <summary>Field number for the "map_string_nested_message" field.</summary>
public const int MapStringNestedMessageFieldNumber = 71;
- private static readonly pbc::MapField<string, global::ProtobufTestMessages.Proto3.TestAllTypes.Types.NestedMessage>.Codec _map_mapStringNestedMessage_codec
- = new pbc::MapField<string, global::ProtobufTestMessages.Proto3.TestAllTypes.Types.NestedMessage>.Codec(pb::FieldCodec.ForString(10), pb::FieldCodec.ForMessage(18, global::ProtobufTestMessages.Proto3.TestAllTypes.Types.NestedMessage.Parser), 570);
- private readonly pbc::MapField<string, global::ProtobufTestMessages.Proto3.TestAllTypes.Types.NestedMessage> mapStringNestedMessage_ = new pbc::MapField<string, global::ProtobufTestMessages.Proto3.TestAllTypes.Types.NestedMessage>();
+ private static readonly pbc::MapField<string, global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Types.NestedMessage>.Codec _map_mapStringNestedMessage_codec
+ = new pbc::MapField<string, global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Types.NestedMessage>.Codec(pb::FieldCodec.ForString(10), pb::FieldCodec.ForMessage(18, global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Types.NestedMessage.Parser), 570);
+ private readonly pbc::MapField<string, global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Types.NestedMessage> mapStringNestedMessage_ = new pbc::MapField<string, global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Types.NestedMessage>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public pbc::MapField<string, global::ProtobufTestMessages.Proto3.TestAllTypes.Types.NestedMessage> MapStringNestedMessage {
+ public pbc::MapField<string, global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Types.NestedMessage> MapStringNestedMessage {
get { return mapStringNestedMessage_; }
}
@@ -1031,11 +1035,11 @@ namespace ProtobufTestMessages.Proto3 {
/// <summary>Field number for the "map_string_nested_enum" field.</summary>
public const int MapStringNestedEnumFieldNumber = 73;
- private static readonly pbc::MapField<string, global::ProtobufTestMessages.Proto3.TestAllTypes.Types.NestedEnum>.Codec _map_mapStringNestedEnum_codec
- = new pbc::MapField<string, global::ProtobufTestMessages.Proto3.TestAllTypes.Types.NestedEnum>.Codec(pb::FieldCodec.ForString(10), pb::FieldCodec.ForEnum(16, x => (int) x, x => (global::ProtobufTestMessages.Proto3.TestAllTypes.Types.NestedEnum) x), 586);
- private readonly pbc::MapField<string, global::ProtobufTestMessages.Proto3.TestAllTypes.Types.NestedEnum> mapStringNestedEnum_ = new pbc::MapField<string, global::ProtobufTestMessages.Proto3.TestAllTypes.Types.NestedEnum>();
+ private static readonly pbc::MapField<string, global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Types.NestedEnum>.Codec _map_mapStringNestedEnum_codec
+ = new pbc::MapField<string, global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Types.NestedEnum>.Codec(pb::FieldCodec.ForString(10), pb::FieldCodec.ForEnum(16, x => (int) x, x => (global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Types.NestedEnum) x), 586);
+ private readonly pbc::MapField<string, global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Types.NestedEnum> mapStringNestedEnum_ = new pbc::MapField<string, global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Types.NestedEnum>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public pbc::MapField<string, global::ProtobufTestMessages.Proto3.TestAllTypes.Types.NestedEnum> MapStringNestedEnum {
+ public pbc::MapField<string, global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Types.NestedEnum> MapStringNestedEnum {
get { return mapStringNestedEnum_; }
}
@@ -1063,8 +1067,8 @@ namespace ProtobufTestMessages.Proto3 {
/// <summary>Field number for the "oneof_nested_message" field.</summary>
public const int OneofNestedMessageFieldNumber = 112;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public global::ProtobufTestMessages.Proto3.TestAllTypes.Types.NestedMessage OneofNestedMessage {
- get { return oneofFieldCase_ == OneofFieldOneofCase.OneofNestedMessage ? (global::ProtobufTestMessages.Proto3.TestAllTypes.Types.NestedMessage) oneofField_ : null; }
+ public global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Types.NestedMessage OneofNestedMessage {
+ get { return oneofFieldCase_ == OneofFieldOneofCase.OneofNestedMessage ? (global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Types.NestedMessage) oneofField_ : null; }
set {
oneofField_ = value;
oneofFieldCase_ = value == null ? OneofFieldOneofCase.None : OneofFieldOneofCase.OneofNestedMessage;
@@ -1140,8 +1144,8 @@ namespace ProtobufTestMessages.Proto3 {
/// <summary>Field number for the "oneof_enum" field.</summary>
public const int OneofEnumFieldNumber = 119;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public global::ProtobufTestMessages.Proto3.TestAllTypes.Types.NestedEnum OneofEnum {
- get { return oneofFieldCase_ == OneofFieldOneofCase.OneofEnum ? (global::ProtobufTestMessages.Proto3.TestAllTypes.Types.NestedEnum) oneofField_ : 0; }
+ public global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Types.NestedEnum OneofEnum {
+ get { return oneofFieldCase_ == OneofFieldOneofCase.OneofEnum ? (global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Types.NestedEnum) oneofField_ : 0; }
set {
oneofField_ = value;
oneofFieldCase_ = OneofFieldOneofCase.OneofEnum;
@@ -1705,11 +1709,11 @@ namespace ProtobufTestMessages.Proto3 {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
- return Equals(other as TestAllTypes);
+ return Equals(other as TestAllTypesProto3);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool Equals(TestAllTypes other) {
+ public bool Equals(TestAllTypesProto3 other) {
if (ReferenceEquals(other, null)) {
return false;
}
@@ -2530,7 +2534,7 @@ namespace ProtobufTestMessages.Proto3 {
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void MergeFrom(TestAllTypes other) {
+ public void MergeFrom(TestAllTypesProto3 other) {
if (other == null) {
return;
}
@@ -2581,7 +2585,7 @@ namespace ProtobufTestMessages.Proto3 {
}
if (other.optionalNestedMessage_ != null) {
if (optionalNestedMessage_ == null) {
- optionalNestedMessage_ = new global::ProtobufTestMessages.Proto3.TestAllTypes.Types.NestedMessage();
+ optionalNestedMessage_ = new global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Types.NestedMessage();
}
OptionalNestedMessage.MergeFrom(other.OptionalNestedMessage);
}
@@ -2605,7 +2609,7 @@ namespace ProtobufTestMessages.Proto3 {
}
if (other.recursiveMessage_ != null) {
if (recursiveMessage_ == null) {
- recursiveMessage_ = new global::ProtobufTestMessages.Proto3.TestAllTypes();
+ recursiveMessage_ = new global::ProtobufTestMessages.Proto3.TestAllTypesProto3();
}
RecursiveMessage.MergeFrom(other.RecursiveMessage);
}
@@ -2804,7 +2808,10 @@ namespace ProtobufTestMessages.Proto3 {
OneofUint32 = other.OneofUint32;
break;
case OneofFieldOneofCase.OneofNestedMessage:
- OneofNestedMessage = other.OneofNestedMessage;
+ if (OneofNestedMessage == null) {
+ OneofNestedMessage = new global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Types.NestedMessage();
+ }
+ OneofNestedMessage.MergeFrom(other.OneofNestedMessage);
break;
case OneofFieldOneofCase.OneofString:
OneofString = other.OneofString;
@@ -2901,7 +2908,7 @@ namespace ProtobufTestMessages.Proto3 {
}
case 146: {
if (optionalNestedMessage_ == null) {
- optionalNestedMessage_ = new global::ProtobufTestMessages.Proto3.TestAllTypes.Types.NestedMessage();
+ optionalNestedMessage_ = new global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Types.NestedMessage();
}
input.ReadMessage(optionalNestedMessage_);
break;
@@ -2914,7 +2921,7 @@ namespace ProtobufTestMessages.Proto3 {
break;
}
case 168: {
- optionalNestedEnum_ = (global::ProtobufTestMessages.Proto3.TestAllTypes.Types.NestedEnum) input.ReadEnum();
+ optionalNestedEnum_ = (global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Types.NestedEnum) input.ReadEnum();
break;
}
case 176: {
@@ -2931,7 +2938,7 @@ namespace ProtobufTestMessages.Proto3 {
}
case 218: {
if (recursiveMessage_ == null) {
- recursiveMessage_ = new global::ProtobufTestMessages.Proto3.TestAllTypes();
+ recursiveMessage_ = new global::ProtobufTestMessages.Proto3.TestAllTypesProto3();
}
input.ReadMessage(recursiveMessage_);
break;
@@ -3116,7 +3123,7 @@ namespace ProtobufTestMessages.Proto3 {
break;
}
case 898: {
- global::ProtobufTestMessages.Proto3.TestAllTypes.Types.NestedMessage subBuilder = new global::ProtobufTestMessages.Proto3.TestAllTypes.Types.NestedMessage();
+ global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Types.NestedMessage subBuilder = new global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Types.NestedMessage();
if (oneofFieldCase_ == OneofFieldOneofCase.OneofNestedMessage) {
subBuilder.MergeFrom(OneofNestedMessage);
}
@@ -3395,7 +3402,7 @@ namespace ProtobufTestMessages.Proto3 {
}
#region Nested types
- /// <summary>Container for nested types declared in the TestAllTypes message type.</summary>
+ /// <summary>Container for nested types declared in the TestAllTypesProto3 message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
public enum NestedEnum {
@@ -3415,7 +3422,7 @@ namespace ProtobufTestMessages.Proto3 {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::ProtobufTestMessages.Proto3.TestAllTypes.Descriptor.NestedTypes[0]; }
+ get { return global::ProtobufTestMessages.Proto3.TestAllTypesProto3.Descriptor.NestedTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -3454,9 +3461,9 @@ namespace ProtobufTestMessages.Proto3 {
/// <summary>Field number for the "corecursive" field.</summary>
public const int CorecursiveFieldNumber = 2;
- private global::ProtobufTestMessages.Proto3.TestAllTypes corecursive_;
+ private global::ProtobufTestMessages.Proto3.TestAllTypesProto3 corecursive_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public global::ProtobufTestMessages.Proto3.TestAllTypes Corecursive {
+ public global::ProtobufTestMessages.Proto3.TestAllTypesProto3 Corecursive {
get { return corecursive_; }
set {
corecursive_ = value;
@@ -3528,7 +3535,7 @@ namespace ProtobufTestMessages.Proto3 {
}
if (other.corecursive_ != null) {
if (corecursive_ == null) {
- corecursive_ = new global::ProtobufTestMessages.Proto3.TestAllTypes();
+ corecursive_ = new global::ProtobufTestMessages.Proto3.TestAllTypesProto3();
}
Corecursive.MergeFrom(other.Corecursive);
}
@@ -3548,7 +3555,7 @@ namespace ProtobufTestMessages.Proto3 {
}
case 18: {
if (corecursive_ == null) {
- corecursive_ = new global::ProtobufTestMessages.Proto3.TestAllTypes();
+ corecursive_ = new global::ProtobufTestMessages.Proto3.TestAllTypesProto3();
}
input.ReadMessage(corecursive_);
break;
diff --git a/csharp/src/Google.Protobuf.Test/TestProtos/UnittestCustomOptionsProto3.cs b/csharp/src/Google.Protobuf.Test/TestProtos/UnittestCustomOptionsProto3.cs
new file mode 100644
index 00000000..e21ede9c
--- /dev/null
+++ b/csharp/src/Google.Protobuf.Test/TestProtos/UnittestCustomOptionsProto3.cs
@@ -0,0 +1,2625 @@
+// Generated by the protocol buffer compiler. DO NOT EDIT!
+// source: unittest_custom_options_proto3.proto
+#pragma warning disable 1591, 0612, 3021
+#region Designer generated code
+
+using pb = global::Google.Protobuf;
+using pbc = global::Google.Protobuf.Collections;
+using pbr = global::Google.Protobuf.Reflection;
+using scg = global::System.Collections.Generic;
+namespace UnitTest.Issues.TestProtos {
+
+ /// <summary>Holder for reflection information generated from unittest_custom_options_proto3.proto</summary>
+ public static partial class UnittestCustomOptionsProto3Reflection {
+
+ #region Descriptor
+ /// <summary>File descriptor for unittest_custom_options_proto3.proto</summary>
+ public static pbr::FileDescriptor Descriptor {
+ get { return descriptor; }
+ }
+ private static pbr::FileDescriptor descriptor;
+
+ static UnittestCustomOptionsProto3Reflection() {
+ byte[] descriptorData = global::System.Convert.FromBase64String(
+ string.Concat(
+ "CiR1bml0dGVzdF9jdXN0b21fb3B0aW9uc19wcm90bzMucHJvdG8SEXByb3Rv",
+ "YnVmX3VuaXR0ZXN0GiBnb29nbGUvcHJvdG9idWYvZGVzY3JpcHRvci5wcm90",
+ "byLXAQocVGVzdE1lc3NhZ2VXaXRoQ3VzdG9tT3B0aW9ucxIeCgZmaWVsZDEY",
+ "ASABKAlCDggBweDDHS3hdQoCAAAAEhUKC29uZW9mX2ZpZWxkGAIgASgFSAAi",
+ "UwoGQW5FbnVtEhYKEkFORU5VTV9VTlNQRUNJRklFRBAAEg8KC0FORU5VTV9W",
+ "QUwxEAESFgoLQU5FTlVNX1ZBTDIQAhoFsIb6BXsaCMX2yR3r/P//OhAIAODp",
+ "wh3I//////////8BQhkKB0FuT25lb2YSDviswx2d//////////8BIhgKFkN1",
+ "c3RvbU9wdGlvbkZvb1JlcXVlc3QiGQoXQ3VzdG9tT3B0aW9uRm9vUmVzcG9u",
+ "c2UiHgocQ3VzdG9tT3B0aW9uRm9vQ2xpZW50TWVzc2FnZSIeChxDdXN0b21P",
+ "cHRpb25Gb29TZXJ2ZXJNZXNzYWdlIo8BChpEdW1teU1lc3NhZ2VDb250YWlu",
+ "aW5nRW51bSJxCgxUZXN0RW51bVR5cGUSIAocVEVTVF9PUFRJT05fRU5VTV9V",
+ "TlNQRUNJRklFRBAAEhoKFlRFU1RfT1BUSU9OX0VOVU1fVFlQRTEQFhIjChZU",
+ "RVNUX09QVElPTl9FTlVNX1RZUEUyEOn//////////wEiIQofRHVtbXlNZXNz",
+ "YWdlSW52YWxpZEFzT3B0aW9uVHlwZSKKAQocQ3VzdG9tT3B0aW9uTWluSW50",
+ "ZWdlclZhbHVlczpq0N6yHQDoxrIdgICAgPj/////AbC8sh2AgICAgICAgIAB",
+ "gJOyHQD49bAdAIDEsB3/////D/iXsB3///////////8BnfWvHQAAAACR7q8d",
+ "AAAAAAAAAACtja8dAAAAgJnWqB0AAAAAAAAAgCKRAQocQ3VzdG9tT3B0aW9u",
+ "TWF4SW50ZWdlclZhbHVlczpx0N6yHQHoxrId/////wewvLId//////////9/",
+ "gJOyHf////8P+PWwHf///////////wGAxLAd/v///w/4l7Ad/v//////////",
+ "AZ31rx3/////ke6vHf//////////rY2vHf///3+Z1qgd/////////38ibgoX",
+ "Q3VzdG9tT3B0aW9uT3RoZXJWYWx1ZXM6U+jGsh2c//////////8B9d+jHeeH",
+ "RUHp3KId+1mMQsrA8z+q3KIdDkhlbGxvLCAiV29ybGQistmiHQtIZWxsbwBX",
+ "b3JsZIjZoh3p//////////8BIjQKHFNldHRpbmdSZWFsc0Zyb21Qb3NpdGl2",
+ "ZUludHM6FPXfox0AAEBB6dyiHQAAAAAAQGNAIjQKHFNldHRpbmdSZWFsc0Zy",
+ "b21OZWdhdGl2ZUludHM6FPXfox0AAEDB6dyiHQAAAAAAQGPAIksKEkNvbXBs",
+ "ZXhPcHRpb25UeXBlMRILCgNmb28YASABKAUSDAoEZm9vMhgCIAEoBRIMCgRm",
+ "b28zGAMgASgFEgwKBGZvbzQYBCADKAUigQMKEkNvbXBsZXhPcHRpb25UeXBl",
+ "MhIyCgNiYXIYASABKAsyJS5wcm90b2J1Zl91bml0dGVzdC5Db21wbGV4T3B0",
+ "aW9uVHlwZTESCwoDYmF6GAIgASgFEkYKBGZyZWQYAyABKAsyOC5wcm90b2J1",
+ "Zl91bml0dGVzdC5Db21wbGV4T3B0aW9uVHlwZTIuQ29tcGxleE9wdGlvblR5",
+ "cGU0EkgKBmJhcm5leRgEIAMoCzI4LnByb3RvYnVmX3VuaXR0ZXN0LkNvbXBs",
+ "ZXhPcHRpb25UeXBlMi5Db21wbGV4T3B0aW9uVHlwZTQalwEKEkNvbXBsZXhP",
+ "cHRpb25UeXBlNBINCgV3YWxkbxgBIAEoBTJyCgxjb21wbGV4X29wdDQSHy5n",
+ "b29nbGUucHJvdG9idWYuTWVzc2FnZU9wdGlvbnMYivXRAyABKAsyOC5wcm90",
+ "b2J1Zl91bml0dGVzdC5Db21wbGV4T3B0aW9uVHlwZTIuQ29tcGxleE9wdGlv",
+ "blR5cGU0IiEKEkNvbXBsZXhPcHRpb25UeXBlMxILCgNxdXgYASABKAUibAoV",
+ "VmFyaW91c0NvbXBsZXhPcHRpb25zOlOi4pUdAggqouKVHQIgY6LilR0CIFiq",
+ "/ZAdAxDbB6r9kB0FCgMI5wXSqI8dAwizD6r9kB0FGgMIwQKq/ZAdBCICCGWq",
+ "/ZAdBSIDCNQB+t6QHQIICSJMCglBZ2dyZWdhdGUSCQoBaRgBIAEoBRIJCgFz",
+ "GAIgASgJEikKA3N1YhgDIAEoCzIcLnByb3RvYnVmX3VuaXR0ZXN0LkFnZ3Jl",
+ "Z2F0ZSJZChBBZ2dyZWdhdGVNZXNzYWdlEikKCWZpZWxkbmFtZRgBIAEoBUIW",
+ "8qGHOxESD0ZpZWxkQW5ub3RhdGlvbjoawtGGOxUIZRIRTWVzc2FnZUFubm90",
+ "YXRpb24ilwEKEE5lc3RlZE9wdGlvblR5cGUaOwoNTmVzdGVkTWVzc2FnZRIi",
+ "CgxuZXN0ZWRfZmllbGQYASABKAVCDMHgwx3qAwAAAAAAADoG4OnCHekHIkYK",
+ "Ck5lc3RlZEVudW0SDwoLVU5TUEVDSUZJRUQQABIdChFORVNURURfRU5VTV9W",
+ "QUxVRRABGgawhvoF7AcaCMX2yR3rAwAAKlIKCk1ldGhvZE9wdDESGgoWTUVU",
+ "SE9ET1BUMV9VTlNQRUNJRklFRBAAEhMKD01FVEhPRE9QVDFfVkFMMRABEhMK",
+ "D01FVEhPRE9QVDFfVkFMMhACKl4KDUFnZ3JlZ2F0ZUVudW0SDwoLVU5TUEVD",
+ "SUZJRUQQABIlCgVWQUxVRRABGhrK/Ik7FRITRW51bVZhbHVlQW5ub3RhdGlv",
+ "bhoVkpWIOxASDkVudW1Bbm5vdGF0aW9uMo4BChxUZXN0U2VydmljZVdpdGhD",
+ "dXN0b21PcHRpb25zEmMKA0ZvbxIpLnByb3RvYnVmX3VuaXR0ZXN0LkN1c3Rv",
+ "bU9wdGlvbkZvb1JlcXVlc3QaKi5wcm90b2J1Zl91bml0dGVzdC5DdXN0b21P",
+ "cHRpb25Gb29SZXNwb25zZSIF4PqMHgIaCZCyix7T24DLSTKZAQoQQWdncmVn",
+ "YXRlU2VydmljZRJrCgZNZXRob2QSIy5wcm90b2J1Zl91bml0dGVzdC5BZ2dy",
+ "ZWdhdGVNZXNzYWdlGiMucHJvdG9idWZfdW5pdHRlc3QuQWdncmVnYXRlTWVz",
+ "c2FnZSIXysiWOxISEE1ldGhvZEFubm90YXRpb24aGMr7jjsTEhFTZXJ2aWNl",
+ "QW5ub3RhdGlvbjoyCglmaWxlX29wdDESHC5nb29nbGUucHJvdG9idWYuRmls",
+ "ZU9wdGlvbnMYjp3YAyABKAQ6OAoMbWVzc2FnZV9vcHQxEh8uZ29vZ2xlLnBy",
+ "b3RvYnVmLk1lc3NhZ2VPcHRpb25zGJyt2AMgASgFOjQKCmZpZWxkX29wdDES",
+ "HS5nb29nbGUucHJvdG9idWYuRmllbGRPcHRpb25zGIi82AMgASgGOjQKCm9u",
+ "ZW9mX29wdDESHS5nb29nbGUucHJvdG9idWYuT25lb2ZPcHRpb25zGM+12AMg",
+ "ASgFOjIKCWVudW1fb3B0MRIcLmdvb2dsZS5wcm90b2J1Zi5FbnVtT3B0aW9u",
+ "cxjontkDIAEoDzo8Cg9lbnVtX3ZhbHVlX29wdDESIS5nb29nbGUucHJvdG9i",
+ "dWYuRW51bVZhbHVlT3B0aW9ucxjmoF8gASgFOjgKDHNlcnZpY2Vfb3B0MRIf",
+ "Lmdvb2dsZS5wcm90b2J1Zi5TZXJ2aWNlT3B0aW9ucxiituEDIAEoEjpVCgtt",
+ "ZXRob2Rfb3B0MRIeLmdvb2dsZS5wcm90b2J1Zi5NZXRob2RPcHRpb25zGKzP",
+ "4QMgASgOMh0ucHJvdG9idWZfdW5pdHRlc3QuTWV0aG9kT3B0MTo0Cghib29s",
+ "X29wdBIfLmdvb2dsZS5wcm90b2J1Zi5NZXNzYWdlT3B0aW9ucxjqq9YDIAEo",
+ "CDo1CglpbnQzMl9vcHQSHy5nb29nbGUucHJvdG9idWYuTWVzc2FnZU9wdGlv",
+ "bnMY7ajWAyABKAU6NQoJaW50NjRfb3B0Eh8uZ29vZ2xlLnByb3RvYnVmLk1l",
+ "c3NhZ2VPcHRpb25zGMan1gMgASgDOjYKCnVpbnQzMl9vcHQSHy5nb29nbGUu",
+ "cHJvdG9idWYuTWVzc2FnZU9wdGlvbnMYsKLWAyABKA06NgoKdWludDY0X29w",
+ "dBIfLmdvb2dsZS5wcm90b2J1Zi5NZXNzYWdlT3B0aW9ucxjfjtYDIAEoBDo2",
+ "CgpzaW50MzJfb3B0Eh8uZ29vZ2xlLnByb3RvYnVmLk1lc3NhZ2VPcHRpb25z",
+ "GMCI1gMgASgROjYKCnNpbnQ2NF9vcHQSHy5nb29nbGUucHJvdG9idWYuTWVz",
+ "c2FnZU9wdGlvbnMY/4LWAyABKBI6NwoLZml4ZWQzMl9vcHQSHy5nb29nbGUu",
+ "cHJvdG9idWYuTWVzc2FnZU9wdGlvbnMY0/7VAyABKAc6NwoLZml4ZWQ2NF9v",
+ "cHQSHy5nb29nbGUucHJvdG9idWYuTWVzc2FnZU9wdGlvbnMY4v3VAyABKAY6",
+ "OAoMc2ZpeGVkMzJfb3B0Eh8uZ29vZ2xlLnByb3RvYnVmLk1lc3NhZ2VPcHRp",
+ "b25zGNXx1QMgASgPOjgKDHNmaXhlZDY0X29wdBIfLmdvb2dsZS5wcm90b2J1",
+ "Zi5NZXNzYWdlT3B0aW9ucxjjitUDIAEoEDo1CglmbG9hdF9vcHQSHy5nb29n",
+ "bGUucHJvdG9idWYuTWVzc2FnZU9wdGlvbnMY/rvUAyABKAI6NgoKZG91Ymxl",
+ "X29wdBIfLmdvb2dsZS5wcm90b2J1Zi5NZXNzYWdlT3B0aW9ucxjNq9QDIAEo",
+ "ATo2CgpzdHJpbmdfb3B0Eh8uZ29vZ2xlLnByb3RvYnVmLk1lc3NhZ2VPcHRp",
+ "b25zGMWr1AMgASgJOjUKCWJ5dGVzX29wdBIfLmdvb2dsZS5wcm90b2J1Zi5N",
+ "ZXNzYWdlT3B0aW9ucxiWq9QDIAEoDDpwCghlbnVtX29wdBIfLmdvb2dsZS5w",
+ "cm90b2J1Zi5NZXNzYWdlT3B0aW9ucxiRq9QDIAEoDjI6LnByb3RvYnVmX3Vu",
+ "aXR0ZXN0LkR1bW15TWVzc2FnZUNvbnRhaW5pbmdFbnVtLlRlc3RFbnVtVHlw",
+ "ZTpwChBtZXNzYWdlX3R5cGVfb3B0Eh8uZ29vZ2xlLnByb3RvYnVmLk1lc3Nh",
+ "Z2VPcHRpb25zGK/y0wMgASgLMjIucHJvdG9idWZfdW5pdHRlc3QuRHVtbXlN",
+ "ZXNzYWdlSW52YWxpZEFzT3B0aW9uVHlwZTpfCgxjb21wbGV4X29wdDESHy5n",
+ "b29nbGUucHJvdG9idWYuTWVzc2FnZU9wdGlvbnMYpNzSAyABKAsyJS5wcm90",
+ "b2J1Zl91bml0dGVzdC5Db21wbGV4T3B0aW9uVHlwZTE6XwoMY29tcGxleF9v",
+ "cHQyEh8uZ29vZ2xlLnByb3RvYnVmLk1lc3NhZ2VPcHRpb25zGNWP0gMgASgL",
+ "MiUucHJvdG9idWZfdW5pdHRlc3QuQ29tcGxleE9wdGlvblR5cGUyOl8KDGNv",
+ "bXBsZXhfb3B0MxIfLmdvb2dsZS5wcm90b2J1Zi5NZXNzYWdlT3B0aW9ucxjv",
+ "i9IDIAEoCzIlLnByb3RvYnVmX3VuaXR0ZXN0LkNvbXBsZXhPcHRpb25UeXBl",
+ "MzpOCgdmaWxlb3B0EhwuZ29vZ2xlLnByb3RvYnVmLkZpbGVPcHRpb25zGM/d",
+ "sAcgASgLMhwucHJvdG9idWZfdW5pdHRlc3QuQWdncmVnYXRlOlAKBm1zZ29w",
+ "dBIfLmdvb2dsZS5wcm90b2J1Zi5NZXNzYWdlT3B0aW9ucxiY6rAHIAEoCzIc",
+ "LnByb3RvYnVmX3VuaXR0ZXN0LkFnZ3JlZ2F0ZTpQCghmaWVsZG9wdBIdLmdv",
+ "b2dsZS5wcm90b2J1Zi5GaWVsZE9wdGlvbnMYnvSwByABKAsyHC5wcm90b2J1",
+ "Zl91bml0dGVzdC5BZ2dyZWdhdGU6TgoHZW51bW9wdBIcLmdvb2dsZS5wcm90",
+ "b2J1Zi5FbnVtT3B0aW9ucxjSgrEHIAEoCzIcLnByb3RvYnVmX3VuaXR0ZXN0",
+ "LkFnZ3JlZ2F0ZTpWCgplbnVtdmFsb3B0EiEuZ29vZ2xlLnByb3RvYnVmLkVu",
+ "dW1WYWx1ZU9wdGlvbnMYyZ+xByABKAsyHC5wcm90b2J1Zl91bml0dGVzdC5B",
+ "Z2dyZWdhdGU6VAoKc2VydmljZW9wdBIfLmdvb2dsZS5wcm90b2J1Zi5TZXJ2",
+ "aWNlT3B0aW9ucxi577EHIAEoCzIcLnByb3RvYnVmX3VuaXR0ZXN0LkFnZ3Jl",
+ "Z2F0ZTpSCgltZXRob2RvcHQSHi5nb29nbGUucHJvdG9idWYuTWV0aG9kT3B0",
+ "aW9ucxiJ6bIHIAEoCzIcLnByb3RvYnVmX3VuaXR0ZXN0LkFnZ3JlZ2F0ZUJV",
+ "qgIaVW5pdFRlc3QuSXNzdWVzLlRlc3RQcm90b3Pw6MEd6q3A5ST67IU7Kghk",
+ "Eg5GaWxlQW5ub3RhdGlvbhoWEhROZXN0ZWRGaWxlQW5ub3RhdGlvbmIGcHJv",
+ "dG8z"));
+ descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
+ new pbr::FileDescriptor[] { pbr::FileDescriptor.DescriptorProtoFileDescriptor, },
+ new pbr::GeneratedClrTypeInfo(new[] {typeof(global::UnitTest.Issues.TestProtos.MethodOpt1), typeof(global::UnitTest.Issues.TestProtos.AggregateEnum), }, new pbr::GeneratedClrTypeInfo[] {
+ new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.TestMessageWithCustomOptions), global::UnitTest.Issues.TestProtos.TestMessageWithCustomOptions.Parser, new[]{ "Field1", "OneofField" }, new[]{ "AnOneof" }, new[]{ typeof(global::UnitTest.Issues.TestProtos.TestMessageWithCustomOptions.Types.AnEnum) }, null),
+ new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.CustomOptionFooRequest), global::UnitTest.Issues.TestProtos.CustomOptionFooRequest.Parser, null, null, null, null),
+ new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.CustomOptionFooResponse), global::UnitTest.Issues.TestProtos.CustomOptionFooResponse.Parser, null, null, null, null),
+ new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.CustomOptionFooClientMessage), global::UnitTest.Issues.TestProtos.CustomOptionFooClientMessage.Parser, null, null, null, null),
+ new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.CustomOptionFooServerMessage), global::UnitTest.Issues.TestProtos.CustomOptionFooServerMessage.Parser, null, null, null, null),
+ new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.DummyMessageContainingEnum), global::UnitTest.Issues.TestProtos.DummyMessageContainingEnum.Parser, null, null, new[]{ typeof(global::UnitTest.Issues.TestProtos.DummyMessageContainingEnum.Types.TestEnumType) }, null),
+ new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.DummyMessageInvalidAsOptionType), global::UnitTest.Issues.TestProtos.DummyMessageInvalidAsOptionType.Parser, null, null, null, null),
+ new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.CustomOptionMinIntegerValues), global::UnitTest.Issues.TestProtos.CustomOptionMinIntegerValues.Parser, null, null, null, null),
+ new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.CustomOptionMaxIntegerValues), global::UnitTest.Issues.TestProtos.CustomOptionMaxIntegerValues.Parser, null, null, null, null),
+ new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.CustomOptionOtherValues), global::UnitTest.Issues.TestProtos.CustomOptionOtherValues.Parser, null, null, null, null),
+ new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.SettingRealsFromPositiveInts), global::UnitTest.Issues.TestProtos.SettingRealsFromPositiveInts.Parser, null, null, null, null),
+ new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.SettingRealsFromNegativeInts), global::UnitTest.Issues.TestProtos.SettingRealsFromNegativeInts.Parser, null, null, null, null),
+ new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.ComplexOptionType1), global::UnitTest.Issues.TestProtos.ComplexOptionType1.Parser, new[]{ "Foo", "Foo2", "Foo3", "Foo4" }, null, null, null),
+ new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.ComplexOptionType2), global::UnitTest.Issues.TestProtos.ComplexOptionType2.Parser, new[]{ "Bar", "Baz", "Fred", "Barney" }, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.ComplexOptionType2.Types.ComplexOptionType4), global::UnitTest.Issues.TestProtos.ComplexOptionType2.Types.ComplexOptionType4.Parser, new[]{ "Waldo" }, null, null, null)}),
+ new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.ComplexOptionType3), global::UnitTest.Issues.TestProtos.ComplexOptionType3.Parser, new[]{ "Qux" }, null, null, null),
+ new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.VariousComplexOptions), global::UnitTest.Issues.TestProtos.VariousComplexOptions.Parser, null, null, null, null),
+ new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.Aggregate), global::UnitTest.Issues.TestProtos.Aggregate.Parser, new[]{ "I", "S", "Sub" }, null, null, null),
+ new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.AggregateMessage), global::UnitTest.Issues.TestProtos.AggregateMessage.Parser, new[]{ "Fieldname" }, null, null, null),
+ new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.NestedOptionType), global::UnitTest.Issues.TestProtos.NestedOptionType.Parser, null, null, new[]{ typeof(global::UnitTest.Issues.TestProtos.NestedOptionType.Types.NestedEnum) }, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.NestedOptionType.Types.NestedMessage), global::UnitTest.Issues.TestProtos.NestedOptionType.Types.NestedMessage.Parser, new[]{ "NestedField" }, null, null, null)})
+ }));
+ }
+ #endregion
+
+ }
+ #region Enums
+ public enum MethodOpt1 {
+ [pbr::OriginalName("METHODOPT1_UNSPECIFIED")] Unspecified = 0,
+ [pbr::OriginalName("METHODOPT1_VAL1")] Val1 = 1,
+ [pbr::OriginalName("METHODOPT1_VAL2")] Val2 = 2,
+ }
+
+ public enum AggregateEnum {
+ [pbr::OriginalName("UNSPECIFIED")] Unspecified = 0,
+ [pbr::OriginalName("VALUE")] Value = 1,
+ }
+
+ #endregion
+
+ #region Messages
+ /// <summary>
+ /// A test message with custom options at all possible locations (and also some
+ /// regular options, to make sure they interact nicely).
+ /// </summary>
+ public sealed partial class TestMessageWithCustomOptions : pb::IMessage<TestMessageWithCustomOptions> {
+ private static readonly pb::MessageParser<TestMessageWithCustomOptions> _parser = new pb::MessageParser<TestMessageWithCustomOptions>(() => new TestMessageWithCustomOptions());
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pb::MessageParser<TestMessageWithCustomOptions> Parser { get { return _parser; } }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::UnitTest.Issues.TestProtos.UnittestCustomOptionsProto3Reflection.Descriptor.MessageTypes[0]; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public TestMessageWithCustomOptions() {
+ OnConstruction();
+ }
+
+ partial void OnConstruction();
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public TestMessageWithCustomOptions(TestMessageWithCustomOptions other) : this() {
+ field1_ = other.field1_;
+ switch (other.AnOneofCase) {
+ case AnOneofOneofCase.OneofField:
+ OneofField = other.OneofField;
+ break;
+ }
+
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public TestMessageWithCustomOptions Clone() {
+ return new TestMessageWithCustomOptions(this);
+ }
+
+ /// <summary>Field number for the "field1" field.</summary>
+ public const int Field1FieldNumber = 1;
+ private string field1_ = "";
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public string Field1 {
+ get { return field1_; }
+ set {
+ field1_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
+ }
+ }
+
+ /// <summary>Field number for the "oneof_field" field.</summary>
+ public const int OneofFieldFieldNumber = 2;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int OneofField {
+ get { return anOneofCase_ == AnOneofOneofCase.OneofField ? (int) anOneof_ : 0; }
+ set {
+ anOneof_ = value;
+ anOneofCase_ = AnOneofOneofCase.OneofField;
+ }
+ }
+
+ private object anOneof_;
+ /// <summary>Enum of possible cases for the "AnOneof" oneof.</summary>
+ public enum AnOneofOneofCase {
+ None = 0,
+ OneofField = 2,
+ }
+ private AnOneofOneofCase anOneofCase_ = AnOneofOneofCase.None;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public AnOneofOneofCase AnOneofCase {
+ get { return anOneofCase_; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void ClearAnOneof() {
+ anOneofCase_ = AnOneofOneofCase.None;
+ anOneof_ = null;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override bool Equals(object other) {
+ return Equals(other as TestMessageWithCustomOptions);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool Equals(TestMessageWithCustomOptions other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
+ }
+ if (ReferenceEquals(other, this)) {
+ return true;
+ }
+ if (Field1 != other.Field1) return false;
+ if (OneofField != other.OneofField) return false;
+ if (AnOneofCase != other.AnOneofCase) return false;
+ return true;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override int GetHashCode() {
+ int hash = 1;
+ if (Field1.Length != 0) hash ^= Field1.GetHashCode();
+ if (anOneofCase_ == AnOneofOneofCase.OneofField) hash ^= OneofField.GetHashCode();
+ hash ^= (int) anOneofCase_;
+ return hash;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override string ToString() {
+ return pb::JsonFormatter.ToDiagnosticString(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void WriteTo(pb::CodedOutputStream output) {
+ if (Field1.Length != 0) {
+ output.WriteRawTag(10);
+ output.WriteString(Field1);
+ }
+ if (anOneofCase_ == AnOneofOneofCase.OneofField) {
+ output.WriteRawTag(16);
+ output.WriteInt32(OneofField);
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int CalculateSize() {
+ int size = 0;
+ if (Field1.Length != 0) {
+ size += 1 + pb::CodedOutputStream.ComputeStringSize(Field1);
+ }
+ if (anOneofCase_ == AnOneofOneofCase.OneofField) {
+ size += 1 + pb::CodedOutputStream.ComputeInt32Size(OneofField);
+ }
+ return size;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(TestMessageWithCustomOptions other) {
+ if (other == null) {
+ return;
+ }
+ if (other.Field1.Length != 0) {
+ Field1 = other.Field1;
+ }
+ switch (other.AnOneofCase) {
+ case AnOneofOneofCase.OneofField:
+ OneofField = other.OneofField;
+ break;
+ }
+
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ case 10: {
+ Field1 = input.ReadString();
+ break;
+ }
+ case 16: {
+ OneofField = input.ReadInt32();
+ break;
+ }
+ }
+ }
+ }
+
+ #region Nested types
+ /// <summary>Container for nested types declared in the TestMessageWithCustomOptions message type.</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static partial class Types {
+ public enum AnEnum {
+ [pbr::OriginalName("ANENUM_UNSPECIFIED")] Unspecified = 0,
+ [pbr::OriginalName("ANENUM_VAL1")] Val1 = 1,
+ [pbr::OriginalName("ANENUM_VAL2")] Val2 = 2,
+ }
+
+ }
+ #endregion
+
+ }
+
+ /// <summary>
+ /// A test RPC service with custom options at all possible locations (and also
+ /// some regular options, to make sure they interact nicely).
+ /// </summary>
+ public sealed partial class CustomOptionFooRequest : pb::IMessage<CustomOptionFooRequest> {
+ private static readonly pb::MessageParser<CustomOptionFooRequest> _parser = new pb::MessageParser<CustomOptionFooRequest>(() => new CustomOptionFooRequest());
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pb::MessageParser<CustomOptionFooRequest> Parser { get { return _parser; } }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::UnitTest.Issues.TestProtos.UnittestCustomOptionsProto3Reflection.Descriptor.MessageTypes[1]; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public CustomOptionFooRequest() {
+ OnConstruction();
+ }
+
+ partial void OnConstruction();
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public CustomOptionFooRequest(CustomOptionFooRequest other) : this() {
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public CustomOptionFooRequest Clone() {
+ return new CustomOptionFooRequest(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override bool Equals(object other) {
+ return Equals(other as CustomOptionFooRequest);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool Equals(CustomOptionFooRequest other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
+ }
+ if (ReferenceEquals(other, this)) {
+ return true;
+ }
+ return true;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override int GetHashCode() {
+ int hash = 1;
+ return hash;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override string ToString() {
+ return pb::JsonFormatter.ToDiagnosticString(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void WriteTo(pb::CodedOutputStream output) {
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int CalculateSize() {
+ int size = 0;
+ return size;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(CustomOptionFooRequest other) {
+ if (other == null) {
+ return;
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ }
+ }
+ }
+
+ }
+
+ public sealed partial class CustomOptionFooResponse : pb::IMessage<CustomOptionFooResponse> {
+ private static readonly pb::MessageParser<CustomOptionFooResponse> _parser = new pb::MessageParser<CustomOptionFooResponse>(() => new CustomOptionFooResponse());
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pb::MessageParser<CustomOptionFooResponse> Parser { get { return _parser; } }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::UnitTest.Issues.TestProtos.UnittestCustomOptionsProto3Reflection.Descriptor.MessageTypes[2]; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public CustomOptionFooResponse() {
+ OnConstruction();
+ }
+
+ partial void OnConstruction();
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public CustomOptionFooResponse(CustomOptionFooResponse other) : this() {
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public CustomOptionFooResponse Clone() {
+ return new CustomOptionFooResponse(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override bool Equals(object other) {
+ return Equals(other as CustomOptionFooResponse);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool Equals(CustomOptionFooResponse other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
+ }
+ if (ReferenceEquals(other, this)) {
+ return true;
+ }
+ return true;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override int GetHashCode() {
+ int hash = 1;
+ return hash;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override string ToString() {
+ return pb::JsonFormatter.ToDiagnosticString(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void WriteTo(pb::CodedOutputStream output) {
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int CalculateSize() {
+ int size = 0;
+ return size;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(CustomOptionFooResponse other) {
+ if (other == null) {
+ return;
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ }
+ }
+ }
+
+ }
+
+ public sealed partial class CustomOptionFooClientMessage : pb::IMessage<CustomOptionFooClientMessage> {
+ private static readonly pb::MessageParser<CustomOptionFooClientMessage> _parser = new pb::MessageParser<CustomOptionFooClientMessage>(() => new CustomOptionFooClientMessage());
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pb::MessageParser<CustomOptionFooClientMessage> Parser { get { return _parser; } }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::UnitTest.Issues.TestProtos.UnittestCustomOptionsProto3Reflection.Descriptor.MessageTypes[3]; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public CustomOptionFooClientMessage() {
+ OnConstruction();
+ }
+
+ partial void OnConstruction();
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public CustomOptionFooClientMessage(CustomOptionFooClientMessage other) : this() {
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public CustomOptionFooClientMessage Clone() {
+ return new CustomOptionFooClientMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override bool Equals(object other) {
+ return Equals(other as CustomOptionFooClientMessage);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool Equals(CustomOptionFooClientMessage other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
+ }
+ if (ReferenceEquals(other, this)) {
+ return true;
+ }
+ return true;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override int GetHashCode() {
+ int hash = 1;
+ return hash;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override string ToString() {
+ return pb::JsonFormatter.ToDiagnosticString(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void WriteTo(pb::CodedOutputStream output) {
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int CalculateSize() {
+ int size = 0;
+ return size;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(CustomOptionFooClientMessage other) {
+ if (other == null) {
+ return;
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ }
+ }
+ }
+
+ }
+
+ public sealed partial class CustomOptionFooServerMessage : pb::IMessage<CustomOptionFooServerMessage> {
+ private static readonly pb::MessageParser<CustomOptionFooServerMessage> _parser = new pb::MessageParser<CustomOptionFooServerMessage>(() => new CustomOptionFooServerMessage());
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pb::MessageParser<CustomOptionFooServerMessage> Parser { get { return _parser; } }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::UnitTest.Issues.TestProtos.UnittestCustomOptionsProto3Reflection.Descriptor.MessageTypes[4]; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public CustomOptionFooServerMessage() {
+ OnConstruction();
+ }
+
+ partial void OnConstruction();
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public CustomOptionFooServerMessage(CustomOptionFooServerMessage other) : this() {
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public CustomOptionFooServerMessage Clone() {
+ return new CustomOptionFooServerMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override bool Equals(object other) {
+ return Equals(other as CustomOptionFooServerMessage);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool Equals(CustomOptionFooServerMessage other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
+ }
+ if (ReferenceEquals(other, this)) {
+ return true;
+ }
+ return true;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override int GetHashCode() {
+ int hash = 1;
+ return hash;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override string ToString() {
+ return pb::JsonFormatter.ToDiagnosticString(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void WriteTo(pb::CodedOutputStream output) {
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int CalculateSize() {
+ int size = 0;
+ return size;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(CustomOptionFooServerMessage other) {
+ if (other == null) {
+ return;
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ }
+ }
+ }
+
+ }
+
+ public sealed partial class DummyMessageContainingEnum : pb::IMessage<DummyMessageContainingEnum> {
+ private static readonly pb::MessageParser<DummyMessageContainingEnum> _parser = new pb::MessageParser<DummyMessageContainingEnum>(() => new DummyMessageContainingEnum());
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pb::MessageParser<DummyMessageContainingEnum> Parser { get { return _parser; } }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::UnitTest.Issues.TestProtos.UnittestCustomOptionsProto3Reflection.Descriptor.MessageTypes[5]; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public DummyMessageContainingEnum() {
+ OnConstruction();
+ }
+
+ partial void OnConstruction();
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public DummyMessageContainingEnum(DummyMessageContainingEnum other) : this() {
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public DummyMessageContainingEnum Clone() {
+ return new DummyMessageContainingEnum(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override bool Equals(object other) {
+ return Equals(other as DummyMessageContainingEnum);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool Equals(DummyMessageContainingEnum other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
+ }
+ if (ReferenceEquals(other, this)) {
+ return true;
+ }
+ return true;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override int GetHashCode() {
+ int hash = 1;
+ return hash;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override string ToString() {
+ return pb::JsonFormatter.ToDiagnosticString(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void WriteTo(pb::CodedOutputStream output) {
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int CalculateSize() {
+ int size = 0;
+ return size;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(DummyMessageContainingEnum other) {
+ if (other == null) {
+ return;
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ }
+ }
+ }
+
+ #region Nested types
+ /// <summary>Container for nested types declared in the DummyMessageContainingEnum message type.</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static partial class Types {
+ public enum TestEnumType {
+ [pbr::OriginalName("TEST_OPTION_ENUM_UNSPECIFIED")] TestOptionEnumUnspecified = 0,
+ [pbr::OriginalName("TEST_OPTION_ENUM_TYPE1")] TestOptionEnumType1 = 22,
+ [pbr::OriginalName("TEST_OPTION_ENUM_TYPE2")] TestOptionEnumType2 = -23,
+ }
+
+ }
+ #endregion
+
+ }
+
+ public sealed partial class DummyMessageInvalidAsOptionType : pb::IMessage<DummyMessageInvalidAsOptionType> {
+ private static readonly pb::MessageParser<DummyMessageInvalidAsOptionType> _parser = new pb::MessageParser<DummyMessageInvalidAsOptionType>(() => new DummyMessageInvalidAsOptionType());
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pb::MessageParser<DummyMessageInvalidAsOptionType> Parser { get { return _parser; } }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::UnitTest.Issues.TestProtos.UnittestCustomOptionsProto3Reflection.Descriptor.MessageTypes[6]; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public DummyMessageInvalidAsOptionType() {
+ OnConstruction();
+ }
+
+ partial void OnConstruction();
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public DummyMessageInvalidAsOptionType(DummyMessageInvalidAsOptionType other) : this() {
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public DummyMessageInvalidAsOptionType Clone() {
+ return new DummyMessageInvalidAsOptionType(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override bool Equals(object other) {
+ return Equals(other as DummyMessageInvalidAsOptionType);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool Equals(DummyMessageInvalidAsOptionType other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
+ }
+ if (ReferenceEquals(other, this)) {
+ return true;
+ }
+ return true;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override int GetHashCode() {
+ int hash = 1;
+ return hash;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override string ToString() {
+ return pb::JsonFormatter.ToDiagnosticString(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void WriteTo(pb::CodedOutputStream output) {
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int CalculateSize() {
+ int size = 0;
+ return size;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(DummyMessageInvalidAsOptionType other) {
+ if (other == null) {
+ return;
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ }
+ }
+ }
+
+ }
+
+ public sealed partial class CustomOptionMinIntegerValues : pb::IMessage<CustomOptionMinIntegerValues> {
+ private static readonly pb::MessageParser<CustomOptionMinIntegerValues> _parser = new pb::MessageParser<CustomOptionMinIntegerValues>(() => new CustomOptionMinIntegerValues());
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pb::MessageParser<CustomOptionMinIntegerValues> Parser { get { return _parser; } }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::UnitTest.Issues.TestProtos.UnittestCustomOptionsProto3Reflection.Descriptor.MessageTypes[7]; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public CustomOptionMinIntegerValues() {
+ OnConstruction();
+ }
+
+ partial void OnConstruction();
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public CustomOptionMinIntegerValues(CustomOptionMinIntegerValues other) : this() {
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public CustomOptionMinIntegerValues Clone() {
+ return new CustomOptionMinIntegerValues(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override bool Equals(object other) {
+ return Equals(other as CustomOptionMinIntegerValues);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool Equals(CustomOptionMinIntegerValues other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
+ }
+ if (ReferenceEquals(other, this)) {
+ return true;
+ }
+ return true;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override int GetHashCode() {
+ int hash = 1;
+ return hash;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override string ToString() {
+ return pb::JsonFormatter.ToDiagnosticString(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void WriteTo(pb::CodedOutputStream output) {
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int CalculateSize() {
+ int size = 0;
+ return size;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(CustomOptionMinIntegerValues other) {
+ if (other == null) {
+ return;
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ }
+ }
+ }
+
+ }
+
+ public sealed partial class CustomOptionMaxIntegerValues : pb::IMessage<CustomOptionMaxIntegerValues> {
+ private static readonly pb::MessageParser<CustomOptionMaxIntegerValues> _parser = new pb::MessageParser<CustomOptionMaxIntegerValues>(() => new CustomOptionMaxIntegerValues());
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pb::MessageParser<CustomOptionMaxIntegerValues> Parser { get { return _parser; } }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::UnitTest.Issues.TestProtos.UnittestCustomOptionsProto3Reflection.Descriptor.MessageTypes[8]; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public CustomOptionMaxIntegerValues() {
+ OnConstruction();
+ }
+
+ partial void OnConstruction();
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public CustomOptionMaxIntegerValues(CustomOptionMaxIntegerValues other) : this() {
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public CustomOptionMaxIntegerValues Clone() {
+ return new CustomOptionMaxIntegerValues(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override bool Equals(object other) {
+ return Equals(other as CustomOptionMaxIntegerValues);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool Equals(CustomOptionMaxIntegerValues other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
+ }
+ if (ReferenceEquals(other, this)) {
+ return true;
+ }
+ return true;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override int GetHashCode() {
+ int hash = 1;
+ return hash;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override string ToString() {
+ return pb::JsonFormatter.ToDiagnosticString(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void WriteTo(pb::CodedOutputStream output) {
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int CalculateSize() {
+ int size = 0;
+ return size;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(CustomOptionMaxIntegerValues other) {
+ if (other == null) {
+ return;
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ }
+ }
+ }
+
+ }
+
+ public sealed partial class CustomOptionOtherValues : pb::IMessage<CustomOptionOtherValues> {
+ private static readonly pb::MessageParser<CustomOptionOtherValues> _parser = new pb::MessageParser<CustomOptionOtherValues>(() => new CustomOptionOtherValues());
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pb::MessageParser<CustomOptionOtherValues> Parser { get { return _parser; } }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::UnitTest.Issues.TestProtos.UnittestCustomOptionsProto3Reflection.Descriptor.MessageTypes[9]; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public CustomOptionOtherValues() {
+ OnConstruction();
+ }
+
+ partial void OnConstruction();
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public CustomOptionOtherValues(CustomOptionOtherValues other) : this() {
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public CustomOptionOtherValues Clone() {
+ return new CustomOptionOtherValues(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override bool Equals(object other) {
+ return Equals(other as CustomOptionOtherValues);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool Equals(CustomOptionOtherValues other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
+ }
+ if (ReferenceEquals(other, this)) {
+ return true;
+ }
+ return true;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override int GetHashCode() {
+ int hash = 1;
+ return hash;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override string ToString() {
+ return pb::JsonFormatter.ToDiagnosticString(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void WriteTo(pb::CodedOutputStream output) {
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int CalculateSize() {
+ int size = 0;
+ return size;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(CustomOptionOtherValues other) {
+ if (other == null) {
+ return;
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ }
+ }
+ }
+
+ }
+
+ public sealed partial class SettingRealsFromPositiveInts : pb::IMessage<SettingRealsFromPositiveInts> {
+ private static readonly pb::MessageParser<SettingRealsFromPositiveInts> _parser = new pb::MessageParser<SettingRealsFromPositiveInts>(() => new SettingRealsFromPositiveInts());
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pb::MessageParser<SettingRealsFromPositiveInts> Parser { get { return _parser; } }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::UnitTest.Issues.TestProtos.UnittestCustomOptionsProto3Reflection.Descriptor.MessageTypes[10]; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public SettingRealsFromPositiveInts() {
+ OnConstruction();
+ }
+
+ partial void OnConstruction();
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public SettingRealsFromPositiveInts(SettingRealsFromPositiveInts other) : this() {
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public SettingRealsFromPositiveInts Clone() {
+ return new SettingRealsFromPositiveInts(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override bool Equals(object other) {
+ return Equals(other as SettingRealsFromPositiveInts);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool Equals(SettingRealsFromPositiveInts other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
+ }
+ if (ReferenceEquals(other, this)) {
+ return true;
+ }
+ return true;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override int GetHashCode() {
+ int hash = 1;
+ return hash;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override string ToString() {
+ return pb::JsonFormatter.ToDiagnosticString(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void WriteTo(pb::CodedOutputStream output) {
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int CalculateSize() {
+ int size = 0;
+ return size;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(SettingRealsFromPositiveInts other) {
+ if (other == null) {
+ return;
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ }
+ }
+ }
+
+ }
+
+ public sealed partial class SettingRealsFromNegativeInts : pb::IMessage<SettingRealsFromNegativeInts> {
+ private static readonly pb::MessageParser<SettingRealsFromNegativeInts> _parser = new pb::MessageParser<SettingRealsFromNegativeInts>(() => new SettingRealsFromNegativeInts());
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pb::MessageParser<SettingRealsFromNegativeInts> Parser { get { return _parser; } }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::UnitTest.Issues.TestProtos.UnittestCustomOptionsProto3Reflection.Descriptor.MessageTypes[11]; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public SettingRealsFromNegativeInts() {
+ OnConstruction();
+ }
+
+ partial void OnConstruction();
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public SettingRealsFromNegativeInts(SettingRealsFromNegativeInts other) : this() {
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public SettingRealsFromNegativeInts Clone() {
+ return new SettingRealsFromNegativeInts(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override bool Equals(object other) {
+ return Equals(other as SettingRealsFromNegativeInts);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool Equals(SettingRealsFromNegativeInts other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
+ }
+ if (ReferenceEquals(other, this)) {
+ return true;
+ }
+ return true;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override int GetHashCode() {
+ int hash = 1;
+ return hash;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override string ToString() {
+ return pb::JsonFormatter.ToDiagnosticString(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void WriteTo(pb::CodedOutputStream output) {
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int CalculateSize() {
+ int size = 0;
+ return size;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(SettingRealsFromNegativeInts other) {
+ if (other == null) {
+ return;
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ }
+ }
+ }
+
+ }
+
+ public sealed partial class ComplexOptionType1 : pb::IMessage<ComplexOptionType1> {
+ private static readonly pb::MessageParser<ComplexOptionType1> _parser = new pb::MessageParser<ComplexOptionType1>(() => new ComplexOptionType1());
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pb::MessageParser<ComplexOptionType1> Parser { get { return _parser; } }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::UnitTest.Issues.TestProtos.UnittestCustomOptionsProto3Reflection.Descriptor.MessageTypes[12]; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public ComplexOptionType1() {
+ OnConstruction();
+ }
+
+ partial void OnConstruction();
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public ComplexOptionType1(ComplexOptionType1 other) : this() {
+ foo_ = other.foo_;
+ foo2_ = other.foo2_;
+ foo3_ = other.foo3_;
+ foo4_ = other.foo4_.Clone();
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public ComplexOptionType1 Clone() {
+ return new ComplexOptionType1(this);
+ }
+
+ /// <summary>Field number for the "foo" field.</summary>
+ public const int FooFieldNumber = 1;
+ private int foo_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int Foo {
+ get { return foo_; }
+ set {
+ foo_ = value;
+ }
+ }
+
+ /// <summary>Field number for the "foo2" field.</summary>
+ public const int Foo2FieldNumber = 2;
+ private int foo2_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int Foo2 {
+ get { return foo2_; }
+ set {
+ foo2_ = value;
+ }
+ }
+
+ /// <summary>Field number for the "foo3" field.</summary>
+ public const int Foo3FieldNumber = 3;
+ private int foo3_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int Foo3 {
+ get { return foo3_; }
+ set {
+ foo3_ = value;
+ }
+ }
+
+ /// <summary>Field number for the "foo4" field.</summary>
+ public const int Foo4FieldNumber = 4;
+ private static readonly pb::FieldCodec<int> _repeated_foo4_codec
+ = pb::FieldCodec.ForInt32(34);
+ private readonly pbc::RepeatedField<int> foo4_ = new pbc::RepeatedField<int>();
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public pbc::RepeatedField<int> Foo4 {
+ get { return foo4_; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override bool Equals(object other) {
+ return Equals(other as ComplexOptionType1);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool Equals(ComplexOptionType1 other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
+ }
+ if (ReferenceEquals(other, this)) {
+ return true;
+ }
+ if (Foo != other.Foo) return false;
+ if (Foo2 != other.Foo2) return false;
+ if (Foo3 != other.Foo3) return false;
+ if(!foo4_.Equals(other.foo4_)) return false;
+ return true;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override int GetHashCode() {
+ int hash = 1;
+ if (Foo != 0) hash ^= Foo.GetHashCode();
+ if (Foo2 != 0) hash ^= Foo2.GetHashCode();
+ if (Foo3 != 0) hash ^= Foo3.GetHashCode();
+ hash ^= foo4_.GetHashCode();
+ return hash;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override string ToString() {
+ return pb::JsonFormatter.ToDiagnosticString(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void WriteTo(pb::CodedOutputStream output) {
+ if (Foo != 0) {
+ output.WriteRawTag(8);
+ output.WriteInt32(Foo);
+ }
+ if (Foo2 != 0) {
+ output.WriteRawTag(16);
+ output.WriteInt32(Foo2);
+ }
+ if (Foo3 != 0) {
+ output.WriteRawTag(24);
+ output.WriteInt32(Foo3);
+ }
+ foo4_.WriteTo(output, _repeated_foo4_codec);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int CalculateSize() {
+ int size = 0;
+ if (Foo != 0) {
+ size += 1 + pb::CodedOutputStream.ComputeInt32Size(Foo);
+ }
+ if (Foo2 != 0) {
+ size += 1 + pb::CodedOutputStream.ComputeInt32Size(Foo2);
+ }
+ if (Foo3 != 0) {
+ size += 1 + pb::CodedOutputStream.ComputeInt32Size(Foo3);
+ }
+ size += foo4_.CalculateSize(_repeated_foo4_codec);
+ return size;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(ComplexOptionType1 other) {
+ if (other == null) {
+ return;
+ }
+ if (other.Foo != 0) {
+ Foo = other.Foo;
+ }
+ if (other.Foo2 != 0) {
+ Foo2 = other.Foo2;
+ }
+ if (other.Foo3 != 0) {
+ Foo3 = other.Foo3;
+ }
+ foo4_.Add(other.foo4_);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ case 8: {
+ Foo = input.ReadInt32();
+ break;
+ }
+ case 16: {
+ Foo2 = input.ReadInt32();
+ break;
+ }
+ case 24: {
+ Foo3 = input.ReadInt32();
+ break;
+ }
+ case 34:
+ case 32: {
+ foo4_.AddEntriesFrom(input, _repeated_foo4_codec);
+ break;
+ }
+ }
+ }
+ }
+
+ }
+
+ public sealed partial class ComplexOptionType2 : pb::IMessage<ComplexOptionType2> {
+ private static readonly pb::MessageParser<ComplexOptionType2> _parser = new pb::MessageParser<ComplexOptionType2>(() => new ComplexOptionType2());
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pb::MessageParser<ComplexOptionType2> Parser { get { return _parser; } }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::UnitTest.Issues.TestProtos.UnittestCustomOptionsProto3Reflection.Descriptor.MessageTypes[13]; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public ComplexOptionType2() {
+ OnConstruction();
+ }
+
+ partial void OnConstruction();
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public ComplexOptionType2(ComplexOptionType2 other) : this() {
+ Bar = other.bar_ != null ? other.Bar.Clone() : null;
+ baz_ = other.baz_;
+ Fred = other.fred_ != null ? other.Fred.Clone() : null;
+ barney_ = other.barney_.Clone();
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public ComplexOptionType2 Clone() {
+ return new ComplexOptionType2(this);
+ }
+
+ /// <summary>Field number for the "bar" field.</summary>
+ public const int BarFieldNumber = 1;
+ private global::UnitTest.Issues.TestProtos.ComplexOptionType1 bar_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public global::UnitTest.Issues.TestProtos.ComplexOptionType1 Bar {
+ get { return bar_; }
+ set {
+ bar_ = value;
+ }
+ }
+
+ /// <summary>Field number for the "baz" field.</summary>
+ public const int BazFieldNumber = 2;
+ private int baz_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int Baz {
+ get { return baz_; }
+ set {
+ baz_ = value;
+ }
+ }
+
+ /// <summary>Field number for the "fred" field.</summary>
+ public const int FredFieldNumber = 3;
+ private global::UnitTest.Issues.TestProtos.ComplexOptionType2.Types.ComplexOptionType4 fred_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public global::UnitTest.Issues.TestProtos.ComplexOptionType2.Types.ComplexOptionType4 Fred {
+ get { return fred_; }
+ set {
+ fred_ = value;
+ }
+ }
+
+ /// <summary>Field number for the "barney" field.</summary>
+ public const int BarneyFieldNumber = 4;
+ private static readonly pb::FieldCodec<global::UnitTest.Issues.TestProtos.ComplexOptionType2.Types.ComplexOptionType4> _repeated_barney_codec
+ = pb::FieldCodec.ForMessage(34, global::UnitTest.Issues.TestProtos.ComplexOptionType2.Types.ComplexOptionType4.Parser);
+ private readonly pbc::RepeatedField<global::UnitTest.Issues.TestProtos.ComplexOptionType2.Types.ComplexOptionType4> barney_ = new pbc::RepeatedField<global::UnitTest.Issues.TestProtos.ComplexOptionType2.Types.ComplexOptionType4>();
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public pbc::RepeatedField<global::UnitTest.Issues.TestProtos.ComplexOptionType2.Types.ComplexOptionType4> Barney {
+ get { return barney_; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override bool Equals(object other) {
+ return Equals(other as ComplexOptionType2);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool Equals(ComplexOptionType2 other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
+ }
+ if (ReferenceEquals(other, this)) {
+ return true;
+ }
+ if (!object.Equals(Bar, other.Bar)) return false;
+ if (Baz != other.Baz) return false;
+ if (!object.Equals(Fred, other.Fred)) return false;
+ if(!barney_.Equals(other.barney_)) return false;
+ return true;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override int GetHashCode() {
+ int hash = 1;
+ if (bar_ != null) hash ^= Bar.GetHashCode();
+ if (Baz != 0) hash ^= Baz.GetHashCode();
+ if (fred_ != null) hash ^= Fred.GetHashCode();
+ hash ^= barney_.GetHashCode();
+ return hash;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override string ToString() {
+ return pb::JsonFormatter.ToDiagnosticString(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void WriteTo(pb::CodedOutputStream output) {
+ if (bar_ != null) {
+ output.WriteRawTag(10);
+ output.WriteMessage(Bar);
+ }
+ if (Baz != 0) {
+ output.WriteRawTag(16);
+ output.WriteInt32(Baz);
+ }
+ if (fred_ != null) {
+ output.WriteRawTag(26);
+ output.WriteMessage(Fred);
+ }
+ barney_.WriteTo(output, _repeated_barney_codec);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int CalculateSize() {
+ int size = 0;
+ if (bar_ != null) {
+ size += 1 + pb::CodedOutputStream.ComputeMessageSize(Bar);
+ }
+ if (Baz != 0) {
+ size += 1 + pb::CodedOutputStream.ComputeInt32Size(Baz);
+ }
+ if (fred_ != null) {
+ size += 1 + pb::CodedOutputStream.ComputeMessageSize(Fred);
+ }
+ size += barney_.CalculateSize(_repeated_barney_codec);
+ return size;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(ComplexOptionType2 other) {
+ if (other == null) {
+ return;
+ }
+ if (other.bar_ != null) {
+ if (bar_ == null) {
+ bar_ = new global::UnitTest.Issues.TestProtos.ComplexOptionType1();
+ }
+ Bar.MergeFrom(other.Bar);
+ }
+ if (other.Baz != 0) {
+ Baz = other.Baz;
+ }
+ if (other.fred_ != null) {
+ if (fred_ == null) {
+ fred_ = new global::UnitTest.Issues.TestProtos.ComplexOptionType2.Types.ComplexOptionType4();
+ }
+ Fred.MergeFrom(other.Fred);
+ }
+ barney_.Add(other.barney_);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ case 10: {
+ if (bar_ == null) {
+ bar_ = new global::UnitTest.Issues.TestProtos.ComplexOptionType1();
+ }
+ input.ReadMessage(bar_);
+ break;
+ }
+ case 16: {
+ Baz = input.ReadInt32();
+ break;
+ }
+ case 26: {
+ if (fred_ == null) {
+ fred_ = new global::UnitTest.Issues.TestProtos.ComplexOptionType2.Types.ComplexOptionType4();
+ }
+ input.ReadMessage(fred_);
+ break;
+ }
+ case 34: {
+ barney_.AddEntriesFrom(input, _repeated_barney_codec);
+ break;
+ }
+ }
+ }
+ }
+
+ #region Nested types
+ /// <summary>Container for nested types declared in the ComplexOptionType2 message type.</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static partial class Types {
+ public sealed partial class ComplexOptionType4 : pb::IMessage<ComplexOptionType4> {
+ private static readonly pb::MessageParser<ComplexOptionType4> _parser = new pb::MessageParser<ComplexOptionType4>(() => new ComplexOptionType4());
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pb::MessageParser<ComplexOptionType4> Parser { get { return _parser; } }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::UnitTest.Issues.TestProtos.ComplexOptionType2.Descriptor.NestedTypes[0]; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public ComplexOptionType4() {
+ OnConstruction();
+ }
+
+ partial void OnConstruction();
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public ComplexOptionType4(ComplexOptionType4 other) : this() {
+ waldo_ = other.waldo_;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public ComplexOptionType4 Clone() {
+ return new ComplexOptionType4(this);
+ }
+
+ /// <summary>Field number for the "waldo" field.</summary>
+ public const int WaldoFieldNumber = 1;
+ private int waldo_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int Waldo {
+ get { return waldo_; }
+ set {
+ waldo_ = value;
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override bool Equals(object other) {
+ return Equals(other as ComplexOptionType4);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool Equals(ComplexOptionType4 other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
+ }
+ if (ReferenceEquals(other, this)) {
+ return true;
+ }
+ if (Waldo != other.Waldo) return false;
+ return true;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override int GetHashCode() {
+ int hash = 1;
+ if (Waldo != 0) hash ^= Waldo.GetHashCode();
+ return hash;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override string ToString() {
+ return pb::JsonFormatter.ToDiagnosticString(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void WriteTo(pb::CodedOutputStream output) {
+ if (Waldo != 0) {
+ output.WriteRawTag(8);
+ output.WriteInt32(Waldo);
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int CalculateSize() {
+ int size = 0;
+ if (Waldo != 0) {
+ size += 1 + pb::CodedOutputStream.ComputeInt32Size(Waldo);
+ }
+ return size;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(ComplexOptionType4 other) {
+ if (other == null) {
+ return;
+ }
+ if (other.Waldo != 0) {
+ Waldo = other.Waldo;
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ case 8: {
+ Waldo = input.ReadInt32();
+ break;
+ }
+ }
+ }
+ }
+
+ }
+
+ }
+ #endregion
+
+ }
+
+ public sealed partial class ComplexOptionType3 : pb::IMessage<ComplexOptionType3> {
+ private static readonly pb::MessageParser<ComplexOptionType3> _parser = new pb::MessageParser<ComplexOptionType3>(() => new ComplexOptionType3());
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pb::MessageParser<ComplexOptionType3> Parser { get { return _parser; } }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::UnitTest.Issues.TestProtos.UnittestCustomOptionsProto3Reflection.Descriptor.MessageTypes[14]; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public ComplexOptionType3() {
+ OnConstruction();
+ }
+
+ partial void OnConstruction();
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public ComplexOptionType3(ComplexOptionType3 other) : this() {
+ qux_ = other.qux_;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public ComplexOptionType3 Clone() {
+ return new ComplexOptionType3(this);
+ }
+
+ /// <summary>Field number for the "qux" field.</summary>
+ public const int QuxFieldNumber = 1;
+ private int qux_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int Qux {
+ get { return qux_; }
+ set {
+ qux_ = value;
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override bool Equals(object other) {
+ return Equals(other as ComplexOptionType3);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool Equals(ComplexOptionType3 other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
+ }
+ if (ReferenceEquals(other, this)) {
+ return true;
+ }
+ if (Qux != other.Qux) return false;
+ return true;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override int GetHashCode() {
+ int hash = 1;
+ if (Qux != 0) hash ^= Qux.GetHashCode();
+ return hash;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override string ToString() {
+ return pb::JsonFormatter.ToDiagnosticString(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void WriteTo(pb::CodedOutputStream output) {
+ if (Qux != 0) {
+ output.WriteRawTag(8);
+ output.WriteInt32(Qux);
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int CalculateSize() {
+ int size = 0;
+ if (Qux != 0) {
+ size += 1 + pb::CodedOutputStream.ComputeInt32Size(Qux);
+ }
+ return size;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(ComplexOptionType3 other) {
+ if (other == null) {
+ return;
+ }
+ if (other.Qux != 0) {
+ Qux = other.Qux;
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ case 8: {
+ Qux = input.ReadInt32();
+ break;
+ }
+ }
+ }
+ }
+
+ }
+
+ /// <summary>
+ /// Note that we try various different ways of naming the same extension.
+ /// </summary>
+ public sealed partial class VariousComplexOptions : pb::IMessage<VariousComplexOptions> {
+ private static readonly pb::MessageParser<VariousComplexOptions> _parser = new pb::MessageParser<VariousComplexOptions>(() => new VariousComplexOptions());
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pb::MessageParser<VariousComplexOptions> Parser { get { return _parser; } }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::UnitTest.Issues.TestProtos.UnittestCustomOptionsProto3Reflection.Descriptor.MessageTypes[15]; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public VariousComplexOptions() {
+ OnConstruction();
+ }
+
+ partial void OnConstruction();
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public VariousComplexOptions(VariousComplexOptions other) : this() {
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public VariousComplexOptions Clone() {
+ return new VariousComplexOptions(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override bool Equals(object other) {
+ return Equals(other as VariousComplexOptions);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool Equals(VariousComplexOptions other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
+ }
+ if (ReferenceEquals(other, this)) {
+ return true;
+ }
+ return true;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override int GetHashCode() {
+ int hash = 1;
+ return hash;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override string ToString() {
+ return pb::JsonFormatter.ToDiagnosticString(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void WriteTo(pb::CodedOutputStream output) {
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int CalculateSize() {
+ int size = 0;
+ return size;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(VariousComplexOptions other) {
+ if (other == null) {
+ return;
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ }
+ }
+ }
+
+ }
+
+ /// <summary>
+ /// A helper type used to test aggregate option parsing
+ /// </summary>
+ public sealed partial class Aggregate : pb::IMessage<Aggregate> {
+ private static readonly pb::MessageParser<Aggregate> _parser = new pb::MessageParser<Aggregate>(() => new Aggregate());
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pb::MessageParser<Aggregate> Parser { get { return _parser; } }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::UnitTest.Issues.TestProtos.UnittestCustomOptionsProto3Reflection.Descriptor.MessageTypes[16]; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public Aggregate() {
+ OnConstruction();
+ }
+
+ partial void OnConstruction();
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public Aggregate(Aggregate other) : this() {
+ i_ = other.i_;
+ s_ = other.s_;
+ Sub = other.sub_ != null ? other.Sub.Clone() : null;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public Aggregate Clone() {
+ return new Aggregate(this);
+ }
+
+ /// <summary>Field number for the "i" field.</summary>
+ public const int IFieldNumber = 1;
+ private int i_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int I {
+ get { return i_; }
+ set {
+ i_ = value;
+ }
+ }
+
+ /// <summary>Field number for the "s" field.</summary>
+ public const int SFieldNumber = 2;
+ private string s_ = "";
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public string S {
+ get { return s_; }
+ set {
+ s_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
+ }
+ }
+
+ /// <summary>Field number for the "sub" field.</summary>
+ public const int SubFieldNumber = 3;
+ private global::UnitTest.Issues.TestProtos.Aggregate sub_;
+ /// <summary>
+ /// A nested object
+ /// </summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public global::UnitTest.Issues.TestProtos.Aggregate Sub {
+ get { return sub_; }
+ set {
+ sub_ = value;
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override bool Equals(object other) {
+ return Equals(other as Aggregate);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool Equals(Aggregate other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
+ }
+ if (ReferenceEquals(other, this)) {
+ return true;
+ }
+ if (I != other.I) return false;
+ if (S != other.S) return false;
+ if (!object.Equals(Sub, other.Sub)) return false;
+ return true;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override int GetHashCode() {
+ int hash = 1;
+ if (I != 0) hash ^= I.GetHashCode();
+ if (S.Length != 0) hash ^= S.GetHashCode();
+ if (sub_ != null) hash ^= Sub.GetHashCode();
+ return hash;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override string ToString() {
+ return pb::JsonFormatter.ToDiagnosticString(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void WriteTo(pb::CodedOutputStream output) {
+ if (I != 0) {
+ output.WriteRawTag(8);
+ output.WriteInt32(I);
+ }
+ if (S.Length != 0) {
+ output.WriteRawTag(18);
+ output.WriteString(S);
+ }
+ if (sub_ != null) {
+ output.WriteRawTag(26);
+ output.WriteMessage(Sub);
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int CalculateSize() {
+ int size = 0;
+ if (I != 0) {
+ size += 1 + pb::CodedOutputStream.ComputeInt32Size(I);
+ }
+ if (S.Length != 0) {
+ size += 1 + pb::CodedOutputStream.ComputeStringSize(S);
+ }
+ if (sub_ != null) {
+ size += 1 + pb::CodedOutputStream.ComputeMessageSize(Sub);
+ }
+ return size;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(Aggregate other) {
+ if (other == null) {
+ return;
+ }
+ if (other.I != 0) {
+ I = other.I;
+ }
+ if (other.S.Length != 0) {
+ S = other.S;
+ }
+ if (other.sub_ != null) {
+ if (sub_ == null) {
+ sub_ = new global::UnitTest.Issues.TestProtos.Aggregate();
+ }
+ Sub.MergeFrom(other.Sub);
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ case 8: {
+ I = input.ReadInt32();
+ break;
+ }
+ case 18: {
+ S = input.ReadString();
+ break;
+ }
+ case 26: {
+ if (sub_ == null) {
+ sub_ = new global::UnitTest.Issues.TestProtos.Aggregate();
+ }
+ input.ReadMessage(sub_);
+ break;
+ }
+ }
+ }
+ }
+
+ }
+
+ public sealed partial class AggregateMessage : pb::IMessage<AggregateMessage> {
+ private static readonly pb::MessageParser<AggregateMessage> _parser = new pb::MessageParser<AggregateMessage>(() => new AggregateMessage());
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pb::MessageParser<AggregateMessage> Parser { get { return _parser; } }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::UnitTest.Issues.TestProtos.UnittestCustomOptionsProto3Reflection.Descriptor.MessageTypes[17]; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public AggregateMessage() {
+ OnConstruction();
+ }
+
+ partial void OnConstruction();
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public AggregateMessage(AggregateMessage other) : this() {
+ fieldname_ = other.fieldname_;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public AggregateMessage Clone() {
+ return new AggregateMessage(this);
+ }
+
+ /// <summary>Field number for the "fieldname" field.</summary>
+ public const int FieldnameFieldNumber = 1;
+ private int fieldname_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int Fieldname {
+ get { return fieldname_; }
+ set {
+ fieldname_ = value;
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override bool Equals(object other) {
+ return Equals(other as AggregateMessage);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool Equals(AggregateMessage other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
+ }
+ if (ReferenceEquals(other, this)) {
+ return true;
+ }
+ if (Fieldname != other.Fieldname) return false;
+ return true;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override int GetHashCode() {
+ int hash = 1;
+ if (Fieldname != 0) hash ^= Fieldname.GetHashCode();
+ return hash;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override string ToString() {
+ return pb::JsonFormatter.ToDiagnosticString(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void WriteTo(pb::CodedOutputStream output) {
+ if (Fieldname != 0) {
+ output.WriteRawTag(8);
+ output.WriteInt32(Fieldname);
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int CalculateSize() {
+ int size = 0;
+ if (Fieldname != 0) {
+ size += 1 + pb::CodedOutputStream.ComputeInt32Size(Fieldname);
+ }
+ return size;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(AggregateMessage other) {
+ if (other == null) {
+ return;
+ }
+ if (other.Fieldname != 0) {
+ Fieldname = other.Fieldname;
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ case 8: {
+ Fieldname = input.ReadInt32();
+ break;
+ }
+ }
+ }
+ }
+
+ }
+
+ /// <summary>
+ /// Test custom options for nested type.
+ /// </summary>
+ public sealed partial class NestedOptionType : pb::IMessage<NestedOptionType> {
+ private static readonly pb::MessageParser<NestedOptionType> _parser = new pb::MessageParser<NestedOptionType>(() => new NestedOptionType());
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pb::MessageParser<NestedOptionType> Parser { get { return _parser; } }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::UnitTest.Issues.TestProtos.UnittestCustomOptionsProto3Reflection.Descriptor.MessageTypes[18]; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public NestedOptionType() {
+ OnConstruction();
+ }
+
+ partial void OnConstruction();
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public NestedOptionType(NestedOptionType other) : this() {
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public NestedOptionType Clone() {
+ return new NestedOptionType(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override bool Equals(object other) {
+ return Equals(other as NestedOptionType);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool Equals(NestedOptionType other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
+ }
+ if (ReferenceEquals(other, this)) {
+ return true;
+ }
+ return true;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override int GetHashCode() {
+ int hash = 1;
+ return hash;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override string ToString() {
+ return pb::JsonFormatter.ToDiagnosticString(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void WriteTo(pb::CodedOutputStream output) {
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int CalculateSize() {
+ int size = 0;
+ return size;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(NestedOptionType other) {
+ if (other == null) {
+ return;
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ }
+ }
+ }
+
+ #region Nested types
+ /// <summary>Container for nested types declared in the NestedOptionType message type.</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static partial class Types {
+ public enum NestedEnum {
+ [pbr::OriginalName("UNSPECIFIED")] Unspecified = 0,
+ [pbr::OriginalName("NESTED_ENUM_VALUE")] Value = 1,
+ }
+
+ public sealed partial class NestedMessage : pb::IMessage<NestedMessage> {
+ private static readonly pb::MessageParser<NestedMessage> _parser = new pb::MessageParser<NestedMessage>(() => new NestedMessage());
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pb::MessageParser<NestedMessage> Parser { get { return _parser; } }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::UnitTest.Issues.TestProtos.NestedOptionType.Descriptor.NestedTypes[0]; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public NestedMessage() {
+ OnConstruction();
+ }
+
+ partial void OnConstruction();
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public NestedMessage(NestedMessage other) : this() {
+ nestedField_ = other.nestedField_;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public NestedMessage Clone() {
+ return new NestedMessage(this);
+ }
+
+ /// <summary>Field number for the "nested_field" field.</summary>
+ public const int NestedFieldFieldNumber = 1;
+ private int nestedField_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int NestedField {
+ get { return nestedField_; }
+ set {
+ nestedField_ = value;
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override bool Equals(object other) {
+ return Equals(other as NestedMessage);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool Equals(NestedMessage other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
+ }
+ if (ReferenceEquals(other, this)) {
+ return true;
+ }
+ if (NestedField != other.NestedField) return false;
+ return true;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override int GetHashCode() {
+ int hash = 1;
+ if (NestedField != 0) hash ^= NestedField.GetHashCode();
+ return hash;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override string ToString() {
+ return pb::JsonFormatter.ToDiagnosticString(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void WriteTo(pb::CodedOutputStream output) {
+ if (NestedField != 0) {
+ output.WriteRawTag(8);
+ output.WriteInt32(NestedField);
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int CalculateSize() {
+ int size = 0;
+ if (NestedField != 0) {
+ size += 1 + pb::CodedOutputStream.ComputeInt32Size(NestedField);
+ }
+ return size;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(NestedMessage other) {
+ if (other == null) {
+ return;
+ }
+ if (other.NestedField != 0) {
+ NestedField = other.NestedField;
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ case 8: {
+ NestedField = input.ReadInt32();
+ break;
+ }
+ }
+ }
+ }
+
+ }
+
+ }
+ #endregion
+
+ }
+
+ #endregion
+
+}
+
+#endregion Designer generated code
diff --git a/csharp/src/Google.Protobuf.Test/TestProtos/UnittestImportProto3.cs b/csharp/src/Google.Protobuf.Test/TestProtos/UnittestImportProto3.cs
index f6df4e87..1ebf007f 100644
--- a/csharp/src/Google.Protobuf.Test/TestProtos/UnittestImportProto3.cs
+++ b/csharp/src/Google.Protobuf.Test/TestProtos/UnittestImportProto3.cs
@@ -1,5 +1,5 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
-// source: google/protobuf/unittest_import_proto3.proto
+// source: unittest_import_proto3.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
@@ -9,11 +9,11 @@ using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Protobuf.TestProtos {
- /// <summary>Holder for reflection information generated from google/protobuf/unittest_import_proto3.proto</summary>
+ /// <summary>Holder for reflection information generated from unittest_import_proto3.proto</summary>
public static partial class UnittestImportProto3Reflection {
#region Descriptor
- /// <summary>File descriptor for google/protobuf/unittest_import_proto3.proto</summary>
+ /// <summary>File descriptor for unittest_import_proto3.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
@@ -22,14 +22,12 @@ namespace Google.Protobuf.TestProtos {
static UnittestImportProto3Reflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
- "Cixnb29nbGUvcHJvdG9idWYvdW5pdHRlc3RfaW1wb3J0X3Byb3RvMy5wcm90",
- "bxIYcHJvdG9idWZfdW5pdHRlc3RfaW1wb3J0GjNnb29nbGUvcHJvdG9idWYv",
- "dW5pdHRlc3RfaW1wb3J0X3B1YmxpY19wcm90bzMucHJvdG8iGgoNSW1wb3J0",
- "TWVzc2FnZRIJCgFkGAEgASgFKlkKCkltcG9ydEVudW0SGwoXSU1QT1JUX0VO",
- "VU1fVU5TUEVDSUZJRUQQABIOCgpJTVBPUlRfRk9PEAcSDgoKSU1QT1JUX0JB",
- "UhAIEg4KCklNUE9SVF9CQVoQCUI8Chhjb20uZ29vZ2xlLnByb3RvYnVmLnRl",
- "c3RIAfgBAaoCGkdvb2dsZS5Qcm90b2J1Zi5UZXN0UHJvdG9zUABiBnByb3Rv",
- "Mw=="));
+ "Chx1bml0dGVzdF9pbXBvcnRfcHJvdG8zLnByb3RvEhhwcm90b2J1Zl91bml0",
+ "dGVzdF9pbXBvcnQaI3VuaXR0ZXN0X2ltcG9ydF9wdWJsaWNfcHJvdG8zLnBy",
+ "b3RvIhoKDUltcG9ydE1lc3NhZ2USCQoBZBgBIAEoBSpZCgpJbXBvcnRFbnVt",
+ "EhsKF0lNUE9SVF9FTlVNX1VOU1BFQ0lGSUVEEAASDgoKSU1QT1JUX0ZPTxAH",
+ "Eg4KCklNUE9SVF9CQVIQCBIOCgpJTVBPUlRfQkFaEAlCHaoCGkdvb2dsZS5Q",
+ "cm90b2J1Zi5UZXN0UHJvdG9zUABiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Protobuf.TestProtos.UnittestImportPublicProto3Reflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(new[] {typeof(global::Google.Protobuf.TestProtos.ImportEnum), }, new pbr::GeneratedClrTypeInfo[] {
diff --git a/csharp/src/Google.Protobuf.Test/TestProtos/UnittestImportPublicProto3.cs b/csharp/src/Google.Protobuf.Test/TestProtos/UnittestImportPublicProto3.cs
index 67b8edf4..422f0b50 100644
--- a/csharp/src/Google.Protobuf.Test/TestProtos/UnittestImportPublicProto3.cs
+++ b/csharp/src/Google.Protobuf.Test/TestProtos/UnittestImportPublicProto3.cs
@@ -1,5 +1,5 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
-// source: google/protobuf/unittest_import_public_proto3.proto
+// source: unittest_import_public_proto3.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
@@ -9,11 +9,11 @@ using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Protobuf.TestProtos {
- /// <summary>Holder for reflection information generated from google/protobuf/unittest_import_public_proto3.proto</summary>
+ /// <summary>Holder for reflection information generated from unittest_import_public_proto3.proto</summary>
public static partial class UnittestImportPublicProto3Reflection {
#region Descriptor
- /// <summary>File descriptor for google/protobuf/unittest_import_public_proto3.proto</summary>
+ /// <summary>File descriptor for unittest_import_public_proto3.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
@@ -22,10 +22,10 @@ namespace Google.Protobuf.TestProtos {
static UnittestImportPublicProto3Reflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
- "CjNnb29nbGUvcHJvdG9idWYvdW5pdHRlc3RfaW1wb3J0X3B1YmxpY19wcm90",
- "bzMucHJvdG8SGHByb3RvYnVmX3VuaXR0ZXN0X2ltcG9ydCIgChNQdWJsaWNJ",
- "bXBvcnRNZXNzYWdlEgkKAWUYASABKAVCNwoYY29tLmdvb2dsZS5wcm90b2J1",
- "Zi50ZXN0qgIaR29vZ2xlLlByb3RvYnVmLlRlc3RQcm90b3NiBnByb3RvMw=="));
+ "CiN1bml0dGVzdF9pbXBvcnRfcHVibGljX3Byb3RvMy5wcm90bxIYcHJvdG9i",
+ "dWZfdW5pdHRlc3RfaW1wb3J0IiAKE1B1YmxpY0ltcG9ydE1lc3NhZ2USCQoB",
+ "ZRgBIAEoBUIdqgIaR29vZ2xlLlByb3RvYnVmLlRlc3RQcm90b3NiBnByb3Rv",
+ "Mw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
diff --git a/csharp/src/Google.Protobuf.Test/TestProtos/UnittestIssues.cs b/csharp/src/Google.Protobuf.Test/TestProtos/UnittestIssues.cs
index 7c0ba8a6..ccf99dc5 100644
--- a/csharp/src/Google.Protobuf.Test/TestProtos/UnittestIssues.cs
+++ b/csharp/src/Google.Protobuf.Test/TestProtos/UnittestIssues.cs
@@ -42,11 +42,14 @@ namespace UnitTest.Issues.TestProtos {
"MV9pbnQzMhgFIAEoBUgAEhQKDHBsYWluX3N0cmluZxgBIAEoCRISCghvMl9p",
"bnQzMhgGIAEoBUgBEhMKCW8yX3N0cmluZxgDIAEoCUgBQgQKAm8xQgQKAm8y",
"IksKDFRlc3RKc29uTmFtZRIMCgRuYW1lGAEgASgJEhkKC2Rlc2NyaXB0aW9u",
- "GAIgASgJUgRkZXNjEhIKBGd1aWQYAyABKAlSBGV4aWQqVQoMTmVnYXRpdmVF",
- "bnVtEhYKEk5FR0FUSVZFX0VOVU1fWkVSTxAAEhYKCUZpdmVCZWxvdxD7////",
- "//////8BEhUKCE1pbnVzT25lEP///////////wEqLgoORGVwcmVjYXRlZEVu",
- "dW0SEwoPREVQUkVDQVRFRF9aRVJPEAASBwoDb25lEAFCH0gBqgIaVW5pdFRl",
- "c3QuSXNzdWVzLlRlc3RQcm90b3NiBnByb3RvMw=="));
+ "GAIgASgJUgRkZXNjEhIKBGd1aWQYAyABKAlSBGV4aWQifwoMT25lb2ZNZXJn",
+ "aW5nEg4KBHRleHQYASABKAlIABI2CgZuZXN0ZWQYAiABKAsyJC51bml0dGVz",
+ "dF9pc3N1ZXMuT25lb2ZNZXJnaW5nLk5lc3RlZEgAGh4KBk5lc3RlZBIJCgF4",
+ "GAEgASgFEgkKAXkYAiABKAVCBwoFdmFsdWUqVQoMTmVnYXRpdmVFbnVtEhYK",
+ "Ek5FR0FUSVZFX0VOVU1fWkVSTxAAEhYKCUZpdmVCZWxvdxD7//////////8B",
+ "EhUKCE1pbnVzT25lEP///////////wEqLgoORGVwcmVjYXRlZEVudW0SEwoP",
+ "REVQUkVDQVRFRF9aRVJPEAASBwoDb25lEAFCHaoCGlVuaXRUZXN0Lklzc3Vl",
+ "cy5UZXN0UHJvdG9zYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(new[] {typeof(global::UnitTest.Issues.TestProtos.NegativeEnum), typeof(global::UnitTest.Issues.TestProtos.DeprecatedEnum), }, new pbr::GeneratedClrTypeInfo[] {
@@ -57,7 +60,8 @@ namespace UnitTest.Issues.TestProtos {
new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.ItemField), global::UnitTest.Issues.TestProtos.ItemField.Parser, new[]{ "Item" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.ReservedNames), global::UnitTest.Issues.TestProtos.ReservedNames.Parser, new[]{ "Types_", "Descriptor_" }, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.ReservedNames.Types.SomeNestedType), global::UnitTest.Issues.TestProtos.ReservedNames.Types.SomeNestedType.Parser, null, null, null, null)}),
new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.TestJsonFieldOrdering), global::UnitTest.Issues.TestProtos.TestJsonFieldOrdering.Parser, new[]{ "PlainInt32", "O1String", "O1Int32", "PlainString", "O2Int32", "O2String" }, new[]{ "O1", "O2" }, null, null),
- new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.TestJsonName), global::UnitTest.Issues.TestProtos.TestJsonName.Parser, new[]{ "Name", "Description", "Guid" }, null, null, null)
+ new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.TestJsonName), global::UnitTest.Issues.TestProtos.TestJsonName.Parser, new[]{ "Name", "Description", "Guid" }, null, null, null),
+ new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.OneofMerging), global::UnitTest.Issues.TestProtos.OneofMerging.Parser, new[]{ "Text", "Nested" }, new[]{ "Value" }, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.OneofMerging.Types.Nested), global::UnitTest.Issues.TestProtos.OneofMerging.Types.Nested.Parser, new[]{ "X", "Y" }, null, null, null)})
}));
}
#endregion
@@ -1729,6 +1733,347 @@ namespace UnitTest.Issues.TestProtos {
}
+ /// <summary>
+ /// Issue 3200: When merging two messages which use the same
+ /// oneof case, which is itself a message type, the submessages should
+ /// be merged.
+ /// </summary>
+ public sealed partial class OneofMerging : pb::IMessage<OneofMerging> {
+ private static readonly pb::MessageParser<OneofMerging> _parser = new pb::MessageParser<OneofMerging>(() => new OneofMerging());
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pb::MessageParser<OneofMerging> Parser { get { return _parser; } }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::UnitTest.Issues.TestProtos.UnittestIssuesReflection.Descriptor.MessageTypes[8]; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public OneofMerging() {
+ OnConstruction();
+ }
+
+ partial void OnConstruction();
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public OneofMerging(OneofMerging other) : this() {
+ switch (other.ValueCase) {
+ case ValueOneofCase.Text:
+ Text = other.Text;
+ break;
+ case ValueOneofCase.Nested:
+ Nested = other.Nested.Clone();
+ break;
+ }
+
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public OneofMerging Clone() {
+ return new OneofMerging(this);
+ }
+
+ /// <summary>Field number for the "text" field.</summary>
+ public const int TextFieldNumber = 1;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public string Text {
+ get { return valueCase_ == ValueOneofCase.Text ? (string) value_ : ""; }
+ set {
+ value_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
+ valueCase_ = ValueOneofCase.Text;
+ }
+ }
+
+ /// <summary>Field number for the "nested" field.</summary>
+ public const int NestedFieldNumber = 2;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public global::UnitTest.Issues.TestProtos.OneofMerging.Types.Nested Nested {
+ get { return valueCase_ == ValueOneofCase.Nested ? (global::UnitTest.Issues.TestProtos.OneofMerging.Types.Nested) value_ : null; }
+ set {
+ value_ = value;
+ valueCase_ = value == null ? ValueOneofCase.None : ValueOneofCase.Nested;
+ }
+ }
+
+ private object value_;
+ /// <summary>Enum of possible cases for the "value" oneof.</summary>
+ public enum ValueOneofCase {
+ None = 0,
+ Text = 1,
+ Nested = 2,
+ }
+ private ValueOneofCase valueCase_ = ValueOneofCase.None;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public ValueOneofCase ValueCase {
+ get { return valueCase_; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void ClearValue() {
+ valueCase_ = ValueOneofCase.None;
+ value_ = null;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override bool Equals(object other) {
+ return Equals(other as OneofMerging);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool Equals(OneofMerging other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
+ }
+ if (ReferenceEquals(other, this)) {
+ return true;
+ }
+ if (Text != other.Text) return false;
+ if (!object.Equals(Nested, other.Nested)) return false;
+ if (ValueCase != other.ValueCase) return false;
+ return true;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override int GetHashCode() {
+ int hash = 1;
+ if (valueCase_ == ValueOneofCase.Text) hash ^= Text.GetHashCode();
+ if (valueCase_ == ValueOneofCase.Nested) hash ^= Nested.GetHashCode();
+ hash ^= (int) valueCase_;
+ return hash;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override string ToString() {
+ return pb::JsonFormatter.ToDiagnosticString(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void WriteTo(pb::CodedOutputStream output) {
+ if (valueCase_ == ValueOneofCase.Text) {
+ output.WriteRawTag(10);
+ output.WriteString(Text);
+ }
+ if (valueCase_ == ValueOneofCase.Nested) {
+ output.WriteRawTag(18);
+ output.WriteMessage(Nested);
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int CalculateSize() {
+ int size = 0;
+ if (valueCase_ == ValueOneofCase.Text) {
+ size += 1 + pb::CodedOutputStream.ComputeStringSize(Text);
+ }
+ if (valueCase_ == ValueOneofCase.Nested) {
+ size += 1 + pb::CodedOutputStream.ComputeMessageSize(Nested);
+ }
+ return size;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(OneofMerging other) {
+ if (other == null) {
+ return;
+ }
+ switch (other.ValueCase) {
+ case ValueOneofCase.Text:
+ Text = other.Text;
+ break;
+ case ValueOneofCase.Nested:
+ if (Nested == null) {
+ Nested = new global::UnitTest.Issues.TestProtos.OneofMerging.Types.Nested();
+ }
+ Nested.MergeFrom(other.Nested);
+ break;
+ }
+
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ case 10: {
+ Text = input.ReadString();
+ break;
+ }
+ case 18: {
+ global::UnitTest.Issues.TestProtos.OneofMerging.Types.Nested subBuilder = new global::UnitTest.Issues.TestProtos.OneofMerging.Types.Nested();
+ if (valueCase_ == ValueOneofCase.Nested) {
+ subBuilder.MergeFrom(Nested);
+ }
+ input.ReadMessage(subBuilder);
+ Nested = subBuilder;
+ break;
+ }
+ }
+ }
+ }
+
+ #region Nested types
+ /// <summary>Container for nested types declared in the OneofMerging message type.</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static partial class Types {
+ public sealed partial class Nested : pb::IMessage<Nested> {
+ private static readonly pb::MessageParser<Nested> _parser = new pb::MessageParser<Nested>(() => new Nested());
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pb::MessageParser<Nested> Parser { get { return _parser; } }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::UnitTest.Issues.TestProtos.OneofMerging.Descriptor.NestedTypes[0]; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public Nested() {
+ OnConstruction();
+ }
+
+ partial void OnConstruction();
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public Nested(Nested other) : this() {
+ x_ = other.x_;
+ y_ = other.y_;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public Nested Clone() {
+ return new Nested(this);
+ }
+
+ /// <summary>Field number for the "x" field.</summary>
+ public const int XFieldNumber = 1;
+ private int x_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int X {
+ get { return x_; }
+ set {
+ x_ = value;
+ }
+ }
+
+ /// <summary>Field number for the "y" field.</summary>
+ public const int YFieldNumber = 2;
+ private int y_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int Y {
+ get { return y_; }
+ set {
+ y_ = value;
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override bool Equals(object other) {
+ return Equals(other as Nested);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool Equals(Nested other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
+ }
+ if (ReferenceEquals(other, this)) {
+ return true;
+ }
+ if (X != other.X) return false;
+ if (Y != other.Y) return false;
+ return true;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override int GetHashCode() {
+ int hash = 1;
+ if (X != 0) hash ^= X.GetHashCode();
+ if (Y != 0) hash ^= Y.GetHashCode();
+ return hash;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override string ToString() {
+ return pb::JsonFormatter.ToDiagnosticString(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void WriteTo(pb::CodedOutputStream output) {
+ if (X != 0) {
+ output.WriteRawTag(8);
+ output.WriteInt32(X);
+ }
+ if (Y != 0) {
+ output.WriteRawTag(16);
+ output.WriteInt32(Y);
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int CalculateSize() {
+ int size = 0;
+ if (X != 0) {
+ size += 1 + pb::CodedOutputStream.ComputeInt32Size(X);
+ }
+ if (Y != 0) {
+ size += 1 + pb::CodedOutputStream.ComputeInt32Size(Y);
+ }
+ return size;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(Nested other) {
+ if (other == null) {
+ return;
+ }
+ if (other.X != 0) {
+ X = other.X;
+ }
+ if (other.Y != 0) {
+ Y = other.Y;
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ case 8: {
+ X = input.ReadInt32();
+ break;
+ }
+ case 16: {
+ Y = input.ReadInt32();
+ break;
+ }
+ }
+ }
+ }
+
+ }
+
+ }
+ #endregion
+
+ }
+
#endregion
}
diff --git a/csharp/src/Google.Protobuf.Test/TestProtos/UnittestProto3.cs b/csharp/src/Google.Protobuf.Test/TestProtos/UnittestProto3.cs
index d89bbbb0..35bd2137 100644
--- a/csharp/src/Google.Protobuf.Test/TestProtos/UnittestProto3.cs
+++ b/csharp/src/Google.Protobuf.Test/TestProtos/UnittestProto3.cs
@@ -1,5 +1,5 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
-// source: google/protobuf/unittest_proto3.proto
+// source: unittest_proto3.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
@@ -9,11 +9,11 @@ using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Protobuf.TestProtos {
- /// <summary>Holder for reflection information generated from google/protobuf/unittest_proto3.proto</summary>
+ /// <summary>Holder for reflection information generated from unittest_proto3.proto</summary>
public static partial class UnittestProto3Reflection {
#region Descriptor
- /// <summary>File descriptor for google/protobuf/unittest_proto3.proto</summary>
+ /// <summary>File descriptor for unittest_proto3.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
@@ -22,133 +22,135 @@ namespace Google.Protobuf.TestProtos {
static UnittestProto3Reflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
- "CiVnb29nbGUvcHJvdG9idWYvdW5pdHRlc3RfcHJvdG8zLnByb3RvEhFwcm90",
- "b2J1Zl91bml0dGVzdBosZ29vZ2xlL3Byb3RvYnVmL3VuaXR0ZXN0X2ltcG9y",
- "dF9wcm90bzMucHJvdG8i8A8KDFRlc3RBbGxUeXBlcxIUCgxzaW5nbGVfaW50",
- "MzIYASABKAUSFAoMc2luZ2xlX2ludDY0GAIgASgDEhUKDXNpbmdsZV91aW50",
- "MzIYAyABKA0SFQoNc2luZ2xlX3VpbnQ2NBgEIAEoBBIVCg1zaW5nbGVfc2lu",
- "dDMyGAUgASgREhUKDXNpbmdsZV9zaW50NjQYBiABKBISFgoOc2luZ2xlX2Zp",
- "eGVkMzIYByABKAcSFgoOc2luZ2xlX2ZpeGVkNjQYCCABKAYSFwoPc2luZ2xl",
- "X3NmaXhlZDMyGAkgASgPEhcKD3NpbmdsZV9zZml4ZWQ2NBgKIAEoEBIUCgxz",
- "aW5nbGVfZmxvYXQYCyABKAISFQoNc2luZ2xlX2RvdWJsZRgMIAEoARITCgtz",
- "aW5nbGVfYm9vbBgNIAEoCBIVCg1zaW5nbGVfc3RyaW5nGA4gASgJEhQKDHNp",
- "bmdsZV9ieXRlcxgPIAEoDBJMChVzaW5nbGVfbmVzdGVkX21lc3NhZ2UYEiAB",
- "KAsyLS5wcm90b2J1Zl91bml0dGVzdC5UZXN0QWxsVHlwZXMuTmVzdGVkTWVz",
- "c2FnZRJBChZzaW5nbGVfZm9yZWlnbl9tZXNzYWdlGBMgASgLMiEucHJvdG9i",
- "dWZfdW5pdHRlc3QuRm9yZWlnbk1lc3NhZ2USRgoVc2luZ2xlX2ltcG9ydF9t",
- "ZXNzYWdlGBQgASgLMicucHJvdG9idWZfdW5pdHRlc3RfaW1wb3J0LkltcG9y",
- "dE1lc3NhZ2USRgoSc2luZ2xlX25lc3RlZF9lbnVtGBUgASgOMioucHJvdG9i",
- "dWZfdW5pdHRlc3QuVGVzdEFsbFR5cGVzLk5lc3RlZEVudW0SOwoTc2luZ2xl",
- "X2ZvcmVpZ25fZW51bRgWIAEoDjIeLnByb3RvYnVmX3VuaXR0ZXN0LkZvcmVp",
- "Z25FbnVtEkAKEnNpbmdsZV9pbXBvcnRfZW51bRgXIAEoDjIkLnByb3RvYnVm",
- "X3VuaXR0ZXN0X2ltcG9ydC5JbXBvcnRFbnVtElMKHHNpbmdsZV9wdWJsaWNf",
- "aW1wb3J0X21lc3NhZ2UYGiABKAsyLS5wcm90b2J1Zl91bml0dGVzdF9pbXBv",
- "cnQuUHVibGljSW1wb3J0TWVzc2FnZRIWCg5yZXBlYXRlZF9pbnQzMhgfIAMo",
- "BRIWCg5yZXBlYXRlZF9pbnQ2NBggIAMoAxIXCg9yZXBlYXRlZF91aW50MzIY",
- "ISADKA0SFwoPcmVwZWF0ZWRfdWludDY0GCIgAygEEhcKD3JlcGVhdGVkX3Np",
- "bnQzMhgjIAMoERIXCg9yZXBlYXRlZF9zaW50NjQYJCADKBISGAoQcmVwZWF0",
- "ZWRfZml4ZWQzMhglIAMoBxIYChByZXBlYXRlZF9maXhlZDY0GCYgAygGEhkK",
- "EXJlcGVhdGVkX3NmaXhlZDMyGCcgAygPEhkKEXJlcGVhdGVkX3NmaXhlZDY0",
- "GCggAygQEhYKDnJlcGVhdGVkX2Zsb2F0GCkgAygCEhcKD3JlcGVhdGVkX2Rv",
- "dWJsZRgqIAMoARIVCg1yZXBlYXRlZF9ib29sGCsgAygIEhcKD3JlcGVhdGVk",
- "X3N0cmluZxgsIAMoCRIWCg5yZXBlYXRlZF9ieXRlcxgtIAMoDBJOChdyZXBl",
- "YXRlZF9uZXN0ZWRfbWVzc2FnZRgwIAMoCzItLnByb3RvYnVmX3VuaXR0ZXN0",
- "LlRlc3RBbGxUeXBlcy5OZXN0ZWRNZXNzYWdlEkMKGHJlcGVhdGVkX2ZvcmVp",
- "Z25fbWVzc2FnZRgxIAMoCzIhLnByb3RvYnVmX3VuaXR0ZXN0LkZvcmVpZ25N",
- "ZXNzYWdlEkgKF3JlcGVhdGVkX2ltcG9ydF9tZXNzYWdlGDIgAygLMicucHJv",
- "dG9idWZfdW5pdHRlc3RfaW1wb3J0LkltcG9ydE1lc3NhZ2USSAoUcmVwZWF0",
- "ZWRfbmVzdGVkX2VudW0YMyADKA4yKi5wcm90b2J1Zl91bml0dGVzdC5UZXN0",
- "QWxsVHlwZXMuTmVzdGVkRW51bRI9ChVyZXBlYXRlZF9mb3JlaWduX2VudW0Y",
- "NCADKA4yHi5wcm90b2J1Zl91bml0dGVzdC5Gb3JlaWduRW51bRJCChRyZXBl",
- "YXRlZF9pbXBvcnRfZW51bRg1IAMoDjIkLnByb3RvYnVmX3VuaXR0ZXN0X2lt",
- "cG9ydC5JbXBvcnRFbnVtElUKHnJlcGVhdGVkX3B1YmxpY19pbXBvcnRfbWVz",
- "c2FnZRg2IAMoCzItLnByb3RvYnVmX3VuaXR0ZXN0X2ltcG9ydC5QdWJsaWNJ",
- "bXBvcnRNZXNzYWdlEhYKDG9uZW9mX3VpbnQzMhhvIAEoDUgAEk0KFG9uZW9m",
- "X25lc3RlZF9tZXNzYWdlGHAgASgLMi0ucHJvdG9idWZfdW5pdHRlc3QuVGVz",
- "dEFsbFR5cGVzLk5lc3RlZE1lc3NhZ2VIABIWCgxvbmVvZl9zdHJpbmcYcSAB",
- "KAlIABIVCgtvbmVvZl9ieXRlcxhyIAEoDEgAGhsKDU5lc3RlZE1lc3NhZ2US",
- "CgoCYmIYASABKAUiVgoKTmVzdGVkRW51bRIbChdORVNURURfRU5VTV9VTlNQ",
- "RUNJRklFRBAAEgcKA0ZPTxABEgcKA0JBUhACEgcKA0JBWhADEhAKA05FRxD/",
- "//////////8BQg0KC29uZW9mX2ZpZWxkIrsBChJOZXN0ZWRUZXN0QWxsVHlw",
- "ZXMSNAoFY2hpbGQYASABKAsyJS5wcm90b2J1Zl91bml0dGVzdC5OZXN0ZWRU",
- "ZXN0QWxsVHlwZXMSMAoHcGF5bG9hZBgCIAEoCzIfLnByb3RvYnVmX3VuaXR0",
- "ZXN0LlRlc3RBbGxUeXBlcxI9Cg5yZXBlYXRlZF9jaGlsZBgDIAMoCzIlLnBy",
- "b3RvYnVmX3VuaXR0ZXN0Lk5lc3RlZFRlc3RBbGxUeXBlcyI0ChRUZXN0RGVw",
- "cmVjYXRlZEZpZWxkcxIcChBkZXByZWNhdGVkX2ludDMyGAEgASgFQgIYASIb",
- "Cg5Gb3JlaWduTWVzc2FnZRIJCgFjGAEgASgFIjAKElRlc3RSZXNlcnZlZEZp",
- "ZWxkc0oECAIQA0oECA8QEEoECAkQDFIDYmFyUgNiYXoiWgoRVGVzdEZvcmVp",
- "Z25OZXN0ZWQSRQoOZm9yZWlnbl9uZXN0ZWQYASABKAsyLS5wcm90b2J1Zl91",
- "bml0dGVzdC5UZXN0QWxsVHlwZXMuTmVzdGVkTWVzc2FnZSI0ChhUZXN0UmVh",
- "bGx5TGFyZ2VUYWdOdW1iZXISCQoBYRgBIAEoBRINCgJiYhj///9/IAEoBSJV",
- "ChRUZXN0UmVjdXJzaXZlTWVzc2FnZRIyCgFhGAEgASgLMicucHJvdG9idWZf",
- "dW5pdHRlc3QuVGVzdFJlY3Vyc2l2ZU1lc3NhZ2USCQoBaRgCIAEoBSJLChRU",
- "ZXN0TXV0dWFsUmVjdXJzaW9uQRIzCgJiYhgBIAEoCzInLnByb3RvYnVmX3Vu",
- "aXR0ZXN0LlRlc3RNdXR1YWxSZWN1cnNpb25CImIKFFRlc3RNdXR1YWxSZWN1",
- "cnNpb25CEjIKAWEYASABKAsyJy5wcm90b2J1Zl91bml0dGVzdC5UZXN0TXV0",
- "dWFsUmVjdXJzaW9uQRIWCg5vcHRpb25hbF9pbnQzMhgCIAEoBSLrAgoXVGVz",
- "dENhbWVsQ2FzZUZpZWxkTmFtZXMSFgoOUHJpbWl0aXZlRmllbGQYASABKAUS",
- "EwoLU3RyaW5nRmllbGQYAiABKAkSMQoJRW51bUZpZWxkGAMgASgOMh4ucHJv",
- "dG9idWZfdW5pdHRlc3QuRm9yZWlnbkVudW0SNwoMTWVzc2FnZUZpZWxkGAQg",
- "ASgLMiEucHJvdG9idWZfdW5pdHRlc3QuRm9yZWlnbk1lc3NhZ2USHgoWUmVw",
- "ZWF0ZWRQcmltaXRpdmVGaWVsZBgHIAMoBRIbChNSZXBlYXRlZFN0cmluZ0Zp",
- "ZWxkGAggAygJEjkKEVJlcGVhdGVkRW51bUZpZWxkGAkgAygOMh4ucHJvdG9i",
- "dWZfdW5pdHRlc3QuRm9yZWlnbkVudW0SPwoUUmVwZWF0ZWRNZXNzYWdlRmll",
- "bGQYCiADKAsyIS5wcm90b2J1Zl91bml0dGVzdC5Gb3JlaWduTWVzc2FnZSLH",
- "AQoSVGVzdEZpZWxkT3JkZXJpbmdzEhEKCW15X3N0cmluZxgLIAEoCRIOCgZt",
- "eV9pbnQYASABKAMSEAoIbXlfZmxvYXQYZSABKAISUwoVc2luZ2xlX25lc3Rl",
- "ZF9tZXNzYWdlGMgBIAEoCzIzLnByb3RvYnVmX3VuaXR0ZXN0LlRlc3RGaWVs",
- "ZE9yZGVyaW5ncy5OZXN0ZWRNZXNzYWdlGicKDU5lc3RlZE1lc3NhZ2USCgoC",
- "b28YAiABKAMSCgoCYmIYASABKAUiSwoRU3BhcnNlRW51bU1lc3NhZ2USNgoL",
- "c3BhcnNlX2VudW0YASABKA4yIS5wcm90b2J1Zl91bml0dGVzdC5UZXN0U3Bh",
- "cnNlRW51bSIZCglPbmVTdHJpbmcSDAoEZGF0YRgBIAEoCSIaCgpNb3JlU3Ry",
- "aW5nEgwKBGRhdGEYASADKAkiGAoIT25lQnl0ZXMSDAoEZGF0YRgBIAEoDCIZ",
- "CglNb3JlQnl0ZXMSDAoEZGF0YRgBIAEoDCIcCgxJbnQzMk1lc3NhZ2USDAoE",
- "ZGF0YRgBIAEoBSIdCg1VaW50MzJNZXNzYWdlEgwKBGRhdGEYASABKA0iHAoM",
- "SW50NjRNZXNzYWdlEgwKBGRhdGEYASABKAMiHQoNVWludDY0TWVzc2FnZRIM",
- "CgRkYXRhGAEgASgEIhsKC0Jvb2xNZXNzYWdlEgwKBGRhdGEYASABKAgicwoJ",
- "VGVzdE9uZW9mEhEKB2Zvb19pbnQYASABKAVIABIUCgpmb29fc3RyaW5nGAIg",
- "ASgJSAASNgoLZm9vX21lc3NhZ2UYAyABKAsyHy5wcm90b2J1Zl91bml0dGVz",
- "dC5UZXN0QWxsVHlwZXNIAEIFCgNmb28iqgMKD1Rlc3RQYWNrZWRUeXBlcxIY",
- "CgxwYWNrZWRfaW50MzIYWiADKAVCAhABEhgKDHBhY2tlZF9pbnQ2NBhbIAMo",
- "A0ICEAESGQoNcGFja2VkX3VpbnQzMhhcIAMoDUICEAESGQoNcGFja2VkX3Vp",
- "bnQ2NBhdIAMoBEICEAESGQoNcGFja2VkX3NpbnQzMhheIAMoEUICEAESGQoN",
- "cGFja2VkX3NpbnQ2NBhfIAMoEkICEAESGgoOcGFja2VkX2ZpeGVkMzIYYCAD",
- "KAdCAhABEhoKDnBhY2tlZF9maXhlZDY0GGEgAygGQgIQARIbCg9wYWNrZWRf",
- "c2ZpeGVkMzIYYiADKA9CAhABEhsKD3BhY2tlZF9zZml4ZWQ2NBhjIAMoEEIC",
- "EAESGAoMcGFja2VkX2Zsb2F0GGQgAygCQgIQARIZCg1wYWNrZWRfZG91Ymxl",
- "GGUgAygBQgIQARIXCgtwYWNrZWRfYm9vbBhmIAMoCEICEAESNwoLcGFja2Vk",
- "X2VudW0YZyADKA4yHi5wcm90b2J1Zl91bml0dGVzdC5Gb3JlaWduRW51bUIC",
- "EAEiyAMKEVRlc3RVbnBhY2tlZFR5cGVzEhoKDnVucGFja2VkX2ludDMyGFog",
- "AygFQgIQABIaCg51bnBhY2tlZF9pbnQ2NBhbIAMoA0ICEAASGwoPdW5wYWNr",
- "ZWRfdWludDMyGFwgAygNQgIQABIbCg91bnBhY2tlZF91aW50NjQYXSADKARC",
- "AhAAEhsKD3VucGFja2VkX3NpbnQzMhheIAMoEUICEAASGwoPdW5wYWNrZWRf",
- "c2ludDY0GF8gAygSQgIQABIcChB1bnBhY2tlZF9maXhlZDMyGGAgAygHQgIQ",
- "ABIcChB1bnBhY2tlZF9maXhlZDY0GGEgAygGQgIQABIdChF1bnBhY2tlZF9z",
- "Zml4ZWQzMhhiIAMoD0ICEAASHQoRdW5wYWNrZWRfc2ZpeGVkNjQYYyADKBBC",
- "AhAAEhoKDnVucGFja2VkX2Zsb2F0GGQgAygCQgIQABIbCg91bnBhY2tlZF9k",
- "b3VibGUYZSADKAFCAhAAEhkKDXVucGFja2VkX2Jvb2wYZiADKAhCAhAAEjkK",
- "DXVucGFja2VkX2VudW0YZyADKA4yHi5wcm90b2J1Zl91bml0dGVzdC5Gb3Jl",
- "aWduRW51bUICEAAiwAEKI1Rlc3RSZXBlYXRlZFNjYWxhckRpZmZlcmVudFRh",
- "Z1NpemVzEhgKEHJlcGVhdGVkX2ZpeGVkMzIYDCADKAcSFgoOcmVwZWF0ZWRf",
- "aW50MzIYDSADKAUSGQoQcmVwZWF0ZWRfZml4ZWQ2NBj+DyADKAYSFwoOcmVw",
- "ZWF0ZWRfaW50NjQY/w8gAygDEhgKDnJlcGVhdGVkX2Zsb2F0GP7/DyADKAIS",
- "GQoPcmVwZWF0ZWRfdWludDY0GP//DyADKAQiKAobVGVzdENvbW1lbnRJbmpl",
- "Y3Rpb25NZXNzYWdlEgkKAWEYASABKAkiDAoKRm9vUmVxdWVzdCINCgtGb29S",
- "ZXNwb25zZSISChBGb29DbGllbnRNZXNzYWdlIhIKEEZvb1NlcnZlck1lc3Nh",
- "Z2UiDAoKQmFyUmVxdWVzdCINCgtCYXJSZXNwb25zZSpZCgtGb3JlaWduRW51",
- "bRIXChNGT1JFSUdOX1VOU1BFQ0lGSUVEEAASDwoLRk9SRUlHTl9GT08QBBIP",
- "CgtGT1JFSUdOX0JBUhAFEg8KC0ZPUkVJR05fQkFaEAYqdQoUVGVzdEVudW1X",
- "aXRoRHVwVmFsdWUSKAokVEVTVF9FTlVNX1dJVEhfRFVQX1ZBTFVFX1VOU1BF",
- "Q0lGSUVEEAASCAoERk9PMRABEggKBEJBUjEQAhIHCgNCQVoQAxIICgRGT08y",
- "EAESCAoEQkFSMhACGgIQASqdAQoOVGVzdFNwYXJzZUVudW0SIAocVEVTVF9T",
- "UEFSU0VfRU5VTV9VTlNQRUNJRklFRBAAEgwKCFNQQVJTRV9BEHsSDgoIU1BB",
- "UlNFX0IQpucDEg8KCFNQQVJTRV9DELKxgAYSFQoIU1BBUlNFX0QQ8f//////",
- "////ARIVCghTUEFSU0VfRRC03vz///////8BEgwKCFNQQVJTRV9HEAIymQEK",
- "C1Rlc3RTZXJ2aWNlEkQKA0ZvbxIdLnByb3RvYnVmX3VuaXR0ZXN0LkZvb1Jl",
- "cXVlc3QaHi5wcm90b2J1Zl91bml0dGVzdC5Gb29SZXNwb25zZRJECgNCYXIS",
- "HS5wcm90b2J1Zl91bml0dGVzdC5CYXJSZXF1ZXN0Gh4ucHJvdG9idWZfdW5p",
- "dHRlc3QuQmFyUmVzcG9uc2VCOkINVW5pdHRlc3RQcm90b0gBgAEBiAEBkAEB",
- "+AEBqgIaR29vZ2xlLlByb3RvYnVmLlRlc3RQcm90b3NiBnByb3RvMw=="));
+ "ChV1bml0dGVzdF9wcm90bzMucHJvdG8SEnByb3RvYnVmX3VuaXR0ZXN0Mxoc",
+ "dW5pdHRlc3RfaW1wb3J0X3Byb3RvMy5wcm90byL5DwoMVGVzdEFsbFR5cGVz",
+ "EhQKDHNpbmdsZV9pbnQzMhgBIAEoBRIUCgxzaW5nbGVfaW50NjQYAiABKAMS",
+ "FQoNc2luZ2xlX3VpbnQzMhgDIAEoDRIVCg1zaW5nbGVfdWludDY0GAQgASgE",
+ "EhUKDXNpbmdsZV9zaW50MzIYBSABKBESFQoNc2luZ2xlX3NpbnQ2NBgGIAEo",
+ "EhIWCg5zaW5nbGVfZml4ZWQzMhgHIAEoBxIWCg5zaW5nbGVfZml4ZWQ2NBgI",
+ "IAEoBhIXCg9zaW5nbGVfc2ZpeGVkMzIYCSABKA8SFwoPc2luZ2xlX3NmaXhl",
+ "ZDY0GAogASgQEhQKDHNpbmdsZV9mbG9hdBgLIAEoAhIVCg1zaW5nbGVfZG91",
+ "YmxlGAwgASgBEhMKC3NpbmdsZV9ib29sGA0gASgIEhUKDXNpbmdsZV9zdHJp",
+ "bmcYDiABKAkSFAoMc2luZ2xlX2J5dGVzGA8gASgMEk0KFXNpbmdsZV9uZXN0",
+ "ZWRfbWVzc2FnZRgSIAEoCzIuLnByb3RvYnVmX3VuaXR0ZXN0My5UZXN0QWxs",
+ "VHlwZXMuTmVzdGVkTWVzc2FnZRJCChZzaW5nbGVfZm9yZWlnbl9tZXNzYWdl",
+ "GBMgASgLMiIucHJvdG9idWZfdW5pdHRlc3QzLkZvcmVpZ25NZXNzYWdlEkYK",
+ "FXNpbmdsZV9pbXBvcnRfbWVzc2FnZRgUIAEoCzInLnByb3RvYnVmX3VuaXR0",
+ "ZXN0X2ltcG9ydC5JbXBvcnRNZXNzYWdlEkcKEnNpbmdsZV9uZXN0ZWRfZW51",
+ "bRgVIAEoDjIrLnByb3RvYnVmX3VuaXR0ZXN0My5UZXN0QWxsVHlwZXMuTmVz",
+ "dGVkRW51bRI8ChNzaW5nbGVfZm9yZWlnbl9lbnVtGBYgASgOMh8ucHJvdG9i",
+ "dWZfdW5pdHRlc3QzLkZvcmVpZ25FbnVtEkAKEnNpbmdsZV9pbXBvcnRfZW51",
+ "bRgXIAEoDjIkLnByb3RvYnVmX3VuaXR0ZXN0X2ltcG9ydC5JbXBvcnRFbnVt",
+ "ElMKHHNpbmdsZV9wdWJsaWNfaW1wb3J0X21lc3NhZ2UYGiABKAsyLS5wcm90",
+ "b2J1Zl91bml0dGVzdF9pbXBvcnQuUHVibGljSW1wb3J0TWVzc2FnZRIWCg5y",
+ "ZXBlYXRlZF9pbnQzMhgfIAMoBRIWCg5yZXBlYXRlZF9pbnQ2NBggIAMoAxIX",
+ "Cg9yZXBlYXRlZF91aW50MzIYISADKA0SFwoPcmVwZWF0ZWRfdWludDY0GCIg",
+ "AygEEhcKD3JlcGVhdGVkX3NpbnQzMhgjIAMoERIXCg9yZXBlYXRlZF9zaW50",
+ "NjQYJCADKBISGAoQcmVwZWF0ZWRfZml4ZWQzMhglIAMoBxIYChByZXBlYXRl",
+ "ZF9maXhlZDY0GCYgAygGEhkKEXJlcGVhdGVkX3NmaXhlZDMyGCcgAygPEhkK",
+ "EXJlcGVhdGVkX3NmaXhlZDY0GCggAygQEhYKDnJlcGVhdGVkX2Zsb2F0GCkg",
+ "AygCEhcKD3JlcGVhdGVkX2RvdWJsZRgqIAMoARIVCg1yZXBlYXRlZF9ib29s",
+ "GCsgAygIEhcKD3JlcGVhdGVkX3N0cmluZxgsIAMoCRIWCg5yZXBlYXRlZF9i",
+ "eXRlcxgtIAMoDBJPChdyZXBlYXRlZF9uZXN0ZWRfbWVzc2FnZRgwIAMoCzIu",
+ "LnByb3RvYnVmX3VuaXR0ZXN0My5UZXN0QWxsVHlwZXMuTmVzdGVkTWVzc2Fn",
+ "ZRJEChhyZXBlYXRlZF9mb3JlaWduX21lc3NhZ2UYMSADKAsyIi5wcm90b2J1",
+ "Zl91bml0dGVzdDMuRm9yZWlnbk1lc3NhZ2USSAoXcmVwZWF0ZWRfaW1wb3J0",
+ "X21lc3NhZ2UYMiADKAsyJy5wcm90b2J1Zl91bml0dGVzdF9pbXBvcnQuSW1w",
+ "b3J0TWVzc2FnZRJJChRyZXBlYXRlZF9uZXN0ZWRfZW51bRgzIAMoDjIrLnBy",
+ "b3RvYnVmX3VuaXR0ZXN0My5UZXN0QWxsVHlwZXMuTmVzdGVkRW51bRI+ChVy",
+ "ZXBlYXRlZF9mb3JlaWduX2VudW0YNCADKA4yHy5wcm90b2J1Zl91bml0dGVz",
+ "dDMuRm9yZWlnbkVudW0SQgoUcmVwZWF0ZWRfaW1wb3J0X2VudW0YNSADKA4y",
+ "JC5wcm90b2J1Zl91bml0dGVzdF9pbXBvcnQuSW1wb3J0RW51bRJVCh5yZXBl",
+ "YXRlZF9wdWJsaWNfaW1wb3J0X21lc3NhZ2UYNiADKAsyLS5wcm90b2J1Zl91",
+ "bml0dGVzdF9pbXBvcnQuUHVibGljSW1wb3J0TWVzc2FnZRIWCgxvbmVvZl91",
+ "aW50MzIYbyABKA1IABJOChRvbmVvZl9uZXN0ZWRfbWVzc2FnZRhwIAEoCzIu",
+ "LnByb3RvYnVmX3VuaXR0ZXN0My5UZXN0QWxsVHlwZXMuTmVzdGVkTWVzc2Fn",
+ "ZUgAEhYKDG9uZW9mX3N0cmluZxhxIAEoCUgAEhUKC29uZW9mX2J5dGVzGHIg",
+ "ASgMSAAaGwoNTmVzdGVkTWVzc2FnZRIKCgJiYhgBIAEoBSJWCgpOZXN0ZWRF",
+ "bnVtEhsKF05FU1RFRF9FTlVNX1VOU1BFQ0lGSUVEEAASBwoDRk9PEAESBwoD",
+ "QkFSEAISBwoDQkFaEAMSEAoDTkVHEP///////////wFCDQoLb25lb2ZfZmll",
+ "bGQivgEKEk5lc3RlZFRlc3RBbGxUeXBlcxI1CgVjaGlsZBgBIAEoCzImLnBy",
+ "b3RvYnVmX3VuaXR0ZXN0My5OZXN0ZWRUZXN0QWxsVHlwZXMSMQoHcGF5bG9h",
+ "ZBgCIAEoCzIgLnByb3RvYnVmX3VuaXR0ZXN0My5UZXN0QWxsVHlwZXMSPgoO",
+ "cmVwZWF0ZWRfY2hpbGQYAyADKAsyJi5wcm90b2J1Zl91bml0dGVzdDMuTmVz",
+ "dGVkVGVzdEFsbFR5cGVzIjQKFFRlc3REZXByZWNhdGVkRmllbGRzEhwKEGRl",
+ "cHJlY2F0ZWRfaW50MzIYASABKAVCAhgBIhsKDkZvcmVpZ25NZXNzYWdlEgkK",
+ "AWMYASABKAUiMAoSVGVzdFJlc2VydmVkRmllbGRzSgQIAhADSgQIDxAQSgQI",
+ "CRAMUgNiYXJSA2JheiJbChFUZXN0Rm9yZWlnbk5lc3RlZBJGCg5mb3JlaWdu",
+ "X25lc3RlZBgBIAEoCzIuLnByb3RvYnVmX3VuaXR0ZXN0My5UZXN0QWxsVHlw",
+ "ZXMuTmVzdGVkTWVzc2FnZSI0ChhUZXN0UmVhbGx5TGFyZ2VUYWdOdW1iZXIS",
+ "CQoBYRgBIAEoBRINCgJiYhj///9/IAEoBSJWChRUZXN0UmVjdXJzaXZlTWVz",
+ "c2FnZRIzCgFhGAEgASgLMigucHJvdG9idWZfdW5pdHRlc3QzLlRlc3RSZWN1",
+ "cnNpdmVNZXNzYWdlEgkKAWkYAiABKAUiTAoUVGVzdE11dHVhbFJlY3Vyc2lv",
+ "bkESNAoCYmIYASABKAsyKC5wcm90b2J1Zl91bml0dGVzdDMuVGVzdE11dHVh",
+ "bFJlY3Vyc2lvbkIiYwoUVGVzdE11dHVhbFJlY3Vyc2lvbkISMwoBYRgBIAEo",
+ "CzIoLnByb3RvYnVmX3VuaXR0ZXN0My5UZXN0TXV0dWFsUmVjdXJzaW9uQRIW",
+ "Cg5vcHRpb25hbF9pbnQzMhgCIAEoBSJNChJUZXN0RW51bUFsbG93QWxpYXMS",
+ "NwoFdmFsdWUYASABKA4yKC5wcm90b2J1Zl91bml0dGVzdDMuVGVzdEVudW1X",
+ "aXRoRHVwVmFsdWUi7wIKF1Rlc3RDYW1lbENhc2VGaWVsZE5hbWVzEhYKDlBy",
+ "aW1pdGl2ZUZpZWxkGAEgASgFEhMKC1N0cmluZ0ZpZWxkGAIgASgJEjIKCUVu",
+ "dW1GaWVsZBgDIAEoDjIfLnByb3RvYnVmX3VuaXR0ZXN0My5Gb3JlaWduRW51",
+ "bRI4CgxNZXNzYWdlRmllbGQYBCABKAsyIi5wcm90b2J1Zl91bml0dGVzdDMu",
+ "Rm9yZWlnbk1lc3NhZ2USHgoWUmVwZWF0ZWRQcmltaXRpdmVGaWVsZBgHIAMo",
+ "BRIbChNSZXBlYXRlZFN0cmluZ0ZpZWxkGAggAygJEjoKEVJlcGVhdGVkRW51",
+ "bUZpZWxkGAkgAygOMh8ucHJvdG9idWZfdW5pdHRlc3QzLkZvcmVpZ25FbnVt",
+ "EkAKFFJlcGVhdGVkTWVzc2FnZUZpZWxkGAogAygLMiIucHJvdG9idWZfdW5p",
+ "dHRlc3QzLkZvcmVpZ25NZXNzYWdlIsgBChJUZXN0RmllbGRPcmRlcmluZ3MS",
+ "EQoJbXlfc3RyaW5nGAsgASgJEg4KBm15X2ludBgBIAEoAxIQCghteV9mbG9h",
+ "dBhlIAEoAhJUChVzaW5nbGVfbmVzdGVkX21lc3NhZ2UYyAEgASgLMjQucHJv",
+ "dG9idWZfdW5pdHRlc3QzLlRlc3RGaWVsZE9yZGVyaW5ncy5OZXN0ZWRNZXNz",
+ "YWdlGicKDU5lc3RlZE1lc3NhZ2USCgoCb28YAiABKAMSCgoCYmIYASABKAUi",
+ "TAoRU3BhcnNlRW51bU1lc3NhZ2USNwoLc3BhcnNlX2VudW0YASABKA4yIi5w",
+ "cm90b2J1Zl91bml0dGVzdDMuVGVzdFNwYXJzZUVudW0iGQoJT25lU3RyaW5n",
+ "EgwKBGRhdGEYASABKAkiGgoKTW9yZVN0cmluZxIMCgRkYXRhGAEgAygJIhgK",
+ "CE9uZUJ5dGVzEgwKBGRhdGEYASABKAwiGQoJTW9yZUJ5dGVzEgwKBGRhdGEY",
+ "ASABKAwiHAoMSW50MzJNZXNzYWdlEgwKBGRhdGEYASABKAUiHQoNVWludDMy",
+ "TWVzc2FnZRIMCgRkYXRhGAEgASgNIhwKDEludDY0TWVzc2FnZRIMCgRkYXRh",
+ "GAEgASgDIh0KDVVpbnQ2NE1lc3NhZ2USDAoEZGF0YRgBIAEoBCIbCgtCb29s",
+ "TWVzc2FnZRIMCgRkYXRhGAEgASgIInQKCVRlc3RPbmVvZhIRCgdmb29faW50",
+ "GAEgASgFSAASFAoKZm9vX3N0cmluZxgCIAEoCUgAEjcKC2Zvb19tZXNzYWdl",
+ "GAMgASgLMiAucHJvdG9idWZfdW5pdHRlc3QzLlRlc3RBbGxUeXBlc0gAQgUK",
+ "A2ZvbyKrAwoPVGVzdFBhY2tlZFR5cGVzEhgKDHBhY2tlZF9pbnQzMhhaIAMo",
+ "BUICEAESGAoMcGFja2VkX2ludDY0GFsgAygDQgIQARIZCg1wYWNrZWRfdWlu",
+ "dDMyGFwgAygNQgIQARIZCg1wYWNrZWRfdWludDY0GF0gAygEQgIQARIZCg1w",
+ "YWNrZWRfc2ludDMyGF4gAygRQgIQARIZCg1wYWNrZWRfc2ludDY0GF8gAygS",
+ "QgIQARIaCg5wYWNrZWRfZml4ZWQzMhhgIAMoB0ICEAESGgoOcGFja2VkX2Zp",
+ "eGVkNjQYYSADKAZCAhABEhsKD3BhY2tlZF9zZml4ZWQzMhhiIAMoD0ICEAES",
+ "GwoPcGFja2VkX3NmaXhlZDY0GGMgAygQQgIQARIYCgxwYWNrZWRfZmxvYXQY",
+ "ZCADKAJCAhABEhkKDXBhY2tlZF9kb3VibGUYZSADKAFCAhABEhcKC3BhY2tl",
+ "ZF9ib29sGGYgAygIQgIQARI4CgtwYWNrZWRfZW51bRhnIAMoDjIfLnByb3Rv",
+ "YnVmX3VuaXR0ZXN0My5Gb3JlaWduRW51bUICEAEiyQMKEVRlc3RVbnBhY2tl",
+ "ZFR5cGVzEhoKDnVucGFja2VkX2ludDMyGFogAygFQgIQABIaCg51bnBhY2tl",
+ "ZF9pbnQ2NBhbIAMoA0ICEAASGwoPdW5wYWNrZWRfdWludDMyGFwgAygNQgIQ",
+ "ABIbCg91bnBhY2tlZF91aW50NjQYXSADKARCAhAAEhsKD3VucGFja2VkX3Np",
+ "bnQzMhheIAMoEUICEAASGwoPdW5wYWNrZWRfc2ludDY0GF8gAygSQgIQABIc",
+ "ChB1bnBhY2tlZF9maXhlZDMyGGAgAygHQgIQABIcChB1bnBhY2tlZF9maXhl",
+ "ZDY0GGEgAygGQgIQABIdChF1bnBhY2tlZF9zZml4ZWQzMhhiIAMoD0ICEAAS",
+ "HQoRdW5wYWNrZWRfc2ZpeGVkNjQYYyADKBBCAhAAEhoKDnVucGFja2VkX2Zs",
+ "b2F0GGQgAygCQgIQABIbCg91bnBhY2tlZF9kb3VibGUYZSADKAFCAhAAEhkK",
+ "DXVucGFja2VkX2Jvb2wYZiADKAhCAhAAEjoKDXVucGFja2VkX2VudW0YZyAD",
+ "KA4yHy5wcm90b2J1Zl91bml0dGVzdDMuRm9yZWlnbkVudW1CAhAAIsABCiNU",
+ "ZXN0UmVwZWF0ZWRTY2FsYXJEaWZmZXJlbnRUYWdTaXplcxIYChByZXBlYXRl",
+ "ZF9maXhlZDMyGAwgAygHEhYKDnJlcGVhdGVkX2ludDMyGA0gAygFEhkKEHJl",
+ "cGVhdGVkX2ZpeGVkNjQY/g8gAygGEhcKDnJlcGVhdGVkX2ludDY0GP8PIAMo",
+ "AxIYCg5yZXBlYXRlZF9mbG9hdBj+/w8gAygCEhkKD3JlcGVhdGVkX3VpbnQ2",
+ "NBj//w8gAygEIigKG1Rlc3RDb21tZW50SW5qZWN0aW9uTWVzc2FnZRIJCgFh",
+ "GAEgASgJIgwKCkZvb1JlcXVlc3QiDQoLRm9vUmVzcG9uc2UiEgoQRm9vQ2xp",
+ "ZW50TWVzc2FnZSISChBGb29TZXJ2ZXJNZXNzYWdlIgwKCkJhclJlcXVlc3Qi",
+ "DQoLQmFyUmVzcG9uc2UqWQoLRm9yZWlnbkVudW0SFwoTRk9SRUlHTl9VTlNQ",
+ "RUNJRklFRBAAEg8KC0ZPUkVJR05fRk9PEAQSDwoLRk9SRUlHTl9CQVIQBRIP",
+ "CgtGT1JFSUdOX0JBWhAGKnUKFFRlc3RFbnVtV2l0aER1cFZhbHVlEigKJFRF",
+ "U1RfRU5VTV9XSVRIX0RVUF9WQUxVRV9VTlNQRUNJRklFRBAAEggKBEZPTzEQ",
+ "ARIICgRCQVIxEAISBwoDQkFaEAMSCAoERk9PMhABEggKBEJBUjIQAhoCEAEq",
+ "nQEKDlRlc3RTcGFyc2VFbnVtEiAKHFRFU1RfU1BBUlNFX0VOVU1fVU5TUEVD",
+ "SUZJRUQQABIMCghTUEFSU0VfQRB7Eg4KCFNQQVJTRV9CEKbnAxIPCghTUEFS",
+ "U0VfQxCysYAGEhUKCFNQQVJTRV9EEPH//////////wESFQoIU1BBUlNFX0UQ",
+ "tN78////////ARIMCghTUEFSU0VfRxACMp0BCgtUZXN0U2VydmljZRJGCgNG",
+ "b28SHi5wcm90b2J1Zl91bml0dGVzdDMuRm9vUmVxdWVzdBofLnByb3RvYnVm",
+ "X3VuaXR0ZXN0My5Gb29SZXNwb25zZRJGCgNCYXISHi5wcm90b2J1Zl91bml0",
+ "dGVzdDMuQmFyUmVxdWVzdBofLnByb3RvYnVmX3VuaXR0ZXN0My5CYXJSZXNw",
+ "b25zZUIsQg1Vbml0dGVzdFByb3RvqgIaR29vZ2xlLlByb3RvYnVmLlRlc3RQ",
+ "cm90b3NiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Protobuf.TestProtos.UnittestImportProto3Reflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(new[] {typeof(global::Google.Protobuf.TestProtos.ForeignEnum), typeof(global::Google.Protobuf.TestProtos.TestEnumWithDupValue), typeof(global::Google.Protobuf.TestProtos.TestSparseEnum), }, new pbr::GeneratedClrTypeInfo[] {
@@ -162,6 +164,7 @@ namespace Google.Protobuf.TestProtos {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.TestRecursiveMessage), global::Google.Protobuf.TestProtos.TestRecursiveMessage.Parser, new[]{ "A", "I" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.TestMutualRecursionA), global::Google.Protobuf.TestProtos.TestMutualRecursionA.Parser, new[]{ "Bb" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.TestMutualRecursionB), global::Google.Protobuf.TestProtos.TestMutualRecursionB.Parser, new[]{ "A", "OptionalInt32" }, null, null, null),
+ new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.TestEnumAllowAlias), global::Google.Protobuf.TestProtos.TestEnumAllowAlias.Parser, new[]{ "Value" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.TestCamelCaseFieldNames), global::Google.Protobuf.TestProtos.TestCamelCaseFieldNames.Parser, new[]{ "PrimitiveField", "StringField", "EnumField", "MessageField", "RepeatedPrimitiveField", "RepeatedStringField", "RepeatedEnumField", "RepeatedMessageField" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.TestFieldOrderings), global::Google.Protobuf.TestProtos.TestFieldOrderings.Parser, new[]{ "MyString", "MyInt", "MyFloat", "SingleNestedMessage" }, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.TestFieldOrderings.Types.NestedMessage), global::Google.Protobuf.TestProtos.TestFieldOrderings.Types.NestedMessage.Parser, new[]{ "Oo", "Bb" }, null, null, null)}),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.SparseEnumMessage), global::Google.Protobuf.TestProtos.SparseEnumMessage.Parser, new[]{ "SparseEnum" }, null, null, null),
@@ -206,8 +209,8 @@ namespace Google.Protobuf.TestProtos {
[pbr::OriginalName("FOO1")] Foo1 = 1,
[pbr::OriginalName("BAR1")] Bar1 = 2,
[pbr::OriginalName("BAZ")] Baz = 3,
- [pbr::OriginalName("FOO2")] Foo2 = 1,
- [pbr::OriginalName("BAR2")] Bar2 = 2,
+ [pbr::OriginalName("FOO2", PreferredAlias = false)] Foo2 = 1,
+ [pbr::OriginalName("BAR2", PreferredAlias = false)] Bar2 = 2,
}
/// <summary>
@@ -1334,7 +1337,10 @@ namespace Google.Protobuf.TestProtos {
OneofUint32 = other.OneofUint32;
break;
case OneofFieldOneofCase.OneofNestedMessage:
- OneofNestedMessage = other.OneofNestedMessage;
+ if (OneofNestedMessage == null) {
+ OneofNestedMessage = new global::Google.Protobuf.TestProtos.TestAllTypes.Types.NestedMessage();
+ }
+ OneofNestedMessage.MergeFrom(other.OneofNestedMessage);
break;
case OneofFieldOneofCase.OneofString:
OneofString = other.OneofString;
@@ -2939,6 +2945,123 @@ namespace Google.Protobuf.TestProtos {
}
+ public sealed partial class TestEnumAllowAlias : pb::IMessage<TestEnumAllowAlias> {
+ private static readonly pb::MessageParser<TestEnumAllowAlias> _parser = new pb::MessageParser<TestEnumAllowAlias>(() => new TestEnumAllowAlias());
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pb::MessageParser<TestEnumAllowAlias> Parser { get { return _parser; } }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[10]; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public TestEnumAllowAlias() {
+ OnConstruction();
+ }
+
+ partial void OnConstruction();
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public TestEnumAllowAlias(TestEnumAllowAlias other) : this() {
+ value_ = other.value_;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public TestEnumAllowAlias Clone() {
+ return new TestEnumAllowAlias(this);
+ }
+
+ /// <summary>Field number for the "value" field.</summary>
+ public const int ValueFieldNumber = 1;
+ private global::Google.Protobuf.TestProtos.TestEnumWithDupValue value_ = 0;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public global::Google.Protobuf.TestProtos.TestEnumWithDupValue Value {
+ get { return value_; }
+ set {
+ value_ = value;
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override bool Equals(object other) {
+ return Equals(other as TestEnumAllowAlias);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool Equals(TestEnumAllowAlias other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
+ }
+ if (ReferenceEquals(other, this)) {
+ return true;
+ }
+ if (Value != other.Value) return false;
+ return true;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override int GetHashCode() {
+ int hash = 1;
+ if (Value != 0) hash ^= Value.GetHashCode();
+ return hash;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override string ToString() {
+ return pb::JsonFormatter.ToDiagnosticString(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void WriteTo(pb::CodedOutputStream output) {
+ if (Value != 0) {
+ output.WriteRawTag(8);
+ output.WriteEnum((int) Value);
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int CalculateSize() {
+ int size = 0;
+ if (Value != 0) {
+ size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Value);
+ }
+ return size;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(TestEnumAllowAlias other) {
+ if (other == null) {
+ return;
+ }
+ if (other.Value != 0) {
+ Value = other.Value;
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ case 8: {
+ value_ = (global::Google.Protobuf.TestProtos.TestEnumWithDupValue) input.ReadEnum();
+ break;
+ }
+ }
+ }
+ }
+
+ }
+
/// <summary>
/// Test message with CamelCase field names. This violates Protocol Buffer
/// standard style.
@@ -2950,7 +3073,7 @@ namespace Google.Protobuf.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[10]; }
+ get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[11]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -3243,7 +3366,7 @@ namespace Google.Protobuf.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[11]; }
+ get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[12]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -3607,7 +3730,7 @@ namespace Google.Protobuf.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[12]; }
+ get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[13]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -3727,7 +3850,7 @@ namespace Google.Protobuf.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[13]; }
+ get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[14]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -3844,7 +3967,7 @@ namespace Google.Protobuf.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[14]; }
+ get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[15]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -3953,7 +4076,7 @@ namespace Google.Protobuf.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[15]; }
+ get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[16]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -4070,7 +4193,7 @@ namespace Google.Protobuf.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[16]; }
+ get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[17]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -4190,7 +4313,7 @@ namespace Google.Protobuf.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[17]; }
+ get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[18]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -4307,7 +4430,7 @@ namespace Google.Protobuf.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[18]; }
+ get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[19]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -4424,7 +4547,7 @@ namespace Google.Protobuf.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[19]; }
+ get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[20]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -4541,7 +4664,7 @@ namespace Google.Protobuf.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[20]; }
+ get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[21]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -4658,7 +4781,7 @@ namespace Google.Protobuf.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[21]; }
+ get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[22]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -4778,7 +4901,7 @@ namespace Google.Protobuf.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[22]; }
+ get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[23]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -4946,7 +5069,10 @@ namespace Google.Protobuf.TestProtos {
FooString = other.FooString;
break;
case FooOneofCase.FooMessage:
- FooMessage = other.FooMessage;
+ if (FooMessage == null) {
+ FooMessage = new global::Google.Protobuf.TestProtos.TestAllTypes();
+ }
+ FooMessage.MergeFrom(other.FooMessage);
break;
}
@@ -4990,7 +5116,7 @@ namespace Google.Protobuf.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[23]; }
+ get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[24]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -5377,7 +5503,7 @@ namespace Google.Protobuf.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[24]; }
+ get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[25]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -5760,7 +5886,7 @@ namespace Google.Protobuf.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[25]; }
+ get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[26]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -5989,7 +6115,7 @@ namespace Google.Protobuf.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[26]; }
+ get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[27]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -6112,7 +6238,7 @@ namespace Google.Protobuf.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[27]; }
+ get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[28]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -6201,7 +6327,7 @@ namespace Google.Protobuf.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[28]; }
+ get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[29]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -6290,7 +6416,7 @@ namespace Google.Protobuf.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[29]; }
+ get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[30]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -6379,7 +6505,7 @@ namespace Google.Protobuf.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[30]; }
+ get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[31]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -6468,7 +6594,7 @@ namespace Google.Protobuf.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[31]; }
+ get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[32]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -6557,7 +6683,7 @@ namespace Google.Protobuf.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[32]; }
+ get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[33]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
diff --git a/csharp/src/Google.Protobuf.Test/TestProtos/UnittestWellKnownTypes.cs b/csharp/src/Google.Protobuf.Test/TestProtos/UnittestWellKnownTypes.cs
index 2c7f0e0e..9c415d6c 100644
--- a/csharp/src/Google.Protobuf.Test/TestProtos/UnittestWellKnownTypes.cs
+++ b/csharp/src/Google.Protobuf.Test/TestProtos/UnittestWellKnownTypes.cs
@@ -1890,31 +1890,58 @@ namespace Google.Protobuf.TestProtos {
}
switch (other.OneofFieldCase) {
case OneofFieldOneofCase.AnyField:
- AnyField = other.AnyField;
+ if (AnyField == null) {
+ AnyField = new global::Google.Protobuf.WellKnownTypes.Any();
+ }
+ AnyField.MergeFrom(other.AnyField);
break;
case OneofFieldOneofCase.ApiField:
- ApiField = other.ApiField;
+ if (ApiField == null) {
+ ApiField = new global::Google.Protobuf.WellKnownTypes.Api();
+ }
+ ApiField.MergeFrom(other.ApiField);
break;
case OneofFieldOneofCase.DurationField:
- DurationField = other.DurationField;
+ if (DurationField == null) {
+ DurationField = new global::Google.Protobuf.WellKnownTypes.Duration();
+ }
+ DurationField.MergeFrom(other.DurationField);
break;
case OneofFieldOneofCase.EmptyField:
- EmptyField = other.EmptyField;
+ if (EmptyField == null) {
+ EmptyField = new global::Google.Protobuf.WellKnownTypes.Empty();
+ }
+ EmptyField.MergeFrom(other.EmptyField);
break;
case OneofFieldOneofCase.FieldMaskField:
- FieldMaskField = other.FieldMaskField;
+ if (FieldMaskField == null) {
+ FieldMaskField = new global::Google.Protobuf.WellKnownTypes.FieldMask();
+ }
+ FieldMaskField.MergeFrom(other.FieldMaskField);
break;
case OneofFieldOneofCase.SourceContextField:
- SourceContextField = other.SourceContextField;
+ if (SourceContextField == null) {
+ SourceContextField = new global::Google.Protobuf.WellKnownTypes.SourceContext();
+ }
+ SourceContextField.MergeFrom(other.SourceContextField);
break;
case OneofFieldOneofCase.StructField:
- StructField = other.StructField;
+ if (StructField == null) {
+ StructField = new global::Google.Protobuf.WellKnownTypes.Struct();
+ }
+ StructField.MergeFrom(other.StructField);
break;
case OneofFieldOneofCase.TimestampField:
- TimestampField = other.TimestampField;
+ if (TimestampField == null) {
+ TimestampField = new global::Google.Protobuf.WellKnownTypes.Timestamp();
+ }
+ TimestampField.MergeFrom(other.TimestampField);
break;
case OneofFieldOneofCase.TypeField:
- TypeField = other.TypeField;
+ if (TypeField == null) {
+ TypeField = new global::Google.Protobuf.WellKnownTypes.Type();
+ }
+ TypeField.MergeFrom(other.TypeField);
break;
case OneofFieldOneofCase.DoubleField:
DoubleField = other.DoubleField;
diff --git a/csharp/src/Google.Protobuf.Test/WellKnownTypes/AnyTest.cs b/csharp/src/Google.Protobuf.Test/WellKnownTypes/AnyTest.cs
index 4aecc998..6ca1e1f0 100644
--- a/csharp/src/Google.Protobuf.Test/WellKnownTypes/AnyTest.cs
+++ b/csharp/src/Google.Protobuf.Test/WellKnownTypes/AnyTest.cs
@@ -42,7 +42,7 @@ namespace Google.Protobuf.WellKnownTypes
{
var message = SampleMessages.CreateFullTestAllTypes();
var any = Any.Pack(message);
- Assert.AreEqual("type.googleapis.com/protobuf_unittest.TestAllTypes", any.TypeUrl);
+ Assert.AreEqual("type.googleapis.com/protobuf_unittest3.TestAllTypes", any.TypeUrl);
Assert.AreEqual(message.CalculateSize(), any.Value.Length);
}
@@ -51,7 +51,7 @@ namespace Google.Protobuf.WellKnownTypes
{
var message = SampleMessages.CreateFullTestAllTypes();
var any = Any.Pack(message, "foo.bar/baz");
- Assert.AreEqual("foo.bar/baz/protobuf_unittest.TestAllTypes", any.TypeUrl);
+ Assert.AreEqual("foo.bar/baz/protobuf_unittest3.TestAllTypes", any.TypeUrl);
Assert.AreEqual(message.CalculateSize(), any.Value.Length);
}
@@ -60,7 +60,7 @@ namespace Google.Protobuf.WellKnownTypes
{
var message = SampleMessages.CreateFullTestAllTypes();
var any = Any.Pack(message, "foo.bar/baz/");
- Assert.AreEqual("foo.bar/baz/protobuf_unittest.TestAllTypes", any.TypeUrl);
+ Assert.AreEqual("foo.bar/baz/protobuf_unittest3.TestAllTypes", any.TypeUrl);
Assert.AreEqual(message.CalculateSize(), any.Value.Length);
}
@@ -91,6 +91,24 @@ namespace Google.Protobuf.WellKnownTypes
}
[Test]
+ public void TryUnpack_WrongType()
+ {
+ var message = SampleMessages.CreateFullTestAllTypes();
+ var any = Any.Pack(message);
+ Assert.False(any.TryUnpack(out TestOneof unpacked));
+ Assert.Null(unpacked);
+ }
+
+ [Test]
+ public void TryUnpack_RightType()
+ {
+ var message = SampleMessages.CreateFullTestAllTypes();
+ var any = Any.Pack(message);
+ Assert.IsTrue(any.TryUnpack(out TestAllTypes unpacked));
+ Assert.AreEqual(message, unpacked);
+ }
+
+ [Test]
public void ToString_WithValues()
{
var message = SampleMessages.CreateFullTestAllTypes();
@@ -100,6 +118,16 @@ namespace Google.Protobuf.WellKnownTypes
}
[Test]
+ [TestCase("proto://foo.bar", "foo.bar")]
+ [TestCase("/foo/bar/baz", "baz")]
+ [TestCase("foobar", "")]
+ public void GetTypeName(string typeUrl, string expectedTypeName)
+ {
+ var any = new Any { TypeUrl = typeUrl };
+ Assert.AreEqual(expectedTypeName, Any.GetTypeName(typeUrl));
+ }
+
+ [Test]
public void ToString_Empty()
{
var any = new Any();
diff --git a/csharp/src/Google.Protobuf.Test/project.json b/csharp/src/Google.Protobuf.Test/project.json
deleted file mode 100644
index 3a73bf7a..00000000
--- a/csharp/src/Google.Protobuf.Test/project.json
+++ /dev/null
@@ -1,44 +0,0 @@
-{
- "buildOptions": {
- "debugType": "portable",
- "keyFile": "../../keys/Google.Protobuf.snk"
- },
-
- "configurations": {
- "Debug": {
- "buildOptions": {
- "define": [ "DEBUG", "TRACE" ]
- }
- },
- "Release": {
- "buildOptions": {
- "define": [ "RELEASE", "TRACE" ],
- "optimize": true
- }
- }
- },
-
- "dependencies": {
- "Google.Protobuf": { "target": "project" },
- "NUnit": "3.4.0",
- "dotnet-test-nunit": "3.4.0-alpha-2"
- },
-
- "testRunner": "nunit",
-
- "frameworks": {
- "netcoreapp1.0": {
- "imports" : [ "dnxcore50", "netcoreapp1.0", "portable-net45+win8" ],
- "buildOptions": {
- "define": [ "PCL" ]
- },
- "dependencies": {
- "Microsoft.NETCore.App": {
- "version": "1.0.0",
- "type": "platform"
- },
- "System.Console": "4.0.0"
- }
- }
- }
-} \ No newline at end of file
diff --git a/csharp/src/Google.Protobuf.sln b/csharp/src/Google.Protobuf.sln
index 3c62bba3..443ee3e9 100644
--- a/csharp/src/Google.Protobuf.sln
+++ b/csharp/src/Google.Protobuf.sln
@@ -1,16 +1,16 @@
Microsoft Visual Studio Solution File, Format Version 12.00
-# Visual Studio 14
-VisualStudioVersion = 14.0.25420.1
-MinimumVisualStudioVersion = 14.0.24720.0
-Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "AddressBook", "AddressBook\AddressBook.xproj", "{AFB63919-1E05-43B4-802A-8FB8C9B2F463}"
+# Visual Studio 15
+VisualStudioVersion = 15.0.26114.2
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AddressBook", "AddressBook\AddressBook.csproj", "{AFB63919-1E05-43B4-802A-8FB8C9B2F463}"
EndProject
-Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Google.Protobuf", "Google.Protobuf\Google.Protobuf.xproj", "{9B576380-726D-4142-8238-60A43AB0E35A}"
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Google.Protobuf", "Google.Protobuf\Google.Protobuf.csproj", "{9B576380-726D-4142-8238-60A43AB0E35A}"
EndProject
-Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Google.Protobuf.Test", "Google.Protobuf.Test\Google.Protobuf.Test.xproj", "{580EB013-D3C7-4578-B845-015F4A3B0591}"
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Google.Protobuf.Test", "Google.Protobuf.Test\Google.Protobuf.Test.csproj", "{580EB013-D3C7-4578-B845-015F4A3B0591}"
EndProject
-Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Google.Protobuf.Conformance", "Google.Protobuf.Conformance\Google.Protobuf.Conformance.xproj", "{DDDC055B-E185-4181-BAB0-072F0F984569}"
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Google.Protobuf.Conformance", "Google.Protobuf.Conformance\Google.Protobuf.Conformance.csproj", "{DDDC055B-E185-4181-BAB0-072F0F984569}"
EndProject
-Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Google.Protobuf.JsonDump", "Google.Protobuf.JsonDump\Google.Protobuf.JsonDump.xproj", "{9695E08F-9829-497D-B95C-B38F28D48690}"
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Google.Protobuf.JsonDump", "Google.Protobuf.JsonDump\Google.Protobuf.JsonDump.csproj", "{9695E08F-9829-497D-B95C-B38F28D48690}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
diff --git a/csharp/src/Google.Protobuf/ByteString.cs b/csharp/src/Google.Protobuf/ByteString.cs
index 5c652cc3..4abdb718 100644..100755
--- a/csharp/src/Google.Protobuf/ByteString.cs
+++ b/csharp/src/Google.Protobuf/ByteString.cs
@@ -35,6 +35,13 @@ using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
+#if !NET35
+using System.Threading;
+using System.Threading.Tasks;
+#endif
+#if NET35
+using Google.Protobuf.Compatibility;
+#endif
namespace Google.Protobuf
{
@@ -142,6 +149,55 @@ namespace Google.Protobuf
}
/// <summary>
+ /// Constructs a <see cref="ByteString"/> from data in the given stream, synchronously.
+ /// </summary>
+ /// <remarks>If successful, <paramref name="stream"/> will be read completely, from the position
+ /// at the start of the call.</remarks>
+ /// <param name="stream">The stream to copy into a ByteString.</param>
+ /// <returns>A ByteString with content read from the given stream.</returns>
+ public static ByteString FromStream(Stream stream)
+ {
+ ProtoPreconditions.CheckNotNull(stream, nameof(stream));
+ int capacity = stream.CanSeek ? checked((int) (stream.Length - stream.Position)) : 0;
+ var memoryStream = new MemoryStream(capacity);
+ stream.CopyTo(memoryStream);
+#if NETSTANDARD1_0
+ byte[] bytes = memoryStream.ToArray();
+#else
+ // Avoid an extra copy if we can.
+ byte[] bytes = memoryStream.Length == memoryStream.Capacity ? memoryStream.GetBuffer() : memoryStream.ToArray();
+#endif
+ return AttachBytes(bytes);
+ }
+
+#if !NET35
+ /// <summary>
+ /// Constructs a <see cref="ByteString"/> from data in the given stream, asynchronously.
+ /// </summary>
+ /// <remarks>If successful, <paramref name="stream"/> will be read completely, from the position
+ /// at the start of the call.</remarks>
+ /// <param name="stream">The stream to copy into a ByteString.</param>
+ /// <param name="cancellationToken">The cancellation token to use when reading from the stream, if any.</param>
+ /// <returns>A ByteString with content read from the given stream.</returns>
+ public async static Task<ByteString> FromStreamAsync(Stream stream, CancellationToken cancellationToken = default(CancellationToken))
+ {
+ ProtoPreconditions.CheckNotNull(stream, nameof(stream));
+ int capacity = stream.CanSeek ? checked((int) (stream.Length - stream.Position)) : 0;
+ var memoryStream = new MemoryStream(capacity);
+ // We have to specify the buffer size here, as there's no overload accepting the cancellation token
+ // alone. But it's documented to use 81920 by default if not specified.
+ await stream.CopyToAsync(memoryStream, 81920, cancellationToken);
+#if NETSTANDARD1_0
+ byte[] bytes = memoryStream.ToArray();
+#else
+ // Avoid an extra copy if we can.
+ byte[] bytes = memoryStream.Length == memoryStream.Capacity ? memoryStream.GetBuffer() : memoryStream.ToArray();
+#endif
+ return AttachBytes(bytes);
+ }
+#endif
+
+ /// <summary>
/// Constructs a <see cref="ByteString" /> from the given array. The contents
/// are copied, so further modifications to the array will not
/// be reflected in the returned ByteString.
diff --git a/csharp/src/Google.Protobuf/CodedInputStream.cs b/csharp/src/Google.Protobuf/CodedInputStream.cs
index 072e2e17..abd352b9 100644
--- a/csharp/src/Google.Protobuf/CodedInputStream.cs
+++ b/csharp/src/Google.Protobuf/CodedInputStream.cs
@@ -121,7 +121,7 @@ namespace Google.Protobuf
/// <summary>
/// Creates a new CodedInputStream reading data from the given byte array.
/// </summary>
- public CodedInputStream(byte[] buffer) : this(null, ProtoPreconditions.CheckNotNull(buffer, "buffer"), 0, buffer.Length)
+ public CodedInputStream(byte[] buffer) : this(null, ProtoPreconditions.CheckNotNull(buffer, "buffer"), 0, buffer.Length, true)
{
}
@@ -129,7 +129,7 @@ namespace Google.Protobuf
/// Creates a new <see cref="CodedInputStream"/> that reads from the given byte array slice.
/// </summary>
public CodedInputStream(byte[] buffer, int offset, int length)
- : this(null, ProtoPreconditions.CheckNotNull(buffer, "buffer"), offset, offset + length)
+ : this(null, ProtoPreconditions.CheckNotNull(buffer, "buffer"), offset, offset + length, true)
{
if (offset < 0 || offset > buffer.Length)
{
@@ -158,16 +158,15 @@ namespace Google.Protobuf
/// <c cref="CodedInputStream"/> is disposed; <c>false</c> to dispose of the given stream when the
/// returned object is disposed.</param>
public CodedInputStream(Stream input, bool leaveOpen)
- : this(ProtoPreconditions.CheckNotNull(input, "input"), new byte[BufferSize], 0, 0)
+ : this(ProtoPreconditions.CheckNotNull(input, "input"), new byte[BufferSize], 0, 0, leaveOpen)
{
- this.leaveOpen = leaveOpen;
}
/// <summary>
/// Creates a new CodedInputStream reading data from the given
/// stream and buffer, using the default limits.
/// </summary>
- internal CodedInputStream(Stream input, byte[] buffer, int bufferPos, int bufferSize)
+ internal CodedInputStream(Stream input, byte[] buffer, int bufferPos, int bufferSize, bool leaveOpen)
{
this.input = input;
this.buffer = buffer;
@@ -175,6 +174,7 @@ namespace Google.Protobuf
this.bufferSize = bufferSize;
this.sizeLimit = DefaultSizeLimit;
this.recursionLimit = DefaultRecursionLimit;
+ this.leaveOpen = leaveOpen;
}
/// <summary>
@@ -185,8 +185,8 @@ namespace Google.Protobuf
/// This chains to the version with the default limits instead of vice versa to avoid
/// having to check that the default values are valid every time.
/// </remarks>
- internal CodedInputStream(Stream input, byte[] buffer, int bufferPos, int bufferSize, int sizeLimit, int recursionLimit)
- : this(input, buffer, bufferPos, bufferSize)
+ internal CodedInputStream(Stream input, byte[] buffer, int bufferPos, int bufferSize, int sizeLimit, int recursionLimit, bool leaveOpen)
+ : this(input, buffer, bufferPos, bufferSize, leaveOpen)
{
if (sizeLimit <= 0)
{
@@ -217,7 +217,8 @@ namespace Google.Protobuf
/// and recursion limits.</returns>
public static CodedInputStream CreateWithLimits(Stream input, int sizeLimit, int recursionLimit)
{
- return new CodedInputStream(input, new byte[BufferSize], 0, 0, sizeLimit, recursionLimit);
+ // Note: we may want an overload accepting leaveOpen
+ return new CodedInputStream(input, new byte[BufferSize], 0, 0, sizeLimit, recursionLimit, false);
}
/// <summary>
@@ -372,9 +373,9 @@ namespace Google.Protobuf
lastTag = ReadRawVarint32();
}
- if (lastTag == 0)
+ if (WireFormat.GetTagFieldNumber(lastTag) == 0)
{
- // If we actually read zero, that's not a valid tag.
+ // If we actually read a tag with a field of 0, that's not a valid tag.
throw InvalidProtocolBufferException.InvalidTag();
}
return lastTag;
diff --git a/csharp/src/Google.Protobuf/Collections/MapField.cs b/csharp/src/Google.Protobuf/Collections/MapField.cs
index 537ce261..8dac8e30 100644
--- a/csharp/src/Google.Protobuf/Collections/MapField.cs
+++ b/csharp/src/Google.Protobuf/Collections/MapField.cs
@@ -67,6 +67,9 @@ namespace Google.Protobuf.Collections
/// </para>
/// </remarks>
public sealed class MapField<TKey, TValue> : IDeepCloneable<MapField<TKey, TValue>>, IDictionary<TKey, TValue>, IEquatable<MapField<TKey, TValue>>, IDictionary
+#if !NET35
+ , IReadOnlyDictionary<TKey, TValue>
+#endif
{
// TODO: Don't create the map/list until we have an entry. (Assume many maps will be empty.)
private readonly Dictionary<TKey, LinkedListNode<KeyValuePair<TKey, TValue>>> map =
@@ -548,6 +551,14 @@ namespace Google.Protobuf.Collections
}
#endregion
+ #region IReadOnlyDictionary explicit interface implementation
+#if !NET35
+ IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys => Keys;
+
+ IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values => Values;
+#endif
+ #endregion
+
private class DictionaryEnumerator : IDictionaryEnumerator
{
private readonly IEnumerator<KeyValuePair<TKey, TValue>> enumerator;
@@ -715,7 +726,7 @@ namespace Google.Protobuf.Collections
{
throw new ArgumentOutOfRangeException(nameof(arrayIndex));
}
- if (arrayIndex + Count >= array.Length)
+ if (arrayIndex + Count > array.Length)
{
throw new ArgumentException("Not enough space in the array", nameof(array));
}
@@ -746,7 +757,7 @@ namespace Google.Protobuf.Collections
{
throw new ArgumentOutOfRangeException(nameof(index));
}
- if (index + Count >= array.Length)
+ if (index + Count > array.Length)
{
throw new ArgumentException("Not enough space in the array", nameof(array));
}
diff --git a/csharp/src/Google.Protobuf/Collections/RepeatedField.cs b/csharp/src/Google.Protobuf/Collections/RepeatedField.cs
index 7bb56448..6063ff61 100644..100755
--- a/csharp/src/Google.Protobuf/Collections/RepeatedField.cs
+++ b/csharp/src/Google.Protobuf/Collections/RepeatedField.cs
@@ -47,6 +47,9 @@ namespace Google.Protobuf.Collections
/// </remarks>
/// <typeparam name="T">The element type of the repeated field.</typeparam>
public sealed class RepeatedField<T> : IList<T>, IList, IDeepCloneable<RepeatedField<T>>, IEquatable<RepeatedField<T>>
+#if !NET35
+ , IReadOnlyList<T>
+#endif
{
private static readonly T[] EmptyArray = new T[0];
private const int MinArraySize = 8;
diff --git a/csharp/src/Google.Protobuf/Compatibility/PropertyInfoExtensions.cs b/csharp/src/Google.Protobuf/Compatibility/PropertyInfoExtensions.cs
index e3914dd3..95a02c72 100644..100755
--- a/csharp/src/Google.Protobuf/Compatibility/PropertyInfoExtensions.cs
+++ b/csharp/src/Google.Protobuf/Compatibility/PropertyInfoExtensions.cs
@@ -47,7 +47,7 @@ namespace Google.Protobuf.Compatibility
/// </summary>
internal static MethodInfo GetGetMethod(this PropertyInfo target)
{
-#if DOTNET35
+#if NET35
var method = target.GetGetMethod();
#else
var method = target.GetMethod;
@@ -61,7 +61,7 @@ namespace Google.Protobuf.Compatibility
/// </summary>
internal static MethodInfo GetSetMethod(this PropertyInfo target)
{
-#if DOTNET35
+#if NET35
var method = target.GetSetMethod();
#else
var method = target.SetMethod;
diff --git a/csharp/src/Google.Protobuf/Compatibility/StreamExtensions.cs b/csharp/src/Google.Protobuf/Compatibility/StreamExtensions.cs
new file mode 100755
index 00000000..bf4bf220
--- /dev/null
+++ b/csharp/src/Google.Protobuf/Compatibility/StreamExtensions.cs
@@ -0,0 +1,66 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2015 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+#if NET35
+using System;
+using System.IO;
+
+namespace Google.Protobuf.Compatibility
+{
+ /// <summary>
+ /// Extension methods for <see cref="Stream"/> in order to provide
+ /// backwards compatibility with .NET 3.5
+ /// </summary>
+ public static class StreamExtensions
+ {
+ // 81920 seems to be the default buffer size used in .NET 4.5.1
+ private const int BUFFER_SIZE = 81920;
+
+ /// <summary>
+ /// Write the contents of the current stream to the destination stream
+ /// </summary>
+ public static void CopyTo(this Stream source, Stream destination)
+ {
+ if (destination == null)
+ {
+ throw new ArgumentNullException(nameof(destination));
+ }
+
+ byte[] buffer = new byte[BUFFER_SIZE];
+ int numBytesRead;
+ while ((numBytesRead = source.Read(buffer, 0, buffer.Length)) > 0) {
+ destination.Write(buffer, 0, numBytesRead);
+ }
+ }
+ }
+}
+#endif
diff --git a/csharp/src/Google.Protobuf/Compatibility/TypeExtensions.cs b/csharp/src/Google.Protobuf/Compatibility/TypeExtensions.cs
index 2d93183b..2f237138 100644..100755
--- a/csharp/src/Google.Protobuf/Compatibility/TypeExtensions.cs
+++ b/csharp/src/Google.Protobuf/Compatibility/TypeExtensions.cs
@@ -33,7 +33,7 @@
using System;
using System.Reflection;
-#if !DOTNET35
+#if !NET35
namespace Google.Protobuf.Compatibility
{
/// <summary>
diff --git a/csharp/src/Google.Protobuf/Google.Protobuf.csproj b/csharp/src/Google.Protobuf/Google.Protobuf.csproj
new file mode 100644
index 00000000..75b38175
--- /dev/null
+++ b/csharp/src/Google.Protobuf/Google.Protobuf.csproj
@@ -0,0 +1,33 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <PropertyGroup>
+ <Description>C# runtime library for Protocol Buffers - Google's data interchange format.</Description>
+ <Copyright>Copyright 2015, Google Inc.</Copyright>
+ <AssemblyTitle>Google Protocol Buffers</AssemblyTitle>
+ <VersionPrefix>3.4.1</VersionPrefix>
+ <Authors>Google Inc.</Authors>
+ <TargetFrameworks>netstandard1.0;net45</TargetFrameworks>
+ <GenerateDocumentationFile>true</GenerateDocumentationFile>
+ <AssemblyOriginatorKeyFile>../../keys/Google.Protobuf.snk</AssemblyOriginatorKeyFile>
+ <SignAssembly>true</SignAssembly>
+ <PublicSign Condition=" '$(OS)' != 'Windows_NT' ">true</PublicSign>
+ <PackageTags>Protocol;Buffers;Binary;Serialization;Format;Google;proto;proto3</PackageTags>
+ <PackageReleaseNotes>C# proto3 support</PackageReleaseNotes>
+ <PackageProjectUrl>https://github.com/google/protobuf</PackageProjectUrl>
+ <PackageLicenseUrl>https://github.com/google/protobuf/blob/master/LICENSE</PackageLicenseUrl>
+ <RepositoryType>git</RepositoryType>
+ <RepositoryUrl>https://github.com/google/protobuf.git</RepositoryUrl>
+ <IncludeSymbols>true</IncludeSymbols>
+ <IncludeSource>true</IncludeSource>
+ </PropertyGroup>
+
+ <!--
+ - Override target frameworks on non-Windows to just .NET Core
+ - Doing this conditionally in the initial PropertyGroup confuses
+ - Visual Studio.
+ -->
+ <PropertyGroup Condition="'$(OS)' != 'Windows_NT'">
+ <TargetFrameworks>netstandard1.0</TargetFrameworks>
+ </PropertyGroup>
+
+</Project>
diff --git a/csharp/src/Google.Protobuf/Google.Protobuf.xproj b/csharp/src/Google.Protobuf/Google.Protobuf.xproj
deleted file mode 100644
index c68e0db3..00000000
--- a/csharp/src/Google.Protobuf/Google.Protobuf.xproj
+++ /dev/null
@@ -1,19 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
- <PropertyGroup>
- <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">14.0</VisualStudioVersion>
- <VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
- </PropertyGroup>
- <Import Project="$(VSToolsPath)\DotNet\Microsoft.DotNet.Props" Condition="'$(VSToolsPath)' != ''" />
- <PropertyGroup Label="Globals">
- <ProjectGuid>9b576380-726d-4142-8238-60a43ab0e35a</ProjectGuid>
- <RootNamespace>Google.Protobuf</RootNamespace>
- <BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">.\obj</BaseIntermediateOutputPath>
- <OutputPath Condition="'$(OutputPath)'=='' ">.\bin\</OutputPath>
- </PropertyGroup>
-
- <PropertyGroup>
- <SchemaVersion>2.0</SchemaVersion>
- </PropertyGroup>
- <Import Project="$(VSToolsPath)\DotNet\Microsoft.DotNet.targets" Condition="'$(VSToolsPath)' != ''" />
-</Project> \ No newline at end of file
diff --git a/csharp/src/Google.Protobuf/JsonFormatter.cs b/csharp/src/Google.Protobuf/JsonFormatter.cs
index bb1a361e..4ae10d8b 100644..100755
--- a/csharp/src/Google.Protobuf/JsonFormatter.cs
+++ b/csharp/src/Google.Protobuf/JsonFormatter.cs
@@ -375,14 +375,21 @@ namespace Google.Protobuf
}
else if (value is System.Enum)
{
- string name = OriginalEnumValueHelper.GetOriginalName(value);
- if (name != null)
+ if (settings.FormatEnumsAsIntegers)
{
- WriteString(writer, name);
+ WriteValue(writer, (int)value);
}
else
{
- WriteValue(writer, (int)value);
+ string name = OriginalEnumValueHelper.GetOriginalName(value);
+ if (name != null)
+ {
+ WriteString(writer, name);
+ }
+ else
+ {
+ WriteValue(writer, (int)value);
+ }
}
}
else if (value is float || value is double)
@@ -778,7 +785,11 @@ namespace Google.Protobuf
/// </summary>
public TypeRegistry TypeRegistry { get; }
- // TODO: Work out how we're going to scale this to multiple settings. "WithXyz" methods?
+ /// <summary>
+ /// Whether to format enums as ints. Defaults to false.
+ /// </summary>
+ public bool FormatEnumsAsIntegers { get; }
+
/// <summary>
/// Creates a new <see cref="Settings"/> object with the specified formatting of default values
@@ -795,11 +806,42 @@ namespace Google.Protobuf
/// </summary>
/// <param name="formatDefaultValues"><c>true</c> if default values (0, empty strings etc) should be formatted; <c>false</c> otherwise.</param>
/// <param name="typeRegistry">The <see cref="TypeRegistry"/> to use when formatting <see cref="Any"/> messages.</param>
- public Settings(bool formatDefaultValues, TypeRegistry typeRegistry)
+ public Settings(bool formatDefaultValues, TypeRegistry typeRegistry) : this(formatDefaultValues, typeRegistry, false)
+ {
+ }
+
+ /// <summary>
+ /// Creates a new <see cref="Settings"/> object with the specified parameters.
+ /// </summary>
+ /// <param name="formatDefaultValues"><c>true</c> if default values (0, empty strings etc) should be formatted; <c>false</c> otherwise.</param>
+ /// <param name="typeRegistry">The <see cref="TypeRegistry"/> to use when formatting <see cref="Any"/> messages. TypeRegistry.Empty will be used if it is null.</param>
+ /// <param name="formatEnumsAsIntegers"><c>true</c> to format the enums as integers; <c>false</c> to format enums as enum names.</param>
+ private Settings(bool formatDefaultValues,
+ TypeRegistry typeRegistry,
+ bool formatEnumsAsIntegers)
{
FormatDefaultValues = formatDefaultValues;
- TypeRegistry = ProtoPreconditions.CheckNotNull(typeRegistry, nameof(typeRegistry));
+ TypeRegistry = typeRegistry ?? TypeRegistry.Empty;
+ FormatEnumsAsIntegers = formatEnumsAsIntegers;
}
+
+ /// <summary>
+ /// Creates a new <see cref="Settings"/> object with the specified formatting of default values and the current settings.
+ /// </summary>
+ /// <param name="formatDefaultValues"><c>true</c> if default values (0, empty strings etc) should be formatted; <c>false</c> otherwise.</param>
+ public Settings WithFormatDefaultValues(bool formatDefaultValues) => new Settings(formatDefaultValues, TypeRegistry, FormatEnumsAsIntegers);
+
+ /// <summary>
+ /// Creates a new <see cref="Settings"/> object with the specified type registry and the current settings.
+ /// </summary>
+ /// <param name="typeRegistry">The <see cref="TypeRegistry"/> to use when formatting <see cref="Any"/> messages.</param>
+ public Settings WithTypeRegistry(TypeRegistry typeRegistry) => new Settings(FormatDefaultValues, typeRegistry, FormatEnumsAsIntegers);
+
+ /// <summary>
+ /// Creates a new <see cref="Settings"/> object with the specified enums formatting option and the current settings.
+ /// </summary>
+ /// <param name="formatEnumsAsIntegers"><c>true</c> to format the enums as integers; <c>false</c> to format enums as enum names.</param>
+ public Settings WithFormatEnumsAsIntegers(bool formatEnumsAsIntegers) => new Settings(FormatDefaultValues, TypeRegistry, formatEnumsAsIntegers);
}
// Effectively a cache of mapping from enum values to the original name as specified in the proto file,
@@ -831,10 +873,13 @@ namespace Google.Protobuf
return originalName;
}
-#if DOTNET35
+#if NET35
// TODO: Consider adding functionality to TypeExtensions to avoid this difference.
private static Dictionary<object, string> GetNameMapping(System.Type enumType) =>
enumType.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)
+ .Where(f => (f.GetCustomAttributes(typeof(OriginalNameAttribute), false)
+ .FirstOrDefault() as OriginalNameAttribute)
+ ?.PreferredAlias ?? true)
.ToDictionary(f => f.GetValue(null),
f => (f.GetCustomAttributes(typeof(OriginalNameAttribute), false)
.FirstOrDefault() as OriginalNameAttribute)
@@ -844,6 +889,8 @@ namespace Google.Protobuf
private static Dictionary<object, string> GetNameMapping(System.Type enumType) =>
enumType.GetTypeInfo().DeclaredFields
.Where(f => f.IsStatic)
+ .Where(f => f.GetCustomAttributes<OriginalNameAttribute>()
+ .FirstOrDefault()?.PreferredAlias ?? true)
.ToDictionary(f => f.GetValue(null),
f => f.GetCustomAttributes<OriginalNameAttribute>()
.FirstOrDefault()
diff --git a/csharp/src/Google.Protobuf/JsonParser.cs b/csharp/src/Google.Protobuf/JsonParser.cs
index 6b6f2d9a..3621b0c0 100644
--- a/csharp/src/Google.Protobuf/JsonParser.cs
+++ b/csharp/src/Google.Protobuf/JsonParser.cs
@@ -203,10 +203,14 @@ namespace Google.Protobuf
}
else
{
- // TODO: Is this what we want to do? If not, we'll need to skip the value,
- // which may be an object or array. (We might want to put code in the tokenizer
- // to do that.)
- throw new InvalidProtocolBufferException("Unknown field: " + name);
+ if (settings.IgnoreUnknownFields)
+ {
+ tokenizer.SkipValue();
+ }
+ else
+ {
+ throw new InvalidProtocolBufferException("Unknown field: " + name);
+ }
}
}
}
@@ -997,6 +1001,19 @@ namespace Google.Protobuf
public TypeRegistry TypeRegistry { get; }
/// <summary>
+ /// Whether the parser should ignore unknown fields (<c>true</c>) or throw an exception when
+ /// they are encountered (<c>false</c>).
+ /// </summary>
+ public bool IgnoreUnknownFields { get; }
+
+ private Settings(int recursionLimit, TypeRegistry typeRegistry, bool ignoreUnknownFields)
+ {
+ RecursionLimit = recursionLimit;
+ TypeRegistry = ProtoPreconditions.CheckNotNull(typeRegistry, nameof(typeRegistry));
+ IgnoreUnknownFields = ignoreUnknownFields;
+ }
+
+ /// <summary>
/// Creates a new <see cref="Settings"/> object with the specified recursion limit.
/// </summary>
/// <param name="recursionLimit">The maximum depth of messages to parse</param>
@@ -1009,11 +1026,34 @@ namespace Google.Protobuf
/// </summary>
/// <param name="recursionLimit">The maximum depth of messages to parse</param>
/// <param name="typeRegistry">The type registry used to parse <see cref="Any"/> messages</param>
- public Settings(int recursionLimit, TypeRegistry typeRegistry)
+ public Settings(int recursionLimit, TypeRegistry typeRegistry) : this(recursionLimit, typeRegistry, false)
{
- RecursionLimit = recursionLimit;
- TypeRegistry = ProtoPreconditions.CheckNotNull(typeRegistry, nameof(typeRegistry));
}
+
+ /// <summary>
+ /// Creates a new <see cref="Settings"/> object set to either ignore unknown fields, or throw an exception
+ /// when unknown fields are encountered.
+ /// </summary>
+ /// <param name="ignoreUnknownFields"><c>true</c> if unknown fields should be ignored when parsing; <c>false</c> to throw an exception.</param>
+ public Settings WithIgnoreUnknownFields(bool ignoreUnknownFields) =>
+ new Settings(RecursionLimit, TypeRegistry, ignoreUnknownFields);
+
+ /// <summary>
+ /// Creates a new <see cref="Settings"/> object based on this one, but with the specified recursion limit.
+ /// </summary>
+ /// <param name="recursionLimit">The new recursion limit.</param>
+ public Settings WithRecursionLimit(int recursionLimit) =>
+ new Settings(recursionLimit, TypeRegistry, IgnoreUnknownFields);
+
+ /// <summary>
+ /// Creates a new <see cref="Settings"/> object based on this one, but with the specified type registry.
+ /// </summary>
+ /// <param name="typeRegistry">The new type registry. Must not be null.</param>
+ public Settings WithTypeRegistry(TypeRegistry typeRegistry) =>
+ new Settings(
+ RecursionLimit,
+ ProtoPreconditions.CheckNotNull(typeRegistry, nameof(typeRegistry)),
+ IgnoreUnknownFields);
}
}
}
diff --git a/csharp/src/Google.Protobuf/JsonTokenizer.cs b/csharp/src/Google.Protobuf/JsonTokenizer.cs
index 09a6d43b..0e403f78 100644
--- a/csharp/src/Google.Protobuf/JsonTokenizer.cs
+++ b/csharp/src/Google.Protobuf/JsonTokenizer.cs
@@ -138,6 +138,34 @@ namespace Google.Protobuf
protected abstract JsonToken NextImpl();
/// <summary>
+ /// Skips the value we're about to read. This must only be called immediately after reading a property name.
+ /// If the value is an object or an array, the complete object/array is skipped.
+ /// </summary>
+ internal void SkipValue()
+ {
+ // We'll assume that Next() makes sure that the end objects and end arrays are all valid.
+ // All we care about is the total nesting depth we need to close.
+ int depth = 0;
+
+ // do/while rather than while loop so that we read at least one token.
+ do
+ {
+ var token = Next();
+ switch (token.Type)
+ {
+ case JsonToken.TokenType.EndArray:
+ case JsonToken.TokenType.EndObject:
+ depth--;
+ break;
+ case JsonToken.TokenType.StartArray:
+ case JsonToken.TokenType.StartObject:
+ depth++;
+ break;
+ }
+ } while (depth != 0);
+ }
+
+ /// <summary>
/// Tokenizer which first exhausts a list of tokens, then consults another tokenizer.
/// </summary>
private class JsonReplayTokenizer : JsonTokenizer
@@ -217,7 +245,7 @@ namespace Google.Protobuf
state = State.ObjectAfterColon;
break;
case ',':
- ValidateState(State.ObjectAfterProperty | State.ArrayAfterValue, "Invalid state to read a colon: ");
+ ValidateState(State.ObjectAfterProperty | State.ArrayAfterValue, "Invalid state to read a comma: ");
state = state == State.ObjectAfterProperty ? State.ObjectAfterComma : State.ArrayAfterComma;
break;
case '"':
diff --git a/csharp/src/Google.Protobuf/MessageExtensions.cs b/csharp/src/Google.Protobuf/MessageExtensions.cs
index 047156c3..9dbc49d6 100644
--- a/csharp/src/Google.Protobuf/MessageExtensions.cs
+++ b/csharp/src/Google.Protobuf/MessageExtensions.cs
@@ -54,6 +54,22 @@ namespace Google.Protobuf
}
/// <summary>
+ /// Merges data from the given byte array slice into an existing message.
+ /// </summary>
+ /// <param name="message">The message to merge the data into.</param>
+ /// <param name="data">The data containing the slice to merge, which must be protobuf-encoded binary data.</param>
+ /// <param name="offset">The offset of the slice to merge.</param>
+ /// <param name="length">The length of the slice to merge.</param>
+ public static void MergeFrom(this IMessage message, byte[] data, int offset, int length)
+ {
+ ProtoPreconditions.CheckNotNull(message, "message");
+ ProtoPreconditions.CheckNotNull(data, "data");
+ CodedInputStream input = new CodedInputStream(data, offset, length);
+ message.MergeFrom(input);
+ input.CheckReadEndOfStreamTag();
+ }
+
+ /// <summary>
/// Merges data from the given byte string into an existing message.
/// </summary>
/// <param name="message">The message to merge the data into.</param>
diff --git a/csharp/src/Google.Protobuf/MessageParser.cs b/csharp/src/Google.Protobuf/MessageParser.cs
index 8889638b..66d44135 100644
--- a/csharp/src/Google.Protobuf/MessageParser.cs
+++ b/csharp/src/Google.Protobuf/MessageParser.cs
@@ -64,20 +64,32 @@ namespace Google.Protobuf
/// <returns>The newly parsed message.</returns>
public IMessage ParseFrom(byte[] data)
{
- ProtoPreconditions.CheckNotNull(data, "data");
IMessage message = factory();
message.MergeFrom(data);
return message;
}
/// <summary>
+ /// Parses a message from a byte array slice.
+ /// </summary>
+ /// <param name="data">The byte array containing the message. Must not be null.</param>
+ /// <param name="offset">The offset of the slice to parse.</param>
+ /// <param name="length">The length of the slice to parse.</param>
+ /// <returns>The newly parsed message.</returns>
+ public IMessage ParseFrom(byte[] data, int offset, int length)
+ {
+ IMessage message = factory();
+ message.MergeFrom(data, offset, length);
+ return message;
+ }
+
+ /// <summary>
/// Parses a message from the given byte string.
/// </summary>
/// <param name="data">The data to parse.</param>
/// <returns>The parsed message.</returns>
public IMessage ParseFrom(ByteString data)
{
- ProtoPreconditions.CheckNotNull(data, "data");
IMessage message = factory();
message.MergeFrom(data);
return message;
@@ -191,20 +203,32 @@ namespace Google.Protobuf
/// <returns>The newly parsed message.</returns>
public new T ParseFrom(byte[] data)
{
- ProtoPreconditions.CheckNotNull(data, "data");
T message = factory();
message.MergeFrom(data);
return message;
}
/// <summary>
+ /// Parses a message from a byte array slice.
+ /// </summary>
+ /// <param name="data">The byte array containing the message. Must not be null.</param>
+ /// <param name="offset">The offset of the slice to parse.</param>
+ /// <param name="length">The length of the slice to parse.</param>
+ /// <returns>The newly parsed message.</returns>
+ public new T ParseFrom(byte[] data, int offset, int length)
+ {
+ T message = factory();
+ message.MergeFrom(data, offset, length);
+ return message;
+ }
+
+ /// <summary>
/// Parses a message from the given byte string.
/// </summary>
/// <param name="data">The data to parse.</param>
/// <returns>The parsed message.</returns>
public new T ParseFrom(ByteString data)
{
- ProtoPreconditions.CheckNotNull(data, "data");
T message = factory();
message.MergeFrom(data);
return message;
diff --git a/csharp/src/Google.Protobuf/Reflection/CustomOptions.cs b/csharp/src/Google.Protobuf/Reflection/CustomOptions.cs
new file mode 100644
index 00000000..88b3ec00
--- /dev/null
+++ b/csharp/src/Google.Protobuf/Reflection/CustomOptions.cs
@@ -0,0 +1,390 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2017 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+using System;
+using System.Collections.Generic;
+
+namespace Google.Protobuf.Reflection
+{
+ /// <summary>
+ /// Container for a set of custom options specified within a message, field etc.
+ /// </summary>
+ /// <remarks>
+ /// <para>
+ /// This type is publicly immutable, but internally mutable. It is only populated
+ /// by the descriptor parsing code - by the time any user code is able to see an instance,
+ /// it will be fully initialized.
+ /// </para>
+ /// <para>
+ /// If an option is requested using the incorrect method, an answer may still be returned: all
+ /// of the numeric types are represented internally using 64-bit integers, for example. It is up to
+ /// the caller to ensure that they make the appropriate method call for the option they're interested in.
+ /// Note that enum options are simply stored as integers, so the value should be fetched using
+ /// <see cref="TryGetInt32(int, out int)"/> and then cast appropriately.
+ /// </para>
+ /// <para>
+ /// Repeated options are currently not supported. Asking for a single value of an option
+ /// which was actually repeated will return the last value, except for message types where
+ /// all the set values are merged together.
+ /// </para>
+ /// </remarks>
+ public sealed class CustomOptions
+ {
+ /// <summary>
+ /// Singleton for all descriptors with an empty set of options.
+ /// </summary>
+ internal static readonly CustomOptions Empty = new CustomOptions();
+
+ /// <summary>
+ /// A sequence of values per field. This needs to be per field rather than per tag to allow correct deserialization
+ /// of repeated fields which could be "int, ByteString, int" - unlikely as that is. The fact that values are boxed
+ /// is unfortunate; we might be able to use a struct instead, and we could combine uint and ulong values.
+ /// </summary>
+ private readonly Dictionary<int, List<FieldValue>> valuesByField = new Dictionary<int, List<FieldValue>>();
+
+ private CustomOptions() { }
+
+ /// <summary>
+ /// Retrieves a Boolean value for the specified option field.
+ /// </summary>
+ /// <param name="field">The field to fetch the value for.</param>
+ /// <param name="value">The output variable to populate.</param>
+ /// <returns><c>true</c> if a suitable value for the field was found; <c>false</c> otherwise.</returns>
+ public bool TryGetBool(int field, out bool value)
+ {
+ ulong? tmp = GetLastNumericValue(field);
+ value = tmp == 1UL;
+ return tmp != null;
+ }
+
+ /// <summary>
+ /// Retrieves a signed 32-bit integer value for the specified option field.
+ /// </summary>
+ /// <param name="field">The field to fetch the value for.</param>
+ /// <param name="value">The output variable to populate.</param>
+ /// <returns><c>true</c> if a suitable value for the field was found; <c>false</c> otherwise.</returns>
+ public bool TryGetInt32(int field, out int value)
+ {
+ ulong? tmp = GetLastNumericValue(field);
+ value = (int) tmp.GetValueOrDefault();
+ return tmp != null;
+ }
+
+ /// <summary>
+ /// Retrieves a signed 64-bit integer value for the specified option field.
+ /// </summary>
+ /// <param name="field">The field to fetch the value for.</param>
+ /// <param name="value">The output variable to populate.</param>
+ /// <returns><c>true</c> if a suitable value for the field was found; <c>false</c> otherwise.</returns>
+ public bool TryGetInt64(int field, out long value)
+ {
+ ulong? tmp = GetLastNumericValue(field);
+ value = (long) tmp.GetValueOrDefault();
+ return tmp != null;
+ }
+
+ /// <summary>
+ /// Retrieves an unsigned 32-bit integer value for the specified option field,
+ /// assuming a fixed-length representation.
+ /// </summary>
+ /// <param name="field">The field to fetch the value for.</param>
+ /// <param name="value">The output variable to populate.</param>
+ /// <returns><c>true</c> if a suitable value for the field was found; <c>false</c> otherwise.</returns>
+ public bool TryGetFixed32(int field, out uint value) => TryGetUInt32(field, out value);
+
+ /// <summary>
+ /// Retrieves an unsigned 64-bit integer value for the specified option field,
+ /// assuming a fixed-length representation.
+ /// </summary>
+ /// <param name="field">The field to fetch the value for.</param>
+ /// <param name="value">The output variable to populate.</param>
+ /// <returns><c>true</c> if a suitable value for the field was found; <c>false</c> otherwise.</returns>
+ public bool TryGetFixed64(int field, out ulong value) => TryGetUInt64(field, out value);
+
+ /// <summary>
+ /// Retrieves a signed 32-bit integer value for the specified option field,
+ /// assuming a fixed-length representation.
+ /// </summary>
+ /// <param name="field">The field to fetch the value for.</param>
+ /// <param name="value">The output variable to populate.</param>
+ /// <returns><c>true</c> if a suitable value for the field was found; <c>false</c> otherwise.</returns>
+ public bool TryGetSFixed32(int field, out int value) => TryGetInt32(field, out value);
+
+ /// <summary>
+ /// Retrieves a signed 64-bit integer value for the specified option field,
+ /// assuming a fixed-length representation.
+ /// </summary>
+ /// <param name="field">The field to fetch the value for.</param>
+ /// <param name="value">The output variable to populate.</param>
+ /// <returns><c>true</c> if a suitable value for the field was found; <c>false</c> otherwise.</returns>
+ public bool TryGetSFixed64(int field, out long value) => TryGetInt64(field, out value);
+
+ /// <summary>
+ /// Retrieves a signed 32-bit integer value for the specified option field,
+ /// assuming a zigzag encoding.
+ /// </summary>
+ /// <param name="field">The field to fetch the value for.</param>
+ /// <param name="value">The output variable to populate.</param>
+ /// <returns><c>true</c> if a suitable value for the field was found; <c>false</c> otherwise.</returns>
+ public bool TryGetSInt32(int field, out int value)
+ {
+ ulong? tmp = GetLastNumericValue(field);
+ value = CodedInputStream.DecodeZigZag32((uint) tmp.GetValueOrDefault());
+ return tmp != null;
+ }
+
+ /// <summary>
+ /// Retrieves a signed 64-bit integer value for the specified option field,
+ /// assuming a zigzag encoding.
+ /// </summary>
+ /// <param name="field">The field to fetch the value for.</param>
+ /// <param name="value">The output variable to populate.</param>
+ /// <returns><c>true</c> if a suitable value for the field was found; <c>false</c> otherwise.</returns>
+ public bool TryGetSInt64(int field, out long value)
+ {
+ ulong? tmp = GetLastNumericValue(field);
+ value = CodedInputStream.DecodeZigZag64(tmp.GetValueOrDefault());
+ return tmp != null;
+ }
+
+ /// <summary>
+ /// Retrieves an unsigned 32-bit integer value for the specified option field.
+ /// </summary>
+ /// <param name="field">The field to fetch the value for.</param>
+ /// <param name="value">The output variable to populate.</param>
+ /// <returns><c>true</c> if a suitable value for the field was found; <c>false</c> otherwise.</returns>
+ public bool TryGetUInt32(int field, out uint value)
+ {
+ ulong? tmp = GetLastNumericValue(field);
+ value = (uint) tmp.GetValueOrDefault();
+ return tmp != null;
+ }
+
+ /// <summary>
+ /// Retrieves an unsigned 64-bit integer value for the specified option field.
+ /// </summary>
+ /// <param name="field">The field to fetch the value for.</param>
+ /// <param name="value">The output variable to populate.</param>
+ /// <returns><c>true</c> if a suitable value for the field was found; <c>false</c> otherwise.</returns>
+ public bool TryGetUInt64(int field, out ulong value)
+ {
+ ulong? tmp = GetLastNumericValue(field);
+ value = tmp.GetValueOrDefault();
+ return tmp != null;
+ }
+
+ /// <summary>
+ /// Retrieves a 32-bit floating point value for the specified option field.
+ /// </summary>
+ /// <param name="field">The field to fetch the value for.</param>
+ /// <param name="value">The output variable to populate.</param>
+ /// <returns><c>true</c> if a suitable value for the field was found; <c>false</c> otherwise.</returns>
+ public bool TryGetFloat(int field, out float value)
+ {
+ ulong? tmp = GetLastNumericValue(field);
+ int int32 = (int) tmp.GetValueOrDefault();
+ byte[] bytes = BitConverter.GetBytes(int32);
+ value = BitConverter.ToSingle(bytes, 0);
+ return tmp != null;
+ }
+
+ /// <summary>
+ /// Retrieves a 64-bit floating point value for the specified option field.
+ /// </summary>
+ /// <param name="field">The field to fetch the value for.</param>
+ /// <param name="value">The output variable to populate.</param>
+ /// <returns><c>true</c> if a suitable value for the field was found; <c>false</c> otherwise.</returns>
+ public bool TryGetDouble(int field, out double value)
+ {
+ ulong? tmp = GetLastNumericValue(field);
+ value = BitConverter.Int64BitsToDouble((long) tmp.GetValueOrDefault());
+ return tmp != null;
+ }
+
+ /// <summary>
+ /// Retrieves a string value for the specified option field.
+ /// </summary>
+ /// <param name="field">The field to fetch the value for.</param>
+ /// <param name="value">The output variable to populate.</param>
+ /// <returns><c>true</c> if a suitable value for the field was found; <c>false</c> otherwise.</returns>
+ public bool TryGetString(int field, out string value)
+ {
+ ByteString bytes = GetLastByteStringValue(field);
+ value = bytes?.ToStringUtf8();
+ return bytes != null;
+ }
+
+ /// <summary>
+ /// Retrieves a bytes value for the specified option field.
+ /// </summary>
+ /// <param name="field">The field to fetch the value for.</param>
+ /// <param name="value">The output variable to populate.</param>
+ /// <returns><c>true</c> if a suitable value for the field was found; <c>false</c> otherwise.</returns>
+ public bool TryGetBytes(int field, out ByteString value)
+ {
+ ByteString bytes = GetLastByteStringValue(field);
+ value = bytes;
+ return bytes != null;
+ }
+
+ /// <summary>
+ /// Retrieves a message value for the specified option field.
+ /// </summary>
+ /// <param name="field">The field to fetch the value for.</param>
+ /// <param name="value">The output variable to populate.</param>
+ /// <returns><c>true</c> if a suitable value for the field was found; <c>false</c> otherwise.</returns>
+ public bool TryGetMessage<T>(int field, out T value) where T : class, IMessage, new()
+ {
+ value = null;
+ List<FieldValue> values;
+ if (!valuesByField.TryGetValue(field, out values))
+ {
+ return false;
+ }
+ foreach (FieldValue fieldValue in values)
+ {
+ if (fieldValue.ByteString != null)
+ {
+ if (value == null)
+ {
+ value = new T();
+ }
+ value.MergeFrom(fieldValue.ByteString);
+ }
+ }
+ return value != null;
+ }
+
+ private ulong? GetLastNumericValue(int field)
+ {
+ List<FieldValue> values;
+ if (!valuesByField.TryGetValue(field, out values))
+ {
+ return null;
+ }
+ for (int i = values.Count - 1; i >= 0; i--)
+ {
+ // A non-bytestring value is a numeric value
+ if (values[i].ByteString == null)
+ {
+ return values[i].Number;
+ }
+ }
+ return null;
+ }
+
+ private ByteString GetLastByteStringValue(int field)
+ {
+ List<FieldValue> values;
+ if (!valuesByField.TryGetValue(field, out values))
+ {
+ return null;
+ }
+ for (int i = values.Count - 1; i >= 0; i--)
+ {
+ if (values[i].ByteString != null)
+ {
+ return values[i].ByteString;
+ }
+ }
+ return null;
+ }
+
+ /// <summary>
+ /// Reads an unknown field, either parsing it and storing it or skipping it.
+ /// </summary>
+ /// <remarks>
+ /// If the current set of options is empty and we manage to read a field, a new set of options
+ /// will be created and returned. Otherwise, the return value is <c>this</c>. This allows
+ /// us to start with a singleton empty set of options and just create new ones where necessary.
+ /// </remarks>
+ /// <param name="input">Input stream to read from. </param>
+ /// <returns>The resulting set of custom options, either <c>this</c> or a new set.</returns>
+ internal CustomOptions ReadOrSkipUnknownField(CodedInputStream input)
+ {
+ var tag = input.LastTag;
+ var field = WireFormat.GetTagFieldNumber(tag);
+ switch (WireFormat.GetTagWireType(tag))
+ {
+ case WireFormat.WireType.LengthDelimited:
+ return AddValue(field, new FieldValue(input.ReadBytes()));
+ case WireFormat.WireType.Fixed32:
+ return AddValue(field, new FieldValue(input.ReadFixed32()));
+ case WireFormat.WireType.Fixed64:
+ return AddValue(field, new FieldValue(input.ReadFixed64()));
+ case WireFormat.WireType.Varint:
+ return AddValue(field, new FieldValue(input.ReadRawVarint64()));
+ // For StartGroup, EndGroup or any wire format we don't understand,
+ // just use the normal behavior (call SkipLastField).
+ default:
+ input.SkipLastField();
+ return this;
+ }
+ }
+
+ private CustomOptions AddValue(int field, FieldValue value)
+ {
+ var ret = valuesByField.Count == 0 ? new CustomOptions() : this;
+ List<FieldValue> valuesForField;
+ if (!ret.valuesByField.TryGetValue(field, out valuesForField))
+ {
+ // Expect almost all
+ valuesForField = new List<FieldValue>(1);
+ ret.valuesByField[field] = valuesForField;
+ }
+ valuesForField.Add(value);
+ return ret;
+ }
+
+ /// <summary>
+ /// All field values can be stored as a byte string or a 64-bit integer.
+ /// This struct avoids unnecessary boxing.
+ /// </summary>
+ private struct FieldValue
+ {
+ internal ulong Number { get; }
+ internal ByteString ByteString { get; }
+
+ internal FieldValue(ulong number)
+ {
+ Number = number;
+ ByteString = null;
+ }
+
+ internal FieldValue(ByteString byteString)
+ {
+ Number = 0;
+ ByteString = byteString;
+ }
+ }
+ }
+}
diff --git a/csharp/src/Google.Protobuf/Reflection/Descriptor.cs b/csharp/src/Google.Protobuf/Reflection/Descriptor.cs
index d743e516..6aad0e99 100644
--- a/csharp/src/Google.Protobuf/Reflection/Descriptor.cs
+++ b/csharp/src/Google.Protobuf/Reflection/Descriptor.cs
@@ -35,7 +35,7 @@ namespace Google.Protobuf.Reflection {
"LnByb3RvYnVmLkZpZWxkRGVzY3JpcHRvclByb3RvEi0KB29wdGlvbnMYCCAB",
"KAsyHC5nb29nbGUucHJvdG9idWYuRmlsZU9wdGlvbnMSOQoQc291cmNlX2Nv",
"ZGVfaW5mbxgJIAEoCzIfLmdvb2dsZS5wcm90b2J1Zi5Tb3VyY2VDb2RlSW5m",
- "bxIOCgZzeW50YXgYDCABKAki8AQKD0Rlc2NyaXB0b3JQcm90bxIMCgRuYW1l",
+ "bxIOCgZzeW50YXgYDCABKAkiqQUKD0Rlc2NyaXB0b3JQcm90bxIMCgRuYW1l",
"GAEgASgJEjQKBWZpZWxkGAIgAygLMiUuZ29vZ2xlLnByb3RvYnVmLkZpZWxk",
"RGVzY3JpcHRvclByb3RvEjgKCWV4dGVuc2lvbhgGIAMoCzIlLmdvb2dsZS5w",
"cm90b2J1Zi5GaWVsZERlc2NyaXB0b3JQcm90bxI1CgtuZXN0ZWRfdHlwZRgD",
@@ -47,119 +47,129 @@ namespace Google.Protobuf.Reflection {
"b3RvEjAKB29wdGlvbnMYByABKAsyHy5nb29nbGUucHJvdG9idWYuTWVzc2Fn",
"ZU9wdGlvbnMSRgoOcmVzZXJ2ZWRfcmFuZ2UYCSADKAsyLi5nb29nbGUucHJv",
"dG9idWYuRGVzY3JpcHRvclByb3RvLlJlc2VydmVkUmFuZ2USFQoNcmVzZXJ2",
- "ZWRfbmFtZRgKIAMoCRosCg5FeHRlbnNpb25SYW5nZRINCgVzdGFydBgBIAEo",
- "BRILCgNlbmQYAiABKAUaKwoNUmVzZXJ2ZWRSYW5nZRINCgVzdGFydBgBIAEo",
- "BRILCgNlbmQYAiABKAUivAUKFEZpZWxkRGVzY3JpcHRvclByb3RvEgwKBG5h",
- "bWUYASABKAkSDgoGbnVtYmVyGAMgASgFEjoKBWxhYmVsGAQgASgOMisuZ29v",
- "Z2xlLnByb3RvYnVmLkZpZWxkRGVzY3JpcHRvclByb3RvLkxhYmVsEjgKBHR5",
- "cGUYBSABKA4yKi5nb29nbGUucHJvdG9idWYuRmllbGREZXNjcmlwdG9yUHJv",
- "dG8uVHlwZRIRCgl0eXBlX25hbWUYBiABKAkSEAoIZXh0ZW5kZWUYAiABKAkS",
- "FQoNZGVmYXVsdF92YWx1ZRgHIAEoCRITCgtvbmVvZl9pbmRleBgJIAEoBRIR",
- "Cglqc29uX25hbWUYCiABKAkSLgoHb3B0aW9ucxgIIAEoCzIdLmdvb2dsZS5w",
- "cm90b2J1Zi5GaWVsZE9wdGlvbnMitgIKBFR5cGUSDwoLVFlQRV9ET1VCTEUQ",
- "ARIOCgpUWVBFX0ZMT0FUEAISDgoKVFlQRV9JTlQ2NBADEg8KC1RZUEVfVUlO",
- "VDY0EAQSDgoKVFlQRV9JTlQzMhAFEhAKDFRZUEVfRklYRUQ2NBAGEhAKDFRZ",
- "UEVfRklYRUQzMhAHEg0KCVRZUEVfQk9PTBAIEg8KC1RZUEVfU1RSSU5HEAkS",
- "DgoKVFlQRV9HUk9VUBAKEhAKDFRZUEVfTUVTU0FHRRALEg4KClRZUEVfQllU",
- "RVMQDBIPCgtUWVBFX1VJTlQzMhANEg0KCVRZUEVfRU5VTRAOEhEKDVRZUEVf",
- "U0ZJWEVEMzIQDxIRCg1UWVBFX1NGSVhFRDY0EBASDwoLVFlQRV9TSU5UMzIQ",
- "ERIPCgtUWVBFX1NJTlQ2NBASIkMKBUxhYmVsEhIKDkxBQkVMX09QVElPTkFM",
- "EAESEgoOTEFCRUxfUkVRVUlSRUQQAhISCg5MQUJFTF9SRVBFQVRFRBADIlQK",
- "FE9uZW9mRGVzY3JpcHRvclByb3RvEgwKBG5hbWUYASABKAkSLgoHb3B0aW9u",
- "cxgCIAEoCzIdLmdvb2dsZS5wcm90b2J1Zi5PbmVvZk9wdGlvbnMijAEKE0Vu",
- "dW1EZXNjcmlwdG9yUHJvdG8SDAoEbmFtZRgBIAEoCRI4CgV2YWx1ZRgCIAMo",
- "CzIpLmdvb2dsZS5wcm90b2J1Zi5FbnVtVmFsdWVEZXNjcmlwdG9yUHJvdG8S",
- "LQoHb3B0aW9ucxgDIAEoCzIcLmdvb2dsZS5wcm90b2J1Zi5FbnVtT3B0aW9u",
- "cyJsChhFbnVtVmFsdWVEZXNjcmlwdG9yUHJvdG8SDAoEbmFtZRgBIAEoCRIO",
- "CgZudW1iZXIYAiABKAUSMgoHb3B0aW9ucxgDIAEoCzIhLmdvb2dsZS5wcm90",
- "b2J1Zi5FbnVtVmFsdWVPcHRpb25zIpABChZTZXJ2aWNlRGVzY3JpcHRvclBy",
- "b3RvEgwKBG5hbWUYASABKAkSNgoGbWV0aG9kGAIgAygLMiYuZ29vZ2xlLnBy",
- "b3RvYnVmLk1ldGhvZERlc2NyaXB0b3JQcm90bxIwCgdvcHRpb25zGAMgASgL",
- "Mh8uZ29vZ2xlLnByb3RvYnVmLlNlcnZpY2VPcHRpb25zIsEBChVNZXRob2RE",
- "ZXNjcmlwdG9yUHJvdG8SDAoEbmFtZRgBIAEoCRISCgppbnB1dF90eXBlGAIg",
- "ASgJEhMKC291dHB1dF90eXBlGAMgASgJEi8KB29wdGlvbnMYBCABKAsyHi5n",
- "b29nbGUucHJvdG9idWYuTWV0aG9kT3B0aW9ucxIfChBjbGllbnRfc3RyZWFt",
- "aW5nGAUgASgIOgVmYWxzZRIfChBzZXJ2ZXJfc3RyZWFtaW5nGAYgASgIOgVm",
- "YWxzZSKaBQoLRmlsZU9wdGlvbnMSFAoMamF2YV9wYWNrYWdlGAEgASgJEhwK",
- "FGphdmFfb3V0ZXJfY2xhc3NuYW1lGAggASgJEiIKE2phdmFfbXVsdGlwbGVf",
- "ZmlsZXMYCiABKAg6BWZhbHNlEikKHWphdmFfZ2VuZXJhdGVfZXF1YWxzX2Fu",
- "ZF9oYXNoGBQgASgIQgIYARIlChZqYXZhX3N0cmluZ19jaGVja191dGY4GBsg",
- "ASgIOgVmYWxzZRJGCgxvcHRpbWl6ZV9mb3IYCSABKA4yKS5nb29nbGUucHJv",
- "dG9idWYuRmlsZU9wdGlvbnMuT3B0aW1pemVNb2RlOgVTUEVFRBISCgpnb19w",
- "YWNrYWdlGAsgASgJEiIKE2NjX2dlbmVyaWNfc2VydmljZXMYECABKAg6BWZh",
- "bHNlEiQKFWphdmFfZ2VuZXJpY19zZXJ2aWNlcxgRIAEoCDoFZmFsc2USIgoT",
- "cHlfZ2VuZXJpY19zZXJ2aWNlcxgSIAEoCDoFZmFsc2USGQoKZGVwcmVjYXRl",
- "ZBgXIAEoCDoFZmFsc2USHwoQY2NfZW5hYmxlX2FyZW5hcxgfIAEoCDoFZmFs",
- "c2USGQoRb2JqY19jbGFzc19wcmVmaXgYJCABKAkSGAoQY3NoYXJwX25hbWVz",
- "cGFjZRglIAEoCRIUCgxzd2lmdF9wcmVmaXgYJyABKAkSQwoUdW5pbnRlcnBy",
- "ZXRlZF9vcHRpb24Y5wcgAygLMiQuZ29vZ2xlLnByb3RvYnVmLlVuaW50ZXJw",
- "cmV0ZWRPcHRpb24iOgoMT3B0aW1pemVNb2RlEgkKBVNQRUVEEAESDQoJQ09E",
- "RV9TSVpFEAISEAoMTElURV9SVU5USU1FEAMqCQjoBxCAgICAAkoECCYQJyLs",
- "AQoOTWVzc2FnZU9wdGlvbnMSJgoXbWVzc2FnZV9zZXRfd2lyZV9mb3JtYXQY",
- "ASABKAg6BWZhbHNlEi4KH25vX3N0YW5kYXJkX2Rlc2NyaXB0b3JfYWNjZXNz",
- "b3IYAiABKAg6BWZhbHNlEhkKCmRlcHJlY2F0ZWQYAyABKAg6BWZhbHNlEhEK",
- "CW1hcF9lbnRyeRgHIAEoCBJDChR1bmludGVycHJldGVkX29wdGlvbhjnByAD",
- "KAsyJC5nb29nbGUucHJvdG9idWYuVW5pbnRlcnByZXRlZE9wdGlvbioJCOgH",
- "EICAgIACSgQICBAJIp4DCgxGaWVsZE9wdGlvbnMSOgoFY3R5cGUYASABKA4y",
- "Iy5nb29nbGUucHJvdG9idWYuRmllbGRPcHRpb25zLkNUeXBlOgZTVFJJTkcS",
- "DgoGcGFja2VkGAIgASgIEj8KBmpzdHlwZRgGIAEoDjIkLmdvb2dsZS5wcm90",
- "b2J1Zi5GaWVsZE9wdGlvbnMuSlNUeXBlOglKU19OT1JNQUwSEwoEbGF6eRgF",
- "IAEoCDoFZmFsc2USGQoKZGVwcmVjYXRlZBgDIAEoCDoFZmFsc2USEwoEd2Vh",
- "axgKIAEoCDoFZmFsc2USQwoUdW5pbnRlcnByZXRlZF9vcHRpb24Y5wcgAygL",
- "MiQuZ29vZ2xlLnByb3RvYnVmLlVuaW50ZXJwcmV0ZWRPcHRpb24iLwoFQ1R5",
- "cGUSCgoGU1RSSU5HEAASCAoEQ09SRBABEhAKDFNUUklOR19QSUVDRRACIjUK",
- "BkpTVHlwZRINCglKU19OT1JNQUwQABINCglKU19TVFJJTkcQARINCglKU19O",
- "VU1CRVIQAioJCOgHEICAgIACSgQIBBAFIl4KDE9uZW9mT3B0aW9ucxJDChR1",
- "bmludGVycHJldGVkX29wdGlvbhjnByADKAsyJC5nb29nbGUucHJvdG9idWYu",
- "VW5pbnRlcnByZXRlZE9wdGlvbioJCOgHEICAgIACIo0BCgtFbnVtT3B0aW9u",
- "cxITCgthbGxvd19hbGlhcxgCIAEoCBIZCgpkZXByZWNhdGVkGAMgASgIOgVm",
- "YWxzZRJDChR1bmludGVycHJldGVkX29wdGlvbhjnByADKAsyJC5nb29nbGUu",
- "cHJvdG9idWYuVW5pbnRlcnByZXRlZE9wdGlvbioJCOgHEICAgIACIn0KEEVu",
- "dW1WYWx1ZU9wdGlvbnMSGQoKZGVwcmVjYXRlZBgBIAEoCDoFZmFsc2USQwoU",
+ "ZWRfbmFtZRgKIAMoCRplCg5FeHRlbnNpb25SYW5nZRINCgVzdGFydBgBIAEo",
+ "BRILCgNlbmQYAiABKAUSNwoHb3B0aW9ucxgDIAEoCzImLmdvb2dsZS5wcm90",
+ "b2J1Zi5FeHRlbnNpb25SYW5nZU9wdGlvbnMaKwoNUmVzZXJ2ZWRSYW5nZRIN",
+ "CgVzdGFydBgBIAEoBRILCgNlbmQYAiABKAUiZwoVRXh0ZW5zaW9uUmFuZ2VP",
+ "cHRpb25zEkMKFHVuaW50ZXJwcmV0ZWRfb3B0aW9uGOcHIAMoCzIkLmdvb2ds",
+ "ZS5wcm90b2J1Zi5VbmludGVycHJldGVkT3B0aW9uKgkI6AcQgICAgAIivAUK",
+ "FEZpZWxkRGVzY3JpcHRvclByb3RvEgwKBG5hbWUYASABKAkSDgoGbnVtYmVy",
+ "GAMgASgFEjoKBWxhYmVsGAQgASgOMisuZ29vZ2xlLnByb3RvYnVmLkZpZWxk",
+ "RGVzY3JpcHRvclByb3RvLkxhYmVsEjgKBHR5cGUYBSABKA4yKi5nb29nbGUu",
+ "cHJvdG9idWYuRmllbGREZXNjcmlwdG9yUHJvdG8uVHlwZRIRCgl0eXBlX25h",
+ "bWUYBiABKAkSEAoIZXh0ZW5kZWUYAiABKAkSFQoNZGVmYXVsdF92YWx1ZRgH",
+ "IAEoCRITCgtvbmVvZl9pbmRleBgJIAEoBRIRCglqc29uX25hbWUYCiABKAkS",
+ "LgoHb3B0aW9ucxgIIAEoCzIdLmdvb2dsZS5wcm90b2J1Zi5GaWVsZE9wdGlv",
+ "bnMitgIKBFR5cGUSDwoLVFlQRV9ET1VCTEUQARIOCgpUWVBFX0ZMT0FUEAIS",
+ "DgoKVFlQRV9JTlQ2NBADEg8KC1RZUEVfVUlOVDY0EAQSDgoKVFlQRV9JTlQz",
+ "MhAFEhAKDFRZUEVfRklYRUQ2NBAGEhAKDFRZUEVfRklYRUQzMhAHEg0KCVRZ",
+ "UEVfQk9PTBAIEg8KC1RZUEVfU1RSSU5HEAkSDgoKVFlQRV9HUk9VUBAKEhAK",
+ "DFRZUEVfTUVTU0FHRRALEg4KClRZUEVfQllURVMQDBIPCgtUWVBFX1VJTlQz",
+ "MhANEg0KCVRZUEVfRU5VTRAOEhEKDVRZUEVfU0ZJWEVEMzIQDxIRCg1UWVBF",
+ "X1NGSVhFRDY0EBASDwoLVFlQRV9TSU5UMzIQERIPCgtUWVBFX1NJTlQ2NBAS",
+ "IkMKBUxhYmVsEhIKDkxBQkVMX09QVElPTkFMEAESEgoOTEFCRUxfUkVRVUlS",
+ "RUQQAhISCg5MQUJFTF9SRVBFQVRFRBADIlQKFE9uZW9mRGVzY3JpcHRvclBy",
+ "b3RvEgwKBG5hbWUYASABKAkSLgoHb3B0aW9ucxgCIAEoCzIdLmdvb2dsZS5w",
+ "cm90b2J1Zi5PbmVvZk9wdGlvbnMipAIKE0VudW1EZXNjcmlwdG9yUHJvdG8S",
+ "DAoEbmFtZRgBIAEoCRI4CgV2YWx1ZRgCIAMoCzIpLmdvb2dsZS5wcm90b2J1",
+ "Zi5FbnVtVmFsdWVEZXNjcmlwdG9yUHJvdG8SLQoHb3B0aW9ucxgDIAEoCzIc",
+ "Lmdvb2dsZS5wcm90b2J1Zi5FbnVtT3B0aW9ucxJOCg5yZXNlcnZlZF9yYW5n",
+ "ZRgEIAMoCzI2Lmdvb2dsZS5wcm90b2J1Zi5FbnVtRGVzY3JpcHRvclByb3Rv",
+ "LkVudW1SZXNlcnZlZFJhbmdlEhUKDXJlc2VydmVkX25hbWUYBSADKAkaLwoR",
+ "RW51bVJlc2VydmVkUmFuZ2USDQoFc3RhcnQYASABKAUSCwoDZW5kGAIgASgF",
+ "ImwKGEVudW1WYWx1ZURlc2NyaXB0b3JQcm90bxIMCgRuYW1lGAEgASgJEg4K",
+ "Bm51bWJlchgCIAEoBRIyCgdvcHRpb25zGAMgASgLMiEuZ29vZ2xlLnByb3Rv",
+ "YnVmLkVudW1WYWx1ZU9wdGlvbnMikAEKFlNlcnZpY2VEZXNjcmlwdG9yUHJv",
+ "dG8SDAoEbmFtZRgBIAEoCRI2CgZtZXRob2QYAiADKAsyJi5nb29nbGUucHJv",
+ "dG9idWYuTWV0aG9kRGVzY3JpcHRvclByb3RvEjAKB29wdGlvbnMYAyABKAsy",
+ "Hy5nb29nbGUucHJvdG9idWYuU2VydmljZU9wdGlvbnMiwQEKFU1ldGhvZERl",
+ "c2NyaXB0b3JQcm90bxIMCgRuYW1lGAEgASgJEhIKCmlucHV0X3R5cGUYAiAB",
+ "KAkSEwoLb3V0cHV0X3R5cGUYAyABKAkSLwoHb3B0aW9ucxgEIAEoCzIeLmdv",
+ "b2dsZS5wcm90b2J1Zi5NZXRob2RPcHRpb25zEh8KEGNsaWVudF9zdHJlYW1p",
+ "bmcYBSABKAg6BWZhbHNlEh8KEHNlcnZlcl9zdHJlYW1pbmcYBiABKAg6BWZh",
+ "bHNlIvAFCgtGaWxlT3B0aW9ucxIUCgxqYXZhX3BhY2thZ2UYASABKAkSHAoU",
+ "amF2YV9vdXRlcl9jbGFzc25hbWUYCCABKAkSIgoTamF2YV9tdWx0aXBsZV9m",
+ "aWxlcxgKIAEoCDoFZmFsc2USKQodamF2YV9nZW5lcmF0ZV9lcXVhbHNfYW5k",
+ "X2hhc2gYFCABKAhCAhgBEiUKFmphdmFfc3RyaW5nX2NoZWNrX3V0ZjgYGyAB",
+ "KAg6BWZhbHNlEkYKDG9wdGltaXplX2ZvchgJIAEoDjIpLmdvb2dsZS5wcm90",
+ "b2J1Zi5GaWxlT3B0aW9ucy5PcHRpbWl6ZU1vZGU6BVNQRUVEEhIKCmdvX3Bh",
+ "Y2thZ2UYCyABKAkSIgoTY2NfZ2VuZXJpY19zZXJ2aWNlcxgQIAEoCDoFZmFs",
+ "c2USJAoVamF2YV9nZW5lcmljX3NlcnZpY2VzGBEgASgIOgVmYWxzZRIiChNw",
+ "eV9nZW5lcmljX3NlcnZpY2VzGBIgASgIOgVmYWxzZRIjChRwaHBfZ2VuZXJp",
+ "Y19zZXJ2aWNlcxgqIAEoCDoFZmFsc2USGQoKZGVwcmVjYXRlZBgXIAEoCDoF",
+ "ZmFsc2USHwoQY2NfZW5hYmxlX2FyZW5hcxgfIAEoCDoFZmFsc2USGQoRb2Jq",
+ "Y19jbGFzc19wcmVmaXgYJCABKAkSGAoQY3NoYXJwX25hbWVzcGFjZRglIAEo",
+ "CRIUCgxzd2lmdF9wcmVmaXgYJyABKAkSGAoQcGhwX2NsYXNzX3ByZWZpeBgo",
+ "IAEoCRIVCg1waHBfbmFtZXNwYWNlGCkgASgJEkMKFHVuaW50ZXJwcmV0ZWRf",
+ "b3B0aW9uGOcHIAMoCzIkLmdvb2dsZS5wcm90b2J1Zi5VbmludGVycHJldGVk",
+ "T3B0aW9uIjoKDE9wdGltaXplTW9kZRIJCgVTUEVFRBABEg0KCUNPREVfU0la",
+ "RRACEhAKDExJVEVfUlVOVElNRRADKgkI6AcQgICAgAJKBAgmECci8gEKDk1l",
+ "c3NhZ2VPcHRpb25zEiYKF21lc3NhZ2Vfc2V0X3dpcmVfZm9ybWF0GAEgASgI",
+ "OgVmYWxzZRIuCh9ub19zdGFuZGFyZF9kZXNjcmlwdG9yX2FjY2Vzc29yGAIg",
+ "ASgIOgVmYWxzZRIZCgpkZXByZWNhdGVkGAMgASgIOgVmYWxzZRIRCgltYXBf",
+ "ZW50cnkYByABKAgSQwoUdW5pbnRlcnByZXRlZF9vcHRpb24Y5wcgAygLMiQu",
+ "Z29vZ2xlLnByb3RvYnVmLlVuaW50ZXJwcmV0ZWRPcHRpb24qCQjoBxCAgICA",
+ "AkoECAgQCUoECAkQCiKeAwoMRmllbGRPcHRpb25zEjoKBWN0eXBlGAEgASgO",
+ "MiMuZ29vZ2xlLnByb3RvYnVmLkZpZWxkT3B0aW9ucy5DVHlwZToGU1RSSU5H",
+ "Eg4KBnBhY2tlZBgCIAEoCBI/CgZqc3R5cGUYBiABKA4yJC5nb29nbGUucHJv",
+ "dG9idWYuRmllbGRPcHRpb25zLkpTVHlwZToJSlNfTk9STUFMEhMKBGxhenkY",
+ "BSABKAg6BWZhbHNlEhkKCmRlcHJlY2F0ZWQYAyABKAg6BWZhbHNlEhMKBHdl",
+ "YWsYCiABKAg6BWZhbHNlEkMKFHVuaW50ZXJwcmV0ZWRfb3B0aW9uGOcHIAMo",
+ "CzIkLmdvb2dsZS5wcm90b2J1Zi5VbmludGVycHJldGVkT3B0aW9uIi8KBUNU",
+ "eXBlEgoKBlNUUklORxAAEggKBENPUkQQARIQCgxTVFJJTkdfUElFQ0UQAiI1",
+ "CgZKU1R5cGUSDQoJSlNfTk9STUFMEAASDQoJSlNfU1RSSU5HEAESDQoJSlNf",
+ "TlVNQkVSEAIqCQjoBxCAgICAAkoECAQQBSJeCgxPbmVvZk9wdGlvbnMSQwoU",
"dW5pbnRlcnByZXRlZF9vcHRpb24Y5wcgAygLMiQuZ29vZ2xlLnByb3RvYnVm",
- "LlVuaW50ZXJwcmV0ZWRPcHRpb24qCQjoBxCAgICAAiJ7Cg5TZXJ2aWNlT3B0",
- "aW9ucxIZCgpkZXByZWNhdGVkGCEgASgIOgVmYWxzZRJDChR1bmludGVycHJl",
- "dGVkX29wdGlvbhjnByADKAsyJC5nb29nbGUucHJvdG9idWYuVW5pbnRlcnBy",
- "ZXRlZE9wdGlvbioJCOgHEICAgIACIq0CCg1NZXRob2RPcHRpb25zEhkKCmRl",
- "cHJlY2F0ZWQYISABKAg6BWZhbHNlEl8KEWlkZW1wb3RlbmN5X2xldmVsGCIg",
- "ASgOMi8uZ29vZ2xlLnByb3RvYnVmLk1ldGhvZE9wdGlvbnMuSWRlbXBvdGVu",
- "Y3lMZXZlbDoTSURFTVBPVEVOQ1lfVU5LTk9XThJDChR1bmludGVycHJldGVk",
- "X29wdGlvbhjnByADKAsyJC5nb29nbGUucHJvdG9idWYuVW5pbnRlcnByZXRl",
- "ZE9wdGlvbiJQChBJZGVtcG90ZW5jeUxldmVsEhcKE0lERU1QT1RFTkNZX1VO",
- "S05PV04QABITCg9OT19TSURFX0VGRkVDVFMQARIOCgpJREVNUE9URU5UEAIq",
- "CQjoBxCAgICAAiKeAgoTVW5pbnRlcnByZXRlZE9wdGlvbhI7CgRuYW1lGAIg",
- "AygLMi0uZ29vZ2xlLnByb3RvYnVmLlVuaW50ZXJwcmV0ZWRPcHRpb24uTmFt",
- "ZVBhcnQSGAoQaWRlbnRpZmllcl92YWx1ZRgDIAEoCRIaChJwb3NpdGl2ZV9p",
- "bnRfdmFsdWUYBCABKAQSGgoSbmVnYXRpdmVfaW50X3ZhbHVlGAUgASgDEhQK",
- "DGRvdWJsZV92YWx1ZRgGIAEoARIUCgxzdHJpbmdfdmFsdWUYByABKAwSFwoP",
- "YWdncmVnYXRlX3ZhbHVlGAggASgJGjMKCE5hbWVQYXJ0EhEKCW5hbWVfcGFy",
- "dBgBIAIoCRIUCgxpc19leHRlbnNpb24YAiACKAgi1QEKDlNvdXJjZUNvZGVJ",
- "bmZvEjoKCGxvY2F0aW9uGAEgAygLMiguZ29vZ2xlLnByb3RvYnVmLlNvdXJj",
- "ZUNvZGVJbmZvLkxvY2F0aW9uGoYBCghMb2NhdGlvbhIQCgRwYXRoGAEgAygF",
- "QgIQARIQCgRzcGFuGAIgAygFQgIQARIYChBsZWFkaW5nX2NvbW1lbnRzGAMg",
- "ASgJEhkKEXRyYWlsaW5nX2NvbW1lbnRzGAQgASgJEiEKGWxlYWRpbmdfZGV0",
- "YWNoZWRfY29tbWVudHMYBiADKAkipwEKEUdlbmVyYXRlZENvZGVJbmZvEkEK",
- "CmFubm90YXRpb24YASADKAsyLS5nb29nbGUucHJvdG9idWYuR2VuZXJhdGVk",
- "Q29kZUluZm8uQW5ub3RhdGlvbhpPCgpBbm5vdGF0aW9uEhAKBHBhdGgYASAD",
- "KAVCAhABEhMKC3NvdXJjZV9maWxlGAIgASgJEg0KBWJlZ2luGAMgASgFEgsK",
- "A2VuZBgEIAEoBUKMAQoTY29tLmdvb2dsZS5wcm90b2J1ZkIQRGVzY3JpcHRv",
- "clByb3Rvc0gBWj5naXRodWIuY29tL2dvbGFuZy9wcm90b2J1Zi9wcm90b2Mt",
- "Z2VuLWdvL2Rlc2NyaXB0b3I7ZGVzY3JpcHRvcqICA0dQQqoCGkdvb2dsZS5Q",
- "cm90b2J1Zi5SZWZsZWN0aW9u"));
+ "LlVuaW50ZXJwcmV0ZWRPcHRpb24qCQjoBxCAgICAAiKTAQoLRW51bU9wdGlv",
+ "bnMSEwoLYWxsb3dfYWxpYXMYAiABKAgSGQoKZGVwcmVjYXRlZBgDIAEoCDoF",
+ "ZmFsc2USQwoUdW5pbnRlcnByZXRlZF9vcHRpb24Y5wcgAygLMiQuZ29vZ2xl",
+ "LnByb3RvYnVmLlVuaW50ZXJwcmV0ZWRPcHRpb24qCQjoBxCAgICAAkoECAUQ",
+ "BiJ9ChBFbnVtVmFsdWVPcHRpb25zEhkKCmRlcHJlY2F0ZWQYASABKAg6BWZh",
+ "bHNlEkMKFHVuaW50ZXJwcmV0ZWRfb3B0aW9uGOcHIAMoCzIkLmdvb2dsZS5w",
+ "cm90b2J1Zi5VbmludGVycHJldGVkT3B0aW9uKgkI6AcQgICAgAIiewoOU2Vy",
+ "dmljZU9wdGlvbnMSGQoKZGVwcmVjYXRlZBghIAEoCDoFZmFsc2USQwoUdW5p",
+ "bnRlcnByZXRlZF9vcHRpb24Y5wcgAygLMiQuZ29vZ2xlLnByb3RvYnVmLlVu",
+ "aW50ZXJwcmV0ZWRPcHRpb24qCQjoBxCAgICAAiKtAgoNTWV0aG9kT3B0aW9u",
+ "cxIZCgpkZXByZWNhdGVkGCEgASgIOgVmYWxzZRJfChFpZGVtcG90ZW5jeV9s",
+ "ZXZlbBgiIAEoDjIvLmdvb2dsZS5wcm90b2J1Zi5NZXRob2RPcHRpb25zLklk",
+ "ZW1wb3RlbmN5TGV2ZWw6E0lERU1QT1RFTkNZX1VOS05PV04SQwoUdW5pbnRl",
+ "cnByZXRlZF9vcHRpb24Y5wcgAygLMiQuZ29vZ2xlLnByb3RvYnVmLlVuaW50",
+ "ZXJwcmV0ZWRPcHRpb24iUAoQSWRlbXBvdGVuY3lMZXZlbBIXChNJREVNUE9U",
+ "RU5DWV9VTktOT1dOEAASEwoPTk9fU0lERV9FRkZFQ1RTEAESDgoKSURFTVBP",
+ "VEVOVBACKgkI6AcQgICAgAIingIKE1VuaW50ZXJwcmV0ZWRPcHRpb24SOwoE",
+ "bmFtZRgCIAMoCzItLmdvb2dsZS5wcm90b2J1Zi5VbmludGVycHJldGVkT3B0",
+ "aW9uLk5hbWVQYXJ0EhgKEGlkZW50aWZpZXJfdmFsdWUYAyABKAkSGgoScG9z",
+ "aXRpdmVfaW50X3ZhbHVlGAQgASgEEhoKEm5lZ2F0aXZlX2ludF92YWx1ZRgF",
+ "IAEoAxIUCgxkb3VibGVfdmFsdWUYBiABKAESFAoMc3RyaW5nX3ZhbHVlGAcg",
+ "ASgMEhcKD2FnZ3JlZ2F0ZV92YWx1ZRgIIAEoCRozCghOYW1lUGFydBIRCglu",
+ "YW1lX3BhcnQYASACKAkSFAoMaXNfZXh0ZW5zaW9uGAIgAigIItUBCg5Tb3Vy",
+ "Y2VDb2RlSW5mbxI6Cghsb2NhdGlvbhgBIAMoCzIoLmdvb2dsZS5wcm90b2J1",
+ "Zi5Tb3VyY2VDb2RlSW5mby5Mb2NhdGlvbhqGAQoITG9jYXRpb24SEAoEcGF0",
+ "aBgBIAMoBUICEAESEAoEc3BhbhgCIAMoBUICEAESGAoQbGVhZGluZ19jb21t",
+ "ZW50cxgDIAEoCRIZChF0cmFpbGluZ19jb21tZW50cxgEIAEoCRIhChlsZWFk",
+ "aW5nX2RldGFjaGVkX2NvbW1lbnRzGAYgAygJIqcBChFHZW5lcmF0ZWRDb2Rl",
+ "SW5mbxJBCgphbm5vdGF0aW9uGAEgAygLMi0uZ29vZ2xlLnByb3RvYnVmLkdl",
+ "bmVyYXRlZENvZGVJbmZvLkFubm90YXRpb24aTwoKQW5ub3RhdGlvbhIQCgRw",
+ "YXRoGAEgAygFQgIQARITCgtzb3VyY2VfZmlsZRgCIAEoCRINCgViZWdpbhgD",
+ "IAEoBRILCgNlbmQYBCABKAVCjwEKE2NvbS5nb29nbGUucHJvdG9idWZCEERl",
+ "c2NyaXB0b3JQcm90b3NIAVo+Z2l0aHViLmNvbS9nb2xhbmcvcHJvdG9idWYv",
+ "cHJvdG9jLWdlbi1nby9kZXNjcmlwdG9yO2Rlc2NyaXB0b3L4AQGiAgNHUEKq",
+ "AhpHb29nbGUuUHJvdG9idWYuUmVmbGVjdGlvbg=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.FileDescriptorSet), global::Google.Protobuf.Reflection.FileDescriptorSet.Parser, new[]{ "File" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.FileDescriptorProto), global::Google.Protobuf.Reflection.FileDescriptorProto.Parser, new[]{ "Name", "Package", "Dependency", "PublicDependency", "WeakDependency", "MessageType", "EnumType", "Service", "Extension", "Options", "SourceCodeInfo", "Syntax" }, null, null, null),
- new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.DescriptorProto), global::Google.Protobuf.Reflection.DescriptorProto.Parser, new[]{ "Name", "Field", "Extension", "NestedType", "EnumType", "ExtensionRange", "OneofDecl", "Options", "ReservedRange", "ReservedName" }, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.DescriptorProto.Types.ExtensionRange), global::Google.Protobuf.Reflection.DescriptorProto.Types.ExtensionRange.Parser, new[]{ "Start", "End" }, null, null, null),
+ new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.DescriptorProto), global::Google.Protobuf.Reflection.DescriptorProto.Parser, new[]{ "Name", "Field", "Extension", "NestedType", "EnumType", "ExtensionRange", "OneofDecl", "Options", "ReservedRange", "ReservedName" }, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.DescriptorProto.Types.ExtensionRange), global::Google.Protobuf.Reflection.DescriptorProto.Types.ExtensionRange.Parser, new[]{ "Start", "End", "Options" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.DescriptorProto.Types.ReservedRange), global::Google.Protobuf.Reflection.DescriptorProto.Types.ReservedRange.Parser, new[]{ "Start", "End" }, null, null, null)}),
+ new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.ExtensionRangeOptions), global::Google.Protobuf.Reflection.ExtensionRangeOptions.Parser, new[]{ "UninterpretedOption" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.FieldDescriptorProto), global::Google.Protobuf.Reflection.FieldDescriptorProto.Parser, new[]{ "Name", "Number", "Label", "Type", "TypeName", "Extendee", "DefaultValue", "OneofIndex", "JsonName", "Options" }, null, new[]{ typeof(global::Google.Protobuf.Reflection.FieldDescriptorProto.Types.Type), typeof(global::Google.Protobuf.Reflection.FieldDescriptorProto.Types.Label) }, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.OneofDescriptorProto), global::Google.Protobuf.Reflection.OneofDescriptorProto.Parser, new[]{ "Name", "Options" }, null, null, null),
- new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.EnumDescriptorProto), global::Google.Protobuf.Reflection.EnumDescriptorProto.Parser, new[]{ "Name", "Value", "Options" }, null, null, null),
+ new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.EnumDescriptorProto), global::Google.Protobuf.Reflection.EnumDescriptorProto.Parser, new[]{ "Name", "Value", "Options", "ReservedRange", "ReservedName" }, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.EnumDescriptorProto.Types.EnumReservedRange), global::Google.Protobuf.Reflection.EnumDescriptorProto.Types.EnumReservedRange.Parser, new[]{ "Start", "End" }, null, null, null)}),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.EnumValueDescriptorProto), global::Google.Protobuf.Reflection.EnumValueDescriptorProto.Parser, new[]{ "Name", "Number", "Options" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.ServiceDescriptorProto), global::Google.Protobuf.Reflection.ServiceDescriptorProto.Parser, new[]{ "Name", "Method", "Options" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.MethodDescriptorProto), global::Google.Protobuf.Reflection.MethodDescriptorProto.Parser, new[]{ "Name", "InputType", "OutputType", "Options", "ClientStreaming", "ServerStreaming" }, null, null, null),
- new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.FileOptions), global::Google.Protobuf.Reflection.FileOptions.Parser, new[]{ "JavaPackage", "JavaOuterClassname", "JavaMultipleFiles", "JavaGenerateEqualsAndHash", "JavaStringCheckUtf8", "OptimizeFor", "GoPackage", "CcGenericServices", "JavaGenericServices", "PyGenericServices", "Deprecated", "CcEnableArenas", "ObjcClassPrefix", "CsharpNamespace", "SwiftPrefix", "UninterpretedOption" }, null, new[]{ typeof(global::Google.Protobuf.Reflection.FileOptions.Types.OptimizeMode) }, null),
+ new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.FileOptions), global::Google.Protobuf.Reflection.FileOptions.Parser, new[]{ "JavaPackage", "JavaOuterClassname", "JavaMultipleFiles", "JavaGenerateEqualsAndHash", "JavaStringCheckUtf8", "OptimizeFor", "GoPackage", "CcGenericServices", "JavaGenericServices", "PyGenericServices", "PhpGenericServices", "Deprecated", "CcEnableArenas", "ObjcClassPrefix", "CsharpNamespace", "SwiftPrefix", "PhpClassPrefix", "PhpNamespace", "UninterpretedOption" }, null, new[]{ typeof(global::Google.Protobuf.Reflection.FileOptions.Types.OptimizeMode) }, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.MessageOptions), global::Google.Protobuf.Reflection.MessageOptions.Parser, new[]{ "MessageSetWireFormat", "NoStandardDescriptorAccessor", "Deprecated", "MapEntry", "UninterpretedOption" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.FieldOptions), global::Google.Protobuf.Reflection.FieldOptions.Parser, new[]{ "Ctype", "Packed", "Jstype", "Lazy", "Deprecated", "Weak", "UninterpretedOption" }, null, new[]{ typeof(global::Google.Protobuf.Reflection.FieldOptions.Types.CType), typeof(global::Google.Protobuf.Reflection.FieldOptions.Types.JSType) }, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.OneofOptions), global::Google.Protobuf.Reflection.OneofOptions.Parser, new[]{ "UninterpretedOption" }, null, null, null),
@@ -1050,6 +1060,7 @@ namespace Google.Protobuf.Reflection {
public ExtensionRange(ExtensionRange other) : this() {
start_ = other.start_;
end_ = other.end_;
+ Options = other.options_ != null ? other.Options.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -1079,6 +1090,17 @@ namespace Google.Protobuf.Reflection {
}
}
+ /// <summary>Field number for the "options" field.</summary>
+ public const int OptionsFieldNumber = 3;
+ private global::Google.Protobuf.Reflection.ExtensionRangeOptions options_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public global::Google.Protobuf.Reflection.ExtensionRangeOptions Options {
+ get { return options_; }
+ set {
+ options_ = value;
+ }
+ }
+
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ExtensionRange);
@@ -1094,6 +1116,7 @@ namespace Google.Protobuf.Reflection {
}
if (Start != other.Start) return false;
if (End != other.End) return false;
+ if (!object.Equals(Options, other.Options)) return false;
return true;
}
@@ -1102,6 +1125,7 @@ namespace Google.Protobuf.Reflection {
int hash = 1;
if (Start != 0) hash ^= Start.GetHashCode();
if (End != 0) hash ^= End.GetHashCode();
+ if (options_ != null) hash ^= Options.GetHashCode();
return hash;
}
@@ -1120,6 +1144,10 @@ namespace Google.Protobuf.Reflection {
output.WriteRawTag(16);
output.WriteInt32(End);
}
+ if (options_ != null) {
+ output.WriteRawTag(26);
+ output.WriteMessage(Options);
+ }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -1131,6 +1159,9 @@ namespace Google.Protobuf.Reflection {
if (End != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(End);
}
+ if (options_ != null) {
+ size += 1 + pb::CodedOutputStream.ComputeMessageSize(Options);
+ }
return size;
}
@@ -1145,6 +1176,12 @@ namespace Google.Protobuf.Reflection {
if (other.End != 0) {
End = other.End;
}
+ if (other.options_ != null) {
+ if (options_ == null) {
+ options_ = new global::Google.Protobuf.Reflection.ExtensionRangeOptions();
+ }
+ Options.MergeFrom(other.Options);
+ }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -1163,6 +1200,13 @@ namespace Google.Protobuf.Reflection {
End = input.ReadInt32();
break;
}
+ case 26: {
+ if (options_ == null) {
+ options_ = new global::Google.Protobuf.Reflection.ExtensionRangeOptions();
+ }
+ input.ReadMessage(options_);
+ break;
+ }
}
}
}
@@ -1330,6 +1374,118 @@ namespace Google.Protobuf.Reflection {
}
+ internal sealed partial class ExtensionRangeOptions : pb::IMessage<ExtensionRangeOptions> {
+ private static readonly pb::MessageParser<ExtensionRangeOptions> _parser = new pb::MessageParser<ExtensionRangeOptions>(() => new ExtensionRangeOptions());
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pb::MessageParser<ExtensionRangeOptions> Parser { get { return _parser; } }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[3]; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public ExtensionRangeOptions() {
+ OnConstruction();
+ }
+
+ partial void OnConstruction();
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public ExtensionRangeOptions(ExtensionRangeOptions other) : this() {
+ uninterpretedOption_ = other.uninterpretedOption_.Clone();
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public ExtensionRangeOptions Clone() {
+ return new ExtensionRangeOptions(this);
+ }
+
+ /// <summary>Field number for the "uninterpreted_option" field.</summary>
+ public const int UninterpretedOptionFieldNumber = 999;
+ private static readonly pb::FieldCodec<global::Google.Protobuf.Reflection.UninterpretedOption> _repeated_uninterpretedOption_codec
+ = pb::FieldCodec.ForMessage(7994, global::Google.Protobuf.Reflection.UninterpretedOption.Parser);
+ private readonly pbc::RepeatedField<global::Google.Protobuf.Reflection.UninterpretedOption> uninterpretedOption_ = new pbc::RepeatedField<global::Google.Protobuf.Reflection.UninterpretedOption>();
+ /// <summary>
+ /// The parser stores options it doesn't recognize here. See above.
+ /// </summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public pbc::RepeatedField<global::Google.Protobuf.Reflection.UninterpretedOption> UninterpretedOption {
+ get { return uninterpretedOption_; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override bool Equals(object other) {
+ return Equals(other as ExtensionRangeOptions);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool Equals(ExtensionRangeOptions other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
+ }
+ if (ReferenceEquals(other, this)) {
+ return true;
+ }
+ if(!uninterpretedOption_.Equals(other.uninterpretedOption_)) return false;
+ return true;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override int GetHashCode() {
+ int hash = 1;
+ hash ^= uninterpretedOption_.GetHashCode();
+ return hash;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override string ToString() {
+ return pb::JsonFormatter.ToDiagnosticString(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void WriteTo(pb::CodedOutputStream output) {
+ uninterpretedOption_.WriteTo(output, _repeated_uninterpretedOption_codec);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int CalculateSize() {
+ int size = 0;
+ size += uninterpretedOption_.CalculateSize(_repeated_uninterpretedOption_codec);
+ return size;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(ExtensionRangeOptions other) {
+ if (other == null) {
+ return;
+ }
+ uninterpretedOption_.Add(other.uninterpretedOption_);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ case 7994: {
+ uninterpretedOption_.AddEntriesFrom(input, _repeated_uninterpretedOption_codec);
+ break;
+ }
+ }
+ }
+ }
+
+ }
+
/// <summary>
/// Describes a field within a message.
/// </summary>
@@ -1340,7 +1496,7 @@ namespace Google.Protobuf.Reflection {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[3]; }
+ get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[4]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -1766,6 +1922,9 @@ namespace Google.Protobuf.Reflection {
[pbr::OriginalName("TYPE_STRING")] String = 9,
/// <summary>
/// Tag-delimited aggregate.
+ /// Group type is deprecated and not supported in proto3. However, Proto3
+ /// implementations should still be able to parse the group wire format and
+ /// treat group fields as unknown fields.
/// </summary>
[pbr::OriginalName("TYPE_GROUP")] Group = 10,
/// <summary>
@@ -1814,7 +1973,7 @@ namespace Google.Protobuf.Reflection {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[4]; }
+ get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[5]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -1968,7 +2127,7 @@ namespace Google.Protobuf.Reflection {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[5]; }
+ get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[6]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -1988,6 +2147,8 @@ namespace Google.Protobuf.Reflection {
name_ = other.name_;
value_ = other.value_.Clone();
Options = other.options_ != null ? other.Options.Clone() : null;
+ reservedRange_ = other.reservedRange_.Clone();
+ reservedName_ = other.reservedName_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -2027,6 +2188,35 @@ namespace Google.Protobuf.Reflection {
}
}
+ /// <summary>Field number for the "reserved_range" field.</summary>
+ public const int ReservedRangeFieldNumber = 4;
+ private static readonly pb::FieldCodec<global::Google.Protobuf.Reflection.EnumDescriptorProto.Types.EnumReservedRange> _repeated_reservedRange_codec
+ = pb::FieldCodec.ForMessage(34, global::Google.Protobuf.Reflection.EnumDescriptorProto.Types.EnumReservedRange.Parser);
+ private readonly pbc::RepeatedField<global::Google.Protobuf.Reflection.EnumDescriptorProto.Types.EnumReservedRange> reservedRange_ = new pbc::RepeatedField<global::Google.Protobuf.Reflection.EnumDescriptorProto.Types.EnumReservedRange>();
+ /// <summary>
+ /// Range of reserved numeric values. Reserved numeric values may not be used
+ /// by enum values in the same enum declaration. Reserved ranges may not
+ /// overlap.
+ /// </summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public pbc::RepeatedField<global::Google.Protobuf.Reflection.EnumDescriptorProto.Types.EnumReservedRange> ReservedRange {
+ get { return reservedRange_; }
+ }
+
+ /// <summary>Field number for the "reserved_name" field.</summary>
+ public const int ReservedNameFieldNumber = 5;
+ private static readonly pb::FieldCodec<string> _repeated_reservedName_codec
+ = pb::FieldCodec.ForString(42);
+ private readonly pbc::RepeatedField<string> reservedName_ = new pbc::RepeatedField<string>();
+ /// <summary>
+ /// Reserved enum value names, which may not be reused. A given name may only
+ /// be reserved once.
+ /// </summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public pbc::RepeatedField<string> ReservedName {
+ get { return reservedName_; }
+ }
+
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as EnumDescriptorProto);
@@ -2043,6 +2233,8 @@ namespace Google.Protobuf.Reflection {
if (Name != other.Name) return false;
if(!value_.Equals(other.value_)) return false;
if (!object.Equals(Options, other.Options)) return false;
+ if(!reservedRange_.Equals(other.reservedRange_)) return false;
+ if(!reservedName_.Equals(other.reservedName_)) return false;
return true;
}
@@ -2052,6 +2244,8 @@ namespace Google.Protobuf.Reflection {
if (Name.Length != 0) hash ^= Name.GetHashCode();
hash ^= value_.GetHashCode();
if (options_ != null) hash ^= Options.GetHashCode();
+ hash ^= reservedRange_.GetHashCode();
+ hash ^= reservedName_.GetHashCode();
return hash;
}
@@ -2071,6 +2265,8 @@ namespace Google.Protobuf.Reflection {
output.WriteRawTag(26);
output.WriteMessage(Options);
}
+ reservedRange_.WriteTo(output, _repeated_reservedRange_codec);
+ reservedName_.WriteTo(output, _repeated_reservedName_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -2083,6 +2279,8 @@ namespace Google.Protobuf.Reflection {
if (options_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Options);
}
+ size += reservedRange_.CalculateSize(_repeated_reservedRange_codec);
+ size += reservedName_.CalculateSize(_repeated_reservedName_codec);
return size;
}
@@ -2101,6 +2299,8 @@ namespace Google.Protobuf.Reflection {
}
Options.MergeFrom(other.Options);
}
+ reservedRange_.Add(other.reservedRange_);
+ reservedName_.Add(other.reservedName_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -2126,10 +2326,184 @@ namespace Google.Protobuf.Reflection {
input.ReadMessage(options_);
break;
}
+ case 34: {
+ reservedRange_.AddEntriesFrom(input, _repeated_reservedRange_codec);
+ break;
+ }
+ case 42: {
+ reservedName_.AddEntriesFrom(input, _repeated_reservedName_codec);
+ break;
+ }
}
}
}
+ #region Nested types
+ /// <summary>Container for nested types declared in the EnumDescriptorProto message type.</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static partial class Types {
+ /// <summary>
+ /// Range of reserved numeric values. Reserved values may not be used by
+ /// entries in the same enum. Reserved ranges may not overlap.
+ ///
+ /// Note that this is distinct from DescriptorProto.ReservedRange in that it
+ /// is inclusive such that it can appropriately represent the entire int32
+ /// domain.
+ /// </summary>
+ internal sealed partial class EnumReservedRange : pb::IMessage<EnumReservedRange> {
+ private static readonly pb::MessageParser<EnumReservedRange> _parser = new pb::MessageParser<EnumReservedRange>(() => new EnumReservedRange());
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pb::MessageParser<EnumReservedRange> Parser { get { return _parser; } }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::Google.Protobuf.Reflection.EnumDescriptorProto.Descriptor.NestedTypes[0]; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public EnumReservedRange() {
+ OnConstruction();
+ }
+
+ partial void OnConstruction();
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public EnumReservedRange(EnumReservedRange other) : this() {
+ start_ = other.start_;
+ end_ = other.end_;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public EnumReservedRange Clone() {
+ return new EnumReservedRange(this);
+ }
+
+ /// <summary>Field number for the "start" field.</summary>
+ public const int StartFieldNumber = 1;
+ private int start_;
+ /// <summary>
+ /// Inclusive.
+ /// </summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int Start {
+ get { return start_; }
+ set {
+ start_ = value;
+ }
+ }
+
+ /// <summary>Field number for the "end" field.</summary>
+ public const int EndFieldNumber = 2;
+ private int end_;
+ /// <summary>
+ /// Inclusive.
+ /// </summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int End {
+ get { return end_; }
+ set {
+ end_ = value;
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override bool Equals(object other) {
+ return Equals(other as EnumReservedRange);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool Equals(EnumReservedRange other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
+ }
+ if (ReferenceEquals(other, this)) {
+ return true;
+ }
+ if (Start != other.Start) return false;
+ if (End != other.End) return false;
+ return true;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override int GetHashCode() {
+ int hash = 1;
+ if (Start != 0) hash ^= Start.GetHashCode();
+ if (End != 0) hash ^= End.GetHashCode();
+ return hash;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override string ToString() {
+ return pb::JsonFormatter.ToDiagnosticString(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void WriteTo(pb::CodedOutputStream output) {
+ if (Start != 0) {
+ output.WriteRawTag(8);
+ output.WriteInt32(Start);
+ }
+ if (End != 0) {
+ output.WriteRawTag(16);
+ output.WriteInt32(End);
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int CalculateSize() {
+ int size = 0;
+ if (Start != 0) {
+ size += 1 + pb::CodedOutputStream.ComputeInt32Size(Start);
+ }
+ if (End != 0) {
+ size += 1 + pb::CodedOutputStream.ComputeInt32Size(End);
+ }
+ return size;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(EnumReservedRange other) {
+ if (other == null) {
+ return;
+ }
+ if (other.Start != 0) {
+ Start = other.Start;
+ }
+ if (other.End != 0) {
+ End = other.End;
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ case 8: {
+ Start = input.ReadInt32();
+ break;
+ }
+ case 16: {
+ End = input.ReadInt32();
+ break;
+ }
+ }
+ }
+ }
+
+ }
+
+ }
+ #endregion
+
}
/// <summary>
@@ -2142,7 +2516,7 @@ namespace Google.Protobuf.Reflection {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[6]; }
+ get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[7]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -2324,7 +2698,7 @@ namespace Google.Protobuf.Reflection {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[7]; }
+ get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[8]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -2498,7 +2872,7 @@ namespace Google.Protobuf.Reflection {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[8]; }
+ get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[9]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -2771,7 +3145,7 @@ namespace Google.Protobuf.Reflection {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[9]; }
+ get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[10]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -2779,6 +3153,8 @@ namespace Google.Protobuf.Reflection {
get { return Descriptor; }
}
+ internal CustomOptions CustomOptions{ get; private set; } = CustomOptions.Empty;
+
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FileOptions() {
OnConstruction();
@@ -2798,11 +3174,14 @@ namespace Google.Protobuf.Reflection {
ccGenericServices_ = other.ccGenericServices_;
javaGenericServices_ = other.javaGenericServices_;
pyGenericServices_ = other.pyGenericServices_;
+ phpGenericServices_ = other.phpGenericServices_;
deprecated_ = other.deprecated_;
ccEnableArenas_ = other.ccEnableArenas_;
objcClassPrefix_ = other.objcClassPrefix_;
csharpNamespace_ = other.csharpNamespace_;
swiftPrefix_ = other.swiftPrefix_;
+ phpClassPrefix_ = other.phpClassPrefix_;
+ phpNamespace_ = other.phpNamespace_;
uninterpretedOption_ = other.uninterpretedOption_.Clone();
}
@@ -2973,6 +3352,17 @@ namespace Google.Protobuf.Reflection {
}
}
+ /// <summary>Field number for the "php_generic_services" field.</summary>
+ public const int PhpGenericServicesFieldNumber = 42;
+ private bool phpGenericServices_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool PhpGenericServices {
+ get { return phpGenericServices_; }
+ set {
+ phpGenericServices_ = value;
+ }
+ }
+
/// <summary>Field number for the "deprecated" field.</summary>
public const int DeprecatedFieldNumber = 23;
private bool deprecated_;
@@ -3051,13 +3441,45 @@ namespace Google.Protobuf.Reflection {
}
}
+ /// <summary>Field number for the "php_class_prefix" field.</summary>
+ public const int PhpClassPrefixFieldNumber = 40;
+ private string phpClassPrefix_ = "";
+ /// <summary>
+ /// Sets the php class prefix which is prepended to all php generated classes
+ /// from this .proto. Default is empty.
+ /// </summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public string PhpClassPrefix {
+ get { return phpClassPrefix_; }
+ set {
+ phpClassPrefix_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
+ }
+ }
+
+ /// <summary>Field number for the "php_namespace" field.</summary>
+ public const int PhpNamespaceFieldNumber = 41;
+ private string phpNamespace_ = "";
+ /// <summary>
+ /// Use this option to change the namespace of php generated classes. Default
+ /// is empty. When this option is empty, the package name will be used for
+ /// determining the namespace.
+ /// </summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public string PhpNamespace {
+ get { return phpNamespace_; }
+ set {
+ phpNamespace_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
+ }
+ }
+
/// <summary>Field number for the "uninterpreted_option" field.</summary>
public const int UninterpretedOptionFieldNumber = 999;
private static readonly pb::FieldCodec<global::Google.Protobuf.Reflection.UninterpretedOption> _repeated_uninterpretedOption_codec
= pb::FieldCodec.ForMessage(7994, global::Google.Protobuf.Reflection.UninterpretedOption.Parser);
private readonly pbc::RepeatedField<global::Google.Protobuf.Reflection.UninterpretedOption> uninterpretedOption_ = new pbc::RepeatedField<global::Google.Protobuf.Reflection.UninterpretedOption>();
/// <summary>
- /// The parser stores options it doesn't recognize here. See above.
+ /// The parser stores options it doesn't recognize here.
+ /// See the documentation for the "Options" section above.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Protobuf.Reflection.UninterpretedOption> UninterpretedOption {
@@ -3087,11 +3509,14 @@ namespace Google.Protobuf.Reflection {
if (CcGenericServices != other.CcGenericServices) return false;
if (JavaGenericServices != other.JavaGenericServices) return false;
if (PyGenericServices != other.PyGenericServices) return false;
+ if (PhpGenericServices != other.PhpGenericServices) return false;
if (Deprecated != other.Deprecated) return false;
if (CcEnableArenas != other.CcEnableArenas) return false;
if (ObjcClassPrefix != other.ObjcClassPrefix) return false;
if (CsharpNamespace != other.CsharpNamespace) return false;
if (SwiftPrefix != other.SwiftPrefix) return false;
+ if (PhpClassPrefix != other.PhpClassPrefix) return false;
+ if (PhpNamespace != other.PhpNamespace) return false;
if(!uninterpretedOption_.Equals(other.uninterpretedOption_)) return false;
return true;
}
@@ -3109,11 +3534,14 @@ namespace Google.Protobuf.Reflection {
if (CcGenericServices != false) hash ^= CcGenericServices.GetHashCode();
if (JavaGenericServices != false) hash ^= JavaGenericServices.GetHashCode();
if (PyGenericServices != false) hash ^= PyGenericServices.GetHashCode();
+ if (PhpGenericServices != false) hash ^= PhpGenericServices.GetHashCode();
if (Deprecated != false) hash ^= Deprecated.GetHashCode();
if (CcEnableArenas != false) hash ^= CcEnableArenas.GetHashCode();
if (ObjcClassPrefix.Length != 0) hash ^= ObjcClassPrefix.GetHashCode();
if (CsharpNamespace.Length != 0) hash ^= CsharpNamespace.GetHashCode();
if (SwiftPrefix.Length != 0) hash ^= SwiftPrefix.GetHashCode();
+ if (PhpClassPrefix.Length != 0) hash ^= PhpClassPrefix.GetHashCode();
+ if (PhpNamespace.Length != 0) hash ^= PhpNamespace.GetHashCode();
hash ^= uninterpretedOption_.GetHashCode();
return hash;
}
@@ -3185,6 +3613,18 @@ namespace Google.Protobuf.Reflection {
output.WriteRawTag(186, 2);
output.WriteString(SwiftPrefix);
}
+ if (PhpClassPrefix.Length != 0) {
+ output.WriteRawTag(194, 2);
+ output.WriteString(PhpClassPrefix);
+ }
+ if (PhpNamespace.Length != 0) {
+ output.WriteRawTag(202, 2);
+ output.WriteString(PhpNamespace);
+ }
+ if (PhpGenericServices != false) {
+ output.WriteRawTag(208, 2);
+ output.WriteBool(PhpGenericServices);
+ }
uninterpretedOption_.WriteTo(output, _repeated_uninterpretedOption_codec);
}
@@ -3221,6 +3661,9 @@ namespace Google.Protobuf.Reflection {
if (PyGenericServices != false) {
size += 2 + 1;
}
+ if (PhpGenericServices != false) {
+ size += 2 + 1;
+ }
if (Deprecated != false) {
size += 2 + 1;
}
@@ -3236,6 +3679,12 @@ namespace Google.Protobuf.Reflection {
if (SwiftPrefix.Length != 0) {
size += 2 + pb::CodedOutputStream.ComputeStringSize(SwiftPrefix);
}
+ if (PhpClassPrefix.Length != 0) {
+ size += 2 + pb::CodedOutputStream.ComputeStringSize(PhpClassPrefix);
+ }
+ if (PhpNamespace.Length != 0) {
+ size += 2 + pb::CodedOutputStream.ComputeStringSize(PhpNamespace);
+ }
size += uninterpretedOption_.CalculateSize(_repeated_uninterpretedOption_codec);
return size;
}
@@ -3275,6 +3724,9 @@ namespace Google.Protobuf.Reflection {
if (other.PyGenericServices != false) {
PyGenericServices = other.PyGenericServices;
}
+ if (other.PhpGenericServices != false) {
+ PhpGenericServices = other.PhpGenericServices;
+ }
if (other.Deprecated != false) {
Deprecated = other.Deprecated;
}
@@ -3290,6 +3742,12 @@ namespace Google.Protobuf.Reflection {
if (other.SwiftPrefix.Length != 0) {
SwiftPrefix = other.SwiftPrefix;
}
+ if (other.PhpClassPrefix.Length != 0) {
+ PhpClassPrefix = other.PhpClassPrefix;
+ }
+ if (other.PhpNamespace.Length != 0) {
+ PhpNamespace = other.PhpNamespace;
+ }
uninterpretedOption_.Add(other.uninterpretedOption_);
}
@@ -3299,7 +3757,7 @@ namespace Google.Protobuf.Reflection {
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- input.SkipLastField();
+ CustomOptions = CustomOptions.ReadOrSkipUnknownField(input);
break;
case 10: {
JavaPackage = input.ReadString();
@@ -3361,6 +3819,18 @@ namespace Google.Protobuf.Reflection {
SwiftPrefix = input.ReadString();
break;
}
+ case 322: {
+ PhpClassPrefix = input.ReadString();
+ break;
+ }
+ case 330: {
+ PhpNamespace = input.ReadString();
+ break;
+ }
+ case 336: {
+ PhpGenericServices = input.ReadBool();
+ break;
+ }
case 7994: {
uninterpretedOption_.AddEntriesFrom(input, _repeated_uninterpretedOption_codec);
break;
@@ -3403,7 +3873,7 @@ namespace Google.Protobuf.Reflection {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[10]; }
+ get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[11]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -3411,6 +3881,8 @@ namespace Google.Protobuf.Reflection {
get { return Descriptor; }
}
+ internal CustomOptions CustomOptions{ get; private set; } = CustomOptions.Empty;
+
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public MessageOptions() {
OnConstruction();
@@ -3646,7 +4118,7 @@ namespace Google.Protobuf.Reflection {
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- input.SkipLastField();
+ CustomOptions = CustomOptions.ReadOrSkipUnknownField(input);
break;
case 8: {
MessageSetWireFormat = input.ReadBool();
@@ -3681,7 +4153,7 @@ namespace Google.Protobuf.Reflection {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[11]; }
+ get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[12]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -3689,6 +4161,8 @@ namespace Google.Protobuf.Reflection {
get { return Descriptor; }
}
+ internal CustomOptions CustomOptions{ get; private set; } = CustomOptions.Empty;
+
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FieldOptions() {
OnConstruction();
@@ -3753,13 +4227,15 @@ namespace Google.Protobuf.Reflection {
/// <summary>
/// The jstype option determines the JavaScript type used for values of the
/// field. The option is permitted only for 64 bit integral and fixed types
- /// (int64, uint64, sint64, fixed64, sfixed64). By default these types are
- /// represented as JavaScript strings. This avoids loss of precision that can
- /// happen when a large value is converted to a floating point JavaScript
- /// numbers. Specifying JS_NUMBER for the jstype causes the generated
- /// JavaScript code to use the JavaScript "number" type instead of strings.
- /// This option is an enum to permit additional types to be added,
- /// e.g. goog.math.Integer.
+ /// (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING
+ /// is represented as JavaScript string, which avoids loss of precision that
+ /// can happen when a large value is converted to a floating point JavaScript.
+ /// Specifying JS_NUMBER for the jstype causes the generated JavaScript code to
+ /// use the JavaScript "number" type. The behavior of the default option
+ /// JS_NORMAL is implementation dependent.
+ ///
+ /// This option is an enum to permit additional types to be added, e.g.
+ /// goog.math.Integer.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.Reflection.FieldOptions.Types.JSType Jstype {
@@ -3980,7 +4456,7 @@ namespace Google.Protobuf.Reflection {
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- input.SkipLastField();
+ CustomOptions = CustomOptions.ReadOrSkipUnknownField(input);
break;
case 8: {
ctype_ = (global::Google.Protobuf.Reflection.FieldOptions.Types.CType) input.ReadEnum();
@@ -4054,7 +4530,7 @@ namespace Google.Protobuf.Reflection {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[12]; }
+ get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[13]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -4062,6 +4538,8 @@ namespace Google.Protobuf.Reflection {
get { return Descriptor; }
}
+ internal CustomOptions CustomOptions{ get; private set; } = CustomOptions.Empty;
+
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public OneofOptions() {
OnConstruction();
@@ -4147,7 +4625,7 @@ namespace Google.Protobuf.Reflection {
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- input.SkipLastField();
+ CustomOptions = CustomOptions.ReadOrSkipUnknownField(input);
break;
case 7994: {
uninterpretedOption_.AddEntriesFrom(input, _repeated_uninterpretedOption_codec);
@@ -4166,7 +4644,7 @@ namespace Google.Protobuf.Reflection {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[13]; }
+ get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[14]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -4174,6 +4652,8 @@ namespace Google.Protobuf.Reflection {
get { return Descriptor; }
}
+ internal CustomOptions CustomOptions{ get; private set; } = CustomOptions.Empty;
+
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public EnumOptions() {
OnConstruction();
@@ -4317,7 +4797,7 @@ namespace Google.Protobuf.Reflection {
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- input.SkipLastField();
+ CustomOptions = CustomOptions.ReadOrSkipUnknownField(input);
break;
case 16: {
AllowAlias = input.ReadBool();
@@ -4344,7 +4824,7 @@ namespace Google.Protobuf.Reflection {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[14]; }
+ get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[15]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -4352,6 +4832,8 @@ namespace Google.Protobuf.Reflection {
get { return Descriptor; }
}
+ internal CustomOptions CustomOptions{ get; private set; } = CustomOptions.Empty;
+
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public EnumValueOptions() {
OnConstruction();
@@ -4467,7 +4949,7 @@ namespace Google.Protobuf.Reflection {
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- input.SkipLastField();
+ CustomOptions = CustomOptions.ReadOrSkipUnknownField(input);
break;
case 8: {
Deprecated = input.ReadBool();
@@ -4490,7 +4972,7 @@ namespace Google.Protobuf.Reflection {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[15]; }
+ get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[16]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -4498,6 +4980,8 @@ namespace Google.Protobuf.Reflection {
get { return Descriptor; }
}
+ internal CustomOptions CustomOptions{ get; private set; } = CustomOptions.Empty;
+
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ServiceOptions() {
OnConstruction();
@@ -4613,7 +5097,7 @@ namespace Google.Protobuf.Reflection {
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- input.SkipLastField();
+ CustomOptions = CustomOptions.ReadOrSkipUnknownField(input);
break;
case 264: {
Deprecated = input.ReadBool();
@@ -4636,7 +5120,7 @@ namespace Google.Protobuf.Reflection {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[16]; }
+ get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[17]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -4644,6 +5128,8 @@ namespace Google.Protobuf.Reflection {
get { return Descriptor; }
}
+ internal CustomOptions CustomOptions{ get; private set; } = CustomOptions.Empty;
+
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public MethodOptions() {
OnConstruction();
@@ -4783,7 +5269,7 @@ namespace Google.Protobuf.Reflection {
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- input.SkipLastField();
+ CustomOptions = CustomOptions.ReadOrSkipUnknownField(input);
break;
case 264: {
Deprecated = input.ReadBool();
@@ -4842,7 +5328,7 @@ namespace Google.Protobuf.Reflection {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[17]; }
+ get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[18]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -5286,7 +5772,7 @@ namespace Google.Protobuf.Reflection {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[18]; }
+ get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[19]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -5740,7 +6226,7 @@ namespace Google.Protobuf.Reflection {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
- get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[19]; }
+ get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[20]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
diff --git a/csharp/src/Google.Protobuf/Reflection/EnumDescriptor.cs b/csharp/src/Google.Protobuf/Reflection/EnumDescriptor.cs
index c732c93a..89c73a61 100644
--- a/csharp/src/Google.Protobuf/Reflection/EnumDescriptor.cs
+++ b/csharp/src/Google.Protobuf/Reflection/EnumDescriptor.cs
@@ -112,5 +112,10 @@ namespace Google.Protobuf.Reflection
{
return File.DescriptorPool.FindSymbol<EnumValueDescriptor>(FullName + "." + name);
}
+
+ /// <summary>
+ /// The (possibly empty) set of custom options for this enum.
+ /// </summary>
+ public CustomOptions CustomOptions => Proto.Options?.CustomOptions ?? CustomOptions.Empty;
}
} \ No newline at end of file
diff --git a/csharp/src/Google.Protobuf/Reflection/EnumValueDescriptor.cs b/csharp/src/Google.Protobuf/Reflection/EnumValueDescriptor.cs
index b212ce96..8b838c68 100644
--- a/csharp/src/Google.Protobuf/Reflection/EnumValueDescriptor.cs
+++ b/csharp/src/Google.Protobuf/Reflection/EnumValueDescriptor.cs
@@ -66,5 +66,10 @@ namespace Google.Protobuf.Reflection
/// Returns the enum descriptor that this value is part of.
/// </summary>
public EnumDescriptor EnumDescriptor { get { return enumDescriptor; } }
+
+ /// <summary>
+ /// The (possibly empty) set of custom options for this enum value.
+ /// </summary>
+ public CustomOptions CustomOptions => Proto.Options?.CustomOptions ?? CustomOptions.Empty;
}
} \ No newline at end of file
diff --git a/csharp/src/Google.Protobuf/Reflection/FieldDescriptor.cs b/csharp/src/Google.Protobuf/Reflection/FieldDescriptor.cs
index ed15d0e1..2a3d5c7a 100644
--- a/csharp/src/Google.Protobuf/Reflection/FieldDescriptor.cs
+++ b/csharp/src/Google.Protobuf/Reflection/FieldDescriptor.cs
@@ -251,6 +251,11 @@ namespace Google.Protobuf.Reflection
}
/// <summary>
+ /// The (possibly empty) set of custom options for this field.
+ /// </summary>
+ public CustomOptions CustomOptions => Proto.Options?.CustomOptions ?? CustomOptions.Empty;
+
+ /// <summary>
/// Look up and cross-link all field types etc.
/// </summary>
internal void CrossLink()
diff --git a/csharp/src/Google.Protobuf/Reflection/FileDescriptor.cs b/csharp/src/Google.Protobuf/Reflection/FileDescriptor.cs
index 94efea9e..9124beee 100644
--- a/csharp/src/Google.Protobuf/Reflection/FileDescriptor.cs
+++ b/csharp/src/Google.Protobuf/Reflection/FileDescriptor.cs
@@ -329,5 +329,10 @@ namespace Google.Protobuf.Reflection
/// The file descriptor for <c>descriptor.proto</c>.
/// </value>
public static FileDescriptor DescriptorProtoFileDescriptor { get { return DescriptorReflection.Descriptor; } }
+
+ /// <summary>
+ /// The (possibly empty) set of custom options for this file.
+ /// </summary>
+ public CustomOptions CustomOptions => Proto.Options?.CustomOptions ?? CustomOptions.Empty;
}
}
diff --git a/csharp/src/Google.Protobuf/Reflection/MessageDescriptor.cs b/csharp/src/Google.Protobuf/Reflection/MessageDescriptor.cs
index 7a1cb9d5..86942acc 100644..100755
--- a/csharp/src/Google.Protobuf/Reflection/MessageDescriptor.cs
+++ b/csharp/src/Google.Protobuf/Reflection/MessageDescriptor.cs
@@ -34,7 +34,7 @@ using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
-#if DOTNET35
+#if NET35
// Needed for ReadOnlyDictionary, which does not exist in .NET 3.5
using Google.Protobuf.Collections;
#endif
@@ -221,6 +221,11 @@ namespace Google.Protobuf.Reflection
File.DescriptorPool.FindSymbol<T>(FullName + "." + name);
/// <summary>
+ /// The (possibly empty) set of custom options for this message.
+ /// </summary>
+ public CustomOptions CustomOptions => Proto.Options?.CustomOptions ?? CustomOptions.Empty;
+
+ /// <summary>
/// Looks up and cross-links all fields and nested types.
/// </summary>
internal void CrossLink()
diff --git a/csharp/src/Google.Protobuf/Reflection/MethodDescriptor.cs b/csharp/src/Google.Protobuf/Reflection/MethodDescriptor.cs
index f9539f6c..19d7f8a0 100644
--- a/csharp/src/Google.Protobuf/Reflection/MethodDescriptor.cs
+++ b/csharp/src/Google.Protobuf/Reflection/MethodDescriptor.cs
@@ -67,6 +67,11 @@ namespace Google.Protobuf.Reflection
/// </value>
public bool IsServerStreaming { get { return proto.ServerStreaming; } }
+ /// <summary>
+ /// The (possibly empty) set of custom options for this method.
+ /// </summary>
+ public CustomOptions CustomOptions => Proto.Options?.CustomOptions ?? CustomOptions.Empty;
+
internal MethodDescriptor(MethodDescriptorProto proto, FileDescriptor file,
ServiceDescriptor parent, int index)
: base(file, parent.FullName + "." + proto.Name, index)
diff --git a/csharp/src/Google.Protobuf/Reflection/OneofDescriptor.cs b/csharp/src/Google.Protobuf/Reflection/OneofDescriptor.cs
index 22020acf..5906c2e3 100644
--- a/csharp/src/Google.Protobuf/Reflection/OneofDescriptor.cs
+++ b/csharp/src/Google.Protobuf/Reflection/OneofDescriptor.cs
@@ -90,6 +90,11 @@ namespace Google.Protobuf.Reflection
/// </value>
public OneofAccessor Accessor { get { return accessor; } }
+ /// <summary>
+ /// The (possibly empty) set of custom options for this oneof.
+ /// </summary>
+ public CustomOptions CustomOptions => proto.Options?.CustomOptions ?? CustomOptions.Empty;
+
internal void CrossLink()
{
List<FieldDescriptor> fieldCollection = new List<FieldDescriptor>();
diff --git a/csharp/src/Google.Protobuf/Reflection/OriginalNameAttribute.cs b/csharp/src/Google.Protobuf/Reflection/OriginalNameAttribute.cs
index 27f9ab98..07d0fd99 100644
--- a/csharp/src/Google.Protobuf/Reflection/OriginalNameAttribute.cs
+++ b/csharp/src/Google.Protobuf/Reflection/OriginalNameAttribute.cs
@@ -47,12 +47,19 @@ namespace Google.Protobuf.Reflection
public string Name { get; set; }
/// <summary>
+ /// If the name is preferred in the .proto file.
+ /// </summary>
+ public bool PreferredAlias { get; set; }
+
+ /// <summary>
/// Constructs a new attribute instance for the given name.
/// </summary>
/// <param name="name">The name of the element in the .proto file.</param>
public OriginalNameAttribute(string name)
{
Name = ProtoPreconditions.CheckNotNull(name, nameof(name));
+ PreferredAlias = true;
}
+
}
-} \ No newline at end of file
+}
diff --git a/csharp/src/Google.Protobuf/Reflection/ServiceDescriptor.cs b/csharp/src/Google.Protobuf/Reflection/ServiceDescriptor.cs
index cc0a5010..fe5c072c 100644
--- a/csharp/src/Google.Protobuf/Reflection/ServiceDescriptor.cs
+++ b/csharp/src/Google.Protobuf/Reflection/ServiceDescriptor.cs
@@ -78,6 +78,11 @@ namespace Google.Protobuf.Reflection
return File.DescriptorPool.FindSymbol<MethodDescriptor>(FullName + "." + name);
}
+ /// <summary>
+ /// The (possibly empty) set of custom options for this service.
+ /// </summary>
+ public CustomOptions CustomOptions => Proto.Options?.CustomOptions ?? CustomOptions.Empty;
+
internal void CrossLink()
{
foreach (MethodDescriptor method in methods)
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/Any.cs b/csharp/src/Google.Protobuf/WellKnownTypes/Any.cs
index b90c9a2a..5b39b809 100644
--- a/csharp/src/Google.Protobuf/WellKnownTypes/Any.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/Any.cs
@@ -73,6 +73,16 @@ namespace Google.Protobuf.WellKnownTypes {
/// any.Unpack(foo)
/// ...
///
+ /// Example 4: Pack and unpack a message in Go
+ ///
+ /// foo := &amp;pb.Foo{...}
+ /// any, err := ptypes.MarshalAny(foo)
+ /// ...
+ /// foo := &amp;pb.Foo{}
+ /// if err := ptypes.UnmarshalAny(any, foo); err != nil {
+ /// ...
+ /// }
+ ///
/// The pack methods provided by protobuf library will by default use
/// 'type.googleapis.com/full.type.name' as the type URL and the unpack
/// methods only use the fully qualified type name after the last '/'
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/AnyPartial.cs b/csharp/src/Google.Protobuf/WellKnownTypes/AnyPartial.cs
index f4fac738..fca689dc 100644
--- a/csharp/src/Google.Protobuf/WellKnownTypes/AnyPartial.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/AnyPartial.cs
@@ -44,17 +44,25 @@ namespace Google.Protobuf.WellKnownTypes
prefix.EndsWith("/") ? prefix + descriptor.FullName : prefix + "/" + descriptor.FullName;
/// <summary>
- /// Retrieves the type name for a type URL. This is always just the last part of the URL,
- /// after the trailing slash. No validation of anything before the trailing slash is performed.
- /// If the type URL does not include a slash, an empty string is returned rather than an exception
- /// being thrown; this won't match any types, and the calling code is probably in a better position
- /// to give a meaningful error.
- /// There is no handling of fragments or queries at the moment.
+ /// Retrieves the type name for a type URL, matching the <see cref="DescriptorBase.FullName"/>
+ /// of the packed message type.
/// </summary>
+ /// <remarks>
+ /// <para>
+ /// This is always just the last part of the URL, after the final slash. No validation of
+ /// anything before the trailing slash is performed. If the type URL does not include a slash,
+ /// an empty string is returned rather than an exception being thrown; this won't match any types,
+ /// and the calling code is probably in a better position to give a meaningful error.
+ /// </para>
+ /// <para>
+ /// There is no handling of fragments or queries at the moment.
+ /// </para>
+ /// </remarks>
/// <param name="typeUrl">The URL to extract the type name from</param>
/// <returns>The type name</returns>
- internal static string GetTypeName(string typeUrl)
+ public static string GetTypeName(string typeUrl)
{
+ ProtoPreconditions.CheckNotNull(typeUrl, nameof(typeUrl));
int lastSlash = typeUrl.LastIndexOf('/');
return lastSlash == -1 ? "" : typeUrl.Substring(lastSlash + 1);
}
@@ -81,6 +89,27 @@ namespace Google.Protobuf.WellKnownTypes
}
/// <summary>
+ /// Attempts to unpack the content of this Any message into the target message type,
+ /// if it matches the type URL within this Any message.
+ /// </summary>
+ /// <typeparam name="T">The type of message to attempt to unpack the content into.</typeparam>
+ /// <returns><c>true</c> if the message was successfully unpacked; <c>false</c> if the type name didn't match</returns>
+ public bool TryUnpack<T>(out T result) where T : IMessage, new()
+ {
+ // Note: deliberately avoid writing anything to result until the end, in case it's being
+ // monitored by other threads. (That would be a bug in the calling code, but let's not make it worse.)
+ T target = new T();
+ if (GetTypeName(TypeUrl) != target.Descriptor.FullName)
+ {
+ result = default(T); // Can't use null as there's no class constraint, but this always *will* be null in real usage.
+ return false;
+ }
+ target.MergeFrom(Value);
+ result = target;
+ return true;
+ }
+
+ /// <summary>
/// Packs the specified message into an Any message using a type URL prefix of "type.googleapis.com".
/// </summary>
/// <param name="message">The message to pack.</param>
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/Api.cs b/csharp/src/Google.Protobuf/WellKnownTypes/Api.cs
index aeeb8e73..6705e092 100644
--- a/csharp/src/Google.Protobuf/WellKnownTypes/Api.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/Api.cs
@@ -52,7 +52,15 @@ namespace Google.Protobuf.WellKnownTypes {
}
#region Messages
/// <summary>
- /// Api is a light-weight descriptor for a protocol buffer service.
+ /// Api is a light-weight descriptor for an API Interface.
+ ///
+ /// Interfaces are also described as "protocol buffer services" in some contexts,
+ /// such as by the "service" keyword in a .proto file, but they are different
+ /// from API Services, which represent a concrete implementation of an interface
+ /// as opposed to simply a description of methods and bindings. They are also
+ /// sometimes simply referred to as "APIs" in other contexts, such as the name of
+ /// this message itself. See https://cloud.google.com/apis/design/glossary for
+ /// detailed terminology.
/// </summary>
public sealed partial class Api : pb::IMessage<Api> {
private static readonly pb::MessageParser<Api> _parser = new pb::MessageParser<Api>(() => new Api());
@@ -96,8 +104,8 @@ namespace Google.Protobuf.WellKnownTypes {
public const int NameFieldNumber = 1;
private string name_ = "";
/// <summary>
- /// The fully qualified name of this api, including package name
- /// followed by the api's simple name.
+ /// The fully qualified name of this interface, including package name
+ /// followed by the interface's simple name.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
@@ -113,7 +121,7 @@ namespace Google.Protobuf.WellKnownTypes {
= pb::FieldCodec.ForMessage(18, global::Google.Protobuf.WellKnownTypes.Method.Parser);
private readonly pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Method> methods_ = new pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Method>();
/// <summary>
- /// The methods of this api, in unspecified order.
+ /// The methods of this interface, in unspecified order.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Method> Methods {
@@ -126,7 +134,7 @@ namespace Google.Protobuf.WellKnownTypes {
= pb::FieldCodec.ForMessage(26, global::Google.Protobuf.WellKnownTypes.Option.Parser);
private readonly pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Option> options_ = new pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Option>();
/// <summary>
- /// Any metadata attached to the API.
+ /// Any metadata attached to the interface.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Option> Options {
@@ -137,13 +145,12 @@ namespace Google.Protobuf.WellKnownTypes {
public const int VersionFieldNumber = 4;
private string version_ = "";
/// <summary>
- /// A version string for this api. If specified, must have the form
- /// `major-version.minor-version`, as in `1.10`. If the minor version
- /// is omitted, it defaults to zero. If the entire version field is
- /// empty, the major version is derived from the package name, as
- /// outlined below. If the field is not empty, the version in the
- /// package name will be verified to be consistent with what is
- /// provided here.
+ /// A version string for this interface. If specified, must have the form
+ /// `major-version.minor-version`, as in `1.10`. If the minor version is
+ /// omitted, it defaults to zero. If the entire version field is empty, the
+ /// major version is derived from the package name, as outlined below. If the
+ /// field is not empty, the version in the package name will be verified to be
+ /// consistent with what is provided here.
///
/// The versioning schema uses [semantic
/// versioning](http://semver.org) where the major version number
@@ -153,10 +160,10 @@ namespace Google.Protobuf.WellKnownTypes {
/// chosen based on the product plan.
///
/// The major version is also reflected in the package name of the
- /// API, which must end in `v&lt;major-version>`, as in
+ /// interface, which must end in `v&lt;major-version>`, as in
/// `google.feature.v1`. For major versions 0 and 1, the suffix can
/// be omitted. Zero major versions must only be used for
- /// experimental, none-GA apis.
+ /// experimental, non-GA interfaces.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Version {
@@ -187,7 +194,7 @@ namespace Google.Protobuf.WellKnownTypes {
= pb::FieldCodec.ForMessage(50, global::Google.Protobuf.WellKnownTypes.Mixin.Parser);
private readonly pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Mixin> mixins_ = new pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Mixin>();
/// <summary>
- /// Included APIs. See [Mixin][].
+ /// Included interfaces. See [Mixin][].
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Mixin> Mixins {
@@ -364,7 +371,7 @@ namespace Google.Protobuf.WellKnownTypes {
}
/// <summary>
- /// Method represents a method of an api.
+ /// Method represents a method of an API interface.
/// </summary>
public sealed partial class Method : pb::IMessage<Method> {
private static readonly pb::MessageParser<Method> _parser = new pb::MessageParser<Method>(() => new Method());
@@ -665,9 +672,9 @@ namespace Google.Protobuf.WellKnownTypes {
}
/// <summary>
- /// Declares an API to be included in this API. The including API must
- /// redeclare all the methods from the included API, but documentation
- /// and options are inherited as follows:
+ /// Declares an API Interface to be included in this interface. The including
+ /// interface must redeclare all the methods from the included interface, but
+ /// documentation and options are inherited as follows:
///
/// - If after comment and whitespace stripping, the documentation
/// string of the redeclared method is empty, it will be inherited
@@ -679,7 +686,8 @@ namespace Google.Protobuf.WellKnownTypes {
///
/// - If an http annotation is inherited, the path pattern will be
/// modified as follows. Any version prefix will be replaced by the
- /// version of the including API plus the [root][] path if specified.
+ /// version of the including interface plus the [root][] path if
+ /// specified.
///
/// Example of a simple mixin:
///
@@ -780,7 +788,7 @@ namespace Google.Protobuf.WellKnownTypes {
public const int NameFieldNumber = 1;
private string name_ = "";
/// <summary>
- /// The fully qualified name of the API which is included.
+ /// The fully qualified name of the interface which is included.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/Duration.cs b/csharp/src/Google.Protobuf/WellKnownTypes/Duration.cs
index 03b19c77..94159cb8 100644
--- a/csharp/src/Google.Protobuf/WellKnownTypes/Duration.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/Duration.cs
@@ -46,6 +46,8 @@ namespace Google.Protobuf.WellKnownTypes {
/// two Timestamp values is a Duration and it can be added or subtracted
/// from a Timestamp. Range is approximately +-10,000 years.
///
+ /// # Examples
+ ///
/// Example 1: Compute Duration from two Timestamps in pseudo code.
///
/// Timestamp start = ...;
@@ -85,6 +87,16 @@ namespace Google.Protobuf.WellKnownTypes {
/// td = datetime.timedelta(days=3, minutes=10)
/// duration = Duration()
/// duration.FromTimedelta(td)
+ ///
+ /// # JSON Mapping
+ ///
+ /// In JSON format, the Duration type is encoded as a string rather than an
+ /// object, where the string ends in the suffix "s" (indicating seconds) and
+ /// is preceded by the number of seconds, with nanoseconds expressed as
+ /// fractional seconds. For example, 3 seconds with 0 nanoseconds should be
+ /// encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should
+ /// be expressed in JSON format as "3.000000001s", and 3 seconds and 1
+ /// microsecond should be expressed in JSON format as "3.000001s".
/// </summary>
public sealed partial class Duration : pb::IMessage<Duration> {
private static readonly pb::MessageParser<Duration> _parser = new pb::MessageParser<Duration>(() => new Duration());
@@ -124,7 +136,8 @@ namespace Google.Protobuf.WellKnownTypes {
private long seconds_;
/// <summary>
/// Signed seconds of the span of time. Must be from -315,576,000,000
- /// to +315,576,000,000 inclusive.
+ /// to +315,576,000,000 inclusive. Note: these bounds are computed from:
+ /// 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long Seconds {
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/FieldMask.cs b/csharp/src/Google.Protobuf/WellKnownTypes/FieldMask.cs
index ef3bc10a..ee4561ff 100644
--- a/csharp/src/Google.Protobuf/WellKnownTypes/FieldMask.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/FieldMask.cs
@@ -239,6 +239,12 @@ namespace Google.Protobuf.WellKnownTypes {
///
/// Note that oneof type names ("test_oneof" in this case) cannot be used in
/// paths.
+ ///
+ /// ## Field Mask Verification
+ ///
+ /// The implementation of the all the API methods, which have any FieldMask type
+ /// field in the request, should verify the included field paths, and return
+ /// `INVALID_ARGUMENT` error if any path is duplicated or unmappable.
/// </summary>
public sealed partial class FieldMask : pb::IMessage<FieldMask> {
private static readonly pb::MessageParser<FieldMask> _parser = new pb::MessageParser<FieldMask>(() => new FieldMask());
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/FieldMaskPartial.cs b/csharp/src/Google.Protobuf/WellKnownTypes/FieldMaskPartial.cs
index 0685c21a..4b0670f6 100644..100755
--- a/csharp/src/Google.Protobuf/WellKnownTypes/FieldMaskPartial.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/FieldMaskPartial.cs
@@ -59,7 +59,7 @@ namespace Google.Protobuf.WellKnownTypes
if (firstInvalid == null)
{
var writer = new StringWriter();
-#if DOTNET35
+#if NET35
var query = paths.Select(JsonFormatter.ToJsonName);
JsonFormatter.WriteString(writer, string.Join(",", query.ToArray()));
#else
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/Struct.cs b/csharp/src/Google.Protobuf/WellKnownTypes/Struct.cs
index 1fa35521..65119894 100644
--- a/csharp/src/Google.Protobuf/WellKnownTypes/Struct.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/Struct.cs
@@ -466,10 +466,16 @@ namespace Google.Protobuf.WellKnownTypes {
BoolValue = other.BoolValue;
break;
case KindOneofCase.StructValue:
- StructValue = other.StructValue;
+ if (StructValue == null) {
+ StructValue = new global::Google.Protobuf.WellKnownTypes.Struct();
+ }
+ StructValue.MergeFrom(other.StructValue);
break;
case KindOneofCase.ListValue:
- ListValue = other.ListValue;
+ if (ListValue == null) {
+ ListValue = new global::Google.Protobuf.WellKnownTypes.ListValue();
+ }
+ ListValue.MergeFrom(other.ListValue);
break;
}
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs b/csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs
index b789f6da..9f7ad73a 100644
--- a/csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs
@@ -51,6 +51,8 @@ namespace Google.Protobuf.WellKnownTypes {
/// and from RFC 3339 date strings.
/// See [https://www.ietf.org/rfc/rfc3339.txt](https://www.ietf.org/rfc/rfc3339.txt).
///
+ /// # Examples
+ ///
/// Example 1: Compute Timestamp from POSIX `time()`.
///
/// Timestamp timestamp;
@@ -89,6 +91,29 @@ namespace Google.Protobuf.WellKnownTypes {
///
/// timestamp = Timestamp()
/// timestamp.GetCurrentTime()
+ ///
+ /// # JSON Mapping
+ ///
+ /// In JSON format, the Timestamp type is encoded as a string in the
+ /// [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the
+ /// format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z"
+ /// where {year} is always expressed using four digits while {month}, {day},
+ /// {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional
+ /// seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution),
+ /// are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone
+ /// is required, though only UTC (as indicated by "Z") is presently supported.
+ ///
+ /// For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past
+ /// 01:30 UTC on January 15, 2017.
+ ///
+ /// In JavaScript, one can convert a Date object to this format using the
+ /// standard [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString]
+ /// method. In Python, a standard `datetime.datetime` object can be converted
+ /// to this format using [`strftime`](https://docs.python.org/2/library/time.html#time.strftime)
+ /// with the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one
+ /// can use the Joda Time's [`ISODateTimeFormat.dateTime()`](
+ /// http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime--)
+ /// to obtain a formatter capable of generating timestamps in this format.
/// </summary>
public sealed partial class Timestamp : pb::IMessage<Timestamp> {
private static readonly pb::MessageParser<Timestamp> _parser = new pb::MessageParser<Timestamp>(() => new Timestamp());
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/Type.cs b/csharp/src/Google.Protobuf/WellKnownTypes/Type.cs
index 9212ce81..7375b6cb 100644
--- a/csharp/src/Google.Protobuf/WellKnownTypes/Type.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/Type.cs
@@ -1311,7 +1311,10 @@ namespace Google.Protobuf.WellKnownTypes {
public const int NameFieldNumber = 1;
private string name_ = "";
/// <summary>
- /// The option's name. For example, `"java_package"`.
+ /// The option's name. For protobuf built-in options (options defined in
+ /// descriptor.proto), this is the short name. For example, `"map_entry"`.
+ /// For custom options, it should be the fully-qualified name. For example,
+ /// `"google.api.http"`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
@@ -1325,7 +1328,10 @@ namespace Google.Protobuf.WellKnownTypes {
public const int ValueFieldNumber = 2;
private global::Google.Protobuf.WellKnownTypes.Any value_;
/// <summary>
- /// The option's value. For example, `"com.google.protobuf"`.
+ /// The option's value packed in an Any message. If the value is a primitive,
+ /// the corresponding wrapper type defined in google/protobuf/wrappers.proto
+ /// should be used. If the value is an enum, it should be stored as an int32
+ /// value using the google.protobuf.Int32Value type.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Any Value {
diff --git a/csharp/src/Google.Protobuf/project.json b/csharp/src/Google.Protobuf/project.json
deleted file mode 100644
index 12e86248..00000000
--- a/csharp/src/Google.Protobuf/project.json
+++ /dev/null
@@ -1,65 +0,0 @@
-{
- "version": "3.1.0",
- "title": "Google Protocol Buffers",
- "description": "See project site for more info.",
- "authors": [ "Google Inc." ],
- "copyright": "Copyright 2015, Google Inc.",
-
- "packOptions": {
- "summary": "C# runtime library for Protocol Buffers - Google's data interchange format.",
- "tags": [ "Protocol", "Buffers", "Binary", "Serialization", "Format", "Google", "proto", "proto3" ],
- "owners": [ "protobuf-packages" ],
- "licenseUrl": "https://github.com/google/protobuf/blob/master/LICENSE",
- "projectUrl": "https://github.com/google/protobuf",
- "releaseNotes": "C# proto3 support",
- "requireLicenseAcceptance": false,
- "repository": {
- "url": "https://github.com/nodatime/nodatime.git"
- }
- },
-
- "buildOptions": {
- "debugType": "portable",
- "keyFile": "../../keys/Google.Protobuf.snk",
- "xmlDoc": true
- },
-
- "configurations": {
- "Debug": {
- "buildOptions": {
- "define": [ "DEBUG", "TRACE" ]
- }
- },
- "Release": {
- "buildOptions": {
- "define": [ "RELEASE", "TRACE" ],
- "optimize": true
- }
- }
- },
-
- "frameworks": {
- // This target allows the package to be installed in a .NET 4.5+
- // project without asking for myriad other dependencies.
- "net45": {
- },
- "netstandard1.0": {
- "dependencies": {
- "System.Collections": "4.0.11",
- "System.Diagnostics.Debug": "4.0.11",
- "System.Globalization": "4.0.11",
- "System.IO": "4.1.0",
- "System.Linq": "4.1.0",
- "System.Linq.Expressions": "4.1.0",
- "System.ObjectModel": "4.0.12",
- "System.Reflection": "4.1.0",
- "System.Reflection.Extensions": "4.0.1",
- "System.Runtime": "4.1.0",
- "System.Runtime.Extensions": "4.1.0",
- "System.Text.Encoding": "4.0.11",
- "System.Text.RegularExpressions": "4.1.0",
- "System.Threading": "4.0.11"
- }
- }
- }
-}
diff --git a/csharp/src/packages/repositories.config b/csharp/src/packages/repositories.config
deleted file mode 100644
index 70379412..00000000
--- a/csharp/src/packages/repositories.config
+++ /dev/null
@@ -1,4 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<repositories>
- <repository path="..\Google.Protobuf.Test\packages.config" />
-</repositories> \ No newline at end of file
diff --git a/docs/third_party.md b/docs/third_party.md
index 0bbde914..1a22e7f9 100644
--- a/docs/third_party.md
+++ b/docs/third_party.md
@@ -23,7 +23,7 @@ These are projects we know about implementing Protocol Buffers for other program
* C#: https://silentorbit.com/protobuf/
* C#/.NET/WCF/VB: http://code.google.com/p/protobuf-net/
* Clojure: http://github.com/ninjudd/clojure-protobuf
-* Common Lisp: http://www.prism.gatech.edu/~ndantam3/docs/s-protobuf/
+* Common Lisp: http://github.com/ndantam/s-protobuf
* Common Lisp: http://github.com/brown/protobuf
* D: https://github.com/msoucy/dproto
* D: http://256.makerslocal.org/wiki/index.php/ProtocolBuffer
@@ -32,15 +32,19 @@ These are projects we know about implementing Protocol Buffers for other program
* Delphi: http://sourceforge.net/projects/protobuf-delphi/
* Delphi: http://fundementals.sourceforge.net/dl.html
* Elixir: https://github.com/jeremyong/exprotoc
+* Elixir: https://github.com/tony612/protobuf-elixir
+* Elm: https://github.com/tiziano88/elm-protobuf
* Erlang: http://github.com/ngerakines/erlang_protobuffs/tree/master
* Erlang: http://piqi.org/
* Erlang: https://code.google.com/p/protoc-gen-erl/
* Erlang: https://github.com/basho/erlang_protobuffs
* Erlang: https://github.com/tomas-abrahamsson/gpb
* Go: https://github.com/golang/protobuf (Google-official implementation)
-* Go: http://code.google.com/p/goprotobuf/
* Go: https://github.com/akunspy/gopbuf
+* Go: https://github.com/gogo/protobuf
+* GopherJS: https://github.com/johanbrandhorst/protobuf
* Haskell: http://hackage.haskell.org/package/hprotoc
+* Haskell: https://github.com/google/proto-lens (Google-unofficial implementation)
* Haxe: https://github.com/Atry/protoc-gen-haxe
* Java: https://github.com/google/protobuf (Google-official implementation)
* Java/Android: https://github.com/square/wire
@@ -115,11 +119,18 @@ GRPC (http://www.grpc.io/) is Google's RPC implementation for Protocol Buffers.
* https://github.com/thesamet/rpcz (C++/Python, based on ZeroMQ)
* https://github.com/w359405949/libmaid (C++, Python)
* https://github.com/madwyn/libpbrpc (C++)
+* https://github.com/SeriousMa/grpc-protobuf-validation (Java)
+* https://github.com/tony612/grpc-elixir (Elixir)
+* https://github.com/johanbrandhorst/protobuf (GopherJS)
## Other Utilities
There are miscellaneous other things you may find useful as a Protocol Buffers developer.
+* [Bazel Build](https://bazel.build)
+ * [rules_closure](https://github.com/bazelbuild/rules_closure) `js-closure`
+ * [rules_go](https://github.com/bazelbuild/rules_go) `go`
+ * [rules_protobuf](https://github.com/pubref/rules_protobuf) `java` `c++` `c#` `go` `js-closure` `js-node` `python` `ruby`
* [NetBeans IDE plugin](http://code.google.com/p/protobuf-netbeans-plugin/)
* [Wireshark/Ethereal packet sniffer plugin](http://code.google.com/p/protobuf-wireshark/)
* [Alternate encodings (JSON, XML, HTML) for Java protobufs](http://code.google.com/p/protobuf-java-format/)
@@ -135,7 +146,7 @@ There are miscellaneous other things you may find useful as a Protocol Buffers d
* http://igor-petruk.github.com/protobuf-maven-plugin/
* http://code.google.com/p/maven-protoc-plugin/
* https://github.com/os72/protoc-jar-maven-plugin
-* [Documentation generator plugin (Markdown/HTML/DocBook/...)](https://github.com/estan/protoc-gen-doc)
+* [Documentation generator plugin (Markdown/HTML/DocBook/...)](https://github.com/pseudomuto/protoc-gen-doc)
* [DocBook generator for .proto files](http://code.google.com/p/protoc-gen-docbook/)
* [Protobuf for nginx module](https://github.com/dbcode/protobuf-nginx/)
* [RSpec matchers and Cucumber step defs for testing Protocol Buffers](https://github.com/connamara/protobuf_spec)
@@ -149,3 +160,6 @@ There are miscellaneous other things you may find useful as a Protocol Buffers d
* [Notepad++ Syntax Highlighting for .proto files](https://github.com/chai2010/notepadplus-protobuf)
* [Linter for .proto files](https://github.com/ckaznocha/protoc-gen-lint)
* [Protocol Buffers Dynamic Schema - create protobuf schemas programmatically (Java)] (https://github.com/os72/protobuf-dynamic)
+* [Make protoc plugins in NodeJS](https://github.com/konsumer/node-protoc-plugin)
+* [ProfaneDB - A Protocol Buffers database](https://profanedb.gitlab.io)
+* [Protocol Buffer property-based testing utility and example message generator (Python / Hypothesis)](https://github.com/CurataEng/hypothesis-protobuf)
diff --git a/editors/protobuf-mode.el b/editors/protobuf-mode.el
index 1cef4137..d3bdcded 100644
--- a/editors/protobuf-mode.el
+++ b/editors/protobuf-mode.el
@@ -64,9 +64,11 @@
;;; Code:
(require 'cc-mode)
-(require 'cl)
(eval-when-compile
+ (and (= emacs-major-version 24)
+ (>= emacs-minor-version 4)
+ (require 'cl))
(require 'cc-langs)
(require 'cc-fonts))
diff --git a/examples/BUILD b/examples/BUILD
new file mode 100644
index 00000000..d5d5d9a5
--- /dev/null
+++ b/examples/BUILD
@@ -0,0 +1,101 @@
+# This BUILD file shows how to use protobuf with bazel. Before you can use
+# proto_library/<lang>_proto_library rules in a BUILD file, you need to
+# include protobuf repo as remote repositories in your WORKSPACE file. See
+# the WORKSPACE file in the same directory with this BUILD file for an
+# example.
+
+# For each .proto file, a proto_library target should be defined. This target
+# is not bound to any particular language. Instead, it defines the dependency
+# graph of the .proto files (i.e., proto imports) and serves as the provider
+# of .proto source files to the protocol compiler.
+#
+# Remote repository "com_google_protobuf" must be defined to use this rule.
+proto_library(
+ name = "addressbook_proto",
+ srcs = ["addressbook.proto"],
+ deps = ["@com_google_protobuf//:timestamp_proto"],
+)
+
+# The cc_proto_library rule generates C++ code for a proto_library rule. It
+# must have exactly one proto_library dependency. If you want to use multiple
+# proto_library targets, create a separate cc_proto_library target for each
+# of them.
+#
+# Remote repository "com_google_protobuf_cc" must be defined to use this rule.
+cc_proto_library(
+ name = "addressbook_cc_proto",
+ deps = [":addressbook_proto"],
+)
+
+# cc_library/cc_binary targets can depend on cc_proto_library targets.
+cc_binary(
+ name = "add_person_cpp",
+ srcs = ["add_person.cc"],
+ deps = [":addressbook_cc_proto"],
+)
+
+cc_binary(
+ name = "list_people_cpp",
+ srcs = ["list_people.cc"],
+ deps = [":addressbook_cc_proto"],
+)
+
+# Similar to cc_proto_library but for Java.
+#
+# Remote repository "com_google_protobuf_java" must be defined to use this rule.
+java_proto_library(
+ name = "addressbook_java_proto",
+ deps = [":addressbook_proto"],
+)
+
+java_binary(
+ name = "add_person_java",
+ srcs = ["AddPerson.java"],
+ main_class = "AddPerson",
+ deps = [":addressbook_java_proto"],
+)
+
+java_binary(
+ name = "list_people_java",
+ srcs = ["ListPeople.java"],
+ main_class = "ListPeople",
+ deps = [":addressbook_java_proto"],
+)
+
+# Java lite.
+#
+# Remote repository "com_google_protobuf_javalite" must be defined to use this
+# rule.
+java_lite_proto_library(
+ name = "addressbook_java_lite_proto",
+ deps = [":addressbook_proto"],
+)
+
+# Java lite API is a subset of the regular Java API so if you only uses this
+# subset in your code, you can actually compile your code against both (i.e.,
+# share code between server build and Android build).
+#
+# The lite version has a smaller code size, and you can see that by comparing
+# the resulted .jar file:
+#
+# $ bazel build :add_person_java_deploy.jar :add_person_java_lite_deploy.jar
+# $ ls -l bazel-bin/*_deploy.jar
+# -r-xr-xr-x 1 xiaofeng eng 1230797 Sep 8 12:24 bazel-bin/add_person_java_deploy.jar
+# -r-xr-xr-x 1 xiaofeng eng 236166 Sep 8 12:24 bazel-bin/add_person_java_lite_deploy.jar
+#
+# In the above example, the lite .jar file is 6 times smaller. With proper
+# proguard inlining/stripping, the difference can be much more larger than
+# that.
+java_binary(
+ name = "add_person_java_lite",
+ srcs = ["AddPerson.java"],
+ main_class = "AddPerson",
+ deps = [":addressbook_java_lite_proto"],
+)
+
+java_binary(
+ name = "list_people_java_lite",
+ srcs = ["ListPeople.java"],
+ main_class = "ListPeople",
+ deps = [":addressbook_java_lite_proto"],
+)
diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt
index 2cd2acc0..3e8e6541 100644
--- a/examples/CMakeLists.txt
+++ b/examples/CMakeLists.txt
@@ -32,22 +32,6 @@ foreach(example add_person list_people)
if(protobuf_MODULE_COMPATIBLE) #Legacy Support
protobuf_generate_cpp(${example}_PROTO_SRCS ${example}_PROTO_HDRS ${${example}_PROTOS})
list(APPEND ${example}_SRCS ${${example}_PROTO_SRCS} ${${example}_PROTO_HDRS})
- else()
-
- foreach(proto_file ${${example}_PROTOS})
- get_filename_component(proto_file_abs ${proto_file} ABSOLUTE)
- get_filename_component(basename ${proto_file} NAME_WE)
- set(generated_files ${basename}.pb.cc ${basename}.pb.h)
- list(APPEND ${example}_SRCS ${generated_files})
-
- add_custom_command(
- OUTPUT ${generated_files}
- COMMAND protobuf::protoc
- ARGS --cpp_out ${CMAKE_CURRENT_BINARY_DIR} -I ${CMAKE_CURRENT_SOURCE_DIR} ${proto_file_abs}
- COMMENT "Generating ${generated_files} from ${proto_file}"
- VERBATIM
- )
- endforeach()
endif()
#Executable setup
@@ -58,6 +42,7 @@ foreach(example add_person list_people)
target_link_libraries(${executable_name} ${PROTOBUF_LIBRARIES})
else()
target_link_libraries(${executable_name} protobuf::libprotobuf)
+ protobuf_generate(TARGET ${executable_name})
endif()
endforeach()
diff --git a/examples/ListPeople.java b/examples/ListPeople.java
index 78924305..580f7ac2 100644
--- a/examples/ListPeople.java
+++ b/examples/ListPeople.java
@@ -27,6 +27,9 @@ class ListPeople {
case WORK:
System.out.print(" Work phone #: ");
break;
+ default:
+ System.out.println(" Unknown phone #: ");
+ break;
}
System.out.println(phoneNumber.getNumber());
}
diff --git a/examples/Makefile b/examples/Makefile
index 51f13426..1ff7fa7f 100644
--- a/examples/Makefile
+++ b/examples/Makefile
@@ -22,12 +22,12 @@ clean:
rmdir com 2>/dev/null || true
protoc_middleman: addressbook.proto
- protoc --cpp_out=. --java_out=. --python_out=. addressbook.proto
+ protoc $$PROTO_PATH --cpp_out=. --java_out=. --python_out=. addressbook.proto
@touch protoc_middleman
protoc_middleman_go: addressbook.proto
- mkdir tutorial # make directory for go package
- protoc --go_out=tutorial addressbook.proto
+ mkdir -p tutorial # make directory for go package
+ protoc $$PROTO_PATH --go_out=tutorial addressbook.proto
@touch protoc_middleman_go
add_person_cpp: add_person.cc protoc_middleman
@@ -51,7 +51,7 @@ list_people_gotest: list_people.go list_people_go
go test list_people.go list_people_test.go
javac_middleman: AddPerson.java ListPeople.java protoc_middleman
- javac AddPerson.java ListPeople.java com/example/tutorial/AddressBookProtos.java
+ javac -cp $$CLASSPATH AddPerson.java ListPeople.java com/example/tutorial/AddressBookProtos.java
@touch javac_middleman
add_person_java: javac_middleman
diff --git a/examples/README.md b/examples/README.md
new file mode 100644
index 00000000..20f285cd
--- /dev/null
+++ b/examples/README.md
@@ -0,0 +1,124 @@
+# Protocol Buffers - Code Example
+
+This directory contains example code that uses Protocol Buffers to manage an
+address book. Two programs are provided for each supported language. The
+add_person example adds a new person to an address book, prompting the user to
+input the person's information. The list_people example lists people already in
+the address book. The examples use the exact same format in all three languages,
+so you can, for example, use add_person_java to create an address book and then
+use list_people_python to read it.
+
+These examples are part of the Protocol Buffers tutorial, located at:
+ https://developers.google.com/protocol-buffers/docs/tutorials
+
+## Build the example using bazel
+
+The example requires bazel 0.5.4 or newer to build. You can download/install
+the latest version of bazel from bazel's release page:
+
+ https://github.com/bazelbuild/bazel/releases
+
+Once you have bazel installed, simply run the following command in this examples
+directory to build the code:
+
+ $ bazel build :all
+
+Then you can run the built binary:
+
+ $ bazel-bin/add_person_cpp addressbook.data
+
+To use protobuf in your own bazel project, please follow instructions in the
+[BUILD](BUILD) file and [WORKSPACE](WORKSPACE) file.
+
+## Build the example using make
+
+You must install the protobuf package before you can build it using make. The
+minimum requirement is to install protocol compiler (i.e., the protoc binary)
+and the protobuf runtime for the language you want to build.
+
+You can simply run "make" to build the example for all languages (except for
+Go). However, since different language has different installation requirement,
+it will likely fail. It's better to follow individual instrutions below to
+build only the language you are interested in.
+
+### C++
+
+You can follow instructions in [../src/README.md](../src/README.md) to install
+protoc and protobuf C++ runtime from source.
+
+Then run "make cpp" in this examples directory to build the C++ example. It
+will create two executables: add_person_cpp and list_people_cpp. These programs
+simply take an address book file as their parameter. The add_person_cpp
+programs will create the file if it doesn't already exist.
+
+To run the examples:
+
+ $ ./add_person_cpp addressbook.data
+ $ ./list_people_cpp addressbook.data
+
+Note that on some platforms you may have to edit the Makefile and remove
+"-lpthread" from the linker commands (perhaps replacing it with something else).
+We didn't do this automatically because we wanted to keep the example simple.
+
+### Python
+
+Follow instructions in [../README.md](../README.md) to install protoc and then
+follow [../python/README.md](../python/README.md) to install protobuf python
+runtime from source. You can also install python runtime using pip:
+
+ $ pip install protobuf
+
+Make sure the runtime version is the same as protoc binary, or it may not work.
+
+After you have install both protoc and python runtime, run "make python" to
+build two executables (shell scripts actually): add_person_python and
+list_people_python. They work the same way as the C++ executables.
+
+### Java
+
+Follow instructions in [../README.md](../README.md) to install protoc and then
+download protobuf Java runtime .jar file from maven:
+
+ https://mvnrepository.com/artifact/com.google.protobuf/protobuf-java
+
+Then run the following:
+
+ $ export CLASSPATH=/path/to/protobuf-java-[version].jar
+ $ make java
+
+This will create the add_person_java/list_people_java executables (shell
+scripts) and can be used to create/display an address book data file.
+
+### Go
+
+The Go example requires a plugin to the protocol buffer compiler, so it is not
+build with all the other examples. See:
+
+ https://github.com/golang/protobuf
+
+for more information about Go protocol buffer support.
+
+First, install the Protocol Buffers compiler (protoc).
+
+Then, install the Go Protocol Buffers plugin ($GOPATH/bin must be in your $PATH
+for protoc to find it):
+
+ go get github.com/golang/protobuf/protoc-gen-go
+
+Build the Go samples in this directory with "make go". This creates the
+following executable files in the current directory:
+
+ add_person_go list_people_go
+
+To run the example:
+
+ ./add_person_go addressbook.data
+
+to add a person to the protocol buffer encoded file addressbook.data. The file
+is created if it does not exist. To view the data, run:
+
+ ./list_people_go addressbook.data
+
+Observe that the C++, Python, and Java examples in this directory run in a
+similar way and can view/modify files created by the Go example and vice
+versa.
diff --git a/examples/README.txt b/examples/README.txt
deleted file mode 100644
index b33f8414..00000000
--- a/examples/README.txt
+++ /dev/null
@@ -1,54 +0,0 @@
-This directory contains example code that uses Protocol Buffers to manage an
-address book. Two programs are provided, each with three different
-implementations, one written in each of C++, Java, and Python. The add_person
-example adds a new person to an address book, prompting the user to input
-the person's information. The list_people example lists people already in the
-address book. The examples use the exact same format in all three languages,
-so you can, for example, use add_person_java to create an address book and then
-use list_people_python to read it.
-
-You must install the protobuf package before you can build these.
-
-To build all the examples (on a unix-like system), simply run "make". This
-creates the following executable files in the current directory:
- add_person_cpp list_people_cpp
- add_person_java list_people_java
- add_person_python list_people_python
-
-If you only want to compile examples in one language, use "make cpp"*,
-"make java", or "make python".
-
-All of these programs simply take an address book file as their parameter.
-The add_person programs will create the file if it doesn't already exist.
-
-These examples are part of the Protocol Buffers tutorial, located at:
- https://developers.google.com/protocol-buffers/docs/tutorials
-
-* Note that on some platforms you may have to edit the Makefile and remove
-"-lpthread" from the linker commands (perhaps replacing it with something else).
-We didn't do this automatically because we wanted to keep the example simple.
-
-## Go ##
-
-The Go example requires a plugin to the protocol buffer compiler, so it is not
-build with all the other examples. See:
- https://github.com/golang/protobuf
-for more information about Go protocol buffer support.
-
-First, install the Protocol Buffers compiler (protoc).
-Then, install the Go Protocol Buffers plugin
-($GOPATH/bin must be in your $PATH for protoc to find it):
- go get github.com/golang/protobuf/protoc-gen-go
-
-Build the Go samples in this directory with "make go". This creates the
-following executable files in the current directory:
- add_person_go list_people_go
-To run the example:
- ./add_person_go addressbook.data
-to add a person to the protocol buffer encoded file addressbook.data. The file
-is created if it does not exist. To view the data, run:
- ./list_people_go addressbook.data
-
-Observe that the C++, Python, and Java examples in this directory run in a
-similar way and can view/modify files created by the Go example and vice
-versa.
diff --git a/examples/WORKSPACE b/examples/WORKSPACE
new file mode 100644
index 00000000..bb003107
--- /dev/null
+++ b/examples/WORKSPACE
@@ -0,0 +1,33 @@
+# This com_google_protobuf repository is required for proto_library rule.
+# It provides the protocol compiler binary (i.e., protoc).
+http_archive(
+ name = "com_google_protobuf",
+ strip_prefix = "protobuf-master",
+ urls = ["https://github.com/google/protobuf/archive/master.zip"],
+)
+
+# This com_google_protobuf_cc repository is required for cc_proto_library
+# rule. It provides protobuf C++ runtime. Note that it actually is the same
+# repo as com_google_protobuf but has to be given a different name as
+# required by bazel.
+http_archive(
+ name = "com_google_protobuf_cc",
+ strip_prefix = "protobuf-master",
+ urls = ["https://github.com/google/protobuf/archive/master.zip"],
+)
+
+# Similar to com_google_protobuf_cc but for Java (i.e., java_proto_library).
+http_archive(
+ name = "com_google_protobuf_java",
+ strip_prefix = "protobuf-master",
+ urls = ["https://github.com/google/protobuf/archive/master.zip"],
+)
+
+# Similar to com_google_protobuf_cc but for Java lite. If you are building
+# for Android, the lite version should be prefered because it has a much
+# smaller code size.
+http_archive(
+ name = "com_google_protobuf_javalite",
+ strip_prefix = "protobuf-javalite",
+ urls = ["https://github.com/google/protobuf/archive/javalite.zip"],
+)
diff --git a/examples/add_person.cc b/examples/add_person.cc
index 9bec4b37..856e90bb 100644
--- a/examples/add_person.cc
+++ b/examples/add_person.cc
@@ -1,11 +1,17 @@
// See README.txt for information and build instructions.
-#include <iostream>
+#include <ctime>
#include <fstream>
+#include <google/protobuf/util/time_util.h>
+#include <iostream>
#include <string>
+
#include "addressbook.pb.h"
+
using namespace std;
+using google::protobuf::util::TimeUtil;
+
// This function fills in a Person message based on user input.
void PromptForAddress(tutorial::Person* person) {
cout << "Enter person ID number: ";
@@ -48,6 +54,7 @@ void PromptForAddress(tutorial::Person* person) {
cout << "Unknown phone type. Using default." << endl;
}
}
+ *person->mutable_last_updated() = TimeUtil::SecondsToTimestamp(time(NULL));
}
// Main function: Reads the entire address book from a file,
diff --git a/examples/add_person.py b/examples/add_person.py
index 0b698579..aa0fbca7 100755
--- a/examples/add_person.py
+++ b/examples/add_person.py
@@ -5,6 +5,12 @@
import addressbook_pb2
import sys
+try:
+ raw_input # Python 2
+except NameError:
+ raw_input = input # Python 3
+
+
# This function fills in a Person message based on user input.
def PromptForAddress(person):
person.id = int(raw_input("Enter person ID number: "))
@@ -30,13 +36,14 @@ def PromptForAddress(person):
elif type == "work":
phone_number.type = addressbook_pb2.Person.WORK
else:
- print "Unknown phone type; leaving as default value."
+ print("Unknown phone type; leaving as default value.")
+
# Main procedure: Reads the entire address book from a file,
# adds one person based on user input, then writes it back out to the same
# file.
if len(sys.argv) != 2:
- print "Usage:", sys.argv[0], "ADDRESS_BOOK_FILE"
+ print("Usage:", sys.argv[0], "ADDRESS_BOOK_FILE")
sys.exit(-1)
address_book = addressbook_pb2.AddressBook()
@@ -46,7 +53,7 @@ try:
with open(sys.argv[1], "rb") as f:
address_book.ParseFromString(f.read())
except IOError:
- print sys.argv[1] + ": File not found. Creating a new file."
+ print(sys.argv[1] + ": File not found. Creating a new file.")
# Add an address.
PromptForAddress(address_book.people.add())
diff --git a/examples/addressbook.proto b/examples/addressbook.proto
index 23cc2f97..b4b33b4c 100644
--- a/examples/addressbook.proto
+++ b/examples/addressbook.proto
@@ -9,6 +9,8 @@
// [START declaration]
syntax = "proto3";
package tutorial;
+
+import "google/protobuf/timestamp.proto";
// [END declaration]
// [START java_declaration]
@@ -38,6 +40,8 @@ message Person {
}
repeated PhoneNumber phones = 4;
+
+ google.protobuf.Timestamp last_updated = 5;
}
// Our address book file is just one of these.
diff --git a/examples/list_people.cc b/examples/list_people.cc
index 68e5666d..b309c596 100644
--- a/examples/list_people.cc
+++ b/examples/list_people.cc
@@ -1,11 +1,16 @@
// See README.txt for information and build instructions.
-#include <iostream>
#include <fstream>
+#include <google/protobuf/util/time_util.h>
+#include <iostream>
#include <string>
+
#include "addressbook.pb.h"
+
using namespace std;
+using google::protobuf::util::TimeUtil;
+
// Iterates though all people in the AddressBook and prints info about them.
void ListPeople(const tutorial::AddressBook& address_book) {
for (int i = 0; i < address_book.people_size(); i++) {
@@ -30,9 +35,15 @@ void ListPeople(const tutorial::AddressBook& address_book) {
case tutorial::Person::WORK:
cout << " Work phone #: ";
break;
+ default:
+ cout << " Unknown phone #: ";
+ break;
}
cout << phone_number.number() << endl;
}
+ if (person.has_last_updated()) {
+ cout << " Updated: " << TimeUtil::ToString(person.last_updated()) << endl;
+ }
}
}
diff --git a/examples/list_people.py b/examples/list_people.py
index f131872d..d2c294c6 100755
--- a/examples/list_people.py
+++ b/examples/list_people.py
@@ -2,30 +2,33 @@
# See README.txt for information and build instructions.
+from __future__ import print_function
import addressbook_pb2
import sys
+
# Iterates though all people in the AddressBook and prints info about them.
def ListPeople(address_book):
for person in address_book.people:
- print "Person ID:", person.id
- print " Name:", person.name
+ print("Person ID:", person.id)
+ print(" Name:", person.name)
if person.email != "":
- print " E-mail address:", person.email
+ print(" E-mail address:", person.email)
for phone_number in person.phones:
if phone_number.type == addressbook_pb2.Person.MOBILE:
- print " Mobile phone #:",
+ print(" Mobile phone #:", end=" ")
elif phone_number.type == addressbook_pb2.Person.HOME:
- print " Home phone #:",
+ print(" Home phone #:", end=" ")
elif phone_number.type == addressbook_pb2.Person.WORK:
- print " Work phone #:",
- print phone_number.number
+ print(" Work phone #:", end=" ")
+ print(phone_number.number)
+
# Main procedure: Reads the entire address book from a file and prints all
# the information inside.
if len(sys.argv) != 2:
- print "Usage:", sys.argv[0], "ADDRESS_BOOK_FILE"
+ print("Usage:", sys.argv[0], "ADDRESS_BOOK_FILE")
sys.exit(-1)
address_book = addressbook_pb2.AddressBook()
diff --git a/generate_descriptor_proto.sh b/generate_descriptor_proto.sh
index 668e6d13..8a5ed48a 100755
--- a/generate_descriptor_proto.sh
+++ b/generate_descriptor_proto.sh
@@ -41,8 +41,24 @@ declare -a RUNTIME_PROTO_FILES=(\
google/protobuf/type.proto \
google/protobuf/wrappers.proto)
+declare -a COMPILER_PROTO_FILES=(\
+ google/protobuf/compiler/plugin.proto)
+
CORE_PROTO_IS_CORRECT=0
PROCESS_ROUND=1
+BOOTSTRAP_PROTOC=""
+while [ $# -gt 0 ]; do
+ case $1 in
+ --bootstrap_protoc)
+ BOOTSTRAP_PROTOC=$2
+ shift
+ ;;
+ *)
+ break
+ ;;
+ esac
+ shift
+done
TMP=$(mktemp -d)
echo "Updating descriptor protos..."
while [ $CORE_PROTO_IS_CORRECT -ne 1 ]
@@ -50,16 +66,22 @@ do
echo "Round $PROCESS_ROUND"
CORE_PROTO_IS_CORRECT=1
- make $@ protoc
- if test $? -ne 0; then
- echo "Failed to build protoc."
- exit 1
+ if [ "$BOOTSTRAP_PROTOC" != "" ]; then
+ PROTOC=$BOOTSTRAP_PROTOC
+ BOOTSTRAP_PROTOC=""
+ else
+ make $@ protoc
+ if test $? -ne 0; then
+ echo "Failed to build protoc."
+ exit 1
+ fi
+ PROTOC="./protoc"
fi
- ./protoc --cpp_out=dllexport_decl=LIBPROTOBUF_EXPORT:$TMP ${RUNTIME_PROTO_FILES[@]} && \
- ./protoc --cpp_out=dllexport_decl=LIBPROTOC_EXPORT:$TMP google/protobuf/compiler/plugin.proto
+ $PROTOC --cpp_out=dllexport_decl=LIBPROTOBUF_EXPORT:$TMP ${RUNTIME_PROTO_FILES[@]} && \
+ $PROTOC --cpp_out=dllexport_decl=LIBPROTOC_EXPORT:$TMP ${COMPILER_PROTO_FILES[@]}
- for PROTO_FILE in ${RUNTIME_PROTO_FILES[@]}; do
+ for PROTO_FILE in ${RUNTIME_PROTO_FILES[@]} ${COMPILER_PROTO_FILES[@]}; do
BASE_NAME=${PROTO_FILE%.*}
diff ${BASE_NAME}.pb.h $TMP/${BASE_NAME}.pb.h > /dev/null
if test $? -ne 0; then
@@ -71,24 +93,14 @@ do
fi
done
- diff google/protobuf/compiler/plugin.pb.h $TMP/google/protobuf/compiler/plugin.pb.h > /dev/null
- if test $? -ne 0; then
- CORE_PROTO_IS_CORRECT=0
- fi
- diff google/protobuf/compiler/plugin.pb.cc $TMP/google/protobuf/compiler/plugin.pb.cc > /dev/null
- if test $? -ne 0; then
- CORE_PROTO_IS_CORRECT=0
- fi
-
# Only override the output if the files are different to avoid re-compilation
# of the protoc.
if [ $CORE_PROTO_IS_CORRECT -ne 1 ]; then
- for PROTO_FILE in ${RUNTIME_PROTO_FILES[@]}; do
+ for PROTO_FILE in ${RUNTIME_PROTO_FILES[@]} ${COMPILER_PROTO_FILES[@]}; do
BASE_NAME=${PROTO_FILE%.*}
mv $TMP/${BASE_NAME}.pb.h ${BASE_NAME}.pb.h
mv $TMP/${BASE_NAME}.pb.cc ${BASE_NAME}.pb.cc
done
- mv $TMP/google/protobuf/compiler/plugin.pb.* google/protobuf/compiler/
fi
PROCESS_ROUND=$((PROCESS_ROUND + 1))
@@ -104,3 +116,8 @@ if test -x csharp/generate_protos.sh; then
echo "Generating messages for C#."
csharp/generate_protos.sh $@
fi
+
+if test -x php/generate_descriptor_protos.sh; then
+ echo "Generating messages for PHP."
+ php/generate_descriptor_protos.sh $@
+fi
diff --git a/java/core/generate-test-sources-build.xml b/java/core/generate-test-sources-build.xml
index ab415db6..abcdf5dd 100644
--- a/java/core/generate-test-sources-build.xml
+++ b/java/core/generate-test-sources-build.xml
@@ -5,6 +5,7 @@
<arg value="--proto_path=${protobuf.source.dir}"/>
<arg value="--proto_path=${test.proto.dir}"/>
<arg value="${protobuf.source.dir}/google/protobuf/unittest.proto"/>
+ <arg value="${protobuf.source.dir}/google/protobuf/unittest_proto3.proto"/>
<arg value="${protobuf.source.dir}/google/protobuf/unittest_import.proto"/>
<arg value="${protobuf.source.dir}/google/protobuf/unittest_import_public.proto"/>
<arg value="${protobuf.source.dir}/google/protobuf/unittest_mset.proto"/>
@@ -18,6 +19,7 @@
<arg value="${protobuf.source.dir}/google/protobuf/unittest_enormous_descriptor.proto"/>
<arg value="${protobuf.source.dir}/google/protobuf/unittest_no_generic_services.proto"/>
<arg value="${protobuf.source.dir}/google/protobuf/unittest_well_known_types.proto"/>
+ <arg value="${test.proto.dir}/com/google/protobuf/deprecated_file.proto"/>
<arg value="${test.proto.dir}/com/google/protobuf/lazy_fields_lite.proto"/>
<arg value="${test.proto.dir}/com/google/protobuf/lite_equals_and_hash.proto"/>
<arg value="${test.proto.dir}/com/google/protobuf/multiple_files_test.proto"/>
@@ -40,4 +42,4 @@
<arg value="${test.proto.dir}/com/google/protobuf/map_test.proto"/>
<arg value="${test.proto.dir}/com/google/protobuf/map_initialization_order_test.proto"/>
</exec>
-</project> \ No newline at end of file
+</project>
diff --git a/java/core/pom.xml b/java/core/pom.xml
index cced344e..b0925f74 100644
--- a/java/core/pom.xml
+++ b/java/core/pom.xml
@@ -6,7 +6,7 @@
<parent>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-parent</artifactId>
- <version>3.1.0</version>
+ <version>3.4.1</version>
</parent>
<artifactId>protobuf-java</artifactId>
@@ -22,14 +22,17 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
+ <scope>test</scope>
</dependency>
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymock</artifactId>
+ <scope>test</scope>
</dependency>
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymockclassextension</artifactId>
+ <scope>test</scope>
</dependency>
</dependencies>
diff --git a/java/core/src/main/java/com/google/protobuf/AbstractMessage.java b/java/core/src/main/java/com/google/protobuf/AbstractMessage.java
index 7639efcf..908764df 100644
--- a/java/core/src/main/java/com/google/protobuf/AbstractMessage.java
+++ b/java/core/src/main/java/com/google/protobuf/AbstractMessage.java
@@ -32,9 +32,9 @@ package com.google.protobuf;
import com.google.protobuf.Descriptors.EnumValueDescriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
+import com.google.protobuf.Descriptors.FileDescriptor.Syntax;
import com.google.protobuf.Descriptors.OneofDescriptor;
import com.google.protobuf.Internal.EnumLite;
-
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
@@ -163,7 +163,7 @@ public abstract class AbstractMessage
}
return hash;
}
-
+
private static ByteString toByteString(Object value) {
if (value instanceof byte[]) {
return ByteString.copyFrom((byte[]) value);
@@ -171,7 +171,7 @@ public abstract class AbstractMessage
return (ByteString) value;
}
}
-
+
/**
* Compares two bytes fields. The parameters must be either a byte array or a
* ByteString object. They can be of different type though.
@@ -182,7 +182,7 @@ public abstract class AbstractMessage
}
return toByteString(a).equals(toByteString(b));
}
-
+
/**
* Converts a list of MapEntry messages into a Map used for equals() and
* hashCode().
@@ -213,7 +213,7 @@ public abstract class AbstractMessage
}
return result;
}
-
+
/**
* Compares two map fields. The parameters must be a list of MapEntry
* messages.
@@ -224,13 +224,13 @@ public abstract class AbstractMessage
Map mb = convertMapEntryListToMap((List) b);
return MapFieldLite.equals(ma, mb);
}
-
+
/**
* Compares two set of fields.
* This method is used to implement {@link AbstractMessage#equals(Object)}
* and {@link AbstractMutableMessage#equals(Object)}. It takes special care
* of bytes fields because immutable messages and mutable messages use
- * different Java type to reprensent a bytes field and this method should be
+ * different Java type to represent a bytes field and this method should be
* able to compare immutable messages, mutable messages and also an immutable
* message to a mutable message.
*/
@@ -276,7 +276,7 @@ public abstract class AbstractMessage
}
return true;
}
-
+
/**
* Calculates the hash code of a map field. {@code value} must be a list of
* MapEntry messages.
@@ -328,8 +328,12 @@ public abstract class AbstractMessage
extends AbstractMessageLite.Builder
implements Message.Builder {
// The compiler produces an error if this is not declared explicitly.
+ // Method isn't abstract to bypass Java 1.6 compiler issue:
+ // http://bugs.java.com/view_bug.do?bug_id=6908259
@Override
- public abstract BuilderType clone();
+ public BuilderType clone() {
+ throw new UnsupportedOperationException("clone() should be implemented in subclasses.");
+ }
/** TODO(jieluo): Clear it when all subclasses have implemented this method. */
@Override
@@ -368,7 +372,7 @@ public abstract class AbstractMessage
public String getInitializationErrorString() {
return MessageReflection.delimitWithCommas(findInitializationErrors());
}
-
+
@Override
protected BuilderType internalMergeFrom(AbstractMessageLite other) {
return mergeFrom((Message) other);
@@ -376,6 +380,10 @@ public abstract class AbstractMessage
@Override
public BuilderType mergeFrom(final Message other) {
+ return mergeFrom(other, other.getAllFields());
+ }
+
+ BuilderType mergeFrom(final Message other, Map<FieldDescriptor, Object> allFields) {
if (other.getDescriptorForType() != getDescriptorForType()) {
throw new IllegalArgumentException(
"mergeFrom(Message) can only merge messages of the same type.");
@@ -390,8 +398,7 @@ public abstract class AbstractMessage
// TODO(kenton): Provide a function somewhere called makeDeepCopy()
// which allows people to make secure deep copies of messages.
- for (final Map.Entry<FieldDescriptor, Object> entry :
- other.getAllFields().entrySet()) {
+ for (final Map.Entry<FieldDescriptor, Object> entry : allFields.entrySet()) {
final FieldDescriptor field = entry.getKey();
if (field.isRepeated()) {
for (final Object element : (List)entry.getValue()) {
@@ -429,8 +436,12 @@ public abstract class AbstractMessage
final CodedInputStream input,
final ExtensionRegistryLite extensionRegistry)
throws IOException {
+ boolean discardUnknown =
+ getDescriptorForType().getFile().getSyntax() == Syntax.PROTO3
+ ? input.shouldDiscardUnknownFieldsProto3()
+ : input.shouldDiscardUnknownFields();
final UnknownFieldSet.Builder unknownFields =
- UnknownFieldSet.newBuilder(getUnknownFields());
+ discardUnknown ? null : UnknownFieldSet.newBuilder(getUnknownFields());
while (true) {
final int tag = input.readTag();
if (tag == 0) {
@@ -448,7 +459,9 @@ public abstract class AbstractMessage
break;
}
}
- setUnknownFields(unknownFields.build());
+ if (unknownFields != null) {
+ setUnknownFields(unknownFields.build());
+ }
return (BuilderType) this;
}
diff --git a/java/core/src/main/java/com/google/protobuf/AbstractMessageLite.java b/java/core/src/main/java/com/google/protobuf/AbstractMessageLite.java
index 046030f3..24830c0a 100644
--- a/java/core/src/main/java/com/google/protobuf/AbstractMessageLite.java
+++ b/java/core/src/main/java/com/google/protobuf/AbstractMessageLite.java
@@ -30,11 +30,15 @@
package com.google.protobuf;
+import static com.google.protobuf.Internal.checkNotNull;
+
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
+import java.util.ArrayList;
import java.util.Collection;
+import java.util.List;
/**
* A partial implementation of the {@link MessageLite} interface which
@@ -48,7 +52,6 @@ public abstract class AbstractMessageLite<
BuilderType extends AbstractMessageLite.Builder<MessageType, BuilderType>>
implements MessageLite {
protected int memoizedHashCode = 0;
-
@Override
public ByteString toByteString() {
try {
@@ -117,8 +120,13 @@ public abstract class AbstractMessageLite<
}
}
- protected static <T> void addAll(final Iterable<T> values,
- final Collection<? super T> list) {
+ // For binary compatibility
+ @Deprecated
+ protected static <T> void addAll(final Iterable<T> values, final Collection<? super T> list) {
+ Builder.addAll(values, (List) list);
+ }
+
+ protected static <T> void addAll(final Iterable<T> values, final List<? super T> list) {
Builder.addAll(values, list);
}
@@ -333,6 +341,25 @@ public abstract class AbstractMessageLite<
+ " threw an IOException (should never happen).";
}
+ // We check nulls as we iterate to avoid iterating over values twice.
+ private static <T> void addAllCheckingNulls(Iterable<T> values, List<? super T> list) {
+ if (list instanceof ArrayList && values instanceof Collection) {
+ ((ArrayList<T>) list).ensureCapacity(list.size() + ((Collection<T>) values).size());
+ }
+ int begin = list.size();
+ for (T value : values) {
+ if (value == null) {
+ // encountered a null value so we must undo our modifications prior to throwing
+ String message = "Element at index " + (list.size() - begin) + " is null.";
+ for (int i = list.size() - 1; i >= begin; i--) {
+ list.remove(i);
+ }
+ throw new NullPointerException(message);
+ }
+ list.add(value);
+ }
+ }
+
/**
* Construct an UninitializedMessageException reporting missing fields in
* the given message.
@@ -342,41 +369,50 @@ public abstract class AbstractMessageLite<
return new UninitializedMessageException(message);
}
+ // For binary compatibility.
+ @Deprecated
+ protected static <T> void addAll(final Iterable<T> values, final Collection<? super T> list) {
+ addAll(values, (List<T>) list);
+ }
+
/**
- * Adds the {@code values} to the {@code list}. This is a helper method
- * used by generated code. Users should ignore it.
+ * Adds the {@code values} to the {@code list}. This is a helper method used by generated code.
+ * Users should ignore it.
*
- * @throws NullPointerException if {@code values} or any of the elements of
- * {@code values} is null. When that happens, some elements of
- * {@code values} may have already been added to the result {@code list}.
+ * @throws NullPointerException if {@code values} or any of the elements of {@code values} is
+ * null.
*/
- protected static <T> void addAll(final Iterable<T> values,
- final Collection<? super T> list) {
- if (values == null) {
- throw new NullPointerException();
- }
+ protected static <T> void addAll(final Iterable<T> values, final List<? super T> list) {
+ checkNotNull(values);
if (values instanceof LazyStringList) {
// For StringOrByteStringLists, check the underlying elements to avoid
// forcing conversions of ByteStrings to Strings.
- checkForNullValues(((LazyStringList) values).getUnderlyingElements());
- list.addAll((Collection<T>) values);
- } else if (values instanceof Collection) {
- checkForNullValues(values);
- list.addAll((Collection<T>) values);
- } else {
- for (final T value : values) {
+ // TODO(dweis): Could we just prohibit nulls in all protobuf lists and get rid of this? Is
+ // if even possible to hit this condition as all protobuf methods check for null first,
+ // right?
+ List<?> lazyValues = ((LazyStringList) values).getUnderlyingElements();
+ LazyStringList lazyList = (LazyStringList) list;
+ int begin = list.size();
+ for (Object value : lazyValues) {
if (value == null) {
- throw new NullPointerException();
+ // encountered a null value so we must undo our modifications prior to throwing
+ String message = "Element at index " + (lazyList.size() - begin) + " is null.";
+ for (int i = lazyList.size() - 1; i >= begin; i--) {
+ lazyList.remove(i);
+ }
+ throw new NullPointerException(message);
+ }
+ if (value instanceof ByteString) {
+ lazyList.add((ByteString) value);
+ } else {
+ lazyList.add((String) value);
}
- list.add(value);
}
- }
- }
-
- private static void checkForNullValues(final Iterable<?> values) {
- for (final Object value : values) {
- if (value == null) {
- throw new NullPointerException();
+ } else {
+ if (values instanceof PrimitiveNonBoxingCollection) {
+ list.addAll((Collection<T>) values);
+ } else {
+ addAllCheckingNulls(values, list);
}
}
}
diff --git a/java/core/src/main/java/com/google/protobuf/AbstractParser.java b/java/core/src/main/java/com/google/protobuf/AbstractParser.java
index 7ff73ba4..ba570e3d 100644
--- a/java/core/src/main/java/com/google/protobuf/AbstractParser.java
+++ b/java/core/src/main/java/com/google/protobuf/AbstractParser.java
@@ -31,9 +31,9 @@
package com.google.protobuf;
import com.google.protobuf.AbstractMessageLite.Builder.LimitedInputStream;
-
import java.io.IOException;
import java.io.InputStream;
+import java.nio.ByteBuffer;
/**
* A partial implementation of the {@link Parser} interface which implements
@@ -131,6 +131,30 @@ public abstract class AbstractParser<MessageType extends MessageLite>
}
@Override
+ public MessageType parseFrom(ByteBuffer data, ExtensionRegistryLite extensionRegistry)
+ throws InvalidProtocolBufferException {
+ MessageType message;
+ try {
+ CodedInputStream input = CodedInputStream.newInstance(data);
+ message = parsePartialFrom(input, extensionRegistry);
+ try {
+ input.checkLastTagWas(0);
+ } catch (InvalidProtocolBufferException e) {
+ throw e.setUnfinishedMessage(message);
+ }
+ } catch (InvalidProtocolBufferException e) {
+ throw e;
+ }
+
+ return checkMessageInitialized(message);
+ }
+
+ @Override
+ public MessageType parseFrom(ByteBuffer data) throws InvalidProtocolBufferException {
+ return parseFrom(data, EMPTY_REGISTRY);
+ }
+
+ @Override
public MessageType parsePartialFrom(
byte[] data, int off, int len, ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException {
diff --git a/java/core/src/main/java/com/google/protobuf/BooleanArrayList.java b/java/core/src/main/java/com/google/protobuf/BooleanArrayList.java
index 0d9f87ba..fd4c142b 100644
--- a/java/core/src/main/java/com/google/protobuf/BooleanArrayList.java
+++ b/java/core/src/main/java/com/google/protobuf/BooleanArrayList.java
@@ -30,8 +30,9 @@
package com.google.protobuf;
-import com.google.protobuf.Internal.BooleanList;
+import static com.google.protobuf.Internal.checkNotNull;
+import com.google.protobuf.Internal.BooleanList;
import java.util.Arrays;
import java.util.Collection;
import java.util.RandomAccess;
@@ -41,9 +42,8 @@ import java.util.RandomAccess;
*
* @author dweis@google.com (Daniel Weis)
*/
-final class BooleanArrayList
- extends AbstractProtobufList<Boolean>
- implements BooleanList, RandomAccess {
+final class BooleanArrayList extends AbstractProtobufList<Boolean>
+ implements BooleanList, RandomAccess, PrimitiveNonBoxingCollection {
private static final BooleanArrayList EMPTY_LIST = new BooleanArrayList();
static {
@@ -198,9 +198,7 @@ final class BooleanArrayList
public boolean addAll(Collection<? extends Boolean> collection) {
ensureIsMutable();
- if (collection == null) {
- throw new NullPointerException();
- }
+ checkNotNull(collection);
// We specialize when adding another BooleanArrayList to avoid boxing elements.
if (!(collection instanceof BooleanArrayList)) {
diff --git a/java/core/src/main/java/com/google/protobuf/CodedInputStream.java b/java/core/src/main/java/com/google/protobuf/CodedInputStream.java
index 14169dc4..e08a993b 100644
--- a/java/core/src/main/java/com/google/protobuf/CodedInputStream.java
+++ b/java/core/src/main/java/com/google/protobuf/CodedInputStream.java
@@ -34,8 +34,8 @@ import static com.google.protobuf.Internal.EMPTY_BYTE_ARRAY;
import static com.google.protobuf.Internal.EMPTY_BYTE_BUFFER;
import static com.google.protobuf.Internal.UTF_8;
import static com.google.protobuf.Internal.checkNotNull;
-import static com.google.protobuf.WireFormat.FIXED_32_SIZE;
-import static com.google.protobuf.WireFormat.FIXED_64_SIZE;
+import static com.google.protobuf.WireFormat.FIXED32_SIZE;
+import static com.google.protobuf.WireFormat.FIXED64_SIZE;
import static com.google.protobuf.WireFormat.MAX_VARINT_SIZE;
import java.io.ByteArrayOutputStream;
@@ -44,6 +44,7 @@ import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Iterator;
import java.util.List;
/**
@@ -85,6 +86,43 @@ public abstract class CodedInputStream {
return new StreamDecoder(input, bufferSize);
}
+ /** Create a new CodedInputStream wrapping the given {@code Iterable <ByteBuffer>}. */
+ public static CodedInputStream newInstance(final Iterable<ByteBuffer> input) {
+ if (!UnsafeDirectNioDecoder.isSupported()) {
+ return newInstance(new IterableByteBufferInputStream(input));
+ }
+ return newInstance(input, false);
+ }
+
+ /** Create a new CodedInputStream wrapping the given {@code Iterable <ByteBuffer>}. */
+ static CodedInputStream newInstance(
+ final Iterable<ByteBuffer> bufs, final boolean bufferIsImmutable) {
+ // flag is to check the type of input's ByteBuffers.
+ // flag equals 1: all ByteBuffers have array.
+ // flag equals 2: all ByteBuffers are direct ByteBuffers.
+ // flag equals 3: some ByteBuffers are direct and some have array.
+ // flag greater than 3: other cases.
+ int flag = 0;
+ // Total size of the input
+ int totalSize = 0;
+ for (ByteBuffer buf : bufs) {
+ totalSize += buf.remaining();
+ if (buf.hasArray()) {
+ flag |= 1;
+ } else if (buf.isDirect()) {
+ flag |= 2;
+ } else {
+ flag |= 4;
+ }
+ }
+ if (flag == 2) {
+ return new IterableDirectByteBufferDecoder(bufs, totalSize, bufferIsImmutable);
+ } else {
+ // TODO(yilunchong): add another decoders to deal case 1 and 3.
+ return newInstance(new IterableByteBufferInputStream(bufs));
+ }
+ }
+
/** Create a new CodedInputStream wrapping the given byte array. */
public static CodedInputStream newInstance(final byte[] buf) {
return newInstance(buf, 0, buf.length);
@@ -354,9 +392,9 @@ public abstract class CodedInputStream {
*
* <p>Set the maximum message size. In order to prevent malicious messages from exhausting memory
* or causing integer overflows, {@code CodedInputStream} limits how large a message may be. The
- * default limit is 64MB. You should set this limit as small as you can without harming your app's
- * functionality. Note that size limits only apply when reading from an {@code InputStream}, not
- * when constructed around a raw byte array (nor with {@link ByteString#newCodedInput}).
+ * default limit is {@code Integer.MAX_INT}. You should set this limit as small as you can without
+ * harming your app's functionality. Note that size limits only apply when reading from an {@code
+ * InputStream}, not when constructed around a raw byte array.
*
* <p>If you want to read several messages from a single CodedInputStream, you could call {@link
* #resetSizeCounter()} after each one to avoid hitting the size limit.
@@ -372,6 +410,63 @@ public abstract class CodedInputStream {
return oldLimit;
}
+
+ private boolean explicitDiscardUnknownFields = false;
+
+ private static volatile boolean proto3DiscardUnknownFieldsDefault = false;
+
+ static void setProto3DiscardUnknownsByDefaultForTest() {
+ proto3DiscardUnknownFieldsDefault = true;
+ }
+
+ static void setProto3KeepUnknownsByDefaultForTest() {
+ proto3DiscardUnknownFieldsDefault = false;
+ }
+
+ static boolean getProto3DiscardUnknownFieldsDefault() {
+ return proto3DiscardUnknownFieldsDefault;
+ }
+
+ /**
+ * Sets this {@code CodedInputStream} to discard unknown fields. Only applies to full runtime
+ * messages; lite messages will always preserve unknowns.
+ *
+ * <p>Note calling this function alone will have NO immediate effect on the underlying input data.
+ * The unknown fields will be discarded during parsing. This affects both Proto2 and Proto3 full
+ * runtime.
+ */
+ final void discardUnknownFields() {
+ explicitDiscardUnknownFields = true;
+ }
+
+ /**
+ * Reverts the unknown fields preservation behavior for Proto2 and Proto3 full runtime to their
+ * default.
+ */
+ final void unsetDiscardUnknownFields() {
+ explicitDiscardUnknownFields = false;
+ }
+
+ /**
+ * Whether unknown fields in this input stream should be discarded during parsing into full
+ * runtime messages.
+ */
+ final boolean shouldDiscardUnknownFields() {
+ return explicitDiscardUnknownFields;
+ }
+
+ /**
+ * Whether unknown fields in this input stream should be discarded during parsing for proto3 full
+ * runtime messages.
+ *
+ * <p>This function was temporarily introduced before proto3 unknown fields behavior is changed.
+ * TODO(liujisi): remove this and related code in GeneratedMessage after proto3 unknown
+ * fields migration is done.
+ */
+ final boolean shouldDiscardUnknownFieldsProto3() {
+ return explicitDiscardUnknownFields ? true : proto3DiscardUnknownFieldsDefault;
+ }
+
/**
* Resets the current size counter to zero (see {@link #setSizeLimit(int)}). Only valid for {@link
* InputStream}-backed streams.
@@ -572,7 +667,7 @@ public abstract class CodedInputStream {
skipRawVarint();
return true;
case WireFormat.WIRETYPE_FIXED64:
- skipRawBytes(FIXED_64_SIZE);
+ skipRawBytes(FIXED64_SIZE);
return true;
case WireFormat.WIRETYPE_LENGTH_DELIMITED:
skipRawBytes(readRawVarint32());
@@ -585,7 +680,7 @@ public abstract class CodedInputStream {
case WireFormat.WIRETYPE_END_GROUP:
return false;
case WireFormat.WIRETYPE_FIXED32:
- skipRawBytes(FIXED_32_SIZE);
+ skipRawBytes(FIXED32_SIZE);
return true;
default:
throw InvalidProtocolBufferException.invalidWireType();
@@ -1064,12 +1159,12 @@ public abstract class CodedInputStream {
public int readRawLittleEndian32() throws IOException {
int tempPos = pos;
- if (limit - tempPos < FIXED_32_SIZE) {
+ if (limit - tempPos < FIXED32_SIZE) {
throw InvalidProtocolBufferException.truncatedMessage();
}
final byte[] buffer = this.buffer;
- pos = tempPos + FIXED_32_SIZE;
+ pos = tempPos + FIXED32_SIZE;
return (((buffer[tempPos] & 0xff))
| ((buffer[tempPos + 1] & 0xff) << 8)
| ((buffer[tempPos + 2] & 0xff) << 16)
@@ -1080,12 +1175,12 @@ public abstract class CodedInputStream {
public long readRawLittleEndian64() throws IOException {
int tempPos = pos;
- if (limit - tempPos < FIXED_64_SIZE) {
+ if (limit - tempPos < FIXED64_SIZE) {
throw InvalidProtocolBufferException.truncatedMessage();
}
final byte[] buffer = this.buffer;
- pos = tempPos + FIXED_64_SIZE;
+ pos = tempPos + FIXED64_SIZE;
return (((buffer[tempPos] & 0xffL))
| ((buffer[tempPos + 1] & 0xffL) << 8)
| ((buffer[tempPos + 2] & 0xffL) << 16)
@@ -1290,7 +1385,7 @@ public abstract class CodedInputStream {
skipRawVarint();
return true;
case WireFormat.WIRETYPE_FIXED64:
- skipRawBytes(FIXED_64_SIZE);
+ skipRawBytes(FIXED64_SIZE);
return true;
case WireFormat.WIRETYPE_LENGTH_DELIMITED:
skipRawBytes(readRawVarint32());
@@ -1303,7 +1398,7 @@ public abstract class CodedInputStream {
case WireFormat.WIRETYPE_END_GROUP:
return false;
case WireFormat.WIRETYPE_FIXED32:
- skipRawBytes(FIXED_32_SIZE);
+ skipRawBytes(FIXED32_SIZE);
return true;
default:
throw InvalidProtocolBufferException.invalidWireType();
@@ -1429,7 +1524,9 @@ public abstract class CodedInputStream {
final int size = readRawVarint32();
if (size > 0 && size <= remaining()) {
// TODO(nathanmittler): Is there a way to avoid this copy?
- byte[] bytes = copyToArray(pos, pos + size);
+ // The same as readBytes' logic
+ byte[] bytes = new byte[size];
+ UnsafeUtil.copyMemory(pos, bytes, 0, size);
String result = new String(bytes, UTF_8);
pos += size;
return result;
@@ -1449,7 +1546,9 @@ public abstract class CodedInputStream {
final int size = readRawVarint32();
if (size >= 0 && size <= remaining()) {
// TODO(nathanmittler): Is there a way to avoid this copy?
- byte[] bytes = copyToArray(pos, pos + size);
+ // The same as readBytes' logic
+ byte[] bytes = new byte[size];
+ UnsafeUtil.copyMemory(pos, bytes, 0, size);
// TODO(martinrb): We could save a pass by validating while decoding.
if (!Utf8.isValidUtf8(bytes)) {
throw InvalidProtocolBufferException.invalidUtf8();
@@ -1545,14 +1644,17 @@ public abstract class CodedInputStream {
public ByteString readBytes() throws IOException {
final int size = readRawVarint32();
if (size > 0 && size <= remaining()) {
- ByteBuffer result;
if (immutable && enableAliasing) {
- result = slice(pos, pos + size);
+ final ByteBuffer result = slice(pos, pos + size);
+ pos += size;
+ return ByteString.wrap(result);
} else {
- result = copy(pos, pos + size);
+ // Use UnsafeUtil to copy the memory to bytes instead of using ByteBuffer ways.
+ byte[] bytes = new byte[size];
+ UnsafeUtil.copyMemory(pos, bytes, 0, size);
+ pos += size;
+ return ByteString.wrap(bytes);
}
- pos += size;
- return ByteString.wrap(result);
}
if (size == 0) {
@@ -1573,18 +1675,21 @@ public abstract class CodedInputStream {
public ByteBuffer readByteBuffer() throws IOException {
final int size = readRawVarint32();
if (size > 0 && size <= remaining()) {
- ByteBuffer result;
// "Immutable" implies that buffer is backing a ByteString.
// Disallow slicing in this case to prevent the caller from modifying the contents
// of the ByteString.
if (!immutable && enableAliasing) {
- result = slice(pos, pos + size);
+ final ByteBuffer result = slice(pos, pos + size);
+ pos += size;
+ return result;
} else {
- result = copy(pos, pos + size);
+ // The same as readBytes' logic
+ byte[] bytes = new byte[size];
+ UnsafeUtil.copyMemory(pos, bytes, 0, size);
+ pos += size;
+ return ByteBuffer.wrap(bytes);
}
- pos += size;
// TODO(nathanmittler): Investigate making the ByteBuffer be made read-only
- return result;
}
if (size == 0) {
@@ -1785,11 +1890,11 @@ public abstract class CodedInputStream {
public int readRawLittleEndian32() throws IOException {
long tempPos = pos;
- if (limit - tempPos < FIXED_32_SIZE) {
+ if (limit - tempPos < FIXED32_SIZE) {
throw InvalidProtocolBufferException.truncatedMessage();
}
- pos = tempPos + FIXED_32_SIZE;
+ pos = tempPos + FIXED32_SIZE;
return (((UnsafeUtil.getByte(tempPos) & 0xff))
| ((UnsafeUtil.getByte(tempPos + 1) & 0xff) << 8)
| ((UnsafeUtil.getByte(tempPos + 2) & 0xff) << 16)
@@ -1800,11 +1905,11 @@ public abstract class CodedInputStream {
public long readRawLittleEndian64() throws IOException {
long tempPos = pos;
- if (limit - tempPos < FIXED_64_SIZE) {
+ if (limit - tempPos < FIXED64_SIZE) {
throw InvalidProtocolBufferException.truncatedMessage();
}
- pos = tempPos + FIXED_64_SIZE;
+ pos = tempPos + FIXED64_SIZE;
return (((UnsafeUtil.getByte(tempPos) & 0xffL))
| ((UnsafeUtil.getByte(tempPos + 1) & 0xffL) << 8)
| ((UnsafeUtil.getByte(tempPos + 2) & 0xffL) << 16)
@@ -1943,27 +2048,6 @@ public abstract class CodedInputStream {
buffer.limit(prevLimit);
}
}
-
- private ByteBuffer copy(long begin, long end) throws IOException {
- return ByteBuffer.wrap(copyToArray(begin, end));
- }
-
- private byte[] copyToArray(long begin, long end) throws IOException {
- int prevPos = buffer.position();
- int prevLimit = buffer.limit();
- try {
- buffer.position(bufferPos(begin));
- buffer.limit(bufferPos(end));
- byte[] bytes = new byte[(int) (end - begin)];
- buffer.get(bytes);
- return bytes;
- } catch (IllegalArgumentException e) {
- throw InvalidProtocolBufferException.truncatedMessage();
- } finally {
- buffer.position(prevPos);
- buffer.limit(prevLimit);
- }
- }
}
/**
@@ -2034,7 +2118,7 @@ public abstract class CodedInputStream {
skipRawVarint();
return true;
case WireFormat.WIRETYPE_FIXED64:
- skipRawBytes(FIXED_64_SIZE);
+ skipRawBytes(FIXED64_SIZE);
return true;
case WireFormat.WIRETYPE_LENGTH_DELIMITED:
skipRawBytes(readRawVarint32());
@@ -2047,7 +2131,7 @@ public abstract class CodedInputStream {
case WireFormat.WIRETYPE_END_GROUP:
return false;
case WireFormat.WIRETYPE_FIXED32:
- skipRawBytes(FIXED_32_SIZE);
+ skipRawBytes(FIXED32_SIZE);
return true;
default:
throw InvalidProtocolBufferException.invalidWireType();
@@ -2332,8 +2416,7 @@ public abstract class CodedInputStream {
if (size == 0) {
return ByteString.EMPTY;
}
- // Slow path: Build a byte array first then copy it.
- return ByteString.wrap(readRawBytesSlowPath(size));
+ return readBytesSlowPath(size);
}
@Override
@@ -2558,13 +2641,13 @@ public abstract class CodedInputStream {
public int readRawLittleEndian32() throws IOException {
int tempPos = pos;
- if (bufferSize - tempPos < FIXED_32_SIZE) {
- refillBuffer(FIXED_32_SIZE);
+ if (bufferSize - tempPos < FIXED32_SIZE) {
+ refillBuffer(FIXED32_SIZE);
tempPos = pos;
}
final byte[] buffer = this.buffer;
- pos = tempPos + FIXED_32_SIZE;
+ pos = tempPos + FIXED32_SIZE;
return (((buffer[tempPos] & 0xff))
| ((buffer[tempPos + 1] & 0xff) << 8)
| ((buffer[tempPos + 2] & 0xff) << 16)
@@ -2575,13 +2658,13 @@ public abstract class CodedInputStream {
public long readRawLittleEndian64() throws IOException {
int tempPos = pos;
- if (bufferSize - tempPos < FIXED_64_SIZE) {
- refillBuffer(FIXED_64_SIZE);
+ if (bufferSize - tempPos < FIXED64_SIZE) {
+ refillBuffer(FIXED64_SIZE);
tempPos = pos;
}
final byte[] buffer = this.buffer;
- pos = tempPos + FIXED_64_SIZE;
+ pos = tempPos + FIXED64_SIZE;
return (((buffer[tempPos] & 0xffL))
| ((buffer[tempPos + 1] & 0xffL) << 8)
| ((buffer[tempPos + 2] & 0xffL) << 16)
@@ -2675,7 +2758,13 @@ public abstract class CodedInputStream {
*/
private void refillBuffer(int n) throws IOException {
if (!tryRefillBuffer(n)) {
- throw InvalidProtocolBufferException.truncatedMessage();
+ // We have to distinguish the exception between sizeLimitExceeded and truncatedMessage. So
+ // we just throw an sizeLimitExceeded exception here if it exceeds the sizeLimit
+ if (n > sizeLimit - totalBytesRetired - pos) {
+ throw InvalidProtocolBufferException.sizeLimitExceeded();
+ } else {
+ throw InvalidProtocolBufferException.truncatedMessage();
+ }
}
}
@@ -2684,8 +2773,8 @@ public abstract class CodedInputStream {
* buffer. Caller must ensure that the requested space is not yet available, and that the
* requested space is less than BUFFER_SIZE.
*
- * @return {@code true} if the bytes could be made available; {@code false} if the end of the
- * stream or the current limit was reached.
+ * @return {@code true} If the bytes could be made available; {@code false} 1. Current at the
+ * end of the stream 2. The current limit was reached 3. The total size limit was reached
*/
private boolean tryRefillBuffer(int n) throws IOException {
if (pos + n <= bufferSize) {
@@ -2693,6 +2782,14 @@ public abstract class CodedInputStream {
"refillBuffer() called when " + n + " bytes were already available in buffer");
}
+ // Check whether the size of total message needs to read is bigger than the size limit.
+ // We shouldn't throw an exception here as isAtEnd() function needs to get this function's
+ // return as the result.
+ if (n > sizeLimit - totalBytesRetired - pos) {
+ return false;
+ }
+
+ // Shouldn't throw the exception here either.
if (totalBytesRetired + pos + n > currentLimit) {
// Oops, we hit a limit.
return false;
@@ -2712,7 +2809,16 @@ public abstract class CodedInputStream {
pos = 0;
}
- int bytesRead = input.read(buffer, bufferSize, buffer.length - bufferSize);
+ // Here we should refill the buffer as many bytes as possible.
+ int bytesRead =
+ input.read(
+ buffer,
+ bufferSize,
+ Math.min(
+ // the size of allocated but unused bytes in the buffer
+ buffer.length - bufferSize,
+ // do not exceed the total bytes limit
+ sizeLimit - totalBytesRetired - bufferSize));
if (bytesRead == 0 || bytesRead < -1 || bytesRead > buffer.length) {
throw new IllegalStateException(
"InputStream#read(byte[]) returned invalid result: "
@@ -2721,10 +2827,6 @@ public abstract class CodedInputStream {
}
if (bytesRead > 0) {
bufferSize += bytesRead;
- // Integer-overflow-conscious check against sizeLimit
- if (totalBytesRetired + n - sizeLimit > 0) {
- throw InvalidProtocolBufferException.sizeLimitExceeded();
- }
recomputeBufferSizeAfterLimit();
return (bufferSize >= n) ? true : tryRefillBuffer(n);
}
@@ -2756,6 +2858,49 @@ public abstract class CodedInputStream {
* (bufferSize - pos) && size > 0)
*/
private byte[] readRawBytesSlowPath(final int size) throws IOException {
+ // Attempt to read the data in one byte array when it's safe to do.
+ byte[] result = readRawBytesSlowPathOneChunk(size);
+ if (result != null) {
+ return result;
+ }
+
+ final int originalBufferPos = pos;
+ final int bufferedBytes = bufferSize - pos;
+
+ // Mark the current buffer consumed.
+ totalBytesRetired += bufferSize;
+ pos = 0;
+ bufferSize = 0;
+
+ // Determine the number of bytes we need to read from the input stream.
+ int sizeLeft = size - bufferedBytes;
+
+ // The size is very large. For security reasons we read them in small
+ // chunks.
+ List<byte[]> chunks = readRawBytesSlowPathRemainingChunks(sizeLeft);
+
+ // OK, got everything. Now concatenate it all into one buffer.
+ final byte[] bytes = new byte[size];
+
+ // Start by copying the leftover bytes from this.buffer.
+ System.arraycopy(buffer, originalBufferPos, bytes, 0, bufferedBytes);
+
+ // And now all the chunks.
+ int tempPos = bufferedBytes;
+ for (final byte[] chunk : chunks) {
+ System.arraycopy(chunk, 0, bytes, tempPos, chunk.length);
+ tempPos += chunk.length;
+ }
+
+ // Done.
+ return bytes;
+ }
+
+ /**
+ * Attempts to read the data in one byte array when it's safe to do. Returns null if the size to
+ * read is too large and needs to be allocated in smaller chunks for security reasons.
+ */
+ private byte[] readRawBytesSlowPathOneChunk(final int size) throws IOException {
if (size == 0) {
return Internal.EMPTY_BYTE_ARRAY;
}
@@ -2776,14 +2921,7 @@ public abstract class CodedInputStream {
throw InvalidProtocolBufferException.truncatedMessage();
}
- final int originalBufferPos = pos;
final int bufferedBytes = bufferSize - pos;
-
- // Mark the current buffer consumed.
- totalBytesRetired += bufferSize;
- pos = 0;
- bufferSize = 0;
-
// Determine the number of bytes we need to read from the input stream.
int sizeLeft = size - bufferedBytes;
// TODO(nathanmittler): Consider using a value larger than DEFAULT_BUFFER_SIZE.
@@ -2793,7 +2931,10 @@ public abstract class CodedInputStream {
final byte[] bytes = new byte[size];
// Copy all of the buffered bytes to the result buffer.
- System.arraycopy(buffer, originalBufferPos, bytes, 0, bufferedBytes);
+ System.arraycopy(buffer, pos, bytes, 0, bufferedBytes);
+ totalBytesRetired += bufferSize;
+ pos = 0;
+ bufferSize = 0;
// Fill the remaining bytes from the input stream.
int tempPos = bufferedBytes;
@@ -2809,6 +2950,11 @@ public abstract class CodedInputStream {
return bytes;
}
+ return null;
+ }
+
+ /** Reads the remaining data in small chunks from the input stream. */
+ private List<byte[]> readRawBytesSlowPathRemainingChunks(int sizeLeft) throws IOException {
// The size is very large. For security reasons, we can't allocate the
// entire byte array yet. The size comes directly from the input, so a
// maliciously-crafted message could provide a bogus very large size in
@@ -2834,21 +2980,41 @@ public abstract class CodedInputStream {
chunks.add(chunk);
}
- // OK, got everything. Now concatenate it all into one buffer.
- final byte[] bytes = new byte[size];
-
- // Start by copying the leftover bytes from this.buffer.
- System.arraycopy(buffer, originalBufferPos, bytes, 0, bufferedBytes);
+ return chunks;
+ }
- // And now all the chunks.
- int tempPos = bufferedBytes;
- for (final byte[] chunk : chunks) {
- System.arraycopy(chunk, 0, bytes, tempPos, chunk.length);
- tempPos += chunk.length;
+ /**
+ * Like readBytes, but caller must have already checked the fast path: (size <= (bufferSize -
+ * pos) && size > 0 || size == 0)
+ */
+ private ByteString readBytesSlowPath(final int size) throws IOException {
+ final byte[] result = readRawBytesSlowPathOneChunk(size);
+ if (result != null) {
+ return ByteString.wrap(result);
}
- // Done.
- return bytes;
+ final int originalBufferPos = pos;
+ final int bufferedBytes = bufferSize - pos;
+
+ // Mark the current buffer consumed.
+ totalBytesRetired += bufferSize;
+ pos = 0;
+ bufferSize = 0;
+
+ // Determine the number of bytes we need to read from the input stream.
+ int sizeLeft = size - bufferedBytes;
+
+ // The size is very large. For security reasons we read them in small
+ // chunks.
+ List<byte[]> chunks = readRawBytesSlowPathRemainingChunks(sizeLeft);
+
+ // Wrap the byte arrays into a single ByteString.
+ List<ByteString> byteStrings = new ArrayList<ByteString>(1 + chunks.size());
+ byteStrings.add(ByteString.copyFrom(buffer, originalBufferPos, bufferedBytes));
+ for (byte[] chunk : chunks) {
+ byteStrings.add(ByteString.wrap(chunk));
+ }
+ return ByteString.copyFrom(byteStrings);
}
@Override
@@ -2893,4 +3059,848 @@ public abstract class CodedInputStream {
pos = size - tempPos;
}
}
+
+ /**
+ * Implementation of {@link CodedInputStream} that uses an {@link Iterable <ByteBuffer>} as the
+ * data source. Requires the use of {@code sun.misc.Unsafe} to perform fast reads on the buffer.
+ */
+ private static final class IterableDirectByteBufferDecoder extends CodedInputStream {
+ /** The object that need to decode. */
+ private Iterable<ByteBuffer> input;
+ /** The {@link Iterator} with type {@link ByteBuffer} of {@code input} */
+ private Iterator<ByteBuffer> iterator;
+ /** The current ByteBuffer; */
+ private ByteBuffer currentByteBuffer;
+ /**
+ * If {@code true}, indicates that all the buffer are backing a {@link ByteString} and are
+ * therefore considered to be an immutable input source.
+ */
+ private boolean immutable;
+ /**
+ * If {@code true}, indicates that calls to read {@link ByteString} or {@code byte[]}
+ * <strong>may</strong> return slices of the underlying buffer, rather than copies.
+ */
+ private boolean enableAliasing;
+ /** The global total message length limit */
+ private int totalBufferSize;
+ /** The amount of available data in the input beyond {@link #currentLimit}. */
+ private int bufferSizeAfterCurrentLimit;
+ /** The absolute position of the end of the current message. */
+ private int currentLimit = Integer.MAX_VALUE;
+ /** The last tag that was read from this stream. */
+ private int lastTag;
+ /** Total Bytes have been Read from the {@link Iterable} {@link ByteBuffer} */
+ private int totalBytesRead;
+ /** The start position offset of the whole message, used as to reset the totalBytesRead */
+ private int startOffset;
+ /** The current position for current ByteBuffer */
+ private long currentByteBufferPos;
+
+ private long currentByteBufferStartPos;
+ /**
+ * If the current ByteBuffer is unsafe-direct based, currentAddress is the start address of this
+ * ByteBuffer; otherwise should be zero.
+ */
+ private long currentAddress;
+ /** The limit position for current ByteBuffer */
+ private long currentByteBufferLimit;
+
+ /**
+ * The constructor of {@code Iterable<ByteBuffer>} decoder.
+ *
+ * @param inputBufs The input data.
+ * @param size The total size of the input data.
+ * @param immutableFlag whether the input data is immutable.
+ */
+ private IterableDirectByteBufferDecoder(
+ Iterable<ByteBuffer> inputBufs, int size, boolean immutableFlag) {
+ totalBufferSize = size;
+ input = inputBufs;
+ iterator = input.iterator();
+ immutable = immutableFlag;
+ startOffset = totalBytesRead = 0;
+ if (size == 0) {
+ currentByteBuffer = EMPTY_BYTE_BUFFER;
+ currentByteBufferPos = 0;
+ currentByteBufferStartPos = 0;
+ currentByteBufferLimit = 0;
+ currentAddress = 0;
+ } else {
+ tryGetNextByteBuffer();
+ }
+ }
+
+ /** To get the next ByteBuffer from {@code input}, and then update the parameters */
+ private void getNextByteBuffer() throws InvalidProtocolBufferException {
+ if (!iterator.hasNext()) {
+ throw InvalidProtocolBufferException.truncatedMessage();
+ }
+ tryGetNextByteBuffer();
+ }
+
+ private void tryGetNextByteBuffer() {
+ currentByteBuffer = iterator.next();
+ totalBytesRead += (int) (currentByteBufferPos - currentByteBufferStartPos);
+ currentByteBufferPos = currentByteBuffer.position();
+ currentByteBufferStartPos = currentByteBufferPos;
+ currentByteBufferLimit = currentByteBuffer.limit();
+ currentAddress = UnsafeUtil.addressOffset(currentByteBuffer);
+ currentByteBufferPos += currentAddress;
+ currentByteBufferStartPos += currentAddress;
+ currentByteBufferLimit += currentAddress;
+ }
+
+ @Override
+ public int readTag() throws IOException {
+ if (isAtEnd()) {
+ lastTag = 0;
+ return 0;
+ }
+
+ lastTag = readRawVarint32();
+ if (WireFormat.getTagFieldNumber(lastTag) == 0) {
+ // If we actually read zero (or any tag number corresponding to field
+ // number zero), that's not a valid tag.
+ throw InvalidProtocolBufferException.invalidTag();
+ }
+ return lastTag;
+ }
+
+ @Override
+ public void checkLastTagWas(final int value) throws InvalidProtocolBufferException {
+ if (lastTag != value) {
+ throw InvalidProtocolBufferException.invalidEndTag();
+ }
+ }
+
+ @Override
+ public int getLastTag() {
+ return lastTag;
+ }
+
+ @Override
+ public boolean skipField(final int tag) throws IOException {
+ switch (WireFormat.getTagWireType(tag)) {
+ case WireFormat.WIRETYPE_VARINT:
+ skipRawVarint();
+ return true;
+ case WireFormat.WIRETYPE_FIXED64:
+ skipRawBytes(FIXED64_SIZE);
+ return true;
+ case WireFormat.WIRETYPE_LENGTH_DELIMITED:
+ skipRawBytes(readRawVarint32());
+ return true;
+ case WireFormat.WIRETYPE_START_GROUP:
+ skipMessage();
+ checkLastTagWas(
+ WireFormat.makeTag(WireFormat.getTagFieldNumber(tag), WireFormat.WIRETYPE_END_GROUP));
+ return true;
+ case WireFormat.WIRETYPE_END_GROUP:
+ return false;
+ case WireFormat.WIRETYPE_FIXED32:
+ skipRawBytes(FIXED32_SIZE);
+ return true;
+ default:
+ throw InvalidProtocolBufferException.invalidWireType();
+ }
+ }
+
+ @Override
+ public boolean skipField(final int tag, final CodedOutputStream output) throws IOException {
+ switch (WireFormat.getTagWireType(tag)) {
+ case WireFormat.WIRETYPE_VARINT:
+ {
+ long value = readInt64();
+ output.writeRawVarint32(tag);
+ output.writeUInt64NoTag(value);
+ return true;
+ }
+ case WireFormat.WIRETYPE_FIXED64:
+ {
+ long value = readRawLittleEndian64();
+ output.writeRawVarint32(tag);
+ output.writeFixed64NoTag(value);
+ return true;
+ }
+ case WireFormat.WIRETYPE_LENGTH_DELIMITED:
+ {
+ ByteString value = readBytes();
+ output.writeRawVarint32(tag);
+ output.writeBytesNoTag(value);
+ return true;
+ }
+ case WireFormat.WIRETYPE_START_GROUP:
+ {
+ output.writeRawVarint32(tag);
+ skipMessage(output);
+ int endtag =
+ WireFormat.makeTag(
+ WireFormat.getTagFieldNumber(tag), WireFormat.WIRETYPE_END_GROUP);
+ checkLastTagWas(endtag);
+ output.writeRawVarint32(endtag);
+ return true;
+ }
+ case WireFormat.WIRETYPE_END_GROUP:
+ {
+ return false;
+ }
+ case WireFormat.WIRETYPE_FIXED32:
+ {
+ int value = readRawLittleEndian32();
+ output.writeRawVarint32(tag);
+ output.writeFixed32NoTag(value);
+ return true;
+ }
+ default:
+ throw InvalidProtocolBufferException.invalidWireType();
+ }
+ }
+
+ @Override
+ public void skipMessage() throws IOException {
+ while (true) {
+ final int tag = readTag();
+ if (tag == 0 || !skipField(tag)) {
+ return;
+ }
+ }
+ }
+
+ @Override
+ public void skipMessage(CodedOutputStream output) throws IOException {
+ while (true) {
+ final int tag = readTag();
+ if (tag == 0 || !skipField(tag, output)) {
+ return;
+ }
+ }
+ }
+
+ // -----------------------------------------------------------------
+
+ @Override
+ public double readDouble() throws IOException {
+ return Double.longBitsToDouble(readRawLittleEndian64());
+ }
+
+ @Override
+ public float readFloat() throws IOException {
+ return Float.intBitsToFloat(readRawLittleEndian32());
+ }
+
+ @Override
+ public long readUInt64() throws IOException {
+ return readRawVarint64();
+ }
+
+ @Override
+ public long readInt64() throws IOException {
+ return readRawVarint64();
+ }
+
+ @Override
+ public int readInt32() throws IOException {
+ return readRawVarint32();
+ }
+
+ @Override
+ public long readFixed64() throws IOException {
+ return readRawLittleEndian64();
+ }
+
+ @Override
+ public int readFixed32() throws IOException {
+ return readRawLittleEndian32();
+ }
+
+ @Override
+ public boolean readBool() throws IOException {
+ return readRawVarint64() != 0;
+ }
+
+ @Override
+ public String readString() throws IOException {
+ final int size = readRawVarint32();
+ if (size > 0 && size <= currentByteBufferLimit - currentByteBufferPos) {
+ byte[] bytes = new byte[size];
+ UnsafeUtil.copyMemory(currentByteBufferPos, bytes, 0, size);
+ String result = new String(bytes, UTF_8);
+ currentByteBufferPos += size;
+ return result;
+ } else if (size > 0 && size <= remaining()) {
+ // TODO(yilunchong): To use an underlying bytes[] instead of allocating a new bytes[]
+ byte[] bytes = new byte[size];
+ readRawBytesTo(bytes, 0, size);
+ String result = new String(bytes, UTF_8);
+ return result;
+ }
+
+ if (size == 0) {
+ return "";
+ }
+ if (size < 0) {
+ throw InvalidProtocolBufferException.negativeSize();
+ }
+ throw InvalidProtocolBufferException.truncatedMessage();
+ }
+
+ @Override
+ public String readStringRequireUtf8() throws IOException {
+ final int size = readRawVarint32();
+ if (size > 0 && size <= currentByteBufferLimit - currentByteBufferPos) {
+ byte[] bytes = new byte[size];
+ UnsafeUtil.copyMemory(currentByteBufferPos, bytes, 0, size);
+ if (!Utf8.isValidUtf8(bytes)) {
+ throw InvalidProtocolBufferException.invalidUtf8();
+ }
+ String result = new String(bytes, UTF_8);
+ currentByteBufferPos += size;
+ return result;
+ }
+ if (size >= 0 && size <= remaining()) {
+ byte[] bytes = new byte[size];
+ readRawBytesTo(bytes, 0, size);
+ if (!Utf8.isValidUtf8(bytes)) {
+ throw InvalidProtocolBufferException.invalidUtf8();
+ }
+ String result = new String(bytes, UTF_8);
+ return result;
+ }
+
+ if (size == 0) {
+ return "";
+ }
+ if (size <= 0) {
+ throw InvalidProtocolBufferException.negativeSize();
+ }
+ throw InvalidProtocolBufferException.truncatedMessage();
+ }
+
+ @Override
+ public void readGroup(
+ final int fieldNumber,
+ final MessageLite.Builder builder,
+ final ExtensionRegistryLite extensionRegistry)
+ throws IOException {
+ if (recursionDepth >= recursionLimit) {
+ throw InvalidProtocolBufferException.recursionLimitExceeded();
+ }
+ ++recursionDepth;
+ builder.mergeFrom(this, extensionRegistry);
+ checkLastTagWas(WireFormat.makeTag(fieldNumber, WireFormat.WIRETYPE_END_GROUP));
+ --recursionDepth;
+ }
+
+
+ @Override
+ public <T extends MessageLite> T readGroup(
+ final int fieldNumber,
+ final Parser<T> parser,
+ final ExtensionRegistryLite extensionRegistry)
+ throws IOException {
+ if (recursionDepth >= recursionLimit) {
+ throw InvalidProtocolBufferException.recursionLimitExceeded();
+ }
+ ++recursionDepth;
+ T result = parser.parsePartialFrom(this, extensionRegistry);
+ checkLastTagWas(WireFormat.makeTag(fieldNumber, WireFormat.WIRETYPE_END_GROUP));
+ --recursionDepth;
+ return result;
+ }
+
+ @Deprecated
+ @Override
+ public void readUnknownGroup(final int fieldNumber, final MessageLite.Builder builder)
+ throws IOException {
+ readGroup(fieldNumber, builder, ExtensionRegistryLite.getEmptyRegistry());
+ }
+
+ @Override
+ public void readMessage(
+ final MessageLite.Builder builder, final ExtensionRegistryLite extensionRegistry)
+ throws IOException {
+ final int length = readRawVarint32();
+ if (recursionDepth >= recursionLimit) {
+ throw InvalidProtocolBufferException.recursionLimitExceeded();
+ }
+ final int oldLimit = pushLimit(length);
+ ++recursionDepth;
+ builder.mergeFrom(this, extensionRegistry);
+ checkLastTagWas(0);
+ --recursionDepth;
+ popLimit(oldLimit);
+ }
+
+
+ @Override
+ public <T extends MessageLite> T readMessage(
+ final Parser<T> parser, final ExtensionRegistryLite extensionRegistry) throws IOException {
+ int length = readRawVarint32();
+ if (recursionDepth >= recursionLimit) {
+ throw InvalidProtocolBufferException.recursionLimitExceeded();
+ }
+ final int oldLimit = pushLimit(length);
+ ++recursionDepth;
+ T result = parser.parsePartialFrom(this, extensionRegistry);
+ checkLastTagWas(0);
+ --recursionDepth;
+ popLimit(oldLimit);
+ return result;
+ }
+
+ @Override
+ public ByteString readBytes() throws IOException {
+ final int size = readRawVarint32();
+ if (size > 0 && size <= currentByteBufferLimit - currentByteBufferPos) {
+ if (immutable && enableAliasing) {
+ final int idx = (int) (currentByteBufferPos - currentAddress);
+ final ByteString result = ByteString.wrap(slice(idx, idx + size));
+ currentByteBufferPos += size;
+ return result;
+ } else {
+ byte[] bytes;
+ bytes = new byte[size];
+ UnsafeUtil.copyMemory(currentByteBufferPos, bytes, 0, size);
+ currentByteBufferPos += size;
+ return ByteString.wrap(bytes);
+ }
+ } else if (size > 0 && size <= remaining()) {
+ byte[] temp = new byte[size];
+ readRawBytesTo(temp, 0, size);
+ return ByteString.wrap(temp);
+ }
+
+ if (size == 0) {
+ return ByteString.EMPTY;
+ }
+ if (size < 0) {
+ throw InvalidProtocolBufferException.negativeSize();
+ }
+ throw InvalidProtocolBufferException.truncatedMessage();
+ }
+
+ @Override
+ public byte[] readByteArray() throws IOException {
+ return readRawBytes(readRawVarint32());
+ }
+
+ @Override
+ public ByteBuffer readByteBuffer() throws IOException {
+ final int size = readRawVarint32();
+ if (size > 0 && size <= currentRemaining()) {
+ if (!immutable && enableAliasing) {
+ currentByteBufferPos += size;
+ return slice(
+ (int) (currentByteBufferPos - currentAddress - size),
+ (int) (currentByteBufferPos - currentAddress));
+ } else {
+ byte[] bytes = new byte[size];
+ UnsafeUtil.copyMemory(currentByteBufferPos, bytes, 0, size);
+ currentByteBufferPos += size;
+ return ByteBuffer.wrap(bytes);
+ }
+ } else if (size > 0 && size <= remaining()) {
+ byte[] temp = new byte[size];
+ readRawBytesTo(temp, 0, size);
+ return ByteBuffer.wrap(temp);
+ }
+
+ if (size == 0) {
+ return EMPTY_BYTE_BUFFER;
+ }
+ if (size < 0) {
+ throw InvalidProtocolBufferException.negativeSize();
+ }
+ throw InvalidProtocolBufferException.truncatedMessage();
+ }
+
+ @Override
+ public int readUInt32() throws IOException {
+ return readRawVarint32();
+ }
+
+ @Override
+ public int readEnum() throws IOException {
+ return readRawVarint32();
+ }
+
+ @Override
+ public int readSFixed32() throws IOException {
+ return readRawLittleEndian32();
+ }
+
+ @Override
+ public long readSFixed64() throws IOException {
+ return readRawLittleEndian64();
+ }
+
+ @Override
+ public int readSInt32() throws IOException {
+ return decodeZigZag32(readRawVarint32());
+ }
+
+ @Override
+ public long readSInt64() throws IOException {
+ return decodeZigZag64(readRawVarint64());
+ }
+
+ @Override
+ public int readRawVarint32() throws IOException {
+ fastpath:
+ {
+ long tempPos = currentByteBufferPos;
+
+ if (currentByteBufferLimit == currentByteBufferPos) {
+ break fastpath;
+ }
+
+ int x;
+ if ((x = UnsafeUtil.getByte(tempPos++)) >= 0) {
+ currentByteBufferPos++;
+ return x;
+ } else if (currentByteBufferLimit - currentByteBufferPos < 10) {
+ break fastpath;
+ } else if ((x ^= (UnsafeUtil.getByte(tempPos++) << 7)) < 0) {
+ x ^= (~0 << 7);
+ } else if ((x ^= (UnsafeUtil.getByte(tempPos++) << 14)) >= 0) {
+ x ^= (~0 << 7) ^ (~0 << 14);
+ } else if ((x ^= (UnsafeUtil.getByte(tempPos++) << 21)) < 0) {
+ x ^= (~0 << 7) ^ (~0 << 14) ^ (~0 << 21);
+ } else {
+ int y = UnsafeUtil.getByte(tempPos++);
+ x ^= y << 28;
+ x ^= (~0 << 7) ^ (~0 << 14) ^ (~0 << 21) ^ (~0 << 28);
+ if (y < 0
+ && UnsafeUtil.getByte(tempPos++) < 0
+ && UnsafeUtil.getByte(tempPos++) < 0
+ && UnsafeUtil.getByte(tempPos++) < 0
+ && UnsafeUtil.getByte(tempPos++) < 0
+ && UnsafeUtil.getByte(tempPos++) < 0) {
+ break fastpath; // Will throw malformedVarint()
+ }
+ }
+ currentByteBufferPos = tempPos;
+ return x;
+ }
+ return (int) readRawVarint64SlowPath();
+ }
+
+ @Override
+ public long readRawVarint64() throws IOException {
+ fastpath:
+ {
+ long tempPos = currentByteBufferPos;
+
+ if (currentByteBufferLimit == currentByteBufferPos) {
+ break fastpath;
+ }
+
+ long x;
+ int y;
+ if ((y = UnsafeUtil.getByte(tempPos++)) >= 0) {
+ currentByteBufferPos++;
+ return y;
+ } else if (currentByteBufferLimit - currentByteBufferPos < 10) {
+ break fastpath;
+ } else if ((y ^= (UnsafeUtil.getByte(tempPos++) << 7)) < 0) {
+ x = y ^ (~0 << 7);
+ } else if ((y ^= (UnsafeUtil.getByte(tempPos++) << 14)) >= 0) {
+ x = y ^ ((~0 << 7) ^ (~0 << 14));
+ } else if ((y ^= (UnsafeUtil.getByte(tempPos++) << 21)) < 0) {
+ x = y ^ ((~0 << 7) ^ (~0 << 14) ^ (~0 << 21));
+ } else if ((x = y ^ ((long) UnsafeUtil.getByte(tempPos++) << 28)) >= 0L) {
+ x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28);
+ } else if ((x ^= ((long) UnsafeUtil.getByte(tempPos++) << 35)) < 0L) {
+ x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28) ^ (~0L << 35);
+ } else if ((x ^= ((long) UnsafeUtil.getByte(tempPos++) << 42)) >= 0L) {
+ x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28) ^ (~0L << 35) ^ (~0L << 42);
+ } else if ((x ^= ((long) UnsafeUtil.getByte(tempPos++) << 49)) < 0L) {
+ x ^=
+ (~0L << 7)
+ ^ (~0L << 14)
+ ^ (~0L << 21)
+ ^ (~0L << 28)
+ ^ (~0L << 35)
+ ^ (~0L << 42)
+ ^ (~0L << 49);
+ } else {
+ x ^= ((long) UnsafeUtil.getByte(tempPos++) << 56);
+ x ^=
+ (~0L << 7)
+ ^ (~0L << 14)
+ ^ (~0L << 21)
+ ^ (~0L << 28)
+ ^ (~0L << 35)
+ ^ (~0L << 42)
+ ^ (~0L << 49)
+ ^ (~0L << 56);
+ if (x < 0L) {
+ if (UnsafeUtil.getByte(tempPos++) < 0L) {
+ break fastpath; // Will throw malformedVarint()
+ }
+ }
+ }
+ currentByteBufferPos = tempPos;
+ return x;
+ }
+ return readRawVarint64SlowPath();
+ }
+
+ @Override
+ long readRawVarint64SlowPath() throws IOException {
+ long result = 0;
+ for (int shift = 0; shift < 64; shift += 7) {
+ final byte b = readRawByte();
+ result |= (long) (b & 0x7F) << shift;
+ if ((b & 0x80) == 0) {
+ return result;
+ }
+ }
+ throw InvalidProtocolBufferException.malformedVarint();
+ }
+
+ @Override
+ public int readRawLittleEndian32() throws IOException {
+ if (currentRemaining() >= FIXED32_SIZE) {
+ long tempPos = currentByteBufferPos;
+ currentByteBufferPos += FIXED32_SIZE;
+ return (((UnsafeUtil.getByte(tempPos) & 0xff))
+ | ((UnsafeUtil.getByte(tempPos + 1) & 0xff) << 8)
+ | ((UnsafeUtil.getByte(tempPos + 2) & 0xff) << 16)
+ | ((UnsafeUtil.getByte(tempPos + 3) & 0xff) << 24));
+ }
+ return ((readRawByte() & 0xff)
+ | ((readRawByte() & 0xff) << 8)
+ | ((readRawByte() & 0xff) << 16)
+ | ((readRawByte() & 0xff) << 24));
+ }
+
+ @Override
+ public long readRawLittleEndian64() throws IOException {
+ if (currentRemaining() >= FIXED64_SIZE) {
+ long tempPos = currentByteBufferPos;
+ currentByteBufferPos += FIXED64_SIZE;
+ return (((UnsafeUtil.getByte(tempPos) & 0xffL))
+ | ((UnsafeUtil.getByte(tempPos + 1) & 0xffL) << 8)
+ | ((UnsafeUtil.getByte(tempPos + 2) & 0xffL) << 16)
+ | ((UnsafeUtil.getByte(tempPos + 3) & 0xffL) << 24)
+ | ((UnsafeUtil.getByte(tempPos + 4) & 0xffL) << 32)
+ | ((UnsafeUtil.getByte(tempPos + 5) & 0xffL) << 40)
+ | ((UnsafeUtil.getByte(tempPos + 6) & 0xffL) << 48)
+ | ((UnsafeUtil.getByte(tempPos + 7) & 0xffL) << 56));
+ }
+ return ((readRawByte() & 0xffL)
+ | ((readRawByte() & 0xffL) << 8)
+ | ((readRawByte() & 0xffL) << 16)
+ | ((readRawByte() & 0xffL) << 24)
+ | ((readRawByte() & 0xffL) << 32)
+ | ((readRawByte() & 0xffL) << 40)
+ | ((readRawByte() & 0xffL) << 48)
+ | ((readRawByte() & 0xffL) << 56));
+ }
+
+ @Override
+ public void enableAliasing(boolean enabled) {
+ this.enableAliasing = enabled;
+ }
+
+ @Override
+ public void resetSizeCounter() {
+ startOffset = (int) (totalBytesRead + currentByteBufferPos - currentByteBufferStartPos);
+ }
+
+ @Override
+ public int pushLimit(int byteLimit) throws InvalidProtocolBufferException {
+ if (byteLimit < 0) {
+ throw InvalidProtocolBufferException.negativeSize();
+ }
+ byteLimit += getTotalBytesRead();
+ final int oldLimit = currentLimit;
+ if (byteLimit > oldLimit) {
+ throw InvalidProtocolBufferException.truncatedMessage();
+ }
+ currentLimit = byteLimit;
+
+ recomputeBufferSizeAfterLimit();
+
+ return oldLimit;
+ }
+
+ private void recomputeBufferSizeAfterLimit() {
+ totalBufferSize += bufferSizeAfterCurrentLimit;
+ final int bufferEnd = totalBufferSize - startOffset;
+ if (bufferEnd > currentLimit) {
+ // Limit is in current buffer.
+ bufferSizeAfterCurrentLimit = bufferEnd - currentLimit;
+ totalBufferSize -= bufferSizeAfterCurrentLimit;
+ } else {
+ bufferSizeAfterCurrentLimit = 0;
+ }
+ }
+
+ @Override
+ public void popLimit(final int oldLimit) {
+ currentLimit = oldLimit;
+ recomputeBufferSizeAfterLimit();
+ }
+
+ @Override
+ public int getBytesUntilLimit() {
+ if (currentLimit == Integer.MAX_VALUE) {
+ return -1;
+ }
+
+ return currentLimit - getTotalBytesRead();
+ }
+
+ @Override
+ public boolean isAtEnd() throws IOException {
+ return totalBytesRead + currentByteBufferPos - currentByteBufferStartPos == totalBufferSize;
+ }
+
+ @Override
+ public int getTotalBytesRead() {
+ return (int)
+ (totalBytesRead - startOffset + currentByteBufferPos - currentByteBufferStartPos);
+ }
+
+ @Override
+ public byte readRawByte() throws IOException {
+ if (currentRemaining() == 0) {
+ getNextByteBuffer();
+ }
+ return UnsafeUtil.getByte(currentByteBufferPos++);
+ }
+
+ @Override
+ public byte[] readRawBytes(final int length) throws IOException {
+ if (length >= 0 && length <= currentRemaining()) {
+ byte[] bytes = new byte[length];
+ UnsafeUtil.copyMemory(currentByteBufferPos, bytes, 0, length);
+ currentByteBufferPos += length;
+ return bytes;
+ }
+ if (length >= 0 && length <= remaining()) {
+ byte[] bytes = new byte[length];
+ readRawBytesTo(bytes, 0, length);
+ return bytes;
+ }
+
+ if (length <= 0) {
+ if (length == 0) {
+ return EMPTY_BYTE_ARRAY;
+ } else {
+ throw InvalidProtocolBufferException.negativeSize();
+ }
+ }
+
+ throw InvalidProtocolBufferException.truncatedMessage();
+ }
+
+ /**
+ * Try to get raw bytes from {@code input} with the size of {@code length} and copy to {@code
+ * bytes} array. If the size is bigger than the number of remaining bytes in the input, then
+ * throw {@code truncatedMessage} exception.
+ *
+ * @param bytes
+ * @param offset
+ * @param length
+ * @throws IOException
+ */
+ private void readRawBytesTo(byte[] bytes, int offset, final int length) throws IOException {
+ if (length >= 0 && length <= remaining()) {
+ int l = length;
+ while (l > 0) {
+ if (currentRemaining() == 0) {
+ getNextByteBuffer();
+ }
+ int bytesToCopy = Math.min(l, (int) currentRemaining());
+ UnsafeUtil.copyMemory(currentByteBufferPos, bytes, length - l + offset, bytesToCopy);
+ l -= bytesToCopy;
+ currentByteBufferPos += bytesToCopy;
+ }
+ return;
+ }
+
+ if (length <= 0) {
+ if (length == 0) {
+ return;
+ } else {
+ throw InvalidProtocolBufferException.negativeSize();
+ }
+ }
+ throw InvalidProtocolBufferException.truncatedMessage();
+ }
+
+ @Override
+ public void skipRawBytes(final int length) throws IOException {
+ if (length >= 0
+ && length
+ <= (totalBufferSize
+ - totalBytesRead
+ - currentByteBufferPos
+ + currentByteBufferStartPos)) {
+ // We have all the bytes we need already.
+ int l = length;
+ while (l > 0) {
+ if (currentRemaining() == 0) {
+ getNextByteBuffer();
+ }
+ int rl = Math.min(l, (int) currentRemaining());
+ l -= rl;
+ currentByteBufferPos += rl;
+ }
+ return;
+ }
+
+ if (length < 0) {
+ throw InvalidProtocolBufferException.negativeSize();
+ }
+ throw InvalidProtocolBufferException.truncatedMessage();
+ }
+
+ // TODO: optimize to fastpath
+ private void skipRawVarint() throws IOException {
+ for (int i = 0; i < MAX_VARINT_SIZE; i++) {
+ if (readRawByte() >= 0) {
+ return;
+ }
+ }
+ throw InvalidProtocolBufferException.malformedVarint();
+ }
+
+ /**
+ * Try to get the number of remaining bytes in {@code input}.
+ *
+ * @return the number of remaining bytes in {@code input}.
+ */
+ private int remaining() {
+ return (int)
+ (totalBufferSize - totalBytesRead - currentByteBufferPos + currentByteBufferStartPos);
+ }
+
+ /**
+ * Try to get the number of remaining bytes in {@code currentByteBuffer}.
+ *
+ * @return the number of remaining bytes in {@code currentByteBuffer}
+ */
+ private long currentRemaining() {
+ return (currentByteBufferLimit - currentByteBufferPos);
+ }
+
+ private ByteBuffer slice(int begin, int end) throws IOException {
+ int prevPos = currentByteBuffer.position();
+ int prevLimit = currentByteBuffer.limit();
+ try {
+ currentByteBuffer.position(begin);
+ currentByteBuffer.limit(end);
+ return currentByteBuffer.slice();
+ } catch (IllegalArgumentException e) {
+ throw InvalidProtocolBufferException.truncatedMessage();
+ } finally {
+ currentByteBuffer.position(prevPos);
+ currentByteBuffer.limit(prevLimit);
+ }
+ }
+ }
}
diff --git a/java/core/src/main/java/com/google/protobuf/CodedOutputStream.java b/java/core/src/main/java/com/google/protobuf/CodedOutputStream.java
index 3e32c2c5..093a5f61 100644
--- a/java/core/src/main/java/com/google/protobuf/CodedOutputStream.java
+++ b/java/core/src/main/java/com/google/protobuf/CodedOutputStream.java
@@ -30,8 +30,8 @@
package com.google.protobuf;
-import static com.google.protobuf.WireFormat.FIXED_32_SIZE;
-import static com.google.protobuf.WireFormat.FIXED_64_SIZE;
+import static com.google.protobuf.WireFormat.FIXED32_SIZE;
+import static com.google.protobuf.WireFormat.FIXED64_SIZE;
import static com.google.protobuf.WireFormat.MAX_VARINT_SIZE;
import static java.lang.Math.max;
@@ -59,13 +59,12 @@ import java.util.logging.Logger;
public abstract class CodedOutputStream extends ByteOutput {
private static final Logger logger = Logger.getLogger(CodedOutputStream.class.getName());
private static final boolean HAS_UNSAFE_ARRAY_OPERATIONS = UnsafeUtil.hasUnsafeArrayOperations();
- private static final long ARRAY_BASE_OFFSET = UnsafeUtil.getArrayBaseOffset();
/**
* @deprecated Use {@link #computeFixed32SizeNoTag(int)} instead.
*/
@Deprecated
- public static final int LITTLE_ENDIAN_32_SIZE = FIXED_32_SIZE;
+ public static final int LITTLE_ENDIAN_32_SIZE = FIXED32_SIZE;
/**
* The buffer size used in {@link #newInstance(OutputStream)}.
@@ -184,7 +183,7 @@ public abstract class CodedOutputStream extends ByteOutput {
* maps are sorted on the lexicographical order of the UTF8 encoded keys.
* </ul>
*/
- void useDeterministicSerialization() {
+ public void useDeterministicSerialization() {
serializationDeterministic = true;
}
@@ -755,7 +754,7 @@ public abstract class CodedOutputStream extends ByteOutput {
* {@code fixed32} field.
*/
public static int computeFixed32SizeNoTag(@SuppressWarnings("unused") final int unused) {
- return FIXED_32_SIZE;
+ return FIXED32_SIZE;
}
/**
@@ -763,7 +762,7 @@ public abstract class CodedOutputStream extends ByteOutput {
* {@code sfixed32} field.
*/
public static int computeSFixed32SizeNoTag(@SuppressWarnings("unused") final int unused) {
- return FIXED_32_SIZE;
+ return FIXED32_SIZE;
}
/**
@@ -813,7 +812,7 @@ public abstract class CodedOutputStream extends ByteOutput {
* {@code fixed64} field.
*/
public static int computeFixed64SizeNoTag(@SuppressWarnings("unused") final long unused) {
- return FIXED_64_SIZE;
+ return FIXED64_SIZE;
}
/**
@@ -821,7 +820,7 @@ public abstract class CodedOutputStream extends ByteOutput {
* {@code sfixed64} field.
*/
public static int computeSFixed64SizeNoTag(@SuppressWarnings("unused") final long unused) {
- return FIXED_64_SIZE;
+ return FIXED64_SIZE;
}
/**
@@ -829,7 +828,7 @@ public abstract class CodedOutputStream extends ByteOutput {
* {@code float} field, including tag.
*/
public static int computeFloatSizeNoTag(@SuppressWarnings("unused") final float unused) {
- return FIXED_32_SIZE;
+ return FIXED32_SIZE;
}
/**
@@ -837,7 +836,7 @@ public abstract class CodedOutputStream extends ByteOutput {
* {@code double} field, including tag.
*/
public static int computeDoubleSizeNoTag(@SuppressWarnings("unused") final double unused) {
- return FIXED_64_SIZE;
+ return FIXED64_SIZE;
}
/**
@@ -1321,15 +1320,12 @@ public abstract class CodedOutputStream extends ByteOutput {
@Override
public final void writeUInt32NoTag(int value) throws IOException {
if (HAS_UNSAFE_ARRAY_OPERATIONS && spaceLeft() >= MAX_VARINT_SIZE) {
- long pos = ARRAY_BASE_OFFSET + position;
while (true) {
if ((value & ~0x7F) == 0) {
- UnsafeUtil.putByte(buffer, pos++, (byte) value);
- position++;
+ UnsafeUtil.putByte(buffer, position++, (byte) value);
return;
} else {
- UnsafeUtil.putByte(buffer, pos++, (byte) ((value & 0x7F) | 0x80));
- position++;
+ UnsafeUtil.putByte(buffer, position++, (byte) ((value & 0x7F) | 0x80));
value >>>= 7;
}
}
@@ -1367,15 +1363,12 @@ public abstract class CodedOutputStream extends ByteOutput {
@Override
public final void writeUInt64NoTag(long value) throws IOException {
if (HAS_UNSAFE_ARRAY_OPERATIONS && spaceLeft() >= MAX_VARINT_SIZE) {
- long pos = ARRAY_BASE_OFFSET + position;
while (true) {
if ((value & ~0x7FL) == 0) {
- UnsafeUtil.putByte(buffer, pos++, (byte) value);
- position++;
+ UnsafeUtil.putByte(buffer, position++, (byte) value);
return;
} else {
- UnsafeUtil.putByte(buffer, pos++, (byte) (((int) value & 0x7F) | 0x80));
- position++;
+ UnsafeUtil.putByte(buffer, position++, (byte) (((int) value & 0x7F) | 0x80));
value >>>= 7;
}
}
@@ -2030,7 +2023,7 @@ public abstract class CodedOutputStream extends ByteOutput {
@Override
public void writeFixed32NoTag(int value) throws IOException {
buffer.putInt(bufferPos(position), value);
- position += FIXED_32_SIZE;
+ position += FIXED32_SIZE;
}
@Override
@@ -2064,7 +2057,7 @@ public abstract class CodedOutputStream extends ByteOutput {
@Override
public void writeFixed64NoTag(long value) throws IOException {
buffer.putLong(bufferPos(position), value);
- position += FIXED_64_SIZE;
+ position += FIXED64_SIZE;
}
@Override
@@ -2081,8 +2074,7 @@ public abstract class CodedOutputStream extends ByteOutput {
String.format("Pos: %d, limit: %d, len: %d", position, limit, length));
}
- UnsafeUtil.copyMemory(
- value, UnsafeUtil.getArrayBaseOffset() + offset, null, position, length);
+ UnsafeUtil.copyMemory(value, offset, position, length);
position += length;
}
@@ -2249,19 +2241,17 @@ public abstract class CodedOutputStream extends ByteOutput {
*/
final void bufferUInt32NoTag(int value) {
if (HAS_UNSAFE_ARRAY_OPERATIONS) {
- final long originalPos = ARRAY_BASE_OFFSET + position;
- long pos = originalPos;
+ final long originalPos = position;
while (true) {
if ((value & ~0x7F) == 0) {
- UnsafeUtil.putByte(buffer, pos++, (byte) value);
+ UnsafeUtil.putByte(buffer, position++, (byte) value);
break;
} else {
- UnsafeUtil.putByte(buffer, pos++, (byte) ((value & 0x7F) | 0x80));
+ UnsafeUtil.putByte(buffer, position++, (byte) ((value & 0x7F) | 0x80));
value >>>= 7;
}
}
- int delta = (int) (pos - originalPos);
- position += delta;
+ int delta = (int) (position - originalPos);
totalBytesWritten += delta;
} else {
while (true) {
@@ -2284,19 +2274,17 @@ public abstract class CodedOutputStream extends ByteOutput {
*/
final void bufferUInt64NoTag(long value) {
if (HAS_UNSAFE_ARRAY_OPERATIONS) {
- final long originalPos = ARRAY_BASE_OFFSET + position;
- long pos = originalPos;
+ final long originalPos = position;
while (true) {
if ((value & ~0x7FL) == 0) {
- UnsafeUtil.putByte(buffer, pos++, (byte) value);
+ UnsafeUtil.putByte(buffer, position++, (byte) value);
break;
} else {
- UnsafeUtil.putByte(buffer, pos++, (byte) (((int) value & 0x7F) | 0x80));
+ UnsafeUtil.putByte(buffer, position++, (byte) (((int) value & 0x7F) | 0x80));
value >>>= 7;
}
}
- int delta = (int) (pos - originalPos);
- position += delta;
+ int delta = (int) (position - originalPos);
totalBytesWritten += delta;
} else {
while (true) {
@@ -2322,7 +2310,7 @@ public abstract class CodedOutputStream extends ByteOutput {
buffer[position++] = (byte) ((value >> 8) & 0xFF);
buffer[position++] = (byte) ((value >> 16) & 0xFF);
buffer[position++] = (byte) ((value >> 24) & 0xFF);
- totalBytesWritten += FIXED_32_SIZE;
+ totalBytesWritten += FIXED32_SIZE;
}
/**
@@ -2338,7 +2326,7 @@ public abstract class CodedOutputStream extends ByteOutput {
buffer[position++] = (byte) ((int) (value >> 40) & 0xFF);
buffer[position++] = (byte) ((int) (value >> 48) & 0xFF);
buffer[position++] = (byte) ((int) (value >> 56) & 0xFF);
- totalBytesWritten += FIXED_64_SIZE;
+ totalBytesWritten += FIXED64_SIZE;
}
}
@@ -2379,7 +2367,7 @@ public abstract class CodedOutputStream extends ByteOutput {
@Override
public void writeFixed32(final int fieldNumber, final int value) throws IOException {
- flushIfNotAvailable(MAX_VARINT_SIZE + FIXED_32_SIZE);
+ flushIfNotAvailable(MAX_VARINT_SIZE + FIXED32_SIZE);
bufferTag(fieldNumber, WireFormat.WIRETYPE_FIXED32);
bufferFixed32NoTag(value);
}
@@ -2393,7 +2381,7 @@ public abstract class CodedOutputStream extends ByteOutput {
@Override
public void writeFixed64(final int fieldNumber, final long value) throws IOException {
- flushIfNotAvailable(MAX_VARINT_SIZE + FIXED_64_SIZE);
+ flushIfNotAvailable(MAX_VARINT_SIZE + FIXED64_SIZE);
bufferTag(fieldNumber, WireFormat.WIRETYPE_FIXED64);
bufferFixed64NoTag(value);
}
@@ -2519,7 +2507,7 @@ public abstract class CodedOutputStream extends ByteOutput {
@Override
public void writeFixed32NoTag(final int value) throws IOException {
- flushIfNotAvailable(FIXED_32_SIZE);
+ flushIfNotAvailable(FIXED32_SIZE);
bufferFixed32NoTag(value);
}
@@ -2531,7 +2519,7 @@ public abstract class CodedOutputStream extends ByteOutput {
@Override
public void writeFixed64NoTag(final long value) throws IOException {
- flushIfNotAvailable(FIXED_64_SIZE);
+ flushIfNotAvailable(FIXED64_SIZE);
bufferFixed64NoTag(value);
}
@@ -2682,7 +2670,7 @@ public abstract class CodedOutputStream extends ByteOutput {
@Override
public void writeFixed32(final int fieldNumber, final int value) throws IOException {
- flushIfNotAvailable(MAX_VARINT_SIZE + FIXED_32_SIZE);
+ flushIfNotAvailable(MAX_VARINT_SIZE + FIXED32_SIZE);
bufferTag(fieldNumber, WireFormat.WIRETYPE_FIXED32);
bufferFixed32NoTag(value);
}
@@ -2696,7 +2684,7 @@ public abstract class CodedOutputStream extends ByteOutput {
@Override
public void writeFixed64(final int fieldNumber, final long value) throws IOException {
- flushIfNotAvailable(MAX_VARINT_SIZE + FIXED_64_SIZE);
+ flushIfNotAvailable(MAX_VARINT_SIZE + FIXED64_SIZE);
bufferTag(fieldNumber, WireFormat.WIRETYPE_FIXED64);
bufferFixed64NoTag(value);
}
@@ -2822,7 +2810,7 @@ public abstract class CodedOutputStream extends ByteOutput {
@Override
public void writeFixed32NoTag(final int value) throws IOException {
- flushIfNotAvailable(FIXED_32_SIZE);
+ flushIfNotAvailable(FIXED32_SIZE);
bufferFixed32NoTag(value);
}
@@ -2834,7 +2822,7 @@ public abstract class CodedOutputStream extends ByteOutput {
@Override
public void writeFixed64NoTag(final long value) throws IOException {
- flushIfNotAvailable(FIXED_64_SIZE);
+ flushIfNotAvailable(FIXED64_SIZE);
bufferFixed64NoTag(value);
}
diff --git a/java/core/src/main/java/com/google/protobuf/Descriptors.java b/java/core/src/main/java/com/google/protobuf/Descriptors.java
index 38346f15..75b16fe3 100644
--- a/java/core/src/main/java/com/google/protobuf/Descriptors.java
+++ b/java/core/src/main/java/com/google/protobuf/Descriptors.java
@@ -30,9 +30,10 @@
package com.google.protobuf;
+import static com.google.protobuf.Internal.checkNotNull;
+
import com.google.protobuf.DescriptorProtos.*;
import com.google.protobuf.Descriptors.FileDescriptor.Syntax;
-
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
@@ -682,9 +683,7 @@ public final class Descriptors {
/** Determines if the given field name is reserved. */
public boolean isReservedName(final String name) {
- if (name == null) {
- throw new NullPointerException();
- }
+ checkNotNull(name);
for (final String reservedName : proto.getReservedNameList()) {
if (reservedName.equals(name)) {
return true;
diff --git a/java/core/src/main/java/com/google/protobuf/DiscardUnknownFieldsParser.java b/java/core/src/main/java/com/google/protobuf/DiscardUnknownFieldsParser.java
new file mode 100644
index 00000000..7ae94349
--- /dev/null
+++ b/java/core/src/main/java/com/google/protobuf/DiscardUnknownFieldsParser.java
@@ -0,0 +1,71 @@
+// 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.
+
+package com.google.protobuf;
+
+/**
+ * Parsers to discard unknown fields during parsing.
+ */
+public final class DiscardUnknownFieldsParser {
+
+ /**
+ * Warps a given {@link Parser} into a new {@link Parser} that discards unknown fields during
+ * parsing.
+ *
+ * <p>Usage example:
+ * <pre>{@code
+ * private final static Parser<Foo> FOO_PARSER = DiscardUnknownFieldsParser.wrap(Foo.parser());
+ * Foo parseFooDiscardUnknown(ByteBuffer input) throws IOException {
+ * return FOO_PARSER.parseFrom(input);
+ * }
+ * }</pre>
+ *
+ * <p>Like all other implementations of {@code Parser}, this parser is stateless and thread-safe.
+ *
+ * @param parser The delegated parser that parses messages.
+ * @return a {@link Parser} that will discard unknown fields during parsing.
+ */
+ public static final <T extends Message> Parser<T> wrap(final Parser<T> parser) {
+ return new AbstractParser<T>() {
+ @Override
+ public T parsePartialFrom(CodedInputStream input, ExtensionRegistryLite extensionRegistry)
+ throws InvalidProtocolBufferException {
+ try {
+ input.discardUnknownFields();
+ return parser.parsePartialFrom(input, extensionRegistry);
+ } finally {
+ input.unsetDiscardUnknownFields();
+ }
+ }
+ };
+ }
+
+ private DiscardUnknownFieldsParser() {}
+}
diff --git a/java/core/src/main/java/com/google/protobuf/DoubleArrayList.java b/java/core/src/main/java/com/google/protobuf/DoubleArrayList.java
index 6177f3ca..867b85ce 100644
--- a/java/core/src/main/java/com/google/protobuf/DoubleArrayList.java
+++ b/java/core/src/main/java/com/google/protobuf/DoubleArrayList.java
@@ -30,8 +30,9 @@
package com.google.protobuf;
-import com.google.protobuf.Internal.DoubleList;
+import static com.google.protobuf.Internal.checkNotNull;
+import com.google.protobuf.Internal.DoubleList;
import java.util.Arrays;
import java.util.Collection;
import java.util.RandomAccess;
@@ -41,9 +42,8 @@ import java.util.RandomAccess;
*
* @author dweis@google.com (Daniel Weis)
*/
-final class DoubleArrayList
- extends AbstractProtobufList<Double>
- implements DoubleList, RandomAccess {
+final class DoubleArrayList extends AbstractProtobufList<Double>
+ implements DoubleList, RandomAccess, PrimitiveNonBoxingCollection {
private static final DoubleArrayList EMPTY_LIST = new DoubleArrayList();
static {
@@ -199,9 +199,7 @@ final class DoubleArrayList
public boolean addAll(Collection<? extends Double> collection) {
ensureIsMutable();
- if (collection == null) {
- throw new NullPointerException();
- }
+ checkNotNull(collection);
// We specialize when adding another DoubleArrayList to avoid boxing elements.
if (!(collection instanceof DoubleArrayList)) {
diff --git a/java/core/src/main/java/com/google/protobuf/DynamicMessage.java b/java/core/src/main/java/com/google/protobuf/DynamicMessage.java
index e6358c3b..ba532021 100644
--- a/java/core/src/main/java/com/google/protobuf/DynamicMessage.java
+++ b/java/core/src/main/java/com/google/protobuf/DynamicMessage.java
@@ -30,11 +30,12 @@
package com.google.protobuf;
+import static com.google.protobuf.Internal.checkNotNull;
+
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.EnumValueDescriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.Descriptors.OneofDescriptor;
-
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
@@ -589,9 +590,8 @@ public final class DynamicMessage extends AbstractMessage {
@Override
public Builder setUnknownFields(UnknownFieldSet unknownFields) {
- if (getDescriptorForType().getFile().getSyntax()
- == Descriptors.FileDescriptor.Syntax.PROTO3) {
- // Proto3 discards unknown fields.
+ if (getDescriptorForType().getFile().getSyntax() == Descriptors.FileDescriptor.Syntax.PROTO3
+ && CodedInputStream.getProto3DiscardUnknownFieldsDefault()) {
return this;
}
this.unknownFields = unknownFields;
@@ -600,9 +600,8 @@ public final class DynamicMessage extends AbstractMessage {
@Override
public Builder mergeUnknownFields(UnknownFieldSet unknownFields) {
- if (getDescriptorForType().getFile().getSyntax()
- == Descriptors.FileDescriptor.Syntax.PROTO3) {
- // Proto3 discards unknown fields.
+ if (getDescriptorForType().getFile().getSyntax() == Descriptors.FileDescriptor.Syntax.PROTO3
+ && CodedInputStream.getProto3DiscardUnknownFieldsDefault()) {
return this;
}
this.unknownFields =
@@ -631,9 +630,7 @@ public final class DynamicMessage extends AbstractMessage {
/** Verifies that the value is EnumValueDescriptor and matches Enum Type. */
private void ensureSingularEnumValueDescriptor(
FieldDescriptor field, Object value) {
- if (value == null) {
- throw new NullPointerException();
- }
+ checkNotNull(value);
if (!(value instanceof EnumValueDescriptor)) {
throw new IllegalArgumentException(
"DynamicMessage should use EnumValueDescriptor to set Enum Value.");
diff --git a/java/core/src/main/java/com/google/protobuf/Extension.java b/java/core/src/main/java/com/google/protobuf/Extension.java
index 08ec5b45..5df12e64 100644
--- a/java/core/src/main/java/com/google/protobuf/Extension.java
+++ b/java/core/src/main/java/com/google/protobuf/Extension.java
@@ -58,10 +58,7 @@ public abstract class Extension<ContainingType extends MessageLite, Type>
PROTO1,
}
- protected ExtensionType getExtensionType() {
- // TODO(liujisi): make this abstract after we fix proto1.
- return ExtensionType.IMMUTABLE;
- }
+ protected abstract ExtensionType getExtensionType();
/**
* Type of a message extension.
@@ -70,7 +67,7 @@ public abstract class Extension<ContainingType extends MessageLite, Type>
PROTO1,
PROTO2,
}
-
+
/**
* If the extension is a message extension (i.e., getLiteType() == MESSAGE),
* returns the type of the message, otherwise undefined.
diff --git a/java/core/src/main/java/com/google/protobuf/ExtensionRegistryFactory.java b/java/core/src/main/java/com/google/protobuf/ExtensionRegistryFactory.java
index 23174e24..89f7ab9b 100644
--- a/java/core/src/main/java/com/google/protobuf/ExtensionRegistryFactory.java
+++ b/java/core/src/main/java/com/google/protobuf/ExtensionRegistryFactory.java
@@ -34,7 +34,7 @@ import static com.google.protobuf.ExtensionRegistryLite.EMPTY_REGISTRY_LITE;
/**
* A factory object to create instances of {@link ExtensionRegistryLite}.
- *
+ *
* <p>
* This factory detects (via reflection) if the full (non-Lite) protocol buffer libraries
* are available, and if so, the instances returned are actually {@link ExtensionRegistry}.
@@ -82,6 +82,7 @@ final class ExtensionRegistryFactory {
return EMPTY_REGISTRY_LITE;
}
+
static boolean isFullRegistry(ExtensionRegistryLite registry) {
return EXTENSION_REGISTRY_CLASS != null
&& EXTENSION_REGISTRY_CLASS.isAssignableFrom(registry.getClass());
@@ -90,6 +91,6 @@ final class ExtensionRegistryFactory {
private static final ExtensionRegistryLite invokeSubclassFactory(String methodName)
throws Exception {
return (ExtensionRegistryLite) EXTENSION_REGISTRY_CLASS
- .getMethod(methodName).invoke(null);
+ .getDeclaredMethod(methodName).invoke(null);
}
}
diff --git a/java/core/src/main/java/com/google/protobuf/FieldSet.java b/java/core/src/main/java/com/google/protobuf/FieldSet.java
index 5b251743..8a9239ed 100644
--- a/java/core/src/main/java/com/google/protobuf/FieldSet.java
+++ b/java/core/src/main/java/com/google/protobuf/FieldSet.java
@@ -30,8 +30,9 @@
package com.google.protobuf;
-import com.google.protobuf.LazyField.LazyIterator;
+import static com.google.protobuf.Internal.checkNotNull;
+import com.google.protobuf.LazyField.LazyIterator;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
@@ -220,6 +221,7 @@ final class FieldSet<FieldDescriptorType extends
return fields.entrySet().iterator();
}
+
/**
* Useful for implementing
* {@link Message#hasField(Descriptors.FieldDescriptor)}.
@@ -384,9 +386,7 @@ final class FieldSet<FieldDescriptorType extends
*/
private static void verifyType(final WireFormat.FieldType type,
final Object value) {
- if (value == null) {
- throw new NullPointerException();
- }
+ checkNotNull(value);
boolean isValid = false;
switch (type.getJavaType()) {
diff --git a/java/core/src/main/java/com/google/protobuf/FloatArrayList.java b/java/core/src/main/java/com/google/protobuf/FloatArrayList.java
index 90d6154b..76645583 100644
--- a/java/core/src/main/java/com/google/protobuf/FloatArrayList.java
+++ b/java/core/src/main/java/com/google/protobuf/FloatArrayList.java
@@ -30,8 +30,9 @@
package com.google.protobuf;
-import com.google.protobuf.Internal.FloatList;
+import static com.google.protobuf.Internal.checkNotNull;
+import com.google.protobuf.Internal.FloatList;
import java.util.Arrays;
import java.util.Collection;
import java.util.RandomAccess;
@@ -41,9 +42,8 @@ import java.util.RandomAccess;
*
* @author dweis@google.com (Daniel Weis)
*/
-final class FloatArrayList
- extends AbstractProtobufList<Float>
- implements FloatList, RandomAccess {
+final class FloatArrayList extends AbstractProtobufList<Float>
+ implements FloatList, RandomAccess, PrimitiveNonBoxingCollection {
private static final FloatArrayList EMPTY_LIST = new FloatArrayList();
static {
@@ -198,9 +198,7 @@ final class FloatArrayList
public boolean addAll(Collection<? extends Float> collection) {
ensureIsMutable();
- if (collection == null) {
- throw new NullPointerException();
- }
+ checkNotNull(collection);
// We specialize when adding another FloatArrayList to avoid boxing elements.
if (!(collection instanceof FloatArrayList)) {
diff --git a/java/core/src/main/java/com/google/protobuf/GeneratedMessage.java b/java/core/src/main/java/com/google/protobuf/GeneratedMessage.java
index cea05794..60179e37 100644
--- a/java/core/src/main/java/com/google/protobuf/GeneratedMessage.java
+++ b/java/core/src/main/java/com/google/protobuf/GeneratedMessage.java
@@ -854,6 +854,7 @@ public abstract class GeneratedMessage extends AbstractMessage
/** Check if a singular extension is present. */
@Override
+ @SuppressWarnings("unchecked")
public final <Type> boolean hasExtension(final ExtensionLite<MessageType, Type> extensionLite) {
Extension<MessageType, Type> extension = checkNotLite(extensionLite);
@@ -863,6 +864,7 @@ public abstract class GeneratedMessage extends AbstractMessage
/** Get the number of elements in a repeated extension. */
@Override
+ @SuppressWarnings("unchecked")
public final <Type> int getExtensionCount(
final ExtensionLite<MessageType, List<Type>> extensionLite) {
Extension<MessageType, List<Type>> extension = checkNotLite(extensionLite);
@@ -2555,6 +2557,7 @@ public abstract class GeneratedMessage extends AbstractMessage
}
@Override
+ @SuppressWarnings("unchecked")
public Object get(GeneratedMessage message) {
List result = new ArrayList();
for (int i = 0; i < getRepeatedCount(message); i++) {
@@ -2564,6 +2567,7 @@ public abstract class GeneratedMessage extends AbstractMessage
}
@Override
+ @SuppressWarnings("unchecked")
public Object get(Builder builder) {
List result = new ArrayList();
for (int i = 0; i < getRepeatedCount(builder); i++) {
diff --git a/java/core/src/main/java/com/google/protobuf/GeneratedMessageLite.java b/java/core/src/main/java/com/google/protobuf/GeneratedMessageLite.java
index f885b01e..09084646 100644
--- a/java/core/src/main/java/com/google/protobuf/GeneratedMessageLite.java
+++ b/java/core/src/main/java/com/google/protobuf/GeneratedMessageLite.java
@@ -31,9 +31,9 @@
package com.google.protobuf;
import com.google.protobuf.AbstractMessageLite.Builder.LimitedInputStream;
-import com.google.protobuf.GeneratedMessageLite.EqualsVisitor.NotEqualsException;
import com.google.protobuf.Internal.BooleanList;
import com.google.protobuf.Internal.DoubleList;
+import com.google.protobuf.Internal.EnumLiteMap;
import com.google.protobuf.Internal.FloatList;
import com.google.protobuf.Internal.IntList;
import com.google.protobuf.Internal.LongList;
@@ -45,11 +45,13 @@ import java.io.ObjectStreamException;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
+import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
/**
* Lite version of {@link GeneratedMessage}.
@@ -60,6 +62,12 @@ public abstract class GeneratedMessageLite<
MessageType extends GeneratedMessageLite<MessageType, BuilderType>,
BuilderType extends GeneratedMessageLite.Builder<MessageType, BuilderType>>
extends AbstractMessageLite<MessageType, BuilderType> {
+ // BEGIN REGULAR
+ static final boolean ENABLE_EXPERIMENTAL_RUNTIME_AT_BUILD_TIME = false;
+ // END REGULAR
+ // BEGIN EXPERIMENTAL
+ // static final boolean ENABLE_EXPERIMENTAL_RUNTIME_AT_BUILD_TIME = true;
+ // END EXPERIMENTAL
/** For use by generated code only. Lazily initialized to reduce allocations. */
protected UnknownFieldSetLite unknownFields = UnknownFieldSetLite.getDefaultInstance();
@@ -105,14 +113,22 @@ public abstract class GeneratedMessageLite<
@SuppressWarnings("unchecked") // Guaranteed by runtime
@Override
public int hashCode() {
- if (memoizedHashCode == 0) {
- HashCodeVisitor visitor = new HashCodeVisitor();
- visit(visitor, (MessageType) this);
- memoizedHashCode = visitor.hashCode;
- }
+ if (memoizedHashCode != 0) {
+ return memoizedHashCode;
+ }
+ // BEGIN EXPERIMENTAL
+ // memoizedHashCode = Protobuf.getInstance().schemaFor(this).hashCode(this);
+ // return memoizedHashCode;
+ // END EXPERIMENTAL
+ // BEGIN REGULAR
+ HashCodeVisitor visitor = new HashCodeVisitor();
+ visit(visitor, (MessageType) this);
+ memoizedHashCode = visitor.hashCode;
return memoizedHashCode;
+ // END REGULAR
}
+ // BEGIN REGULAR
@SuppressWarnings("unchecked") // Guaranteed by runtime
int hashCode(HashCodeVisitor visitor) {
if (memoizedHashCode == 0) {
@@ -124,6 +140,7 @@ public abstract class GeneratedMessageLite<
}
return memoizedHashCode;
}
+ // END REGULAR
@SuppressWarnings("unchecked") // Guaranteed by isInstance + runtime
@Override
@@ -136,17 +153,22 @@ public abstract class GeneratedMessageLite<
return false;
}
+ // BEGIN EXPERIMENTAL
+ // return Protobuf.getInstance().schemaFor(this).equals(this, (MessageType) other);
+ // END EXPERIMENTAL
+ // BEGIN REGULAR
+
try {
visit(EqualsVisitor.INSTANCE, (MessageType) other);
- } catch (NotEqualsException e) {
+ } catch (EqualsVisitor.NotEqualsException e) {
return false;
}
return true;
+ // END REGULAR
}
- /**
- * Same as {@link #equals(Object)} but throws {@code NotEqualsException}.
- */
+ // BEGIN REGULAR
+ /** Same as {@link #equals(Object)} but throws {@code NotEqualsException}. */
@SuppressWarnings("unchecked") // Guaranteed by isInstance + runtime
boolean equals(EqualsVisitor visitor, MessageLite other) {
if (this == other) {
@@ -160,14 +182,13 @@ public abstract class GeneratedMessageLite<
visit(visitor, (MessageType) other);
return true;
}
+ // END REGULAR
// The general strategy for unknown fields is to use an UnknownFieldSetLite that is treated as
// mutable during the parsing constructor and immutable after. This allows us to avoid
// any unnecessary intermediary allocations while reducing the generated code size.
- /**
- * Lazily initializes unknown fields.
- */
+ /** Lazily initializes unknown fields. */
private final void ensureUnknownFieldsInitialized() {
if (unknownFields == UnknownFieldSetLite.getDefaultInstance()) {
unknownFields = UnknownFieldSetLite.newInstance();
@@ -214,12 +235,27 @@ public abstract class GeneratedMessageLite<
unknownFields.makeImmutable();
}
+ protected final <
+ MessageType extends GeneratedMessageLite<MessageType, BuilderType>,
+ BuilderType extends GeneratedMessageLite.Builder<MessageType, BuilderType>>
+ BuilderType createBuilder() {
+ return (BuilderType) dynamicMethod(MethodToInvoke.NEW_BUILDER);
+ }
+
+ protected final <
+ MessageType extends GeneratedMessageLite<MessageType, BuilderType>,
+ BuilderType extends GeneratedMessageLite.Builder<MessageType, BuilderType>>
+ BuilderType createBuilder(MessageType prototype) {
+ return ((BuilderType) createBuilder()).mergeFrom(prototype);
+ }
+
@Override
public final boolean isInitialized() {
- return dynamicMethod(MethodToInvoke.IS_INITIALIZED, Boolean.TRUE) != null;
+ return isInitialized((MessageType) this, Boolean.TRUE);
}
@Override
+ @SuppressWarnings("unchecked")
public final BuilderType toBuilder() {
BuilderType builder = (BuilderType) dynamicMethod(MethodToInvoke.NEW_BUILDER);
builder.mergeFrom((MessageType) this);
@@ -233,9 +269,13 @@ public abstract class GeneratedMessageLite<
* For use by generated code only.
*/
public static enum MethodToInvoke {
- // Rely on/modify instance state
IS_INITIALIZED,
+ // BEGIN REGULAR
VISIT,
+ // END REGULAR
+ // Rely on/modify instance state
+ GET_MEMOIZED_IS_INITIALIZED,
+ SET_MEMOIZED_IS_INITIALIZED,
MERGE_FROM_STREAM,
MAKE_IMMUTABLE,
@@ -251,25 +291,30 @@ public abstract class GeneratedMessageLite<
* Theses different kinds of operations are required to implement message-level operations for
* builders in the runtime. This method bundles those operations to reduce the generated methods
* count.
+ *
* <ul>
- * <li>{@code MERGE_FROM_STREAM} is parameterized with an {@link CodedInputStream} and
- * {@link ExtensionRegistryLite}. It consumes the input stream, parsing the contents into the
- * returned protocol buffer. If parsing throws an {@link InvalidProtocolBufferException}, the
- * implementation wraps it in a RuntimeException.
- * <li>{@code NEW_INSTANCE} returns a new instance of the protocol buffer that has not yet been
- * made immutable. See {@code MAKE_IMMUTABLE}.
- * <li>{@code IS_INITIALIZED} is parameterized with a {@code Boolean} detailing whether to
- * memoize. It returns {@code null} for false and the default instance for true. We optionally
- * memoize to support the Builder case, where memoization is not desired.
- * <li>{@code NEW_BUILDER} returns a {@code BuilderType} instance.
- * <li>{@code VISIT} is parameterized with a {@code Visitor} and a {@code MessageType} and
- * recursively iterates through the fields side by side between this and the instance.
- * <li>{@code MAKE_IMMUTABLE} sets all internal fields to an immutable state.
+ * <li>{@code MERGE_FROM_STREAM} is parameterized with an {@link CodedInputStream} and {@link
+ * ExtensionRegistryLite}. It consumes the input stream, parsing the contents into the
+ * returned protocol buffer. If parsing throws an {@link InvalidProtocolBufferException},
+ * the implementation wraps it in a RuntimeException.
+ * <li>{@code NEW_INSTANCE} returns a new instance of the protocol buffer that has not yet been
+ * made immutable. See {@code MAKE_IMMUTABLE}.
+ * <li>{@code IS_INITIALIZED} returns {@code null} for false and the default instance for true.
+ * It doesn't use or modify any memoized value.
+ * <li>{@code GET_MEMOIZED_IS_INITIALIZED} returns the memoized {@code isInitialized} byte
+ * value.
+ * <li>{@code SET_MEMOIZED_IS_INITIALIZED} sets the memoized {@code isInitilaized} byte value to
+ * 1 if the first parameter is not null, or to 0 if the first parameter is null.
+ * <li>{@code NEW_BUILDER} returns a {@code BuilderType} instance.
+ * <li>{@code VISIT} is parameterized with a {@code Visitor} and a {@code MessageType} and
+ * recursively iterates through the fields side by side between this and the instance.
+ * <li>{@code MAKE_IMMUTABLE} sets all internal fields to an immutable state.
* </ul>
+ *
* This method, plus the implementation of the Builder, enables the Builder class to be proguarded
* away entirely on Android.
- * <p>
- * For use by generated code only.
+ *
+ * <p>For use by generated code only.
*/
protected abstract Object dynamicMethod(MethodToInvoke method, Object arg0, Object arg1);
@@ -287,14 +332,17 @@ public abstract class GeneratedMessageLite<
return dynamicMethod(method, null, null);
}
+ // BEGIN REGULAR
void visit(Visitor visitor, MessageType other) {
dynamicMethod(MethodToInvoke.VISIT, visitor, other);
unknownFields = visitor.visitUnknownFields(unknownFields, other.unknownFields);
}
+ // END REGULAR
+
+
/**
- * Merge some unknown fields into the {@link UnknownFieldSetLite} for this
- * message.
+ * Merge some unknown fields into the {@link UnknownFieldSetLite} for this message.
*
* <p>For use by generated code only.
*/
@@ -327,7 +375,7 @@ public abstract class GeneratedMessageLite<
if (isBuilt) {
MessageType newInstance =
(MessageType) instance.dynamicMethod(MethodToInvoke.NEW_MUTABLE_INSTANCE);
- newInstance.visit(MergeFromVisitor.INSTANCE, instance);
+ mergeFromInstance(newInstance, instance);
instance = newInstance;
isBuilt = false;
}
@@ -382,10 +430,19 @@ public abstract class GeneratedMessageLite<
/** All subclasses implement this. */
public BuilderType mergeFrom(MessageType message) {
copyOnWrite();
- instance.visit(MergeFromVisitor.INSTANCE, message);
+ mergeFromInstance(instance, message);
return (BuilderType) this;
}
+ private void mergeFromInstance(MessageType dest, MessageType src) {
+ // BEGIN EXPERIMENTAL
+ // Protobuf.getInstance().schemaFor(dest).mergeFrom(dest, src);
+ // END EXPERIMENTAL
+ // BEGIN REGULAR
+ dest.visit(MergeFromVisitor.INSTANCE, src);
+ // END REGULAR
+ }
+
@Override
public MessageType getDefaultInstanceForType() {
return defaultInstance;
@@ -453,6 +510,7 @@ public abstract class GeneratedMessageLite<
*/
protected FieldSet<ExtensionDescriptor> extensions = FieldSet.newFieldSet();
+ @SuppressWarnings("unchecked")
protected final void mergeExtensionFields(final MessageType other) {
if (extensions.isImmutable()) {
extensions = extensions.clone();
@@ -460,11 +518,13 @@ public abstract class GeneratedMessageLite<
extensions.mergeFrom(((ExtendableMessage) other).extensions);
}
+ // BEGIN REGULAR
@Override
final void visit(Visitor visitor, MessageType other) {
super.visit(visitor, other);
extensions = visitor.visitExtensions(extensions, other.extensions);
}
+ // END REGULAR
/**
* Parse an unknown field or an extension. For use by generated code only.
@@ -477,7 +537,8 @@ public abstract class GeneratedMessageLite<
MessageType defaultInstance,
CodedInputStream input,
ExtensionRegistryLite extensionRegistry,
- int tag) throws IOException {
+ int tag)
+ throws IOException {
int fieldNumber = WireFormat.getTagFieldNumber(tag);
// TODO(dweis): How much bytecode would be saved by not requiring the generated code to
@@ -1152,6 +1213,7 @@ public abstract class GeneratedMessageLite<
}
}
+
/**
* Lite equivalent to {@link GeneratedMessage.GeneratedExtension}.
*
@@ -1392,7 +1454,21 @@ public abstract class GeneratedMessageLite<
*/
protected static final <T extends GeneratedMessageLite<T, ?>> boolean isInitialized(
T message, boolean shouldMemoize) {
- return message.dynamicMethod(MethodToInvoke.IS_INITIALIZED, shouldMemoize) != null;
+ byte memoizedIsInitialized =
+ (Byte) message.dynamicMethod(MethodToInvoke.GET_MEMOIZED_IS_INITIALIZED);
+ if (memoizedIsInitialized == 1) {
+ return true;
+ }
+ if (memoizedIsInitialized == 0) {
+ return false;
+ }
+ boolean isInitialized =
+ message.dynamicMethod(MethodToInvoke.IS_INITIALIZED, Boolean.FALSE) != null;
+ if (shouldMemoize) {
+ message.dynamicMethod(
+ MethodToInvoke.SET_MEMOIZED_IS_INITIALIZED, isInitialized ? message : null);
+ }
+ return isInitialized;
}
protected static final <T extends GeneratedMessageLite<T, ?>> void makeImmutable(T message) {
@@ -1527,6 +1603,20 @@ public abstract class GeneratedMessageLite<
// Validates last tag.
protected static <T extends GeneratedMessageLite<T, ?>> T parseFrom(
+ T defaultInstance, ByteBuffer data, ExtensionRegistryLite extensionRegistry)
+ throws InvalidProtocolBufferException {
+ return checkMessageInitialized(
+ parseFrom(defaultInstance, CodedInputStream.newInstance(data), extensionRegistry));
+ }
+
+ // Validates last tag.
+ protected static <T extends GeneratedMessageLite<T, ?>> T parseFrom(
+ T defaultInstance, ByteBuffer data) throws InvalidProtocolBufferException {
+ return parseFrom(defaultInstance, data, ExtensionRegistryLite.getEmptyRegistry());
+ }
+
+ // Validates last tag.
+ protected static <T extends GeneratedMessageLite<T, ?>> T parseFrom(
T defaultInstance, ByteString data)
throws InvalidProtocolBufferException {
return checkMessageInitialized(
@@ -1670,6 +1760,7 @@ public abstract class GeneratedMessageLite<
return message;
}
+ // BEGIN REGULAR
/**
* An abstract visitor that the generated code calls into that we use to implement various
* features. Fields that are not members of oneofs are always visited. Members of a oneof are only
@@ -1693,7 +1784,6 @@ public abstract class GeneratedMessageLite<
Object visitOneofLong(boolean minePresent, Object mine, Object other);
Object visitOneofString(boolean minePresent, Object mine, Object other);
Object visitOneofByteString(boolean minePresent, Object mine, Object other);
- Object visitOneofLazyMessage(boolean minePresent, Object mine, Object other);
Object visitOneofMessage(boolean minePresent, Object mine, Object other);
void visitOneofNotSet(boolean minePresent);
@@ -1701,7 +1791,6 @@ public abstract class GeneratedMessageLite<
* Message fields use null sentinals.
*/
<T extends MessageLite> T visitMessage(T mine, T other);
- LazyFieldLite visitLazyMessage(LazyFieldLite mine, LazyFieldLite other);
<T> ProtobufList<T> visitList(ProtobufList<T> mine, ProtobufList<T> other);
BooleanList visitBooleanList(BooleanList mine, BooleanList other);
@@ -1845,14 +1934,6 @@ public abstract class GeneratedMessageLite<
}
@Override
- public Object visitOneofLazyMessage(boolean minePresent, Object mine, Object other) {
- if (minePresent && mine.equals(other)) {
- return mine;
- }
- throw NOT_EQUALS;
- }
-
- @Override
public Object visitOneofMessage(boolean minePresent, Object mine, Object other) {
if (minePresent && ((GeneratedMessageLite<?, ?>) mine).equals(this, (MessageLite) other)) {
return mine;
@@ -1883,21 +1964,6 @@ public abstract class GeneratedMessageLite<
}
@Override
- public LazyFieldLite visitLazyMessage(
- LazyFieldLite mine, LazyFieldLite other) {
- if (mine == null && other == null) {
- return null;
- }
- if (mine == null || other == null) {
- throw NOT_EQUALS;
- }
- if (mine.equals(other)) {
- return mine;
- }
- throw NOT_EQUALS;
- }
-
- @Override
public <T> ProtobufList<T> visitList(ProtobufList<T> mine, ProtobufList<T> other) {
if (!mine.equals(other)) {
throw NOT_EQUALS;
@@ -1977,13 +2043,13 @@ public abstract class GeneratedMessageLite<
/**
* Implements hashCode by accumulating state.
*/
- private static class HashCodeVisitor implements Visitor {
+ static class HashCodeVisitor implements Visitor {
// The caller must ensure that the visitor is invoked parameterized with this and this such that
// other is this. This is required due to how oneof cases are handled. See the class comment
// on Visitor for more information.
- private int hashCode = 0;
+ int hashCode = 0;
@Override
public boolean visitBoolean(
@@ -2074,12 +2140,6 @@ public abstract class GeneratedMessageLite<
}
@Override
- public Object visitOneofLazyMessage(boolean minePresent, Object mine, Object other) {
- hashCode = (53 * hashCode) + mine.hashCode();
- return mine;
- }
-
- @Override
public Object visitOneofMessage(boolean minePresent, Object mine, Object other) {
return visitMessage((MessageLite) mine, (MessageLite) other);
}
@@ -2108,18 +2168,6 @@ public abstract class GeneratedMessageLite<
}
@Override
- public LazyFieldLite visitLazyMessage(LazyFieldLite mine, LazyFieldLite other) {
- final int protoHash;
- if (mine != null) {
- protoHash = mine.hashCode();
- } else {
- protoHash = 37;
- }
- hashCode = (53 * hashCode) + protoHash;
- return mine;
- }
-
- @Override
public <T> ProtobufList<T> visitList(ProtobufList<T> mine, ProtobufList<T> other) {
hashCode = (53 * hashCode) + mine.hashCode();
return mine;
@@ -2262,13 +2310,6 @@ public abstract class GeneratedMessageLite<
}
@Override
- public Object visitOneofLazyMessage(boolean minePresent, Object mine, Object other) {
- LazyFieldLite lazy = minePresent ? (LazyFieldLite) mine : new LazyFieldLite();
- lazy.merge((LazyFieldLite) other);
- return lazy;
- }
-
- @Override
public Object visitOneofMessage(boolean minePresent, Object mine, Object other) {
if (minePresent) {
return visitMessage((MessageLite) mine, (MessageLite) other);
@@ -2292,17 +2333,6 @@ public abstract class GeneratedMessageLite<
}
@Override
- public LazyFieldLite visitLazyMessage(LazyFieldLite mine, LazyFieldLite other) {
- if (other != null) {
- if (mine == null) {
- mine = new LazyFieldLite();
- }
- mine.merge(other);
- }
- return mine;
- }
-
- @Override
public <T> ProtobufList<T> visitList(ProtobufList<T> mine, ProtobufList<T> other) {
int size = mine.size();
int otherSize = other.size();
@@ -2416,4 +2446,5 @@ public abstract class GeneratedMessageLite<
return mine;
}
}
+ // END REGULAR
}
diff --git a/java/core/src/main/java/com/google/protobuf/GeneratedMessageV3.java b/java/core/src/main/java/com/google/protobuf/GeneratedMessageV3.java
index 2a5d8b50..4acd8f2f 100644
--- a/java/core/src/main/java/com/google/protobuf/GeneratedMessageV3.java
+++ b/java/core/src/main/java/com/google/protobuf/GeneratedMessageV3.java
@@ -30,6 +30,8 @@
package com.google.protobuf;
+import static com.google.protobuf.Internal.checkNotNull;
+
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.EnumDescriptor;
import com.google.protobuf.Descriptors.EnumValueDescriptor;
@@ -41,13 +43,12 @@ import com.google.protobuf.Descriptors.OneofDescriptor;
// class without breaking binary compatibility with old generated code that still subclasses
// the old GeneratedMessageV3 class. To allow these different GeneratedMessageV3V? classes to
// interoperate (e.g., a GeneratedMessageV3V3 object has a message extension field whose class
-// type is GeneratedMessageV3V4), these classes still share a common parent class AbstarctMessage
+// type is GeneratedMessageV3V4), these classes still share a common parent class AbstractMessage
// and are using the same GeneratedMessage.GeneratedExtension class for extension definitions.
// Since this class becomes GeneratedMessageV3V? in opensource, we have to add an import here
// to be able to use GeneratedMessage.GeneratedExtension. The GeneratedExtension definition in
// this file is also excluded from opensource to avoid conflict.
import com.google.protobuf.GeneratedMessage.GeneratedExtension;
-
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectStreamException;
@@ -277,13 +278,30 @@ public abstract class GeneratedMessageV3 extends AbstractMessage
/**
* Called by subclasses to parse an unknown field.
+ *
* @return {@code true} unless the tag is an end-group tag.
*/
protected boolean parseUnknownField(
CodedInputStream input,
UnknownFieldSet.Builder unknownFields,
ExtensionRegistryLite extensionRegistry,
- int tag) throws IOException {
+ int tag)
+ throws IOException {
+ if (input.shouldDiscardUnknownFields()) {
+ return input.skipField(tag);
+ }
+ return unknownFields.mergeFieldFrom(tag, input);
+ }
+
+ protected boolean parseUnknownFieldProto3(
+ CodedInputStream input,
+ UnknownFieldSet.Builder unknownFields,
+ ExtensionRegistryLite extensionRegistry,
+ int tag)
+ throws IOException {
+ if (input.shouldDiscardUnknownFieldsProto3()) {
+ return input.skipField(tag);
+ }
return unknownFields.mergeFieldFrom(tag, input);
}
@@ -340,6 +358,10 @@ public abstract class GeneratedMessageV3 extends AbstractMessage
throw e.unwrapIOException();
}
}
+
+ protected static boolean canUseUnsafe() {
+ return UnsafeUtil.hasUnsafeArrayOperations() && UnsafeUtil.hasUnsafeByteBufferOperations();
+ }
@Override
public void writeTo(final CodedOutputStream output) throws IOException {
@@ -619,17 +641,25 @@ public abstract class GeneratedMessageV3 extends AbstractMessage
return (BuilderType) this;
}
+ protected BuilderType setUnknownFieldsProto3(final UnknownFieldSet unknownFields) {
+ if (CodedInputStream.getProto3DiscardUnknownFieldsDefault()) {
+ return (BuilderType) this;
+ }
+ this.unknownFields = unknownFields;
+ onChanged();
+ return (BuilderType) this;
+ }
+
@Override
public BuilderType mergeUnknownFields(
final UnknownFieldSet unknownFields) {
- this.unknownFields =
+ return setUnknownFields(
UnknownFieldSet.newBuilder(this.unknownFields)
.mergeFrom(unknownFields)
- .build();
- onChanged();
- return (BuilderType) this;
+ .build());
}
+
@Override
public boolean isInitialized() {
for (final FieldDescriptor field : getDescriptorForType().getFields()) {
@@ -666,18 +696,6 @@ public abstract class GeneratedMessageV3 extends AbstractMessage
}
/**
- * Called by subclasses to parse an unknown field.
- * @return {@code true} unless the tag is an end-group tag.
- */
- protected boolean parseUnknownField(
- final CodedInputStream input,
- final UnknownFieldSet.Builder unknownFields,
- final ExtensionRegistryLite extensionRegistry,
- final int tag) throws IOException {
- return unknownFields.mergeFieldFrom(tag, input);
- }
-
- /**
* Implementation of {@link BuilderParent} for giving to our children. This
* small inner class makes it so we don't publicly expose the BuilderParent
* methods.
@@ -866,6 +884,7 @@ public abstract class GeneratedMessageV3 extends AbstractMessage
/** Check if a singular extension is present. */
@Override
+ @SuppressWarnings("unchecked")
public final <Type> boolean hasExtension(final ExtensionLite<MessageType, Type> extensionLite) {
Extension<MessageType, Type> extension = checkNotLite(extensionLite);
@@ -875,6 +894,7 @@ public abstract class GeneratedMessageV3 extends AbstractMessage
/** Get the number of elements in a repeated extension. */
@Override
+ @SuppressWarnings("unchecked")
public final <Type> int getExtensionCount(
final ExtensionLite<MessageType, List<Type>> extensionLite) {
Extension<MessageType, List<Type>> extension = checkNotLite(extensionLite);
@@ -985,8 +1005,23 @@ public abstract class GeneratedMessageV3 extends AbstractMessage
ExtensionRegistryLite extensionRegistry,
int tag) throws IOException {
return MessageReflection.mergeFieldFrom(
- input, unknownFields, extensionRegistry, getDescriptorForType(),
- new MessageReflection.ExtensionAdapter(extensions), tag);
+ input, input.shouldDiscardUnknownFields() ? null : unknownFields, extensionRegistry,
+ getDescriptorForType(), new MessageReflection.ExtensionAdapter(extensions), tag);
+ }
+
+ @Override
+ protected boolean parseUnknownFieldProto3(
+ CodedInputStream input,
+ UnknownFieldSet.Builder unknownFields,
+ ExtensionRegistryLite extensionRegistry,
+ int tag) throws IOException {
+ return MessageReflection.mergeFieldFrom(
+ input,
+ input.shouldDiscardUnknownFieldsProto3() ? null : unknownFields,
+ extensionRegistry,
+ getDescriptorForType(),
+ new MessageReflection.ExtensionAdapter(extensions),
+ tag);
}
@@ -1456,21 +1491,6 @@ public abstract class GeneratedMessageV3 extends AbstractMessage
return super.isInitialized() && extensionsAreInitialized();
}
- /**
- * Called by subclasses to parse an unknown field or an extension.
- * @return {@code true} unless the tag is an end-group tag.
- */
- @Override
- protected boolean parseUnknownField(
- final CodedInputStream input,
- final UnknownFieldSet.Builder unknownFields,
- final ExtensionRegistryLite extensionRegistry,
- final int tag) throws IOException {
- return MessageReflection.mergeFieldFrom(
- input, unknownFields, extensionRegistry, getDescriptorForType(),
- new MessageReflection.BuilderAdapter(this), tag);
- }
-
// ---------------------------------------------------------------
// Reflection
@@ -2219,6 +2239,7 @@ public abstract class GeneratedMessageV3 extends AbstractMessage
}
@Override
+ @SuppressWarnings("unchecked")
public Object get(GeneratedMessageV3 message) {
List result = new ArrayList();
for (int i = 0; i < getRepeatedCount(message); i++) {
@@ -2228,6 +2249,7 @@ public abstract class GeneratedMessageV3 extends AbstractMessage
}
@Override
+ @SuppressWarnings("unchecked")
public Object get(Builder builder) {
List result = new ArrayList();
for (int i = 0; i < getRepeatedCount(builder); i++) {
@@ -2273,7 +2295,7 @@ public abstract class GeneratedMessageV3 extends AbstractMessage
public Object getRepeatedRaw(Builder builder, int index) {
return getRepeated(builder, index);
}
-
+
@Override
public void setRepeated(Builder builder, int index, Object value) {
getMutableMapField(builder).getMutableList().set(index, coerceType((Message) value));
@@ -2674,7 +2696,7 @@ public abstract class GeneratedMessageV3 extends AbstractMessage
return (Extension<MessageType, T>) extension;
}
-
+
protected static int computeStringSize(final int fieldNumber, final Object value) {
if (value instanceof String) {
return CodedOutputStream.computeStringSize(fieldNumber, (String) value);
@@ -2682,7 +2704,7 @@ public abstract class GeneratedMessageV3 extends AbstractMessage
return CodedOutputStream.computeBytesSize(fieldNumber, (ByteString) value);
}
}
-
+
protected static int computeStringSizeNoTag(final Object value) {
if (value instanceof String) {
return CodedOutputStream.computeStringSizeNoTag((String) value);
@@ -2690,7 +2712,7 @@ public abstract class GeneratedMessageV3 extends AbstractMessage
return CodedOutputStream.computeBytesSizeNoTag((ByteString) value);
}
}
-
+
protected static void writeString(
CodedOutputStream output, final int fieldNumber, final Object value) throws IOException {
if (value instanceof String) {
@@ -2699,7 +2721,7 @@ public abstract class GeneratedMessageV3 extends AbstractMessage
output.writeBytes(fieldNumber, (ByteString) value);
}
}
-
+
protected static void writeStringNoTag(
CodedOutputStream output, final Object value) throws IOException {
if (value instanceof String) {
@@ -2836,3 +2858,4 @@ public abstract class GeneratedMessageV3 extends AbstractMessage
}
}
}
+
diff --git a/java/core/src/main/java/com/google/protobuf/IntArrayList.java b/java/core/src/main/java/com/google/protobuf/IntArrayList.java
index 2f526e3f..aff5c21b 100644
--- a/java/core/src/main/java/com/google/protobuf/IntArrayList.java
+++ b/java/core/src/main/java/com/google/protobuf/IntArrayList.java
@@ -30,8 +30,9 @@
package com.google.protobuf;
-import com.google.protobuf.Internal.IntList;
+import static com.google.protobuf.Internal.checkNotNull;
+import com.google.protobuf.Internal.IntList;
import java.util.Arrays;
import java.util.Collection;
import java.util.RandomAccess;
@@ -41,9 +42,8 @@ import java.util.RandomAccess;
*
* @author dweis@google.com (Daniel Weis)
*/
-final class IntArrayList
- extends AbstractProtobufList<Integer>
- implements IntList, RandomAccess {
+final class IntArrayList extends AbstractProtobufList<Integer>
+ implements IntList, RandomAccess, PrimitiveNonBoxingCollection {
private static final IntArrayList EMPTY_LIST = new IntArrayList();
static {
@@ -198,9 +198,7 @@ final class IntArrayList
public boolean addAll(Collection<? extends Integer> collection) {
ensureIsMutable();
- if (collection == null) {
- throw new NullPointerException();
- }
+ checkNotNull(collection);
// We specialize when adding another IntArrayList to avoid boxing elements.
if (!(collection instanceof IntArrayList)) {
diff --git a/java/core/src/main/java/com/google/protobuf/Internal.java b/java/core/src/main/java/com/google/protobuf/Internal.java
index c234559c..848cad03 100644
--- a/java/core/src/main/java/com/google/protobuf/Internal.java
+++ b/java/core/src/main/java/com/google/protobuf/Internal.java
@@ -62,6 +62,16 @@ public final class Internal {
/**
* Throws an appropriate {@link NullPointerException} if the given objects is {@code null}.
*/
+ static <T> T checkNotNull(T obj) {
+ if (obj == null) {
+ throw new NullPointerException();
+ }
+ return obj;
+ }
+
+ /**
+ * Throws an appropriate {@link NullPointerException} if the given objects is {@code null}.
+ */
static <T> T checkNotNull(T obj, String message) {
if (obj == null) {
throw new NullPointerException(message);
@@ -404,9 +414,8 @@ public final class Internal {
}
}
- /**
- * An empty byte array constant used in generated code.
- */
+
+ /** An empty byte array constant used in generated code. */
public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
/**
@@ -420,6 +429,11 @@ public final class Internal {
CodedInputStream.newInstance(EMPTY_BYTE_ARRAY);
+ /** Helper method to merge two MessageLite instances. */
+ static Object mergeMessage(Object destination, Object source) {
+ return ((MessageLite) destination).toBuilder().mergeFrom((MessageLite) source).buildPartial();
+ }
+
/**
* Provides an immutable view of {@code List<T>} around a {@code List<F>}.
*
diff --git a/java/core/src/main/java/com/google/protobuf/InvalidProtocolBufferException.java b/java/core/src/main/java/com/google/protobuf/InvalidProtocolBufferException.java
index 55e33d21..510c6aac 100644
--- a/java/core/src/main/java/com/google/protobuf/InvalidProtocolBufferException.java
+++ b/java/core/src/main/java/com/google/protobuf/InvalidProtocolBufferException.java
@@ -50,6 +50,10 @@ public class InvalidProtocolBufferException extends IOException {
super(e.getMessage(), e);
}
+ public InvalidProtocolBufferException(final String description, IOException e) {
+ super(description, e);
+ }
+
/**
* Attaches an unfinished message to the exception to support best-effort
* parsing in {@code Parser} interface.
diff --git a/java/core/src/main/java/com/google/protobuf/IterableByteBufferInputStream.java b/java/core/src/main/java/com/google/protobuf/IterableByteBufferInputStream.java
new file mode 100644
index 00000000..713e8064
--- /dev/null
+++ b/java/core/src/main/java/com/google/protobuf/IterableByteBufferInputStream.java
@@ -0,0 +1,150 @@
+// 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.
+
+package com.google.protobuf;
+
+import static com.google.protobuf.Internal.EMPTY_BYTE_BUFFER;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.ByteBuffer;
+import java.util.Iterator;
+
+class IterableByteBufferInputStream extends InputStream {
+ /** The {@link Iterator} with type {@link ByteBuffer} of {@code input} */
+ private Iterator<ByteBuffer> iterator;
+ /** The current ByteBuffer; */
+ private ByteBuffer currentByteBuffer;
+ /** The number of ByteBuffers in the input data. */
+ private int dataSize;
+ /**
+ * Current {@code ByteBuffer}'s index
+ *
+ * <p>If index equals dataSize, then all the data in the InputStream has been consumed
+ */
+ private int currentIndex;
+ /** The current position for current ByteBuffer */
+ private int currentByteBufferPos;
+ /** Whether current ByteBuffer has an array */
+ private boolean hasArray;
+ /**
+ * If the current ByteBuffer is unsafe-direct based, currentArray is null; otherwise should be the
+ * array inside ByteBuffer.
+ */
+ private byte[] currentArray;
+ /** Current ByteBuffer's array offset */
+ private int currentArrayOffset;
+ /**
+ * If the current ByteBuffer is unsafe-direct based, currentAddress is the start address of this
+ * ByteBuffer; otherwise should be zero.
+ */
+ private long currentAddress;
+
+ IterableByteBufferInputStream(Iterable<ByteBuffer> data) {
+ iterator = data.iterator();
+ dataSize = 0;
+ for (ByteBuffer unused : data) {
+ dataSize++;
+ }
+ currentIndex = -1;
+
+ if (!getNextByteBuffer()) {
+ currentByteBuffer = EMPTY_BYTE_BUFFER;
+ currentIndex = 0;
+ currentByteBufferPos = 0;
+ currentAddress = 0;
+ }
+ }
+
+ private boolean getNextByteBuffer() {
+ currentIndex++;
+ if (!iterator.hasNext()) {
+ return false;
+ }
+ currentByteBuffer = iterator.next();
+ currentByteBufferPos = currentByteBuffer.position();
+ if (currentByteBuffer.hasArray()) {
+ hasArray = true;
+ currentArray = currentByteBuffer.array();
+ currentArrayOffset = currentByteBuffer.arrayOffset();
+ } else {
+ hasArray = false;
+ currentAddress = UnsafeUtil.addressOffset(currentByteBuffer);
+ currentArray = null;
+ }
+ return true;
+ }
+
+ private void updateCurrentByteBufferPos(int numberOfBytesRead) {
+ currentByteBufferPos += numberOfBytesRead;
+ if (currentByteBufferPos == currentByteBuffer.limit()) {
+ getNextByteBuffer();
+ }
+ }
+
+ @Override
+ public int read() throws IOException {
+ if (currentIndex == dataSize) {
+ return -1;
+ }
+ if (hasArray) {
+ int result = currentArray[currentByteBufferPos + currentArrayOffset] & 0xFF;
+ updateCurrentByteBufferPos(1);
+ return result;
+ } else {
+ int result = UnsafeUtil.getByte(currentByteBufferPos + currentAddress) & 0xFF;
+ updateCurrentByteBufferPos(1);
+ return result;
+ }
+ }
+
+ @Override
+ public int read(byte[] output, int offset, int length) throws IOException {
+ if (currentIndex == dataSize) {
+ return -1;
+ }
+ int remaining = currentByteBuffer.limit() - currentByteBufferPos;
+ if (length > remaining) {
+ length = remaining;
+ }
+ if (hasArray) {
+ System.arraycopy(
+ currentArray, currentByteBufferPos + currentArrayOffset, output, offset, length);
+ updateCurrentByteBufferPos(length);
+ } else {
+ int prevPos = currentByteBuffer.position();
+ currentByteBuffer.position(currentByteBufferPos);
+ currentByteBuffer.get(output, offset, length);
+ currentByteBuffer.position(prevPos);
+ updateCurrentByteBufferPos(length);
+ }
+ return length;
+ }
+}
diff --git a/java/core/src/main/java/com/google/protobuf/LazyFieldLite.java b/java/core/src/main/java/com/google/protobuf/LazyFieldLite.java
index 4b0ba0fd..49ecfc0b 100644
--- a/java/core/src/main/java/com/google/protobuf/LazyFieldLite.java
+++ b/java/core/src/main/java/com/google/protobuf/LazyFieldLite.java
@@ -394,6 +394,7 @@ public class LazyFieldLite {
}
}
+
/**
* Might lazily parse the bytes that were previously passed in. Is thread-safe.
*/
diff --git a/java/core/src/main/java/com/google/protobuf/LongArrayList.java b/java/core/src/main/java/com/google/protobuf/LongArrayList.java
index 5a772e3a..fc146e23 100644
--- a/java/core/src/main/java/com/google/protobuf/LongArrayList.java
+++ b/java/core/src/main/java/com/google/protobuf/LongArrayList.java
@@ -30,8 +30,9 @@
package com.google.protobuf;
-import com.google.protobuf.Internal.LongList;
+import static com.google.protobuf.Internal.checkNotNull;
+import com.google.protobuf.Internal.LongList;
import java.util.Arrays;
import java.util.Collection;
import java.util.RandomAccess;
@@ -41,9 +42,8 @@ import java.util.RandomAccess;
*
* @author dweis@google.com (Daniel Weis)
*/
-final class LongArrayList
- extends AbstractProtobufList<Long>
- implements LongList, RandomAccess {
+final class LongArrayList extends AbstractProtobufList<Long>
+ implements LongList, RandomAccess, PrimitiveNonBoxingCollection {
private static final LongArrayList EMPTY_LIST = new LongArrayList();
static {
@@ -198,9 +198,7 @@ final class LongArrayList
public boolean addAll(Collection<? extends Long> collection) {
ensureIsMutable();
- if (collection == null) {
- throw new NullPointerException();
- }
+ checkNotNull(collection);
// We specialize when adding another LongArrayList to avoid boxing elements.
if (!(collection instanceof LongArrayList)) {
diff --git a/java/core/src/main/java/com/google/protobuf/MapEntry.java b/java/core/src/main/java/com/google/protobuf/MapEntry.java
index 179c3348..0849b821 100644
--- a/java/core/src/main/java/com/google/protobuf/MapEntry.java
+++ b/java/core/src/main/java/com/google/protobuf/MapEntry.java
@@ -33,7 +33,6 @@ package com.google.protobuf;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.EnumValueDescriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
-
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
@@ -89,6 +88,7 @@ public final class MapEntry<K, V> extends AbstractMessage {
}
/** Create a MapEntry with the provided key and value. */
+ @SuppressWarnings("unchecked")
private MapEntry(Metadata metadata, K key, V value) {
this.key = key;
this.value = value;
@@ -170,7 +170,7 @@ public final class MapEntry<K, V> extends AbstractMessage {
@Override
public Builder<K, V> toBuilder() {
- return new Builder<K, V>(metadata, key, value);
+ return new Builder<K, V>(metadata, key, value, true, true);
}
@Override
@@ -246,15 +246,19 @@ public final class MapEntry<K, V> extends AbstractMessage {
private final Metadata<K, V> metadata;
private K key;
private V value;
+ private boolean hasKey;
+ private boolean hasValue;
private Builder(Metadata<K, V> metadata) {
- this(metadata, metadata.defaultKey, metadata.defaultValue);
+ this(metadata, metadata.defaultKey, metadata.defaultValue, false, false);
}
- private Builder(Metadata<K, V> metadata, K key, V value) {
+ private Builder(Metadata<K, V> metadata, K key, V value, boolean hasKey, boolean hasValue) {
this.metadata = metadata;
this.key = key;
this.value = value;
+ this.hasKey = hasKey;
+ this.hasValue = hasValue;
}
public K getKey() {
@@ -267,21 +271,25 @@ public final class MapEntry<K, V> extends AbstractMessage {
public Builder<K, V> setKey(K key) {
this.key = key;
+ this.hasKey = true;
return this;
}
public Builder<K, V> clearKey() {
this.key = metadata.defaultKey;
+ this.hasKey = false;
return this;
}
public Builder<K, V> setValue(V value) {
this.value = value;
+ this.hasValue = true;
return this;
}
public Builder<K, V> clearValue() {
this.value = metadata.defaultValue;
+ this.hasValue = false;
return this;
}
@@ -403,7 +411,7 @@ public final class MapEntry<K, V> extends AbstractMessage {
@Override
public boolean hasField(FieldDescriptor field) {
checkFieldDescriptor(field);
- return true;
+ return field.getNumber() == 1 ? hasKey : hasValue;
}
@Override
@@ -435,8 +443,9 @@ public final class MapEntry<K, V> extends AbstractMessage {
}
@Override
+ @SuppressWarnings("unchecked")
public Builder<K, V> clone() {
- return new Builder(metadata, key, value);
+ return new Builder(metadata, key, value, hasKey, hasValue);
}
}
@@ -446,4 +455,9 @@ public final class MapEntry<K, V> extends AbstractMessage {
}
return true;
}
+
+ /** Returns the metadata only for experimental runtime. */
+ final Metadata<K, V> getMetadata() {
+ return metadata;
+ }
}
diff --git a/java/core/src/main/java/com/google/protobuf/MapEntryLite.java b/java/core/src/main/java/com/google/protobuf/MapEntryLite.java
index 22aef8f9..dcb5dfad 100644
--- a/java/core/src/main/java/com/google/protobuf/MapEntryLite.java
+++ b/java/core/src/main/java/com/google/protobuf/MapEntryLite.java
@@ -223,4 +223,9 @@ public class MapEntryLite<K, V> {
input.popLimit(oldLimit);
map.put(key, value);
}
+
+ /** For experimental runtime internal use only. */
+ Metadata<K, V> getMetadata() {
+ return metadata;
+ }
}
diff --git a/java/core/src/main/java/com/google/protobuf/MapField.java b/java/core/src/main/java/com/google/protobuf/MapField.java
index a6109f98..ad8ceb02 100644
--- a/java/core/src/main/java/com/google/protobuf/MapField.java
+++ b/java/core/src/main/java/com/google/protobuf/MapField.java
@@ -30,6 +30,8 @@
package com.google.protobuf;
+import static com.google.protobuf.Internal.checkNotNull;
+
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@@ -100,6 +102,7 @@ public class MapField<K, V> implements MutabilityOracle {
}
@Override
+ @SuppressWarnings("unchecked")
public void convertMessageToKeyAndValue(Message message, Map<K, V> map) {
MapEntry<K, V> entry = (MapEntry<K, V>) message;
map.put(entry.getKey(), entry.getValue());
@@ -328,6 +331,8 @@ public class MapField<K, V> implements MutabilityOracle {
@Override
public V put(K key, V value) {
mutabilityOracle.ensureMutable();
+ checkNotNull(key);
+ checkNotNull(value);
return delegate.put(key, value);
}
@@ -340,6 +345,10 @@ public class MapField<K, V> implements MutabilityOracle {
@Override
public void putAll(Map<? extends K, ? extends V> m) {
mutabilityOracle.ensureMutable();
+ for (K key : m.keySet()) {
+ checkNotNull(key);
+ checkNotNull(m.get(key));
+ }
delegate.putAll(m);
}
diff --git a/java/core/src/main/java/com/google/protobuf/MapFieldLite.java b/java/core/src/main/java/com/google/protobuf/MapFieldLite.java
index 16b3fefe..a8b3dd88 100644
--- a/java/core/src/main/java/com/google/protobuf/MapFieldLite.java
+++ b/java/core/src/main/java/com/google/protobuf/MapFieldLite.java
@@ -30,8 +30,9 @@
package com.google.protobuf;
-import com.google.protobuf.Internal.EnumLite;
+import static com.google.protobuf.Internal.checkNotNull;
+import com.google.protobuf.Internal.EnumLite;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
@@ -83,11 +84,14 @@ public final class MapFieldLite<K, V> extends LinkedHashMap<K, V> {
@Override public void clear() {
ensureMutable();
- clear();
+ super.clear();
}
@Override public V put(K key, V value) {
ensureMutable();
+ checkNotNull(key);
+
+ checkNotNull(value);
return super.put(key, value);
}
@@ -97,6 +101,7 @@ public final class MapFieldLite<K, V> extends LinkedHashMap<K, V> {
@Override public void putAll(Map<? extends K, ? extends V> m) {
ensureMutable();
+ checkForNullKeysAndValues(m);
super.putAll(m);
}
@@ -105,6 +110,13 @@ public final class MapFieldLite<K, V> extends LinkedHashMap<K, V> {
return super.remove(key);
}
+ private static void checkForNullKeysAndValues(Map<?, ?> m) {
+ for (Object key : m.keySet()) {
+ checkNotNull(key);
+ checkNotNull(m.get(key));
+ }
+ }
+
private static boolean equals(Object a, Object b) {
if (a instanceof byte[] && b instanceof byte[]) {
return Arrays.equals((byte[]) a, (byte[]) b);
diff --git a/java/core/src/main/java/com/google/protobuf/Message.java b/java/core/src/main/java/com/google/protobuf/Message.java
index 94590fb9..0770d417 100644
--- a/java/core/src/main/java/com/google/protobuf/Message.java
+++ b/java/core/src/main/java/com/google/protobuf/Message.java
@@ -125,7 +125,7 @@ public interface Message extends MessageLite, MessageOrBuilder {
* it is merged into the corresponding sub-message of this message
* using the same merging rules.<br>
* * For repeated fields, the elements in {@code other} are concatenated
- * with the elements in this message.
+ * with the elements in this message.<br>
* * For oneof groups, if the other message has one of the fields set,
* the group of this message is cleared and replaced by the field
* of the other message, so that the oneof constraint is preserved.
diff --git a/java/core/src/main/java/com/google/protobuf/MessageReflection.java b/java/core/src/main/java/com/google/protobuf/MessageReflection.java
index 3d73efb3..69ad7ddf 100644
--- a/java/core/src/main/java/com/google/protobuf/MessageReflection.java
+++ b/java/core/src/main/java/com/google/protobuf/MessageReflection.java
@@ -31,7 +31,6 @@
package com.google.protobuf;
import com.google.protobuf.Descriptors.FieldDescriptor;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@@ -714,12 +713,14 @@ class MessageReflection {
}
/**
- * Parses a single field into MergeTarget. The target can be Message.Builder,
- * FieldSet or MutableMessage.
+ * Parses a single field into MergeTarget. The target can be Message.Builder, FieldSet or
+ * MutableMessage.
*
- * Package-private because it is used by GeneratedMessage.ExtendableMessage.
+ * <p>Package-private because it is used by GeneratedMessage.ExtendableMessage.
*
* @param tag The tag, which should have already been read.
+ * @param unknownFields If not null, unknown fields will be merged to this {@link
+ * UnknownFieldSet}, otherwise unknown fields will be discarded.
* @return {@code true} unless the tag is an end-group tag.
*/
static boolean mergeFieldFrom(
@@ -728,7 +729,8 @@ class MessageReflection {
ExtensionRegistryLite extensionRegistry,
Descriptors.Descriptor type,
MergeTarget target,
- int tag) throws IOException {
+ int tag)
+ throws IOException {
if (type.getOptions().getMessageSetWireFormat() &&
tag == WireFormat.MESSAGE_SET_ITEM_TAG) {
mergeMessageSetExtensionFromCodedStream(
@@ -792,7 +794,11 @@ class MessageReflection {
}
if (unknown) { // Unknown field or wrong wire type. Skip.
- return unknownFields.mergeFieldFrom(tag, input);
+ if (unknownFields != null) {
+ return unknownFields.mergeFieldFrom(tag, input);
+ } else {
+ return input.skipField(tag);
+ }
}
if (packed) {
@@ -844,7 +850,9 @@ class MessageReflection {
// If the number isn't recognized as a valid value for this enum,
// drop it.
if (value == null) {
- unknownFields.mergeVarintField(fieldNumber, rawValue);
+ if (unknownFields != null) {
+ unknownFields.mergeVarintField(fieldNumber, rawValue);
+ }
return true;
}
}
@@ -947,7 +955,7 @@ class MessageReflection {
mergeMessageSetExtensionFromBytes(
rawBytes, extension, extensionRegistry, target);
} else { // We don't know how to parse this. Ignore it.
- if (rawBytes != null) {
+ if (rawBytes != null && unknownFields != null) {
unknownFields.mergeField(typeId, UnknownFieldSet.Field.newBuilder()
.addLengthDelimited(rawBytes).build());
}
diff --git a/java/core/src/main/java/com/google/protobuf/Parser.java b/java/core/src/main/java/com/google/protobuf/Parser.java
index cfbcb442..e07c6895 100644
--- a/java/core/src/main/java/com/google/protobuf/Parser.java
+++ b/java/core/src/main/java/com/google/protobuf/Parser.java
@@ -31,6 +31,7 @@
package com.google.protobuf;
import java.io.InputStream;
+import java.nio.ByteBuffer;
/**
* Abstract interface for parsing Protocol Messages.
@@ -93,6 +94,18 @@ public interface Parser<MessageType> {
// Convenience methods.
/**
+ * Parses {@code data} as a message of {@code MessageType}. This is just a small wrapper around
+ * {@link #parseFrom(CodedInputStream)}.
+ */
+ public MessageType parseFrom(ByteBuffer data) throws InvalidProtocolBufferException;
+
+ /**
+ * Parses {@code data} as a message of {@code MessageType}. This is just a small wrapper around
+ * {@link #parseFrom(CodedInputStream, ExtensionRegistryLite)}.
+ */
+ public MessageType parseFrom(ByteBuffer data, ExtensionRegistryLite extensionRegistry)
+ throws InvalidProtocolBufferException;
+ /**
* Parses {@code data} as a message of {@code MessageType}.
* This is just a small wrapper around {@link #parseFrom(CodedInputStream)}.
*/
diff --git a/java/core/src/main/java/com/google/protobuf/PrimitiveNonBoxingCollection.java b/java/core/src/main/java/com/google/protobuf/PrimitiveNonBoxingCollection.java
new file mode 100644
index 00000000..79b5769d
--- /dev/null
+++ b/java/core/src/main/java/com/google/protobuf/PrimitiveNonBoxingCollection.java
@@ -0,0 +1,34 @@
+// 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.
+
+package com.google.protobuf;
+
+/** A marker interface indicating that the collection supports primitives and is non-boxing. */
+interface PrimitiveNonBoxingCollection {}
diff --git a/java/core/src/main/java/com/google/protobuf/RepeatedFieldBuilderV3.java b/java/core/src/main/java/com/google/protobuf/RepeatedFieldBuilderV3.java
index 77b61b5f..30c991d4 100644
--- a/java/core/src/main/java/com/google/protobuf/RepeatedFieldBuilderV3.java
+++ b/java/core/src/main/java/com/google/protobuf/RepeatedFieldBuilderV3.java
@@ -30,6 +30,8 @@
package com.google.protobuf;
+import static com.google.protobuf.Internal.checkNotNull;
+
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collection;
@@ -290,9 +292,7 @@ public class RepeatedFieldBuilderV3
*/
public RepeatedFieldBuilderV3<MType, BType, IType> setMessage(
int index, MType message) {
- if (message == null) {
- throw new NullPointerException();
- }
+ checkNotNull(message);
ensureMutableMessageList();
messages.set(index, message);
if (builders != null) {
@@ -315,9 +315,7 @@ public class RepeatedFieldBuilderV3
*/
public RepeatedFieldBuilderV3<MType, BType, IType> addMessage(
MType message) {
- if (message == null) {
- throw new NullPointerException();
- }
+ checkNotNull(message);
ensureMutableMessageList();
messages.add(message);
if (builders != null) {
@@ -339,9 +337,7 @@ public class RepeatedFieldBuilderV3
*/
public RepeatedFieldBuilderV3<MType, BType, IType> addMessage(
int index, MType message) {
- if (message == null) {
- throw new NullPointerException();
- }
+ checkNotNull(message);
ensureMutableMessageList();
messages.add(index, message);
if (builders != null) {
@@ -363,9 +359,7 @@ public class RepeatedFieldBuilderV3
public RepeatedFieldBuilderV3<MType, BType, IType> addAllMessages(
Iterable<? extends MType> values) {
for (final MType value : values) {
- if (value == null) {
- throw new NullPointerException();
- }
+ checkNotNull(value);
}
// If we can inspect the size, we can more efficiently add messages.
diff --git a/java/core/src/main/java/com/google/protobuf/SingleFieldBuilderV3.java b/java/core/src/main/java/com/google/protobuf/SingleFieldBuilderV3.java
index fb1f76a7..8ab0f26d 100644
--- a/java/core/src/main/java/com/google/protobuf/SingleFieldBuilderV3.java
+++ b/java/core/src/main/java/com/google/protobuf/SingleFieldBuilderV3.java
@@ -30,6 +30,8 @@
package com.google.protobuf;
+import static com.google.protobuf.Internal.checkNotNull;
+
/**
* {@code SingleFieldBuilderV3} implements a structure that a protocol
* message uses to hold a single field of another protocol message. It supports
@@ -84,10 +86,7 @@ public class SingleFieldBuilderV3
MType message,
AbstractMessage.BuilderParent parent,
boolean isClean) {
- if (message == null) {
- throw new NullPointerException();
- }
- this.message = message;
+ this.message = checkNotNull(message);
this.parent = parent;
this.isClean = isClean;
}
@@ -169,10 +168,7 @@ public class SingleFieldBuilderV3
*/
public SingleFieldBuilderV3<MType, BType, IType> setMessage(
MType message) {
- if (message == null) {
- throw new NullPointerException();
- }
- this.message = message;
+ this.message = checkNotNull(message);
if (builder != null) {
builder.dispose();
builder = null;
diff --git a/java/core/src/main/java/com/google/protobuf/SmallSortedMap.java b/java/core/src/main/java/com/google/protobuf/SmallSortedMap.java
index 409fec10..279edc4d 100644
--- a/java/core/src/main/java/com/google/protobuf/SmallSortedMap.java
+++ b/java/core/src/main/java/com/google/protobuf/SmallSortedMap.java
@@ -197,6 +197,7 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> {
overflowEntries.entrySet();
}
+
@Override
public int size() {
return entryList.size() + overflowEntries.size();
@@ -356,6 +357,7 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> {
return lazyEntrySet;
}
+
/**
* @throws UnsupportedOperationException if {@link #makeImmutable()} has
* has been called.
@@ -525,6 +527,7 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> {
}
}
+
/**
* Iterator implementation that switches from the entry array to the overflow
* entries appropriately.
@@ -537,8 +540,8 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> {
@Override
public boolean hasNext() {
- return (pos + 1) < entryList.size() ||
- getOverflowIterator().hasNext();
+ return (pos + 1) < entryList.size()
+ || (!overflowEntries.isEmpty() && getOverflowIterator().hasNext());
}
@Override
@@ -617,43 +620,43 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> {
return (Iterable<T>) ITERABLE;
}
}
-
+
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
-
+
if (!(o instanceof SmallSortedMap)) {
return super.equals(o);
}
-
+
SmallSortedMap<?, ?> other = (SmallSortedMap<?, ?>) o;
final int size = size();
if (size != other.size()) {
return false;
}
-
+
// Best effort try to avoid allocating an entry set.
final int numArrayEntries = getNumArrayEntries();
if (numArrayEntries != other.getNumArrayEntries()) {
return entrySet().equals(other.entrySet());
}
-
+
for (int i = 0; i < numArrayEntries; i++) {
if (!getArrayEntryAt(i).equals(other.getArrayEntryAt(i))) {
return false;
}
}
-
+
if (numArrayEntries != size) {
return overflowEntries.equals(other.overflowEntries);
}
-
-
+
+
return true;
}
-
+
@Override
public int hashCode() {
int h = 0;
diff --git a/java/core/src/main/java/com/google/protobuf/TextFormat.java b/java/core/src/main/java/com/google/protobuf/TextFormat.java
index 49708242..ab9acf2f 100644
--- a/java/core/src/main/java/com/google/protobuf/TextFormat.java
+++ b/java/core/src/main/java/com/google/protobuf/TextFormat.java
@@ -34,7 +34,6 @@ import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.EnumDescriptor;
import com.google.protobuf.Descriptors.EnumValueDescriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
-
import java.io.IOException;
import java.math.BigInteger;
import java.nio.CharBuffer;
@@ -56,14 +55,7 @@ import java.util.regex.Pattern;
public final class TextFormat {
private TextFormat() {}
- private static final Logger logger =
- Logger.getLogger(TextFormat.class.getName());
-
- private static final Printer DEFAULT_PRINTER = new Printer();
- private static final Printer SINGLE_LINE_PRINTER =
- (new Printer()).setSingleLineMode(true);
- private static final Printer UNICODE_PRINTER =
- (new Printer()).setEscapeNonAscii(false);
+ private static final Logger logger = Logger.getLogger(TextFormat.class.getName());
/**
* Outputs a textual representation of the Protocol Message supplied into
@@ -73,14 +65,14 @@ public final class TextFormat {
public static void print(
final MessageOrBuilder message, final Appendable output)
throws IOException {
- DEFAULT_PRINTER.print(message, new TextGenerator(output));
+ Printer.DEFAULT.print(message, multiLineOutput(output));
}
/** Outputs a textual representation of {@code fields} to {@code output}. */
public static void print(final UnknownFieldSet fields,
final Appendable output)
throws IOException {
- DEFAULT_PRINTER.printUnknownFields(fields, new TextGenerator(output));
+ Printer.DEFAULT.printUnknownFields(fields, multiLineOutput(output));
}
/**
@@ -90,7 +82,7 @@ public final class TextFormat {
public static void printUnicode(
final MessageOrBuilder message, final Appendable output)
throws IOException {
- UNICODE_PRINTER.print(message, new TextGenerator(output));
+ Printer.UNICODE.print(message, multiLineOutput(output));
}
/**
@@ -100,7 +92,7 @@ public final class TextFormat {
public static void printUnicode(final UnknownFieldSet fields,
final Appendable output)
throws IOException {
- UNICODE_PRINTER.printUnknownFields(fields, new TextGenerator(output));
+ Printer.UNICODE.printUnknownFields(fields, multiLineOutput(output));
}
/**
@@ -109,10 +101,9 @@ public final class TextFormat {
*/
public static String shortDebugString(final MessageOrBuilder message) {
try {
- final StringBuilder sb = new StringBuilder();
- SINGLE_LINE_PRINTER.print(message, new TextGenerator(sb));
- // Single line mode currently might have an extra space at the end.
- return sb.toString().trim();
+ final StringBuilder text = new StringBuilder();
+ Printer.DEFAULT.print(message, singleLineOutput(text));
+ return text.toString();
} catch (IOException e) {
throw new IllegalStateException(e);
}
@@ -125,11 +116,11 @@ public final class TextFormat {
public static String shortDebugString(final FieldDescriptor field,
final Object value) {
try {
- final StringBuilder sb = new StringBuilder();
- SINGLE_LINE_PRINTER.printField(field, value, new TextGenerator(sb));
- return sb.toString().trim();
+ final StringBuilder text = new StringBuilder();
+ Printer.DEFAULT.printField(field, value, singleLineOutput(text));
+ return text.toString();
} catch (IOException e) {
- throw new IllegalStateException(e);
+ throw new IllegalStateException(e);
}
}
@@ -139,10 +130,9 @@ public final class TextFormat {
*/
public static String shortDebugString(final UnknownFieldSet fields) {
try {
- final StringBuilder sb = new StringBuilder();
- SINGLE_LINE_PRINTER.printUnknownFields(fields, new TextGenerator(sb));
- // Single line mode currently might have an extra space at the end.
- return sb.toString().trim();
+ final StringBuilder text = new StringBuilder();
+ Printer.DEFAULT.printUnknownFields(fields, singleLineOutput(text));
+ return text.toString();
} catch (IOException e) {
throw new IllegalStateException(e);
}
@@ -183,7 +173,7 @@ public final class TextFormat {
public static String printToUnicodeString(final MessageOrBuilder message) {
try {
final StringBuilder text = new StringBuilder();
- UNICODE_PRINTER.print(message, new TextGenerator(text));
+ Printer.UNICODE.print(message, multiLineOutput(text));
return text.toString();
} catch (IOException e) {
throw new IllegalStateException(e);
@@ -197,7 +187,7 @@ public final class TextFormat {
public static String printToUnicodeString(final UnknownFieldSet fields) {
try {
final StringBuilder text = new StringBuilder();
- UNICODE_PRINTER.printUnknownFields(fields, new TextGenerator(text));
+ Printer.UNICODE.printUnknownFields(fields, multiLineOutput(text));
return text.toString();
} catch (IOException e) {
throw new IllegalStateException(e);
@@ -208,7 +198,7 @@ public final class TextFormat {
final Object value,
final Appendable output)
throws IOException {
- DEFAULT_PRINTER.printField(field, value, new TextGenerator(output));
+ Printer.DEFAULT.printField(field, value, multiLineOutput(output));
}
public static String printFieldToString(final FieldDescriptor field,
@@ -223,6 +213,23 @@ public final class TextFormat {
}
/**
+ * Outputs a unicode textual representation of the value of given field value.
+ *
+ * <p>Same as {@code printFieldValue()}, except that non-ASCII characters in string type fields
+ * are not escaped in backslash+octals.
+ *
+ * @param field the descriptor of the field
+ * @param value the value of the field
+ * @param output the output to which to append the formatted value
+ * @throws ClassCastException if the value is not appropriate for the given field descriptor
+ * @throws IOException if there is an exception writing to the output
+ */
+ public static void printUnicodeFieldValue(
+ final FieldDescriptor field, final Object value, final Appendable output) throws IOException {
+ Printer.UNICODE.printFieldValue(field, value, multiLineOutput(output));
+ }
+
+ /**
* Outputs a textual representation of the value of given field value.
*
* @param field the descriptor of the field
@@ -236,7 +243,7 @@ public final class TextFormat {
final Object value,
final Appendable output)
throws IOException {
- DEFAULT_PRINTER.printFieldValue(field, value, new TextGenerator(output));
+ Printer.DEFAULT.printFieldValue(field, value, multiLineOutput(output));
}
/**
@@ -253,7 +260,7 @@ public final class TextFormat {
final Object value,
final Appendable output)
throws IOException {
- printUnknownFieldValue(tag, value, new TextGenerator(output));
+ printUnknownFieldValue(tag, value, multiLineOutput(output));
}
private static void printUnknownFieldValue(final int tag,
@@ -272,12 +279,24 @@ public final class TextFormat {
generator.print(String.format((Locale) null, "0x%016x", (Long) value));
break;
case WireFormat.WIRETYPE_LENGTH_DELIMITED:
- generator.print("\"");
- generator.print(escapeBytes((ByteString) value));
- generator.print("\"");
+ try {
+ // Try to parse and print the field as an embedded message
+ UnknownFieldSet message = UnknownFieldSet.parseFrom((ByteString) value);
+ generator.print("{");
+ generator.eol();
+ generator.indent();
+ Printer.DEFAULT.printUnknownFields(message, generator);
+ generator.outdent();
+ generator.print("}");
+ } catch (InvalidProtocolBufferException e) {
+ // If not parseable as a message, print as a String
+ generator.print("\"");
+ generator.print(escapeBytes((ByteString) value));
+ generator.print("\"");
+ }
break;
case WireFormat.WIRETYPE_START_GROUP:
- DEFAULT_PRINTER.printUnknownFields((UnknownFieldSet) value, generator);
+ Printer.DEFAULT.printUnknownFields((UnknownFieldSet) value, generator);
break;
default:
throw new IllegalArgumentException("Bad tag: " + tag);
@@ -286,24 +305,16 @@ public final class TextFormat {
/** Helper class for converting protobufs to text. */
private static final class Printer {
- /** Whether to omit newlines from the output. */
- boolean singleLineMode = false;
+ // Printer instance which escapes non-ASCII characters.
+ static final Printer DEFAULT = new Printer(true);
+ // Printer instance which emits Unicode (it still escapes newlines and quotes in strings).
+ static final Printer UNICODE = new Printer(false);
/** Whether to escape non ASCII characters with backslash and octal. */
- boolean escapeNonAscii = true;
-
- private Printer() {}
+ private final boolean escapeNonAscii;
- /** Setter of singleLineMode */
- private Printer setSingleLineMode(boolean singleLineMode) {
- this.singleLineMode = singleLineMode;
- return this;
- }
-
- /** Setter of escapeNonAscii */
- private Printer setEscapeNonAscii(boolean escapeNonAscii) {
+ private Printer(boolean escapeNonAscii) {
this.escapeNonAscii = escapeNonAscii;
- return this;
}
private void print(
@@ -355,12 +366,9 @@ public final class TextFormat {
}
if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
- if (singleLineMode) {
- generator.print(" { ");
- } else {
- generator.print(" {\n");
- generator.indent();
- }
+ generator.print(" {");
+ generator.eol();
+ generator.indent();
} else {
generator.print(": ");
}
@@ -368,19 +376,10 @@ public final class TextFormat {
printFieldValue(field, value, generator);
if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
- if (singleLineMode) {
- generator.print("} ");
- } else {
- generator.outdent();
- generator.print("}\n");
- }
- } else {
- if (singleLineMode) {
- generator.print(" ");
- } else {
- generator.print("\n");
- }
+ generator.outdent();
+ generator.print("}");
}
+ generator.eol();
}
private void printFieldValue(final FieldDescriptor field,
@@ -469,19 +468,13 @@ public final class TextFormat {
field.getLengthDelimitedList(), generator);
for (final UnknownFieldSet value : field.getGroupList()) {
generator.print(entry.getKey().toString());
- if (singleLineMode) {
- generator.print(" { ");
- } else {
- generator.print(" {\n");
- generator.indent();
- }
+ generator.print(" {");
+ generator.eol();
+ generator.indent();
printUnknownFields(value, generator);
- if (singleLineMode) {
- generator.print("} ");
- } else {
- generator.outdent();
- generator.print("}\n");
- }
+ generator.outdent();
+ generator.print("}");
+ generator.eol();
}
}
}
@@ -495,7 +488,7 @@ public final class TextFormat {
generator.print(String.valueOf(number));
generator.print(": ");
printUnknownFieldValue(wireType, value, generator);
- generator.print(singleLineMode ? " " : "\n");
+ generator.eol();
}
}
}
@@ -521,16 +514,29 @@ public final class TextFormat {
}
}
- /**
+ private static TextGenerator multiLineOutput(Appendable output) {
+ return new TextGenerator(output, false);
+ }
+
+ private static TextGenerator singleLineOutput(Appendable output) {
+ return new TextGenerator(output, true);
+ }
+
+ /**
* An inner class for writing text to the output stream.
*/
private static final class TextGenerator {
private final Appendable output;
private final StringBuilder indent = new StringBuilder();
- private boolean atStartOfLine = true;
+ private final boolean singleLineMode;
+ // While technically we are "at the start of a line" at the very beginning of the output, all
+ // we would do in response to this is emit the (zero length) indentation, so it has no effect.
+ // Setting it false here does however suppress an unwanted leading space in single-line mode.
+ private boolean atStartOfLine = false;
- private TextGenerator(final Appendable output) {
+ private TextGenerator(final Appendable output, boolean singleLineMode) {
this.output = output;
+ this.singleLineMode = singleLineMode;
}
/**
@@ -552,35 +558,31 @@ public final class TextFormat {
throw new IllegalArgumentException(
" Outdent() without matching Indent().");
}
- indent.delete(length - 2, length);
+ indent.setLength(length - 2);
}
/**
- * Print text to the output stream.
+ * Print text to the output stream. Bare newlines are never expected to be passed to this
+ * method; to indicate the end of a line, call "eol()".
*/
public void print(final CharSequence text) throws IOException {
- final int size = text.length();
- int pos = 0;
-
- for (int i = 0; i < size; i++) {
- if (text.charAt(i) == '\n') {
- write(text.subSequence(pos, i + 1));
- pos = i + 1;
- atStartOfLine = true;
- }
+ if (atStartOfLine) {
+ atStartOfLine = false;
+ output.append(singleLineMode ? " " : indent);
}
- write(text.subSequence(pos, size));
+ output.append(text);
}
- private void write(final CharSequence data) throws IOException {
- if (data.length() == 0) {
- return;
- }
- if (atStartOfLine) {
- atStartOfLine = false;
- output.append(indent);
+ /**
+ * Signifies reaching the "end of the current line" in the output. In single-line mode, this
+ * does not result in a newline being emitted, but ensures that a separating space is written
+ * before the next output.
+ */
+ public void eol() throws IOException {
+ if (!singleLineMode) {
+ output.append("\n");
}
- output.append(data);
+ atStartOfLine = true;
}
}
@@ -1442,7 +1444,7 @@ public final class TextFormat {
/**
* Parse a single field from {@code tokenizer} and merge it into
- * {@code builder}.
+ * {@code target}.
*/
private void mergeField(final Tokenizer tokenizer,
final ExtensionRegistry extensionRegistry,
@@ -1469,9 +1471,15 @@ public final class TextFormat {
extensionRegistry, name.toString());
if (extension == null) {
- unknownFields.add((tokenizer.getPreviousLine() + 1) + ":" +
- (tokenizer.getPreviousColumn() + 1) + ":\t" +
- type.getFullName() + ".[" + name + "]");
+ unknownFields.add(
+ (tokenizer.getPreviousLine() + 1)
+ + ":"
+ + (tokenizer.getPreviousColumn() + 1)
+ + ":\t"
+ + type.getFullName()
+ + ".["
+ + name
+ + "]");
} else {
if (extension.descriptor.getContainingType() != type) {
throw tokenizer.parseExceptionPreviousToken(
@@ -1506,9 +1514,14 @@ public final class TextFormat {
}
if (field == null) {
- unknownFields.add((tokenizer.getPreviousLine() + 1) + ":" +
- (tokenizer.getPreviousColumn() + 1) + ":\t" +
- type.getFullName() + "." + name);
+ unknownFields.add(
+ (tokenizer.getPreviousLine() + 1)
+ + ":"
+ + (tokenizer.getPreviousColumn() + 1)
+ + ":\t"
+ + type.getFullName()
+ + "."
+ + name);
}
}
@@ -1712,6 +1725,8 @@ public final class TextFormat {
}
if (field.isRepeated()) {
+ // TODO(b/29122459): If field.isMapField() and FORBID_SINGULAR_OVERWRITES mode,
+ // check for duplicate map keys here.
target.addRepeatedField(field, value);
} else if ((singularOverwritePolicy
== SingularOverwritePolicy.FORBID_SINGULAR_OVERWRITES)
diff --git a/java/core/src/main/java/com/google/protobuf/UnknownFieldSet.java b/java/core/src/main/java/com/google/protobuf/UnknownFieldSet.java
index 49b3504f..37d64633 100644
--- a/java/core/src/main/java/com/google/protobuf/UnknownFieldSet.java
+++ b/java/core/src/main/java/com/google/protobuf/UnknownFieldSet.java
@@ -31,7 +31,6 @@
package com.google.protobuf;
import com.google.protobuf.AbstractMessageLite.Builder.LimitedInputStream;
-
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -39,6 +38,7 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
+import java.util.ListIterator;
import java.util.Map;
import java.util.TreeMap;
@@ -58,7 +58,9 @@ import java.util.TreeMap;
*/
public final class UnknownFieldSet implements MessageLite {
- private UnknownFieldSet() {}
+ private UnknownFieldSet() {
+ fields = null;
+ }
/** Create a new {@link Builder}. */
public static Builder newBuilder() {
@@ -82,16 +84,18 @@ public final class UnknownFieldSet implements MessageLite {
return defaultInstance;
}
private static final UnknownFieldSet defaultInstance =
- new UnknownFieldSet(Collections.<Integer, Field>emptyMap());
+ new UnknownFieldSet(Collections.<Integer, Field>emptyMap(),
+ Collections.<Integer, Field>emptyMap());
/**
* Construct an {@code UnknownFieldSet} around the given map. The map is
* expected to be immutable.
*/
- private UnknownFieldSet(final Map<Integer, Field> fields) {
+ UnknownFieldSet(final Map<Integer, Field> fields,
+ final Map<Integer, Field> fieldsDescending) {
this.fields = fields;
}
- private Map<Integer, Field> fields;
+ private final Map<Integer, Field> fields;
@Override
@@ -224,10 +228,8 @@ public final class UnknownFieldSet implements MessageLite {
}
}
- /**
- * Get the number of bytes required to encode this set using
- * {@code MessageSet} wire format.
- */
+
+ /** Get the number of bytes required to encode this set using {@code MessageSet} wire format. */
public int getSerializedSizeAsMessageSet() {
int result = 0;
for (final Map.Entry<Integer, Field> entry : fields.entrySet()) {
@@ -343,12 +345,13 @@ public final class UnknownFieldSet implements MessageLite {
*/
@Override
public UnknownFieldSet build() {
- getFieldBuilder(0); // Force lastField to be built.
+ getFieldBuilder(0); // Force lastField to be built.
final UnknownFieldSet result;
if (fields.isEmpty()) {
result = getDefaultInstance();
} else {
- result = new UnknownFieldSet(Collections.unmodifiableMap(fields));
+ Map<Integer, Field> descendingFields = null;
+ result = new UnknownFieldSet(Collections.unmodifiableMap(fields), descendingFields);
}
fields = null;
return result;
@@ -363,8 +366,9 @@ public final class UnknownFieldSet implements MessageLite {
@Override
public Builder clone() {
getFieldBuilder(0); // Force lastField to be built.
+ Map<Integer, Field> descendingFields = null;
return UnknownFieldSet.newBuilder().mergeFrom(
- new UnknownFieldSet(fields));
+ new UnknownFieldSet(fields, descendingFields));
}
@Override
@@ -841,9 +845,10 @@ public final class UnknownFieldSet implements MessageLite {
}
}
+
/**
- * Get the number of bytes required to encode this field, including field
- * number, using {@code MessageSet} wire format.
+ * Get the number of bytes required to encode this field, including field number, using {@code
+ * MessageSet} wire format.
*/
public int getSerializedSizeAsMessageSetExtension(final int fieldNumber) {
int result = 0;
diff --git a/java/core/src/main/java/com/google/protobuf/UnknownFieldSetLite.java b/java/core/src/main/java/com/google/protobuf/UnknownFieldSetLite.java
index 104f8007..2a614c84 100644
--- a/java/core/src/main/java/com/google/protobuf/UnknownFieldSetLite.java
+++ b/java/core/src/main/java/com/google/protobuf/UnknownFieldSetLite.java
@@ -81,7 +81,7 @@ public final class UnknownFieldSetLite {
System.arraycopy(second.objects, 0, objects, first.count, second.count);
return new UnknownFieldSetLite(count, tags, objects, true /* isMutable */);
}
-
+
/**
* The number of elements in the set.
*/
@@ -186,10 +186,11 @@ public final class UnknownFieldSetLite {
output.writeRawMessageSetExtension(fieldNumber, (ByteString) objects[i]);
}
}
-
+
+
/**
- * Get the number of bytes required to encode this field, including field
- * number, using {@code MessageSet} wire format.
+ * Get the number of bytes required to encode this field, including field number, using {@code
+ * MessageSet} wire format.
*/
public int getSerializedSizeAsMessageSet() {
int size = memoizedSerializedSize;
@@ -251,6 +252,24 @@ public final class UnknownFieldSetLite {
return size;
}
+
+ private static boolean equals(int[] tags1, int[] tags2, int count) {
+ for (int i = 0; i < count; ++i) {
+ if (tags1[i] != tags2[i]) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private static boolean equals(Object[] objects1, Object[] objects2, int count) {
+ for (int i = 0; i < count; ++i) {
+ if (!objects1[i].equals(objects2[i])) {
+ return false;
+ }
+ }
+ return true;
+ }
@Override
public boolean equals(Object obj) {
@@ -268,9 +287,8 @@ public final class UnknownFieldSetLite {
UnknownFieldSetLite other = (UnknownFieldSetLite) obj;
if (count != other.count
- // TODO(dweis): Only have to compare up to count but at worst 2x worse than we need to do.
- || !Arrays.equals(tags, other.tags)
- || !Arrays.deepEquals(objects, other.objects)) {
+ || !equals(tags, other.tags, count)
+ || !equals(objects, other.objects, count)) {
return false;
}
@@ -305,6 +323,7 @@ public final class UnknownFieldSetLite {
// Package private for unsafe experimental runtime.
void storeField(int tag, Object value) {
+ checkMutable();
ensureCapacity();
tags[count] = tag;
diff --git a/java/core/src/main/java/com/google/protobuf/UnsafeUtil.java b/java/core/src/main/java/com/google/protobuf/UnsafeUtil.java
index 5f7bafd6..88315cb6 100644
--- a/java/core/src/main/java/com/google/protobuf/UnsafeUtil.java
+++ b/java/core/src/main/java/com/google/protobuf/UnsafeUtil.java
@@ -33,19 +33,44 @@ package com.google.protobuf;
import java.lang.reflect.Field;
import java.nio.Buffer;
import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
-import sun.misc.Unsafe;
+import java.util.logging.Level;
+import java.util.logging.Logger;
/** Utility class for working with unsafe operations. */
-// TODO(nathanmittler): Add support for Android Memory/MemoryBlock
final class UnsafeUtil {
+ private static final Logger logger = Logger.getLogger(UnsafeUtil.class.getName());
private static final sun.misc.Unsafe UNSAFE = getUnsafe();
+ private static final MemoryAccessor MEMORY_ACCESSOR = getMemoryAccessor();
private static final boolean HAS_UNSAFE_BYTEBUFFER_OPERATIONS =
supportsUnsafeByteBufferOperations();
private static final boolean HAS_UNSAFE_ARRAY_OPERATIONS = supportsUnsafeArrayOperations();
- private static final long ARRAY_BASE_OFFSET = byteArrayBaseOffset();
- private static final long BUFFER_ADDRESS_OFFSET = fieldOffset(field(Buffer.class, "address"));
+
+ private static final long BYTE_ARRAY_BASE_OFFSET = arrayBaseOffset(byte[].class);
+ // Micro-optimization: we can assume a scale of 1 and skip the multiply
+ // private static final long BYTE_ARRAY_INDEX_SCALE = 1;
+
+ private static final long BOOLEAN_ARRAY_BASE_OFFSET = arrayBaseOffset(boolean[].class);
+ private static final long BOOLEAN_ARRAY_INDEX_SCALE = arrayIndexScale(boolean[].class);
+
+ private static final long INT_ARRAY_BASE_OFFSET = arrayBaseOffset(int[].class);
+ private static final long INT_ARRAY_INDEX_SCALE = arrayIndexScale(int[].class);
+
+ private static final long LONG_ARRAY_BASE_OFFSET = arrayBaseOffset(long[].class);
+ private static final long LONG_ARRAY_INDEX_SCALE = arrayIndexScale(long[].class);
+
+ private static final long FLOAT_ARRAY_BASE_OFFSET = arrayBaseOffset(float[].class);
+ private static final long FLOAT_ARRAY_INDEX_SCALE = arrayIndexScale(float[].class);
+
+ private static final long DOUBLE_ARRAY_BASE_OFFSET = arrayBaseOffset(double[].class);
+ private static final long DOUBLE_ARRAY_INDEX_SCALE = arrayIndexScale(double[].class);
+
+ private static final long OBJECT_ARRAY_BASE_OFFSET = arrayBaseOffset(Object[].class);
+ private static final long OBJECT_ARRAY_INDEX_SCALE = arrayIndexScale(Object[].class);
+
+ private static final long BUFFER_ADDRESS_OFFSET = fieldOffset(bufferAddressField());
private UnsafeUtil() {}
@@ -57,120 +82,185 @@ final class UnsafeUtil {
return HAS_UNSAFE_BYTEBUFFER_OPERATIONS;
}
- static Object allocateInstance(Class<?> clazz) {
- try {
- return UNSAFE.allocateInstance(clazz);
- } catch (InstantiationException e) {
- throw new RuntimeException(e);
- }
+ static long objectFieldOffset(Field field) {
+ return MEMORY_ACCESSOR.objectFieldOffset(field);
}
- static long objectFieldOffset(Field field) {
- return UNSAFE.objectFieldOffset(field);
+ private static int arrayBaseOffset(Class<?> clazz) {
+ return HAS_UNSAFE_ARRAY_OPERATIONS ? MEMORY_ACCESSOR.arrayBaseOffset(clazz) : -1;
}
- static long getArrayBaseOffset() {
- return ARRAY_BASE_OFFSET;
+ private static int arrayIndexScale(Class<?> clazz) {
+ return HAS_UNSAFE_ARRAY_OPERATIONS ? MEMORY_ACCESSOR.arrayIndexScale(clazz) : -1;
}
static byte getByte(Object target, long offset) {
- return UNSAFE.getByte(target, offset);
+ return MEMORY_ACCESSOR.getByte(target, offset);
}
static void putByte(Object target, long offset, byte value) {
- UNSAFE.putByte(target, offset, value);
+ MEMORY_ACCESSOR.putByte(target, offset, value);
}
static int getInt(Object target, long offset) {
- return UNSAFE.getInt(target, offset);
+ return MEMORY_ACCESSOR.getInt(target, offset);
}
static void putInt(Object target, long offset, int value) {
- UNSAFE.putInt(target, offset, value);
+ MEMORY_ACCESSOR.putInt(target, offset, value);
}
static long getLong(Object target, long offset) {
- return UNSAFE.getLong(target, offset);
+ return MEMORY_ACCESSOR.getLong(target, offset);
}
static void putLong(Object target, long offset, long value) {
- UNSAFE.putLong(target, offset, value);
+ MEMORY_ACCESSOR.putLong(target, offset, value);
}
static boolean getBoolean(Object target, long offset) {
- return UNSAFE.getBoolean(target, offset);
+ return MEMORY_ACCESSOR.getBoolean(target, offset);
}
static void putBoolean(Object target, long offset, boolean value) {
- UNSAFE.putBoolean(target, offset, value);
+ MEMORY_ACCESSOR.putBoolean(target, offset, value);
}
static float getFloat(Object target, long offset) {
- return UNSAFE.getFloat(target, offset);
+ return MEMORY_ACCESSOR.getFloat(target, offset);
}
static void putFloat(Object target, long offset, float value) {
- UNSAFE.putFloat(target, offset, value);
+ MEMORY_ACCESSOR.putFloat(target, offset, value);
}
static double getDouble(Object target, long offset) {
- return UNSAFE.getDouble(target, offset);
+ return MEMORY_ACCESSOR.getDouble(target, offset);
}
static void putDouble(Object target, long offset, double value) {
- UNSAFE.putDouble(target, offset, value);
+ MEMORY_ACCESSOR.putDouble(target, offset, value);
}
static Object getObject(Object target, long offset) {
- return UNSAFE.getObject(target, offset);
+ return MEMORY_ACCESSOR.getObject(target, offset);
}
static void putObject(Object target, long offset, Object value) {
- UNSAFE.putObject(target, offset, value);
+ MEMORY_ACCESSOR.putObject(target, offset, value);
+ }
+
+ static byte getByte(byte[] target, long index) {
+ return MEMORY_ACCESSOR.getByte(target, BYTE_ARRAY_BASE_OFFSET + index);
+ }
+
+ static void putByte(byte[] target, long index, byte value) {
+ MEMORY_ACCESSOR.putByte(target, BYTE_ARRAY_BASE_OFFSET + index, value);
+ }
+
+ static int getInt(int[] target, long index) {
+ return MEMORY_ACCESSOR.getInt(target, INT_ARRAY_BASE_OFFSET + (index * INT_ARRAY_INDEX_SCALE));
+ }
+
+ static void putInt(int[] target, long index, int value) {
+ MEMORY_ACCESSOR.putInt(target, INT_ARRAY_BASE_OFFSET + (index * INT_ARRAY_INDEX_SCALE), value);
+ }
+
+ static long getLong(long[] target, long index) {
+ return MEMORY_ACCESSOR.getLong(
+ target, LONG_ARRAY_BASE_OFFSET + (index * LONG_ARRAY_INDEX_SCALE));
+ }
+
+ static void putLong(long[] target, long index, long value) {
+ MEMORY_ACCESSOR.putLong(
+ target, LONG_ARRAY_BASE_OFFSET + (index * LONG_ARRAY_INDEX_SCALE), value);
+ }
+
+ static boolean getBoolean(boolean[] target, long index) {
+ return MEMORY_ACCESSOR.getBoolean(
+ target, BOOLEAN_ARRAY_BASE_OFFSET + (index * BOOLEAN_ARRAY_INDEX_SCALE));
+ }
+
+ static void putBoolean(boolean[] target, long index, boolean value) {
+ MEMORY_ACCESSOR.putBoolean(
+ target, BOOLEAN_ARRAY_BASE_OFFSET + (index * BOOLEAN_ARRAY_INDEX_SCALE), value);
+ }
+
+ static float getFloat(float[] target, long index) {
+ return MEMORY_ACCESSOR.getFloat(
+ target, FLOAT_ARRAY_BASE_OFFSET + (index * FLOAT_ARRAY_INDEX_SCALE));
+ }
+
+ static void putFloat(float[] target, long index, float value) {
+ MEMORY_ACCESSOR.putFloat(
+ target, FLOAT_ARRAY_BASE_OFFSET + (index * FLOAT_ARRAY_INDEX_SCALE), value);
+ }
+
+ static double getDouble(double[] target, long index) {
+ return MEMORY_ACCESSOR.getDouble(
+ target, DOUBLE_ARRAY_BASE_OFFSET + (index * DOUBLE_ARRAY_INDEX_SCALE));
+ }
+
+ static void putDouble(double[] target, long index, double value) {
+ MEMORY_ACCESSOR.putDouble(
+ target, DOUBLE_ARRAY_BASE_OFFSET + (index * DOUBLE_ARRAY_INDEX_SCALE), value);
}
- static void copyMemory(
- Object src, long srcOffset, Object target, long targetOffset, long length) {
- UNSAFE.copyMemory(src, srcOffset, target, targetOffset, length);
+ static Object getObject(Object[] target, long index) {
+ return MEMORY_ACCESSOR.getObject(
+ target, OBJECT_ARRAY_BASE_OFFSET + (index * OBJECT_ARRAY_INDEX_SCALE));
+ }
+
+ static void putObject(Object[] target, long index, Object value) {
+ MEMORY_ACCESSOR.putObject(
+ target, OBJECT_ARRAY_BASE_OFFSET + (index * OBJECT_ARRAY_INDEX_SCALE), value);
+ }
+
+ static void copyMemory(byte[] src, long srcIndex, long targetOffset, long length) {
+ MEMORY_ACCESSOR.copyMemory(src, srcIndex, targetOffset, length);
+ }
+
+ static void copyMemory(long srcOffset, byte[] target, long targetIndex, long length) {
+ MEMORY_ACCESSOR.copyMemory(srcOffset, target, targetIndex, length);
+ }
+
+ static void copyMemory(byte[] src, long srcIndex, byte[] target, long targetIndex, long length) {
+ System.arraycopy(src, (int) srcIndex, target, (int) targetIndex, (int) length);
}
static byte getByte(long address) {
- return UNSAFE.getByte(address);
+ return MEMORY_ACCESSOR.getByte(address);
}
static void putByte(long address, byte value) {
- UNSAFE.putByte(address, value);
+ MEMORY_ACCESSOR.putByte(address, value);
}
static int getInt(long address) {
- return UNSAFE.getInt(address);
+ return MEMORY_ACCESSOR.getInt(address);
}
static void putInt(long address, int value) {
- UNSAFE.putInt(address, value);
+ MEMORY_ACCESSOR.putInt(address, value);
}
static long getLong(long address) {
- return UNSAFE.getLong(address);
+ return MEMORY_ACCESSOR.getLong(address);
}
static void putLong(long address, long value) {
- UNSAFE.putLong(address, value);
- }
-
- static void copyMemory(long srcAddress, long targetAddress, long length) {
- UNSAFE.copyMemory(srcAddress, targetAddress, length);
- }
-
- static void setMemory(long address, long numBytes, byte value) {
- UNSAFE.setMemory(address, numBytes, value);
+ MEMORY_ACCESSOR.putLong(address, value);
}
/**
* Gets the offset of the {@code address} field of the given direct {@link ByteBuffer}.
*/
static long addressOffset(ByteBuffer buffer) {
- return UNSAFE.getLong(buffer, BUFFER_ADDRESS_OFFSET);
+ return MEMORY_ACCESSOR.getLong(buffer, BUFFER_ADDRESS_OFFSET);
+ }
+
+ static Object getStaticObject(Field field) {
+ return MEMORY_ACCESSOR.getStaticObject(field);
}
/**
@@ -181,7 +271,7 @@ final class UnsafeUtil {
try {
unsafe =
AccessController.doPrivileged(
- new PrivilegedExceptionAction<Unsafe>() {
+ new PrivilegedExceptionAction<sun.misc.Unsafe>() {
@Override
public sun.misc.Unsafe run() throws Exception {
Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
@@ -204,69 +294,88 @@ final class UnsafeUtil {
return unsafe;
}
+ /** Get a {@link MemoryAccessor} appropriate for the platform, or null if not supported. */
+ private static MemoryAccessor getMemoryAccessor() {
+ if (UNSAFE == null) {
+ return null;
+ }
+ return new JvmMemoryAccessor(UNSAFE);
+ }
+
/** Indicates whether or not unsafe array operations are supported on this platform. */
private static boolean supportsUnsafeArrayOperations() {
- boolean supported = false;
- if (UNSAFE != null) {
- try {
- Class<?> clazz = UNSAFE.getClass();
- clazz.getMethod("objectFieldOffset", Field.class);
- clazz.getMethod("allocateInstance", Class.class);
- clazz.getMethod("arrayBaseOffset", Class.class);
- clazz.getMethod("getByte", Object.class, long.class);
- clazz.getMethod("putByte", Object.class, long.class, byte.class);
- clazz.getMethod("getBoolean", Object.class, long.class);
- clazz.getMethod("putBoolean", Object.class, long.class, boolean.class);
- clazz.getMethod("getInt", Object.class, long.class);
- clazz.getMethod("putInt", Object.class, long.class, int.class);
- clazz.getMethod("getLong", Object.class, long.class);
- clazz.getMethod("putLong", Object.class, long.class, long.class);
- clazz.getMethod("getFloat", Object.class, long.class);
- clazz.getMethod("putFloat", Object.class, long.class, float.class);
- clazz.getMethod("getDouble", Object.class, long.class);
- clazz.getMethod("putDouble", Object.class, long.class, double.class);
- clazz.getMethod("getObject", Object.class, long.class);
- clazz.getMethod("putObject", Object.class, long.class, Object.class);
- clazz.getMethod(
- "copyMemory", Object.class, long.class, Object.class, long.class, long.class);
- supported = true;
- } catch (Throwable e) {
- // Do nothing.
- }
- }
- return supported;
+ if (UNSAFE == null) {
+ return false;
+ }
+ try {
+ Class<?> clazz = UNSAFE.getClass();
+ clazz.getMethod("objectFieldOffset", Field.class);
+ clazz.getMethod("arrayBaseOffset", Class.class);
+ clazz.getMethod("arrayIndexScale", Class.class);
+ clazz.getMethod("getInt", Object.class, long.class);
+ clazz.getMethod("putInt", Object.class, long.class, int.class);
+ clazz.getMethod("getLong", Object.class, long.class);
+ clazz.getMethod("putLong", Object.class, long.class, long.class);
+ clazz.getMethod("getObject", Object.class, long.class);
+ clazz.getMethod("putObject", Object.class, long.class, Object.class);
+ clazz.getMethod("getByte", Object.class, long.class);
+ clazz.getMethod("putByte", Object.class, long.class, byte.class);
+ clazz.getMethod("getBoolean", Object.class, long.class);
+ clazz.getMethod("putBoolean", Object.class, long.class, boolean.class);
+ clazz.getMethod("getFloat", Object.class, long.class);
+ clazz.getMethod("putFloat", Object.class, long.class, float.class);
+ clazz.getMethod("getDouble", Object.class, long.class);
+ clazz.getMethod("putDouble", Object.class, long.class, double.class);
+
+ return true;
+ } catch (Throwable e) {
+ logger.log(
+ Level.WARNING,
+ "platform method missing - proto runtime falling back to safer methods: " + e);
+ }
+ return false;
}
private static boolean supportsUnsafeByteBufferOperations() {
- boolean supported = false;
- if (UNSAFE != null) {
- try {
- Class<?> clazz = UNSAFE.getClass();
- // Methods for getting direct buffer address.
- clazz.getMethod("objectFieldOffset", Field.class);
- clazz.getMethod("getLong", Object.class, long.class);
-
- clazz.getMethod("getByte", long.class);
- clazz.getMethod("putByte", long.class, byte.class);
- clazz.getMethod("getInt", long.class);
- clazz.getMethod("putInt", long.class, int.class);
- clazz.getMethod("getLong", long.class);
- clazz.getMethod("putLong", long.class, long.class);
- clazz.getMethod("setMemory", long.class, long.class, byte.class);
- clazz.getMethod("copyMemory", long.class, long.class, long.class);
- supported = true;
- } catch (Throwable e) {
- // Do nothing.
- }
- }
- return supported;
+ if (UNSAFE == null) {
+ return false;
+ }
+ try {
+ Class<?> clazz = UNSAFE.getClass();
+ // Methods for getting direct buffer address.
+ clazz.getMethod("objectFieldOffset", Field.class);
+ clazz.getMethod("getLong", Object.class, long.class);
+
+ clazz.getMethod("getByte", long.class);
+ clazz.getMethod("putByte", long.class, byte.class);
+ clazz.getMethod("getInt", long.class);
+ clazz.getMethod("putInt", long.class, int.class);
+ clazz.getMethod("getLong", long.class);
+ clazz.getMethod("putLong", long.class, long.class);
+ clazz.getMethod("copyMemory", long.class, long.class, long.class);
+ clazz.getMethod("copyMemory", Object.class, long.class, Object.class, long.class, long.class);
+ return true;
+ } catch (Throwable e) {
+ logger.log(
+ Level.WARNING,
+ "platform method missing - proto runtime falling back to safer methods: " + e);
+ }
+ return false;
}
- /**
- * Get the base offset for byte arrays, or {@code -1} if {@code sun.misc.Unsafe} is not available.
- */
- private static int byteArrayBaseOffset() {
- return HAS_UNSAFE_ARRAY_OPERATIONS ? UNSAFE.arrayBaseOffset(byte[].class) : -1;
+
+ @SuppressWarnings("unchecked")
+ private static <T> Class<T> getClassForName(String name) {
+ try {
+ return (Class<T>) Class.forName(name);
+ } catch (Throwable e) {
+ return null;
+ }
+ }
+
+ /** Finds the address field within a direct {@link Buffer}. */
+ private static Field bufferAddressField() {
+ return field(Buffer.class, "address");
}
/**
@@ -274,7 +383,7 @@ final class UnsafeUtil {
* available.
*/
private static long fieldOffset(Field field) {
- return field == null || UNSAFE == null ? -1 : UNSAFE.objectFieldOffset(field);
+ return field == null || MEMORY_ACCESSOR == null ? -1 : MEMORY_ACCESSOR.objectFieldOffset(field);
}
/**
@@ -292,4 +401,176 @@ final class UnsafeUtil {
}
return field;
}
+
+ private abstract static class MemoryAccessor {
+
+ sun.misc.Unsafe unsafe;
+
+ MemoryAccessor(sun.misc.Unsafe unsafe) {
+ this.unsafe = unsafe;
+ }
+
+ public final long objectFieldOffset(Field field) {
+ return unsafe.objectFieldOffset(field);
+ }
+
+ public abstract byte getByte(Object target, long offset);
+
+ public abstract void putByte(Object target, long offset, byte value);
+
+ public final int getInt(Object target, long offset) {
+ return unsafe.getInt(target, offset);
+ }
+
+ public final void putInt(Object target, long offset, int value) {
+ unsafe.putInt(target, offset, value);
+ }
+
+ public final long getLong(Object target, long offset) {
+ return unsafe.getLong(target, offset);
+ }
+
+ public final void putLong(Object target, long offset, long value) {
+ unsafe.putLong(target, offset, value);
+ }
+
+ public abstract boolean getBoolean(Object target, long offset);
+
+ public abstract void putBoolean(Object target, long offset, boolean value);
+
+ public abstract float getFloat(Object target, long offset);
+
+ public abstract void putFloat(Object target, long offset, float value);
+
+ public abstract double getDouble(Object target, long offset);
+
+ public abstract void putDouble(Object target, long offset, double value);
+
+ public final Object getObject(Object target, long offset) {
+ return unsafe.getObject(target, offset);
+ }
+
+ public final void putObject(Object target, long offset, Object value) {
+ unsafe.putObject(target, offset, value);
+ }
+
+ public final int arrayBaseOffset(Class<?> clazz) {
+ return unsafe.arrayBaseOffset(clazz);
+ }
+
+ public final int arrayIndexScale(Class<?> clazz) {
+ return unsafe.arrayIndexScale(clazz);
+ }
+
+ public abstract byte getByte(long address);
+
+ public abstract void putByte(long address, byte value);
+
+ public abstract int getInt(long address);
+
+ public abstract void putInt(long address, int value);
+
+ public abstract long getLong(long address);
+
+ public abstract void putLong(long address, long value);
+
+ public abstract Object getStaticObject(Field field);
+
+ public abstract void copyMemory(long srcOffset, byte[] target, long targetIndex, long length);
+
+ public abstract void copyMemory(byte[] src, long srcIndex, long targetOffset, long length);
+ }
+
+ private static final class JvmMemoryAccessor extends MemoryAccessor {
+
+ JvmMemoryAccessor(sun.misc.Unsafe unsafe) {
+ super(unsafe);
+ }
+
+ @Override
+ public byte getByte(long address) {
+ return unsafe.getByte(address);
+ }
+
+ @Override
+ public void putByte(long address, byte value) {
+ unsafe.putByte(address, value);
+ }
+
+ @Override
+ public int getInt(long address) {
+ return unsafe.getInt(address);
+ }
+
+ @Override
+ public void putInt(long address, int value) {
+ unsafe.putInt(address, value);
+ }
+
+ @Override
+ public long getLong(long address) {
+ return unsafe.getLong(address);
+ }
+
+ @Override
+ public void putLong(long address, long value) {
+ unsafe.putLong(address, value);
+ }
+
+ @Override
+ public byte getByte(Object target, long offset) {
+ return unsafe.getByte(target, offset);
+ }
+
+ @Override
+ public void putByte(Object target, long offset, byte value) {
+ unsafe.putByte(target, offset, value);
+ }
+
+ @Override
+ public boolean getBoolean(Object target, long offset) {
+ return unsafe.getBoolean(target, offset);
+ }
+
+ @Override
+ public void putBoolean(Object target, long offset, boolean value) {
+ unsafe.putBoolean(target, offset, value);
+ }
+
+ @Override
+ public float getFloat(Object target, long offset) {
+ return unsafe.getFloat(target, offset);
+ }
+
+ @Override
+ public void putFloat(Object target, long offset, float value) {
+ unsafe.putFloat(target, offset, value);
+ }
+
+ @Override
+ public double getDouble(Object target, long offset) {
+ return unsafe.getDouble(target, offset);
+ }
+
+ @Override
+ public void putDouble(Object target, long offset, double value) {
+ unsafe.putDouble(target, offset, value);
+ }
+
+ @Override
+ public void copyMemory(long srcOffset, byte[] target, long targetIndex, long length) {
+ unsafe.copyMemory(null, srcOffset, target, BYTE_ARRAY_BASE_OFFSET + targetIndex, length);
+ }
+
+ @Override
+ public void copyMemory(byte[] src, long srcIndex, long targetOffset, long length) {
+ unsafe.copyMemory(src, BYTE_ARRAY_BASE_OFFSET + srcIndex, null, targetOffset, length);
+ }
+
+ @Override
+ public Object getStaticObject(Field field) {
+ return getObject(unsafe.staticFieldBase(field), unsafe.staticFieldOffset(field));
+ }
+ }
+
}
diff --git a/java/core/src/main/java/com/google/protobuf/Utf8.java b/java/core/src/main/java/com/google/protobuf/Utf8.java
index 5b80d405..1b136144 100644
--- a/java/core/src/main/java/com/google/protobuf/Utf8.java
+++ b/java/core/src/main/java/com/google/protobuf/Utf8.java
@@ -31,7 +31,6 @@
package com.google.protobuf;
import static com.google.protobuf.UnsafeUtil.addressOffset;
-import static com.google.protobuf.UnsafeUtil.getArrayBaseOffset;
import static com.google.protobuf.UnsafeUtil.hasUnsafeArrayOperations;
import static com.google.protobuf.UnsafeUtil.hasUnsafeByteBufferOperations;
import static java.lang.Character.MAX_SURROGATE;
@@ -1001,8 +1000,8 @@ final class Utf8 {
throw new ArrayIndexOutOfBoundsException(
String.format("Array length=%d, index=%d, limit=%d", bytes.length, index, limit));
}
- long offset = getArrayBaseOffset() + index;
- final long offsetLimit = getArrayBaseOffset() + limit;
+ long offset = index;
+ final long offsetLimit = limit;
if (state != COMPLETE) {
// The previous decoding operation was incomplete (or malformed).
// We look for a well-formed sequence consisting of bytes from
@@ -1187,7 +1186,7 @@ final class Utf8 {
@Override
int encodeUtf8(final CharSequence in, final byte[] out, final int offset, final int length) {
- long outIx = getArrayBaseOffset() + offset;
+ long outIx = offset;
final long outLimit = outIx + length;
final int inLimit = in.length();
if (inLimit > length || out.length - length < offset) {
@@ -1204,7 +1203,7 @@ final class Utf8 {
}
if (inIx == inLimit) {
// We're done, it was ASCII encoded.
- return (int) (outIx - getArrayBaseOffset());
+ return (int) outIx;
}
for (char c; inIx < inLimit; ++inIx) {
@@ -1243,7 +1242,7 @@ final class Utf8 {
}
// All bytes have been encoded.
- return (int) (outIx - getArrayBaseOffset());
+ return (int) outIx;
}
@Override
@@ -1321,31 +1320,17 @@ final class Utf8 {
*/
private static int unsafeEstimateConsecutiveAscii(
byte[] bytes, long offset, final int maxChars) {
- int remaining = maxChars;
- if (remaining < UNSAFE_COUNT_ASCII_THRESHOLD) {
+ if (maxChars < UNSAFE_COUNT_ASCII_THRESHOLD) {
// Don't bother with small strings.
return 0;
}
- // Read bytes until 8-byte aligned so that we can read longs in the loop below.
- // Byte arrays are already either 8 or 16-byte aligned, so we just need to make sure that
- // the index (relative to the start of the array) is also 8-byte aligned. We do this by
- // ANDing the index with 7 to determine the number of bytes that need to be read before
- // we're 8-byte aligned.
- final int unaligned = (int) offset & 7;
- for (int j = unaligned; j > 0; j--) {
+ for (int i = 0; i < maxChars; i++) {
if (UnsafeUtil.getByte(bytes, offset++) < 0) {
- return unaligned - j;
+ return i;
}
}
-
- // This simple loop stops when we encounter a byte >= 0x80 (i.e. non-ASCII).
- // To speed things up further, we're reading longs instead of bytes so we use a mask to
- // determine if any byte in the current long is non-ASCII.
- remaining -= unaligned;
- for (; remaining >= 8 && (UnsafeUtil.getLong(bytes, offset) & ASCII_MASK_LONG) == 0;
- offset += 8, remaining -= 8) {}
- return maxChars - remaining;
+ return maxChars;
}
/**
@@ -1362,7 +1347,7 @@ final class Utf8 {
// Read bytes until 8-byte aligned so that we can read longs in the loop below.
// We do this by ANDing the address with 7 to determine the number of bytes that need to
// be read before we're 8-byte aligned.
- final int unaligned = (int) address & 7;
+ final int unaligned = 8 - ((int) address & 7);
for (int j = unaligned; j > 0; j--) {
if (UnsafeUtil.getByte(address++) < 0) {
return unaligned - j;
diff --git a/java/core/src/main/java/com/google/protobuf/WireFormat.java b/java/core/src/main/java/com/google/protobuf/WireFormat.java
index 0b0cdb7d..8b837ee5 100644
--- a/java/core/src/main/java/com/google/protobuf/WireFormat.java
+++ b/java/core/src/main/java/com/google/protobuf/WireFormat.java
@@ -47,8 +47,10 @@ public final class WireFormat {
// Do not allow instantiation.
private WireFormat() {}
- static final int FIXED_32_SIZE = 4;
- static final int FIXED_64_SIZE = 8;
+ static final int FIXED32_SIZE = 4;
+ static final int FIXED64_SIZE = 8;
+ static final int MAX_VARINT32_SIZE = 5;
+ static final int MAX_VARINT64_SIZE = 10;
static final int MAX_VARINT_SIZE = 10;
public static final int WIRETYPE_VARINT = 0;
diff --git a/java/core/src/test/java/com/google/protobuf/CodedInputStreamTest.java b/java/core/src/test/java/com/google/protobuf/CodedInputStreamTest.java
index e440c7db..5ea6b79c 100644
--- a/java/core/src/test/java/com/google/protobuf/CodedInputStreamTest.java
+++ b/java/core/src/test/java/com/google/protobuf/CodedInputStreamTest.java
@@ -41,6 +41,8 @@ import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.Arrays;
import junit.framework.TestCase;
/**
@@ -49,6 +51,9 @@ import junit.framework.TestCase;
* @author kenton@google.com Kenton Varda
*/
public class CodedInputStreamTest extends TestCase {
+
+ private static final int DEFAULT_BLOCK_SIZE = 4096;
+
private enum InputType {
ARRAY {
@Override
@@ -76,7 +81,43 @@ public class CodedInputStreamTest extends TestCase {
CodedInputStream newDecoder(byte[] data, int blockSize) {
return CodedInputStream.newInstance(new SmallBlockInputStream(data, blockSize));
}
+ },
+ ITER_DIRECT {
+ @Override
+ CodedInputStream newDecoder(byte[] data, int blockSize) {
+ if (blockSize > DEFAULT_BLOCK_SIZE) {
+ blockSize = DEFAULT_BLOCK_SIZE;
+ }
+ ArrayList <ByteBuffer> input = new ArrayList <ByteBuffer>();
+ for (int i = 0; i < data.length; i += blockSize) {
+ int rl = Math.min(blockSize, data.length - i);
+ ByteBuffer rb = ByteBuffer.allocateDirect(rl);
+ rb.put(data, i, rl);
+ rb.flip();
+ input.add(rb);
+ }
+ return CodedInputStream.newInstance(input);
+ }
+ },
+ STREAM_ITER_DIRECT {
+ @Override
+ CodedInputStream newDecoder(byte[] data, int blockSize) {
+ if (blockSize > DEFAULT_BLOCK_SIZE) {
+ blockSize = DEFAULT_BLOCK_SIZE;
+ }
+ ArrayList <ByteBuffer> input = new ArrayList <ByteBuffer>();
+ for (int i = 0; i < data.length; i += blockSize) {
+ int rl = Math.min(blockSize, data.length - i);
+ ByteBuffer rb = ByteBuffer.allocateDirect(rl);
+ rb.put(data, i, rl);
+ rb.flip();
+ input.add(rb);
+ }
+ return CodedInputStream.newInstance(new IterableByteBufferInputStream(input));
+ }
};
+
+
CodedInputStream newDecoder(byte[] data) {
return newDecoder(data, data.length);
@@ -613,6 +654,82 @@ public class CodedInputStreamTest extends TestCase {
checkSizeLimitExceeded(expected);
}
}
+
+ public void testRefillBufferWithCorrectSize() throws Exception {
+ // NOTE: refillBuffer only applies to the stream-backed CIS.
+ byte[] bytes = "123456789".getBytes("UTF-8");
+ ByteArrayOutputStream rawOutput = new ByteArrayOutputStream();
+ CodedOutputStream output = CodedOutputStream.newInstance(rawOutput, bytes.length);
+
+ int tag = WireFormat.makeTag(1, WireFormat.WIRETYPE_LENGTH_DELIMITED);
+ output.writeRawVarint32(tag);
+ output.writeRawVarint32(bytes.length);
+ output.writeRawBytes(bytes);
+ output.writeRawVarint32(tag);
+ output.writeRawVarint32(bytes.length);
+ output.writeRawBytes(bytes);
+ output.writeRawByte(4);
+ output.flush();
+
+ // Input is two string with length 9 and one raw byte.
+ byte[] rawInput = rawOutput.toByteArray();
+ for (int inputStreamBufferLength = 8;
+ inputStreamBufferLength <= rawInput.length + 1; inputStreamBufferLength++) {
+ CodedInputStream input = CodedInputStream.newInstance(
+ new ByteArrayInputStream(rawInput), inputStreamBufferLength);
+ input.setSizeLimit(rawInput.length - 1);
+ input.readString();
+ input.readString();
+ try {
+ input.readRawByte(); // Hits limit.
+ fail("Should have thrown an exception!");
+ } catch (InvalidProtocolBufferException expected) {
+ checkSizeLimitExceeded(expected);
+ }
+ }
+ }
+
+ public void testIsAtEnd() throws Exception {
+ CodedInputStream input = CodedInputStream.newInstance(
+ new ByteArrayInputStream(new byte[5]));
+ try {
+ for (int i = 0; i < 5; i++) {
+ assertEquals(false, input.isAtEnd());
+ input.readRawByte();
+ }
+ assertEquals(true, input.isAtEnd());
+ } catch (Exception e) {
+ fail("Catch exception in the testIsAtEnd");
+ }
+ }
+
+ public void testCurrentLimitExceeded() throws Exception {
+ byte[] bytes = "123456789".getBytes("UTF-8");
+ ByteArrayOutputStream rawOutput = new ByteArrayOutputStream();
+ CodedOutputStream output = CodedOutputStream.newInstance(rawOutput, bytes.length);
+
+ int tag = WireFormat.makeTag(1, WireFormat.WIRETYPE_LENGTH_DELIMITED);
+ output.writeRawVarint32(tag);
+ output.writeRawVarint32(bytes.length);
+ output.writeRawBytes(bytes);
+ output.flush();
+
+ byte[] rawInput = rawOutput.toByteArray();
+ CodedInputStream input = CodedInputStream.newInstance(
+ new ByteArrayInputStream(rawInput));
+ // The length of the whole rawInput
+ input.setSizeLimit(11);
+ // Some number that is smaller than the rawInput's length
+ // but larger than 2
+ input.pushLimit(5);
+ try {
+ input.readString();
+ fail("Should have thrown an exception");
+ } catch (InvalidProtocolBufferException expected) {
+ assertEquals(expected.getMessage(),
+ InvalidProtocolBufferException.truncatedMessage().getMessage());
+ }
+ }
public void testSizeLimitMultipleMessages() throws Exception {
// NOTE: Size limit only applies to the stream-backed CIS.
@@ -807,6 +924,52 @@ public class CodedInputStreamTest extends TestCase {
}
}
+ public void testReadLargeByteStringFromInputStream() throws Exception {
+ byte[] bytes = new byte[1024 * 1024];
+ for (int i = 0; i < bytes.length; i++) {
+ bytes[i] = (byte) (i & 0xFF);
+ }
+ ByteString.Output rawOutput = ByteString.newOutput();
+ CodedOutputStream output = CodedOutputStream.newInstance(rawOutput);
+ output.writeRawVarint32(bytes.length);
+ output.writeRawBytes(bytes);
+ output.flush();
+ byte[] data = rawOutput.toByteString().toByteArray();
+
+ CodedInputStream input = CodedInputStream.newInstance(
+ new ByteArrayInputStream(data) {
+ @Override
+ public synchronized int available() {
+ return 0;
+ }
+ });
+ ByteString result = input.readBytes();
+ assertEquals(ByteString.copyFrom(bytes), result);
+ }
+
+ public void testReadLargeByteArrayFromInputStream() throws Exception {
+ byte[] bytes = new byte[1024 * 1024];
+ for (int i = 0; i < bytes.length; i++) {
+ bytes[i] = (byte) (i & 0xFF);
+ }
+ ByteString.Output rawOutput = ByteString.newOutput();
+ CodedOutputStream output = CodedOutputStream.newInstance(rawOutput);
+ output.writeRawVarint32(bytes.length);
+ output.writeRawBytes(bytes);
+ output.flush();
+ byte[] data = rawOutput.toByteString().toByteArray();
+
+ CodedInputStream input = CodedInputStream.newInstance(
+ new ByteArrayInputStream(data) {
+ @Override
+ public synchronized int available() {
+ return 0;
+ }
+ });
+ byte[] result = input.readByteArray();
+ assertTrue(Arrays.equals(bytes, result));
+ }
+
public void testReadByteBuffer() throws Exception {
ByteString.Output rawOutput = ByteString.newOutput();
CodedOutputStream output = CodedOutputStream.newInstance(rawOutput);
@@ -871,7 +1034,9 @@ public class CodedInputStreamTest extends TestCase {
byte[] data = byteArrayStream.toByteArray();
for (InputType inputType : InputType.values()) {
- if (inputType == InputType.STREAM) {
+ if (inputType == InputType.STREAM
+ || inputType == InputType.STREAM_ITER_DIRECT
+ || inputType == InputType.ITER_DIRECT) {
// Aliasing doesn't apply to stream-backed CIS.
continue;
}
@@ -896,7 +1061,7 @@ public class CodedInputStreamTest extends TestCase {
assertEquals(inputType.name(), (byte) 89, result.get());
// Enable aliasing
- inputStream = inputType.newDecoder(data);
+ inputStream = inputType.newDecoder(data, data.length);
inputStream.enableAliasing(true);
result = inputStream.readByteBuffer();
assertEquals(inputType.name(), 0, result.capacity());
diff --git a/java/core/src/test/java/com/google/protobuf/DiscardUnknownFieldsTest.java b/java/core/src/test/java/com/google/protobuf/DiscardUnknownFieldsTest.java
new file mode 100644
index 00000000..0f09a51b
--- /dev/null
+++ b/java/core/src/test/java/com/google/protobuf/DiscardUnknownFieldsTest.java
@@ -0,0 +1,157 @@
+// 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.
+
+package com.google.protobuf;
+
+import static org.junit.Assert.assertEquals;
+
+import protobuf_unittest.UnittestProto;
+import proto3_unittest.UnittestProto3;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/** Unit tests for discard or preserve unknown fields. */
+@RunWith(JUnit4.class)
+public class DiscardUnknownFieldsTest {
+ @Test
+ public void testProto2() throws Exception {
+ testProto2Message(
+ UnittestProto.TestEmptyMessage.getDefaultInstance());
+ testProto2Message(
+ UnittestProto.TestEmptyMessageWithExtensions.getDefaultInstance());
+ testProto2Message(
+ DynamicMessage.getDefaultInstance(UnittestProto.TestEmptyMessage.getDescriptor()));
+ testProto2Message(
+ DynamicMessage.getDefaultInstance(
+ UnittestProto.TestEmptyMessageWithExtensions.getDescriptor()));
+ }
+
+ @Test
+ public void testProto3() throws Exception {
+ testProto3Message(UnittestProto3.TestEmptyMessage.getDefaultInstance());
+ testProto3Message(
+ DynamicMessage.getDefaultInstance(UnittestProto3.TestEmptyMessage.getDescriptor()));
+ }
+
+ private static void testProto2Message(Message message) throws Exception {
+ assertUnknownFieldsDefaultPreserved(message);
+ assertUnknownFieldsExplicitlyDiscarded(message);
+ assertReuseCodedInputStreamPreserve(message);
+ assertUnknownFieldsInUnknownFieldSetArePreserve(message);
+ }
+
+ private static void testProto3Message(Message message) throws Exception {
+ CodedInputStream.setProto3KeepUnknownsByDefaultForTest();
+ assertUnknownFieldsDefaultPreserved(message);
+ assertUnknownFieldsExplicitlyDiscarded(message);
+ assertReuseCodedInputStreamPreserve(message);
+ assertUnknownFieldsInUnknownFieldSetArePreserve(message);
+ CodedInputStream.setProto3DiscardUnknownsByDefaultForTest();
+ assertUnknownFieldsDefaultDiscarded(message);
+ assertUnknownFieldsExplicitlyDiscarded(message);
+ assertUnknownFieldsInUnknownFieldSetAreDiscarded(message);
+ }
+
+ private static void assertReuseCodedInputStreamPreserve(Message message) throws Exception {
+ final int messageSize = payload.size();
+ byte[] copied = new byte[messageSize * 2];
+ payload.copyTo(copied, 0);
+ payload.copyTo(copied, messageSize);
+ CodedInputStream input = CodedInputStream.newInstance(copied);
+ {
+ // Use DiscardUnknownFieldsParser to parse the first payload.
+ int oldLimit = input.pushLimit(messageSize);
+ Message parsed = DiscardUnknownFieldsParser.wrap(message.getParserForType()).parseFrom(input);
+ assertEquals(message.getClass().getName(), 0, parsed.getSerializedSize());
+ input.popLimit(oldLimit);
+ }
+ {
+ // Use the normal parser to parse the remaining payload should have unknown fields preserved.
+ Message parsed = message.getParserForType().parseFrom(input);
+ assertEquals(message.getClass().getName(), payload, parsed.toByteString());
+ }
+ }
+
+ /**
+ * {@link Message.Builder#setUnknownFields(UnknownFieldSet)} and {@link
+ * Message.Builder#mergeUnknownFields(UnknownFieldSet)} should preserve the unknown fields.
+ */
+ private static void assertUnknownFieldsInUnknownFieldSetArePreserve(Message message)
+ throws Exception {
+ UnknownFieldSet unknownFields = UnknownFieldSet.newBuilder().mergeFrom(payload).build();
+ Message built = message.newBuilderForType().setUnknownFields(unknownFields).build();
+ assertEquals(message.getClass().getName(), payload, built.toByteString());
+
+ }
+ /**
+ * {@link Message.Builder#setUnknownFields(UnknownFieldSet)} and {@link
+ * Message.Builder#mergeUnknownFields(UnknownFieldSet)} should discard the unknown fields.
+ */
+ private static void assertUnknownFieldsInUnknownFieldSetAreDiscarded(Message message)
+ throws Exception {
+ UnknownFieldSet unknownFields = UnknownFieldSet.newBuilder().mergeFrom(payload).build();
+ Message built = message.newBuilderForType().setUnknownFields(unknownFields).build();
+ assertEquals(message.getClass().getName(), 0, built.getSerializedSize());
+ }
+
+ private static void assertUnknownFieldsDefaultPreserved(MessageLite message) throws Exception {
+ {
+ MessageLite parsed = message.getParserForType().parseFrom(payload);
+ assertEquals(message.getClass().getName(), payload, parsed.toByteString());
+ }
+
+ {
+ MessageLite parsed = message.newBuilderForType().mergeFrom(payload).build();
+ assertEquals(message.getClass().getName(), payload, parsed.toByteString());
+ }
+ }
+
+ private static void assertUnknownFieldsDefaultDiscarded(MessageLite message) throws Exception {
+ {
+ MessageLite parsed = message.getParserForType().parseFrom(payload);
+ assertEquals(message.getClass().getName(), 0, parsed.getSerializedSize());
+ }
+
+ {
+ MessageLite parsed = message.newBuilderForType().mergeFrom(payload).build();
+ assertEquals(message.getClass().getName(), 0, parsed.getSerializedSize());
+ }
+ }
+
+ private static void assertUnknownFieldsExplicitlyDiscarded(Message message) throws Exception {
+ Message parsed =
+ DiscardUnknownFieldsParser.wrap(message.getParserForType()).parseFrom(payload);
+ assertEquals(message.getClass().getName(), 0, parsed.getSerializedSize());
+ }
+
+ private static final ByteString payload =
+ TestUtilLite.getAllLiteSetBuilder().build().toByteString();
+}
diff --git a/java/core/src/test/java/com/google/protobuf/FieldPresenceTest.java b/java/core/src/test/java/com/google/protobuf/FieldPresenceTest.java
index 4a42c897..42da5bb3 100644
--- a/java/core/src/test/java/com/google/protobuf/FieldPresenceTest.java
+++ b/java/core/src/test/java/com/google/protobuf/FieldPresenceTest.java
@@ -108,7 +108,7 @@ public class FieldPresenceTest extends TestCase {
assertFalse(TestAllTypes.newBuilder().build().hasOptionalNestedMessage());
assertFalse(TestAllTypes.newBuilder().hasOptionalNestedMessage());
- // oneof fields don't have hasFoo() methods (even for message types).
+ // oneof fields don't have hasFoo() methods for non-message types.
assertHasMethodRemoved(
UnittestProto.TestAllTypes.class,
TestAllTypes.class,
@@ -121,10 +121,8 @@ public class FieldPresenceTest extends TestCase {
UnittestProto.TestAllTypes.class,
TestAllTypes.class,
"OneofBytes");
- assertHasMethodRemoved(
- UnittestProto.TestAllTypes.class,
- TestAllTypes.class,
- "OneofNestedMessage");
+ assertFalse(TestAllTypes.newBuilder().build().hasOneofNestedMessage());
+ assertFalse(TestAllTypes.newBuilder().hasOneofNestedMessage());
assertHasMethodRemoved(
UnittestProto.TestAllTypes.Builder.class,
@@ -138,10 +136,6 @@ public class FieldPresenceTest extends TestCase {
UnittestProto.TestAllTypes.Builder.class,
TestAllTypes.Builder.class,
"OneofBytes");
- assertHasMethodRemoved(
- UnittestProto.TestAllTypes.Builder.class,
- TestAllTypes.Builder.class,
- "OneofNestedMessage");
}
public void testOneofEquals() throws Exception {
@@ -410,34 +404,4 @@ public class FieldPresenceTest extends TestCase {
assertTrue(builder.buildPartial().isInitialized());
}
-
- // Test that unknown fields are dropped.
- public void testUnknownFields() throws Exception {
- TestAllTypes.Builder builder = TestAllTypes.newBuilder();
- builder.setOptionalInt32(1234);
- builder.addRepeatedInt32(5678);
- TestAllTypes message = builder.build();
- ByteString data = message.toByteString();
-
- TestOptionalFieldsOnly optionalOnlyMessage =
- TestOptionalFieldsOnly.parseFrom(data);
- // UnknownFieldSet should be empty.
- assertEquals(
- 0, optionalOnlyMessage.getUnknownFields().toByteString().size());
- assertEquals(1234, optionalOnlyMessage.getOptionalInt32());
- message = TestAllTypes.parseFrom(optionalOnlyMessage.toByteString());
- assertEquals(1234, message.getOptionalInt32());
- // The repeated field is discarded because it's unknown to the optional-only
- // message.
- assertEquals(0, message.getRepeatedInt32Count());
-
- DynamicMessage dynamicOptionalOnlyMessage =
- DynamicMessage.getDefaultInstance(
- TestOptionalFieldsOnly.getDescriptor())
- .getParserForType().parseFrom(data);
- assertEquals(
- 0, dynamicOptionalOnlyMessage.getUnknownFields().toByteString().size());
- assertEquals(optionalOnlyMessage.toByteString(),
- dynamicOptionalOnlyMessage.toByteString());
- }
}
diff --git a/java/core/src/test/java/com/google/protobuf/GeneratedMessageTest.java b/java/core/src/test/java/com/google/protobuf/GeneratedMessageTest.java
index 3eece26a..c9ebe7f5 100644
--- a/java/core/src/test/java/com/google/protobuf/GeneratedMessageTest.java
+++ b/java/core/src/test/java/com/google/protobuf/GeneratedMessageTest.java
@@ -32,19 +32,14 @@ package com.google.protobuf;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
-import com.google.protobuf.UnittestLite.TestAllExtensionsLite;
import com.google.protobuf.test.UnittestImport;
import protobuf_unittest.EnumWithNoOuter;
import protobuf_unittest.MessageWithNoOuter;
import protobuf_unittest.MultipleFilesTestProto;
import protobuf_unittest.NestedExtension.MyNestedExtension;
-import protobuf_unittest.NestedExtensionLite.MyNestedExtensionLite;
import protobuf_unittest.NonNestedExtension;
import protobuf_unittest.NonNestedExtension.MessageToBeExtended;
import protobuf_unittest.NonNestedExtension.MyNonNestedExtension;
-import protobuf_unittest.NonNestedExtensionLite;
-import protobuf_unittest.NonNestedExtensionLite.MessageLiteToBeExtended;
-import protobuf_unittest.NonNestedExtensionLite.MyNonNestedExtensionLite;
import protobuf_unittest.OuterClassNameTest2OuterClass;
import protobuf_unittest.OuterClassNameTest3OuterClass;
import protobuf_unittest.OuterClassNameTestOuterClass;
@@ -712,70 +707,6 @@ public class GeneratedMessageTest extends TestCase {
}
// =================================================================
- // Lite Extensions.
-
- // We test lite extensions directly because they have a separate
- // implementation from full extensions. In contrast, we do not test
- // lite fields directly since they are implemented exactly the same as
- // regular fields.
-
- public void testLiteExtensionMessageOrBuilder() throws Exception {
- TestAllExtensionsLite.Builder builder = TestAllExtensionsLite.newBuilder();
- TestUtilLite.setAllExtensions(builder);
- TestUtil.assertAllExtensionsSet(builder);
-
- TestAllExtensionsLite message = builder.build();
- TestUtil.assertAllExtensionsSet(message);
- }
-
- public void testLiteExtensionRepeatedSetters() throws Exception {
- TestAllExtensionsLite.Builder builder = TestAllExtensionsLite.newBuilder();
- TestUtilLite.setAllExtensions(builder);
- TestUtilLite.modifyRepeatedExtensions(builder);
- TestUtil.assertRepeatedExtensionsModified(builder);
-
- TestAllExtensionsLite message = builder.build();
- TestUtil.assertRepeatedExtensionsModified(message);
- }
-
- public void testLiteExtensionDefaults() throws Exception {
- TestUtil.assertExtensionsClear(TestAllExtensionsLite.getDefaultInstance());
- TestUtil.assertExtensionsClear(TestAllExtensionsLite.newBuilder().build());
- }
-
- public void testClearLiteExtension() throws Exception {
- // clearExtension() is not actually used in TestUtil, so try it manually.
- assertFalse(
- TestAllExtensionsLite.newBuilder()
- .setExtension(UnittestLite.optionalInt32ExtensionLite, 1)
- .clearExtension(UnittestLite.optionalInt32ExtensionLite)
- .hasExtension(UnittestLite.optionalInt32ExtensionLite));
- assertEquals(0,
- TestAllExtensionsLite.newBuilder()
- .addExtension(UnittestLite.repeatedInt32ExtensionLite, 1)
- .clearExtension(UnittestLite.repeatedInt32ExtensionLite)
- .getExtensionCount(UnittestLite.repeatedInt32ExtensionLite));
- }
-
- public void testLiteExtensionCopy() throws Exception {
- TestAllExtensionsLite original = TestUtilLite.getAllLiteExtensionsSet();
- TestAllExtensionsLite copy =
- TestAllExtensionsLite.newBuilder(original).build();
- TestUtil.assertAllExtensionsSet(copy);
- }
-
- public void testLiteExtensionMergeFrom() throws Exception {
- TestAllExtensionsLite original =
- TestAllExtensionsLite.newBuilder()
- .setExtension(UnittestLite.optionalInt32ExtensionLite, 1).build();
- TestAllExtensionsLite merged =
- TestAllExtensionsLite.newBuilder().mergeFrom(original).build();
- assertTrue(merged.hasExtension(UnittestLite.optionalInt32ExtensionLite));
- assertEquals(
- 1, (int) merged.getExtension(UnittestLite.optionalInt32ExtensionLite));
- }
-
- // =================================================================
// multiple_files_test
// Test that custom options of an file level enum are properly initialized.
@@ -923,15 +854,9 @@ public class GeneratedMessageTest extends TestCase {
}
public void testEnumValues() {
- assertEquals(
- TestAllTypes.NestedEnum.BAR.getNumber(),
- TestAllTypes.NestedEnum.BAR_VALUE);
- assertEquals(
- TestAllTypes.NestedEnum.BAZ.getNumber(),
- TestAllTypes.NestedEnum.BAZ_VALUE);
- assertEquals(
- TestAllTypes.NestedEnum.FOO.getNumber(),
- TestAllTypes.NestedEnum.FOO_VALUE);
+ assertEquals(TestAllTypes.NestedEnum.BAR_VALUE, TestAllTypes.NestedEnum.BAR.getNumber());
+ assertEquals(TestAllTypes.NestedEnum.BAZ_VALUE, TestAllTypes.NestedEnum.BAZ.getNumber());
+ assertEquals(TestAllTypes.NestedEnum.FOO_VALUE, TestAllTypes.NestedEnum.FOO.getNumber());
}
public void testNonNestedExtensionInitialization() {
@@ -948,16 +873,6 @@ public class GeneratedMessageTest extends TestCase {
MyNestedExtension.recursiveExtension.getDescriptor().getName());
}
- public void testNonNestedExtensionLiteInitialization() {
- assertTrue(NonNestedExtensionLite.nonNestedExtensionLite
- .getMessageDefaultInstance() instanceof MyNonNestedExtensionLite);
- }
-
- public void testNestedExtensionLiteInitialization() {
- assertTrue(MyNestedExtensionLite.recursiveExtensionLite
- .getMessageDefaultInstance() instanceof MessageLiteToBeExtended);
- }
-
public void testInvalidations() throws Exception {
GeneratedMessage.enableAlwaysUseFieldBuildersForTesting();
TestAllTypes.NestedMessage nestedMessage1 =
@@ -1319,51 +1234,51 @@ public class GeneratedMessageTest extends TestCase {
assertFalse(builder.clearFooInt().hasFooInt());
TestOneof2 message2 = builder.build();
assertFalse(message2.hasFooInt());
- assertEquals(message2.getFooInt(), 0);
+ assertEquals(0, message2.getFooInt());
}
// Enum
{
TestOneof2.Builder builder = TestOneof2.newBuilder();
- assertEquals(builder.getFooEnum(), TestOneof2.NestedEnum.FOO);
+ assertEquals(TestOneof2.NestedEnum.FOO, builder.getFooEnum());
assertTrue(builder.setFooEnum(TestOneof2.NestedEnum.BAR).hasFooEnum());
- assertEquals(builder.getFooEnum(), TestOneof2.NestedEnum.BAR);
+ assertEquals(TestOneof2.NestedEnum.BAR, builder.getFooEnum());
TestOneof2 message = builder.buildPartial();
assertTrue(message.hasFooEnum());
- assertEquals(message.getFooEnum(), TestOneof2.NestedEnum.BAR);
+ assertEquals(TestOneof2.NestedEnum.BAR, message.getFooEnum());
assertFalse(builder.clearFooEnum().hasFooEnum());
TestOneof2 message2 = builder.build();
assertFalse(message2.hasFooEnum());
- assertEquals(message2.getFooEnum(), TestOneof2.NestedEnum.FOO);
+ assertEquals(TestOneof2.NestedEnum.FOO, message2.getFooEnum());
}
// String
{
TestOneof2.Builder builder = TestOneof2.newBuilder();
- assertEquals(builder.getFooString(), "");
+ assertEquals("", builder.getFooString());
builder.setFooString("foo");
assertTrue(builder.hasFooString());
- assertEquals(builder.getFooString(), "foo");
+ assertEquals("foo", builder.getFooString());
TestOneof2 message = builder.buildPartial();
assertTrue(message.hasFooString());
- assertEquals(message.getFooString(), "foo");
+ assertEquals("foo", message.getFooString());
assertEquals(message.getFooStringBytes(), TestUtil.toBytes("foo"));
assertFalse(builder.clearFooString().hasFooString());
TestOneof2 message2 = builder.buildPartial();
assertFalse(message2.hasFooString());
- assertEquals(message2.getFooString(), "");
+ assertEquals("", message2.getFooString());
assertEquals(message2.getFooStringBytes(), TestUtil.toBytes(""));
// Get method should not change the oneof value.
builder.setFooInt(123);
- assertEquals(builder.getFooString(), "");
+ assertEquals("", builder.getFooString());
assertEquals(builder.getFooStringBytes(), TestUtil.toBytes(""));
assertEquals(123, builder.getFooInt());
message = builder.build();
- assertEquals(message.getFooString(), "");
+ assertEquals("", message.getFooString());
assertEquals(message.getFooStringBytes(), TestUtil.toBytes(""));
assertEquals(123, message.getFooInt());
}
@@ -1371,38 +1286,38 @@ public class GeneratedMessageTest extends TestCase {
// Cord
{
TestOneof2.Builder builder = TestOneof2.newBuilder();
- assertEquals(builder.getFooCord(), "");
+ assertEquals("", builder.getFooCord());
builder.setFooCord("foo");
assertTrue(builder.hasFooCord());
- assertEquals(builder.getFooCord(), "foo");
+ assertEquals("foo", builder.getFooCord());
TestOneof2 message = builder.buildPartial();
assertTrue(message.hasFooCord());
- assertEquals(message.getFooCord(), "foo");
+ assertEquals("foo", message.getFooCord());
assertEquals(message.getFooCordBytes(), TestUtil.toBytes("foo"));
assertFalse(builder.clearFooCord().hasFooCord());
TestOneof2 message2 = builder.build();
assertFalse(message2.hasFooCord());
- assertEquals(message2.getFooCord(), "");
+ assertEquals("", message2.getFooCord());
assertEquals(message2.getFooCordBytes(), TestUtil.toBytes(""));
}
// StringPiece
{
TestOneof2.Builder builder = TestOneof2.newBuilder();
- assertEquals(builder.getFooStringPiece(), "");
+ assertEquals("", builder.getFooStringPiece());
builder.setFooStringPiece("foo");
assertTrue(builder.hasFooStringPiece());
- assertEquals(builder.getFooStringPiece(), "foo");
+ assertEquals("foo", builder.getFooStringPiece());
TestOneof2 message = builder.buildPartial();
assertTrue(message.hasFooStringPiece());
- assertEquals(message.getFooStringPiece(), "foo");
+ assertEquals("foo", message.getFooStringPiece());
assertEquals(message.getFooStringPieceBytes(), TestUtil.toBytes("foo"));
assertFalse(builder.clearFooStringPiece().hasFooStringPiece());
TestOneof2 message2 = builder.build();
assertFalse(message2.hasFooStringPiece());
- assertEquals(message2.getFooStringPiece(), "");
+ assertEquals("", message2.getFooStringPiece());
assertEquals(message2.getFooStringPieceBytes(), TestUtil.toBytes(""));
}
@@ -1410,20 +1325,20 @@ public class GeneratedMessageTest extends TestCase {
{
// set
TestOneof2.Builder builder = TestOneof2.newBuilder();
- assertEquals(builder.getFooMessage().getQuxInt(), 0);
+ assertEquals(0, builder.getFooMessage().getQuxInt());
builder.setFooMessage(
TestOneof2.NestedMessage.newBuilder().setQuxInt(234).build());
assertTrue(builder.hasFooMessage());
- assertEquals(builder.getFooMessage().getQuxInt(), 234);
+ assertEquals(234, builder.getFooMessage().getQuxInt());
TestOneof2 message = builder.buildPartial();
assertTrue(message.hasFooMessage());
- assertEquals(message.getFooMessage().getQuxInt(), 234);
+ assertEquals(234, message.getFooMessage().getQuxInt());
// clear
assertFalse(builder.clearFooMessage().hasFooString());
message = builder.build();
assertFalse(message.hasFooMessage());
- assertEquals(message.getFooMessage().getQuxInt(), 0);
+ assertEquals(0, message.getFooMessage().getQuxInt());
// nested builder
builder = TestOneof2.newBuilder();
@@ -1432,10 +1347,10 @@ public class GeneratedMessageTest extends TestCase {
assertFalse(builder.hasFooMessage());
builder.getFooMessageBuilder().setQuxInt(123);
assertTrue(builder.hasFooMessage());
- assertEquals(builder.getFooMessage().getQuxInt(), 123);
+ assertEquals(123, builder.getFooMessage().getQuxInt());
message = builder.build();
assertTrue(message.hasFooMessage());
- assertEquals(message.getFooMessage().getQuxInt(), 123);
+ assertEquals(123, message.getFooMessage().getQuxInt());
}
// LazyMessage is tested in LazyMessageLiteTest.java
@@ -1448,7 +1363,7 @@ public class GeneratedMessageTest extends TestCase {
TestOneof2 message = builder.setFooInt(123).build();
TestOneof2 message2 = TestOneof2.newBuilder().mergeFrom(message).build();
assertTrue(message2.hasFooInt());
- assertEquals(message2.getFooInt(), 123);
+ assertEquals(123, message2.getFooInt());
}
// String
@@ -1457,7 +1372,7 @@ public class GeneratedMessageTest extends TestCase {
TestOneof2 message = builder.setFooString("foo").build();
TestOneof2 message2 = TestOneof2.newBuilder().mergeFrom(message).build();
assertTrue(message2.hasFooString());
- assertEquals(message2.getFooString(), "foo");
+ assertEquals("foo", message2.getFooString());
}
// Enum
@@ -1466,7 +1381,7 @@ public class GeneratedMessageTest extends TestCase {
TestOneof2 message = builder.setFooEnum(TestOneof2.NestedEnum.BAR).build();
TestOneof2 message2 = TestOneof2.newBuilder().mergeFrom(message).build();
assertTrue(message2.hasFooEnum());
- assertEquals(message2.getFooEnum(), TestOneof2.NestedEnum.BAR);
+ assertEquals(TestOneof2.NestedEnum.BAR, message2.getFooEnum());
}
// Message
@@ -1476,7 +1391,7 @@ public class GeneratedMessageTest extends TestCase {
TestOneof2.NestedMessage.newBuilder().setQuxInt(234).build()).build();
TestOneof2 message2 = TestOneof2.newBuilder().mergeFrom(message).build();
assertTrue(message2.hasFooMessage());
- assertEquals(message2.getFooMessage().getQuxInt(), 234);
+ assertEquals(234, message2.getFooMessage().getQuxInt());
}
}
@@ -1488,7 +1403,7 @@ public class GeneratedMessageTest extends TestCase {
ByteString serialized = message.toByteString();
TestOneof2 message2 = TestOneof2.parseFrom(serialized);
assertTrue(message2.hasFooInt());
- assertEquals(message2.getFooInt(), 123);
+ assertEquals(123, message2.getFooInt());
}
// String
@@ -1498,7 +1413,7 @@ public class GeneratedMessageTest extends TestCase {
ByteString serialized = message.toByteString();
TestOneof2 message2 = TestOneof2.parseFrom(serialized);
assertTrue(message2.hasFooString());
- assertEquals(message2.getFooString(), "foo");
+ assertEquals("foo", message2.getFooString());
}
// Enum
@@ -1508,7 +1423,7 @@ public class GeneratedMessageTest extends TestCase {
ByteString serialized = message.toByteString();
TestOneof2 message2 = TestOneof2.parseFrom(serialized);
assertTrue(message2.hasFooEnum());
- assertEquals(message2.getFooEnum(), TestOneof2.NestedEnum.BAR);
+ assertEquals(TestOneof2.NestedEnum.BAR, message2.getFooEnum());
}
// Message
@@ -1519,7 +1434,7 @@ public class GeneratedMessageTest extends TestCase {
ByteString serialized = message.toByteString();
TestOneof2 message2 = TestOneof2.parseFrom(serialized);
assertTrue(message2.hasFooMessage());
- assertEquals(message2.getFooMessage().getQuxInt(), 234);
+ assertEquals(234, message2.getFooMessage().getQuxInt());
}
}
diff --git a/java/core/src/test/java/com/google/protobuf/LazyFieldTest.java b/java/core/src/test/java/com/google/protobuf/LazyFieldTest.java
index 5f013f3c..f27e8e51 100644
--- a/java/core/src/test/java/com/google/protobuf/LazyFieldTest.java
+++ b/java/core/src/test/java/com/google/protobuf/LazyFieldTest.java
@@ -32,7 +32,6 @@ package com.google.protobuf;
import protobuf_unittest.UnittestProto.TestAllExtensions;
import protobuf_unittest.UnittestProto.TestAllTypes;
-import java.io.IOException;
import junit.framework.TestCase;
/**
@@ -89,6 +88,7 @@ public class LazyFieldTest extends TestCase {
assertFalse(message.equals(lazyField.getValue()));
}
+ @SuppressWarnings("EqualsIncompatibleType") // LazyField.equals() is not symmetric
public void testEqualsObjectEx() throws Exception {
TestAllExtensions message = TestUtil.getAllExtensionsSet();
LazyField lazyField = createLazyFieldFromMessage(message);
diff --git a/java/core/src/test/java/com/google/protobuf/LazyStringArrayListTest.java b/java/core/src/test/java/com/google/protobuf/LazyStringArrayListTest.java
index d2bee2a4..2fc3124d 100644
--- a/java/core/src/test/java/com/google/protobuf/LazyStringArrayListTest.java
+++ b/java/core/src/test/java/com/google/protobuf/LazyStringArrayListTest.java
@@ -281,6 +281,7 @@ public class LazyStringArrayListTest extends TestCase {
assertGenericListImmutable(byteArrayList, byteArrayList.get(0));
}
+ @SuppressWarnings("unchecked")
private static <T> void assertGenericListImmutable(List<T> list, T value) {
try {
list.add(value);
diff --git a/java/core/src/test/java/com/google/protobuf/LiteTest.java b/java/core/src/test/java/com/google/protobuf/LiteTest.java
index 538432f7..40b44538 100644
--- a/java/core/src/test/java/com/google/protobuf/LiteTest.java
+++ b/java/core/src/test/java/com/google/protobuf/LiteTest.java
@@ -33,6 +33,7 @@ package com.google.protobuf;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
+import com.google.protobuf.FieldPresenceTestProto.TestAllTypes;
import com.google.protobuf.UnittestImportLite.ImportEnumLite;
import com.google.protobuf.UnittestImportPublicLite.PublicImportMessageLite;
import com.google.protobuf.UnittestLite.ForeignEnumLite;
@@ -52,6 +53,12 @@ import protobuf_unittest.lite_equals_and_hash.LiteEqualsAndHash.BarPrime;
import protobuf_unittest.lite_equals_and_hash.LiteEqualsAndHash.Foo;
import protobuf_unittest.lite_equals_and_hash.LiteEqualsAndHash.TestOneofEquals;
import protobuf_unittest.lite_equals_and_hash.LiteEqualsAndHash.TestRecursiveOneof;
+import java.lang.reflect.Field;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.List;
import junit.framework.TestCase;
/**
@@ -154,6 +161,31 @@ public class LiteTest extends TestCase {
// expected.
}
}
+
+ public void testMemoization() throws Exception {
+ TestAllExtensionsLite message = TestUtilLite.getAllLiteExtensionsSet();
+
+ // Test serialized size is memoized
+ message.memoizedSerializedSize = -1;
+ int size = message.getSerializedSize();
+ assertTrue(size > 0);
+ assertEquals(size, message.memoizedSerializedSize);
+
+ // Test hashCode is memoized
+ assertEquals(0, message.memoizedHashCode);
+ int hashCode = message.hashCode();
+ assertTrue(hashCode != 0);
+ assertEquals(hashCode, message.memoizedHashCode);
+
+ // Test isInitialized is memoized
+ Field memo = message.getClass().getDeclaredField("memoizedIsInitialized");
+ memo.setAccessible(true);
+ memo.set(message, (byte) -1);
+ boolean initialized = message.isInitialized();
+ assertTrue(initialized);
+ // We have to cast to Byte first. Casting to byte causes a type error
+ assertEquals(1, ((Byte) memo.get(message)).intValue());
+ }
public void testSanityCopyOnWrite() throws InvalidProtocolBufferException {
// Since builders are implemented as a thin wrapper around a message
@@ -1421,6 +1453,45 @@ public class LiteTest extends TestCase {
UnittestLite.optionalFixed32ExtensionLite));
}
+ public void testBuilderMergeFromNull() throws Exception {
+ try {
+ TestAllTypesLite.newBuilder().mergeFrom((TestAllTypesLite) null);
+ fail("Expected exception");
+ } catch (NullPointerException e) {
+ // Pass.
+ }
+ }
+
+ // Builder.mergeFrom() should keep existing extensions.
+ public void testBuilderMergeFromWithExtensions() throws Exception {
+ TestAllExtensionsLite message =
+ TestAllExtensionsLite.newBuilder()
+ .addExtension(UnittestLite.repeatedInt32ExtensionLite, 12)
+ .build();
+
+ ExtensionRegistryLite registry = ExtensionRegistryLite.newInstance();
+ UnittestLite.registerAllExtensions(registry);
+
+ TestAllExtensionsLite.Builder builder = TestAllExtensionsLite.newBuilder();
+ builder.mergeFrom(message.toByteArray(), registry);
+ builder.mergeFrom(message.toByteArray(), registry);
+ TestAllExtensionsLite result = builder.build();
+ assertEquals(2, result.getExtensionCount(UnittestLite.repeatedInt32ExtensionLite));
+ assertEquals(12, result.getExtension(UnittestLite.repeatedInt32ExtensionLite, 0).intValue());
+ assertEquals(12, result.getExtension(UnittestLite.repeatedInt32ExtensionLite, 1).intValue());
+ }
+
+ // Builder.mergeFrom() should keep existing unknown fields.
+ public void testBuilderMergeFromWithUnknownFields() throws Exception {
+ TestAllTypesLite message = TestAllTypesLite.newBuilder().addRepeatedInt32(1).build();
+
+ NestedMessage.Builder builder = NestedMessage.newBuilder();
+ builder.mergeFrom(message.toByteArray());
+ builder.mergeFrom(message.toByteArray());
+ NestedMessage result = builder.build();
+ assertEquals(message.getSerializedSize() * 2, result.getSerializedSize());
+ }
+
public void testToStringDefaultInstance() throws Exception {
assertToStringEquals("", TestAllTypesLite.getDefaultInstance());
}
@@ -2174,6 +2245,24 @@ public class LiteTest extends TestCase {
assertFalse(bar.equals(barPrime));
}
+ public void testEqualsAndHashCodeForTrickySchemaTypes() {
+ Foo foo1 = Foo.newBuilder()
+ .build();
+ Foo foo2 = Foo.newBuilder()
+ .setSint64(1)
+ .build();
+ Foo foo3 = Foo.newBuilder()
+ .putMyMap("key", "value2")
+ .build();
+ Foo foo4 = Foo.newBuilder()
+ .setMyGroup(Foo.MyGroup.newBuilder().setValue(4).build())
+ .build();
+
+ assertEqualsAndHashCodeAreFalse(foo1, foo2);
+ assertEqualsAndHashCodeAreFalse(foo1, foo3);
+ assertEqualsAndHashCodeAreFalse(foo1, foo4);
+ }
+
public void testOneofEquals() throws Exception {
TestOneofEquals.Builder builder = TestOneofEquals.newBuilder();
TestOneofEquals message1 = builder.build();
@@ -2270,4 +2359,284 @@ public class LiteTest extends TestCase {
// This tests that we don't infinite loop.
TestRecursiveOneof.getDefaultInstance().hashCode();
}
+
+ public void testParseFromByteBuffer() throws Exception {
+ TestAllTypesLite message =
+ TestAllTypesLite.newBuilder()
+ .setOptionalInt32(123)
+ .addRepeatedString("hello")
+ .setOptionalNestedMessage(TestAllTypesLite.NestedMessage.newBuilder().setBb(7))
+ .build();
+
+ TestAllTypesLite copy =
+ TestAllTypesLite.parseFrom(message.toByteString().asReadOnlyByteBuffer());
+
+ assertEquals(message, copy);
+ }
+
+ public void testParseFromByteBufferThrows() {
+ try {
+ TestAllTypesLite.parseFrom(ByteBuffer.wrap(new byte[] { 0x5 }));
+ fail();
+ } catch (InvalidProtocolBufferException expected) {
+ }
+
+ TestAllTypesLite message =
+ TestAllTypesLite.newBuilder()
+ .setOptionalInt32(123)
+ .addRepeatedString("hello")
+ .build();
+
+ ByteBuffer buffer = ByteBuffer.wrap(message.toByteArray(), 0, message.getSerializedSize() - 1);
+ try {
+ TestAllTypesLite.parseFrom(buffer);
+ fail();
+ } catch (InvalidProtocolBufferException expected) {
+ assertEquals(
+ TestAllTypesLite.newBuilder()
+ .setOptionalInt32(123)
+ .build(),
+ expected.getUnfinishedMessage());
+ }
+ }
+
+ public void testParseFromByteBuffer_extensions() throws Exception {
+ TestAllExtensionsLite message =
+ TestAllExtensionsLite.newBuilder()
+ .setExtension(UnittestLite.optionalInt32ExtensionLite, 123)
+ .addExtension(UnittestLite.repeatedStringExtensionLite, "hello")
+ .setExtension(
+ UnittestLite.optionalNestedEnumExtensionLite, TestAllTypesLite.NestedEnum.BAZ)
+ .setExtension(
+ UnittestLite.optionalNestedMessageExtensionLite,
+ TestAllTypesLite.NestedMessage.newBuilder().setBb(7).build())
+ .build();
+
+ ExtensionRegistryLite registry = ExtensionRegistryLite.newInstance();
+ UnittestLite.registerAllExtensions(registry);
+
+ TestAllExtensionsLite copy =
+ TestAllExtensionsLite.parseFrom(message.toByteString().asReadOnlyByteBuffer(), registry);
+
+ assertEquals(message, copy);
+ }
+
+ public void testParseFromByteBufferThrows_extensions() {
+ ExtensionRegistryLite registry = ExtensionRegistryLite.newInstance();
+ UnittestLite.registerAllExtensions(registry);
+ try {
+ TestAllExtensionsLite.parseFrom(ByteBuffer.wrap(new byte[] { 0x5 }), registry);
+ fail();
+ } catch (InvalidProtocolBufferException expected) {
+ }
+
+ TestAllExtensionsLite message =
+ TestAllExtensionsLite.newBuilder()
+ .setExtension(UnittestLite.optionalInt32ExtensionLite, 123)
+ .addExtension(UnittestLite.repeatedStringExtensionLite, "hello")
+ .build();
+
+ ByteBuffer buffer = ByteBuffer.wrap(message.toByteArray(), 0, message.getSerializedSize() - 1);
+ try {
+ TestAllExtensionsLite.parseFrom(buffer, registry);
+ fail();
+ } catch (InvalidProtocolBufferException expected) {
+ assertEquals(
+ TestAllExtensionsLite.newBuilder()
+ .setExtension(UnittestLite.optionalInt32ExtensionLite, 123)
+ .build(),
+ expected.getUnfinishedMessage());
+ }
+ }
+
+ // Make sure we haven't screwed up the code generation for packing fields by default.
+ public void testPackedSerialization() throws Exception {
+ TestAllTypes.Builder builder = TestAllTypes.newBuilder();
+ builder.addRepeatedInt32(4321);
+ builder.addRepeatedNestedEnum(TestAllTypes.NestedEnum.BAZ);
+ TestAllTypes message = builder.build();
+
+ CodedInputStream in = CodedInputStream.newInstance(message.toByteArray());
+
+ while (!in.isAtEnd()) {
+ int tag = in.readTag();
+ assertEquals(WireFormat.WIRETYPE_LENGTH_DELIMITED, WireFormat.getTagWireType(tag));
+ in.skipField(tag);
+ }
+ }
+
+ public void testAddAllIteratesOnce() {
+ TestAllTypesLite message =
+ TestAllTypesLite.newBuilder()
+ .addAllRepeatedBool(new OneTimeIterableList(false))
+ .addAllRepeatedInt32(new OneTimeIterableList(0))
+ .addAllRepeatedInt64(new OneTimeIterableList(0L))
+ .addAllRepeatedFloat(new OneTimeIterableList(0f))
+ .addAllRepeatedDouble(new OneTimeIterableList(0d))
+ .addAllRepeatedBytes(new OneTimeIterableList(ByteString.EMPTY))
+ .addAllRepeatedString(new OneTimeIterableList(""))
+ .addAllRepeatedNestedMessage(
+ new OneTimeIterableList(NestedMessage.getDefaultInstance()))
+ .addAllRepeatedBool(new OneTimeIterable(false))
+ .addAllRepeatedInt32(new OneTimeIterable(0))
+ .addAllRepeatedInt64(new OneTimeIterable(0L))
+ .addAllRepeatedFloat(new OneTimeIterable(0f))
+ .addAllRepeatedDouble(new OneTimeIterable(0d))
+ .addAllRepeatedBytes(new OneTimeIterable(ByteString.EMPTY))
+ .addAllRepeatedString(new OneTimeIterable(""))
+ .addAllRepeatedNestedMessage(new OneTimeIterable(NestedMessage.getDefaultInstance()))
+ .build();
+ }
+
+ public void testAddAllIteratesOnce_throwsOnNull() {
+ TestAllTypesLite.Builder builder = TestAllTypesLite.newBuilder();
+ try {
+ builder.addAllRepeatedBool(new OneTimeIterableList(true, false, (Boolean) null));
+ fail();
+ } catch (NullPointerException expected) {
+ assertEquals("Element at index 2 is null.", expected.getMessage());
+ assertEquals(0, builder.getRepeatedBoolCount());
+ }
+
+ try {
+ builder.addAllRepeatedBool(new OneTimeIterable(true, false, (Boolean) null));
+ fail();
+ } catch (NullPointerException expected) {
+ assertEquals("Element at index 2 is null.", expected.getMessage());
+ assertEquals(0, builder.getRepeatedBoolCount());
+ }
+
+ try {
+ builder = TestAllTypesLite.newBuilder();
+ builder.addAllRepeatedBool(new OneTimeIterableList((Boolean) null));
+ fail();
+ } catch (NullPointerException expected) {
+ assertEquals("Element at index 0 is null.", expected.getMessage());
+ assertEquals(0, builder.getRepeatedBoolCount());
+ }
+
+ try {
+ builder = TestAllTypesLite.newBuilder();
+ builder.addAllRepeatedInt32(new OneTimeIterableList((Integer) null));
+ fail();
+ } catch (NullPointerException expected) {
+ assertEquals("Element at index 0 is null.", expected.getMessage());
+ assertEquals(0, builder.getRepeatedInt32Count());
+ }
+
+ try {
+ builder = TestAllTypesLite.newBuilder();
+ builder.addAllRepeatedInt64(new OneTimeIterableList((Long) null));
+ fail();
+ } catch (NullPointerException expected) {
+ assertEquals("Element at index 0 is null.", expected.getMessage());
+ assertEquals(0, builder.getRepeatedInt64Count());
+ }
+
+ try {
+ builder = TestAllTypesLite.newBuilder();
+ builder.addAllRepeatedFloat(new OneTimeIterableList((Float) null));
+ fail();
+ } catch (NullPointerException expected) {
+ assertEquals("Element at index 0 is null.", expected.getMessage());
+ assertEquals(0, builder.getRepeatedFloatCount());
+ }
+
+ try {
+ builder = TestAllTypesLite.newBuilder();
+ builder.addAllRepeatedDouble(new OneTimeIterableList((Double) null));
+ fail();
+ } catch (NullPointerException expected) {
+ assertEquals("Element at index 0 is null.", expected.getMessage());
+ assertEquals(0, builder.getRepeatedDoubleCount());
+ }
+
+ try {
+ builder = TestAllTypesLite.newBuilder();
+ builder.addAllRepeatedBytes(new OneTimeIterableList((ByteString) null));
+ fail();
+ } catch (NullPointerException expected) {
+ assertEquals("Element at index 0 is null.", expected.getMessage());
+ assertEquals(0, builder.getRepeatedBytesCount());
+ }
+
+ try {
+ builder = TestAllTypesLite.newBuilder();
+ builder.addAllRepeatedString(new OneTimeIterableList("", "", (String) null, ""));
+ fail();
+ } catch (NullPointerException expected) {
+ assertEquals("Element at index 2 is null.", expected.getMessage());
+ assertEquals(0, builder.getRepeatedStringCount());
+ }
+
+ try {
+ builder = TestAllTypesLite.newBuilder();
+ builder.addAllRepeatedString(new OneTimeIterable("", "", (String) null, ""));
+ fail();
+ } catch (NullPointerException expected) {
+ assertEquals("Element at index 2 is null.", expected.getMessage());
+ assertEquals(0, builder.getRepeatedStringCount());
+ }
+
+ try {
+ builder = TestAllTypesLite.newBuilder();
+ builder.addAllRepeatedString(new OneTimeIterableList((String) null));
+ fail();
+ } catch (NullPointerException expected) {
+ assertEquals("Element at index 0 is null.", expected.getMessage());
+ assertEquals(0, builder.getRepeatedStringCount());
+ }
+
+ try {
+ builder = TestAllTypesLite.newBuilder();
+ builder.addAllRepeatedNestedMessage(new OneTimeIterableList((NestedMessage) null));
+ fail();
+ } catch (NullPointerException expected) {
+ assertEquals("Element at index 0 is null.", expected.getMessage());
+ assertEquals(0, builder.getRepeatedNestedMessageCount());
+ }
+ }
+
+ private static final class OneTimeIterableList<T> extends ArrayList<T> {
+ private boolean wasIterated = false;
+
+ OneTimeIterableList(T... contents) {
+ addAll(Arrays.asList(contents));
+ }
+
+ @Override
+ public Iterator<T> iterator() {
+ if (wasIterated) {
+ fail();
+ }
+ wasIterated = true;
+ return super.iterator();
+ }
+ }
+
+ private static final class OneTimeIterable<T> implements Iterable<T> {
+ private final List<T> list;
+ private boolean wasIterated = false;
+
+ OneTimeIterable(T... contents) {
+ list = Arrays.asList(contents);
+ }
+
+ @Override
+ public Iterator<T> iterator() {
+ if (wasIterated) {
+ fail();
+ }
+ wasIterated = true;
+ return list.iterator();
+ }
+ }
+
+ public void testNullExtensionRegistry() throws Exception {
+ try {
+ TestAllTypesLite.parseFrom(new byte[] {}, null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
}
diff --git a/java/core/src/test/java/com/google/protobuf/MapForProto2LiteTest.java b/java/core/src/test/java/com/google/protobuf/MapForProto2LiteTest.java
index 0a14f584..da9195f9 100644
--- a/java/core/src/test/java/com/google/protobuf/MapForProto2LiteTest.java
+++ b/java/core/src/test/java/com/google/protobuf/MapForProto2LiteTest.java
@@ -408,12 +408,12 @@ public final class MapForProto2LiteTest extends TestCase {
TestMap map = tryParseTestMap(BizarroTestMap.newBuilder()
.putInt32ToInt32Field(5, bytes)
.build());
- assertEquals(map.getInt32ToInt32FieldOrDefault(5, -1), 0);
+ assertEquals(0, map.getInt32ToInt32FieldOrDefault(5, -1));
map = tryParseTestMap(BizarroTestMap.newBuilder()
.putInt32ToStringField(stringKey, 5)
.build());
- assertEquals(map.getInt32ToStringFieldOrDefault(0, null), "");
+ assertEquals("", map.getInt32ToStringFieldOrDefault(0, null));
map = tryParseTestMap(BizarroTestMap.newBuilder()
.putInt32ToBytesField(stringKey, 5)
@@ -423,7 +423,7 @@ public final class MapForProto2LiteTest extends TestCase {
map = tryParseTestMap(BizarroTestMap.newBuilder()
.putInt32ToEnumField(stringKey, bytes)
.build());
- assertEquals(map.getInt32ToEnumFieldOrDefault(0, null), TestMap.EnumValue.FOO);
+ assertEquals(TestMap.EnumValue.FOO, map.getInt32ToEnumFieldOrDefault(0, null));
try {
tryParseTestMap(BizarroTestMap.newBuilder()
@@ -439,7 +439,7 @@ public final class MapForProto2LiteTest extends TestCase {
map = tryParseTestMap(BizarroTestMap.newBuilder()
.putStringToInt32Field(stringKey, bytes)
.build());
- assertEquals(map.getStringToInt32FieldOrDefault(stringKey, -1), 0);
+ assertEquals(0, map.getStringToInt32FieldOrDefault(stringKey, -1));
}
public void testMergeFrom() throws Exception {
diff --git a/java/core/src/test/java/com/google/protobuf/MapForProto2Test.java b/java/core/src/test/java/com/google/protobuf/MapForProto2Test.java
index cfe4c453..37827f76 100644
--- a/java/core/src/test/java/com/google/protobuf/MapForProto2Test.java
+++ b/java/core/src/test/java/com/google/protobuf/MapForProto2Test.java
@@ -546,12 +546,12 @@ public class MapForProto2Test extends TestCase {
TestMap map = tryParseTestMap(BizarroTestMap.newBuilder()
.putInt32ToInt32Field(5, bytes)
.build());
- assertEquals(map.getInt32ToInt32FieldOrDefault(5, -1), 0);
+ assertEquals(0, map.getInt32ToInt32FieldOrDefault(5, -1));
map = tryParseTestMap(BizarroTestMap.newBuilder()
.putInt32ToStringField(stringKey, 5)
.build());
- assertEquals(map.getInt32ToStringFieldOrDefault(0, null), "");
+ assertEquals("", map.getInt32ToStringFieldOrDefault(0, null));
map = tryParseTestMap(BizarroTestMap.newBuilder()
.putInt32ToBytesField(stringKey, 5)
@@ -561,7 +561,7 @@ public class MapForProto2Test extends TestCase {
map = tryParseTestMap(BizarroTestMap.newBuilder()
.putInt32ToEnumField(stringKey, bytes)
.build());
- assertEquals(map.getInt32ToEnumFieldOrDefault(0, null), TestMap.EnumValue.FOO);
+ assertEquals(TestMap.EnumValue.FOO, map.getInt32ToEnumFieldOrDefault(0, null));
try {
tryParseTestMap(BizarroTestMap.newBuilder()
@@ -577,7 +577,7 @@ public class MapForProto2Test extends TestCase {
map = tryParseTestMap(BizarroTestMap.newBuilder()
.putStringToInt32Field(stringKey, bytes)
.build());
- assertEquals(map.getStringToInt32FieldOrDefault(stringKey, -1), 0);
+ assertEquals(0, map.getStringToInt32FieldOrDefault(stringKey, -1));
}
public void testMergeFrom() throws Exception {
@@ -759,6 +759,7 @@ public class MapForProto2Test extends TestCase {
assertEquals(55, message.getInt32ToInt32Field().get(55).intValue());
}
+ // See additional coverage in TextFormatTest.java.
public void testTextFormat() throws Exception {
TestMap.Builder builder = TestMap.newBuilder();
setMapValuesUsingAccessors(builder);
diff --git a/java/core/src/test/java/com/google/protobuf/MapTest.java b/java/core/src/test/java/com/google/protobuf/MapTest.java
index 81e951cc..64ae4435 100644
--- a/java/core/src/test/java/com/google/protobuf/MapTest.java
+++ b/java/core/src/test/java/com/google/protobuf/MapTest.java
@@ -30,7 +30,7 @@
package com.google.protobuf;
-
+import static org.junit.Assert.assertArrayEquals;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.EnumDescriptor;
import com.google.protobuf.Descriptors.EnumValueDescriptor;
@@ -490,19 +490,13 @@ public class MapTest extends TestCase {
public void testPutForUnknownEnumValues() throws Exception {
TestMap.Builder builder = TestMap.newBuilder()
.putInt32ToEnumFieldValue(0, 0)
- .putInt32ToEnumFieldValue(1, 1);
-
- try {
- builder.putInt32ToEnumFieldValue(2, 1000); // unknown value.
- fail();
- } catch (IllegalArgumentException e) {
- // expected
- }
-
+ .putInt32ToEnumFieldValue(1, 1)
+ .putInt32ToEnumFieldValue(2, 1000); // unknown value.
TestMap message = builder.build();
assertEquals(0, message.getInt32ToEnumFieldValueOrThrow(0));
assertEquals(1, message.getInt32ToEnumFieldValueOrThrow(1));
- assertEquals(2, message.getInt32ToEnumFieldCount());
+ assertEquals(1000, message.getInt32ToEnumFieldValueOrThrow(2));
+ assertEquals(3, message.getInt32ToEnumFieldCount());
}
public void testPutChecksNullKeysAndValues() throws Exception {
@@ -582,12 +576,12 @@ public class MapTest extends TestCase {
TestMap map = tryParseTestMap(BizarroTestMap.newBuilder()
.putInt32ToInt32Field(5, bytes)
.build());
- assertEquals(map.getInt32ToInt32FieldOrDefault(5, -1), 0);
+ assertEquals(0, map.getInt32ToInt32FieldOrDefault(5, -1));
map = tryParseTestMap(BizarroTestMap.newBuilder()
.putInt32ToStringField(stringKey, 5)
.build());
- assertEquals(map.getInt32ToStringFieldOrDefault(0, null), "");
+ assertEquals("", map.getInt32ToStringFieldOrDefault(0, null));
map = tryParseTestMap(BizarroTestMap.newBuilder()
.putInt32ToBytesField(stringKey, 5)
@@ -597,7 +591,7 @@ public class MapTest extends TestCase {
map = tryParseTestMap(BizarroTestMap.newBuilder()
.putInt32ToEnumField(stringKey, bytes)
.build());
- assertEquals(map.getInt32ToEnumFieldOrDefault(0, null), TestMap.EnumValue.FOO);
+ assertEquals(TestMap.EnumValue.FOO, map.getInt32ToEnumFieldOrDefault(0, null));
try {
tryParseTestMap(BizarroTestMap.newBuilder()
@@ -613,7 +607,7 @@ public class MapTest extends TestCase {
map = tryParseTestMap(BizarroTestMap.newBuilder()
.putStringToInt32Field(stringKey, bytes)
.build());
- assertEquals(map.getStringToInt32FieldOrDefault(stringKey, -1), 0);
+ assertEquals(0, map.getStringToInt32FieldOrDefault(stringKey, -1));
}
public void testMergeFrom() throws Exception {
@@ -870,6 +864,7 @@ public class MapTest extends TestCase {
assertEquals(55, message.getInt32ToInt32Field().get(55).intValue());
}
+ // See additional coverage in TextFormatTest.java.
public void testTextFormat() throws Exception {
TestMap.Builder builder = TestMap.newBuilder();
setMapValuesUsingAccessors(builder);
@@ -1250,12 +1245,9 @@ public class MapTest extends TestCase {
builder.putInt32ToEnumFieldValue(1, TestMap.EnumValue.BAR.getNumber());
assertEquals(
TestMap.EnumValue.BAR.getNumber(), builder.getInt32ToEnumFieldValueOrThrow(1));
- try {
- builder.putInt32ToEnumFieldValue(1, -1);
- fail();
- } catch (IllegalArgumentException e) {
- // expected
- }
+ builder.putInt32ToEnumFieldValue(1, -1);
+ assertEquals(-1, builder.getInt32ToEnumFieldValueOrThrow(1));
+ assertEquals(TestMap.EnumValue.UNRECOGNIZED, builder.getInt32ToEnumFieldOrThrow(1));
builder.putStringToInt32Field("a", 1);
assertEquals(1, builder.getStringToInt32FieldOrThrow("a"));
@@ -1492,4 +1484,41 @@ public class MapTest extends TestCase {
map.put(key3, value3);
return map;
}
+
+ public void testMap_withNulls() {
+ TestMap.Builder builder = TestMap.newBuilder();
+
+ try {
+ builder.putStringToInt32Field(null, 3);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+
+ try {
+ builder.putAllStringToInt32Field(newMap(null, 3, "hi", 4));
+ fail();
+ } catch (NullPointerException expected) {
+ }
+
+ try {
+ builder.putInt32ToMessageField(3, null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+
+ try {
+ builder.putAllInt32ToMessageField(
+ MapTest.<Integer, MessageValue>newMap(4, null, 5, null));
+ fail();
+ } catch (NullPointerException expected) {
+ }
+
+ try {
+ builder.putAllInt32ToMessageField(null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+
+ assertArrayEquals(new byte[0], builder.build().toByteArray());
+ }
}
diff --git a/java/core/src/test/java/com/google/protobuf/MessageTest.java b/java/core/src/test/java/com/google/protobuf/MessageTest.java
index 75b79a34..4fc8f78e 100644
--- a/java/core/src/test/java/com/google/protobuf/MessageTest.java
+++ b/java/core/src/test/java/com/google/protobuf/MessageTest.java
@@ -74,6 +74,14 @@ public class MessageTest extends TestCase {
"repeated_string: \"qux\"\n" +
"repeated_string: \"bar\"\n";
+ public void testParsingWithNullExtensionRegistry() throws Exception {
+ try {
+ TestAllTypes.parseFrom(new byte[] {}, null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
+
public void testMergeFrom() throws Exception {
TestAllTypes result =
TestAllTypes.newBuilder(MERGE_DEST)
@@ -321,8 +329,10 @@ public class MessageTest extends TestCase {
assertTrue(result.getField(result.getDescriptorForType()
.findFieldByName("repeated_foreign_message")) instanceof List<?>);
- assertEquals(result.getRepeatedFieldCount(result.getDescriptorForType()
- .findFieldByName("repeated_foreign_message")), 0);
+ assertEquals(
+ 0,
+ result.getRepeatedFieldCount(
+ result.getDescriptorForType().findFieldByName("repeated_foreign_message")));
}
/** Test reading repeated message from DynamicMessage. */
@@ -345,7 +355,9 @@ public class MessageTest extends TestCase {
assertTrue(result.getField(result.getDescriptorForType()
.findFieldByName("repeated_foreign_message")) instanceof List<?>);
- assertEquals(result.getRepeatedFieldCount(result.getDescriptorForType()
- .findFieldByName("repeated_foreign_message")), 2);
+ assertEquals(
+ 2,
+ result.getRepeatedFieldCount(
+ result.getDescriptorForType().findFieldByName("repeated_foreign_message")));
}
}
diff --git a/java/core/src/test/java/com/google/protobuf/ParserTest.java b/java/core/src/test/java/com/google/protobuf/ParserTest.java
index 8c2e4c26..1e891112 100644
--- a/java/core/src/test/java/com/google/protobuf/ParserTest.java
+++ b/java/core/src/test/java/com/google/protobuf/ParserTest.java
@@ -30,9 +30,6 @@
package com.google.protobuf;
-import com.google.protobuf.UnittestLite.TestAllTypesLite;
-import com.google.protobuf.UnittestLite.TestPackedExtensionsLite;
-import com.google.protobuf.UnittestLite.TestParsingMergeLite;
import protobuf_unittest.UnittestOptimizeFor;
import protobuf_unittest.UnittestOptimizeFor.TestOptimizedForSize;
import protobuf_unittest.UnittestOptimizeFor.TestRequiredOptimizedForSize;
@@ -79,6 +76,8 @@ public class ParserTest extends TestCase {
new ByteArrayInputStream(data), registry));
assertMessageEquals(message, parser.parseFrom(
CodedInputStream.newInstance(data), registry));
+ assertMessageEquals(
+ message, parser.parseFrom(message.toByteString().asReadOnlyByteBuffer(), registry));
}
@SuppressWarnings("unchecked")
@@ -99,6 +98,7 @@ public class ParserTest extends TestCase {
new ByteArrayInputStream(data)));
assertMessageEquals(message, parser.parseFrom(
CodedInputStream.newInstance(data)));
+ assertMessageEquals(message, parser.parseFrom(message.toByteString().asReadOnlyByteBuffer()));
}
private void assertMessageEquals(
@@ -178,16 +178,12 @@ public class ParserTest extends TestCase {
public void testParseExtensions() throws Exception {
assertRoundTripEquals(TestUtil.getAllExtensionsSet(),
TestUtil.getExtensionRegistry());
- assertRoundTripEquals(
- TestUtilLite.getAllLiteExtensionsSet(), TestUtilLite.getExtensionRegistryLite());
}
public void testParsePacked() throws Exception {
assertRoundTripEquals(TestUtil.getPackedSet());
assertRoundTripEquals(TestUtil.getPackedExtensionsSet(),
TestUtil.getExtensionRegistry());
- assertRoundTripEquals(
- TestUtilLite.getLitePackedExtensionsSet(), TestUtilLite.getExtensionRegistryLite());
}
public void testParseDelimitedTo() throws Exception {
@@ -195,20 +191,11 @@ public class ParserTest extends TestCase {
TestAllTypes normalMessage = TestUtil.getAllSet();
ByteArrayOutputStream output = new ByteArrayOutputStream();
normalMessage.writeDelimitedTo(output);
-
- // Write MessageLite with packed extension fields.
- TestPackedExtensionsLite packedMessage = TestUtilLite.getLitePackedExtensionsSet();
- packedMessage.writeDelimitedTo(output);
+ normalMessage.writeDelimitedTo(output);
InputStream input = new ByteArrayInputStream(output.toByteArray());
- assertMessageEquals(
- normalMessage,
- normalMessage.getParserForType().parseDelimitedFrom(input));
- assertMessageEquals(
- packedMessage,
- packedMessage
- .getParserForType()
- .parseDelimitedFrom(input, TestUtilLite.getExtensionRegistryLite()));
+ assertMessageEquals(normalMessage, normalMessage.getParserForType().parseDelimitedFrom(input));
+ assertMessageEquals(normalMessage, normalMessage.getParserForType().parseDelimitedFrom(input));
}
public void testParseUnknownFields() throws Exception {
@@ -243,14 +230,6 @@ public class ParserTest extends TestCase {
assertEquals("hello", allTypes.getOptionalString());
}
- /** Helper method for {@link #testParsingMergeLite()}.*/
- private void assertMessageMerged(TestAllTypesLite allTypes)
- throws Exception {
- assertEquals(3, allTypes.getOptionalInt32());
- assertEquals(2, allTypes.getOptionalInt64());
- assertEquals("hello", allTypes.getOptionalString());
- }
-
public void testParsingMerge() throws Exception {
// Build messages.
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
@@ -312,68 +291,6 @@ public class ParserTest extends TestCase {
TestParsingMerge.repeatedExt));
}
- public void testParsingMergeLite() throws Exception {
- // Build messages.
- TestAllTypesLite.Builder builder =
- TestAllTypesLite.newBuilder();
- TestAllTypesLite msg1 = builder.setOptionalInt32(1).build();
- builder.clear();
- TestAllTypesLite msg2 = builder.setOptionalInt64(2).build();
- builder.clear();
- TestAllTypesLite msg3 = builder.setOptionalInt32(3)
- .setOptionalString("hello").build();
-
- // Build groups.
- TestParsingMergeLite.RepeatedFieldsGenerator.Group1 optionalG1 =
- TestParsingMergeLite.RepeatedFieldsGenerator.Group1.newBuilder()
- .setField1(msg1).build();
- TestParsingMergeLite.RepeatedFieldsGenerator.Group1 optionalG2 =
- TestParsingMergeLite.RepeatedFieldsGenerator.Group1.newBuilder()
- .setField1(msg2).build();
- TestParsingMergeLite.RepeatedFieldsGenerator.Group1 optionalG3 =
- TestParsingMergeLite.RepeatedFieldsGenerator.Group1.newBuilder()
- .setField1(msg3).build();
- TestParsingMergeLite.RepeatedFieldsGenerator.Group2 repeatedG1 =
- TestParsingMergeLite.RepeatedFieldsGenerator.Group2.newBuilder()
- .setField1(msg1).build();
- TestParsingMergeLite.RepeatedFieldsGenerator.Group2 repeatedG2 =
- TestParsingMergeLite.RepeatedFieldsGenerator.Group2.newBuilder()
- .setField1(msg2).build();
- TestParsingMergeLite.RepeatedFieldsGenerator.Group2 repeatedG3 =
- TestParsingMergeLite.RepeatedFieldsGenerator.Group2.newBuilder()
- .setField1(msg3).build();
-
- // Assign and serialize RepeatedFieldsGenerator.
- ByteString data = TestParsingMergeLite.RepeatedFieldsGenerator.newBuilder()
- .addField1(msg1).addField1(msg2).addField1(msg3)
- .addField2(msg1).addField2(msg2).addField2(msg3)
- .addField3(msg1).addField3(msg2).addField3(msg3)
- .addGroup1(optionalG1).addGroup1(optionalG2).addGroup1(optionalG3)
- .addGroup2(repeatedG1).addGroup2(repeatedG2).addGroup2(repeatedG3)
- .addExt1(msg1).addExt1(msg2).addExt1(msg3)
- .addExt2(msg1).addExt2(msg2).addExt2(msg3)
- .build().toByteString();
-
- // Parse TestParsingMergeLite.
- ExtensionRegistry registry = ExtensionRegistry.newInstance();
- UnittestLite.registerAllExtensions(registry);
- TestParsingMergeLite parsingMerge = TestParsingMergeLite.parser().parseFrom(data, registry);
-
- // Required and optional fields should be merged.
- assertMessageMerged(parsingMerge.getRequiredAllTypes());
- assertMessageMerged(parsingMerge.getOptionalAllTypes());
- assertMessageMerged(
- parsingMerge.getOptionalGroup().getOptionalGroupAllTypes());
- assertMessageMerged(parsingMerge.getExtension(
- TestParsingMergeLite.optionalExt));
-
- // Repeated fields should not be merged.
- assertEquals(3, parsingMerge.getRepeatedAllTypesCount());
- assertEquals(3, parsingMerge.getRepeatedGroupCount());
- assertEquals(3, parsingMerge.getExtensionCount(
- TestParsingMergeLite.repeatedExt));
- }
-
public void testParseDelimitedFrom_firstByteInterrupted_preservesCause() {
try {
TestUtil.getAllSet().parseDelimitedFrom(
diff --git a/java/core/src/test/java/com/google/protobuf/TestBadIdentifiers.java b/java/core/src/test/java/com/google/protobuf/TestBadIdentifiers.java
index 2c60fe0e..4af55429 100644
--- a/java/core/src/test/java/com/google/protobuf/TestBadIdentifiers.java
+++ b/java/core/src/test/java/com/google/protobuf/TestBadIdentifiers.java
@@ -92,5 +92,31 @@ public class TestBadIdentifiers extends TestCase {
assertEquals(0L, message.getExtension(
TestBadIdentifiersProto.TestConflictingFieldNames.int64FieldList).longValue());
+ assertEquals("", message.getFieldName32());
+ assertEquals("", message.getFieldName33());
+ assertEquals(0, message.get2Conflict34());
+ assertEquals(0, message.get2Conflict35());
+
+ }
+
+ public void testNumberFields() throws Exception {
+ TestBadIdentifiersProto.TestLeadingNumberFields message =
+ TestBadIdentifiersProto.TestLeadingNumberFields.getDefaultInstance();
+ // Make sure generated accessors are properly named.
+ assertFalse(message.has30DayImpressions());
+ assertEquals(0, message.get30DayImpressions());
+ assertEquals(0, message.get60DayImpressionsCount());
+ assertEquals(0, message.get60DayImpressionsList().size());
+
+ assertFalse(message.has2Underscores());
+ assertEquals("", message.get2Underscores());
+ assertEquals(0, message.get2RepeatedUnderscoresCount());
+ assertEquals(0, message.get2RepeatedUnderscoresList().size());
+
+ assertFalse(message.has32());
+ assertEquals(0, message.get32());
+ assertEquals(0, message.get64Count());
+ assertEquals(0, message.get64List().size());
+
}
}
diff --git a/java/core/src/test/java/com/google/protobuf/TestBadIdentifiersLite.java b/java/core/src/test/java/com/google/protobuf/TestBadIdentifiersLite.java
new file mode 100644
index 00000000..37f94c03
--- /dev/null
+++ b/java/core/src/test/java/com/google/protobuf/TestBadIdentifiersLite.java
@@ -0,0 +1,83 @@
+// 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.
+
+package com.google.protobuf;
+
+import junit.framework.TestCase;
+
+/**
+ * Tests that proto2 api generation doesn't cause compile errors when compiling protocol buffers
+ * that have names that would otherwise conflict if not fully qualified (like @Deprecated
+ * and @Override).
+ *
+ * <p>Forked from {@link TestBadIdentifiers}.
+ *
+ * @author jonp@google.com (Jon Perlow)
+ */
+public final class TestBadIdentifiersLite extends TestCase {
+
+ public void testCompilation() {
+ // If this compiles, it means the generation was correct.
+ TestBadIdentifiersProto.Deprecated.newBuilder();
+ TestBadIdentifiersProto.Override.newBuilder();
+ }
+
+ public void testConflictingFieldNames() throws Exception {
+ TestBadIdentifiersProto.TestConflictingFieldNames message =
+ TestBadIdentifiersProto.TestConflictingFieldNames.getDefaultInstance();
+ // Make sure generated accessors are properly named.
+ assertEquals(0, message.getInt32Field1Count());
+ assertEquals(0, message.getEnumField2Count());
+ assertEquals(0, message.getStringField3Count());
+ assertEquals(0, message.getBytesField4Count());
+ assertEquals(0, message.getMessageField5Count());
+
+ assertEquals(0, message.getInt32FieldCount11());
+ assertEquals(0, message.getEnumFieldCount12().getNumber());
+ assertEquals("", message.getStringFieldCount13());
+ assertEquals(ByteString.EMPTY, message.getBytesFieldCount14());
+ assertEquals(0, message.getMessageFieldCount15().getSerializedSize());
+
+ assertEquals(0, message.getInt32Field21Count());
+ assertEquals(0, message.getEnumField22Count());
+ assertEquals(0, message.getStringField23Count());
+ assertEquals(0, message.getBytesField24Count());
+ assertEquals(0, message.getMessageField25Count());
+
+ assertEquals(0, message.getInt32Field1List().size());
+ assertEquals(0, message.getInt32FieldList31());
+
+ assertEquals(0, message.getInt64FieldCount());
+ assertEquals(0L, message.getExtension(
+ TestBadIdentifiersProto.TestConflictingFieldNames.int64FieldCount).longValue());
+ assertEquals(0L, message.getExtension(
+ TestBadIdentifiersProto.TestConflictingFieldNames.int64FieldList).longValue());
+ }
+}
diff --git a/java/core/src/test/java/com/google/protobuf/TestUtil.java b/java/core/src/test/java/com/google/protobuf/TestUtil.java
index d4a18a22..e96adf07 100644
--- a/java/core/src/test/java/com/google/protobuf/TestUtil.java
+++ b/java/core/src/test/java/com/google/protobuf/TestUtil.java
@@ -2602,6 +2602,9 @@ public final class TestUtil {
case FOO_CORD:
Assert.assertTrue(message.hasFooCord());
break;
+ case FOO_STRING_PIECE:
+ Assert.assertTrue(message.hasFooStringPiece());
+ break;
case FOO_BYTES:
Assert.assertTrue(message.hasFooBytes());
break;
@@ -2619,6 +2622,8 @@ public final class TestUtil {
break;
case FOO_NOT_SET:
break;
+ default:
+ // TODO(b/18683919): go/enum-switch-lsc
}
}
diff --git a/java/core/src/test/java/com/google/protobuf/TextFormatTest.java b/java/core/src/test/java/com/google/protobuf/TextFormatTest.java
index 6a91b02f..28c4fdea 100644
--- a/java/core/src/test/java/com/google/protobuf/TextFormatTest.java
+++ b/java/core/src/test/java/com/google/protobuf/TextFormatTest.java
@@ -33,6 +33,7 @@ package com.google.protobuf;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.TextFormat.Parser.SingularOverwritePolicy;
+import map_test.MapTestProto.TestMap;
import protobuf_unittest.UnittestMset.TestMessageSetExtension1;
import protobuf_unittest.UnittestMset.TestMessageSetExtension2;
import protobuf_unittest.UnittestProto.OneString;
@@ -167,6 +168,7 @@ public class TextFormatTest extends TestCase {
// Creates an example unknown field set.
private UnknownFieldSet makeUnknownFieldSet() {
+
return UnknownFieldSet.newBuilder()
.addField(5,
UnknownFieldSet.Field.newBuilder()
@@ -174,6 +176,12 @@ public class TextFormatTest extends TestCase {
.addFixed32(2)
.addFixed64(3)
.addLengthDelimited(ByteString.copyFromUtf8("4"))
+ .addLengthDelimited(UnknownFieldSet.newBuilder()
+ .addField(12,
+ UnknownFieldSet.Field.newBuilder()
+ .addVarint(6)
+ .build())
+ .build().toByteString())
.addGroup(
UnknownFieldSet.newBuilder()
.addField(10,
@@ -206,20 +214,23 @@ public class TextFormatTest extends TestCase {
.build();
assertEquals(
- "5: 1\n" +
- "5: 0x00000002\n" +
- "5: 0x0000000000000003\n" +
- "5: \"4\"\n" +
- "5 {\n" +
- " 10: 5\n" +
- "}\n" +
- "8: 1\n" +
- "8: 2\n" +
- "8: 3\n" +
- "15: 12379813812177893520\n" +
- "15: 0xabcd1234\n" +
- "15: 0xabcdef1234567890\n",
- TextFormat.printToString(message));
+ "5: 1\n"
+ + "5: 0x00000002\n"
+ + "5: 0x0000000000000003\n"
+ + "5: \"4\"\n"
+ + "5: {\n"
+ + " 12: 6\n"
+ + "}\n"
+ + "5 {\n"
+ + " 10: 5\n"
+ + "}\n"
+ + "8: 1\n"
+ + "8: 2\n"
+ + "8: 3\n"
+ + "15: 12379813812177893520\n"
+ + "15: 0xabcd1234\n"
+ + "15: 0xabcdef1234567890\n",
+ TextFormat.printToString(message));
}
public void testPrintField() throws Exception {
@@ -860,7 +871,7 @@ public class TextFormatTest extends TestCase {
}
public void testShortDebugString_unknown() {
- assertEquals("5: 1 5: 0x00000002 5: 0x0000000000000003 5: \"4\" 5 { 10: 5 }"
+ assertEquals("5: 1 5: 0x00000002 5: 0x0000000000000003 5: \"4\" 5: { 12: 6 } 5 { 10: 5 }"
+ " 8: 1 8: 2 8: 3 15: 12379813812177893520 15: 0xabcd1234 15:"
+ " 0xabcdef1234567890",
TextFormat.shortDebugString(makeUnknownFieldSet()));
@@ -940,6 +951,7 @@ public class TextFormatTest extends TestCase {
}
+ // See additional coverage in testOneofOverwriteForbidden and testMapOverwriteForbidden.
public void testParseNonRepeatedFields() throws Exception {
assertParseSuccessWithOverwriteForbidden(
"repeated_int32: 1\n" +
@@ -950,6 +962,7 @@ public class TextFormatTest extends TestCase {
assertParseSuccessWithOverwriteForbidden(
"repeated_nested_message { bb: 1 }\n" +
"repeated_nested_message { bb: 2 }\n");
+
assertParseErrorWithOverwriteForbidden(
"3:17: Non-repeated field " +
"\"protobuf_unittest.TestAllTypes.optional_int32\" " +
@@ -988,6 +1001,7 @@ public class TextFormatTest extends TestCase {
assertParseSuccessWithOverwriteForbidden("repeated_int32: [ 1, 2 ]\n");
assertParseSuccessWithOverwriteForbidden("RepeatedGroup [{ a: 1 },{ a: 2 }]\n");
assertParseSuccessWithOverwriteForbidden("repeated_nested_message [{ bb: 1 }, { bb: 2 }]\n");
+ // See also testMapShortForm.
}
public void testParseShortRepeatedFormOfEmptyRepeatedFields() throws Exception {
@@ -995,6 +1009,7 @@ public class TextFormatTest extends TestCase {
assertParseSuccessWithOverwriteForbidden("repeated_int32: []\n");
assertParseSuccessWithOverwriteForbidden("RepeatedGroup []\n");
assertParseSuccessWithOverwriteForbidden("repeated_nested_message []\n");
+ // See also testMapShortFormEmpty.
}
public void testParseShortRepeatedFormWithTrailingComma() throws Exception {
@@ -1010,6 +1025,7 @@ public class TextFormatTest extends TestCase {
assertParseErrorWithOverwriteForbidden(
"1:37: Expected \"{\".",
"repeated_nested_message [{ bb: 1 }, ]\n");
+ // See also testMapShortFormTrailingComma.
}
public void testParseShortRepeatedFormOfNonRepeatedFields() throws Exception {
@@ -1058,6 +1074,90 @@ public class TextFormatTest extends TestCase {
}
// =======================================================================
+ // test map
+
+ public void testMapTextFormat() throws Exception {
+ TestMap message =
+ TestMap.newBuilder()
+ .putInt32ToStringField(10, "apple")
+ .putInt32ToStringField(20, "banana")
+ .putInt32ToStringField(30, "cherry")
+ .build();
+ String text = TextFormat.printToUnicodeString(message);
+ {
+ TestMap.Builder dest = TestMap.newBuilder();
+ TextFormat.merge(text, dest);
+ assertEquals(message, dest.build());
+ }
+ {
+ TestMap.Builder dest = TestMap.newBuilder();
+ parserWithOverwriteForbidden.merge(text, dest);
+ assertEquals(message, dest.build());
+ }
+ }
+
+ public void testMapShortForm() throws Exception {
+ String text =
+ "string_to_int32_field [{ key: 'x' value: 10 }, { key: 'y' value: 20 }]\n"
+ + "int32_to_message_field "
+ + "[{ key: 1 value { value: 100 } }, { key: 2 value: { value: 200 } }]\n";
+ TestMap.Builder dest = TestMap.newBuilder();
+ parserWithOverwriteForbidden.merge(text, dest);
+ TestMap message = dest.build();
+ assertEquals(2, message.getStringToInt32Field().size());
+ assertEquals(2, message.getInt32ToMessageField().size());
+ assertEquals(10, message.getStringToInt32Field().get("x").intValue());
+ assertEquals(200, message.getInt32ToMessageField().get(2).getValue());
+ }
+
+ public void testMapShortFormEmpty() throws Exception {
+ String text = "string_to_int32_field []\n"
+ + "int32_to_message_field: []\n";
+ TestMap.Builder dest = TestMap.newBuilder();
+ parserWithOverwriteForbidden.merge(text, dest);
+ TestMap message = dest.build();
+ assertEquals(0, message.getStringToInt32Field().size());
+ assertEquals(0, message.getInt32ToMessageField().size());
+ }
+
+ public void testMapShortFormTrailingComma() throws Exception {
+ String text = "string_to_int32_field [{ key: 'x' value: 10 }, ]\n";
+ TestMap.Builder dest = TestMap.newBuilder();
+ try {
+ parserWithOverwriteForbidden.merge(text, dest);
+ fail("Expected parse exception.");
+ } catch (TextFormat.ParseException e) {
+ assertEquals("1:48: Expected \"{\".", e.getMessage());
+ }
+ }
+
+ public void testMapOverwrite() throws Exception {
+ String text =
+ "int32_to_int32_field { key: 1 value: 10 }\n"
+ + "int32_to_int32_field { key: 2 value: 20 }\n"
+ + "int32_to_int32_field { key: 1 value: 30 }\n";
+
+ {
+ // With default parser, last value set for the key holds.
+ TestMap.Builder builder = TestMap.newBuilder();
+ defaultParser.merge(text, builder);
+ TestMap map = builder.build();
+ assertEquals(2, map.getInt32ToInt32Field().size());
+ assertEquals(30, map.getInt32ToInt32Field().get(1).intValue());
+ }
+
+ {
+ // With overwrite forbidden, same behavior.
+ // TODO(b/29122459): Expect parse exception here.
+ TestMap.Builder builder = TestMap.newBuilder();
+ defaultParser.merge(text, builder);
+ TestMap map = builder.build();
+ assertEquals(2, map.getInt32ToInt32Field().size());
+ assertEquals(30, map.getInt32ToInt32Field().get(1).intValue());
+ }
+ }
+
+ // =======================================================================
// test location information
public void testParseInfoTreeBuilding() throws Exception {
diff --git a/java/core/src/test/java/com/google/protobuf/UnknownEnumValueTest.java b/java/core/src/test/java/com/google/protobuf/UnknownEnumValueTest.java
index 8f45976f..88cbbf86 100644
--- a/java/core/src/test/java/com/google/protobuf/UnknownEnumValueTest.java
+++ b/java/core/src/test/java/com/google/protobuf/UnknownEnumValueTest.java
@@ -36,7 +36,6 @@ import com.google.protobuf.Descriptors.EnumValueDescriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.FieldPresenceTestProto.TestAllTypes;
import com.google.protobuf.TextFormat.ParseException;
-
import junit.framework.TestCase;
/**
@@ -151,18 +150,15 @@ public class UnknownEnumValueTest extends TestCase {
assertEquals(4321, unknown4321.getNumber());
assertEquals(5432, unknown5432.getNumber());
assertEquals(6543, unknown6543.getNumber());
-
+
// Unknown EnumValueDescriptor will map to UNRECOGNIZED.
assertEquals(
- TestAllTypes.NestedEnum.valueOf(unknown4321),
- TestAllTypes.NestedEnum.UNRECOGNIZED);
+ TestAllTypes.NestedEnum.UNRECOGNIZED, TestAllTypes.NestedEnum.valueOf(unknown4321));
assertEquals(
- TestAllTypes.NestedEnum.valueOf(unknown5432),
- TestAllTypes.NestedEnum.UNRECOGNIZED);
+ TestAllTypes.NestedEnum.UNRECOGNIZED, TestAllTypes.NestedEnum.valueOf(unknown5432));
assertEquals(
- TestAllTypes.NestedEnum.valueOf(unknown6543),
- TestAllTypes.NestedEnum.UNRECOGNIZED);
-
+ TestAllTypes.NestedEnum.UNRECOGNIZED, TestAllTypes.NestedEnum.valueOf(unknown6543));
+
// Setters also accept unknown EnumValueDescriptor.
builder.setField(optionalNestedEnumField, unknown6543);
builder.setRepeatedField(repeatedNestedEnumField, 0, unknown4321);
diff --git a/java/core/src/test/java/com/google/protobuf/UnknownFieldSetLiteTest.java b/java/core/src/test/java/com/google/protobuf/UnknownFieldSetLiteTest.java
index 26ea850e..9928d44a 100644
--- a/java/core/src/test/java/com/google/protobuf/UnknownFieldSetLiteTest.java
+++ b/java/core/src/test/java/com/google/protobuf/UnknownFieldSetLiteTest.java
@@ -32,11 +32,20 @@ package com.google.protobuf;
import com.google.protobuf.UnittestLite.TestAllExtensionsLite;
import com.google.protobuf.UnittestLite.TestAllTypesLite;
+import protobuf_unittest.UnittestProto;
+import protobuf_unittest.UnittestProto.ForeignEnum;
+import protobuf_unittest.UnittestProto.TestAllExtensions;
+import protobuf_unittest.UnittestProto.TestAllTypes;
+import protobuf_unittest.UnittestProto.TestEmptyMessage;
+import protobuf_unittest.UnittestProto.TestPackedExtensions;
+import protobuf_unittest.UnittestProto.TestPackedTypes;
import protobuf_unittest.lite_equals_and_hash.LiteEqualsAndHash;
import protobuf_unittest.lite_equals_and_hash.LiteEqualsAndHash.Bar;
import protobuf_unittest.lite_equals_and_hash.LiteEqualsAndHash.Foo;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
+import java.util.Arrays;
+import java.util.Map;
import junit.framework.TestCase;
/**
@@ -45,7 +54,44 @@ import junit.framework.TestCase;
* @author dweis@google.com (Daniel Weis)
*/
public class UnknownFieldSetLiteTest extends TestCase {
-
+ @Override
+ public void setUp() throws Exception {
+ allFields = TestUtil.getAllSet();
+ allFieldsData = allFields.toByteString();
+ emptyMessage = TestEmptyMessage.parseFrom(allFieldsData);
+ unknownFields = emptyMessage.getUnknownFields();
+ }
+
+ TestAllTypes allFields;
+ ByteString allFieldsData;
+
+ // Constructs a protocol buffer which contains fields with all the same
+ // numbers as allFieldsData except that each field is some other wire
+ // type.
+ private ByteString getBizarroData() throws Exception {
+ UnknownFieldSet.Builder bizarroFields = UnknownFieldSet.newBuilder();
+
+ UnknownFieldSet.Field varintField = UnknownFieldSet.Field.newBuilder().addVarint(1).build();
+ UnknownFieldSet.Field fixed32Field = UnknownFieldSet.Field.newBuilder().addFixed32(1).build();
+
+ for (Map.Entry<Integer, UnknownFieldSet.Field> entry : unknownFields.asMap().entrySet()) {
+ if (entry.getValue().getVarintList().isEmpty()) {
+ // Original field is not a varint, so use a varint.
+ bizarroFields.addField(entry.getKey(), varintField);
+ } else {
+ // Original field *is* a varint, so use something else.
+ bizarroFields.addField(entry.getKey(), fixed32Field);
+ }
+ }
+
+ return bizarroFields.build().toByteString();
+ }
+
+ // An empty message that has been parsed from allFieldsData. So, it has
+ // unknown fields of every type.
+ TestEmptyMessage emptyMessage;
+ UnknownFieldSet unknownFields;
+
public void testDefaultInstance() {
UnknownFieldSetLite unknownFields = UnknownFieldSetLite.getDefaultInstance();
@@ -53,6 +99,14 @@ public class UnknownFieldSetLiteTest extends TestCase {
assertEquals(ByteString.EMPTY, toByteString(unknownFields));
}
+ public void testEmptyInstance() {
+ UnknownFieldSetLite instance = UnknownFieldSetLite.newInstance();
+
+ assertEquals(0, instance.getSerializedSize());
+ assertEquals(ByteString.EMPTY, toByteString(instance));
+ assertEquals(UnknownFieldSetLite.getDefaultInstance(), instance);
+ }
+
public void testMergeFieldFrom() throws IOException {
Foo foo = Foo.newBuilder()
.setValue(2)
@@ -323,4 +377,203 @@ public class UnknownFieldSetLiteTest extends TestCase {
}
return ByteString.copyFrom(byteArrayOutputStream.toByteArray());
}
+
+ public void testSerializeLite() throws Exception {
+ UnittestLite.TestEmptyMessageLite emptyMessageLite =
+ UnittestLite.TestEmptyMessageLite.parseFrom(allFieldsData);
+ assertEquals(allFieldsData.size(), emptyMessageLite.getSerializedSize());
+ ByteString data = emptyMessageLite.toByteString();
+ TestAllTypes message = TestAllTypes.parseFrom(data);
+ TestUtil.assertAllFieldsSet(message);
+ assertEquals(allFieldsData, data);
+ }
+
+ public void testAllExtensionsLite() throws Exception {
+ TestAllExtensions allExtensions = TestUtil.getAllExtensionsSet();
+ ByteString allExtensionsData = allExtensions.toByteString();
+ UnittestLite.TestEmptyMessageLite emptyMessageLite =
+ UnittestLite.TestEmptyMessageLite.parser().parseFrom(allExtensionsData);
+ ByteString data = emptyMessageLite.toByteString();
+ TestAllExtensions message = TestAllExtensions.parseFrom(data, TestUtil.getExtensionRegistry());
+ TestUtil.assertAllExtensionsSet(message);
+ assertEquals(allExtensionsData, data);
+ }
+
+ public void testAllPackedFieldsLite() throws Exception {
+ TestPackedTypes allPackedFields = TestUtil.getPackedSet();
+ ByteString allPackedData = allPackedFields.toByteString();
+ UnittestLite.TestEmptyMessageLite emptyMessageLite =
+ UnittestLite.TestEmptyMessageLite.parseFrom(allPackedData);
+ ByteString data = emptyMessageLite.toByteString();
+ TestPackedTypes message = TestPackedTypes.parseFrom(data, TestUtil.getExtensionRegistry());
+ TestUtil.assertPackedFieldsSet(message);
+ assertEquals(allPackedData, data);
+ }
+
+ public void testAllPackedExtensionsLite() throws Exception {
+ TestPackedExtensions allPackedExtensions = TestUtil.getPackedExtensionsSet();
+ ByteString allPackedExtensionsData = allPackedExtensions.toByteString();
+ UnittestLite.TestEmptyMessageLite emptyMessageLite =
+ UnittestLite.TestEmptyMessageLite.parseFrom(allPackedExtensionsData);
+ ByteString data = emptyMessageLite.toByteString();
+ TestPackedExtensions message =
+ TestPackedExtensions.parseFrom(data, TestUtil.getExtensionRegistry());
+ TestUtil.assertPackedExtensionsSet(message);
+ assertEquals(allPackedExtensionsData, data);
+ }
+
+ public void testCopyFromLite() throws Exception {
+ UnittestLite.TestEmptyMessageLite emptyMessageLite =
+ UnittestLite.TestEmptyMessageLite.parseFrom(allFieldsData);
+ UnittestLite.TestEmptyMessageLite emptyMessageLite2 =
+ UnittestLite.TestEmptyMessageLite.newBuilder().mergeFrom(emptyMessageLite).build();
+ assertEquals(emptyMessageLite.toByteString(), emptyMessageLite2.toByteString());
+ }
+
+ public void testMergeFromLite() throws Exception {
+ TestAllTypes message1 =
+ TestAllTypes.newBuilder()
+ .setOptionalInt32(1)
+ .setOptionalString("foo")
+ .addRepeatedString("bar")
+ .setOptionalNestedEnum(TestAllTypes.NestedEnum.BAZ)
+ .build();
+
+ TestAllTypes message2 =
+ TestAllTypes.newBuilder()
+ .setOptionalInt64(2)
+ .setOptionalString("baz")
+ .addRepeatedString("qux")
+ .setOptionalForeignEnum(ForeignEnum.FOREIGN_BAZ)
+ .build();
+
+ ByteString data1 = message1.toByteString();
+ UnittestLite.TestEmptyMessageLite emptyMessageLite1 =
+ UnittestLite.TestEmptyMessageLite.parseFrom(data1);
+ ByteString data2 = message2.toByteString();
+ UnittestLite.TestEmptyMessageLite emptyMessageLite2 =
+ UnittestLite.TestEmptyMessageLite.parseFrom(data2);
+
+ message1 = TestAllTypes.newBuilder(message1).mergeFrom(message2).build();
+ emptyMessageLite1 =
+ UnittestLite.TestEmptyMessageLite.newBuilder(emptyMessageLite1)
+ .mergeFrom(emptyMessageLite2)
+ .build();
+
+ data1 = emptyMessageLite1.toByteString();
+ message2 = TestAllTypes.parseFrom(data1);
+
+ assertEquals(message1, message2);
+ }
+
+ public void testWrongTypeTreatedAsUnknownLite() throws Exception {
+ // Test that fields of the wrong wire type are treated like unknown fields
+ // when parsing.
+
+ ByteString bizarroData = getBizarroData();
+ TestAllTypes allTypesMessage = TestAllTypes.parseFrom(bizarroData);
+ UnittestLite.TestEmptyMessageLite emptyMessageLite =
+ UnittestLite.TestEmptyMessageLite.parseFrom(bizarroData);
+ ByteString data = emptyMessageLite.toByteString();
+ TestAllTypes allTypesMessage2 = TestAllTypes.parseFrom(data);
+
+ assertEquals(allTypesMessage.toString(), allTypesMessage2.toString());
+ }
+
+ public void testUnknownExtensionsLite() throws Exception {
+ // Make sure fields are properly parsed to the UnknownFieldSet even when
+ // they are declared as extension numbers.
+
+ UnittestLite.TestEmptyMessageWithExtensionsLite message =
+ UnittestLite.TestEmptyMessageWithExtensionsLite.parseFrom(allFieldsData);
+
+ assertEquals(allFieldsData, message.toByteString());
+ }
+
+ public void testWrongExtensionTypeTreatedAsUnknownLite() throws Exception {
+ // Test that fields of the wrong wire type are treated like unknown fields
+ // when parsing extensions.
+
+ ByteString bizarroData = getBizarroData();
+ TestAllExtensions allExtensionsMessage = TestAllExtensions.parseFrom(bizarroData);
+ UnittestLite.TestEmptyMessageLite emptyMessageLite =
+ UnittestLite.TestEmptyMessageLite.parseFrom(bizarroData);
+
+ // All fields should have been interpreted as unknown, so the byte strings
+ // should be the same.
+ assertEquals(emptyMessageLite.toByteString(), allExtensionsMessage.toByteString());
+ }
+
+ public void testParseUnknownEnumValueLite() throws Exception {
+ Descriptors.FieldDescriptor singularField =
+ TestAllTypes.getDescriptor().findFieldByName("optional_nested_enum");
+ Descriptors.FieldDescriptor repeatedField =
+ TestAllTypes.getDescriptor().findFieldByName("repeated_nested_enum");
+ assertNotNull(singularField);
+ assertNotNull(repeatedField);
+
+ ByteString data =
+ UnknownFieldSet.newBuilder()
+ .addField(
+ singularField.getNumber(),
+ UnknownFieldSet.Field.newBuilder()
+ .addVarint(TestAllTypes.NestedEnum.BAR.getNumber())
+ .addVarint(5) // not valid
+ .build())
+ .addField(
+ repeatedField.getNumber(),
+ UnknownFieldSet.Field.newBuilder()
+ .addVarint(TestAllTypes.NestedEnum.FOO.getNumber())
+ .addVarint(4) // not valid
+ .addVarint(TestAllTypes.NestedEnum.BAZ.getNumber())
+ .addVarint(6) // not valid
+ .build())
+ .build()
+ .toByteString();
+
+ UnittestLite.TestEmptyMessageLite emptyMessageLite =
+ UnittestLite.TestEmptyMessageLite.parseFrom(data);
+ data = emptyMessageLite.toByteString();
+
+ {
+ TestAllTypes message = TestAllTypes.parseFrom(data);
+ assertEquals(TestAllTypes.NestedEnum.BAR, message.getOptionalNestedEnum());
+ assertEquals(
+ Arrays.asList(TestAllTypes.NestedEnum.FOO, TestAllTypes.NestedEnum.BAZ),
+ message.getRepeatedNestedEnumList());
+ assertEquals(
+ Arrays.asList(5L),
+ message.getUnknownFields().getField(singularField.getNumber()).getVarintList());
+ assertEquals(
+ Arrays.asList(4L, 6L),
+ message.getUnknownFields().getField(repeatedField.getNumber()).getVarintList());
+ }
+
+ {
+ TestAllExtensions message =
+ TestAllExtensions.parseFrom(data, TestUtil.getExtensionRegistry());
+ assertEquals(
+ TestAllTypes.NestedEnum.BAR,
+ message.getExtension(UnittestProto.optionalNestedEnumExtension));
+ assertEquals(
+ Arrays.asList(TestAllTypes.NestedEnum.FOO, TestAllTypes.NestedEnum.BAZ),
+ message.getExtension(UnittestProto.repeatedNestedEnumExtension));
+ assertEquals(
+ Arrays.asList(5L),
+ message.getUnknownFields().getField(singularField.getNumber()).getVarintList());
+ assertEquals(
+ Arrays.asList(4L, 6L),
+ message.getUnknownFields().getField(repeatedField.getNumber()).getVarintList());
+ }
+ }
+
+ public void testClearLite() throws Exception {
+ UnittestLite.TestEmptyMessageLite emptyMessageLite1 =
+ UnittestLite.TestEmptyMessageLite.parseFrom(allFieldsData);
+ UnittestLite.TestEmptyMessageLite emptyMessageLite2 =
+ UnittestLite.TestEmptyMessageLite.newBuilder().mergeFrom(emptyMessageLite1).clear().build();
+ assertEquals(0, emptyMessageLite2.getSerializedSize());
+ ByteString data = emptyMessageLite2.toByteString();
+ assertEquals(0, data.size());
+ }
}
diff --git a/java/core/src/test/java/com/google/protobuf/UnknownFieldSetTest.java b/java/core/src/test/java/com/google/protobuf/UnknownFieldSetTest.java
index f81e90b4..1a84806a 100644
--- a/java/core/src/test/java/com/google/protobuf/UnknownFieldSetTest.java
+++ b/java/core/src/test/java/com/google/protobuf/UnknownFieldSetTest.java
@@ -445,208 +445,4 @@ public class UnknownFieldSetTest extends TestCase {
}
// =================================================================
-
- public void testSerializeLite() throws Exception {
- UnittestLite.TestEmptyMessageLite emptyMessageLite =
- UnittestLite.TestEmptyMessageLite.parseFrom(allFieldsData);
- assertEquals(allFieldsData.size(), emptyMessageLite.getSerializedSize());
- ByteString data = emptyMessageLite.toByteString();
- TestAllTypes message = TestAllTypes.parseFrom(data);
- TestUtil.assertAllFieldsSet(message);
- assertEquals(allFieldsData, data);
- }
-
- public void testAllExtensionsLite() throws Exception {
- TestAllExtensions allExtensions = TestUtil.getAllExtensionsSet();
- ByteString allExtensionsData = allExtensions.toByteString();
- UnittestLite.TestEmptyMessageLite emptyMessageLite =
- UnittestLite.TestEmptyMessageLite.parser().parseFrom(allExtensionsData);
- ByteString data = emptyMessageLite.toByteString();
- TestAllExtensions message =
- TestAllExtensions.parseFrom(data, TestUtil.getExtensionRegistry());
- TestUtil.assertAllExtensionsSet(message);
- assertEquals(allExtensionsData, data);
- }
-
- public void testAllPackedFieldsLite() throws Exception {
- TestPackedTypes allPackedFields = TestUtil.getPackedSet();
- ByteString allPackedData = allPackedFields.toByteString();
- UnittestLite.TestEmptyMessageLite emptyMessageLite =
- UnittestLite.TestEmptyMessageLite.parseFrom(allPackedData);
- ByteString data = emptyMessageLite.toByteString();
- TestPackedTypes message =
- TestPackedTypes.parseFrom(data, TestUtil.getExtensionRegistry());
- TestUtil.assertPackedFieldsSet(message);
- assertEquals(allPackedData, data);
- }
-
- public void testAllPackedExtensionsLite() throws Exception {
- TestPackedExtensions allPackedExtensions = TestUtil.getPackedExtensionsSet();
- ByteString allPackedExtensionsData = allPackedExtensions.toByteString();
- UnittestLite.TestEmptyMessageLite emptyMessageLite =
- UnittestLite.TestEmptyMessageLite.parseFrom(allPackedExtensionsData);
- ByteString data = emptyMessageLite.toByteString();
- TestPackedExtensions message =
- TestPackedExtensions.parseFrom(data, TestUtil.getExtensionRegistry());
- TestUtil.assertPackedExtensionsSet(message);
- assertEquals(allPackedExtensionsData, data);
- }
-
- public void testCopyFromLite() throws Exception {
- UnittestLite.TestEmptyMessageLite emptyMessageLite =
- UnittestLite.TestEmptyMessageLite.parseFrom(allFieldsData);
- UnittestLite.TestEmptyMessageLite emptyMessageLite2 =
- UnittestLite.TestEmptyMessageLite.newBuilder()
- .mergeFrom(emptyMessageLite).build();
- assertEquals(emptyMessageLite.toByteString(), emptyMessageLite2.toByteString());
- }
-
- public void testMergeFromLite() throws Exception {
- TestAllTypes message1 = TestAllTypes.newBuilder()
- .setOptionalInt32(1)
- .setOptionalString("foo")
- .addRepeatedString("bar")
- .setOptionalNestedEnum(TestAllTypes.NestedEnum.BAZ)
- .build();
-
- TestAllTypes message2 = TestAllTypes.newBuilder()
- .setOptionalInt64(2)
- .setOptionalString("baz")
- .addRepeatedString("qux")
- .setOptionalForeignEnum(ForeignEnum.FOREIGN_BAZ)
- .build();
-
- ByteString data1 = message1.toByteString();
- UnittestLite.TestEmptyMessageLite emptyMessageLite1 =
- UnittestLite.TestEmptyMessageLite.parseFrom(data1);
- ByteString data2 = message2.toByteString();
- UnittestLite.TestEmptyMessageLite emptyMessageLite2 =
- UnittestLite.TestEmptyMessageLite.parseFrom(data2);
-
- message1 = TestAllTypes.newBuilder(message1).mergeFrom(message2).build();
- emptyMessageLite1 = UnittestLite.TestEmptyMessageLite.newBuilder(emptyMessageLite1)
- .mergeFrom(emptyMessageLite2).build();
-
- data1 = emptyMessageLite1.toByteString();
- message2 = TestAllTypes.parseFrom(data1);
-
- assertEquals(message1, message2);
- }
-
- public void testWrongTypeTreatedAsUnknownLite() throws Exception {
- // Test that fields of the wrong wire type are treated like unknown fields
- // when parsing.
-
- ByteString bizarroData = getBizarroData();
- TestAllTypes allTypesMessage = TestAllTypes.parseFrom(bizarroData);
- UnittestLite.TestEmptyMessageLite emptyMessageLite =
- UnittestLite.TestEmptyMessageLite.parseFrom(bizarroData);
- ByteString data = emptyMessageLite.toByteString();
- TestAllTypes allTypesMessage2 = TestAllTypes.parseFrom(data);
-
- assertEquals(allTypesMessage.toString(), allTypesMessage2.toString());
- }
-
- public void testUnknownExtensionsLite() throws Exception {
- // Make sure fields are properly parsed to the UnknownFieldSet even when
- // they are declared as extension numbers.
-
- UnittestLite.TestEmptyMessageWithExtensionsLite message =
- UnittestLite.TestEmptyMessageWithExtensionsLite.parseFrom(allFieldsData);
-
- assertEquals(allFieldsData, message.toByteString());
- }
-
- public void testWrongExtensionTypeTreatedAsUnknownLite() throws Exception {
- // Test that fields of the wrong wire type are treated like unknown fields
- // when parsing extensions.
-
- ByteString bizarroData = getBizarroData();
- TestAllExtensions allExtensionsMessage =
- TestAllExtensions.parseFrom(bizarroData);
- UnittestLite.TestEmptyMessageLite emptyMessageLite =
- UnittestLite.TestEmptyMessageLite.parseFrom(bizarroData);
-
- // All fields should have been interpreted as unknown, so the byte strings
- // should be the same.
- assertEquals(emptyMessageLite.toByteString(),
- allExtensionsMessage.toByteString());
- }
-
- public void testParseUnknownEnumValueLite() throws Exception {
- Descriptors.FieldDescriptor singularField =
- TestAllTypes.getDescriptor().findFieldByName("optional_nested_enum");
- Descriptors.FieldDescriptor repeatedField =
- TestAllTypes.getDescriptor().findFieldByName("repeated_nested_enum");
- assertNotNull(singularField);
- assertNotNull(repeatedField);
-
- ByteString data =
- UnknownFieldSet.newBuilder()
- .addField(singularField.getNumber(),
- UnknownFieldSet.Field.newBuilder()
- .addVarint(TestAllTypes.NestedEnum.BAR.getNumber())
- .addVarint(5) // not valid
- .build())
- .addField(repeatedField.getNumber(),
- UnknownFieldSet.Field.newBuilder()
- .addVarint(TestAllTypes.NestedEnum.FOO.getNumber())
- .addVarint(4) // not valid
- .addVarint(TestAllTypes.NestedEnum.BAZ.getNumber())
- .addVarint(6) // not valid
- .build())
- .build()
- .toByteString();
-
- UnittestLite.TestEmptyMessageLite emptyMessageLite =
- UnittestLite.TestEmptyMessageLite.parseFrom(data);
- data = emptyMessageLite.toByteString();
-
- {
- TestAllTypes message = TestAllTypes.parseFrom(data);
- assertEquals(TestAllTypes.NestedEnum.BAR,
- message.getOptionalNestedEnum());
- assertEquals(
- Arrays.asList(TestAllTypes.NestedEnum.FOO, TestAllTypes.NestedEnum.BAZ),
- message.getRepeatedNestedEnumList());
- assertEquals(Arrays.asList(5L),
- message.getUnknownFields()
- .getField(singularField.getNumber())
- .getVarintList());
- assertEquals(Arrays.asList(4L, 6L),
- message.getUnknownFields()
- .getField(repeatedField.getNumber())
- .getVarintList());
- }
-
- {
- TestAllExtensions message =
- TestAllExtensions.parseFrom(data, TestUtil.getExtensionRegistry());
- assertEquals(TestAllTypes.NestedEnum.BAR,
- message.getExtension(UnittestProto.optionalNestedEnumExtension));
- assertEquals(
- Arrays.asList(TestAllTypes.NestedEnum.FOO, TestAllTypes.NestedEnum.BAZ),
- message.getExtension(UnittestProto.repeatedNestedEnumExtension));
- assertEquals(Arrays.asList(5L),
- message.getUnknownFields()
- .getField(singularField.getNumber())
- .getVarintList());
- assertEquals(Arrays.asList(4L, 6L),
- message.getUnknownFields()
- .getField(repeatedField.getNumber())
- .getVarintList());
- }
- }
-
- public void testClearLite() throws Exception {
- UnittestLite.TestEmptyMessageLite emptyMessageLite1 =
- UnittestLite.TestEmptyMessageLite.parseFrom(allFieldsData);
- UnittestLite.TestEmptyMessageLite emptyMessageLite2 =
- UnittestLite.TestEmptyMessageLite.newBuilder()
- .mergeFrom(emptyMessageLite1).clear().build();
- assertEquals(0, emptyMessageLite2.getSerializedSize());
- ByteString data = emptyMessageLite2.toByteString();
- assertEquals(0, data.size());
- }
-
}
diff --git a/java/core/src/test/java/com/google/protobuf/WireFormatTest.java b/java/core/src/test/java/com/google/protobuf/WireFormatTest.java
index 370860c2..625d4b42 100644
--- a/java/core/src/test/java/com/google/protobuf/WireFormatTest.java
+++ b/java/core/src/test/java/com/google/protobuf/WireFormatTest.java
@@ -30,8 +30,6 @@
package com.google.protobuf;
-import com.google.protobuf.UnittestLite.TestAllExtensionsLite;
-import com.google.protobuf.UnittestLite.TestPackedExtensionsLite;
import protobuf_unittest.UnittestMset.RawMessageSet;
import protobuf_unittest.UnittestMset.TestMessageSetExtension1;
import protobuf_unittest.UnittestMset.TestMessageSetExtension2;
@@ -125,32 +123,6 @@ public class WireFormatTest extends TestCase {
TestUtil.assertPackedFieldsSet(message2);
}
- public void testSerializeExtensionsLite() throws Exception {
- // TestAllTypes and TestAllExtensions should have compatible wire formats,
- // so if we serialize a TestAllExtensions then parse it as TestAllTypes
- // it should work.
-
- TestAllExtensionsLite message = TestUtilLite.getAllLiteExtensionsSet();
- ByteString rawBytes = message.toByteString();
- assertEquals(rawBytes.size(), message.getSerializedSize());
-
- TestAllTypes message2 = TestAllTypes.parseFrom(rawBytes);
-
- TestUtil.assertAllFieldsSet(message2);
- }
-
- public void testSerializePackedExtensionsLite() throws Exception {
- // TestPackedTypes and TestPackedExtensions should have compatible wire
- // formats; check that they serialize to the same string.
- TestPackedExtensionsLite message = TestUtilLite.getLitePackedExtensionsSet();
- ByteString rawBytes = message.toByteString();
-
- TestPackedTypes message2 = TestUtil.getPackedSet();
- ByteString rawBytes2 = message2.toByteString();
-
- assertEquals(rawBytes, rawBytes2);
- }
-
public void testParseExtensions() throws Exception {
// TestAllTypes and TestAllExtensions should have compatible wire formats,
// so if we serialize a TestAllTypes then parse it as TestAllExtensions
@@ -180,48 +152,6 @@ public class WireFormatTest extends TestCase {
TestUtil.assertPackedExtensionsSet(message2);
}
- public void testParseExtensionsLite() throws Exception {
- // TestAllTypes and TestAllExtensions should have compatible wire formats,
- // so if we serialize a TestAllTypes then parse it as TestAllExtensions
- // it should work.
-
- TestAllTypes message = TestUtil.getAllSet();
- ByteString rawBytes = message.toByteString();
-
- ExtensionRegistryLite registry_lite = TestUtilLite.getExtensionRegistryLite();
-
- TestAllExtensionsLite message2 =
- TestAllExtensionsLite.parseFrom(rawBytes, registry_lite);
-
- TestUtil.assertAllExtensionsSet(message2);
-
- // Try again using a full extension registry.
- ExtensionRegistry registry = TestUtil.getExtensionRegistry();
-
- TestAllExtensionsLite message3 =
- TestAllExtensionsLite.parseFrom(rawBytes, registry);
-
- TestUtil.assertAllExtensionsSet(message3);
- }
-
- public void testParsePackedExtensionsLite() throws Exception {
- // Ensure that packed extensions can be properly parsed.
- TestPackedExtensionsLite message = TestUtilLite.getLitePackedExtensionsSet();
- ByteString rawBytes = message.toByteString();
-
- ExtensionRegistryLite registry = TestUtilLite.getExtensionRegistryLite();
-
- TestPackedExtensionsLite message2 =
- TestPackedExtensionsLite.parseFrom(rawBytes, registry);
-
- TestUtil.assertPackedExtensionsSet(message2);
- }
-
- public void testExtensionsSerializedSize() throws Exception {
- assertNotSame(TestUtil.getAllSet().getSerializedSize(),
- TestUtil.getAllExtensionsSet().getSerializedSize());
- }
-
public void testSerializeDelimited() throws Exception {
ByteArrayOutputStream output = new ByteArrayOutputStream();
TestUtil.getAllSet().writeDelimitedTo(output);
diff --git a/java/core/src/test/proto/com/google/protobuf/deprecated_file.proto b/java/core/src/test/proto/com/google/protobuf/deprecated_file.proto
new file mode 100644
index 00000000..ca90e927
--- /dev/null
+++ b/java/core/src/test/proto/com/google/protobuf/deprecated_file.proto
@@ -0,0 +1,38 @@
+// 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.
+
+syntax = "proto3";
+
+package deprecated_file;
+
+option deprecated = true;
+
+// TODO (liujisi): Add deprecation options on messages, enums fields as well and
+// add tests to verify those annotations are actually generated.
diff --git a/java/core/src/test/proto/com/google/protobuf/lite_equals_and_hash.proto b/java/core/src/test/proto/com/google/protobuf/lite_equals_and_hash.proto
index 6eef42c5..b18b0d79 100644
--- a/java/core/src/test/proto/com/google/protobuf/lite_equals_and_hash.proto
+++ b/java/core/src/test/proto/com/google/protobuf/lite_equals_and_hash.proto
@@ -46,6 +46,14 @@ message TestOneofEquals {
message Foo {
optional int32 value = 1;
repeated Bar bar = 2;
+ map<string, string> my_map = 3;
+ oneof Single {
+ sint64 sint64 = 4;
+ // LINT: ALLOW_GROUPS
+ group MyGroup = 5 {
+ optional int32 value = 1;
+ }
+ }
extensions 100 to max;
}
diff --git a/java/core/src/test/proto/com/google/protobuf/test_bad_identifiers.proto b/java/core/src/test/proto/com/google/protobuf/test_bad_identifiers.proto
index d2c77936..ff5bf3ae 100644
--- a/java/core/src/test/proto/com/google/protobuf/test_bad_identifiers.proto
+++ b/java/core/src/test/proto/com/google/protobuf/test_bad_identifiers.proto
@@ -148,6 +148,12 @@ message TestConflictingFieldNames {
// the method getInt32FieldList().
required int32 int32_field_list = 31; // NO_PROTO3
+ // These field pairs have the same Java converted name
+ optional string field_name = 32; // NO_PROTO3
+ optional string field__name = 33; // NO_PROTO3
+ optional int32 _2conflict = 34; // NO_PROTO3
+ optional int32 __2conflict = 35;
+
extensions 1000 to max; // NO_PROTO3
repeated int64 int64_field = 41;
@@ -166,3 +172,14 @@ message TestMapField {
map<int32, int32> map_field = 1;
}
+
+message TestLeadingNumberFields {
+ optional int32 _30day_impressions = 1;
+ repeated string _60day_impressions = 2;
+
+ optional string __2_underscores = 3;
+ repeated string __2repeated_underscores = 4;
+
+ optional int32 _32 = 32;
+ repeated int64 _64 = 64;
+}
diff --git a/java/lite/pom.xml b/java/lite/pom.xml
index d7b15097..c902f819 100644
--- a/java/lite/pom.xml
+++ b/java/lite/pom.xml
@@ -137,6 +137,7 @@
<include>**/MutabilityOracle.java</include>
<include>**/NioByteString.java</include>
<include>**/Parser.java</include>
+ <include>**/PrimitiveNonBoxingCollection.java</include>
<include>**/ProtobufArrayList.java</include>
<include>**/ProtocolStringList.java</include>
<include>**/RopeByteString.java</include>
diff --git a/java/pom.xml b/java/pom.xml
index 6789e7c1..bc8e89b5 100644
--- a/java/pom.xml
+++ b/java/pom.xml
@@ -11,7 +11,7 @@
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-parent</artifactId>
- <version>3.1.0</version>
+ <version>3.4.1</version>
<packaging>pom</packaging>
<name>Protocol Buffers [Parent]</name>
@@ -39,8 +39,8 @@
<licenses>
<license>
- <name>New BSD license</name>
- <url>http://www.opensource.org/licenses/bsd-license.php</url>
+ <name>3-Clause BSD License</name>
+ <url>https://opensource.org/licenses/BSD-3-Clause</url>
<distribution>repo</distribution>
</license>
</licenses>
@@ -84,7 +84,7 @@
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
- <version>18.0</version>
+ <version>19.0</version>
</dependency>
</dependencies>
</dependencyManagement>
diff --git a/java/util/pom.xml b/java/util/pom.xml
index 0ccfc848..35afb844 100644
--- a/java/util/pom.xml
+++ b/java/util/pom.xml
@@ -6,7 +6,7 @@
<parent>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-parent</artifactId>
- <version>3.1.0</version>
+ <version>3.4.1</version>
</parent>
<artifactId>protobuf-java-util</artifactId>
diff --git a/java/util/src/main/java/com/google/protobuf/util/Durations.java b/java/util/src/main/java/com/google/protobuf/util/Durations.java
index 46b21828..fb7f4343 100644
--- a/java/util/src/main/java/com/google/protobuf/util/Durations.java
+++ b/java/util/src/main/java/com/google/protobuf/util/Durations.java
@@ -30,7 +30,6 @@
package com.google.protobuf.util;
-import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.math.IntMath.checkedAdd;
import static com.google.common.math.IntMath.checkedSubtract;
import static com.google.common.math.LongMath.checkedAdd;
@@ -84,6 +83,17 @@ public final class Durations {
}
/**
+ * Compares two durations. The value returned is identical to what would be returned by:
+ * {@code Durations.comparator().compare(x, y)}.
+ *
+ * @return the value {@code 0} if {@code x == y}; a value less than {@code 0} if {@code x < y};
+ * and a value greater than {@code 0} if {@code x > y}
+ */
+ public static int compare(Duration x, Duration y) {
+ return COMPARATOR.compare(x, y);
+ }
+
+ /**
* Returns true if the given {@link Duration} is valid. The {@code seconds} value must be in the
* range [-315,576,000,000, +315,576,000,000]. The {@code nanos} value must be in the range
* [-999,999,999, +999,999,999].
@@ -124,14 +134,13 @@ public final class Durations {
public static Duration checkValid(Duration duration) {
long seconds = duration.getSeconds();
int nanos = duration.getNanos();
- checkArgument(
- isValid(seconds, nanos),
- "Duration is not valid. See proto definition for valid values. "
+ if (!isValid(seconds, nanos)) {
+ throw new IllegalArgumentException(String.format(
+ "Duration is not valid. See proto definition for valid values. "
+ "Seconds (%s) must be in range [-315,576,000,000, +315,576,000,000]. "
+ "Nanos (%s) must be in range [-999,999,999, +999,999,999]. "
- + "Nanos must have the same sign as seconds",
- seconds,
- nanos);
+ + "Nanos must have the same sign as seconds", seconds, nanos));
+ }
return duration;
}
diff --git a/java/util/src/main/java/com/google/protobuf/util/FieldMaskTree.java b/java/util/src/main/java/com/google/protobuf/util/FieldMaskTree.java
index b192b53e..e017b987 100644
--- a/java/util/src/main/java/com/google/protobuf/util/FieldMaskTree.java
+++ b/java/util/src/main/java/com/google/protobuf/util/FieldMaskTree.java
@@ -34,7 +34,6 @@ import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.FieldMask;
import com.google.protobuf.Message;
-
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
@@ -244,6 +243,11 @@ final class FieldMaskTree {
+ "singluar message field and cannot have sub-fields.");
continue;
}
+ if (!source.hasField(field) && !destination.hasField(field)) {
+ // If the message field is not present in both source and destination, skip recursing
+ // so we don't create unneccessary empty messages.
+ continue;
+ }
String childPath = path.isEmpty() ? entry.getKey() : path + "." + entry.getKey();
merge(
entry.getValue(),
diff --git a/java/util/src/main/java/com/google/protobuf/util/FieldMaskUtil.java b/java/util/src/main/java/com/google/protobuf/util/FieldMaskUtil.java
index 21d11b2c..b2f849c4 100644
--- a/java/util/src/main/java/com/google/protobuf/util/FieldMaskUtil.java
+++ b/java/util/src/main/java/com/google/protobuf/util/FieldMaskUtil.java
@@ -311,16 +311,19 @@ public class FieldMaskUtil {
return replacePrimitiveFields;
}
- public void setReplaceMessageFields(boolean value) {
+ public MergeOptions setReplaceMessageFields(boolean value) {
replaceMessageFields = value;
+ return this;
}
- public void setReplaceRepeatedFields(boolean value) {
+ public MergeOptions setReplaceRepeatedFields(boolean value) {
replaceRepeatedFields = value;
+ return this;
}
- public void setReplacePrimitiveFields(boolean value) {
+ public MergeOptions setReplacePrimitiveFields(boolean value) {
replacePrimitiveFields = value;
+ return this;
}
}
diff --git a/java/util/src/main/java/com/google/protobuf/util/JsonFormat.java b/java/util/src/main/java/com/google/protobuf/util/JsonFormat.java
index ac712c94..a26dbc2d 100644
--- a/java/util/src/main/java/com/google/protobuf/util/JsonFormat.java
+++ b/java/util/src/main/java/com/google/protobuf/util/JsonFormat.java
@@ -30,11 +30,13 @@
package com.google.protobuf.util;
+import com.google.common.base.Preconditions;
import com.google.common.io.BaseEncoding;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
+import com.google.gson.JsonIOException;
import com.google.gson.JsonNull;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
@@ -101,7 +103,9 @@ public class JsonFormat {
* Creates a {@link Printer} with default configurations.
*/
public static Printer printer() {
- return new Printer(TypeRegistry.getEmptyTypeRegistry(), false, false, false);
+ return new Printer(
+ TypeRegistry.getEmptyTypeRegistry(), false, Collections.<FieldDescriptor>emptySet(),
+ false, false);
}
/**
@@ -109,16 +113,27 @@ public class JsonFormat {
*/
public static class Printer {
private final TypeRegistry registry;
- private final boolean includingDefaultValueFields;
+ // NOTE: There are 3 states for these *defaultValueFields variables:
+ // 1) Default - alwaysOutput is false & including is empty set. Fields only output if they are
+ // set to non-default values.
+ // 2) No-args includingDefaultValueFields() called - alwaysOutput is true & including is
+ // irrelevant (but set to empty set). All fields are output regardless of their values.
+ // 3) includingDefaultValueFields(Set<FieldDescriptor>) called - alwaysOutput is false &
+ // including is set to the specified set. Fields in that set are always output & fields not
+ // in that set are only output if set to non-default values.
+ private boolean alwaysOutputDefaultValueFields;
+ private Set<FieldDescriptor> includingDefaultValueFields;
private final boolean preservingProtoFieldNames;
private final boolean omittingInsignificantWhitespace;
private Printer(
TypeRegistry registry,
- boolean includingDefaultValueFields,
+ boolean alwaysOutputDefaultValueFields,
+ Set<FieldDescriptor> includingDefaultValueFields,
boolean preservingProtoFieldNames,
boolean omittingInsignificantWhitespace) {
this.registry = registry;
+ this.alwaysOutputDefaultValueFields = alwaysOutputDefaultValueFields;
this.includingDefaultValueFields = includingDefaultValueFields;
this.preservingProtoFieldNames = preservingProtoFieldNames;
this.omittingInsignificantWhitespace = omittingInsignificantWhitespace;
@@ -136,6 +151,7 @@ public class JsonFormat {
}
return new Printer(
registry,
+ alwaysOutputDefaultValueFields,
includingDefaultValueFields,
preservingProtoFieldNames,
omittingInsignificantWhitespace);
@@ -148,8 +164,41 @@ public class JsonFormat {
* {@link Printer}.
*/
public Printer includingDefaultValueFields() {
+ checkUnsetIncludingDefaultValueFields();
return new Printer(
- registry, true, preservingProtoFieldNames, omittingInsignificantWhitespace);
+ registry,
+ true,
+ Collections.<FieldDescriptor>emptySet(),
+ preservingProtoFieldNames,
+ omittingInsignificantWhitespace);
+ }
+
+ /**
+ * Creates a new {@link Printer} that will also print default-valued fields if their
+ * FieldDescriptors are found in the supplied set. Empty repeated fields and map fields will be
+ * printed as well, if they match. The new Printer clones all other configurations from the
+ * current {@link Printer}. Call includingDefaultValueFields() with no args to unconditionally
+ * output all fields.
+ */
+ public Printer includingDefaultValueFields(Set<FieldDescriptor> fieldsToAlwaysOutput) {
+ Preconditions.checkArgument(
+ null != fieldsToAlwaysOutput && !fieldsToAlwaysOutput.isEmpty(),
+ "Non-empty Set must be supplied for includingDefaultValueFields.");
+
+ checkUnsetIncludingDefaultValueFields();
+ return new Printer(
+ registry,
+ false,
+ fieldsToAlwaysOutput,
+ preservingProtoFieldNames,
+ omittingInsignificantWhitespace);
+ }
+
+ private void checkUnsetIncludingDefaultValueFields() {
+ if (alwaysOutputDefaultValueFields || !includingDefaultValueFields.isEmpty()) {
+ throw new IllegalStateException(
+ "JsonFormat includingDefaultValueFields has already been set.");
+ }
}
/**
@@ -160,15 +209,20 @@ public class JsonFormat {
*/
public Printer preservingProtoFieldNames() {
return new Printer(
- registry, includingDefaultValueFields, true, omittingInsignificantWhitespace);
+ registry,
+ alwaysOutputDefaultValueFields,
+ includingDefaultValueFields,
+ true,
+ omittingInsignificantWhitespace);
}
/**
- * Create a new {@link Printer} that will omit all insignificant whitespace
- * in the JSON output. This new Printer clones all other configurations from the
- * current Printer. Insignificant whitespace is defined by the JSON spec as whitespace
- * that appear between JSON structural elements:
+ * Create a new {@link Printer} that will omit all insignificant whitespace in the JSON output.
+ * This new Printer clones all other configurations from the current Printer. Insignificant
+ * whitespace is defined by the JSON spec as whitespace that appear between JSON structural
+ * elements:
+ *
* <pre>
* ws = *(
* %x20 / ; Space
@@ -176,18 +230,24 @@ public class JsonFormat {
* %x0A / ; Line feed or New line
* %x0D ) ; Carriage return
* </pre>
+ *
* See <a href="https://tools.ietf.org/html/rfc7159">https://tools.ietf.org/html/rfc7159</a>
* current {@link Printer}.
*/
public Printer omittingInsignificantWhitespace() {
- return new Printer(registry, includingDefaultValueFields, preservingProtoFieldNames, true);
+ return new Printer(
+ registry,
+ alwaysOutputDefaultValueFields,
+ includingDefaultValueFields,
+ preservingProtoFieldNames,
+ true);
}
/**
* Converts a protobuf message to JSON format.
*
- * @throws InvalidProtocolBufferException if the message contains Any types
- * that can't be resolved.
+ * @throws InvalidProtocolBufferException if the message contains Any types that can't be
+ * resolved.
* @throws IOException if writing to the output fails.
*/
public void appendTo(MessageOrBuilder message, Appendable output) throws IOException {
@@ -195,6 +255,7 @@ public class JsonFormat {
// mobile.
new PrinterImpl(
registry,
+ alwaysOutputDefaultValueFields,
includingDefaultValueFields,
preservingProtoFieldNames,
output,
@@ -427,19 +488,16 @@ public class JsonFormat {
this.output = output;
}
- /**
- * ignored by compact printer
- */
+ /** ignored by compact printer */
+ @Override
public void indent() {}
- /**
- * ignored by compact printer
- */
+ /** ignored by compact printer */
+ @Override
public void outdent() {}
- /**
- * Print text to the output stream.
- */
+ /** Print text to the output stream. */
+ @Override
public void print(final CharSequence text) throws IOException {
output.append(text);
}
@@ -457,18 +515,17 @@ public class JsonFormat {
}
/**
- * Indent text by two spaces. After calling Indent(), two spaces will be
- * inserted at the beginning of each line of text. Indent() may be called
- * multiple times to produce deeper indents.
+ * Indent text by two spaces. After calling Indent(), two spaces will be inserted at the
+ * beginning of each line of text. Indent() may be called multiple times to produce deeper
+ * indents.
*/
+ @Override
public void indent() {
indent.append(" ");
}
- /**
- * Reduces the current indent level by two spaces, or crashes if the indent
- * level is zero.
- */
+ /** Reduces the current indent level by two spaces, or crashes if the indent level is zero. */
+ @Override
public void outdent() {
final int length = indent.length();
if (length < 2) {
@@ -477,9 +534,8 @@ public class JsonFormat {
indent.delete(length - 2, length);
}
- /**
- * Print text to the output stream.
- */
+ /** Print text to the output stream. */
+ @Override
public void print(final CharSequence text) throws IOException {
final int size = text.length();
int pos = 0;
@@ -511,7 +567,8 @@ public class JsonFormat {
*/
private static final class PrinterImpl {
private final TypeRegistry registry;
- private final boolean includingDefaultValueFields;
+ private final boolean alwaysOutputDefaultValueFields;
+ private final Set<FieldDescriptor> includingDefaultValueFields;
private final boolean preservingProtoFieldNames;
private final TextGenerator generator;
// We use Gson to help handle string escapes.
@@ -525,11 +582,13 @@ public class JsonFormat {
PrinterImpl(
TypeRegistry registry,
- boolean includingDefaultValueFields,
+ boolean alwaysOutputDefaultValueFields,
+ Set<FieldDescriptor> includingDefaultValueFields,
boolean preservingProtoFieldNames,
Appendable jsonOutput,
boolean omittingInsignificantWhitespace) {
this.registry = registry;
+ this.alwaysOutputDefaultValueFields = alwaysOutputDefaultValueFields;
this.includingDefaultValueFields = includingDefaultValueFields;
this.preservingProtoFieldNames = preservingProtoFieldNames;
this.gson = GsonHolder.DEFAULT_GSON;
@@ -780,23 +839,26 @@ public class JsonFormat {
printedField = true;
}
Map<FieldDescriptor, Object> fieldsToPrint = null;
- if (includingDefaultValueFields) {
- fieldsToPrint = new TreeMap<FieldDescriptor, Object>();
+ if (alwaysOutputDefaultValueFields || !includingDefaultValueFields.isEmpty()) {
+ fieldsToPrint = new TreeMap<FieldDescriptor, Object>(message.getAllFields());
for (FieldDescriptor field : message.getDescriptorForType().getFields()) {
if (field.isOptional()) {
if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE
- && !message.hasField(field)){
+ && !message.hasField(field)) {
// Always skip empty optional message fields. If not we will recurse indefinitely if
// a message has itself as a sub-field.
continue;
}
OneofDescriptor oneof = field.getContainingOneof();
if (oneof != null && !message.hasField(field)) {
- // Skip all oneof fields except the one that is actually set
+ // Skip all oneof fields except the one that is actually set
continue;
}
}
- fieldsToPrint.put(field, message.getField(field));
+ if (!fieldsToPrint.containsKey(field)
+ && (alwaysOutputDefaultValueFields || includingDefaultValueFields.contains(field))) {
+ fieldsToPrint.put(field, message.getField(field));
+ }
}
} else {
fieldsToPrint = message.getAllFields();
@@ -1067,9 +1129,23 @@ public class JsonFormat {
}
void merge(Reader json, Message.Builder builder) throws IOException {
- JsonReader reader = new JsonReader(json);
- reader.setLenient(false);
- merge(jsonParser.parse(reader), builder);
+ try {
+ JsonReader reader = new JsonReader(json);
+ reader.setLenient(false);
+ merge(jsonParser.parse(reader), builder);
+ } catch (InvalidProtocolBufferException e) {
+ throw e;
+ } catch (JsonIOException e) {
+ // Unwrap IOException.
+ if (e.getCause() instanceof IOException) {
+ throw (IOException) e.getCause();
+ } else {
+ throw new InvalidProtocolBufferException(e.getMessage());
+ }
+ } catch (Exception e) {
+ // We convert all exceptions from JSON parsing to our own exceptions.
+ throw new InvalidProtocolBufferException(e.getMessage());
+ }
}
void merge(String json, Message.Builder builder) throws InvalidProtocolBufferException {
@@ -1436,45 +1512,6 @@ public class JsonFormat {
}
}
- /**
- * Gets the default value for a field type. Note that we use proto3
- * language defaults and ignore any default values set through the
- * proto "default" option.
- */
- private Object getDefaultValue(FieldDescriptor field, Message.Builder builder) {
- switch (field.getType()) {
- case INT32:
- case SINT32:
- case SFIXED32:
- case UINT32:
- case FIXED32:
- return 0;
- case INT64:
- case SINT64:
- case SFIXED64:
- case UINT64:
- case FIXED64:
- return 0L;
- case FLOAT:
- return 0.0f;
- case DOUBLE:
- return 0.0;
- case BOOL:
- return false;
- case STRING:
- return "";
- case BYTES:
- return ByteString.EMPTY;
- case ENUM:
- return field.getEnumType().getValues().get(0);
- case MESSAGE:
- case GROUP:
- return builder.newBuilderForField(field).getDefaultInstanceForType();
- default:
- throw new IllegalStateException("Invalid field type: " + field.getType());
- }
- }
-
private void mergeRepeatedField(
FieldDescriptor field, JsonElement json, Message.Builder builder)
throws InvalidProtocolBufferException {
@@ -1485,7 +1522,8 @@ public class JsonFormat {
for (int i = 0; i < array.size(); ++i) {
Object value = parseFieldValue(field, array.get(i), builder);
if (value == null) {
- throw new InvalidProtocolBufferException("Repeated field elements cannot be null");
+ throw new InvalidProtocolBufferException(
+ "Repeated field elements cannot be null in field: " + field.getFullName());
}
builder.addRepeatedField(field, value);
}
@@ -1521,7 +1559,7 @@ public class JsonFormat {
BigDecimal value = new BigDecimal(json.getAsString());
return value.longValueExact();
} catch (Exception e) {
- throw new InvalidProtocolBufferException("Not an int32 value: " + json);
+ throw new InvalidProtocolBufferException("Not an int64 value: " + json);
}
}
@@ -1649,7 +1687,11 @@ public class JsonFormat {
}
private ByteString parseBytes(JsonElement json) throws InvalidProtocolBufferException {
- return ByteString.copyFrom(BaseEncoding.base64().decode(json.getAsString()));
+ try {
+ return ByteString.copyFrom(BaseEncoding.base64().decode(json.getAsString()));
+ } catch (IllegalArgumentException e) {
+ return ByteString.copyFrom(BaseEncoding.base64Url().decode(json.getAsString()));
+ }
}
private EnumValueDescriptor parseEnum(EnumDescriptor enumDescriptor, JsonElement json)
diff --git a/java/util/src/main/java/com/google/protobuf/util/Timestamps.java b/java/util/src/main/java/com/google/protobuf/util/Timestamps.java
index 2160e4d5..7a1f2014 100644
--- a/java/util/src/main/java/com/google/protobuf/util/Timestamps.java
+++ b/java/util/src/main/java/com/google/protobuf/util/Timestamps.java
@@ -30,7 +30,6 @@
package com.google.protobuf.util;
-import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.math.IntMath.checkedAdd;
import static com.google.common.math.IntMath.checkedSubtract;
import static com.google.common.math.LongMath.checkedAdd;
@@ -44,6 +43,7 @@ import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.Date;
import java.util.GregorianCalendar;
+import java.util.Locale;
import java.util.TimeZone;
/**
@@ -83,7 +83,7 @@ public final class Timestamps {
};
private static SimpleDateFormat createTimestampFormat() {
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
+ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH);
GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
// We use Proleptic Gregorian Calendar (i.e., Gregorian calendar extends
// backwards to year one) for timestamp formating.
@@ -114,6 +114,17 @@ public final class Timestamps {
}
/**
+ * Compares two timestamps. The value returned is identical to what would be returned by:
+ * {@code Timestamps.comparator().compare(x, y)}.
+ *
+ * @return the value {@code 0} if {@code x == y}; a value less than {@code 0} if {@code x < y};
+ * and a value greater than {@code 0} if {@code x > y}
+ */
+ public static int compare(Timestamp x, Timestamp y) {
+ return COMPARATOR.compare(x, y);
+ }
+
+ /**
* Returns true if the given {@link Timestamp} is valid. The {@code seconds} value must be in the
* range [-62,135,596,800, +253,402,300,799] (i.e., between 0001-01-01T00:00:00Z and
* 9999-12-31T23:59:59Z). The {@code nanos} value must be in the range [0, +999,999,999].
@@ -148,13 +159,12 @@ public final class Timestamps {
public static Timestamp checkValid(Timestamp timestamp) {
long seconds = timestamp.getSeconds();
int nanos = timestamp.getNanos();
- checkArgument(
- isValid(seconds, nanos),
- "Timestamp is not valid. See proto definition for valid values. "
+ if (!isValid(seconds, nanos)) {
+ throw new IllegalArgumentException(String.format(
+ "Timestamp is not valid. See proto definition for valid values. "
+ "Seconds (%s) must be in range [-62,135,596,800, +253,402,300,799]. "
- + "Nanos (%s) must be in range [0, +999,999,999].",
- seconds,
- nanos);
+ + "Nanos (%s) must be in range [0, +999,999,999].", seconds, nanos));
+ }
return timestamp;
}
@@ -296,7 +306,7 @@ public final class Timestamps {
* Convert a Timestamp to the number of microseconds elapsed from the epoch.
*
* <p>The result will be rounded down to the nearest microsecond. E.g., if the timestamp
- * represents "1969-12-31T23:59:59.999999999Z", it will be rounded to -1 millisecond.
+ * represents "1969-12-31T23:59:59.999999999Z", it will be rounded to -1 microsecond.
*/
public static long toMicros(Timestamp timestamp) {
checkValid(timestamp);
@@ -386,11 +396,11 @@ public final class Timestamps {
static String formatNanos(int nanos) {
// Determine whether to use 3, 6, or 9 digits for the nano part.
if (nanos % NANOS_PER_MILLISECOND == 0) {
- return String.format("%1$03d", nanos / NANOS_PER_MILLISECOND);
+ return String.format(Locale.ENGLISH, "%1$03d", nanos / NANOS_PER_MILLISECOND);
} else if (nanos % NANOS_PER_MICROSECOND == 0) {
- return String.format("%1$06d", nanos / NANOS_PER_MICROSECOND);
+ return String.format(Locale.ENGLISH, "%1$06d", nanos / NANOS_PER_MICROSECOND);
} else {
- return String.format("%1$09d", nanos);
+ return String.format(Locale.ENGLISH, "%1$09d", nanos);
}
}
}
diff --git a/java/util/src/test/java/com/google/protobuf/util/FieldMaskTreeTest.java b/java/util/src/test/java/com/google/protobuf/util/FieldMaskTreeTest.java
index 3ee0fc6e..853b6151 100644
--- a/java/util/src/test/java/com/google/protobuf/util/FieldMaskTreeTest.java
+++ b/java/util/src/test/java/com/google/protobuf/util/FieldMaskTreeTest.java
@@ -33,7 +33,6 @@ package com.google.protobuf.util;
import protobuf_unittest.UnittestProto.NestedTestAllTypes;
import protobuf_unittest.UnittestProto.TestAllTypes;
import protobuf_unittest.UnittestProto.TestAllTypes.NestedMessage;
-
import junit.framework.TestCase;
public class FieldMaskTreeTest extends TestCase {
@@ -222,6 +221,13 @@ public class FieldMaskTreeTest extends TestCase {
new FieldMaskTree().addFieldPath("payload").merge(clearedSource, builder, options);
assertEquals(false, builder.hasPayload());
+ // Skip a message field if they are unset in both source and target.
+ builder = NestedTestAllTypes.newBuilder();
+ new FieldMaskTree()
+ .addFieldPath("payload.optional_int32")
+ .merge(clearedSource, builder, options);
+ assertEquals(false, builder.hasPayload());
+
// Change to replace message fields.
options.setReplaceMessageFields(true);
builder = NestedTestAllTypes.newBuilder();
diff --git a/java/util/src/test/java/com/google/protobuf/util/JsonFormatTest.java b/java/util/src/test/java/com/google/protobuf/util/JsonFormatTest.java
index dafd9bb5..e4c5387a 100644
--- a/java/util/src/test/java/com/google/protobuf/util/JsonFormatTest.java
+++ b/java/util/src/test/java/com/google/protobuf/util/JsonFormatTest.java
@@ -34,6 +34,7 @@ import com.google.protobuf.Any;
import com.google.protobuf.BoolValue;
import com.google.protobuf.ByteString;
import com.google.protobuf.BytesValue;
+import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.DoubleValue;
import com.google.protobuf.FloatValue;
import com.google.protobuf.Int32Value;
@@ -62,13 +63,25 @@ import com.google.protobuf.util.JsonTestProto.TestStruct;
import com.google.protobuf.util.JsonTestProto.TestTimestamp;
import com.google.protobuf.util.JsonTestProto.TestWrappers;
import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.Reader;
+import java.io.StringReader;
import java.math.BigDecimal;
import java.math.BigInteger;
+import java.util.Collections;
import java.util.HashMap;
-import java.util.Map;
+import java.util.HashSet;
+import java.util.Locale;
+import java.util.Set;
import junit.framework.TestCase;
public class JsonFormatTest extends TestCase {
+ public JsonFormatTest() {
+ // Test that locale does not affect JsonFormat.
+ Locale.setDefault(Locale.forLanguageTag("hi-IN"));
+ }
+
private void setAllFields(TestAllTypes.Builder builder) {
builder.setOptionalInt32(1234);
builder.setOptionalInt64(1234567890123456789L);
@@ -219,9 +232,7 @@ public class JsonFormatTest extends TestCase {
TestMap.Builder mapBuilder = TestMap.newBuilder();
mapBuilder.putInt32ToEnumMapValue(1, 0);
- Map<Integer, Integer> mapWithInvalidValues = new HashMap<Integer, Integer>();
- mapWithInvalidValues.put(2, 12345);
- mapBuilder.putAllInt32ToEnumMapValue(mapWithInvalidValues);
+ mapBuilder.putInt32ToEnumMapValue(2, 12345);
TestMap mapMessage = mapBuilder.build();
assertEquals(
"{\n"
@@ -254,7 +265,7 @@ public class JsonFormatTest extends TestCase {
assertRoundTripEquals(message);
}
- public void testParserAcceptStringForNumbericField() throws Exception {
+ public void testParserAcceptStringForNumericField() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
mergeFromJson(
"{\n"
@@ -274,8 +285,8 @@ public class JsonFormatTest extends TestCase {
assertEquals(9012, message.getOptionalSint32());
assertEquals(3456, message.getOptionalFixed32());
assertEquals(7890, message.getOptionalSfixed32());
- assertEquals(1.5f, message.getOptionalFloat());
- assertEquals(1.25, message.getOptionalDouble());
+ assertEquals(1.5f, message.getOptionalFloat(), 0.0f);
+ assertEquals(1.25, message.getOptionalDouble(), 0.0);
assertEquals(true, message.getOptionalBool());
}
@@ -469,8 +480,8 @@ public class JsonFormatTest extends TestCase {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
mergeFromJson(
"{\n"
- + " \"repeatedNestedMessage\": [null, null],\n"
- + " \"repeated_nested_message\": [null, null]\n"
+ + " \"repeatedInt32\": [1, 2],\n"
+ + " \"repeated_int32\": [5, 6]\n"
+ "}",
builder);
fail();
@@ -478,7 +489,7 @@ public class JsonFormatTest extends TestCase {
// Exception expected.
}
- // Duplicated oneof fields.
+ // Duplicated oneof fields, same name.
try {
TestOneof.Builder builder = TestOneof.newBuilder();
mergeFromJson("{\n" + " \"oneofInt32\": 1,\n" + " \"oneof_int32\": 2\n" + "}", builder);
@@ -486,6 +497,16 @@ public class JsonFormatTest extends TestCase {
} catch (InvalidProtocolBufferException e) {
// Exception expected.
}
+
+ // Duplicated oneof fields, different name.
+ try {
+ TestOneof.Builder builder = TestOneof.newBuilder();
+ mergeFromJson(
+ "{\n" + " \"oneofInt32\": 1,\n" + " \"oneofNullValue\": null\n" + "}", builder);
+ fail();
+ } catch (InvalidProtocolBufferException e) {
+ // Exception expected.
+ }
}
public void testMapFields() throws Exception {
@@ -1079,7 +1100,7 @@ public class JsonFormatTest extends TestCase {
public void testParserUnexpectedTypeUrl() throws Exception {
try {
- TestAllTypes.Builder builder = TestAllTypes.newBuilder();
+ Any.Builder builder = Any.newBuilder();
mergeFromJson(
"{\n"
+ " \"@type\": \"type.googleapis.com/json_test.TestAllTypes\",\n"
@@ -1122,7 +1143,8 @@ public class JsonFormatTest extends TestCase {
}
public void testParserAcceptBase64Variants() throws Exception {
- assertAccepts("optionalBytes", "AQI");
+ assertAccepts("optionalBytes", "AQI"); // No padding
+ assertAccepts("optionalBytes", "-_w"); // base64Url, no padding
}
public void testParserRejectInvalidEnumValue() throws Exception {
@@ -1205,6 +1227,115 @@ public class JsonFormatTest extends TestCase {
+ "}",
JsonFormat.printer().includingDefaultValueFields().print(message));
+ Set<FieldDescriptor> fixedFields = new HashSet<FieldDescriptor>();
+ for (FieldDescriptor fieldDesc : TestAllTypes.getDescriptor().getFields()) {
+ if (fieldDesc.getName().contains("_fixed")) {
+ fixedFields.add(fieldDesc);
+ }
+ }
+
+ assertEquals(
+ "{\n"
+ + " \"optionalFixed32\": 0,\n"
+ + " \"optionalFixed64\": \"0\",\n"
+ + " \"repeatedFixed32\": [],\n"
+ + " \"repeatedFixed64\": []\n"
+ + "}",
+ JsonFormat.printer().includingDefaultValueFields(fixedFields).print(message));
+
+ TestAllTypes messageNonDefaults =
+ message.toBuilder().setOptionalInt64(1234).setOptionalFixed32(3232).build();
+ assertEquals(
+ "{\n"
+ + " \"optionalInt64\": \"1234\",\n"
+ + " \"optionalFixed32\": 3232,\n"
+ + " \"optionalFixed64\": \"0\",\n"
+ + " \"repeatedFixed32\": [],\n"
+ + " \"repeatedFixed64\": []\n"
+ + "}",
+ JsonFormat.printer().includingDefaultValueFields(fixedFields).print(messageNonDefaults));
+
+ try {
+ JsonFormat.printer().includingDefaultValueFields().includingDefaultValueFields();
+ fail("IllegalStateException is expected.");
+ } catch (IllegalStateException e) {
+ // Expected.
+ assertTrue(
+ "Exception message should mention includingDefaultValueFields.",
+ e.getMessage().contains("includingDefaultValueFields"));
+ }
+
+ try {
+ JsonFormat.printer().includingDefaultValueFields().includingDefaultValueFields(fixedFields);
+ fail("IllegalStateException is expected.");
+ } catch (IllegalStateException e) {
+ // Expected.
+ assertTrue(
+ "Exception message should mention includingDefaultValueFields.",
+ e.getMessage().contains("includingDefaultValueFields"));
+ }
+
+ try {
+ JsonFormat.printer().includingDefaultValueFields(fixedFields).includingDefaultValueFields();
+ fail("IllegalStateException is expected.");
+ } catch (IllegalStateException e) {
+ // Expected.
+ assertTrue(
+ "Exception message should mention includingDefaultValueFields.",
+ e.getMessage().contains("includingDefaultValueFields"));
+ }
+
+ try {
+ JsonFormat.printer()
+ .includingDefaultValueFields(fixedFields)
+ .includingDefaultValueFields(fixedFields);
+ fail("IllegalStateException is expected.");
+ } catch (IllegalStateException e) {
+ // Expected.
+ assertTrue(
+ "Exception message should mention includingDefaultValueFields.",
+ e.getMessage().contains("includingDefaultValueFields"));
+ }
+
+ Set<FieldDescriptor> intFields = new HashSet<FieldDescriptor>();
+ for (FieldDescriptor fieldDesc : TestAllTypes.getDescriptor().getFields()) {
+ if (fieldDesc.getName().contains("_int")) {
+ intFields.add(fieldDesc);
+ }
+ }
+
+ try {
+ JsonFormat.printer()
+ .includingDefaultValueFields(intFields)
+ .includingDefaultValueFields(fixedFields);
+ fail("IllegalStateException is expected.");
+ } catch (IllegalStateException e) {
+ // Expected.
+ assertTrue(
+ "Exception message should mention includingDefaultValueFields.",
+ e.getMessage().contains("includingDefaultValueFields"));
+ }
+
+ try {
+ JsonFormat.printer().includingDefaultValueFields(null);
+ fail("IllegalArgumentException is expected.");
+ } catch (IllegalArgumentException e) {
+ // Expected.
+ assertTrue(
+ "Exception message should mention includingDefaultValueFields.",
+ e.getMessage().contains("includingDefaultValueFields"));
+ }
+
+ try {
+ JsonFormat.printer().includingDefaultValueFields(Collections.<FieldDescriptor>emptySet());
+ fail("IllegalArgumentException is expected.");
+ } catch (IllegalArgumentException e) {
+ // Expected.
+ assertTrue(
+ "Exception message should mention includingDefaultValueFields.",
+ e.getMessage().contains("includingDefaultValueFields"));
+ }
+
TestMap mapMessage = TestMap.getDefaultInstance();
assertEquals("{\n}", JsonFormat.printer().print(mapMessage));
assertEquals(
@@ -1273,16 +1404,17 @@ public class JsonFormatTest extends TestCase {
assertEquals("{\n}", JsonFormat.printer().includingDefaultValueFields().print(oneofMessage));
oneofMessage = TestOneof.newBuilder().setOneofInt32(42).build();
- assertEquals("{\n \"oneofInt32\": 42\n}",
- JsonFormat.printer().print(oneofMessage));
- assertEquals("{\n \"oneofInt32\": 42\n}",
+ assertEquals("{\n \"oneofInt32\": 42\n}", JsonFormat.printer().print(oneofMessage));
+ assertEquals(
+ "{\n \"oneofInt32\": 42\n}",
JsonFormat.printer().includingDefaultValueFields().print(oneofMessage));
TestOneof.Builder oneofBuilder = TestOneof.newBuilder();
mergeFromJson("{\n" + " \"oneofNullValue\": null \n" + "}", oneofBuilder);
oneofMessage = oneofBuilder.build();
assertEquals("{\n \"oneofNullValue\": null\n}", JsonFormat.printer().print(oneofMessage));
- assertEquals("{\n \"oneofNullValue\": null\n}",
+ assertEquals(
+ "{\n \"oneofNullValue\": null\n}",
JsonFormat.printer().includingDefaultValueFields().print(oneofMessage));
}
@@ -1411,4 +1543,35 @@ public class JsonFormatTest extends TestCase {
// Expected.
}
}
+
+ // Test that we are not leaking out JSON exceptions.
+ public void testJsonException() throws Exception {
+ InputStream throwingInputStream =
+ new InputStream() {
+ public int read() throws IOException {
+ throw new IOException("12345");
+ }
+ };
+ InputStreamReader throwingReader = new InputStreamReader(throwingInputStream);
+ // When the underlying reader throws IOException, JsonFormat should forward
+ // through this IOException.
+ try {
+ TestAllTypes.Builder builder = TestAllTypes.newBuilder();
+ JsonFormat.parser().merge(throwingReader, builder);
+ fail("Exception is expected.");
+ } catch (IOException e) {
+ assertEquals("12345", e.getMessage());
+ }
+
+ Reader invalidJsonReader = new StringReader("{ xxx - yyy }");
+ // When the JSON parser throws parser exceptions, JsonFormat should turn
+ // that into InvalidProtocolBufferException.
+ try {
+ TestAllTypes.Builder builder = TestAllTypes.newBuilder();
+ JsonFormat.parser().merge(invalidJsonReader, builder);
+ fail("Exception is expected.");
+ } catch (InvalidProtocolBufferException e) {
+ // Expected.
+ }
+ }
}
diff --git a/java/util/src/test/proto/com/google/protobuf/util/json_test.proto b/java/util/src/test/proto/com/google/protobuf/util/json_test.proto
index a75338ef..d1248cfb 100644
--- a/java/util/src/test/proto/com/google/protobuf/util/json_test.proto
+++ b/java/util/src/test/proto/com/google/protobuf/util/json_test.proto
@@ -28,36 +28,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-// 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.
-
syntax = "proto3";
package json_test;
diff --git a/javanano/README.md b/javanano/README.md
index e19b90b1..6b13ecea 100644
--- a/javanano/README.md
+++ b/javanano/README.md
@@ -7,6 +7,9 @@ Copyright 2008 Google Inc.
This directory contains the Java Protocol Buffers Nano runtime library.
+**Nano is no longer supported by protobuf team. We recommend Android users to
+use protobuf lite runtime instead.**
+
Installation - With Maven
-------------------------
diff --git a/javanano/pom.xml b/javanano/pom.xml
index 6bac76c9..0395e8f2 100644
--- a/javanano/pom.xml
+++ b/javanano/pom.xml
@@ -10,7 +10,7 @@
</parent>
<groupId>com.google.protobuf.nano</groupId>
<artifactId>protobuf-javanano</artifactId>
- <version>3.1.0</version>
+ <version>3.2.0</version>
<packaging>bundle</packaging>
<name>Protocol Buffer JavaNano API</name>
<description>
@@ -21,8 +21,8 @@
<url>https://developers.google.com/protocol-buffers/</url>
<licenses>
<license>
- <name>New BSD license</name>
- <url>http://www.opensource.org/licenses/bsd-license.php</url>
+ <name>3-Clause BSD License</name>
+ <url>https://opensource.org/licenses/BSD-3-Clause</url>
<distribution>repo</distribution>
</license>
</licenses>
diff --git a/javanano/src/test/java/com/google/protobuf/nano/NanoTest.java b/javanano/src/test/java/com/google/protobuf/nano/NanoTest.java
index debf7c0a..4d6e7f09 100644
--- a/javanano/src/test/java/com/google/protobuf/nano/NanoTest.java
+++ b/javanano/src/test/java/com/google/protobuf/nano/NanoTest.java
@@ -30,8 +30,11 @@
package com.google.protobuf.nano;
-import com.google.protobuf.nano.MapTestProto.TestMap;
import com.google.protobuf.nano.CodedOutputByteBufferNano;
+import com.google.protobuf.nano.EnumClassNanos.EnumClassNano;
+import com.google.protobuf.nano.EnumClassNanos.EnumClassNano.MessageScopeEnum;
+import com.google.protobuf.nano.EnumClassNanos.FileScopeEnum;
+import com.google.protobuf.nano.MapTestProto.TestMap;
import com.google.protobuf.nano.MapTestProto.TestMap.MessageValue;
import com.google.protobuf.nano.NanoAccessorsOuterClass.TestNanoAccessors;
import com.google.protobuf.nano.NanoHasOuterClass.TestAllTypesNanoHas;
diff --git a/jenkins/docker/Dockerfile b/jenkins/docker/Dockerfile
index c5ee1ec0..3a279e66 100644
--- a/jenkins/docker/Dockerfile
+++ b/jenkins/docker/Dockerfile
@@ -30,7 +30,7 @@ RUN echo "deb http://ppa.launchpad.net/ondrej/php/ubuntu trusty main" | tee /etc
# Install dotnet SDK based on https://www.microsoft.com/net/core#debian
# (Ubuntu instructions need apt to support https)
RUN apt-get update && apt-get install -y --force-yes curl libunwind8 gettext && \
- curl -sSL -o dotnet.tar.gz https://go.microsoft.com/fwlink/?LinkID=809130 && \
+ curl -sSL -o dotnet.tar.gz https://go.microsoft.com/fwlink/?LinkID=847105 && \
mkdir -p /opt/dotnet && tar zxf dotnet.tar.gz -C /opt/dotnet && \
ln -s /opt/dotnet/dotnet /usr/local/bin
@@ -78,9 +78,6 @@ RUN apt-get clean && apt-get update && apt-get install -y --force-yes \
# -- For C++ benchmarks --
cmake \
# -- For PHP --
- php5.5 \
- php5.5-dev \
- php5.5-xml \
php5.6 \
php5.6-dev \
php5.6-xml \
@@ -132,7 +129,7 @@ ENV MVN mvn --batch-mode
RUN cd /tmp && \
git clone https://github.com/google/protobuf.git && \
cd protobuf && \
- git reset bf379715c93b581eeb078cec1f0dd8a7d79df431 && \
+ git reset --hard 129a6e2aca95dcfb6c3e717d7b9cca1f104fde39 && \
./autogen.sh && \
./configure && \
make -j4 && \
@@ -143,36 +140,70 @@ RUN cd /tmp && \
##################
# PHP dependencies.
+RUN wget http://am1.php.net/get/php-5.5.38.tar.bz2/from/this/mirror
+RUN mv mirror php-5.5.38.tar.bz2
+RUN tar -xvf php-5.5.38.tar.bz2
+RUN cd php-5.5.38 && ./configure --enable-maintainer-zts --prefix=/usr/local/php-5.5-zts && \
+ make && make install && cd ..
+RUN cd php-5.5.38 && make clean && ./configure --enable-bcmath --prefix=/usr/local/php-5.5 && \
+ make && make install && cd ..
+
+RUN wget http://am1.php.net/get/php-5.6.30.tar.bz2/from/this/mirror
+RUN mv mirror php-5.6.30.tar.bz2
+RUN tar -xvf php-5.6.30.tar.bz2
+RUN cd php-5.6.30 && ./configure --enable-maintainer-zts --prefix=/usr/local/php-5.6-zts && \
+ make && make install && cd ..
+RUN cd php-5.6.30 && make clean && ./configure --enable-bcmath --prefix=/usr/local/php-5.6 && \
+ make && make install && cd ..
+
+RUN wget http://am1.php.net/get/php-7.0.18.tar.bz2/from/this/mirror
+RUN mv mirror php-7.0.18.tar.bz2
+RUN tar -xvf php-7.0.18.tar.bz2
+RUN cd php-7.0.18 && ./configure --enable-maintainer-zts --prefix=/usr/local/php-7.0-zts && \
+ make && make install && cd ..
+RUN cd php-7.0.18 && make clean && ./configure --enable-bcmath --prefix=/usr/local/php-7.0 && \
+ make && make install && cd ..
+
+RUN wget http://am1.php.net/get/php-7.1.4.tar.bz2/from/this/mirror
+RUN mv mirror php-7.1.4.tar.bz2
+RUN tar -xvf php-7.1.4.tar.bz2
+RUN cd php-7.1.4 && ./configure --enable-maintainer-zts --prefix=/usr/local/php-7.1-zts && \
+ make && make install && cd ..
+RUN cd php-7.1.4 && make clean && ./configure --enable-bcmath --prefix=/usr/local/php-7.1 && \
+ make && make install && cd ..
+
RUN php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
RUN php composer-setup.php
RUN mv composer.phar /usr/bin/composer
RUN php -r "unlink('composer-setup.php');"
+RUN composer config -g -- disable-tls true
+RUN composer config -g -- secure-http false
RUN cd /tmp && \
rm -rf protobuf && \
git clone https://github.com/google/protobuf.git && \
cd protobuf && \
- git reset 46ae90dc5e145b12fffa7e053a908a9f3e066286 && \
+ git reset --hard 49b44bff2b6257a119f9c6a342d6151c736586b8 && \
cd php && \
- ln -sfn /usr/bin/php5.5 /usr/bin/php && \
- ln -sfn /usr/bin/php-config5.5 /usr/bin/php-config && \
- ln -sfn /usr/bin/phpize5.5 /usr/bin/phpize && \
+ ln -sfn /usr/local/php-5.5/bin/php /usr/bin/php && \
+ ln -sfn /usr/local/php-5.5/bin/php-config /usr/bin/php-config && \
+ ln -sfn /usr/local/php-5.5/bin/phpize /usr/bin/phpize && \
composer install && \
mv vendor /usr/local/vendor-5.5 && \
- ln -sfn /usr/bin/php5.6 /usr/bin/php && \
- ln -sfn /usr/bin/php-config5.6 /usr/bin/php-config && \
- ln -sfn /usr/bin/phpize5.6 /usr/bin/phpize && \
+ ln -sfn /usr/local/php-5.6/bin/php /usr/bin/php && \
+ ln -sfn /usr/local/php-5.6/bin/php-config /usr/bin/php-config && \
+ ln -sfn /usr/local/php-5.6/bin/phpize /usr/bin/phpize && \
composer install && \
mv vendor /usr/local/vendor-5.6 && \
- ln -sfn /usr/bin/php7.0 /usr/bin/php && \
- ln -sfn /usr/bin/php-config7.0 /usr/bin/php-config && \
- ln -sfn /usr/bin/phpize7.0 /usr/bin/phpize && \
+ ln -sfn /usr/local/php-7.0/bin/php /usr/bin/php && \
+ ln -sfn /usr/local/php-7.0/bin/php-config /usr/bin/php-config && \
+ ln -sfn /usr/local/php-7.0/bin/phpize /usr/bin/phpize && \
composer install && \
- mv vendor /usr/local/vendor-7.0
-RUN wget http://am1.php.net/get/php-5.5.38.tar.bz2/from/this/mirror
-RUN mv mirror php-5.5.38.tar.bz2
-RUN tar -xvf php-5.5.38.tar.bz2
-RUN cd php-5.5.38 && ./configure --enable-maintainer-zts --prefix=/usr/local/php-5.5-zts && \
- make && make install
+ mv vendor /usr/local/vendor-7.0 && \
+ ln -sfn /usr/local/php-7.1/bin/php /usr/bin/php && \
+ ln -sfn /usr/local/php-7.1/bin/php-config /usr/bin/php-config && \
+ ln -sfn /usr/local/php-7.1/bin/phpize /usr/bin/phpize && \
+ composer install && \
+ mv vendor /usr/local/vendor-7.1
##################
# Go dependencies.
@@ -186,6 +217,13 @@ RUN apt-get install -y \
# -- For javascript -- \
npm
+##################
+# Python 3.5 3.6 dependencies.
+RUN apt-get clean && apt-get update && apt-get install -y --force-yes \
+ python3.5-dev \
+ python3.6-dev \
+ && apt-get clean
+
# On Debian/Ubuntu, nodejs binary is named 'nodejs' because the name 'node'
# is taken by another legacy binary. We don't have that legacy binary and
# npm expects the binary to be named 'node', so we just create a symbol
diff --git a/jenkins/docker32/Dockerfile b/jenkins/docker32/Dockerfile
index 94d9a4c3..1278889f 100644
--- a/jenkins/docker32/Dockerfile
+++ b/jenkins/docker32/Dockerfile
@@ -57,36 +57,68 @@ RUN apt-get clean && apt-get update && apt-get install -y --force-yes \
##################
# PHP dependencies.
+RUN wget http://am1.php.net/get/php-5.5.38.tar.bz2/from/this/mirror
+RUN mv mirror php-5.5.38.tar.bz2
+RUN tar -xvf php-5.5.38.tar.bz2
+RUN cd php-5.5.38 && ./configure --enable-maintainer-zts --prefix=/usr/local/php-5.5-zts && \
+ make && make install && make clean && cd ..
+RUN cd php-5.5.38 && make clean && ./configure --enable-bcmath --prefix=/usr/local/php-5.5 && \
+ make && make install && make clean && cd ..
+
+RUN wget http://am1.php.net/get/php-5.6.30.tar.bz2/from/this/mirror
+RUN mv mirror php-5.6.30.tar.bz2
+RUN tar -xvf php-5.6.30.tar.bz2
+RUN cd php-5.6.30 && ./configure --enable-maintainer-zts --prefix=/usr/local/php-5.6-zts && \
+ make && make install && cd ..
+RUN cd php-5.6.30 && make clean && ./configure --enable-bcmath --prefix=/usr/local/php-5.6 && \
+ make && make install && cd ..
+
+RUN wget http://am1.php.net/get/php-7.0.18.tar.bz2/from/this/mirror
+RUN mv mirror php-7.0.18.tar.bz2
+RUN tar -xvf php-7.0.18.tar.bz2
+RUN cd php-7.0.18 && ./configure --enable-maintainer-zts --prefix=/usr/local/php-7.0-zts && \
+ make && make install && cd ..
+RUN cd php-7.0.18 && make clean && ./configure --enable-bcmath --prefix=/usr/local/php-7.0 && \
+ make && make install && cd ..
+
+RUN wget http://am1.php.net/get/php-7.1.4.tar.bz2/from/this/mirror
+RUN mv mirror php-7.1.4.tar.bz2
+RUN tar -xvf php-7.1.4.tar.bz2
+RUN cd php-7.1.4 && ./configure --enable-maintainer-zts --prefix=/usr/local/php-7.1-zts && \
+ make && make install && cd ..
+RUN cd php-7.1.4 && make clean && ./configure --enable-bcmath --prefix=/usr/local/php-7.1 && \
+ make && make install && cd ..
+
RUN php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
RUN php composer-setup.php
RUN mv composer.phar /usr/bin/composer
RUN php -r "unlink('composer-setup.php');"
+RUN composer config -g -- disable-tls true
+RUN composer config -g -- secure-http false
RUN cd /tmp && \
git clone https://github.com/google/protobuf.git && \
cd protobuf/php && \
- git reset 46ae90dc5e145b12fffa7e053a908a9f3e066286 && \
- ln -sfn /usr/bin/php5.5 /usr/bin/php && \
- ln -sfn /usr/bin/php-config5.5 /usr/bin/php-config && \
- ln -sfn /usr/bin/phpize5.5 /usr/bin/phpize && \
+ git reset --hard 49b44bff2b6257a119f9c6a342d6151c736586b8 && \
+ ln -sfn /usr/local/php-5.5/bin/php /usr/bin/php && \
+ ln -sfn /usr/local/php-5.5/bin/php-config /usr/bin/php-config && \
+ ln -sfn /usr/local/php-5.5/bin/phpize /usr/bin/phpize && \
composer install && \
mv vendor /usr/local/vendor-5.5 && \
- ln -sfn /usr/bin/php5.6 /usr/bin/php && \
- ln -sfn /usr/bin/php-config5.6 /usr/bin/php-config && \
- ln -sfn /usr/bin/phpize5.6 /usr/bin/phpize && \
+ ln -sfn /usr/local/php-5.6/bin/php /usr/bin/php && \
+ ln -sfn /usr/local/php-5.6/bin/php-config /usr/bin/php-config && \
+ ln -sfn /usr/local/php-5.6/bin/phpize /usr/bin/phpize && \
composer install && \
mv vendor /usr/local/vendor-5.6 && \
- ln -sfn /usr/bin/php7.0 /usr/bin/php && \
- ln -sfn /usr/bin/php-config7.0 /usr/bin/php-config && \
- ln -sfn /usr/bin/phpize7.0 /usr/bin/phpize && \
+ ln -sfn /usr/local/php-7.0/bin/php /usr/bin/php && \
+ ln -sfn /usr/local/php-7.0/bin/php-config /usr/bin/php-config && \
+ ln -sfn /usr/local/php-7.0/bin/phpize /usr/bin/phpize && \
composer install && \
- mv vendor /usr/local/vendor-7.0
-RUN wget http://am1.php.net/get/php-5.5.38.tar.bz2/from/this/mirror
-RUN mv mirror php-5.5.38.tar.bz2
-RUN tar -xvf php-5.5.38.tar.bz2
-RUN cd php-5.5.38 && ./configure --enable-maintainer-zts --prefix=/usr/local/php-5.5-zts && \
- make && make install && make clean && cd ..
-RUN cd php-5.5.38 && ./configure --enable-bcmath --prefix=/usr/local/php-5.5-bc && \
- make && make install && make clean && cd ..
+ mv vendor /usr/local/vendor-7.0 && \
+ ln -sfn /usr/local/php-7.1/bin/php /usr/bin/php && \
+ ln -sfn /usr/local/php-7.1/bin/php-config /usr/bin/php-config && \
+ ln -sfn /usr/local/php-7.1/bin/phpize /usr/bin/phpize && \
+ composer install && \
+ mv vendor /usr/local/vendor-7.1
##################
# Python dependencies
diff --git a/jenkins/make_test_output.py b/jenkins/make_test_output.py
index b1f2e2c0..98536853 100644
--- a/jenkins/make_test_output.py
+++ b/jenkins/make_test_output.py
@@ -17,11 +17,12 @@ detailed test results. It runs as the last step before the Jenkins build
finishes.
"""
-import os;
-import sys;
+import os
+import sys
from yattag import Doc
from collections import defaultdict
+
def readtests(basedir):
tests = defaultdict(dict)
@@ -68,6 +69,7 @@ def readtests(basedir):
return ret
+
def genxml(tests):
doc, tag, text = Doc().tagtext()
@@ -86,6 +88,7 @@ def genxml(tests):
return doc.getvalue()
+
sys.stderr.write("make_test_output.py: writing XML from directory: " +
- sys.argv[1] + "\n");
-print genxml(readtests(sys.argv[1]))
+ sys.argv[1] + "\n")
+print(genxml(readtests(sys.argv[1])))
diff --git a/js/README.md b/js/README.md
index f4184621..ef0d4b19 100644
--- a/js/README.md
+++ b/js/README.md
@@ -19,7 +19,9 @@ resolve imports at compile time.
To use Protocol Buffers with JavaScript, you need two main components:
1. The protobuf runtime library. You can install this with
- `npm install google-protobuf`, or use the files in this directory.
+ `npm install google-protobuf`, or use the files in this directory.
+ If npm is not being used, as of 3.3.0, the files needed are located in binary subdirectory;
+ arith.js, constants.js, decoder.js, encoder.js, map.js, message.js, reader.js, utils.js, writer.js
2. The Protocol Compiler `protoc`. This translates `.proto` files
into `.js` files. The compiler is not currently available via
npm, but you can download a pre-built binary
@@ -93,6 +95,12 @@ statements like:
var message = proto.my.package.MyMessage();
+If unfamiliar with Closure or it's compiler, consider reviewing Closure documentation
+https://developers.google.com/closure/library/docs/tutorial
+https://developers.google.com/closure/library/docs/closurebuilder
+https://developers.google.com/closure/library/docs/depswriter
+At a high level, closurebuilder.py can walk dependencies, and compile your code, and all dependencies for Protobuf into a single .js file. Using depsbuilder.py to generate a dependency file can also be considered for non-production dev environments.
+
CommonJS imports
----------------
@@ -150,7 +158,7 @@ idea of how the library generally works:
message.setPhoneNumbers(["800-555-1212", "800-555-0000"]);
// Serializes to a UInt8Array.
- bytes = message.serializeBinary();
+ var bytes = message.serializeBinary();
var message2 = MyMessage.deserializeBinary(bytes);
diff --git a/js/binary/arith_test.js b/js/binary/arith_test.js
index 89796bf7..dd5791a7 100644
--- a/js/binary/arith_test.js
+++ b/js/binary/arith_test.js
@@ -36,7 +36,6 @@
* @author cfallin@google.com (Chris Fallin)
*/
-goog.require('goog.testing.asserts');
goog.require('jspb.arith.Int64');
goog.require('jspb.arith.UInt64');
@@ -48,30 +47,30 @@ describe('binaryArithTest', function() {
it('testCompare', function() {
var a = new jspb.arith.UInt64(1234, 5678);
var b = new jspb.arith.UInt64(1234, 5678);
- assertEquals(a.cmp(b), 0);
- assertEquals(b.cmp(a), 0);
+ expect(a.cmp(b)).toEqual(0);
+ expect(b.cmp(a)).toEqual(0);
b.lo -= 1;
- assertEquals(a.cmp(b), 1);
- assertEquals(b.cmp(a), -1);
+ expect(a.cmp(b)).toEqual(1);
+ expect(b.cmp(a)).toEqual(-1);
b.lo += 2;
- assertEquals(a.cmp(b), -1);
- assertEquals(b.cmp(a), 1);
+ expect(a.cmp(b)).toEqual(-1);
+ expect(b.cmp(a)).toEqual(1);
b.lo = a.lo;
b.hi = a.hi - 1;
- assertEquals(a.cmp(b), 1);
- assertEquals(b.cmp(a), -1);
+ expect(a.cmp(b)).toEqual(1);
+ expect(b.cmp(a)).toEqual(-1);
- assertEquals(a.zero(), false);
- assertEquals(a.msb(), false);
- assertEquals(a.lsb(), false);
+ expect(a.zero()).toEqual(false);
+ expect(a.msb()).toEqual(false);
+ expect(a.lsb()).toEqual(false);
a.hi = 0;
a.lo = 0;
- assertEquals(a.zero(), true);
+ expect(a.zero()).toEqual(true);
a.hi = 0x80000000;
- assertEquals(a.zero(), false);
- assertEquals(a.msb(), true);
+ expect(a.zero()).toEqual(false);
+ expect(a.msb()).toEqual(true);
a.lo = 0x00000001;
- assertEquals(a.lsb(), true);
+ expect(a.lsb()).toEqual(true);
});
@@ -80,35 +79,35 @@ describe('binaryArithTest', function() {
*/
it('testShifts', function() {
var a = new jspb.arith.UInt64(1, 0);
- assertEquals(a.lo, 1);
- assertEquals(a.hi, 0);
+ expect(a.lo).toEqual(1);
+ expect(a.hi).toEqual(0);
var orig = a;
a = a.leftShift();
- assertEquals(orig.lo, 1); // original unmodified.
- assertEquals(orig.hi, 0);
- assertEquals(a.lo, 2);
- assertEquals(a.hi, 0);
+ expect(orig.lo).toEqual(1); // original unmodified.
+ expect(orig.hi).toEqual(0);
+ expect(a.lo).toEqual(2);
+ expect(a.hi).toEqual(0);
a = a.leftShift();
- assertEquals(a.lo, 4);
- assertEquals(a.hi, 0);
+ expect(a.lo).toEqual(4);
+ expect(a.hi).toEqual(0);
for (var i = 0; i < 29; i++) {
a = a.leftShift();
}
- assertEquals(a.lo, 0x80000000);
- assertEquals(a.hi, 0);
+ expect(a.lo).toEqual(0x80000000);
+ expect(a.hi).toEqual(0);
a = a.leftShift();
- assertEquals(a.lo, 0);
- assertEquals(a.hi, 1);
+ expect(a.lo).toEqual(0);
+ expect(a.hi).toEqual(1);
a = a.leftShift();
- assertEquals(a.lo, 0);
- assertEquals(a.hi, 2);
+ expect(a.lo).toEqual(0);
+ expect(a.hi).toEqual(2);
a = a.rightShift();
a = a.rightShift();
- assertEquals(a.lo, 0x80000000);
- assertEquals(a.hi, 0);
+ expect(a.lo).toEqual(0x80000000);
+ expect(a.hi).toEqual(0);
a = a.rightShift();
- assertEquals(a.lo, 0x40000000);
- assertEquals(a.hi, 0);
+ expect(a.lo).toEqual(0x40000000);
+ expect(a.hi).toEqual(0);
});
@@ -122,12 +121,12 @@ describe('binaryArithTest', function() {
/* hi = */ 0x92fa2123);
// Addition with carry.
var c = a.add(b);
- assertEquals(a.lo, 0x89abcdef); // originals unmodified.
- assertEquals(a.hi, 0x01234567);
- assertEquals(b.lo, 0xff52ab91);
- assertEquals(b.hi, 0x92fa2123);
- assertEquals(c.lo, 0x88fe7980);
- assertEquals(c.hi, 0x941d668b);
+ expect(a.lo).toEqual(0x89abcdef); // originals unmodified.
+ expect(a.hi).toEqual(0x01234567);
+ expect(b.lo).toEqual(0xff52ab91);
+ expect(b.hi).toEqual(0x92fa2123);
+ expect(c.lo).toEqual(0x88fe7980);
+ expect(c.hi).toEqual(0x941d668b);
// Simple addition without carry.
a.lo = 2;
@@ -135,8 +134,8 @@ describe('binaryArithTest', function() {
b.lo = 3;
b.hi = 0;
c = a.add(b);
- assertEquals(c.lo, 5);
- assertEquals(c.hi, 0);
+ expect(c.lo).toEqual(5);
+ expect(c.hi).toEqual(0);
});
@@ -170,8 +169,8 @@ describe('binaryArithTest', function() {
var a = new jspb.arith.UInt64(loValues[i], hiValues[j]);
var b = new jspb.arith.UInt64(loValues[j], hiValues[i]);
var c = a.add(b).sub(b);
- assertEquals(c.hi, a.hi);
- assertEquals(c.lo, a.lo);
+ expect(c.hi).toEqual(a.hi);
+ expect(c.lo).toEqual(a.lo);
}
}
});
@@ -201,8 +200,8 @@ describe('binaryArithTest', function() {
var cLow = testData[i][2] >>> 0;
var cHigh = testData[i][3] >>> 0;
var c = jspb.arith.UInt64.mul32x32(a, b);
- assertEquals(c.lo, cLow);
- assertEquals(c.hi, cHigh);
+ expect(c.lo).toEqual(cLow);
+ expect(c.hi).toEqual(cHigh);
}
});
@@ -231,8 +230,8 @@ describe('binaryArithTest', function() {
for (var i = 0; i < testData.length; i++) {
var a = new jspb.arith.UInt64(testData[i][0], testData[i][1]);
var prod = a.mul(testData[i][2]);
- assertEquals(prod.lo, testData[i][3]);
- assertEquals(prod.hi, testData[i][4]);
+ expect(prod.lo).toEqual(testData[i][3]);
+ expect(prod.hi).toEqual(testData[i][4]);
}
});
@@ -274,9 +273,9 @@ describe('binaryArithTest', function() {
var result = a.div(testData[i][2]);
var quotient = result[0];
var remainder = result[1];
- assertEquals(quotient.lo, testData[i][3]);
- assertEquals(quotient.hi, testData[i][4]);
- assertEquals(remainder.lo, testData[i][5]);
+ expect(quotient.lo).toEqual(testData[i][3]);
+ expect(quotient.hi).toEqual(testData[i][4]);
+ expect(remainder.lo).toEqual(testData[i][5]);
}
});
@@ -311,9 +310,9 @@ describe('binaryArithTest', function() {
for (var i = 0; i < testData.length; i++) {
var a = new jspb.arith.UInt64(testData[i][0], testData[i][1]);
var roundtrip = jspb.arith.UInt64.fromString(a.toString());
- assertEquals(roundtrip.lo, a.lo);
- assertEquals(roundtrip.hi, a.hi);
- assertEquals(a.toString(), testData[i][2]);
+ expect(roundtrip.lo).toEqual(a.lo);
+ expect(roundtrip.hi).toEqual(a.hi);
+ expect(a.toString()).toEqual(testData[i][2]);
}
});
@@ -349,7 +348,7 @@ describe('binaryArithTest', function() {
for (var i = 0; i < testStrings.length; i++) {
var roundtrip =
jspb.arith.Int64.fromString(testStrings[i]).toString();
- assertEquals(roundtrip, testStrings[i]);
+ expect(roundtrip).toEqual(testStrings[i]);
}
});
});
diff --git a/js/binary/constants.js b/js/binary/constants.js
index ef5fecdd..75a8a52c 100644
--- a/js/binary/constants.js
+++ b/js/binary/constants.js
@@ -51,6 +51,9 @@ goog.provide('jspb.ScalarFieldType');
goog.provide('jspb.WriterFunction');
+goog.forwardDeclare('jspb.BinaryMessage');
+goog.forwardDeclare('jspb.BinaryReader');
+goog.forwardDeclare('jspb.BinaryWriter');
goog.forwardDeclare('jspb.Message');
goog.forwardDeclare('jsproto.BinaryExtension');
diff --git a/js/binary/decoder.js b/js/binary/decoder.js
index 36828a73..4ec3cada 100644
--- a/js/binary/decoder.js
+++ b/js/binary/decoder.js
@@ -47,6 +47,7 @@ goog.provide('jspb.BinaryDecoder');
goog.provide('jspb.BinaryIterator');
goog.require('goog.asserts');
+goog.require('goog.crypt');
goog.require('jspb.utils');
@@ -71,7 +72,7 @@ jspb.BinaryIterator = function(opt_decoder, opt_next, opt_elements) {
*/
this.nextMethod_ = null;
- /** @private {Array.<number>} */
+ /** @private {?Array<number|boolean|string>} */
this.elements_ = null;
/** @private {number} */
@@ -100,7 +101,7 @@ jspb.BinaryIterator.prototype.init_ =
this.decoder_ = opt_decoder;
this.nextMethod_ = opt_next;
}
- this.elements_ = opt_elements ? opt_elements : null;
+ this.elements_ = opt_elements || null;
this.cursor_ = 0;
this.nextValue_ = null;
this.atEnd_ = !this.decoder_ && !this.elements_;
@@ -582,27 +583,24 @@ jspb.BinaryDecoder.prototype.readUnsignedVarint32 = function() {
x |= (temp & 0x0F) << 28;
if (temp < 128) {
// We're reading the high bits of an unsigned varint. The byte we just read
- // also contains bits 33 through 35, which we're going to discard. Those
- // bits _must_ be zero, or the encoding is invalid.
- goog.asserts.assert((temp & 0xF0) == 0);
+ // also contains bits 33 through 35, which we're going to discard.
this.cursor_ += 5;
goog.asserts.assert(this.cursor_ <= this.end_);
return x >>> 0;
}
- // If we get here, we're reading the sign extension of a negative 32-bit int.
- // We can skip these bytes, as we know in advance that they have to be all
- // 1's if the varint is correctly encoded. Since we also know the value is
- // negative, we don't have to coerce it to unsigned before we return it.
-
- goog.asserts.assert((temp & 0xF0) == 0xF0);
- goog.asserts.assert(bytes[this.cursor_ + 5] == 0xFF);
- goog.asserts.assert(bytes[this.cursor_ + 6] == 0xFF);
- goog.asserts.assert(bytes[this.cursor_ + 7] == 0xFF);
- goog.asserts.assert(bytes[this.cursor_ + 8] == 0xFF);
- goog.asserts.assert(bytes[this.cursor_ + 9] == 0x01);
+ // If we get here, we need to truncate coming bytes. However we need to make
+ // sure cursor place is correct.
+ this.cursor_ += 5;
+ if (bytes[this.cursor_++] >= 128 &&
+ bytes[this.cursor_++] >= 128 &&
+ bytes[this.cursor_++] >= 128 &&
+ bytes[this.cursor_++] >= 128 &&
+ bytes[this.cursor_++] >= 128) {
+ // If we get here, the varint is too long.
+ goog.asserts.assert(false);
+ }
- this.cursor_ += 10;
goog.asserts.assert(this.cursor_ <= this.end_);
return x;
};
@@ -942,7 +940,7 @@ jspb.BinaryDecoder.prototype.readEnum = function() {
/**
* Reads and parses a UTF-8 encoded unicode string from the stream.
* The code is inspired by maps.vectortown.parse.StreamedDataViewReader.
- * Supports codepoints from U+0000 up to U+10FFFF.
+ * Supports codepoints from U+0000 up to U+10FFFF.
* (http://en.wikipedia.org/wiki/UTF-8).
* @param {number} length The length of the string to read.
* @return {string} The decoded string.
@@ -953,6 +951,7 @@ jspb.BinaryDecoder.prototype.readString = function(length) {
var end = cursor + length;
var codeUnits = [];
+ var result = '';
while (cursor < end) {
var c = bytes[cursor++];
if (c < 128) { // Regular 7-bit ASCII.
@@ -973,7 +972,7 @@ jspb.BinaryDecoder.prototype.readString = function(length) {
var c2 = bytes[cursor++];
var c3 = bytes[cursor++];
var c4 = bytes[cursor++];
- // Characters written on 4 bytes have 21 bits for a codepoint.
+ // Characters written on 4 bytes have 21 bits for a codepoint.
// We can't fit that on 16bit characters, so we use surrogates.
var codepoint = ((c & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63);
// Surrogates formula from wikipedia.
@@ -984,12 +983,16 @@ jspb.BinaryDecoder.prototype.readString = function(length) {
// 4. Add 0xDC00 to the low value to form the low surrogate:
var low = (codepoint & 1023) + 0xDC00;
var high = ((codepoint >> 10) & 1023) + 0xD800;
- codeUnits.push(high, low)
+ codeUnits.push(high, low);
+ }
+
+ // Avoid exceeding the maximum stack size when calling {@code apply}.
+ if (codeUnits.length >= 8192) {
+ result += String.fromCharCode.apply(null, codeUnits);
+ codeUnits.length = 0;
}
}
- // String.fromCharCode.apply is faster than manually appending characters on
- // Chrome 25+, and generates no additional cons string garbage.
- var result = String.fromCharCode.apply(null, codeUnits);
+ result += goog.crypt.byteArrayToString(codeUnits);
this.cursor_ = cursor;
return result;
};
diff --git a/js/binary/decoder_test.js b/js/binary/decoder_test.js
index 9f947b99..b19e1d1b 100644
--- a/js/binary/decoder_test.js
+++ b/js/binary/decoder_test.js
@@ -209,25 +209,44 @@ describe('binaryDecoderTest', function() {
assertEquals(hashC, decoder.readFixedHash64());
assertEquals(hashD, decoder.readFixedHash64());
});
-
+
+ /**
+ * Tests reading and writing large strings
+ */
+ it('testLargeStrings', function() {
+ var encoder = new jspb.BinaryEncoder();
+
+ var len = 150000;
+ var long_string = '';
+ for (var i = 0; i < len; i++) {
+ long_string += 'a';
+ }
+
+ encoder.writeString(long_string);
+
+ var decoder = jspb.BinaryDecoder.alloc(encoder.end());
+
+ assertEquals(long_string, decoder.readString(len));
+ });
+
/**
* Test encoding and decoding utf-8.
*/
it('testUtf8', function() {
var encoder = new jspb.BinaryEncoder();
- var ascii = "ASCII should work in 3, 2, 1..."
+ var ascii = "ASCII should work in 3, 2, 1...";
var utf8_two_bytes = "©";
var utf8_three_bytes = "❄";
var utf8_four_bytes = "😁";
-
+
encoder.writeString(ascii);
encoder.writeString(utf8_two_bytes);
encoder.writeString(utf8_three_bytes);
encoder.writeString(utf8_four_bytes);
-
+
var decoder = jspb.BinaryDecoder.alloc(encoder.end());
-
+
assertEquals(ascii, decoder.readString(ascii.length));
assertEquals(utf8_two_bytes, decoder.readString(utf8_two_bytes.length));
assertEquals(utf8_three_bytes, decoder.readString(utf8_three_bytes.length));
@@ -251,24 +270,7 @@ describe('binaryDecoderTest', function() {
assertThrows(function() {decoder.readSignedVarint64()});
decoder.reset();
assertThrows(function() {decoder.readZigzagVarint64()});
-
- // Positive 32-bit varints encoded with 1 bits in positions 33 through 35
- // should trigger assertions.
- decoder.setBlock([255, 255, 255, 255, 0x1F]);
- assertThrows(function() {decoder.readUnsignedVarint32()});
-
- decoder.setBlock([255, 255, 255, 255, 0x2F]);
- assertThrows(function() {decoder.readUnsignedVarint32()});
-
- decoder.setBlock([255, 255, 255, 255, 0x4F]);
- assertThrows(function() {decoder.readUnsignedVarint32()});
-
- // Negative 32-bit varints encoded with non-1 bits in the high dword should
- // trigger assertions.
- decoder.setBlock([255, 255, 255, 255, 255, 255, 0, 255, 255, 1]);
- assertThrows(function() {decoder.readUnsignedVarint32()});
-
- decoder.setBlock([255, 255, 255, 255, 255, 255, 255, 255, 255, 0]);
+ decoder.reset();
assertThrows(function() {decoder.readUnsignedVarint32()});
});
diff --git a/js/binary/encoder.js b/js/binary/encoder.js
index 1663bbd4..8e9f5bbc 100644
--- a/js/binary/encoder.js
+++ b/js/binary/encoder.js
@@ -355,8 +355,8 @@ jspb.BinaryEncoder.prototype.writeInt64 = function(value) {
*/
jspb.BinaryEncoder.prototype.writeInt64String = function(value) {
goog.asserts.assert(value == Math.floor(value));
- goog.asserts.assert((value >= -jspb.BinaryConstants.TWO_TO_63) &&
- (value < jspb.BinaryConstants.TWO_TO_63));
+ goog.asserts.assert((+value >= -jspb.BinaryConstants.TWO_TO_63) &&
+ (+value < jspb.BinaryConstants.TWO_TO_63));
jspb.utils.splitHash64(jspb.utils.decimalStringToHash64(value));
this.writeSplitFixed64(jspb.utils.split64Low, jspb.utils.split64High);
};
@@ -390,11 +390,13 @@ jspb.BinaryEncoder.prototype.writeDouble = function(value) {
/**
- * Writes a boolean value to the buffer as a varint.
- * @param {boolean} value The value to write.
+ * Writes a boolean value to the buffer as a varint. We allow numbers as input
+ * because the JSPB code generator uses 0/1 instead of true/false to save space
+ * in the string representation of the proto.
+ * @param {boolean|number} value The value to write.
*/
jspb.BinaryEncoder.prototype.writeBool = function(value) {
- goog.asserts.assert(goog.isBoolean(value));
+ goog.asserts.assert(goog.isBoolean(value) || goog.isNumber(value));
this.buffer_.push(value ? 1 : 0);
};
@@ -452,9 +454,9 @@ jspb.BinaryEncoder.prototype.writeFixedHash64 = function(hash) {
*/
jspb.BinaryEncoder.prototype.writeString = function(value) {
var oldLength = this.buffer_.length;
-
+
for (var i = 0; i < value.length; i++) {
-
+
var c = value.charCodeAt(i);
if (c < 128) {
diff --git a/js/binary/message_test.js b/js/binary/message_test.js
new file mode 100644
index 00000000..4edc666b
--- /dev/null
+++ b/js/binary/message_test.js
@@ -0,0 +1,60 @@
+// 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.
+
+// Test suite is written using Jasmine -- see http://jasmine.github.io/
+
+goog.setTestOnly();
+
+goog.require('goog.testing.asserts');
+
+// CommonJS-LoadFromFile: test_pb proto.jspb.test
+goog.require('proto.jspb.test.Deeply.Nested.Message');
+
+// CommonJS-LoadFromFile: test2_pb proto.jspb.test
+goog.require('proto.jspb.test.ForeignNestedFieldMessage');
+
+describe('Message test suite', function() {
+ // Verify that we can successfully use a field referring to a nested message
+ // from a different .proto file.
+ it('testForeignNestedMessage', function() {
+ var msg = new proto.jspb.test.ForeignNestedFieldMessage();
+ var nested = new proto.jspb.test.Deeply.Nested.Message();
+ nested.setCount(5);
+ msg.setDeeplyNestedMessage(nested);
+ assertEquals(5, msg.getDeeplyNestedMessage().getCount());
+
+ // After a serialization-deserialization round trip we should get back the
+ // same data we started with.
+ var serialized = msg.serializeBinary();
+ var deserialized =
+ proto.jspb.test.ForeignNestedFieldMessage.deserializeBinary(serialized);
+ assertEquals(5, deserialized.getDeeplyNestedMessage().getCount());
+ });
+});
diff --git a/js/binary/proto_test.js b/js/binary/proto_test.js
index f86dc645..f5e1b6bb 100644
--- a/js/binary/proto_test.js
+++ b/js/binary/proto_test.js
@@ -283,8 +283,7 @@ function checkAllFields(original, copy) {
* @param {!proto.jspb.test.TestExtendable} msg
*/
function checkExtensions(msg) {
- assertEquals(-42,
- msg.getExtension(proto.jspb.test.extendOptionalInt32));
+ assertEquals(0, msg.getExtension(proto.jspb.test.extendOptionalInt32));
assertEquals(-0x7fffffff00000000,
msg.getExtension(proto.jspb.test.extendOptionalInt64));
assertEquals(0x80000000,
@@ -512,8 +511,7 @@ describe('protoBinaryTest', function() {
* @param {proto.jspb.test.TestExtendable} msg
*/
function fillExtensions(msg) {
- msg.setExtension(
- proto.jspb.test.extendOptionalInt32, -42);
+ msg.setExtension(proto.jspb.test.extendOptionalInt32, 0);
msg.setExtension(
proto.jspb.test.extendOptionalInt64, -0x7fffffff00000000);
msg.setExtension(
diff --git a/js/binary/reader.js b/js/binary/reader.js
index 8c5a4e88..d5d698f7 100644
--- a/js/binary/reader.js
+++ b/js/binary/reader.js
@@ -971,7 +971,7 @@ jspb.BinaryReader.prototype.readFixedHash64 = function() {
/**
* Reads a packed scalar field using the supplied raw reader function.
- * @param {function()} decodeMethod
+ * @param {function(this:jspb.BinaryDecoder)} decodeMethod
* @return {!Array}
* @private
*/
diff --git a/js/binary/utils.js b/js/binary/utils.js
index bbf99cdf..c706bff4 100644
--- a/js/binary/utils.js
+++ b/js/binary/utils.js
@@ -38,6 +38,7 @@
goog.provide('jspb.utils');
goog.require('goog.asserts');
+goog.require('goog.crypt');
goog.require('goog.crypt.base64');
goog.require('goog.string');
goog.require('jspb.BinaryConstants');
@@ -430,7 +431,7 @@ jspb.utils.joinHash64 = function(bitsLow, bitsHigh) {
/**
* Individual digits for number->string conversion.
- * @const {!Array.<number>}
+ * @const {!Array.<string>}
*/
jspb.utils.DIGITS = [
'0', '1', '2', '3', '4', '5', '6', '7',
@@ -613,7 +614,7 @@ jspb.utils.decimalStringToHash64 = function(dec) {
muladd(1, 1);
}
- return String.fromCharCode.apply(null, resultBytes);
+ return goog.crypt.byteArrayToString(resultBytes);
};
diff --git a/js/binary/utils_test.js b/js/binary/utils_test.js
index d27e5ea2..6b481dce 100644
--- a/js/binary/utils_test.js
+++ b/js/binary/utils_test.js
@@ -36,6 +36,7 @@
* @author aappleby@google.com (Austin Appleby)
*/
+goog.require('goog.crypt');
goog.require('goog.crypt.base64');
goog.require('goog.testing.asserts');
goog.require('jspb.BinaryConstants');
@@ -205,31 +206,31 @@ describe('binaryUtilsTest', function() {
var convert = jspb.utils.decimalStringToHash64;
result = convert('0');
- assertEquals(String.fromCharCode.apply(null,
+ assertEquals(goog.crypt.byteArrayToString(
[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), result);
result = convert('-1');
- assertEquals(String.fromCharCode.apply(null,
+ assertEquals(goog.crypt.byteArrayToString(
[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]), result);
result = convert('18446744073709551615');
- assertEquals(String.fromCharCode.apply(null,
+ assertEquals(goog.crypt.byteArrayToString(
[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]), result);
result = convert('9223372036854775808');
- assertEquals(String.fromCharCode.apply(null,
+ assertEquals(goog.crypt.byteArrayToString(
[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80]), result);
result = convert('-9223372036854775808');
- assertEquals(String.fromCharCode.apply(null,
+ assertEquals(goog.crypt.byteArrayToString(
[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80]), result);
result = convert('123456789123456789');
- assertEquals(String.fromCharCode.apply(null,
+ assertEquals(goog.crypt.byteArrayToString(
[0x15, 0x5F, 0xD0, 0xAC, 0x4B, 0x9B, 0xB6, 0x01]), result);
result = convert('-123456789123456789');
- assertEquals(String.fromCharCode.apply(null,
+ assertEquals(goog.crypt.byteArrayToString(
[0xEB, 0xA0, 0x2F, 0x53, 0xB4, 0x64, 0x49, 0xFE]), result);
});
@@ -259,21 +260,21 @@ describe('binaryUtilsTest', function() {
var convert = jspb.utils.hexStringToHash64;
result = convert('0x0000000000000000');
- assertEquals(String.fromCharCode.apply(null,
+ assertEquals(goog.crypt.byteArrayToString(
[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), result);
result = convert('0xffffffffffffffff');
- assertEquals(String.fromCharCode.apply(null,
+ assertEquals(goog.crypt.byteArrayToString(
[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]), result);
// Hex string is big-endian, hash string is little-endian.
result = convert('0x123456789ABCDEF0');
- assertEquals(String.fromCharCode.apply(null,
+ assertEquals(goog.crypt.byteArrayToString(
[0xF0, 0xDE, 0xBC, 0x9A, 0x78, 0x56, 0x34, 0x12]), result);
// Capitalization should not matter.
result = convert('0x0000abcdefABCDEF');
- assertEquals(String.fromCharCode.apply(null,
+ assertEquals(goog.crypt.byteArrayToString(
[0xEF, 0xCD, 0xAB, 0xEF, 0xCD, 0xAB, 0x00, 0x00]), result);
});
@@ -643,7 +644,7 @@ describe('binaryUtilsTest', function() {
var sourceBytes = new Uint8Array(sourceData);
var sourceBuffer = sourceBytes.buffer;
var sourceBase64 = goog.crypt.base64.encodeByteArray(sourceData);
- var sourceString = String.fromCharCode.apply(null, sourceData);
+ var sourceString = goog.crypt.byteArrayToString(sourceData);
function check(result) {
assertEquals(Uint8Array, result.constructor);
diff --git a/js/binary/writer.js b/js/binary/writer.js
index c3009dbb..037e92b2 100644
--- a/js/binary/writer.js
+++ b/js/binary/writer.js
@@ -235,7 +235,7 @@ jspb.BinaryWriter.prototype.getResultBuffer = function() {
/**
- * Converts the encoded data into a bas64-encoded string.
+ * Converts the encoded data into a base64-encoded string.
* @return {string}
*/
jspb.BinaryWriter.prototype.getResultBase64String = function() {
@@ -596,8 +596,8 @@ jspb.BinaryWriter.prototype.writeSint64 = function(field, value) {
*/
jspb.BinaryWriter.prototype.writeSint64String = function(field, value) {
if (value == null) return;
- goog.asserts.assert((value >= -jspb.BinaryConstants.TWO_TO_63) &&
- (value < jspb.BinaryConstants.TWO_TO_63));
+ goog.asserts.assert((+value >= -jspb.BinaryConstants.TWO_TO_63) &&
+ (+value < jspb.BinaryConstants.TWO_TO_63));
this.writeZigzagVarint64String_(field, value);
};
@@ -716,13 +716,15 @@ jspb.BinaryWriter.prototype.writeDouble = function(field, value) {
/**
- * Writes a boolean field to the buffer.
+ * Writes a boolean field to the buffer. We allow numbers as input
+ * because the JSPB code generator uses 0/1 instead of true/false to save space
+ * in the string representation of the proto.
* @param {number} field The field number.
- * @param {boolean?} value The value to write.
+ * @param {boolean?|number?} value The value to write.
*/
jspb.BinaryWriter.prototype.writeBool = function(field, value) {
if (value == null) return;
- goog.asserts.assert(goog.isBoolean(value));
+ goog.asserts.assert(goog.isBoolean(value) || goog.isNumber(value));
this.writeFieldHeader_(field, jspb.BinaryConstants.WireType.VARINT);
this.encoder_.writeBool(value);
};
diff --git a/js/binary/writer_test.js b/js/binary/writer_test.js
index 54d37a21..118eecfc 100644
--- a/js/binary/writer_test.js
+++ b/js/binary/writer_test.js
@@ -47,9 +47,7 @@ goog.require('jspb.BinaryWriter');
* @param {function()} func This function should throw an error when run.
*/
function assertFails(func) {
- var e = assertThrows(func);
- console.log(e);
- //assertNotNull(e.toString().match(/Error/));
+ assertThrows(func);
}
diff --git a/js/commonjs/export.js b/js/commonjs/export.js
index 1eaab5d5..a93ee928 100644
--- a/js/commonjs/export.js
+++ b/js/commonjs/export.js
@@ -5,6 +5,10 @@
* the google-protobuf.js file that we build at distribution time.
*/
+// Include a dummy provide statement so that closurebuilder.py does not skip over this
+// file.
+goog.provide('jspb.Export');
+
goog.require('goog.object');
goog.require('jspb.BinaryReader');
goog.require('jspb.BinaryWriter');
diff --git a/js/commonjs/export_asserts.js b/js/commonjs/export_asserts.js
index 5219d120..ad9446c7 100644
--- a/js/commonjs/export_asserts.js
+++ b/js/commonjs/export_asserts.js
@@ -6,6 +6,10 @@
* closure_asserts_commonjs.js that is only used at testing time.
*/
+// Include a dummy provide statement so that closurebuilder.py does not skip over this
+// file.
+goog.provide('jspb.ExportAsserts');
+
goog.require('goog.testing.asserts');
var global = Function('return this')();
diff --git a/js/commonjs/export_testdeps.js b/js/commonjs/export_testdeps.js
index 174c61e6..6f5cd083 100644
--- a/js/commonjs/export_testdeps.js
+++ b/js/commonjs/export_testdeps.js
@@ -7,6 +7,10 @@
* export_asserts.js.
*/
+// Include a dummy provide statement so that closurebuilder.py does not skip over this
+// file.
+goog.provide('jspb.ExportTestDeps');
+
goog.require('goog.crypt.base64');
goog.require('jspb.arith.Int64');
goog.require('jspb.arith.UInt64');
diff --git a/js/compatibility_tests/v3.0.0/binary/arith_test.js b/js/compatibility_tests/v3.0.0/binary/arith_test.js
new file mode 100644
index 00000000..89796bf7
--- /dev/null
+++ b/js/compatibility_tests/v3.0.0/binary/arith_test.js
@@ -0,0 +1,355 @@
+// 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.
+
+/**
+ * @fileoverview Test cases for Int64-manipulation functions.
+ *
+ * Test suite is written using Jasmine -- see http://jasmine.github.io/
+ *
+ * @author cfallin@google.com (Chris Fallin)
+ */
+
+goog.require('goog.testing.asserts');
+goog.require('jspb.arith.Int64');
+goog.require('jspb.arith.UInt64');
+
+
+describe('binaryArithTest', function() {
+ /**
+ * Tests comparison operations.
+ */
+ it('testCompare', function() {
+ var a = new jspb.arith.UInt64(1234, 5678);
+ var b = new jspb.arith.UInt64(1234, 5678);
+ assertEquals(a.cmp(b), 0);
+ assertEquals(b.cmp(a), 0);
+ b.lo -= 1;
+ assertEquals(a.cmp(b), 1);
+ assertEquals(b.cmp(a), -1);
+ b.lo += 2;
+ assertEquals(a.cmp(b), -1);
+ assertEquals(b.cmp(a), 1);
+ b.lo = a.lo;
+ b.hi = a.hi - 1;
+ assertEquals(a.cmp(b), 1);
+ assertEquals(b.cmp(a), -1);
+
+ assertEquals(a.zero(), false);
+ assertEquals(a.msb(), false);
+ assertEquals(a.lsb(), false);
+ a.hi = 0;
+ a.lo = 0;
+ assertEquals(a.zero(), true);
+ a.hi = 0x80000000;
+ assertEquals(a.zero(), false);
+ assertEquals(a.msb(), true);
+ a.lo = 0x00000001;
+ assertEquals(a.lsb(), true);
+ });
+
+
+ /**
+ * Tests shifts.
+ */
+ it('testShifts', function() {
+ var a = new jspb.arith.UInt64(1, 0);
+ assertEquals(a.lo, 1);
+ assertEquals(a.hi, 0);
+ var orig = a;
+ a = a.leftShift();
+ assertEquals(orig.lo, 1); // original unmodified.
+ assertEquals(orig.hi, 0);
+ assertEquals(a.lo, 2);
+ assertEquals(a.hi, 0);
+ a = a.leftShift();
+ assertEquals(a.lo, 4);
+ assertEquals(a.hi, 0);
+ for (var i = 0; i < 29; i++) {
+ a = a.leftShift();
+ }
+ assertEquals(a.lo, 0x80000000);
+ assertEquals(a.hi, 0);
+ a = a.leftShift();
+ assertEquals(a.lo, 0);
+ assertEquals(a.hi, 1);
+ a = a.leftShift();
+ assertEquals(a.lo, 0);
+ assertEquals(a.hi, 2);
+ a = a.rightShift();
+ a = a.rightShift();
+ assertEquals(a.lo, 0x80000000);
+ assertEquals(a.hi, 0);
+ a = a.rightShift();
+ assertEquals(a.lo, 0x40000000);
+ assertEquals(a.hi, 0);
+ });
+
+
+ /**
+ * Tests additions.
+ */
+ it('testAdd', function() {
+ var a = new jspb.arith.UInt64(/* lo = */ 0x89abcdef,
+ /* hi = */ 0x01234567);
+ var b = new jspb.arith.UInt64(/* lo = */ 0xff52ab91,
+ /* hi = */ 0x92fa2123);
+ // Addition with carry.
+ var c = a.add(b);
+ assertEquals(a.lo, 0x89abcdef); // originals unmodified.
+ assertEquals(a.hi, 0x01234567);
+ assertEquals(b.lo, 0xff52ab91);
+ assertEquals(b.hi, 0x92fa2123);
+ assertEquals(c.lo, 0x88fe7980);
+ assertEquals(c.hi, 0x941d668b);
+
+ // Simple addition without carry.
+ a.lo = 2;
+ a.hi = 0;
+ b.lo = 3;
+ b.hi = 0;
+ c = a.add(b);
+ assertEquals(c.lo, 5);
+ assertEquals(c.hi, 0);
+ });
+
+
+ /**
+ * Test subtractions.
+ */
+ it('testSub', function() {
+ var kLength = 10;
+ var hiValues = [0x1682ef32,
+ 0x583902f7,
+ 0xb62f5955,
+ 0x6ea99bbf,
+ 0x25a39c20,
+ 0x0700a08b,
+ 0x00f7304d,
+ 0x91a5b5af,
+ 0x89077fd2,
+ 0xe09e347c];
+ var loValues = [0xe1538b18,
+ 0xbeacd556,
+ 0x74100758,
+ 0x96e3cb26,
+ 0x56c37c3f,
+ 0xe00b3f7d,
+ 0x859f25d7,
+ 0xc2ee614a,
+ 0xe1d21cd7,
+ 0x30aae6a4];
+ for (var i = 0; i < kLength; i++) {
+ for (var j = 0; j < kLength; j++) {
+ var a = new jspb.arith.UInt64(loValues[i], hiValues[j]);
+ var b = new jspb.arith.UInt64(loValues[j], hiValues[i]);
+ var c = a.add(b).sub(b);
+ assertEquals(c.hi, a.hi);
+ assertEquals(c.lo, a.lo);
+ }
+ }
+ });
+
+
+ /**
+ * Tests 32-by-32 multiplication.
+ */
+ it('testMul32x32', function() {
+ var testData = [
+ // a b low(a*b) high(a*b)
+ [0xc0abe2f8, 0x1607898a, 0x5de711b0, 0x109471b8],
+ [0x915eb3cb, 0x4fb66d0e, 0xbd0d441a, 0x2d43d0bc],
+ [0xfe4efe70, 0x80b48c37, 0xbcddea10, 0x7fdada0c],
+ [0xe222fd4a, 0xe43d524a, 0xd5e0eb64, 0xc99d549c],
+ [0xd171f469, 0xb94ebd01, 0x4be17969, 0x979bc4fa],
+ [0x829cc1df, 0xe2598b38, 0xf4157dc8, 0x737c12ad],
+ [0xf10c3767, 0x8382881e, 0x942b3612, 0x7bd428b8],
+ [0xb0f6dd24, 0x232597e1, 0x079c98a4, 0x184bbce7],
+ [0xfcdb05a7, 0x902f55bc, 0x636199a4, 0x8e69f412],
+ [0x0dd0bfa9, 0x916e27b1, 0x6e2542d9, 0x07d92e65]
+ ];
+
+ for (var i = 0; i < testData.length; i++) {
+ var a = testData[i][0] >>> 0;
+ var b = testData[i][1] >>> 0;
+ var cLow = testData[i][2] >>> 0;
+ var cHigh = testData[i][3] >>> 0;
+ var c = jspb.arith.UInt64.mul32x32(a, b);
+ assertEquals(c.lo, cLow);
+ assertEquals(c.hi, cHigh);
+ }
+ });
+
+
+ /**
+ * Tests 64-by-32 multiplication.
+ */
+ it('testMul', function() {
+ // 64x32 bits produces 96 bits of product. The multiplication function under
+ // test truncates the top 32 bits, so we compare against a 64-bit expected
+ // product.
+ var testData = [
+ // low(a) high(a) low(a*b) high(a*b)
+ [0xec10955b, 0x360eb168, 0x4b7f3f5b, 0xbfcb7c59, 0x9517da5f],
+ [0x42b000fc, 0x9d101642, 0x6fa1ab72, 0x2584c438, 0x6a9e6d2b],
+ [0xf42d4fb4, 0xae366403, 0xa65a1000, 0x92434000, 0x1ff978df],
+ [0x17e2f56b, 0x25487693, 0xf13f98c7, 0x73794e2d, 0xa96b0c6a],
+ [0x492f241f, 0x76c0eb67, 0x7377ac44, 0xd4336c3c, 0xfc4b1ebe],
+ [0xd6b92321, 0xe184fa48, 0xd6e76904, 0x93141584, 0xcbf44da1],
+ [0x4bf007ea, 0x968c0a9e, 0xf5e4026a, 0x4fdb1ae4, 0x61b9fb7d],
+ [0x10a83be7, 0x2d685ba6, 0xc9e5fb7f, 0x2ad43499, 0x3742473d],
+ [0x2f261829, 0x1aca681a, 0x3d3494e3, 0x8213205b, 0x283719f8],
+ [0xe4f2ce21, 0x2e74b7bd, 0xd801b38b, 0xbc17feeb, 0xc6c44e0f]
+ ];
+
+ for (var i = 0; i < testData.length; i++) {
+ var a = new jspb.arith.UInt64(testData[i][0], testData[i][1]);
+ var prod = a.mul(testData[i][2]);
+ assertEquals(prod.lo, testData[i][3]);
+ assertEquals(prod.hi, testData[i][4]);
+ }
+ });
+
+
+ /**
+ * Tests 64-div-by-32 division.
+ */
+ it('testDiv', function() {
+ // Compute a/b, yielding quot = a/b and rem = a%b.
+ var testData = [
+ // --- divisors in (0, 2^32-1) to test full divisor range
+ // low(a) high(a) b low(quot) high(quot) rem
+ [0x712443f1, 0xe85cefcc, 0xc1a7050b, 0x332c79ad, 0x00000001, 0x92ffa882],
+ [0x11912915, 0xb2699eb5, 0x30467cbe, 0xb21b4be4, 0x00000003, 0x283465dd],
+ [0x0d917982, 0x201f2a6e, 0x3f35bf03, 0x8217c8e4, 0x00000000, 0x153402d6],
+ [0xa072c108, 0x74020c96, 0xc60568fd, 0x95f9613e, 0x00000000, 0x3f4676c2],
+ [0xd845d5d8, 0xcdd235c4, 0x20426475, 0x6154e78b, 0x00000006, 0x202fb751],
+ [0xa4dbf71f, 0x9e90465e, 0xf08e022f, 0xa8be947f, 0x00000000, 0xbe43b5ce],
+ [0x3dbe627f, 0xa791f4b9, 0x28a5bd89, 0x1f5dfe93, 0x00000004, 0x02bf9ed4],
+ [0x5c1c53ee, 0xccf5102e, 0x198576e7, 0x07e3ae31, 0x00000008, 0x02ea8fb7],
+ [0xfef1e581, 0x04714067, 0xca6540c1, 0x059e73ec, 0x00000000, 0x31658095],
+ [0x1e2dd90c, 0x13dd6667, 0x8b2184c3, 0x248d1a42, 0x00000000, 0x4ca6d0c6],
+ // --- divisors in (0, 2^16-1) to test larger quotient high-words
+ // low(a) high(a) b low(quot) high(quot) rem
+ [0x86722b47, 0x2cd57c9a, 0x00003123, 0x2ae41b7a, 0x0000e995, 0x00000f99],
+ [0x1dd7884c, 0xf5e839bc, 0x00009eeb, 0x5c886242, 0x00018c21, 0x000099b6],
+ [0x5c53d625, 0x899fc7e5, 0x000087d7, 0xd625007a, 0x0001035c, 0x000019af],
+ [0x6932d932, 0x9d0a5488, 0x000051fb, 0x9d976143, 0x0001ea63, 0x00004981],
+ [0x4d18bb85, 0x0c92fb31, 0x00001d9f, 0x03265ab4, 0x00006cac, 0x000001b9],
+ [0xbe756768, 0xdea67ccb, 0x00008a03, 0x58add442, 0x00019cff, 0x000056a2],
+ [0xe2466f9a, 0x2521f114, 0x0000c350, 0xa0c0860d, 0x000030ab, 0x0000a48a],
+ [0xf00ddad1, 0xe2f5446a, 0x00002cfc, 0x762697a6, 0x00050b96, 0x00000b69],
+ [0xa879152a, 0x0a70e0a5, 0x00007cdf, 0xb44151b3, 0x00001567, 0x0000363d],
+ [0x7179a74c, 0x46083fff, 0x0000253c, 0x4d39ba6e, 0x0001e17f, 0x00000f84]
+ ];
+
+ for (var i = 0; i < testData.length; i++) {
+ var a = new jspb.arith.UInt64(testData[i][0], testData[i][1]);
+ var result = a.div(testData[i][2]);
+ var quotient = result[0];
+ var remainder = result[1];
+ assertEquals(quotient.lo, testData[i][3]);
+ assertEquals(quotient.hi, testData[i][4]);
+ assertEquals(remainder.lo, testData[i][5]);
+ }
+ });
+
+
+ /**
+ * Tests .toString() and .fromString().
+ */
+ it('testStrings', function() {
+ var testData = [
+ [0x5e84c935, 0xcae33d0e, '14619595947299359029'],
+ [0x62b3b8b8, 0x93480544, '10612738313170434232'],
+ [0x319bfb13, 0xc01c4172, '13843011313344445203'],
+ [0x5b8a65fb, 0xa5885b31, '11927883880638080507'],
+ [0x6bdb80f1, 0xb0d1b16b, '12741159895737008369'],
+ [0x4b82b442, 0x2e0d8c97, '3318463081876730946'],
+ [0x780d5208, 0x7d76752c, '9040542135845999112'],
+ [0x2e46800f, 0x0993778d, '690026616168284175'],
+ [0xf00a7e32, 0xcd8e3931, '14811839111111540274'],
+ [0x1baeccd6, 0x923048c4, '10533999535534820566'],
+ [0x03669d29, 0xbff3ab72, '13831587386756603177'],
+ [0x2526073e, 0x01affc81, '121593346566522686'],
+ [0xc24244e0, 0xd7f40d0e, '15561076969511732448'],
+ [0xc56a341e, 0xa68b66a7, '12000798502816461854'],
+ [0x8738d64d, 0xbfe78604, '13828168534871037517'],
+ [0x5baff03b, 0xd7572aea, '15516918227177304123'],
+ [0x4a843d8a, 0x864e132b, '9677693725920476554'],
+ [0x25b4e94d, 0x22b54dc6, '2500990681505655117'],
+ [0x6bbe664b, 0x55a5cc0e, '6171563226690381387'],
+ [0xee916c81, 0xb00aabb3, '12685140089732426881']
+ ];
+
+ for (var i = 0; i < testData.length; i++) {
+ var a = new jspb.arith.UInt64(testData[i][0], testData[i][1]);
+ var roundtrip = jspb.arith.UInt64.fromString(a.toString());
+ assertEquals(roundtrip.lo, a.lo);
+ assertEquals(roundtrip.hi, a.hi);
+ assertEquals(a.toString(), testData[i][2]);
+ }
+ });
+
+
+ /**
+ * Tests signed Int64s. These are built on UInt64s, so we only need to test
+ * the explicit overrides: .toString() and .fromString().
+ */
+ it('testSignedInt64', function() {
+ var testStrings = [
+ '-7847499644178593666',
+ '3771946501229139523',
+ '2872856549054995060',
+ '-5780049594274350904',
+ '3383785956695105201',
+ '2973055184857072610',
+ '-3879428459215627206',
+ '4589812431064156631',
+ '8484075557333689940',
+ '1075325817098092407',
+ '-4346697501012292314',
+ '2488620459718316637',
+ '6112655187423520672',
+ '-3655278273928612104',
+ '3439154019435803196',
+ '1004112478843763757',
+ '-6587790776614368413',
+ '664320065099714586',
+ '4760412909973292912',
+ '-7911903989602274672'
+ ];
+
+ for (var i = 0; i < testStrings.length; i++) {
+ var roundtrip =
+ jspb.arith.Int64.fromString(testStrings[i]).toString();
+ assertEquals(roundtrip, testStrings[i]);
+ }
+ });
+});
diff --git a/js/compatibility_tests/v3.0.0/binary/decoder_test.js b/js/compatibility_tests/v3.0.0/binary/decoder_test.js
new file mode 100644
index 00000000..fce2fe18
--- /dev/null
+++ b/js/compatibility_tests/v3.0.0/binary/decoder_test.js
@@ -0,0 +1,317 @@
+// 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.
+
+/**
+ * @fileoverview Test cases for jspb's binary protocol buffer decoder.
+ *
+ * There are two particular magic numbers that need to be pointed out -
+ * 2^64-1025 is the largest number representable as both a double and an
+ * unsigned 64-bit integer, and 2^63-513 is the largest number representable as
+ * both a double and a signed 64-bit integer.
+ *
+ * Test suite is written using Jasmine -- see http://jasmine.github.io/
+ *
+ * @author aappleby@google.com (Austin Appleby)
+ */
+
+goog.require('goog.testing.asserts');
+goog.require('jspb.BinaryConstants');
+goog.require('jspb.BinaryDecoder');
+goog.require('jspb.BinaryEncoder');
+
+
+/**
+ * Tests encoding and decoding of unsigned types.
+ * @param {Function} readValue
+ * @param {Function} writeValue
+ * @param {number} epsilon
+ * @param {number} upperLimit
+ * @param {Function} filter
+ * @suppress {missingProperties|visibility}
+ */
+function doTestUnsignedValue(readValue,
+ writeValue, epsilon, upperLimit, filter) {
+ var encoder = new jspb.BinaryEncoder();
+
+ // Encode zero and limits.
+ writeValue.call(encoder, filter(0));
+ writeValue.call(encoder, filter(epsilon));
+ writeValue.call(encoder, filter(upperLimit));
+
+ // Encode positive values.
+ for (var cursor = epsilon; cursor < upperLimit; cursor *= 1.1) {
+ writeValue.call(encoder, filter(cursor));
+ }
+
+ var decoder = jspb.BinaryDecoder.alloc(encoder.end());
+
+ // Check zero and limits.
+ assertEquals(filter(0), readValue.call(decoder));
+ assertEquals(filter(epsilon), readValue.call(decoder));
+ assertEquals(filter(upperLimit), readValue.call(decoder));
+
+ // Check positive values.
+ for (var cursor = epsilon; cursor < upperLimit; cursor *= 1.1) {
+ if (filter(cursor) != readValue.call(decoder)) throw 'fail!';
+ }
+
+ // Encoding values outside the valid range should assert.
+ assertThrows(function() {writeValue.call(encoder, -1);});
+ assertThrows(function() {writeValue.call(encoder, upperLimit * 1.1);});
+}
+
+
+/**
+ * Tests encoding and decoding of signed types.
+ * @param {Function} readValue
+ * @param {Function} writeValue
+ * @param {number} epsilon
+ * @param {number} lowerLimit
+ * @param {number} upperLimit
+ * @param {Function} filter
+ * @suppress {missingProperties}
+ */
+function doTestSignedValue(readValue,
+ writeValue, epsilon, lowerLimit, upperLimit, filter) {
+ var encoder = new jspb.BinaryEncoder();
+
+ // Encode zero and limits.
+ writeValue.call(encoder, filter(lowerLimit));
+ writeValue.call(encoder, filter(-epsilon));
+ writeValue.call(encoder, filter(0));
+ writeValue.call(encoder, filter(epsilon));
+ writeValue.call(encoder, filter(upperLimit));
+
+ var inputValues = [];
+
+ // Encode negative values.
+ for (var cursor = lowerLimit; cursor < -epsilon; cursor /= 1.1) {
+ var val = filter(cursor);
+ writeValue.call(encoder, val);
+ inputValues.push(val);
+ }
+
+ // Encode positive values.
+ for (var cursor = epsilon; cursor < upperLimit; cursor *= 1.1) {
+ var val = filter(cursor);
+ writeValue.call(encoder, val);
+ inputValues.push(val);
+ }
+
+ var decoder = jspb.BinaryDecoder.alloc(encoder.end());
+
+ // Check zero and limits.
+ assertEquals(filter(lowerLimit), readValue.call(decoder));
+ assertEquals(filter(-epsilon), readValue.call(decoder));
+ assertEquals(filter(0), readValue.call(decoder));
+ assertEquals(filter(epsilon), readValue.call(decoder));
+ assertEquals(filter(upperLimit), readValue.call(decoder));
+
+ // Verify decoded values.
+ for (var i = 0; i < inputValues.length; i++) {
+ assertEquals(inputValues[i], readValue.call(decoder));
+ }
+
+ // Encoding values outside the valid range should assert.
+ assertThrows(function() {writeValue.call(encoder, lowerLimit * 1.1);});
+ assertThrows(function() {writeValue.call(encoder, upperLimit * 1.1);});
+}
+
+describe('binaryDecoderTest', function() {
+ /**
+ * Tests the decoder instance cache.
+ */
+ it('testInstanceCache', /** @suppress {visibility} */ function() {
+ // Empty the instance caches.
+ jspb.BinaryDecoder.instanceCache_ = [];
+
+ // Allocating and then freeing a decoder should put it in the instance
+ // cache.
+ jspb.BinaryDecoder.alloc().free();
+
+ assertEquals(1, jspb.BinaryDecoder.instanceCache_.length);
+
+ // Allocating and then freeing three decoders should leave us with three in
+ // the cache.
+
+ var decoder1 = jspb.BinaryDecoder.alloc();
+ var decoder2 = jspb.BinaryDecoder.alloc();
+ var decoder3 = jspb.BinaryDecoder.alloc();
+ decoder1.free();
+ decoder2.free();
+ decoder3.free();
+
+ assertEquals(3, jspb.BinaryDecoder.instanceCache_.length);
+ });
+
+
+ /**
+ * Tests reading 64-bit integers as hash strings.
+ */
+ it('testHashStrings', function() {
+ var encoder = new jspb.BinaryEncoder();
+
+ var hashA = String.fromCharCode(0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00);
+ var hashB = String.fromCharCode(0x12, 0x34, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00);
+ var hashC = String.fromCharCode(0x12, 0x34, 0x56, 0x78,
+ 0x87, 0x65, 0x43, 0x21);
+ var hashD = String.fromCharCode(0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF);
+
+ encoder.writeVarintHash64(hashA);
+ encoder.writeVarintHash64(hashB);
+ encoder.writeVarintHash64(hashC);
+ encoder.writeVarintHash64(hashD);
+
+ encoder.writeFixedHash64(hashA);
+ encoder.writeFixedHash64(hashB);
+ encoder.writeFixedHash64(hashC);
+ encoder.writeFixedHash64(hashD);
+
+ var decoder = jspb.BinaryDecoder.alloc(encoder.end());
+
+ assertEquals(hashA, decoder.readVarintHash64());
+ assertEquals(hashB, decoder.readVarintHash64());
+ assertEquals(hashC, decoder.readVarintHash64());
+ assertEquals(hashD, decoder.readVarintHash64());
+
+ assertEquals(hashA, decoder.readFixedHash64());
+ assertEquals(hashB, decoder.readFixedHash64());
+ assertEquals(hashC, decoder.readFixedHash64());
+ assertEquals(hashD, decoder.readFixedHash64());
+ });
+
+
+ /**
+ * Verifies that misuse of the decoder class triggers assertions.
+ * @suppress {checkTypes|visibility}
+ */
+ it('testDecodeErrors', function() {
+ // Reading a value past the end of the stream should trigger an assertion.
+ var decoder = jspb.BinaryDecoder.alloc([0, 1, 2]);
+ assertThrows(function() {decoder.readUint64()});
+
+ // Overlong varints should trigger assertions.
+ decoder.setBlock([255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 0]);
+ assertThrows(function() {decoder.readUnsignedVarint64()});
+ decoder.reset();
+ assertThrows(function() {decoder.readSignedVarint64()});
+ decoder.reset();
+ assertThrows(function() {decoder.readZigzagVarint64()});
+ decoder.reset();
+ assertThrows(function() {decoder.readUnsignedVarint32()});
+ });
+
+
+ /**
+ * Tests encoding and decoding of unsigned integers.
+ */
+ it('testUnsignedIntegers', function() {
+ doTestUnsignedValue(
+ jspb.BinaryDecoder.prototype.readUint8,
+ jspb.BinaryEncoder.prototype.writeUint8,
+ 1, 0xFF, Math.round);
+
+ doTestUnsignedValue(
+ jspb.BinaryDecoder.prototype.readUint16,
+ jspb.BinaryEncoder.prototype.writeUint16,
+ 1, 0xFFFF, Math.round);
+
+ doTestUnsignedValue(
+ jspb.BinaryDecoder.prototype.readUint32,
+ jspb.BinaryEncoder.prototype.writeUint32,
+ 1, 0xFFFFFFFF, Math.round);
+
+ doTestUnsignedValue(
+ jspb.BinaryDecoder.prototype.readUint64,
+ jspb.BinaryEncoder.prototype.writeUint64,
+ 1, Math.pow(2, 64) - 1025, Math.round);
+ });
+
+
+ /**
+ * Tests encoding and decoding of signed integers.
+ */
+ it('testSignedIntegers', function() {
+ doTestSignedValue(
+ jspb.BinaryDecoder.prototype.readInt8,
+ jspb.BinaryEncoder.prototype.writeInt8,
+ 1, -0x80, 0x7F, Math.round);
+
+ doTestSignedValue(
+ jspb.BinaryDecoder.prototype.readInt16,
+ jspb.BinaryEncoder.prototype.writeInt16,
+ 1, -0x8000, 0x7FFF, Math.round);
+
+ doTestSignedValue(
+ jspb.BinaryDecoder.prototype.readInt32,
+ jspb.BinaryEncoder.prototype.writeInt32,
+ 1, -0x80000000, 0x7FFFFFFF, Math.round);
+
+ doTestSignedValue(
+ jspb.BinaryDecoder.prototype.readInt64,
+ jspb.BinaryEncoder.prototype.writeInt64,
+ 1, -Math.pow(2, 63), Math.pow(2, 63) - 513, Math.round);
+ });
+
+
+ /**
+ * Tests encoding and decoding of floats.
+ */
+ it('testFloats', function() {
+ /**
+ * @param {number} x
+ * @return {number}
+ */
+ function truncate(x) {
+ var temp = new Float32Array(1);
+ temp[0] = x;
+ return temp[0];
+ }
+ doTestSignedValue(
+ jspb.BinaryDecoder.prototype.readFloat,
+ jspb.BinaryEncoder.prototype.writeFloat,
+ jspb.BinaryConstants.FLOAT32_EPS,
+ -jspb.BinaryConstants.FLOAT32_MAX,
+ jspb.BinaryConstants.FLOAT32_MAX,
+ truncate);
+
+ doTestSignedValue(
+ jspb.BinaryDecoder.prototype.readDouble,
+ jspb.BinaryEncoder.prototype.writeDouble,
+ jspb.BinaryConstants.FLOAT64_EPS * 10,
+ -jspb.BinaryConstants.FLOAT64_MAX,
+ jspb.BinaryConstants.FLOAT64_MAX,
+ function(x) { return x; });
+ });
+});
diff --git a/js/compatibility_tests/v3.0.0/binary/proto_test.js b/js/compatibility_tests/v3.0.0/binary/proto_test.js
new file mode 100644
index 00000000..14d0f42e
--- /dev/null
+++ b/js/compatibility_tests/v3.0.0/binary/proto_test.js
@@ -0,0 +1,628 @@
+// 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.
+
+// Test suite is written using Jasmine -- see http://jasmine.github.io/
+
+goog.require('goog.crypt.base64');
+goog.require('goog.testing.asserts');
+goog.require('jspb.Message');
+
+// CommonJS-LoadFromFile: ../testbinary_pb proto.jspb.test
+goog.require('proto.jspb.test.ExtendsWithMessage');
+goog.require('proto.jspb.test.ForeignEnum');
+goog.require('proto.jspb.test.ForeignMessage');
+goog.require('proto.jspb.test.TestAllTypes');
+goog.require('proto.jspb.test.TestExtendable');
+goog.require('proto.jspb.test.extendOptionalBool');
+goog.require('proto.jspb.test.extendOptionalBytes');
+goog.require('proto.jspb.test.extendOptionalDouble');
+goog.require('proto.jspb.test.extendOptionalFixed32');
+goog.require('proto.jspb.test.extendOptionalFixed64');
+goog.require('proto.jspb.test.extendOptionalFloat');
+goog.require('proto.jspb.test.extendOptionalForeignEnum');
+goog.require('proto.jspb.test.extendOptionalInt32');
+goog.require('proto.jspb.test.extendOptionalInt64');
+goog.require('proto.jspb.test.extendOptionalSfixed32');
+goog.require('proto.jspb.test.extendOptionalSfixed64');
+goog.require('proto.jspb.test.extendOptionalSint32');
+goog.require('proto.jspb.test.extendOptionalSint64');
+goog.require('proto.jspb.test.extendOptionalString');
+goog.require('proto.jspb.test.extendOptionalUint32');
+goog.require('proto.jspb.test.extendOptionalUint64');
+goog.require('proto.jspb.test.extendPackedRepeatedBoolList');
+goog.require('proto.jspb.test.extendPackedRepeatedDoubleList');
+goog.require('proto.jspb.test.extendPackedRepeatedFixed32List');
+goog.require('proto.jspb.test.extendPackedRepeatedFixed64List');
+goog.require('proto.jspb.test.extendPackedRepeatedFloatList');
+goog.require('proto.jspb.test.extendPackedRepeatedForeignEnumList');
+goog.require('proto.jspb.test.extendPackedRepeatedInt32List');
+goog.require('proto.jspb.test.extendPackedRepeatedInt64List');
+goog.require('proto.jspb.test.extendPackedRepeatedSfixed32List');
+goog.require('proto.jspb.test.extendPackedRepeatedSfixed64List');
+goog.require('proto.jspb.test.extendPackedRepeatedSint32List');
+goog.require('proto.jspb.test.extendPackedRepeatedSint64List');
+goog.require('proto.jspb.test.extendPackedRepeatedUint32List');
+goog.require('proto.jspb.test.extendPackedRepeatedUint64List');
+goog.require('proto.jspb.test.extendRepeatedBoolList');
+goog.require('proto.jspb.test.extendRepeatedBytesList');
+goog.require('proto.jspb.test.extendRepeatedDoubleList');
+goog.require('proto.jspb.test.extendRepeatedFixed32List');
+goog.require('proto.jspb.test.extendRepeatedFixed64List');
+goog.require('proto.jspb.test.extendRepeatedFloatList');
+goog.require('proto.jspb.test.extendRepeatedForeignEnumList');
+goog.require('proto.jspb.test.extendRepeatedInt32List');
+goog.require('proto.jspb.test.extendRepeatedInt64List');
+goog.require('proto.jspb.test.extendRepeatedSfixed32List');
+goog.require('proto.jspb.test.extendRepeatedSfixed64List');
+goog.require('proto.jspb.test.extendRepeatedSint32List');
+goog.require('proto.jspb.test.extendRepeatedSint64List');
+goog.require('proto.jspb.test.extendRepeatedStringList');
+goog.require('proto.jspb.test.extendRepeatedUint32List');
+goog.require('proto.jspb.test.extendRepeatedUint64List');
+
+
+var suite = {};
+
+var BYTES = new Uint8Array([1, 2, 8, 9]);
+
+var BYTES_B64 = goog.crypt.base64.encodeByteArray(BYTES);
+
+
+/**
+ * Helper: fill all fields on a TestAllTypes message.
+ * @param {proto.jspb.test.TestAllTypes} msg
+ */
+function fillAllFields(msg) {
+ msg.setOptionalInt32(-42);
+ // can be exactly represented by JS number (64-bit double, i.e., 52-bit
+ // mantissa).
+ msg.setOptionalInt64(-0x7fffffff00000000);
+ msg.setOptionalUint32(0x80000000);
+ msg.setOptionalUint64(0xf000000000000000);
+ msg.setOptionalSint32(-100);
+ msg.setOptionalSint64(-0x8000000000000000);
+ msg.setOptionalFixed32(1234);
+ msg.setOptionalFixed64(0x1234567800000000);
+ msg.setOptionalSfixed32(-1234);
+ msg.setOptionalSfixed64(-0x1234567800000000);
+ msg.setOptionalFloat(1.5);
+ msg.setOptionalDouble(-1.5);
+ msg.setOptionalBool(true);
+ msg.setOptionalString('hello world');
+ msg.setOptionalBytes(BYTES);
+ msg.setOptionalGroup(new proto.jspb.test.TestAllTypes.OptionalGroup());
+ msg.getOptionalGroup().setA(100);
+ var submsg = new proto.jspb.test.ForeignMessage();
+ submsg.setC(16);
+ msg.setOptionalForeignMessage(submsg);
+ msg.setOptionalForeignEnum(proto.jspb.test.ForeignEnum.FOREIGN_FOO);
+ msg.setOneofString('oneof');
+
+
+ msg.setRepeatedInt32List([-42]);
+ msg.setRepeatedInt64List([-0x7fffffff00000000]);
+ msg.setRepeatedUint32List([0x80000000]);
+ msg.setRepeatedUint64List([0xf000000000000000]);
+ msg.setRepeatedSint32List([-100]);
+ msg.setRepeatedSint64List([-0x8000000000000000]);
+ msg.setRepeatedFixed32List([1234]);
+ msg.setRepeatedFixed64List([0x1234567800000000]);
+ msg.setRepeatedSfixed32List([-1234]);
+ msg.setRepeatedSfixed64List([-0x1234567800000000]);
+ msg.setRepeatedFloatList([1.5]);
+ msg.setRepeatedDoubleList([-1.5]);
+ msg.setRepeatedBoolList([true]);
+ msg.setRepeatedStringList(['hello world']);
+ msg.setRepeatedBytesList([BYTES, BYTES]);
+ msg.setRepeatedGroupList([new proto.jspb.test.TestAllTypes.RepeatedGroup()]);
+ msg.getRepeatedGroupList()[0].setA(100);
+ submsg = new proto.jspb.test.ForeignMessage();
+ submsg.setC(1000);
+ msg.setRepeatedForeignMessageList([submsg]);
+ msg.setRepeatedForeignEnumList([proto.jspb.test.ForeignEnum.FOREIGN_FOO]);
+
+ msg.setPackedRepeatedInt32List([-42]);
+ msg.setPackedRepeatedInt64List([-0x7fffffff00000000]);
+ msg.setPackedRepeatedUint32List([0x80000000]);
+ msg.setPackedRepeatedUint64List([0xf000000000000000]);
+ msg.setPackedRepeatedSint32List([-100]);
+ msg.setPackedRepeatedSint64List([-0x8000000000000000]);
+ msg.setPackedRepeatedFixed32List([1234]);
+ msg.setPackedRepeatedFixed64List([0x1234567800000000]);
+ msg.setPackedRepeatedSfixed32List([-1234]);
+ msg.setPackedRepeatedSfixed64List([-0x1234567800000000]);
+ msg.setPackedRepeatedFloatList([1.5]);
+ msg.setPackedRepeatedDoubleList([-1.5]);
+ msg.setPackedRepeatedBoolList([true]);
+
+}
+
+
+/**
+ * Helper: compare a bytes field to an expected value
+ * @param {Uint8Array|string} arr
+ * @param {Uint8Array} expected
+ * @return {boolean}
+ */
+function bytesCompare(arr, expected) {
+ if (goog.isString(arr)) {
+ arr = goog.crypt.base64.decodeStringToUint8Array(arr);
+ }
+ if (arr.length != expected.length) {
+ return false;
+ }
+ for (var i = 0; i < arr.length; i++) {
+ if (arr[i] != expected[i]) {
+ return false;
+ }
+ }
+ return true;
+}
+
+
+/**
+ * Helper: verify contents of given TestAllTypes message as set by
+ * fillAllFields().
+ * @param {proto.jspb.test.TestAllTypes} original
+ * @param {proto.jspb.test.TestAllTypes} copy
+ */
+function checkAllFields(original, copy) {
+ assertTrue(jspb.Message.equals(original, copy));
+
+ assertEquals(copy.getOptionalInt32(), -42);
+ assertEquals(copy.getOptionalInt64(), -0x7fffffff00000000);
+ assertEquals(copy.getOptionalUint32(), 0x80000000);
+ assertEquals(copy.getOptionalUint64(), 0xf000000000000000);
+ assertEquals(copy.getOptionalSint32(), -100);
+ assertEquals(copy.getOptionalSint64(), -0x8000000000000000);
+ assertEquals(copy.getOptionalFixed32(), 1234);
+ assertEquals(copy.getOptionalFixed64(), 0x1234567800000000);
+ assertEquals(copy.getOptionalSfixed32(), -1234);
+ assertEquals(copy.getOptionalSfixed64(), -0x1234567800000000);
+ assertEquals(copy.getOptionalFloat(), 1.5);
+ assertEquals(copy.getOptionalDouble(), -1.5);
+ assertEquals(copy.getOptionalBool(), true);
+ assertEquals(copy.getOptionalString(), 'hello world');
+ assertEquals(true, bytesCompare(copy.getOptionalBytes(), BYTES));
+ assertEquals(true, bytesCompare(copy.getOptionalBytes_asU8(), BYTES));
+ assertEquals(
+ copy.getOptionalBytes_asB64(), goog.crypt.base64.encodeByteArray(BYTES));
+
+ assertEquals(copy.getOptionalGroup().getA(), 100);
+ assertEquals(copy.getOptionalForeignMessage().getC(), 16);
+ assertEquals(copy.getOptionalForeignEnum(),
+ proto.jspb.test.ForeignEnum.FOREIGN_FOO);
+
+
+ assertEquals(copy.getOneofString(), 'oneof');
+ assertEquals(copy.getOneofFieldCase(),
+ proto.jspb.test.TestAllTypes.OneofFieldCase.ONEOF_STRING);
+
+ assertElementsEquals(copy.getRepeatedInt32List(), [-42]);
+ assertElementsEquals(copy.getRepeatedInt64List(), [-0x7fffffff00000000]);
+ assertElementsEquals(copy.getRepeatedUint32List(), [0x80000000]);
+ assertElementsEquals(copy.getRepeatedUint64List(), [0xf000000000000000]);
+ assertElementsEquals(copy.getRepeatedSint32List(), [-100]);
+ assertElementsEquals(copy.getRepeatedSint64List(), [-0x8000000000000000]);
+ assertElementsEquals(copy.getRepeatedFixed32List(), [1234]);
+ assertElementsEquals(copy.getRepeatedFixed64List(), [0x1234567800000000]);
+ assertElementsEquals(copy.getRepeatedSfixed32List(), [-1234]);
+ assertElementsEquals(copy.getRepeatedSfixed64List(), [-0x1234567800000000]);
+ assertElementsEquals(copy.getRepeatedFloatList(), [1.5]);
+ assertElementsEquals(copy.getRepeatedDoubleList(), [-1.5]);
+ assertElementsEquals(copy.getRepeatedBoolList(), [true]);
+ assertElementsEquals(copy.getRepeatedStringList(), ['hello world']);
+ assertEquals(copy.getRepeatedBytesList().length, 2);
+ assertEquals(true, bytesCompare(copy.getRepeatedBytesList_asU8()[0], BYTES));
+ assertEquals(true, bytesCompare(copy.getRepeatedBytesList()[0], BYTES));
+ assertEquals(true, bytesCompare(copy.getRepeatedBytesList_asU8()[1], BYTES));
+ assertEquals(copy.getRepeatedBytesList_asB64()[0], BYTES_B64);
+ assertEquals(copy.getRepeatedBytesList_asB64()[1], BYTES_B64);
+ assertEquals(copy.getRepeatedGroupList().length, 1);
+ assertEquals(copy.getRepeatedGroupList()[0].getA(), 100);
+ assertEquals(copy.getRepeatedForeignMessageList().length, 1);
+ assertEquals(copy.getRepeatedForeignMessageList()[0].getC(), 1000);
+ assertElementsEquals(copy.getRepeatedForeignEnumList(),
+ [proto.jspb.test.ForeignEnum.FOREIGN_FOO]);
+
+ assertElementsEquals(copy.getPackedRepeatedInt32List(), [-42]);
+ assertElementsEquals(copy.getPackedRepeatedInt64List(),
+ [-0x7fffffff00000000]);
+ assertElementsEquals(copy.getPackedRepeatedUint32List(), [0x80000000]);
+ assertElementsEquals(copy.getPackedRepeatedUint64List(),
+ [0xf000000000000000]);
+ assertElementsEquals(copy.getPackedRepeatedSint32List(), [-100]);
+ assertElementsEquals(copy.getPackedRepeatedSint64List(),
+ [-0x8000000000000000]);
+ assertElementsEquals(copy.getPackedRepeatedFixed32List(), [1234]);
+ assertElementsEquals(copy.getPackedRepeatedFixed64List(),
+ [0x1234567800000000]);
+ assertElementsEquals(copy.getPackedRepeatedSfixed32List(), [-1234]);
+ assertElementsEquals(copy.getPackedRepeatedSfixed64List(),
+ [-0x1234567800000000]);
+ assertElementsEquals(copy.getPackedRepeatedFloatList(), [1.5]);
+ assertElementsEquals(copy.getPackedRepeatedDoubleList(), [-1.5]);
+
+}
+
+
+/**
+ * Helper: verify that all expected extensions are present.
+ * @param {!proto.jspb.test.TestExtendable} msg
+ */
+function checkExtensions(msg) {
+ assertEquals(-42,
+ msg.getExtension(proto.jspb.test.extendOptionalInt32));
+ assertEquals(-0x7fffffff00000000,
+ msg.getExtension(proto.jspb.test.extendOptionalInt64));
+ assertEquals(0x80000000,
+ msg.getExtension(proto.jspb.test.extendOptionalUint32));
+ assertEquals(0xf000000000000000,
+ msg.getExtension(proto.jspb.test.extendOptionalUint64));
+ assertEquals(-100,
+ msg.getExtension(proto.jspb.test.extendOptionalSint32));
+ assertEquals(-0x8000000000000000,
+ msg.getExtension(proto.jspb.test.extendOptionalSint64));
+ assertEquals(1234,
+ msg.getExtension(proto.jspb.test.extendOptionalFixed32));
+ assertEquals(0x1234567800000000,
+ msg.getExtension(proto.jspb.test.extendOptionalFixed64));
+ assertEquals(-1234,
+ msg.getExtension(proto.jspb.test.extendOptionalSfixed32));
+ assertEquals(-0x1234567800000000,
+ msg.getExtension(proto.jspb.test.extendOptionalSfixed64));
+ assertEquals(1.5,
+ msg.getExtension(proto.jspb.test.extendOptionalFloat));
+ assertEquals(-1.5,
+ msg.getExtension(proto.jspb.test.extendOptionalDouble));
+ assertEquals(true,
+ msg.getExtension(proto.jspb.test.extendOptionalBool));
+ assertEquals('hello world',
+ msg.getExtension(proto.jspb.test.extendOptionalString));
+ assertEquals(
+ true, bytesCompare(
+ msg.getExtension(proto.jspb.test.extendOptionalBytes), BYTES));
+ assertEquals(16,
+ msg.getExtension(
+ proto.jspb.test.ExtendsWithMessage.optionalExtension).getFoo());
+
+
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendRepeatedInt32List),
+ [-42]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendRepeatedInt64List),
+ [-0x7fffffff00000000]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendRepeatedUint32List),
+ [0x80000000]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendRepeatedUint64List),
+ [0xf000000000000000]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendRepeatedSint32List),
+ [-100]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendRepeatedSint64List),
+ [-0x8000000000000000]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendRepeatedFixed32List),
+ [1234]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendRepeatedFixed64List),
+ [0x1234567800000000]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendRepeatedSfixed32List),
+ [-1234]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendRepeatedSfixed64List),
+ [-0x1234567800000000]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendRepeatedFloatList),
+ [1.5]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendRepeatedDoubleList),
+ [-1.5]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendRepeatedBoolList),
+ [true]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendRepeatedStringList),
+ ['hello world']);
+ assertEquals(
+ true,
+ bytesCompare(
+ msg.getExtension(proto.jspb.test.extendRepeatedBytesList)[0], BYTES));
+ assertEquals(1000,
+ msg.getExtension(
+ proto.jspb.test.ExtendsWithMessage.repeatedExtensionList)[0]
+ .getFoo());
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendRepeatedForeignEnumList),
+ [proto.jspb.test.ForeignEnum.FOREIGN_FOO]);
+
+
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendPackedRepeatedInt32List),
+ [-42]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendPackedRepeatedInt64List),
+ [-0x7fffffff00000000]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendPackedRepeatedUint32List),
+ [0x80000000]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendPackedRepeatedUint64List),
+ [0xf000000000000000]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendPackedRepeatedSint32List),
+ [-100]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendPackedRepeatedSint64List),
+ [-0x8000000000000000]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendPackedRepeatedFixed32List),
+ [1234]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendPackedRepeatedFixed64List),
+ [0x1234567800000000]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendPackedRepeatedSfixed32List),
+ [-1234]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendPackedRepeatedSfixed64List),
+ [-0x1234567800000000]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendPackedRepeatedFloatList),
+ [1.5]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendPackedRepeatedDoubleList),
+ [-1.5]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendPackedRepeatedBoolList),
+ [true]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendPackedRepeatedForeignEnumList),
+ [proto.jspb.test.ForeignEnum.FOREIGN_FOO]);
+
+}
+
+
+describe('protoBinaryTest', function() {
+ /**
+ * Tests a basic serialization-deserializaton round-trip with all supported
+ * field types (on the TestAllTypes message type).
+ */
+ it('testRoundTrip', function() {
+ var msg = new proto.jspb.test.TestAllTypes();
+ fillAllFields(msg);
+ var encoded = msg.serializeBinary();
+ var decoded = proto.jspb.test.TestAllTypes.deserializeBinary(encoded);
+ checkAllFields(msg, decoded);
+ });
+
+ /**
+ * Test that base64 string and Uint8Array are interchangeable in bytes fields.
+ */
+ it('testBytesFieldsGettersInterop', function() {
+ var msg = new proto.jspb.test.TestAllTypes();
+ // Set from a base64 string and check all the getters work.
+ msg.setOptionalBytes(BYTES_B64);
+ assertTrue(bytesCompare(msg.getOptionalBytes_asU8(), BYTES));
+ assertTrue(bytesCompare(msg.getOptionalBytes_asB64(), BYTES));
+ assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
+
+ // Test binary serialize round trip doesn't break it.
+ msg = proto.jspb.test.TestAllTypes.deserializeBinary(msg.serializeBinary());
+ assertTrue(bytesCompare(msg.getOptionalBytes_asU8(), BYTES));
+ assertTrue(bytesCompare(msg.getOptionalBytes_asB64(), BYTES));
+ assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
+
+ msg = new proto.jspb.test.TestAllTypes();
+ // Set from a Uint8Array and check all the getters work.
+ msg.setOptionalBytes(BYTES);
+ assertTrue(bytesCompare(msg.getOptionalBytes_asU8(), BYTES));
+ assertTrue(bytesCompare(msg.getOptionalBytes_asB64(), BYTES));
+ assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
+
+ });
+
+ /**
+ * Test that bytes setters will receive result of any of the getters.
+ */
+ it('testBytesFieldsSettersInterop', function() {
+ var msg = new proto.jspb.test.TestAllTypes();
+ msg.setOptionalBytes(BYTES);
+ assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
+
+ msg.setOptionalBytes(msg.getOptionalBytes());
+ assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
+ msg.setOptionalBytes(msg.getOptionalBytes_asB64());
+ assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
+ msg.setOptionalBytes(msg.getOptionalBytes_asU8());
+ assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
+ });
+
+ /**
+ * Test that bytes setters will receive result of any of the getters.
+ */
+ it('testRepeatedBytesGetters', function() {
+ var msg = new proto.jspb.test.TestAllTypes();
+
+ function assertGetters() {
+ assertTrue(goog.isString(msg.getRepeatedBytesList_asB64()[0]));
+ assertTrue(goog.isString(msg.getRepeatedBytesList_asB64()[1]));
+ assertTrue(msg.getRepeatedBytesList_asU8()[0] instanceof Uint8Array);
+ assertTrue(msg.getRepeatedBytesList_asU8()[1] instanceof Uint8Array);
+
+ assertTrue(bytesCompare(msg.getRepeatedBytesList()[0], BYTES));
+ assertTrue(bytesCompare(msg.getRepeatedBytesList()[1], BYTES));
+ assertTrue(bytesCompare(msg.getRepeatedBytesList_asB64()[0], BYTES));
+ assertTrue(bytesCompare(msg.getRepeatedBytesList_asB64()[1], BYTES));
+ assertTrue(bytesCompare(msg.getRepeatedBytesList_asU8()[0], BYTES));
+ assertTrue(bytesCompare(msg.getRepeatedBytesList_asU8()[1], BYTES));
+ }
+
+ msg.setRepeatedBytesList([BYTES, BYTES]);
+ assertGetters();
+
+ msg.setRepeatedBytesList([BYTES_B64, BYTES_B64]);
+ assertGetters();
+
+ msg.setRepeatedBytesList(null);
+ assertEquals(0, msg.getRepeatedBytesList().length);
+ assertEquals(0, msg.getRepeatedBytesList_asB64().length);
+ assertEquals(0, msg.getRepeatedBytesList_asU8().length);
+ });
+
+ /**
+ * Helper: fill all extension values.
+ * @param {proto.jspb.test.TestExtendable} msg
+ */
+ function fillExtensions(msg) {
+ msg.setExtension(
+ proto.jspb.test.extendOptionalInt32, -42);
+ msg.setExtension(
+ proto.jspb.test.extendOptionalInt64, -0x7fffffff00000000);
+ msg.setExtension(
+ proto.jspb.test.extendOptionalUint32, 0x80000000);
+ msg.setExtension(
+ proto.jspb.test.extendOptionalUint64, 0xf000000000000000);
+ msg.setExtension(
+ proto.jspb.test.extendOptionalSint32, -100);
+ msg.setExtension(
+ proto.jspb.test.extendOptionalSint64, -0x8000000000000000);
+ msg.setExtension(
+ proto.jspb.test.extendOptionalFixed32, 1234);
+ msg.setExtension(
+ proto.jspb.test.extendOptionalFixed64, 0x1234567800000000);
+ msg.setExtension(
+ proto.jspb.test.extendOptionalSfixed32, -1234);
+ msg.setExtension(
+ proto.jspb.test.extendOptionalSfixed64, -0x1234567800000000);
+ msg.setExtension(
+ proto.jspb.test.extendOptionalFloat, 1.5);
+ msg.setExtension(
+ proto.jspb.test.extendOptionalDouble, -1.5);
+ msg.setExtension(
+ proto.jspb.test.extendOptionalBool, true);
+ msg.setExtension(
+ proto.jspb.test.extendOptionalString, 'hello world');
+ msg.setExtension(proto.jspb.test.extendOptionalBytes, BYTES);
+ var submsg = new proto.jspb.test.ExtendsWithMessage();
+ submsg.setFoo(16);
+ msg.setExtension(
+ proto.jspb.test.ExtendsWithMessage.optionalExtension, submsg);
+ msg.setExtension(
+ proto.jspb.test.extendOptionalForeignEnum,
+ proto.jspb.test.ForeignEnum.FOREIGN_FOO);
+
+
+ msg.setExtension(
+ proto.jspb.test.extendRepeatedInt32List, [-42]);
+ msg.setExtension(
+ proto.jspb.test.extendRepeatedInt64List, [-0x7fffffff00000000]);
+ msg.setExtension(
+ proto.jspb.test.extendRepeatedUint32List, [0x80000000]);
+ msg.setExtension(
+ proto.jspb.test.extendRepeatedUint64List, [0xf000000000000000]);
+ msg.setExtension(
+ proto.jspb.test.extendRepeatedSint32List, [-100]);
+ msg.setExtension(
+ proto.jspb.test.extendRepeatedSint64List, [-0x8000000000000000]);
+ msg.setExtension(
+ proto.jspb.test.extendRepeatedFixed32List, [1234]);
+ msg.setExtension(
+ proto.jspb.test.extendRepeatedFixed64List, [0x1234567800000000]);
+ msg.setExtension(
+ proto.jspb.test.extendRepeatedSfixed32List, [-1234]);
+ msg.setExtension(
+ proto.jspb.test.extendRepeatedSfixed64List, [-0x1234567800000000]);
+ msg.setExtension(
+ proto.jspb.test.extendRepeatedFloatList, [1.5]);
+ msg.setExtension(
+ proto.jspb.test.extendRepeatedDoubleList, [-1.5]);
+ msg.setExtension(
+ proto.jspb.test.extendRepeatedBoolList, [true]);
+ msg.setExtension(
+ proto.jspb.test.extendRepeatedStringList, ['hello world']);
+ msg.setExtension(proto.jspb.test.extendRepeatedBytesList, [BYTES]);
+ submsg = new proto.jspb.test.ExtendsWithMessage();
+ submsg.setFoo(1000);
+ msg.setExtension(
+ proto.jspb.test.ExtendsWithMessage.repeatedExtensionList, [submsg]);
+ msg.setExtension(proto.jspb.test.extendRepeatedForeignEnumList,
+ [proto.jspb.test.ForeignEnum.FOREIGN_FOO]);
+
+
+ msg.setExtension(
+ proto.jspb.test.extendPackedRepeatedInt32List, [-42]);
+ msg.setExtension(
+ proto.jspb.test.extendPackedRepeatedInt64List, [-0x7fffffff00000000]);
+ msg.setExtension(
+ proto.jspb.test.extendPackedRepeatedUint32List, [0x80000000]);
+ msg.setExtension(
+ proto.jspb.test.extendPackedRepeatedUint64List, [0xf000000000000000]);
+ msg.setExtension(
+ proto.jspb.test.extendPackedRepeatedSint32List, [-100]);
+ msg.setExtension(
+ proto.jspb.test.extendPackedRepeatedSint64List, [-0x8000000000000000]);
+ msg.setExtension(
+ proto.jspb.test.extendPackedRepeatedFixed32List, [1234]);
+ msg.setExtension(
+ proto.jspb.test.extendPackedRepeatedFixed64List, [0x1234567800000000]);
+ msg.setExtension(
+ proto.jspb.test.extendPackedRepeatedSfixed32List, [-1234]);
+ msg.setExtension(
+ proto.jspb.test.extendPackedRepeatedSfixed64List,
+ [-0x1234567800000000]);
+ msg.setExtension(
+ proto.jspb.test.extendPackedRepeatedFloatList, [1.5]);
+ msg.setExtension(
+ proto.jspb.test.extendPackedRepeatedDoubleList, [-1.5]);
+ msg.setExtension(
+ proto.jspb.test.extendPackedRepeatedBoolList, [true]);
+ msg.setExtension(proto.jspb.test.extendPackedRepeatedForeignEnumList,
+ [proto.jspb.test.ForeignEnum.FOREIGN_FOO]);
+
+ }
+
+
+ /**
+ * Tests extension serialization and deserialization.
+ */
+ it('testExtensions', function() {
+ var msg = new proto.jspb.test.TestExtendable();
+ fillExtensions(msg);
+ var encoded = msg.serializeBinary();
+ var decoded = proto.jspb.test.TestExtendable.deserializeBinary(encoded);
+ checkExtensions(decoded);
+ });
+});
diff --git a/js/compatibility_tests/v3.0.0/binary/reader_test.js b/js/compatibility_tests/v3.0.0/binary/reader_test.js
new file mode 100644
index 00000000..95711385
--- /dev/null
+++ b/js/compatibility_tests/v3.0.0/binary/reader_test.js
@@ -0,0 +1,922 @@
+// 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.
+
+/**
+ * @fileoverview Test cases for jspb's binary protocol buffer reader.
+ *
+ * There are two particular magic numbers that need to be pointed out -
+ * 2^64-1025 is the largest number representable as both a double and an
+ * unsigned 64-bit integer, and 2^63-513 is the largest number representable as
+ * both a double and a signed 64-bit integer.
+ *
+ * Test suite is written using Jasmine -- see http://jasmine.github.io/
+ *
+ * @author aappleby@google.com (Austin Appleby)
+ */
+
+goog.require('goog.testing.asserts');
+goog.require('jspb.BinaryConstants');
+goog.require('jspb.BinaryDecoder');
+goog.require('jspb.BinaryReader');
+goog.require('jspb.BinaryWriter');
+
+
+
+describe('binaryReaderTest', function() {
+ /**
+ * Tests the reader instance cache.
+ */
+ it('testInstanceCaches', /** @suppress {visibility} */ function() {
+ var writer = new jspb.BinaryWriter();
+ var dummyMessage = /** @type {!jspb.BinaryMessage} */({});
+ writer.writeMessage(1, dummyMessage, goog.nullFunction);
+ writer.writeMessage(2, dummyMessage, goog.nullFunction);
+
+ var buffer = writer.getResultBuffer();
+
+ // Empty the instance caches.
+ jspb.BinaryReader.instanceCache_ = [];
+
+ // Allocating and then freeing three decoders should leave us with three in
+ // the cache.
+
+ var decoder1 = jspb.BinaryDecoder.alloc();
+ var decoder2 = jspb.BinaryDecoder.alloc();
+ var decoder3 = jspb.BinaryDecoder.alloc();
+ decoder1.free();
+ decoder2.free();
+ decoder3.free();
+
+ assertEquals(3, jspb.BinaryDecoder.instanceCache_.length);
+ assertEquals(0, jspb.BinaryReader.instanceCache_.length);
+
+ // Allocating and then freeing a reader should remove one decoder from its
+ // cache, but it should stay stuck to the reader afterwards since we can't
+ // have a reader without a decoder.
+ jspb.BinaryReader.alloc().free();
+
+ assertEquals(2, jspb.BinaryDecoder.instanceCache_.length);
+ assertEquals(1, jspb.BinaryReader.instanceCache_.length);
+
+ // Allocating a reader should remove a reader from the cache.
+ var reader = jspb.BinaryReader.alloc(buffer);
+
+ assertEquals(2, jspb.BinaryDecoder.instanceCache_.length);
+ assertEquals(0, jspb.BinaryReader.instanceCache_.length);
+
+ // Processing the message reuses the current reader.
+ reader.nextField();
+ assertEquals(1, reader.getFieldNumber());
+ reader.readMessage(dummyMessage, function() {
+ assertEquals(0, jspb.BinaryReader.instanceCache_.length);
+ });
+
+ reader.nextField();
+ assertEquals(2, reader.getFieldNumber());
+ reader.readMessage(dummyMessage, function() {
+ assertEquals(0, jspb.BinaryReader.instanceCache_.length);
+ });
+
+ assertEquals(false, reader.nextField());
+
+ assertEquals(2, jspb.BinaryDecoder.instanceCache_.length);
+ assertEquals(0, jspb.BinaryReader.instanceCache_.length);
+
+ // Freeing the reader should put it back into the cache.
+ reader.free();
+
+ assertEquals(2, jspb.BinaryDecoder.instanceCache_.length);
+ assertEquals(1, jspb.BinaryReader.instanceCache_.length);
+ });
+
+
+ /**
+ * @param {number} x
+ * @return {number}
+ */
+ function truncate(x) {
+ var temp = new Float32Array(1);
+ temp[0] = x;
+ return temp[0];
+ }
+
+
+ /**
+ * Verifies that misuse of the reader class triggers assertions.
+ */
+ it('testReadErrors', /** @suppress {checkTypes|visibility} */ function() {
+ // Calling readMessage on a non-delimited field should trigger an
+ // assertion.
+ var reader = jspb.BinaryReader.alloc([8, 1]);
+ var dummyMessage = /** @type {!jspb.BinaryMessage} */({});
+ reader.nextField();
+ assertThrows(function() {
+ reader.readMessage(dummyMessage, goog.nullFunction);
+ });
+
+ // Reading past the end of the stream should trigger an assertion.
+ reader = jspb.BinaryReader.alloc([9, 1]);
+ reader.nextField();
+ assertThrows(function() {reader.readFixed64()});
+
+ // Reading past the end of a submessage should trigger an assertion.
+ reader = jspb.BinaryReader.alloc([10, 4, 13, 1, 1, 1]);
+ reader.nextField();
+ reader.readMessage(dummyMessage, function() {
+ reader.nextField();
+ assertThrows(function() {reader.readFixed32()});
+ });
+
+ // Skipping an invalid field should trigger an assertion.
+ reader = jspb.BinaryReader.alloc([12, 1]);
+ reader.nextWireType_ = 1000;
+ assertThrows(function() {reader.skipField()});
+
+ // Reading fields with the wrong wire type should assert.
+ reader = jspb.BinaryReader.alloc([9, 0, 0, 0, 0, 0, 0, 0, 0]);
+ reader.nextField();
+ assertThrows(function() {reader.readInt32()});
+ assertThrows(function() {reader.readInt32String()});
+ assertThrows(function() {reader.readInt64()});
+ assertThrows(function() {reader.readInt64String()});
+ assertThrows(function() {reader.readUint32()});
+ assertThrows(function() {reader.readUint32String()});
+ assertThrows(function() {reader.readUint64()});
+ assertThrows(function() {reader.readUint64String()});
+ assertThrows(function() {reader.readSint32()});
+ assertThrows(function() {reader.readBool()});
+ assertThrows(function() {reader.readEnum()});
+
+ reader = jspb.BinaryReader.alloc([8, 1]);
+ reader.nextField();
+ assertThrows(function() {reader.readFixed32()});
+ assertThrows(function() {reader.readFixed64()});
+ assertThrows(function() {reader.readSfixed32()});
+ assertThrows(function() {reader.readSfixed64()});
+ assertThrows(function() {reader.readFloat()});
+ assertThrows(function() {reader.readDouble()});
+
+ assertThrows(function() {reader.readString()});
+ assertThrows(function() {reader.readBytes()});
+ });
+
+
+ /**
+ * Tests encoding and decoding of unsigned field types.
+ * @param {Function} readField
+ * @param {Function} writeField
+ * @param {number} epsilon
+ * @param {number} upperLimit
+ * @param {Function} filter
+ * @private
+ * @suppress {missingProperties}
+ */
+ var doTestUnsignedField_ = function(readField,
+ writeField, epsilon, upperLimit, filter) {
+ assertNotNull(readField);
+ assertNotNull(writeField);
+
+ var writer = new jspb.BinaryWriter();
+
+ // Encode zero and limits.
+ writeField.call(writer, 1, filter(0));
+ writeField.call(writer, 2, filter(epsilon));
+ writeField.call(writer, 3, filter(upperLimit));
+
+ // Encode positive values.
+ for (var cursor = epsilon; cursor < upperLimit; cursor *= 1.1) {
+ writeField.call(writer, 4, filter(cursor));
+ }
+
+ var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
+
+ // Check zero and limits.
+ reader.nextField();
+ assertEquals(1, reader.getFieldNumber());
+ assertEquals(filter(0), readField.call(reader));
+
+ reader.nextField();
+ assertEquals(2, reader.getFieldNumber());
+ assertEquals(filter(epsilon), readField.call(reader));
+
+ reader.nextField();
+ assertEquals(3, reader.getFieldNumber());
+ assertEquals(filter(upperLimit), readField.call(reader));
+
+ // Check positive values.
+ for (var cursor = epsilon; cursor < upperLimit; cursor *= 1.1) {
+ reader.nextField();
+ if (4 != reader.getFieldNumber()) throw 'fail!';
+ if (filter(cursor) != readField.call(reader)) throw 'fail!';
+ }
+ };
+
+
+ /**
+ * Tests encoding and decoding of signed field types.
+ * @param {Function} readField
+ * @param {Function} writeField
+ * @param {number} epsilon
+ * @param {number} lowerLimit
+ * @param {number} upperLimit
+ * @param {Function} filter
+ * @private
+ * @suppress {missingProperties}
+ */
+ var doTestSignedField_ = function(readField,
+ writeField, epsilon, lowerLimit, upperLimit, filter) {
+ var writer = new jspb.BinaryWriter();
+
+ // Encode zero and limits.
+ writeField.call(writer, 1, filter(lowerLimit));
+ writeField.call(writer, 2, filter(-epsilon));
+ writeField.call(writer, 3, filter(0));
+ writeField.call(writer, 4, filter(epsilon));
+ writeField.call(writer, 5, filter(upperLimit));
+
+ var inputValues = [];
+
+ // Encode negative values.
+ for (var cursor = lowerLimit; cursor < -epsilon; cursor /= 1.1) {
+ var val = filter(cursor);
+ writeField.call(writer, 6, val);
+ inputValues.push({
+ fieldNumber: 6,
+ value: val
+ });
+ }
+
+ // Encode positive values.
+ for (var cursor = epsilon; cursor < upperLimit; cursor *= 1.1) {
+ var val = filter(cursor);
+ writeField.call(writer, 7, val);
+ inputValues.push({
+ fieldNumber: 7,
+ value: val
+ });
+ }
+
+ var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
+
+ // Check zero and limits.
+ reader.nextField();
+ assertEquals(1, reader.getFieldNumber());
+ assertEquals(filter(lowerLimit), readField.call(reader));
+
+ reader.nextField();
+ assertEquals(2, reader.getFieldNumber());
+ assertEquals(filter(-epsilon), readField.call(reader));
+
+ reader.nextField();
+ assertEquals(3, reader.getFieldNumber());
+ assertEquals(filter(0), readField.call(reader));
+
+ reader.nextField();
+ assertEquals(4, reader.getFieldNumber());
+ assertEquals(filter(epsilon), readField.call(reader));
+
+ reader.nextField();
+ assertEquals(5, reader.getFieldNumber());
+ assertEquals(filter(upperLimit), readField.call(reader));
+
+ for (var i = 0; i < inputValues.length; i++) {
+ var expected = inputValues[i];
+ reader.nextField();
+ assertEquals(expected.fieldNumber, reader.getFieldNumber());
+ assertEquals(expected.value, readField.call(reader));
+ }
+ };
+
+
+ /**
+ * Tests fields that use varint encoding.
+ */
+ it('testVarintFields', function() {
+ assertNotUndefined(jspb.BinaryReader.prototype.readUint32);
+ assertNotUndefined(jspb.BinaryWriter.prototype.writeUint32);
+ assertNotUndefined(jspb.BinaryReader.prototype.readUint64);
+ assertNotUndefined(jspb.BinaryWriter.prototype.writeUint64);
+ assertNotUndefined(jspb.BinaryReader.prototype.readBool);
+ assertNotUndefined(jspb.BinaryWriter.prototype.writeBool);
+ doTestUnsignedField_(
+ jspb.BinaryReader.prototype.readUint32,
+ jspb.BinaryWriter.prototype.writeUint32,
+ 1, Math.pow(2, 32) - 1, Math.round);
+
+ doTestUnsignedField_(
+ jspb.BinaryReader.prototype.readUint64,
+ jspb.BinaryWriter.prototype.writeUint64,
+ 1, Math.pow(2, 64) - 1025, Math.round);
+
+ doTestSignedField_(
+ jspb.BinaryReader.prototype.readInt32,
+ jspb.BinaryWriter.prototype.writeInt32,
+ 1, -Math.pow(2, 31), Math.pow(2, 31) - 1, Math.round);
+
+ doTestSignedField_(
+ jspb.BinaryReader.prototype.readInt64,
+ jspb.BinaryWriter.prototype.writeInt64,
+ 1, -Math.pow(2, 63), Math.pow(2, 63) - 513, Math.round);
+
+ doTestSignedField_(
+ jspb.BinaryReader.prototype.readEnum,
+ jspb.BinaryWriter.prototype.writeEnum,
+ 1, -Math.pow(2, 31), Math.pow(2, 31) - 1, Math.round);
+
+ doTestUnsignedField_(
+ jspb.BinaryReader.prototype.readBool,
+ jspb.BinaryWriter.prototype.writeBool,
+ 1, 1, function(x) { return !!x; });
+ });
+
+
+ /**
+ * Tests reading a field from hexadecimal string (format: '08 BE EF').
+ * @param {Function} readField
+ * @param {number} expected
+ * @param {string} hexString
+ */
+ function doTestHexStringVarint_(readField, expected, hexString) {
+ var bytesCount = (hexString.length + 1) / 3;
+ var bytes = new Uint8Array(bytesCount);
+ for (var i = 0; i < bytesCount; i++) {
+ bytes[i] = parseInt(hexString.substring(i * 3, i * 3 + 2), 16);
+ }
+ var reader = jspb.BinaryReader.alloc(bytes);
+ reader.nextField();
+ assertEquals(expected, readField.call(reader));
+ }
+
+
+ /**
+ * Tests non-canonical redundant varint decoding.
+ */
+ it('testRedundantVarintFields', function() {
+ assertNotNull(jspb.BinaryReader.prototype.readUint32);
+ assertNotNull(jspb.BinaryReader.prototype.readUint64);
+ assertNotNull(jspb.BinaryReader.prototype.readSint32);
+ assertNotNull(jspb.BinaryReader.prototype.readSint64);
+
+ // uint32 and sint32 take no more than 5 bytes
+ // 08 - field prefix (type = 0 means varint)
+ doTestHexStringVarint_(
+ jspb.BinaryReader.prototype.readUint32,
+ 12, '08 8C 80 80 80 00');
+
+ // 11 stands for -6 in zigzag encoding
+ doTestHexStringVarint_(
+ jspb.BinaryReader.prototype.readSint32,
+ -6, '08 8B 80 80 80 00');
+
+ // uint64 and sint64 take no more than 10 bytes
+ // 08 - field prefix (type = 0 means varint)
+ doTestHexStringVarint_(
+ jspb.BinaryReader.prototype.readUint64,
+ 12, '08 8C 80 80 80 80 80 80 80 80 00');
+
+ // 11 stands for -6 in zigzag encoding
+ doTestHexStringVarint_(
+ jspb.BinaryReader.prototype.readSint64,
+ -6, '08 8B 80 80 80 80 80 80 80 80 00');
+ });
+
+
+ /**
+ * Tests 64-bit fields that are handled as strings.
+ */
+ it('testStringInt64Fields', function() {
+ var writer = new jspb.BinaryWriter();
+
+ var testSignedData = [
+ '2730538252207801776',
+ '-2688470994844604560',
+ '3398529779486536359',
+ '3568577411627971000',
+ '272477188847484900',
+ '-6649058714086158188',
+ '-7695254765712060806',
+ '-4525541438037104029',
+ '-4993706538836508568',
+ '4990160321893729138'
+ ];
+ var testUnsignedData = [
+ '7822732630241694882',
+ '6753602971916687352',
+ '2399935075244442116',
+ '8724292567325338867',
+ '16948784802625696584',
+ '4136275908516066934',
+ '3575388346793700364',
+ '5167142028379259461',
+ '1557573948689737699',
+ '17100725280812548567'
+ ];
+
+ for (var i = 0; i < testSignedData.length; i++) {
+ writer.writeInt64String(2 * i + 1, testSignedData[i]);
+ writer.writeUint64String(2 * i + 2, testUnsignedData[i]);
+ }
+
+ var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
+
+ for (var i = 0; i < testSignedData.length; i++) {
+ reader.nextField();
+ assertEquals(2 * i + 1, reader.getFieldNumber());
+ assertEquals(testSignedData[i], reader.readInt64String());
+ reader.nextField();
+ assertEquals(2 * i + 2, reader.getFieldNumber());
+ assertEquals(testUnsignedData[i], reader.readUint64String());
+ }
+ });
+
+
+ /**
+ * Tests fields that use zigzag encoding.
+ */
+ it('testZigzagFields', function() {
+ doTestSignedField_(
+ jspb.BinaryReader.prototype.readSint32,
+ jspb.BinaryWriter.prototype.writeSint32,
+ 1, -Math.pow(2, 31), Math.pow(2, 31) - 1, Math.round);
+
+ doTestSignedField_(
+ jspb.BinaryReader.prototype.readSint64,
+ jspb.BinaryWriter.prototype.writeSint64,
+ 1, -Math.pow(2, 63), Math.pow(2, 63) - 513, Math.round);
+ });
+
+
+ /**
+ * Tests fields that use fixed-length encoding.
+ */
+ it('testFixedFields', function() {
+ doTestUnsignedField_(
+ jspb.BinaryReader.prototype.readFixed32,
+ jspb.BinaryWriter.prototype.writeFixed32,
+ 1, Math.pow(2, 32) - 1, Math.round);
+
+ doTestUnsignedField_(
+ jspb.BinaryReader.prototype.readFixed64,
+ jspb.BinaryWriter.prototype.writeFixed64,
+ 1, Math.pow(2, 64) - 1025, Math.round);
+
+ doTestSignedField_(
+ jspb.BinaryReader.prototype.readSfixed32,
+ jspb.BinaryWriter.prototype.writeSfixed32,
+ 1, -Math.pow(2, 31), Math.pow(2, 31) - 1, Math.round);
+
+ doTestSignedField_(
+ jspb.BinaryReader.prototype.readSfixed64,
+ jspb.BinaryWriter.prototype.writeSfixed64,
+ 1, -Math.pow(2, 63), Math.pow(2, 63) - 513, Math.round);
+ });
+
+
+ /**
+ * Tests floating point fields.
+ */
+ it('testFloatFields', function() {
+ doTestSignedField_(
+ jspb.BinaryReader.prototype.readFloat,
+ jspb.BinaryWriter.prototype.writeFloat,
+ jspb.BinaryConstants.FLOAT32_MIN,
+ -jspb.BinaryConstants.FLOAT32_MAX,
+ jspb.BinaryConstants.FLOAT32_MAX,
+ truncate);
+
+ doTestSignedField_(
+ jspb.BinaryReader.prototype.readDouble,
+ jspb.BinaryWriter.prototype.writeDouble,
+ jspb.BinaryConstants.FLOAT64_EPS * 10,
+ -jspb.BinaryConstants.FLOAT64_MIN,
+ jspb.BinaryConstants.FLOAT64_MIN,
+ function(x) { return x; });
+ });
+
+
+ /**
+ * Tests length-delimited string fields.
+ */
+ it('testStringFields', function() {
+ var s1 = 'The quick brown fox jumps over the lazy dog.';
+ var s2 = '人人生而自由,在尊嚴和權利上一律平等。';
+
+ var writer = new jspb.BinaryWriter();
+
+ writer.writeString(1, s1);
+ writer.writeString(2, s2);
+
+ var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
+
+ reader.nextField();
+ assertEquals(1, reader.getFieldNumber());
+ assertEquals(s1, reader.readString());
+
+ reader.nextField();
+ assertEquals(2, reader.getFieldNumber());
+ assertEquals(s2, reader.readString());
+ });
+
+
+ /**
+ * Tests length-delimited byte fields.
+ */
+ it('testByteFields', function() {
+ var message = [];
+ var lowerLimit = 1;
+ var upperLimit = 256;
+ var scale = 1.1;
+
+ var writer = new jspb.BinaryWriter();
+
+ for (var cursor = lowerLimit; cursor < upperLimit; cursor *= 1.1) {
+ var len = Math.round(cursor);
+ var bytes = [];
+ for (var i = 0; i < len; i++) bytes.push(i % 256);
+
+ writer.writeBytes(len, bytes);
+ }
+
+ var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
+
+ for (var cursor = lowerLimit; reader.nextField(); cursor *= 1.1) {
+ var len = Math.round(cursor);
+ if (len != reader.getFieldNumber()) throw 'fail!';
+
+ var bytes = reader.readBytes();
+ if (len != bytes.length) throw 'fail!';
+ for (var i = 0; i < bytes.length; i++) {
+ if (i % 256 != bytes[i]) throw 'fail!';
+ }
+ }
+ });
+
+
+ /**
+ * Tests nested messages.
+ */
+ it('testNesting', function() {
+ var writer = new jspb.BinaryWriter();
+ var dummyMessage = /** @type {!jspb.BinaryMessage} */({});
+
+ writer.writeInt32(1, 100);
+
+ // Add one message with 3 int fields.
+ writer.writeMessage(2, dummyMessage, function() {
+ writer.writeInt32(3, 300);
+ writer.writeInt32(4, 400);
+ writer.writeInt32(5, 500);
+ });
+
+ // Add one empty message.
+ writer.writeMessage(6, dummyMessage, goog.nullFunction);
+
+ writer.writeInt32(7, 700);
+
+ var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
+
+ // Validate outermost message.
+
+ reader.nextField();
+ assertEquals(1, reader.getFieldNumber());
+ assertEquals(100, reader.readInt32());
+
+ reader.nextField();
+ assertEquals(2, reader.getFieldNumber());
+ reader.readMessage(dummyMessage, function() {
+ // Validate embedded message 1.
+ reader.nextField();
+ assertEquals(3, reader.getFieldNumber());
+ assertEquals(300, reader.readInt32());
+
+ reader.nextField();
+ assertEquals(4, reader.getFieldNumber());
+ assertEquals(400, reader.readInt32());
+
+ reader.nextField();
+ assertEquals(5, reader.getFieldNumber());
+ assertEquals(500, reader.readInt32());
+
+ assertEquals(false, reader.nextField());
+ });
+
+ reader.nextField();
+ assertEquals(6, reader.getFieldNumber());
+ reader.readMessage(dummyMessage, function() {
+ // Validate embedded message 2.
+
+ assertEquals(false, reader.nextField());
+ });
+
+ reader.nextField();
+ assertEquals(7, reader.getFieldNumber());
+ assertEquals(700, reader.readInt32());
+
+ assertEquals(false, reader.nextField());
+ });
+
+ /**
+ * Tests skipping fields of each type by interleaving them with sentinel
+ * values and skipping everything that's not a sentinel.
+ */
+ it('testSkipField', function() {
+ var writer = new jspb.BinaryWriter();
+
+ var sentinel = 123456789;
+
+ // Write varint fields of different sizes.
+ writer.writeInt32(1, sentinel);
+ writer.writeInt32(1, 1);
+ writer.writeInt32(1, 1000);
+ writer.writeInt32(1, 1000000);
+ writer.writeInt32(1, 1000000000);
+
+ // Write fixed 64-bit encoded fields.
+ writer.writeInt32(2, sentinel);
+ writer.writeDouble(2, 1);
+ writer.writeFixed64(2, 1);
+ writer.writeSfixed64(2, 1);
+
+ // Write fixed 32-bit encoded fields.
+ writer.writeInt32(3, sentinel);
+ writer.writeFloat(3, 1);
+ writer.writeFixed32(3, 1);
+ writer.writeSfixed32(3, 1);
+
+ // Write delimited fields.
+ writer.writeInt32(4, sentinel);
+ writer.writeBytes(4, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
+ writer.writeString(4, 'The quick brown fox jumps over the lazy dog');
+
+ // Write a group with a nested group inside.
+ writer.writeInt32(5, sentinel);
+ var dummyMessage = /** @type {!jspb.BinaryMessage} */({});
+ writer.writeGroup(5, dummyMessage, function() {
+ writer.writeInt64(42, 42);
+ writer.writeGroup(6, dummyMessage, function() {
+ writer.writeInt64(84, 42);
+ });
+ });
+
+ // Write final sentinel.
+ writer.writeInt32(6, sentinel);
+
+ var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
+
+ function skip(field, count) {
+ for (var i = 0; i < count; i++) {
+ reader.nextField();
+ if (field != reader.getFieldNumber()) throw 'fail!';
+ reader.skipField();
+ }
+ }
+
+ reader.nextField();
+ assertEquals(1, reader.getFieldNumber());
+ assertEquals(sentinel, reader.readInt32());
+ skip(1, 4);
+
+ reader.nextField();
+ assertEquals(2, reader.getFieldNumber());
+ assertEquals(sentinel, reader.readInt32());
+ skip(2, 3);
+
+ reader.nextField();
+ assertEquals(3, reader.getFieldNumber());
+ assertEquals(sentinel, reader.readInt32());
+ skip(3, 3);
+
+ reader.nextField();
+ assertEquals(4, reader.getFieldNumber());
+ assertEquals(sentinel, reader.readInt32());
+ skip(4, 2);
+
+ reader.nextField();
+ assertEquals(5, reader.getFieldNumber());
+ assertEquals(sentinel, reader.readInt32());
+ skip(5, 1);
+
+ reader.nextField();
+ assertEquals(6, reader.getFieldNumber());
+ assertEquals(sentinel, reader.readInt32());
+ });
+
+
+ /**
+ * Tests packed fields.
+ */
+ it('testPackedFields', function() {
+ var writer = new jspb.BinaryWriter();
+
+ var sentinel = 123456789;
+
+ var unsignedData = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
+ var signedData = [-1, 2, -3, 4, -5, 6, -7, 8, -9, 10];
+ var floatData = [1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10];
+ var doubleData = [1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10];
+ var boolData = [true, false, true, true, false, false, true, false];
+
+ for (var i = 0; i < floatData.length; i++) {
+ floatData[i] = truncate(floatData[i]);
+ }
+
+ writer.writeInt32(1, sentinel);
+
+ writer.writePackedInt32(2, signedData);
+ writer.writePackedInt64(2, signedData);
+ writer.writePackedUint32(2, unsignedData);
+ writer.writePackedUint64(2, unsignedData);
+ writer.writePackedSint32(2, signedData);
+ writer.writePackedSint64(2, signedData);
+ writer.writePackedFixed32(2, unsignedData);
+ writer.writePackedFixed64(2, unsignedData);
+ writer.writePackedSfixed32(2, signedData);
+ writer.writePackedSfixed64(2, signedData);
+ writer.writePackedFloat(2, floatData);
+ writer.writePackedDouble(2, doubleData);
+ writer.writePackedBool(2, boolData);
+ writer.writePackedEnum(2, unsignedData);
+
+ writer.writeInt32(3, sentinel);
+
+ var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
+
+ reader.nextField();
+ assertEquals(sentinel, reader.readInt32());
+
+ reader.nextField();
+ assertElementsEquals(reader.readPackedInt32(), signedData);
+
+ reader.nextField();
+ assertElementsEquals(reader.readPackedInt64(), signedData);
+
+ reader.nextField();
+ assertElementsEquals(reader.readPackedUint32(), unsignedData);
+
+ reader.nextField();
+ assertElementsEquals(reader.readPackedUint64(), unsignedData);
+
+ reader.nextField();
+ assertElementsEquals(reader.readPackedSint32(), signedData);
+
+ reader.nextField();
+ assertElementsEquals(reader.readPackedSint64(), signedData);
+
+ reader.nextField();
+ assertElementsEquals(reader.readPackedFixed32(), unsignedData);
+
+ reader.nextField();
+ assertElementsEquals(reader.readPackedFixed64(), unsignedData);
+
+ reader.nextField();
+ assertElementsEquals(reader.readPackedSfixed32(), signedData);
+
+ reader.nextField();
+ assertElementsEquals(reader.readPackedSfixed64(), signedData);
+
+ reader.nextField();
+ assertElementsEquals(reader.readPackedFloat(), floatData);
+
+ reader.nextField();
+ assertElementsEquals(reader.readPackedDouble(), doubleData);
+
+ reader.nextField();
+ assertElementsEquals(reader.readPackedBool(), boolData);
+
+ reader.nextField();
+ assertElementsEquals(reader.readPackedEnum(), unsignedData);
+
+ reader.nextField();
+ assertEquals(sentinel, reader.readInt32());
+ });
+
+
+ /**
+ * Byte blobs inside nested messages should always have their byte offset set
+ * relative to the start of the outermost blob, not the start of their parent
+ * blob.
+ */
+ it('testNestedBlobs', function() {
+ // Create a proto consisting of two nested messages, with the inner one
+ // containing a blob of bytes.
+
+ var fieldTag = (1 << 3) | jspb.BinaryConstants.WireType.DELIMITED;
+ var blob = [1, 2, 3, 4, 5];
+ var writer = new jspb.BinaryWriter();
+ var dummyMessage = /** @type {!jspb.BinaryMessage} */({});
+
+ writer.writeMessage(1, dummyMessage, function() {
+ writer.writeMessage(1, dummyMessage, function() {
+ writer.writeBytes(1, blob);
+ });
+ });
+
+ // Peel off the outer two message layers. Each layer should have two bytes
+ // of overhead, one for the field tag and one for the length of the inner
+ // blob.
+
+ var decoder1 = new jspb.BinaryDecoder(writer.getResultBuffer());
+ assertEquals(fieldTag, decoder1.readUnsignedVarint32());
+ assertEquals(blob.length + 4, decoder1.readUnsignedVarint32());
+
+ var decoder2 = new jspb.BinaryDecoder(decoder1.readBytes(blob.length + 4));
+ assertEquals(fieldTag, decoder2.readUnsignedVarint32());
+ assertEquals(blob.length + 2, decoder2.readUnsignedVarint32());
+
+ assertEquals(fieldTag, decoder2.readUnsignedVarint32());
+ assertEquals(blob.length, decoder2.readUnsignedVarint32());
+ var bytes = decoder2.readBytes(blob.length);
+
+ assertElementsEquals(bytes, blob);
+ });
+
+
+ /**
+ * Tests read callbacks.
+ */
+ it('testReadCallbacks', function() {
+ var writer = new jspb.BinaryWriter();
+ var dummyMessage = /** @type {!jspb.BinaryMessage} */({});
+
+ // Add an int, a submessage, and another int.
+ writer.writeInt32(1, 100);
+
+ writer.writeMessage(2, dummyMessage, function() {
+ writer.writeInt32(3, 300);
+ writer.writeInt32(4, 400);
+ writer.writeInt32(5, 500);
+ });
+
+ writer.writeInt32(7, 700);
+
+ // Create the reader and register a custom read callback.
+ var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
+
+ /**
+ * @param {!jspb.BinaryReader} reader
+ * @return {*}
+ */
+ function readCallback(reader) {
+ reader.nextField();
+ assertEquals(3, reader.getFieldNumber());
+ assertEquals(300, reader.readInt32());
+
+ reader.nextField();
+ assertEquals(4, reader.getFieldNumber());
+ assertEquals(400, reader.readInt32());
+
+ reader.nextField();
+ assertEquals(5, reader.getFieldNumber());
+ assertEquals(500, reader.readInt32());
+
+ assertEquals(false, reader.nextField());
+ };
+
+ reader.registerReadCallback('readCallback', readCallback);
+
+ // Read the container message.
+ reader.nextField();
+ assertEquals(1, reader.getFieldNumber());
+ assertEquals(100, reader.readInt32());
+
+ reader.nextField();
+ assertEquals(2, reader.getFieldNumber());
+ reader.readMessage(dummyMessage, function() {
+ // Decode the embedded message using the registered callback.
+ reader.runReadCallback('readCallback');
+ });
+
+ reader.nextField();
+ assertEquals(7, reader.getFieldNumber());
+ assertEquals(700, reader.readInt32());
+
+ assertEquals(false, reader.nextField());
+ });
+});
diff --git a/js/compatibility_tests/v3.0.0/binary/utils_test.js b/js/compatibility_tests/v3.0.0/binary/utils_test.js
new file mode 100644
index 00000000..d27e5ea2
--- /dev/null
+++ b/js/compatibility_tests/v3.0.0/binary/utils_test.js
@@ -0,0 +1,668 @@
+// 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.
+
+/**
+ * @fileoverview Test cases for jspb's helper functions.
+ *
+ * Test suite is written using Jasmine -- see http://jasmine.github.io/
+ *
+ * @author aappleby@google.com (Austin Appleby)
+ */
+
+goog.require('goog.crypt.base64');
+goog.require('goog.testing.asserts');
+goog.require('jspb.BinaryConstants');
+goog.require('jspb.BinaryWriter');
+goog.require('jspb.utils');
+
+
+/**
+ * @param {number} x
+ * @return {number}
+ */
+function truncate(x) {
+ var temp = new Float32Array(1);
+ temp[0] = x;
+ return temp[0];
+}
+
+
+/**
+ * Converts an 64-bit integer in split representation to a 64-bit hash string
+ * (8 bits encoded per character).
+ * @param {number} bitsLow The low 32 bits of the split 64-bit integer.
+ * @param {number} bitsHigh The high 32 bits of the split 64-bit integer.
+ * @return {string} The encoded hash string, 8 bits per character.
+ */
+function toHashString(bitsLow, bitsHigh) {
+ return String.fromCharCode((bitsLow >>> 0) & 0xFF,
+ (bitsLow >>> 8) & 0xFF,
+ (bitsLow >>> 16) & 0xFF,
+ (bitsLow >>> 24) & 0xFF,
+ (bitsHigh >>> 0) & 0xFF,
+ (bitsHigh >>> 8) & 0xFF,
+ (bitsHigh >>> 16) & 0xFF,
+ (bitsHigh >>> 24) & 0xFF);
+}
+
+
+describe('binaryUtilsTest', function() {
+ /**
+ * Tests lossless binary-to-decimal conversion.
+ */
+ it('testDecimalConversion', function() {
+ // Check some magic numbers.
+ var result =
+ jspb.utils.joinUnsignedDecimalString(0x89e80001, 0x8ac72304);
+ assertEquals('10000000000000000001', result);
+
+ result = jspb.utils.joinUnsignedDecimalString(0xacd05f15, 0x1b69b4b);
+ assertEquals('123456789123456789', result);
+
+ result = jspb.utils.joinUnsignedDecimalString(0xeb1f0ad2, 0xab54a98c);
+ assertEquals('12345678901234567890', result);
+
+ result = jspb.utils.joinUnsignedDecimalString(0xe3b70cb1, 0x891087b8);
+ assertEquals('9876543210987654321', result);
+
+ // Check limits.
+ result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x00000000);
+ assertEquals('0', result);
+
+ result = jspb.utils.joinUnsignedDecimalString(0xFFFFFFFF, 0xFFFFFFFF);
+ assertEquals('18446744073709551615', result);
+
+ // Check each bit of the low dword.
+ for (var i = 0; i < 32; i++) {
+ var low = (1 << i) >>> 0;
+ result = jspb.utils.joinUnsignedDecimalString(low, 0);
+ assertEquals('' + Math.pow(2, i), result);
+ }
+
+ // Check the first 20 bits of the high dword.
+ for (var i = 0; i < 20; i++) {
+ var high = (1 << i) >>> 0;
+ result = jspb.utils.joinUnsignedDecimalString(0, high);
+ assertEquals('' + Math.pow(2, 32 + i), result);
+ }
+
+ // V8's internal double-to-string conversion is inaccurate for values above
+ // 2^52, even if they're representable integers - check the rest of the bits
+ // manually against the correct string representations of 2^N.
+
+ result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x00100000);
+ assertEquals('4503599627370496', result);
+
+ result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x00200000);
+ assertEquals('9007199254740992', result);
+
+ result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x00400000);
+ assertEquals('18014398509481984', result);
+
+ result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x00800000);
+ assertEquals('36028797018963968', result);
+
+ result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x01000000);
+ assertEquals('72057594037927936', result);
+
+ result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x02000000);
+ assertEquals('144115188075855872', result);
+
+ result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x04000000);
+ assertEquals('288230376151711744', result);
+
+ result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x08000000);
+ assertEquals('576460752303423488', result);
+
+ result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x10000000);
+ assertEquals('1152921504606846976', result);
+
+ result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x20000000);
+ assertEquals('2305843009213693952', result);
+
+ result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x40000000);
+ assertEquals('4611686018427387904', result);
+
+ result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x80000000);
+ assertEquals('9223372036854775808', result);
+ });
+
+
+ /**
+ * Going from hash strings to decimal strings should also be lossless.
+ */
+ it('testHashToDecimalConversion', function() {
+ var result;
+ var convert = jspb.utils.hash64ToDecimalString;
+
+ result = convert(toHashString(0x00000000, 0x00000000), false);
+ assertEquals('0', result);
+
+ result = convert(toHashString(0x00000000, 0x00000000), true);
+ assertEquals('0', result);
+
+ result = convert(toHashString(0xFFFFFFFF, 0xFFFFFFFF), false);
+ assertEquals('18446744073709551615', result);
+
+ result = convert(toHashString(0xFFFFFFFF, 0xFFFFFFFF), true);
+ assertEquals('-1', result);
+
+ result = convert(toHashString(0x00000000, 0x80000000), false);
+ assertEquals('9223372036854775808', result);
+
+ result = convert(toHashString(0x00000000, 0x80000000), true);
+ assertEquals('-9223372036854775808', result);
+
+ result = convert(toHashString(0xacd05f15, 0x01b69b4b), false);
+ assertEquals('123456789123456789', result);
+
+ result = convert(toHashString(~0xacd05f15 + 1, ~0x01b69b4b), true);
+ assertEquals('-123456789123456789', result);
+
+ // And converting arrays of hashes should work the same way.
+ result = jspb.utils.hash64ArrayToDecimalStrings([
+ toHashString(0xFFFFFFFF, 0xFFFFFFFF),
+ toHashString(0x00000000, 0x80000000),
+ toHashString(0xacd05f15, 0x01b69b4b)], false);
+ assertEquals(3, result.length);
+ assertEquals('18446744073709551615', result[0]);
+ assertEquals('9223372036854775808', result[1]);
+ assertEquals('123456789123456789', result[2]);
+ });
+
+ /*
+ * Going from decimal strings to hash strings should be lossless.
+ */
+ it('testDecimalToHashConversion', function() {
+ var result;
+ var convert = jspb.utils.decimalStringToHash64;
+
+ result = convert('0');
+ assertEquals(String.fromCharCode.apply(null,
+ [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), result);
+
+ result = convert('-1');
+ assertEquals(String.fromCharCode.apply(null,
+ [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]), result);
+
+ result = convert('18446744073709551615');
+ assertEquals(String.fromCharCode.apply(null,
+ [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]), result);
+
+ result = convert('9223372036854775808');
+ assertEquals(String.fromCharCode.apply(null,
+ [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80]), result);
+
+ result = convert('-9223372036854775808');
+ assertEquals(String.fromCharCode.apply(null,
+ [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80]), result);
+
+ result = convert('123456789123456789');
+ assertEquals(String.fromCharCode.apply(null,
+ [0x15, 0x5F, 0xD0, 0xAC, 0x4B, 0x9B, 0xB6, 0x01]), result);
+
+ result = convert('-123456789123456789');
+ assertEquals(String.fromCharCode.apply(null,
+ [0xEB, 0xA0, 0x2F, 0x53, 0xB4, 0x64, 0x49, 0xFE]), result);
+ });
+
+ /**
+ * Going from hash strings to hex strings should be lossless.
+ */
+ it('testHashToHexConversion', function() {
+ var result;
+ var convert = jspb.utils.hash64ToHexString;
+
+ result = convert(toHashString(0x00000000, 0x00000000));
+ assertEquals('0x0000000000000000', result);
+
+ result = convert(toHashString(0xFFFFFFFF, 0xFFFFFFFF));
+ assertEquals('0xffffffffffffffff', result);
+
+ result = convert(toHashString(0x12345678, 0x9ABCDEF0));
+ assertEquals('0x9abcdef012345678', result);
+ });
+
+
+ /**
+ * Going from hex strings to hash strings should be lossless.
+ */
+ it('testHexToHashConversion', function() {
+ var result;
+ var convert = jspb.utils.hexStringToHash64;
+
+ result = convert('0x0000000000000000');
+ assertEquals(String.fromCharCode.apply(null,
+ [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), result);
+
+ result = convert('0xffffffffffffffff');
+ assertEquals(String.fromCharCode.apply(null,
+ [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]), result);
+
+ // Hex string is big-endian, hash string is little-endian.
+ result = convert('0x123456789ABCDEF0');
+ assertEquals(String.fromCharCode.apply(null,
+ [0xF0, 0xDE, 0xBC, 0x9A, 0x78, 0x56, 0x34, 0x12]), result);
+
+ // Capitalization should not matter.
+ result = convert('0x0000abcdefABCDEF');
+ assertEquals(String.fromCharCode.apply(null,
+ [0xEF, 0xCD, 0xAB, 0xEF, 0xCD, 0xAB, 0x00, 0x00]), result);
+ });
+
+
+ /**
+ * Going from numbers to hash strings should be lossless for up to 53 bits of
+ * precision.
+ */
+ it('testNumberToHashConversion', function() {
+ var result;
+ var convert = jspb.utils.numberToHash64;
+
+ result = convert(0x0000000000000);
+ assertEquals('0x0000000000000000', jspb.utils.hash64ToHexString(result));
+
+ result = convert(0xFFFFFFFFFFFFF);
+ assertEquals('0x000fffffffffffff', jspb.utils.hash64ToHexString(result));
+
+ result = convert(0x123456789ABCD);
+ assertEquals('0x000123456789abcd', jspb.utils.hash64ToHexString(result));
+
+ result = convert(0xDCBA987654321);
+ assertEquals('0x000dcba987654321', jspb.utils.hash64ToHexString(result));
+
+ // 53 bits of precision should not be truncated.
+ result = convert(0x10000000000001);
+ assertEquals('0x0010000000000001', jspb.utils.hash64ToHexString(result));
+
+ // 54 bits of precision should be truncated.
+ result = convert(0x20000000000001);
+ assertNotEquals(
+ '0x0020000000000001', jspb.utils.hash64ToHexString(result));
+ });
+
+
+ /**
+ * Sanity check the behavior of Javascript's strings when doing funny things
+ * with unicode characters.
+ */
+ it('sanityCheckUnicodeStrings', function() {
+ var strings = new Array(65536);
+
+ // All possible unsigned 16-bit values should be storable in a string, they
+ // shouldn't do weird things with the length of the string, and they should
+ // come back out of the string unchanged.
+ for (var i = 0; i < 65536; i++) {
+ strings[i] = 'a' + String.fromCharCode(i) + 'a';
+ if (3 != strings[i].length) throw 'fail!';
+ if (i != strings[i].charCodeAt(1)) throw 'fail!';
+ }
+
+ // Each unicode character should compare equal to itself and not equal to a
+ // different unicode character.
+ for (var i = 0; i < 65536; i++) {
+ if (strings[i] != strings[i]) throw 'fail!';
+ if (strings[i] == strings[(i + 1) % 65536]) throw 'fail!';
+ }
+ });
+
+
+ /**
+ * Tests conversion from 32-bit floating point numbers to split64 numbers.
+ */
+ it('testFloat32ToSplit64', function() {
+ var f32_eps = jspb.BinaryConstants.FLOAT32_EPS;
+ var f32_min = jspb.BinaryConstants.FLOAT32_MIN;
+ var f32_max = jspb.BinaryConstants.FLOAT32_MAX;
+
+ // NaN.
+ jspb.utils.splitFloat32(NaN);
+ if (!isNaN(jspb.utils.joinFloat32(jspb.utils.split64Low,
+ jspb.utils.split64High))) {
+ throw 'fail!';
+ }
+
+ /**
+ * @param {number} x
+ * @param {number=} opt_bits
+ */
+ function test(x, opt_bits) {
+ jspb.utils.splitFloat32(x);
+ if (goog.isDef(opt_bits)) {
+ if (opt_bits != jspb.utils.split64Low) throw 'fail!';
+ }
+ if (truncate(x) != jspb.utils.joinFloat32(jspb.utils.split64Low,
+ jspb.utils.split64High)) {
+ throw 'fail!';
+ }
+ }
+
+ // Positive and negative infinity.
+ test(Infinity, 0x7f800000);
+ test(-Infinity, 0xff800000);
+
+ // Positive and negative zero.
+ test(0, 0x00000000);
+ test(-0, 0x80000000);
+
+ // Positive and negative epsilon.
+ test(f32_eps, 0x00000001);
+ test(-f32_eps, 0x80000001);
+
+ // Positive and negative min.
+ test(f32_min, 0x00800000);
+ test(-f32_min, 0x80800000);
+
+ // Positive and negative max.
+ test(f32_max, 0x7F7FFFFF);
+ test(-f32_max, 0xFF7FFFFF);
+
+ // Various positive values.
+ var cursor = f32_eps * 10;
+ while (cursor != Infinity) {
+ test(cursor);
+ cursor *= 1.1;
+ }
+
+ // Various negative values.
+ cursor = -f32_eps * 10;
+ while (cursor != -Infinity) {
+ test(cursor);
+ cursor *= 1.1;
+ }
+ });
+
+
+ /**
+ * Tests conversion from 64-bit floating point numbers to split64 numbers.
+ */
+ it('testFloat64ToSplit64', function() {
+ var f64_eps = jspb.BinaryConstants.FLOAT64_EPS;
+ var f64_min = jspb.BinaryConstants.FLOAT64_MIN;
+ var f64_max = jspb.BinaryConstants.FLOAT64_MAX;
+
+ // NaN.
+ jspb.utils.splitFloat64(NaN);
+ if (!isNaN(jspb.utils.joinFloat64(jspb.utils.split64Low,
+ jspb.utils.split64High))) {
+ throw 'fail!';
+ }
+
+ /**
+ * @param {number} x
+ * @param {number=} opt_highBits
+ * @param {number=} opt_lowBits
+ */
+ function test(x, opt_highBits, opt_lowBits) {
+ jspb.utils.splitFloat64(x);
+ if (goog.isDef(opt_highBits)) {
+ if (opt_highBits != jspb.utils.split64High) throw 'fail!';
+ }
+ if (goog.isDef(opt_lowBits)) {
+ if (opt_lowBits != jspb.utils.split64Low) throw 'fail!';
+ }
+ if (x != jspb.utils.joinFloat64(jspb.utils.split64Low,
+ jspb.utils.split64High)) {
+ throw 'fail!';
+ }
+ }
+
+ // Positive and negative infinity.
+ test(Infinity, 0x7ff00000, 0x00000000);
+ test(-Infinity, 0xfff00000, 0x00000000);
+
+ // Positive and negative zero.
+ test(0, 0x00000000, 0x00000000);
+ test(-0, 0x80000000, 0x00000000);
+
+ // Positive and negative epsilon.
+ test(f64_eps, 0x00000000, 0x00000001);
+ test(-f64_eps, 0x80000000, 0x00000001);
+
+ // Positive and negative min.
+ test(f64_min, 0x00100000, 0x00000000);
+ test(-f64_min, 0x80100000, 0x00000000);
+
+ // Positive and negative max.
+ test(f64_max, 0x7FEFFFFF, 0xFFFFFFFF);
+ test(-f64_max, 0xFFEFFFFF, 0xFFFFFFFF);
+
+ // Various positive values.
+ var cursor = f64_eps * 10;
+ while (cursor != Infinity) {
+ test(cursor);
+ cursor *= 1.1;
+ }
+
+ // Various negative values.
+ cursor = -f64_eps * 10;
+ while (cursor != -Infinity) {
+ test(cursor);
+ cursor *= 1.1;
+ }
+ });
+
+
+ /**
+ * Tests counting packed varints.
+ */
+ it('testCountVarints', function() {
+ var values = [];
+ for (var i = 1; i < 1000000000; i *= 1.1) {
+ values.push(Math.floor(i));
+ }
+
+ var writer = new jspb.BinaryWriter();
+ writer.writePackedUint64(1, values);
+
+ var buffer = new Uint8Array(writer.getResultBuffer());
+
+ // We should have two more varints than we started with - one for the field
+ // tag, one for the packed length.
+ assertEquals(values.length + 2,
+ jspb.utils.countVarints(buffer, 0, buffer.length));
+ });
+
+
+ /**
+ * Tests counting matching varint fields.
+ */
+ it('testCountVarintFields', function() {
+ var writer = new jspb.BinaryWriter();
+
+ var count = 0;
+ for (var i = 1; i < 1000000000; i *= 1.1) {
+ writer.writeUint64(1, Math.floor(i));
+ count++;
+ }
+ writer.writeString(2, 'terminator');
+
+ var buffer = new Uint8Array(writer.getResultBuffer());
+ assertEquals(count,
+ jspb.utils.countVarintFields(buffer, 0, buffer.length, 1));
+
+ writer = new jspb.BinaryWriter();
+
+ count = 0;
+ for (var i = 1; i < 1000000000; i *= 1.1) {
+ writer.writeUint64(123456789, Math.floor(i));
+ count++;
+ }
+ writer.writeString(2, 'terminator');
+
+ buffer = new Uint8Array(writer.getResultBuffer());
+ assertEquals(count,
+ jspb.utils.countVarintFields(buffer, 0, buffer.length, 123456789));
+ });
+
+
+ /**
+ * Tests counting matching fixed32 fields.
+ */
+ it('testCountFixed32Fields', function() {
+ var writer = new jspb.BinaryWriter();
+
+ var count = 0;
+ for (var i = 1; i < 1000000000; i *= 1.1) {
+ writer.writeFixed32(1, Math.floor(i));
+ count++;
+ }
+ writer.writeString(2, 'terminator');
+
+ var buffer = new Uint8Array(writer.getResultBuffer());
+ assertEquals(count,
+ jspb.utils.countFixed32Fields(buffer, 0, buffer.length, 1));
+
+ writer = new jspb.BinaryWriter();
+
+ count = 0;
+ for (var i = 1; i < 1000000000; i *= 1.1) {
+ writer.writeFixed32(123456789, Math.floor(i));
+ count++;
+ }
+ writer.writeString(2, 'terminator');
+
+ buffer = new Uint8Array(writer.getResultBuffer());
+ assertEquals(count,
+ jspb.utils.countFixed32Fields(buffer, 0, buffer.length, 123456789));
+ });
+
+
+ /**
+ * Tests counting matching fixed64 fields.
+ */
+ it('testCountFixed64Fields', function() {
+ var writer = new jspb.BinaryWriter();
+
+ var count = 0;
+ for (var i = 1; i < 1000000000; i *= 1.1) {
+ writer.writeDouble(1, i);
+ count++;
+ }
+ writer.writeString(2, 'terminator');
+
+ var buffer = new Uint8Array(writer.getResultBuffer());
+ assertEquals(count,
+ jspb.utils.countFixed64Fields(buffer, 0, buffer.length, 1));
+
+ writer = new jspb.BinaryWriter();
+
+ count = 0;
+ for (var i = 1; i < 1000000000; i *= 1.1) {
+ writer.writeDouble(123456789, i);
+ count++;
+ }
+ writer.writeString(2, 'terminator');
+
+ buffer = new Uint8Array(writer.getResultBuffer());
+ assertEquals(count,
+ jspb.utils.countFixed64Fields(buffer, 0, buffer.length, 123456789));
+ });
+
+
+ /**
+ * Tests counting matching delimited fields.
+ */
+ it('testCountDelimitedFields', function() {
+ var writer = new jspb.BinaryWriter();
+
+ var count = 0;
+ for (var i = 1; i < 1000; i *= 1.1) {
+ writer.writeBytes(1, [Math.floor(i)]);
+ count++;
+ }
+ writer.writeString(2, 'terminator');
+
+ var buffer = new Uint8Array(writer.getResultBuffer());
+ assertEquals(count,
+ jspb.utils.countDelimitedFields(buffer, 0, buffer.length, 1));
+
+ writer = new jspb.BinaryWriter();
+
+ count = 0;
+ for (var i = 1; i < 1000; i *= 1.1) {
+ writer.writeBytes(123456789, [Math.floor(i)]);
+ count++;
+ }
+ writer.writeString(2, 'terminator');
+
+ buffer = new Uint8Array(writer.getResultBuffer());
+ assertEquals(count,
+ jspb.utils.countDelimitedFields(buffer, 0, buffer.length, 123456789));
+ });
+
+
+ /**
+ * Tests byte format for debug strings.
+ */
+ it('testDebugBytesToTextFormat', function() {
+ assertEquals('""', jspb.utils.debugBytesToTextFormat(null));
+ assertEquals('"\\x00\\x10\\xff"',
+ jspb.utils.debugBytesToTextFormat([0, 16, 255]));
+ });
+
+
+ /**
+ * Tests converting byte blob sources into byte blobs.
+ */
+ it('testByteSourceToUint8Array', function() {
+ var convert = jspb.utils.byteSourceToUint8Array;
+
+ var sourceData = [];
+ for (var i = 0; i < 256; i++) {
+ sourceData.push(i);
+ }
+
+ var sourceBytes = new Uint8Array(sourceData);
+ var sourceBuffer = sourceBytes.buffer;
+ var sourceBase64 = goog.crypt.base64.encodeByteArray(sourceData);
+ var sourceString = String.fromCharCode.apply(null, sourceData);
+
+ function check(result) {
+ assertEquals(Uint8Array, result.constructor);
+ assertEquals(sourceData.length, result.length);
+ for (var i = 0; i < result.length; i++) {
+ assertEquals(sourceData[i], result[i]);
+ }
+ }
+
+ // Converting Uint8Arrays into Uint8Arrays should be a no-op.
+ assertEquals(sourceBytes, convert(sourceBytes));
+
+ // Converting Array.<numbers> into Uint8Arrays should work.
+ check(convert(sourceData));
+
+ // Converting ArrayBuffers into Uint8Arrays should work.
+ check(convert(sourceBuffer));
+
+ // Converting base64-encoded strings into Uint8Arrays should work.
+ check(convert(sourceBase64));
+ });
+});
diff --git a/js/compatibility_tests/v3.0.0/binary/writer_test.js b/js/compatibility_tests/v3.0.0/binary/writer_test.js
new file mode 100644
index 00000000..d5dadb41
--- /dev/null
+++ b/js/compatibility_tests/v3.0.0/binary/writer_test.js
@@ -0,0 +1,122 @@
+// 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.
+
+/**
+ * @fileoverview Test cases for jspb's binary protocol buffer writer. In
+ * practice BinaryWriter is used to drive the Decoder and Reader test cases,
+ * so only writer-specific tests are here.
+ *
+ * Test suite is written using Jasmine -- see http://jasmine.github.io/
+ *
+ * @author aappleby@google.com (Austin Appleby)
+ */
+
+goog.require('goog.crypt');
+goog.require('goog.testing.asserts');
+goog.require('jspb.BinaryWriter');
+
+
+/**
+ * @param {function()} func This function should throw an error when run.
+ */
+function assertFails(func) {
+ var e = assertThrows(func);
+ //assertNotNull(e.toString().match(/Error/));
+}
+
+
+describe('binaryWriterTest', function() {
+ /**
+ * Verifies that misuse of the writer class triggers assertions.
+ */
+ it('testWriteErrors', function() {
+ // Submessages with invalid field indices should assert.
+ var writer = new jspb.BinaryWriter();
+ var dummyMessage = /** @type {!jspb.BinaryMessage} */({});
+
+ assertFails(function() {
+ writer.writeMessage(-1, dummyMessage, goog.nullFunction);
+ });
+
+ // Writing invalid field indices should assert.
+ writer = new jspb.BinaryWriter();
+ assertFails(function() {writer.writeUint64(-1, 1);});
+
+ // Writing out-of-range field values should assert.
+ writer = new jspb.BinaryWriter();
+
+ assertFails(function() {writer.writeInt32(1, -Infinity);});
+ assertFails(function() {writer.writeInt32(1, Infinity);});
+
+ assertFails(function() {writer.writeInt64(1, -Infinity);});
+ assertFails(function() {writer.writeInt64(1, Infinity);});
+
+ assertFails(function() {writer.writeUint32(1, -1);});
+ assertFails(function() {writer.writeUint32(1, Infinity);});
+
+ assertFails(function() {writer.writeUint64(1, -1);});
+ assertFails(function() {writer.writeUint64(1, Infinity);});
+
+ assertFails(function() {writer.writeSint32(1, -Infinity);});
+ assertFails(function() {writer.writeSint32(1, Infinity);});
+
+ assertFails(function() {writer.writeSint64(1, -Infinity);});
+ assertFails(function() {writer.writeSint64(1, Infinity);});
+
+ assertFails(function() {writer.writeFixed32(1, -1);});
+ assertFails(function() {writer.writeFixed32(1, Infinity);});
+
+ assertFails(function() {writer.writeFixed64(1, -1);});
+ assertFails(function() {writer.writeFixed64(1, Infinity);});
+
+ assertFails(function() {writer.writeSfixed32(1, -Infinity);});
+ assertFails(function() {writer.writeSfixed32(1, Infinity);});
+
+ assertFails(function() {writer.writeSfixed64(1, -Infinity);});
+ assertFails(function() {writer.writeSfixed64(1, Infinity);});
+ });
+
+
+ /**
+ * Basic test of retrieving the result as a Uint8Array buffer
+ */
+ it('testGetResultBuffer', function() {
+ var expected = '0864120b48656c6c6f20776f726c641a0301020320c801';
+
+ var writer = new jspb.BinaryWriter();
+ writer.writeUint32(1, 100);
+ writer.writeString(2, 'Hello world');
+ writer.writeBytes(3, new Uint8Array([1, 2, 3]));
+ writer.writeUint32(4, 200);
+
+ var buffer = writer.getResultBuffer();
+ assertEquals(expected, goog.crypt.byteArrayToHex(buffer));
+ });
+});
diff --git a/js/compatibility_tests/v3.0.0/commonjs/export_asserts.js b/js/compatibility_tests/v3.0.0/commonjs/export_asserts.js
new file mode 100644
index 00000000..5219d120
--- /dev/null
+++ b/js/compatibility_tests/v3.0.0/commonjs/export_asserts.js
@@ -0,0 +1,37 @@
+/**
+ * @fileoverview Exports symbols needed only by tests.
+ *
+ * This file exports several Closure Library symbols that are only
+ * used by tests. It is used to generate a file
+ * closure_asserts_commonjs.js that is only used at testing time.
+ */
+
+goog.require('goog.testing.asserts');
+
+var global = Function('return this')();
+
+// All of the closure "assert" functions are exported at the global level.
+//
+// The Google Closure assert functions start with assert, eg.
+// assertThrows
+// assertNotThrows
+// assertTrue
+// ...
+//
+// The one exception is the "fail" function.
+function shouldExport(str) {
+ return str.lastIndexOf('assert') === 0 || str == 'fail';
+}
+
+for (var key in global) {
+ if ((typeof key == "string") && global.hasOwnProperty(key) &&
+ shouldExport(key)) {
+ exports[key] = global[key];
+ }
+}
+
+// The COMPILED variable is set by Closure compiler to "true" when it compiles
+// JavaScript, so in practice this is equivalent to "exports.COMPILED = true".
+// This will disable some debugging functionality in debug.js. We could
+// investigate whether this can/should be enabled in CommonJS builds.
+exports.COMPILED = COMPILED
diff --git a/js/compatibility_tests/v3.0.0/commonjs/export_testdeps.js b/js/compatibility_tests/v3.0.0/commonjs/export_testdeps.js
new file mode 100644
index 00000000..59c77ca2
--- /dev/null
+++ b/js/compatibility_tests/v3.0.0/commonjs/export_testdeps.js
@@ -0,0 +1,18 @@
+/**
+ * @fileoverview Export symbols needed by tests in CommonJS style.
+ *
+ * This file is like export.js, but for symbols that are only used by tests.
+ * However we exclude assert functions here, because they are exported into
+ * the global namespace, so those are handled as a special case in
+ * export_asserts.js.
+ */
+
+goog.require('goog.crypt.base64');
+goog.require('jspb.arith.Int64');
+goog.require('jspb.arith.UInt64');
+goog.require('jspb.BinaryEncoder');
+goog.require('jspb.BinaryDecoder');
+goog.require('jspb.utils');
+
+exports.goog = goog;
+exports.jspb = jspb;
diff --git a/js/compatibility_tests/v3.0.0/commonjs/import_test.js b/js/compatibility_tests/v3.0.0/commonjs/import_test.js
new file mode 100644
index 00000000..ffa34fea
--- /dev/null
+++ b/js/compatibility_tests/v3.0.0/commonjs/import_test.js
@@ -0,0 +1,52 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2016 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.
+
+// Test suite is written using Jasmine -- see http://jasmine.github.io/
+
+
+
+var googleProtobuf = require('google-protobuf');
+var asserts = require('closure_asserts_commonjs');
+var global = Function('return this')();
+
+// Bring asserts into the global namespace.
+googleProtobuf.object.extend(global, asserts);
+googleProtobuf.exportSymbol('jspb.Message', googleProtobuf.Message, global);
+
+var test7_pb = require('./test7/test7_pb');
+googleProtobuf.exportSymbol('proto.jspb.test.framing.FramingMessage', test7_pb.FramingMessage, global);
+
+describe('Import test suite', function() {
+ it('testImportedMessage', function() {
+ var framing1 = new proto.jspb.test.framing.FramingMessage([]);
+ var framing2 = new proto.jspb.test.framing.FramingMessage([]);
+ assertObjectEquals(framing1.toObject(), framing2.toObject());
+ });
+});
diff --git a/js/compatibility_tests/v3.0.0/commonjs/jasmine.json b/js/compatibility_tests/v3.0.0/commonjs/jasmine.json
new file mode 100644
index 00000000..666b8edb
--- /dev/null
+++ b/js/compatibility_tests/v3.0.0/commonjs/jasmine.json
@@ -0,0 +1,9 @@
+{
+ "spec_dir": "",
+ "spec_files": [
+ "*_test.js",
+ "binary/proto_test.js"
+ ],
+ "helpers": [
+ ]
+}
diff --git a/js/compatibility_tests/v3.0.0/commonjs/rewrite_tests_for_commonjs.js b/js/compatibility_tests/v3.0.0/commonjs/rewrite_tests_for_commonjs.js
new file mode 100644
index 00000000..b6d90d28
--- /dev/null
+++ b/js/compatibility_tests/v3.0.0/commonjs/rewrite_tests_for_commonjs.js
@@ -0,0 +1,97 @@
+/**
+ * @fileoverview Utility to translate test files to CommonJS imports.
+ *
+ * This is a somewhat hacky tool designed to do one very specific thing.
+ * All of the test files in *_test.js are written with Closure-style
+ * imports (goog.require()). This works great for running the tests
+ * against Closure-style generated code, but we also want to run the
+ * tests against CommonJS-style generated code without having to fork
+ * the tests.
+ *
+ * Closure-style imports import each individual type by name. This is
+ * very different than CommonJS imports which are by file. So we put
+ * special comments in these tests like:
+ *
+ * // CommonJS-LoadFromFile: test_pb
+ * goog.require('proto.jspb.test.CloneExtension');
+ * goog.require('proto.jspb.test.Complex');
+ * goog.require('proto.jspb.test.DefaultValues');
+ *
+ * This script parses that special comment and uses it to generate proper
+ * CommonJS require() statements so that the tests can run and pass using
+ * CommonJS imports. The script will change the above statements into:
+ *
+ * var test_pb = require('test_pb');
+ * googleProtobuf.exportSymbol('proto.jspb.test.CloneExtension', test_pb.CloneExtension, global);
+ * googleProtobuf.exportSymbol('proto.jspb.test.Complex', test_pb.Complex, global);
+ * googleProtobuf.exportSymbol('proto.jspb.test.DefaultValues', test_pb.DefaultValues, global);
+ *
+ * (The "exportSymbol" function will define the given names in the global
+ * namespace, taking care not to overwrite any previous value for
+ * "proto.jspb.test").
+ */
+
+var lineReader = require('readline').createInterface({
+ input: process.stdin,
+ output: process.stdout
+});
+
+function tryStripPrefix(str, prefix) {
+ if (str.lastIndexOf(prefix) !== 0) {
+ throw "String: " + str + " didn't start with: " + prefix;
+ }
+ return str.substr(prefix.length);
+}
+
+function camelCase(str) {
+ var ret = '';
+ var ucaseNext = false;
+ for (var i = 0; i < str.length; i++) {
+ if (str[i] == '-') {
+ ucaseNext = true;
+ } else if (ucaseNext) {
+ ret += str[i].toUpperCase();
+ ucaseNext = false;
+ } else {
+ ret += str[i];
+ }
+ }
+ return ret;
+}
+
+var module = null;
+var pkg = null;
+
+// Header: goes in every file at the top.
+console.log("var global = Function('return this')();");
+console.log("var googleProtobuf = require('google-protobuf');");
+console.log("var testdeps = require('testdeps_commonjs');");
+console.log("global.goog = testdeps.goog;");
+console.log("global.jspb = testdeps.jspb;");
+console.log("var asserts = require('closure_asserts_commonjs');");
+console.log("");
+console.log("// Bring asserts into the global namespace.");
+console.log("googleProtobuf.object.extend(global, asserts);");
+
+lineReader.on('line', function(line) {
+ var isRequire = line.match(/goog\.require\('([^']*)'\)/);
+ var isLoadFromFile = line.match(/CommonJS-LoadFromFile: (\S*) (.*)/);
+ var isSetTestOnly = line.match(/goog.setTestOnly()/);
+ if (isRequire) {
+ if (module) { // Skip goog.require() lines before the first directive.
+ var fullSym = isRequire[1];
+ var sym = tryStripPrefix(fullSym, pkg);
+ console.log("googleProtobuf.exportSymbol('" + fullSym + "', " + module + sym + ', global);');
+ }
+ } else if (isLoadFromFile) {
+ var module_path = isLoadFromFile[1].split('/');
+ module = camelCase(module_path[module_path.length - 1]);
+ pkg = isLoadFromFile[2];
+
+ if (module != "googleProtobuf") { // We unconditionally require this in the header.
+ console.log("var " + module + " = require('./" + isLoadFromFile[1] + "');");
+ }
+ } else if (!isSetTestOnly) { // Remove goog.setTestOnly() lines.
+ console.log(line);
+ }
+});
diff --git a/js/compatibility_tests/v3.0.0/commonjs/test6/test6.proto b/js/compatibility_tests/v3.0.0/commonjs/test6/test6.proto
new file mode 100644
index 00000000..a060925f
--- /dev/null
+++ b/js/compatibility_tests/v3.0.0/commonjs/test6/test6.proto
@@ -0,0 +1,40 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2016 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.
+
+syntax = "proto3";
+
+option java_package = "com.google.apps.jspb.proto";
+option java_multiple_files = true;
+
+package jspb.test.importing;
+
+message ImportedMessage {
+ string string_value = 1;
+}
diff --git a/js/compatibility_tests/v3.0.0/commonjs/test7/test7.proto b/js/compatibility_tests/v3.0.0/commonjs/test7/test7.proto
new file mode 100644
index 00000000..f5574a3d
--- /dev/null
+++ b/js/compatibility_tests/v3.0.0/commonjs/test7/test7.proto
@@ -0,0 +1,42 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2016 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.
+
+syntax = "proto3";
+
+option java_package = "com.google.apps.jspb.proto";
+option java_multiple_files = true;
+
+package jspb.test.framing;
+
+import "test6/test6.proto";
+
+message FramingMessage {
+ jspb.test.importing.ImportedMessage imported_message = 1;
+}
diff --git a/js/compatibility_tests/v3.0.0/data.proto b/js/compatibility_tests/v3.0.0/data.proto
new file mode 100644
index 00000000..74a8a994
--- /dev/null
+++ b/js/compatibility_tests/v3.0.0/data.proto
@@ -0,0 +1,51 @@
+// 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: mwr@google.com (Mark Rawling)
+
+syntax = "proto2";
+
+option java_package = "com.google.apps.jspb.proto";
+option java_multiple_files = true;
+
+package jspb.test;
+
+// legacy data, must be nested
+message data {
+ message NestedData {
+ required string str = 1;
+ }
+}
+
+// new data, does not require nesting
+message UnnestedData {
+ required string str = 1;
+}
+
diff --git a/js/compatibility_tests/v3.0.0/debug_test.js b/js/compatibility_tests/v3.0.0/debug_test.js
new file mode 100644
index 00000000..01cbf891
--- /dev/null
+++ b/js/compatibility_tests/v3.0.0/debug_test.js
@@ -0,0 +1,105 @@
+// 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.
+
+goog.setTestOnly();
+
+goog.require('goog.testing.asserts');
+
+// CommonJS-LoadFromFile: google-protobuf
+goog.require('jspb.debug');
+
+// CommonJS-LoadFromFile: test_pb
+goog.require('proto.jspb.test.HasExtensions');
+goog.require('proto.jspb.test.IsExtension');
+goog.require('proto.jspb.test.Simple1');
+
+
+
+describe('debugTest', function() {
+ it('testSimple1', function() {
+ if (COMPILED) {
+ return;
+ }
+ var message = new proto.jspb.test.Simple1();
+ message.setAString('foo');
+ assertObjectEquals({
+ $name: 'proto.jspb.test.Simple1',
+ 'aString': 'foo',
+ 'aRepeatedStringList': []
+ }, jspb.debug.dump(message));
+
+ message.setABoolean(true);
+ message.setARepeatedStringList(['1', '2']);
+
+ assertObjectEquals({
+ $name: 'proto.jspb.test.Simple1',
+ 'aString': 'foo',
+ 'aRepeatedStringList': ['1', '2'],
+ 'aBoolean': true
+ }, jspb.debug.dump(message));
+
+ message.setAString(undefined);
+
+ assertObjectEquals({
+ $name: 'proto.jspb.test.Simple1',
+ 'aRepeatedStringList': ['1', '2'],
+ 'aBoolean': true
+ }, jspb.debug.dump(message));
+ });
+
+
+ it('testExtensions', function() {
+ if (COMPILED) {
+ return;
+ }
+ var extension = new proto.jspb.test.IsExtension();
+ extension.setExt1('ext1field');
+ var extendable = new proto.jspb.test.HasExtensions();
+ extendable.setStr1('v1');
+ extendable.setStr2('v2');
+ extendable.setStr3('v3');
+ extendable.setExtension(proto.jspb.test.IsExtension.extField, extension);
+
+ assertObjectEquals({
+ '$name': 'proto.jspb.test.HasExtensions',
+ 'str1': 'v1',
+ 'str2': 'v2',
+ 'str3': 'v3',
+ '$extensions': {
+ 'extField': {
+ '$name': 'proto.jspb.test.IsExtension',
+ 'ext1': 'ext1field'
+ },
+ 'repeatedSimpleList': []
+ }
+ }, jspb.debug.dump(extendable));
+ });
+
+});
diff --git a/js/compatibility_tests/v3.0.0/jasmine1.json b/js/compatibility_tests/v3.0.0/jasmine1.json
new file mode 100644
index 00000000..6653c01c
--- /dev/null
+++ b/js/compatibility_tests/v3.0.0/jasmine1.json
@@ -0,0 +1,17 @@
+{
+ "spec_dir": "",
+ "spec_files": [
+ "*_test.js",
+ "binary/*_test.js"
+ ],
+ "helpers": [
+ "../../../js/node_modules/google-closure-library/closure/goog/bootstrap/nodejs.js",
+ "../../../js/node_loader.js",
+ "../../../js/deps.js",
+ "../../../js/google/protobuf/any.js",
+ "../../../js/google/protobuf/struct.js",
+ "../../../js/google/protobuf/timestamp.js",
+ "testproto_libs1.js",
+ "testproto_libs2.js"
+ ]
+}
diff --git a/js/compatibility_tests/v3.0.0/jasmine2.json b/js/compatibility_tests/v3.0.0/jasmine2.json
new file mode 100644
index 00000000..3208078f
--- /dev/null
+++ b/js/compatibility_tests/v3.0.0/jasmine2.json
@@ -0,0 +1,17 @@
+{
+ "spec_dir": "",
+ "spec_files": [
+ "*_test.js",
+ "binary/*_test.js"
+ ],
+ "helpers": [
+ "../../../js/node_modules/google-closure-library/closure/goog/bootstrap/nodejs.js",
+ "../../../js/node_loader.js",
+ "../../../js/deps.js",
+ "../../../js/google/protobuf/any.js",
+ "../../../js/google/protobuf/struct.js",
+ "../../../js/google/protobuf/timestamp.js",
+ "testproto_libs1_new.js",
+ "testproto_libs2.js"
+ ]
+}
diff --git a/js/compatibility_tests/v3.0.0/jasmine3.json b/js/compatibility_tests/v3.0.0/jasmine3.json
new file mode 100644
index 00000000..3fb9a1b0
--- /dev/null
+++ b/js/compatibility_tests/v3.0.0/jasmine3.json
@@ -0,0 +1,17 @@
+{
+ "spec_dir": "",
+ "spec_files": [
+ "*_test.js",
+ "binary/*_test.js"
+ ],
+ "helpers": [
+ "../../../js/node_modules/google-closure-library/closure/goog/bootstrap/nodejs.js",
+ "../../../js/node_loader.js",
+ "../../../js/deps.js",
+ "../../../js/google/protobuf/any.js",
+ "../../../js/google/protobuf/struct.js",
+ "../../../js/google/protobuf/timestamp.js",
+ "testproto_libs1.js",
+ "testproto_libs2_new.js"
+ ]
+}
diff --git a/js/compatibility_tests/v3.0.0/message_test.js b/js/compatibility_tests/v3.0.0/message_test.js
new file mode 100644
index 00000000..b7791431
--- /dev/null
+++ b/js/compatibility_tests/v3.0.0/message_test.js
@@ -0,0 +1,1080 @@
+// 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.
+
+// Test suite is written using Jasmine -- see http://jasmine.github.io/
+
+goog.setTestOnly();
+
+goog.require('goog.json');
+goog.require('goog.testing.asserts');
+goog.require('goog.userAgent');
+
+// CommonJS-LoadFromFile: google-protobuf jspb
+goog.require('jspb.Message');
+
+// CommonJS-LoadFromFile: test5_pb proto.jspb.exttest.beta
+goog.require('proto.jspb.exttest.beta.floatingStrField');
+
+// CommonJS-LoadFromFile: test3_pb proto.jspb.exttest
+goog.require('proto.jspb.exttest.floatingMsgField');
+
+// CommonJS-LoadFromFile: test4_pb proto.jspb.exttest
+goog.require('proto.jspb.exttest.floatingMsgFieldTwo');
+
+// CommonJS-LoadFromFile: test_pb proto.jspb.test
+goog.require('proto.jspb.test.CloneExtension');
+goog.require('proto.jspb.test.Complex');
+goog.require('proto.jspb.test.DefaultValues');
+goog.require('proto.jspb.test.Empty');
+goog.require('proto.jspb.test.EnumContainer');
+goog.require('proto.jspb.test.floatingMsgField');
+goog.require('proto.jspb.test.FloatingPointFields');
+goog.require('proto.jspb.test.floatingStrField');
+goog.require('proto.jspb.test.HasExtensions');
+goog.require('proto.jspb.test.IndirectExtension');
+goog.require('proto.jspb.test.IsExtension');
+goog.require('proto.jspb.test.OptionalFields');
+goog.require('proto.jspb.test.OuterEnum');
+goog.require('proto.jspb.test.OuterMessage.Complex');
+goog.require('proto.jspb.test.Simple1');
+goog.require('proto.jspb.test.Simple2');
+goog.require('proto.jspb.test.SpecialCases');
+goog.require('proto.jspb.test.TestClone');
+goog.require('proto.jspb.test.TestEndsWithBytes');
+goog.require('proto.jspb.test.TestGroup');
+goog.require('proto.jspb.test.TestGroup1');
+goog.require('proto.jspb.test.TestMessageWithOneof');
+goog.require('proto.jspb.test.TestReservedNames');
+goog.require('proto.jspb.test.TestReservedNamesExtension');
+
+// CommonJS-LoadFromFile: test2_pb proto.jspb.test
+goog.require('proto.jspb.test.ExtensionMessage');
+goog.require('proto.jspb.test.TestExtensionsMessage');
+
+
+
+
+describe('Message test suite', function() {
+ it('testEmptyProto', function() {
+ var empty1 = new proto.jspb.test.Empty([]);
+ var empty2 = new proto.jspb.test.Empty([]);
+ assertObjectEquals({}, empty1.toObject());
+ assertObjectEquals('Message should not be corrupted:', empty2, empty1);
+ });
+
+ it('testTopLevelEnum', function() {
+ var response = new proto.jspb.test.EnumContainer([]);
+ response.setOuterEnum(proto.jspb.test.OuterEnum.FOO);
+ assertEquals(proto.jspb.test.OuterEnum.FOO, response.getOuterEnum());
+ });
+
+ it('testByteStrings', function() {
+ var data = new proto.jspb.test.DefaultValues([]);
+ data.setBytesField('some_bytes');
+ assertEquals('some_bytes', data.getBytesField());
+ });
+
+ it('testComplexConversion', function() {
+ var data1 = ['a',,, [, 11], [[, 22], [, 33]],, ['s1', 's2'],, 1];
+ var data2 = ['a',,, [, 11], [[, 22], [, 33]],, ['s1', 's2'],, 1];
+ var foo = new proto.jspb.test.Complex(data1);
+ var bar = new proto.jspb.test.Complex(data2);
+ var result = foo.toObject();
+ assertObjectEquals({
+ aString: 'a',
+ anOutOfOrderBool: 1,
+ aNestedMessage: {
+ anInt: 11
+ },
+ aRepeatedMessageList: [{anInt: 22}, {anInt: 33}],
+ aRepeatedStringList: ['s1', 's2']
+ }, result);
+
+ // Now test with the jspb instances included.
+ result = foo.toObject(true /* opt_includeInstance */);
+ assertObjectEquals({
+ aString: 'a',
+ anOutOfOrderBool: 1,
+ aNestedMessage: {
+ anInt: 11,
+ $jspbMessageInstance: foo.getANestedMessage()
+ },
+ aRepeatedMessageList: [
+ {anInt: 22, $jspbMessageInstance: foo.getARepeatedMessageList()[0]},
+ {anInt: 33, $jspbMessageInstance: foo.getARepeatedMessageList()[1]}
+ ],
+ aRepeatedStringList: ['s1', 's2'],
+ $jspbMessageInstance: foo
+ }, result);
+
+ });
+
+ it('testMissingFields', function() {
+ var foo = new proto.jspb.test.Complex([
+ undefined, undefined, undefined, [],
+ undefined, undefined, undefined, undefined]);
+ var bar = new proto.jspb.test.Complex([
+ undefined, undefined, undefined, [],
+ undefined, undefined, undefined, undefined]);
+ var result = foo.toObject();
+ assertObjectEquals({
+ aString: undefined,
+ anOutOfOrderBool: undefined,
+ aNestedMessage: {
+ anInt: undefined
+ },
+ // Note: JsPb converts undefined repeated fields to empty arrays.
+ aRepeatedMessageList: [],
+ aRepeatedStringList: []
+ }, result);
+
+ });
+
+ it('testNestedComplexMessage', function() {
+ // Instantiate the message and set a unique field, just to ensure that we
+ // are not getting jspb.test.Complex instead.
+ var msg = new proto.jspb.test.OuterMessage.Complex();
+ msg.setInnerComplexField(5);
+ });
+
+ it('testSpecialCases', function() {
+ // Note: Some property names are reserved in JavaScript.
+ // These names are converted to the Js property named pb_<reserved_name>.
+ var special =
+ new proto.jspb.test.SpecialCases(['normal', 'default', 'function',
+ 'var']);
+ var result = special.toObject();
+ assertObjectEquals({
+ normal: 'normal',
+ pb_default: 'default',
+ pb_function: 'function',
+ pb_var: 'var'
+ }, result);
+ });
+
+ it('testDefaultValues', function() {
+ var defaultString = "default<>\'\"abc";
+ var response = new proto.jspb.test.DefaultValues();
+
+ // Test toObject
+ var expectedObject = {
+ stringField: defaultString,
+ boolField: true,
+ intField: 11,
+ enumField: 13,
+ emptyField: '',
+ bytesField: 'bW9v'
+ };
+ assertObjectEquals(expectedObject, response.toObject());
+
+
+ // Test getters
+ response = new proto.jspb.test.DefaultValues();
+ assertEquals(defaultString, response.getStringField());
+ assertEquals(true, response.getBoolField());
+ assertEquals(11, response.getIntField());
+ assertEquals(13, response.getEnumField());
+ assertEquals('', response.getEmptyField());
+ assertEquals('bW9v', response.getBytesField());
+
+ function makeDefault(values) {
+ return new proto.jspb.test.DefaultValues(values);
+ }
+
+ // Test with undefined values,
+ // Use push to workaround IE treating undefined array elements as holes.
+ response = makeDefault([undefined, undefined, undefined, undefined]);
+ assertEquals(defaultString, response.getStringField());
+ assertEquals(true, response.getBoolField());
+ assertEquals(11, response.getIntField());
+ assertEquals(13, response.getEnumField());
+ assertFalse(response.hasStringField());
+ assertFalse(response.hasBoolField());
+ assertFalse(response.hasIntField());
+ assertFalse(response.hasEnumField());
+
+ // Test with null values, as would be returned by a JSON serializer.
+ response = makeDefault([null, null, null, null]);
+ assertEquals(defaultString, response.getStringField());
+ assertEquals(true, response.getBoolField());
+ assertEquals(11, response.getIntField());
+ assertEquals(13, response.getEnumField());
+ assertFalse(response.hasStringField());
+ assertFalse(response.hasBoolField());
+ assertFalse(response.hasIntField());
+ assertFalse(response.hasEnumField());
+
+ // Test with false-like values.
+ response = makeDefault(['', false, 0, 0]);
+ assertEquals('', response.getStringField());
+ assertEquals(false, response.getBoolField());
+ assertEquals(true, response.getIntField() == 0);
+ assertEquals(true, response.getEnumField() == 0);
+ assertTrue(response.hasStringField());
+ assertTrue(response.hasBoolField());
+ assertTrue(response.hasIntField());
+ assertTrue(response.hasEnumField());
+
+ // Test that clearing the values reverts them to the default state.
+ response = makeDefault(['blah', false, 111, 77]);
+ response.clearStringField(); response.clearBoolField();
+ response.clearIntField(); response.clearEnumField();
+ assertEquals(defaultString, response.getStringField());
+ assertEquals(true, response.getBoolField());
+ assertEquals(11, response.getIntField());
+ assertEquals(13, response.getEnumField());
+ assertFalse(response.hasStringField());
+ assertFalse(response.hasBoolField());
+ assertFalse(response.hasIntField());
+ assertFalse(response.hasEnumField());
+
+ // Test that setFoo(null) clears the values.
+ response = makeDefault(['blah', false, 111, 77]);
+ response.setStringField(null); response.setBoolField(null);
+ response.setIntField(undefined); response.setEnumField(undefined);
+ assertEquals(defaultString, response.getStringField());
+ assertEquals(true, response.getBoolField());
+ assertEquals(11, response.getIntField());
+ assertEquals(13, response.getEnumField());
+ assertFalse(response.hasStringField());
+ assertFalse(response.hasBoolField());
+ assertFalse(response.hasIntField());
+ assertFalse(response.hasEnumField());
+ });
+
+ it('testMessageRegistration', function() {
+ // goog.require(SomeResponse) will include its library, which will in
+ // turn add SomeResponse to the message registry.
+ assertEquals(jspb.Message.registry_['res'], proto.jspb.test.SomeResponse);
+ });
+
+ it('testClearFields', function() {
+ var data = ['str', true, [11], [[22], [33]], ['s1', 's2']];
+ var foo = new proto.jspb.test.OptionalFields(data);
+ foo.clearAString();
+ foo.clearABool();
+ foo.clearANestedMessage();
+ foo.clearARepeatedMessageList();
+ foo.clearARepeatedStringList();
+ assertEquals('', foo.getAString());
+ assertEquals(false, foo.getABool());
+ assertUndefined(foo.getANestedMessage());
+ assertFalse(foo.hasAString());
+ assertFalse(foo.hasABool());
+ assertObjectEquals([], foo.getARepeatedMessageList());
+ assertObjectEquals([], foo.getARepeatedStringList());
+ // NOTE: We want the missing fields in 'expected' to be undefined,
+ // but we actually get a sparse array instead. We could use something
+ // like [1,undefined,2] to avoid this, except that this is still
+ // sparse on IE. No comment...
+ var expected = [,,, [], []];
+ expected[0] = expected[1] = expected[2] = undefined;
+ assertObjectEquals(expected, foo.toArray());
+
+ // Test set(null). We could deprecated this in favor of clear(), but
+ // it's also convenient to have.
+ data = ['str', true, [11], [[22], [33]], ['s1', 's2']];
+ foo = new proto.jspb.test.OptionalFields(data);
+ foo.setAString(null);
+ foo.setABool(null);
+ foo.setANestedMessage(null);
+ foo.setARepeatedMessageList(null);
+ foo.setARepeatedStringList(null);
+ assertEquals('', foo.getAString());
+ assertEquals(false, foo.getABool());
+ assertNull(foo.getANestedMessage());
+ assertFalse(foo.hasAString());
+ assertFalse(foo.hasABool());
+ assertObjectEquals([], foo.getARepeatedMessageList());
+ assertObjectEquals([], foo.getARepeatedStringList());
+ assertObjectEquals([null, null, null, [], []], foo.toArray());
+
+ // Test set(undefined). Again, not something we really need, and not
+ // supported directly by our typing, but it should 'do the right thing'.
+ data = ['str', true, [11], [[22], [33]], ['s1', 's2']];
+ foo = new proto.jspb.test.OptionalFields(data);
+ foo.setAString(undefined);
+ foo.setABool(undefined);
+ foo.setANestedMessage(undefined);
+ foo.setARepeatedMessageList(undefined);
+ foo.setARepeatedStringList(undefined);
+ assertEquals('', foo.getAString());
+ assertEquals(false, foo.getABool());
+ assertUndefined(foo.getANestedMessage());
+ assertFalse(foo.hasAString());
+ assertFalse(foo.hasABool());
+ assertObjectEquals([], foo.getARepeatedMessageList());
+ assertObjectEquals([], foo.getARepeatedStringList());
+ expected = [,,, [], []];
+ expected[0] = expected[1] = expected[2] = undefined;
+ assertObjectEquals(expected, foo.toArray());
+ });
+
+ it('testDifferenceRawObject', function() {
+ var p1 = new proto.jspb.test.HasExtensions(['hi', 'diff', {}]);
+ var p2 = new proto.jspb.test.HasExtensions(['hi', 'what',
+ {1000: 'unique'}]);
+ var diff = /** @type {proto.jspb.test.HasExtensions} */
+ (jspb.Message.difference(p1, p2));
+ assertEquals('', diff.getStr1());
+ assertEquals('what', diff.getStr2());
+ assertEquals('', diff.getStr3());
+ assertEquals('unique', diff.extensionObject_[1000]);
+ });
+
+ it('testEqualsSimple', function() {
+ var s1 = new proto.jspb.test.Simple1(['hi']);
+ assertTrue(jspb.Message.equals(s1, new proto.jspb.test.Simple1(['hi'])));
+ assertFalse(jspb.Message.equals(s1, new proto.jspb.test.Simple1(['bye'])));
+ var s1b = new proto.jspb.test.Simple1(['hi', ['hello']]);
+ assertTrue(jspb.Message.equals(s1b,
+ new proto.jspb.test.Simple1(['hi', ['hello']])));
+ assertTrue(jspb.Message.equals(s1b,
+ new proto.jspb.test.Simple1(['hi', ['hello', undefined,
+ undefined, undefined]])));
+ assertFalse(jspb.Message.equals(s1b,
+ new proto.jspb.test.Simple1(['no', ['hello']])));
+ // Test with messages of different types
+ var s2 = new proto.jspb.test.Simple2(['hi']);
+ assertFalse(jspb.Message.equals(s1, s2));
+ });
+
+ it('testEquals_softComparison', function() {
+ var s1 = new proto.jspb.test.Simple1(['hi', [], null]);
+ assertTrue(jspb.Message.equals(s1,
+ new proto.jspb.test.Simple1(['hi', []])));
+
+ var s1b = new proto.jspb.test.Simple1(['hi', [], true]);
+ assertTrue(jspb.Message.equals(s1b,
+ new proto.jspb.test.Simple1(['hi', [], 1])));
+ });
+
+ it('testEqualsComplex', function() {
+ var data1 = ['a',,, [, 11], [[, 22], [, 33]],, ['s1', 's2'],, 1];
+ var data2 = ['a',,, [, 11], [[, 22], [, 34]],, ['s1', 's2'],, 1];
+ var data3 = ['a',,, [, 11], [[, 22]],, ['s1', 's2'],, 1];
+ var data4 = ['hi'];
+ var c1a = new proto.jspb.test.Complex(data1);
+ var c1b = new proto.jspb.test.Complex(data1);
+ var c2 = new proto.jspb.test.Complex(data2);
+ var c3 = new proto.jspb.test.Complex(data3);
+ var s1 = new proto.jspb.test.Simple1(data4);
+
+ assertTrue(jspb.Message.equals(c1a, c1b));
+ assertFalse(jspb.Message.equals(c1a, c2));
+ assertFalse(jspb.Message.equals(c2, c3));
+ assertFalse(jspb.Message.equals(c1a, s1));
+ });
+
+ it('testEqualsExtensionsConstructed', function() {
+ assertTrue(jspb.Message.equals(
+ new proto.jspb.test.HasExtensions([]),
+ new proto.jspb.test.HasExtensions([{}])
+ ));
+ assertTrue(jspb.Message.equals(
+ new proto.jspb.test.HasExtensions(['hi', {100: [{200: 'a'}]}]),
+ new proto.jspb.test.HasExtensions(['hi', {100: [{200: 'a'}]}])
+ ));
+ assertFalse(jspb.Message.equals(
+ new proto.jspb.test.HasExtensions(['hi', {100: [{200: 'a'}]}]),
+ new proto.jspb.test.HasExtensions(['hi', {100: [{200: 'b'}]}])
+ ));
+ assertTrue(jspb.Message.equals(
+ new proto.jspb.test.HasExtensions([{100: [{200: 'a'}]}]),
+ new proto.jspb.test.HasExtensions([{100: [{200: 'a'}]}])
+ ));
+ assertTrue(jspb.Message.equals(
+ new proto.jspb.test.HasExtensions([{100: [{200: 'a'}]}]),
+ new proto.jspb.test.HasExtensions([,,, {100: [{200: 'a'}]}])
+ ));
+ assertTrue(jspb.Message.equals(
+ new proto.jspb.test.HasExtensions([,,, {100: [{200: 'a'}]}]),
+ new proto.jspb.test.HasExtensions([{100: [{200: 'a'}]}])
+ ));
+ assertTrue(jspb.Message.equals(
+ new proto.jspb.test.HasExtensions(['hi', {100: [{200: 'a'}]}]),
+ new proto.jspb.test.HasExtensions(['hi',,, {100: [{200: 'a'}]}])
+ ));
+ assertTrue(jspb.Message.equals(
+ new proto.jspb.test.HasExtensions(['hi',,, {100: [{200: 'a'}]}]),
+ new proto.jspb.test.HasExtensions(['hi', {100: [{200: 'a'}]}])
+ ));
+ });
+
+ it('testEqualsExtensionsUnconstructed', function() {
+ assertTrue(jspb.Message.compareFields([], [{}]));
+ assertTrue(jspb.Message.compareFields([,,, {}], []));
+ assertTrue(jspb.Message.compareFields([,,, {}], [,, {}]));
+ assertTrue(jspb.Message.compareFields(
+ ['hi', {100: [{200: 'a'}]}], ['hi', {100: [{200: 'a'}]}]));
+ assertFalse(jspb.Message.compareFields(
+ ['hi', {100: [{200: 'a'}]}], ['hi', {100: [{200: 'b'}]}]));
+ assertTrue(jspb.Message.compareFields(
+ [{100: [{200: 'a'}]}], [{100: [{200: 'a'}]}]));
+ assertTrue(jspb.Message.compareFields(
+ [{100: [{200: 'a'}]}], [,,, {100: [{200: 'a'}]}]));
+ assertTrue(jspb.Message.compareFields(
+ [,,, {100: [{200: 'a'}]}], [{100: [{200: 'a'}]}]));
+ assertTrue(jspb.Message.compareFields(
+ ['hi', {100: [{200: 'a'}]}], ['hi',,, {100: [{200: 'a'}]}]));
+ assertTrue(jspb.Message.compareFields(
+ ['hi',,, {100: [{200: 'a'}]}], ['hi', {100: [{200: 'a'}]}]));
+ });
+
+ it('testToMap', function() {
+ var p1 = new proto.jspb.test.Simple1(['k', ['v']]);
+ var p2 = new proto.jspb.test.Simple1(['k1', ['v1', 'v2']]);
+ var soymap = jspb.Message.toMap([p1, p2],
+ proto.jspb.test.Simple1.prototype.getAString,
+ proto.jspb.test.Simple1.prototype.toObject);
+ assertEquals('k', soymap['k'].aString);
+ assertArrayEquals(['v'], soymap['k'].aRepeatedStringList);
+ var protomap = jspb.Message.toMap([p1, p2],
+ proto.jspb.test.Simple1.prototype.getAString);
+ assertEquals('k', protomap['k'].getAString());
+ assertArrayEquals(['v'], protomap['k'].getARepeatedStringList());
+ });
+
+ it('testClone', function() {
+ var supportsUint8Array =
+ !goog.userAgent.IE || goog.userAgent.isVersionOrHigher('10');
+ var original = new proto.jspb.test.TestClone();
+ original.setStr('v1');
+ var simple1 = new proto.jspb.test.Simple1(['x1', ['y1', 'z1']]);
+ var simple2 = new proto.jspb.test.Simple1(['x2', ['y2', 'z2']]);
+ var simple3 = new proto.jspb.test.Simple1(['x3', ['y3', 'z3']]);
+ original.setSimple1(simple1);
+ original.setSimple2List([simple2, simple3]);
+ var bytes1 = supportsUint8Array ? new Uint8Array([1, 2, 3]) : '123';
+ original.setBytesField(bytes1);
+ var extension = new proto.jspb.test.CloneExtension();
+ extension.setExt('e1');
+ original.setExtension(proto.jspb.test.IsExtension.extField, extension);
+ var clone = original.cloneMessage();
+ assertArrayEquals(['v1',, ['x1', ['y1', 'z1']],,
+ [['x2', ['y2', 'z2']], ['x3', ['y3', 'z3']]], bytes1,, { 100: [, 'e1'] }],
+ clone.toArray());
+ clone.setStr('v2');
+ var simple4 = new proto.jspb.test.Simple1(['a1', ['b1', 'c1']]);
+ var simple5 = new proto.jspb.test.Simple1(['a2', ['b2', 'c2']]);
+ var simple6 = new proto.jspb.test.Simple1(['a3', ['b3', 'c3']]);
+ clone.setSimple1(simple4);
+ clone.setSimple2List([simple5, simple6]);
+ if (supportsUint8Array) {
+ clone.getBytesField()[0] = 4;
+ assertObjectEquals(bytes1, original.getBytesField());
+ }
+ var bytes2 = supportsUint8Array ? new Uint8Array([4, 5, 6]) : '456';
+ clone.setBytesField(bytes2);
+ var newExtension = new proto.jspb.test.CloneExtension();
+ newExtension.setExt('e2');
+ clone.setExtension(proto.jspb.test.CloneExtension.extField, newExtension);
+ assertArrayEquals(['v2',, ['a1', ['b1', 'c1']],,
+ [['a2', ['b2', 'c2']], ['a3', ['b3', 'c3']]], bytes2,, { 100: [, 'e2'] }],
+ clone.toArray());
+ assertArrayEquals(['v1',, ['x1', ['y1', 'z1']],,
+ [['x2', ['y2', 'z2']], ['x3', ['y3', 'z3']]], bytes1,, { 100: [, 'e1'] }],
+ original.toArray());
+ });
+
+ it('testCopyInto', function() {
+ var supportsUint8Array =
+ !goog.userAgent.IE || goog.userAgent.isVersionOrHigher('10');
+ var original = new proto.jspb.test.TestClone();
+ original.setStr('v1');
+ var dest = new proto.jspb.test.TestClone();
+ dest.setStr('override');
+ var simple1 = new proto.jspb.test.Simple1(['x1', ['y1', 'z1']]);
+ var simple2 = new proto.jspb.test.Simple1(['x2', ['y2', 'z2']]);
+ var simple3 = new proto.jspb.test.Simple1(['x3', ['y3', 'z3']]);
+ var destSimple1 = new proto.jspb.test.Simple1(['ox1', ['oy1', 'oz1']]);
+ var destSimple2 = new proto.jspb.test.Simple1(['ox2', ['oy2', 'oz2']]);
+ var destSimple3 = new proto.jspb.test.Simple1(['ox3', ['oy3', 'oz3']]);
+ original.setSimple1(simple1);
+ original.setSimple2List([simple2, simple3]);
+ dest.setSimple1(destSimple1);
+ dest.setSimple2List([destSimple2, destSimple3]);
+ var bytes1 = supportsUint8Array ? new Uint8Array([1, 2, 3]) : '123';
+ var bytes2 = supportsUint8Array ? new Uint8Array([4, 5, 6]) : '456';
+ original.setBytesField(bytes1);
+ dest.setBytesField(bytes2);
+ var extension = new proto.jspb.test.CloneExtension();
+ extension.setExt('e1');
+ original.setExtension(proto.jspb.test.CloneExtension.extField, extension);
+
+ jspb.Message.copyInto(original, dest);
+ assertArrayEquals(original.toArray(), dest.toArray());
+ assertEquals('x1', dest.getSimple1().getAString());
+ assertEquals('e1',
+ dest.getExtension(proto.jspb.test.CloneExtension.extField).getExt());
+ dest.getSimple1().setAString('new value');
+ assertNotEquals(dest.getSimple1().getAString(),
+ original.getSimple1().getAString());
+ if (supportsUint8Array) {
+ dest.getBytesField()[0] = 7;
+ assertObjectEquals(bytes1, original.getBytesField());
+ assertObjectEquals(new Uint8Array([7, 2, 3]), dest.getBytesField());
+ } else {
+ dest.setBytesField('789');
+ assertObjectEquals(bytes1, original.getBytesField());
+ assertObjectEquals('789', dest.getBytesField());
+ }
+ dest.getExtension(proto.jspb.test.CloneExtension.extField).
+ setExt('new value');
+ assertNotEquals(
+ dest.getExtension(proto.jspb.test.CloneExtension.extField).getExt(),
+ original.getExtension(
+ proto.jspb.test.CloneExtension.extField).getExt());
+ });
+
+ it('testCopyInto_notSameType', function() {
+ var a = new proto.jspb.test.TestClone();
+ var b = new proto.jspb.test.Simple1(['str', ['s1', 's2']]);
+
+ var e = assertThrows(function() {
+ jspb.Message.copyInto(a, b);
+ });
+ assertContains('should have the same type', e.message);
+ });
+
+ it('testExtensions', function() {
+ var extension1 = new proto.jspb.test.IsExtension(['ext1field']);
+ var extension2 = new proto.jspb.test.Simple1(['str', ['s1', 's2']]);
+ var extendable = new proto.jspb.test.HasExtensions(['v1', 'v2', 'v3']);
+ extendable.setExtension(proto.jspb.test.IsExtension.extField, extension1);
+ extendable.setExtension(proto.jspb.test.IndirectExtension.simple,
+ extension2);
+ extendable.setExtension(proto.jspb.test.IndirectExtension.str, 'xyzzy');
+ extendable.setExtension(proto.jspb.test.IndirectExtension.repeatedStrList,
+ ['a', 'b']);
+ var s1 = new proto.jspb.test.Simple1(['foo', ['s1', 's2']]);
+ var s2 = new proto.jspb.test.Simple1(['bar', ['t1', 't2']]);
+ extendable.setExtension(
+ proto.jspb.test.IndirectExtension.repeatedSimpleList,
+ [s1, s2]);
+ assertObjectEquals(extension1,
+ extendable.getExtension(proto.jspb.test.IsExtension.extField));
+ assertObjectEquals(extension2,
+ extendable.getExtension(proto.jspb.test.IndirectExtension.simple));
+ assertObjectEquals('xyzzy',
+ extendable.getExtension(proto.jspb.test.IndirectExtension.str));
+ assertObjectEquals(['a', 'b'], extendable.getExtension(
+ proto.jspb.test.IndirectExtension.repeatedStrList));
+ assertObjectEquals([s1, s2], extendable.getExtension(
+ proto.jspb.test.IndirectExtension.repeatedSimpleList));
+ // Not supported yet, but it should work...
+ extendable.setExtension(proto.jspb.test.IndirectExtension.simple, null);
+ assertNull(
+ extendable.getExtension(proto.jspb.test.IndirectExtension.simple));
+ extendable.setExtension(proto.jspb.test.IndirectExtension.str, null);
+ assertNull(extendable.getExtension(proto.jspb.test.IndirectExtension.str));
+
+
+ // Extension fields with jspb.ignore = true are ignored.
+ assertUndefined(proto.jspb.test.IndirectExtension['ignored']);
+ assertUndefined(proto.jspb.test.HasExtensions['ignoredFloating']);
+ });
+
+ it('testFloatingExtensions', function() {
+ // From an autogenerated container.
+ var extendable = new proto.jspb.test.HasExtensions(['v1', 'v2', 'v3']);
+ var extension = new proto.jspb.test.Simple1(['foo', ['s1', 's2']]);
+ extendable.setExtension(proto.jspb.test.simple1, extension);
+ assertObjectEquals(extension,
+ extendable.getExtension(proto.jspb.test.simple1));
+
+ // From _lib mode.
+ extension = new proto.jspb.test.ExtensionMessage(['s1']);
+ extendable = new proto.jspb.test.TestExtensionsMessage([16]);
+ extendable.setExtension(proto.jspb.test.floatingMsgField, extension);
+ extendable.setExtension(proto.jspb.test.floatingStrField, 's2');
+ assertObjectEquals(extension,
+ extendable.getExtension(proto.jspb.test.floatingMsgField));
+ assertObjectEquals('s2',
+ extendable.getExtension(proto.jspb.test.floatingStrField));
+ assertNotUndefined(proto.jspb.exttest.floatingMsgField);
+ assertNotUndefined(proto.jspb.exttest.floatingMsgFieldTwo);
+ assertNotUndefined(proto.jspb.exttest.beta.floatingStrField);
+ });
+
+ it('testToObject_extendedObject', function() {
+ var extension1 = new proto.jspb.test.IsExtension(['ext1field']);
+ var extension2 = new proto.jspb.test.Simple1(['str', ['s1', 's2'], true]);
+ var extendable = new proto.jspb.test.HasExtensions(['v1', 'v2', 'v3']);
+ extendable.setExtension(proto.jspb.test.IsExtension.extField, extension1);
+ extendable.setExtension(proto.jspb.test.IndirectExtension.simple,
+ extension2);
+ extendable.setExtension(proto.jspb.test.IndirectExtension.str, 'xyzzy');
+ extendable.setExtension(proto.jspb.test.IndirectExtension.repeatedStrList,
+ ['a', 'b']);
+ var s1 = new proto.jspb.test.Simple1(['foo', ['s1', 's2'], true]);
+ var s2 = new proto.jspb.test.Simple1(['bar', ['t1', 't2'], false]);
+ extendable.setExtension(
+ proto.jspb.test.IndirectExtension.repeatedSimpleList,
+ [s1, s2]);
+ assertObjectEquals({
+ str1: 'v1', str2: 'v2', str3: 'v3',
+ extField: { ext1: 'ext1field' },
+ simple: {
+ aString: 'str', aRepeatedStringList: ['s1', 's2'], aBoolean: true
+ },
+ str: 'xyzzy',
+ repeatedStrList: ['a', 'b'],
+ repeatedSimpleList: [
+ { aString: 'foo', aRepeatedStringList: ['s1', 's2'], aBoolean: true},
+ { aString: 'bar', aRepeatedStringList: ['t1', 't2'], aBoolean: false}
+ ]
+ }, extendable.toObject());
+
+ // Now, with instances included.
+ assertObjectEquals({
+ str1: 'v1', str2: 'v2', str3: 'v3',
+ extField: {
+ ext1: 'ext1field',
+ $jspbMessageInstance:
+ extendable.getExtension(proto.jspb.test.IsExtension.extField)
+ },
+ simple: {
+ aString: 'str',
+ aRepeatedStringList: ['s1', 's2'],
+ aBoolean: true,
+ $jspbMessageInstance:
+ extendable.getExtension(proto.jspb.test.IndirectExtension.simple)
+ },
+ str: 'xyzzy',
+ repeatedStrList: ['a', 'b'],
+ repeatedSimpleList: [{
+ aString: 'foo',
+ aRepeatedStringList: ['s1', 's2'],
+ aBoolean: true,
+ $jspbMessageInstance: s1
+ }, {
+ aString: 'bar',
+ aRepeatedStringList: ['t1', 't2'],
+ aBoolean: false,
+ $jspbMessageInstance: s2
+ }],
+ $jspbMessageInstance: extendable
+ }, extendable.toObject(true /* opt_includeInstance */));
+ });
+
+ it('testInitialization_emptyArray', function() {
+ var msg = new proto.jspb.test.HasExtensions([]);
+ if (jspb.Message.MINIMIZE_MEMORY_ALLOCATIONS) {
+ assertArrayEquals([], msg.toArray());
+ } else {
+ // Extension object is created past all regular fields.
+ assertArrayEquals([,,, {}], msg.toArray());
+ }
+ });
+
+ it('testInitialization_justExtensionObject', function() {
+ var msg = new proto.jspb.test.Empty([{1: 'hi'}]);
+ // The extensionObject is not moved from its original location.
+ assertArrayEquals([{1: 'hi'}], msg.toArray());
+ });
+
+ it('testInitialization_incompleteList', function() {
+ var msg = new proto.jspb.test.Empty([1, {4: 'hi'}]);
+ // The extensionObject is not moved from its original location.
+ assertArrayEquals([1, {4: 'hi'}], msg.toArray());
+ });
+
+ it('testInitialization_forwardCompatible', function() {
+ var msg = new proto.jspb.test.Empty([1, 2, 3, {1: 'hi'}]);
+ assertArrayEquals([1, 2, 3, {1: 'hi'}], msg.toArray());
+ });
+
+ it('testExtendedMessageEnsureObject', function() {
+ var data = new proto.jspb.test.HasExtensions(['str1',
+ {'a_key': 'an_object'}]);
+ assertEquals('an_object', data.extensionObject_['a_key']);
+ });
+
+ it('testToObject_hasExtensionField', function() {
+ var data = new proto.jspb.test.HasExtensions(['str1', {100: ['ext1']}]);
+ var obj = data.toObject();
+ assertEquals('str1', obj.str1);
+ assertEquals('ext1', obj.extField.ext1);
+ });
+
+ it('testGetExtension', function() {
+ var data = new proto.jspb.test.HasExtensions(['str1', {100: ['ext1']}]);
+ assertEquals('str1', data.getStr1());
+ var extension = data.getExtension(proto.jspb.test.IsExtension.extField);
+ assertNotNull(extension);
+ assertEquals('ext1', extension.getExt1());
+ });
+
+ it('testSetExtension', function() {
+ var data = new proto.jspb.test.HasExtensions();
+ var extensionMessage = new proto.jspb.test.IsExtension(['is_extension']);
+ data.setExtension(proto.jspb.test.IsExtension.extField, extensionMessage);
+ var obj = data.toObject();
+ assertNotNull(
+ data.getExtension(proto.jspb.test.IsExtension.extField));
+ assertEquals('is_extension', obj.extField.ext1);
+ });
+
+ /**
+ * Note that group is long deprecated, we only support it because JsPb has
+ * a goal of being able to generate JS classes for all proto descriptors.
+ */
+ it('testGroups', function() {
+ var group = new proto.jspb.test.TestGroup();
+ var someGroup = new proto.jspb.test.TestGroup.RepeatedGroup();
+ someGroup.setId('g1');
+ someGroup.setSomeBoolList([true, false]);
+ group.setRepeatedGroupList([someGroup]);
+ var groups = group.getRepeatedGroupList();
+ assertEquals('g1', groups[0].getId());
+ assertObjectEquals([true, false], groups[0].getSomeBoolList());
+ assertObjectEquals({id: 'g1', someBoolList: [true, false]},
+ groups[0].toObject());
+ assertObjectEquals({
+ repeatedGroupList: [{id: 'g1', someBoolList: [true, false]}],
+ requiredGroup: {id: undefined},
+ optionalGroup: undefined,
+ requiredSimple: {aRepeatedStringList: [], aString: undefined},
+ optionalSimple: undefined,
+ id: undefined
+ }, group.toObject());
+ var group1 = new proto.jspb.test.TestGroup1();
+ group1.setGroup(someGroup);
+ assertEquals(someGroup, group1.getGroup());
+ });
+
+ it('testNonExtensionFieldsAfterExtensionRange', function() {
+ var data = [{'1': 'a_string'}];
+ var message = new proto.jspb.test.Complex(data);
+ assertArrayEquals([], message.getARepeatedStringList());
+ });
+
+ it('testReservedGetterNames', function() {
+ var message = new proto.jspb.test.TestReservedNames();
+ message.setExtension$(11);
+ message.setExtension(proto.jspb.test.TestReservedNamesExtension.foo, 12);
+ assertEquals(11, message.getExtension$());
+ assertEquals(12, message.getExtension(
+ proto.jspb.test.TestReservedNamesExtension.foo));
+ assertObjectEquals({extension: 11, foo: 12}, message.toObject());
+ });
+
+ it('testInitializeMessageWithUnsetOneof', function() {
+ var message = new proto.jspb.test.TestMessageWithOneof([]);
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.PartialOneofCase.
+ PARTIAL_ONEOF_NOT_SET,
+ message.getPartialOneofCase());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.RecursiveOneofCase.
+ RECURSIVE_ONEOF_NOT_SET,
+ message.getRecursiveOneofCase());
+ });
+
+ it('testInitializeMessageWithSingleValueSetInOneof', function() {
+ var message = new proto.jspb.test.TestMessageWithOneof([,, 'x']);
+
+ assertEquals('x', message.getPone());
+ assertEquals('', message.getPthree());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.PartialOneofCase.PONE,
+ message.getPartialOneofCase());
+ });
+
+ it('testKeepsLastWireValueSetInUnion_multipleValues', function() {
+ var message = new proto.jspb.test.TestMessageWithOneof([,, 'x',, 'y']);
+
+ assertEquals('', message.getPone());
+ assertEquals('y', message.getPthree());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.PartialOneofCase.PTHREE,
+ message.getPartialOneofCase());
+ });
+
+ it('testSettingOneofFieldClearsOthers', function() {
+ var message = new proto.jspb.test.TestMessageWithOneof;
+ assertEquals('', message.getPone());
+ assertEquals('', message.getPthree());
+ assertFalse(message.hasPone());
+ assertFalse(message.hasPthree());
+
+ message.setPone('hi');
+ assertEquals('hi', message.getPone());
+ assertEquals('', message.getPthree());
+ assertTrue(message.hasPone());
+ assertFalse(message.hasPthree());
+
+ message.setPthree('bye');
+ assertEquals('', message.getPone());
+ assertEquals('bye', message.getPthree());
+ assertFalse(message.hasPone());
+ assertTrue(message.hasPthree());
+ });
+
+ it('testSettingOneofFieldDoesNotClearFieldsFromOtherUnions', function() {
+ var other = new proto.jspb.test.TestMessageWithOneof;
+ var message = new proto.jspb.test.TestMessageWithOneof;
+ assertEquals('', message.getPone());
+ assertEquals('', message.getPthree());
+ assertUndefined(message.getRone());
+ assertFalse(message.hasPone());
+ assertFalse(message.hasPthree());
+
+ message.setPone('hi');
+ message.setRone(other);
+ assertEquals('hi', message.getPone());
+ assertEquals('', message.getPthree());
+ assertEquals(other, message.getRone());
+ assertTrue(message.hasPone());
+ assertFalse(message.hasPthree());
+
+ message.setPthree('bye');
+ assertEquals('', message.getPone());
+ assertEquals('bye', message.getPthree());
+ assertEquals(other, message.getRone());
+ assertFalse(message.hasPone());
+ assertTrue(message.hasPthree());
+ });
+
+ it('testUnsetsOneofCaseWhenFieldIsCleared', function() {
+ var message = new proto.jspb.test.TestMessageWithOneof;
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.PartialOneofCase.
+ PARTIAL_ONEOF_NOT_SET,
+ message.getPartialOneofCase());
+
+ message.setPone('hi');
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.PartialOneofCase.PONE,
+ message.getPartialOneofCase());
+
+ message.clearPone();
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.PartialOneofCase.
+ PARTIAL_ONEOF_NOT_SET,
+ message.getPartialOneofCase());
+ });
+
+ it('testMessageWithDefaultOneofValues', function() {
+ var message = new proto.jspb.test.TestMessageWithOneof;
+ assertEquals(1234, message.getAone());
+ assertEquals(0, message.getAtwo());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.DefaultOneofACase
+ .DEFAULT_ONEOF_A_NOT_SET,
+ message.getDefaultOneofACase());
+
+ message.setAone(567);
+ assertEquals(567, message.getAone());
+ assertEquals(0, message.getAtwo());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.DefaultOneofACase.AONE,
+ message.getDefaultOneofACase());
+
+ message.setAtwo(890);
+ assertEquals(1234, message.getAone());
+ assertEquals(890, message.getAtwo());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.DefaultOneofACase.ATWO,
+ message.getDefaultOneofACase());
+
+ message.clearAtwo();
+ assertEquals(1234, message.getAone());
+ assertEquals(0, message.getAtwo());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.DefaultOneofACase
+ .DEFAULT_ONEOF_A_NOT_SET,
+ message.getDefaultOneofACase());
+ });
+
+ it('testMessageWithDefaultOneofValues_defaultNotOnFirstField', function() {
+ var message = new proto.jspb.test.TestMessageWithOneof;
+ assertEquals(0, message.getBone());
+ assertEquals(1234, message.getBtwo());
+ assertFalse(message.hasBone());
+ assertFalse(message.hasBtwo());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.DefaultOneofBCase
+ .DEFAULT_ONEOF_B_NOT_SET,
+ message.getDefaultOneofBCase());
+
+ message.setBone(2);
+ assertEquals(2, message.getBone());
+ assertEquals(1234, message.getBtwo());
+ assertTrue(message.hasBone());
+ assertFalse(message.hasBtwo());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.DefaultOneofBCase.BONE,
+ message.getDefaultOneofBCase());
+
+ message.setBtwo(3);
+ assertEquals(0, message.getBone());
+ assertFalse(message.hasBone());
+ assertTrue(message.hasBtwo());
+ assertEquals(3, message.getBtwo());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.DefaultOneofBCase.BTWO,
+ message.getDefaultOneofBCase());
+
+ message.clearBtwo();
+ assertEquals(0, message.getBone());
+ assertFalse(message.hasBone());
+ assertFalse(message.hasBtwo());
+ assertEquals(1234, message.getBtwo());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.DefaultOneofBCase
+ .DEFAULT_ONEOF_B_NOT_SET,
+ message.getDefaultOneofBCase());
+ });
+
+ it('testInitializeMessageWithOneofDefaults', function() {
+ var message =
+ new proto.jspb.test.TestMessageWithOneof(new Array(9).concat(567));
+ assertEquals(567, message.getAone());
+ assertEquals(0, message.getAtwo());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.DefaultOneofACase.AONE,
+ message.getDefaultOneofACase());
+
+ message =
+ new proto.jspb.test.TestMessageWithOneof(new Array(10).concat(890));
+ assertEquals(1234, message.getAone());
+ assertEquals(890, message.getAtwo());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.DefaultOneofACase.ATWO,
+ message.getDefaultOneofACase());
+
+ message =
+ new proto.jspb.test.TestMessageWithOneof(new Array(9).concat(567, 890));
+ assertEquals(1234, message.getAone());
+ assertEquals(890, message.getAtwo());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.DefaultOneofACase.ATWO,
+ message.getDefaultOneofACase());
+ });
+
+ it('testInitializeMessageWithOneofDefaults_defaultNotSetOnFirstField',
+ function() {
+ var message;
+
+ message =
+ new proto.jspb.test.TestMessageWithOneof(new Array(11).concat(567));
+ assertEquals(567, message.getBone());
+ assertEquals(1234, message.getBtwo());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.DefaultOneofBCase.BONE,
+ message.getDefaultOneofBCase());
+
+ message =
+ new proto.jspb.test.TestMessageWithOneof(new Array(12).concat(890));
+ assertEquals(0, message.getBone());
+ assertEquals(890, message.getBtwo());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.DefaultOneofBCase.BTWO,
+ message.getDefaultOneofBCase());
+
+ message = new proto.jspb.test.TestMessageWithOneof(
+ new Array(11).concat(567, 890));
+ assertEquals(0, message.getBone());
+ assertEquals(890, message.getBtwo());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.DefaultOneofBCase.BTWO,
+ message.getDefaultOneofBCase());
+ });
+
+ it('testOneofContainingAnotherMessage', function() {
+ var message = new proto.jspb.test.TestMessageWithOneof;
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.RecursiveOneofCase.
+ RECURSIVE_ONEOF_NOT_SET,
+ message.getRecursiveOneofCase());
+
+ var other = new proto.jspb.test.TestMessageWithOneof;
+ message.setRone(other);
+ assertEquals(other, message.getRone());
+ assertEquals('', message.getRtwo());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.RecursiveOneofCase.RONE,
+ message.getRecursiveOneofCase());
+
+ message.setRtwo('hi');
+ assertUndefined(message.getRone());
+ assertEquals('hi', message.getRtwo());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.RecursiveOneofCase.RTWO,
+ message.getRecursiveOneofCase());
+ });
+
+ it('testQueryingOneofCaseEnsuresOnlyOneFieldIsSetInUnderlyingArray',
+ function() {
+ var message = new proto.jspb.test.TestMessageWithOneof;
+ message.setPone('x');
+ assertEquals('x', message.getPone());
+ assertEquals('', message.getPthree());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.PartialOneofCase.PONE,
+ message.getPartialOneofCase());
+
+ var array = message.toArray();
+ assertEquals('x', array[2]);
+ assertUndefined(array[4]);
+ array[4] = 'y';
+
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.PartialOneofCase.PTHREE,
+ message.getPartialOneofCase());
+ assertUndefined(array[2]);
+ assertEquals('y', array[4]);
+ });
+
+ it('testFloatingPointFieldsSupportNan', function() {
+ var assertNan = function(x) {
+ assertTrue('Expected ' + x + ' (' + goog.typeOf(x) + ') to be NaN.',
+ goog.isNumber(x) && isNaN(x));
+ };
+
+ var message = new proto.jspb.test.FloatingPointFields([
+ 'NaN', 'NaN', ['NaN', 'NaN'], 'NaN',
+ 'NaN', 'NaN', ['NaN', 'NaN'], 'NaN'
+ ]);
+ assertNan(message.getOptionalFloatField());
+ assertNan(message.getRequiredFloatField());
+ assertNan(message.getRepeatedFloatFieldList()[0]);
+ assertNan(message.getRepeatedFloatFieldList()[1]);
+ assertNan(message.getDefaultFloatField());
+ assertNan(message.getOptionalDoubleField());
+ assertNan(message.getRequiredDoubleField());
+ assertNan(message.getRepeatedDoubleFieldList()[0]);
+ assertNan(message.getRepeatedDoubleFieldList()[1]);
+ assertNan(message.getDefaultDoubleField());
+ });
+
+});
diff --git a/js/compatibility_tests/v3.0.0/proto3_test.js b/js/compatibility_tests/v3.0.0/proto3_test.js
new file mode 100644
index 00000000..fab0fd44
--- /dev/null
+++ b/js/compatibility_tests/v3.0.0/proto3_test.js
@@ -0,0 +1,329 @@
+// 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.
+
+goog.require('goog.crypt.base64');
+goog.require('goog.testing.asserts');
+
+// CommonJS-LoadFromFile: testbinary_pb proto.jspb.test
+goog.require('proto.jspb.test.ForeignMessage');
+
+// CommonJS-LoadFromFile: proto3_test_pb proto.jspb.test
+goog.require('proto.jspb.test.Proto3Enum');
+goog.require('proto.jspb.test.TestProto3');
+
+
+var BYTES = new Uint8Array([1, 2, 8, 9]);
+var BYTES_B64 = goog.crypt.base64.encodeByteArray(BYTES);
+
+
+/**
+ * Helper: compare a bytes field to an expected value
+ * @param {Uint8Array|string} arr
+ * @param {Uint8Array} expected
+ * @return {boolean}
+ */
+function bytesCompare(arr, expected) {
+ if (goog.isString(arr)) {
+ arr = goog.crypt.base64.decodeStringToUint8Array(arr);
+ }
+ if (arr.length != expected.length) {
+ return false;
+ }
+ for (var i = 0; i < arr.length; i++) {
+ if (arr[i] != expected[i]) {
+ return false;
+ }
+ }
+ return true;
+}
+
+
+describe('proto3Test', function() {
+ /**
+ * Test defaults for proto3 message fields.
+ */
+ it('testProto3FieldDefaults', function() {
+ var msg = new proto.jspb.test.TestProto3();
+
+ assertEquals(msg.getOptionalInt32(), 0);
+ assertEquals(msg.getOptionalInt64(), 0);
+ assertEquals(msg.getOptionalUint32(), 0);
+ assertEquals(msg.getOptionalUint64(), 0);
+ assertEquals(msg.getOptionalSint32(), 0);
+ assertEquals(msg.getOptionalSint64(), 0);
+ assertEquals(msg.getOptionalFixed32(), 0);
+ assertEquals(msg.getOptionalFixed64(), 0);
+ assertEquals(msg.getOptionalSfixed32(), 0);
+ assertEquals(msg.getOptionalSfixed64(), 0);
+ assertEquals(msg.getOptionalFloat(), 0);
+ assertEquals(msg.getOptionalDouble(), 0);
+ assertEquals(msg.getOptionalString(), '');
+
+ // TODO(b/26173701): when we change bytes fields default getter to return
+ // Uint8Array, we'll want to switch this assertion to match the u8 case.
+ assertEquals(typeof msg.getOptionalBytes(), 'string');
+ assertEquals(msg.getOptionalBytes_asU8() instanceof Uint8Array, true);
+ assertEquals(typeof msg.getOptionalBytes_asB64(), 'string');
+ assertEquals(msg.getOptionalBytes().length, 0);
+ assertEquals(msg.getOptionalBytes_asU8().length, 0);
+ assertEquals(msg.getOptionalBytes_asB64(), '');
+
+ assertEquals(msg.getOptionalForeignEnum(),
+ proto.jspb.test.Proto3Enum.PROTO3_FOO);
+ assertEquals(msg.getOptionalForeignMessage(), undefined);
+ assertEquals(msg.getOptionalForeignMessage(), undefined);
+
+ assertEquals(msg.getRepeatedInt32List().length, 0);
+ assertEquals(msg.getRepeatedInt64List().length, 0);
+ assertEquals(msg.getRepeatedUint32List().length, 0);
+ assertEquals(msg.getRepeatedUint64List().length, 0);
+ assertEquals(msg.getRepeatedSint32List().length, 0);
+ assertEquals(msg.getRepeatedSint64List().length, 0);
+ assertEquals(msg.getRepeatedFixed32List().length, 0);
+ assertEquals(msg.getRepeatedFixed64List().length, 0);
+ assertEquals(msg.getRepeatedSfixed32List().length, 0);
+ assertEquals(msg.getRepeatedSfixed64List().length, 0);
+ assertEquals(msg.getRepeatedFloatList().length, 0);
+ assertEquals(msg.getRepeatedDoubleList().length, 0);
+ assertEquals(msg.getRepeatedStringList().length, 0);
+ assertEquals(msg.getRepeatedBytesList().length, 0);
+ assertEquals(msg.getRepeatedForeignEnumList().length, 0);
+ assertEquals(msg.getRepeatedForeignMessageList().length, 0);
+
+ });
+
+
+ /**
+ * Test that all fields can be set and read via a serialization roundtrip.
+ */
+ it('testProto3FieldSetGet', function() {
+ var msg = new proto.jspb.test.TestProto3();
+
+ msg.setOptionalInt32(-42);
+ msg.setOptionalInt64(-0x7fffffff00000000);
+ msg.setOptionalUint32(0x80000000);
+ msg.setOptionalUint64(0xf000000000000000);
+ msg.setOptionalSint32(-100);
+ msg.setOptionalSint64(-0x8000000000000000);
+ msg.setOptionalFixed32(1234);
+ msg.setOptionalFixed64(0x1234567800000000);
+ msg.setOptionalSfixed32(-1234);
+ msg.setOptionalSfixed64(-0x1234567800000000);
+ msg.setOptionalFloat(1.5);
+ msg.setOptionalDouble(-1.5);
+ msg.setOptionalBool(true);
+ msg.setOptionalString('hello world');
+ msg.setOptionalBytes(BYTES);
+ var submsg = new proto.jspb.test.ForeignMessage();
+ submsg.setC(16);
+ msg.setOptionalForeignMessage(submsg);
+ msg.setOptionalForeignEnum(proto.jspb.test.Proto3Enum.PROTO3_BAR);
+
+ msg.setRepeatedInt32List([-42]);
+ msg.setRepeatedInt64List([-0x7fffffff00000000]);
+ msg.setRepeatedUint32List([0x80000000]);
+ msg.setRepeatedUint64List([0xf000000000000000]);
+ msg.setRepeatedSint32List([-100]);
+ msg.setRepeatedSint64List([-0x8000000000000000]);
+ msg.setRepeatedFixed32List([1234]);
+ msg.setRepeatedFixed64List([0x1234567800000000]);
+ msg.setRepeatedSfixed32List([-1234]);
+ msg.setRepeatedSfixed64List([-0x1234567800000000]);
+ msg.setRepeatedFloatList([1.5]);
+ msg.setRepeatedDoubleList([-1.5]);
+ msg.setRepeatedBoolList([true]);
+ msg.setRepeatedStringList(['hello world']);
+ msg.setRepeatedBytesList([BYTES]);
+ submsg = new proto.jspb.test.ForeignMessage();
+ submsg.setC(1000);
+ msg.setRepeatedForeignMessageList([submsg]);
+ msg.setRepeatedForeignEnumList([proto.jspb.test.Proto3Enum.PROTO3_BAR]);
+
+ msg.setOneofString('asdf');
+
+ var serialized = msg.serializeBinary();
+ msg = proto.jspb.test.TestProto3.deserializeBinary(serialized);
+
+ assertEquals(msg.getOptionalInt32(), -42);
+ assertEquals(msg.getOptionalInt64(), -0x7fffffff00000000);
+ assertEquals(msg.getOptionalUint32(), 0x80000000);
+ assertEquals(msg.getOptionalUint64(), 0xf000000000000000);
+ assertEquals(msg.getOptionalSint32(), -100);
+ assertEquals(msg.getOptionalSint64(), -0x8000000000000000);
+ assertEquals(msg.getOptionalFixed32(), 1234);
+ assertEquals(msg.getOptionalFixed64(), 0x1234567800000000);
+ assertEquals(msg.getOptionalSfixed32(), -1234);
+ assertEquals(msg.getOptionalSfixed64(), -0x1234567800000000);
+ assertEquals(msg.getOptionalFloat(), 1.5);
+ assertEquals(msg.getOptionalDouble(), -1.5);
+ assertEquals(msg.getOptionalBool(), true);
+ assertEquals(msg.getOptionalString(), 'hello world');
+ assertEquals(true, bytesCompare(msg.getOptionalBytes(), BYTES));
+ assertEquals(msg.getOptionalForeignMessage().getC(), 16);
+ assertEquals(msg.getOptionalForeignEnum(),
+ proto.jspb.test.Proto3Enum.PROTO3_BAR);
+
+ assertElementsEquals(msg.getRepeatedInt32List(), [-42]);
+ assertElementsEquals(msg.getRepeatedInt64List(), [-0x7fffffff00000000]);
+ assertElementsEquals(msg.getRepeatedUint32List(), [0x80000000]);
+ assertElementsEquals(msg.getRepeatedUint64List(), [0xf000000000000000]);
+ assertElementsEquals(msg.getRepeatedSint32List(), [-100]);
+ assertElementsEquals(msg.getRepeatedSint64List(), [-0x8000000000000000]);
+ assertElementsEquals(msg.getRepeatedFixed32List(), [1234]);
+ assertElementsEquals(msg.getRepeatedFixed64List(), [0x1234567800000000]);
+ assertElementsEquals(msg.getRepeatedSfixed32List(), [-1234]);
+ assertElementsEquals(msg.getRepeatedSfixed64List(), [-0x1234567800000000]);
+ assertElementsEquals(msg.getRepeatedFloatList(), [1.5]);
+ assertElementsEquals(msg.getRepeatedDoubleList(), [-1.5]);
+ assertElementsEquals(msg.getRepeatedBoolList(), [true]);
+ assertElementsEquals(msg.getRepeatedStringList(), ['hello world']);
+ assertEquals(msg.getRepeatedBytesList().length, 1);
+ assertEquals(true, bytesCompare(msg.getRepeatedBytesList()[0], BYTES));
+ assertEquals(msg.getRepeatedForeignMessageList().length, 1);
+ assertEquals(msg.getRepeatedForeignMessageList()[0].getC(), 1000);
+ assertElementsEquals(msg.getRepeatedForeignEnumList(),
+ [proto.jspb.test.Proto3Enum.PROTO3_BAR]);
+
+ assertEquals(msg.getOneofString(), 'asdf');
+ });
+
+
+ /**
+ * Test that oneofs continue to have a notion of field presence.
+ */
+ it('testOneofs', function() {
+ var msg = new proto.jspb.test.TestProto3();
+
+ assertEquals(msg.getOneofUint32(), 0);
+ assertEquals(msg.getOneofForeignMessage(), undefined);
+ assertEquals(msg.getOneofString(), '');
+ assertEquals(msg.getOneofBytes(), '');
+ assertFalse(msg.hasOneofUint32());
+ assertFalse(msg.hasOneofString());
+ assertFalse(msg.hasOneofBytes());
+
+ msg.setOneofUint32(42);
+ assertEquals(msg.getOneofUint32(), 42);
+ assertEquals(msg.getOneofForeignMessage(), undefined);
+ assertEquals(msg.getOneofString(), '');
+ assertEquals(msg.getOneofBytes(), '');
+ assertTrue(msg.hasOneofUint32());
+ assertFalse(msg.hasOneofString());
+ assertFalse(msg.hasOneofBytes());
+
+
+ var submsg = new proto.jspb.test.ForeignMessage();
+ msg.setOneofForeignMessage(submsg);
+ assertEquals(msg.getOneofUint32(), 0);
+ assertEquals(msg.getOneofForeignMessage(), submsg);
+ assertEquals(msg.getOneofString(), '');
+ assertEquals(msg.getOneofBytes(), '');
+ assertFalse(msg.hasOneofUint32());
+ assertFalse(msg.hasOneofString());
+ assertFalse(msg.hasOneofBytes());
+
+ msg.setOneofString('hello');
+ assertEquals(msg.getOneofUint32(), 0);
+ assertEquals(msg.getOneofForeignMessage(), undefined);
+ assertEquals(msg.getOneofString(), 'hello');
+ assertEquals(msg.getOneofBytes(), '');
+ assertFalse(msg.hasOneofUint32());
+ assertTrue(msg.hasOneofString());
+ assertFalse(msg.hasOneofBytes());
+
+ msg.setOneofBytes(goog.crypt.base64.encodeString('\u00FF\u00FF'));
+ assertEquals(msg.getOneofUint32(), 0);
+ assertEquals(msg.getOneofForeignMessage(), undefined);
+ assertEquals(msg.getOneofString(), '');
+ assertEquals(msg.getOneofBytes_asB64(),
+ goog.crypt.base64.encodeString('\u00FF\u00FF'));
+ assertFalse(msg.hasOneofUint32());
+ assertFalse(msg.hasOneofString());
+ assertTrue(msg.hasOneofBytes());
+ });
+
+
+ /**
+ * Test that "default"-valued primitive fields are not emitted on the wire.
+ */
+ it('testNoSerializeDefaults', function() {
+ var msg = new proto.jspb.test.TestProto3();
+
+ // Set each primitive to a non-default value, then back to its default, to
+ // ensure that the serialization is actually checking the value and not just
+ // whether it has ever been set.
+ msg.setOptionalInt32(42);
+ msg.setOptionalInt32(0);
+ msg.setOptionalDouble(3.14);
+ msg.setOptionalDouble(0.0);
+ msg.setOptionalBool(true);
+ msg.setOptionalBool(false);
+ msg.setOptionalString('hello world');
+ msg.setOptionalString('');
+ msg.setOptionalBytes(goog.crypt.base64.encodeString('\u00FF\u00FF'));
+ msg.setOptionalBytes('');
+ msg.setOptionalForeignMessage(new proto.jspb.test.ForeignMessage());
+ msg.setOptionalForeignMessage(null);
+ msg.setOptionalForeignEnum(proto.jspb.test.Proto3Enum.PROTO3_BAR);
+ msg.setOptionalForeignEnum(proto.jspb.test.Proto3Enum.PROTO3_FOO);
+ msg.setOneofUint32(32);
+ msg.setOneofUint32(null);
+
+
+ var serialized = msg.serializeBinary();
+ assertEquals(0, serialized.length);
+ });
+
+ /**
+ * Test that base64 string and Uint8Array are interchangeable in bytes fields.
+ */
+ it('testBytesFieldsInterop', function() {
+ var msg = new proto.jspb.test.TestProto3();
+ // Set as a base64 string and check all the getters work.
+ msg.setOptionalBytes(BYTES_B64);
+ assertTrue(bytesCompare(msg.getOptionalBytes_asU8(), BYTES));
+ assertTrue(bytesCompare(msg.getOptionalBytes_asB64(), BYTES));
+ assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
+
+ // Test binary serialize round trip doesn't break it.
+ msg = proto.jspb.test.TestProto3.deserializeBinary(msg.serializeBinary());
+ assertTrue(bytesCompare(msg.getOptionalBytes_asU8(), BYTES));
+ assertTrue(bytesCompare(msg.getOptionalBytes_asB64(), BYTES));
+ assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
+
+ msg = new proto.jspb.test.TestProto3();
+ // Set as a Uint8Array and check all the getters work.
+ msg.setOptionalBytes(BYTES);
+ assertTrue(bytesCompare(msg.getOptionalBytes_asU8(), BYTES));
+ assertTrue(bytesCompare(msg.getOptionalBytes_asB64(), BYTES));
+ assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
+
+ });
+});
diff --git a/js/compatibility_tests/v3.0.0/proto3_test.proto b/js/compatibility_tests/v3.0.0/proto3_test.proto
new file mode 100644
index 00000000..acb67164
--- /dev/null
+++ b/js/compatibility_tests/v3.0.0/proto3_test.proto
@@ -0,0 +1,89 @@
+// 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.
+
+syntax = "proto3";
+
+import "testbinary.proto";
+
+package jspb.test;
+
+message TestProto3 {
+ int32 optional_int32 = 1;
+ int64 optional_int64 = 2;
+ uint32 optional_uint32 = 3;
+ uint64 optional_uint64 = 4;
+ sint32 optional_sint32 = 5;
+ sint64 optional_sint64 = 6;
+ fixed32 optional_fixed32 = 7;
+ fixed64 optional_fixed64 = 8;
+ sfixed32 optional_sfixed32 = 9;
+ sfixed64 optional_sfixed64 = 10;
+ float optional_float = 11;
+ double optional_double = 12;
+ bool optional_bool = 13;
+ string optional_string = 14;
+ bytes optional_bytes = 15;
+
+ ForeignMessage optional_foreign_message = 19;
+ Proto3Enum optional_foreign_enum = 22;
+
+ 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 ForeignMessage repeated_foreign_message = 49;
+ repeated Proto3Enum repeated_foreign_enum = 52;
+
+
+ oneof oneof_field {
+ uint32 oneof_uint32 = 111;
+ ForeignMessage oneof_foreign_message = 112;
+ string oneof_string = 113;
+ bytes oneof_bytes = 114;
+ }
+}
+
+enum Proto3Enum {
+ PROTO3_FOO = 0;
+ PROTO3_BAR = 1;
+ PROTO3_BAZ = 2;
+}
diff --git a/js/compatibility_tests/v3.0.0/test.proto b/js/compatibility_tests/v3.0.0/test.proto
new file mode 100644
index 00000000..937ffb89
--- /dev/null
+++ b/js/compatibility_tests/v3.0.0/test.proto
@@ -0,0 +1,236 @@
+// 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: mwr@google.com (Mark Rawling)
+
+syntax = "proto2";
+
+option java_package = "com.google.apps.jspb.proto";
+option java_multiple_files = true;
+
+import "google/protobuf/descriptor.proto";
+
+package jspb.test;
+
+message Empty {
+}
+
+enum OuterEnum {
+ FOO = 1;
+ BAR = 2;
+}
+
+message EnumContainer {
+ optional OuterEnum outer_enum = 1;
+}
+
+message Simple1 {
+ required string a_string = 1;
+ repeated string a_repeated_string = 2;
+ optional bool a_boolean = 3;
+}
+
+// A message that differs from Simple1 only by name
+message Simple2 {
+ required string a_string = 1;
+ repeated string a_repeated_string = 2;
+}
+
+message SpecialCases {
+ required string normal = 1;
+ // Examples of Js reserved names that are converted to pb_<name>.
+ required string default = 2;
+ required string function = 3;
+ required string var = 4;
+}
+
+message OptionalFields {
+ message Nested {
+ optional int32 an_int = 1;
+ }
+ optional string a_string = 1;
+ required bool a_bool = 2;
+ optional Nested a_nested_message = 3;
+ repeated Nested a_repeated_message = 4;
+ repeated string a_repeated_string = 5;
+}
+
+message HasExtensions {
+ optional string str1 = 1;
+ optional string str2 = 2;
+ optional string str3 = 3;
+ extensions 10 to max;
+}
+
+message Complex {
+ message Nested {
+ required int32 an_int = 2;
+ }
+ required string a_string = 1;
+ required bool an_out_of_order_bool = 9;
+ optional Nested a_nested_message = 4;
+ repeated Nested a_repeated_message = 5;
+ repeated string a_repeated_string = 7;
+}
+
+message OuterMessage {
+ // Make sure this doesn't conflict with the other Complex message.
+ message Complex {
+ optional int32 inner_complex_field = 1;
+ }
+}
+
+message IsExtension {
+ extend HasExtensions {
+ optional IsExtension ext_field = 100;
+ }
+ optional string ext1 = 1;
+
+ // Extensions of proto2 Descriptor messages will be ignored.
+ extend google.protobuf.EnumOptions {
+ optional string simple_option = 42113038;
+ }
+}
+
+message IndirectExtension {
+ extend HasExtensions {
+ optional Simple1 simple = 101;
+ optional string str = 102;
+ repeated string repeated_str = 103;
+ repeated Simple1 repeated_simple = 104;
+ }
+}
+
+extend HasExtensions {
+ optional Simple1 simple1 = 105;
+}
+
+message DefaultValues {
+ enum Enum {
+ E1 = 13;
+ E2 = 77;
+ }
+ optional string string_field = 1 [default="default<>\'\"abc"];
+ optional bool bool_field = 2 [default=true];
+ optional int64 int_field = 3 [default=11];
+ optional Enum enum_field = 4 [default=E1];
+ optional string empty_field = 6 [default=""];
+ optional bytes bytes_field = 8 [default="moo"]; // Base64 encoding is "bW9v"
+}
+
+message FloatingPointFields {
+ optional float optional_float_field = 1;
+ required float required_float_field = 2;
+ repeated float repeated_float_field = 3;
+ optional float default_float_field = 4 [default = 2.0];
+ optional double optional_double_field = 5;
+ required double required_double_field = 6;
+ repeated double repeated_double_field = 7;
+ optional double default_double_field = 8 [default = 2.0];
+}
+
+message TestClone {
+ optional string str = 1;
+ optional Simple1 simple1 = 3;
+ repeated Simple1 simple2 = 5;
+ optional bytes bytes_field = 6;
+ optional string unused = 7;
+ extensions 10 to max;
+}
+
+message CloneExtension {
+ extend TestClone {
+ optional CloneExtension ext_field = 100;
+ }
+ optional string ext = 2;
+}
+
+message TestGroup {
+ repeated group RepeatedGroup = 1 {
+ required string id = 1;
+ repeated bool some_bool = 2;
+ }
+ required group RequiredGroup = 2 {
+ required string id = 1;
+ }
+ optional group OptionalGroup = 3 {
+ required string id = 1;
+ }
+ optional string id = 4;
+ required Simple2 required_simple = 5;
+ optional Simple2 optional_simple = 6;
+}
+
+message TestGroup1 {
+ optional TestGroup.RepeatedGroup group = 1;
+}
+
+message TestReservedNames {
+ optional int32 extension = 1;
+ extensions 10 to max;
+}
+
+message TestReservedNamesExtension {
+ extend TestReservedNames {
+ optional int32 foo = 10;
+ }
+}
+
+message TestMessageWithOneof {
+
+ oneof partial_oneof {
+ string pone = 3;
+ string pthree = 5;
+ }
+
+ oneof recursive_oneof {
+ TestMessageWithOneof rone = 6;
+ string rtwo = 7;
+ }
+
+ optional bool normal_field = 8;
+ repeated string repeated_field = 9;
+
+ oneof default_oneof_a {
+ int32 aone = 10 [default = 1234];
+ int32 atwo = 11;
+ }
+
+ oneof default_oneof_b {
+ int32 bone = 12;
+ int32 btwo = 13 [default = 1234];
+ }
+}
+
+message TestEndsWithBytes {
+ optional int32 value = 1;
+ optional bytes data = 2;
+}
+
diff --git a/js/compatibility_tests/v3.0.0/test.sh b/js/compatibility_tests/v3.0.0/test.sh
new file mode 100755
index 00000000..9d58f30a
--- /dev/null
+++ b/js/compatibility_tests/v3.0.0/test.sh
@@ -0,0 +1,92 @@
+#!/bin/bash
+
+set -e
+
+# Download protoc 3.0.0 from Maven if it is not already present.
+OLD_PROTOC_URL=https://repo1.maven.org/maven2/com/google/protobuf/protoc/3.0.0/protoc-3.0.0-linux-x86_64.exe
+if [ ! -f protoc ]; then
+ wget $OLD_PROTOC_URL -O protoc
+ chmod +x protoc
+fi
+
+pushd ../..
+npm install && npm test
+popd
+
+old_protoc=./protoc
+new_protoc=../../../src/protoc
+
+# The protos in group 2 have some dependencies on protos in group 1. The tests
+# will verify that the generated code for one group can be regenerated
+# independently of the other group in a compatible way.
+#
+# Note: these lists of protos duplicate the lists in gulpfile.js. Ideally we
+# should find a good way of having a single source of truth for this.
+group1_protos="data.proto test3.proto test5.proto commonjs/test6/test6.proto testbinary.proto testempty.proto test.proto"
+group2_protos="proto3_test.proto test2.proto test4.proto commonjs/test7/test7.proto"
+
+# We test the following cases:
+#
+# Case 1: build groups 1 and 2 with the old protoc
+# Case 2: build group 1 with new protoc but group 2 with old protoc
+# Case 3: build group 1 with old protoc but group 2 with new protoc
+#
+# In each case, we use the current runtime.
+
+#
+# CommonJS tests
+#
+mkdir -p commonjs_out{1,2,3}
+# Case 1
+$old_protoc --js_out=import_style=commonjs,binary:commonjs_out1 -I ../../../src -I commonjs -I . $group1_protos
+$old_protoc --js_out=import_style=commonjs,binary:commonjs_out1 -I ../../../src -I commonjs -I . $group2_protos
+# Case 2
+$new_protoc --js_out=import_style=commonjs,binary:commonjs_out2 -I ../../../src -I commonjs -I . $group1_protos
+$old_protoc --js_out=import_style=commonjs,binary:commonjs_out2 -I ../../../src -I commonjs -I . $group2_protos
+# Case 3
+$old_protoc --js_out=import_style=commonjs,binary:commonjs_out3 -I ../../../src -I commonjs -I . $group1_protos
+$new_protoc --js_out=import_style=commonjs,binary:commonjs_out3 -I ../../../src -I commonjs -I . $group2_protos
+
+mkdir -p commonjs_out/binary
+for file in *_test.js binary/*_test.js; do
+ node commonjs/rewrite_tests_for_commonjs.js < "$file" > "commonjs_out/$file"
+done
+cp commonjs/{jasmine.json,import_test.js} commonjs_out/
+mkdir -p commonjs_out/test_node_modules
+../../node_modules/google-closure-library/closure/bin/calcdeps.py -i commonjs/export_asserts.js -p . -p ../../node_modules/google-closure-library/closure -o compiled --compiler_jar ../../node_modules/google-closure-compiler/compiler.jar > commonjs_out/test_node_modules/closure_asserts_commonjs.js
+../../node_modules/google-closure-library/closure/bin/calcdeps.py -i commonjs/export_testdeps.js -p ../.. -p ../../node_modules/google-closure-library/closure -o compiled --compiler_jar ../../node_modules/google-closure-compiler/compiler.jar > commonjs_out/test_node_modules/testdeps_commonjs.js
+cp ../../google-protobuf.js commonjs_out/test_node_modules
+cp -r ../../commonjs_out/node_modules commonjs_out
+
+echo
+echo "Running tests with CommonJS imports"
+echo "-----------------------------------"
+for i in 1 2 3; do
+ cp -r commonjs_out/* "commonjs_out$i"
+ pushd "commonjs_out$i"
+ JASMINE_CONFIG_PATH=jasmine.json NODE_PATH=test_node_modules ../../../node_modules/.bin/jasmine
+ popd
+done
+
+#
+# Closure tests
+#
+$old_protoc --js_out=library=testproto_libs1,binary:. -I ../../../src -I commonjs -I . $group1_protos
+$old_protoc --js_out=library=testproto_libs2,binary:. -I ../../../src -I commonjs -I . $group2_protos
+$new_protoc --js_out=library=testproto_libs1_new,binary:. -I ../../../src -I commonjs -I . $group1_protos
+$new_protoc --js_out=library=testproto_libs2_new,binary:. -I ../../../src -I commonjs -I . $group2_protos
+
+echo
+echo "Running tests with Closure-style imports"
+echo "----------------------------------------"
+
+# Case 1
+JASMINE_CONFIG_PATH=jasmine1.json ../../node_modules/.bin/jasmine
+# Case 2
+JASMINE_CONFIG_PATH=jasmine2.json ../../node_modules/.bin/jasmine
+# Case 3
+JASMINE_CONFIG_PATH=jasmine3.json ../../node_modules/.bin/jasmine
+
+# Remove these files so that calcdeps.py does not get confused by them the next
+# time this script runs.
+rm testproto_libs[12]*
diff --git a/js/compatibility_tests/v3.0.0/test2.proto b/js/compatibility_tests/v3.0.0/test2.proto
new file mode 100644
index 00000000..44e55eff
--- /dev/null
+++ b/js/compatibility_tests/v3.0.0/test2.proto
@@ -0,0 +1,54 @@
+// 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.
+
+syntax = "proto2";
+
+option java_package = "com.google.apps.jspb.proto";
+option java_multiple_files = true;
+
+package jspb.test;
+
+message TestExtensionsMessage {
+ optional int32 intfield = 1;
+ extensions 100 to max;
+}
+
+message ExtensionMessage {
+ extend TestExtensionsMessage {
+ optional ExtensionMessage ext_field = 100;
+ }
+ optional string ext1 = 1;
+}
+
+// Floating extensions are only supported when generating a _lib.js library.
+extend TestExtensionsMessage {
+ optional ExtensionMessage floating_msg_field = 101;
+ optional string floating_str_field = 102;
+}
diff --git a/js/compatibility_tests/v3.0.0/test3.proto b/js/compatibility_tests/v3.0.0/test3.proto
new file mode 100644
index 00000000..940a552e
--- /dev/null
+++ b/js/compatibility_tests/v3.0.0/test3.proto
@@ -0,0 +1,53 @@
+// 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.
+
+syntax = "proto2";
+
+option java_package = "com.google.apps.jspb.proto";
+option java_multiple_files = true;
+
+package jspb.exttest;
+
+message TestExtensionsMessage {
+ optional int32 intfield = 1;
+ extensions 100 to max;
+}
+
+message ExtensionMessage {
+ extend TestExtensionsMessage {
+ optional ExtensionMessage ext_field = 100;
+ }
+ optional string ext1 = 1;
+}
+
+extend TestExtensionsMessage {
+ optional ExtensionMessage floating_msg_field = 101;
+ optional string floating_str_field = 102;
+}
diff --git a/js/compatibility_tests/v3.0.0/test4.proto b/js/compatibility_tests/v3.0.0/test4.proto
new file mode 100644
index 00000000..cf2451e9
--- /dev/null
+++ b/js/compatibility_tests/v3.0.0/test4.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.
+
+syntax = "proto2";
+
+option java_package = "com.google.apps.jspb.proto";
+option java_multiple_files = true;
+
+package jspb.exttest;
+
+import "test3.proto";
+
+extend TestExtensionsMessage {
+ optional ExtensionMessage floating_msg_field_two = 103;
+}
diff --git a/js/compatibility_tests/v3.0.0/test5.proto b/js/compatibility_tests/v3.0.0/test5.proto
new file mode 100644
index 00000000..34979517
--- /dev/null
+++ b/js/compatibility_tests/v3.0.0/test5.proto
@@ -0,0 +1,44 @@
+// 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.
+
+syntax = "proto2";
+
+option java_package = "com.google.apps.jspb.proto";
+option java_multiple_files = true;
+
+package jspb.exttest.beta;
+
+message TestBetaExtensionsMessage {
+ extensions 100 to max;
+}
+
+extend TestBetaExtensionsMessage {
+ optional string floating_str_field = 101;
+}
diff --git a/js/compatibility_tests/v3.0.0/testbinary.proto b/js/compatibility_tests/v3.0.0/testbinary.proto
new file mode 100644
index 00000000..116f17fb
--- /dev/null
+++ b/js/compatibility_tests/v3.0.0/testbinary.proto
@@ -0,0 +1,212 @@
+// 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.
+
+// LINT: ALLOW_GROUPS
+
+syntax = "proto2";
+
+
+package jspb.test;
+
+// These types are borrowed from `unittest.proto` in the protobuf tree. We want
+// to ensure that the binary-format support will handle all field types
+// properly.
+message TestAllTypes {
+ optional int32 optional_int32 = 1;
+ optional int64 optional_int64 = 2;
+ optional uint32 optional_uint32 = 3;
+ optional uint64 optional_uint64 = 4;
+ optional sint32 optional_sint32 = 5;
+ optional sint64 optional_sint64 = 6;
+ optional fixed32 optional_fixed32 = 7;
+ optional fixed64 optional_fixed64 = 8;
+ optional sfixed32 optional_sfixed32 = 9;
+ optional sfixed64 optional_sfixed64 = 10;
+ optional float optional_float = 11;
+ optional double optional_double = 12;
+ optional bool optional_bool = 13;
+ optional string optional_string = 14;
+ optional bytes optional_bytes = 15;
+ optional group OptionalGroup = 16 {
+ optional int32 a = 17;
+ }
+
+ optional ForeignMessage optional_foreign_message = 19;
+ optional ForeignEnum optional_foreign_enum = 22;
+
+ // Repeated
+ repeated int32 repeated_int32 = 31;
+ repeated int64 repeated_int64 = 32;
+ repeated uint32 repeated_uint32 = 33;
+ repeated uint64 repeated_uint64 = 34;
+ repeated sint32 repeated_sint32 = 35;
+ repeated sint64 repeated_sint64 = 36;
+ repeated fixed32 repeated_fixed32 = 37;
+ repeated fixed64 repeated_fixed64 = 38;
+ repeated sfixed32 repeated_sfixed32 = 39;
+ repeated sfixed64 repeated_sfixed64 = 40;
+ repeated float repeated_float = 41;
+ repeated double repeated_double = 42;
+ repeated bool repeated_bool = 43;
+ repeated string repeated_string = 44;
+ repeated bytes repeated_bytes = 45;
+
+ repeated group RepeatedGroup = 46 {
+ optional int32 a = 47;
+ }
+
+ repeated ForeignMessage repeated_foreign_message = 49;
+ repeated ForeignEnum repeated_foreign_enum = 52;
+
+ // Packed repeated
+ repeated int32 packed_repeated_int32 = 61 [packed=true];
+ repeated int64 packed_repeated_int64 = 62 [packed=true];
+ repeated uint32 packed_repeated_uint32 = 63 [packed=true];
+ repeated uint64 packed_repeated_uint64 = 64 [packed=true];
+ repeated sint32 packed_repeated_sint32 = 65 [packed=true];
+ repeated sint64 packed_repeated_sint64 = 66 [packed=true];
+ repeated fixed32 packed_repeated_fixed32 = 67 [packed=true];
+ repeated fixed64 packed_repeated_fixed64 = 68 [packed=true];
+ repeated sfixed32 packed_repeated_sfixed32 = 69 [packed=true];
+ repeated sfixed64 packed_repeated_sfixed64 = 70 [packed=true];
+ repeated float packed_repeated_float = 71 [packed=true];
+ repeated double packed_repeated_double = 72 [packed=true];
+ repeated bool packed_repeated_bool = 73 [packed=true];
+
+ oneof oneof_field {
+ uint32 oneof_uint32 = 111;
+ ForeignMessage oneof_foreign_message = 112;
+ string oneof_string = 113;
+ bytes oneof_bytes = 114;
+ }
+
+}
+
+message ForeignMessage {
+ optional int32 c = 1;
+}
+
+enum ForeignEnum {
+ FOREIGN_FOO = 4;
+ FOREIGN_BAR = 5;
+ FOREIGN_BAZ = 6;
+}
+
+message TestExtendable {
+ extensions 1 to max;
+}
+
+message ExtendsWithMessage {
+ extend TestExtendable {
+ optional ExtendsWithMessage optional_extension = 19;
+ repeated ExtendsWithMessage repeated_extension = 49;
+ }
+ optional int32 foo = 1;
+}
+
+extend TestExtendable {
+ optional int32 extend_optional_int32 = 1;
+ optional int64 extend_optional_int64 = 2;
+ optional uint32 extend_optional_uint32 = 3;
+ optional uint64 extend_optional_uint64 = 4;
+ optional sint32 extend_optional_sint32 = 5;
+ optional sint64 extend_optional_sint64 = 6;
+ optional fixed32 extend_optional_fixed32 = 7;
+ optional fixed64 extend_optional_fixed64 = 8;
+ optional sfixed32 extend_optional_sfixed32 = 9;
+ optional sfixed64 extend_optional_sfixed64 = 10;
+ optional float extend_optional_float = 11;
+ optional double extend_optional_double = 12;
+ optional bool extend_optional_bool = 13;
+ optional string extend_optional_string = 14;
+ optional bytes extend_optional_bytes = 15;
+ optional ForeignEnum extend_optional_foreign_enum = 22;
+
+ repeated int32 extend_repeated_int32 = 31;
+ repeated int64 extend_repeated_int64 = 32;
+ repeated uint32 extend_repeated_uint32 = 33;
+ repeated uint64 extend_repeated_uint64 = 34;
+ repeated sint32 extend_repeated_sint32 = 35;
+ repeated sint64 extend_repeated_sint64 = 36;
+ repeated fixed32 extend_repeated_fixed32 = 37;
+ repeated fixed64 extend_repeated_fixed64 = 38;
+ repeated sfixed32 extend_repeated_sfixed32 = 39;
+ repeated sfixed64 extend_repeated_sfixed64 = 40;
+ repeated float extend_repeated_float = 41;
+ repeated double extend_repeated_double = 42;
+ repeated bool extend_repeated_bool = 43;
+ repeated string extend_repeated_string = 44;
+ repeated bytes extend_repeated_bytes = 45;
+ repeated ForeignEnum extend_repeated_foreign_enum = 52;
+
+ repeated int32 extend_packed_repeated_int32 = 61 [packed=true];
+ repeated int64 extend_packed_repeated_int64 = 62 [packed=true];
+ repeated uint32 extend_packed_repeated_uint32 = 63 [packed=true];
+ repeated uint64 extend_packed_repeated_uint64 = 64 [packed=true];
+ repeated sint32 extend_packed_repeated_sint32 = 65 [packed=true];
+ repeated sint64 extend_packed_repeated_sint64 = 66 [packed=true];
+ repeated fixed32 extend_packed_repeated_fixed32 = 67 [packed=true];
+ repeated fixed64 extend_packed_repeated_fixed64 = 68 [packed=true];
+ repeated sfixed32 extend_packed_repeated_sfixed32 = 69 [packed=true];
+ repeated sfixed64 extend_packed_repeated_sfixed64 = 70 [packed=true];
+ repeated float extend_packed_repeated_float = 71 [packed=true];
+ repeated double extend_packed_repeated_double = 72 [packed=true];
+ repeated bool extend_packed_repeated_bool = 73 [packed=true];
+ repeated ForeignEnum extend_packed_repeated_foreign_enum = 82
+ [packed=true];
+
+}
+
+message TestMapFields {
+ map<string, string> map_string_string = 1;
+ map<string, int32> map_string_int32 = 2;
+ map<string, int64> map_string_int64 = 3;
+ map<string, bool> map_string_bool = 4;
+ map<string, double> map_string_double = 5;
+ map<string, MapValueEnum> map_string_enum = 6;
+ map<string, MapValueMessage> map_string_msg = 7;
+
+ map<int32, string> map_int32_string = 8;
+ map<int64, string> map_int64_string = 9;
+ map<bool, string> map_bool_string = 10;
+
+ optional TestMapFields test_map_fields = 11;
+ map<string, TestMapFields> map_string_testmapfields = 12;
+}
+
+enum MapValueEnum {
+ MAP_VALUE_FOO = 0;
+ MAP_VALUE_BAR = 1;
+ MAP_VALUE_BAZ = 2;
+}
+
+message MapValueMessage {
+ optional int32 foo = 1;
+}
diff --git a/js/compatibility_tests/v3.0.0/testempty.proto b/js/compatibility_tests/v3.0.0/testempty.proto
new file mode 100644
index 00000000..960bce4e
--- /dev/null
+++ b/js/compatibility_tests/v3.0.0/testempty.proto
@@ -0,0 +1,34 @@
+// 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.
+
+syntax = "proto2";
+
+package javatests.com.google.apps.jspb;
+
diff --git a/js/compatibility_tests/v3.1.0/binary/arith_test.js b/js/compatibility_tests/v3.1.0/binary/arith_test.js
new file mode 100644
index 00000000..89796bf7
--- /dev/null
+++ b/js/compatibility_tests/v3.1.0/binary/arith_test.js
@@ -0,0 +1,355 @@
+// 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.
+
+/**
+ * @fileoverview Test cases for Int64-manipulation functions.
+ *
+ * Test suite is written using Jasmine -- see http://jasmine.github.io/
+ *
+ * @author cfallin@google.com (Chris Fallin)
+ */
+
+goog.require('goog.testing.asserts');
+goog.require('jspb.arith.Int64');
+goog.require('jspb.arith.UInt64');
+
+
+describe('binaryArithTest', function() {
+ /**
+ * Tests comparison operations.
+ */
+ it('testCompare', function() {
+ var a = new jspb.arith.UInt64(1234, 5678);
+ var b = new jspb.arith.UInt64(1234, 5678);
+ assertEquals(a.cmp(b), 0);
+ assertEquals(b.cmp(a), 0);
+ b.lo -= 1;
+ assertEquals(a.cmp(b), 1);
+ assertEquals(b.cmp(a), -1);
+ b.lo += 2;
+ assertEquals(a.cmp(b), -1);
+ assertEquals(b.cmp(a), 1);
+ b.lo = a.lo;
+ b.hi = a.hi - 1;
+ assertEquals(a.cmp(b), 1);
+ assertEquals(b.cmp(a), -1);
+
+ assertEquals(a.zero(), false);
+ assertEquals(a.msb(), false);
+ assertEquals(a.lsb(), false);
+ a.hi = 0;
+ a.lo = 0;
+ assertEquals(a.zero(), true);
+ a.hi = 0x80000000;
+ assertEquals(a.zero(), false);
+ assertEquals(a.msb(), true);
+ a.lo = 0x00000001;
+ assertEquals(a.lsb(), true);
+ });
+
+
+ /**
+ * Tests shifts.
+ */
+ it('testShifts', function() {
+ var a = new jspb.arith.UInt64(1, 0);
+ assertEquals(a.lo, 1);
+ assertEquals(a.hi, 0);
+ var orig = a;
+ a = a.leftShift();
+ assertEquals(orig.lo, 1); // original unmodified.
+ assertEquals(orig.hi, 0);
+ assertEquals(a.lo, 2);
+ assertEquals(a.hi, 0);
+ a = a.leftShift();
+ assertEquals(a.lo, 4);
+ assertEquals(a.hi, 0);
+ for (var i = 0; i < 29; i++) {
+ a = a.leftShift();
+ }
+ assertEquals(a.lo, 0x80000000);
+ assertEquals(a.hi, 0);
+ a = a.leftShift();
+ assertEquals(a.lo, 0);
+ assertEquals(a.hi, 1);
+ a = a.leftShift();
+ assertEquals(a.lo, 0);
+ assertEquals(a.hi, 2);
+ a = a.rightShift();
+ a = a.rightShift();
+ assertEquals(a.lo, 0x80000000);
+ assertEquals(a.hi, 0);
+ a = a.rightShift();
+ assertEquals(a.lo, 0x40000000);
+ assertEquals(a.hi, 0);
+ });
+
+
+ /**
+ * Tests additions.
+ */
+ it('testAdd', function() {
+ var a = new jspb.arith.UInt64(/* lo = */ 0x89abcdef,
+ /* hi = */ 0x01234567);
+ var b = new jspb.arith.UInt64(/* lo = */ 0xff52ab91,
+ /* hi = */ 0x92fa2123);
+ // Addition with carry.
+ var c = a.add(b);
+ assertEquals(a.lo, 0x89abcdef); // originals unmodified.
+ assertEquals(a.hi, 0x01234567);
+ assertEquals(b.lo, 0xff52ab91);
+ assertEquals(b.hi, 0x92fa2123);
+ assertEquals(c.lo, 0x88fe7980);
+ assertEquals(c.hi, 0x941d668b);
+
+ // Simple addition without carry.
+ a.lo = 2;
+ a.hi = 0;
+ b.lo = 3;
+ b.hi = 0;
+ c = a.add(b);
+ assertEquals(c.lo, 5);
+ assertEquals(c.hi, 0);
+ });
+
+
+ /**
+ * Test subtractions.
+ */
+ it('testSub', function() {
+ var kLength = 10;
+ var hiValues = [0x1682ef32,
+ 0x583902f7,
+ 0xb62f5955,
+ 0x6ea99bbf,
+ 0x25a39c20,
+ 0x0700a08b,
+ 0x00f7304d,
+ 0x91a5b5af,
+ 0x89077fd2,
+ 0xe09e347c];
+ var loValues = [0xe1538b18,
+ 0xbeacd556,
+ 0x74100758,
+ 0x96e3cb26,
+ 0x56c37c3f,
+ 0xe00b3f7d,
+ 0x859f25d7,
+ 0xc2ee614a,
+ 0xe1d21cd7,
+ 0x30aae6a4];
+ for (var i = 0; i < kLength; i++) {
+ for (var j = 0; j < kLength; j++) {
+ var a = new jspb.arith.UInt64(loValues[i], hiValues[j]);
+ var b = new jspb.arith.UInt64(loValues[j], hiValues[i]);
+ var c = a.add(b).sub(b);
+ assertEquals(c.hi, a.hi);
+ assertEquals(c.lo, a.lo);
+ }
+ }
+ });
+
+
+ /**
+ * Tests 32-by-32 multiplication.
+ */
+ it('testMul32x32', function() {
+ var testData = [
+ // a b low(a*b) high(a*b)
+ [0xc0abe2f8, 0x1607898a, 0x5de711b0, 0x109471b8],
+ [0x915eb3cb, 0x4fb66d0e, 0xbd0d441a, 0x2d43d0bc],
+ [0xfe4efe70, 0x80b48c37, 0xbcddea10, 0x7fdada0c],
+ [0xe222fd4a, 0xe43d524a, 0xd5e0eb64, 0xc99d549c],
+ [0xd171f469, 0xb94ebd01, 0x4be17969, 0x979bc4fa],
+ [0x829cc1df, 0xe2598b38, 0xf4157dc8, 0x737c12ad],
+ [0xf10c3767, 0x8382881e, 0x942b3612, 0x7bd428b8],
+ [0xb0f6dd24, 0x232597e1, 0x079c98a4, 0x184bbce7],
+ [0xfcdb05a7, 0x902f55bc, 0x636199a4, 0x8e69f412],
+ [0x0dd0bfa9, 0x916e27b1, 0x6e2542d9, 0x07d92e65]
+ ];
+
+ for (var i = 0; i < testData.length; i++) {
+ var a = testData[i][0] >>> 0;
+ var b = testData[i][1] >>> 0;
+ var cLow = testData[i][2] >>> 0;
+ var cHigh = testData[i][3] >>> 0;
+ var c = jspb.arith.UInt64.mul32x32(a, b);
+ assertEquals(c.lo, cLow);
+ assertEquals(c.hi, cHigh);
+ }
+ });
+
+
+ /**
+ * Tests 64-by-32 multiplication.
+ */
+ it('testMul', function() {
+ // 64x32 bits produces 96 bits of product. The multiplication function under
+ // test truncates the top 32 bits, so we compare against a 64-bit expected
+ // product.
+ var testData = [
+ // low(a) high(a) low(a*b) high(a*b)
+ [0xec10955b, 0x360eb168, 0x4b7f3f5b, 0xbfcb7c59, 0x9517da5f],
+ [0x42b000fc, 0x9d101642, 0x6fa1ab72, 0x2584c438, 0x6a9e6d2b],
+ [0xf42d4fb4, 0xae366403, 0xa65a1000, 0x92434000, 0x1ff978df],
+ [0x17e2f56b, 0x25487693, 0xf13f98c7, 0x73794e2d, 0xa96b0c6a],
+ [0x492f241f, 0x76c0eb67, 0x7377ac44, 0xd4336c3c, 0xfc4b1ebe],
+ [0xd6b92321, 0xe184fa48, 0xd6e76904, 0x93141584, 0xcbf44da1],
+ [0x4bf007ea, 0x968c0a9e, 0xf5e4026a, 0x4fdb1ae4, 0x61b9fb7d],
+ [0x10a83be7, 0x2d685ba6, 0xc9e5fb7f, 0x2ad43499, 0x3742473d],
+ [0x2f261829, 0x1aca681a, 0x3d3494e3, 0x8213205b, 0x283719f8],
+ [0xe4f2ce21, 0x2e74b7bd, 0xd801b38b, 0xbc17feeb, 0xc6c44e0f]
+ ];
+
+ for (var i = 0; i < testData.length; i++) {
+ var a = new jspb.arith.UInt64(testData[i][0], testData[i][1]);
+ var prod = a.mul(testData[i][2]);
+ assertEquals(prod.lo, testData[i][3]);
+ assertEquals(prod.hi, testData[i][4]);
+ }
+ });
+
+
+ /**
+ * Tests 64-div-by-32 division.
+ */
+ it('testDiv', function() {
+ // Compute a/b, yielding quot = a/b and rem = a%b.
+ var testData = [
+ // --- divisors in (0, 2^32-1) to test full divisor range
+ // low(a) high(a) b low(quot) high(quot) rem
+ [0x712443f1, 0xe85cefcc, 0xc1a7050b, 0x332c79ad, 0x00000001, 0x92ffa882],
+ [0x11912915, 0xb2699eb5, 0x30467cbe, 0xb21b4be4, 0x00000003, 0x283465dd],
+ [0x0d917982, 0x201f2a6e, 0x3f35bf03, 0x8217c8e4, 0x00000000, 0x153402d6],
+ [0xa072c108, 0x74020c96, 0xc60568fd, 0x95f9613e, 0x00000000, 0x3f4676c2],
+ [0xd845d5d8, 0xcdd235c4, 0x20426475, 0x6154e78b, 0x00000006, 0x202fb751],
+ [0xa4dbf71f, 0x9e90465e, 0xf08e022f, 0xa8be947f, 0x00000000, 0xbe43b5ce],
+ [0x3dbe627f, 0xa791f4b9, 0x28a5bd89, 0x1f5dfe93, 0x00000004, 0x02bf9ed4],
+ [0x5c1c53ee, 0xccf5102e, 0x198576e7, 0x07e3ae31, 0x00000008, 0x02ea8fb7],
+ [0xfef1e581, 0x04714067, 0xca6540c1, 0x059e73ec, 0x00000000, 0x31658095],
+ [0x1e2dd90c, 0x13dd6667, 0x8b2184c3, 0x248d1a42, 0x00000000, 0x4ca6d0c6],
+ // --- divisors in (0, 2^16-1) to test larger quotient high-words
+ // low(a) high(a) b low(quot) high(quot) rem
+ [0x86722b47, 0x2cd57c9a, 0x00003123, 0x2ae41b7a, 0x0000e995, 0x00000f99],
+ [0x1dd7884c, 0xf5e839bc, 0x00009eeb, 0x5c886242, 0x00018c21, 0x000099b6],
+ [0x5c53d625, 0x899fc7e5, 0x000087d7, 0xd625007a, 0x0001035c, 0x000019af],
+ [0x6932d932, 0x9d0a5488, 0x000051fb, 0x9d976143, 0x0001ea63, 0x00004981],
+ [0x4d18bb85, 0x0c92fb31, 0x00001d9f, 0x03265ab4, 0x00006cac, 0x000001b9],
+ [0xbe756768, 0xdea67ccb, 0x00008a03, 0x58add442, 0x00019cff, 0x000056a2],
+ [0xe2466f9a, 0x2521f114, 0x0000c350, 0xa0c0860d, 0x000030ab, 0x0000a48a],
+ [0xf00ddad1, 0xe2f5446a, 0x00002cfc, 0x762697a6, 0x00050b96, 0x00000b69],
+ [0xa879152a, 0x0a70e0a5, 0x00007cdf, 0xb44151b3, 0x00001567, 0x0000363d],
+ [0x7179a74c, 0x46083fff, 0x0000253c, 0x4d39ba6e, 0x0001e17f, 0x00000f84]
+ ];
+
+ for (var i = 0; i < testData.length; i++) {
+ var a = new jspb.arith.UInt64(testData[i][0], testData[i][1]);
+ var result = a.div(testData[i][2]);
+ var quotient = result[0];
+ var remainder = result[1];
+ assertEquals(quotient.lo, testData[i][3]);
+ assertEquals(quotient.hi, testData[i][4]);
+ assertEquals(remainder.lo, testData[i][5]);
+ }
+ });
+
+
+ /**
+ * Tests .toString() and .fromString().
+ */
+ it('testStrings', function() {
+ var testData = [
+ [0x5e84c935, 0xcae33d0e, '14619595947299359029'],
+ [0x62b3b8b8, 0x93480544, '10612738313170434232'],
+ [0x319bfb13, 0xc01c4172, '13843011313344445203'],
+ [0x5b8a65fb, 0xa5885b31, '11927883880638080507'],
+ [0x6bdb80f1, 0xb0d1b16b, '12741159895737008369'],
+ [0x4b82b442, 0x2e0d8c97, '3318463081876730946'],
+ [0x780d5208, 0x7d76752c, '9040542135845999112'],
+ [0x2e46800f, 0x0993778d, '690026616168284175'],
+ [0xf00a7e32, 0xcd8e3931, '14811839111111540274'],
+ [0x1baeccd6, 0x923048c4, '10533999535534820566'],
+ [0x03669d29, 0xbff3ab72, '13831587386756603177'],
+ [0x2526073e, 0x01affc81, '121593346566522686'],
+ [0xc24244e0, 0xd7f40d0e, '15561076969511732448'],
+ [0xc56a341e, 0xa68b66a7, '12000798502816461854'],
+ [0x8738d64d, 0xbfe78604, '13828168534871037517'],
+ [0x5baff03b, 0xd7572aea, '15516918227177304123'],
+ [0x4a843d8a, 0x864e132b, '9677693725920476554'],
+ [0x25b4e94d, 0x22b54dc6, '2500990681505655117'],
+ [0x6bbe664b, 0x55a5cc0e, '6171563226690381387'],
+ [0xee916c81, 0xb00aabb3, '12685140089732426881']
+ ];
+
+ for (var i = 0; i < testData.length; i++) {
+ var a = new jspb.arith.UInt64(testData[i][0], testData[i][1]);
+ var roundtrip = jspb.arith.UInt64.fromString(a.toString());
+ assertEquals(roundtrip.lo, a.lo);
+ assertEquals(roundtrip.hi, a.hi);
+ assertEquals(a.toString(), testData[i][2]);
+ }
+ });
+
+
+ /**
+ * Tests signed Int64s. These are built on UInt64s, so we only need to test
+ * the explicit overrides: .toString() and .fromString().
+ */
+ it('testSignedInt64', function() {
+ var testStrings = [
+ '-7847499644178593666',
+ '3771946501229139523',
+ '2872856549054995060',
+ '-5780049594274350904',
+ '3383785956695105201',
+ '2973055184857072610',
+ '-3879428459215627206',
+ '4589812431064156631',
+ '8484075557333689940',
+ '1075325817098092407',
+ '-4346697501012292314',
+ '2488620459718316637',
+ '6112655187423520672',
+ '-3655278273928612104',
+ '3439154019435803196',
+ '1004112478843763757',
+ '-6587790776614368413',
+ '664320065099714586',
+ '4760412909973292912',
+ '-7911903989602274672'
+ ];
+
+ for (var i = 0; i < testStrings.length; i++) {
+ var roundtrip =
+ jspb.arith.Int64.fromString(testStrings[i]).toString();
+ assertEquals(roundtrip, testStrings[i]);
+ }
+ });
+});
diff --git a/js/compatibility_tests/v3.1.0/binary/decoder_test.js b/js/compatibility_tests/v3.1.0/binary/decoder_test.js
new file mode 100644
index 00000000..fce2fe18
--- /dev/null
+++ b/js/compatibility_tests/v3.1.0/binary/decoder_test.js
@@ -0,0 +1,317 @@
+// 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.
+
+/**
+ * @fileoverview Test cases for jspb's binary protocol buffer decoder.
+ *
+ * There are two particular magic numbers that need to be pointed out -
+ * 2^64-1025 is the largest number representable as both a double and an
+ * unsigned 64-bit integer, and 2^63-513 is the largest number representable as
+ * both a double and a signed 64-bit integer.
+ *
+ * Test suite is written using Jasmine -- see http://jasmine.github.io/
+ *
+ * @author aappleby@google.com (Austin Appleby)
+ */
+
+goog.require('goog.testing.asserts');
+goog.require('jspb.BinaryConstants');
+goog.require('jspb.BinaryDecoder');
+goog.require('jspb.BinaryEncoder');
+
+
+/**
+ * Tests encoding and decoding of unsigned types.
+ * @param {Function} readValue
+ * @param {Function} writeValue
+ * @param {number} epsilon
+ * @param {number} upperLimit
+ * @param {Function} filter
+ * @suppress {missingProperties|visibility}
+ */
+function doTestUnsignedValue(readValue,
+ writeValue, epsilon, upperLimit, filter) {
+ var encoder = new jspb.BinaryEncoder();
+
+ // Encode zero and limits.
+ writeValue.call(encoder, filter(0));
+ writeValue.call(encoder, filter(epsilon));
+ writeValue.call(encoder, filter(upperLimit));
+
+ // Encode positive values.
+ for (var cursor = epsilon; cursor < upperLimit; cursor *= 1.1) {
+ writeValue.call(encoder, filter(cursor));
+ }
+
+ var decoder = jspb.BinaryDecoder.alloc(encoder.end());
+
+ // Check zero and limits.
+ assertEquals(filter(0), readValue.call(decoder));
+ assertEquals(filter(epsilon), readValue.call(decoder));
+ assertEquals(filter(upperLimit), readValue.call(decoder));
+
+ // Check positive values.
+ for (var cursor = epsilon; cursor < upperLimit; cursor *= 1.1) {
+ if (filter(cursor) != readValue.call(decoder)) throw 'fail!';
+ }
+
+ // Encoding values outside the valid range should assert.
+ assertThrows(function() {writeValue.call(encoder, -1);});
+ assertThrows(function() {writeValue.call(encoder, upperLimit * 1.1);});
+}
+
+
+/**
+ * Tests encoding and decoding of signed types.
+ * @param {Function} readValue
+ * @param {Function} writeValue
+ * @param {number} epsilon
+ * @param {number} lowerLimit
+ * @param {number} upperLimit
+ * @param {Function} filter
+ * @suppress {missingProperties}
+ */
+function doTestSignedValue(readValue,
+ writeValue, epsilon, lowerLimit, upperLimit, filter) {
+ var encoder = new jspb.BinaryEncoder();
+
+ // Encode zero and limits.
+ writeValue.call(encoder, filter(lowerLimit));
+ writeValue.call(encoder, filter(-epsilon));
+ writeValue.call(encoder, filter(0));
+ writeValue.call(encoder, filter(epsilon));
+ writeValue.call(encoder, filter(upperLimit));
+
+ var inputValues = [];
+
+ // Encode negative values.
+ for (var cursor = lowerLimit; cursor < -epsilon; cursor /= 1.1) {
+ var val = filter(cursor);
+ writeValue.call(encoder, val);
+ inputValues.push(val);
+ }
+
+ // Encode positive values.
+ for (var cursor = epsilon; cursor < upperLimit; cursor *= 1.1) {
+ var val = filter(cursor);
+ writeValue.call(encoder, val);
+ inputValues.push(val);
+ }
+
+ var decoder = jspb.BinaryDecoder.alloc(encoder.end());
+
+ // Check zero and limits.
+ assertEquals(filter(lowerLimit), readValue.call(decoder));
+ assertEquals(filter(-epsilon), readValue.call(decoder));
+ assertEquals(filter(0), readValue.call(decoder));
+ assertEquals(filter(epsilon), readValue.call(decoder));
+ assertEquals(filter(upperLimit), readValue.call(decoder));
+
+ // Verify decoded values.
+ for (var i = 0; i < inputValues.length; i++) {
+ assertEquals(inputValues[i], readValue.call(decoder));
+ }
+
+ // Encoding values outside the valid range should assert.
+ assertThrows(function() {writeValue.call(encoder, lowerLimit * 1.1);});
+ assertThrows(function() {writeValue.call(encoder, upperLimit * 1.1);});
+}
+
+describe('binaryDecoderTest', function() {
+ /**
+ * Tests the decoder instance cache.
+ */
+ it('testInstanceCache', /** @suppress {visibility} */ function() {
+ // Empty the instance caches.
+ jspb.BinaryDecoder.instanceCache_ = [];
+
+ // Allocating and then freeing a decoder should put it in the instance
+ // cache.
+ jspb.BinaryDecoder.alloc().free();
+
+ assertEquals(1, jspb.BinaryDecoder.instanceCache_.length);
+
+ // Allocating and then freeing three decoders should leave us with three in
+ // the cache.
+
+ var decoder1 = jspb.BinaryDecoder.alloc();
+ var decoder2 = jspb.BinaryDecoder.alloc();
+ var decoder3 = jspb.BinaryDecoder.alloc();
+ decoder1.free();
+ decoder2.free();
+ decoder3.free();
+
+ assertEquals(3, jspb.BinaryDecoder.instanceCache_.length);
+ });
+
+
+ /**
+ * Tests reading 64-bit integers as hash strings.
+ */
+ it('testHashStrings', function() {
+ var encoder = new jspb.BinaryEncoder();
+
+ var hashA = String.fromCharCode(0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00);
+ var hashB = String.fromCharCode(0x12, 0x34, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00);
+ var hashC = String.fromCharCode(0x12, 0x34, 0x56, 0x78,
+ 0x87, 0x65, 0x43, 0x21);
+ var hashD = String.fromCharCode(0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF);
+
+ encoder.writeVarintHash64(hashA);
+ encoder.writeVarintHash64(hashB);
+ encoder.writeVarintHash64(hashC);
+ encoder.writeVarintHash64(hashD);
+
+ encoder.writeFixedHash64(hashA);
+ encoder.writeFixedHash64(hashB);
+ encoder.writeFixedHash64(hashC);
+ encoder.writeFixedHash64(hashD);
+
+ var decoder = jspb.BinaryDecoder.alloc(encoder.end());
+
+ assertEquals(hashA, decoder.readVarintHash64());
+ assertEquals(hashB, decoder.readVarintHash64());
+ assertEquals(hashC, decoder.readVarintHash64());
+ assertEquals(hashD, decoder.readVarintHash64());
+
+ assertEquals(hashA, decoder.readFixedHash64());
+ assertEquals(hashB, decoder.readFixedHash64());
+ assertEquals(hashC, decoder.readFixedHash64());
+ assertEquals(hashD, decoder.readFixedHash64());
+ });
+
+
+ /**
+ * Verifies that misuse of the decoder class triggers assertions.
+ * @suppress {checkTypes|visibility}
+ */
+ it('testDecodeErrors', function() {
+ // Reading a value past the end of the stream should trigger an assertion.
+ var decoder = jspb.BinaryDecoder.alloc([0, 1, 2]);
+ assertThrows(function() {decoder.readUint64()});
+
+ // Overlong varints should trigger assertions.
+ decoder.setBlock([255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 0]);
+ assertThrows(function() {decoder.readUnsignedVarint64()});
+ decoder.reset();
+ assertThrows(function() {decoder.readSignedVarint64()});
+ decoder.reset();
+ assertThrows(function() {decoder.readZigzagVarint64()});
+ decoder.reset();
+ assertThrows(function() {decoder.readUnsignedVarint32()});
+ });
+
+
+ /**
+ * Tests encoding and decoding of unsigned integers.
+ */
+ it('testUnsignedIntegers', function() {
+ doTestUnsignedValue(
+ jspb.BinaryDecoder.prototype.readUint8,
+ jspb.BinaryEncoder.prototype.writeUint8,
+ 1, 0xFF, Math.round);
+
+ doTestUnsignedValue(
+ jspb.BinaryDecoder.prototype.readUint16,
+ jspb.BinaryEncoder.prototype.writeUint16,
+ 1, 0xFFFF, Math.round);
+
+ doTestUnsignedValue(
+ jspb.BinaryDecoder.prototype.readUint32,
+ jspb.BinaryEncoder.prototype.writeUint32,
+ 1, 0xFFFFFFFF, Math.round);
+
+ doTestUnsignedValue(
+ jspb.BinaryDecoder.prototype.readUint64,
+ jspb.BinaryEncoder.prototype.writeUint64,
+ 1, Math.pow(2, 64) - 1025, Math.round);
+ });
+
+
+ /**
+ * Tests encoding and decoding of signed integers.
+ */
+ it('testSignedIntegers', function() {
+ doTestSignedValue(
+ jspb.BinaryDecoder.prototype.readInt8,
+ jspb.BinaryEncoder.prototype.writeInt8,
+ 1, -0x80, 0x7F, Math.round);
+
+ doTestSignedValue(
+ jspb.BinaryDecoder.prototype.readInt16,
+ jspb.BinaryEncoder.prototype.writeInt16,
+ 1, -0x8000, 0x7FFF, Math.round);
+
+ doTestSignedValue(
+ jspb.BinaryDecoder.prototype.readInt32,
+ jspb.BinaryEncoder.prototype.writeInt32,
+ 1, -0x80000000, 0x7FFFFFFF, Math.round);
+
+ doTestSignedValue(
+ jspb.BinaryDecoder.prototype.readInt64,
+ jspb.BinaryEncoder.prototype.writeInt64,
+ 1, -Math.pow(2, 63), Math.pow(2, 63) - 513, Math.round);
+ });
+
+
+ /**
+ * Tests encoding and decoding of floats.
+ */
+ it('testFloats', function() {
+ /**
+ * @param {number} x
+ * @return {number}
+ */
+ function truncate(x) {
+ var temp = new Float32Array(1);
+ temp[0] = x;
+ return temp[0];
+ }
+ doTestSignedValue(
+ jspb.BinaryDecoder.prototype.readFloat,
+ jspb.BinaryEncoder.prototype.writeFloat,
+ jspb.BinaryConstants.FLOAT32_EPS,
+ -jspb.BinaryConstants.FLOAT32_MAX,
+ jspb.BinaryConstants.FLOAT32_MAX,
+ truncate);
+
+ doTestSignedValue(
+ jspb.BinaryDecoder.prototype.readDouble,
+ jspb.BinaryEncoder.prototype.writeDouble,
+ jspb.BinaryConstants.FLOAT64_EPS * 10,
+ -jspb.BinaryConstants.FLOAT64_MAX,
+ jspb.BinaryConstants.FLOAT64_MAX,
+ function(x) { return x; });
+ });
+});
diff --git a/js/compatibility_tests/v3.1.0/binary/proto_test.js b/js/compatibility_tests/v3.1.0/binary/proto_test.js
new file mode 100644
index 00000000..26e1d30f
--- /dev/null
+++ b/js/compatibility_tests/v3.1.0/binary/proto_test.js
@@ -0,0 +1,628 @@
+// 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.
+
+// Test suite is written using Jasmine -- see http://jasmine.github.io/
+
+goog.require('goog.crypt.base64');
+goog.require('goog.testing.asserts');
+goog.require('jspb.Message');
+
+// CommonJS-LoadFromFile: ../testbinary_pb proto.jspb.test
+goog.require('proto.jspb.test.ExtendsWithMessage');
+goog.require('proto.jspb.test.ForeignEnum');
+goog.require('proto.jspb.test.ForeignMessage');
+goog.require('proto.jspb.test.TestAllTypes');
+goog.require('proto.jspb.test.TestExtendable');
+goog.require('proto.jspb.test.extendOptionalBool');
+goog.require('proto.jspb.test.extendOptionalBytes');
+goog.require('proto.jspb.test.extendOptionalDouble');
+goog.require('proto.jspb.test.extendOptionalFixed32');
+goog.require('proto.jspb.test.extendOptionalFixed64');
+goog.require('proto.jspb.test.extendOptionalFloat');
+goog.require('proto.jspb.test.extendOptionalForeignEnum');
+goog.require('proto.jspb.test.extendOptionalInt32');
+goog.require('proto.jspb.test.extendOptionalInt64');
+goog.require('proto.jspb.test.extendOptionalSfixed32');
+goog.require('proto.jspb.test.extendOptionalSfixed64');
+goog.require('proto.jspb.test.extendOptionalSint32');
+goog.require('proto.jspb.test.extendOptionalSint64');
+goog.require('proto.jspb.test.extendOptionalString');
+goog.require('proto.jspb.test.extendOptionalUint32');
+goog.require('proto.jspb.test.extendOptionalUint64');
+goog.require('proto.jspb.test.extendPackedRepeatedBoolList');
+goog.require('proto.jspb.test.extendPackedRepeatedDoubleList');
+goog.require('proto.jspb.test.extendPackedRepeatedFixed32List');
+goog.require('proto.jspb.test.extendPackedRepeatedFixed64List');
+goog.require('proto.jspb.test.extendPackedRepeatedFloatList');
+goog.require('proto.jspb.test.extendPackedRepeatedForeignEnumList');
+goog.require('proto.jspb.test.extendPackedRepeatedInt32List');
+goog.require('proto.jspb.test.extendPackedRepeatedInt64List');
+goog.require('proto.jspb.test.extendPackedRepeatedSfixed32List');
+goog.require('proto.jspb.test.extendPackedRepeatedSfixed64List');
+goog.require('proto.jspb.test.extendPackedRepeatedSint32List');
+goog.require('proto.jspb.test.extendPackedRepeatedSint64List');
+goog.require('proto.jspb.test.extendPackedRepeatedUint32List');
+goog.require('proto.jspb.test.extendPackedRepeatedUint64List');
+goog.require('proto.jspb.test.extendRepeatedBoolList');
+goog.require('proto.jspb.test.extendRepeatedBytesList');
+goog.require('proto.jspb.test.extendRepeatedDoubleList');
+goog.require('proto.jspb.test.extendRepeatedFixed32List');
+goog.require('proto.jspb.test.extendRepeatedFixed64List');
+goog.require('proto.jspb.test.extendRepeatedFloatList');
+goog.require('proto.jspb.test.extendRepeatedForeignEnumList');
+goog.require('proto.jspb.test.extendRepeatedInt32List');
+goog.require('proto.jspb.test.extendRepeatedInt64List');
+goog.require('proto.jspb.test.extendRepeatedSfixed32List');
+goog.require('proto.jspb.test.extendRepeatedSfixed64List');
+goog.require('proto.jspb.test.extendRepeatedSint32List');
+goog.require('proto.jspb.test.extendRepeatedSint64List');
+goog.require('proto.jspb.test.extendRepeatedStringList');
+goog.require('proto.jspb.test.extendRepeatedUint32List');
+goog.require('proto.jspb.test.extendRepeatedUint64List');
+
+
+var suite = {};
+
+var BYTES = new Uint8Array([1, 2, 8, 9]);
+
+var BYTES_B64 = goog.crypt.base64.encodeByteArray(BYTES);
+
+
+/**
+ * Helper: fill all fields on a TestAllTypes message.
+ * @param {proto.jspb.test.TestAllTypes} msg
+ */
+function fillAllFields(msg) {
+ msg.setOptionalInt32(-42);
+ // can be exactly represented by JS number (64-bit double, i.e., 52-bit
+ // mantissa).
+ msg.setOptionalInt64(-0x7fffffff00000000);
+ msg.setOptionalUint32(0x80000000);
+ msg.setOptionalUint64(0xf000000000000000);
+ msg.setOptionalSint32(-100);
+ msg.setOptionalSint64(-0x8000000000000000);
+ msg.setOptionalFixed32(1234);
+ msg.setOptionalFixed64(0x1234567800000000);
+ msg.setOptionalSfixed32(-1234);
+ msg.setOptionalSfixed64(-0x1234567800000000);
+ msg.setOptionalFloat(1.5);
+ msg.setOptionalDouble(-1.5);
+ msg.setOptionalBool(true);
+ msg.setOptionalString('hello world');
+ msg.setOptionalBytes(BYTES);
+ msg.setOptionalGroup(new proto.jspb.test.TestAllTypes.OptionalGroup());
+ msg.getOptionalGroup().setA(100);
+ var submsg = new proto.jspb.test.ForeignMessage();
+ submsg.setC(16);
+ msg.setOptionalForeignMessage(submsg);
+ msg.setOptionalForeignEnum(proto.jspb.test.ForeignEnum.FOREIGN_FOO);
+ msg.setOneofString('oneof');
+
+
+ msg.setRepeatedInt32List([-42]);
+ msg.setRepeatedInt64List([-0x7fffffff00000000]);
+ msg.setRepeatedUint32List([0x80000000]);
+ msg.setRepeatedUint64List([0xf000000000000000]);
+ msg.setRepeatedSint32List([-100]);
+ msg.setRepeatedSint64List([-0x8000000000000000]);
+ msg.setRepeatedFixed32List([1234]);
+ msg.setRepeatedFixed64List([0x1234567800000000]);
+ msg.setRepeatedSfixed32List([-1234]);
+ msg.setRepeatedSfixed64List([-0x1234567800000000]);
+ msg.setRepeatedFloatList([1.5]);
+ msg.setRepeatedDoubleList([-1.5]);
+ msg.setRepeatedBoolList([true]);
+ msg.setRepeatedStringList(['hello world']);
+ msg.setRepeatedBytesList([BYTES, BYTES]);
+ msg.setRepeatedGroupList([new proto.jspb.test.TestAllTypes.RepeatedGroup()]);
+ msg.getRepeatedGroupList()[0].setA(100);
+ submsg = new proto.jspb.test.ForeignMessage();
+ submsg.setC(1000);
+ msg.setRepeatedForeignMessageList([submsg]);
+ msg.setRepeatedForeignEnumList([proto.jspb.test.ForeignEnum.FOREIGN_FOO]);
+
+ msg.setPackedRepeatedInt32List([-42]);
+ msg.setPackedRepeatedInt64List([-0x7fffffff00000000]);
+ msg.setPackedRepeatedUint32List([0x80000000]);
+ msg.setPackedRepeatedUint64List([0xf000000000000000]);
+ msg.setPackedRepeatedSint32List([-100]);
+ msg.setPackedRepeatedSint64List([-0x8000000000000000]);
+ msg.setPackedRepeatedFixed32List([1234]);
+ msg.setPackedRepeatedFixed64List([0x1234567800000000]);
+ msg.setPackedRepeatedSfixed32List([-1234]);
+ msg.setPackedRepeatedSfixed64List([-0x1234567800000000]);
+ msg.setPackedRepeatedFloatList([1.5]);
+ msg.setPackedRepeatedDoubleList([-1.5]);
+ msg.setPackedRepeatedBoolList([true]);
+
+}
+
+
+/**
+ * Helper: compare a bytes field to an expected value
+ * @param {Uint8Array|string} arr
+ * @param {Uint8Array} expected
+ * @return {boolean}
+ */
+function bytesCompare(arr, expected) {
+ if (goog.isString(arr)) {
+ arr = goog.crypt.base64.decodeStringToUint8Array(arr);
+ }
+ if (arr.length != expected.length) {
+ return false;
+ }
+ for (var i = 0; i < arr.length; i++) {
+ if (arr[i] != expected[i]) {
+ return false;
+ }
+ }
+ return true;
+}
+
+
+/**
+ * Helper: verify contents of given TestAllTypes message as set by
+ * fillAllFields().
+ * @param {proto.jspb.test.TestAllTypes} original
+ * @param {proto.jspb.test.TestAllTypes} copy
+ */
+function checkAllFields(original, copy) {
+ assertTrue(jspb.Message.equals(original, copy));
+
+ assertEquals(copy.getOptionalInt32(), -42);
+ assertEquals(copy.getOptionalInt64(), -0x7fffffff00000000);
+ assertEquals(copy.getOptionalUint32(), 0x80000000);
+ assertEquals(copy.getOptionalUint64(), 0xf000000000000000);
+ assertEquals(copy.getOptionalSint32(), -100);
+ assertEquals(copy.getOptionalSint64(), -0x8000000000000000);
+ assertEquals(copy.getOptionalFixed32(), 1234);
+ assertEquals(copy.getOptionalFixed64(), 0x1234567800000000);
+ assertEquals(copy.getOptionalSfixed32(), -1234);
+ assertEquals(copy.getOptionalSfixed64(), -0x1234567800000000);
+ assertEquals(copy.getOptionalFloat(), 1.5);
+ assertEquals(copy.getOptionalDouble(), -1.5);
+ assertEquals(copy.getOptionalBool(), true);
+ assertEquals(copy.getOptionalString(), 'hello world');
+ assertEquals(true, bytesCompare(copy.getOptionalBytes(), BYTES));
+ assertEquals(true, bytesCompare(copy.getOptionalBytes_asU8(), BYTES));
+ assertEquals(
+ copy.getOptionalBytes_asB64(), goog.crypt.base64.encodeByteArray(BYTES));
+
+ assertEquals(copy.getOptionalGroup().getA(), 100);
+ assertEquals(copy.getOptionalForeignMessage().getC(), 16);
+ assertEquals(copy.getOptionalForeignEnum(),
+ proto.jspb.test.ForeignEnum.FOREIGN_FOO);
+
+
+ assertEquals(copy.getOneofString(), 'oneof');
+ assertEquals(copy.getOneofFieldCase(),
+ proto.jspb.test.TestAllTypes.OneofFieldCase.ONEOF_STRING);
+
+ assertElementsEquals(copy.getRepeatedInt32List(), [-42]);
+ assertElementsEquals(copy.getRepeatedInt64List(), [-0x7fffffff00000000]);
+ assertElementsEquals(copy.getRepeatedUint32List(), [0x80000000]);
+ assertElementsEquals(copy.getRepeatedUint64List(), [0xf000000000000000]);
+ assertElementsEquals(copy.getRepeatedSint32List(), [-100]);
+ assertElementsEquals(copy.getRepeatedSint64List(), [-0x8000000000000000]);
+ assertElementsEquals(copy.getRepeatedFixed32List(), [1234]);
+ assertElementsEquals(copy.getRepeatedFixed64List(), [0x1234567800000000]);
+ assertElementsEquals(copy.getRepeatedSfixed32List(), [-1234]);
+ assertElementsEquals(copy.getRepeatedSfixed64List(), [-0x1234567800000000]);
+ assertElementsEquals(copy.getRepeatedFloatList(), [1.5]);
+ assertElementsEquals(copy.getRepeatedDoubleList(), [-1.5]);
+ assertElementsEquals(copy.getRepeatedBoolList(), [true]);
+ assertElementsEquals(copy.getRepeatedStringList(), ['hello world']);
+ assertEquals(copy.getRepeatedBytesList().length, 2);
+ assertEquals(true, bytesCompare(copy.getRepeatedBytesList_asU8()[0], BYTES));
+ assertEquals(true, bytesCompare(copy.getRepeatedBytesList()[0], BYTES));
+ assertEquals(true, bytesCompare(copy.getRepeatedBytesList_asU8()[1], BYTES));
+ assertEquals(copy.getRepeatedBytesList_asB64()[0], BYTES_B64);
+ assertEquals(copy.getRepeatedBytesList_asB64()[1], BYTES_B64);
+ assertEquals(copy.getRepeatedGroupList().length, 1);
+ assertEquals(copy.getRepeatedGroupList()[0].getA(), 100);
+ assertEquals(copy.getRepeatedForeignMessageList().length, 1);
+ assertEquals(copy.getRepeatedForeignMessageList()[0].getC(), 1000);
+ assertElementsEquals(copy.getRepeatedForeignEnumList(),
+ [proto.jspb.test.ForeignEnum.FOREIGN_FOO]);
+
+ assertElementsEquals(copy.getPackedRepeatedInt32List(), [-42]);
+ assertElementsEquals(copy.getPackedRepeatedInt64List(),
+ [-0x7fffffff00000000]);
+ assertElementsEquals(copy.getPackedRepeatedUint32List(), [0x80000000]);
+ assertElementsEquals(copy.getPackedRepeatedUint64List(),
+ [0xf000000000000000]);
+ assertElementsEquals(copy.getPackedRepeatedSint32List(), [-100]);
+ assertElementsEquals(copy.getPackedRepeatedSint64List(),
+ [-0x8000000000000000]);
+ assertElementsEquals(copy.getPackedRepeatedFixed32List(), [1234]);
+ assertElementsEquals(copy.getPackedRepeatedFixed64List(),
+ [0x1234567800000000]);
+ assertElementsEquals(copy.getPackedRepeatedSfixed32List(), [-1234]);
+ assertElementsEquals(copy.getPackedRepeatedSfixed64List(),
+ [-0x1234567800000000]);
+ assertElementsEquals(copy.getPackedRepeatedFloatList(), [1.5]);
+ assertElementsEquals(copy.getPackedRepeatedDoubleList(), [-1.5]);
+
+}
+
+
+/**
+ * Helper: verify that all expected extensions are present.
+ * @param {!proto.jspb.test.TestExtendable} msg
+ */
+function checkExtensions(msg) {
+ assertEquals(-42,
+ msg.getExtension(proto.jspb.test.extendOptionalInt32));
+ assertEquals(-0x7fffffff00000000,
+ msg.getExtension(proto.jspb.test.extendOptionalInt64));
+ assertEquals(0x80000000,
+ msg.getExtension(proto.jspb.test.extendOptionalUint32));
+ assertEquals(0xf000000000000000,
+ msg.getExtension(proto.jspb.test.extendOptionalUint64));
+ assertEquals(-100,
+ msg.getExtension(proto.jspb.test.extendOptionalSint32));
+ assertEquals(-0x8000000000000000,
+ msg.getExtension(proto.jspb.test.extendOptionalSint64));
+ assertEquals(1234,
+ msg.getExtension(proto.jspb.test.extendOptionalFixed32));
+ assertEquals(0x1234567800000000,
+ msg.getExtension(proto.jspb.test.extendOptionalFixed64));
+ assertEquals(-1234,
+ msg.getExtension(proto.jspb.test.extendOptionalSfixed32));
+ assertEquals(-0x1234567800000000,
+ msg.getExtension(proto.jspb.test.extendOptionalSfixed64));
+ assertEquals(1.5,
+ msg.getExtension(proto.jspb.test.extendOptionalFloat));
+ assertEquals(-1.5,
+ msg.getExtension(proto.jspb.test.extendOptionalDouble));
+ assertEquals(true,
+ msg.getExtension(proto.jspb.test.extendOptionalBool));
+ assertEquals('hello world',
+ msg.getExtension(proto.jspb.test.extendOptionalString));
+ assertEquals(
+ true, bytesCompare(
+ msg.getExtension(proto.jspb.test.extendOptionalBytes), BYTES));
+ assertEquals(16,
+ msg.getExtension(
+ proto.jspb.test.ExtendsWithMessage.optionalExtension).getFoo());
+
+
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendRepeatedInt32List),
+ [-42]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendRepeatedInt64List),
+ [-0x7fffffff00000000]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendRepeatedUint32List),
+ [0x80000000]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendRepeatedUint64List),
+ [0xf000000000000000]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendRepeatedSint32List),
+ [-100]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendRepeatedSint64List),
+ [-0x8000000000000000]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendRepeatedFixed32List),
+ [1234]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendRepeatedFixed64List),
+ [0x1234567800000000]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendRepeatedSfixed32List),
+ [-1234]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendRepeatedSfixed64List),
+ [-0x1234567800000000]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendRepeatedFloatList),
+ [1.5]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendRepeatedDoubleList),
+ [-1.5]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendRepeatedBoolList),
+ [true]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendRepeatedStringList),
+ ['hello world']);
+ assertEquals(
+ true,
+ bytesCompare(
+ msg.getExtension(proto.jspb.test.extendRepeatedBytesList)[0], BYTES));
+ assertEquals(1000,
+ msg.getExtension(
+ proto.jspb.test.ExtendsWithMessage.repeatedExtensionList)[0]
+ .getFoo());
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendRepeatedForeignEnumList),
+ [proto.jspb.test.ForeignEnum.FOREIGN_FOO]);
+
+
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendPackedRepeatedInt32List),
+ [-42]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendPackedRepeatedInt64List),
+ [-0x7fffffff00000000]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendPackedRepeatedUint32List),
+ [0x80000000]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendPackedRepeatedUint64List),
+ [0xf000000000000000]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendPackedRepeatedSint32List),
+ [-100]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendPackedRepeatedSint64List),
+ [-0x8000000000000000]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendPackedRepeatedFixed32List),
+ [1234]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendPackedRepeatedFixed64List),
+ [0x1234567800000000]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendPackedRepeatedSfixed32List),
+ [-1234]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendPackedRepeatedSfixed64List),
+ [-0x1234567800000000]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendPackedRepeatedFloatList),
+ [1.5]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendPackedRepeatedDoubleList),
+ [-1.5]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendPackedRepeatedBoolList),
+ [true]);
+ assertElementsEquals(
+ msg.getExtension(proto.jspb.test.extendPackedRepeatedForeignEnumList),
+ [proto.jspb.test.ForeignEnum.FOREIGN_FOO]);
+
+}
+
+
+describe('protoBinaryTest', function() {
+ /**
+ * Tests a basic serialization-deserializaton round-trip with all supported
+ * field types (on the TestAllTypes message type).
+ */
+ it('testRoundTrip', function() {
+ var msg = new proto.jspb.test.TestAllTypes();
+ fillAllFields(msg);
+ var encoded = msg.serializeBinary();
+ var decoded = proto.jspb.test.TestAllTypes.deserializeBinary(encoded);
+ checkAllFields(msg, decoded);
+ });
+
+ /**
+ * Test that base64 string and Uint8Array are interchangeable in bytes fields.
+ */
+ it('testBytesFieldsGettersInterop', function() {
+ var msg = new proto.jspb.test.TestAllTypes();
+ // Set from a base64 string and check all the getters work.
+ msg.setOptionalBytes(BYTES_B64);
+ assertTrue(bytesCompare(msg.getOptionalBytes_asU8(), BYTES));
+ assertTrue(bytesCompare(msg.getOptionalBytes_asB64(), BYTES));
+ assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
+
+ // Test binary serialize round trip doesn't break it.
+ msg = proto.jspb.test.TestAllTypes.deserializeBinary(msg.serializeBinary());
+ assertTrue(bytesCompare(msg.getOptionalBytes_asU8(), BYTES));
+ assertTrue(bytesCompare(msg.getOptionalBytes_asB64(), BYTES));
+ assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
+
+ msg = new proto.jspb.test.TestAllTypes();
+ // Set from a Uint8Array and check all the getters work.
+ msg.setOptionalBytes(BYTES);
+ assertTrue(bytesCompare(msg.getOptionalBytes_asU8(), BYTES));
+ assertTrue(bytesCompare(msg.getOptionalBytes_asB64(), BYTES));
+ assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
+
+ });
+
+ /**
+ * Test that bytes setters will receive result of any of the getters.
+ */
+ it('testBytesFieldsSettersInterop', function() {
+ var msg = new proto.jspb.test.TestAllTypes();
+ msg.setOptionalBytes(BYTES);
+ assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
+
+ msg.setOptionalBytes(msg.getOptionalBytes());
+ assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
+ msg.setOptionalBytes(msg.getOptionalBytes_asB64());
+ assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
+ msg.setOptionalBytes(msg.getOptionalBytes_asU8());
+ assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
+ });
+
+ /**
+ * Test that bytes setters will receive result of any of the getters.
+ */
+ it('testRepeatedBytesGetters', function() {
+ var msg = new proto.jspb.test.TestAllTypes();
+
+ function assertGetters() {
+ assertTrue(goog.isString(msg.getRepeatedBytesList_asB64()[0]));
+ assertTrue(goog.isString(msg.getRepeatedBytesList_asB64()[1]));
+ assertTrue(msg.getRepeatedBytesList_asU8()[0] instanceof Uint8Array);
+ assertTrue(msg.getRepeatedBytesList_asU8()[1] instanceof Uint8Array);
+
+ assertTrue(bytesCompare(msg.getRepeatedBytesList()[0], BYTES));
+ assertTrue(bytesCompare(msg.getRepeatedBytesList()[1], BYTES));
+ assertTrue(bytesCompare(msg.getRepeatedBytesList_asB64()[0], BYTES));
+ assertTrue(bytesCompare(msg.getRepeatedBytesList_asB64()[1], BYTES));
+ assertTrue(bytesCompare(msg.getRepeatedBytesList_asU8()[0], BYTES));
+ assertTrue(bytesCompare(msg.getRepeatedBytesList_asU8()[1], BYTES));
+ }
+
+ msg.setRepeatedBytesList([BYTES, BYTES]);
+ assertGetters();
+
+ msg.setRepeatedBytesList([BYTES_B64, BYTES_B64]);
+ assertGetters();
+
+ msg.setRepeatedBytesList([]);
+ assertEquals(0, msg.getRepeatedBytesList().length);
+ assertEquals(0, msg.getRepeatedBytesList_asB64().length);
+ assertEquals(0, msg.getRepeatedBytesList_asU8().length);
+ });
+
+ /**
+ * Helper: fill all extension values.
+ * @param {proto.jspb.test.TestExtendable} msg
+ */
+ function fillExtensions(msg) {
+ msg.setExtension(
+ proto.jspb.test.extendOptionalInt32, -42);
+ msg.setExtension(
+ proto.jspb.test.extendOptionalInt64, -0x7fffffff00000000);
+ msg.setExtension(
+ proto.jspb.test.extendOptionalUint32, 0x80000000);
+ msg.setExtension(
+ proto.jspb.test.extendOptionalUint64, 0xf000000000000000);
+ msg.setExtension(
+ proto.jspb.test.extendOptionalSint32, -100);
+ msg.setExtension(
+ proto.jspb.test.extendOptionalSint64, -0x8000000000000000);
+ msg.setExtension(
+ proto.jspb.test.extendOptionalFixed32, 1234);
+ msg.setExtension(
+ proto.jspb.test.extendOptionalFixed64, 0x1234567800000000);
+ msg.setExtension(
+ proto.jspb.test.extendOptionalSfixed32, -1234);
+ msg.setExtension(
+ proto.jspb.test.extendOptionalSfixed64, -0x1234567800000000);
+ msg.setExtension(
+ proto.jspb.test.extendOptionalFloat, 1.5);
+ msg.setExtension(
+ proto.jspb.test.extendOptionalDouble, -1.5);
+ msg.setExtension(
+ proto.jspb.test.extendOptionalBool, true);
+ msg.setExtension(
+ proto.jspb.test.extendOptionalString, 'hello world');
+ msg.setExtension(proto.jspb.test.extendOptionalBytes, BYTES);
+ var submsg = new proto.jspb.test.ExtendsWithMessage();
+ submsg.setFoo(16);
+ msg.setExtension(
+ proto.jspb.test.ExtendsWithMessage.optionalExtension, submsg);
+ msg.setExtension(
+ proto.jspb.test.extendOptionalForeignEnum,
+ proto.jspb.test.ForeignEnum.FOREIGN_FOO);
+
+
+ msg.setExtension(
+ proto.jspb.test.extendRepeatedInt32List, [-42]);
+ msg.setExtension(
+ proto.jspb.test.extendRepeatedInt64List, [-0x7fffffff00000000]);
+ msg.setExtension(
+ proto.jspb.test.extendRepeatedUint32List, [0x80000000]);
+ msg.setExtension(
+ proto.jspb.test.extendRepeatedUint64List, [0xf000000000000000]);
+ msg.setExtension(
+ proto.jspb.test.extendRepeatedSint32List, [-100]);
+ msg.setExtension(
+ proto.jspb.test.extendRepeatedSint64List, [-0x8000000000000000]);
+ msg.setExtension(
+ proto.jspb.test.extendRepeatedFixed32List, [1234]);
+ msg.setExtension(
+ proto.jspb.test.extendRepeatedFixed64List, [0x1234567800000000]);
+ msg.setExtension(
+ proto.jspb.test.extendRepeatedSfixed32List, [-1234]);
+ msg.setExtension(
+ proto.jspb.test.extendRepeatedSfixed64List, [-0x1234567800000000]);
+ msg.setExtension(
+ proto.jspb.test.extendRepeatedFloatList, [1.5]);
+ msg.setExtension(
+ proto.jspb.test.extendRepeatedDoubleList, [-1.5]);
+ msg.setExtension(
+ proto.jspb.test.extendRepeatedBoolList, [true]);
+ msg.setExtension(
+ proto.jspb.test.extendRepeatedStringList, ['hello world']);
+ msg.setExtension(proto.jspb.test.extendRepeatedBytesList, [BYTES]);
+ submsg = new proto.jspb.test.ExtendsWithMessage();
+ submsg.setFoo(1000);
+ msg.setExtension(
+ proto.jspb.test.ExtendsWithMessage.repeatedExtensionList, [submsg]);
+ msg.setExtension(proto.jspb.test.extendRepeatedForeignEnumList,
+ [proto.jspb.test.ForeignEnum.FOREIGN_FOO]);
+
+
+ msg.setExtension(
+ proto.jspb.test.extendPackedRepeatedInt32List, [-42]);
+ msg.setExtension(
+ proto.jspb.test.extendPackedRepeatedInt64List, [-0x7fffffff00000000]);
+ msg.setExtension(
+ proto.jspb.test.extendPackedRepeatedUint32List, [0x80000000]);
+ msg.setExtension(
+ proto.jspb.test.extendPackedRepeatedUint64List, [0xf000000000000000]);
+ msg.setExtension(
+ proto.jspb.test.extendPackedRepeatedSint32List, [-100]);
+ msg.setExtension(
+ proto.jspb.test.extendPackedRepeatedSint64List, [-0x8000000000000000]);
+ msg.setExtension(
+ proto.jspb.test.extendPackedRepeatedFixed32List, [1234]);
+ msg.setExtension(
+ proto.jspb.test.extendPackedRepeatedFixed64List, [0x1234567800000000]);
+ msg.setExtension(
+ proto.jspb.test.extendPackedRepeatedSfixed32List, [-1234]);
+ msg.setExtension(
+ proto.jspb.test.extendPackedRepeatedSfixed64List,
+ [-0x1234567800000000]);
+ msg.setExtension(
+ proto.jspb.test.extendPackedRepeatedFloatList, [1.5]);
+ msg.setExtension(
+ proto.jspb.test.extendPackedRepeatedDoubleList, [-1.5]);
+ msg.setExtension(
+ proto.jspb.test.extendPackedRepeatedBoolList, [true]);
+ msg.setExtension(proto.jspb.test.extendPackedRepeatedForeignEnumList,
+ [proto.jspb.test.ForeignEnum.FOREIGN_FOO]);
+
+ }
+
+
+ /**
+ * Tests extension serialization and deserialization.
+ */
+ it('testExtensions', function() {
+ var msg = new proto.jspb.test.TestExtendable();
+ fillExtensions(msg);
+ var encoded = msg.serializeBinary();
+ var decoded = proto.jspb.test.TestExtendable.deserializeBinary(encoded);
+ checkExtensions(decoded);
+ });
+});
diff --git a/js/compatibility_tests/v3.1.0/binary/reader_test.js b/js/compatibility_tests/v3.1.0/binary/reader_test.js
new file mode 100644
index 00000000..95711385
--- /dev/null
+++ b/js/compatibility_tests/v3.1.0/binary/reader_test.js
@@ -0,0 +1,922 @@
+// 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.
+
+/**
+ * @fileoverview Test cases for jspb's binary protocol buffer reader.
+ *
+ * There are two particular magic numbers that need to be pointed out -
+ * 2^64-1025 is the largest number representable as both a double and an
+ * unsigned 64-bit integer, and 2^63-513 is the largest number representable as
+ * both a double and a signed 64-bit integer.
+ *
+ * Test suite is written using Jasmine -- see http://jasmine.github.io/
+ *
+ * @author aappleby@google.com (Austin Appleby)
+ */
+
+goog.require('goog.testing.asserts');
+goog.require('jspb.BinaryConstants');
+goog.require('jspb.BinaryDecoder');
+goog.require('jspb.BinaryReader');
+goog.require('jspb.BinaryWriter');
+
+
+
+describe('binaryReaderTest', function() {
+ /**
+ * Tests the reader instance cache.
+ */
+ it('testInstanceCaches', /** @suppress {visibility} */ function() {
+ var writer = new jspb.BinaryWriter();
+ var dummyMessage = /** @type {!jspb.BinaryMessage} */({});
+ writer.writeMessage(1, dummyMessage, goog.nullFunction);
+ writer.writeMessage(2, dummyMessage, goog.nullFunction);
+
+ var buffer = writer.getResultBuffer();
+
+ // Empty the instance caches.
+ jspb.BinaryReader.instanceCache_ = [];
+
+ // Allocating and then freeing three decoders should leave us with three in
+ // the cache.
+
+ var decoder1 = jspb.BinaryDecoder.alloc();
+ var decoder2 = jspb.BinaryDecoder.alloc();
+ var decoder3 = jspb.BinaryDecoder.alloc();
+ decoder1.free();
+ decoder2.free();
+ decoder3.free();
+
+ assertEquals(3, jspb.BinaryDecoder.instanceCache_.length);
+ assertEquals(0, jspb.BinaryReader.instanceCache_.length);
+
+ // Allocating and then freeing a reader should remove one decoder from its
+ // cache, but it should stay stuck to the reader afterwards since we can't
+ // have a reader without a decoder.
+ jspb.BinaryReader.alloc().free();
+
+ assertEquals(2, jspb.BinaryDecoder.instanceCache_.length);
+ assertEquals(1, jspb.BinaryReader.instanceCache_.length);
+
+ // Allocating a reader should remove a reader from the cache.
+ var reader = jspb.BinaryReader.alloc(buffer);
+
+ assertEquals(2, jspb.BinaryDecoder.instanceCache_.length);
+ assertEquals(0, jspb.BinaryReader.instanceCache_.length);
+
+ // Processing the message reuses the current reader.
+ reader.nextField();
+ assertEquals(1, reader.getFieldNumber());
+ reader.readMessage(dummyMessage, function() {
+ assertEquals(0, jspb.BinaryReader.instanceCache_.length);
+ });
+
+ reader.nextField();
+ assertEquals(2, reader.getFieldNumber());
+ reader.readMessage(dummyMessage, function() {
+ assertEquals(0, jspb.BinaryReader.instanceCache_.length);
+ });
+
+ assertEquals(false, reader.nextField());
+
+ assertEquals(2, jspb.BinaryDecoder.instanceCache_.length);
+ assertEquals(0, jspb.BinaryReader.instanceCache_.length);
+
+ // Freeing the reader should put it back into the cache.
+ reader.free();
+
+ assertEquals(2, jspb.BinaryDecoder.instanceCache_.length);
+ assertEquals(1, jspb.BinaryReader.instanceCache_.length);
+ });
+
+
+ /**
+ * @param {number} x
+ * @return {number}
+ */
+ function truncate(x) {
+ var temp = new Float32Array(1);
+ temp[0] = x;
+ return temp[0];
+ }
+
+
+ /**
+ * Verifies that misuse of the reader class triggers assertions.
+ */
+ it('testReadErrors', /** @suppress {checkTypes|visibility} */ function() {
+ // Calling readMessage on a non-delimited field should trigger an
+ // assertion.
+ var reader = jspb.BinaryReader.alloc([8, 1]);
+ var dummyMessage = /** @type {!jspb.BinaryMessage} */({});
+ reader.nextField();
+ assertThrows(function() {
+ reader.readMessage(dummyMessage, goog.nullFunction);
+ });
+
+ // Reading past the end of the stream should trigger an assertion.
+ reader = jspb.BinaryReader.alloc([9, 1]);
+ reader.nextField();
+ assertThrows(function() {reader.readFixed64()});
+
+ // Reading past the end of a submessage should trigger an assertion.
+ reader = jspb.BinaryReader.alloc([10, 4, 13, 1, 1, 1]);
+ reader.nextField();
+ reader.readMessage(dummyMessage, function() {
+ reader.nextField();
+ assertThrows(function() {reader.readFixed32()});
+ });
+
+ // Skipping an invalid field should trigger an assertion.
+ reader = jspb.BinaryReader.alloc([12, 1]);
+ reader.nextWireType_ = 1000;
+ assertThrows(function() {reader.skipField()});
+
+ // Reading fields with the wrong wire type should assert.
+ reader = jspb.BinaryReader.alloc([9, 0, 0, 0, 0, 0, 0, 0, 0]);
+ reader.nextField();
+ assertThrows(function() {reader.readInt32()});
+ assertThrows(function() {reader.readInt32String()});
+ assertThrows(function() {reader.readInt64()});
+ assertThrows(function() {reader.readInt64String()});
+ assertThrows(function() {reader.readUint32()});
+ assertThrows(function() {reader.readUint32String()});
+ assertThrows(function() {reader.readUint64()});
+ assertThrows(function() {reader.readUint64String()});
+ assertThrows(function() {reader.readSint32()});
+ assertThrows(function() {reader.readBool()});
+ assertThrows(function() {reader.readEnum()});
+
+ reader = jspb.BinaryReader.alloc([8, 1]);
+ reader.nextField();
+ assertThrows(function() {reader.readFixed32()});
+ assertThrows(function() {reader.readFixed64()});
+ assertThrows(function() {reader.readSfixed32()});
+ assertThrows(function() {reader.readSfixed64()});
+ assertThrows(function() {reader.readFloat()});
+ assertThrows(function() {reader.readDouble()});
+
+ assertThrows(function() {reader.readString()});
+ assertThrows(function() {reader.readBytes()});
+ });
+
+
+ /**
+ * Tests encoding and decoding of unsigned field types.
+ * @param {Function} readField
+ * @param {Function} writeField
+ * @param {number} epsilon
+ * @param {number} upperLimit
+ * @param {Function} filter
+ * @private
+ * @suppress {missingProperties}
+ */
+ var doTestUnsignedField_ = function(readField,
+ writeField, epsilon, upperLimit, filter) {
+ assertNotNull(readField);
+ assertNotNull(writeField);
+
+ var writer = new jspb.BinaryWriter();
+
+ // Encode zero and limits.
+ writeField.call(writer, 1, filter(0));
+ writeField.call(writer, 2, filter(epsilon));
+ writeField.call(writer, 3, filter(upperLimit));
+
+ // Encode positive values.
+ for (var cursor = epsilon; cursor < upperLimit; cursor *= 1.1) {
+ writeField.call(writer, 4, filter(cursor));
+ }
+
+ var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
+
+ // Check zero and limits.
+ reader.nextField();
+ assertEquals(1, reader.getFieldNumber());
+ assertEquals(filter(0), readField.call(reader));
+
+ reader.nextField();
+ assertEquals(2, reader.getFieldNumber());
+ assertEquals(filter(epsilon), readField.call(reader));
+
+ reader.nextField();
+ assertEquals(3, reader.getFieldNumber());
+ assertEquals(filter(upperLimit), readField.call(reader));
+
+ // Check positive values.
+ for (var cursor = epsilon; cursor < upperLimit; cursor *= 1.1) {
+ reader.nextField();
+ if (4 != reader.getFieldNumber()) throw 'fail!';
+ if (filter(cursor) != readField.call(reader)) throw 'fail!';
+ }
+ };
+
+
+ /**
+ * Tests encoding and decoding of signed field types.
+ * @param {Function} readField
+ * @param {Function} writeField
+ * @param {number} epsilon
+ * @param {number} lowerLimit
+ * @param {number} upperLimit
+ * @param {Function} filter
+ * @private
+ * @suppress {missingProperties}
+ */
+ var doTestSignedField_ = function(readField,
+ writeField, epsilon, lowerLimit, upperLimit, filter) {
+ var writer = new jspb.BinaryWriter();
+
+ // Encode zero and limits.
+ writeField.call(writer, 1, filter(lowerLimit));
+ writeField.call(writer, 2, filter(-epsilon));
+ writeField.call(writer, 3, filter(0));
+ writeField.call(writer, 4, filter(epsilon));
+ writeField.call(writer, 5, filter(upperLimit));
+
+ var inputValues = [];
+
+ // Encode negative values.
+ for (var cursor = lowerLimit; cursor < -epsilon; cursor /= 1.1) {
+ var val = filter(cursor);
+ writeField.call(writer, 6, val);
+ inputValues.push({
+ fieldNumber: 6,
+ value: val
+ });
+ }
+
+ // Encode positive values.
+ for (var cursor = epsilon; cursor < upperLimit; cursor *= 1.1) {
+ var val = filter(cursor);
+ writeField.call(writer, 7, val);
+ inputValues.push({
+ fieldNumber: 7,
+ value: val
+ });
+ }
+
+ var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
+
+ // Check zero and limits.
+ reader.nextField();
+ assertEquals(1, reader.getFieldNumber());
+ assertEquals(filter(lowerLimit), readField.call(reader));
+
+ reader.nextField();
+ assertEquals(2, reader.getFieldNumber());
+ assertEquals(filter(-epsilon), readField.call(reader));
+
+ reader.nextField();
+ assertEquals(3, reader.getFieldNumber());
+ assertEquals(filter(0), readField.call(reader));
+
+ reader.nextField();
+ assertEquals(4, reader.getFieldNumber());
+ assertEquals(filter(epsilon), readField.call(reader));
+
+ reader.nextField();
+ assertEquals(5, reader.getFieldNumber());
+ assertEquals(filter(upperLimit), readField.call(reader));
+
+ for (var i = 0; i < inputValues.length; i++) {
+ var expected = inputValues[i];
+ reader.nextField();
+ assertEquals(expected.fieldNumber, reader.getFieldNumber());
+ assertEquals(expected.value, readField.call(reader));
+ }
+ };
+
+
+ /**
+ * Tests fields that use varint encoding.
+ */
+ it('testVarintFields', function() {
+ assertNotUndefined(jspb.BinaryReader.prototype.readUint32);
+ assertNotUndefined(jspb.BinaryWriter.prototype.writeUint32);
+ assertNotUndefined(jspb.BinaryReader.prototype.readUint64);
+ assertNotUndefined(jspb.BinaryWriter.prototype.writeUint64);
+ assertNotUndefined(jspb.BinaryReader.prototype.readBool);
+ assertNotUndefined(jspb.BinaryWriter.prototype.writeBool);
+ doTestUnsignedField_(
+ jspb.BinaryReader.prototype.readUint32,
+ jspb.BinaryWriter.prototype.writeUint32,
+ 1, Math.pow(2, 32) - 1, Math.round);
+
+ doTestUnsignedField_(
+ jspb.BinaryReader.prototype.readUint64,
+ jspb.BinaryWriter.prototype.writeUint64,
+ 1, Math.pow(2, 64) - 1025, Math.round);
+
+ doTestSignedField_(
+ jspb.BinaryReader.prototype.readInt32,
+ jspb.BinaryWriter.prototype.writeInt32,
+ 1, -Math.pow(2, 31), Math.pow(2, 31) - 1, Math.round);
+
+ doTestSignedField_(
+ jspb.BinaryReader.prototype.readInt64,
+ jspb.BinaryWriter.prototype.writeInt64,
+ 1, -Math.pow(2, 63), Math.pow(2, 63) - 513, Math.round);
+
+ doTestSignedField_(
+ jspb.BinaryReader.prototype.readEnum,
+ jspb.BinaryWriter.prototype.writeEnum,
+ 1, -Math.pow(2, 31), Math.pow(2, 31) - 1, Math.round);
+
+ doTestUnsignedField_(
+ jspb.BinaryReader.prototype.readBool,
+ jspb.BinaryWriter.prototype.writeBool,
+ 1, 1, function(x) { return !!x; });
+ });
+
+
+ /**
+ * Tests reading a field from hexadecimal string (format: '08 BE EF').
+ * @param {Function} readField
+ * @param {number} expected
+ * @param {string} hexString
+ */
+ function doTestHexStringVarint_(readField, expected, hexString) {
+ var bytesCount = (hexString.length + 1) / 3;
+ var bytes = new Uint8Array(bytesCount);
+ for (var i = 0; i < bytesCount; i++) {
+ bytes[i] = parseInt(hexString.substring(i * 3, i * 3 + 2), 16);
+ }
+ var reader = jspb.BinaryReader.alloc(bytes);
+ reader.nextField();
+ assertEquals(expected, readField.call(reader));
+ }
+
+
+ /**
+ * Tests non-canonical redundant varint decoding.
+ */
+ it('testRedundantVarintFields', function() {
+ assertNotNull(jspb.BinaryReader.prototype.readUint32);
+ assertNotNull(jspb.BinaryReader.prototype.readUint64);
+ assertNotNull(jspb.BinaryReader.prototype.readSint32);
+ assertNotNull(jspb.BinaryReader.prototype.readSint64);
+
+ // uint32 and sint32 take no more than 5 bytes
+ // 08 - field prefix (type = 0 means varint)
+ doTestHexStringVarint_(
+ jspb.BinaryReader.prototype.readUint32,
+ 12, '08 8C 80 80 80 00');
+
+ // 11 stands for -6 in zigzag encoding
+ doTestHexStringVarint_(
+ jspb.BinaryReader.prototype.readSint32,
+ -6, '08 8B 80 80 80 00');
+
+ // uint64 and sint64 take no more than 10 bytes
+ // 08 - field prefix (type = 0 means varint)
+ doTestHexStringVarint_(
+ jspb.BinaryReader.prototype.readUint64,
+ 12, '08 8C 80 80 80 80 80 80 80 80 00');
+
+ // 11 stands for -6 in zigzag encoding
+ doTestHexStringVarint_(
+ jspb.BinaryReader.prototype.readSint64,
+ -6, '08 8B 80 80 80 80 80 80 80 80 00');
+ });
+
+
+ /**
+ * Tests 64-bit fields that are handled as strings.
+ */
+ it('testStringInt64Fields', function() {
+ var writer = new jspb.BinaryWriter();
+
+ var testSignedData = [
+ '2730538252207801776',
+ '-2688470994844604560',
+ '3398529779486536359',
+ '3568577411627971000',
+ '272477188847484900',
+ '-6649058714086158188',
+ '-7695254765712060806',
+ '-4525541438037104029',
+ '-4993706538836508568',
+ '4990160321893729138'
+ ];
+ var testUnsignedData = [
+ '7822732630241694882',
+ '6753602971916687352',
+ '2399935075244442116',
+ '8724292567325338867',
+ '16948784802625696584',
+ '4136275908516066934',
+ '3575388346793700364',
+ '5167142028379259461',
+ '1557573948689737699',
+ '17100725280812548567'
+ ];
+
+ for (var i = 0; i < testSignedData.length; i++) {
+ writer.writeInt64String(2 * i + 1, testSignedData[i]);
+ writer.writeUint64String(2 * i + 2, testUnsignedData[i]);
+ }
+
+ var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
+
+ for (var i = 0; i < testSignedData.length; i++) {
+ reader.nextField();
+ assertEquals(2 * i + 1, reader.getFieldNumber());
+ assertEquals(testSignedData[i], reader.readInt64String());
+ reader.nextField();
+ assertEquals(2 * i + 2, reader.getFieldNumber());
+ assertEquals(testUnsignedData[i], reader.readUint64String());
+ }
+ });
+
+
+ /**
+ * Tests fields that use zigzag encoding.
+ */
+ it('testZigzagFields', function() {
+ doTestSignedField_(
+ jspb.BinaryReader.prototype.readSint32,
+ jspb.BinaryWriter.prototype.writeSint32,
+ 1, -Math.pow(2, 31), Math.pow(2, 31) - 1, Math.round);
+
+ doTestSignedField_(
+ jspb.BinaryReader.prototype.readSint64,
+ jspb.BinaryWriter.prototype.writeSint64,
+ 1, -Math.pow(2, 63), Math.pow(2, 63) - 513, Math.round);
+ });
+
+
+ /**
+ * Tests fields that use fixed-length encoding.
+ */
+ it('testFixedFields', function() {
+ doTestUnsignedField_(
+ jspb.BinaryReader.prototype.readFixed32,
+ jspb.BinaryWriter.prototype.writeFixed32,
+ 1, Math.pow(2, 32) - 1, Math.round);
+
+ doTestUnsignedField_(
+ jspb.BinaryReader.prototype.readFixed64,
+ jspb.BinaryWriter.prototype.writeFixed64,
+ 1, Math.pow(2, 64) - 1025, Math.round);
+
+ doTestSignedField_(
+ jspb.BinaryReader.prototype.readSfixed32,
+ jspb.BinaryWriter.prototype.writeSfixed32,
+ 1, -Math.pow(2, 31), Math.pow(2, 31) - 1, Math.round);
+
+ doTestSignedField_(
+ jspb.BinaryReader.prototype.readSfixed64,
+ jspb.BinaryWriter.prototype.writeSfixed64,
+ 1, -Math.pow(2, 63), Math.pow(2, 63) - 513, Math.round);
+ });
+
+
+ /**
+ * Tests floating point fields.
+ */
+ it('testFloatFields', function() {
+ doTestSignedField_(
+ jspb.BinaryReader.prototype.readFloat,
+ jspb.BinaryWriter.prototype.writeFloat,
+ jspb.BinaryConstants.FLOAT32_MIN,
+ -jspb.BinaryConstants.FLOAT32_MAX,
+ jspb.BinaryConstants.FLOAT32_MAX,
+ truncate);
+
+ doTestSignedField_(
+ jspb.BinaryReader.prototype.readDouble,
+ jspb.BinaryWriter.prototype.writeDouble,
+ jspb.BinaryConstants.FLOAT64_EPS * 10,
+ -jspb.BinaryConstants.FLOAT64_MIN,
+ jspb.BinaryConstants.FLOAT64_MIN,
+ function(x) { return x; });
+ });
+
+
+ /**
+ * Tests length-delimited string fields.
+ */
+ it('testStringFields', function() {
+ var s1 = 'The quick brown fox jumps over the lazy dog.';
+ var s2 = '人人生而自由,在尊嚴和權利上一律平等。';
+
+ var writer = new jspb.BinaryWriter();
+
+ writer.writeString(1, s1);
+ writer.writeString(2, s2);
+
+ var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
+
+ reader.nextField();
+ assertEquals(1, reader.getFieldNumber());
+ assertEquals(s1, reader.readString());
+
+ reader.nextField();
+ assertEquals(2, reader.getFieldNumber());
+ assertEquals(s2, reader.readString());
+ });
+
+
+ /**
+ * Tests length-delimited byte fields.
+ */
+ it('testByteFields', function() {
+ var message = [];
+ var lowerLimit = 1;
+ var upperLimit = 256;
+ var scale = 1.1;
+
+ var writer = new jspb.BinaryWriter();
+
+ for (var cursor = lowerLimit; cursor < upperLimit; cursor *= 1.1) {
+ var len = Math.round(cursor);
+ var bytes = [];
+ for (var i = 0; i < len; i++) bytes.push(i % 256);
+
+ writer.writeBytes(len, bytes);
+ }
+
+ var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
+
+ for (var cursor = lowerLimit; reader.nextField(); cursor *= 1.1) {
+ var len = Math.round(cursor);
+ if (len != reader.getFieldNumber()) throw 'fail!';
+
+ var bytes = reader.readBytes();
+ if (len != bytes.length) throw 'fail!';
+ for (var i = 0; i < bytes.length; i++) {
+ if (i % 256 != bytes[i]) throw 'fail!';
+ }
+ }
+ });
+
+
+ /**
+ * Tests nested messages.
+ */
+ it('testNesting', function() {
+ var writer = new jspb.BinaryWriter();
+ var dummyMessage = /** @type {!jspb.BinaryMessage} */({});
+
+ writer.writeInt32(1, 100);
+
+ // Add one message with 3 int fields.
+ writer.writeMessage(2, dummyMessage, function() {
+ writer.writeInt32(3, 300);
+ writer.writeInt32(4, 400);
+ writer.writeInt32(5, 500);
+ });
+
+ // Add one empty message.
+ writer.writeMessage(6, dummyMessage, goog.nullFunction);
+
+ writer.writeInt32(7, 700);
+
+ var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
+
+ // Validate outermost message.
+
+ reader.nextField();
+ assertEquals(1, reader.getFieldNumber());
+ assertEquals(100, reader.readInt32());
+
+ reader.nextField();
+ assertEquals(2, reader.getFieldNumber());
+ reader.readMessage(dummyMessage, function() {
+ // Validate embedded message 1.
+ reader.nextField();
+ assertEquals(3, reader.getFieldNumber());
+ assertEquals(300, reader.readInt32());
+
+ reader.nextField();
+ assertEquals(4, reader.getFieldNumber());
+ assertEquals(400, reader.readInt32());
+
+ reader.nextField();
+ assertEquals(5, reader.getFieldNumber());
+ assertEquals(500, reader.readInt32());
+
+ assertEquals(false, reader.nextField());
+ });
+
+ reader.nextField();
+ assertEquals(6, reader.getFieldNumber());
+ reader.readMessage(dummyMessage, function() {
+ // Validate embedded message 2.
+
+ assertEquals(false, reader.nextField());
+ });
+
+ reader.nextField();
+ assertEquals(7, reader.getFieldNumber());
+ assertEquals(700, reader.readInt32());
+
+ assertEquals(false, reader.nextField());
+ });
+
+ /**
+ * Tests skipping fields of each type by interleaving them with sentinel
+ * values and skipping everything that's not a sentinel.
+ */
+ it('testSkipField', function() {
+ var writer = new jspb.BinaryWriter();
+
+ var sentinel = 123456789;
+
+ // Write varint fields of different sizes.
+ writer.writeInt32(1, sentinel);
+ writer.writeInt32(1, 1);
+ writer.writeInt32(1, 1000);
+ writer.writeInt32(1, 1000000);
+ writer.writeInt32(1, 1000000000);
+
+ // Write fixed 64-bit encoded fields.
+ writer.writeInt32(2, sentinel);
+ writer.writeDouble(2, 1);
+ writer.writeFixed64(2, 1);
+ writer.writeSfixed64(2, 1);
+
+ // Write fixed 32-bit encoded fields.
+ writer.writeInt32(3, sentinel);
+ writer.writeFloat(3, 1);
+ writer.writeFixed32(3, 1);
+ writer.writeSfixed32(3, 1);
+
+ // Write delimited fields.
+ writer.writeInt32(4, sentinel);
+ writer.writeBytes(4, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
+ writer.writeString(4, 'The quick brown fox jumps over the lazy dog');
+
+ // Write a group with a nested group inside.
+ writer.writeInt32(5, sentinel);
+ var dummyMessage = /** @type {!jspb.BinaryMessage} */({});
+ writer.writeGroup(5, dummyMessage, function() {
+ writer.writeInt64(42, 42);
+ writer.writeGroup(6, dummyMessage, function() {
+ writer.writeInt64(84, 42);
+ });
+ });
+
+ // Write final sentinel.
+ writer.writeInt32(6, sentinel);
+
+ var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
+
+ function skip(field, count) {
+ for (var i = 0; i < count; i++) {
+ reader.nextField();
+ if (field != reader.getFieldNumber()) throw 'fail!';
+ reader.skipField();
+ }
+ }
+
+ reader.nextField();
+ assertEquals(1, reader.getFieldNumber());
+ assertEquals(sentinel, reader.readInt32());
+ skip(1, 4);
+
+ reader.nextField();
+ assertEquals(2, reader.getFieldNumber());
+ assertEquals(sentinel, reader.readInt32());
+ skip(2, 3);
+
+ reader.nextField();
+ assertEquals(3, reader.getFieldNumber());
+ assertEquals(sentinel, reader.readInt32());
+ skip(3, 3);
+
+ reader.nextField();
+ assertEquals(4, reader.getFieldNumber());
+ assertEquals(sentinel, reader.readInt32());
+ skip(4, 2);
+
+ reader.nextField();
+ assertEquals(5, reader.getFieldNumber());
+ assertEquals(sentinel, reader.readInt32());
+ skip(5, 1);
+
+ reader.nextField();
+ assertEquals(6, reader.getFieldNumber());
+ assertEquals(sentinel, reader.readInt32());
+ });
+
+
+ /**
+ * Tests packed fields.
+ */
+ it('testPackedFields', function() {
+ var writer = new jspb.BinaryWriter();
+
+ var sentinel = 123456789;
+
+ var unsignedData = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
+ var signedData = [-1, 2, -3, 4, -5, 6, -7, 8, -9, 10];
+ var floatData = [1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10];
+ var doubleData = [1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10];
+ var boolData = [true, false, true, true, false, false, true, false];
+
+ for (var i = 0; i < floatData.length; i++) {
+ floatData[i] = truncate(floatData[i]);
+ }
+
+ writer.writeInt32(1, sentinel);
+
+ writer.writePackedInt32(2, signedData);
+ writer.writePackedInt64(2, signedData);
+ writer.writePackedUint32(2, unsignedData);
+ writer.writePackedUint64(2, unsignedData);
+ writer.writePackedSint32(2, signedData);
+ writer.writePackedSint64(2, signedData);
+ writer.writePackedFixed32(2, unsignedData);
+ writer.writePackedFixed64(2, unsignedData);
+ writer.writePackedSfixed32(2, signedData);
+ writer.writePackedSfixed64(2, signedData);
+ writer.writePackedFloat(2, floatData);
+ writer.writePackedDouble(2, doubleData);
+ writer.writePackedBool(2, boolData);
+ writer.writePackedEnum(2, unsignedData);
+
+ writer.writeInt32(3, sentinel);
+
+ var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
+
+ reader.nextField();
+ assertEquals(sentinel, reader.readInt32());
+
+ reader.nextField();
+ assertElementsEquals(reader.readPackedInt32(), signedData);
+
+ reader.nextField();
+ assertElementsEquals(reader.readPackedInt64(), signedData);
+
+ reader.nextField();
+ assertElementsEquals(reader.readPackedUint32(), unsignedData);
+
+ reader.nextField();
+ assertElementsEquals(reader.readPackedUint64(), unsignedData);
+
+ reader.nextField();
+ assertElementsEquals(reader.readPackedSint32(), signedData);
+
+ reader.nextField();
+ assertElementsEquals(reader.readPackedSint64(), signedData);
+
+ reader.nextField();
+ assertElementsEquals(reader.readPackedFixed32(), unsignedData);
+
+ reader.nextField();
+ assertElementsEquals(reader.readPackedFixed64(), unsignedData);
+
+ reader.nextField();
+ assertElementsEquals(reader.readPackedSfixed32(), signedData);
+
+ reader.nextField();
+ assertElementsEquals(reader.readPackedSfixed64(), signedData);
+
+ reader.nextField();
+ assertElementsEquals(reader.readPackedFloat(), floatData);
+
+ reader.nextField();
+ assertElementsEquals(reader.readPackedDouble(), doubleData);
+
+ reader.nextField();
+ assertElementsEquals(reader.readPackedBool(), boolData);
+
+ reader.nextField();
+ assertElementsEquals(reader.readPackedEnum(), unsignedData);
+
+ reader.nextField();
+ assertEquals(sentinel, reader.readInt32());
+ });
+
+
+ /**
+ * Byte blobs inside nested messages should always have their byte offset set
+ * relative to the start of the outermost blob, not the start of their parent
+ * blob.
+ */
+ it('testNestedBlobs', function() {
+ // Create a proto consisting of two nested messages, with the inner one
+ // containing a blob of bytes.
+
+ var fieldTag = (1 << 3) | jspb.BinaryConstants.WireType.DELIMITED;
+ var blob = [1, 2, 3, 4, 5];
+ var writer = new jspb.BinaryWriter();
+ var dummyMessage = /** @type {!jspb.BinaryMessage} */({});
+
+ writer.writeMessage(1, dummyMessage, function() {
+ writer.writeMessage(1, dummyMessage, function() {
+ writer.writeBytes(1, blob);
+ });
+ });
+
+ // Peel off the outer two message layers. Each layer should have two bytes
+ // of overhead, one for the field tag and one for the length of the inner
+ // blob.
+
+ var decoder1 = new jspb.BinaryDecoder(writer.getResultBuffer());
+ assertEquals(fieldTag, decoder1.readUnsignedVarint32());
+ assertEquals(blob.length + 4, decoder1.readUnsignedVarint32());
+
+ var decoder2 = new jspb.BinaryDecoder(decoder1.readBytes(blob.length + 4));
+ assertEquals(fieldTag, decoder2.readUnsignedVarint32());
+ assertEquals(blob.length + 2, decoder2.readUnsignedVarint32());
+
+ assertEquals(fieldTag, decoder2.readUnsignedVarint32());
+ assertEquals(blob.length, decoder2.readUnsignedVarint32());
+ var bytes = decoder2.readBytes(blob.length);
+
+ assertElementsEquals(bytes, blob);
+ });
+
+
+ /**
+ * Tests read callbacks.
+ */
+ it('testReadCallbacks', function() {
+ var writer = new jspb.BinaryWriter();
+ var dummyMessage = /** @type {!jspb.BinaryMessage} */({});
+
+ // Add an int, a submessage, and another int.
+ writer.writeInt32(1, 100);
+
+ writer.writeMessage(2, dummyMessage, function() {
+ writer.writeInt32(3, 300);
+ writer.writeInt32(4, 400);
+ writer.writeInt32(5, 500);
+ });
+
+ writer.writeInt32(7, 700);
+
+ // Create the reader and register a custom read callback.
+ var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
+
+ /**
+ * @param {!jspb.BinaryReader} reader
+ * @return {*}
+ */
+ function readCallback(reader) {
+ reader.nextField();
+ assertEquals(3, reader.getFieldNumber());
+ assertEquals(300, reader.readInt32());
+
+ reader.nextField();
+ assertEquals(4, reader.getFieldNumber());
+ assertEquals(400, reader.readInt32());
+
+ reader.nextField();
+ assertEquals(5, reader.getFieldNumber());
+ assertEquals(500, reader.readInt32());
+
+ assertEquals(false, reader.nextField());
+ };
+
+ reader.registerReadCallback('readCallback', readCallback);
+
+ // Read the container message.
+ reader.nextField();
+ assertEquals(1, reader.getFieldNumber());
+ assertEquals(100, reader.readInt32());
+
+ reader.nextField();
+ assertEquals(2, reader.getFieldNumber());
+ reader.readMessage(dummyMessage, function() {
+ // Decode the embedded message using the registered callback.
+ reader.runReadCallback('readCallback');
+ });
+
+ reader.nextField();
+ assertEquals(7, reader.getFieldNumber());
+ assertEquals(700, reader.readInt32());
+
+ assertEquals(false, reader.nextField());
+ });
+});
diff --git a/js/compatibility_tests/v3.1.0/binary/utils_test.js b/js/compatibility_tests/v3.1.0/binary/utils_test.js
new file mode 100644
index 00000000..d27e5ea2
--- /dev/null
+++ b/js/compatibility_tests/v3.1.0/binary/utils_test.js
@@ -0,0 +1,668 @@
+// 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.
+
+/**
+ * @fileoverview Test cases for jspb's helper functions.
+ *
+ * Test suite is written using Jasmine -- see http://jasmine.github.io/
+ *
+ * @author aappleby@google.com (Austin Appleby)
+ */
+
+goog.require('goog.crypt.base64');
+goog.require('goog.testing.asserts');
+goog.require('jspb.BinaryConstants');
+goog.require('jspb.BinaryWriter');
+goog.require('jspb.utils');
+
+
+/**
+ * @param {number} x
+ * @return {number}
+ */
+function truncate(x) {
+ var temp = new Float32Array(1);
+ temp[0] = x;
+ return temp[0];
+}
+
+
+/**
+ * Converts an 64-bit integer in split representation to a 64-bit hash string
+ * (8 bits encoded per character).
+ * @param {number} bitsLow The low 32 bits of the split 64-bit integer.
+ * @param {number} bitsHigh The high 32 bits of the split 64-bit integer.
+ * @return {string} The encoded hash string, 8 bits per character.
+ */
+function toHashString(bitsLow, bitsHigh) {
+ return String.fromCharCode((bitsLow >>> 0) & 0xFF,
+ (bitsLow >>> 8) & 0xFF,
+ (bitsLow >>> 16) & 0xFF,
+ (bitsLow >>> 24) & 0xFF,
+ (bitsHigh >>> 0) & 0xFF,
+ (bitsHigh >>> 8) & 0xFF,
+ (bitsHigh >>> 16) & 0xFF,
+ (bitsHigh >>> 24) & 0xFF);
+}
+
+
+describe('binaryUtilsTest', function() {
+ /**
+ * Tests lossless binary-to-decimal conversion.
+ */
+ it('testDecimalConversion', function() {
+ // Check some magic numbers.
+ var result =
+ jspb.utils.joinUnsignedDecimalString(0x89e80001, 0x8ac72304);
+ assertEquals('10000000000000000001', result);
+
+ result = jspb.utils.joinUnsignedDecimalString(0xacd05f15, 0x1b69b4b);
+ assertEquals('123456789123456789', result);
+
+ result = jspb.utils.joinUnsignedDecimalString(0xeb1f0ad2, 0xab54a98c);
+ assertEquals('12345678901234567890', result);
+
+ result = jspb.utils.joinUnsignedDecimalString(0xe3b70cb1, 0x891087b8);
+ assertEquals('9876543210987654321', result);
+
+ // Check limits.
+ result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x00000000);
+ assertEquals('0', result);
+
+ result = jspb.utils.joinUnsignedDecimalString(0xFFFFFFFF, 0xFFFFFFFF);
+ assertEquals('18446744073709551615', result);
+
+ // Check each bit of the low dword.
+ for (var i = 0; i < 32; i++) {
+ var low = (1 << i) >>> 0;
+ result = jspb.utils.joinUnsignedDecimalString(low, 0);
+ assertEquals('' + Math.pow(2, i), result);
+ }
+
+ // Check the first 20 bits of the high dword.
+ for (var i = 0; i < 20; i++) {
+ var high = (1 << i) >>> 0;
+ result = jspb.utils.joinUnsignedDecimalString(0, high);
+ assertEquals('' + Math.pow(2, 32 + i), result);
+ }
+
+ // V8's internal double-to-string conversion is inaccurate for values above
+ // 2^52, even if they're representable integers - check the rest of the bits
+ // manually against the correct string representations of 2^N.
+
+ result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x00100000);
+ assertEquals('4503599627370496', result);
+
+ result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x00200000);
+ assertEquals('9007199254740992', result);
+
+ result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x00400000);
+ assertEquals('18014398509481984', result);
+
+ result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x00800000);
+ assertEquals('36028797018963968', result);
+
+ result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x01000000);
+ assertEquals('72057594037927936', result);
+
+ result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x02000000);
+ assertEquals('144115188075855872', result);
+
+ result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x04000000);
+ assertEquals('288230376151711744', result);
+
+ result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x08000000);
+ assertEquals('576460752303423488', result);
+
+ result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x10000000);
+ assertEquals('1152921504606846976', result);
+
+ result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x20000000);
+ assertEquals('2305843009213693952', result);
+
+ result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x40000000);
+ assertEquals('4611686018427387904', result);
+
+ result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x80000000);
+ assertEquals('9223372036854775808', result);
+ });
+
+
+ /**
+ * Going from hash strings to decimal strings should also be lossless.
+ */
+ it('testHashToDecimalConversion', function() {
+ var result;
+ var convert = jspb.utils.hash64ToDecimalString;
+
+ result = convert(toHashString(0x00000000, 0x00000000), false);
+ assertEquals('0', result);
+
+ result = convert(toHashString(0x00000000, 0x00000000), true);
+ assertEquals('0', result);
+
+ result = convert(toHashString(0xFFFFFFFF, 0xFFFFFFFF), false);
+ assertEquals('18446744073709551615', result);
+
+ result = convert(toHashString(0xFFFFFFFF, 0xFFFFFFFF), true);
+ assertEquals('-1', result);
+
+ result = convert(toHashString(0x00000000, 0x80000000), false);
+ assertEquals('9223372036854775808', result);
+
+ result = convert(toHashString(0x00000000, 0x80000000), true);
+ assertEquals('-9223372036854775808', result);
+
+ result = convert(toHashString(0xacd05f15, 0x01b69b4b), false);
+ assertEquals('123456789123456789', result);
+
+ result = convert(toHashString(~0xacd05f15 + 1, ~0x01b69b4b), true);
+ assertEquals('-123456789123456789', result);
+
+ // And converting arrays of hashes should work the same way.
+ result = jspb.utils.hash64ArrayToDecimalStrings([
+ toHashString(0xFFFFFFFF, 0xFFFFFFFF),
+ toHashString(0x00000000, 0x80000000),
+ toHashString(0xacd05f15, 0x01b69b4b)], false);
+ assertEquals(3, result.length);
+ assertEquals('18446744073709551615', result[0]);
+ assertEquals('9223372036854775808', result[1]);
+ assertEquals('123456789123456789', result[2]);
+ });
+
+ /*
+ * Going from decimal strings to hash strings should be lossless.
+ */
+ it('testDecimalToHashConversion', function() {
+ var result;
+ var convert = jspb.utils.decimalStringToHash64;
+
+ result = convert('0');
+ assertEquals(String.fromCharCode.apply(null,
+ [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), result);
+
+ result = convert('-1');
+ assertEquals(String.fromCharCode.apply(null,
+ [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]), result);
+
+ result = convert('18446744073709551615');
+ assertEquals(String.fromCharCode.apply(null,
+ [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]), result);
+
+ result = convert('9223372036854775808');
+ assertEquals(String.fromCharCode.apply(null,
+ [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80]), result);
+
+ result = convert('-9223372036854775808');
+ assertEquals(String.fromCharCode.apply(null,
+ [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80]), result);
+
+ result = convert('123456789123456789');
+ assertEquals(String.fromCharCode.apply(null,
+ [0x15, 0x5F, 0xD0, 0xAC, 0x4B, 0x9B, 0xB6, 0x01]), result);
+
+ result = convert('-123456789123456789');
+ assertEquals(String.fromCharCode.apply(null,
+ [0xEB, 0xA0, 0x2F, 0x53, 0xB4, 0x64, 0x49, 0xFE]), result);
+ });
+
+ /**
+ * Going from hash strings to hex strings should be lossless.
+ */
+ it('testHashToHexConversion', function() {
+ var result;
+ var convert = jspb.utils.hash64ToHexString;
+
+ result = convert(toHashString(0x00000000, 0x00000000));
+ assertEquals('0x0000000000000000', result);
+
+ result = convert(toHashString(0xFFFFFFFF, 0xFFFFFFFF));
+ assertEquals('0xffffffffffffffff', result);
+
+ result = convert(toHashString(0x12345678, 0x9ABCDEF0));
+ assertEquals('0x9abcdef012345678', result);
+ });
+
+
+ /**
+ * Going from hex strings to hash strings should be lossless.
+ */
+ it('testHexToHashConversion', function() {
+ var result;
+ var convert = jspb.utils.hexStringToHash64;
+
+ result = convert('0x0000000000000000');
+ assertEquals(String.fromCharCode.apply(null,
+ [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), result);
+
+ result = convert('0xffffffffffffffff');
+ assertEquals(String.fromCharCode.apply(null,
+ [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]), result);
+
+ // Hex string is big-endian, hash string is little-endian.
+ result = convert('0x123456789ABCDEF0');
+ assertEquals(String.fromCharCode.apply(null,
+ [0xF0, 0xDE, 0xBC, 0x9A, 0x78, 0x56, 0x34, 0x12]), result);
+
+ // Capitalization should not matter.
+ result = convert('0x0000abcdefABCDEF');
+ assertEquals(String.fromCharCode.apply(null,
+ [0xEF, 0xCD, 0xAB, 0xEF, 0xCD, 0xAB, 0x00, 0x00]), result);
+ });
+
+
+ /**
+ * Going from numbers to hash strings should be lossless for up to 53 bits of
+ * precision.
+ */
+ it('testNumberToHashConversion', function() {
+ var result;
+ var convert = jspb.utils.numberToHash64;
+
+ result = convert(0x0000000000000);
+ assertEquals('0x0000000000000000', jspb.utils.hash64ToHexString(result));
+
+ result = convert(0xFFFFFFFFFFFFF);
+ assertEquals('0x000fffffffffffff', jspb.utils.hash64ToHexString(result));
+
+ result = convert(0x123456789ABCD);
+ assertEquals('0x000123456789abcd', jspb.utils.hash64ToHexString(result));
+
+ result = convert(0xDCBA987654321);
+ assertEquals('0x000dcba987654321', jspb.utils.hash64ToHexString(result));
+
+ // 53 bits of precision should not be truncated.
+ result = convert(0x10000000000001);
+ assertEquals('0x0010000000000001', jspb.utils.hash64ToHexString(result));
+
+ // 54 bits of precision should be truncated.
+ result = convert(0x20000000000001);
+ assertNotEquals(
+ '0x0020000000000001', jspb.utils.hash64ToHexString(result));
+ });
+
+
+ /**
+ * Sanity check the behavior of Javascript's strings when doing funny things
+ * with unicode characters.
+ */
+ it('sanityCheckUnicodeStrings', function() {
+ var strings = new Array(65536);
+
+ // All possible unsigned 16-bit values should be storable in a string, they
+ // shouldn't do weird things with the length of the string, and they should
+ // come back out of the string unchanged.
+ for (var i = 0; i < 65536; i++) {
+ strings[i] = 'a' + String.fromCharCode(i) + 'a';
+ if (3 != strings[i].length) throw 'fail!';
+ if (i != strings[i].charCodeAt(1)) throw 'fail!';
+ }
+
+ // Each unicode character should compare equal to itself and not equal to a
+ // different unicode character.
+ for (var i = 0; i < 65536; i++) {
+ if (strings[i] != strings[i]) throw 'fail!';
+ if (strings[i] == strings[(i + 1) % 65536]) throw 'fail!';
+ }
+ });
+
+
+ /**
+ * Tests conversion from 32-bit floating point numbers to split64 numbers.
+ */
+ it('testFloat32ToSplit64', function() {
+ var f32_eps = jspb.BinaryConstants.FLOAT32_EPS;
+ var f32_min = jspb.BinaryConstants.FLOAT32_MIN;
+ var f32_max = jspb.BinaryConstants.FLOAT32_MAX;
+
+ // NaN.
+ jspb.utils.splitFloat32(NaN);
+ if (!isNaN(jspb.utils.joinFloat32(jspb.utils.split64Low,
+ jspb.utils.split64High))) {
+ throw 'fail!';
+ }
+
+ /**
+ * @param {number} x
+ * @param {number=} opt_bits
+ */
+ function test(x, opt_bits) {
+ jspb.utils.splitFloat32(x);
+ if (goog.isDef(opt_bits)) {
+ if (opt_bits != jspb.utils.split64Low) throw 'fail!';
+ }
+ if (truncate(x) != jspb.utils.joinFloat32(jspb.utils.split64Low,
+ jspb.utils.split64High)) {
+ throw 'fail!';
+ }
+ }
+
+ // Positive and negative infinity.
+ test(Infinity, 0x7f800000);
+ test(-Infinity, 0xff800000);
+
+ // Positive and negative zero.
+ test(0, 0x00000000);
+ test(-0, 0x80000000);
+
+ // Positive and negative epsilon.
+ test(f32_eps, 0x00000001);
+ test(-f32_eps, 0x80000001);
+
+ // Positive and negative min.
+ test(f32_min, 0x00800000);
+ test(-f32_min, 0x80800000);
+
+ // Positive and negative max.
+ test(f32_max, 0x7F7FFFFF);
+ test(-f32_max, 0xFF7FFFFF);
+
+ // Various positive values.
+ var cursor = f32_eps * 10;
+ while (cursor != Infinity) {
+ test(cursor);
+ cursor *= 1.1;
+ }
+
+ // Various negative values.
+ cursor = -f32_eps * 10;
+ while (cursor != -Infinity) {
+ test(cursor);
+ cursor *= 1.1;
+ }
+ });
+
+
+ /**
+ * Tests conversion from 64-bit floating point numbers to split64 numbers.
+ */
+ it('testFloat64ToSplit64', function() {
+ var f64_eps = jspb.BinaryConstants.FLOAT64_EPS;
+ var f64_min = jspb.BinaryConstants.FLOAT64_MIN;
+ var f64_max = jspb.BinaryConstants.FLOAT64_MAX;
+
+ // NaN.
+ jspb.utils.splitFloat64(NaN);
+ if (!isNaN(jspb.utils.joinFloat64(jspb.utils.split64Low,
+ jspb.utils.split64High))) {
+ throw 'fail!';
+ }
+
+ /**
+ * @param {number} x
+ * @param {number=} opt_highBits
+ * @param {number=} opt_lowBits
+ */
+ function test(x, opt_highBits, opt_lowBits) {
+ jspb.utils.splitFloat64(x);
+ if (goog.isDef(opt_highBits)) {
+ if (opt_highBits != jspb.utils.split64High) throw 'fail!';
+ }
+ if (goog.isDef(opt_lowBits)) {
+ if (opt_lowBits != jspb.utils.split64Low) throw 'fail!';
+ }
+ if (x != jspb.utils.joinFloat64(jspb.utils.split64Low,
+ jspb.utils.split64High)) {
+ throw 'fail!';
+ }
+ }
+
+ // Positive and negative infinity.
+ test(Infinity, 0x7ff00000, 0x00000000);
+ test(-Infinity, 0xfff00000, 0x00000000);
+
+ // Positive and negative zero.
+ test(0, 0x00000000, 0x00000000);
+ test(-0, 0x80000000, 0x00000000);
+
+ // Positive and negative epsilon.
+ test(f64_eps, 0x00000000, 0x00000001);
+ test(-f64_eps, 0x80000000, 0x00000001);
+
+ // Positive and negative min.
+ test(f64_min, 0x00100000, 0x00000000);
+ test(-f64_min, 0x80100000, 0x00000000);
+
+ // Positive and negative max.
+ test(f64_max, 0x7FEFFFFF, 0xFFFFFFFF);
+ test(-f64_max, 0xFFEFFFFF, 0xFFFFFFFF);
+
+ // Various positive values.
+ var cursor = f64_eps * 10;
+ while (cursor != Infinity) {
+ test(cursor);
+ cursor *= 1.1;
+ }
+
+ // Various negative values.
+ cursor = -f64_eps * 10;
+ while (cursor != -Infinity) {
+ test(cursor);
+ cursor *= 1.1;
+ }
+ });
+
+
+ /**
+ * Tests counting packed varints.
+ */
+ it('testCountVarints', function() {
+ var values = [];
+ for (var i = 1; i < 1000000000; i *= 1.1) {
+ values.push(Math.floor(i));
+ }
+
+ var writer = new jspb.BinaryWriter();
+ writer.writePackedUint64(1, values);
+
+ var buffer = new Uint8Array(writer.getResultBuffer());
+
+ // We should have two more varints than we started with - one for the field
+ // tag, one for the packed length.
+ assertEquals(values.length + 2,
+ jspb.utils.countVarints(buffer, 0, buffer.length));
+ });
+
+
+ /**
+ * Tests counting matching varint fields.
+ */
+ it('testCountVarintFields', function() {
+ var writer = new jspb.BinaryWriter();
+
+ var count = 0;
+ for (var i = 1; i < 1000000000; i *= 1.1) {
+ writer.writeUint64(1, Math.floor(i));
+ count++;
+ }
+ writer.writeString(2, 'terminator');
+
+ var buffer = new Uint8Array(writer.getResultBuffer());
+ assertEquals(count,
+ jspb.utils.countVarintFields(buffer, 0, buffer.length, 1));
+
+ writer = new jspb.BinaryWriter();
+
+ count = 0;
+ for (var i = 1; i < 1000000000; i *= 1.1) {
+ writer.writeUint64(123456789, Math.floor(i));
+ count++;
+ }
+ writer.writeString(2, 'terminator');
+
+ buffer = new Uint8Array(writer.getResultBuffer());
+ assertEquals(count,
+ jspb.utils.countVarintFields(buffer, 0, buffer.length, 123456789));
+ });
+
+
+ /**
+ * Tests counting matching fixed32 fields.
+ */
+ it('testCountFixed32Fields', function() {
+ var writer = new jspb.BinaryWriter();
+
+ var count = 0;
+ for (var i = 1; i < 1000000000; i *= 1.1) {
+ writer.writeFixed32(1, Math.floor(i));
+ count++;
+ }
+ writer.writeString(2, 'terminator');
+
+ var buffer = new Uint8Array(writer.getResultBuffer());
+ assertEquals(count,
+ jspb.utils.countFixed32Fields(buffer, 0, buffer.length, 1));
+
+ writer = new jspb.BinaryWriter();
+
+ count = 0;
+ for (var i = 1; i < 1000000000; i *= 1.1) {
+ writer.writeFixed32(123456789, Math.floor(i));
+ count++;
+ }
+ writer.writeString(2, 'terminator');
+
+ buffer = new Uint8Array(writer.getResultBuffer());
+ assertEquals(count,
+ jspb.utils.countFixed32Fields(buffer, 0, buffer.length, 123456789));
+ });
+
+
+ /**
+ * Tests counting matching fixed64 fields.
+ */
+ it('testCountFixed64Fields', function() {
+ var writer = new jspb.BinaryWriter();
+
+ var count = 0;
+ for (var i = 1; i < 1000000000; i *= 1.1) {
+ writer.writeDouble(1, i);
+ count++;
+ }
+ writer.writeString(2, 'terminator');
+
+ var buffer = new Uint8Array(writer.getResultBuffer());
+ assertEquals(count,
+ jspb.utils.countFixed64Fields(buffer, 0, buffer.length, 1));
+
+ writer = new jspb.BinaryWriter();
+
+ count = 0;
+ for (var i = 1; i < 1000000000; i *= 1.1) {
+ writer.writeDouble(123456789, i);
+ count++;
+ }
+ writer.writeString(2, 'terminator');
+
+ buffer = new Uint8Array(writer.getResultBuffer());
+ assertEquals(count,
+ jspb.utils.countFixed64Fields(buffer, 0, buffer.length, 123456789));
+ });
+
+
+ /**
+ * Tests counting matching delimited fields.
+ */
+ it('testCountDelimitedFields', function() {
+ var writer = new jspb.BinaryWriter();
+
+ var count = 0;
+ for (var i = 1; i < 1000; i *= 1.1) {
+ writer.writeBytes(1, [Math.floor(i)]);
+ count++;
+ }
+ writer.writeString(2, 'terminator');
+
+ var buffer = new Uint8Array(writer.getResultBuffer());
+ assertEquals(count,
+ jspb.utils.countDelimitedFields(buffer, 0, buffer.length, 1));
+
+ writer = new jspb.BinaryWriter();
+
+ count = 0;
+ for (var i = 1; i < 1000; i *= 1.1) {
+ writer.writeBytes(123456789, [Math.floor(i)]);
+ count++;
+ }
+ writer.writeString(2, 'terminator');
+
+ buffer = new Uint8Array(writer.getResultBuffer());
+ assertEquals(count,
+ jspb.utils.countDelimitedFields(buffer, 0, buffer.length, 123456789));
+ });
+
+
+ /**
+ * Tests byte format for debug strings.
+ */
+ it('testDebugBytesToTextFormat', function() {
+ assertEquals('""', jspb.utils.debugBytesToTextFormat(null));
+ assertEquals('"\\x00\\x10\\xff"',
+ jspb.utils.debugBytesToTextFormat([0, 16, 255]));
+ });
+
+
+ /**
+ * Tests converting byte blob sources into byte blobs.
+ */
+ it('testByteSourceToUint8Array', function() {
+ var convert = jspb.utils.byteSourceToUint8Array;
+
+ var sourceData = [];
+ for (var i = 0; i < 256; i++) {
+ sourceData.push(i);
+ }
+
+ var sourceBytes = new Uint8Array(sourceData);
+ var sourceBuffer = sourceBytes.buffer;
+ var sourceBase64 = goog.crypt.base64.encodeByteArray(sourceData);
+ var sourceString = String.fromCharCode.apply(null, sourceData);
+
+ function check(result) {
+ assertEquals(Uint8Array, result.constructor);
+ assertEquals(sourceData.length, result.length);
+ for (var i = 0; i < result.length; i++) {
+ assertEquals(sourceData[i], result[i]);
+ }
+ }
+
+ // Converting Uint8Arrays into Uint8Arrays should be a no-op.
+ assertEquals(sourceBytes, convert(sourceBytes));
+
+ // Converting Array.<numbers> into Uint8Arrays should work.
+ check(convert(sourceData));
+
+ // Converting ArrayBuffers into Uint8Arrays should work.
+ check(convert(sourceBuffer));
+
+ // Converting base64-encoded strings into Uint8Arrays should work.
+ check(convert(sourceBase64));
+ });
+});
diff --git a/js/compatibility_tests/v3.1.0/binary/writer_test.js b/js/compatibility_tests/v3.1.0/binary/writer_test.js
new file mode 100644
index 00000000..d5dadb41
--- /dev/null
+++ b/js/compatibility_tests/v3.1.0/binary/writer_test.js
@@ -0,0 +1,122 @@
+// 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.
+
+/**
+ * @fileoverview Test cases for jspb's binary protocol buffer writer. In
+ * practice BinaryWriter is used to drive the Decoder and Reader test cases,
+ * so only writer-specific tests are here.
+ *
+ * Test suite is written using Jasmine -- see http://jasmine.github.io/
+ *
+ * @author aappleby@google.com (Austin Appleby)
+ */
+
+goog.require('goog.crypt');
+goog.require('goog.testing.asserts');
+goog.require('jspb.BinaryWriter');
+
+
+/**
+ * @param {function()} func This function should throw an error when run.
+ */
+function assertFails(func) {
+ var e = assertThrows(func);
+ //assertNotNull(e.toString().match(/Error/));
+}
+
+
+describe('binaryWriterTest', function() {
+ /**
+ * Verifies that misuse of the writer class triggers assertions.
+ */
+ it('testWriteErrors', function() {
+ // Submessages with invalid field indices should assert.
+ var writer = new jspb.BinaryWriter();
+ var dummyMessage = /** @type {!jspb.BinaryMessage} */({});
+
+ assertFails(function() {
+ writer.writeMessage(-1, dummyMessage, goog.nullFunction);
+ });
+
+ // Writing invalid field indices should assert.
+ writer = new jspb.BinaryWriter();
+ assertFails(function() {writer.writeUint64(-1, 1);});
+
+ // Writing out-of-range field values should assert.
+ writer = new jspb.BinaryWriter();
+
+ assertFails(function() {writer.writeInt32(1, -Infinity);});
+ assertFails(function() {writer.writeInt32(1, Infinity);});
+
+ assertFails(function() {writer.writeInt64(1, -Infinity);});
+ assertFails(function() {writer.writeInt64(1, Infinity);});
+
+ assertFails(function() {writer.writeUint32(1, -1);});
+ assertFails(function() {writer.writeUint32(1, Infinity);});
+
+ assertFails(function() {writer.writeUint64(1, -1);});
+ assertFails(function() {writer.writeUint64(1, Infinity);});
+
+ assertFails(function() {writer.writeSint32(1, -Infinity);});
+ assertFails(function() {writer.writeSint32(1, Infinity);});
+
+ assertFails(function() {writer.writeSint64(1, -Infinity);});
+ assertFails(function() {writer.writeSint64(1, Infinity);});
+
+ assertFails(function() {writer.writeFixed32(1, -1);});
+ assertFails(function() {writer.writeFixed32(1, Infinity);});
+
+ assertFails(function() {writer.writeFixed64(1, -1);});
+ assertFails(function() {writer.writeFixed64(1, Infinity);});
+
+ assertFails(function() {writer.writeSfixed32(1, -Infinity);});
+ assertFails(function() {writer.writeSfixed32(1, Infinity);});
+
+ assertFails(function() {writer.writeSfixed64(1, -Infinity);});
+ assertFails(function() {writer.writeSfixed64(1, Infinity);});
+ });
+
+
+ /**
+ * Basic test of retrieving the result as a Uint8Array buffer
+ */
+ it('testGetResultBuffer', function() {
+ var expected = '0864120b48656c6c6f20776f726c641a0301020320c801';
+
+ var writer = new jspb.BinaryWriter();
+ writer.writeUint32(1, 100);
+ writer.writeString(2, 'Hello world');
+ writer.writeBytes(3, new Uint8Array([1, 2, 3]));
+ writer.writeUint32(4, 200);
+
+ var buffer = writer.getResultBuffer();
+ assertEquals(expected, goog.crypt.byteArrayToHex(buffer));
+ });
+});
diff --git a/js/compatibility_tests/v3.1.0/commonjs/test6/test6.proto b/js/compatibility_tests/v3.1.0/commonjs/test6/test6.proto
new file mode 100644
index 00000000..a060925f
--- /dev/null
+++ b/js/compatibility_tests/v3.1.0/commonjs/test6/test6.proto
@@ -0,0 +1,40 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2016 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.
+
+syntax = "proto3";
+
+option java_package = "com.google.apps.jspb.proto";
+option java_multiple_files = true;
+
+package jspb.test.importing;
+
+message ImportedMessage {
+ string string_value = 1;
+}
diff --git a/js/compatibility_tests/v3.1.0/commonjs/test7/test7.proto b/js/compatibility_tests/v3.1.0/commonjs/test7/test7.proto
new file mode 100644
index 00000000..f5574a3d
--- /dev/null
+++ b/js/compatibility_tests/v3.1.0/commonjs/test7/test7.proto
@@ -0,0 +1,42 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2016 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.
+
+syntax = "proto3";
+
+option java_package = "com.google.apps.jspb.proto";
+option java_multiple_files = true;
+
+package jspb.test.framing;
+
+import "test6/test6.proto";
+
+message FramingMessage {
+ jspb.test.importing.ImportedMessage imported_message = 1;
+}
diff --git a/js/compatibility_tests/v3.1.0/data.proto b/js/compatibility_tests/v3.1.0/data.proto
new file mode 100644
index 00000000..74a8a994
--- /dev/null
+++ b/js/compatibility_tests/v3.1.0/data.proto
@@ -0,0 +1,51 @@
+// 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: mwr@google.com (Mark Rawling)
+
+syntax = "proto2";
+
+option java_package = "com.google.apps.jspb.proto";
+option java_multiple_files = true;
+
+package jspb.test;
+
+// legacy data, must be nested
+message data {
+ message NestedData {
+ required string str = 1;
+ }
+}
+
+// new data, does not require nesting
+message UnnestedData {
+ required string str = 1;
+}
+
diff --git a/js/compatibility_tests/v3.1.0/debug_test.js b/js/compatibility_tests/v3.1.0/debug_test.js
new file mode 100644
index 00000000..702cc76e
--- /dev/null
+++ b/js/compatibility_tests/v3.1.0/debug_test.js
@@ -0,0 +1,105 @@
+// 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.
+
+goog.setTestOnly();
+
+goog.require('goog.testing.asserts');
+
+// CommonJS-LoadFromFile: google-protobuf
+goog.require('jspb.debug');
+
+// CommonJS-LoadFromFile: test_pb
+goog.require('proto.jspb.test.HasExtensions');
+goog.require('proto.jspb.test.IsExtension');
+goog.require('proto.jspb.test.Simple1');
+
+
+
+describe('debugTest', function() {
+ it('testSimple1', function() {
+ if (COMPILED) {
+ return;
+ }
+ var message = new proto.jspb.test.Simple1();
+ message.setAString('foo');
+ assertObjectEquals({
+ $name: 'proto.jspb.test.Simple1',
+ 'aString': 'foo',
+ 'aRepeatedStringList': []
+ }, jspb.debug.dump(message));
+
+ message.setABoolean(true);
+ message.setARepeatedStringList(['1', '2']);
+
+ assertObjectEquals({
+ $name: 'proto.jspb.test.Simple1',
+ 'aString': 'foo',
+ 'aRepeatedStringList': ['1', '2'],
+ 'aBoolean': true
+ }, jspb.debug.dump(message));
+
+ message.clearAString();
+
+ assertObjectEquals({
+ $name: 'proto.jspb.test.Simple1',
+ 'aRepeatedStringList': ['1', '2'],
+ 'aBoolean': true
+ }, jspb.debug.dump(message));
+ });
+
+
+ it('testExtensions', function() {
+ if (COMPILED) {
+ return;
+ }
+ var extension = new proto.jspb.test.IsExtension();
+ extension.setExt1('ext1field');
+ var extendable = new proto.jspb.test.HasExtensions();
+ extendable.setStr1('v1');
+ extendable.setStr2('v2');
+ extendable.setStr3('v3');
+ extendable.setExtension(proto.jspb.test.IsExtension.extField, extension);
+
+ assertObjectEquals({
+ '$name': 'proto.jspb.test.HasExtensions',
+ 'str1': 'v1',
+ 'str2': 'v2',
+ 'str3': 'v3',
+ '$extensions': {
+ 'extField': {
+ '$name': 'proto.jspb.test.IsExtension',
+ 'ext1': 'ext1field'
+ },
+ 'repeatedSimpleList': []
+ }
+ }, jspb.debug.dump(extendable));
+ });
+
+});
diff --git a/js/compatibility_tests/v3.1.0/maps_test.js b/js/compatibility_tests/v3.1.0/maps_test.js
new file mode 100644
index 00000000..0d442f4f
--- /dev/null
+++ b/js/compatibility_tests/v3.1.0/maps_test.js
@@ -0,0 +1,301 @@
+// 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.
+
+goog.require('goog.testing.asserts');
+goog.require('goog.userAgent');
+
+// CommonJS-LoadFromFile: testbinary_pb proto.jspb.test
+goog.require('proto.jspb.test.MapValueEnum');
+goog.require('proto.jspb.test.MapValueMessage');
+goog.require('proto.jspb.test.TestMapFields');
+
+// CommonJS-LoadFromFile: test_pb proto.jspb.test
+goog.require('proto.jspb.test.MapValueMessageNoBinary');
+goog.require('proto.jspb.test.TestMapFieldsNoBinary');
+
+/**
+ * Helper: check that the given map has exactly this set of (sorted) entries.
+ * @param {!jspb.Map} map
+ * @param {!Array<!Array<?>>} entries
+ */
+function checkMapEquals(map, entries) {
+ var arr = map.toArray();
+ assertEquals(arr.length, entries.length);
+ for (var i = 0; i < arr.length; i++) {
+ assertElementsEquals(arr[i], entries[i]);
+ }
+}
+
+/**
+ * Converts an ES6 iterator to an array.
+ * @template T
+ * @param {!Iterator<T>} iter an iterator
+ * @return {!Array<T>}
+ */
+function toArray(iter) {
+ var arr = [];
+ while (true) {
+ var val = iter.next();
+ if (val.done) {
+ break;
+ }
+ arr.push(val.value);
+ }
+ return arr;
+}
+
+
+/**
+ * Helper: generate test methods for this TestMapFields class.
+ * @param {?} msgInfo
+ * @param {?} submessageCtor
+ * @param {!string} suffix
+ */
+function makeTests(msgInfo, submessageCtor, suffix) {
+ /**
+ * Helper: fill all maps on a TestMapFields.
+ * @param {?} msg
+ */
+ var fillMapFields = function(msg) {
+ msg.getMapStringStringMap().set('asdf', 'jkl;').set('key 2', 'hello world');
+ msg.getMapStringInt32Map().set('a', 1).set('b', -2);
+ msg.getMapStringInt64Map().set('c', 0x100000000).set('d', 0x200000000);
+ msg.getMapStringBoolMap().set('e', true).set('f', false);
+ msg.getMapStringDoubleMap().set('g', 3.14159).set('h', 2.71828);
+ msg.getMapStringEnumMap()
+ .set('i', proto.jspb.test.MapValueEnum.MAP_VALUE_BAR)
+ .set('j', proto.jspb.test.MapValueEnum.MAP_VALUE_BAZ);
+ msg.getMapStringMsgMap()
+ .set('k', new submessageCtor())
+ .set('l', new submessageCtor());
+ msg.getMapStringMsgMap().get('k').setFoo(42);
+ msg.getMapStringMsgMap().get('l').setFoo(84);
+ msg.getMapInt32StringMap().set(-1, 'a').set(42, 'b');
+ msg.getMapInt64StringMap().set(0x123456789abc, 'c').set(0xcba987654321, 'd');
+ msg.getMapBoolStringMap().set(false, 'e').set(true, 'f');
+ };
+
+ /**
+ * Helper: check all maps on a TestMapFields.
+ * @param {?} msg
+ */
+ var checkMapFields = function(msg) {
+ checkMapEquals(msg.getMapStringStringMap(), [
+ ['asdf', 'jkl;'],
+ ['key 2', 'hello world']
+ ]);
+ checkMapEquals(msg.getMapStringInt32Map(), [
+ ['a', 1],
+ ['b', -2]
+ ]);
+ checkMapEquals(msg.getMapStringInt64Map(), [
+ ['c', 0x100000000],
+ ['d', 0x200000000]
+ ]);
+ checkMapEquals(msg.getMapStringBoolMap(), [
+ ['e', true],
+ ['f', false]
+ ]);
+ checkMapEquals(msg.getMapStringDoubleMap(), [
+ ['g', 3.14159],
+ ['h', 2.71828]
+ ]);
+ checkMapEquals(msg.getMapStringEnumMap(), [
+ ['i', proto.jspb.test.MapValueEnum.MAP_VALUE_BAR],
+ ['j', proto.jspb.test.MapValueEnum.MAP_VALUE_BAZ]
+ ]);
+ checkMapEquals(msg.getMapInt32StringMap(), [
+ [-1, 'a'],
+ [42, 'b']
+ ]);
+ checkMapEquals(msg.getMapInt64StringMap(), [
+ [0x123456789abc, 'c'],
+ [0xcba987654321, 'd']
+ ]);
+ checkMapEquals(msg.getMapBoolStringMap(), [
+ [false, 'e'],
+ [true, 'f']
+ ]);
+
+ assertEquals(msg.getMapStringMsgMap().getLength(), 2);
+ assertEquals(msg.getMapStringMsgMap().get('k').getFoo(), 42);
+ assertEquals(msg.getMapStringMsgMap().get('l').getFoo(), 84);
+
+ var entries = toArray(msg.getMapStringMsgMap().entries());
+ assertEquals(entries.length, 2);
+ entries.forEach(function(entry) {
+ var key = entry[0];
+ var val = entry[1];
+ assert(val === msg.getMapStringMsgMap().get(key));
+ });
+
+ msg.getMapStringMsgMap().forEach(function(val, key) {
+ assert(val === msg.getMapStringMsgMap().get(key));
+ });
+ };
+
+ it('testMapStringStringField' + suffix, function() {
+ var msg = new msgInfo.constructor();
+ assertEquals(msg.getMapStringStringMap().getLength(), 0);
+ assertEquals(msg.getMapStringInt32Map().getLength(), 0);
+ assertEquals(msg.getMapStringInt64Map().getLength(), 0);
+ assertEquals(msg.getMapStringBoolMap().getLength(), 0);
+ assertEquals(msg.getMapStringDoubleMap().getLength(), 0);
+ assertEquals(msg.getMapStringEnumMap().getLength(), 0);
+ assertEquals(msg.getMapStringMsgMap().getLength(), 0);
+
+ // Re-create to clear out any internally-cached wrappers, etc.
+ msg = new msgInfo.constructor();
+ var m = msg.getMapStringStringMap();
+ assertEquals(m.has('asdf'), false);
+ assertEquals(m.get('asdf'), undefined);
+ m.set('asdf', 'hello world');
+ assertEquals(m.has('asdf'), true);
+ assertEquals(m.get('asdf'), 'hello world');
+ m.set('jkl;', 'key 2');
+ assertEquals(m.has('jkl;'), true);
+ assertEquals(m.get('jkl;'), 'key 2');
+ assertEquals(m.getLength(), 2);
+ var it = m.entries();
+ assertElementsEquals(it.next().value, ['asdf', 'hello world']);
+ assertElementsEquals(it.next().value, ['jkl;', 'key 2']);
+ assertEquals(it.next().done, true);
+ checkMapEquals(m, [
+ ['asdf', 'hello world'],
+ ['jkl;', 'key 2']
+ ]);
+ m.del('jkl;');
+ assertEquals(m.has('jkl;'), false);
+ assertEquals(m.get('jkl;'), undefined);
+ assertEquals(m.getLength(), 1);
+ it = m.keys();
+ assertEquals(it.next().value, 'asdf');
+ assertEquals(it.next().done, true);
+ it = m.values();
+ assertEquals(it.next().value, 'hello world');
+ assertEquals(it.next().done, true);
+
+ var count = 0;
+ m.forEach(function(value, key, map) {
+ assertEquals(map, m);
+ assertEquals(key, 'asdf');
+ assertEquals(value, 'hello world');
+ count++;
+ });
+ assertEquals(count, 1);
+
+ m.clear();
+ assertEquals(m.getLength(), 0);
+ });
+
+
+ /**
+ * Tests operations on maps with all key and value types.
+ */
+ it('testAllMapTypes' + suffix, function() {
+ var msg = new msgInfo.constructor();
+ fillMapFields(msg);
+ checkMapFields(msg);
+ });
+
+
+ if (msgInfo.deserializeBinary) {
+ /**
+ * Tests serialization and deserialization in binary format.
+ */
+ it('testBinaryFormat' + suffix, function() {
+ if (goog.userAgent.IE && !goog.userAgent.isDocumentModeOrHigher(10)) {
+ // IE8/9 currently doesn't support binary format because they lack
+ // TypedArray.
+ return;
+ }
+
+ // Check that the format is correct.
+ var msg = new msgInfo.constructor();
+ msg.getMapStringStringMap().set('A', 'a');
+ var serialized = msg.serializeBinary();
+ var expectedSerialized = [
+ 0x0a, 0x6, // field 1 (map_string_string), delimited, length 6
+ 0x0a, 0x1, // field 1 in submessage (key), delimited, length 1
+ 0x41, // ASCII 'A'
+ 0x12, 0x1, // field 2 in submessage (value), delimited, length 1
+ 0x61 // ASCII 'a'
+ ];
+ assertEquals(serialized.length, expectedSerialized.length);
+ for (var i = 0; i < serialized.length; i++) {
+ assertEquals(serialized[i], expectedSerialized[i]);
+ }
+
+ // Check that all map fields successfully round-trip.
+ msg = new msgInfo.constructor();
+ fillMapFields(msg);
+ serialized = msg.serializeBinary();
+ var decoded = msgInfo.deserializeBinary(serialized);
+ checkMapFields(decoded);
+ });
+ }
+
+ /**
+ * Exercises the lazy map<->underlying array sync.
+ */
+ it('testLazyMapSync' + suffix, function() {
+ // Start with a JSPB array containing a few map entries.
+ var entries = [
+ ['a', 'entry 1'],
+ ['c', 'entry 2'],
+ ['b', 'entry 3']
+ ];
+ var msg = new msgInfo.constructor([entries]);
+ assertEquals(entries.length, 3);
+ assertEquals(entries[0][0], 'a');
+ assertEquals(entries[1][0], 'c');
+ assertEquals(entries[2][0], 'b');
+ msg.getMapStringStringMap().del('a');
+ assertEquals(entries.length, 3); // not yet sync'd
+ msg.toArray(); // force a sync
+ assertEquals(entries.length, 2);
+ assertEquals(entries[0][0], 'b'); // now in sorted order
+ assertEquals(entries[1][0], 'c');
+
+ var a = msg.toArray();
+ assertEquals(a[0], entries); // retains original reference
+ });
+}
+
+describe('mapsTest', function() {
+ makeTests({
+ constructor: proto.jspb.test.TestMapFields,
+ deserializeBinary: proto.jspb.test.TestMapFields.deserializeBinary
+ }, proto.jspb.test.MapValueMessage, "_Binary");
+ makeTests({
+ constructor: proto.jspb.test.TestMapFieldsNoBinary,
+ deserializeBinary: null
+ }, proto.jspb.test.MapValueMessageNoBinary, "_NoBinary");
+});
diff --git a/js/compatibility_tests/v3.1.0/message_test.js b/js/compatibility_tests/v3.1.0/message_test.js
new file mode 100644
index 00000000..c1023784
--- /dev/null
+++ b/js/compatibility_tests/v3.1.0/message_test.js
@@ -0,0 +1,1032 @@
+// 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.
+
+// Test suite is written using Jasmine -- see http://jasmine.github.io/
+
+goog.setTestOnly();
+
+goog.require('goog.json');
+goog.require('goog.testing.asserts');
+goog.require('goog.userAgent');
+
+// CommonJS-LoadFromFile: google-protobuf jspb
+goog.require('jspb.Message');
+
+// CommonJS-LoadFromFile: test5_pb proto.jspb.exttest.beta
+goog.require('proto.jspb.exttest.beta.floatingStrField');
+
+// CommonJS-LoadFromFile: test3_pb proto.jspb.exttest
+goog.require('proto.jspb.exttest.floatingMsgField');
+
+// CommonJS-LoadFromFile: test4_pb proto.jspb.exttest
+goog.require('proto.jspb.exttest.floatingMsgFieldTwo');
+
+// CommonJS-LoadFromFile: test_pb proto.jspb.test
+goog.require('proto.jspb.test.CloneExtension');
+goog.require('proto.jspb.test.Complex');
+goog.require('proto.jspb.test.DefaultValues');
+goog.require('proto.jspb.test.Empty');
+goog.require('proto.jspb.test.EnumContainer');
+goog.require('proto.jspb.test.floatingMsgField');
+goog.require('proto.jspb.test.FloatingPointFields');
+goog.require('proto.jspb.test.floatingStrField');
+goog.require('proto.jspb.test.HasExtensions');
+goog.require('proto.jspb.test.IndirectExtension');
+goog.require('proto.jspb.test.IsExtension');
+goog.require('proto.jspb.test.OptionalFields');
+goog.require('proto.jspb.test.OuterEnum');
+goog.require('proto.jspb.test.OuterMessage.Complex');
+goog.require('proto.jspb.test.Simple1');
+goog.require('proto.jspb.test.Simple2');
+goog.require('proto.jspb.test.SpecialCases');
+goog.require('proto.jspb.test.TestClone');
+goog.require('proto.jspb.test.TestEndsWithBytes');
+goog.require('proto.jspb.test.TestGroup');
+goog.require('proto.jspb.test.TestGroup1');
+goog.require('proto.jspb.test.TestMessageWithOneof');
+goog.require('proto.jspb.test.TestReservedNames');
+goog.require('proto.jspb.test.TestReservedNamesExtension');
+
+// CommonJS-LoadFromFile: test2_pb proto.jspb.test
+goog.require('proto.jspb.test.ExtensionMessage');
+goog.require('proto.jspb.test.TestExtensionsMessage');
+
+
+
+
+describe('Message test suite', function() {
+ it('testEmptyProto', function() {
+ var empty1 = new proto.jspb.test.Empty([]);
+ var empty2 = new proto.jspb.test.Empty([]);
+ assertObjectEquals({}, empty1.toObject());
+ assertObjectEquals('Message should not be corrupted:', empty2, empty1);
+ });
+
+ it('testTopLevelEnum', function() {
+ var response = new proto.jspb.test.EnumContainer([]);
+ response.setOuterEnum(proto.jspb.test.OuterEnum.FOO);
+ assertEquals(proto.jspb.test.OuterEnum.FOO, response.getOuterEnum());
+ });
+
+ it('testByteStrings', function() {
+ var data = new proto.jspb.test.DefaultValues([]);
+ data.setBytesField('some_bytes');
+ assertEquals('some_bytes', data.getBytesField());
+ });
+
+ it('testComplexConversion', function() {
+ var data1 = ['a',,, [, 11], [[, 22], [, 33]],, ['s1', 's2'],, 1];
+ var data2 = ['a',,, [, 11], [[, 22], [, 33]],, ['s1', 's2'],, 1];
+ var foo = new proto.jspb.test.Complex(data1);
+ var bar = new proto.jspb.test.Complex(data2);
+ var result = foo.toObject();
+ assertObjectEquals({
+ aString: 'a',
+ anOutOfOrderBool: 1,
+ aNestedMessage: {
+ anInt: 11
+ },
+ aRepeatedMessageList: [{anInt: 22}, {anInt: 33}],
+ aRepeatedStringList: ['s1', 's2']
+ }, result);
+
+ // Now test with the jspb instances included.
+ result = foo.toObject(true /* opt_includeInstance */);
+ assertObjectEquals({
+ aString: 'a',
+ anOutOfOrderBool: 1,
+ aNestedMessage: {
+ anInt: 11,
+ $jspbMessageInstance: foo.getANestedMessage()
+ },
+ aRepeatedMessageList: [
+ {anInt: 22, $jspbMessageInstance: foo.getARepeatedMessageList()[0]},
+ {anInt: 33, $jspbMessageInstance: foo.getARepeatedMessageList()[1]}
+ ],
+ aRepeatedStringList: ['s1', 's2'],
+ $jspbMessageInstance: foo
+ }, result);
+
+ });
+
+ it('testMissingFields', function() {
+ var foo = new proto.jspb.test.Complex([
+ undefined, undefined, undefined, [],
+ undefined, undefined, undefined, undefined]);
+ var bar = new proto.jspb.test.Complex([
+ undefined, undefined, undefined, [],
+ undefined, undefined, undefined, undefined]);
+ var result = foo.toObject();
+ assertObjectEquals({
+ aString: undefined,
+ anOutOfOrderBool: undefined,
+ aNestedMessage: {
+ anInt: undefined
+ },
+ // Note: JsPb converts undefined repeated fields to empty arrays.
+ aRepeatedMessageList: [],
+ aRepeatedStringList: []
+ }, result);
+
+ });
+
+ it('testNestedComplexMessage', function() {
+ // Instantiate the message and set a unique field, just to ensure that we
+ // are not getting jspb.test.Complex instead.
+ var msg = new proto.jspb.test.OuterMessage.Complex();
+ msg.setInnerComplexField(5);
+ });
+
+ it('testSpecialCases', function() {
+ // Note: Some property names are reserved in JavaScript.
+ // These names are converted to the Js property named pb_<reserved_name>.
+ var special =
+ new proto.jspb.test.SpecialCases(['normal', 'default', 'function',
+ 'var']);
+ var result = special.toObject();
+ assertObjectEquals({
+ normal: 'normal',
+ pb_default: 'default',
+ pb_function: 'function',
+ pb_var: 'var'
+ }, result);
+ });
+
+ it('testDefaultValues', function() {
+ var defaultString = "default<>\'\"abc";
+ var response = new proto.jspb.test.DefaultValues();
+
+ // Test toObject
+ var expectedObject = {
+ stringField: defaultString,
+ boolField: true,
+ intField: 11,
+ enumField: 13,
+ emptyField: '',
+ bytesField: 'bW9v'
+ };
+ assertObjectEquals(expectedObject, response.toObject());
+
+
+ // Test getters
+ response = new proto.jspb.test.DefaultValues();
+ assertEquals(defaultString, response.getStringField());
+ assertEquals(true, response.getBoolField());
+ assertEquals(11, response.getIntField());
+ assertEquals(13, response.getEnumField());
+ assertEquals('', response.getEmptyField());
+ assertEquals('bW9v', response.getBytesField());
+
+ function makeDefault(values) {
+ return new proto.jspb.test.DefaultValues(values);
+ }
+
+ // Test with undefined values,
+ // Use push to workaround IE treating undefined array elements as holes.
+ response = makeDefault([undefined, undefined, undefined, undefined]);
+ assertEquals(defaultString, response.getStringField());
+ assertEquals(true, response.getBoolField());
+ assertEquals(11, response.getIntField());
+ assertEquals(13, response.getEnumField());
+ assertFalse(response.hasStringField());
+ assertFalse(response.hasBoolField());
+ assertFalse(response.hasIntField());
+ assertFalse(response.hasEnumField());
+
+ // Test with null values, as would be returned by a JSON serializer.
+ response = makeDefault([null, null, null, null]);
+ assertEquals(defaultString, response.getStringField());
+ assertEquals(true, response.getBoolField());
+ assertEquals(11, response.getIntField());
+ assertEquals(13, response.getEnumField());
+ assertFalse(response.hasStringField());
+ assertFalse(response.hasBoolField());
+ assertFalse(response.hasIntField());
+ assertFalse(response.hasEnumField());
+
+ // Test with false-like values.
+ response = makeDefault(['', false, 0, 0]);
+ assertEquals('', response.getStringField());
+ assertEquals(false, response.getBoolField());
+ assertEquals(true, response.getIntField() == 0);
+ assertEquals(true, response.getEnumField() == 0);
+ assertTrue(response.hasStringField());
+ assertTrue(response.hasBoolField());
+ assertTrue(response.hasIntField());
+ assertTrue(response.hasEnumField());
+
+ // Test that clearing the values reverts them to the default state.
+ response = makeDefault(['blah', false, 111, 77]);
+ response.clearStringField(); response.clearBoolField();
+ response.clearIntField(); response.clearEnumField();
+ assertEquals(defaultString, response.getStringField());
+ assertEquals(true, response.getBoolField());
+ assertEquals(11, response.getIntField());
+ assertEquals(13, response.getEnumField());
+ assertFalse(response.hasStringField());
+ assertFalse(response.hasBoolField());
+ assertFalse(response.hasIntField());
+ assertFalse(response.hasEnumField());
+
+ // Test that setFoo(null) clears the values.
+ response = makeDefault(['blah', false, 111, 77]);
+ response.setStringField(null); response.setBoolField(null);
+ response.setIntField(undefined); response.setEnumField(undefined);
+ assertEquals(defaultString, response.getStringField());
+ assertEquals(true, response.getBoolField());
+ assertEquals(11, response.getIntField());
+ assertEquals(13, response.getEnumField());
+ assertFalse(response.hasStringField());
+ assertFalse(response.hasBoolField());
+ assertFalse(response.hasIntField());
+ assertFalse(response.hasEnumField());
+ });
+
+ it('testClearFields', function() {
+ var data = ['str', true, [11], [[22], [33]], ['s1', 's2']];
+ var foo = new proto.jspb.test.OptionalFields(data);
+ foo.clearAString();
+ foo.clearABool();
+ foo.clearANestedMessage();
+ foo.clearARepeatedMessageList();
+ foo.clearARepeatedStringList();
+ assertEquals('', foo.getAString());
+ assertEquals(false, foo.getABool());
+ assertUndefined(foo.getANestedMessage());
+ assertFalse(foo.hasAString());
+ assertFalse(foo.hasABool());
+ assertObjectEquals([], foo.getARepeatedMessageList());
+ assertObjectEquals([], foo.getARepeatedStringList());
+ // NOTE: We want the missing fields in 'expected' to be undefined,
+ // but we actually get a sparse array instead. We could use something
+ // like [1,undefined,2] to avoid this, except that this is still
+ // sparse on IE. No comment...
+ var expected = [,,, [], []];
+ expected[0] = expected[1] = expected[2] = undefined;
+ assertObjectEquals(expected, foo.toArray());
+ });
+
+ it('testDifferenceRawObject', /** @suppress {visibility} */ function() {
+ var p1 = new proto.jspb.test.HasExtensions(['hi', 'diff', {}]);
+ var p2 = new proto.jspb.test.HasExtensions(['hi', 'what',
+ {1000: 'unique'}]);
+ var diff = /** @type {proto.jspb.test.HasExtensions} */
+ (jspb.Message.difference(p1, p2));
+ assertEquals('', diff.getStr1());
+ assertEquals('what', diff.getStr2());
+ assertEquals('', diff.getStr3());
+ assertEquals('unique', diff.extensionObject_[1000]);
+ });
+
+ it('testEqualsSimple', function() {
+ var s1 = new proto.jspb.test.Simple1(['hi']);
+ assertTrue(jspb.Message.equals(s1, new proto.jspb.test.Simple1(['hi'])));
+ assertFalse(jspb.Message.equals(s1, new proto.jspb.test.Simple1(['bye'])));
+ var s1b = new proto.jspb.test.Simple1(['hi', ['hello']]);
+ assertTrue(jspb.Message.equals(s1b,
+ new proto.jspb.test.Simple1(['hi', ['hello']])));
+ assertTrue(jspb.Message.equals(s1b,
+ new proto.jspb.test.Simple1(['hi', ['hello', undefined,
+ undefined, undefined]])));
+ assertFalse(jspb.Message.equals(s1b,
+ new proto.jspb.test.Simple1(['no', ['hello']])));
+ // Test with messages of different types
+ var s2 = new proto.jspb.test.Simple2(['hi']);
+ assertFalse(jspb.Message.equals(s1, s2));
+ });
+
+ it('testEquals_softComparison', function() {
+ var s1 = new proto.jspb.test.Simple1(['hi', [], null]);
+ assertTrue(jspb.Message.equals(s1,
+ new proto.jspb.test.Simple1(['hi', []])));
+
+ var s1b = new proto.jspb.test.Simple1(['hi', [], true]);
+ assertTrue(jspb.Message.equals(s1b,
+ new proto.jspb.test.Simple1(['hi', [], 1])));
+ });
+
+ it('testEqualsComplex', function() {
+ var data1 = ['a',,, [, 11], [[, 22], [, 33]],, ['s1', 's2'],, 1];
+ var data2 = ['a',,, [, 11], [[, 22], [, 34]],, ['s1', 's2'],, 1];
+ var data3 = ['a',,, [, 11], [[, 22]],, ['s1', 's2'],, 1];
+ var data4 = ['hi'];
+ var c1a = new proto.jspb.test.Complex(data1);
+ var c1b = new proto.jspb.test.Complex(data1);
+ var c2 = new proto.jspb.test.Complex(data2);
+ var c3 = new proto.jspb.test.Complex(data3);
+ var s1 = new proto.jspb.test.Simple1(data4);
+
+ assertTrue(jspb.Message.equals(c1a, c1b));
+ assertFalse(jspb.Message.equals(c1a, c2));
+ assertFalse(jspb.Message.equals(c2, c3));
+ assertFalse(jspb.Message.equals(c1a, s1));
+ });
+
+ it('testEqualsExtensionsConstructed', function() {
+ assertTrue(jspb.Message.equals(
+ new proto.jspb.test.HasExtensions([]),
+ new proto.jspb.test.HasExtensions([{}])
+ ));
+ assertTrue(jspb.Message.equals(
+ new proto.jspb.test.HasExtensions(['hi', {100: [{200: 'a'}]}]),
+ new proto.jspb.test.HasExtensions(['hi', {100: [{200: 'a'}]}])
+ ));
+ assertFalse(jspb.Message.equals(
+ new proto.jspb.test.HasExtensions(['hi', {100: [{200: 'a'}]}]),
+ new proto.jspb.test.HasExtensions(['hi', {100: [{200: 'b'}]}])
+ ));
+ assertTrue(jspb.Message.equals(
+ new proto.jspb.test.HasExtensions([{100: [{200: 'a'}]}]),
+ new proto.jspb.test.HasExtensions([{100: [{200: 'a'}]}])
+ ));
+ assertTrue(jspb.Message.equals(
+ new proto.jspb.test.HasExtensions([{100: [{200: 'a'}]}]),
+ new proto.jspb.test.HasExtensions([,,, {100: [{200: 'a'}]}])
+ ));
+ assertTrue(jspb.Message.equals(
+ new proto.jspb.test.HasExtensions([,,, {100: [{200: 'a'}]}]),
+ new proto.jspb.test.HasExtensions([{100: [{200: 'a'}]}])
+ ));
+ assertTrue(jspb.Message.equals(
+ new proto.jspb.test.HasExtensions(['hi', {100: [{200: 'a'}]}]),
+ new proto.jspb.test.HasExtensions(['hi',,, {100: [{200: 'a'}]}])
+ ));
+ assertTrue(jspb.Message.equals(
+ new proto.jspb.test.HasExtensions(['hi',,, {100: [{200: 'a'}]}]),
+ new proto.jspb.test.HasExtensions(['hi', {100: [{200: 'a'}]}])
+ ));
+ });
+
+ it('testEqualsExtensionsUnconstructed', function() {
+ assertTrue(jspb.Message.compareFields([], [{}]));
+ assertTrue(jspb.Message.compareFields([,,, {}], []));
+ assertTrue(jspb.Message.compareFields([,,, {}], [,, {}]));
+ assertTrue(jspb.Message.compareFields(
+ ['hi', {100: [{200: 'a'}]}], ['hi', {100: [{200: 'a'}]}]));
+ assertFalse(jspb.Message.compareFields(
+ ['hi', {100: [{200: 'a'}]}], ['hi', {100: [{200: 'b'}]}]));
+ assertTrue(jspb.Message.compareFields(
+ [{100: [{200: 'a'}]}], [{100: [{200: 'a'}]}]));
+ assertTrue(jspb.Message.compareFields(
+ [{100: [{200: 'a'}]}], [,,, {100: [{200: 'a'}]}]));
+ assertTrue(jspb.Message.compareFields(
+ [,,, {100: [{200: 'a'}]}], [{100: [{200: 'a'}]}]));
+ assertTrue(jspb.Message.compareFields(
+ ['hi', {100: [{200: 'a'}]}], ['hi',,, {100: [{200: 'a'}]}]));
+ assertTrue(jspb.Message.compareFields(
+ ['hi',,, {100: [{200: 'a'}]}], ['hi', {100: [{200: 'a'}]}]));
+ });
+
+ it('testToMap', function() {
+ var p1 = new proto.jspb.test.Simple1(['k', ['v']]);
+ var p2 = new proto.jspb.test.Simple1(['k1', ['v1', 'v2']]);
+ var soymap = jspb.Message.toMap([p1, p2],
+ proto.jspb.test.Simple1.prototype.getAString,
+ proto.jspb.test.Simple1.prototype.toObject);
+ assertEquals('k', soymap['k'].aString);
+ assertArrayEquals(['v'], soymap['k'].aRepeatedStringList);
+ var protomap = jspb.Message.toMap([p1, p2],
+ proto.jspb.test.Simple1.prototype.getAString);
+ assertEquals('k', protomap['k'].getAString());
+ assertArrayEquals(['v'], protomap['k'].getARepeatedStringList());
+ });
+
+ it('testClone', function() {
+ var supportsUint8Array =
+ !goog.userAgent.IE || goog.userAgent.isVersionOrHigher('10');
+ var original = new proto.jspb.test.TestClone();
+ original.setStr('v1');
+ var simple1 = new proto.jspb.test.Simple1(['x1', ['y1', 'z1']]);
+ var simple2 = new proto.jspb.test.Simple1(['x2', ['y2', 'z2']]);
+ var simple3 = new proto.jspb.test.Simple1(['x3', ['y3', 'z3']]);
+ original.setSimple1(simple1);
+ original.setSimple2List([simple2, simple3]);
+ var bytes1 = supportsUint8Array ? new Uint8Array([1, 2, 3]) : '123';
+ original.setBytesField(bytes1);
+ var extension = new proto.jspb.test.CloneExtension();
+ extension.setExt('e1');
+ original.setExtension(proto.jspb.test.IsExtension.extField, extension);
+ var clone = original.clone();
+ assertArrayEquals(['v1',, ['x1', ['y1', 'z1']],,
+ [['x2', ['y2', 'z2']], ['x3', ['y3', 'z3']]], bytes1,, { 100: [, 'e1'] }],
+ clone.toArray());
+ clone.setStr('v2');
+ var simple4 = new proto.jspb.test.Simple1(['a1', ['b1', 'c1']]);
+ var simple5 = new proto.jspb.test.Simple1(['a2', ['b2', 'c2']]);
+ var simple6 = new proto.jspb.test.Simple1(['a3', ['b3', 'c3']]);
+ clone.setSimple1(simple4);
+ clone.setSimple2List([simple5, simple6]);
+ if (supportsUint8Array) {
+ clone.getBytesField()[0] = 4;
+ assertObjectEquals(bytes1, original.getBytesField());
+ }
+ var bytes2 = supportsUint8Array ? new Uint8Array([4, 5, 6]) : '456';
+ clone.setBytesField(bytes2);
+ var newExtension = new proto.jspb.test.CloneExtension();
+ newExtension.setExt('e2');
+ clone.setExtension(proto.jspb.test.CloneExtension.extField, newExtension);
+ assertArrayEquals(['v2',, ['a1', ['b1', 'c1']],,
+ [['a2', ['b2', 'c2']], ['a3', ['b3', 'c3']]], bytes2,, { 100: [, 'e2'] }],
+ clone.toArray());
+ assertArrayEquals(['v1',, ['x1', ['y1', 'z1']],,
+ [['x2', ['y2', 'z2']], ['x3', ['y3', 'z3']]], bytes1,, { 100: [, 'e1'] }],
+ original.toArray());
+ });
+
+ it('testCopyInto', function() {
+ var supportsUint8Array =
+ !goog.userAgent.IE || goog.userAgent.isVersionOrHigher('10');
+ var original = new proto.jspb.test.TestClone();
+ original.setStr('v1');
+ var dest = new proto.jspb.test.TestClone();
+ dest.setStr('override');
+ var simple1 = new proto.jspb.test.Simple1(['x1', ['y1', 'z1']]);
+ var simple2 = new proto.jspb.test.Simple1(['x2', ['y2', 'z2']]);
+ var simple3 = new proto.jspb.test.Simple1(['x3', ['y3', 'z3']]);
+ var destSimple1 = new proto.jspb.test.Simple1(['ox1', ['oy1', 'oz1']]);
+ var destSimple2 = new proto.jspb.test.Simple1(['ox2', ['oy2', 'oz2']]);
+ var destSimple3 = new proto.jspb.test.Simple1(['ox3', ['oy3', 'oz3']]);
+ original.setSimple1(simple1);
+ original.setSimple2List([simple2, simple3]);
+ dest.setSimple1(destSimple1);
+ dest.setSimple2List([destSimple2, destSimple3]);
+ var bytes1 = supportsUint8Array ? new Uint8Array([1, 2, 3]) : '123';
+ var bytes2 = supportsUint8Array ? new Uint8Array([4, 5, 6]) : '456';
+ original.setBytesField(bytes1);
+ dest.setBytesField(bytes2);
+ var extension = new proto.jspb.test.CloneExtension();
+ extension.setExt('e1');
+ original.setExtension(proto.jspb.test.CloneExtension.extField, extension);
+
+ jspb.Message.copyInto(original, dest);
+ assertArrayEquals(original.toArray(), dest.toArray());
+ assertEquals('x1', dest.getSimple1().getAString());
+ assertEquals('e1',
+ dest.getExtension(proto.jspb.test.CloneExtension.extField).getExt());
+ dest.getSimple1().setAString('new value');
+ assertNotEquals(dest.getSimple1().getAString(),
+ original.getSimple1().getAString());
+ if (supportsUint8Array) {
+ dest.getBytesField()[0] = 7;
+ assertObjectEquals(bytes1, original.getBytesField());
+ assertObjectEquals(new Uint8Array([7, 2, 3]), dest.getBytesField());
+ } else {
+ dest.setBytesField('789');
+ assertObjectEquals(bytes1, original.getBytesField());
+ assertObjectEquals('789', dest.getBytesField());
+ }
+ dest.getExtension(proto.jspb.test.CloneExtension.extField).
+ setExt('new value');
+ assertNotEquals(
+ dest.getExtension(proto.jspb.test.CloneExtension.extField).getExt(),
+ original.getExtension(
+ proto.jspb.test.CloneExtension.extField).getExt());
+ });
+
+ it('testCopyInto_notSameType', function() {
+ var a = new proto.jspb.test.TestClone();
+ var b = new proto.jspb.test.Simple1(['str', ['s1', 's2']]);
+
+ var e = assertThrows(function() {
+ jspb.Message.copyInto(a, b);
+ });
+ assertContains('should have the same type', e.message);
+ });
+
+ it('testExtensions', function() {
+ var extension1 = new proto.jspb.test.IsExtension(['ext1field']);
+ var extension2 = new proto.jspb.test.Simple1(['str', ['s1', 's2']]);
+ var extendable = new proto.jspb.test.HasExtensions(['v1', 'v2', 'v3']);
+ extendable.setExtension(proto.jspb.test.IsExtension.extField, extension1);
+ extendable.setExtension(proto.jspb.test.IndirectExtension.simple,
+ extension2);
+ extendable.setExtension(proto.jspb.test.IndirectExtension.str, 'xyzzy');
+ extendable.setExtension(proto.jspb.test.IndirectExtension.repeatedStrList,
+ ['a', 'b']);
+ var s1 = new proto.jspb.test.Simple1(['foo', ['s1', 's2']]);
+ var s2 = new proto.jspb.test.Simple1(['bar', ['t1', 't2']]);
+ extendable.setExtension(
+ proto.jspb.test.IndirectExtension.repeatedSimpleList,
+ [s1, s2]);
+ assertObjectEquals(extension1,
+ extendable.getExtension(proto.jspb.test.IsExtension.extField));
+ assertObjectEquals(extension2,
+ extendable.getExtension(proto.jspb.test.IndirectExtension.simple));
+ assertObjectEquals('xyzzy',
+ extendable.getExtension(proto.jspb.test.IndirectExtension.str));
+ assertObjectEquals(['a', 'b'], extendable.getExtension(
+ proto.jspb.test.IndirectExtension.repeatedStrList));
+ assertObjectEquals([s1, s2], extendable.getExtension(
+ proto.jspb.test.IndirectExtension.repeatedSimpleList));
+ // Not supported yet, but it should work...
+ extendable.setExtension(proto.jspb.test.IndirectExtension.simple, null);
+ assertNull(
+ extendable.getExtension(proto.jspb.test.IndirectExtension.simple));
+ extendable.setExtension(proto.jspb.test.IndirectExtension.str, null);
+ assertNull(extendable.getExtension(proto.jspb.test.IndirectExtension.str));
+
+
+ // Extension fields with jspb.ignore = true are ignored.
+ assertUndefined(proto.jspb.test.IndirectExtension['ignored']);
+ assertUndefined(proto.jspb.test.HasExtensions['ignoredFloating']);
+ });
+
+ it('testFloatingExtensions', function() {
+ // From an autogenerated container.
+ var extendable = new proto.jspb.test.HasExtensions(['v1', 'v2', 'v3']);
+ var extension = new proto.jspb.test.Simple1(['foo', ['s1', 's2']]);
+ extendable.setExtension(proto.jspb.test.simple1, extension);
+ assertObjectEquals(extension,
+ extendable.getExtension(proto.jspb.test.simple1));
+
+ // From _lib mode.
+ extension = new proto.jspb.test.ExtensionMessage(['s1']);
+ extendable = new proto.jspb.test.TestExtensionsMessage([16]);
+ extendable.setExtension(proto.jspb.test.floatingMsgField, extension);
+ extendable.setExtension(proto.jspb.test.floatingStrField, 's2');
+ assertObjectEquals(extension,
+ extendable.getExtension(proto.jspb.test.floatingMsgField));
+ assertObjectEquals('s2',
+ extendable.getExtension(proto.jspb.test.floatingStrField));
+ assertNotUndefined(proto.jspb.exttest.floatingMsgField);
+ assertNotUndefined(proto.jspb.exttest.floatingMsgFieldTwo);
+ assertNotUndefined(proto.jspb.exttest.beta.floatingStrField);
+ });
+
+ it('testToObject_extendedObject', function() {
+ var extension1 = new proto.jspb.test.IsExtension(['ext1field']);
+ var extension2 = new proto.jspb.test.Simple1(['str', ['s1', 's2'], true]);
+ var extendable = new proto.jspb.test.HasExtensions(['v1', 'v2', 'v3']);
+ extendable.setExtension(proto.jspb.test.IsExtension.extField, extension1);
+ extendable.setExtension(proto.jspb.test.IndirectExtension.simple,
+ extension2);
+ extendable.setExtension(proto.jspb.test.IndirectExtension.str, 'xyzzy');
+ extendable.setExtension(proto.jspb.test.IndirectExtension.repeatedStrList,
+ ['a', 'b']);
+ var s1 = new proto.jspb.test.Simple1(['foo', ['s1', 's2'], true]);
+ var s2 = new proto.jspb.test.Simple1(['bar', ['t1', 't2'], false]);
+ extendable.setExtension(
+ proto.jspb.test.IndirectExtension.repeatedSimpleList,
+ [s1, s2]);
+ assertObjectEquals({
+ str1: 'v1', str2: 'v2', str3: 'v3',
+ extField: { ext1: 'ext1field' },
+ simple: {
+ aString: 'str', aRepeatedStringList: ['s1', 's2'], aBoolean: true
+ },
+ str: 'xyzzy',
+ repeatedStrList: ['a', 'b'],
+ repeatedSimpleList: [
+ { aString: 'foo', aRepeatedStringList: ['s1', 's2'], aBoolean: true},
+ { aString: 'bar', aRepeatedStringList: ['t1', 't2'], aBoolean: false}
+ ]
+ }, extendable.toObject());
+
+ // Now, with instances included.
+ assertObjectEquals({
+ str1: 'v1', str2: 'v2', str3: 'v3',
+ extField: {
+ ext1: 'ext1field',
+ $jspbMessageInstance:
+ extendable.getExtension(proto.jspb.test.IsExtension.extField)
+ },
+ simple: {
+ aString: 'str',
+ aRepeatedStringList: ['s1', 's2'],
+ aBoolean: true,
+ $jspbMessageInstance:
+ extendable.getExtension(proto.jspb.test.IndirectExtension.simple)
+ },
+ str: 'xyzzy',
+ repeatedStrList: ['a', 'b'],
+ repeatedSimpleList: [{
+ aString: 'foo',
+ aRepeatedStringList: ['s1', 's2'],
+ aBoolean: true,
+ $jspbMessageInstance: s1
+ }, {
+ aString: 'bar',
+ aRepeatedStringList: ['t1', 't2'],
+ aBoolean: false,
+ $jspbMessageInstance: s2
+ }],
+ $jspbMessageInstance: extendable
+ }, extendable.toObject(true /* opt_includeInstance */));
+ });
+
+ it('testInitialization_emptyArray', function() {
+ var msg = new proto.jspb.test.HasExtensions([]);
+ assertArrayEquals([], msg.toArray());
+ });
+
+ it('testInitialization_justExtensionObject', function() {
+ var msg = new proto.jspb.test.Empty([{1: 'hi'}]);
+ // The extensionObject is not moved from its original location.
+ assertArrayEquals([{1: 'hi'}], msg.toArray());
+ });
+
+ it('testInitialization_incompleteList', function() {
+ var msg = new proto.jspb.test.Empty([1, {4: 'hi'}]);
+ // The extensionObject is not moved from its original location.
+ assertArrayEquals([1, {4: 'hi'}], msg.toArray());
+ });
+
+ it('testInitialization_forwardCompatible', function() {
+ var msg = new proto.jspb.test.Empty([1, 2, 3, {1: 'hi'}]);
+ assertArrayEquals([1, 2, 3, {1: 'hi'}], msg.toArray());
+ });
+
+ it('testExtendedMessageEnsureObject',
+ /** @suppress {visibility} */ function() {
+ var data =
+ new proto.jspb.test.HasExtensions(['str1', {'a_key': 'an_object'}]);
+ assertEquals('an_object', data.extensionObject_['a_key']);
+ });
+
+ it('testToObject_hasExtensionField', function() {
+ var data = new proto.jspb.test.HasExtensions(['str1', {100: ['ext1']}]);
+ var obj = data.toObject();
+ assertEquals('str1', obj.str1);
+ assertEquals('ext1', obj.extField.ext1);
+ });
+
+ it('testGetExtension', function() {
+ var data = new proto.jspb.test.HasExtensions(['str1', {100: ['ext1']}]);
+ assertEquals('str1', data.getStr1());
+ var extension = data.getExtension(proto.jspb.test.IsExtension.extField);
+ assertNotNull(extension);
+ assertEquals('ext1', extension.getExt1());
+ });
+
+ it('testSetExtension', function() {
+ var data = new proto.jspb.test.HasExtensions();
+ var extensionMessage = new proto.jspb.test.IsExtension(['is_extension']);
+ data.setExtension(proto.jspb.test.IsExtension.extField, extensionMessage);
+ var obj = data.toObject();
+ assertNotNull(
+ data.getExtension(proto.jspb.test.IsExtension.extField));
+ assertEquals('is_extension', obj.extField.ext1);
+ });
+
+ /**
+ * Note that group is long deprecated, we only support it because JsPb has
+ * a goal of being able to generate JS classes for all proto descriptors.
+ */
+ it('testGroups', function() {
+ var group = new proto.jspb.test.TestGroup();
+ var someGroup = new proto.jspb.test.TestGroup.RepeatedGroup();
+ someGroup.setId('g1');
+ someGroup.setSomeBoolList([true, false]);
+ group.setRepeatedGroupList([someGroup]);
+ var groups = group.getRepeatedGroupList();
+ assertEquals('g1', groups[0].getId());
+ assertObjectEquals([true, false], groups[0].getSomeBoolList());
+ assertObjectEquals({id: 'g1', someBoolList: [true, false]},
+ groups[0].toObject());
+ assertObjectEquals({
+ repeatedGroupList: [{id: 'g1', someBoolList: [true, false]}],
+ requiredGroup: {id: undefined},
+ optionalGroup: undefined,
+ requiredSimple: {aRepeatedStringList: [], aString: undefined},
+ optionalSimple: undefined,
+ id: undefined
+ }, group.toObject());
+ var group1 = new proto.jspb.test.TestGroup1();
+ group1.setGroup(someGroup);
+ assertEquals(someGroup, group1.getGroup());
+ });
+
+ it('testNonExtensionFieldsAfterExtensionRange', function() {
+ var data = [{'1': 'a_string'}];
+ var message = new proto.jspb.test.Complex(data);
+ assertArrayEquals([], message.getARepeatedStringList());
+ });
+
+ it('testReservedGetterNames', function() {
+ var message = new proto.jspb.test.TestReservedNames();
+ message.setExtension$(11);
+ message.setExtension(proto.jspb.test.TestReservedNamesExtension.foo, 12);
+ assertEquals(11, message.getExtension$());
+ assertEquals(12, message.getExtension(
+ proto.jspb.test.TestReservedNamesExtension.foo));
+ assertObjectEquals({extension: 11, foo: 12}, message.toObject());
+ });
+
+ it('testInitializeMessageWithUnsetOneof', function() {
+ var message = new proto.jspb.test.TestMessageWithOneof([]);
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.PartialOneofCase.
+ PARTIAL_ONEOF_NOT_SET,
+ message.getPartialOneofCase());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.RecursiveOneofCase.
+ RECURSIVE_ONEOF_NOT_SET,
+ message.getRecursiveOneofCase());
+ });
+
+ it('testInitializeMessageWithSingleValueSetInOneof', function() {
+ var message = new proto.jspb.test.TestMessageWithOneof([,, 'x']);
+
+ assertEquals('x', message.getPone());
+ assertEquals('', message.getPthree());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.PartialOneofCase.PONE,
+ message.getPartialOneofCase());
+ });
+
+ it('testKeepsLastWireValueSetInUnion_multipleValues', function() {
+ var message = new proto.jspb.test.TestMessageWithOneof([,, 'x',, 'y']);
+
+ assertEquals('', message.getPone());
+ assertEquals('y', message.getPthree());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.PartialOneofCase.PTHREE,
+ message.getPartialOneofCase());
+ });
+
+ it('testSettingOneofFieldClearsOthers', function() {
+ var message = new proto.jspb.test.TestMessageWithOneof;
+ assertEquals('', message.getPone());
+ assertEquals('', message.getPthree());
+ assertFalse(message.hasPone());
+ assertFalse(message.hasPthree());
+
+ message.setPone('hi');
+ assertEquals('hi', message.getPone());
+ assertEquals('', message.getPthree());
+ assertTrue(message.hasPone());
+ assertFalse(message.hasPthree());
+
+ message.setPthree('bye');
+ assertEquals('', message.getPone());
+ assertEquals('bye', message.getPthree());
+ assertFalse(message.hasPone());
+ assertTrue(message.hasPthree());
+ });
+
+ it('testSettingOneofFieldDoesNotClearFieldsFromOtherUnions', function() {
+ var other = new proto.jspb.test.TestMessageWithOneof;
+ var message = new proto.jspb.test.TestMessageWithOneof;
+ assertEquals('', message.getPone());
+ assertEquals('', message.getPthree());
+ assertUndefined(message.getRone());
+ assertFalse(message.hasPone());
+ assertFalse(message.hasPthree());
+
+ message.setPone('hi');
+ message.setRone(other);
+ assertEquals('hi', message.getPone());
+ assertEquals('', message.getPthree());
+ assertEquals(other, message.getRone());
+ assertTrue(message.hasPone());
+ assertFalse(message.hasPthree());
+
+ message.setPthree('bye');
+ assertEquals('', message.getPone());
+ assertEquals('bye', message.getPthree());
+ assertEquals(other, message.getRone());
+ assertFalse(message.hasPone());
+ assertTrue(message.hasPthree());
+ });
+
+ it('testUnsetsOneofCaseWhenFieldIsCleared', function() {
+ var message = new proto.jspb.test.TestMessageWithOneof;
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.PartialOneofCase.
+ PARTIAL_ONEOF_NOT_SET,
+ message.getPartialOneofCase());
+
+ message.setPone('hi');
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.PartialOneofCase.PONE,
+ message.getPartialOneofCase());
+
+ message.clearPone();
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.PartialOneofCase.
+ PARTIAL_ONEOF_NOT_SET,
+ message.getPartialOneofCase());
+ });
+
+ it('testMessageWithDefaultOneofValues', function() {
+ var message = new proto.jspb.test.TestMessageWithOneof;
+ assertEquals(1234, message.getAone());
+ assertEquals(0, message.getAtwo());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.DefaultOneofACase
+ .DEFAULT_ONEOF_A_NOT_SET,
+ message.getDefaultOneofACase());
+
+ message.setAone(567);
+ assertEquals(567, message.getAone());
+ assertEquals(0, message.getAtwo());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.DefaultOneofACase.AONE,
+ message.getDefaultOneofACase());
+
+ message.setAtwo(890);
+ assertEquals(1234, message.getAone());
+ assertEquals(890, message.getAtwo());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.DefaultOneofACase.ATWO,
+ message.getDefaultOneofACase());
+
+ message.clearAtwo();
+ assertEquals(1234, message.getAone());
+ assertEquals(0, message.getAtwo());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.DefaultOneofACase
+ .DEFAULT_ONEOF_A_NOT_SET,
+ message.getDefaultOneofACase());
+ });
+
+ it('testMessageWithDefaultOneofValues_defaultNotOnFirstField', function() {
+ var message = new proto.jspb.test.TestMessageWithOneof;
+ assertEquals(0, message.getBone());
+ assertEquals(1234, message.getBtwo());
+ assertFalse(message.hasBone());
+ assertFalse(message.hasBtwo());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.DefaultOneofBCase
+ .DEFAULT_ONEOF_B_NOT_SET,
+ message.getDefaultOneofBCase());
+
+ message.setBone(2);
+ assertEquals(2, message.getBone());
+ assertEquals(1234, message.getBtwo());
+ assertTrue(message.hasBone());
+ assertFalse(message.hasBtwo());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.DefaultOneofBCase.BONE,
+ message.getDefaultOneofBCase());
+
+ message.setBtwo(3);
+ assertEquals(0, message.getBone());
+ assertFalse(message.hasBone());
+ assertTrue(message.hasBtwo());
+ assertEquals(3, message.getBtwo());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.DefaultOneofBCase.BTWO,
+ message.getDefaultOneofBCase());
+
+ message.clearBtwo();
+ assertEquals(0, message.getBone());
+ assertFalse(message.hasBone());
+ assertFalse(message.hasBtwo());
+ assertEquals(1234, message.getBtwo());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.DefaultOneofBCase
+ .DEFAULT_ONEOF_B_NOT_SET,
+ message.getDefaultOneofBCase());
+ });
+
+ it('testInitializeMessageWithOneofDefaults', function() {
+ var message =
+ new proto.jspb.test.TestMessageWithOneof(new Array(9).concat(567));
+ assertEquals(567, message.getAone());
+ assertEquals(0, message.getAtwo());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.DefaultOneofACase.AONE,
+ message.getDefaultOneofACase());
+
+ message =
+ new proto.jspb.test.TestMessageWithOneof(new Array(10).concat(890));
+ assertEquals(1234, message.getAone());
+ assertEquals(890, message.getAtwo());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.DefaultOneofACase.ATWO,
+ message.getDefaultOneofACase());
+
+ message =
+ new proto.jspb.test.TestMessageWithOneof(new Array(9).concat(567, 890));
+ assertEquals(1234, message.getAone());
+ assertEquals(890, message.getAtwo());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.DefaultOneofACase.ATWO,
+ message.getDefaultOneofACase());
+ });
+
+ it('testInitializeMessageWithOneofDefaults_defaultNotSetOnFirstField',
+ function() {
+ var message;
+
+ message =
+ new proto.jspb.test.TestMessageWithOneof(new Array(11).concat(567));
+ assertEquals(567, message.getBone());
+ assertEquals(1234, message.getBtwo());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.DefaultOneofBCase.BONE,
+ message.getDefaultOneofBCase());
+
+ message =
+ new proto.jspb.test.TestMessageWithOneof(new Array(12).concat(890));
+ assertEquals(0, message.getBone());
+ assertEquals(890, message.getBtwo());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.DefaultOneofBCase.BTWO,
+ message.getDefaultOneofBCase());
+
+ message = new proto.jspb.test.TestMessageWithOneof(
+ new Array(11).concat(567, 890));
+ assertEquals(0, message.getBone());
+ assertEquals(890, message.getBtwo());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.DefaultOneofBCase.BTWO,
+ message.getDefaultOneofBCase());
+ });
+
+ it('testOneofContainingAnotherMessage', function() {
+ var message = new proto.jspb.test.TestMessageWithOneof;
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.RecursiveOneofCase.
+ RECURSIVE_ONEOF_NOT_SET,
+ message.getRecursiveOneofCase());
+
+ var other = new proto.jspb.test.TestMessageWithOneof;
+ message.setRone(other);
+ assertEquals(other, message.getRone());
+ assertEquals('', message.getRtwo());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.RecursiveOneofCase.RONE,
+ message.getRecursiveOneofCase());
+
+ message.setRtwo('hi');
+ assertUndefined(message.getRone());
+ assertEquals('hi', message.getRtwo());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.RecursiveOneofCase.RTWO,
+ message.getRecursiveOneofCase());
+ });
+
+ it('testQueryingOneofCaseEnsuresOnlyOneFieldIsSetInUnderlyingArray',
+ function() {
+ var message = new proto.jspb.test.TestMessageWithOneof;
+ message.setPone('x');
+ assertEquals('x', message.getPone());
+ assertEquals('', message.getPthree());
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.PartialOneofCase.PONE,
+ message.getPartialOneofCase());
+
+ var array = message.toArray();
+ assertEquals('x', array[2]);
+ assertUndefined(array[4]);
+ array[4] = 'y';
+
+ assertEquals(
+ proto.jspb.test.TestMessageWithOneof.PartialOneofCase.PTHREE,
+ message.getPartialOneofCase());
+ assertUndefined(array[2]);
+ assertEquals('y', array[4]);
+ });
+
+ it('testFloatingPointFieldsSupportNan', function() {
+ var assertNan = function(x) {
+ assertTrue('Expected ' + x + ' (' + goog.typeOf(x) + ') to be NaN.',
+ goog.isNumber(x) && isNaN(x));
+ };
+
+ var message = new proto.jspb.test.FloatingPointFields([
+ 'NaN', 'NaN', ['NaN', 'NaN'], 'NaN',
+ 'NaN', 'NaN', ['NaN', 'NaN'], 'NaN'
+ ]);
+ assertNan(message.getOptionalFloatField());
+ assertNan(message.getRequiredFloatField());
+ assertNan(message.getRepeatedFloatFieldList()[0]);
+ assertNan(message.getRepeatedFloatFieldList()[1]);
+ assertNan(message.getDefaultFloatField());
+ assertNan(message.getOptionalDoubleField());
+ assertNan(message.getRequiredDoubleField());
+ assertNan(message.getRepeatedDoubleFieldList()[0]);
+ assertNan(message.getRepeatedDoubleFieldList()[1]);
+ assertNan(message.getDefaultDoubleField());
+ });
+
+});
diff --git a/js/compatibility_tests/v3.1.0/proto3_test.js b/js/compatibility_tests/v3.1.0/proto3_test.js
new file mode 100644
index 00000000..3c929eff
--- /dev/null
+++ b/js/compatibility_tests/v3.1.0/proto3_test.js
@@ -0,0 +1,329 @@
+// 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.
+
+goog.require('goog.crypt.base64');
+goog.require('goog.testing.asserts');
+
+// CommonJS-LoadFromFile: testbinary_pb proto.jspb.test
+goog.require('proto.jspb.test.ForeignMessage');
+
+// CommonJS-LoadFromFile: proto3_test_pb proto.jspb.test
+goog.require('proto.jspb.test.Proto3Enum');
+goog.require('proto.jspb.test.TestProto3');
+
+
+var BYTES = new Uint8Array([1, 2, 8, 9]);
+var BYTES_B64 = goog.crypt.base64.encodeByteArray(BYTES);
+
+
+/**
+ * Helper: compare a bytes field to an expected value
+ * @param {Uint8Array|string} arr
+ * @param {Uint8Array} expected
+ * @return {boolean}
+ */
+function bytesCompare(arr, expected) {
+ if (goog.isString(arr)) {
+ arr = goog.crypt.base64.decodeStringToUint8Array(arr);
+ }
+ if (arr.length != expected.length) {
+ return false;
+ }
+ for (var i = 0; i < arr.length; i++) {
+ if (arr[i] != expected[i]) {
+ return false;
+ }
+ }
+ return true;
+}
+
+
+describe('proto3Test', function() {
+ /**
+ * Test defaults for proto3 message fields.
+ */
+ it('testProto3FieldDefaults', function() {
+ var msg = new proto.jspb.test.TestProto3();
+
+ assertEquals(msg.getOptionalInt32(), 0);
+ assertEquals(msg.getOptionalInt64(), 0);
+ assertEquals(msg.getOptionalUint32(), 0);
+ assertEquals(msg.getOptionalUint64(), 0);
+ assertEquals(msg.getOptionalSint32(), 0);
+ assertEquals(msg.getOptionalSint64(), 0);
+ assertEquals(msg.getOptionalFixed32(), 0);
+ assertEquals(msg.getOptionalFixed64(), 0);
+ assertEquals(msg.getOptionalSfixed32(), 0);
+ assertEquals(msg.getOptionalSfixed64(), 0);
+ assertEquals(msg.getOptionalFloat(), 0);
+ assertEquals(msg.getOptionalDouble(), 0);
+ assertEquals(msg.getOptionalString(), '');
+
+ // TODO(b/26173701): when we change bytes fields default getter to return
+ // Uint8Array, we'll want to switch this assertion to match the u8 case.
+ assertEquals(typeof msg.getOptionalBytes(), 'string');
+ assertEquals(msg.getOptionalBytes_asU8() instanceof Uint8Array, true);
+ assertEquals(typeof msg.getOptionalBytes_asB64(), 'string');
+ assertEquals(msg.getOptionalBytes().length, 0);
+ assertEquals(msg.getOptionalBytes_asU8().length, 0);
+ assertEquals(msg.getOptionalBytes_asB64(), '');
+
+ assertEquals(msg.getOptionalForeignEnum(),
+ proto.jspb.test.Proto3Enum.PROTO3_FOO);
+ assertEquals(msg.getOptionalForeignMessage(), undefined);
+ assertEquals(msg.getOptionalForeignMessage(), undefined);
+
+ assertEquals(msg.getRepeatedInt32List().length, 0);
+ assertEquals(msg.getRepeatedInt64List().length, 0);
+ assertEquals(msg.getRepeatedUint32List().length, 0);
+ assertEquals(msg.getRepeatedUint64List().length, 0);
+ assertEquals(msg.getRepeatedSint32List().length, 0);
+ assertEquals(msg.getRepeatedSint64List().length, 0);
+ assertEquals(msg.getRepeatedFixed32List().length, 0);
+ assertEquals(msg.getRepeatedFixed64List().length, 0);
+ assertEquals(msg.getRepeatedSfixed32List().length, 0);
+ assertEquals(msg.getRepeatedSfixed64List().length, 0);
+ assertEquals(msg.getRepeatedFloatList().length, 0);
+ assertEquals(msg.getRepeatedDoubleList().length, 0);
+ assertEquals(msg.getRepeatedStringList().length, 0);
+ assertEquals(msg.getRepeatedBytesList().length, 0);
+ assertEquals(msg.getRepeatedForeignEnumList().length, 0);
+ assertEquals(msg.getRepeatedForeignMessageList().length, 0);
+
+ });
+
+
+ /**
+ * Test that all fields can be set and read via a serialization roundtrip.
+ */
+ it('testProto3FieldSetGet', function() {
+ var msg = new proto.jspb.test.TestProto3();
+
+ msg.setOptionalInt32(-42);
+ msg.setOptionalInt64(-0x7fffffff00000000);
+ msg.setOptionalUint32(0x80000000);
+ msg.setOptionalUint64(0xf000000000000000);
+ msg.setOptionalSint32(-100);
+ msg.setOptionalSint64(-0x8000000000000000);
+ msg.setOptionalFixed32(1234);
+ msg.setOptionalFixed64(0x1234567800000000);
+ msg.setOptionalSfixed32(-1234);
+ msg.setOptionalSfixed64(-0x1234567800000000);
+ msg.setOptionalFloat(1.5);
+ msg.setOptionalDouble(-1.5);
+ msg.setOptionalBool(true);
+ msg.setOptionalString('hello world');
+ msg.setOptionalBytes(BYTES);
+ var submsg = new proto.jspb.test.ForeignMessage();
+ submsg.setC(16);
+ msg.setOptionalForeignMessage(submsg);
+ msg.setOptionalForeignEnum(proto.jspb.test.Proto3Enum.PROTO3_BAR);
+
+ msg.setRepeatedInt32List([-42]);
+ msg.setRepeatedInt64List([-0x7fffffff00000000]);
+ msg.setRepeatedUint32List([0x80000000]);
+ msg.setRepeatedUint64List([0xf000000000000000]);
+ msg.setRepeatedSint32List([-100]);
+ msg.setRepeatedSint64List([-0x8000000000000000]);
+ msg.setRepeatedFixed32List([1234]);
+ msg.setRepeatedFixed64List([0x1234567800000000]);
+ msg.setRepeatedSfixed32List([-1234]);
+ msg.setRepeatedSfixed64List([-0x1234567800000000]);
+ msg.setRepeatedFloatList([1.5]);
+ msg.setRepeatedDoubleList([-1.5]);
+ msg.setRepeatedBoolList([true]);
+ msg.setRepeatedStringList(['hello world']);
+ msg.setRepeatedBytesList([BYTES]);
+ submsg = new proto.jspb.test.ForeignMessage();
+ submsg.setC(1000);
+ msg.setRepeatedForeignMessageList([submsg]);
+ msg.setRepeatedForeignEnumList([proto.jspb.test.Proto3Enum.PROTO3_BAR]);
+
+ msg.setOneofString('asdf');
+
+ var serialized = msg.serializeBinary();
+ msg = proto.jspb.test.TestProto3.deserializeBinary(serialized);
+
+ assertEquals(msg.getOptionalInt32(), -42);
+ assertEquals(msg.getOptionalInt64(), -0x7fffffff00000000);
+ assertEquals(msg.getOptionalUint32(), 0x80000000);
+ assertEquals(msg.getOptionalUint64(), 0xf000000000000000);
+ assertEquals(msg.getOptionalSint32(), -100);
+ assertEquals(msg.getOptionalSint64(), -0x8000000000000000);
+ assertEquals(msg.getOptionalFixed32(), 1234);
+ assertEquals(msg.getOptionalFixed64(), 0x1234567800000000);
+ assertEquals(msg.getOptionalSfixed32(), -1234);
+ assertEquals(msg.getOptionalSfixed64(), -0x1234567800000000);
+ assertEquals(msg.getOptionalFloat(), 1.5);
+ assertEquals(msg.getOptionalDouble(), -1.5);
+ assertEquals(msg.getOptionalBool(), true);
+ assertEquals(msg.getOptionalString(), 'hello world');
+ assertEquals(true, bytesCompare(msg.getOptionalBytes(), BYTES));
+ assertEquals(msg.getOptionalForeignMessage().getC(), 16);
+ assertEquals(msg.getOptionalForeignEnum(),
+ proto.jspb.test.Proto3Enum.PROTO3_BAR);
+
+ assertElementsEquals(msg.getRepeatedInt32List(), [-42]);
+ assertElementsEquals(msg.getRepeatedInt64List(), [-0x7fffffff00000000]);
+ assertElementsEquals(msg.getRepeatedUint32List(), [0x80000000]);
+ assertElementsEquals(msg.getRepeatedUint64List(), [0xf000000000000000]);
+ assertElementsEquals(msg.getRepeatedSint32List(), [-100]);
+ assertElementsEquals(msg.getRepeatedSint64List(), [-0x8000000000000000]);
+ assertElementsEquals(msg.getRepeatedFixed32List(), [1234]);
+ assertElementsEquals(msg.getRepeatedFixed64List(), [0x1234567800000000]);
+ assertElementsEquals(msg.getRepeatedSfixed32List(), [-1234]);
+ assertElementsEquals(msg.getRepeatedSfixed64List(), [-0x1234567800000000]);
+ assertElementsEquals(msg.getRepeatedFloatList(), [1.5]);
+ assertElementsEquals(msg.getRepeatedDoubleList(), [-1.5]);
+ assertElementsEquals(msg.getRepeatedBoolList(), [true]);
+ assertElementsEquals(msg.getRepeatedStringList(), ['hello world']);
+ assertEquals(msg.getRepeatedBytesList().length, 1);
+ assertEquals(true, bytesCompare(msg.getRepeatedBytesList()[0], BYTES));
+ assertEquals(msg.getRepeatedForeignMessageList().length, 1);
+ assertEquals(msg.getRepeatedForeignMessageList()[0].getC(), 1000);
+ assertElementsEquals(msg.getRepeatedForeignEnumList(),
+ [proto.jspb.test.Proto3Enum.PROTO3_BAR]);
+
+ assertEquals(msg.getOneofString(), 'asdf');
+ });
+
+
+ /**
+ * Test that oneofs continue to have a notion of field presence.
+ */
+ it('testOneofs', function() {
+ var msg = new proto.jspb.test.TestProto3();
+
+ assertEquals(msg.getOneofUint32(), 0);
+ assertEquals(msg.getOneofForeignMessage(), undefined);
+ assertEquals(msg.getOneofString(), '');
+ assertEquals(msg.getOneofBytes(), '');
+ assertFalse(msg.hasOneofUint32());
+ assertFalse(msg.hasOneofString());
+ assertFalse(msg.hasOneofBytes());
+
+ msg.setOneofUint32(42);
+ assertEquals(msg.getOneofUint32(), 42);
+ assertEquals(msg.getOneofForeignMessage(), undefined);
+ assertEquals(msg.getOneofString(), '');
+ assertEquals(msg.getOneofBytes(), '');
+ assertTrue(msg.hasOneofUint32());
+ assertFalse(msg.hasOneofString());
+ assertFalse(msg.hasOneofBytes());
+
+
+ var submsg = new proto.jspb.test.ForeignMessage();
+ msg.setOneofForeignMessage(submsg);
+ assertEquals(msg.getOneofUint32(), 0);
+ assertEquals(msg.getOneofForeignMessage(), submsg);
+ assertEquals(msg.getOneofString(), '');
+ assertEquals(msg.getOneofBytes(), '');
+ assertFalse(msg.hasOneofUint32());
+ assertFalse(msg.hasOneofString());
+ assertFalse(msg.hasOneofBytes());
+
+ msg.setOneofString('hello');
+ assertEquals(msg.getOneofUint32(), 0);
+ assertEquals(msg.getOneofForeignMessage(), undefined);
+ assertEquals(msg.getOneofString(), 'hello');
+ assertEquals(msg.getOneofBytes(), '');
+ assertFalse(msg.hasOneofUint32());
+ assertTrue(msg.hasOneofString());
+ assertFalse(msg.hasOneofBytes());
+
+ msg.setOneofBytes(goog.crypt.base64.encodeString('\u00FF\u00FF'));
+ assertEquals(msg.getOneofUint32(), 0);
+ assertEquals(msg.getOneofForeignMessage(), undefined);
+ assertEquals(msg.getOneofString(), '');
+ assertEquals(msg.getOneofBytes_asB64(),
+ goog.crypt.base64.encodeString('\u00FF\u00FF'));
+ assertFalse(msg.hasOneofUint32());
+ assertFalse(msg.hasOneofString());
+ assertTrue(msg.hasOneofBytes());
+ });
+
+
+ /**
+ * Test that "default"-valued primitive fields are not emitted on the wire.
+ */
+ it('testNoSerializeDefaults', function() {
+ var msg = new proto.jspb.test.TestProto3();
+
+ // Set each primitive to a non-default value, then back to its default, to
+ // ensure that the serialization is actually checking the value and not just
+ // whether it has ever been set.
+ msg.setOptionalInt32(42);
+ msg.setOptionalInt32(0);
+ msg.setOptionalDouble(3.14);
+ msg.setOptionalDouble(0.0);
+ msg.setOptionalBool(true);
+ msg.setOptionalBool(false);
+ msg.setOptionalString('hello world');
+ msg.setOptionalString('');
+ msg.setOptionalBytes(goog.crypt.base64.encodeString('\u00FF\u00FF'));
+ msg.setOptionalBytes('');
+ msg.setOptionalForeignMessage(new proto.jspb.test.ForeignMessage());
+ msg.setOptionalForeignMessage(null);
+ msg.setOptionalForeignEnum(proto.jspb.test.Proto3Enum.PROTO3_BAR);
+ msg.setOptionalForeignEnum(proto.jspb.test.Proto3Enum.PROTO3_FOO);
+ msg.setOneofUint32(32);
+ msg.clearOneofUint32();
+
+
+ var serialized = msg.serializeBinary();
+ assertEquals(0, serialized.length);
+ });
+
+ /**
+ * Test that base64 string and Uint8Array are interchangeable in bytes fields.
+ */
+ it('testBytesFieldsInterop', function() {
+ var msg = new proto.jspb.test.TestProto3();
+ // Set as a base64 string and check all the getters work.
+ msg.setOptionalBytes(BYTES_B64);
+ assertTrue(bytesCompare(msg.getOptionalBytes_asU8(), BYTES));
+ assertTrue(bytesCompare(msg.getOptionalBytes_asB64(), BYTES));
+ assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
+
+ // Test binary serialize round trip doesn't break it.
+ msg = proto.jspb.test.TestProto3.deserializeBinary(msg.serializeBinary());
+ assertTrue(bytesCompare(msg.getOptionalBytes_asU8(), BYTES));
+ assertTrue(bytesCompare(msg.getOptionalBytes_asB64(), BYTES));
+ assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
+
+ msg = new proto.jspb.test.TestProto3();
+ // Set as a Uint8Array and check all the getters work.
+ msg.setOptionalBytes(BYTES);
+ assertTrue(bytesCompare(msg.getOptionalBytes_asU8(), BYTES));
+ assertTrue(bytesCompare(msg.getOptionalBytes_asB64(), BYTES));
+ assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
+
+ });
+});
diff --git a/js/compatibility_tests/v3.1.0/proto3_test.proto b/js/compatibility_tests/v3.1.0/proto3_test.proto
new file mode 100644
index 00000000..acb67164
--- /dev/null
+++ b/js/compatibility_tests/v3.1.0/proto3_test.proto
@@ -0,0 +1,89 @@
+// 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.
+
+syntax = "proto3";
+
+import "testbinary.proto";
+
+package jspb.test;
+
+message TestProto3 {
+ int32 optional_int32 = 1;
+ int64 optional_int64 = 2;
+ uint32 optional_uint32 = 3;
+ uint64 optional_uint64 = 4;
+ sint32 optional_sint32 = 5;
+ sint64 optional_sint64 = 6;
+ fixed32 optional_fixed32 = 7;
+ fixed64 optional_fixed64 = 8;
+ sfixed32 optional_sfixed32 = 9;
+ sfixed64 optional_sfixed64 = 10;
+ float optional_float = 11;
+ double optional_double = 12;
+ bool optional_bool = 13;
+ string optional_string = 14;
+ bytes optional_bytes = 15;
+
+ ForeignMessage optional_foreign_message = 19;
+ Proto3Enum optional_foreign_enum = 22;
+
+ 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 ForeignMessage repeated_foreign_message = 49;
+ repeated Proto3Enum repeated_foreign_enum = 52;
+
+
+ oneof oneof_field {
+ uint32 oneof_uint32 = 111;
+ ForeignMessage oneof_foreign_message = 112;
+ string oneof_string = 113;
+ bytes oneof_bytes = 114;
+ }
+}
+
+enum Proto3Enum {
+ PROTO3_FOO = 0;
+ PROTO3_BAR = 1;
+ PROTO3_BAZ = 2;
+}
diff --git a/js/compatibility_tests/v3.1.0/test.proto b/js/compatibility_tests/v3.1.0/test.proto
new file mode 100644
index 00000000..48cb37e1
--- /dev/null
+++ b/js/compatibility_tests/v3.1.0/test.proto
@@ -0,0 +1,262 @@
+// 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: mwr@google.com (Mark Rawling)
+
+syntax = "proto2";
+
+option java_package = "com.google.apps.jspb.proto";
+option java_multiple_files = true;
+
+import "google/protobuf/descriptor.proto";
+
+package jspb.test;
+
+message Empty {
+}
+
+enum OuterEnum {
+ FOO = 1;
+ BAR = 2;
+}
+
+message EnumContainer {
+ optional OuterEnum outer_enum = 1;
+}
+
+message Simple1 {
+ required string a_string = 1;
+ repeated string a_repeated_string = 2;
+ optional bool a_boolean = 3;
+}
+
+// A message that differs from Simple1 only by name
+message Simple2 {
+ required string a_string = 1;
+ repeated string a_repeated_string = 2;
+}
+
+message SpecialCases {
+ required string normal = 1;
+ // Examples of Js reserved names that are converted to pb_<name>.
+ required string default = 2;
+ required string function = 3;
+ required string var = 4;
+}
+
+message OptionalFields {
+ message Nested {
+ optional int32 an_int = 1;
+ }
+ optional string a_string = 1;
+ required bool a_bool = 2;
+ optional Nested a_nested_message = 3;
+ repeated Nested a_repeated_message = 4;
+ repeated string a_repeated_string = 5;
+}
+
+message HasExtensions {
+ optional string str1 = 1;
+ optional string str2 = 2;
+ optional string str3 = 3;
+ extensions 10 to max;
+}
+
+message Complex {
+ message Nested {
+ required int32 an_int = 2;
+ }
+ required string a_string = 1;
+ required bool an_out_of_order_bool = 9;
+ optional Nested a_nested_message = 4;
+ repeated Nested a_repeated_message = 5;
+ repeated string a_repeated_string = 7;
+}
+
+message OuterMessage {
+ // Make sure this doesn't conflict with the other Complex message.
+ message Complex {
+ optional int32 inner_complex_field = 1;
+ }
+}
+
+message IsExtension {
+ extend HasExtensions {
+ optional IsExtension ext_field = 100;
+ }
+ optional string ext1 = 1;
+
+ // Extensions of proto2 Descriptor messages will be ignored.
+ extend google.protobuf.EnumOptions {
+ optional string simple_option = 42113038;
+ }
+}
+
+message IndirectExtension {
+ extend HasExtensions {
+ optional Simple1 simple = 101;
+ optional string str = 102;
+ repeated string repeated_str = 103;
+ repeated Simple1 repeated_simple = 104;
+ }
+}
+
+extend HasExtensions {
+ optional Simple1 simple1 = 105;
+}
+
+message DefaultValues {
+ enum Enum {
+ E1 = 13;
+ E2 = 77;
+ }
+ optional string string_field = 1 [default="default<>\'\"abc"];
+ optional bool bool_field = 2 [default=true];
+ optional int64 int_field = 3 [default=11];
+ optional Enum enum_field = 4 [default=E1];
+ optional string empty_field = 6 [default=""];
+ optional bytes bytes_field = 8 [default="moo"]; // Base64 encoding is "bW9v"
+}
+
+message FloatingPointFields {
+ optional float optional_float_field = 1;
+ required float required_float_field = 2;
+ repeated float repeated_float_field = 3;
+ optional float default_float_field = 4 [default = 2.0];
+ optional double optional_double_field = 5;
+ required double required_double_field = 6;
+ repeated double repeated_double_field = 7;
+ optional double default_double_field = 8 [default = 2.0];
+}
+
+message TestClone {
+ optional string str = 1;
+ optional Simple1 simple1 = 3;
+ repeated Simple1 simple2 = 5;
+ optional bytes bytes_field = 6;
+ optional string unused = 7;
+ extensions 10 to max;
+}
+
+message CloneExtension {
+ extend TestClone {
+ optional CloneExtension ext_field = 100;
+ }
+ optional string ext = 2;
+}
+
+message TestGroup {
+ repeated group RepeatedGroup = 1 {
+ required string id = 1;
+ repeated bool some_bool = 2;
+ }
+ required group RequiredGroup = 2 {
+ required string id = 1;
+ }
+ optional group OptionalGroup = 3 {
+ required string id = 1;
+ }
+ optional string id = 4;
+ required Simple2 required_simple = 5;
+ optional Simple2 optional_simple = 6;
+}
+
+message TestGroup1 {
+ optional TestGroup.RepeatedGroup group = 1;
+}
+
+message TestReservedNames {
+ optional int32 extension = 1;
+ extensions 10 to max;
+}
+
+message TestReservedNamesExtension {
+ extend TestReservedNames {
+ optional int32 foo = 10;
+ }
+}
+
+message TestMessageWithOneof {
+
+ oneof partial_oneof {
+ string pone = 3;
+ string pthree = 5;
+ }
+
+ oneof recursive_oneof {
+ TestMessageWithOneof rone = 6;
+ string rtwo = 7;
+ }
+
+ optional bool normal_field = 8;
+ repeated string repeated_field = 9;
+
+ oneof default_oneof_a {
+ int32 aone = 10 [default = 1234];
+ int32 atwo = 11;
+ }
+
+ oneof default_oneof_b {
+ int32 bone = 12;
+ int32 btwo = 13 [default = 1234];
+ }
+}
+
+message TestEndsWithBytes {
+ optional int32 value = 1;
+ optional bytes data = 2;
+}
+
+message TestMapFieldsNoBinary {
+ map<string, string> map_string_string = 1;
+ map<string, int32> map_string_int32 = 2;
+ map<string, int64> map_string_int64 = 3;
+ map<string, bool> map_string_bool = 4;
+ map<string, double> map_string_double = 5;
+ map<string, MapValueEnumNoBinary> map_string_enum = 6;
+ map<string, MapValueMessageNoBinary> map_string_msg = 7;
+
+ map<int32, string> map_int32_string = 8;
+ map<int64, string> map_int64_string = 9;
+ map<bool, string> map_bool_string = 10;
+
+ optional TestMapFieldsNoBinary test_map_fields = 11;
+ map<string, TestMapFieldsNoBinary> map_string_testmapfields = 12;
+}
+
+enum MapValueEnumNoBinary {
+ MAP_VALUE_FOO_NOBINARY = 0;
+ MAP_VALUE_BAR_NOBINARY = 1;
+ MAP_VALUE_BAZ_NOBINARY = 2;
+}
+
+message MapValueMessageNoBinary {
+ optional int32 foo = 1;
+}
diff --git a/js/compatibility_tests/v3.1.0/test2.proto b/js/compatibility_tests/v3.1.0/test2.proto
new file mode 100644
index 00000000..44e55eff
--- /dev/null
+++ b/js/compatibility_tests/v3.1.0/test2.proto
@@ -0,0 +1,54 @@
+// 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.
+
+syntax = "proto2";
+
+option java_package = "com.google.apps.jspb.proto";
+option java_multiple_files = true;
+
+package jspb.test;
+
+message TestExtensionsMessage {
+ optional int32 intfield = 1;
+ extensions 100 to max;
+}
+
+message ExtensionMessage {
+ extend TestExtensionsMessage {
+ optional ExtensionMessage ext_field = 100;
+ }
+ optional string ext1 = 1;
+}
+
+// Floating extensions are only supported when generating a _lib.js library.
+extend TestExtensionsMessage {
+ optional ExtensionMessage floating_msg_field = 101;
+ optional string floating_str_field = 102;
+}
diff --git a/js/compatibility_tests/v3.1.0/test3.proto b/js/compatibility_tests/v3.1.0/test3.proto
new file mode 100644
index 00000000..940a552e
--- /dev/null
+++ b/js/compatibility_tests/v3.1.0/test3.proto
@@ -0,0 +1,53 @@
+// 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.
+
+syntax = "proto2";
+
+option java_package = "com.google.apps.jspb.proto";
+option java_multiple_files = true;
+
+package jspb.exttest;
+
+message TestExtensionsMessage {
+ optional int32 intfield = 1;
+ extensions 100 to max;
+}
+
+message ExtensionMessage {
+ extend TestExtensionsMessage {
+ optional ExtensionMessage ext_field = 100;
+ }
+ optional string ext1 = 1;
+}
+
+extend TestExtensionsMessage {
+ optional ExtensionMessage floating_msg_field = 101;
+ optional string floating_str_field = 102;
+}
diff --git a/js/compatibility_tests/v3.1.0/test4.proto b/js/compatibility_tests/v3.1.0/test4.proto
new file mode 100644
index 00000000..cf2451e9
--- /dev/null
+++ b/js/compatibility_tests/v3.1.0/test4.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.
+
+syntax = "proto2";
+
+option java_package = "com.google.apps.jspb.proto";
+option java_multiple_files = true;
+
+package jspb.exttest;
+
+import "test3.proto";
+
+extend TestExtensionsMessage {
+ optional ExtensionMessage floating_msg_field_two = 103;
+}
diff --git a/js/compatibility_tests/v3.1.0/test5.proto b/js/compatibility_tests/v3.1.0/test5.proto
new file mode 100644
index 00000000..34979517
--- /dev/null
+++ b/js/compatibility_tests/v3.1.0/test5.proto
@@ -0,0 +1,44 @@
+// 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.
+
+syntax = "proto2";
+
+option java_package = "com.google.apps.jspb.proto";
+option java_multiple_files = true;
+
+package jspb.exttest.beta;
+
+message TestBetaExtensionsMessage {
+ extensions 100 to max;
+}
+
+extend TestBetaExtensionsMessage {
+ optional string floating_str_field = 101;
+}
diff --git a/js/compatibility_tests/v3.1.0/testbinary.proto b/js/compatibility_tests/v3.1.0/testbinary.proto
new file mode 100644
index 00000000..116f17fb
--- /dev/null
+++ b/js/compatibility_tests/v3.1.0/testbinary.proto
@@ -0,0 +1,212 @@
+// 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.
+
+// LINT: ALLOW_GROUPS
+
+syntax = "proto2";
+
+
+package jspb.test;
+
+// These types are borrowed from `unittest.proto` in the protobuf tree. We want
+// to ensure that the binary-format support will handle all field types
+// properly.
+message TestAllTypes {
+ optional int32 optional_int32 = 1;
+ optional int64 optional_int64 = 2;
+ optional uint32 optional_uint32 = 3;
+ optional uint64 optional_uint64 = 4;
+ optional sint32 optional_sint32 = 5;
+ optional sint64 optional_sint64 = 6;
+ optional fixed32 optional_fixed32 = 7;
+ optional fixed64 optional_fixed64 = 8;
+ optional sfixed32 optional_sfixed32 = 9;
+ optional sfixed64 optional_sfixed64 = 10;
+ optional float optional_float = 11;
+ optional double optional_double = 12;
+ optional bool optional_bool = 13;
+ optional string optional_string = 14;
+ optional bytes optional_bytes = 15;
+ optional group OptionalGroup = 16 {
+ optional int32 a = 17;
+ }
+
+ optional ForeignMessage optional_foreign_message = 19;
+ optional ForeignEnum optional_foreign_enum = 22;
+
+ // Repeated
+ repeated int32 repeated_int32 = 31;
+ repeated int64 repeated_int64 = 32;
+ repeated uint32 repeated_uint32 = 33;
+ repeated uint64 repeated_uint64 = 34;
+ repeated sint32 repeated_sint32 = 35;
+ repeated sint64 repeated_sint64 = 36;
+ repeated fixed32 repeated_fixed32 = 37;
+ repeated fixed64 repeated_fixed64 = 38;
+ repeated sfixed32 repeated_sfixed32 = 39;
+ repeated sfixed64 repeated_sfixed64 = 40;
+ repeated float repeated_float = 41;
+ repeated double repeated_double = 42;
+ repeated bool repeated_bool = 43;
+ repeated string repeated_string = 44;
+ repeated bytes repeated_bytes = 45;
+
+ repeated group RepeatedGroup = 46 {
+ optional int32 a = 47;
+ }
+
+ repeated ForeignMessage repeated_foreign_message = 49;
+ repeated ForeignEnum repeated_foreign_enum = 52;
+
+ // Packed repeated
+ repeated int32 packed_repeated_int32 = 61 [packed=true];
+ repeated int64 packed_repeated_int64 = 62 [packed=true];
+ repeated uint32 packed_repeated_uint32 = 63 [packed=true];
+ repeated uint64 packed_repeated_uint64 = 64 [packed=true];
+ repeated sint32 packed_repeated_sint32 = 65 [packed=true];
+ repeated sint64 packed_repeated_sint64 = 66 [packed=true];
+ repeated fixed32 packed_repeated_fixed32 = 67 [packed=true];
+ repeated fixed64 packed_repeated_fixed64 = 68 [packed=true];
+ repeated sfixed32 packed_repeated_sfixed32 = 69 [packed=true];
+ repeated sfixed64 packed_repeated_sfixed64 = 70 [packed=true];
+ repeated float packed_repeated_float = 71 [packed=true];
+ repeated double packed_repeated_double = 72 [packed=true];
+ repeated bool packed_repeated_bool = 73 [packed=true];
+
+ oneof oneof_field {
+ uint32 oneof_uint32 = 111;
+ ForeignMessage oneof_foreign_message = 112;
+ string oneof_string = 113;
+ bytes oneof_bytes = 114;
+ }
+
+}
+
+message ForeignMessage {
+ optional int32 c = 1;
+}
+
+enum ForeignEnum {
+ FOREIGN_FOO = 4;
+ FOREIGN_BAR = 5;
+ FOREIGN_BAZ = 6;
+}
+
+message TestExtendable {
+ extensions 1 to max;
+}
+
+message ExtendsWithMessage {
+ extend TestExtendable {
+ optional ExtendsWithMessage optional_extension = 19;
+ repeated ExtendsWithMessage repeated_extension = 49;
+ }
+ optional int32 foo = 1;
+}
+
+extend TestExtendable {
+ optional int32 extend_optional_int32 = 1;
+ optional int64 extend_optional_int64 = 2;
+ optional uint32 extend_optional_uint32 = 3;
+ optional uint64 extend_optional_uint64 = 4;
+ optional sint32 extend_optional_sint32 = 5;
+ optional sint64 extend_optional_sint64 = 6;
+ optional fixed32 extend_optional_fixed32 = 7;
+ optional fixed64 extend_optional_fixed64 = 8;
+ optional sfixed32 extend_optional_sfixed32 = 9;
+ optional sfixed64 extend_optional_sfixed64 = 10;
+ optional float extend_optional_float = 11;
+ optional double extend_optional_double = 12;
+ optional bool extend_optional_bool = 13;
+ optional string extend_optional_string = 14;
+ optional bytes extend_optional_bytes = 15;
+ optional ForeignEnum extend_optional_foreign_enum = 22;
+
+ repeated int32 extend_repeated_int32 = 31;
+ repeated int64 extend_repeated_int64 = 32;
+ repeated uint32 extend_repeated_uint32 = 33;
+ repeated uint64 extend_repeated_uint64 = 34;
+ repeated sint32 extend_repeated_sint32 = 35;
+ repeated sint64 extend_repeated_sint64 = 36;
+ repeated fixed32 extend_repeated_fixed32 = 37;
+ repeated fixed64 extend_repeated_fixed64 = 38;
+ repeated sfixed32 extend_repeated_sfixed32 = 39;
+ repeated sfixed64 extend_repeated_sfixed64 = 40;
+ repeated float extend_repeated_float = 41;
+ repeated double extend_repeated_double = 42;
+ repeated bool extend_repeated_bool = 43;
+ repeated string extend_repeated_string = 44;
+ repeated bytes extend_repeated_bytes = 45;
+ repeated ForeignEnum extend_repeated_foreign_enum = 52;
+
+ repeated int32 extend_packed_repeated_int32 = 61 [packed=true];
+ repeated int64 extend_packed_repeated_int64 = 62 [packed=true];
+ repeated uint32 extend_packed_repeated_uint32 = 63 [packed=true];
+ repeated uint64 extend_packed_repeated_uint64 = 64 [packed=true];
+ repeated sint32 extend_packed_repeated_sint32 = 65 [packed=true];
+ repeated sint64 extend_packed_repeated_sint64 = 66 [packed=true];
+ repeated fixed32 extend_packed_repeated_fixed32 = 67 [packed=true];
+ repeated fixed64 extend_packed_repeated_fixed64 = 68 [packed=true];
+ repeated sfixed32 extend_packed_repeated_sfixed32 = 69 [packed=true];
+ repeated sfixed64 extend_packed_repeated_sfixed64 = 70 [packed=true];
+ repeated float extend_packed_repeated_float = 71 [packed=true];
+ repeated double extend_packed_repeated_double = 72 [packed=true];
+ repeated bool extend_packed_repeated_bool = 73 [packed=true];
+ repeated ForeignEnum extend_packed_repeated_foreign_enum = 82
+ [packed=true];
+
+}
+
+message TestMapFields {
+ map<string, string> map_string_string = 1;
+ map<string, int32> map_string_int32 = 2;
+ map<string, int64> map_string_int64 = 3;
+ map<string, bool> map_string_bool = 4;
+ map<string, double> map_string_double = 5;
+ map<string, MapValueEnum> map_string_enum = 6;
+ map<string, MapValueMessage> map_string_msg = 7;
+
+ map<int32, string> map_int32_string = 8;
+ map<int64, string> map_int64_string = 9;
+ map<bool, string> map_bool_string = 10;
+
+ optional TestMapFields test_map_fields = 11;
+ map<string, TestMapFields> map_string_testmapfields = 12;
+}
+
+enum MapValueEnum {
+ MAP_VALUE_FOO = 0;
+ MAP_VALUE_BAR = 1;
+ MAP_VALUE_BAZ = 2;
+}
+
+message MapValueMessage {
+ optional int32 foo = 1;
+}
diff --git a/js/compatibility_tests/v3.1.0/testempty.proto b/js/compatibility_tests/v3.1.0/testempty.proto
new file mode 100644
index 00000000..960bce4e
--- /dev/null
+++ b/js/compatibility_tests/v3.1.0/testempty.proto
@@ -0,0 +1,34 @@
+// 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.
+
+syntax = "proto2";
+
+package javatests.com.google.apps.jspb;
+
diff --git a/js/gulpfile.js b/js/gulpfile.js
index 5f1b1d93..fc9559f9 100644
--- a/js/gulpfile.js
+++ b/js/gulpfile.js
@@ -23,8 +23,44 @@ var wellKnownTypes = [
'../src/google/protobuf/wrappers.proto',
];
-gulp.task('genproto_closure', function (cb) {
- exec(protoc + ' --js_out=library=testproto_libs,binary:. -I ../src -I . *.proto && ' + protoc + ' --js_out=one_output_file_per_input_file,binary:. -I ../src -I . ' + wellKnownTypes.join(' '),
+var group1Protos = [
+ 'data.proto',
+ 'test3.proto',
+ 'test5.proto',
+ 'commonjs/test6/test6.proto',
+ 'test8.proto',
+ 'testbinary.proto',
+ 'testempty.proto',
+ 'test.proto',
+];
+
+var group2Protos = [
+ 'proto3_test.proto',
+ 'test2.proto',
+ 'test4.proto',
+ 'commonjs/test7/test7.proto',
+];
+
+gulp.task('genproto_well_known_types_closure', function (cb) {
+ exec(protoc + ' --js_out=one_output_file_per_input_file,binary:. -I ../src -I . ' + wellKnownTypes.join(' '),
+ function (err, stdout, stderr) {
+ console.log(stdout);
+ console.log(stderr);
+ cb(err);
+ });
+});
+
+gulp.task('genproto_group1_closure', function (cb) {
+ exec(protoc + ' --js_out=library=testproto_libs1,binary:. -I ../src -I . ' + group1Protos.join(' '),
+ function (err, stdout, stderr) {
+ console.log(stdout);
+ console.log(stderr);
+ cb(err);
+ });
+});
+
+gulp.task('genproto_group2_closure', function (cb) {
+ exec(protoc + ' --js_out=library=testproto_libs2,binary:. -I ../src -I . -I commonjs ' + group2Protos.join(' '),
function (err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
@@ -32,8 +68,26 @@ gulp.task('genproto_closure', function (cb) {
});
});
-gulp.task('genproto_commonjs', function (cb) {
- exec('mkdir -p commonjs_out && ' + protoc + ' --js_out=import_style=commonjs,binary:commonjs_out -I ../src -I commonjs -I . *.proto commonjs/test*/*.proto ' + wellKnownTypes.join(' '),
+gulp.task('genproto_well_known_types_commonjs', function (cb) {
+ exec('mkdir -p commonjs_out && ' + protoc + ' --js_out=import_style=commonjs,binary:commonjs_out -I ../src ' + wellKnownTypes.join(' '),
+ function (err, stdout, stderr) {
+ console.log(stdout);
+ console.log(stderr);
+ cb(err);
+ });
+});
+
+gulp.task('genproto_group1_commonjs', function (cb) {
+ exec('mkdir -p commonjs_out && ' + protoc + ' --js_out=import_style=commonjs,binary:commonjs_out -I ../src -I commonjs -I . ' + group1Protos.join(' '),
+ function (err, stdout, stderr) {
+ console.log(stdout);
+ console.log(stderr);
+ cb(err);
+ });
+});
+
+gulp.task('genproto_group2_commonjs', function (cb) {
+ exec('mkdir -p commonjs_out && ' + protoc + ' --js_out=import_style=commonjs,binary:commonjs_out -I ../src -I commonjs -I . ' + group2Protos.join(' '),
function (err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
@@ -59,10 +113,21 @@ gulp.task('genproto_wellknowntypes', function (cb) {
});
});
+function getClosureBuilderCommand(exportsFile, outputFile) {
+ return './node_modules/google-closure-library/closure/bin/build/closurebuilder.py ' +
+ '--root node_modules ' +
+ '-o compiled ' +
+ '--compiler_jar node_modules/google-closure-compiler/compiler.jar ' +
+ '-i ' + exportsFile + ' ' +
+ 'map.js message.js binary/arith.js binary/constants.js binary/decoder.js ' +
+ 'binary/encoder.js binary/reader.js binary/utils.js binary/writer.js ' +
+ exportsFile + ' > ' + outputFile;
+}
+
gulp.task('dist', ['genproto_wellknowntypes'], function (cb) {
// TODO(haberman): minify this more aggressively.
// Will require proper externs/exports.
- exec('./node_modules/google-closure-library/closure/bin/calcdeps.py -i message.js -i binary/reader.js -i binary/writer.js -i commonjs/export.js -p . -p node_modules/google-closure-library/closure -o compiled --compiler_jar node_modules/google-closure-compiler/compiler.jar > google-protobuf.js',
+ exec(getClosureBuilderCommand('commonjs/export.js', 'google-protobuf.js'),
function (err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
@@ -71,7 +136,10 @@ gulp.task('dist', ['genproto_wellknowntypes'], function (cb) {
});
gulp.task('commonjs_asserts', function (cb) {
- exec('mkdir -p commonjs_out/test_node_modules && ./node_modules/google-closure-library/closure/bin/calcdeps.py -i commonjs/export_asserts.js -p . -p node_modules/google-closure-library/closure -o compiled --compiler_jar node_modules/google-closure-compiler/compiler.jar > commonjs_out/test_node_modules/closure_asserts_commonjs.js',
+ exec('mkdir -p commonjs_out/test_node_modules && ' +
+ getClosureBuilderCommand(
+ 'commonjs/export_asserts.js',
+ 'commonjs_out/test_node_modules/closure_asserts_commonjs.js'),
function (err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
@@ -80,7 +148,10 @@ gulp.task('commonjs_asserts', function (cb) {
});
gulp.task('commonjs_testdeps', function (cb) {
- exec('mkdir -p commonjs_out/test_node_modules && ./node_modules/google-closure-library/closure/bin/calcdeps.py -i commonjs/export_testdeps.js -p . -p node_modules/google-closure-library/closure -o compiled --compiler_jar node_modules/google-closure-compiler/compiler.jar > commonjs_out/test_node_modules/testdeps_commonjs.js',
+ exec('mkdir -p commonjs_out/test_node_modules && ' +
+ getClosureBuilderCommand(
+ 'commonjs/export_testdeps.js',
+ 'commonjs_out/test_node_modules/testdeps_commonjs.js'),
function (err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
@@ -88,7 +159,7 @@ gulp.task('commonjs_testdeps', function (cb) {
});
});
-gulp.task('make_commonjs_out', ['dist', 'genproto_commonjs', 'genproto_commonjs_wellknowntypes', 'commonjs_asserts', 'commonjs_testdeps'], function (cb) {
+gulp.task('make_commonjs_out', ['dist', 'genproto_well_known_types_commonjs', 'genproto_group1_commonjs', 'genproto_group2_commonjs', 'genproto_commonjs_wellknowntypes', 'commonjs_asserts', 'commonjs_testdeps'], function (cb) {
// TODO(haberman): minify this more aggressively.
// Will require proper externs/exports.
var cmd = "mkdir -p commonjs_out/binary && mkdir -p commonjs_out/test_node_modules && ";
@@ -111,8 +182,8 @@ gulp.task('make_commonjs_out', ['dist', 'genproto_commonjs', 'genproto_commonjs_
});
});
-gulp.task('deps', ['genproto_closure'], function (cb) {
- exec('./node_modules/google-closure-library/closure/bin/build/depswriter.py *.js binary/*.js > deps.js',
+gulp.task('deps', ['genproto_well_known_types_closure', 'genproto_group1_closure', 'genproto_group2_closure'], function (cb) {
+ exec('./node_modules/google-closure-library/closure/bin/build/depswriter.py binary/arith.js binary/constants.js binary/decoder.js binary/encoder.js binary/reader.js binary/utils.js binary/writer.js debug.js map.js message.js node_loader.js test_bootstrap.js > deps.js',
function (err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
@@ -120,7 +191,7 @@ gulp.task('deps', ['genproto_closure'], function (cb) {
});
});
-gulp.task('test_closure', ['genproto_closure', 'deps'], function (cb) {
+gulp.task('test_closure', ['genproto_well_known_types_closure', 'genproto_group1_closure', 'genproto_group2_closure', 'deps'], function (cb) {
exec('JASMINE_CONFIG_PATH=jasmine.json ./node_modules/.bin/jasmine',
function (err, stdout, stderr) {
console.log(stdout);
diff --git a/js/jasmine.json b/js/jasmine.json
index 093f1579..aeea72f8 100644
--- a/js/jasmine.json
+++ b/js/jasmine.json
@@ -10,6 +10,8 @@
"deps.js",
"google/protobuf/any.js",
"google/protobuf/struct.js",
- "google/protobuf/timestamp.js"
+ "google/protobuf/timestamp.js",
+ "testproto_libs1.js",
+ "testproto_libs2.js"
]
}
diff --git a/js/map.js b/js/map.js
index 93f08e03..d423499f 100644
--- a/js/map.js
+++ b/js/map.js
@@ -136,7 +136,7 @@ jspb.Map.prototype.toArray = function() {
*
* @param {boolean=} includeInstance Whether to include the JSPB instance for
* transitional soy proto support: http://goto/soy-param-migration
- * @param {!function((boolean|undefined),!V):!Object=} valueToObject
+ * @param {!function((boolean|undefined),V):!Object=} valueToObject
* The static toObject() method, if V is a message type.
* @return {!Array<!Array<!Object>>}
*/
@@ -146,7 +146,7 @@ jspb.Map.prototype.toObject = function(includeInstance, valueToObject) {
for (var i = 0; i < rawArray.length; i++) {
var entry = this.map_[rawArray[i][0].toString()];
this.wrapEntry_(entry);
- var valueWrapper = /** @type {!V|undefined} */ (entry.valueWrapper);
+ var valueWrapper = /** @type {V|undefined} */ (entry.valueWrapper);
if (valueWrapper) {
goog.asserts.assert(valueToObject);
entries.push([entry.key, valueToObject(includeInstance, valueWrapper)]);
@@ -183,26 +183,39 @@ jspb.Map.fromObject = function(entries, valueCtor, valueFromObject) {
/**
- * Helper: return an iterator over an array.
+ * Helper: an IteratorIterable over an array.
* @template T
* @param {!Array<T>} arr the array
- * @return {!Iterator<T>} an iterator
+ * @implements {IteratorIterable<T>}
+ * @constructor @struct
* @private
*/
-jspb.Map.arrayIterator_ = function(arr) {
- var idx = 0;
- return /** @type {!Iterator} */ ({
- next: function() {
- if (idx < arr.length) {
- return { done: false, value: arr[idx++] };
- } else {
- return { done: true };
- }
- }
- });
+jspb.Map.ArrayIteratorIterable_ = function(arr) {
+ /** @type {number} @private */
+ this.idx_ = 0;
+
+ /** @const @private */
+ this.arr_ = arr;
};
+/** @override @final */
+jspb.Map.ArrayIteratorIterable_.prototype.next = function() {
+ if (this.idx_ < this.arr_.length) {
+ return {done: false, value: this.arr_[this.idx_++]};
+ } else {
+ return {done: true, value: undefined};
+ }
+};
+
+if (typeof(Symbol) != 'undefined') {
+ /** @override */
+ jspb.Map.ArrayIteratorIterable_.prototype[Symbol.iterator] = function() {
+ return this;
+ };
+}
+
+
/**
* Returns the map's length (number of key/value pairs).
* @return {number}
@@ -260,10 +273,9 @@ jspb.Map.prototype.getEntryList = function() {
/**
- * Returns an iterator over [key, value] pairs in the map.
+ * Returns an iterator-iterable over [key, value] pairs in the map.
* Closure compiler sadly doesn't support tuples, ie. Iterator<[K,V]>.
- * @return {!Iterator<!Array<K|V>>}
- * The iterator
+ * @return {!IteratorIterable<!Array<K|V>>} The iterator-iterable.
*/
jspb.Map.prototype.entries = function() {
var entries = [];
@@ -273,13 +285,13 @@ jspb.Map.prototype.entries = function() {
var entry = this.map_[strKeys[i]];
entries.push([entry.key, this.wrapEntry_(entry)]);
}
- return jspb.Map.arrayIterator_(entries);
+ return new jspb.Map.ArrayIteratorIterable_(entries);
};
/**
- * Returns an iterator over keys in the map.
- * @return {!Iterator<K>} The iterator
+ * Returns an iterator-iterable over keys in the map.
+ * @return {!IteratorIterable<K>} The iterator-iterable.
*/
jspb.Map.prototype.keys = function() {
var keys = [];
@@ -289,13 +301,13 @@ jspb.Map.prototype.keys = function() {
var entry = this.map_[strKeys[i]];
keys.push(entry.key);
}
- return jspb.Map.arrayIterator_(keys);
+ return new jspb.Map.ArrayIteratorIterable_(keys);
};
/**
- * Returns an iterator over values in the map.
- * @return {!Iterator<V>} The iterator
+ * Returns an iterator-iterable over values in the map.
+ * @return {!IteratorIterable<V>} The iterator-iterable.
*/
jspb.Map.prototype.values = function() {
var values = [];
@@ -305,7 +317,7 @@ jspb.Map.prototype.values = function() {
var entry = this.map_[strKeys[i]];
values.push(this.wrapEntry_(entry));
}
- return jspb.Map.arrayIterator_(values);
+ return new jspb.Map.ArrayIteratorIterable_(values);
};
@@ -400,8 +412,8 @@ jspb.Map.prototype.has = function(key) {
* @param {!jspb.BinaryWriter} writer
* @param {!function(this:jspb.BinaryWriter,number,K)} keyWriterFn
* The method on BinaryWriter that writes type K to the stream.
- * @param {!function(this:jspb.BinaryWriter,number,V)|
- * function(this:jspb.BinaryReader,V,?)} valueWriterFn
+ * @param {!function(this:jspb.BinaryWriter,number,V,?=)|
+ * function(this:jspb.BinaryWriter,number,V,?)} valueWriterFn
* The method on BinaryWriter that writes type V to the stream. May be
* writeMessage, in which case the second callback arg form is used.
* @param {function(V,!jspb.BinaryWriter)=} opt_valueWriterCallback
@@ -497,7 +509,7 @@ jspb.Map.prototype.stringKeys_ = function() {
/**
- * @param {!K} key The entry's key.
+ * @param {K} key The entry's key.
* @param {V=} opt_value The entry's value wrapper.
* @constructor
* @struct
diff --git a/js/maps_test.js b/js/maps_test.js
index 6e6ddc29..e8dd2f21 100755
--- a/js/maps_test.js
+++ b/js/maps_test.js
@@ -288,6 +288,50 @@ function makeTests(msgInfo, submessageCtor, suffix) {
var a = msg.toArray();
assertEquals(a[0], entries); // retains original reference
});
+
+ /**
+ * Returns IteratorIterables for entries(), keys() and values().
+ */
+ it('testIteratorIterables' + suffix, function() {
+ var msg = new msgInfo.constructor();
+ var m = msg.getMapStringStringMap();
+ m.set('key1', 'value1');
+ m.set('key2', 'value2');
+ var entryIterator = m.entries();
+ assertElementsEquals(entryIterator.next().value, ['key1', 'value1']);
+ assertElementsEquals(entryIterator.next().value, ['key2', 'value2']);
+ assertEquals(entryIterator.next().done, true);
+
+ if (typeof(Symbol) != 'undefined') {
+ var entryIterable = m.entries()[Symbol.iterator]();
+ assertElementsEquals(entryIterable.next().value, ['key1', 'value1']);
+ assertElementsEquals(entryIterable.next().value, ['key2', 'value2']);
+ assertEquals(entryIterable.next().done, true);
+ }
+
+ var keyIterator = m.keys();
+ assertEquals(keyIterator.next().value, 'key1');
+ assertEquals(keyIterator.next().value, 'key2');
+ assertEquals(keyIterator.next().done, true);
+
+ if (typeof(Symbol) != 'undefined') {
+ var keyIterable = m.keys()[Symbol.iterator]();
+ assertEquals(keyIterable.next().value, 'key1');
+ assertEquals(keyIterable.next().value, 'key2');
+ assertEquals(keyIterable.next().done, true);
+ }
+ var valueIterator = m.values();
+ assertEquals(valueIterator.next().value, 'value1');
+ assertEquals(valueIterator.next().value, 'value2');
+ assertEquals(valueIterator.next().done, true);
+
+ if (typeof(Symbol) != 'undefined') {
+ var valueIterable = m.values()[Symbol.iterator]();
+ assertEquals(valueIterable.next().value, 'value1');
+ assertEquals(valueIterable.next().value, 'value2');
+ assertEquals(valueIterable.next().done, true);
+ }
+ });
}
describe('mapsTest', function() {
diff --git a/js/message.js b/js/message.js
index 1eb88aef..1484229d 100644
--- a/js/message.js
+++ b/js/message.js
@@ -41,7 +41,6 @@ goog.provide('jspb.Message');
goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.crypt.base64');
-goog.require('goog.json');
goog.require('jspb.Map');
// Not needed in compilation units that have no protos with xids.
@@ -106,8 +105,9 @@ jspb.ExtensionFieldInfo = function(fieldNumber, fieldName, ctor, toObjectFn,
/**
* Stores binary-related information for a single extension field.
* @param {!jspb.ExtensionFieldInfo<T>} fieldInfo
- * @param {!function(number,?)} binaryReaderFn
- * @param {!function(number,?)|function(number,?,?,?,?,?)} binaryWriterFn
+ * @param {function(this:jspb.BinaryReader,number,?)} binaryReaderFn
+ * @param {function(this:jspb.BinaryWriter,number,?)
+ * |function(this:jspb.BinaryWriter,number,?,?,?,?,?)} binaryWriterFn
* @param {function(?,?)=} opt_binaryMessageSerializeFn
* @param {function(?,?)=} opt_binaryMessageDeserializeFn
* @param {boolean=} opt_isPacked
@@ -141,6 +141,21 @@ jspb.ExtensionFieldInfo.prototype.isMessageType = function() {
/**
* Base class for all JsPb messages.
+ *
+ * Several common methods (toObject, serializeBinary, in particular) are not
+ * defined on the prototype to encourage code patterns that minimize code bloat
+ * due to otherwise unused code on all protos contained in the project.
+ *
+ * If you want to call these methods on a generic message, either
+ * pass in your instance of method as a parameter:
+ * someFunction(instanceOfKnownProto,
+ * KnownProtoClass.prototype.serializeBinary);
+ * or use a lambda that knows the type:
+ * someFunction(()=>instanceOfKnownProto.serializeBinary());
+ * or, if you don't care about code size, just suppress the
+ * WARNING - Property serializeBinary never defined on jspb.Message
+ * and call it the intuitive way.
+ *
* @constructor
* @struct
*/
@@ -175,6 +190,22 @@ goog.define('jspb.Message.GENERATE_FROM_OBJECT', !goog.DISALLOW_TEST_ONLY_CODE);
/**
+ * @define {boolean} Whether to generate toString methods for objects. Turn
+ * this off if you do not use toString in your project and want to trim it
+ * from the compiled JS.
+ */
+goog.define('jspb.Message.GENERATE_TO_STRING', true);
+
+
+/**
+ * @define {boolean} Whether arrays passed to initialize() can be assumed to be
+ * local (e.g. not from another iframe) and thus safely classified with
+ * instanceof Array.
+ */
+goog.define('jspb.Message.ASSUME_LOCAL_ARRAYS', false);
+
+
+/**
* @define {boolean} Turning on this flag does NOT change the behavior of JSPB
* and only affects private internal state. It may, however, break some
* tests that use naive deeply-equals algorithms, because using a proto
@@ -186,7 +217,7 @@ goog.define('jspb.Message.MINIMIZE_MEMORY_ALLOCATIONS', COMPILED);
/**
- * Does this browser support Uint8Aray typed arrays?
+ * Does this JavaScript environment support Uint8Aray typed arrays?
* @type {boolean}
* @private
*/
@@ -319,7 +350,7 @@ jspb.Message.initialize = function(
// which would otherwise go unused.
msg.arrayIndexOffset_ = messageId === 0 ? -1 : 0;
msg.array = data;
- jspb.Message.materializeExtensionObject_(msg, suggestedPivot);
+ jspb.Message.initPivotAndExtensionObject_(msg, suggestedPivot);
msg.convertedFloatingPointFields_ = {};
if (repeatedFields) {
@@ -332,6 +363,7 @@ jspb.Message.initialize = function(
jspb.Message.EMPTY_LIST_SENTINEL_ :
[]);
} else {
+ jspb.Message.maybeInitEmptyExtensionObject_(msg);
msg.extensionObject_[fieldNumber] =
msg.extensionObject_[fieldNumber] ||
(jspb.Message.MINIMIZE_MEMORY_ALLOCATIONS ?
@@ -364,17 +396,28 @@ jspb.Message.EMPTY_LIST_SENTINEL_ = goog.DEBUG && Object.freeze ?
/**
- * Ensures that the array contains an extension object if necessary.
+ * Returns true if the provided argument is an array.
+ * @param {*} o The object to classify as array or not.
+ * @return {boolean} True if the provided object is an array.
+ * @private
+ */
+jspb.Message.isArray_ = function(o) {
+ return jspb.Message.ASSUME_LOCAL_ARRAYS ? o instanceof Array :
+ goog.isArray(o);
+};
+
+
+/**
* If the array contains an extension object in its last position, then the
- * object is kept in place and its position is used as the pivot. If not, then
- * create an extension object using suggestedPivot. If suggestedPivot is -1,
- * we don't have an extension object at all, in which case all fields are stored
- * in the array.
+ * object is kept in place and its position is used as the pivot. If not,
+ * decides the pivot of the message based on suggestedPivot without
+ * materializing the extension object.
+ *
* @param {!jspb.Message} msg The JsPb proto to modify.
* @param {number} suggestedPivot See description for initialize().
* @private
*/
-jspb.Message.materializeExtensionObject_ = function(msg, suggestedPivot) {
+jspb.Message.initPivotAndExtensionObject_ = function(msg, suggestedPivot) {
if (msg.array.length) {
var foundIndex = msg.array.length - 1;
var obj = msg.array[foundIndex];
@@ -383,33 +426,24 @@ jspb.Message.materializeExtensionObject_ = function(msg, suggestedPivot) {
// the object is not an array, since arrays are valid field values.
// NOTE(lukestebbing): We avoid looking at .length to avoid a JIT bug
// in Safari on iOS 8. See the description of CL/86511464 for details.
- if (obj && typeof obj == 'object' && !goog.isArray(obj) &&
- !(jspb.Message.SUPPORTS_UINT8ARRAY_ && obj instanceof Uint8Array)) {
+ if (obj && typeof obj == 'object' && !jspb.Message.isArray_(obj) &&
+ !(jspb.Message.SUPPORTS_UINT8ARRAY_ && obj instanceof Uint8Array)) {
msg.pivot_ = foundIndex - msg.arrayIndexOffset_;
msg.extensionObject_ = obj;
return;
}
}
- // This complexity exists because we keep all extension fields in the
- // extensionObject_ regardless of proto field number. Changing this would
- // simplify the code here, but it would require changing the serialization
- // format from the server, which is not backwards compatible.
- // TODO(jshneier): Should we just treat extension fields the same as
- // non-extension fields, and select whether they appear in the object or in
- // the array purely based on tag number? This would allow simplifying all the
- // get/setExtension logic, but it would require the breaking change described
- // above.
+
if (suggestedPivot > -1) {
msg.pivot_ = suggestedPivot;
- var pivotIndex = jspb.Message.getIndex_(msg, suggestedPivot);
- if (!jspb.Message.MINIMIZE_MEMORY_ALLOCATIONS) {
- msg.extensionObject_ = msg.array[pivotIndex] = {};
- } else {
- // Initialize to null to avoid changing the shape of the proto when it
- // gets eventually set.
- msg.extensionObject_ = null;
- }
+ // Avoid changing the shape of the proto with an empty extension object by
+ // deferring the materialization of the extension object until the first
+ // time a field set into it (may be due to getting a repeated proto field
+ // from it, in which case a new empty array is set into it at first).
+ msg.extensionObject_ = null;
} else {
+ // suggestedPivot is -1, which means that we don't have an extension object
+ // at all, in which case all fields are stored in the array.
msg.pivot_ = Number.MAX_VALUE;
}
};
@@ -469,7 +503,7 @@ jspb.Message.toObjectExtension = function(proto, obj, extensions,
for (var fieldNumber in extensions) {
var fieldInfo = extensions[fieldNumber];
var value = getExtensionFn.call(proto, fieldInfo);
- if (value) {
+ if (value != null) {
for (var name in fieldInfo.fieldName) {
if (fieldInfo.fieldName.hasOwnProperty(name)) {
break; // the compiled field name
@@ -496,7 +530,7 @@ jspb.Message.toObjectExtension = function(proto, obj, extensions,
* @param {!jspb.Message} proto The proto whose extensions to convert.
* @param {*} writer The binary-format writer to write to.
* @param {!Object} extensions The proto class' registered extensions.
- * @param {function(jspb.ExtensionFieldInfo) : *} getExtensionFn The proto
+ * @param {function(this:jspb.Message,!jspb.ExtensionFieldInfo) : *} getExtensionFn The proto
* class' getExtension function. Passed for effective dead code removal.
*/
jspb.Message.serializeBinaryExtensions = function(proto, writer, extensions,
@@ -513,7 +547,7 @@ jspb.Message.serializeBinaryExtensions = function(proto, writer, extensions,
'without binary serialization support');
}
var value = getExtensionFn.call(proto, fieldInfo);
- if (value) {
+ if (value != null) {
if (fieldInfo.isMessageType()) {
// If the message type of the extension was generated without binary
// support, there may not be a binary message serializer function, and
@@ -542,10 +576,13 @@ jspb.Message.serializeBinaryExtensions = function(proto, writer, extensions,
* Reads an extension field from the given reader and, if a valid extension,
* sets the extension value.
* @param {!jspb.Message} msg A jspb proto.
- * @param {{skipField:function(),getFieldNumber:function():number}} reader
+ * @param {{
+ * skipField:function(this:jspb.BinaryReader),
+ * getFieldNumber:function(this:jspb.BinaryReader):number
+ * }} reader
* @param {!Object} extensions The extensions object.
- * @param {function(jspb.ExtensionFieldInfo)} getExtensionFn
- * @param {function(jspb.ExtensionFieldInfo, ?)} setExtensionFn
+ * @param {function(this:jspb.Message,!jspb.ExtensionFieldInfo)} getExtensionFn
+ * @param {function(this:jspb.Message,!jspb.ExtensionFieldInfo, ?)} setExtensionFn
*/
jspb.Message.readBinaryExtension = function(msg, reader, extensions,
getExtensionFn, setExtensionFn) {
@@ -600,6 +637,9 @@ jspb.Message.getField = function(msg, fieldNumber) {
}
return val;
} else {
+ if (!msg.extensionObject_) {
+ return undefined;
+ }
var val = msg.extensionObject_[fieldNumber];
if (val === jspb.Message.EMPTY_LIST_SENTINEL_) {
return msg.extensionObject_[fieldNumber] = [];
@@ -610,6 +650,32 @@ jspb.Message.getField = function(msg, fieldNumber) {
/**
+ * Gets the value of a non-extension repeated field.
+ * @param {!jspb.Message} msg A jspb proto.
+ * @param {number} fieldNumber The field number.
+ * @return {!Array}
+ * The field's value.
+ * @protected
+ */
+jspb.Message.getRepeatedField = function(msg, fieldNumber) {
+ if (fieldNumber < msg.pivot_) {
+ var index = jspb.Message.getIndex_(msg, fieldNumber);
+ var val = msg.array[index];
+ if (val === jspb.Message.EMPTY_LIST_SENTINEL_) {
+ return msg.array[index] = [];
+ }
+ return val;
+ }
+
+ var val = msg.extensionObject_[fieldNumber];
+ if (val === jspb.Message.EMPTY_LIST_SENTINEL_) {
+ return msg.extensionObject_[fieldNumber] = [];
+ }
+ return val;
+};
+
+
+/**
* Gets the value of an optional float or double field.
* @param {!jspb.Message} msg A jspb proto.
* @param {number} fieldNumber The field number.
@@ -631,7 +697,7 @@ jspb.Message.getOptionalFloatingPointField = function(msg, fieldNumber) {
* @protected
*/
jspb.Message.getRepeatedFloatingPointField = function(msg, fieldNumber) {
- var values = jspb.Message.getField(msg, fieldNumber);
+ var values = jspb.Message.getRepeatedField(msg, fieldNumber);
if (!msg.convertedFloatingPointFields_) {
msg.convertedFloatingPointFields_ = {};
}
@@ -817,12 +883,107 @@ jspb.Message.setField = function(msg, fieldNumber, value) {
if (fieldNumber < msg.pivot_) {
msg.array[jspb.Message.getIndex_(msg, fieldNumber)] = value;
} else {
+ jspb.Message.maybeInitEmptyExtensionObject_(msg);
msg.extensionObject_[fieldNumber] = value;
}
};
/**
+ * Sets the value of a non-extension integer field of a proto3
+ * @param {!jspb.Message} msg A jspb proto.
+ * @param {number} fieldNumber The field number.
+ * @param {number} value New value
+ * @protected
+ */
+jspb.Message.setProto3IntField = function(msg, fieldNumber, value) {
+ jspb.Message.setFieldIgnoringDefault_(msg, fieldNumber, value, 0);
+};
+
+
+/**
+ * Sets the value of a non-extension floating point field of a proto3
+ * @param {!jspb.Message} msg A jspb proto.
+ * @param {number} fieldNumber The field number.
+ * @param {number} value New value
+ * @protected
+ */
+jspb.Message.setProto3FloatField = function(msg, fieldNumber, value) {
+ jspb.Message.setFieldIgnoringDefault_(msg, fieldNumber, value, 0.0);
+};
+
+
+/**
+ * Sets the value of a non-extension boolean field of a proto3
+ * @param {!jspb.Message} msg A jspb proto.
+ * @param {number} fieldNumber The field number.
+ * @param {boolean} value New value
+ * @protected
+ */
+jspb.Message.setProto3BooleanField = function(msg, fieldNumber, value) {
+ jspb.Message.setFieldIgnoringDefault_(msg, fieldNumber, value, false);
+};
+
+
+/**
+ * Sets the value of a non-extension String field of a proto3
+ * @param {!jspb.Message} msg A jspb proto.
+ * @param {number} fieldNumber The field number.
+ * @param {string} value New value
+ * @protected
+ */
+jspb.Message.setProto3StringField = function(msg, fieldNumber, value) {
+ jspb.Message.setFieldIgnoringDefault_(msg, fieldNumber, value, "");
+};
+
+
+/**
+ * Sets the value of a non-extension Bytes field of a proto3
+ * @param {!jspb.Message} msg A jspb proto.
+ * @param {number} fieldNumber The field number.
+ * @param {!Uint8Array|string} value New value
+ * @protected
+ */
+jspb.Message.setProto3BytesField = function(msg, fieldNumber, value) {
+ jspb.Message.setFieldIgnoringDefault_(msg, fieldNumber, value, "");
+};
+
+
+/**
+ * Sets the value of a non-extension enum field of a proto3
+ * @param {!jspb.Message} msg A jspb proto.
+ * @param {number} fieldNumber The field number.
+ * @param {number} value New value
+ * @protected
+ */
+jspb.Message.setProto3EnumField = function(msg, fieldNumber, value) {
+ jspb.Message.setFieldIgnoringDefault_(msg, fieldNumber, value, 0);
+};
+
+
+
+/**
+ * Sets the value of a non-extension primitive field, with proto3 (non-nullable
+ * primitives) semantics of ignoring values that are equal to the type's
+ * default.
+ * @template T
+ * @param {!jspb.Message} msg A jspb proto.
+ * @param {number} fieldNumber The field number.
+ * @param {!Uint8Array|string|number|boolean|undefined} value New value
+ * @param {!Uint8Array|string|number|boolean} defaultValue The default value.
+ * @private
+ */
+jspb.Message.setFieldIgnoringDefault_ = function(
+ msg, fieldNumber, value, defaultValue) {
+ if (value != defaultValue) {
+ jspb.Message.setField(msg, fieldNumber, value);
+ } else {
+ msg.array[jspb.Message.getIndex_(msg, fieldNumber)] = null;
+ }
+};
+
+
+/**
* Adds a value to a repeated, primitive field.
* @param {!jspb.Message} msg A jspb proto.
* @param {number} fieldNumber The field number.
@@ -831,7 +992,7 @@ jspb.Message.setField = function(msg, fieldNumber, value) {
* @protected
*/
jspb.Message.addToRepeatedField = function(msg, fieldNumber, value, opt_index) {
- var arr = jspb.Message.getField(msg, fieldNumber);
+ var arr = jspb.Message.getRepeatedField(msg, fieldNumber);
if (opt_index != undefined) {
arr.splice(opt_index, 0, value);
} else {
@@ -959,7 +1120,7 @@ jspb.Message.wrapRepeatedField_ = function(msg, ctor, fieldNumber) {
msg.wrappers_ = {};
}
if (!msg.wrappers_[fieldNumber]) {
- var data = jspb.Message.getField(msg, fieldNumber);
+ var data = jspb.Message.getRepeatedField(msg, fieldNumber);
for (var wrappers = [], i = 0; i < data.length; i++) {
wrappers[i] = new ctor(data[i]);
}
@@ -1054,7 +1215,7 @@ jspb.Message.addToRepeatedWrapperField = function(
wrapperArray = msg.wrappers_[fieldNumber] = [];
}
var insertedValue = value ? value : new ctor();
- var array = jspb.Message.getField(msg, fieldNumber);
+ var array = jspb.Message.getRepeatedField(msg, fieldNumber);
if (index != undefined) {
wrapperArray.splice(index, 0, insertedValue);
array.splice(index, 0, insertedValue.toArray());
@@ -1140,6 +1301,7 @@ jspb.Message.prototype.toArray = function() {
+if (jspb.Message.GENERATE_TO_STRING) {
/**
* Creates a string representation of the internal data array of this proto.
@@ -1152,6 +1314,7 @@ jspb.Message.prototype.toString = function() {
return this.array.toString();
};
+}
/**
* Gets the value of the extension field from the extended object.
diff --git a/js/message_test.js b/js/message_test.js
index 082da944..7d61dacb 100644
--- a/js/message_test.js
+++ b/js/message_test.js
@@ -33,12 +33,17 @@
goog.setTestOnly();
goog.require('goog.json');
+goog.require('goog.string');
goog.require('goog.testing.asserts');
goog.require('goog.userAgent');
// CommonJS-LoadFromFile: google-protobuf jspb
goog.require('jspb.Message');
+// CommonJS-LoadFromFile: test8_pb proto.jspb.exttest.nested
+goog.require('proto.jspb.exttest.nested.TestNestedExtensionsMessage');
+goog.require('proto.jspb.exttest.nested.TestOuterMessage');
+
// CommonJS-LoadFromFile: test5_pb proto.jspb.exttest.beta
goog.require('proto.jspb.exttest.beta.floatingStrField');
@@ -73,14 +78,10 @@ goog.require('proto.jspb.test.TestGroup1');
goog.require('proto.jspb.test.TestMessageWithOneof');
goog.require('proto.jspb.test.TestReservedNames');
goog.require('proto.jspb.test.TestReservedNamesExtension');
-goog.require('proto.jspb.test.Deeply.Nested.Message');
// CommonJS-LoadFromFile: test2_pb proto.jspb.test
goog.require('proto.jspb.test.ExtensionMessage');
goog.require('proto.jspb.test.TestExtensionsMessage');
-goog.require('proto.jspb.test.ForeignNestedFieldMessage');
-
-
describe('Message test suite', function() {
@@ -271,12 +272,6 @@ describe('Message test suite', function() {
assertFalse(response.hasEnumField());
});
- it('testMessageRegistration', /** @suppress {visibility} */ function() {
- // goog.require(SomeResponse) will include its library, which will in
- // turn add SomeResponse to the message registry.
- assertEquals(jspb.Message.registry_['res'], proto.jspb.test.SomeResponse);
- });
-
it('testClearFields', function() {
var data = ['str', true, [11], [[22], [33]], ['s1', 's2']];
var foo = new proto.jspb.test.OptionalFields(data);
@@ -588,6 +583,14 @@ describe('Message test suite', function() {
assertNotUndefined(proto.jspb.exttest.beta.floatingStrField);
});
+ it('testNestedExtensions', function() {
+ var extendable = new proto.jspb.exttest.nested.TestNestedExtensionsMessage();
+ var extension = new proto.jspb.exttest.nested.TestOuterMessage.NestedExtensionMessage(['s1']);
+ extendable.setExtension(proto.jspb.exttest.nested.TestOuterMessage.innerExtension, extension);
+ assertObjectEquals(extension,
+ extendable.getExtension(proto.jspb.exttest.nested.TestOuterMessage.innerExtension));
+ });
+
it('testToObject_extendedObject', function() {
var extension1 = new proto.jspb.test.IsExtension(['ext1field']);
var extension2 = new proto.jspb.test.Simple1(['str', ['s1', 's2'], true]);
@@ -651,12 +654,7 @@ describe('Message test suite', function() {
it('testInitialization_emptyArray', function() {
var msg = new proto.jspb.test.HasExtensions([]);
- if (jspb.Message.MINIMIZE_MEMORY_ALLOCATIONS) {
- assertArrayEquals([], msg.toArray());
- } else {
- // Extension object is created past all regular fields.
- assertArrayEquals([,,, {}], msg.toArray());
- }
+ assertArrayEquals([], msg.toArray());
});
it('testInitialization_justExtensionObject', function() {
@@ -684,10 +682,11 @@ describe('Message test suite', function() {
});
it('testToObject_hasExtensionField', function() {
- var data = new proto.jspb.test.HasExtensions(['str1', {100: ['ext1']}]);
+ var data = new proto.jspb.test.HasExtensions(['str1', {100: ['ext1'], 102: ''}]);
var obj = data.toObject();
assertEquals('str1', obj.str1);
assertEquals('ext1', obj.extField.ext1);
+ assertEquals('', obj.str);
});
it('testGetExtension', function() {
@@ -1042,21 +1041,4 @@ describe('Message test suite', function() {
assertNan(message.getDefaultDoubleField());
});
- // Verify that we can successfully use a field referring to a nested message
- // from a different .proto file.
- it('testForeignNestedMessage', function() {
- var msg = new proto.jspb.test.ForeignNestedFieldMessage();
- var nested = new proto.jspb.test.Deeply.Nested.Message();
- nested.setCount(5);
- msg.setDeeplyNestedMessage(nested);
- assertEquals(5, msg.getDeeplyNestedMessage().getCount());
-
- // After a serialization-deserialization round trip we should get back the
- // same data we started with.
- var serialized = msg.serializeBinary();
- var deserialized =
- proto.jspb.test.ForeignNestedFieldMessage.deserializeBinary(serialized);
- assertEquals(5, deserialized.getDeeplyNestedMessage().getCount());
- });
-
});
diff --git a/js/package.json b/js/package.json
index d3c77eb6..5231c846 100644
--- a/js/package.json
+++ b/js/package.json
@@ -1,6 +1,6 @@
{
"name": "google-protobuf",
- "version": "3.1.0",
+ "version": "3.4.1",
"description": "Protocol Buffers for JavaScript",
"main": "google-protobuf.js",
"files": [
diff --git a/js/proto3_test.js b/js/proto3_test.js
index 81d6de2f..4aed88ba 100644
--- a/js/proto3_test.js
+++ b/js/proto3_test.js
@@ -72,6 +72,37 @@ function bytesCompare(arr, expected) {
describe('proto3Test', function() {
+
+ /**
+ * Test default values don't affect equality test.
+ */
+ it('testEqualsProto3', function() {
+ var msg1 = new proto.jspb.test.TestProto3();
+ var msg2 = new proto.jspb.test.TestProto3();
+ msg2.setOptionalString('');
+
+ assertTrue(jspb.Message.equals(msg1, msg2));
+ });
+
+
+ /**
+ * Test setting when a field has default semantics.
+ */
+ it('testSetProto3ToValueAndBackToDefault', function() {
+ var msg = new proto.jspb.test.TestProto3();
+
+ // Setting should work normally.
+ msg.setOptionalString('optionalString');
+ assertEquals(msg.getOptionalString(), 'optionalString');
+
+ // Clearing should work too ...
+ msg.setOptionalString('');
+ assertEquals(msg.getOptionalString(), '');
+
+ // ... and shouldn't affect the equality with a brand new message.
+ assertTrue(jspb.Message.equals(msg, new proto.jspb.test.TestProto3()));
+ });
+
/**
* Test defaults for proto3 message fields.
*/
@@ -225,52 +256,65 @@ describe('proto3Test', function() {
* Test that oneofs continue to have a notion of field presence.
*/
it('testOneofs', function() {
+ // Default instance.
var msg = new proto.jspb.test.TestProto3();
-
assertEquals(msg.getOneofUint32(), 0);
assertEquals(msg.getOneofForeignMessage(), undefined);
assertEquals(msg.getOneofString(), '');
assertEquals(msg.getOneofBytes(), '');
+
assertFalse(msg.hasOneofUint32());
+ assertFalse(msg.hasOneofForeignMessage());
assertFalse(msg.hasOneofString());
assertFalse(msg.hasOneofBytes());
+ // Integer field.
msg.setOneofUint32(42);
assertEquals(msg.getOneofUint32(), 42);
assertEquals(msg.getOneofForeignMessage(), undefined);
assertEquals(msg.getOneofString(), '');
assertEquals(msg.getOneofBytes(), '');
+
assertTrue(msg.hasOneofUint32());
+ assertFalse(msg.hasOneofForeignMessage());
assertFalse(msg.hasOneofString());
assertFalse(msg.hasOneofBytes());
-
+ // Sub-message field.
var submsg = new proto.jspb.test.ForeignMessage();
msg.setOneofForeignMessage(submsg);
assertEquals(msg.getOneofUint32(), 0);
assertEquals(msg.getOneofForeignMessage(), submsg);
assertEquals(msg.getOneofString(), '');
assertEquals(msg.getOneofBytes(), '');
+
assertFalse(msg.hasOneofUint32());
+ assertTrue(msg.hasOneofForeignMessage());
assertFalse(msg.hasOneofString());
assertFalse(msg.hasOneofBytes());
+ // String field.
msg.setOneofString('hello');
assertEquals(msg.getOneofUint32(), 0);
assertEquals(msg.getOneofForeignMessage(), undefined);
assertEquals(msg.getOneofString(), 'hello');
assertEquals(msg.getOneofBytes(), '');
+
assertFalse(msg.hasOneofUint32());
+ assertFalse(msg.hasOneofForeignMessage());
assertTrue(msg.hasOneofString());
assertFalse(msg.hasOneofBytes());
+ // Bytes field.
msg.setOneofBytes(goog.crypt.base64.encodeString('\u00FF\u00FF'));
assertEquals(msg.getOneofUint32(), 0);
assertEquals(msg.getOneofForeignMessage(), undefined);
assertEquals(msg.getOneofString(), '');
assertEquals(msg.getOneofBytes_asB64(),
goog.crypt.base64.encodeString('\u00FF\u00FF'));
+
assertFalse(msg.hasOneofUint32());
+ assertFalse(msg.hasOneofForeignMessage());
assertFalse(msg.hasOneofString());
assertTrue(msg.hasOneofBytes());
});
diff --git a/js/proto3_test.proto b/js/proto3_test.proto
index acb67164..0d073ea0 100644
--- a/js/proto3_test.proto
+++ b/js/proto3_test.proto
@@ -86,4 +86,5 @@ enum Proto3Enum {
PROTO3_FOO = 0;
PROTO3_BAR = 1;
PROTO3_BAZ = 2;
+ MSG_PROTO3_BAH = 3;
}
diff --git a/js/test.proto b/js/test.proto
index 2be5b8c1..7c881c0d 100644
--- a/js/test.proto
+++ b/js/test.proto
@@ -235,6 +235,13 @@ message TestEndsWithBytes {
}
+message Int64Types {
+ optional int64 int64_normal = 1 [jstype=JS_NORMAL];
+ optional sint64 int64_string = 2 [jstype=JS_STRING];
+ optional uint64 int64_number = 3 [jstype=JS_NUMBER];
+
+}
+
message TestMapFieldsNoBinary {
map<string, string> map_string_string = 1;
@@ -271,3 +278,4 @@ message Deeply {
}
}
}
+
diff --git a/js/test8.proto b/js/test8.proto
new file mode 100644
index 00000000..2ae80dab
--- /dev/null
+++ b/js/test8.proto
@@ -0,0 +1,50 @@
+// 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.
+
+syntax = "proto2";
+
+option java_package = "com.google.apps.jspb.proto";
+option java_multiple_files = true;
+
+package jspb.exttest.nested;
+
+message TestNestedExtensionsMessage {
+ optional int32 intfield = 1;
+ extensions 100 to max;
+}
+
+message TestOuterMessage {
+ message NestedExtensionMessage {
+ optional string ext1 = 1;
+ }
+ extend TestNestedExtensionsMessage {
+ optional NestedExtensionMessage inner_extension = 100;
+ }
+}
diff --git a/kokoro/README.md b/kokoro/README.md
new file mode 100644
index 00000000..0791c925
--- /dev/null
+++ b/kokoro/README.md
@@ -0,0 +1,6 @@
+
+Kokoro Infrastructure
+----------------------
+
+The files in this directory serve as plumbing for running Protobuf
+tests under Kokoro, our internal CI. \ No newline at end of file
diff --git a/kokoro/linux/cpp_distcheck/build.sh b/kokoro/linux/cpp_distcheck/build.sh
new file mode 100755
index 00000000..b8b57e35
--- /dev/null
+++ b/kokoro/linux/cpp_distcheck/build.sh
@@ -0,0 +1,11 @@
+#!/bin/bash
+#
+# Build file to set up and run tests
+
+# Change to repo root
+cd $(dirname $0)/../../..
+
+# Prepare worker environment to run tests
+source kokoro/linux/prepare_build_linux_rc
+
+./tests.sh cpp_distcheck
diff --git a/kokoro/linux/cpp_distcheck/continuous.cfg b/kokoro/linux/cpp_distcheck/continuous.cfg
new file mode 100644
index 00000000..4289f6a7
--- /dev/null
+++ b/kokoro/linux/cpp_distcheck/continuous.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/linux/cpp_distcheck/build.sh"
+timeout_mins: 1440
diff --git a/kokoro/linux/cpp_distcheck/presubmit.cfg b/kokoro/linux/cpp_distcheck/presubmit.cfg
new file mode 100644
index 00000000..4289f6a7
--- /dev/null
+++ b/kokoro/linux/cpp_distcheck/presubmit.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/linux/cpp_distcheck/build.sh"
+timeout_mins: 1440
diff --git a/kokoro/linux/csharp/build.sh b/kokoro/linux/csharp/build.sh
new file mode 100755
index 00000000..de178b84
--- /dev/null
+++ b/kokoro/linux/csharp/build.sh
@@ -0,0 +1,11 @@
+#!/bin/bash
+#
+# Build file to set up and run tests
+
+# Change to repo root
+cd $(dirname $0)/../../..
+
+# Prepare worker environment to run tests
+source kokoro/linux/prepare_build_linux_rc
+
+./tests.sh csharp
diff --git a/kokoro/linux/csharp/continuous.cfg b/kokoro/linux/csharp/continuous.cfg
new file mode 100644
index 00000000..3d177670
--- /dev/null
+++ b/kokoro/linux/csharp/continuous.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/linux/csharp/build.sh"
+timeout_mins: 1440
diff --git a/kokoro/linux/csharp/presubmit.cfg b/kokoro/linux/csharp/presubmit.cfg
new file mode 100644
index 00000000..3d177670
--- /dev/null
+++ b/kokoro/linux/csharp/presubmit.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/linux/csharp/build.sh"
+timeout_mins: 1440
diff --git a/kokoro/linux/java_compatibility/build.sh b/kokoro/linux/java_compatibility/build.sh
new file mode 100755
index 00000000..b1ef2796
--- /dev/null
+++ b/kokoro/linux/java_compatibility/build.sh
@@ -0,0 +1,11 @@
+#!/bin/bash
+#
+# Build file to set up and run tests
+
+# Change to repo root
+cd $(dirname $0)/../../..
+
+# Prepare worker environment to run tests
+source kokoro/linux/prepare_build_linux_rc
+
+./tests.sh java_compatibility
diff --git a/kokoro/linux/java_compatibility/continuous.cfg b/kokoro/linux/java_compatibility/continuous.cfg
new file mode 100644
index 00000000..4897f5c8
--- /dev/null
+++ b/kokoro/linux/java_compatibility/continuous.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/linux/java_compatibility/build.sh"
+timeout_mins: 1440
diff --git a/kokoro/linux/java_compatibility/presubmit.cfg b/kokoro/linux/java_compatibility/presubmit.cfg
new file mode 100644
index 00000000..4897f5c8
--- /dev/null
+++ b/kokoro/linux/java_compatibility/presubmit.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/linux/java_compatibility/build.sh"
+timeout_mins: 1440
diff --git a/kokoro/linux/prepare_build_linux_rc b/kokoro/linux/prepare_build_linux_rc
new file mode 100644
index 00000000..4c3f255d
--- /dev/null
+++ b/kokoro/linux/prepare_build_linux_rc
@@ -0,0 +1,9 @@
+#!/bin/bash
+
+# Source this rc script to prepare the environment for Linux builds
+
+# Set up dotnet
+sudo sh -c 'echo "deb [arch=amd64] https://apt-mo.trafficmanager.net/repos/dotnet-release/ trusty main" > /etc/apt/sources.list.d/dotnetdev.list'
+sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 417A0893
+sudo apt-get update
+sudo apt-get install -y dotnet-dev-1.0.4
diff --git a/kokoro/linux/python_compatibility/build.sh b/kokoro/linux/python_compatibility/build.sh
new file mode 100755
index 00000000..041e65ff
--- /dev/null
+++ b/kokoro/linux/python_compatibility/build.sh
@@ -0,0 +1,11 @@
+#!/bin/bash
+#
+# Build file to set up and run tests
+
+# Change to repo root
+cd $(dirname $0)/../../..
+
+# Prepare worker environment to run tests
+source kokoro/linux/prepare_build_linux_rc
+
+./tests.sh python_compatibility
diff --git a/kokoro/linux/python_compatibility/continuous.cfg b/kokoro/linux/python_compatibility/continuous.cfg
new file mode 100644
index 00000000..4cf6bb07
--- /dev/null
+++ b/kokoro/linux/python_compatibility/continuous.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/linux/python_compatibility/build.sh"
+timeout_mins: 1440
diff --git a/kokoro/linux/python_compatibility/presubmit.cfg b/kokoro/linux/python_compatibility/presubmit.cfg
new file mode 100644
index 00000000..4cf6bb07
--- /dev/null
+++ b/kokoro/linux/python_compatibility/presubmit.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/linux/python_compatibility/build.sh"
+timeout_mins: 1440
diff --git a/kokoro/macos/cpp/build.sh b/kokoro/macos/cpp/build.sh
new file mode 100755
index 00000000..bae2ebbc
--- /dev/null
+++ b/kokoro/macos/cpp/build.sh
@@ -0,0 +1,11 @@
+#!/bin/bash
+#
+# Build file to set up and run tests
+
+# Change to repo root
+cd $(dirname $0)/../../..
+
+# Prepare worker environment to run tests
+source kokoro/macos/prepare_build_macos_rc
+
+./tests.sh cpp
diff --git a/kokoro/macos/cpp/continuous.cfg b/kokoro/macos/cpp/continuous.cfg
new file mode 100644
index 00000000..4bea1cbb
--- /dev/null
+++ b/kokoro/macos/cpp/continuous.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/macos/cpp/build.sh"
+timeout_mins: 1440
diff --git a/kokoro/macos/cpp/presubmit.cfg b/kokoro/macos/cpp/presubmit.cfg
new file mode 100644
index 00000000..4bea1cbb
--- /dev/null
+++ b/kokoro/macos/cpp/presubmit.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/macos/cpp/build.sh"
+timeout_mins: 1440
diff --git a/kokoro/macos/cpp_distcheck/build.sh b/kokoro/macos/cpp_distcheck/build.sh
new file mode 100755
index 00000000..d729b63d
--- /dev/null
+++ b/kokoro/macos/cpp_distcheck/build.sh
@@ -0,0 +1,11 @@
+#!/bin/bash
+#
+# Build file to set up and run tests
+
+# Change to repo root
+cd $(dirname $0)/../../..
+
+# Prepare worker environment to run tests
+source kokoro/macos/prepare_build_macos_rc
+
+./tests.sh cpp_distcheck
diff --git a/kokoro/macos/cpp_distcheck/continuous.cfg b/kokoro/macos/cpp_distcheck/continuous.cfg
new file mode 100644
index 00000000..89441bcc
--- /dev/null
+++ b/kokoro/macos/cpp_distcheck/continuous.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/macos/cpp_distcheck/build.sh"
+timeout_mins: 1440
diff --git a/kokoro/macos/cpp_distcheck/presubmit.cfg b/kokoro/macos/cpp_distcheck/presubmit.cfg
new file mode 100644
index 00000000..89441bcc
--- /dev/null
+++ b/kokoro/macos/cpp_distcheck/presubmit.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/macos/cpp_distcheck/build.sh"
+timeout_mins: 1440
diff --git a/kokoro/macos/javascript/build.sh b/kokoro/macos/javascript/build.sh
new file mode 100755
index 00000000..016832a3
--- /dev/null
+++ b/kokoro/macos/javascript/build.sh
@@ -0,0 +1,11 @@
+#!/bin/bash
+#
+# Build file to set up and run tests
+
+# Change to repo root
+cd $(dirname $0)/../../..
+
+# Prepare worker environment to run tests
+source kokoro/macos/prepare_build_macos_rc
+
+./tests.sh javascript
diff --git a/kokoro/macos/javascript/continuous.cfg b/kokoro/macos/javascript/continuous.cfg
new file mode 100644
index 00000000..b478cc19
--- /dev/null
+++ b/kokoro/macos/javascript/continuous.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/macos/javascript/build.sh"
+timeout_mins: 1440
diff --git a/kokoro/macos/javascript/presubmit.cfg b/kokoro/macos/javascript/presubmit.cfg
new file mode 100644
index 00000000..b478cc19
--- /dev/null
+++ b/kokoro/macos/javascript/presubmit.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/macos/javascript/build.sh"
+timeout_mins: 1440
diff --git a/kokoro/macos/jruby/build.sh b/kokoro/macos/jruby/build.sh
new file mode 100755
index 00000000..c82eaebf
--- /dev/null
+++ b/kokoro/macos/jruby/build.sh
@@ -0,0 +1,11 @@
+#!/bin/bash
+#
+# Build file to set up and run tests
+
+# Change to repo root
+cd $(dirname $0)/../../..
+
+# Prepare worker environment to run tests
+source kokoro/macos/prepare_build_macos_rc
+
+./tests.sh jruby
diff --git a/kokoro/macos/jruby/continuous.cfg b/kokoro/macos/jruby/continuous.cfg
new file mode 100644
index 00000000..f1310fd3
--- /dev/null
+++ b/kokoro/macos/jruby/continuous.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/macos/jruby/build.sh"
+timeout_mins: 1440
diff --git a/kokoro/macos/jruby/presubmit.cfg b/kokoro/macos/jruby/presubmit.cfg
new file mode 100644
index 00000000..f1310fd3
--- /dev/null
+++ b/kokoro/macos/jruby/presubmit.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/macos/jruby/build.sh"
+timeout_mins: 1440
diff --git a/kokoro/macos/objectivec_cocoapods_integration/build.sh b/kokoro/macos/objectivec_cocoapods_integration/build.sh
new file mode 100755
index 00000000..f96d2899
--- /dev/null
+++ b/kokoro/macos/objectivec_cocoapods_integration/build.sh
@@ -0,0 +1,11 @@
+#!/bin/bash
+#
+# Build file to set up and run tests
+
+# Change to repo root
+cd $(dirname $0)/../../..
+
+# Prepare worker environment to run tests
+source kokoro/macos/prepare_build_macos_rc
+
+./tests.sh objectivec_cocoapods_integration
diff --git a/kokoro/macos/objectivec_cocoapods_integration/continuous.cfg b/kokoro/macos/objectivec_cocoapods_integration/continuous.cfg
new file mode 100644
index 00000000..952874ed
--- /dev/null
+++ b/kokoro/macos/objectivec_cocoapods_integration/continuous.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/macos/objectivec_cocoapods_integration/build.sh"
+timeout_mins: 1440
diff --git a/kokoro/macos/objectivec_cocoapods_integration/presubmit.cfg b/kokoro/macos/objectivec_cocoapods_integration/presubmit.cfg
new file mode 100644
index 00000000..952874ed
--- /dev/null
+++ b/kokoro/macos/objectivec_cocoapods_integration/presubmit.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/macos/objectivec_cocoapods_integration/build.sh"
+timeout_mins: 1440
diff --git a/kokoro/macos/objectivec_ios_debug/build.sh b/kokoro/macos/objectivec_ios_debug/build.sh
new file mode 100755
index 00000000..1055d72e
--- /dev/null
+++ b/kokoro/macos/objectivec_ios_debug/build.sh
@@ -0,0 +1,11 @@
+#!/bin/bash
+#
+# Build file to set up and run tests
+
+# Change to repo root
+cd $(dirname $0)/../../..
+
+# Prepare worker environment to run tests
+source kokoro/macos/prepare_build_macos_rc
+
+./tests.sh objectivec_ios_debug
diff --git a/kokoro/macos/objectivec_ios_debug/continuous.cfg b/kokoro/macos/objectivec_ios_debug/continuous.cfg
new file mode 100644
index 00000000..473d5455
--- /dev/null
+++ b/kokoro/macos/objectivec_ios_debug/continuous.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/macos/objectivec_ios_debug/build.sh"
+timeout_mins: 1440
diff --git a/kokoro/macos/objectivec_ios_debug/presubmit.cfg b/kokoro/macos/objectivec_ios_debug/presubmit.cfg
new file mode 100644
index 00000000..473d5455
--- /dev/null
+++ b/kokoro/macos/objectivec_ios_debug/presubmit.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/macos/objectivec_ios_debug/build.sh"
+timeout_mins: 1440
diff --git a/kokoro/macos/objectivec_ios_release/build.sh b/kokoro/macos/objectivec_ios_release/build.sh
new file mode 100755
index 00000000..76ce3ba0
--- /dev/null
+++ b/kokoro/macos/objectivec_ios_release/build.sh
@@ -0,0 +1,11 @@
+#!/bin/bash
+#
+# Build file to set up and run tests
+
+# Change to repo root
+cd $(dirname $0)/../../..
+
+# Prepare worker environment to run tests
+source kokoro/macos/prepare_build_macos_rc
+
+./tests.sh objectivec_ios_release
diff --git a/kokoro/macos/objectivec_ios_release/continuous.cfg b/kokoro/macos/objectivec_ios_release/continuous.cfg
new file mode 100644
index 00000000..3cbfb685
--- /dev/null
+++ b/kokoro/macos/objectivec_ios_release/continuous.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/macos/objectivec_ios_release/build.sh"
+timeout_mins: 1440
diff --git a/kokoro/macos/objectivec_ios_release/presubmit.cfg b/kokoro/macos/objectivec_ios_release/presubmit.cfg
new file mode 100644
index 00000000..3cbfb685
--- /dev/null
+++ b/kokoro/macos/objectivec_ios_release/presubmit.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/macos/objectivec_ios_release/build.sh"
+timeout_mins: 1440
diff --git a/kokoro/macos/objectivec_osx/build.sh b/kokoro/macos/objectivec_osx/build.sh
new file mode 100755
index 00000000..000be274
--- /dev/null
+++ b/kokoro/macos/objectivec_osx/build.sh
@@ -0,0 +1,11 @@
+#!/bin/bash
+#
+# Build file to set up and run tests
+
+# Change to repo root
+cd $(dirname $0)/../../..
+
+# Prepare worker environment to run tests
+source kokoro/macos/prepare_build_macos_rc
+
+./tests.sh objectivec_osx
diff --git a/kokoro/macos/objectivec_osx/continuous.cfg b/kokoro/macos/objectivec_osx/continuous.cfg
new file mode 100644
index 00000000..41bd46aa
--- /dev/null
+++ b/kokoro/macos/objectivec_osx/continuous.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/macos/objectivec_osx/build.sh"
+timeout_mins: 1440
diff --git a/kokoro/macos/objectivec_osx/presubmit.cfg b/kokoro/macos/objectivec_osx/presubmit.cfg
new file mode 100644
index 00000000..41bd46aa
--- /dev/null
+++ b/kokoro/macos/objectivec_osx/presubmit.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/macos/objectivec_osx/build.sh"
+timeout_mins: 1440
diff --git a/kokoro/macos/php5.6_mac/build.sh b/kokoro/macos/php5.6_mac/build.sh
new file mode 100755
index 00000000..74878898
--- /dev/null
+++ b/kokoro/macos/php5.6_mac/build.sh
@@ -0,0 +1,11 @@
+#!/bin/bash
+#
+# Build file to set up and run tests
+
+# Change to repo root
+cd $(dirname $0)/../../..
+
+# Prepare worker environment to run tests
+source kokoro/macos/prepare_build_macos_rc
+
+./tests.sh php5.6_mac
diff --git a/kokoro/macos/php5.6_mac/continuous.cfg b/kokoro/macos/php5.6_mac/continuous.cfg
new file mode 100644
index 00000000..ff345e9f
--- /dev/null
+++ b/kokoro/macos/php5.6_mac/continuous.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/macos/php5.6_mac/build.sh"
+timeout_mins: 1440
diff --git a/kokoro/macos/php5.6_mac/presubmit.cfg b/kokoro/macos/php5.6_mac/presubmit.cfg
new file mode 100644
index 00000000..ff345e9f
--- /dev/null
+++ b/kokoro/macos/php5.6_mac/presubmit.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/macos/php5.6_mac/build.sh"
+timeout_mins: 1440
diff --git a/kokoro/macos/php7.0_mac/build.sh b/kokoro/macos/php7.0_mac/build.sh
new file mode 100755
index 00000000..e5a37e30
--- /dev/null
+++ b/kokoro/macos/php7.0_mac/build.sh
@@ -0,0 +1,11 @@
+#!/bin/bash
+#
+# Build file to set up and run tests
+
+# Change to repo root
+cd $(dirname $0)/../../..
+
+# Prepare worker environment to run tests
+source kokoro/macos/prepare_build_macos_rc
+
+./tests.sh php7.0_mac
diff --git a/kokoro/macos/php7.0_mac/continuous.cfg b/kokoro/macos/php7.0_mac/continuous.cfg
new file mode 100644
index 00000000..c2c18119
--- /dev/null
+++ b/kokoro/macos/php7.0_mac/continuous.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/macos/php7.0_mac/build.sh"
+timeout_mins: 1440
diff --git a/kokoro/macos/php7.0_mac/presubmit.cfg b/kokoro/macos/php7.0_mac/presubmit.cfg
new file mode 100644
index 00000000..c2c18119
--- /dev/null
+++ b/kokoro/macos/php7.0_mac/presubmit.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/macos/php7.0_mac/build.sh"
+timeout_mins: 1440
diff --git a/kokoro/macos/prepare_build_macos_rc b/kokoro/macos/prepare_build_macos_rc
new file mode 100755
index 00000000..dfe66ff8
--- /dev/null
+++ b/kokoro/macos/prepare_build_macos_rc
@@ -0,0 +1,35 @@
+#!/bin/bash
+#
+# This script sets up a Kokoro MacOS worker for running Protobuf tests
+
+##
+# Select Xcode version
+
+export DEVELOPER_DIR=/Applications/Xcode_8.1.app/Contents/Developer
+
+##
+# Select C/C++ compilers
+
+export CC=gcc
+export CXX=g++
+
+##
+# Install Brew and core softwares
+
+ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
+source $HOME/.rvm/scripts/rvm
+brew tap homebrew/homebrew-php
+brew uninstall node icu4c
+brew install gflags gpg gpg2 node pcre php56 ruby
+
+##
+# Install Tox
+
+sudo pip install tox==2.4.1
+
+##
+# Install RVM
+
+gpg2 --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3
+command curl -sSL https://rvm.io/mpapis.asc | gpg2 --import -
+curl -sSL https://get.rvm.io | bash -s stable --ruby
diff --git a/kokoro/macos/python/build.sh b/kokoro/macos/python/build.sh
new file mode 100755
index 00000000..6b17b954
--- /dev/null
+++ b/kokoro/macos/python/build.sh
@@ -0,0 +1,11 @@
+#!/bin/bash
+#
+# Build file to set up and run tests
+
+# Change to repo root
+cd $(dirname $0)/../../..
+
+# Prepare worker environment to run tests
+source kokoro/macos/prepare_build_macos_rc
+
+./tests.sh python
diff --git a/kokoro/macos/python/continuous.cfg b/kokoro/macos/python/continuous.cfg
new file mode 100644
index 00000000..0fc8b503
--- /dev/null
+++ b/kokoro/macos/python/continuous.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/macos/python/build.sh"
+timeout_mins: 1440
diff --git a/kokoro/macos/python/presubmit.cfg b/kokoro/macos/python/presubmit.cfg
new file mode 100644
index 00000000..0fc8b503
--- /dev/null
+++ b/kokoro/macos/python/presubmit.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/macos/python/build.sh"
+timeout_mins: 1440
diff --git a/kokoro/macos/python_cpp/build.sh b/kokoro/macos/python_cpp/build.sh
new file mode 100755
index 00000000..cb53def9
--- /dev/null
+++ b/kokoro/macos/python_cpp/build.sh
@@ -0,0 +1,12 @@
+#!/bin/bash
+#
+# Build file to set up and run tests
+
+# Change to repo root
+cd $(dirname $0)/../../..
+
+# Prepare worker environment to run tests
+source kokoro/macos/prepare_build_macos_rc
+g++ --version
+
+./tests.sh python_cpp
diff --git a/kokoro/macos/python_cpp/continuous.cfg b/kokoro/macos/python_cpp/continuous.cfg
new file mode 100644
index 00000000..22f4a0e4
--- /dev/null
+++ b/kokoro/macos/python_cpp/continuous.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/macos/python_cpp/build.sh"
+timeout_mins: 1440
diff --git a/kokoro/macos/python_cpp/presubmit.cfg b/kokoro/macos/python_cpp/presubmit.cfg
new file mode 100644
index 00000000..22f4a0e4
--- /dev/null
+++ b/kokoro/macos/python_cpp/presubmit.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/macos/python_cpp/build.sh"
+timeout_mins: 1440
diff --git a/kokoro/macos/ruby21/build.sh b/kokoro/macos/ruby21/build.sh
new file mode 100755
index 00000000..748ea655
--- /dev/null
+++ b/kokoro/macos/ruby21/build.sh
@@ -0,0 +1,11 @@
+#!/bin/bash
+#
+# Build file to set up and run tests
+
+# Change to repo root
+cd $(dirname $0)/../../..
+
+# Prepare worker environment to run tests
+source kokoro/macos/prepare_build_macos_rc
+
+./tests.sh ruby21
diff --git a/kokoro/macos/ruby21/continuous.cfg b/kokoro/macos/ruby21/continuous.cfg
new file mode 100644
index 00000000..489796da
--- /dev/null
+++ b/kokoro/macos/ruby21/continuous.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/macos/ruby21/build.sh"
+timeout_mins: 1440
diff --git a/kokoro/macos/ruby21/presubmit.cfg b/kokoro/macos/ruby21/presubmit.cfg
new file mode 100644
index 00000000..489796da
--- /dev/null
+++ b/kokoro/macos/ruby21/presubmit.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/macos/ruby21/build.sh"
+timeout_mins: 1440
diff --git a/kokoro/macos/ruby22/build.sh b/kokoro/macos/ruby22/build.sh
new file mode 100755
index 00000000..5c4de429
--- /dev/null
+++ b/kokoro/macos/ruby22/build.sh
@@ -0,0 +1,11 @@
+#!/bin/bash
+#
+# Build file to set up and run tests
+
+# Change to repo root
+cd $(dirname $0)/../../..
+
+# Prepare worker environment to run tests
+source kokoro/macos/prepare_build_macos_rc
+
+./tests.sh ruby22
diff --git a/kokoro/macos/ruby22/continuous.cfg b/kokoro/macos/ruby22/continuous.cfg
new file mode 100644
index 00000000..d2705441
--- /dev/null
+++ b/kokoro/macos/ruby22/continuous.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/macos/ruby22/build.sh"
+timeout_mins: 1440
diff --git a/kokoro/macos/ruby22/presubmit.cfg b/kokoro/macos/ruby22/presubmit.cfg
new file mode 100644
index 00000000..d2705441
--- /dev/null
+++ b/kokoro/macos/ruby22/presubmit.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/macos/ruby22/build.sh"
+timeout_mins: 1440
diff --git a/m4/ax_cxx_compile_stdcxx.m4 b/m4/ax_cxx_compile_stdcxx.m4
index b61fcb63..d3288e2f 100644
--- a/m4/ax_cxx_compile_stdcxx.m4
+++ b/m4/ax_cxx_compile_stdcxx.m4
@@ -180,6 +180,8 @@ m4_define([_AX_CXX_COMPILE_STDCXX_testbody_new_in_11], [[
#else
+#include <utility>
+
namespace cxx11
{
@@ -445,6 +447,23 @@ namespace cxx11
}
+ namespace test_std_move_and_forward
+ {
+ struct message {};
+ char foo(message&) { return '\0'; }
+ int foo(message&&) { return 0; }
+
+ template<typename Arg, typename RT>
+ void check(Arg&& arg, RT rt) {
+ static_assert(sizeof(rt) == sizeof(foo(std::forward<Arg>(arg))), "");
+ }
+ void test() {
+ message a;
+ check(a, char());
+ check(std::move(a), int());
+ }
+ }
+
} // namespace cxx11
#endif // __cplusplus >= 201103L
diff --git a/m4/ax_prog_cc_for_build.m4 b/m4/ax_prog_cc_for_build.m4
new file mode 100644
index 00000000..77fd346a
--- /dev/null
+++ b/m4/ax_prog_cc_for_build.m4
@@ -0,0 +1,125 @@
+# ===========================================================================
+# http://www.gnu.org/software/autoconf-archive/ax_prog_cc_for_build.html
+# ===========================================================================
+#
+# SYNOPSIS
+#
+# AX_PROG_CC_FOR_BUILD
+#
+# DESCRIPTION
+#
+# This macro searches for a C compiler that generates native executables,
+# that is a C compiler that surely is not a cross-compiler. This can be
+# useful if you have to generate source code at compile-time like for
+# example GCC does.
+#
+# The macro sets the CC_FOR_BUILD and CPP_FOR_BUILD macros to anything
+# needed to compile or link (CC_FOR_BUILD) and preprocess (CPP_FOR_BUILD).
+# The value of these variables can be overridden by the user by specifying
+# a compiler with an environment variable (like you do for standard CC).
+#
+# It also sets BUILD_EXEEXT and BUILD_OBJEXT to the executable and object
+# file extensions for the build platform, and GCC_FOR_BUILD to `yes' if
+# the compiler we found is GCC. All these variables but GCC_FOR_BUILD are
+# substituted in the Makefile.
+#
+# LICENSE
+#
+# Copyright (c) 2008 Paolo Bonzini <bonzini@gnu.org>
+#
+# Copying and distribution of this file, with or without modification, are
+# permitted in any medium without royalty provided the copyright notice
+# and this notice are preserved. This file is offered as-is, without any
+# warranty.
+
+#serial 8
+
+AU_ALIAS([AC_PROG_CC_FOR_BUILD], [AX_PROG_CC_FOR_BUILD])
+AC_DEFUN([AX_PROG_CC_FOR_BUILD], [dnl
+AC_REQUIRE([AC_PROG_CC])dnl
+AC_REQUIRE([AC_PROG_CPP])dnl
+AC_REQUIRE([AC_EXEEXT])dnl
+AC_REQUIRE([AC_CANONICAL_HOST])dnl
+
+dnl Use the standard macros, but make them use other variable names
+dnl
+pushdef([ac_cv_prog_CPP], ac_cv_build_prog_CPP)dnl
+pushdef([ac_cv_prog_gcc], ac_cv_build_prog_gcc)dnl
+pushdef([ac_cv_prog_cc_works], ac_cv_build_prog_cc_works)dnl
+pushdef([ac_cv_prog_cc_cross], ac_cv_build_prog_cc_cross)dnl
+pushdef([ac_cv_prog_cc_g], ac_cv_build_prog_cc_g)dnl
+pushdef([ac_cv_exeext], ac_cv_build_exeext)dnl
+pushdef([ac_cv_objext], ac_cv_build_objext)dnl
+pushdef([ac_exeext], ac_build_exeext)dnl
+pushdef([ac_objext], ac_build_objext)dnl
+pushdef([CC], CC_FOR_BUILD)dnl
+pushdef([CPP], CPP_FOR_BUILD)dnl
+pushdef([CFLAGS], CFLAGS_FOR_BUILD)dnl
+pushdef([CPPFLAGS], CPPFLAGS_FOR_BUILD)dnl
+pushdef([LDFLAGS], LDFLAGS_FOR_BUILD)dnl
+pushdef([host], build)dnl
+pushdef([host_alias], build_alias)dnl
+pushdef([host_cpu], build_cpu)dnl
+pushdef([host_vendor], build_vendor)dnl
+pushdef([host_os], build_os)dnl
+pushdef([ac_cv_host], ac_cv_build)dnl
+pushdef([ac_cv_host_alias], ac_cv_build_alias)dnl
+pushdef([ac_cv_host_cpu], ac_cv_build_cpu)dnl
+pushdef([ac_cv_host_vendor], ac_cv_build_vendor)dnl
+pushdef([ac_cv_host_os], ac_cv_build_os)dnl
+pushdef([ac_cpp], ac_build_cpp)dnl
+pushdef([ac_compile], ac_build_compile)dnl
+pushdef([ac_link], ac_build_link)dnl
+
+save_cross_compiling=$cross_compiling
+save_ac_tool_prefix=$ac_tool_prefix
+cross_compiling=no
+ac_tool_prefix=
+
+AC_PROG_CC
+AC_PROG_CPP
+AC_EXEEXT
+
+ac_tool_prefix=$save_ac_tool_prefix
+cross_compiling=$save_cross_compiling
+
+dnl Restore the old definitions
+dnl
+popdef([ac_link])dnl
+popdef([ac_compile])dnl
+popdef([ac_cpp])dnl
+popdef([ac_cv_host_os])dnl
+popdef([ac_cv_host_vendor])dnl
+popdef([ac_cv_host_cpu])dnl
+popdef([ac_cv_host_alias])dnl
+popdef([ac_cv_host])dnl
+popdef([host_os])dnl
+popdef([host_vendor])dnl
+popdef([host_cpu])dnl
+popdef([host_alias])dnl
+popdef([host])dnl
+popdef([LDFLAGS])dnl
+popdef([CPPFLAGS])dnl
+popdef([CFLAGS])dnl
+popdef([CPP])dnl
+popdef([CC])dnl
+popdef([ac_objext])dnl
+popdef([ac_exeext])dnl
+popdef([ac_cv_objext])dnl
+popdef([ac_cv_exeext])dnl
+popdef([ac_cv_prog_cc_g])dnl
+popdef([ac_cv_prog_cc_cross])dnl
+popdef([ac_cv_prog_cc_works])dnl
+popdef([ac_cv_prog_gcc])dnl
+popdef([ac_cv_prog_CPP])dnl
+
+dnl Finally, set Makefile variables
+dnl
+BUILD_EXEEXT=$ac_build_exeext
+BUILD_OBJEXT=$ac_build_objext
+AC_SUBST(BUILD_EXEEXT)dnl
+AC_SUBST(BUILD_OBJEXT)dnl
+AC_SUBST([CFLAGS_FOR_BUILD])dnl
+AC_SUBST([CPPFLAGS_FOR_BUILD])dnl
+AC_SUBST([LDFLAGS_FOR_BUILD])dnl
+])
diff --git a/m4/ax_prog_cxx_for_build.m4 b/m4/ax_prog_cxx_for_build.m4
new file mode 100644
index 00000000..8cc0f73c
--- /dev/null
+++ b/m4/ax_prog_cxx_for_build.m4
@@ -0,0 +1,110 @@
+# ===========================================================================
+# http://www.gnu.org/software/autoconf-archive/ax_prog_cxx_for_build.html
+# ===========================================================================
+#
+# SYNOPSIS
+#
+# AX_PROG_CXX_FOR_BUILD
+#
+# DESCRIPTION
+#
+# This macro searches for a C++ compiler that generates native
+# executables, that is a C++ compiler that surely is not a cross-compiler.
+# This can be useful if you have to generate source code at compile-time
+# like for example GCC does.
+#
+# The macro sets the CXX_FOR_BUILD and CXXCPP_FOR_BUILD macros to anything
+# needed to compile or link (CXX_FOR_BUILD) and preprocess
+# (CXXCPP_FOR_BUILD). The value of these variables can be overridden by
+# the user by specifying a compiler with an environment variable (like you
+# do for standard CXX).
+#
+# LICENSE
+#
+# Copyright (c) 2008 Paolo Bonzini <bonzini@gnu.org>
+# Copyright (c) 2012 Avionic Design GmbH
+#
+# Based on the AX_PROG_CC_FOR_BUILD macro by Paolo Bonzini.
+#
+# Copying and distribution of this file, with or without modification, are
+# permitted in any medium without royalty provided the copyright notice
+# and this notice are preserved. This file is offered as-is, without any
+# warranty.
+
+#serial 2
+
+AU_ALIAS([AC_PROG_CXX_FOR_BUILD], [AX_PROG_CXX_FOR_BUILD])
+AC_DEFUN([AX_PROG_CXX_FOR_BUILD], [dnl
+AC_REQUIRE([AX_PROG_CC_FOR_BUILD])dnl
+AC_REQUIRE([AC_PROG_CXX])dnl
+AC_REQUIRE([AC_PROG_CXXCPP])dnl
+AC_REQUIRE([AC_CANONICAL_HOST])dnl
+
+dnl Use the standard macros, but make them use other variable names
+dnl
+pushdef([ac_cv_prog_CXXCPP], ac_cv_build_prog_CXXCPP)dnl
+pushdef([ac_cv_prog_gxx], ac_cv_build_prog_gxx)dnl
+pushdef([ac_cv_prog_cxx_works], ac_cv_build_prog_cxx_works)dnl
+pushdef([ac_cv_prog_cxx_cross], ac_cv_build_prog_cxx_cross)dnl
+pushdef([ac_cv_prog_cxx_g], ac_cv_build_prog_cxx_g)dnl
+pushdef([CXX], CXX_FOR_BUILD)dnl
+pushdef([CXXCPP], CXXCPP_FOR_BUILD)dnl
+pushdef([CXXFLAGS], CXXFLAGS_FOR_BUILD)dnl
+pushdef([CPPFLAGS], CPPFLAGS_FOR_BUILD)dnl
+pushdef([CXXCPPFLAGS], CXXCPPFLAGS_FOR_BUILD)dnl
+pushdef([host], build)dnl
+pushdef([host_alias], build_alias)dnl
+pushdef([host_cpu], build_cpu)dnl
+pushdef([host_vendor], build_vendor)dnl
+pushdef([host_os], build_os)dnl
+pushdef([ac_cv_host], ac_cv_build)dnl
+pushdef([ac_cv_host_alias], ac_cv_build_alias)dnl
+pushdef([ac_cv_host_cpu], ac_cv_build_cpu)dnl
+pushdef([ac_cv_host_vendor], ac_cv_build_vendor)dnl
+pushdef([ac_cv_host_os], ac_cv_build_os)dnl
+pushdef([ac_cxxcpp], ac_build_cxxcpp)dnl
+pushdef([ac_compile], ac_build_compile)dnl
+pushdef([ac_link], ac_build_link)dnl
+
+save_cross_compiling=$cross_compiling
+save_ac_tool_prefix=$ac_tool_prefix
+cross_compiling=no
+ac_tool_prefix=
+
+AC_PROG_CXX
+AC_PROG_CXXCPP
+
+ac_tool_prefix=$save_ac_tool_prefix
+cross_compiling=$save_cross_compiling
+
+dnl Restore the old definitions
+dnl
+popdef([ac_link])dnl
+popdef([ac_compile])dnl
+popdef([ac_cxxcpp])dnl
+popdef([ac_cv_host_os])dnl
+popdef([ac_cv_host_vendor])dnl
+popdef([ac_cv_host_cpu])dnl
+popdef([ac_cv_host_alias])dnl
+popdef([ac_cv_host])dnl
+popdef([host_os])dnl
+popdef([host_vendor])dnl
+popdef([host_cpu])dnl
+popdef([host_alias])dnl
+popdef([host])dnl
+popdef([CXXCPPFLAGS])dnl
+popdef([CPPFLAGS])dnl
+popdef([CXXFLAGS])dnl
+popdef([CXXCPP])dnl
+popdef([CXX])dnl
+popdef([ac_cv_prog_cxx_g])dnl
+popdef([ac_cv_prog_cxx_cross])dnl
+popdef([ac_cv_prog_cxx_works])dnl
+popdef([ac_cv_prog_gxx])dnl
+popdef([ac_cv_prog_CXXCPP])dnl
+
+dnl Finally, set Makefile variables
+dnl
+AC_SUBST([CXXFLAGS_FOR_BUILD])dnl
+AC_SUBST([CXXCPPFLAGS_FOR_BUILD])dnl
+])
diff --git a/objectivec/DevTools/full_mac_build.sh b/objectivec/DevTools/full_mac_build.sh
index ef8fb740..7e1e9a05 100755
--- a/objectivec/DevTools/full_mac_build.sh
+++ b/objectivec/DevTools/full_mac_build.sh
@@ -253,16 +253,20 @@ if [[ "${DO_XCODE_IOS_TESTS}" == "yes" ]] ; then
XCODEBUILD_TEST_BASE_IOS+=(
-destination "platform=iOS Simulator,name=iPhone 4s,OS=9.0" # 32bit
-destination "platform=iOS Simulator,name=iPhone 7,OS=10.0" # 64bit
- -destination "platform=iOS Simulator,name=iPad 2,OS=9.0" # 32bit
- -destination "platform=iOS Simulator,name=iPad Pro (9.7 inch),OS=10.0" # 64bit
)
;;
- 8.1* )
+ 8.[1-3]* )
XCODEBUILD_TEST_BASE_IOS+=(
-destination "platform=iOS Simulator,name=iPhone 4s,OS=8.1" # 32bit
- -destination "platform=iOS Simulator,name=iPhone 7,OS=10.1" # 64bit
- -destination "platform=iOS Simulator,name=iPad 2,OS=8.1" # 32bit
- -destination "platform=iOS Simulator,name=iPad Pro (9.7 inch),OS=10.1" # 64bit
+ -destination "platform=iOS Simulator,name=iPhone 7,OS=latest" # 64bit
+ )
+ ;;
+ 9.[0-1]* )
+ XCODEBUILD_TEST_BASE_IOS+=(
+ -destination "platform=iOS Simulator,name=iPhone 4s,OS=8.1" # 32bit
+ -destination "platform=iOS Simulator,name=iPhone 7,OS=latest" # 64bit
+ # 9.0/9.1 both seem to often fail running destinations in parallel
+ -disable-concurrent-testing
)
;;
* )
@@ -279,7 +283,7 @@ if [[ "${DO_XCODE_IOS_TESTS}" == "yes" ]] ; then
"${XCODEBUILD_TEST_BASE_IOS[@]}" -configuration Release test
fi
# Don't leave the simulator in the developer's face.
- killall Simulator
+ killall Simulator 2> /dev/null || true
fi
if [[ "${DO_XCODE_OSX_TESTS}" == "yes" ]] ; then
XCODEBUILD_TEST_BASE_OSX=(
diff --git a/objectivec/DevTools/pddm.py b/objectivec/DevTools/pddm.py
index 9a11fec4..0b5b7b40 100755
--- a/objectivec/DevTools/pddm.py
+++ b/objectivec/DevTools/pddm.py
@@ -124,6 +124,7 @@ def _MacroRefRe(macro_names):
return re.compile(r'\b(?P<macro_ref>(?P<name>(%s))\((?P<args>.*?)\))' %
'|'.join(macro_names))
+
def _MacroArgRefRe(macro_arg_names):
# Takes in a list of macro arg names and makes a regex that will match
# uses of those args.
@@ -318,25 +319,26 @@ class MacroCollection(object):
return macro.body
assert len(arg_values) == len(macro.args)
args = dict(zip(macro.args, arg_values))
+
def _lookupArg(match):
val = args[match.group('name')]
opt = match.group('option')
if opt:
- if opt == 'S': # Spaces for the length
+ if opt == 'S': # Spaces for the length
return ' ' * len(val)
- elif opt == 'l': # Lowercase first character
+ elif opt == 'l': # Lowercase first character
if val:
return val[0].lower() + val[1:]
else:
return val
- elif opt == 'L': # All Lowercase
+ elif opt == 'L': # All Lowercase
return val.lower()
- elif opt == 'u': # Uppercase first character
+ elif opt == 'u': # Uppercase first character
if val:
return val[0].upper() + val[1:]
else:
return val
- elif opt == 'U': # All Uppercase
+ elif opt == 'U': # All Uppercase
return val.upper()
else:
raise PDDMError('Unknown arg option "%s$%s" while expanding "%s".%s'
@@ -350,6 +352,7 @@ class MacroCollection(object):
def _EvalMacrosRefs(self, text, macro_stack):
macro_ref_re = _MacroRefRe(self._macros.keys())
+
def _resolveMacro(match):
return self._Expand(match, macro_stack)
return macro_ref_re.sub(_resolveMacro, text)
@@ -496,9 +499,10 @@ class SourceFile(object):
# Add the ending marker.
if len(captured_lines) == 1:
result.append('//%%PDDM-EXPAND-END %s' %
- captured_lines[0][directive_len:].strip())
+ captured_lines[0][directive_len:].strip())
else:
- result.append('//%%PDDM-EXPAND-END (%s expansions)' % len(captured_lines))
+ result.append('//%%PDDM-EXPAND-END (%s expansions)' %
+ len(captured_lines))
return result
@@ -669,15 +673,15 @@ def main(args):
if src_file.processed_content != src_file.original_content:
if not opts.dry_run:
- print 'Updating for "%s".' % a_path
+ print('Updating for "%s".' % a_path)
with open(a_path, 'w') as f:
f.write(src_file.processed_content)
else:
# Special result to indicate things need updating.
- print 'Update needed for "%s".' % a_path
+ print('Update needed for "%s".' % a_path)
result = 1
elif opts.verbose:
- print 'No update for "%s".' % a_path
+ print('No update for "%s".' % a_path)
return result
diff --git a/objectivec/GPBArray.h b/objectivec/GPBArray.h
index 781cfb6f..638b2882 100644
--- a/objectivec/GPBArray.h
+++ b/objectivec/GPBArray.h
@@ -96,7 +96,7 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized GPBInt32Array with a copy of the values.
**/
-- (instancetype)initWithValues:(const int32_t [])values
+- (instancetype)initWithValues:(const int32_t [__nullable])values
count:(NSUInteger)count;
/**
@@ -161,7 +161,7 @@ NS_ASSUME_NONNULL_BEGIN
* @param values The values to add to this array.
* @param count The number of elements to add.
**/
-- (void)addValues:(const int32_t [])values count:(NSUInteger)count;
+- (void)addValues:(const int32_t [__nullable])values count:(NSUInteger)count;
/**
* Adds the values from the given array to this array.
@@ -268,7 +268,7 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized GPBUInt32Array with a copy of the values.
**/
-- (instancetype)initWithValues:(const uint32_t [])values
+- (instancetype)initWithValues:(const uint32_t [__nullable])values
count:(NSUInteger)count;
/**
@@ -333,7 +333,7 @@ NS_ASSUME_NONNULL_BEGIN
* @param values The values to add to this array.
* @param count The number of elements to add.
**/
-- (void)addValues:(const uint32_t [])values count:(NSUInteger)count;
+- (void)addValues:(const uint32_t [__nullable])values count:(NSUInteger)count;
/**
* Adds the values from the given array to this array.
@@ -440,7 +440,7 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized GPBInt64Array with a copy of the values.
**/
-- (instancetype)initWithValues:(const int64_t [])values
+- (instancetype)initWithValues:(const int64_t [__nullable])values
count:(NSUInteger)count;
/**
@@ -505,7 +505,7 @@ NS_ASSUME_NONNULL_BEGIN
* @param values The values to add to this array.
* @param count The number of elements to add.
**/
-- (void)addValues:(const int64_t [])values count:(NSUInteger)count;
+- (void)addValues:(const int64_t [__nullable])values count:(NSUInteger)count;
/**
* Adds the values from the given array to this array.
@@ -612,7 +612,7 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized GPBUInt64Array with a copy of the values.
**/
-- (instancetype)initWithValues:(const uint64_t [])values
+- (instancetype)initWithValues:(const uint64_t [__nullable])values
count:(NSUInteger)count;
/**
@@ -677,7 +677,7 @@ NS_ASSUME_NONNULL_BEGIN
* @param values The values to add to this array.
* @param count The number of elements to add.
**/
-- (void)addValues:(const uint64_t [])values count:(NSUInteger)count;
+- (void)addValues:(const uint64_t [__nullable])values count:(NSUInteger)count;
/**
* Adds the values from the given array to this array.
@@ -784,7 +784,7 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized GPBFloatArray with a copy of the values.
**/
-- (instancetype)initWithValues:(const float [])values
+- (instancetype)initWithValues:(const float [__nullable])values
count:(NSUInteger)count;
/**
@@ -849,7 +849,7 @@ NS_ASSUME_NONNULL_BEGIN
* @param values The values to add to this array.
* @param count The number of elements to add.
**/
-- (void)addValues:(const float [])values count:(NSUInteger)count;
+- (void)addValues:(const float [__nullable])values count:(NSUInteger)count;
/**
* Adds the values from the given array to this array.
@@ -956,7 +956,7 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized GPBDoubleArray with a copy of the values.
**/
-- (instancetype)initWithValues:(const double [])values
+- (instancetype)initWithValues:(const double [__nullable])values
count:(NSUInteger)count;
/**
@@ -1021,7 +1021,7 @@ NS_ASSUME_NONNULL_BEGIN
* @param values The values to add to this array.
* @param count The number of elements to add.
**/
-- (void)addValues:(const double [])values count:(NSUInteger)count;
+- (void)addValues:(const double [__nullable])values count:(NSUInteger)count;
/**
* Adds the values from the given array to this array.
@@ -1128,7 +1128,7 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized GPBBoolArray with a copy of the values.
**/
-- (instancetype)initWithValues:(const BOOL [])values
+- (instancetype)initWithValues:(const BOOL [__nullable])values
count:(NSUInteger)count;
/**
@@ -1193,7 +1193,7 @@ NS_ASSUME_NONNULL_BEGIN
* @param values The values to add to this array.
* @param count The number of elements to add.
**/
-- (void)addValues:(const BOOL [])values count:(NSUInteger)count;
+- (void)addValues:(const BOOL [__nullable])values count:(NSUInteger)count;
/**
* Adds the values from the given array to this array.
@@ -1325,7 +1325,7 @@ NS_ASSUME_NONNULL_BEGIN
* @return A newly initialized GPBEnumArray with a copy of the values.
**/
- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func
- rawValues:(const int32_t [])values
+ rawValues:(const int32_t [__nullable])values
count:(NSUInteger)count;
/**
@@ -1435,7 +1435,7 @@ NS_ASSUME_NONNULL_BEGIN
* @param values The values to add to this array.
* @param count The number of elements to add.
**/
-- (void)addValues:(const int32_t [])values count:(NSUInteger)count;
+- (void)addValues:(const int32_t [__nullable])values count:(NSUInteger)count;
/**
@@ -1486,7 +1486,7 @@ NS_ASSUME_NONNULL_BEGIN
* @param values Array containing the raw enum values to add to this array.
* @param count The number of raw values to add.
**/
-- (void)addRawValues:(const int32_t [])values count:(NSUInteger)count;
+- (void)addRawValues:(const int32_t [__nullable])values count:(NSUInteger)count;
/**
* Inserts a raw enum value at the given index.
@@ -1574,7 +1574,7 @@ NS_ASSUME_NONNULL_END
//%
//%/**
//% * Creates and initializes a GPB##NAME##Array with the single element given.
-//% *
+//% *
//% * @param value The value to be placed in the array.
//% *
//% * @return A newly instanced GPB##NAME##Array with value in it.
@@ -1600,7 +1600,7 @@ NS_ASSUME_NONNULL_END
//% **/
//%+ (instancetype)arrayWithCapacity:(NSUInteger)count;
//%
-//%/**
+//%/**
//% * @return A newly initialized and empty GPB##NAME##Array.
//% **/
//%- (instancetype)init NS_DESIGNATED_INITIALIZER;
@@ -1613,7 +1613,7 @@ NS_ASSUME_NONNULL_END
//% *
//% * @return A newly initialized GPB##NAME##Array with a copy of the values.
//% **/
-//%- (instancetype)initWithValues:(const TYPE [])values
+//%- (instancetype)initWithValues:(const TYPE [__nullable])values
//% count:(NSUInteger)count;
//%
//%/**
@@ -1730,7 +1730,7 @@ NS_ASSUME_NONNULL_END
//% * @return A newly initialized GPB##NAME##Array with a copy of the values.
//% **/
//%- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func
-//% rawValues:(const TYPE [])values
+//% rawValues:(const TYPE [__nullable])values
//% count:(NSUInteger)count;
//%
//%/**
@@ -1773,7 +1773,7 @@ NS_ASSUME_NONNULL_END
//%
//%/**
//% * Enumerates the values on this array with the given block.
-//% *
+//% *
//% * @param block The block to enumerate with.
//% * **value**: The current value being enumerated.
//% * **idx**: The index of the current value.
@@ -1827,7 +1827,7 @@ NS_ASSUME_NONNULL_END
//% * Enumerates the values on this array with the given block.
//% *
//% * @param opts Options to control the enumeration.
-//% * @param block The block to enumerate with.
+//% * @param block The block to enumerate with.
//% * **value**: The current value being enumerated.
//% * **idx**: The index of the current value.
//% * **stop**: A pointer to a boolean that when set stops the enumeration.
@@ -1849,7 +1849,7 @@ NS_ASSUME_NONNULL_END
//% * @param values The values to add to this array.
//% * @param count The number of elements to add.
//% **/
-//%- (void)addValues:(const TYPE [])values count:(NSUInteger)count;
+//%- (void)addValues:(const TYPE [__nullable])values count:(NSUInteger)count;
//%
//%ARRAY_EXTRA_MUTABLE_METHODS1_##HELPER_NAME(NAME, TYPE)
//%/**
@@ -1939,7 +1939,7 @@ NS_ASSUME_NONNULL_END
//% * @param values Array containing the raw enum values to add to this array.
//% * @param count The number of raw values to add.
//% **/
-//%- (void)addRawValues:(const TYPE [])values count:(NSUInteger)count;
+//%- (void)addRawValues:(const TYPE [__nullable])values count:(NSUInteger)count;
//%
//%/**
//% * Inserts a raw enum value at the given index.
diff --git a/objectivec/GPBArray.m b/objectivec/GPBArray.m
index ae57747d..f401631d 100644
--- a/objectivec/GPBArray.m
+++ b/objectivec/GPBArray.m
@@ -2519,14 +2519,14 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) {
- (id)copyWithZone:(NSZone *)zone {
if (_array == nil) {
- _array = [[NSMutableArray alloc] init];
+ return [[NSMutableArray allocWithZone:zone] init];
}
return [_array copyWithZone:zone];
}
- (id)mutableCopyWithZone:(NSZone *)zone {
if (_array == nil) {
- _array = [[NSMutableArray alloc] init];
+ return [[NSMutableArray allocWithZone:zone] init];
}
return [_array mutableCopyWithZone:zone];
}
diff --git a/objectivec/GPBCodedInputStream.m b/objectivec/GPBCodedInputStream.m
index e8c8989c..0759640d 100644
--- a/objectivec/GPBCodedInputStream.m
+++ b/objectivec/GPBCodedInputStream.m
@@ -45,7 +45,12 @@ NSString *const GPBCodedInputStreamUnderlyingErrorKey =
NSString *const GPBCodedInputStreamErrorDomain =
GPBNSStringifySymbol(GPBCodedInputStreamErrorDomain);
-static const NSUInteger kDefaultRecursionLimit = 64;
+// Matching:
+// https://github.com/google/protobuf/blob/master/java/core/src/main/java/com/google/protobuf/CodedInputStream.java#L62
+// private static final int DEFAULT_RECURSION_LIMIT = 100;
+// https://github.com/google/protobuf/blob/master/src/google/protobuf/io/coded_stream.cc#L86
+// int CodedInputStream::default_recursion_limit_ = 100;
+static const NSUInteger kDefaultRecursionLimit = 100;
static void RaiseException(NSInteger code, NSString *reason) {
NSDictionary *errorInfo = nil;
@@ -63,6 +68,12 @@ static void RaiseException(NSInteger code, NSString *reason) {
userInfo:exceptionInfo] raise];
}
+static void CheckRecursionLimit(GPBCodedInputStreamState *state) {
+ if (state->recursionDepth >= kDefaultRecursionLimit) {
+ RaiseException(GPBCodedInputStreamErrorRecursionDepthExceeded, nil);
+ }
+}
+
static void CheckSize(GPBCodedInputStreamState *state, size_t size) {
size_t newSize = state->bufferPos + size;
if (newSize > state->bufferSize) {
@@ -94,41 +105,6 @@ static int64_t ReadRawLittleEndian64(GPBCodedInputStreamState *state) {
return value;
}
-static int32_t ReadRawVarint32(GPBCodedInputStreamState *state) {
- int8_t tmp = ReadRawByte(state);
- if (tmp >= 0) {
- return tmp;
- }
- int32_t result = tmp & 0x7f;
- if ((tmp = ReadRawByte(state)) >= 0) {
- result |= tmp << 7;
- } else {
- result |= (tmp & 0x7f) << 7;
- if ((tmp = ReadRawByte(state)) >= 0) {
- result |= tmp << 14;
- } else {
- result |= (tmp & 0x7f) << 14;
- if ((tmp = ReadRawByte(state)) >= 0) {
- result |= tmp << 21;
- } else {
- result |= (tmp & 0x7f) << 21;
- result |= (tmp = ReadRawByte(state)) << 28;
- if (tmp < 0) {
- // Discard upper 32 bits.
- for (int i = 0; i < 5; i++) {
- if (ReadRawByte(state) >= 0) {
- return result;
- }
- }
- RaiseException(GPBCodedInputStreamErrorInvalidVarInt,
- @"Invalid VarInt32");
- }
- }
- }
- }
- return result;
-}
-
static int64_t ReadRawVarint64(GPBCodedInputStreamState *state) {
int32_t shift = 0;
int64_t result = 0;
@@ -144,6 +120,10 @@ static int64_t ReadRawVarint64(GPBCodedInputStreamState *state) {
return 0;
}
+static int32_t ReadRawVarint32(GPBCodedInputStreamState *state) {
+ return (int32_t)ReadRawVarint64(state);
+}
+
static void SkipRawData(GPBCodedInputStreamState *state, size_t size) {
CheckSize(state, size);
state->bufferPos += size;
@@ -225,16 +205,16 @@ int32_t GPBCodedInputStreamReadTag(GPBCodedInputStreamState *state) {
}
state->lastTag = ReadRawVarint32(state);
- if (state->lastTag == 0) {
- // If we actually read zero, that's not a valid tag.
- RaiseException(GPBCodedInputStreamErrorInvalidTag,
- @"A zero tag on the wire is invalid.");
- }
- // Tags have to include a valid wireformat, check that also.
+ // Tags have to include a valid wireformat.
if (!GPBWireFormatIsValidTag(state->lastTag)) {
RaiseException(GPBCodedInputStreamErrorInvalidTag,
@"Invalid wireformat in tag.");
}
+ // Zero is not a valid field number.
+ if (GPBWireFormatGetTagFieldNumber(state->lastTag) == 0) {
+ RaiseException(GPBCodedInputStreamErrorInvalidTag,
+ @"A zero field number on the wire is invalid.");
+ }
return state->lastTag;
}
@@ -447,9 +427,7 @@ void GPBCodedInputStreamCheckLastTagWas(GPBCodedInputStreamState *state,
- (void)readGroup:(int32_t)fieldNumber
message:(GPBMessage *)message
extensionRegistry:(GPBExtensionRegistry *)extensionRegistry {
- if (state_.recursionDepth >= kDefaultRecursionLimit) {
- RaiseException(GPBCodedInputStreamErrorRecursionDepthExceeded, nil);
- }
+ CheckRecursionLimit(&state_);
++state_.recursionDepth;
[message mergeFromCodedInputStream:self extensionRegistry:extensionRegistry];
GPBCodedInputStreamCheckLastTagWas(
@@ -459,9 +437,7 @@ void GPBCodedInputStreamCheckLastTagWas(GPBCodedInputStreamState *state,
- (void)readUnknownGroup:(int32_t)fieldNumber
message:(GPBUnknownFieldSet *)message {
- if (state_.recursionDepth >= kDefaultRecursionLimit) {
- RaiseException(GPBCodedInputStreamErrorRecursionDepthExceeded, nil);
- }
+ CheckRecursionLimit(&state_);
++state_.recursionDepth;
[message mergeFromCodedInputStream:self];
GPBCodedInputStreamCheckLastTagWas(
@@ -471,10 +447,8 @@ void GPBCodedInputStreamCheckLastTagWas(GPBCodedInputStreamState *state,
- (void)readMessage:(GPBMessage *)message
extensionRegistry:(GPBExtensionRegistry *)extensionRegistry {
+ CheckRecursionLimit(&state_);
int32_t length = ReadRawVarint32(&state_);
- if (state_.recursionDepth >= kDefaultRecursionLimit) {
- RaiseException(GPBCodedInputStreamErrorRecursionDepthExceeded, nil);
- }
size_t oldLimit = GPBCodedInputStreamPushLimit(&state_, length);
++state_.recursionDepth;
[message mergeFromCodedInputStream:self extensionRegistry:extensionRegistry];
@@ -487,10 +461,8 @@ void GPBCodedInputStreamCheckLastTagWas(GPBCodedInputStreamState *state,
extensionRegistry:(GPBExtensionRegistry *)extensionRegistry
field:(GPBFieldDescriptor *)field
parentMessage:(GPBMessage *)parentMessage {
+ CheckRecursionLimit(&state_);
int32_t length = ReadRawVarint32(&state_);
- if (state_.recursionDepth >= kDefaultRecursionLimit) {
- RaiseException(GPBCodedInputStreamErrorRecursionDepthExceeded, nil);
- }
size_t oldLimit = GPBCodedInputStreamPushLimit(&state_, length);
++state_.recursionDepth;
GPBDictionaryReadEntry(mapDictionary, self, extensionRegistry, field,
diff --git a/objectivec/GPBCodedOutputStream.h b/objectivec/GPBCodedOutputStream.h
index d6fff3db..23c404b8 100644
--- a/objectivec/GPBCodedOutputStream.h
+++ b/objectivec/GPBCodedOutputStream.h
@@ -47,11 +47,20 @@
NS_ASSUME_NONNULL_BEGIN
/**
+ * @c GPBCodedOutputStream exception names.
+ **/
+extern NSString *const GPBCodedOutputStreamException_OutOfSpace;
+extern NSString *const GPBCodedOutputStreamException_WriteFailed;
+
+/**
* Writes out protocol message fields.
*
* The common uses of protocol buffers shouldn't need to use this class.
* GPBMessage's provide a -data method that will serialize the message for you.
*
+ * @note Any -write* api can raise the GPBCodedOutputStreamException_*
+ * exceptions.
+ *
* @note Subclassing of GPBCodedOutputStream is NOT supported.
**/
@interface GPBCodedOutputStream : NSObject
diff --git a/objectivec/GPBCodedOutputStream.m b/objectivec/GPBCodedOutputStream.m
index 7c3ab447..f832e8a6 100644
--- a/objectivec/GPBCodedOutputStream.m
+++ b/objectivec/GPBCodedOutputStream.m
@@ -36,6 +36,11 @@
#import "GPBUnknownFieldSet_PackagePrivate.h"
#import "GPBUtilities_PackagePrivate.h"
+// These values are the existing values so as not to break any code that might
+// have already been inspecting them when they weren't documented/exposed.
+NSString *const GPBCodedOutputStreamException_OutOfSpace = @"OutOfSpace";
+NSString *const GPBCodedOutputStreamException_WriteFailed = @"WriteFailed";
+
// Structure for containing state of a GPBCodedInputStream. Brought out into
// a struct so that we can inline several common functions instead of dealing
// with overhead of ObjC dispatch.
@@ -59,13 +64,13 @@ static const int32_t LITTLE_ENDIAN_64_SIZE = sizeof(uint64_t);
static void GPBRefreshBuffer(GPBOutputBufferState *state) {
if (state->output == nil) {
// We're writing to a single buffer.
- [NSException raise:@"OutOfSpace" format:@""];
+ [NSException raise:GPBCodedOutputStreamException_OutOfSpace format:@""];
}
if (state->position != 0) {
NSInteger written =
[state->output write:state->bytes maxLength:state->position];
if (written != (NSInteger)state->position) {
- [NSException raise:@"WriteFailed" format:@""];
+ [NSException raise:GPBCodedOutputStreamException_WriteFailed format:@""];
}
state->position = 0;
}
@@ -169,10 +174,10 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state,
data:(NSMutableData *)data {
if ((self = [super init])) {
buffer_ = [data retain];
- [output open];
state_.bytes = [data mutableBytes];
state_.size = [data length];
state_.output = [output retain];
+ [state_.output open];
}
return self;
}
diff --git a/objectivec/GPBDescriptor.m b/objectivec/GPBDescriptor.m
index 0753a948..3c3844da 100644
--- a/objectivec/GPBDescriptor.m
+++ b/objectivec/GPBDescriptor.m
@@ -1027,10 +1027,6 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) {
return GPBExtensionIsRepeated(description_);
}
-- (BOOL)isMap {
- return (description_->options & GPBFieldMapKeyMask) != 0;
-}
-
- (BOOL)isPackable {
return GPBExtensionIsPacked(description_);
}
diff --git a/objectivec/GPBDescriptor_PackagePrivate.h b/objectivec/GPBDescriptor_PackagePrivate.h
index 9173e7a2..452b3f8e 100644
--- a/objectivec/GPBDescriptor_PackagePrivate.h
+++ b/objectivec/GPBDescriptor_PackagePrivate.h
@@ -286,10 +286,6 @@ uint32_t GPBFieldTag(GPBFieldDescriptor *self);
// would be the wire type for packed.
uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self);
-GPB_INLINE BOOL GPBPreserveUnknownFields(GPBFileSyntax syntax) {
- return syntax != GPBFileSyntaxProto3;
-}
-
GPB_INLINE BOOL GPBHasPreservingUnknownEnumSemantics(GPBFileSyntax syntax) {
return syntax == GPBFileSyntaxProto3;
}
diff --git a/objectivec/GPBDictionary.h b/objectivec/GPBDictionary.h
index 4b2b9ff3..a81165e8 100644
--- a/objectivec/GPBDictionary.h
+++ b/objectivec/GPBDictionary.h
@@ -60,55 +60,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithUInt32:(uint32_t)value
- forKey:(uint32_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithUInt32s:(const uint32_t [])values
- forKeys:(const uint32_t [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBUInt32UInt32Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -117,8 +68,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithUInt32s:(const uint32_t [])values
- forKeys:(const uint32_t [])keys
+- (instancetype)initWithUInt32s:(const uint32_t [__nullable])values
+ forKeys:(const uint32_t [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -204,55 +155,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithInt32:(int32_t)value
- forKey:(uint32_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithInt32s:(const int32_t [])values
- forKeys:(const uint32_t [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBUInt32Int32Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -261,8 +163,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithInt32s:(const int32_t [])values
- forKeys:(const uint32_t [])keys
+- (instancetype)initWithInt32s:(const int32_t [__nullable])values
+ forKeys:(const uint32_t [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -348,55 +250,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithUInt64:(uint64_t)value
- forKey:(uint32_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithUInt64s:(const uint64_t [])values
- forKeys:(const uint32_t [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBUInt32UInt64Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -405,8 +258,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithUInt64s:(const uint64_t [])values
- forKeys:(const uint32_t [])keys
+- (instancetype)initWithUInt64s:(const uint64_t [__nullable])values
+ forKeys:(const uint32_t [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -492,55 +345,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithInt64:(int64_t)value
- forKey:(uint32_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithInt64s:(const int64_t [])values
- forKeys:(const uint32_t [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBUInt32Int64Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -549,8 +353,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithInt64s:(const int64_t [])values
- forKeys:(const uint32_t [])keys
+- (instancetype)initWithInt64s:(const int64_t [__nullable])values
+ forKeys:(const uint32_t [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -636,55 +440,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithBool:(BOOL)value
- forKey:(uint32_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithBools:(const BOOL [])values
- forKeys:(const uint32_t [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBUInt32BoolDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -693,8 +448,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithBools:(const BOOL [])values
- forKeys:(const uint32_t [])keys
+- (instancetype)initWithBools:(const BOOL [__nullable])values
+ forKeys:(const uint32_t [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -780,55 +535,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithFloat:(float)value
- forKey:(uint32_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithFloats:(const float [])values
- forKeys:(const uint32_t [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBUInt32FloatDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -837,8 +543,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithFloats:(const float [])values
- forKeys:(const uint32_t [])keys
+- (instancetype)initWithFloats:(const float [__nullable])values
+ forKeys:(const uint32_t [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -924,55 +630,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithDouble:(double)value
- forKey:(uint32_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithDoubles:(const double [])values
- forKeys:(const uint32_t [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBUInt32DoubleDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -981,8 +638,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithDoubles:(const double [])values
- forKeys:(const uint32_t [])keys
+- (instancetype)initWithDoubles:(const double [__nullable])values
+ forKeys:(const uint32_t [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -1070,70 +727,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) GPBEnumValidationFunc validationFunc;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given validation function.
- *
- * @param func The enum validation function for the dictionary.
- *
- * @return A newly instanced dictionary.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param func The enum validation function for the dictionary.
- * @param rawValue The raw enum value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
- rawValue:(int32_t)rawValue
- forKey:(uint32_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param func The enum validation function for the dictionary.
- * @param values The raw enum values values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
- rawValues:(const int32_t [])values
- forKeys:(const uint32_t [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBUInt32EnumDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param func The enum validation function for the dictionary.
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
- capacity:(NSUInteger)numItems;
-
-/**
* Initializes a dictionary with the given validation function.
*
* @param func The enum validation function for the dictionary.
@@ -1153,8 +746,8 @@ NS_ASSUME_NONNULL_BEGIN
* @return A newly initialized dictionary with the keys and values in it.
**/
- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func
- rawValues:(const int32_t [])values
- forKeys:(const uint32_t [])keys
+ rawValues:(const int32_t [__nullable])values
+ forKeys:(const uint32_t [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -1294,55 +887,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param object The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithObject:(ObjectType)object
- forKey:(uint32_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param objects The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithObjects:(const ObjectType GPB_UNSAFE_UNRETAINED [])objects
- forKeys:(const uint32_t [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBUInt32ObjectDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param objects The values to be placed in this dictionary.
@@ -1351,8 +895,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithObjects:(const ObjectType GPB_UNSAFE_UNRETAINED [])objects
- forKeys:(const uint32_t [])keys
+- (instancetype)initWithObjects:(const ObjectType __nonnull GPB_UNSAFE_UNRETAINED [__nullable])objects
+ forKeys:(const uint32_t [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -1437,55 +981,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithUInt32:(uint32_t)value
- forKey:(int32_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithUInt32s:(const uint32_t [])values
- forKeys:(const int32_t [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBInt32UInt32Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -1494,8 +989,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithUInt32s:(const uint32_t [])values
- forKeys:(const int32_t [])keys
+- (instancetype)initWithUInt32s:(const uint32_t [__nullable])values
+ forKeys:(const int32_t [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -1581,55 +1076,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithInt32:(int32_t)value
- forKey:(int32_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithInt32s:(const int32_t [])values
- forKeys:(const int32_t [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBInt32Int32Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -1638,8 +1084,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithInt32s:(const int32_t [])values
- forKeys:(const int32_t [])keys
+- (instancetype)initWithInt32s:(const int32_t [__nullable])values
+ forKeys:(const int32_t [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -1725,55 +1171,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithUInt64:(uint64_t)value
- forKey:(int32_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithUInt64s:(const uint64_t [])values
- forKeys:(const int32_t [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBInt32UInt64Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -1782,8 +1179,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithUInt64s:(const uint64_t [])values
- forKeys:(const int32_t [])keys
+- (instancetype)initWithUInt64s:(const uint64_t [__nullable])values
+ forKeys:(const int32_t [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -1869,55 +1266,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithInt64:(int64_t)value
- forKey:(int32_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithInt64s:(const int64_t [])values
- forKeys:(const int32_t [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBInt32Int64Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -1926,8 +1274,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithInt64s:(const int64_t [])values
- forKeys:(const int32_t [])keys
+- (instancetype)initWithInt64s:(const int64_t [__nullable])values
+ forKeys:(const int32_t [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -2013,55 +1361,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithBool:(BOOL)value
- forKey:(int32_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithBools:(const BOOL [])values
- forKeys:(const int32_t [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBInt32BoolDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -2070,8 +1369,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithBools:(const BOOL [])values
- forKeys:(const int32_t [])keys
+- (instancetype)initWithBools:(const BOOL [__nullable])values
+ forKeys:(const int32_t [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -2157,55 +1456,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithFloat:(float)value
- forKey:(int32_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithFloats:(const float [])values
- forKeys:(const int32_t [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBInt32FloatDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -2214,8 +1464,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithFloats:(const float [])values
- forKeys:(const int32_t [])keys
+- (instancetype)initWithFloats:(const float [__nullable])values
+ forKeys:(const int32_t [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -2301,55 +1551,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithDouble:(double)value
- forKey:(int32_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithDoubles:(const double [])values
- forKeys:(const int32_t [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBInt32DoubleDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -2358,8 +1559,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithDoubles:(const double [])values
- forKeys:(const int32_t [])keys
+- (instancetype)initWithDoubles:(const double [__nullable])values
+ forKeys:(const int32_t [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -2447,70 +1648,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) GPBEnumValidationFunc validationFunc;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given validation function.
- *
- * @param func The enum validation function for the dictionary.
- *
- * @return A newly instanced dictionary.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param func The enum validation function for the dictionary.
- * @param rawValue The raw enum value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
- rawValue:(int32_t)rawValue
- forKey:(int32_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param func The enum validation function for the dictionary.
- * @param values The raw enum values values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
- rawValues:(const int32_t [])values
- forKeys:(const int32_t [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBInt32EnumDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param func The enum validation function for the dictionary.
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
- capacity:(NSUInteger)numItems;
-
-/**
* Initializes a dictionary with the given validation function.
*
* @param func The enum validation function for the dictionary.
@@ -2530,8 +1667,8 @@ NS_ASSUME_NONNULL_BEGIN
* @return A newly initialized dictionary with the keys and values in it.
**/
- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func
- rawValues:(const int32_t [])values
- forKeys:(const int32_t [])keys
+ rawValues:(const int32_t [__nullable])values
+ forKeys:(const int32_t [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -2671,55 +1808,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param object The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithObject:(ObjectType)object
- forKey:(int32_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param objects The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithObjects:(const ObjectType GPB_UNSAFE_UNRETAINED [])objects
- forKeys:(const int32_t [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBInt32ObjectDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param objects The values to be placed in this dictionary.
@@ -2728,8 +1816,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithObjects:(const ObjectType GPB_UNSAFE_UNRETAINED [])objects
- forKeys:(const int32_t [])keys
+- (instancetype)initWithObjects:(const ObjectType __nonnull GPB_UNSAFE_UNRETAINED [__nullable])objects
+ forKeys:(const int32_t [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -2814,55 +1902,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithUInt32:(uint32_t)value
- forKey:(uint64_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithUInt32s:(const uint32_t [])values
- forKeys:(const uint64_t [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBUInt64UInt32Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -2871,8 +1910,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithUInt32s:(const uint32_t [])values
- forKeys:(const uint64_t [])keys
+- (instancetype)initWithUInt32s:(const uint32_t [__nullable])values
+ forKeys:(const uint64_t [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -2958,55 +1997,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithInt32:(int32_t)value
- forKey:(uint64_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithInt32s:(const int32_t [])values
- forKeys:(const uint64_t [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBUInt64Int32Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -3015,8 +2005,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithInt32s:(const int32_t [])values
- forKeys:(const uint64_t [])keys
+- (instancetype)initWithInt32s:(const int32_t [__nullable])values
+ forKeys:(const uint64_t [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -3102,55 +2092,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithUInt64:(uint64_t)value
- forKey:(uint64_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithUInt64s:(const uint64_t [])values
- forKeys:(const uint64_t [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBUInt64UInt64Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -3159,8 +2100,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithUInt64s:(const uint64_t [])values
- forKeys:(const uint64_t [])keys
+- (instancetype)initWithUInt64s:(const uint64_t [__nullable])values
+ forKeys:(const uint64_t [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -3246,55 +2187,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithInt64:(int64_t)value
- forKey:(uint64_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithInt64s:(const int64_t [])values
- forKeys:(const uint64_t [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBUInt64Int64Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -3303,8 +2195,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithInt64s:(const int64_t [])values
- forKeys:(const uint64_t [])keys
+- (instancetype)initWithInt64s:(const int64_t [__nullable])values
+ forKeys:(const uint64_t [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -3390,55 +2282,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithBool:(BOOL)value
- forKey:(uint64_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithBools:(const BOOL [])values
- forKeys:(const uint64_t [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBUInt64BoolDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -3447,8 +2290,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithBools:(const BOOL [])values
- forKeys:(const uint64_t [])keys
+- (instancetype)initWithBools:(const BOOL [__nullable])values
+ forKeys:(const uint64_t [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -3534,55 +2377,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithFloat:(float)value
- forKey:(uint64_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithFloats:(const float [])values
- forKeys:(const uint64_t [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBUInt64FloatDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -3591,8 +2385,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithFloats:(const float [])values
- forKeys:(const uint64_t [])keys
+- (instancetype)initWithFloats:(const float [__nullable])values
+ forKeys:(const uint64_t [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -3678,55 +2472,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithDouble:(double)value
- forKey:(uint64_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithDoubles:(const double [])values
- forKeys:(const uint64_t [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBUInt64DoubleDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -3735,8 +2480,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithDoubles:(const double [])values
- forKeys:(const uint64_t [])keys
+- (instancetype)initWithDoubles:(const double [__nullable])values
+ forKeys:(const uint64_t [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -3824,70 +2569,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) GPBEnumValidationFunc validationFunc;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given validation function.
- *
- * @param func The enum validation function for the dictionary.
- *
- * @return A newly instanced dictionary.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param func The enum validation function for the dictionary.
- * @param rawValue The raw enum value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
- rawValue:(int32_t)rawValue
- forKey:(uint64_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param func The enum validation function for the dictionary.
- * @param values The raw enum values values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
- rawValues:(const int32_t [])values
- forKeys:(const uint64_t [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBUInt64EnumDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param func The enum validation function for the dictionary.
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
- capacity:(NSUInteger)numItems;
-
-/**
* Initializes a dictionary with the given validation function.
*
* @param func The enum validation function for the dictionary.
@@ -3907,8 +2588,8 @@ NS_ASSUME_NONNULL_BEGIN
* @return A newly initialized dictionary with the keys and values in it.
**/
- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func
- rawValues:(const int32_t [])values
- forKeys:(const uint64_t [])keys
+ rawValues:(const int32_t [__nullable])values
+ forKeys:(const uint64_t [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -4048,55 +2729,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param object The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithObject:(ObjectType)object
- forKey:(uint64_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param objects The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithObjects:(const ObjectType GPB_UNSAFE_UNRETAINED [])objects
- forKeys:(const uint64_t [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBUInt64ObjectDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param objects The values to be placed in this dictionary.
@@ -4105,8 +2737,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithObjects:(const ObjectType GPB_UNSAFE_UNRETAINED [])objects
- forKeys:(const uint64_t [])keys
+- (instancetype)initWithObjects:(const ObjectType __nonnull GPB_UNSAFE_UNRETAINED [__nullable])objects
+ forKeys:(const uint64_t [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -4191,55 +2823,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithUInt32:(uint32_t)value
- forKey:(int64_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithUInt32s:(const uint32_t [])values
- forKeys:(const int64_t [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBInt64UInt32Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -4248,8 +2831,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithUInt32s:(const uint32_t [])values
- forKeys:(const int64_t [])keys
+- (instancetype)initWithUInt32s:(const uint32_t [__nullable])values
+ forKeys:(const int64_t [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -4335,55 +2918,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithInt32:(int32_t)value
- forKey:(int64_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithInt32s:(const int32_t [])values
- forKeys:(const int64_t [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBInt64Int32Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -4392,8 +2926,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithInt32s:(const int32_t [])values
- forKeys:(const int64_t [])keys
+- (instancetype)initWithInt32s:(const int32_t [__nullable])values
+ forKeys:(const int64_t [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -4479,55 +3013,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithUInt64:(uint64_t)value
- forKey:(int64_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithUInt64s:(const uint64_t [])values
- forKeys:(const int64_t [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBInt64UInt64Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -4536,8 +3021,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithUInt64s:(const uint64_t [])values
- forKeys:(const int64_t [])keys
+- (instancetype)initWithUInt64s:(const uint64_t [__nullable])values
+ forKeys:(const int64_t [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -4623,55 +3108,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithInt64:(int64_t)value
- forKey:(int64_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithInt64s:(const int64_t [])values
- forKeys:(const int64_t [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBInt64Int64Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -4680,8 +3116,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithInt64s:(const int64_t [])values
- forKeys:(const int64_t [])keys
+- (instancetype)initWithInt64s:(const int64_t [__nullable])values
+ forKeys:(const int64_t [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -4767,55 +3203,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithBool:(BOOL)value
- forKey:(int64_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithBools:(const BOOL [])values
- forKeys:(const int64_t [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBInt64BoolDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -4824,8 +3211,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithBools:(const BOOL [])values
- forKeys:(const int64_t [])keys
+- (instancetype)initWithBools:(const BOOL [__nullable])values
+ forKeys:(const int64_t [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -4911,55 +3298,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithFloat:(float)value
- forKey:(int64_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithFloats:(const float [])values
- forKeys:(const int64_t [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBInt64FloatDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -4968,8 +3306,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithFloats:(const float [])values
- forKeys:(const int64_t [])keys
+- (instancetype)initWithFloats:(const float [__nullable])values
+ forKeys:(const int64_t [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -5055,55 +3393,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithDouble:(double)value
- forKey:(int64_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithDoubles:(const double [])values
- forKeys:(const int64_t [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBInt64DoubleDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -5112,8 +3401,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithDoubles:(const double [])values
- forKeys:(const int64_t [])keys
+- (instancetype)initWithDoubles:(const double [__nullable])values
+ forKeys:(const int64_t [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -5201,70 +3490,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) GPBEnumValidationFunc validationFunc;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given validation function.
- *
- * @param func The enum validation function for the dictionary.
- *
- * @return A newly instanced dictionary.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param func The enum validation function for the dictionary.
- * @param rawValue The raw enum value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
- rawValue:(int32_t)rawValue
- forKey:(int64_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param func The enum validation function for the dictionary.
- * @param values The raw enum values values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
- rawValues:(const int32_t [])values
- forKeys:(const int64_t [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBInt64EnumDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param func The enum validation function for the dictionary.
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
- capacity:(NSUInteger)numItems;
-
-/**
* Initializes a dictionary with the given validation function.
*
* @param func The enum validation function for the dictionary.
@@ -5284,8 +3509,8 @@ NS_ASSUME_NONNULL_BEGIN
* @return A newly initialized dictionary with the keys and values in it.
**/
- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func
- rawValues:(const int32_t [])values
- forKeys:(const int64_t [])keys
+ rawValues:(const int32_t [__nullable])values
+ forKeys:(const int64_t [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -5425,55 +3650,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param object The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithObject:(ObjectType)object
- forKey:(int64_t)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param objects The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithObjects:(const ObjectType GPB_UNSAFE_UNRETAINED [])objects
- forKeys:(const int64_t [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBInt64ObjectDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param objects The values to be placed in this dictionary.
@@ -5482,8 +3658,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithObjects:(const ObjectType GPB_UNSAFE_UNRETAINED [])objects
- forKeys:(const int64_t [])keys
+- (instancetype)initWithObjects:(const ObjectType __nonnull GPB_UNSAFE_UNRETAINED [__nullable])objects
+ forKeys:(const int64_t [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -5568,55 +3744,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithUInt32:(uint32_t)value
- forKey:(BOOL)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithUInt32s:(const uint32_t [])values
- forKeys:(const BOOL [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBBoolUInt32Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -5625,8 +3752,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithUInt32s:(const uint32_t [])values
- forKeys:(const BOOL [])keys
+- (instancetype)initWithUInt32s:(const uint32_t [__nullable])values
+ forKeys:(const BOOL [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -5712,55 +3839,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithInt32:(int32_t)value
- forKey:(BOOL)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithInt32s:(const int32_t [])values
- forKeys:(const BOOL [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBBoolInt32Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -5769,8 +3847,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithInt32s:(const int32_t [])values
- forKeys:(const BOOL [])keys
+- (instancetype)initWithInt32s:(const int32_t [__nullable])values
+ forKeys:(const BOOL [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -5856,55 +3934,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithUInt64:(uint64_t)value
- forKey:(BOOL)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithUInt64s:(const uint64_t [])values
- forKeys:(const BOOL [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBBoolUInt64Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -5913,8 +3942,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithUInt64s:(const uint64_t [])values
- forKeys:(const BOOL [])keys
+- (instancetype)initWithUInt64s:(const uint64_t [__nullable])values
+ forKeys:(const BOOL [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -6000,55 +4029,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithInt64:(int64_t)value
- forKey:(BOOL)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithInt64s:(const int64_t [])values
- forKeys:(const BOOL [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBBoolInt64Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -6057,8 +4037,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithInt64s:(const int64_t [])values
- forKeys:(const BOOL [])keys
+- (instancetype)initWithInt64s:(const int64_t [__nullable])values
+ forKeys:(const BOOL [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -6144,55 +4124,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithBool:(BOOL)value
- forKey:(BOOL)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithBools:(const BOOL [])values
- forKeys:(const BOOL [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBBoolBoolDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -6201,8 +4132,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithBools:(const BOOL [])values
- forKeys:(const BOOL [])keys
+- (instancetype)initWithBools:(const BOOL [__nullable])values
+ forKeys:(const BOOL [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -6288,55 +4219,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithFloat:(float)value
- forKey:(BOOL)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithFloats:(const float [])values
- forKeys:(const BOOL [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBBoolFloatDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -6345,8 +4227,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithFloats:(const float [])values
- forKeys:(const BOOL [])keys
+- (instancetype)initWithFloats:(const float [__nullable])values
+ forKeys:(const BOOL [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -6432,55 +4314,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithDouble:(double)value
- forKey:(BOOL)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithDoubles:(const double [])values
- forKeys:(const BOOL [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBBoolDoubleDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -6489,8 +4322,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithDoubles:(const double [])values
- forKeys:(const BOOL [])keys
+- (instancetype)initWithDoubles:(const double [__nullable])values
+ forKeys:(const BOOL [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -6578,70 +4411,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) GPBEnumValidationFunc validationFunc;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given validation function.
- *
- * @param func The enum validation function for the dictionary.
- *
- * @return A newly instanced dictionary.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param func The enum validation function for the dictionary.
- * @param rawValue The raw enum value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
- rawValue:(int32_t)rawValue
- forKey:(BOOL)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param func The enum validation function for the dictionary.
- * @param values The raw enum values values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
- rawValues:(const int32_t [])values
- forKeys:(const BOOL [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBBoolEnumDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param func The enum validation function for the dictionary.
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
- capacity:(NSUInteger)numItems;
-
-/**
* Initializes a dictionary with the given validation function.
*
* @param func The enum validation function for the dictionary.
@@ -6661,8 +4430,8 @@ NS_ASSUME_NONNULL_BEGIN
* @return A newly initialized dictionary with the keys and values in it.
**/
- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func
- rawValues:(const int32_t [])values
- forKeys:(const BOOL [])keys
+ rawValues:(const int32_t [__nullable])values
+ forKeys:(const BOOL [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -6802,55 +4571,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param object The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithObject:(ObjectType)object
- forKey:(BOOL)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param objects The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithObjects:(const ObjectType GPB_UNSAFE_UNRETAINED [])objects
- forKeys:(const BOOL [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBBoolObjectDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param objects The values to be placed in this dictionary.
@@ -6859,8 +4579,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithObjects:(const ObjectType GPB_UNSAFE_UNRETAINED [])objects
- forKeys:(const BOOL [])keys
+- (instancetype)initWithObjects:(const ObjectType __nonnull GPB_UNSAFE_UNRETAINED [__nullable])objects
+ forKeys:(const BOOL [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -6945,55 +4665,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithUInt32:(uint32_t)value
- forKey:(NSString *)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithUInt32s:(const uint32_t [])values
- forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBStringUInt32Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -7002,8 +4673,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithUInt32s:(const uint32_t [])values
- forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys
+- (instancetype)initWithUInt32s:(const uint32_t [__nullable])values
+ forKeys:(const NSString * __nonnull GPB_UNSAFE_UNRETAINED [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -7089,55 +4760,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithInt32:(int32_t)value
- forKey:(NSString *)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithInt32s:(const int32_t [])values
- forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBStringInt32Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -7146,8 +4768,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithInt32s:(const int32_t [])values
- forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys
+- (instancetype)initWithInt32s:(const int32_t [__nullable])values
+ forKeys:(const NSString * __nonnull GPB_UNSAFE_UNRETAINED [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -7233,55 +4855,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithUInt64:(uint64_t)value
- forKey:(NSString *)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithUInt64s:(const uint64_t [])values
- forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBStringUInt64Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -7290,8 +4863,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithUInt64s:(const uint64_t [])values
- forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys
+- (instancetype)initWithUInt64s:(const uint64_t [__nullable])values
+ forKeys:(const NSString * __nonnull GPB_UNSAFE_UNRETAINED [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -7377,55 +4950,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithInt64:(int64_t)value
- forKey:(NSString *)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithInt64s:(const int64_t [])values
- forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBStringInt64Dictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -7434,8 +4958,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithInt64s:(const int64_t [])values
- forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys
+- (instancetype)initWithInt64s:(const int64_t [__nullable])values
+ forKeys:(const NSString * __nonnull GPB_UNSAFE_UNRETAINED [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -7521,55 +5045,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithBool:(BOOL)value
- forKey:(NSString *)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithBools:(const BOOL [])values
- forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBStringBoolDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -7578,8 +5053,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithBools:(const BOOL [])values
- forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys
+- (instancetype)initWithBools:(const BOOL [__nullable])values
+ forKeys:(const NSString * __nonnull GPB_UNSAFE_UNRETAINED [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -7665,55 +5140,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithFloat:(float)value
- forKey:(NSString *)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithFloats:(const float [])values
- forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBStringFloatDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -7722,8 +5148,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithFloats:(const float [])values
- forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys
+- (instancetype)initWithFloats:(const float [__nullable])values
+ forKeys:(const NSString * __nonnull GPB_UNSAFE_UNRETAINED [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -7809,55 +5235,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) NSUInteger count;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param value The value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithDouble:(double)value
- forKey:(NSString *)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param values The values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithDoubles:(const double [])values
- forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBStringDoubleDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-
-/**
* Initializes this dictionary, copying the given values and keys.
*
* @param values The values to be placed in this dictionary.
@@ -7866,8 +5243,8 @@ NS_ASSUME_NONNULL_BEGIN
*
* @return A newly initialized dictionary with a copy of the values and keys.
**/
-- (instancetype)initWithDoubles:(const double [])values
- forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys
+- (instancetype)initWithDoubles:(const double [__nullable])values
+ forKeys:(const NSString * __nonnull GPB_UNSAFE_UNRETAINED [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -7955,70 +5332,6 @@ NS_ASSUME_NONNULL_BEGIN
@property(nonatomic, readonly) GPBEnumValidationFunc validationFunc;
/**
- * @return A newly instanced and empty dictionary.
- **/
-+ (instancetype)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given validation function.
- *
- * @param func The enum validation function for the dictionary.
- *
- * @return A newly instanced dictionary.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func;
-
-/**
- * Creates and initializes a dictionary with the single entry given.
- *
- * @param func The enum validation function for the dictionary.
- * @param rawValue The raw enum value to be placed in the dictionary.
- * @param key The key under which to store the value.
- *
- * @return A newly instanced dictionary with the key and value in it.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
- rawValue:(int32_t)rawValue
- forKey:(NSString *)key;
-
-/**
- * Creates and initializes a dictionary with the entries given.
- *
- * @param func The enum validation function for the dictionary.
- * @param values The raw enum values values to be placed in the dictionary.
- * @param keys The keys under which to store the values.
- * @param count The number of entries to store in the dictionary.
- *
- * @return A newly instanced dictionary with the keys and values in it.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
- rawValues:(const int32_t [])values
- forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys
- count:(NSUInteger)count;
-
-/**
- * Creates and initializes a dictionary with the entries from the given.
- * dictionary.
- *
- * @param dictionary Dictionary containing the entries to add to the dictionary.
- *
- * @return A newly instanced dictionary with the entries from the given
- * dictionary in it.
- **/
-+ (instancetype)dictionaryWithDictionary:(GPBStringEnumDictionary *)dictionary;
-
-/**
- * Creates and initializes a dictionary with the given capacity.
- *
- * @param func The enum validation function for the dictionary.
- * @param numItems Capacity needed for the dictionary.
- *
- * @return A newly instanced dictionary with the given capacity.
- **/
-+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
- capacity:(NSUInteger)numItems;
-
-/**
* Initializes a dictionary with the given validation function.
*
* @param func The enum validation function for the dictionary.
@@ -8038,8 +5351,8 @@ NS_ASSUME_NONNULL_BEGIN
* @return A newly initialized dictionary with the keys and values in it.
**/
- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func
- rawValues:(const int32_t [])values
- forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys
+ rawValues:(const int32_t [__nullable])values
+ forKeys:(const NSString * __nonnull GPB_UNSAFE_UNRETAINED [__nullable])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
/**
@@ -8195,19 +5508,19 @@ NS_ASSUME_NONNULL_END
//%PDDM-DEFINE VALUE_FOR_KEY_POD(KEY_TYPE, VALUE_TYPE, VNAME)
//%/**
//% * Gets the value for the given key.
-//% *
+//% *
//% * @param value Pointer into which the value will be set, if found.
//% * @param key Key under which the value is stored, if present.
-//% *
+//% *
//% * @return YES if the key was found and the value was copied, NO otherwise.
//% **/
//%- (BOOL)get##VNAME##:(nullable VALUE_TYPE *)value forKey:(KEY_TYPE)key;
//%PDDM-DEFINE VALUE_FOR_KEY_OBJECT(KEY_TYPE, VALUE_TYPE, VNAME)
//%/**
//% * Fetches the object stored under the given key.
-//% *
+//% *
//% * @param key Key under which the value is stored, if present.
-//% *
+//% *
//% * @return The object if found, nil otherwise.
//% **/
//%- (VALUE_TYPE)objectForKey:(KEY_TYPE)key;
@@ -8218,7 +5531,7 @@ NS_ASSUME_NONNULL_END
//%PDDM-DEFINE ARRAY_ARG_MODIFIEREnum()
// Nothing
//%PDDM-DEFINE ARRAY_ARG_MODIFIEROBJECT()
-//%GPB_UNSAFE_UNRETAINED ##
+//%__nonnull GPB_UNSAFE_UNRETAINED ##
//%PDDM-DEFINE DICTIONARY_CLASS_DECLPOD(KEY_NAME, VALUE_NAME, VALUE_TYPE)
//%GPB##KEY_NAME##VALUE_NAME##Dictionary
//%PDDM-DEFINE DICTIONARY_CLASS_DECLEnum(KEY_NAME, VALUE_NAME, VALUE_TYPE)
@@ -8231,7 +5544,7 @@ NS_ASSUME_NONNULL_END
//%/**
//% * Class used for map fields of <##KEY_TYPE##, ##VALUE_TYPE##>
//% * values. This performs better than boxing into NSNumbers in NSDictionaries.
-//% *
+//% *
//% * @note This class is not meant to be subclassed.
//% **/
//%@interface DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) : NSObject <NSCopying>
@@ -8240,81 +5553,32 @@ NS_ASSUME_NONNULL_END
//%@property(nonatomic, readonly) NSUInteger count;
//%
//%/**
-//% * @return A newly instanced and empty dictionary.
-//% **/
-//%+ (instancetype)dictionary;
-//%
-//%/**
-//% * Creates and initializes a dictionary with the single entry given.
-//% *
-//% * @param ##VNAME_VAR The value to be placed in the dictionary.
-//% * @param key ##VNAME_VAR$S## The key under which to store the value.
-//% *
-//% * @return A newly instanced dictionary with the key and value in it.
-//% **/
-//%+ (instancetype)dictionaryWith##VNAME##:(VALUE_TYPE)##VNAME_VAR
-//% ##VNAME$S## forKey:(KEY_TYPE##KisP$S##KisP)key;
-//%
-//%/**
-//% * Creates and initializes a dictionary with the entries given.
-//% *
-//% * @param ##VNAME_VAR##s The values to be placed in the dictionary.
-//% * @param keys ##VNAME_VAR$S## The keys under which to store the values.
-//% * @param count ##VNAME_VAR$S## The number of entries to store in the dictionary.
-//% *
-//% * @return A newly instanced dictionary with the keys and values in it.
-//% **/
-//%+ (instancetype)dictionaryWith##VNAME##s:(const VALUE_TYPE ARRAY_ARG_MODIFIER##VHELPER()[])##VNAME_VAR##s
-//% ##VNAME$S## forKeys:(const KEY_TYPE##KisP$S##KisP ARRAY_ARG_MODIFIER##KHELPER()[])keys
-//% ##VNAME$S## count:(NSUInteger)count;
-//%
-//%/**
-//% * Creates and initializes a dictionary with the entries from the given.
-//% * dictionary.
-//% *
-//% * @param dictionary Dictionary containing the entries to add to the dictionary.
-//% *
-//% * @return A newly instanced dictionary with the entries from the given
-//% * dictionary in it.
-//% **/
-//%+ (instancetype)dictionaryWithDictionary:(GPB##KEY_NAME##VALUE_NAME##Dictionary *)dictionary;
-//%
-//%/**
-//% * Creates and initializes a dictionary with the given capacity.
-//% *
-//% * @param numItems Capacity needed for the dictionary.
-//% *
-//% * @return A newly instanced dictionary with the given capacity.
-//% **/
-//%+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
-//%
-//%/**
//% * Initializes this dictionary, copying the given values and keys.
-//% *
+//% *
//% * @param ##VNAME_VAR##s The values to be placed in this dictionary.
//% * @param keys ##VNAME_VAR$S## The keys under which to store the values.
//% * @param count ##VNAME_VAR$S## The number of elements to copy into the dictionary.
-//% *
+//% *
//% * @return A newly initialized dictionary with a copy of the values and keys.
//% **/
-//%- (instancetype)initWith##VNAME##s:(const VALUE_TYPE ARRAY_ARG_MODIFIER##VHELPER()[])##VNAME_VAR##s
-//% ##VNAME$S## forKeys:(const KEY_TYPE##KisP$S##KisP ARRAY_ARG_MODIFIER##KHELPER()[])keys
+//%- (instancetype)initWith##VNAME##s:(const VALUE_TYPE ARRAY_ARG_MODIFIER##VHELPER()[__nullable])##VNAME_VAR##s
+//% ##VNAME$S## forKeys:(const KEY_TYPE##KisP$S##KisP ARRAY_ARG_MODIFIER##KHELPER()[__nullable])keys
//% ##VNAME$S## count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
//%
//%/**
//% * Initializes this dictionary, copying the entries from the given dictionary.
-//% *
+//% *
//% * @param dictionary Dictionary containing the entries to add to this dictionary.
-//% *
+//% *
//% * @return A newly initialized dictionary with the entries of the given dictionary.
//% **/
//%- (instancetype)initWithDictionary:(GPB##KEY_NAME##VALUE_NAME##Dictionary *)dictionary;
//%
//%/**
//% * Initializes this dictionary with the requested capacity.
-//% *
+//% *
//% * @param numItems Number of items needed for this dictionary.
-//% *
+//% *
//% * @return A newly initialized dictionary with the requested capacity.
//% **/
//%- (instancetype)initWithCapacity:(NSUInteger)numItems;
@@ -8323,7 +5587,7 @@ NS_ASSUME_NONNULL_END
//%
//%/**
//% * Adds the keys and values from another dictionary.
-//% *
+//% *
//% * @param otherDictionary Dictionary containing entries to be added to this
//% * dictionary.
//% **/
@@ -8342,7 +5606,7 @@ NS_ASSUME_NONNULL_END
//%/**
//% * Class used for map fields of <##KEY_TYPE##, ##VALUE_TYPE##>
//% * values. This performs better than boxing into NSNumbers in NSDictionaries.
-//% *
+//% *
//% * @note This class is not meant to be subclassed.
//% **/
//%@interface GPB##KEY_NAME##VALUE_NAME##Dictionary : NSObject <NSCopying>
@@ -8353,99 +5617,35 @@ NS_ASSUME_NONNULL_END
//%@property(nonatomic, readonly) GPBEnumValidationFunc validationFunc;
//%
//%/**
-//% * @return A newly instanced and empty dictionary.
-//% **/
-//%+ (instancetype)dictionary;
-//%
-//%/**
-//% * Creates and initializes a dictionary with the given validation function.
-//% *
-//% * @param func The enum validation function for the dictionary.
-//% *
-//% * @return A newly instanced dictionary.
-//% **/
-//%+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func;
-//%
-//%/**
-//% * Creates and initializes a dictionary with the single entry given.
-//% *
-//% * @param func The enum validation function for the dictionary.
-//% * @param rawValue The raw enum value to be placed in the dictionary.
-//% * @param key The key under which to store the value.
-//% *
-//% * @return A newly instanced dictionary with the key and value in it.
-//% **/
-//%+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
-//% rawValue:(VALUE_TYPE)rawValue
-//% forKey:(KEY_TYPE##KisP$S##KisP)key;
-//%
-//%/**
-//% * Creates and initializes a dictionary with the entries given.
-//% *
-//% * @param func The enum validation function for the dictionary.
-//% * @param values The raw enum values values to be placed in the dictionary.
-//% * @param keys The keys under which to store the values.
-//% * @param count The number of entries to store in the dictionary.
-//% *
-//% * @return A newly instanced dictionary with the keys and values in it.
-//% **/
-//%+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
-//% rawValues:(const VALUE_TYPE ARRAY_ARG_MODIFIER##VHELPER()[])values
-//% forKeys:(const KEY_TYPE##KisP$S##KisP ARRAY_ARG_MODIFIER##KHELPER()[])keys
-//% count:(NSUInteger)count;
-//%
-//%/**
-//% * Creates and initializes a dictionary with the entries from the given.
-//% * dictionary.
-//% *
-//% * @param dictionary Dictionary containing the entries to add to the dictionary.
-//% *
-//% * @return A newly instanced dictionary with the entries from the given
-//% * dictionary in it.
-//% **/
-//%+ (instancetype)dictionaryWithDictionary:(GPB##KEY_NAME##VALUE_NAME##Dictionary *)dictionary;
-//%
-//%/**
-//% * Creates and initializes a dictionary with the given capacity.
-//% *
-//% * @param func The enum validation function for the dictionary.
-//% * @param numItems Capacity needed for the dictionary.
-//% *
-//% * @return A newly instanced dictionary with the given capacity.
-//% **/
-//%+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
-//% capacity:(NSUInteger)numItems;
-//%
-//%/**
//% * Initializes a dictionary with the given validation function.
-//% *
+//% *
//% * @param func The enum validation function for the dictionary.
-//% *
+//% *
//% * @return A newly initialized dictionary.
//% **/
//%- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func;
//%
//%/**
//% * Initializes a dictionary with the entries given.
-//% *
+//% *
//% * @param func The enum validation function for the dictionary.
//% * @param values The raw enum values values to be placed in the dictionary.
//% * @param keys The keys under which to store the values.
//% * @param count The number of entries to store in the dictionary.
-//% *
+//% *
//% * @return A newly initialized dictionary with the keys and values in it.
//% **/
//%- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func
-//% rawValues:(const VALUE_TYPE ARRAY_ARG_MODIFIER##VHELPER()[])values
-//% forKeys:(const KEY_TYPE##KisP$S##KisP ARRAY_ARG_MODIFIER##KHELPER()[])keys
+//% rawValues:(const VALUE_TYPE ARRAY_ARG_MODIFIER##VHELPER()[__nullable])values
+//% forKeys:(const KEY_TYPE##KisP$S##KisP ARRAY_ARG_MODIFIER##KHELPER()[__nullable])keys
//% count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
//%
//%/**
//% * Initializes a dictionary with the entries from the given.
//% * dictionary.
-//% *
+//% *
//% * @param dictionary Dictionary containing the entries to add to the dictionary.
-//% *
+//% *
//% * @return A newly initialized dictionary with the entries from the given
//% * dictionary in it.
//% **/
@@ -8453,10 +5653,10 @@ NS_ASSUME_NONNULL_END
//%
//%/**
//% * Initializes a dictionary with the given capacity.
-//% *
+//% *
//% * @param func The enum validation function for the dictionary.
//% * @param numItems Capacity needed for the dictionary.
-//% *
+//% *
//% * @return A newly initialized dictionary with the given capacity.
//% **/
//%- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func
@@ -8470,23 +5670,23 @@ NS_ASSUME_NONNULL_END
//%
//%/**
//% * Gets the raw enum value for the given key.
-//% *
+//% *
//% * @note This method bypass the validationFunc to enable the access of values that
//% * were not known at the time the binary was compiled.
-//% *
+//% *
//% * @param rawValue Pointer into which the value will be set, if found.
//% * @param key Key under which the value is stored, if present.
-//% *
+//% *
//% * @return YES if the key was found and the value was copied, NO otherwise.
//% **/
//%- (BOOL)getRawValue:(nullable VALUE_TYPE *)rawValue forKey:(KEY_TYPE##KisP$S##KisP)key;
//%
//%/**
//% * Enumerates the keys and values on this dictionary with the given block.
-//% *
+//% *
//% * @note This method bypass the validationFunc to enable the access of values that
//% * were not known at the time the binary was compiled.
-//% *
+//% *
//% * @param block The block to enumerate with.
//% * **key**: The key for the current entry.
//% * **rawValue**: The value for the current entry
@@ -8497,10 +5697,10 @@ NS_ASSUME_NONNULL_END
//%
//%/**
//% * Adds the keys and raw enum values from another dictionary.
-//% *
+//% *
//% * @note This method bypass the validationFunc to enable the setting of values that
//% * were not known at the time the binary was compiled.
-//% *
+//% *
//% * @param otherDictionary Dictionary containing entries to be added to this
//% * dictionary.
//% **/
@@ -8521,7 +5721,7 @@ NS_ASSUME_NONNULL_END
//%
//%/**
//% * Enumerates the keys and values on this dictionary with the given block.
-//% *
+//% *
//% * @param block The block to enumerate with.
//% * **key**: ##VNAME_VAR$S## The key for the current entry.
//% * **VNAME_VAR**: The value for the current entry
@@ -8533,7 +5733,7 @@ NS_ASSUME_NONNULL_END
//%PDDM-DEFINE DICTIONARY_MUTABLE_INTERFACE(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, VHELPER, VNAME, VNAME_VAR)
//%/**
//% * Sets the value for the given key.
-//% *
+//% *
//% * @param ##VNAME_VAR The value to set.
//% * @param key ##VNAME_VAR$S## The key under which to store the value.
//% **/
@@ -8541,7 +5741,7 @@ NS_ASSUME_NONNULL_END
//%DICTIONARY_EXTRA_MUTABLE_METHODS_##VHELPER(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE)
//%/**
//% * Removes the entry for the given key.
-//% *
+//% *
//% * @param aKey Key to be removed from this dictionary.
//% **/
//%- (void)remove##VNAME##ForKey:(KEY_TYPE##KisP$S##KisP)aKey;
@@ -8559,10 +5759,10 @@ NS_ASSUME_NONNULL_END
//%
//%/**
//% * Sets the raw enum value for the given key.
-//% *
+//% *
//% * @note This method bypass the validationFunc to enable the setting of values that
//% * were not known at the time the binary was compiled.
-//% *
+//% *
//% * @param rawValue The raw enum value to set.
//% * @param key The key under which to store the raw enum value.
//% **/
diff --git a/objectivec/GPBDictionary.m b/objectivec/GPBDictionary.m
index fd8bd1ce..aa21670a 100644
--- a/objectivec/GPBDictionary.m
+++ b/objectivec/GPBDictionary.m
@@ -329,13 +329,15 @@ static void WriteDictObjectField(GPBCodedOutputStream *stream, id value, uint32_
size_t GPBDictionaryComputeSizeInternalHelper(NSDictionary *dict, GPBFieldDescriptor *field) {
GPBDataType mapValueType = GPBGetFieldDataType(field);
- __block size_t result = 0;
- [dict enumerateKeysAndObjectsUsingBlock:^(NSString *key, id obj, BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSString *key;
+ NSEnumerator *keys = [dict keyEnumerator];
+ while ((key = [keys nextObject])) {
+ id obj = dict[key];
size_t msgSize = GPBComputeStringSize(kMapKeyFieldNumber, key);
msgSize += ComputeDictObjectFieldSize(obj, kMapValueFieldNumber, mapValueType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * dict.count;
return result;
@@ -347,8 +349,10 @@ void GPBDictionaryWriteToStreamInternalHelper(GPBCodedOutputStream *outputStream
NSCAssert(field.mapKeyDataType == GPBDataTypeString, @"Unexpected key type");
GPBDataType mapValueType = GPBGetFieldDataType(field);
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [dict enumerateKeysAndObjectsUsingBlock:^(NSString *key, id obj, BOOL *stop) {
- #pragma unused(stop)
+ NSString *key;
+ NSEnumerator *keys = [dict keyEnumerator];
+ while ((key = [keys nextObject])) {
+ id obj = dict[key];
// Write the tag.
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
@@ -359,14 +363,16 @@ void GPBDictionaryWriteToStreamInternalHelper(GPBCodedOutputStream *outputStream
[outputStream writeInt32NoTag:(int32_t)msgSize];
[outputStream writeString:kMapKeyFieldNumber value:key];
WriteDictObjectField(outputStream, obj, kMapValueFieldNumber, mapValueType);
- }];
+ }
}
BOOL GPBDictionaryIsInitializedInternalHelper(NSDictionary *dict, GPBFieldDescriptor *field) {
NSCAssert(field.mapKeyDataType == GPBDataTypeString, @"Unexpected key type");
NSCAssert(GPBGetFieldDataType(field) == GPBDataTypeMessage, @"Unexpected value type");
#pragma unused(field) // For when asserts are off in release.
- for (GPBMessage *msg in [dict objectEnumerator]) {
+ GPBMessage *msg;
+ NSEnumerator *objects = [dict objectEnumerator];
+ while ((msg = [objects nextObject])) {
if (!msg.initialized) {
return NO;
}
@@ -406,7 +412,7 @@ static void ReadValue(GPBCodedInputStream *stream,
valueToFill->valueInt32 = GPBCodedInputStreamReadInt32(&stream->state_);
break;
case GPBDataTypeInt64:
- valueToFill->valueInt64 = GPBCodedInputStreamReadInt32(&stream->state_);
+ valueToFill->valueInt64 = GPBCodedInputStreamReadInt64(&stream->state_);
break;
case GPBDataTypeSInt32:
valueToFill->valueInt32 = GPBCodedInputStreamReadSInt32(&stream->state_);
@@ -590,39 +596,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
//% NSMutableDictionary *_dictionary;
//%}
//%
-//%+ (instancetype)dictionary {
-//% return [[[self alloc] initWith##VNAME##s:NULL forKeys:NULL count:0] autorelease];
-//%}
-//%
-//%+ (instancetype)dictionaryWith##VNAME##:(VALUE_TYPE)##VNAME_VAR
-//% ##VNAME$S## forKey:(KEY_TYPE##KisP$S##KisP)key {
-//% // Cast is needed so the compiler knows what class we are invoking initWith##VNAME##s:forKeys:count:
-//% // on to get the type correct.
-//% return [[(GPB##KEY_NAME##VALUE_NAME##Dictionary*)[self alloc] initWith##VNAME##s:&##VNAME_VAR
-//% KEY_NAME$S VALUE_NAME$S ##VNAME$S## forKeys:&key
-//% KEY_NAME$S VALUE_NAME$S ##VNAME$S## count:1] autorelease];
-//%}
-//%
-//%+ (instancetype)dictionaryWith##VNAME##s:(const VALUE_TYPE [])##VNAME_VAR##s
-//% ##VNAME$S## forKeys:(const KEY_TYPE##KisP$S##KisP [])keys
-//% ##VNAME$S## count:(NSUInteger)count {
-//% // Cast is needed so the compiler knows what class we are invoking initWith##VNAME##s:forKeys:count:
-//% // on to get the type correct.
-//% return [[(GPB##KEY_NAME##VALUE_NAME##Dictionary*)[self alloc] initWith##VNAME##s:##VNAME_VAR##s
-//% KEY_NAME$S VALUE_NAME$S forKeys:keys
-//% KEY_NAME$S VALUE_NAME$S count:count] autorelease];
-//%}
-//%
-//%+ (instancetype)dictionaryWithDictionary:(GPB##KEY_NAME##VALUE_NAME##Dictionary *)dictionary {
-//% // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
-//% // on to get the type correct.
-//% return [[(GPB##KEY_NAME##VALUE_NAME##Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-//%}
-//%
-//%+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
-//% return [[[self alloc] initWithCapacity:numItems] autorelease];
-//%}
-//%
//%- (instancetype)init {
//% return [self initWith##VNAME##s:NULL forKeys:NULL count:0];
//%}
@@ -679,54 +652,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
//%
//%@synthesize validationFunc = _validationFunc;
//%
-//%+ (instancetype)dictionary {
-//% return [[[self alloc] initWithValidationFunction:NULL
-//% rawValues:NULL
-//% forKeys:NULL
-//% count:0] autorelease];
-//%}
-//%
-//%+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func {
-//% return [[[self alloc] initWithValidationFunction:func
-//% rawValues:NULL
-//% forKeys:NULL
-//% count:0] autorelease];
-//%}
-//%
-//%+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
-//% rawValue:(VALUE_TYPE)rawValue
-//% forKey:(KEY_TYPE##KisP$S##KisP)key {
-//% // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
-//% // on to get the type correct.
-//% return [[(GPB##KEY_NAME##VALUE_NAME##Dictionary*)[self alloc] initWithValidationFunction:func
-//% KEY_NAME$S VALUE_NAME$S rawValues:&rawValue
-//% KEY_NAME$S VALUE_NAME$S forKeys:&key
-//% KEY_NAME$S VALUE_NAME$S count:1] autorelease];
-//%}
-//%
-//%+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
-//% rawValues:(const VALUE_TYPE [])rawValues
-//% forKeys:(const KEY_TYPE##KisP$S##KisP [])keys
-//% count:(NSUInteger)count {
-//% // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
-//% // on to get the type correct.
-//% return [[(GPB##KEY_NAME##VALUE_NAME##Dictionary*)[self alloc] initWithValidationFunction:func
-//% KEY_NAME$S VALUE_NAME$S rawValues:rawValues
-//% KEY_NAME$S VALUE_NAME$S forKeys:keys
-//% KEY_NAME$S VALUE_NAME$S count:count] autorelease];
-//%}
-//%
-//%+ (instancetype)dictionaryWithDictionary:(GPB##KEY_NAME##VALUE_NAME##Dictionary *)dictionary {
-//% // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
-//% // on to get the type correct.
-//% return [[(GPB##KEY_NAME##VALUE_NAME##Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-//%}
-//%
-//%+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
-//% capacity:(NSUInteger)numItems {
-//% return [[[self alloc] initWithValidationFunction:func capacity:numItems] autorelease];
-//%}
-//%
//%- (instancetype)init {
//% return [self initWithValidationFunction:NULL rawValues:NULL forKeys:NULL count:0];
//%}
@@ -796,15 +721,20 @@ void GPBDictionaryReadEntry(id mapDictionary,
//%- (void)enumerateKeysAndEnumsUsingBlock:
//% (void (^)(KEY_TYPE KisP##key, VALUE_TYPE value, BOOL *stop))block {
//% GPBEnumValidationFunc func = _validationFunc;
-//% [_dictionary enumerateKeysAndObjectsUsingBlock:^(ENUM_TYPE##KHELPER(KEY_TYPE)##aKey,
-//% ENUM_TYPE##VHELPER(VALUE_TYPE)##aValue,
-//% BOOL *stop) {
+//% BOOL stop = NO;
+//% NSEnumerator *keys = [_dictionary keyEnumerator];
+//% ENUM_TYPE##KHELPER(KEY_TYPE)##aKey;
+//% while ((aKey = [keys nextObject])) {
+//% ENUM_TYPE##VHELPER(VALUE_TYPE)##aValue = _dictionary[aKey];
//% VALUE_TYPE unwrapped = UNWRAP##VALUE_NAME(aValue);
//% if (!func(unwrapped)) {
//% unwrapped = kGPBUnrecognizedEnumeratorValue;
//% }
-//% block(UNWRAP##KEY_NAME(aKey), unwrapped, stop);
-//% }];
+//% block(UNWRAP##KEY_NAME(aKey), unwrapped, &stop);
+//% if (stop) {
+//% break;
+//% }
+//% }
//%}
//%
//%DICTIONARY_MUTABLE_CORE2(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, KHELPER, VHELPER, Value, Enum, value, Raw)
@@ -863,30 +793,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
//%
//%- (void)enumerateKeysAnd##ACCESSOR_NAME##VNAME##sUsingBlock:
//% (void (^)(KEY_TYPE KisP##key, VALUE_TYPE VNAME_VAR, BOOL *stop))block {
-//% [_dictionary enumerateKeysAndObjectsUsingBlock:^(ENUM_TYPE##KHELPER(KEY_TYPE)##aKey,
-//% ENUM_TYPE##VHELPER(VALUE_TYPE)##a##VNAME_VAR$u,
-//% BOOL *stop) {
-//% block(UNWRAP##KEY_NAME(aKey), UNWRAP##VALUE_NAME(a##VNAME_VAR$u), stop);
-//% }];
+//% BOOL stop = NO;
+//% NSDictionary *internal = _dictionary;
+//% NSEnumerator *keys = [internal keyEnumerator];
+//% ENUM_TYPE##KHELPER(KEY_TYPE)##aKey;
+//% while ((aKey = [keys nextObject])) {
+//% ENUM_TYPE##VHELPER(VALUE_TYPE)##a##VNAME_VAR$u = internal[aKey];
+//% block(UNWRAP##KEY_NAME(aKey), UNWRAP##VALUE_NAME(a##VNAME_VAR$u), &stop);
+//% if (stop) {
+//% break;
+//% }
+//% }
//%}
//%
//%EXTRA_METHODS_##VHELPER(KEY_NAME, VALUE_NAME)- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
-//% NSUInteger count = _dictionary.count;
+//% NSDictionary *internal = _dictionary;
+//% NSUInteger count = internal.count;
//% if (count == 0) {
//% return 0;
//% }
//%
//% GPBDataType valueDataType = GPBGetFieldDataType(field);
//% GPBDataType keyDataType = field.mapKeyDataType;
-//% __block size_t result = 0;
-//% [_dictionary enumerateKeysAndObjectsUsingBlock:^(ENUM_TYPE##KHELPER(KEY_TYPE)##aKey,
-//% ENUM_TYPE##VHELPER(VALUE_TYPE)##a##VNAME_VAR$u##,
-//% BOOL *stop) {
-//% #pragma unused(stop)
+//% size_t result = 0;
+//% NSEnumerator *keys = [internal keyEnumerator];
+//% ENUM_TYPE##KHELPER(KEY_TYPE)##aKey;
+//% while ((aKey = [keys nextObject])) {
+//% ENUM_TYPE##VHELPER(VALUE_TYPE)##a##VNAME_VAR$u = internal[aKey];
//% size_t msgSize = ComputeDict##KEY_NAME##FieldSize(UNWRAP##KEY_NAME(aKey), kMapKeyFieldNumber, keyDataType);
//% msgSize += ComputeDict##VALUE_NAME##FieldSize(UNWRAP##VALUE_NAME(a##VNAME_VAR$u), kMapValueFieldNumber, valueDataType);
//% result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
-//% }];
+//% }
//% size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
//% result += tagSize * count;
//% return result;
@@ -897,20 +834,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
//% GPBDataType valueDataType = GPBGetFieldDataType(field);
//% GPBDataType keyDataType = field.mapKeyDataType;
//% uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
-//% [_dictionary enumerateKeysAndObjectsUsingBlock:^(ENUM_TYPE##KHELPER(KEY_TYPE)##aKey,
-//% ENUM_TYPE##VHELPER(VALUE_TYPE)##a##VNAME_VAR$u,
-//% BOOL *stop) {
-//% #pragma unused(stop)
-//% // Write the tag.
+//% NSDictionary *internal = _dictionary;
+//% NSEnumerator *keys = [internal keyEnumerator];
+//% ENUM_TYPE##KHELPER(KEY_TYPE)##aKey;
+//% while ((aKey = [keys nextObject])) {
+//% ENUM_TYPE##VHELPER(VALUE_TYPE)##a##VNAME_VAR$u = internal[aKey];
//% [outputStream writeInt32NoTag:tag];
//% // Write the size of the message.
-//% size_t msgSize = ComputeDict##KEY_NAME##FieldSize(UNWRAP##KEY_NAME(aKey), kMapKeyFieldNumber, keyDataType);
-//% msgSize += ComputeDict##VALUE_NAME##FieldSize(UNWRAP##VALUE_NAME(a##VNAME_VAR$u), kMapValueFieldNumber, valueDataType);
+//% KEY_TYPE KisP##unwrappedKey = UNWRAP##KEY_NAME(aKey);
+//% VALUE_TYPE unwrappedValue = UNWRAP##VALUE_NAME(a##VNAME_VAR$u);
+//% size_t msgSize = ComputeDict##KEY_NAME##FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+//% msgSize += ComputeDict##VALUE_NAME##FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
//% [outputStream writeInt32NoTag:(int32_t)msgSize];
//% // Write the fields.
-//% WriteDict##KEY_NAME##Field(outputStream, UNWRAP##KEY_NAME(aKey), kMapKeyFieldNumber, keyDataType);
-//% WriteDict##VALUE_NAME##Field(outputStream, UNWRAP##VALUE_NAME(a##VNAME_VAR$u), kMapValueFieldNumber, valueDataType);
-//% }];
+//% WriteDict##KEY_NAME##Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+//% WriteDict##VALUE_NAME##Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+//% }
//%}
//%
//%SERIAL_DATA_FOR_ENTRY_##VHELPER(KEY_NAME, VALUE_NAME)- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -968,39 +907,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
//% VALUE_TYPE _values[2];
//%BOOL_DICT_HAS_STORAGE_##HELPER()}
//%
-//%+ (instancetype)dictionary {
-//% return [[[self alloc] initWith##VNAME##s:NULL forKeys:NULL count:0] autorelease];
-//%}
-//%
-//%+ (instancetype)dictionaryWith##VNAME##:(VALUE_TYPE)VNAME_VAR
-//% ##VNAME$S## forKey:(BOOL)key {
-//% // Cast is needed so the compiler knows what class we are invoking initWith##VNAME##s:forKeys:count:
-//% // on to get the type correct.
-//% return [[(GPBBool##VALUE_NAME##Dictionary*)[self alloc] initWith##VNAME##s:&##VNAME_VAR
-//% VALUE_NAME$S ##VNAME$S## forKeys:&key
-//% VALUE_NAME$S ##VNAME$S## count:1] autorelease];
-//%}
-//%
-//%+ (instancetype)dictionaryWith##VNAME##s:(const VALUE_TYPE [])##VNAME_VAR##s
-//% ##VNAME$S## forKeys:(const BOOL [])keys
-//% ##VNAME$S## count:(NSUInteger)count {
-//% // Cast is needed so the compiler knows what class we are invoking initWith##VNAME##s:forKeys:count:
-//% // on to get the type correct.
-//% return [[(GPBBool##VALUE_NAME##Dictionary*)[self alloc] initWith##VNAME##s:##VNAME_VAR##s
-//% VALUE_NAME$S ##VNAME$S## forKeys:keys
-//% VALUE_NAME$S ##VNAME$S## count:count] autorelease];
-//%}
-//%
-//%+ (instancetype)dictionaryWithDictionary:(GPBBool##VALUE_NAME##Dictionary *)dictionary {
-//% // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
-//% // on to get the type correct.
-//% return [[(GPBBool##VALUE_NAME##Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-//%}
-//%
-//%+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
-//% return [[[self alloc] initWithCapacity:numItems] autorelease];
-//%}
-//%
//%- (instancetype)init {
//% return [self initWith##VNAME##s:NULL forKeys:NULL count:0];
//%}
@@ -1366,14 +1272,15 @@ void GPBDictionaryReadEntry(id mapDictionary,
//%- (instancetype)deepCopyWithZone:(NSZone *)zone {
//% GPB##KEY_NAME##VALUE_NAME##Dictionary *newDict =
//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] init];
-//% [_dictionary enumerateKeysAndObjectsUsingBlock:^(id aKey,
-//% GPBMessage *msg,
-//% BOOL *stop) {
-//% #pragma unused(stop)
+//% NSEnumerator *keys = [_dictionary keyEnumerator];
+//% id aKey;
+//% NSMutableDictionary *internalDict = newDict->_dictionary;
+//% while ((aKey = [keys nextObject])) {
+//% GPBMessage *msg = _dictionary[aKey];
//% GPBMessage *copiedMsg = [msg copyWithZone:zone];
-//% [newDict->_dictionary setObject:copiedMsg forKey:aKey];
+//% [internalDict setObject:copiedMsg forKey:aKey];
//% [copiedMsg release];
-//% }];
+//% }
//% return newDict;
//%}
//%
@@ -1528,39 +1435,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithUInt32s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt32:(uint32_t)value
- forKey:(uint32_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt32UInt32Dictionary*)[self alloc] initWithUInt32s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt32s:(const uint32_t [])values
- forKeys:(const uint32_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt32UInt32Dictionary*)[self alloc] initWithUInt32s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBUInt32UInt32Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBUInt32UInt32Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithUInt32s:NULL forKeys:NULL count:0];
}
@@ -1632,30 +1506,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndUInt32sUsingBlock:
(void (^)(uint32_t key, uint32_t value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block([aKey unsignedIntValue], [aValue unsignedIntValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block([aKey unsignedIntValue], [aValue unsignedIntValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictUInt32FieldSize([aValue unsignedIntValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -1666,20 +1547,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictUInt32FieldSize([aValue unsignedIntValue], kMapValueFieldNumber, valueDataType);
+ uint32_t unwrappedKey = [aKey unsignedIntValue];
+ uint32_t unwrappedValue = [aValue unsignedIntValue];
+ size_t msgSize = ComputeDictUInt32FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictUInt32FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictUInt32Field(outputStream, [aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType);
- WriteDictUInt32Field(outputStream, [aValue unsignedIntValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictUInt32Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictUInt32Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -1735,39 +1618,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithInt32s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt32:(int32_t)value
- forKey:(uint32_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt32Int32Dictionary*)[self alloc] initWithInt32s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt32s:(const int32_t [])values
- forKeys:(const uint32_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt32Int32Dictionary*)[self alloc] initWithInt32s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBUInt32Int32Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBUInt32Int32Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithInt32s:NULL forKeys:NULL count:0];
}
@@ -1839,30 +1689,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndInt32sUsingBlock:
(void (^)(uint32_t key, int32_t value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block([aKey unsignedIntValue], [aValue intValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block([aKey unsignedIntValue], [aValue intValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictInt32FieldSize([aValue intValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -1873,20 +1730,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictInt32FieldSize([aValue intValue], kMapValueFieldNumber, valueDataType);
+ uint32_t unwrappedKey = [aKey unsignedIntValue];
+ int32_t unwrappedValue = [aValue intValue];
+ size_t msgSize = ComputeDictUInt32FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictInt32FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictUInt32Field(outputStream, [aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType);
- WriteDictInt32Field(outputStream, [aValue intValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictUInt32Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictInt32Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -1942,39 +1801,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithUInt64s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt64:(uint64_t)value
- forKey:(uint32_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt32UInt64Dictionary*)[self alloc] initWithUInt64s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt64s:(const uint64_t [])values
- forKeys:(const uint32_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt32UInt64Dictionary*)[self alloc] initWithUInt64s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBUInt32UInt64Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBUInt32UInt64Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithUInt64s:NULL forKeys:NULL count:0];
}
@@ -2046,30 +1872,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndUInt64sUsingBlock:
(void (^)(uint32_t key, uint64_t value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block([aKey unsignedIntValue], [aValue unsignedLongLongValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block([aKey unsignedIntValue], [aValue unsignedLongLongValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictUInt64FieldSize([aValue unsignedLongLongValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -2080,20 +1913,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictUInt64FieldSize([aValue unsignedLongLongValue], kMapValueFieldNumber, valueDataType);
+ uint32_t unwrappedKey = [aKey unsignedIntValue];
+ uint64_t unwrappedValue = [aValue unsignedLongLongValue];
+ size_t msgSize = ComputeDictUInt32FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictUInt64FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictUInt32Field(outputStream, [aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType);
- WriteDictUInt64Field(outputStream, [aValue unsignedLongLongValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictUInt32Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictUInt64Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -2149,39 +1984,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithInt64s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt64:(int64_t)value
- forKey:(uint32_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt32Int64Dictionary*)[self alloc] initWithInt64s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt64s:(const int64_t [])values
- forKeys:(const uint32_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt32Int64Dictionary*)[self alloc] initWithInt64s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBUInt32Int64Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBUInt32Int64Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithInt64s:NULL forKeys:NULL count:0];
}
@@ -2253,30 +2055,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndInt64sUsingBlock:
(void (^)(uint32_t key, int64_t value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block([aKey unsignedIntValue], [aValue longLongValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block([aKey unsignedIntValue], [aValue longLongValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictInt64FieldSize([aValue longLongValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -2287,20 +2096,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictInt64FieldSize([aValue longLongValue], kMapValueFieldNumber, valueDataType);
+ uint32_t unwrappedKey = [aKey unsignedIntValue];
+ int64_t unwrappedValue = [aValue longLongValue];
+ size_t msgSize = ComputeDictUInt32FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictInt64FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictUInt32Field(outputStream, [aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType);
- WriteDictInt64Field(outputStream, [aValue longLongValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictUInt32Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictInt64Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -2356,39 +2167,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithBools:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithBool:(BOOL)value
- forKey:(uint32_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithBools:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt32BoolDictionary*)[self alloc] initWithBools:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithBools:(const BOOL [])values
- forKeys:(const uint32_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithBools:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt32BoolDictionary*)[self alloc] initWithBools:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBUInt32BoolDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBUInt32BoolDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithBools:NULL forKeys:NULL count:0];
}
@@ -2460,30 +2238,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndBoolsUsingBlock:
(void (^)(uint32_t key, BOOL value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block([aKey unsignedIntValue], [aValue boolValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block([aKey unsignedIntValue], [aValue boolValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictBoolFieldSize([aValue boolValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -2494,20 +2279,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictBoolFieldSize([aValue boolValue], kMapValueFieldNumber, valueDataType);
+ uint32_t unwrappedKey = [aKey unsignedIntValue];
+ BOOL unwrappedValue = [aValue boolValue];
+ size_t msgSize = ComputeDictUInt32FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictBoolFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictUInt32Field(outputStream, [aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType);
- WriteDictBoolField(outputStream, [aValue boolValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictUInt32Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictBoolField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -2563,39 +2350,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithFloats:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithFloat:(float)value
- forKey:(uint32_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithFloats:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt32FloatDictionary*)[self alloc] initWithFloats:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithFloats:(const float [])values
- forKeys:(const uint32_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithFloats:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt32FloatDictionary*)[self alloc] initWithFloats:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBUInt32FloatDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBUInt32FloatDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithFloats:NULL forKeys:NULL count:0];
}
@@ -2667,30 +2421,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndFloatsUsingBlock:
(void (^)(uint32_t key, float value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block([aKey unsignedIntValue], [aValue floatValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block([aKey unsignedIntValue], [aValue floatValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictFloatFieldSize([aValue floatValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -2701,20 +2462,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictFloatFieldSize([aValue floatValue], kMapValueFieldNumber, valueDataType);
+ uint32_t unwrappedKey = [aKey unsignedIntValue];
+ float unwrappedValue = [aValue floatValue];
+ size_t msgSize = ComputeDictUInt32FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictFloatFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictUInt32Field(outputStream, [aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType);
- WriteDictFloatField(outputStream, [aValue floatValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictUInt32Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictFloatField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -2770,39 +2533,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithDoubles:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithDouble:(double)value
- forKey:(uint32_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithDoubles:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt32DoubleDictionary*)[self alloc] initWithDoubles:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithDoubles:(const double [])values
- forKeys:(const uint32_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithDoubles:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt32DoubleDictionary*)[self alloc] initWithDoubles:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBUInt32DoubleDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBUInt32DoubleDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithDoubles:NULL forKeys:NULL count:0];
}
@@ -2874,30 +2604,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndDoublesUsingBlock:
(void (^)(uint32_t key, double value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block([aKey unsignedIntValue], [aValue doubleValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block([aKey unsignedIntValue], [aValue doubleValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictDoubleFieldSize([aValue doubleValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -2908,20 +2645,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictDoubleFieldSize([aValue doubleValue], kMapValueFieldNumber, valueDataType);
+ uint32_t unwrappedKey = [aKey unsignedIntValue];
+ double unwrappedValue = [aValue doubleValue];
+ size_t msgSize = ComputeDictUInt32FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictDoubleFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictUInt32Field(outputStream, [aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType);
- WriteDictDoubleField(outputStream, [aValue doubleValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictUInt32Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictDoubleField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -2980,54 +2719,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
@synthesize validationFunc = _validationFunc;
-+ (instancetype)dictionary {
- return [[[self alloc] initWithValidationFunction:NULL
- rawValues:NULL
- forKeys:NULL
- count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func {
- return [[[self alloc] initWithValidationFunction:func
- rawValues:NULL
- forKeys:NULL
- count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
- rawValue:(int32_t)rawValue
- forKey:(uint32_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt32EnumDictionary*)[self alloc] initWithValidationFunction:func
- rawValues:&rawValue
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
- rawValues:(const int32_t [])rawValues
- forKeys:(const uint32_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt32EnumDictionary*)[self alloc] initWithValidationFunction:func
- rawValues:rawValues
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBUInt32EnumDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt32EnumDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
- capacity:(NSUInteger)numItems {
- return [[[self alloc] initWithValidationFunction:func capacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithValidationFunction:NULL rawValues:NULL forKeys:NULL count:0];
}
@@ -3109,30 +2800,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndRawValuesUsingBlock:
(void (^)(uint32_t key, int32_t value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block([aKey unsignedIntValue], [aValue intValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block([aKey unsignedIntValue], [aValue intValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictEnumFieldSize([aValue intValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -3143,20 +2841,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictEnumFieldSize([aValue intValue], kMapValueFieldNumber, valueDataType);
+ uint32_t unwrappedKey = [aKey unsignedIntValue];
+ int32_t unwrappedValue = [aValue intValue];
+ size_t msgSize = ComputeDictUInt32FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictEnumFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictUInt32Field(outputStream, [aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType);
- WriteDictEnumField(outputStream, [aValue intValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictUInt32Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictEnumField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (NSData *)serializedDataForUnknownValue:(int32_t)value
@@ -3206,15 +2906,20 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndEnumsUsingBlock:
(void (^)(uint32_t key, int32_t value, BOOL *stop))block {
GPBEnumValidationFunc func = _validationFunc;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
+ BOOL stop = NO;
+ NSEnumerator *keys = [_dictionary keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = _dictionary[aKey];
int32_t unwrapped = [aValue intValue];
if (!func(unwrapped)) {
unwrapped = kGPBUnrecognizedEnumeratorValue;
}
- block([aKey unsignedIntValue], unwrapped, stop);
- }];
+ block([aKey unsignedIntValue], unwrapped, &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (void)addRawEntriesFromDictionary:(GPBUInt32EnumDictionary *)otherDictionary {
@@ -3263,39 +2968,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithObjects:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithObject:(id)object
- forKey:(uint32_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithObjects:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt32ObjectDictionary*)[self alloc] initWithObjects:&object
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithObjects:(const id [])objects
- forKeys:(const uint32_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithObjects:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt32ObjectDictionary*)[self alloc] initWithObjects:objects
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBUInt32ObjectDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBUInt32ObjectDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithObjects:NULL forKeys:NULL count:0];
}
@@ -3371,11 +3043,17 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndObjectsUsingBlock:
(void (^)(uint32_t key, id object, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- id aObject,
- BOOL *stop) {
- block([aKey unsignedIntValue], aObject, stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ id aObject = internal[aKey];
+ block([aKey unsignedIntValue], aObject, &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (BOOL)isInitialized {
@@ -3390,34 +3068,36 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (instancetype)deepCopyWithZone:(NSZone *)zone {
GPBUInt32ObjectDictionary *newDict =
[[GPBUInt32ObjectDictionary alloc] init];
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(id aKey,
- GPBMessage *msg,
- BOOL *stop) {
- #pragma unused(stop)
+ NSEnumerator *keys = [_dictionary keyEnumerator];
+ id aKey;
+ NSMutableDictionary *internalDict = newDict->_dictionary;
+ while ((aKey = [keys nextObject])) {
+ GPBMessage *msg = _dictionary[aKey];
GPBMessage *copiedMsg = [msg copyWithZone:zone];
- [newDict->_dictionary setObject:copiedMsg forKey:aKey];
+ [internalDict setObject:copiedMsg forKey:aKey];
[copiedMsg release];
- }];
+ }
return newDict;
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- id aObject,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ id aObject = internal[aKey];
size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictObjectFieldSize(aObject, kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -3428,20 +3108,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- id aObject,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ id aObject = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictObjectFieldSize(aObject, kMapValueFieldNumber, valueDataType);
+ uint32_t unwrappedKey = [aKey unsignedIntValue];
+ id unwrappedValue = aObject;
+ size_t msgSize = ComputeDictUInt32FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictObjectFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictUInt32Field(outputStream, [aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType);
- WriteDictObjectField(outputStream, aObject, kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictUInt32Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictObjectField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -3501,39 +3183,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithUInt32s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt32:(uint32_t)value
- forKey:(int32_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt32UInt32Dictionary*)[self alloc] initWithUInt32s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt32s:(const uint32_t [])values
- forKeys:(const int32_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt32UInt32Dictionary*)[self alloc] initWithUInt32s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBInt32UInt32Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBInt32UInt32Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithUInt32s:NULL forKeys:NULL count:0];
}
@@ -3605,30 +3254,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndUInt32sUsingBlock:
(void (^)(int32_t key, uint32_t value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block([aKey intValue], [aValue unsignedIntValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block([aKey intValue], [aValue unsignedIntValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictUInt32FieldSize([aValue unsignedIntValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -3639,20 +3295,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictUInt32FieldSize([aValue unsignedIntValue], kMapValueFieldNumber, valueDataType);
+ int32_t unwrappedKey = [aKey intValue];
+ uint32_t unwrappedValue = [aValue unsignedIntValue];
+ size_t msgSize = ComputeDictInt32FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictUInt32FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictInt32Field(outputStream, [aKey intValue], kMapKeyFieldNumber, keyDataType);
- WriteDictUInt32Field(outputStream, [aValue unsignedIntValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictInt32Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictUInt32Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -3708,39 +3366,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithInt32s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt32:(int32_t)value
- forKey:(int32_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt32Int32Dictionary*)[self alloc] initWithInt32s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt32s:(const int32_t [])values
- forKeys:(const int32_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt32Int32Dictionary*)[self alloc] initWithInt32s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBInt32Int32Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBInt32Int32Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithInt32s:NULL forKeys:NULL count:0];
}
@@ -3812,30 +3437,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndInt32sUsingBlock:
(void (^)(int32_t key, int32_t value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block([aKey intValue], [aValue intValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block([aKey intValue], [aValue intValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictInt32FieldSize([aValue intValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -3846,20 +3478,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictInt32FieldSize([aValue intValue], kMapValueFieldNumber, valueDataType);
+ int32_t unwrappedKey = [aKey intValue];
+ int32_t unwrappedValue = [aValue intValue];
+ size_t msgSize = ComputeDictInt32FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictInt32FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictInt32Field(outputStream, [aKey intValue], kMapKeyFieldNumber, keyDataType);
- WriteDictInt32Field(outputStream, [aValue intValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictInt32Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictInt32Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -3915,39 +3549,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithUInt64s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt64:(uint64_t)value
- forKey:(int32_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt32UInt64Dictionary*)[self alloc] initWithUInt64s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt64s:(const uint64_t [])values
- forKeys:(const int32_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt32UInt64Dictionary*)[self alloc] initWithUInt64s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBInt32UInt64Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBInt32UInt64Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithUInt64s:NULL forKeys:NULL count:0];
}
@@ -4019,30 +3620,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndUInt64sUsingBlock:
(void (^)(int32_t key, uint64_t value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block([aKey intValue], [aValue unsignedLongLongValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block([aKey intValue], [aValue unsignedLongLongValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictUInt64FieldSize([aValue unsignedLongLongValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -4053,20 +3661,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictUInt64FieldSize([aValue unsignedLongLongValue], kMapValueFieldNumber, valueDataType);
+ int32_t unwrappedKey = [aKey intValue];
+ uint64_t unwrappedValue = [aValue unsignedLongLongValue];
+ size_t msgSize = ComputeDictInt32FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictUInt64FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictInt32Field(outputStream, [aKey intValue], kMapKeyFieldNumber, keyDataType);
- WriteDictUInt64Field(outputStream, [aValue unsignedLongLongValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictInt32Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictUInt64Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -4122,39 +3732,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithInt64s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt64:(int64_t)value
- forKey:(int32_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt32Int64Dictionary*)[self alloc] initWithInt64s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt64s:(const int64_t [])values
- forKeys:(const int32_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt32Int64Dictionary*)[self alloc] initWithInt64s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBInt32Int64Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBInt32Int64Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithInt64s:NULL forKeys:NULL count:0];
}
@@ -4226,30 +3803,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndInt64sUsingBlock:
(void (^)(int32_t key, int64_t value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block([aKey intValue], [aValue longLongValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block([aKey intValue], [aValue longLongValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictInt64FieldSize([aValue longLongValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -4260,20 +3844,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictInt64FieldSize([aValue longLongValue], kMapValueFieldNumber, valueDataType);
+ int32_t unwrappedKey = [aKey intValue];
+ int64_t unwrappedValue = [aValue longLongValue];
+ size_t msgSize = ComputeDictInt32FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictInt64FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictInt32Field(outputStream, [aKey intValue], kMapKeyFieldNumber, keyDataType);
- WriteDictInt64Field(outputStream, [aValue longLongValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictInt32Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictInt64Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -4329,39 +3915,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithBools:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithBool:(BOOL)value
- forKey:(int32_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithBools:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt32BoolDictionary*)[self alloc] initWithBools:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithBools:(const BOOL [])values
- forKeys:(const int32_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithBools:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt32BoolDictionary*)[self alloc] initWithBools:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBInt32BoolDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBInt32BoolDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithBools:NULL forKeys:NULL count:0];
}
@@ -4433,30 +3986,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndBoolsUsingBlock:
(void (^)(int32_t key, BOOL value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block([aKey intValue], [aValue boolValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block([aKey intValue], [aValue boolValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictBoolFieldSize([aValue boolValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -4467,20 +4027,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictBoolFieldSize([aValue boolValue], kMapValueFieldNumber, valueDataType);
+ int32_t unwrappedKey = [aKey intValue];
+ BOOL unwrappedValue = [aValue boolValue];
+ size_t msgSize = ComputeDictInt32FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictBoolFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictInt32Field(outputStream, [aKey intValue], kMapKeyFieldNumber, keyDataType);
- WriteDictBoolField(outputStream, [aValue boolValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictInt32Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictBoolField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -4536,39 +4098,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithFloats:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithFloat:(float)value
- forKey:(int32_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithFloats:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt32FloatDictionary*)[self alloc] initWithFloats:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithFloats:(const float [])values
- forKeys:(const int32_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithFloats:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt32FloatDictionary*)[self alloc] initWithFloats:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBInt32FloatDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBInt32FloatDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithFloats:NULL forKeys:NULL count:0];
}
@@ -4640,30 +4169,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndFloatsUsingBlock:
(void (^)(int32_t key, float value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block([aKey intValue], [aValue floatValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block([aKey intValue], [aValue floatValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictFloatFieldSize([aValue floatValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -4674,20 +4210,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictFloatFieldSize([aValue floatValue], kMapValueFieldNumber, valueDataType);
+ int32_t unwrappedKey = [aKey intValue];
+ float unwrappedValue = [aValue floatValue];
+ size_t msgSize = ComputeDictInt32FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictFloatFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictInt32Field(outputStream, [aKey intValue], kMapKeyFieldNumber, keyDataType);
- WriteDictFloatField(outputStream, [aValue floatValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictInt32Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictFloatField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -4743,39 +4281,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithDoubles:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithDouble:(double)value
- forKey:(int32_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithDoubles:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt32DoubleDictionary*)[self alloc] initWithDoubles:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithDoubles:(const double [])values
- forKeys:(const int32_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithDoubles:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt32DoubleDictionary*)[self alloc] initWithDoubles:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBInt32DoubleDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBInt32DoubleDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithDoubles:NULL forKeys:NULL count:0];
}
@@ -4847,30 +4352,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndDoublesUsingBlock:
(void (^)(int32_t key, double value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block([aKey intValue], [aValue doubleValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block([aKey intValue], [aValue doubleValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictDoubleFieldSize([aValue doubleValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -4881,20 +4393,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictDoubleFieldSize([aValue doubleValue], kMapValueFieldNumber, valueDataType);
+ int32_t unwrappedKey = [aKey intValue];
+ double unwrappedValue = [aValue doubleValue];
+ size_t msgSize = ComputeDictInt32FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictDoubleFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictInt32Field(outputStream, [aKey intValue], kMapKeyFieldNumber, keyDataType);
- WriteDictDoubleField(outputStream, [aValue doubleValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictInt32Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictDoubleField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -4953,54 +4467,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
@synthesize validationFunc = _validationFunc;
-+ (instancetype)dictionary {
- return [[[self alloc] initWithValidationFunction:NULL
- rawValues:NULL
- forKeys:NULL
- count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func {
- return [[[self alloc] initWithValidationFunction:func
- rawValues:NULL
- forKeys:NULL
- count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
- rawValue:(int32_t)rawValue
- forKey:(int32_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt32EnumDictionary*)[self alloc] initWithValidationFunction:func
- rawValues:&rawValue
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
- rawValues:(const int32_t [])rawValues
- forKeys:(const int32_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt32EnumDictionary*)[self alloc] initWithValidationFunction:func
- rawValues:rawValues
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBInt32EnumDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt32EnumDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
- capacity:(NSUInteger)numItems {
- return [[[self alloc] initWithValidationFunction:func capacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithValidationFunction:NULL rawValues:NULL forKeys:NULL count:0];
}
@@ -5082,30 +4548,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndRawValuesUsingBlock:
(void (^)(int32_t key, int32_t value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block([aKey intValue], [aValue intValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block([aKey intValue], [aValue intValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictEnumFieldSize([aValue intValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -5116,20 +4589,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictEnumFieldSize([aValue intValue], kMapValueFieldNumber, valueDataType);
+ int32_t unwrappedKey = [aKey intValue];
+ int32_t unwrappedValue = [aValue intValue];
+ size_t msgSize = ComputeDictInt32FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictEnumFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictInt32Field(outputStream, [aKey intValue], kMapKeyFieldNumber, keyDataType);
- WriteDictEnumField(outputStream, [aValue intValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictInt32Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictEnumField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (NSData *)serializedDataForUnknownValue:(int32_t)value
@@ -5179,15 +4654,20 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndEnumsUsingBlock:
(void (^)(int32_t key, int32_t value, BOOL *stop))block {
GPBEnumValidationFunc func = _validationFunc;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
+ BOOL stop = NO;
+ NSEnumerator *keys = [_dictionary keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = _dictionary[aKey];
int32_t unwrapped = [aValue intValue];
if (!func(unwrapped)) {
unwrapped = kGPBUnrecognizedEnumeratorValue;
}
- block([aKey intValue], unwrapped, stop);
- }];
+ block([aKey intValue], unwrapped, &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (void)addRawEntriesFromDictionary:(GPBInt32EnumDictionary *)otherDictionary {
@@ -5236,39 +4716,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithObjects:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithObject:(id)object
- forKey:(int32_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithObjects:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt32ObjectDictionary*)[self alloc] initWithObjects:&object
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithObjects:(const id [])objects
- forKeys:(const int32_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithObjects:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt32ObjectDictionary*)[self alloc] initWithObjects:objects
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBInt32ObjectDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBInt32ObjectDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithObjects:NULL forKeys:NULL count:0];
}
@@ -5344,11 +4791,17 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndObjectsUsingBlock:
(void (^)(int32_t key, id object, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- id aObject,
- BOOL *stop) {
- block([aKey intValue], aObject, stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ id aObject = internal[aKey];
+ block([aKey intValue], aObject, &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (BOOL)isInitialized {
@@ -5363,34 +4816,36 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (instancetype)deepCopyWithZone:(NSZone *)zone {
GPBInt32ObjectDictionary *newDict =
[[GPBInt32ObjectDictionary alloc] init];
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(id aKey,
- GPBMessage *msg,
- BOOL *stop) {
- #pragma unused(stop)
+ NSEnumerator *keys = [_dictionary keyEnumerator];
+ id aKey;
+ NSMutableDictionary *internalDict = newDict->_dictionary;
+ while ((aKey = [keys nextObject])) {
+ GPBMessage *msg = _dictionary[aKey];
GPBMessage *copiedMsg = [msg copyWithZone:zone];
- [newDict->_dictionary setObject:copiedMsg forKey:aKey];
+ [internalDict setObject:copiedMsg forKey:aKey];
[copiedMsg release];
- }];
+ }
return newDict;
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- id aObject,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ id aObject = internal[aKey];
size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictObjectFieldSize(aObject, kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -5401,20 +4856,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- id aObject,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ id aObject = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictObjectFieldSize(aObject, kMapValueFieldNumber, valueDataType);
+ int32_t unwrappedKey = [aKey intValue];
+ id unwrappedValue = aObject;
+ size_t msgSize = ComputeDictInt32FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictObjectFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictInt32Field(outputStream, [aKey intValue], kMapKeyFieldNumber, keyDataType);
- WriteDictObjectField(outputStream, aObject, kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictInt32Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictObjectField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -5474,39 +4931,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithUInt32s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt32:(uint32_t)value
- forKey:(uint64_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt64UInt32Dictionary*)[self alloc] initWithUInt32s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt32s:(const uint32_t [])values
- forKeys:(const uint64_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt64UInt32Dictionary*)[self alloc] initWithUInt32s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBUInt64UInt32Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBUInt64UInt32Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithUInt32s:NULL forKeys:NULL count:0];
}
@@ -5578,30 +5002,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndUInt32sUsingBlock:
(void (^)(uint64_t key, uint32_t value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block([aKey unsignedLongLongValue], [aValue unsignedIntValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block([aKey unsignedLongLongValue], [aValue unsignedIntValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictUInt32FieldSize([aValue unsignedIntValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -5612,20 +5043,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictUInt32FieldSize([aValue unsignedIntValue], kMapValueFieldNumber, valueDataType);
+ uint64_t unwrappedKey = [aKey unsignedLongLongValue];
+ uint32_t unwrappedValue = [aValue unsignedIntValue];
+ size_t msgSize = ComputeDictUInt64FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictUInt32FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictUInt64Field(outputStream, [aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType);
- WriteDictUInt32Field(outputStream, [aValue unsignedIntValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictUInt64Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictUInt32Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -5681,39 +5114,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithInt32s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt32:(int32_t)value
- forKey:(uint64_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt64Int32Dictionary*)[self alloc] initWithInt32s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt32s:(const int32_t [])values
- forKeys:(const uint64_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt64Int32Dictionary*)[self alloc] initWithInt32s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBUInt64Int32Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBUInt64Int32Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithInt32s:NULL forKeys:NULL count:0];
}
@@ -5785,30 +5185,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndInt32sUsingBlock:
(void (^)(uint64_t key, int32_t value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block([aKey unsignedLongLongValue], [aValue intValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block([aKey unsignedLongLongValue], [aValue intValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictInt32FieldSize([aValue intValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -5819,20 +5226,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictInt32FieldSize([aValue intValue], kMapValueFieldNumber, valueDataType);
+ uint64_t unwrappedKey = [aKey unsignedLongLongValue];
+ int32_t unwrappedValue = [aValue intValue];
+ size_t msgSize = ComputeDictUInt64FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictInt32FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictUInt64Field(outputStream, [aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType);
- WriteDictInt32Field(outputStream, [aValue intValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictUInt64Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictInt32Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -5888,39 +5297,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithUInt64s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt64:(uint64_t)value
- forKey:(uint64_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt64UInt64Dictionary*)[self alloc] initWithUInt64s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt64s:(const uint64_t [])values
- forKeys:(const uint64_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt64UInt64Dictionary*)[self alloc] initWithUInt64s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBUInt64UInt64Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBUInt64UInt64Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithUInt64s:NULL forKeys:NULL count:0];
}
@@ -5992,30 +5368,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndUInt64sUsingBlock:
(void (^)(uint64_t key, uint64_t value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block([aKey unsignedLongLongValue], [aValue unsignedLongLongValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block([aKey unsignedLongLongValue], [aValue unsignedLongLongValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictUInt64FieldSize([aValue unsignedLongLongValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -6026,20 +5409,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictUInt64FieldSize([aValue unsignedLongLongValue], kMapValueFieldNumber, valueDataType);
+ uint64_t unwrappedKey = [aKey unsignedLongLongValue];
+ uint64_t unwrappedValue = [aValue unsignedLongLongValue];
+ size_t msgSize = ComputeDictUInt64FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictUInt64FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictUInt64Field(outputStream, [aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType);
- WriteDictUInt64Field(outputStream, [aValue unsignedLongLongValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictUInt64Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictUInt64Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -6095,39 +5480,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithInt64s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt64:(int64_t)value
- forKey:(uint64_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt64Int64Dictionary*)[self alloc] initWithInt64s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt64s:(const int64_t [])values
- forKeys:(const uint64_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt64Int64Dictionary*)[self alloc] initWithInt64s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBUInt64Int64Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBUInt64Int64Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithInt64s:NULL forKeys:NULL count:0];
}
@@ -6199,30 +5551,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndInt64sUsingBlock:
(void (^)(uint64_t key, int64_t value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block([aKey unsignedLongLongValue], [aValue longLongValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block([aKey unsignedLongLongValue], [aValue longLongValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictInt64FieldSize([aValue longLongValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -6233,20 +5592,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictInt64FieldSize([aValue longLongValue], kMapValueFieldNumber, valueDataType);
+ uint64_t unwrappedKey = [aKey unsignedLongLongValue];
+ int64_t unwrappedValue = [aValue longLongValue];
+ size_t msgSize = ComputeDictUInt64FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictInt64FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictUInt64Field(outputStream, [aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType);
- WriteDictInt64Field(outputStream, [aValue longLongValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictUInt64Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictInt64Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -6302,39 +5663,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithBools:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithBool:(BOOL)value
- forKey:(uint64_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithBools:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt64BoolDictionary*)[self alloc] initWithBools:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithBools:(const BOOL [])values
- forKeys:(const uint64_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithBools:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt64BoolDictionary*)[self alloc] initWithBools:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBUInt64BoolDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBUInt64BoolDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithBools:NULL forKeys:NULL count:0];
}
@@ -6406,30 +5734,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndBoolsUsingBlock:
(void (^)(uint64_t key, BOOL value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block([aKey unsignedLongLongValue], [aValue boolValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block([aKey unsignedLongLongValue], [aValue boolValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictBoolFieldSize([aValue boolValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -6440,20 +5775,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictBoolFieldSize([aValue boolValue], kMapValueFieldNumber, valueDataType);
+ uint64_t unwrappedKey = [aKey unsignedLongLongValue];
+ BOOL unwrappedValue = [aValue boolValue];
+ size_t msgSize = ComputeDictUInt64FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictBoolFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictUInt64Field(outputStream, [aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType);
- WriteDictBoolField(outputStream, [aValue boolValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictUInt64Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictBoolField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -6509,39 +5846,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithFloats:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithFloat:(float)value
- forKey:(uint64_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithFloats:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt64FloatDictionary*)[self alloc] initWithFloats:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithFloats:(const float [])values
- forKeys:(const uint64_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithFloats:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt64FloatDictionary*)[self alloc] initWithFloats:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBUInt64FloatDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBUInt64FloatDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithFloats:NULL forKeys:NULL count:0];
}
@@ -6613,30 +5917,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndFloatsUsingBlock:
(void (^)(uint64_t key, float value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block([aKey unsignedLongLongValue], [aValue floatValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block([aKey unsignedLongLongValue], [aValue floatValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictFloatFieldSize([aValue floatValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -6647,20 +5958,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictFloatFieldSize([aValue floatValue], kMapValueFieldNumber, valueDataType);
+ uint64_t unwrappedKey = [aKey unsignedLongLongValue];
+ float unwrappedValue = [aValue floatValue];
+ size_t msgSize = ComputeDictUInt64FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictFloatFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictUInt64Field(outputStream, [aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType);
- WriteDictFloatField(outputStream, [aValue floatValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictUInt64Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictFloatField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -6716,39 +6029,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithDoubles:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithDouble:(double)value
- forKey:(uint64_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithDoubles:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt64DoubleDictionary*)[self alloc] initWithDoubles:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithDoubles:(const double [])values
- forKeys:(const uint64_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithDoubles:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt64DoubleDictionary*)[self alloc] initWithDoubles:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBUInt64DoubleDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBUInt64DoubleDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithDoubles:NULL forKeys:NULL count:0];
}
@@ -6820,30 +6100,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndDoublesUsingBlock:
(void (^)(uint64_t key, double value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block([aKey unsignedLongLongValue], [aValue doubleValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block([aKey unsignedLongLongValue], [aValue doubleValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictDoubleFieldSize([aValue doubleValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -6854,20 +6141,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictDoubleFieldSize([aValue doubleValue], kMapValueFieldNumber, valueDataType);
+ uint64_t unwrappedKey = [aKey unsignedLongLongValue];
+ double unwrappedValue = [aValue doubleValue];
+ size_t msgSize = ComputeDictUInt64FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictDoubleFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictUInt64Field(outputStream, [aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType);
- WriteDictDoubleField(outputStream, [aValue doubleValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictUInt64Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictDoubleField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -6926,54 +6215,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
@synthesize validationFunc = _validationFunc;
-+ (instancetype)dictionary {
- return [[[self alloc] initWithValidationFunction:NULL
- rawValues:NULL
- forKeys:NULL
- count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func {
- return [[[self alloc] initWithValidationFunction:func
- rawValues:NULL
- forKeys:NULL
- count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
- rawValue:(int32_t)rawValue
- forKey:(uint64_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt64EnumDictionary*)[self alloc] initWithValidationFunction:func
- rawValues:&rawValue
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
- rawValues:(const int32_t [])rawValues
- forKeys:(const uint64_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt64EnumDictionary*)[self alloc] initWithValidationFunction:func
- rawValues:rawValues
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBUInt64EnumDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt64EnumDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
- capacity:(NSUInteger)numItems {
- return [[[self alloc] initWithValidationFunction:func capacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithValidationFunction:NULL rawValues:NULL forKeys:NULL count:0];
}
@@ -7055,30 +6296,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndRawValuesUsingBlock:
(void (^)(uint64_t key, int32_t value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block([aKey unsignedLongLongValue], [aValue intValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block([aKey unsignedLongLongValue], [aValue intValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictEnumFieldSize([aValue intValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -7089,20 +6337,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictEnumFieldSize([aValue intValue], kMapValueFieldNumber, valueDataType);
+ uint64_t unwrappedKey = [aKey unsignedLongLongValue];
+ int32_t unwrappedValue = [aValue intValue];
+ size_t msgSize = ComputeDictUInt64FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictEnumFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictUInt64Field(outputStream, [aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType);
- WriteDictEnumField(outputStream, [aValue intValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictUInt64Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictEnumField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (NSData *)serializedDataForUnknownValue:(int32_t)value
@@ -7152,15 +6402,20 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndEnumsUsingBlock:
(void (^)(uint64_t key, int32_t value, BOOL *stop))block {
GPBEnumValidationFunc func = _validationFunc;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
+ BOOL stop = NO;
+ NSEnumerator *keys = [_dictionary keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = _dictionary[aKey];
int32_t unwrapped = [aValue intValue];
if (!func(unwrapped)) {
unwrapped = kGPBUnrecognizedEnumeratorValue;
}
- block([aKey unsignedLongLongValue], unwrapped, stop);
- }];
+ block([aKey unsignedLongLongValue], unwrapped, &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (void)addRawEntriesFromDictionary:(GPBUInt64EnumDictionary *)otherDictionary {
@@ -7209,39 +6464,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithObjects:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithObject:(id)object
- forKey:(uint64_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithObjects:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt64ObjectDictionary*)[self alloc] initWithObjects:&object
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithObjects:(const id [])objects
- forKeys:(const uint64_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithObjects:forKeys:count:
- // on to get the type correct.
- return [[(GPBUInt64ObjectDictionary*)[self alloc] initWithObjects:objects
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBUInt64ObjectDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBUInt64ObjectDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithObjects:NULL forKeys:NULL count:0];
}
@@ -7317,11 +6539,17 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndObjectsUsingBlock:
(void (^)(uint64_t key, id object, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- id aObject,
- BOOL *stop) {
- block([aKey unsignedLongLongValue], aObject, stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ id aObject = internal[aKey];
+ block([aKey unsignedLongLongValue], aObject, &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (BOOL)isInitialized {
@@ -7336,34 +6564,36 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (instancetype)deepCopyWithZone:(NSZone *)zone {
GPBUInt64ObjectDictionary *newDict =
[[GPBUInt64ObjectDictionary alloc] init];
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(id aKey,
- GPBMessage *msg,
- BOOL *stop) {
- #pragma unused(stop)
+ NSEnumerator *keys = [_dictionary keyEnumerator];
+ id aKey;
+ NSMutableDictionary *internalDict = newDict->_dictionary;
+ while ((aKey = [keys nextObject])) {
+ GPBMessage *msg = _dictionary[aKey];
GPBMessage *copiedMsg = [msg copyWithZone:zone];
- [newDict->_dictionary setObject:copiedMsg forKey:aKey];
+ [internalDict setObject:copiedMsg forKey:aKey];
[copiedMsg release];
- }];
+ }
return newDict;
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- id aObject,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ id aObject = internal[aKey];
size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictObjectFieldSize(aObject, kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -7374,20 +6604,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- id aObject,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ id aObject = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictObjectFieldSize(aObject, kMapValueFieldNumber, valueDataType);
+ uint64_t unwrappedKey = [aKey unsignedLongLongValue];
+ id unwrappedValue = aObject;
+ size_t msgSize = ComputeDictUInt64FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictObjectFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictUInt64Field(outputStream, [aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType);
- WriteDictObjectField(outputStream, aObject, kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictUInt64Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictObjectField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -7447,39 +6679,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithUInt32s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt32:(uint32_t)value
- forKey:(int64_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt64UInt32Dictionary*)[self alloc] initWithUInt32s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt32s:(const uint32_t [])values
- forKeys:(const int64_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt64UInt32Dictionary*)[self alloc] initWithUInt32s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBInt64UInt32Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBInt64UInt32Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithUInt32s:NULL forKeys:NULL count:0];
}
@@ -7551,30 +6750,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndUInt32sUsingBlock:
(void (^)(int64_t key, uint32_t value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block([aKey longLongValue], [aValue unsignedIntValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block([aKey longLongValue], [aValue unsignedIntValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictUInt32FieldSize([aValue unsignedIntValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -7585,20 +6791,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictUInt32FieldSize([aValue unsignedIntValue], kMapValueFieldNumber, valueDataType);
+ int64_t unwrappedKey = [aKey longLongValue];
+ uint32_t unwrappedValue = [aValue unsignedIntValue];
+ size_t msgSize = ComputeDictInt64FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictUInt32FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictInt64Field(outputStream, [aKey longLongValue], kMapKeyFieldNumber, keyDataType);
- WriteDictUInt32Field(outputStream, [aValue unsignedIntValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictInt64Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictUInt32Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -7654,39 +6862,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithInt32s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt32:(int32_t)value
- forKey:(int64_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt64Int32Dictionary*)[self alloc] initWithInt32s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt32s:(const int32_t [])values
- forKeys:(const int64_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt64Int32Dictionary*)[self alloc] initWithInt32s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBInt64Int32Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBInt64Int32Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithInt32s:NULL forKeys:NULL count:0];
}
@@ -7758,30 +6933,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndInt32sUsingBlock:
(void (^)(int64_t key, int32_t value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block([aKey longLongValue], [aValue intValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block([aKey longLongValue], [aValue intValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictInt32FieldSize([aValue intValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -7792,20 +6974,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictInt32FieldSize([aValue intValue], kMapValueFieldNumber, valueDataType);
+ int64_t unwrappedKey = [aKey longLongValue];
+ int32_t unwrappedValue = [aValue intValue];
+ size_t msgSize = ComputeDictInt64FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictInt32FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictInt64Field(outputStream, [aKey longLongValue], kMapKeyFieldNumber, keyDataType);
- WriteDictInt32Field(outputStream, [aValue intValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictInt64Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictInt32Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -7861,39 +7045,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithUInt64s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt64:(uint64_t)value
- forKey:(int64_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt64UInt64Dictionary*)[self alloc] initWithUInt64s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt64s:(const uint64_t [])values
- forKeys:(const int64_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt64UInt64Dictionary*)[self alloc] initWithUInt64s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBInt64UInt64Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBInt64UInt64Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithUInt64s:NULL forKeys:NULL count:0];
}
@@ -7965,30 +7116,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndUInt64sUsingBlock:
(void (^)(int64_t key, uint64_t value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block([aKey longLongValue], [aValue unsignedLongLongValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block([aKey longLongValue], [aValue unsignedLongLongValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictUInt64FieldSize([aValue unsignedLongLongValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -7999,20 +7157,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictUInt64FieldSize([aValue unsignedLongLongValue], kMapValueFieldNumber, valueDataType);
+ int64_t unwrappedKey = [aKey longLongValue];
+ uint64_t unwrappedValue = [aValue unsignedLongLongValue];
+ size_t msgSize = ComputeDictInt64FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictUInt64FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictInt64Field(outputStream, [aKey longLongValue], kMapKeyFieldNumber, keyDataType);
- WriteDictUInt64Field(outputStream, [aValue unsignedLongLongValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictInt64Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictUInt64Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -8068,39 +7228,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithInt64s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt64:(int64_t)value
- forKey:(int64_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt64Int64Dictionary*)[self alloc] initWithInt64s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt64s:(const int64_t [])values
- forKeys:(const int64_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt64Int64Dictionary*)[self alloc] initWithInt64s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBInt64Int64Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBInt64Int64Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithInt64s:NULL forKeys:NULL count:0];
}
@@ -8172,30 +7299,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndInt64sUsingBlock:
(void (^)(int64_t key, int64_t value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block([aKey longLongValue], [aValue longLongValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block([aKey longLongValue], [aValue longLongValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictInt64FieldSize([aValue longLongValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -8206,20 +7340,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictInt64FieldSize([aValue longLongValue], kMapValueFieldNumber, valueDataType);
+ int64_t unwrappedKey = [aKey longLongValue];
+ int64_t unwrappedValue = [aValue longLongValue];
+ size_t msgSize = ComputeDictInt64FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictInt64FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictInt64Field(outputStream, [aKey longLongValue], kMapKeyFieldNumber, keyDataType);
- WriteDictInt64Field(outputStream, [aValue longLongValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictInt64Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictInt64Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -8275,39 +7411,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithBools:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithBool:(BOOL)value
- forKey:(int64_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithBools:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt64BoolDictionary*)[self alloc] initWithBools:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithBools:(const BOOL [])values
- forKeys:(const int64_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithBools:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt64BoolDictionary*)[self alloc] initWithBools:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBInt64BoolDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBInt64BoolDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithBools:NULL forKeys:NULL count:0];
}
@@ -8379,30 +7482,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndBoolsUsingBlock:
(void (^)(int64_t key, BOOL value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block([aKey longLongValue], [aValue boolValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block([aKey longLongValue], [aValue boolValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictBoolFieldSize([aValue boolValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -8413,20 +7523,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictBoolFieldSize([aValue boolValue], kMapValueFieldNumber, valueDataType);
+ int64_t unwrappedKey = [aKey longLongValue];
+ BOOL unwrappedValue = [aValue boolValue];
+ size_t msgSize = ComputeDictInt64FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictBoolFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictInt64Field(outputStream, [aKey longLongValue], kMapKeyFieldNumber, keyDataType);
- WriteDictBoolField(outputStream, [aValue boolValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictInt64Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictBoolField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -8482,39 +7594,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithFloats:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithFloat:(float)value
- forKey:(int64_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithFloats:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt64FloatDictionary*)[self alloc] initWithFloats:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithFloats:(const float [])values
- forKeys:(const int64_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithFloats:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt64FloatDictionary*)[self alloc] initWithFloats:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBInt64FloatDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBInt64FloatDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithFloats:NULL forKeys:NULL count:0];
}
@@ -8586,30 +7665,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndFloatsUsingBlock:
(void (^)(int64_t key, float value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block([aKey longLongValue], [aValue floatValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block([aKey longLongValue], [aValue floatValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictFloatFieldSize([aValue floatValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -8620,20 +7706,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictFloatFieldSize([aValue floatValue], kMapValueFieldNumber, valueDataType);
+ int64_t unwrappedKey = [aKey longLongValue];
+ float unwrappedValue = [aValue floatValue];
+ size_t msgSize = ComputeDictInt64FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictFloatFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictInt64Field(outputStream, [aKey longLongValue], kMapKeyFieldNumber, keyDataType);
- WriteDictFloatField(outputStream, [aValue floatValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictInt64Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictFloatField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -8689,39 +7777,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithDoubles:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithDouble:(double)value
- forKey:(int64_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithDoubles:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt64DoubleDictionary*)[self alloc] initWithDoubles:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithDoubles:(const double [])values
- forKeys:(const int64_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithDoubles:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt64DoubleDictionary*)[self alloc] initWithDoubles:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBInt64DoubleDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBInt64DoubleDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithDoubles:NULL forKeys:NULL count:0];
}
@@ -8793,30 +7848,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndDoublesUsingBlock:
(void (^)(int64_t key, double value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block([aKey longLongValue], [aValue doubleValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block([aKey longLongValue], [aValue doubleValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictDoubleFieldSize([aValue doubleValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -8827,20 +7889,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictDoubleFieldSize([aValue doubleValue], kMapValueFieldNumber, valueDataType);
+ int64_t unwrappedKey = [aKey longLongValue];
+ double unwrappedValue = [aValue doubleValue];
+ size_t msgSize = ComputeDictInt64FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictDoubleFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictInt64Field(outputStream, [aKey longLongValue], kMapKeyFieldNumber, keyDataType);
- WriteDictDoubleField(outputStream, [aValue doubleValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictInt64Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictDoubleField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -8899,54 +7963,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
@synthesize validationFunc = _validationFunc;
-+ (instancetype)dictionary {
- return [[[self alloc] initWithValidationFunction:NULL
- rawValues:NULL
- forKeys:NULL
- count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func {
- return [[[self alloc] initWithValidationFunction:func
- rawValues:NULL
- forKeys:NULL
- count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
- rawValue:(int32_t)rawValue
- forKey:(int64_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt64EnumDictionary*)[self alloc] initWithValidationFunction:func
- rawValues:&rawValue
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
- rawValues:(const int32_t [])rawValues
- forKeys:(const int64_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt64EnumDictionary*)[self alloc] initWithValidationFunction:func
- rawValues:rawValues
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBInt64EnumDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt64EnumDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
- capacity:(NSUInteger)numItems {
- return [[[self alloc] initWithValidationFunction:func capacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithValidationFunction:NULL rawValues:NULL forKeys:NULL count:0];
}
@@ -9028,30 +8044,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndRawValuesUsingBlock:
(void (^)(int64_t key, int32_t value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block([aKey longLongValue], [aValue intValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block([aKey longLongValue], [aValue intValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictEnumFieldSize([aValue intValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -9062,20 +8085,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictEnumFieldSize([aValue intValue], kMapValueFieldNumber, valueDataType);
+ int64_t unwrappedKey = [aKey longLongValue];
+ int32_t unwrappedValue = [aValue intValue];
+ size_t msgSize = ComputeDictInt64FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictEnumFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictInt64Field(outputStream, [aKey longLongValue], kMapKeyFieldNumber, keyDataType);
- WriteDictEnumField(outputStream, [aValue intValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictInt64Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictEnumField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (NSData *)serializedDataForUnknownValue:(int32_t)value
@@ -9125,15 +8150,20 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndEnumsUsingBlock:
(void (^)(int64_t key, int32_t value, BOOL *stop))block {
GPBEnumValidationFunc func = _validationFunc;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- NSNumber *aValue,
- BOOL *stop) {
+ BOOL stop = NO;
+ NSEnumerator *keys = [_dictionary keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = _dictionary[aKey];
int32_t unwrapped = [aValue intValue];
if (!func(unwrapped)) {
unwrapped = kGPBUnrecognizedEnumeratorValue;
}
- block([aKey longLongValue], unwrapped, stop);
- }];
+ block([aKey longLongValue], unwrapped, &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (void)addRawEntriesFromDictionary:(GPBInt64EnumDictionary *)otherDictionary {
@@ -9182,39 +8212,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithObjects:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithObject:(id)object
- forKey:(int64_t)key {
- // Cast is needed so the compiler knows what class we are invoking initWithObjects:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt64ObjectDictionary*)[self alloc] initWithObjects:&object
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithObjects:(const id [])objects
- forKeys:(const int64_t [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithObjects:forKeys:count:
- // on to get the type correct.
- return [[(GPBInt64ObjectDictionary*)[self alloc] initWithObjects:objects
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBInt64ObjectDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBInt64ObjectDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithObjects:NULL forKeys:NULL count:0];
}
@@ -9290,11 +8287,17 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndObjectsUsingBlock:
(void (^)(int64_t key, id object, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- id aObject,
- BOOL *stop) {
- block([aKey longLongValue], aObject, stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ id aObject = internal[aKey];
+ block([aKey longLongValue], aObject, &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (BOOL)isInitialized {
@@ -9309,34 +8312,36 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (instancetype)deepCopyWithZone:(NSZone *)zone {
GPBInt64ObjectDictionary *newDict =
[[GPBInt64ObjectDictionary alloc] init];
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(id aKey,
- GPBMessage *msg,
- BOOL *stop) {
- #pragma unused(stop)
+ NSEnumerator *keys = [_dictionary keyEnumerator];
+ id aKey;
+ NSMutableDictionary *internalDict = newDict->_dictionary;
+ while ((aKey = [keys nextObject])) {
+ GPBMessage *msg = _dictionary[aKey];
GPBMessage *copiedMsg = [msg copyWithZone:zone];
- [newDict->_dictionary setObject:copiedMsg forKey:aKey];
+ [internalDict setObject:copiedMsg forKey:aKey];
[copiedMsg release];
- }];
+ }
return newDict;
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- id aObject,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ id aObject = internal[aKey];
size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictObjectFieldSize(aObject, kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -9347,20 +8352,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey,
- id aObject,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSNumber *aKey;
+ while ((aKey = [keys nextObject])) {
+ id aObject = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictObjectFieldSize(aObject, kMapValueFieldNumber, valueDataType);
+ int64_t unwrappedKey = [aKey longLongValue];
+ id unwrappedValue = aObject;
+ size_t msgSize = ComputeDictInt64FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictObjectFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictInt64Field(outputStream, [aKey longLongValue], kMapKeyFieldNumber, keyDataType);
- WriteDictObjectField(outputStream, aObject, kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictInt64Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictObjectField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -9420,39 +8427,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithUInt32s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt32:(uint32_t)value
- forKey:(NSString *)key {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBStringUInt32Dictionary*)[self alloc] initWithUInt32s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt32s:(const uint32_t [])values
- forKeys:(const NSString * [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBStringUInt32Dictionary*)[self alloc] initWithUInt32s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBStringUInt32Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBStringUInt32Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithUInt32s:NULL forKeys:NULL count:0];
}
@@ -9528,30 +8502,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndUInt32sUsingBlock:
(void (^)(NSString *key, uint32_t value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block(aKey, [aValue unsignedIntValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSString *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block(aKey, [aValue unsignedIntValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSString *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictUInt32FieldSize([aValue unsignedIntValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -9562,20 +8543,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSString *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictUInt32FieldSize([aValue unsignedIntValue], kMapValueFieldNumber, valueDataType);
+ NSString *unwrappedKey = aKey;
+ uint32_t unwrappedValue = [aValue unsignedIntValue];
+ size_t msgSize = ComputeDictStringFieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictUInt32FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictStringField(outputStream, aKey, kMapKeyFieldNumber, keyDataType);
- WriteDictUInt32Field(outputStream, [aValue unsignedIntValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictStringField(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictUInt32Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -9635,39 +8618,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithInt32s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt32:(int32_t)value
- forKey:(NSString *)key {
- // Cast is needed so the compiler knows what class we are invoking initWithInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBStringInt32Dictionary*)[self alloc] initWithInt32s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt32s:(const int32_t [])values
- forKeys:(const NSString * [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBStringInt32Dictionary*)[self alloc] initWithInt32s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBStringInt32Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBStringInt32Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithInt32s:NULL forKeys:NULL count:0];
}
@@ -9743,30 +8693,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndInt32sUsingBlock:
(void (^)(NSString *key, int32_t value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block(aKey, [aValue intValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSString *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block(aKey, [aValue intValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSString *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictInt32FieldSize([aValue intValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -9777,20 +8734,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSString *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictInt32FieldSize([aValue intValue], kMapValueFieldNumber, valueDataType);
+ NSString *unwrappedKey = aKey;
+ int32_t unwrappedValue = [aValue intValue];
+ size_t msgSize = ComputeDictStringFieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictInt32FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictStringField(outputStream, aKey, kMapKeyFieldNumber, keyDataType);
- WriteDictInt32Field(outputStream, [aValue intValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictStringField(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictInt32Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -9850,39 +8809,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithUInt64s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt64:(uint64_t)value
- forKey:(NSString *)key {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBStringUInt64Dictionary*)[self alloc] initWithUInt64s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt64s:(const uint64_t [])values
- forKeys:(const NSString * [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBStringUInt64Dictionary*)[self alloc] initWithUInt64s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBStringUInt64Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBStringUInt64Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithUInt64s:NULL forKeys:NULL count:0];
}
@@ -9958,30 +8884,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndUInt64sUsingBlock:
(void (^)(NSString *key, uint64_t value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block(aKey, [aValue unsignedLongLongValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSString *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block(aKey, [aValue unsignedLongLongValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSString *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictUInt64FieldSize([aValue unsignedLongLongValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -9992,20 +8925,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSString *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictUInt64FieldSize([aValue unsignedLongLongValue], kMapValueFieldNumber, valueDataType);
+ NSString *unwrappedKey = aKey;
+ uint64_t unwrappedValue = [aValue unsignedLongLongValue];
+ size_t msgSize = ComputeDictStringFieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictUInt64FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictStringField(outputStream, aKey, kMapKeyFieldNumber, keyDataType);
- WriteDictUInt64Field(outputStream, [aValue unsignedLongLongValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictStringField(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictUInt64Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -10065,39 +9000,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithInt64s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt64:(int64_t)value
- forKey:(NSString *)key {
- // Cast is needed so the compiler knows what class we are invoking initWithInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBStringInt64Dictionary*)[self alloc] initWithInt64s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt64s:(const int64_t [])values
- forKeys:(const NSString * [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBStringInt64Dictionary*)[self alloc] initWithInt64s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBStringInt64Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBStringInt64Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithInt64s:NULL forKeys:NULL count:0];
}
@@ -10173,30 +9075,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndInt64sUsingBlock:
(void (^)(NSString *key, int64_t value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block(aKey, [aValue longLongValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSString *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block(aKey, [aValue longLongValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSString *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictInt64FieldSize([aValue longLongValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -10207,20 +9116,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSString *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictInt64FieldSize([aValue longLongValue], kMapValueFieldNumber, valueDataType);
+ NSString *unwrappedKey = aKey;
+ int64_t unwrappedValue = [aValue longLongValue];
+ size_t msgSize = ComputeDictStringFieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictInt64FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictStringField(outputStream, aKey, kMapKeyFieldNumber, keyDataType);
- WriteDictInt64Field(outputStream, [aValue longLongValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictStringField(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictInt64Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -10280,39 +9191,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithBools:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithBool:(BOOL)value
- forKey:(NSString *)key {
- // Cast is needed so the compiler knows what class we are invoking initWithBools:forKeys:count:
- // on to get the type correct.
- return [[(GPBStringBoolDictionary*)[self alloc] initWithBools:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithBools:(const BOOL [])values
- forKeys:(const NSString * [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithBools:forKeys:count:
- // on to get the type correct.
- return [[(GPBStringBoolDictionary*)[self alloc] initWithBools:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBStringBoolDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBStringBoolDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithBools:NULL forKeys:NULL count:0];
}
@@ -10388,30 +9266,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndBoolsUsingBlock:
(void (^)(NSString *key, BOOL value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block(aKey, [aValue boolValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSString *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block(aKey, [aValue boolValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSString *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictBoolFieldSize([aValue boolValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -10422,20 +9307,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSString *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictBoolFieldSize([aValue boolValue], kMapValueFieldNumber, valueDataType);
+ NSString *unwrappedKey = aKey;
+ BOOL unwrappedValue = [aValue boolValue];
+ size_t msgSize = ComputeDictStringFieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictBoolFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictStringField(outputStream, aKey, kMapKeyFieldNumber, keyDataType);
- WriteDictBoolField(outputStream, [aValue boolValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictStringField(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictBoolField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -10495,39 +9382,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithFloats:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithFloat:(float)value
- forKey:(NSString *)key {
- // Cast is needed so the compiler knows what class we are invoking initWithFloats:forKeys:count:
- // on to get the type correct.
- return [[(GPBStringFloatDictionary*)[self alloc] initWithFloats:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithFloats:(const float [])values
- forKeys:(const NSString * [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithFloats:forKeys:count:
- // on to get the type correct.
- return [[(GPBStringFloatDictionary*)[self alloc] initWithFloats:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBStringFloatDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBStringFloatDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithFloats:NULL forKeys:NULL count:0];
}
@@ -10603,30 +9457,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndFloatsUsingBlock:
(void (^)(NSString *key, float value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block(aKey, [aValue floatValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSString *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block(aKey, [aValue floatValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSString *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictFloatFieldSize([aValue floatValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -10637,20 +9498,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSString *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictFloatFieldSize([aValue floatValue], kMapValueFieldNumber, valueDataType);
+ NSString *unwrappedKey = aKey;
+ float unwrappedValue = [aValue floatValue];
+ size_t msgSize = ComputeDictStringFieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictFloatFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictStringField(outputStream, aKey, kMapKeyFieldNumber, keyDataType);
- WriteDictFloatField(outputStream, [aValue floatValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictStringField(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictFloatField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -10710,39 +9573,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
NSMutableDictionary *_dictionary;
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithDoubles:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithDouble:(double)value
- forKey:(NSString *)key {
- // Cast is needed so the compiler knows what class we are invoking initWithDoubles:forKeys:count:
- // on to get the type correct.
- return [[(GPBStringDoubleDictionary*)[self alloc] initWithDoubles:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithDoubles:(const double [])values
- forKeys:(const NSString * [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithDoubles:forKeys:count:
- // on to get the type correct.
- return [[(GPBStringDoubleDictionary*)[self alloc] initWithDoubles:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBStringDoubleDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBStringDoubleDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithDoubles:NULL forKeys:NULL count:0];
}
@@ -10818,30 +9648,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndDoublesUsingBlock:
(void (^)(NSString *key, double value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block(aKey, [aValue doubleValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSString *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block(aKey, [aValue doubleValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSString *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictDoubleFieldSize([aValue doubleValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -10852,20 +9689,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSString *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictDoubleFieldSize([aValue doubleValue], kMapValueFieldNumber, valueDataType);
+ NSString *unwrappedKey = aKey;
+ double unwrappedValue = [aValue doubleValue];
+ size_t msgSize = ComputeDictStringFieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictDoubleFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictStringField(outputStream, aKey, kMapKeyFieldNumber, keyDataType);
- WriteDictDoubleField(outputStream, [aValue doubleValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictStringField(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictDoubleField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (void)setGPBGenericValue:(GPBGenericValue *)value
@@ -10928,54 +9767,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
@synthesize validationFunc = _validationFunc;
-+ (instancetype)dictionary {
- return [[[self alloc] initWithValidationFunction:NULL
- rawValues:NULL
- forKeys:NULL
- count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func {
- return [[[self alloc] initWithValidationFunction:func
- rawValues:NULL
- forKeys:NULL
- count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
- rawValue:(int32_t)rawValue
- forKey:(NSString *)key {
- // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
- // on to get the type correct.
- return [[(GPBStringEnumDictionary*)[self alloc] initWithValidationFunction:func
- rawValues:&rawValue
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
- rawValues:(const int32_t [])rawValues
- forKeys:(const NSString * [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
- // on to get the type correct.
- return [[(GPBStringEnumDictionary*)[self alloc] initWithValidationFunction:func
- rawValues:rawValues
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBStringEnumDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
- // on to get the type correct.
- return [[(GPBStringEnumDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
- capacity:(NSUInteger)numItems {
- return [[[self alloc] initWithValidationFunction:func capacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithValidationFunction:NULL rawValues:NULL forKeys:NULL count:0];
}
@@ -11061,30 +9852,37 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndRawValuesUsingBlock:
(void (^)(NSString *key, int32_t value, BOOL *stop))block {
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- block(aKey, [aValue intValue], stop);
- }];
+ BOOL stop = NO;
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSString *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
+ block(aKey, [aValue intValue], &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
- NSUInteger count = _dictionary.count;
+ NSDictionary *internal = _dictionary;
+ NSUInteger count = internal.count;
if (count == 0) {
return 0;
}
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
- __block size_t result = 0;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
+ size_t result = 0;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSString *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType);
msgSize += ComputeDictEnumFieldSize([aValue intValue], kMapValueFieldNumber, valueDataType);
result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize;
- }];
+ }
size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage);
result += tagSize * count;
return result;
@@ -11095,20 +9893,22 @@ void GPBDictionaryReadEntry(id mapDictionary,
GPBDataType valueDataType = GPBGetFieldDataType(field);
GPBDataType keyDataType = field.mapKeyDataType;
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey,
- NSNumber *aValue,
- BOOL *stop) {
- #pragma unused(stop)
- // Write the tag.
+ NSDictionary *internal = _dictionary;
+ NSEnumerator *keys = [internal keyEnumerator];
+ NSString *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = internal[aKey];
[outputStream writeInt32NoTag:tag];
// Write the size of the message.
- size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType);
- msgSize += ComputeDictEnumFieldSize([aValue intValue], kMapValueFieldNumber, valueDataType);
+ NSString *unwrappedKey = aKey;
+ int32_t unwrappedValue = [aValue intValue];
+ size_t msgSize = ComputeDictStringFieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ msgSize += ComputeDictEnumFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType);
[outputStream writeInt32NoTag:(int32_t)msgSize];
// Write the fields.
- WriteDictStringField(outputStream, aKey, kMapKeyFieldNumber, keyDataType);
- WriteDictEnumField(outputStream, [aValue intValue], kMapValueFieldNumber, valueDataType);
- }];
+ WriteDictStringField(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType);
+ WriteDictEnumField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType);
+ }
}
- (NSData *)serializedDataForUnknownValue:(int32_t)value
@@ -11158,15 +9958,20 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)enumerateKeysAndEnumsUsingBlock:
(void (^)(NSString *key, int32_t value, BOOL *stop))block {
GPBEnumValidationFunc func = _validationFunc;
- [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey,
- NSNumber *aValue,
- BOOL *stop) {
+ BOOL stop = NO;
+ NSEnumerator *keys = [_dictionary keyEnumerator];
+ NSString *aKey;
+ while ((aKey = [keys nextObject])) {
+ NSNumber *aValue = _dictionary[aKey];
int32_t unwrapped = [aValue intValue];
if (!func(unwrapped)) {
unwrapped = kGPBUnrecognizedEnumeratorValue;
}
- block(aKey, unwrapped, stop);
- }];
+ block(aKey, unwrapped, &stop);
+ if (stop) {
+ break;
+ }
+ }
}
- (void)addRawEntriesFromDictionary:(GPBStringEnumDictionary *)otherDictionary {
@@ -11230,39 +10035,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
BOOL _valueSet[2];
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithUInt32s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt32:(uint32_t)value
- forKey:(BOOL)key {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBBoolUInt32Dictionary*)[self alloc] initWithUInt32s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt32s:(const uint32_t [])values
- forKeys:(const BOOL [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBBoolUInt32Dictionary*)[self alloc] initWithUInt32s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBBoolUInt32Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBBoolUInt32Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithUInt32s:NULL forKeys:NULL count:0];
}
@@ -11472,39 +10244,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
BOOL _valueSet[2];
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithInt32s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt32:(int32_t)value
- forKey:(BOOL)key {
- // Cast is needed so the compiler knows what class we are invoking initWithInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBBoolInt32Dictionary*)[self alloc] initWithInt32s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt32s:(const int32_t [])values
- forKeys:(const BOOL [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithInt32s:forKeys:count:
- // on to get the type correct.
- return [[(GPBBoolInt32Dictionary*)[self alloc] initWithInt32s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBBoolInt32Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBBoolInt32Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithInt32s:NULL forKeys:NULL count:0];
}
@@ -11714,39 +10453,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
BOOL _valueSet[2];
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithUInt64s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt64:(uint64_t)value
- forKey:(BOOL)key {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBBoolUInt64Dictionary*)[self alloc] initWithUInt64s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithUInt64s:(const uint64_t [])values
- forKeys:(const BOOL [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithUInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBBoolUInt64Dictionary*)[self alloc] initWithUInt64s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBBoolUInt64Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBBoolUInt64Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithUInt64s:NULL forKeys:NULL count:0];
}
@@ -11956,39 +10662,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
BOOL _valueSet[2];
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithInt64s:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt64:(int64_t)value
- forKey:(BOOL)key {
- // Cast is needed so the compiler knows what class we are invoking initWithInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBBoolInt64Dictionary*)[self alloc] initWithInt64s:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithInt64s:(const int64_t [])values
- forKeys:(const BOOL [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithInt64s:forKeys:count:
- // on to get the type correct.
- return [[(GPBBoolInt64Dictionary*)[self alloc] initWithInt64s:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBBoolInt64Dictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBBoolInt64Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithInt64s:NULL forKeys:NULL count:0];
}
@@ -12198,39 +10871,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
BOOL _valueSet[2];
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithBools:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithBool:(BOOL)value
- forKey:(BOOL)key {
- // Cast is needed so the compiler knows what class we are invoking initWithBools:forKeys:count:
- // on to get the type correct.
- return [[(GPBBoolBoolDictionary*)[self alloc] initWithBools:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithBools:(const BOOL [])values
- forKeys:(const BOOL [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithBools:forKeys:count:
- // on to get the type correct.
- return [[(GPBBoolBoolDictionary*)[self alloc] initWithBools:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBBoolBoolDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBBoolBoolDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithBools:NULL forKeys:NULL count:0];
}
@@ -12440,39 +11080,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
BOOL _valueSet[2];
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithFloats:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithFloat:(float)value
- forKey:(BOOL)key {
- // Cast is needed so the compiler knows what class we are invoking initWithFloats:forKeys:count:
- // on to get the type correct.
- return [[(GPBBoolFloatDictionary*)[self alloc] initWithFloats:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithFloats:(const float [])values
- forKeys:(const BOOL [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithFloats:forKeys:count:
- // on to get the type correct.
- return [[(GPBBoolFloatDictionary*)[self alloc] initWithFloats:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBBoolFloatDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBBoolFloatDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithFloats:NULL forKeys:NULL count:0];
}
@@ -12682,39 +11289,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
BOOL _valueSet[2];
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithDoubles:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithDouble:(double)value
- forKey:(BOOL)key {
- // Cast is needed so the compiler knows what class we are invoking initWithDoubles:forKeys:count:
- // on to get the type correct.
- return [[(GPBBoolDoubleDictionary*)[self alloc] initWithDoubles:&value
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithDoubles:(const double [])values
- forKeys:(const BOOL [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithDoubles:forKeys:count:
- // on to get the type correct.
- return [[(GPBBoolDoubleDictionary*)[self alloc] initWithDoubles:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBBoolDoubleDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBBoolDoubleDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithDoubles:NULL forKeys:NULL count:0];
}
@@ -12923,39 +11497,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
id _values[2];
}
-+ (instancetype)dictionary {
- return [[[self alloc] initWithObjects:NULL forKeys:NULL count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithObject:(id)object
- forKey:(BOOL)key {
- // Cast is needed so the compiler knows what class we are invoking initWithObjects:forKeys:count:
- // on to get the type correct.
- return [[(GPBBoolObjectDictionary*)[self alloc] initWithObjects:&object
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithObjects:(const id [])objects
- forKeys:(const BOOL [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithObjects:forKeys:count:
- // on to get the type correct.
- return [[(GPBBoolObjectDictionary*)[self alloc] initWithObjects:objects
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBBoolObjectDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithDictionary:
- // on to get the type correct.
- return [[(GPBBoolObjectDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems {
- return [[[self alloc] initWithCapacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithObjects:NULL forKeys:NULL count:0];
}
@@ -13189,54 +11730,6 @@ void GPBDictionaryReadEntry(id mapDictionary,
@synthesize validationFunc = _validationFunc;
-+ (instancetype)dictionary {
- return [[[self alloc] initWithValidationFunction:NULL
- rawValues:NULL
- forKeys:NULL
- count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func {
- return [[[self alloc] initWithValidationFunction:func
- rawValues:NULL
- forKeys:NULL
- count:0] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
- rawValue:(int32_t)rawValue
- forKey:(BOOL)key {
- // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
- // on to get the type correct.
- return [[(GPBBoolEnumDictionary*)[self alloc] initWithValidationFunction:func
- rawValues:&rawValue
- forKeys:&key
- count:1] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
- rawValues:(const int32_t [])values
- forKeys:(const BOOL [])keys
- count:(NSUInteger)count {
- // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
- // on to get the type correct.
- return [[(GPBBoolEnumDictionary*)[self alloc] initWithValidationFunction:func
- rawValues:values
- forKeys:keys
- count:count] autorelease];
-}
-
-+ (instancetype)dictionaryWithDictionary:(GPBBoolEnumDictionary *)dictionary {
- // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count:
- // on to get the type correct.
- return [[(GPBBoolEnumDictionary*)[self alloc] initWithDictionary:dictionary] autorelease];
-}
-
-+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func
- capacity:(NSUInteger)numItems {
- return [[[self alloc] initWithValidationFunction:func capacity:numItems] autorelease];
-}
-
- (instancetype)init {
return [self initWithValidationFunction:NULL rawValues:NULL forKeys:NULL count:0];
}
@@ -13579,22 +12072,26 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (id)copyWithZone:(NSZone *)zone {
if (_dictionary == nil) {
- _dictionary = [[NSMutableDictionary alloc] init];
+ return [[NSMutableDictionary allocWithZone:zone] init];
}
return [_dictionary copyWithZone:zone];
}
- (id)mutableCopyWithZone:(NSZone *)zone {
if (_dictionary == nil) {
- _dictionary = [[NSMutableDictionary alloc] init];
+ return [[NSMutableDictionary allocWithZone:zone] init];
}
return [_dictionary mutableCopyWithZone:zone];
}
+// Not really needed, but subscripting is likely common enough it doesn't hurt
+// to ensure it goes directly to the real NSMutableDictionary.
- (id)objectForKeyedSubscript:(id)key {
return [_dictionary objectForKeyedSubscript:key];
}
+// Not really needed, but subscripting is likely common enough it doesn't hurt
+// to ensure it goes directly to the real NSMutableDictionary.
- (void)setObject:(id)obj forKeyedSubscript:(id<NSCopying>)key {
if (_dictionary == nil) {
_dictionary = [[NSMutableDictionary alloc] init];
diff --git a/objectivec/GPBExtensionRegistry.m b/objectivec/GPBExtensionRegistry.m
index 65534b67..b056a52d 100644
--- a/objectivec/GPBExtensionRegistry.m
+++ b/objectivec/GPBExtensionRegistry.m
@@ -57,14 +57,16 @@
- (instancetype)copyWithZone:(NSZone *)zone {
GPBExtensionRegistry *result = [[[self class] allocWithZone:zone] init];
- if (result && mutableClassMap_.count) {
- [result->mutableClassMap_ addEntriesFromDictionary:mutableClassMap_];
- }
+ [result addExtensions:self];
return result;
}
-- (CFMutableDictionaryRef)extensionMapForContainingMessageClass:
- (Class)containingMessageClass {
+- (void)addExtension:(GPBExtensionDescriptor *)extension {
+ if (extension == nil) {
+ return;
+ }
+
+ Class containingMessageClass = extension.containingMessageClass;
CFMutableDictionaryRef extensionMap = (CFMutableDictionaryRef)
[mutableClassMap_ objectForKey:containingMessageClass];
if (extensionMap == nil) {
@@ -74,18 +76,9 @@
&kCFTypeDictionaryValueCallBacks);
[mutableClassMap_ setObject:(id)extensionMap
forKey:(id<NSCopying>)containingMessageClass];
+ CFRelease(extensionMap);
}
- return extensionMap;
-}
-- (void)addExtension:(GPBExtensionDescriptor *)extension {
- if (extension == nil) {
- return;
- }
-
- Class containingMessageClass = extension.containingMessageClass;
- CFMutableDictionaryRef extensionMap =
- [self extensionMapForContainingMessageClass:containingMessageClass];
ssize_t key = extension.fieldNumber;
CFDictionarySetValue(extensionMap, (const void *)key, extension);
}
@@ -119,10 +112,16 @@ static void CopyKeyValue(const void *key, const void *value, void *context) {
Class containingMessageClass = key;
CFMutableDictionaryRef otherExtensionMap = (CFMutableDictionaryRef)value;
- CFMutableDictionaryRef extensionMap =
- [self extensionMapForContainingMessageClass:containingMessageClass];
-
- CFDictionaryApplyFunction(otherExtensionMap, CopyKeyValue, extensionMap);
+ CFMutableDictionaryRef extensionMap = (CFMutableDictionaryRef)
+ [mutableClassMap_ objectForKey:containingMessageClass];
+ if (extensionMap == nil) {
+ extensionMap = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 0, otherExtensionMap);
+ [mutableClassMap_ setObject:(id)extensionMap
+ forKey:(id<NSCopying>)containingMessageClass];
+ CFRelease(extensionMap);
+ } else {
+ CFDictionaryApplyFunction(otherExtensionMap, CopyKeyValue, extensionMap);
+ }
}];
}
diff --git a/objectivec/GPBMessage.h b/objectivec/GPBMessage.h
index c07ec888..276740d2 100644
--- a/objectivec/GPBMessage.h
+++ b/objectivec/GPBMessage.h
@@ -66,6 +66,11 @@ CF_EXTERN_C_END
/**
* Base class that each generated message subclasses from.
*
+ * @note @c NSCopying support is a "deep copy", in that all sub objects are
+ * copied. Just like you wouldn't want a UIView/NSView trying to
+ * exist in two places, you don't want a sub message to be a property
+ * property of two other messages.
+ *
* @note While the class support NSSecureCoding, if the message has any
* extensions, they will end up reloaded in @c unknownFields as there is
* no way for the @c NSCoding plumbing to pass through a
@@ -287,6 +292,9 @@ CF_EXTERN_C_END
* Writes out the message to the given coded output stream.
*
* @param output The coded output stream into which to write the message.
+ *
+ * @note This can raise the GPBCodedOutputStreamException_* exceptions.
+ *
**/
- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)output;
@@ -294,6 +302,8 @@ CF_EXTERN_C_END
* Writes out the message to the given output stream.
*
* @param output The output stream into which to write the message.
+ *
+ * @note This can raise the GPBCodedOutputStreamException_* exceptions.
**/
- (void)writeToOutputStream:(NSOutputStream *)output;
@@ -302,6 +312,8 @@ CF_EXTERN_C_END
* the given output stream.
*
* @param output The coded output stream into which to write the message.
+ *
+ * @note This can raise the GPBCodedOutputStreamException_* exceptions.
**/
- (void)writeDelimitedToCodedOutputStream:(GPBCodedOutputStream *)output;
@@ -310,6 +322,8 @@ CF_EXTERN_C_END
* the given output stream.
*
* @param output The output stream into which to write the message.
+ *
+ * @note This can raise the GPBCodedOutputStreamException_* exceptions.
**/
- (void)writeDelimitedToOutputStream:(NSOutputStream *)output;
diff --git a/objectivec/GPBMessage.m b/objectivec/GPBMessage.m
index 4a6f0612..90485bd1 100644
--- a/objectivec/GPBMessage.m
+++ b/objectivec/GPBMessage.m
@@ -130,7 +130,7 @@ static NSError *ErrorFromException(NSException *exception) {
static void CheckExtension(GPBMessage *self,
GPBExtensionDescriptor *extension) {
- if ([self class] != extension.containingMessageClass) {
+ if (![self isKindOfClass:extension.containingMessageClass]) {
[NSException
raise:NSInvalidArgumentException
format:@"Extension %@ used on wrong class (%@ instead of %@)",
@@ -738,6 +738,25 @@ void GPBClearMessageAutocreator(GPBMessage *self) {
self->autocreatorExtension_ = nil;
}
+// Call this before using the readOnlySemaphore_. This ensures it is created only once.
+void GPBPrepareReadOnlySemaphore(GPBMessage *self) {
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdirect-ivar-access"
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+
+ // Create the semaphore on demand (rather than init) as developers might not cause them
+ // to be needed, and the heap usage can add up. The atomic swap is used to avoid needing
+ // another lock around creating it.
+ if (self->readOnlySemaphore_ == nil) {
+ dispatch_semaphore_t worker = dispatch_semaphore_create(1);
+ if (!OSAtomicCompareAndSwapPtrBarrier(NULL, worker, (void * volatile *)&(self->readOnlySemaphore_))) {
+ dispatch_release(worker);
+ }
+ }
+
+#pragma clang diagnostic pop
+}
+
static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) {
if (!self->unknownFields_) {
self->unknownFields_ = [[GPBUnknownFieldSet alloc] init];
@@ -1023,9 +1042,11 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) {
if (arrayOrMap) {
if (field.fieldType == GPBFieldTypeRepeated) {
if (GPBFieldDataTypeIsObject(field)) {
- GPBAutocreatedArray *autoArray = arrayOrMap;
- if (autoArray->_autocreator == self) {
- autoArray->_autocreator = nil;
+ if ([arrayOrMap isKindOfClass:[GPBAutocreatedArray class]]) {
+ GPBAutocreatedArray *autoArray = arrayOrMap;
+ if (autoArray->_autocreator == self) {
+ autoArray->_autocreator = nil;
+ }
}
} else {
// Type doesn't matter, it is a GPB*Array.
@@ -1037,9 +1058,11 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) {
} else {
if ((field.mapKeyDataType == GPBDataTypeString) &&
GPBFieldDataTypeIsObject(field)) {
- GPBAutocreatedDictionary *autoDict = arrayOrMap;
- if (autoDict->_autocreator == self) {
- autoDict->_autocreator = nil;
+ if ([arrayOrMap isKindOfClass:[GPBAutocreatedDictionary class]]) {
+ GPBAutocreatedDictionary *autoDict = arrayOrMap;
+ if (autoDict->_autocreator == self) {
+ autoDict->_autocreator = nil;
+ }
}
} else {
// Type doesn't matter, it is a GPB*Dictionary.
@@ -2349,17 +2372,11 @@ static void MergeRepeatedNotPackedFieldFromCodedInputStream(
// zero signals EOF / limit reached
return;
} else {
- if (GPBPreserveUnknownFields(syntax)) {
- if (![self parseUnknownField:input
- extensionRegistry:extensionRegistry
- tag:tag]) {
- // it's an endgroup tag
- return;
- }
- } else {
- if (![input skipField:tag]) {
- return;
- }
+ if (![self parseUnknownField:input
+ extensionRegistry:extensionRegistry
+ tag:tag]) {
+ // it's an endgroup tag
+ return;
}
}
} // if(!merged)
@@ -2574,13 +2591,14 @@ static void MergeRepeatedNotPackedFieldFromCodedInputStream(
if (other == self) {
return YES;
}
- if (![other isKindOfClass:[self class]] &&
- ![self isKindOfClass:[other class]]) {
+ if (![other isKindOfClass:[GPBMessage class]]) {
return NO;
}
-
GPBMessage *otherMsg = other;
GPBDescriptor *descriptor = [[self class] descriptor];
+ if ([[otherMsg class] descriptor] != descriptor) {
+ return NO;
+ }
uint8_t *selfStorage = (uint8_t *)messageStorage_;
uint8_t *otherStorage = (uint8_t *)otherMsg->messageStorage_;
@@ -2980,7 +2998,10 @@ typedef struct ResolveIvarAccessorMethodResult {
SEL encodingSelector;
} ResolveIvarAccessorMethodResult;
-static void ResolveIvarGet(GPBFieldDescriptor *field,
+// |field| can be __unsafe_unretained because they are created at startup
+// and are essentially global. No need to pay for retain/release when
+// they are captured in blocks.
+static void ResolveIvarGet(__unsafe_unretained GPBFieldDescriptor *field,
ResolveIvarAccessorMethodResult *result) {
GPBDataType fieldDataType = GPBGetFieldDataType(field);
switch (fieldDataType) {
@@ -3022,7 +3043,8 @@ static void ResolveIvarGet(GPBFieldDescriptor *field,
}
}
-static void ResolveIvarSet(GPBFieldDescriptor *field,
+// See comment about __unsafe_unretained on ResolveIvarGet.
+static void ResolveIvarSet(__unsafe_unretained GPBFieldDescriptor *field,
GPBFileSyntax syntax,
ResolveIvarAccessorMethodResult *result) {
GPBDataType fieldDataType = GPBGetFieldDataType(field);
@@ -3060,15 +3082,16 @@ static void ResolveIvarSet(GPBFieldDescriptor *field,
+ (BOOL)resolveInstanceMethod:(SEL)sel {
const GPBDescriptor *descriptor = [self descriptor];
if (!descriptor) {
- return NO;
+ return [super resolveInstanceMethod:sel];
}
// NOTE: hasOrCountSel_/setHasSel_ will be NULL if the field for the given
// message should not have has support (done in GPBDescriptor.m), so there is
// no need for checks here to see if has*/setHas* are allowed.
-
ResolveIvarAccessorMethodResult result = {NULL, NULL};
- for (GPBFieldDescriptor *field in descriptor->fields_) {
+
+ // See comment about __unsafe_unretained on ResolveIvarGet.
+ for (__unsafe_unretained GPBFieldDescriptor *field in descriptor->fields_) {
BOOL isMapOrArray = GPBFieldIsMapOrArray(field);
if (!isMapOrArray) {
// Single fields.
@@ -3148,8 +3171,17 @@ static void ResolveIvarSet(GPBFieldDescriptor *field,
if (result.impToAdd) {
const char *encoding =
GPBMessageEncodingForSelector(result.encodingSelector, YES);
- BOOL methodAdded = class_addMethod(descriptor.messageClass, sel,
- result.impToAdd, encoding);
+ Class msgClass = descriptor.messageClass;
+ BOOL methodAdded = class_addMethod(msgClass, sel, result.impToAdd, encoding);
+ // class_addMethod() is documented as also failing if the method was already
+ // added; so we check if the method is already there and return success so
+ // the method dispatch will still happen. Why would it already be added?
+ // Two threads could cause the same method to be bound at the same time,
+ // but only one will actually bind it; the other still needs to return true
+ // so things will dispatch.
+ if (!methodAdded) {
+ methodAdded = GPBClassHasSel(msgClass, sel);
+ }
return methodAdded;
}
return [super resolveInstanceMethod:sel];
@@ -3157,7 +3189,7 @@ static void ResolveIvarSet(GPBFieldDescriptor *field,
+ (BOOL)resolveClassMethod:(SEL)sel {
// Extensions scoped to a Message and looked up via class methods.
- if (GPBResolveExtensionClassMethod(self, sel)) {
+ if (GPBResolveExtensionClassMethod([self descriptor].messageClass, sel)) {
return YES;
}
return [super resolveClassMethod:sel];
diff --git a/objectivec/GPBMessage_PackagePrivate.h b/objectivec/GPBMessage_PackagePrivate.h
index 02d0e16e..90834d40 100644
--- a/objectivec/GPBMessage_PackagePrivate.h
+++ b/objectivec/GPBMessage_PackagePrivate.h
@@ -70,7 +70,6 @@ typedef struct GPBMessage_Storage *GPBMessage_StoragePtr;
// Use of readOnlySemaphore_ must be prefaced by a call to
// GPBPrepareReadOnlySemaphore to ensure it has been created. This allows
// readOnlySemaphore_ to be only created when actually needed.
- dispatch_once_t readOnlySemaphoreCreationOnce_;
dispatch_semaphore_t readOnlySemaphore_;
}
@@ -105,14 +104,7 @@ CF_EXTERN_C_BEGIN
// Call this before using the readOnlySemaphore_. This ensures it is created only once.
-NS_INLINE void GPBPrepareReadOnlySemaphore(GPBMessage *self) {
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdirect-ivar-access"
- dispatch_once(&self->readOnlySemaphoreCreationOnce_, ^{
- self->readOnlySemaphore_ = dispatch_semaphore_create(1);
- });
-#pragma clang diagnostic pop
-}
+void GPBPrepareReadOnlySemaphore(GPBMessage *self);
// Returns a new instance that was automatically created by |autocreator| for
// its field |field|.
diff --git a/objectivec/GPBRootObject.m b/objectivec/GPBRootObject.m
index 4570716f..bad2f9a7 100644
--- a/objectivec/GPBRootObject.m
+++ b/objectivec/GPBRootObject.m
@@ -43,6 +43,14 @@
- (const char *)singletonNameC;
@end
+// We need some object to conform to the MessageSignatureProtocol to make sure
+// the selectors in it are recorded in our Objective C runtime information.
+// GPBMessage is arguably the more "obvious" choice, but given that all messages
+// inherit from GPBMessage, conflicts seem likely, so we are using GPBRootObject
+// instead.
+@interface GPBRootObject () <GPBMessageSignatureProtocol>
+@end
+
@implementation GPBRootObject
// Taken from http://www.burtleburtle.net/bob/hash/doobs.html
@@ -184,11 +192,10 @@ static id ExtensionForName(id self, SEL _cmd) {
dispatch_semaphore_wait(gExtensionSingletonDictionarySemaphore,
DISPATCH_TIME_FOREVER);
id extension = (id)CFDictionaryGetValue(gExtensionSingletonDictionary, key);
- if (extension) {
- // The method is getting wired in to the class, so no need to keep it in
- // the dictionary.
- CFDictionaryRemoveValue(gExtensionSingletonDictionary, key);
- }
+ // We can't remove the key from the dictionary here (as an optimization),
+ // two threads could have gone into +resolveClassMethod: for the same method,
+ // and ended up here; there's no way to ensure both return YES without letting
+ // both try to wire in the method.
dispatch_semaphore_signal(gExtensionSingletonDictionarySemaphore);
return extension;
}
@@ -212,9 +219,17 @@ BOOL GPBResolveExtensionClassMethod(Class self, SEL sel) {
#pragma unused(obj)
return extension;
});
- if (class_addMethod(metaClass, sel, imp, encoding)) {
- return YES;
+ BOOL methodAdded = class_addMethod(metaClass, sel, imp, encoding);
+ // class_addMethod() is documented as also failing if the method was already
+ // added; so we check if the method is already there and return success so
+ // the method dispatch will still happen. Why would it already be added?
+ // Two threads could cause the same method to be bound at the same time,
+ // but only one will actually bind it; the other still needs to return true
+ // so things will dispatch.
+ if (!methodAdded) {
+ methodAdded = GPBClassHasSel(metaClass, sel);
}
+ return methodAdded;
}
return NO;
}
diff --git a/objectivec/GPBUnknownField.h b/objectivec/GPBUnknownField.h
index a135cc20..5b96023b 100644
--- a/objectivec/GPBUnknownField.h
+++ b/objectivec/GPBUnknownField.h
@@ -42,6 +42,9 @@ NS_ASSUME_NONNULL_BEGIN
**/
@interface GPBUnknownField : NSObject<NSCopying>
+/** Initialize a field with the given number. */
+- (instancetype)initWithNumber:(int32_t)number;
+
/** The field number the data is stored under. */
@property(nonatomic, readonly, assign) int32_t number;
diff --git a/objectivec/GPBUnknownField.m b/objectivec/GPBUnknownField.m
index 30efe756..9d5c97f3 100644
--- a/objectivec/GPBUnknownField.m
+++ b/objectivec/GPBUnknownField.m
@@ -79,7 +79,7 @@
result->mutableFixed32List_ = [mutableFixed32List_ copyWithZone:zone];
result->mutableFixed64List_ = [mutableFixed64List_ copyWithZone:zone];
result->mutableLengthDelimitedList_ =
- [mutableLengthDelimitedList_ copyWithZone:zone];
+ [mutableLengthDelimitedList_ mutableCopyWithZone:zone];
result->mutableVarintList_ = [mutableVarintList_ copyWithZone:zone];
if (mutableGroupList_.count) {
result->mutableGroupList_ = [[NSMutableArray allocWithZone:zone]
@@ -97,6 +97,7 @@
if (self == object) return YES;
if (![object isKindOfClass:[GPBUnknownField class]]) return NO;
GPBUnknownField *field = (GPBUnknownField *)object;
+ if (number_ != field->number_) return NO;
BOOL equalVarint =
(mutableVarintList_.count == 0 && field->mutableVarintList_.count == 0) ||
[mutableVarintList_ isEqual:field->mutableVarintList_];
@@ -202,8 +203,9 @@
}
- (NSString *)description {
- NSMutableString *description = [NSMutableString
- stringWithFormat:@"<%@ %p>: Field: %d {\n", [self class], self, number_];
+ NSMutableString *description =
+ [NSMutableString stringWithFormat:@"<%@ %p>: Field: %d {\n",
+ [self class], self, number_];
[mutableVarintList_
enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) {
#pragma unused(idx, stop)
diff --git a/objectivec/GPBUnknownField_PackagePrivate.h b/objectivec/GPBUnknownField_PackagePrivate.h
index 1fbce0f9..2b4c7895 100644
--- a/objectivec/GPBUnknownField_PackagePrivate.h
+++ b/objectivec/GPBUnknownField_PackagePrivate.h
@@ -36,8 +36,6 @@
@interface GPBUnknownField ()
-- (instancetype)initWithNumber:(int32_t)number;
-
- (void)writeToOutput:(GPBCodedOutputStream *)output;
- (size_t)serializedSize;
diff --git a/objectivec/GPBUtilities.h b/objectivec/GPBUtilities.h
index 52e7d2e0..5464dfb3 100644
--- a/objectivec/GPBUtilities.h
+++ b/objectivec/GPBUtilities.h
@@ -392,6 +392,11 @@ void GPBSetMessageMapField(GPBMessage *self,
**/
NSData *GPBEmptyNSData(void) __attribute__((pure));
+/**
+ * Drops the `unknownFields` from the given message and from all sub message.
+ **/
+void GPBMessageDropUnknownFieldsRecursively(GPBMessage *message);
+
NS_ASSUME_NONNULL_END
CF_EXTERN_C_END
diff --git a/objectivec/GPBUtilities.m b/objectivec/GPBUtilities.m
index d4538598..77ea9577 100644
--- a/objectivec/GPBUtilities.m
+++ b/objectivec/GPBUtilities.m
@@ -49,6 +49,19 @@ static void AppendTextFormatForMessage(GPBMessage *message,
NSMutableString *toStr,
NSString *lineIndent);
+// Are two datatypes the same basic type representation (ex Int32 and SInt32).
+// Marked unused because currently only called from asserts/debug.
+static BOOL DataTypesEquivalent(GPBDataType type1,
+ GPBDataType type2) __attribute__ ((unused));
+
+// Basic type representation for a type (ex: for SInt32 it is Int32).
+// Marked unused because currently only called from asserts/debug.
+static GPBDataType BaseDataType(GPBDataType type) __attribute__ ((unused));
+
+// String name for a data type.
+// Marked unused because currently only called from asserts/debug.
+static NSString *TypeToString(GPBDataType dataType) __attribute__ ((unused));
+
NSData *GPBEmptyNSData(void) {
static dispatch_once_t onceToken;
static NSData *defaultNSData = nil;
@@ -58,6 +71,125 @@ NSData *GPBEmptyNSData(void) {
return defaultNSData;
}
+void GPBMessageDropUnknownFieldsRecursively(GPBMessage *initialMessage) {
+ if (!initialMessage) {
+ return;
+ }
+
+ // Use an array as a list to process to avoid recursion.
+ NSMutableArray *todo = [NSMutableArray arrayWithObject:initialMessage];
+
+ while (todo.count) {
+ GPBMessage *msg = todo.lastObject;
+ [todo removeLastObject];
+
+ // Clear unknowns.
+ msg.unknownFields = nil;
+
+ // Handle the message fields.
+ GPBDescriptor *descriptor = [[msg class] descriptor];
+ for (GPBFieldDescriptor *field in descriptor->fields_) {
+ if (!GPBFieldDataTypeIsMessage(field)) {
+ continue;
+ }
+ switch (field.fieldType) {
+ case GPBFieldTypeSingle:
+ if (GPBGetHasIvarField(msg, field)) {
+ GPBMessage *fieldMessage = GPBGetObjectIvarWithFieldNoAutocreate(msg, field);
+ [todo addObject:fieldMessage];
+ }
+ break;
+
+ case GPBFieldTypeRepeated: {
+ NSArray *fieldMessages = GPBGetObjectIvarWithFieldNoAutocreate(msg, field);
+ if (fieldMessages.count) {
+ [todo addObjectsFromArray:fieldMessages];
+ }
+ break;
+ }
+
+ case GPBFieldTypeMap: {
+ id rawFieldMap = GPBGetObjectIvarWithFieldNoAutocreate(msg, field);
+ switch (field.mapKeyDataType) {
+ case GPBDataTypeBool:
+ [(GPBBoolObjectDictionary*)rawFieldMap enumerateKeysAndObjectsUsingBlock:^(
+ BOOL key, id _Nonnull object, BOOL * _Nonnull stop) {
+ #pragma unused(key, stop)
+ [todo addObject:object];
+ }];
+ break;
+ case GPBDataTypeFixed32:
+ case GPBDataTypeUInt32:
+ [(GPBUInt32ObjectDictionary*)rawFieldMap enumerateKeysAndObjectsUsingBlock:^(
+ uint32_t key, id _Nonnull object, BOOL * _Nonnull stop) {
+ #pragma unused(key, stop)
+ [todo addObject:object];
+ }];
+ break;
+ case GPBDataTypeInt32:
+ case GPBDataTypeSFixed32:
+ case GPBDataTypeSInt32:
+ [(GPBInt32ObjectDictionary*)rawFieldMap enumerateKeysAndObjectsUsingBlock:^(
+ int32_t key, id _Nonnull object, BOOL * _Nonnull stop) {
+ #pragma unused(key, stop)
+ [todo addObject:object];
+ }];
+ break;
+ case GPBDataTypeFixed64:
+ case GPBDataTypeUInt64:
+ [(GPBUInt64ObjectDictionary*)rawFieldMap enumerateKeysAndObjectsUsingBlock:^(
+ uint64_t key, id _Nonnull object, BOOL * _Nonnull stop) {
+ #pragma unused(key, stop)
+ [todo addObject:object];
+ }];
+ break;
+ case GPBDataTypeInt64:
+ case GPBDataTypeSFixed64:
+ case GPBDataTypeSInt64:
+ [(GPBInt64ObjectDictionary*)rawFieldMap enumerateKeysAndObjectsUsingBlock:^(
+ int64_t key, id _Nonnull object, BOOL * _Nonnull stop) {
+ #pragma unused(key, stop)
+ [todo addObject:object];
+ }];
+ break;
+ case GPBDataTypeString:
+ [(NSDictionary*)rawFieldMap enumerateKeysAndObjectsUsingBlock:^(
+ NSString * _Nonnull key, GPBMessage * _Nonnull obj, BOOL * _Nonnull stop) {
+ #pragma unused(key, stop)
+ [todo addObject:obj];
+ }];
+ break;
+ case GPBDataTypeFloat:
+ case GPBDataTypeDouble:
+ case GPBDataTypeEnum:
+ case GPBDataTypeBytes:
+ case GPBDataTypeGroup:
+ case GPBDataTypeMessage:
+ NSCAssert(NO, @"Aren't valid key types.");
+ }
+ break;
+ } // switch(field.mapKeyDataType)
+ } // switch(field.fieldType)
+ } // for(fields)
+
+ // Handle any extensions holding messages.
+ for (GPBExtensionDescriptor *extension in [msg extensionsCurrentlySet]) {
+ if (!GPBDataTypeIsMessage(extension.dataType)) {
+ continue;
+ }
+ if (extension.isRepeated) {
+ NSArray *extMessages = [msg getExtension:extension];
+ [todo addObjectsFromArray:extMessages];
+ } else {
+ GPBMessage *extMessage = [msg getExtension:extension];
+ [todo addObject:extMessage];
+ }
+ } // for(extensionsCurrentlySet)
+
+ } // while(todo.count)
+}
+
+
// -- About Version Checks --
// There's actually 3 places these checks all come into play:
// 1. When the generated source is compile into .o files, the header check
@@ -223,6 +355,14 @@ void GPBMaybeClearOneof(GPBMessage *self, GPBOneofDescriptor *oneof,
//%PDDM-DEFINE IVAR_POD_ACCESSORS_DEFN(NAME, TYPE)
//%TYPE GPBGetMessage##NAME##Field(GPBMessage *self,
//% TYPE$S NAME$S GPBFieldDescriptor *field) {
+//%#if defined(DEBUG) && DEBUG
+//% NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+//% GPBDataType##NAME),
+//% @"Attempting to get value of TYPE from field %@ "
+//% @"of %@ which is of type %@.",
+//% [self class], field.name,
+//% TypeToString(GPBGetFieldDataType(field)));
+//%#endif
//% if (GPBGetHasIvarField(self, field)) {
//% uint8_t *storage = (uint8_t *)self->messageStorage_;
//% TYPE *typePtr = (TYPE *)&storage[field->description_->offset];
@@ -245,14 +385,24 @@ void GPBMaybeClearOneof(GPBMessage *self, GPBOneofDescriptor *oneof,
//% NAME$S GPBFieldDescriptor *field,
//% NAME$S TYPE value,
//% NAME$S GPBFileSyntax syntax) {
+//%#if defined(DEBUG) && DEBUG
+//% NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+//% GPBDataType##NAME),
+//% @"Attempting to set field %@ of %@ which is of type %@ with "
+//% @"value of type TYPE.",
+//% [self class], field.name,
+//% TypeToString(GPBGetFieldDataType(field)));
+//%#endif
//% GPBOneofDescriptor *oneof = field->containingOneof_;
//% if (oneof) {
//% GPBMessageFieldDescription *fieldDesc = field->description_;
//% GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
//% }
+//%#if defined(DEBUG) && DEBUG
//% NSCAssert(self->messageStorage_ != NULL,
//% @"%@: All messages should have storage (from init)",
//% [self class]);
+//%#endif
//%#if defined(__clang_analyzer__)
//% if (self->messageStorage_ == NULL) return;
//%#endif
@@ -272,6 +422,14 @@ void GPBMaybeClearOneof(GPBMessage *self, GPBOneofDescriptor *oneof,
//%// Only exists for public api, no core code should use this.
//%TYPE *GPBGetMessage##NAME##Field(GPBMessage *self,
//% TYPE$S NAME$S GPBFieldDescriptor *field) {
+//%#if defined(DEBUG) && DEBUG
+//% NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+//% GPBDataType##NAME),
+//% @"Attempting to get value of TYPE from field %@ "
+//% @"of %@ which is of type %@.",
+//% [self class], field.name,
+//% TypeToString(GPBGetFieldDataType(field)));
+//%#endif
//% return (TYPE *)GPBGetObjectIvarWithField(self, field);
//%}
//%
@@ -279,6 +437,14 @@ void GPBMaybeClearOneof(GPBMessage *self, GPBOneofDescriptor *oneof,
//%void GPBSetMessage##NAME##Field(GPBMessage *self,
//% NAME$S GPBFieldDescriptor *field,
//% NAME$S TYPE *value) {
+//%#if defined(DEBUG) && DEBUG
+//% NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+//% GPBDataType##NAME),
+//% @"Attempting to set field %@ of %@ which is of type %@ with "
+//% @"value of type TYPE.",
+//% [self class], field.name,
+//% TypeToString(GPBGetFieldDataType(field)));
+//%#endif
//% GPBSetObjectIvarWithField(self, field, (id)value);
//%}
//%
@@ -336,7 +502,7 @@ void GPBSetRetainedObjectIvarWithFieldInternal(GPBMessage *self,
GPBDataType fieldType = GPBGetFieldDataType(field);
BOOL isMapOrArray = GPBFieldIsMapOrArray(field);
BOOL fieldIsMessage = GPBDataTypeIsMessage(fieldType);
-#ifdef DEBUG
+#if defined(DEBUG) && DEBUG
if (value == nil && !isMapOrArray && !fieldIsMessage &&
field.hasDefaultValue) {
// Setting a message to nil is an obvious way to "clear" the value
@@ -408,9 +574,11 @@ void GPBSetRetainedObjectIvarWithFieldInternal(GPBMessage *self,
if (field.fieldType == GPBFieldTypeRepeated) {
// If the old array was autocreated by us, then clear it.
if (GPBDataTypeIsObject(fieldType)) {
- GPBAutocreatedArray *autoArray = oldValue;
- if (autoArray->_autocreator == self) {
- autoArray->_autocreator = nil;
+ if ([oldValue isKindOfClass:[GPBAutocreatedArray class]]) {
+ GPBAutocreatedArray *autoArray = oldValue;
+ if (autoArray->_autocreator == self) {
+ autoArray->_autocreator = nil;
+ }
}
} else {
// Type doesn't matter, it is a GPB*Array.
@@ -423,9 +591,11 @@ void GPBSetRetainedObjectIvarWithFieldInternal(GPBMessage *self,
// If the old map was autocreated by us, then clear it.
if ((field.mapKeyDataType == GPBDataTypeString) &&
GPBDataTypeIsObject(fieldType)) {
- GPBAutocreatedDictionary *autoDict = oldValue;
- if (autoDict->_autocreator == self) {
- autoDict->_autocreator = nil;
+ if ([oldValue isKindOfClass:[GPBAutocreatedDictionary class]]) {
+ GPBAutocreatedDictionary *autoDict = oldValue;
+ if (autoDict->_autocreator == self) {
+ autoDict->_autocreator = nil;
+ }
}
} else {
// Type doesn't matter, it is a GPB*Dictionary.
@@ -495,6 +665,13 @@ int32_t GPBGetMessageEnumField(GPBMessage *self, GPBFieldDescriptor *field) {
int32_t GPBGetEnumIvarWithFieldInternal(GPBMessage *self,
GPBFieldDescriptor *field,
GPBFileSyntax syntax) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(GPBGetFieldDataType(field) == GPBDataTypeEnum,
+ @"Attempting to get value of type Enum from field %@ "
+ @"of %@ which is of type %@.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
int32_t result = GPBGetMessageInt32Field(self, field);
// If this is presevering unknown enums, make sure the value is valid before
// returning it.
@@ -515,6 +692,13 @@ void GPBSetMessageEnumField(GPBMessage *self, GPBFieldDescriptor *field,
void GPBSetEnumIvarWithFieldInternal(GPBMessage *self,
GPBFieldDescriptor *field, int32_t value,
GPBFileSyntax syntax) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(GPBGetFieldDataType(field) == GPBDataTypeEnum,
+ @"Attempting to set field %@ of %@ which is of type %@ with "
+ @"value of type Enum.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
// Don't allow in unknown values. Proto3 can use the Raw method.
if (![field isValidEnumValue:value]) {
[NSException raise:NSInvalidArgumentException
@@ -540,6 +724,13 @@ void GPBSetMessageRawEnumField(GPBMessage *self, GPBFieldDescriptor *field,
BOOL GPBGetMessageBoolField(GPBMessage *self,
GPBFieldDescriptor *field) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), GPBDataTypeBool),
+ @"Attempting to get value of type bool from field %@ "
+ @"of %@ which is of type %@.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
if (GPBGetHasIvarField(self, field)) {
// Bools are stored in the has bits to avoid needing explicit space in the
// storage structure.
@@ -565,6 +756,13 @@ void GPBSetBoolIvarWithFieldInternal(GPBMessage *self,
GPBFieldDescriptor *field,
BOOL value,
GPBFileSyntax syntax) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), GPBDataTypeBool),
+ @"Attempting to set field %@ of %@ which is of type %@ with "
+ @"value of type bool.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
GPBMessageFieldDescription *fieldDesc = field->description_;
GPBOneofDescriptor *oneof = field->containingOneof_;
if (oneof) {
@@ -591,6 +789,14 @@ void GPBSetBoolIvarWithFieldInternal(GPBMessage *self,
int32_t GPBGetMessageInt32Field(GPBMessage *self,
GPBFieldDescriptor *field) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeInt32),
+ @"Attempting to get value of int32_t from field %@ "
+ @"of %@ which is of type %@.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
if (GPBGetHasIvarField(self, field)) {
uint8_t *storage = (uint8_t *)self->messageStorage_;
int32_t *typePtr = (int32_t *)&storage[field->description_->offset];
@@ -613,14 +819,24 @@ void GPBSetInt32IvarWithFieldInternal(GPBMessage *self,
GPBFieldDescriptor *field,
int32_t value,
GPBFileSyntax syntax) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeInt32),
+ @"Attempting to set field %@ of %@ which is of type %@ with "
+ @"value of type int32_t.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
GPBOneofDescriptor *oneof = field->containingOneof_;
if (oneof) {
GPBMessageFieldDescription *fieldDesc = field->description_;
GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
}
+#if defined(DEBUG) && DEBUG
NSCAssert(self->messageStorage_ != NULL,
@"%@: All messages should have storage (from init)",
[self class]);
+#endif
#if defined(__clang_analyzer__)
if (self->messageStorage_ == NULL) return;
#endif
@@ -641,6 +857,14 @@ void GPBSetInt32IvarWithFieldInternal(GPBMessage *self,
uint32_t GPBGetMessageUInt32Field(GPBMessage *self,
GPBFieldDescriptor *field) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeUInt32),
+ @"Attempting to get value of uint32_t from field %@ "
+ @"of %@ which is of type %@.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
if (GPBGetHasIvarField(self, field)) {
uint8_t *storage = (uint8_t *)self->messageStorage_;
uint32_t *typePtr = (uint32_t *)&storage[field->description_->offset];
@@ -663,14 +887,24 @@ void GPBSetUInt32IvarWithFieldInternal(GPBMessage *self,
GPBFieldDescriptor *field,
uint32_t value,
GPBFileSyntax syntax) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeUInt32),
+ @"Attempting to set field %@ of %@ which is of type %@ with "
+ @"value of type uint32_t.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
GPBOneofDescriptor *oneof = field->containingOneof_;
if (oneof) {
GPBMessageFieldDescription *fieldDesc = field->description_;
GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
}
+#if defined(DEBUG) && DEBUG
NSCAssert(self->messageStorage_ != NULL,
@"%@: All messages should have storage (from init)",
[self class]);
+#endif
#if defined(__clang_analyzer__)
if (self->messageStorage_ == NULL) return;
#endif
@@ -691,6 +925,14 @@ void GPBSetUInt32IvarWithFieldInternal(GPBMessage *self,
int64_t GPBGetMessageInt64Field(GPBMessage *self,
GPBFieldDescriptor *field) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeInt64),
+ @"Attempting to get value of int64_t from field %@ "
+ @"of %@ which is of type %@.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
if (GPBGetHasIvarField(self, field)) {
uint8_t *storage = (uint8_t *)self->messageStorage_;
int64_t *typePtr = (int64_t *)&storage[field->description_->offset];
@@ -713,14 +955,24 @@ void GPBSetInt64IvarWithFieldInternal(GPBMessage *self,
GPBFieldDescriptor *field,
int64_t value,
GPBFileSyntax syntax) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeInt64),
+ @"Attempting to set field %@ of %@ which is of type %@ with "
+ @"value of type int64_t.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
GPBOneofDescriptor *oneof = field->containingOneof_;
if (oneof) {
GPBMessageFieldDescription *fieldDesc = field->description_;
GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
}
+#if defined(DEBUG) && DEBUG
NSCAssert(self->messageStorage_ != NULL,
@"%@: All messages should have storage (from init)",
[self class]);
+#endif
#if defined(__clang_analyzer__)
if (self->messageStorage_ == NULL) return;
#endif
@@ -741,6 +993,14 @@ void GPBSetInt64IvarWithFieldInternal(GPBMessage *self,
uint64_t GPBGetMessageUInt64Field(GPBMessage *self,
GPBFieldDescriptor *field) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeUInt64),
+ @"Attempting to get value of uint64_t from field %@ "
+ @"of %@ which is of type %@.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
if (GPBGetHasIvarField(self, field)) {
uint8_t *storage = (uint8_t *)self->messageStorage_;
uint64_t *typePtr = (uint64_t *)&storage[field->description_->offset];
@@ -763,14 +1023,24 @@ void GPBSetUInt64IvarWithFieldInternal(GPBMessage *self,
GPBFieldDescriptor *field,
uint64_t value,
GPBFileSyntax syntax) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeUInt64),
+ @"Attempting to set field %@ of %@ which is of type %@ with "
+ @"value of type uint64_t.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
GPBOneofDescriptor *oneof = field->containingOneof_;
if (oneof) {
GPBMessageFieldDescription *fieldDesc = field->description_;
GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
}
+#if defined(DEBUG) && DEBUG
NSCAssert(self->messageStorage_ != NULL,
@"%@: All messages should have storage (from init)",
[self class]);
+#endif
#if defined(__clang_analyzer__)
if (self->messageStorage_ == NULL) return;
#endif
@@ -791,6 +1061,14 @@ void GPBSetUInt64IvarWithFieldInternal(GPBMessage *self,
float GPBGetMessageFloatField(GPBMessage *self,
GPBFieldDescriptor *field) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeFloat),
+ @"Attempting to get value of float from field %@ "
+ @"of %@ which is of type %@.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
if (GPBGetHasIvarField(self, field)) {
uint8_t *storage = (uint8_t *)self->messageStorage_;
float *typePtr = (float *)&storage[field->description_->offset];
@@ -813,14 +1091,24 @@ void GPBSetFloatIvarWithFieldInternal(GPBMessage *self,
GPBFieldDescriptor *field,
float value,
GPBFileSyntax syntax) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeFloat),
+ @"Attempting to set field %@ of %@ which is of type %@ with "
+ @"value of type float.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
GPBOneofDescriptor *oneof = field->containingOneof_;
if (oneof) {
GPBMessageFieldDescription *fieldDesc = field->description_;
GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
}
+#if defined(DEBUG) && DEBUG
NSCAssert(self->messageStorage_ != NULL,
@"%@: All messages should have storage (from init)",
[self class]);
+#endif
#if defined(__clang_analyzer__)
if (self->messageStorage_ == NULL) return;
#endif
@@ -841,6 +1129,14 @@ void GPBSetFloatIvarWithFieldInternal(GPBMessage *self,
double GPBGetMessageDoubleField(GPBMessage *self,
GPBFieldDescriptor *field) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeDouble),
+ @"Attempting to get value of double from field %@ "
+ @"of %@ which is of type %@.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
if (GPBGetHasIvarField(self, field)) {
uint8_t *storage = (uint8_t *)self->messageStorage_;
double *typePtr = (double *)&storage[field->description_->offset];
@@ -863,14 +1159,24 @@ void GPBSetDoubleIvarWithFieldInternal(GPBMessage *self,
GPBFieldDescriptor *field,
double value,
GPBFileSyntax syntax) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeDouble),
+ @"Attempting to set field %@ of %@ which is of type %@ with "
+ @"value of type double.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
GPBOneofDescriptor *oneof = field->containingOneof_;
if (oneof) {
GPBMessageFieldDescription *fieldDesc = field->description_;
GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
}
+#if defined(DEBUG) && DEBUG
NSCAssert(self->messageStorage_ != NULL,
@"%@: All messages should have storage (from init)",
[self class]);
+#endif
#if defined(__clang_analyzer__)
if (self->messageStorage_ == NULL) return;
#endif
@@ -896,6 +1202,14 @@ void GPBSetDoubleIvarWithFieldInternal(GPBMessage *self,
// Only exists for public api, no core code should use this.
NSString *GPBGetMessageStringField(GPBMessage *self,
GPBFieldDescriptor *field) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeString),
+ @"Attempting to get value of NSString from field %@ "
+ @"of %@ which is of type %@.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
return (NSString *)GPBGetObjectIvarWithField(self, field);
}
@@ -903,6 +1217,14 @@ NSString *GPBGetMessageStringField(GPBMessage *self,
void GPBSetMessageStringField(GPBMessage *self,
GPBFieldDescriptor *field,
NSString *value) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeString),
+ @"Attempting to set field %@ of %@ which is of type %@ with "
+ @"value of type NSString.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
GPBSetObjectIvarWithField(self, field, (id)value);
}
@@ -912,6 +1234,14 @@ void GPBSetMessageStringField(GPBMessage *self,
// Only exists for public api, no core code should use this.
NSData *GPBGetMessageBytesField(GPBMessage *self,
GPBFieldDescriptor *field) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeBytes),
+ @"Attempting to get value of NSData from field %@ "
+ @"of %@ which is of type %@.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
return (NSData *)GPBGetObjectIvarWithField(self, field);
}
@@ -919,6 +1249,14 @@ NSData *GPBGetMessageBytesField(GPBMessage *self,
void GPBSetMessageBytesField(GPBMessage *self,
GPBFieldDescriptor *field,
NSData *value) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeBytes),
+ @"Attempting to set field %@ of %@ which is of type %@ with "
+ @"value of type NSData.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
GPBSetObjectIvarWithField(self, field, (id)value);
}
@@ -928,6 +1266,14 @@ void GPBSetMessageBytesField(GPBMessage *self,
// Only exists for public api, no core code should use this.
GPBMessage *GPBGetMessageMessageField(GPBMessage *self,
GPBFieldDescriptor *field) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeMessage),
+ @"Attempting to get value of GPBMessage from field %@ "
+ @"of %@ which is of type %@.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
return (GPBMessage *)GPBGetObjectIvarWithField(self, field);
}
@@ -935,6 +1281,14 @@ GPBMessage *GPBGetMessageMessageField(GPBMessage *self,
void GPBSetMessageMessageField(GPBMessage *self,
GPBFieldDescriptor *field,
GPBMessage *value) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeMessage),
+ @"Attempting to set field %@ of %@ which is of type %@ with "
+ @"value of type GPBMessage.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
GPBSetObjectIvarWithField(self, field, (id)value);
}
@@ -944,6 +1298,14 @@ void GPBSetMessageMessageField(GPBMessage *self,
// Only exists for public api, no core code should use this.
GPBMessage *GPBGetMessageGroupField(GPBMessage *self,
GPBFieldDescriptor *field) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeGroup),
+ @"Attempting to get value of GPBMessage from field %@ "
+ @"of %@ which is of type %@.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
return (GPBMessage *)GPBGetObjectIvarWithField(self, field);
}
@@ -951,6 +1313,14 @@ GPBMessage *GPBGetMessageGroupField(GPBMessage *self,
void GPBSetMessageGroupField(GPBMessage *self,
GPBFieldDescriptor *field,
GPBMessage *value) {
+#if defined(DEBUG) && DEBUG
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
+ GPBDataTypeGroup),
+ @"Attempting to set field %@ of %@ which is of type %@ with "
+ @"value of type GPBMessage.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+#endif
GPBSetObjectIvarWithField(self, field, (id)value);
}
@@ -1014,8 +1384,40 @@ void GPBSetMessageRepeatedField(GPBMessage *self, GPBFieldDescriptor *field, id
GPBSetObjectIvarWithField(self, field, array);
}
-#if defined(DEBUG) && DEBUG
-static NSString *TypeToStr(GPBDataType dataType) {
+static GPBDataType BaseDataType(GPBDataType type) {
+ switch (type) {
+ case GPBDataTypeSFixed32:
+ case GPBDataTypeInt32:
+ case GPBDataTypeSInt32:
+ case GPBDataTypeEnum:
+ return GPBDataTypeInt32;
+ case GPBDataTypeFixed32:
+ case GPBDataTypeUInt32:
+ return GPBDataTypeUInt32;
+ case GPBDataTypeSFixed64:
+ case GPBDataTypeInt64:
+ case GPBDataTypeSInt64:
+ return GPBDataTypeInt64;
+ case GPBDataTypeFixed64:
+ case GPBDataTypeUInt64:
+ return GPBDataTypeUInt64;
+ case GPBDataTypeMessage:
+ case GPBDataTypeGroup:
+ return GPBDataTypeMessage;
+ case GPBDataTypeBool:
+ case GPBDataTypeFloat:
+ case GPBDataTypeDouble:
+ case GPBDataTypeBytes:
+ case GPBDataTypeString:
+ return type;
+ }
+}
+
+static BOOL DataTypesEquivalent(GPBDataType type1, GPBDataType type2) {
+ return BaseDataType(type1) == BaseDataType(type2);
+}
+
+static NSString *TypeToString(GPBDataType dataType) {
switch (dataType) {
case GPBDataTypeBool:
return @"Bool";
@@ -1043,10 +1445,9 @@ static NSString *TypeToStr(GPBDataType dataType) {
case GPBDataTypeGroup:
return @"Object";
case GPBDataTypeEnum:
- return @"Bool";
+ return @"Enum";
}
}
-#endif
// GPBGetMessageMapField is defined in GPBMessage.m
@@ -1062,8 +1463,8 @@ void GPBSetMessageMapField(GPBMessage *self, GPBFieldDescriptor *field,
if (dictionary) {
GPBDataType keyDataType = field.mapKeyDataType;
GPBDataType valueDataType = GPBGetFieldDataType(field);
- NSString *keyStr = TypeToStr(keyDataType);
- NSString *valueStr = TypeToStr(valueDataType);
+ NSString *keyStr = TypeToString(keyDataType);
+ NSString *valueStr = TypeToString(valueDataType);
if (keyDataType == GPBDataTypeString) {
keyStr = @"String";
}
@@ -1093,8 +1494,11 @@ void GPBSetMessageMapField(GPBMessage *self, GPBFieldDescriptor *field,
const char *GPBMessageEncodingForSelector(SEL selector, BOOL instanceSel) {
Protocol *protocol =
objc_getProtocol(GPBStringifySymbol(GPBMessageSignatureProtocol));
+ NSCAssert(protocol, @"Missing GPBMessageSignatureProtocol");
struct objc_method_description description =
protocol_getMethodDescription(protocol, selector, NO, instanceSel);
+ NSCAssert(description.name != Nil && description.types != nil,
+ @"Missing method for selector %@", NSStringFromSelector(selector));
return description.types;
}
@@ -1770,12 +2174,21 @@ NSString *GPBDecodeTextFormatName(const uint8_t *decodeData, int32_t key,
#pragma clang diagnostic pop
-#pragma mark - GPBMessageSignatureProtocol
-
-// A series of selectors that are used solely to get @encoding values
-// for them by the dynamic protobuf runtime code. An object using the protocol
-// needs to be declared for the protocol to be valid at runtime.
-@interface GPBMessageSignatureProtocol : NSObject<GPBMessageSignatureProtocol>
-@end
-@implementation GPBMessageSignatureProtocol
-@end
+BOOL GPBClassHasSel(Class aClass, SEL sel) {
+ // NOTE: We have to use class_copyMethodList, all other runtime method
+ // lookups actually also resolve the method implementation and this
+ // is called from within those methods.
+
+ BOOL result = NO;
+ unsigned int methodCount = 0;
+ Method *methodList = class_copyMethodList(aClass, &methodCount);
+ for (unsigned int i = 0; i < methodCount; ++i) {
+ SEL methodSelector = method_getName(methodList[i]);
+ if (methodSelector == sel) {
+ result = YES;
+ break;
+ }
+ }
+ free(methodList);
+ return result;
+}
diff --git a/objectivec/GPBUtilities_PackagePrivate.h b/objectivec/GPBUtilities_PackagePrivate.h
index 274351b7..c8b21ed7 100644
--- a/objectivec/GPBUtilities_PackagePrivate.h
+++ b/objectivec/GPBUtilities_PackagePrivate.h
@@ -309,7 +309,8 @@ NSString *GPBDecodeTextFormatName(const uint8_t *decodeData, int32_t key,
// A series of selectors that are used solely to get @encoding values
// for them by the dynamic protobuf runtime code. See
-// GPBMessageEncodingForSelector for details.
+// GPBMessageEncodingForSelector for details. GPBRootObject conforms to
+// the protocol so that it is encoded in the Objective C runtime.
@protocol GPBMessageSignatureProtocol
@optional
@@ -345,4 +346,6 @@ GPB_MESSAGE_SIGNATURE_ENTRY(int32_t, Enum)
+ (id)getClassValue;
@end
+BOOL GPBClassHasSel(Class aClass, SEL sel);
+
CF_EXTERN_C_END
diff --git a/objectivec/GPBWellKnownTypes.h b/objectivec/GPBWellKnownTypes.h
index 90d96c6f..04df4178 100644
--- a/objectivec/GPBWellKnownTypes.h
+++ b/objectivec/GPBWellKnownTypes.h
@@ -112,16 +112,27 @@ typedef NS_ENUM(NSInteger, GPBWellKnownTypesErrorCode) {
* @note: Not all second/nanos combinations can be represented in a
* NSTimeInterval, so getting this could be a lossy transform.
**/
-@property(nonatomic, readwrite) NSTimeInterval timeIntervalSince1970;
+@property(nonatomic, readwrite) NSTimeInterval timeInterval;
/**
* Initializes a GPBDuration with the given NSTimeInterval.
*
- * @param timeIntervalSince1970 Time interval to configure the GPBDuration with.
+ * @param timeInterval Time interval to configure the GPBDuration with.
*
* @return A newly initialized GPBDuration.
**/
-- (instancetype)initWithTimeIntervalSince1970:(NSTimeInterval)timeIntervalSince1970;
+- (instancetype)initWithTimeInterval:(NSTimeInterval)timeInterval;
+
+// These next two methods are deprecated because GBPDuration has no need of a
+// "base" time. The older methods were about symmetry with GBPTimestamp, but
+// the unix epoch usage is too confusing.
+
+/** Deprecated, use timeInterval instead. */
+@property(nonatomic, readwrite) NSTimeInterval timeIntervalSince1970
+ __attribute__((deprecated("Use timeInterval")));
+/** Deprecated, use initWithTimeInterval: instead. */
+- (instancetype)initWithTimeIntervalSince1970:(NSTimeInterval)timeIntervalSince1970
+ __attribute__((deprecated("Use initWithTimeInterval:")));
@end
diff --git a/objectivec/GPBWellKnownTypes.m b/objectivec/GPBWellKnownTypes.m
index ed798a2e..2808afeb 100644
--- a/objectivec/GPBWellKnownTypes.m
+++ b/objectivec/GPBWellKnownTypes.m
@@ -41,15 +41,25 @@ NSString *const GPBWellKnownTypesErrorDomain =
static NSString *kTypePrefixGoogleApisCom = @"type.googleapis.com/";
-static NSTimeInterval TimeIntervalSince1970FromSecondsAndNanos(int64_t seconds,
- int32_t nanos) {
+static NSTimeInterval TimeIntervalFromSecondsAndNanos(int64_t seconds,
+ int32_t nanos) {
return seconds + (NSTimeInterval)nanos / 1e9;
}
-static int32_t SecondsAndNanosFromTimeIntervalSince1970(NSTimeInterval time,
- int64_t *outSeconds) {
+static int32_t SecondsAndNanosFromTimeInterval(NSTimeInterval time,
+ int64_t *outSeconds,
+ BOOL nanosMustBePositive) {
NSTimeInterval seconds;
NSTimeInterval nanos = modf(time, &seconds);
+
+ if (nanosMustBePositive && (nanos < 0)) {
+ // Per Timestamp.proto, nanos is non-negative and "Negative second values with
+ // fractions must still have non-negative nanos values that count forward in
+ // time. Must be from 0 to 999,999,999 inclusive."
+ --seconds;
+ nanos = 1.0 + nanos;
+ }
+
nanos *= 1e9;
*outSeconds = (int64_t)seconds;
return (int32_t)nanos;
@@ -88,8 +98,8 @@ static NSString *ParseTypeFromURL(NSString *typeURLString) {
- (instancetype)initWithTimeIntervalSince1970:(NSTimeInterval)timeIntervalSince1970 {
if ((self = [super init])) {
int64_t seconds;
- int32_t nanos = SecondsAndNanosFromTimeIntervalSince1970(
- timeIntervalSince1970, &seconds);
+ int32_t nanos = SecondsAndNanosFromTimeInterval(
+ timeIntervalSince1970, &seconds, YES);
self.seconds = seconds;
self.nanos = nanos;
}
@@ -105,13 +115,13 @@ static NSString *ParseTypeFromURL(NSString *typeURLString) {
}
- (NSTimeInterval)timeIntervalSince1970 {
- return TimeIntervalSince1970FromSecondsAndNanos(self.seconds, self.nanos);
+ return TimeIntervalFromSecondsAndNanos(self.seconds, self.nanos);
}
- (void)setTimeIntervalSince1970:(NSTimeInterval)timeIntervalSince1970 {
int64_t seconds;
int32_t nanos =
- SecondsAndNanosFromTimeIntervalSince1970(timeIntervalSince1970, &seconds);
+ SecondsAndNanosFromTimeInterval(timeIntervalSince1970, &seconds, YES);
self.seconds = seconds;
self.nanos = nanos;
}
@@ -122,29 +132,41 @@ static NSString *ParseTypeFromURL(NSString *typeURLString) {
@implementation GPBDuration (GBPWellKnownTypes)
-- (instancetype)initWithTimeIntervalSince1970:(NSTimeInterval)timeIntervalSince1970 {
+- (instancetype)initWithTimeInterval:(NSTimeInterval)timeInterval {
if ((self = [super init])) {
int64_t seconds;
- int32_t nanos = SecondsAndNanosFromTimeIntervalSince1970(
- timeIntervalSince1970, &seconds);
+ int32_t nanos = SecondsAndNanosFromTimeInterval(
+ timeInterval, &seconds, NO);
self.seconds = seconds;
self.nanos = nanos;
}
return self;
}
-- (NSTimeInterval)timeIntervalSince1970 {
- return TimeIntervalSince1970FromSecondsAndNanos(self.seconds, self.nanos);
+- (instancetype)initWithTimeIntervalSince1970:(NSTimeInterval)timeIntervalSince1970 {
+ return [self initWithTimeInterval:timeIntervalSince1970];
}
-- (void)setTimeIntervalSince1970:(NSTimeInterval)timeIntervalSince1970 {
+- (NSTimeInterval)timeInterval {
+ return TimeIntervalFromSecondsAndNanos(self.seconds, self.nanos);
+}
+
+- (void)setTimeInterval:(NSTimeInterval)timeInterval {
int64_t seconds;
int32_t nanos =
- SecondsAndNanosFromTimeIntervalSince1970(timeIntervalSince1970, &seconds);
+ SecondsAndNanosFromTimeInterval(timeInterval, &seconds, NO);
self.seconds = seconds;
self.nanos = nanos;
}
+- (NSTimeInterval)timeIntervalSince1970 {
+ return self.timeInterval;
+}
+
+- (void)setTimeIntervalSince1970:(NSTimeInterval)timeIntervalSince1970 {
+ self.timeInterval = timeIntervalSince1970;
+}
+
@end
#pragma mark - GPBAny
diff --git a/objectivec/ProtocolBuffers_OSX.xcodeproj/project.pbxproj b/objectivec/ProtocolBuffers_OSX.xcodeproj/project.pbxproj
index 7ce5d54f..266b05a1 100644
--- a/objectivec/ProtocolBuffers_OSX.xcodeproj/project.pbxproj
+++ b/objectivec/ProtocolBuffers_OSX.xcodeproj/project.pbxproj
@@ -52,11 +52,13 @@
F4487C751AADF7F500531423 /* GPBMessageTests+Runtime.m in Sources */ = {isa = PBXBuildFile; fileRef = F4487C741AADF7F500531423 /* GPBMessageTests+Runtime.m */; };
F4487C7F1AAF62CD00531423 /* GPBMessageTests+Serialization.m in Sources */ = {isa = PBXBuildFile; fileRef = F4487C7E1AAF62CD00531423 /* GPBMessageTests+Serialization.m */; };
F4487C831AAF6AB300531423 /* GPBMessageTests+Merge.m in Sources */ = {isa = PBXBuildFile; fileRef = F4487C821AAF6AB300531423 /* GPBMessageTests+Merge.m */; };
+ F4584D821ECCB52A00803AB6 /* GPBExtensionRegistryTest.m in Sources */ = {isa = PBXBuildFile; fileRef = F4584D7E1ECCB38900803AB6 /* GPBExtensionRegistryTest.m */; };
F45C69CC16DFD08D0081955B /* GPBExtensionInternals.m in Sources */ = {isa = PBXBuildFile; fileRef = F45C69CB16DFD08D0081955B /* GPBExtensionInternals.m */; };
F45E57C71AE6DC6A000B7D99 /* text_format_map_unittest_data.txt in Resources */ = {isa = PBXBuildFile; fileRef = F45E57C61AE6DC6A000B7D99 /* text_format_map_unittest_data.txt */; };
F47476E51D21A524007C7B1A /* Duration.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = 8B4248D41A92826400BC1EC6 /* Duration.pbobjc.m */; };
F47476E61D21A524007C7B1A /* Timestamp.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = 8B4248D61A92826400BC1EC6 /* Timestamp.pbobjc.m */; };
F4B51B1E1BBC610700744318 /* GPBObjectiveCPlusPlusTest.mm in Sources */ = {isa = PBXBuildFile; fileRef = F4B51B1D1BBC610700744318 /* GPBObjectiveCPlusPlusTest.mm */; };
+ F4C4B9E41E1D976300D3B61D /* GPBDictionaryTests.m in Sources */ = {isa = PBXBuildFile; fileRef = F4C4B9E21E1D974F00D3B61D /* GPBDictionaryTests.m */; };
F4E675971B21D0000054530B /* Any.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F4E675871B21D0000054530B /* Any.pbobjc.m */; };
F4E675991B21D0000054530B /* Api.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F4E675891B21D0000054530B /* Api.pbobjc.m */; };
F4E6759B1B21D0000054530B /* Empty.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F4E6758B1B21D0000054530B /* Empty.pbobjc.m */; };
@@ -179,6 +181,7 @@
F4487C821AAF6AB300531423 /* GPBMessageTests+Merge.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "GPBMessageTests+Merge.m"; sourceTree = "<group>"; };
F44929001C866B1900C2548A /* GPBCodedOutputStream_PackagePrivate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBCodedOutputStream_PackagePrivate.h; sourceTree = "<group>"; };
F451D3F51A8AAE8700B8A22C /* GPBProtocolBuffers_RuntimeSupport.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GPBProtocolBuffers_RuntimeSupport.h; sourceTree = "<group>"; };
+ F4584D7E1ECCB38900803AB6 /* GPBExtensionRegistryTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBExtensionRegistryTest.m; sourceTree = "<group>"; };
F45C69CB16DFD08D0081955B /* GPBExtensionInternals.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBExtensionInternals.m; sourceTree = "<group>"; };
F45E57C61AE6DC6A000B7D99 /* text_format_map_unittest_data.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = text_format_map_unittest_data.txt; sourceTree = "<group>"; };
F4AC9E1D1A8BEB3500BD6E83 /* unittest_cycle.proto */ = {isa = PBXFileReference; lastKnownFileType = text; path = unittest_cycle.proto; sourceTree = "<group>"; };
@@ -187,6 +190,7 @@
F4B6B8B21A9CCBDA00892426 /* GPBUnknownFieldSet_PackagePrivate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GPBUnknownFieldSet_PackagePrivate.h; sourceTree = "<group>"; };
F4B6B8B61A9CD1DE00892426 /* GPBExtensionInternals.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GPBExtensionInternals.h; sourceTree = "<group>"; };
F4B6B8B81A9CD1DE00892426 /* GPBRootObject_PackagePrivate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GPBRootObject_PackagePrivate.h; sourceTree = "<group>"; };
+ F4C4B9E21E1D974F00D3B61D /* GPBDictionaryTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBDictionaryTests.m; sourceTree = "<group>"; };
F4CF31701B162ED800BD9B06 /* unittest_objc_startup.proto */ = {isa = PBXFileReference; lastKnownFileType = text; path = unittest_objc_startup.proto; sourceTree = "<group>"; };
F4E675861B21D0000054530B /* Any.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Any.pbobjc.h; path = google/protobuf/Any.pbobjc.h; sourceTree = "<group>"; };
F4E675871B21D0000054530B /* Any.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = Any.pbobjc.m; path = google/protobuf/Any.pbobjc.m; sourceTree = "<group>"; };
@@ -393,6 +397,7 @@
7461B69D0F94FDF800A0C422 /* GPBCodedOuputStreamTests.m */,
5102DABB1891A052002037B6 /* GPBConcurrencyTests.m */,
F4353D1C1AB8822D005A6198 /* GPBDescriptorTests.m */,
+ F4C4B9E21E1D974F00D3B61D /* GPBDictionaryTests.m */,
F4353D2C1AC06F10005A6198 /* GPBDictionaryTests.pddm */,
F4353D2D1AC06F10005A6198 /* GPBDictionaryTests+Bool.m */,
F4353D2E1AC06F10005A6198 /* GPBDictionaryTests+Int32.m */,
@@ -400,6 +405,7 @@
F4353D301AC06F10005A6198 /* GPBDictionaryTests+String.m */,
F4353D311AC06F10005A6198 /* GPBDictionaryTests+UInt32.m */,
F4353D321AC06F10005A6198 /* GPBDictionaryTests+UInt64.m */,
+ F4584D7E1ECCB38900803AB6 /* GPBExtensionRegistryTest.m */,
7461B6A30F94FDF800A0C422 /* GPBMessageTests.m */,
F4487C821AAF6AB300531423 /* GPBMessageTests+Merge.m */,
F4487C741AADF7F500531423 /* GPBMessageTests+Runtime.m */,
@@ -415,8 +421,8 @@
7461B6BA0F94FDF900A0C422 /* GPBUtilitiesTests.m */,
8B4248DB1A92933A00BC1EC6 /* GPBWellKnownTypesTest.m */,
7461B6BC0F94FDF900A0C422 /* GPBWireFormatTests.m */,
- F43C88CF191D77FC009E917D /* text_format_unittest_data.txt */,
F45E57C61AE6DC6A000B7D99 /* text_format_map_unittest_data.txt */,
+ F43C88CF191D77FC009E917D /* text_format_unittest_data.txt */,
8B7E6A7414893DBA00F8884A /* unittest_custom_options.proto */,
F4AC9E1D1A8BEB3500BD6E83 /* unittest_cycle.proto */,
8B7E6A7514893DBA00F8884A /* unittest_embed_optimize_for.proto */,
@@ -426,8 +432,8 @@
8BBD9DB016DD1DC8008E1EC1 /* unittest_lite.proto */,
8B7E6A7B14893DBC00F8884A /* unittest_mset.proto */,
8B7E6A7C14893DBC00F8884A /* unittest_no_generic_services.proto */,
- 8B09AAF614B663A7007B4184 /* unittest_objc.proto */,
F4CF31701B162ED800BD9B06 /* unittest_objc_startup.proto */,
+ 8B09AAF614B663A7007B4184 /* unittest_objc.proto */,
8B7E6A7D14893DBC00F8884A /* unittest_optimize_for.proto */,
F4487C781AADFB3100531423 /* unittest_runtime_proto2.proto */,
F4487C791AADFB3200531423 /* unittest_runtime_proto3.proto */,
@@ -556,7 +562,7 @@
attributes = {
LastSwiftUpdateCheck = 0710;
LastTestingUpgradeCheck = 0600;
- LastUpgradeCheck = 0800;
+ LastUpgradeCheck = 0900;
TargetAttributes = {
8BBEA4A5147C727100C4ADB7 = {
LastSwiftMigration = 0800;
@@ -666,6 +672,7 @@
F4F8D8831D789FD9002CE128 /* GPBUnittestProtos2.m in Sources */,
F4353D1D1AB8822D005A6198 /* GPBDescriptorTests.m in Sources */,
8B4248BB1A8C256A00BC1EC6 /* GPBSwiftTests.swift in Sources */,
+ F4584D821ECCB52A00803AB6 /* GPBExtensionRegistryTest.m in Sources */,
5102DABC1891A073002037B6 /* GPBConcurrencyTests.m in Sources */,
F4487C751AADF7F500531423 /* GPBMessageTests+Runtime.m in Sources */,
F4353D351AC06F10005A6198 /* GPBDictionaryTests+Int32.m in Sources */,
@@ -677,6 +684,7 @@
F4353D371AC06F10005A6198 /* GPBDictionaryTests+String.m in Sources */,
F4353D381AC06F10005A6198 /* GPBDictionaryTests+UInt32.m in Sources */,
8BBEA4B7147C727D00C4ADB7 /* GPBUtilitiesTests.m in Sources */,
+ F4C4B9E41E1D976300D3B61D /* GPBDictionaryTests.m in Sources */,
8BBEA4B8147C727D00C4ADB7 /* GPBWireFormatTests.m in Sources */,
8BD3981F14BE59D70081D629 /* GPBUnittestProtos.m in Sources */,
8B8B615D17DF7056002EE618 /* GPBARCUnittestProtos.m in Sources */,
@@ -786,6 +794,8 @@
CLANG_ANALYZER_SECURITY_INSECUREAPI_STRCPY = YES;
CLANG_STATIC_ANALYZER_MODE = deep;
CLANG_WARN_ASSIGN_ENUM = YES;
+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
+ CLANG_WARN_COMMA = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
@@ -795,6 +805,8 @@
CLANG_WARN_OBJC_IMPLICIT_ATOMIC_PROPERTIES = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_MISSING_PROPERTY_SYNTHESIS = YES;
+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
+ CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_IMPLICIT_CONVERSION = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES_AGGRESSIVE;
@@ -852,6 +864,8 @@
CLANG_ANALYZER_SECURITY_INSECUREAPI_STRCPY = YES;
CLANG_STATIC_ANALYZER_MODE = deep;
CLANG_WARN_ASSIGN_ENUM = YES;
+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
+ CLANG_WARN_COMMA = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
@@ -861,6 +875,8 @@
CLANG_WARN_OBJC_IMPLICIT_ATOMIC_PROPERTIES = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_MISSING_PROPERTY_SYNTHESIS = YES;
+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
+ CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_IMPLICIT_CONVERSION = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES_AGGRESSIVE;
diff --git a/objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme b/objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme
index 2f618131..d3c29389 100644
--- a/objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme
+++ b/objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
- LastUpgradeVersion = "0800"
+ LastUpgradeVersion = "0900"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -26,6 +26,7 @@
buildConfiguration = "Release"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
+ language = ""
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
@@ -51,6 +52,12 @@
Identifier = "DescriptorTests">
</Test>
<Test
+ Identifier = "GPBAutocreatedArrayTests">
+ </Test>
+ <Test
+ Identifier = "GPBAutocreatedDictionaryTests">
+ </Test>
+ <Test
Identifier = "GPBBoolArrayTests">
</Test>
<Test
@@ -90,6 +97,9 @@
Identifier = "GPBEnumArrayTests">
</Test>
<Test
+ Identifier = "GPBExtensionRegistryTest">
+ </Test>
+ <Test
Identifier = "GPBFloatArrayTests">
</Test>
<Test
@@ -291,6 +301,7 @@
buildConfiguration = "Release"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
+ language = ""
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
diff --git a/objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme b/objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme
index b1243b79..e7fb8215 100644
--- a/objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme
+++ b/objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
- LastUpgradeVersion = "0800"
+ LastUpgradeVersion = "0900"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -54,6 +54,7 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
+ language = ""
shouldUseLaunchSchemeArgsEnv = "YES"
codeCoverageEnabled = "YES">
<Testables>
@@ -89,6 +90,7 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
+ language = ""
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
diff --git a/objectivec/ProtocolBuffers_iOS.xcodeproj/project.pbxproj b/objectivec/ProtocolBuffers_iOS.xcodeproj/project.pbxproj
index 5f599719..9333ea7d 100644
--- a/objectivec/ProtocolBuffers_iOS.xcodeproj/project.pbxproj
+++ b/objectivec/ProtocolBuffers_iOS.xcodeproj/project.pbxproj
@@ -60,11 +60,13 @@
F4487C771AADF84900531423 /* GPBMessageTests+Runtime.m in Sources */ = {isa = PBXBuildFile; fileRef = F4487C761AADF84900531423 /* GPBMessageTests+Runtime.m */; };
F4487C811AAF62FC00531423 /* GPBMessageTests+Serialization.m in Sources */ = {isa = PBXBuildFile; fileRef = F4487C801AAF62FC00531423 /* GPBMessageTests+Serialization.m */; };
F4487C851AAF6AC500531423 /* GPBMessageTests+Merge.m in Sources */ = {isa = PBXBuildFile; fileRef = F4487C841AAF6AC500531423 /* GPBMessageTests+Merge.m */; };
+ F4584D831ECCB53600803AB6 /* GPBExtensionRegistryTest.m in Sources */ = {isa = PBXBuildFile; fileRef = F4584D801ECCB39E00803AB6 /* GPBExtensionRegistryTest.m */; };
F45C69CC16DFD08D0081955B /* GPBExtensionInternals.m in Sources */ = {isa = PBXBuildFile; fileRef = F45C69CB16DFD08D0081955B /* GPBExtensionInternals.m */; };
F45E57C91AE6DC98000B7D99 /* text_format_map_unittest_data.txt in Resources */ = {isa = PBXBuildFile; fileRef = F45E57C81AE6DC98000B7D99 /* text_format_map_unittest_data.txt */; };
F47476E91D21A537007C7B1A /* Duration.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = 8B4248DE1A929C7D00BC1EC6 /* Duration.pbobjc.m */; };
F47476EA1D21A537007C7B1A /* Timestamp.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = 8B4248E01A929C7D00BC1EC6 /* Timestamp.pbobjc.m */; };
F4B51B1C1BBC5C7100744318 /* GPBObjectiveCPlusPlusTest.mm in Sources */ = {isa = PBXBuildFile; fileRef = F4B51B1B1BBC5C7100744318 /* GPBObjectiveCPlusPlusTest.mm */; };
+ F4C4B9E71E1D97BF00D3B61D /* GPBDictionaryTests.m in Sources */ = {isa = PBXBuildFile; fileRef = F4C4B9E51E1D97BB00D3B61D /* GPBDictionaryTests.m */; };
F4E675D01B21D1620054530B /* Any.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F4E675B71B21D1440054530B /* Any.pbobjc.m */; };
F4E675D11B21D1620054530B /* Api.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F4E675B91B21D1440054530B /* Api.pbobjc.m */; };
F4E675D21B21D1620054530B /* Empty.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F4E675BC1B21D1440054530B /* Empty.pbobjc.m */; };
@@ -201,6 +203,7 @@
F4487C841AAF6AC500531423 /* GPBMessageTests+Merge.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "GPBMessageTests+Merge.m"; sourceTree = "<group>"; };
F44929021C866B3B00C2548A /* GPBCodedOutputStream_PackagePrivate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBCodedOutputStream_PackagePrivate.h; sourceTree = "<group>"; };
F451D3F61A8AAEA600B8A22C /* GPBProtocolBuffers_RuntimeSupport.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GPBProtocolBuffers_RuntimeSupport.h; sourceTree = "<group>"; };
+ F4584D801ECCB39E00803AB6 /* GPBExtensionRegistryTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = GPBExtensionRegistryTest.m; path = Tests/GPBExtensionRegistryTest.m; sourceTree = SOURCE_ROOT; };
F45C69CB16DFD08D0081955B /* GPBExtensionInternals.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBExtensionInternals.m; sourceTree = "<group>"; };
F45E57C81AE6DC98000B7D99 /* text_format_map_unittest_data.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = text_format_map_unittest_data.txt; sourceTree = "<group>"; };
F4AC9E1C1A8BEB1000BD6E83 /* unittest_cycle.proto */ = {isa = PBXFileReference; lastKnownFileType = text; path = unittest_cycle.proto; sourceTree = "<group>"; };
@@ -209,6 +212,7 @@
F4B6B8B11A9CCBBB00892426 /* GPBUnknownFieldSet_PackagePrivate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GPBUnknownFieldSet_PackagePrivate.h; sourceTree = "<group>"; };
F4B6B8B31A9CD1C600892426 /* GPBExtensionInternals.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GPBExtensionInternals.h; sourceTree = "<group>"; };
F4B6B8B51A9CD1C600892426 /* GPBRootObject_PackagePrivate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GPBRootObject_PackagePrivate.h; sourceTree = "<group>"; };
+ F4C4B9E51E1D97BB00D3B61D /* GPBDictionaryTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBDictionaryTests.m; sourceTree = "<group>"; };
F4CF31711B162EF500BD9B06 /* unittest_objc_startup.proto */ = {isa = PBXFileReference; lastKnownFileType = text; path = unittest_objc_startup.proto; sourceTree = "<group>"; };
F4E675B61B21D1440054530B /* Any.pbobjc.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = Any.pbobjc.h; path = google/protobuf/Any.pbobjc.h; sourceTree = "<group>"; };
F4E675B71B21D1440054530B /* Any.pbobjc.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = Any.pbobjc.m; path = google/protobuf/Any.pbobjc.m; sourceTree = "<group>"; };
@@ -431,6 +435,7 @@
7461B69D0F94FDF800A0C422 /* GPBCodedOuputStreamTests.m */,
5102DABB1891A052002037B6 /* GPBConcurrencyTests.m */,
F4353D1E1AB88243005A6198 /* GPBDescriptorTests.m */,
+ F4C4B9E51E1D97BB00D3B61D /* GPBDictionaryTests.m */,
F4353D3A1AC06F31005A6198 /* GPBDictionaryTests.pddm */,
F4353D3B1AC06F31005A6198 /* GPBDictionaryTests+Bool.m */,
F4353D3C1AC06F31005A6198 /* GPBDictionaryTests+Int32.m */,
@@ -438,6 +443,7 @@
F4353D3E1AC06F31005A6198 /* GPBDictionaryTests+String.m */,
F4353D3F1AC06F31005A6198 /* GPBDictionaryTests+UInt32.m */,
F4353D401AC06F31005A6198 /* GPBDictionaryTests+UInt64.m */,
+ F4584D801ECCB39E00803AB6 /* GPBExtensionRegistryTest.m */,
7461B6A30F94FDF800A0C422 /* GPBMessageTests.m */,
F4487C841AAF6AC500531423 /* GPBMessageTests+Merge.m */,
F4487C761AADF84900531423 /* GPBMessageTests+Runtime.m */,
@@ -453,8 +459,8 @@
7461B6BA0F94FDF900A0C422 /* GPBUtilitiesTests.m */,
8B4248E51A929C9900BC1EC6 /* GPBWellKnownTypesTest.m */,
7461B6BC0F94FDF900A0C422 /* GPBWireFormatTests.m */,
- F43C88CF191D77FC009E917D /* text_format_unittest_data.txt */,
F45E57C81AE6DC98000B7D99 /* text_format_map_unittest_data.txt */,
+ F43C88CF191D77FC009E917D /* text_format_unittest_data.txt */,
8B7E6A7414893DBA00F8884A /* unittest_custom_options.proto */,
F4AC9E1C1A8BEB1000BD6E83 /* unittest_cycle.proto */,
8B7E6A7514893DBA00F8884A /* unittest_embed_optimize_for.proto */,
@@ -464,8 +470,8 @@
8BBD9DB016DD1DC8008E1EC1 /* unittest_lite.proto */,
8B7E6A7B14893DBC00F8884A /* unittest_mset.proto */,
8B7E6A7C14893DBC00F8884A /* unittest_no_generic_services.proto */,
- 8B09AAF614B663A7007B4184 /* unittest_objc.proto */,
F4CF31711B162EF500BD9B06 /* unittest_objc_startup.proto */,
+ 8B09AAF614B663A7007B4184 /* unittest_objc.proto */,
8B7E6A7D14893DBC00F8884A /* unittest_optimize_for.proto */,
F4487C7A1AADFB5500531423 /* unittest_runtime_proto2.proto */,
F4487C7B1AADFB5500531423 /* unittest_runtime_proto3.proto */,
@@ -633,7 +639,7 @@
attributes = {
LastSwiftUpdateCheck = 0710;
LastTestingUpgradeCheck = 0600;
- LastUpgradeCheck = 0800;
+ LastUpgradeCheck = 0900;
TargetAttributes = {
8BBEA4A5147C727100C4ADB7 = {
LastSwiftMigration = 0800;
@@ -762,6 +768,7 @@
F4F8D8861D78A193002CE128 /* GPBUnittestProtos2.m in Sources */,
F4B51B1C1BBC5C7100744318 /* GPBObjectiveCPlusPlusTest.mm in Sources */,
8B4248B41A8BD96E00BC1EC6 /* GPBSwiftTests.swift in Sources */,
+ F4584D831ECCB53600803AB6 /* GPBExtensionRegistryTest.m in Sources */,
5102DABC1891A073002037B6 /* GPBConcurrencyTests.m in Sources */,
F4487C771AADF84900531423 /* GPBMessageTests+Runtime.m in Sources */,
F4353D431AC06F31005A6198 /* GPBDictionaryTests+Int32.m in Sources */,
@@ -773,6 +780,7 @@
F4353D451AC06F31005A6198 /* GPBDictionaryTests+String.m in Sources */,
F4353D461AC06F31005A6198 /* GPBDictionaryTests+UInt32.m in Sources */,
8BBEA4B7147C727D00C4ADB7 /* GPBUtilitiesTests.m in Sources */,
+ F4C4B9E71E1D97BF00D3B61D /* GPBDictionaryTests.m in Sources */,
8BBEA4B8147C727D00C4ADB7 /* GPBWireFormatTests.m in Sources */,
8BD3981F14BE59D70081D629 /* GPBUnittestProtos.m in Sources */,
8B8B615D17DF7056002EE618 /* GPBARCUnittestProtos.m in Sources */,
@@ -872,7 +880,6 @@
buildSettings = {
CLANG_ENABLE_MODULES = YES;
FRAMEWORK_SEARCH_PATHS = (
- "\"$(SDKROOT)/Developer/Library/Frameworks\"",
"\"$(DEVELOPER_LIBRARY_DIR)/Frameworks\"",
"$(inherited)",
);
@@ -908,7 +915,6 @@
buildSettings = {
CLANG_ENABLE_MODULES = YES;
FRAMEWORK_SEARCH_PATHS = (
- "\"$(SDKROOT)/Developer/Library/Frameworks\"",
"\"$(DEVELOPER_LIBRARY_DIR)/Frameworks\"",
"$(inherited)",
);
@@ -948,6 +954,8 @@
CLANG_ANALYZER_SECURITY_INSECUREAPI_STRCPY = YES;
CLANG_STATIC_ANALYZER_MODE = deep;
CLANG_WARN_ASSIGN_ENUM = YES;
+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
+ CLANG_WARN_COMMA = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
@@ -957,6 +965,8 @@
CLANG_WARN_OBJC_IMPLICIT_ATOMIC_PROPERTIES = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_MISSING_PROPERTY_SYNTHESIS = YES;
+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
+ CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_IMPLICIT_CONVERSION = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES_AGGRESSIVE;
@@ -1015,6 +1025,8 @@
CLANG_ANALYZER_SECURITY_INSECUREAPI_STRCPY = YES;
CLANG_STATIC_ANALYZER_MODE = deep;
CLANG_WARN_ASSIGN_ENUM = YES;
+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
+ CLANG_WARN_COMMA = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
@@ -1024,6 +1036,8 @@
CLANG_WARN_OBJC_IMPLICIT_ATOMIC_PROPERTIES = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_MISSING_PROPERTY_SYNTHESIS = YES;
+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
+ CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_IMPLICIT_CONVERSION = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES_AGGRESSIVE;
diff --git a/objectivec/ProtocolBuffers_iOS.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme b/objectivec/ProtocolBuffers_iOS.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme
index be31c308..03acb083 100644
--- a/objectivec/ProtocolBuffers_iOS.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme
+++ b/objectivec/ProtocolBuffers_iOS.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
- LastUpgradeVersion = "0800"
+ LastUpgradeVersion = "0900"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -26,6 +26,7 @@
buildConfiguration = "Release"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
+ language = ""
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
@@ -51,6 +52,12 @@
Identifier = "DescriptorTests">
</Test>
<Test
+ Identifier = "GPBAutocreatedArrayTests">
+ </Test>
+ <Test
+ Identifier = "GPBAutocreatedDictionaryTests">
+ </Test>
+ <Test
Identifier = "GPBBoolArrayTests">
</Test>
<Test
@@ -90,6 +97,9 @@
Identifier = "GPBEnumArrayTests">
</Test>
<Test
+ Identifier = "GPBExtensionRegistryTest">
+ </Test>
+ <Test
Identifier = "GPBFloatArrayTests">
</Test>
<Test
@@ -300,6 +310,7 @@
buildConfiguration = "Release"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
+ language = ""
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
diff --git a/objectivec/ProtocolBuffers_iOS.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme b/objectivec/ProtocolBuffers_iOS.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme
index edbe6898..98bcd562 100644
--- a/objectivec/ProtocolBuffers_iOS.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme
+++ b/objectivec/ProtocolBuffers_iOS.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
- LastUpgradeVersion = "0800"
+ LastUpgradeVersion = "0900"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -54,6 +54,7 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
+ language = ""
shouldUseLaunchSchemeArgsEnv = "YES"
codeCoverageEnabled = "YES">
<Testables>
@@ -89,6 +90,7 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
+ language = ""
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
diff --git a/objectivec/Tests/GPBArrayTests.m b/objectivec/Tests/GPBArrayTests.m
index 0fb15e40..e414d90a 100644
--- a/objectivec/Tests/GPBArrayTests.m
+++ b/objectivec/Tests/GPBArrayTests.m
@@ -32,12 +32,14 @@
#import <XCTest/XCTest.h>
#import "GPBArray.h"
+#import "GPBArray_PackagePrivate.h"
#import "GPBTestUtilities.h"
// To let the testing macros work, add some extra methods to simplify things.
@interface GPBEnumArray (TestingTweak)
+ (instancetype)arrayWithValue:(int32_t)value;
++ (instancetype)arrayWithCapacity:(NSUInteger)count;
- (instancetype)initWithValues:(const int32_t [])values
count:(NSUInteger)count;
@end
@@ -71,6 +73,10 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
rawValues:&value
count:1] autorelease];
}
++ (instancetype)arrayWithCapacity:(NSUInteger)count {
+ return [[[self alloc] initWithValidationFunction:TestingEnum_IsValidValue
+ capacity:count] autorelease];
+}
- (instancetype)initWithValues:(const int32_t [])values
count:(NSUInteger)count {
return [self initWithValidationFunction:TestingEnum_IsValidValue
@@ -176,6 +182,8 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
//% XCTAssertNotEqual(idx, 0U);
//% ++idx2;
//% }];
+//% // Ensure description doesn't choke.
+//% XCTAssertTrue(array.description.length > 10);
//% [array release];
//%}
//%
@@ -200,6 +208,10 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
//% NAME$S count:GPBARRAYSIZE(kValues3)];
//% XCTAssertNotNil(array3);
//%
+//% // Identity
+//% XCTAssertTrue([array1 isEqual:array1]);
+//% // Wrong type doesn't blow up.
+//% XCTAssertFalse([array1 isEqual:@"bogus"]);
//% // 1/1Prime should be different objects, but equal.
//% XCTAssertNotEqual(array1, array1prime);
//% XCTAssertEqualObjects(array1, array1prime);
@@ -270,6 +282,12 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
//% [array add##HELPER##ValuesFromArray:array2];
//% XCTAssertEqual(array.count, 5U);
//%
+//% // Zero/nil inputs do nothing.
+//% [array addValues:kValues1 count:0];
+//% XCTAssertEqual(array.count, 5U);
+//% [array addValues:NULL count:5];
+//% XCTAssertEqual(array.count, 5U);
+//%
//% XCTAssertEqual([array valueAtIndex:0], VAL1);
//% XCTAssertEqual([array valueAtIndex:1], VAL2);
//% XCTAssertEqual([array valueAtIndex:2], VAL3);
@@ -390,9 +408,9 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
//%- (void)testInternalResizing {
//% const TYPE kValues[] = { VAL1, VAL2, VAL3, VAL4 };
//% GPB##NAME##Array *array =
-//% [[GPB##NAME##Array alloc] initWithValues:kValues
-//% NAME$S count:GPBARRAYSIZE(kValues)];
+//% [GPB##NAME##Array arrayWithCapacity:GPBARRAYSIZE(kValues)];
//% XCTAssertNotNil(array);
+//% [array addValues:kValues count:GPBARRAYSIZE(kValues)];
//%
//% // Add/remove to trigger the intneral buffer to grow/shrink.
//% for (int i = 0; i < 100; ++i) {
@@ -409,7 +427,6 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
//% XCTAssertEqual(array.count, 404U);
//% [array removeAll];
//% XCTAssertEqual(array.count, 0U);
-//% [array release];
//%}
//%
//%@end
@@ -509,6 +526,8 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
XCTAssertNotEqual(idx, 0U);
++idx2;
}];
+ // Ensure description doesn't choke.
+ XCTAssertTrue(array.description.length > 10);
[array release];
}
@@ -533,6 +552,10 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
count:GPBARRAYSIZE(kValues3)];
XCTAssertNotNil(array3);
+ // Identity
+ XCTAssertTrue([array1 isEqual:array1]);
+ // Wrong type doesn't blow up.
+ XCTAssertFalse([array1 isEqual:@"bogus"]);
// 1/1Prime should be different objects, but equal.
XCTAssertNotEqual(array1, array1prime);
XCTAssertEqualObjects(array1, array1prime);
@@ -603,6 +626,12 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
[array addValuesFromArray:array2];
XCTAssertEqual(array.count, 5U);
+ // Zero/nil inputs do nothing.
+ [array addValues:kValues1 count:0];
+ XCTAssertEqual(array.count, 5U);
+ [array addValues:NULL count:5];
+ XCTAssertEqual(array.count, 5U);
+
XCTAssertEqual([array valueAtIndex:0], 1);
XCTAssertEqual([array valueAtIndex:1], 2);
XCTAssertEqual([array valueAtIndex:2], 3);
@@ -723,9 +752,9 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
- (void)testInternalResizing {
const int32_t kValues[] = { 1, 2, 3, 4 };
GPBInt32Array *array =
- [[GPBInt32Array alloc] initWithValues:kValues
- count:GPBARRAYSIZE(kValues)];
+ [GPBInt32Array arrayWithCapacity:GPBARRAYSIZE(kValues)];
XCTAssertNotNil(array);
+ [array addValues:kValues count:GPBARRAYSIZE(kValues)];
// Add/remove to trigger the intneral buffer to grow/shrink.
for (int i = 0; i < 100; ++i) {
@@ -742,7 +771,6 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
XCTAssertEqual(array.count, 404U);
[array removeAll];
XCTAssertEqual(array.count, 0U);
- [array release];
}
@end
@@ -842,6 +870,8 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
XCTAssertNotEqual(idx, 0U);
++idx2;
}];
+ // Ensure description doesn't choke.
+ XCTAssertTrue(array.description.length > 10);
[array release];
}
@@ -866,6 +896,10 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
count:GPBARRAYSIZE(kValues3)];
XCTAssertNotNil(array3);
+ // Identity
+ XCTAssertTrue([array1 isEqual:array1]);
+ // Wrong type doesn't blow up.
+ XCTAssertFalse([array1 isEqual:@"bogus"]);
// 1/1Prime should be different objects, but equal.
XCTAssertNotEqual(array1, array1prime);
XCTAssertEqualObjects(array1, array1prime);
@@ -936,6 +970,12 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
[array addValuesFromArray:array2];
XCTAssertEqual(array.count, 5U);
+ // Zero/nil inputs do nothing.
+ [array addValues:kValues1 count:0];
+ XCTAssertEqual(array.count, 5U);
+ [array addValues:NULL count:5];
+ XCTAssertEqual(array.count, 5U);
+
XCTAssertEqual([array valueAtIndex:0], 11U);
XCTAssertEqual([array valueAtIndex:1], 12U);
XCTAssertEqual([array valueAtIndex:2], 13U);
@@ -1056,9 +1096,9 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
- (void)testInternalResizing {
const uint32_t kValues[] = { 11U, 12U, 13U, 14U };
GPBUInt32Array *array =
- [[GPBUInt32Array alloc] initWithValues:kValues
- count:GPBARRAYSIZE(kValues)];
+ [GPBUInt32Array arrayWithCapacity:GPBARRAYSIZE(kValues)];
XCTAssertNotNil(array);
+ [array addValues:kValues count:GPBARRAYSIZE(kValues)];
// Add/remove to trigger the intneral buffer to grow/shrink.
for (int i = 0; i < 100; ++i) {
@@ -1075,7 +1115,6 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
XCTAssertEqual(array.count, 404U);
[array removeAll];
XCTAssertEqual(array.count, 0U);
- [array release];
}
@end
@@ -1175,6 +1214,8 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
XCTAssertNotEqual(idx, 0U);
++idx2;
}];
+ // Ensure description doesn't choke.
+ XCTAssertTrue(array.description.length > 10);
[array release];
}
@@ -1199,6 +1240,10 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
count:GPBARRAYSIZE(kValues3)];
XCTAssertNotNil(array3);
+ // Identity
+ XCTAssertTrue([array1 isEqual:array1]);
+ // Wrong type doesn't blow up.
+ XCTAssertFalse([array1 isEqual:@"bogus"]);
// 1/1Prime should be different objects, but equal.
XCTAssertNotEqual(array1, array1prime);
XCTAssertEqualObjects(array1, array1prime);
@@ -1269,6 +1314,12 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
[array addValuesFromArray:array2];
XCTAssertEqual(array.count, 5U);
+ // Zero/nil inputs do nothing.
+ [array addValues:kValues1 count:0];
+ XCTAssertEqual(array.count, 5U);
+ [array addValues:NULL count:5];
+ XCTAssertEqual(array.count, 5U);
+
XCTAssertEqual([array valueAtIndex:0], 31LL);
XCTAssertEqual([array valueAtIndex:1], 32LL);
XCTAssertEqual([array valueAtIndex:2], 33LL);
@@ -1389,9 +1440,9 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
- (void)testInternalResizing {
const int64_t kValues[] = { 31LL, 32LL, 33LL, 34LL };
GPBInt64Array *array =
- [[GPBInt64Array alloc] initWithValues:kValues
- count:GPBARRAYSIZE(kValues)];
+ [GPBInt64Array arrayWithCapacity:GPBARRAYSIZE(kValues)];
XCTAssertNotNil(array);
+ [array addValues:kValues count:GPBARRAYSIZE(kValues)];
// Add/remove to trigger the intneral buffer to grow/shrink.
for (int i = 0; i < 100; ++i) {
@@ -1408,7 +1459,6 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
XCTAssertEqual(array.count, 404U);
[array removeAll];
XCTAssertEqual(array.count, 0U);
- [array release];
}
@end
@@ -1508,6 +1558,8 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
XCTAssertNotEqual(idx, 0U);
++idx2;
}];
+ // Ensure description doesn't choke.
+ XCTAssertTrue(array.description.length > 10);
[array release];
}
@@ -1532,6 +1584,10 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
count:GPBARRAYSIZE(kValues3)];
XCTAssertNotNil(array3);
+ // Identity
+ XCTAssertTrue([array1 isEqual:array1]);
+ // Wrong type doesn't blow up.
+ XCTAssertFalse([array1 isEqual:@"bogus"]);
// 1/1Prime should be different objects, but equal.
XCTAssertNotEqual(array1, array1prime);
XCTAssertEqualObjects(array1, array1prime);
@@ -1602,6 +1658,12 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
[array addValuesFromArray:array2];
XCTAssertEqual(array.count, 5U);
+ // Zero/nil inputs do nothing.
+ [array addValues:kValues1 count:0];
+ XCTAssertEqual(array.count, 5U);
+ [array addValues:NULL count:5];
+ XCTAssertEqual(array.count, 5U);
+
XCTAssertEqual([array valueAtIndex:0], 41ULL);
XCTAssertEqual([array valueAtIndex:1], 42ULL);
XCTAssertEqual([array valueAtIndex:2], 43ULL);
@@ -1722,9 +1784,9 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
- (void)testInternalResizing {
const uint64_t kValues[] = { 41ULL, 42ULL, 43ULL, 44ULL };
GPBUInt64Array *array =
- [[GPBUInt64Array alloc] initWithValues:kValues
- count:GPBARRAYSIZE(kValues)];
+ [GPBUInt64Array arrayWithCapacity:GPBARRAYSIZE(kValues)];
XCTAssertNotNil(array);
+ [array addValues:kValues count:GPBARRAYSIZE(kValues)];
// Add/remove to trigger the intneral buffer to grow/shrink.
for (int i = 0; i < 100; ++i) {
@@ -1741,7 +1803,6 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
XCTAssertEqual(array.count, 404U);
[array removeAll];
XCTAssertEqual(array.count, 0U);
- [array release];
}
@end
@@ -1841,6 +1902,8 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
XCTAssertNotEqual(idx, 0U);
++idx2;
}];
+ // Ensure description doesn't choke.
+ XCTAssertTrue(array.description.length > 10);
[array release];
}
@@ -1865,6 +1928,10 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
count:GPBARRAYSIZE(kValues3)];
XCTAssertNotNil(array3);
+ // Identity
+ XCTAssertTrue([array1 isEqual:array1]);
+ // Wrong type doesn't blow up.
+ XCTAssertFalse([array1 isEqual:@"bogus"]);
// 1/1Prime should be different objects, but equal.
XCTAssertNotEqual(array1, array1prime);
XCTAssertEqualObjects(array1, array1prime);
@@ -1935,6 +2002,12 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
[array addValuesFromArray:array2];
XCTAssertEqual(array.count, 5U);
+ // Zero/nil inputs do nothing.
+ [array addValues:kValues1 count:0];
+ XCTAssertEqual(array.count, 5U);
+ [array addValues:NULL count:5];
+ XCTAssertEqual(array.count, 5U);
+
XCTAssertEqual([array valueAtIndex:0], 51.f);
XCTAssertEqual([array valueAtIndex:1], 52.f);
XCTAssertEqual([array valueAtIndex:2], 53.f);
@@ -2055,9 +2128,9 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
- (void)testInternalResizing {
const float kValues[] = { 51.f, 52.f, 53.f, 54.f };
GPBFloatArray *array =
- [[GPBFloatArray alloc] initWithValues:kValues
- count:GPBARRAYSIZE(kValues)];
+ [GPBFloatArray arrayWithCapacity:GPBARRAYSIZE(kValues)];
XCTAssertNotNil(array);
+ [array addValues:kValues count:GPBARRAYSIZE(kValues)];
// Add/remove to trigger the intneral buffer to grow/shrink.
for (int i = 0; i < 100; ++i) {
@@ -2074,7 +2147,6 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
XCTAssertEqual(array.count, 404U);
[array removeAll];
XCTAssertEqual(array.count, 0U);
- [array release];
}
@end
@@ -2174,6 +2246,8 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
XCTAssertNotEqual(idx, 0U);
++idx2;
}];
+ // Ensure description doesn't choke.
+ XCTAssertTrue(array.description.length > 10);
[array release];
}
@@ -2198,6 +2272,10 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
count:GPBARRAYSIZE(kValues3)];
XCTAssertNotNil(array3);
+ // Identity
+ XCTAssertTrue([array1 isEqual:array1]);
+ // Wrong type doesn't blow up.
+ XCTAssertFalse([array1 isEqual:@"bogus"]);
// 1/1Prime should be different objects, but equal.
XCTAssertNotEqual(array1, array1prime);
XCTAssertEqualObjects(array1, array1prime);
@@ -2268,6 +2346,12 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
[array addValuesFromArray:array2];
XCTAssertEqual(array.count, 5U);
+ // Zero/nil inputs do nothing.
+ [array addValues:kValues1 count:0];
+ XCTAssertEqual(array.count, 5U);
+ [array addValues:NULL count:5];
+ XCTAssertEqual(array.count, 5U);
+
XCTAssertEqual([array valueAtIndex:0], 61.);
XCTAssertEqual([array valueAtIndex:1], 62.);
XCTAssertEqual([array valueAtIndex:2], 63.);
@@ -2388,9 +2472,9 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
- (void)testInternalResizing {
const double kValues[] = { 61., 62., 63., 64. };
GPBDoubleArray *array =
- [[GPBDoubleArray alloc] initWithValues:kValues
- count:GPBARRAYSIZE(kValues)];
+ [GPBDoubleArray arrayWithCapacity:GPBARRAYSIZE(kValues)];
XCTAssertNotNil(array);
+ [array addValues:kValues count:GPBARRAYSIZE(kValues)];
// Add/remove to trigger the intneral buffer to grow/shrink.
for (int i = 0; i < 100; ++i) {
@@ -2407,7 +2491,6 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
XCTAssertEqual(array.count, 404U);
[array removeAll];
XCTAssertEqual(array.count, 0U);
- [array release];
}
@end
@@ -2507,6 +2590,8 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
XCTAssertNotEqual(idx, 0U);
++idx2;
}];
+ // Ensure description doesn't choke.
+ XCTAssertTrue(array.description.length > 10);
[array release];
}
@@ -2531,6 +2616,10 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
count:GPBARRAYSIZE(kValues3)];
XCTAssertNotNil(array3);
+ // Identity
+ XCTAssertTrue([array1 isEqual:array1]);
+ // Wrong type doesn't blow up.
+ XCTAssertFalse([array1 isEqual:@"bogus"]);
// 1/1Prime should be different objects, but equal.
XCTAssertNotEqual(array1, array1prime);
XCTAssertEqualObjects(array1, array1prime);
@@ -2601,6 +2690,12 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
[array addValuesFromArray:array2];
XCTAssertEqual(array.count, 5U);
+ // Zero/nil inputs do nothing.
+ [array addValues:kValues1 count:0];
+ XCTAssertEqual(array.count, 5U);
+ [array addValues:NULL count:5];
+ XCTAssertEqual(array.count, 5U);
+
XCTAssertEqual([array valueAtIndex:0], TRUE);
XCTAssertEqual([array valueAtIndex:1], TRUE);
XCTAssertEqual([array valueAtIndex:2], FALSE);
@@ -2721,9 +2816,9 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
- (void)testInternalResizing {
const BOOL kValues[] = { TRUE, TRUE, FALSE, FALSE };
GPBBoolArray *array =
- [[GPBBoolArray alloc] initWithValues:kValues
- count:GPBARRAYSIZE(kValues)];
+ [GPBBoolArray arrayWithCapacity:GPBARRAYSIZE(kValues)];
XCTAssertNotNil(array);
+ [array addValues:kValues count:GPBARRAYSIZE(kValues)];
// Add/remove to trigger the intneral buffer to grow/shrink.
for (int i = 0; i < 100; ++i) {
@@ -2740,7 +2835,6 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
XCTAssertEqual(array.count, 404U);
[array removeAll];
XCTAssertEqual(array.count, 0U);
- [array release];
}
@end
@@ -2840,6 +2934,8 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
XCTAssertNotEqual(idx, 0U);
++idx2;
}];
+ // Ensure description doesn't choke.
+ XCTAssertTrue(array.description.length > 10);
[array release];
}
@@ -2864,6 +2960,10 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
count:GPBARRAYSIZE(kValues3)];
XCTAssertNotNil(array3);
+ // Identity
+ XCTAssertTrue([array1 isEqual:array1]);
+ // Wrong type doesn't blow up.
+ XCTAssertFalse([array1 isEqual:@"bogus"]);
// 1/1Prime should be different objects, but equal.
XCTAssertNotEqual(array1, array1prime);
XCTAssertEqualObjects(array1, array1prime);
@@ -2934,6 +3034,12 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
[array addRawValuesFromArray:array2];
XCTAssertEqual(array.count, 5U);
+ // Zero/nil inputs do nothing.
+ [array addValues:kValues1 count:0];
+ XCTAssertEqual(array.count, 5U);
+ [array addValues:NULL count:5];
+ XCTAssertEqual(array.count, 5U);
+
XCTAssertEqual([array valueAtIndex:0], 71);
XCTAssertEqual([array valueAtIndex:1], 72);
XCTAssertEqual([array valueAtIndex:2], 73);
@@ -3054,9 +3160,9 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
- (void)testInternalResizing {
const int32_t kValues[] = { 71, 72, 73, 74 };
GPBEnumArray *array =
- [[GPBEnumArray alloc] initWithValues:kValues
- count:GPBARRAYSIZE(kValues)];
+ [GPBEnumArray arrayWithCapacity:GPBARRAYSIZE(kValues)];
XCTAssertNotNil(array);
+ [array addValues:kValues count:GPBARRAYSIZE(kValues)];
// Add/remove to trigger the intneral buffer to grow/shrink.
for (int i = 0; i < 100; ++i) {
@@ -3073,7 +3179,6 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
XCTAssertEqual(array.count, 404U);
[array removeAll];
XCTAssertEqual(array.count, 0U);
- [array release];
}
@end
@@ -3436,3 +3541,175 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) {
}
@end
+
+#pragma mark - GPBAutocreatedArray Tests
+
+// These are hand written tests to double check some behaviors of the
+// GPBAutocreatedArray.
+
+// NOTE: GPBAutocreatedArray is private to the library, users of the library
+// should never have to directly deal with this class.
+
+@interface GPBAutocreatedArrayTests : XCTestCase
+@end
+
+@implementation GPBAutocreatedArrayTests
+
+- (void)testEquality {
+ GPBAutocreatedArray *array = [[GPBAutocreatedArray alloc] init];
+
+ XCTAssertTrue([array isEqual:@[]]);
+ XCTAssertTrue([array isEqualToArray:@[]]);
+
+ XCTAssertFalse([array isEqual:@[ @"foo" ]]);
+ XCTAssertFalse([array isEqualToArray:@[ @"foo" ]]);
+
+ [array addObject:@"foo"];
+
+ XCTAssertFalse([array isEqual:@[]]);
+ XCTAssertFalse([array isEqualToArray:@[]]);
+ XCTAssertTrue([array isEqual:@[ @"foo" ]]);
+ XCTAssertTrue([array isEqualToArray:@[ @"foo" ]]);
+ XCTAssertFalse([array isEqual:@[ @"bar" ]]);
+ XCTAssertFalse([array isEqualToArray:@[ @"bar" ]]);
+
+ GPBAutocreatedArray *array2 = [[GPBAutocreatedArray alloc] init];
+
+ XCTAssertFalse([array isEqual:array2]);
+ XCTAssertFalse([array isEqualToArray:array2]);
+
+ [array2 addObject:@"bar"];
+ XCTAssertFalse([array isEqual:array2]);
+ XCTAssertFalse([array isEqualToArray:array2]);
+
+ [array2 replaceObjectAtIndex:0 withObject:@"foo"];
+ XCTAssertTrue([array isEqual:array2]);
+ XCTAssertTrue([array isEqualToArray:array2]);
+
+ [array2 release];
+ [array release];
+}
+
+- (void)testCopy {
+ {
+ GPBAutocreatedArray *array = [[GPBAutocreatedArray alloc] init];
+
+ NSArray *cpy = [array copy];
+ XCTAssertTrue(cpy != array); // Ptr compare
+ XCTAssertTrue([cpy isKindOfClass:[NSArray class]]);
+ XCTAssertFalse([cpy isKindOfClass:[GPBAutocreatedArray class]]);
+ XCTAssertEqual(cpy.count, (NSUInteger)0);
+
+ NSArray *cpy2 = [array copy];
+ XCTAssertTrue(cpy2 != array); // Ptr compare
+ // Can't compare cpy and cpy2 because NSArray has a singleton empty
+ // array it uses, so the ptrs are the same.
+ XCTAssertTrue([cpy2 isKindOfClass:[NSArray class]]);
+ XCTAssertFalse([cpy2 isKindOfClass:[GPBAutocreatedArray class]]);
+ XCTAssertEqual(cpy2.count, (NSUInteger)0);
+
+ [cpy2 release];
+ [cpy release];
+ [array release];
+ }
+
+ {
+ GPBAutocreatedArray *array = [[GPBAutocreatedArray alloc] init];
+
+ NSMutableArray *cpy = [array mutableCopy];
+ XCTAssertTrue(cpy != array); // Ptr compare
+ XCTAssertTrue([cpy isKindOfClass:[NSMutableArray class]]);
+ XCTAssertFalse([cpy isKindOfClass:[GPBAutocreatedArray class]]);
+ XCTAssertEqual(cpy.count, (NSUInteger)0);
+
+ NSMutableArray *cpy2 = [array mutableCopy];
+ XCTAssertTrue(cpy2 != array); // Ptr compare
+ XCTAssertTrue(cpy2 != cpy); // Ptr compare
+ XCTAssertTrue([cpy2 isKindOfClass:[NSMutableArray class]]);
+ XCTAssertFalse([cpy2 isKindOfClass:[GPBAutocreatedArray class]]);
+ XCTAssertEqual(cpy2.count, (NSUInteger)0);
+
+ [cpy2 release];
+ [cpy release];
+ [array release];
+ }
+
+ {
+ GPBAutocreatedArray *array = [[GPBAutocreatedArray alloc] init];
+ [array addObject:@"foo"];
+ [array addObject:@"bar"];
+
+ NSArray *cpy = [array copy];
+ XCTAssertTrue(cpy != array); // Ptr compare
+ XCTAssertTrue([cpy isKindOfClass:[NSArray class]]);
+ XCTAssertFalse([cpy isKindOfClass:[GPBAutocreatedArray class]]);
+ XCTAssertEqual(cpy.count, (NSUInteger)2);
+ XCTAssertEqualObjects(cpy[0], @"foo");
+ XCTAssertEqualObjects(cpy[1], @"bar");
+
+ NSArray *cpy2 = [array copy];
+ XCTAssertTrue(cpy2 != array); // Ptr compare
+ XCTAssertTrue(cpy2 != cpy); // Ptr compare
+ XCTAssertTrue([cpy2 isKindOfClass:[NSArray class]]);
+ XCTAssertFalse([cpy2 isKindOfClass:[GPBAutocreatedArray class]]);
+ XCTAssertEqual(cpy2.count, (NSUInteger)2);
+ XCTAssertEqualObjects(cpy2[0], @"foo");
+ XCTAssertEqualObjects(cpy2[1], @"bar");
+
+ [cpy2 release];
+ [cpy release];
+ [array release];
+ }
+
+ {
+ GPBAutocreatedArray *array = [[GPBAutocreatedArray alloc] init];
+ [array addObject:@"foo"];
+ [array addObject:@"bar"];
+
+ NSMutableArray *cpy = [array mutableCopy];
+ XCTAssertTrue(cpy != array); // Ptr compare
+ XCTAssertTrue([cpy isKindOfClass:[NSArray class]]);
+ XCTAssertFalse([cpy isKindOfClass:[GPBAutocreatedArray class]]);
+ XCTAssertEqual(cpy.count, (NSUInteger)2);
+ XCTAssertEqualObjects(cpy[0], @"foo");
+ XCTAssertEqualObjects(cpy[1], @"bar");
+
+ NSMutableArray *cpy2 = [array mutableCopy];
+ XCTAssertTrue(cpy2 != array); // Ptr compare
+ XCTAssertTrue(cpy2 != cpy); // Ptr compare
+ XCTAssertTrue([cpy2 isKindOfClass:[NSArray class]]);
+ XCTAssertFalse([cpy2 isKindOfClass:[GPBAutocreatedArray class]]);
+ XCTAssertEqual(cpy2.count, (NSUInteger)2);
+ XCTAssertEqualObjects(cpy2[0], @"foo");
+ XCTAssertEqualObjects(cpy2[1], @"bar");
+
+ [cpy2 release];
+ [cpy release];
+ [array release];
+ }
+}
+
+- (void)testIndexedSubscriptSupport {
+ // The base NSArray/NSMutableArray behaviors for *IndexedSubscript methods
+ // should still work via the methods that one has to override to make an
+ // NSMutableArray subclass. i.e. - this should "just work" and if these
+ // crash/fail, then something is wrong in how NSMutableArray is subclassed.
+
+ GPBAutocreatedArray *array = [[GPBAutocreatedArray alloc] init];
+
+ [array addObject:@"foo"];
+ [array addObject:@"bar"];
+ XCTAssertEqual(array.count, (NSUInteger)2);
+ XCTAssertEqualObjects(array[0], @"foo");
+ XCTAssertEqualObjects(array[1], @"bar");
+ array[0] = @"foo2";
+ array[2] = @"baz";
+ XCTAssertEqual(array.count, (NSUInteger)3);
+ XCTAssertEqualObjects(array[0], @"foo2");
+ XCTAssertEqualObjects(array[1], @"bar");
+ XCTAssertEqualObjects(array[2], @"baz");
+
+ [array release];
+}
+
+@end
diff --git a/objectivec/Tests/GPBCodedInputStreamTests.m b/objectivec/Tests/GPBCodedInputStreamTests.m
index cc402156..11f7ceaf 100644
--- a/objectivec/Tests/GPBCodedInputStreamTests.m
+++ b/objectivec/Tests/GPBCodedInputStreamTests.m
@@ -62,52 +62,101 @@
#define bytes(...) [self bytes_with_sentinel:0, __VA_ARGS__, 256]
- (void)testDecodeZigZag {
- XCTAssertEqual(0, GPBDecodeZigZag32(0));
- XCTAssertEqual(-1, GPBDecodeZigZag32(1));
- XCTAssertEqual(1, GPBDecodeZigZag32(2));
- XCTAssertEqual(-2, GPBDecodeZigZag32(3));
- XCTAssertEqual((int32_t)0x3FFFFFFF, GPBDecodeZigZag32(0x7FFFFFFE));
- XCTAssertEqual((int32_t)0xC0000000, GPBDecodeZigZag32(0x7FFFFFFF));
- XCTAssertEqual((int32_t)0x7FFFFFFF, GPBDecodeZigZag32(0xFFFFFFFE));
- XCTAssertEqual((int32_t)0x80000000, GPBDecodeZigZag32(0xFFFFFFFF));
-
- XCTAssertEqual((int64_t)0, GPBDecodeZigZag64(0));
- XCTAssertEqual((int64_t)-1, GPBDecodeZigZag64(1));
- XCTAssertEqual((int64_t)1, GPBDecodeZigZag64(2));
- XCTAssertEqual((int64_t)-2, GPBDecodeZigZag64(3));
- XCTAssertEqual((int64_t)0x000000003FFFFFFFL,
- GPBDecodeZigZag64(0x000000007FFFFFFEL));
- XCTAssertEqual((int64_t)0xFFFFFFFFC0000000L,
- GPBDecodeZigZag64(0x000000007FFFFFFFL));
- XCTAssertEqual((int64_t)0x000000007FFFFFFFL,
- GPBDecodeZigZag64(0x00000000FFFFFFFEL));
- XCTAssertEqual((int64_t)0xFFFFFFFF80000000L,
- GPBDecodeZigZag64(0x00000000FFFFFFFFL));
- XCTAssertEqual((int64_t)0x7FFFFFFFFFFFFFFFL,
- GPBDecodeZigZag64(0xFFFFFFFFFFFFFFFEL));
- XCTAssertEqual((int64_t)0x8000000000000000L,
- GPBDecodeZigZag64(0xFFFFFFFFFFFFFFFFL));
+ [self assertReadZigZag32:bytes(0x0) value:0];
+ [self assertReadZigZag32:bytes(0x1) value:-1];
+ [self assertReadZigZag32:bytes(0x2) value:1];
+ [self assertReadZigZag32:bytes(0x3) value:-2];
+
+ [self assertReadZigZag32:bytes(0xFE, 0xFF, 0xFF, 0xFF, 0x07) value:(int32_t)0x3FFFFFFF];
+ [self assertReadZigZag32:bytes(0xFF, 0xFF, 0xFF, 0xFF, 0x07) value:(int32_t)0xC0000000];
+ [self assertReadZigZag32:bytes(0xFE, 0xFF, 0xFF, 0xFF, 0x0F) value:(int32_t)0x7FFFFFFF];
+ [self assertReadZigZag32:bytes(0xFF, 0xFF, 0xFF, 0xFF, 0x0F) value:(int32_t)0x80000000];
+
+ [self assertReadZigZag64:bytes(0x0) value:0];
+ [self assertReadZigZag64:bytes(0x1) value:-1];
+ [self assertReadZigZag64:bytes(0x2) value:1];
+ [self assertReadZigZag64:bytes(0x3) value:-2];
+
+ [self assertReadZigZag64:bytes(0xFE, 0xFF, 0xFF, 0xFF, 0x07) value:(int32_t)0x3FFFFFFF];
+ [self assertReadZigZag64:bytes(0xFF, 0xFF, 0xFF, 0xFF, 0x07) value:(int32_t)0xC0000000];
+ [self assertReadZigZag64:bytes(0xFE, 0xFF, 0xFF, 0xFF, 0x0F) value:(int32_t)0x7FFFFFFF];
+ [self assertReadZigZag64:bytes(0xFF, 0xFF, 0xFF, 0xFF, 0x0F) value:(int32_t)0x80000000];
+
+ [self assertReadZigZag64:bytes(0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01) value:0x7FFFFFFFFFFFFFFFL];
+ [self assertReadZigZag64:bytes(0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01) value:0x8000000000000000L];
}
- (void)assertReadVarint:(NSData*)data value:(int64_t)value {
- {
+ if (value <= INT32_MAX && value >= INT32_MIN) {
+ {
+ GPBCodedInputStream* input = [GPBCodedInputStream streamWithData:data];
+ XCTAssertEqual((int32_t)value, [input readInt32]);
+ }
+ {
+ GPBCodedInputStream* input = [GPBCodedInputStream streamWithData:data];
+ XCTAssertEqual((int32_t)value, [input readEnum]);
+ }
+ }
+ if (value <= UINT32_MAX && value >= 0) {
GPBCodedInputStream* input = [GPBCodedInputStream streamWithData:data];
- XCTAssertEqual((int32_t)value, [input readInt32]);
+ XCTAssertEqual((uint32_t)value, [input readUInt32]);
}
{
GPBCodedInputStream* input = [GPBCodedInputStream streamWithData:data];
XCTAssertEqual(value, [input readInt64]);
}
+ if (value >= 0) {
+ GPBCodedInputStream* input = [GPBCodedInputStream streamWithData:data];
+ XCTAssertEqual((uint64_t)value, [input readUInt64]);
+ }
}
- (void)assertReadLittleEndian32:(NSData*)data value:(int32_t)value {
- GPBCodedInputStream* input = [GPBCodedInputStream streamWithData:data];
- XCTAssertEqual(value, [input readSFixed32]);
+ {
+ GPBCodedInputStream* input = [GPBCodedInputStream streamWithData:data];
+ XCTAssertEqual(value, [input readSFixed32]);
+ }
+ {
+ GPBCodedInputStream* input = [GPBCodedInputStream streamWithData:data];
+ XCTAssertEqual(GPBConvertInt32ToFloat(value), [input readFloat]);
+ }
+ {
+ GPBCodedInputStream* input = [GPBCodedInputStream streamWithData:data];
+ XCTAssertEqual((uint32_t)value, [input readFixed32]);
+ }
+ {
+ GPBCodedInputStream* input = [GPBCodedInputStream streamWithData:data];
+ XCTAssertEqual(value, [input readSFixed32]);
+ }
}
- (void)assertReadLittleEndian64:(NSData*)data value:(int64_t)value {
+ {
+ GPBCodedInputStream* input = [GPBCodedInputStream streamWithData:data];
+ XCTAssertEqual(value, [input readSFixed64]);
+ }
+ {
+ GPBCodedInputStream* input = [GPBCodedInputStream streamWithData:data];
+ XCTAssertEqual(GPBConvertInt64ToDouble(value), [input readDouble]);
+ }
+ {
+ GPBCodedInputStream* input = [GPBCodedInputStream streamWithData:data];
+ XCTAssertEqual((uint64_t)value, [input readFixed64]);
+ }
+ {
+ GPBCodedInputStream* input = [GPBCodedInputStream streamWithData:data];
+ XCTAssertEqual(value, [input readSFixed64]);
+ }
+}
+
+- (void)assertReadZigZag32:(NSData*)data value:(int64_t)value {
+ GPBCodedInputStream* input = [GPBCodedInputStream streamWithData:data];
+ XCTAssertEqual((int32_t)value, [input readSInt32]);
+}
+
+- (void)assertReadZigZag64:(NSData*)data value:(int64_t)value {
GPBCodedInputStream* input = [GPBCodedInputStream streamWithData:data];
- XCTAssertEqual(value, [input readSFixed64]);
+ XCTAssertEqual(value, [input readSInt64]);
}
- (void)assertReadVarintFailure:(NSData*)data {
@@ -128,12 +177,28 @@
XCTAssertEqual(((uint8_t*)data.bytes)[1], (uint8_t)0x74);
}
+- (void)testReadBool {
+ {
+ GPBCodedInputStream* input = [GPBCodedInputStream streamWithData:bytes(0x00)];
+ XCTAssertEqual(NO, [input readBool]);
+ }
+ {
+ GPBCodedInputStream* input = [GPBCodedInputStream streamWithData:bytes(0x01)];
+ XCTAssertEqual(YES, [input readBool]);
+ }
+}
+
- (void)testReadVarint {
[self assertReadVarint:bytes(0x00) value:0];
[self assertReadVarint:bytes(0x01) value:1];
[self assertReadVarint:bytes(0x7f) value:127];
// 14882
[self assertReadVarint:bytes(0xa2, 0x74) value:(0x22 << 0) | (0x74 << 7)];
+ // 1904930
+ [self assertReadVarint:bytes(0xa2, 0xa2, 0x74) value:(0x22 << 0) | (0x22 << 7) | (0x74 << 14)];
+ // 243831074
+ [self assertReadVarint:bytes(0xa2, 0xa2, 0xa2, 0x74)
+ value:(0x22 << 0) | (0x22 << 7) | (0x22 << 14) | (0x74 << 21)];
// 2961488830
[self assertReadVarint:bytes(0xbe, 0xf7, 0x92, 0x84, 0x0b)
value:(0x3e << 0) | (0x77 << 7) | (0x12 << 14) |
@@ -163,6 +228,45 @@
[self assertReadVarintFailure:bytes(0x80)];
}
+- (void)testReadVarint32FromVarint64 {
+ {
+ // Turn on lower 31 bits of the upper half on a 64 bit varint.
+ NSData* data = bytes(0x80, 0x80, 0x80, 0x80, 0xF0, 0xFF, 0xFF, 0xFF, 0xFF, 0x7E);
+
+ int32_t value32 = 0x0;
+ GPBCodedInputStream* input32 = [GPBCodedInputStream streamWithData:data];
+ XCTAssertEqual(value32, [input32 readInt32]);
+
+ int64_t value64 = INT64_MAX & 0xFFFFFFFF00000000;
+ GPBCodedInputStream* input64 = [GPBCodedInputStream streamWithData:data];
+ XCTAssertEqual(value64, [input64 readInt64]);
+ }
+ {
+ // Turn on lower 31 bits and lower 31 bits on upper half on a 64 bit varint.
+ NSData* data = bytes(0xFF, 0xFF, 0xFF, 0xFF, 0xF7, 0xFF, 0xFF, 0xFF, 0xFF, 0x7E);
+
+ int32_t value32 = INT32_MAX;
+ GPBCodedInputStream* input32 = [GPBCodedInputStream streamWithData:data];
+ XCTAssertEqual(value32, [input32 readInt32]);
+
+ int64_t value64 = INT64_MAX & 0xFFFFFFFF7FFFFFFF;
+ GPBCodedInputStream* input64 = [GPBCodedInputStream streamWithData:data];
+ XCTAssertEqual(value64, [input64 readInt64]);
+ }
+ {
+ // Turn on bits 32 and 64 bit on a 64 bit varint.
+ NSData* data = bytes(0x80, 0x80, 0x80, 0x80, 0x88, 0x80, 0x80, 0x80, 0x80, 0x01);
+
+ int32_t value32 = INT32_MIN;
+ GPBCodedInputStream* input32 = [GPBCodedInputStream streamWithData:data];
+ XCTAssertEqual(value32, [input32 readInt32]);
+
+ int64_t value64 = INT64_MIN | (0x01LL << 31);
+ GPBCodedInputStream* input64 = [GPBCodedInputStream streamWithData:data];
+ XCTAssertEqual(value64, [input64 readInt64]);
+ }
+}
+
- (void)testReadLittleEndian {
[self assertReadLittleEndian32:bytes(0x78, 0x56, 0x34, 0x12)
value:0x12345678];
@@ -265,6 +369,27 @@
XCTAssertThrows([input readBytes]);
}
+- (void)testReadEmptyString {
+ NSData *data = bytes(0x00);
+ GPBCodedInputStream* input = [GPBCodedInputStream streamWithData:data];
+ XCTAssertEqualObjects(@"", [input readString]);
+}
+
+- (void)testInvalidGroupEndTagThrows {
+ NSData *data = bytes(0x0B, 0x1A, 0x02, 0x4B, 0x50, 0x14);
+ GPBCodedInputStream* input = [GPBCodedInputStream streamWithData:data];
+ XCTAssertThrowsSpecificNamed([input skipMessage],
+ NSException,
+ GPBCodedInputStreamException,
+ @"should throw a GPBCodedInputStreamException exception ");
+}
+
+- (void)testBytesWithNegativeSize {
+ NSData *data = bytes(0xFF, 0xFF, 0xFF, 0xFF, 0x0F);
+ GPBCodedInputStream *input = [GPBCodedInputStream streamWithData:data];
+ XCTAssertNil([input readBytes]);
+}
+
// Verifies fix for b/10315336.
// Note: Now that there isn't a custom string class under the hood, this test
// isn't as critical, but it does cover bad input and if a custom class is added
diff --git a/objectivec/Tests/GPBDescriptorTests.m b/objectivec/Tests/GPBDescriptorTests.m
index 1e1c3de8..199ea655 100644
--- a/objectivec/Tests/GPBDescriptorTests.m
+++ b/objectivec/Tests/GPBDescriptorTests.m
@@ -32,7 +32,7 @@
#import <objc/runtime.h>
-#import "GPBDescriptor.h"
+#import "GPBDescriptor_PackagePrivate.h"
#import "google/protobuf/Unittest.pbobjc.h"
#import "google/protobuf/UnittestObjc.pbobjc.h"
#import "google/protobuf/Descriptor.pbobjc.h"
@@ -83,6 +83,8 @@
XCTAssertNotNil(fieldDescriptorWithNumber.enumDescriptor);
XCTAssertEqualObjects(fieldDescriptorWithNumber.enumDescriptor.name,
@"TestAllTypes_NestedEnum");
+ XCTAssertEqual(fieldDescriptorWithName.number, fieldDescriptorWithNumber.number);
+ XCTAssertEqual(fieldDescriptorWithName.dataType, GPBDataTypeEnum);
// Foreign Enum
fieldDescriptorWithName = [descriptor fieldWithName:@"optionalForeignEnum"];
@@ -93,6 +95,8 @@
XCTAssertNotNil(fieldDescriptorWithNumber.enumDescriptor);
XCTAssertEqualObjects(fieldDescriptorWithNumber.enumDescriptor.name,
@"ForeignEnum");
+ XCTAssertEqual(fieldDescriptorWithName.number, fieldDescriptorWithNumber.number);
+ XCTAssertEqual(fieldDescriptorWithName.dataType, GPBDataTypeEnum);
// Import Enum
fieldDescriptorWithName = [descriptor fieldWithName:@"optionalImportEnum"];
@@ -103,6 +107,8 @@
XCTAssertNotNil(fieldDescriptorWithNumber.enumDescriptor);
XCTAssertEqualObjects(fieldDescriptorWithNumber.enumDescriptor.name,
@"ImportEnum");
+ XCTAssertEqual(fieldDescriptorWithName.number, fieldDescriptorWithNumber.number);
+ XCTAssertEqual(fieldDescriptorWithName.dataType, GPBDataTypeEnum);
// Nested Message
fieldDescriptorWithName = [descriptor fieldWithName:@"optionalNestedMessage"];
@@ -111,6 +117,8 @@
XCTAssertNotNil(fieldDescriptorWithNumber);
XCTAssertEqual(fieldDescriptorWithName, fieldDescriptorWithNumber);
XCTAssertNil(fieldDescriptorWithNumber.enumDescriptor);
+ XCTAssertEqual(fieldDescriptorWithName.number, fieldDescriptorWithNumber.number);
+ XCTAssertEqual(fieldDescriptorWithName.dataType, GPBDataTypeMessage);
// Foreign Message
fieldDescriptorWithName =
@@ -120,6 +128,8 @@
XCTAssertNotNil(fieldDescriptorWithNumber);
XCTAssertEqual(fieldDescriptorWithName, fieldDescriptorWithNumber);
XCTAssertNil(fieldDescriptorWithNumber.enumDescriptor);
+ XCTAssertEqual(fieldDescriptorWithName.number, fieldDescriptorWithNumber.number);
+ XCTAssertEqual(fieldDescriptorWithName.dataType, GPBDataTypeMessage);
// Import Message
fieldDescriptorWithName = [descriptor fieldWithName:@"optionalImportMessage"];
@@ -128,6 +138,12 @@
XCTAssertNotNil(fieldDescriptorWithNumber);
XCTAssertEqual(fieldDescriptorWithName, fieldDescriptorWithNumber);
XCTAssertNil(fieldDescriptorWithNumber.enumDescriptor);
+ XCTAssertEqual(fieldDescriptorWithName.number, fieldDescriptorWithNumber.number);
+ XCTAssertEqual(fieldDescriptorWithName.dataType, GPBDataTypeMessage);
+
+ // Some failed lookups.
+ XCTAssertNil([descriptor fieldWithName:@"NOT THERE"]);
+ XCTAssertNil([descriptor fieldWithNumber:9876543]);
}
- (void)testEnumDescriptor {
@@ -159,6 +175,7 @@
XCTAssertNotNil(enumName);
XCTAssertTrue([descriptor getValue:&value forEnumTextFormatName:@"FOO"]);
XCTAssertEqual(value, TestAllTypes_NestedEnum_Foo);
+ XCTAssertNil([descriptor textFormatNameForValue:99999]);
// Bad values
enumName = [descriptor enumNameForValue:0];
@@ -253,4 +270,102 @@
XCTAssertNil(bazString.containingOneof);
}
+- (void)testExtensiondDescriptor {
+ Class msgClass = [TestAllExtensions class];
+ Class packedMsgClass = [TestPackedExtensions class];
+
+ // Int
+
+ GPBExtensionDescriptor *descriptor = [UnittestRoot optionalInt32Extension];
+ XCTAssertNotNil(descriptor);
+ XCTAssertEqual(descriptor.containingMessageClass, msgClass); // ptr equality
+ XCTAssertFalse(descriptor.isPackable);
+ XCTAssertEqualObjects(descriptor.defaultValue, @0);
+ XCTAssertNil(descriptor.enumDescriptor);
+
+ descriptor = [UnittestRoot defaultInt32Extension];
+ XCTAssertNotNil(descriptor);
+ XCTAssertEqual(descriptor.containingMessageClass, msgClass); // ptr equality
+ XCTAssertFalse(descriptor.isPackable);
+ XCTAssertEqualObjects(descriptor.defaultValue, @41);
+ XCTAssertNil(descriptor.enumDescriptor);
+
+ // Enum
+
+ descriptor = [UnittestRoot optionalNestedEnumExtension];
+ XCTAssertNotNil(descriptor);
+ XCTAssertEqual(descriptor.containingMessageClass, msgClass); // ptr equality
+ XCTAssertFalse(descriptor.isPackable);
+ XCTAssertEqual(descriptor.defaultValue, @1);
+ XCTAssertEqualObjects(descriptor.enumDescriptor.name, @"TestAllTypes_NestedEnum");
+
+ descriptor = [UnittestRoot defaultNestedEnumExtension];
+ XCTAssertNotNil(descriptor);
+ XCTAssertEqual(descriptor.containingMessageClass, msgClass); // ptr equality
+ XCTAssertFalse(descriptor.isPackable);
+ XCTAssertEqual(descriptor.defaultValue, @2);
+ XCTAssertEqualObjects(descriptor.enumDescriptor.name, @"TestAllTypes_NestedEnum");
+
+ // Message
+
+ descriptor = [UnittestRoot optionalNestedMessageExtension];
+ XCTAssertNotNil(descriptor);
+ XCTAssertEqual(descriptor.containingMessageClass, msgClass); // ptr equality
+ XCTAssertFalse(descriptor.isPackable);
+ XCTAssertNil(descriptor.defaultValue);
+ XCTAssertNil(descriptor.enumDescriptor);
+
+ // Repeated Int
+
+ descriptor = [UnittestRoot repeatedInt32Extension];
+ XCTAssertNotNil(descriptor);
+ XCTAssertEqual(descriptor.containingMessageClass, msgClass); // ptr equality
+ XCTAssertFalse(descriptor.isPackable);
+ XCTAssertNil(descriptor.defaultValue);
+ XCTAssertNil(descriptor.enumDescriptor);
+
+ descriptor = [UnittestRoot packedInt32Extension];
+ XCTAssertNotNil(descriptor);
+ XCTAssertEqual(descriptor.containingMessageClass, packedMsgClass); // ptr equality
+ XCTAssertTrue(descriptor.isPackable);
+ XCTAssertNil(descriptor.defaultValue);
+ XCTAssertNil(descriptor.enumDescriptor);
+
+ // Repeated Enum
+
+ descriptor = [UnittestRoot repeatedNestedEnumExtension];
+ XCTAssertNotNil(descriptor);
+ XCTAssertEqual(descriptor.containingMessageClass, msgClass); // ptr equality
+ XCTAssertFalse(descriptor.isPackable);
+ XCTAssertNil(descriptor.defaultValue);
+ XCTAssertEqualObjects(descriptor.enumDescriptor.name, @"TestAllTypes_NestedEnum");
+
+ descriptor = [UnittestRoot packedEnumExtension];
+ XCTAssertNotNil(descriptor);
+ XCTAssertEqual(descriptor.containingMessageClass, packedMsgClass); // ptr equality
+ XCTAssertTrue(descriptor.isPackable);
+ XCTAssertNil(descriptor.defaultValue);
+ XCTAssertEqualObjects(descriptor.enumDescriptor.name, @"ForeignEnum");
+
+ // Repeated Message
+
+ descriptor = [UnittestRoot repeatedNestedMessageExtension];
+ XCTAssertNotNil(descriptor);
+ XCTAssertEqual(descriptor.containingMessageClass, msgClass); // ptr equality
+ XCTAssertFalse(descriptor.isPackable);
+ XCTAssertNil(descriptor.defaultValue);
+ XCTAssertNil(descriptor.enumDescriptor);
+
+ // Compare (used internally for serialization).
+
+ GPBExtensionDescriptor *ext1 = [UnittestRoot optionalInt32Extension];
+ XCTAssertEqual(ext1.fieldNumber, 1u);
+ GPBExtensionDescriptor *ext2 = [UnittestRoot optionalInt64Extension];
+ XCTAssertEqual(ext2.fieldNumber, 2u);
+
+ XCTAssertEqual([ext1 compareByFieldNumber:ext2], NSOrderedAscending);
+ XCTAssertEqual([ext2 compareByFieldNumber:ext1], NSOrderedDescending);
+ XCTAssertEqual([ext1 compareByFieldNumber:ext1], NSOrderedSame);
+}
+
@end
diff --git a/objectivec/Tests/GPBDictionaryTests+Bool.m b/objectivec/Tests/GPBDictionaryTests+Bool.m
index 0dbe07b6..0af0c815 100644
--- a/objectivec/Tests/GPBDictionaryTests+Bool.m
+++ b/objectivec/Tests/GPBDictionaryTests+Bool.m
@@ -63,7 +63,8 @@
}
- (void)testOne {
- GPBBoolUInt32Dictionary *dict = [GPBBoolUInt32Dictionary dictionaryWithUInt32:100U forKey:YES];
+ GPBBoolUInt32Dictionary *dict = [[GPBBoolUInt32Dictionary alloc] init];
+ [dict setUInt32:100U forKey:YES];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
uint32_t value;
@@ -76,6 +77,7 @@
XCTAssertEqual(aValue, 100U);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -214,17 +216,18 @@
XCTAssertNotNil(dict);
GPBBoolUInt32Dictionary *dict2 =
- [GPBBoolUInt32Dictionary dictionaryWithDictionary:dict];
+ [[GPBBoolUInt32Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBBoolUInt32Dictionary *dict = [GPBBoolUInt32Dictionary dictionary];
+ GPBBoolUInt32Dictionary *dict = [[GPBBoolUInt32Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -249,6 +252,7 @@
XCTAssertTrue([dict getUInt32:&value forKey:NO]);
XCTAssertEqual(value, 101U);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -364,7 +368,8 @@
}
- (void)testOne {
- GPBBoolInt32Dictionary *dict = [GPBBoolInt32Dictionary dictionaryWithInt32:200 forKey:YES];
+ GPBBoolInt32Dictionary *dict = [[GPBBoolInt32Dictionary alloc] init];
+ [dict setInt32:200 forKey:YES];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
int32_t value;
@@ -377,6 +382,7 @@
XCTAssertEqual(aValue, 200);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -515,17 +521,18 @@
XCTAssertNotNil(dict);
GPBBoolInt32Dictionary *dict2 =
- [GPBBoolInt32Dictionary dictionaryWithDictionary:dict];
+ [[GPBBoolInt32Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBBoolInt32Dictionary *dict = [GPBBoolInt32Dictionary dictionary];
+ GPBBoolInt32Dictionary *dict = [[GPBBoolInt32Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -550,6 +557,7 @@
XCTAssertTrue([dict getInt32:&value forKey:NO]);
XCTAssertEqual(value, 201);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -665,7 +673,8 @@
}
- (void)testOne {
- GPBBoolUInt64Dictionary *dict = [GPBBoolUInt64Dictionary dictionaryWithUInt64:300U forKey:YES];
+ GPBBoolUInt64Dictionary *dict = [[GPBBoolUInt64Dictionary alloc] init];
+ [dict setUInt64:300U forKey:YES];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
uint64_t value;
@@ -678,6 +687,7 @@
XCTAssertEqual(aValue, 300U);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -816,17 +826,18 @@
XCTAssertNotNil(dict);
GPBBoolUInt64Dictionary *dict2 =
- [GPBBoolUInt64Dictionary dictionaryWithDictionary:dict];
+ [[GPBBoolUInt64Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBBoolUInt64Dictionary *dict = [GPBBoolUInt64Dictionary dictionary];
+ GPBBoolUInt64Dictionary *dict = [[GPBBoolUInt64Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -851,6 +862,7 @@
XCTAssertTrue([dict getUInt64:&value forKey:NO]);
XCTAssertEqual(value, 301U);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -966,7 +978,8 @@
}
- (void)testOne {
- GPBBoolInt64Dictionary *dict = [GPBBoolInt64Dictionary dictionaryWithInt64:400 forKey:YES];
+ GPBBoolInt64Dictionary *dict = [[GPBBoolInt64Dictionary alloc] init];
+ [dict setInt64:400 forKey:YES];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
int64_t value;
@@ -979,6 +992,7 @@
XCTAssertEqual(aValue, 400);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -1117,17 +1131,18 @@
XCTAssertNotNil(dict);
GPBBoolInt64Dictionary *dict2 =
- [GPBBoolInt64Dictionary dictionaryWithDictionary:dict];
+ [[GPBBoolInt64Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBBoolInt64Dictionary *dict = [GPBBoolInt64Dictionary dictionary];
+ GPBBoolInt64Dictionary *dict = [[GPBBoolInt64Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -1152,6 +1167,7 @@
XCTAssertTrue([dict getInt64:&value forKey:NO]);
XCTAssertEqual(value, 401);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -1267,7 +1283,8 @@
}
- (void)testOne {
- GPBBoolBoolDictionary *dict = [GPBBoolBoolDictionary dictionaryWithBool:NO forKey:YES];
+ GPBBoolBoolDictionary *dict = [[GPBBoolBoolDictionary alloc] init];
+ [dict setBool:NO forKey:YES];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
BOOL value;
@@ -1280,6 +1297,7 @@
XCTAssertEqual(aValue, NO);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -1418,17 +1436,18 @@
XCTAssertNotNil(dict);
GPBBoolBoolDictionary *dict2 =
- [GPBBoolBoolDictionary dictionaryWithDictionary:dict];
+ [[GPBBoolBoolDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBBoolBoolDictionary *dict = [GPBBoolBoolDictionary dictionary];
+ GPBBoolBoolDictionary *dict = [[GPBBoolBoolDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -1453,6 +1472,7 @@
XCTAssertTrue([dict getBool:&value forKey:NO]);
XCTAssertEqual(value, YES);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -1568,7 +1588,8 @@
}
- (void)testOne {
- GPBBoolFloatDictionary *dict = [GPBBoolFloatDictionary dictionaryWithFloat:500.f forKey:YES];
+ GPBBoolFloatDictionary *dict = [[GPBBoolFloatDictionary alloc] init];
+ [dict setFloat:500.f forKey:YES];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
float value;
@@ -1581,6 +1602,7 @@
XCTAssertEqual(aValue, 500.f);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -1719,17 +1741,18 @@
XCTAssertNotNil(dict);
GPBBoolFloatDictionary *dict2 =
- [GPBBoolFloatDictionary dictionaryWithDictionary:dict];
+ [[GPBBoolFloatDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBBoolFloatDictionary *dict = [GPBBoolFloatDictionary dictionary];
+ GPBBoolFloatDictionary *dict = [[GPBBoolFloatDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -1754,6 +1777,7 @@
XCTAssertTrue([dict getFloat:&value forKey:NO]);
XCTAssertEqual(value, 501.f);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -1869,7 +1893,8 @@
}
- (void)testOne {
- GPBBoolDoubleDictionary *dict = [GPBBoolDoubleDictionary dictionaryWithDouble:600. forKey:YES];
+ GPBBoolDoubleDictionary *dict = [[GPBBoolDoubleDictionary alloc] init];
+ [dict setDouble:600. forKey:YES];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
double value;
@@ -1882,6 +1907,7 @@
XCTAssertEqual(aValue, 600.);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -2020,17 +2046,18 @@
XCTAssertNotNil(dict);
GPBBoolDoubleDictionary *dict2 =
- [GPBBoolDoubleDictionary dictionaryWithDictionary:dict];
+ [[GPBBoolDoubleDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBBoolDoubleDictionary *dict = [GPBBoolDoubleDictionary dictionary];
+ GPBBoolDoubleDictionary *dict = [[GPBBoolDoubleDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -2055,6 +2082,7 @@
XCTAssertTrue([dict getDouble:&value forKey:NO]);
XCTAssertEqual(value, 601.);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -2170,7 +2198,8 @@
}
- (void)testOne {
- GPBBoolObjectDictionary<NSString*> *dict = [GPBBoolObjectDictionary dictionaryWithObject:@"abc" forKey:YES];
+ GPBBoolObjectDictionary<NSString*> *dict = [[GPBBoolObjectDictionary alloc] init];
+ [dict setObject:@"abc" forKey:YES];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
XCTAssertEqualObjects([dict objectForKey:YES], @"abc");
@@ -2180,6 +2209,7 @@
XCTAssertEqualObjects(aObject, @"abc");
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -2313,17 +2343,18 @@
XCTAssertNotNil(dict);
GPBBoolObjectDictionary<NSString*> *dict2 =
- [GPBBoolObjectDictionary dictionaryWithDictionary:dict];
+ [[GPBBoolObjectDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBBoolObjectDictionary<NSString*> *dict = [GPBBoolObjectDictionary dictionary];
+ GPBBoolObjectDictionary<NSString*> *dict = [[GPBBoolObjectDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -2343,6 +2374,7 @@
XCTAssertEqualObjects([dict objectForKey:YES], @"abc");
XCTAssertEqualObjects([dict objectForKey:NO], @"def");
[dict2 release];
+ [dict release];
}
- (void)testRemove {
diff --git a/objectivec/Tests/GPBDictionaryTests+Int32.m b/objectivec/Tests/GPBDictionaryTests+Int32.m
index c539bdc2..4ba30203 100644
--- a/objectivec/Tests/GPBDictionaryTests+Int32.m
+++ b/objectivec/Tests/GPBDictionaryTests+Int32.m
@@ -45,7 +45,6 @@
// To let the testing macros work, add some extra methods to simplify things.
@interface GPBInt32EnumDictionary (TestingTweak)
-+ (instancetype)dictionaryWithEnum:(int32_t)value forKey:(int32_t)key;
- (instancetype)initWithEnums:(const int32_t [])values
forKeys:(const int32_t [])keys
count:(NSUInteger)count;
@@ -64,14 +63,6 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
@implementation GPBInt32EnumDictionary (TestingTweak)
-+ (instancetype)dictionaryWithEnum:(int32_t)value forKey:(int32_t)key {
- // Cast is needed to compiler knows what class we are invoking initWithValues: on to get the
- // type correct.
- return [[(GPBInt32EnumDictionary*)[self alloc] initWithValidationFunction:TestingEnum_IsValidValue
- rawValues:&value
- forKeys:&key
- count:1] autorelease];
-}
- (instancetype)initWithEnums:(const int32_t [])values
forKeys:(const int32_t [])keys
count:(NSUInteger)count {
@@ -103,7 +94,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBInt32UInt32Dictionary *dict = [GPBInt32UInt32Dictionary dictionaryWithUInt32:100U forKey:11];
+ GPBInt32UInt32Dictionary *dict = [[GPBInt32UInt32Dictionary alloc] init];
+ [dict setUInt32:100U forKey:11];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
uint32_t value;
@@ -116,6 +108,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 100U);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -258,17 +251,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt32UInt32Dictionary *dict2 =
- [GPBInt32UInt32Dictionary dictionaryWithDictionary:dict];
+ [[GPBInt32UInt32Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBInt32UInt32Dictionary *dict = [GPBInt32UInt32Dictionary dictionary];
+ GPBInt32UInt32Dictionary *dict = [[GPBInt32UInt32Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -299,6 +293,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getUInt32:&value forKey:14]);
XCTAssertEqual(value, 103U);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -460,7 +455,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBInt32Int32Dictionary *dict = [GPBInt32Int32Dictionary dictionaryWithInt32:200 forKey:11];
+ GPBInt32Int32Dictionary *dict = [[GPBInt32Int32Dictionary alloc] init];
+ [dict setInt32:200 forKey:11];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
int32_t value;
@@ -473,6 +469,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 200);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -615,17 +612,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt32Int32Dictionary *dict2 =
- [GPBInt32Int32Dictionary dictionaryWithDictionary:dict];
+ [[GPBInt32Int32Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBInt32Int32Dictionary *dict = [GPBInt32Int32Dictionary dictionary];
+ GPBInt32Int32Dictionary *dict = [[GPBInt32Int32Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -656,6 +654,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getInt32:&value forKey:14]);
XCTAssertEqual(value, 203);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -817,7 +816,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBInt32UInt64Dictionary *dict = [GPBInt32UInt64Dictionary dictionaryWithUInt64:300U forKey:11];
+ GPBInt32UInt64Dictionary *dict = [[GPBInt32UInt64Dictionary alloc] init];
+ [dict setUInt64:300U forKey:11];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
uint64_t value;
@@ -830,6 +830,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 300U);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -972,17 +973,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt32UInt64Dictionary *dict2 =
- [GPBInt32UInt64Dictionary dictionaryWithDictionary:dict];
+ [[GPBInt32UInt64Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBInt32UInt64Dictionary *dict = [GPBInt32UInt64Dictionary dictionary];
+ GPBInt32UInt64Dictionary *dict = [[GPBInt32UInt64Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -1013,6 +1015,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getUInt64:&value forKey:14]);
XCTAssertEqual(value, 303U);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -1174,7 +1177,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBInt32Int64Dictionary *dict = [GPBInt32Int64Dictionary dictionaryWithInt64:400 forKey:11];
+ GPBInt32Int64Dictionary *dict = [[GPBInt32Int64Dictionary alloc] init];
+ [dict setInt64:400 forKey:11];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
int64_t value;
@@ -1187,6 +1191,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 400);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -1329,17 +1334,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt32Int64Dictionary *dict2 =
- [GPBInt32Int64Dictionary dictionaryWithDictionary:dict];
+ [[GPBInt32Int64Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBInt32Int64Dictionary *dict = [GPBInt32Int64Dictionary dictionary];
+ GPBInt32Int64Dictionary *dict = [[GPBInt32Int64Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -1370,6 +1376,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getInt64:&value forKey:14]);
XCTAssertEqual(value, 403);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -1531,7 +1538,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBInt32BoolDictionary *dict = [GPBInt32BoolDictionary dictionaryWithBool:YES forKey:11];
+ GPBInt32BoolDictionary *dict = [[GPBInt32BoolDictionary alloc] init];
+ [dict setBool:YES forKey:11];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
BOOL value;
@@ -1544,6 +1552,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, YES);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -1686,17 +1695,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt32BoolDictionary *dict2 =
- [GPBInt32BoolDictionary dictionaryWithDictionary:dict];
+ [[GPBInt32BoolDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBInt32BoolDictionary *dict = [GPBInt32BoolDictionary dictionary];
+ GPBInt32BoolDictionary *dict = [[GPBInt32BoolDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -1727,6 +1737,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getBool:&value forKey:14]);
XCTAssertEqual(value, NO);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -1888,7 +1899,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBInt32FloatDictionary *dict = [GPBInt32FloatDictionary dictionaryWithFloat:500.f forKey:11];
+ GPBInt32FloatDictionary *dict = [[GPBInt32FloatDictionary alloc] init];
+ [dict setFloat:500.f forKey:11];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
float value;
@@ -1901,6 +1913,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 500.f);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -2043,17 +2056,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt32FloatDictionary *dict2 =
- [GPBInt32FloatDictionary dictionaryWithDictionary:dict];
+ [[GPBInt32FloatDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBInt32FloatDictionary *dict = [GPBInt32FloatDictionary dictionary];
+ GPBInt32FloatDictionary *dict = [[GPBInt32FloatDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -2084,6 +2098,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getFloat:&value forKey:14]);
XCTAssertEqual(value, 503.f);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -2245,7 +2260,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBInt32DoubleDictionary *dict = [GPBInt32DoubleDictionary dictionaryWithDouble:600. forKey:11];
+ GPBInt32DoubleDictionary *dict = [[GPBInt32DoubleDictionary alloc] init];
+ [dict setDouble:600. forKey:11];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
double value;
@@ -2258,6 +2274,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 600.);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -2400,17 +2417,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt32DoubleDictionary *dict2 =
- [GPBInt32DoubleDictionary dictionaryWithDictionary:dict];
+ [[GPBInt32DoubleDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBInt32DoubleDictionary *dict = [GPBInt32DoubleDictionary dictionary];
+ GPBInt32DoubleDictionary *dict = [[GPBInt32DoubleDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -2441,6 +2459,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getDouble:&value forKey:14]);
XCTAssertEqual(value, 603.);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -2602,7 +2621,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBInt32EnumDictionary *dict = [GPBInt32EnumDictionary dictionaryWithEnum:700 forKey:11];
+ GPBInt32EnumDictionary *dict = [[GPBInt32EnumDictionary alloc] init];
+ [dict setEnum:700 forKey:11];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
int32_t value;
@@ -2615,6 +2635,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 700);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -2757,17 +2778,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt32EnumDictionary *dict2 =
- [GPBInt32EnumDictionary dictionaryWithDictionary:dict];
+ [[GPBInt32EnumDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBInt32EnumDictionary *dict = [GPBInt32EnumDictionary dictionary];
+ GPBInt32EnumDictionary *dict = [[GPBInt32EnumDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -2798,6 +2820,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getEnum:&value forKey:14]);
XCTAssertEqual(value, 703);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -3120,19 +3143,20 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt32EnumDictionary *dict2 =
- [GPBInt32EnumDictionary dictionaryWithDictionary:dict];
+ [[GPBInt32EnumDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
XCTAssertEqual(dict.validationFunc, dict2.validationFunc); // Pointer comparison
+ [dict2 release];
[dict release];
}
- (void)testUnknownAdds {
GPBInt32EnumDictionary *dict =
- [GPBInt32EnumDictionary dictionaryWithValidationFunction:TestingEnum_IsValidValue];
+ [[GPBInt32EnumDictionary alloc] initWithValidationFunction:TestingEnum_IsValidValue];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -3172,6 +3196,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getRawValue:&value forKey:14]);
XCTAssertEqual(value, 803);
[dict2 release];
+ [dict release];
}
- (void)testUnknownRemove {
@@ -3375,7 +3400,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBInt32ObjectDictionary<NSString*> *dict = [GPBInt32ObjectDictionary dictionaryWithObject:@"abc" forKey:11];
+ GPBInt32ObjectDictionary<NSString*> *dict = [[GPBInt32ObjectDictionary alloc] init];
+ [dict setObject:@"abc" forKey:11];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
XCTAssertEqualObjects([dict objectForKey:11], @"abc");
@@ -3385,6 +3411,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqualObjects(aObject, @"abc");
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -3520,17 +3547,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt32ObjectDictionary<NSString*> *dict2 =
- [GPBInt32ObjectDictionary dictionaryWithDictionary:dict];
+ [[GPBInt32ObjectDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBInt32ObjectDictionary<NSString*> *dict = [GPBInt32ObjectDictionary dictionary];
+ GPBInt32ObjectDictionary<NSString*> *dict = [[GPBInt32ObjectDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -3552,6 +3580,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqualObjects([dict objectForKey:13], @"ghi");
XCTAssertEqualObjects([dict objectForKey:14], @"jkl");
[dict2 release];
+ [dict release];
}
- (void)testRemove {
diff --git a/objectivec/Tests/GPBDictionaryTests+Int64.m b/objectivec/Tests/GPBDictionaryTests+Int64.m
index b90cdf8c..966024b7 100644
--- a/objectivec/Tests/GPBDictionaryTests+Int64.m
+++ b/objectivec/Tests/GPBDictionaryTests+Int64.m
@@ -45,7 +45,6 @@
// To let the testing macros work, add some extra methods to simplify things.
@interface GPBInt64EnumDictionary (TestingTweak)
-+ (instancetype)dictionaryWithEnum:(int32_t)value forKey:(int64_t)key;
- (instancetype)initWithEnums:(const int32_t [])values
forKeys:(const int64_t [])keys
count:(NSUInteger)count;
@@ -64,14 +63,6 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
@implementation GPBInt64EnumDictionary (TestingTweak)
-+ (instancetype)dictionaryWithEnum:(int32_t)value forKey:(int64_t)key {
- // Cast is needed to compiler knows what class we are invoking initWithValues: on to get the
- // type correct.
- return [[(GPBInt64EnumDictionary*)[self alloc] initWithValidationFunction:TestingEnum_IsValidValue
- rawValues:&value
- forKeys:&key
- count:1] autorelease];
-}
- (instancetype)initWithEnums:(const int32_t [])values
forKeys:(const int64_t [])keys
count:(NSUInteger)count {
@@ -103,7 +94,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBInt64UInt32Dictionary *dict = [GPBInt64UInt32Dictionary dictionaryWithUInt32:100U forKey:21LL];
+ GPBInt64UInt32Dictionary *dict = [[GPBInt64UInt32Dictionary alloc] init];
+ [dict setUInt32:100U forKey:21LL];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
uint32_t value;
@@ -116,6 +108,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 100U);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -258,17 +251,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt64UInt32Dictionary *dict2 =
- [GPBInt64UInt32Dictionary dictionaryWithDictionary:dict];
+ [[GPBInt64UInt32Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBInt64UInt32Dictionary *dict = [GPBInt64UInt32Dictionary dictionary];
+ GPBInt64UInt32Dictionary *dict = [[GPBInt64UInt32Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -299,6 +293,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getUInt32:&value forKey:24LL]);
XCTAssertEqual(value, 103U);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -460,7 +455,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBInt64Int32Dictionary *dict = [GPBInt64Int32Dictionary dictionaryWithInt32:200 forKey:21LL];
+ GPBInt64Int32Dictionary *dict = [[GPBInt64Int32Dictionary alloc] init];
+ [dict setInt32:200 forKey:21LL];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
int32_t value;
@@ -473,6 +469,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 200);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -615,17 +612,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt64Int32Dictionary *dict2 =
- [GPBInt64Int32Dictionary dictionaryWithDictionary:dict];
+ [[GPBInt64Int32Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBInt64Int32Dictionary *dict = [GPBInt64Int32Dictionary dictionary];
+ GPBInt64Int32Dictionary *dict = [[GPBInt64Int32Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -656,6 +654,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getInt32:&value forKey:24LL]);
XCTAssertEqual(value, 203);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -817,7 +816,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBInt64UInt64Dictionary *dict = [GPBInt64UInt64Dictionary dictionaryWithUInt64:300U forKey:21LL];
+ GPBInt64UInt64Dictionary *dict = [[GPBInt64UInt64Dictionary alloc] init];
+ [dict setUInt64:300U forKey:21LL];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
uint64_t value;
@@ -830,6 +830,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 300U);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -972,17 +973,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt64UInt64Dictionary *dict2 =
- [GPBInt64UInt64Dictionary dictionaryWithDictionary:dict];
+ [[GPBInt64UInt64Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBInt64UInt64Dictionary *dict = [GPBInt64UInt64Dictionary dictionary];
+ GPBInt64UInt64Dictionary *dict = [[GPBInt64UInt64Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -1013,6 +1015,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getUInt64:&value forKey:24LL]);
XCTAssertEqual(value, 303U);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -1174,7 +1177,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBInt64Int64Dictionary *dict = [GPBInt64Int64Dictionary dictionaryWithInt64:400 forKey:21LL];
+ GPBInt64Int64Dictionary *dict = [[GPBInt64Int64Dictionary alloc] init];
+ [dict setInt64:400 forKey:21LL];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
int64_t value;
@@ -1187,6 +1191,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 400);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -1329,17 +1334,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt64Int64Dictionary *dict2 =
- [GPBInt64Int64Dictionary dictionaryWithDictionary:dict];
+ [[GPBInt64Int64Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBInt64Int64Dictionary *dict = [GPBInt64Int64Dictionary dictionary];
+ GPBInt64Int64Dictionary *dict = [[GPBInt64Int64Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -1370,6 +1376,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getInt64:&value forKey:24LL]);
XCTAssertEqual(value, 403);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -1531,7 +1538,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBInt64BoolDictionary *dict = [GPBInt64BoolDictionary dictionaryWithBool:YES forKey:21LL];
+ GPBInt64BoolDictionary *dict = [[GPBInt64BoolDictionary alloc] init];
+ [dict setBool:YES forKey:21LL];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
BOOL value;
@@ -1544,6 +1552,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, YES);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -1686,17 +1695,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt64BoolDictionary *dict2 =
- [GPBInt64BoolDictionary dictionaryWithDictionary:dict];
+ [[GPBInt64BoolDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBInt64BoolDictionary *dict = [GPBInt64BoolDictionary dictionary];
+ GPBInt64BoolDictionary *dict = [[GPBInt64BoolDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -1727,6 +1737,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getBool:&value forKey:24LL]);
XCTAssertEqual(value, NO);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -1888,7 +1899,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBInt64FloatDictionary *dict = [GPBInt64FloatDictionary dictionaryWithFloat:500.f forKey:21LL];
+ GPBInt64FloatDictionary *dict = [[GPBInt64FloatDictionary alloc] init];
+ [dict setFloat:500.f forKey:21LL];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
float value;
@@ -1901,6 +1913,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 500.f);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -2043,17 +2056,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt64FloatDictionary *dict2 =
- [GPBInt64FloatDictionary dictionaryWithDictionary:dict];
+ [[GPBInt64FloatDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBInt64FloatDictionary *dict = [GPBInt64FloatDictionary dictionary];
+ GPBInt64FloatDictionary *dict = [[GPBInt64FloatDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -2084,6 +2098,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getFloat:&value forKey:24LL]);
XCTAssertEqual(value, 503.f);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -2245,7 +2260,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBInt64DoubleDictionary *dict = [GPBInt64DoubleDictionary dictionaryWithDouble:600. forKey:21LL];
+ GPBInt64DoubleDictionary *dict = [[GPBInt64DoubleDictionary alloc] init];
+ [dict setDouble:600. forKey:21LL];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
double value;
@@ -2258,6 +2274,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 600.);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -2400,17 +2417,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt64DoubleDictionary *dict2 =
- [GPBInt64DoubleDictionary dictionaryWithDictionary:dict];
+ [[GPBInt64DoubleDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBInt64DoubleDictionary *dict = [GPBInt64DoubleDictionary dictionary];
+ GPBInt64DoubleDictionary *dict = [[GPBInt64DoubleDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -2441,6 +2459,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getDouble:&value forKey:24LL]);
XCTAssertEqual(value, 603.);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -2602,7 +2621,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBInt64EnumDictionary *dict = [GPBInt64EnumDictionary dictionaryWithEnum:700 forKey:21LL];
+ GPBInt64EnumDictionary *dict = [[GPBInt64EnumDictionary alloc] init];
+ [dict setEnum:700 forKey:21LL];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
int32_t value;
@@ -2615,6 +2635,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 700);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -2757,17 +2778,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt64EnumDictionary *dict2 =
- [GPBInt64EnumDictionary dictionaryWithDictionary:dict];
+ [[GPBInt64EnumDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBInt64EnumDictionary *dict = [GPBInt64EnumDictionary dictionary];
+ GPBInt64EnumDictionary *dict = [[GPBInt64EnumDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -2798,6 +2820,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getEnum:&value forKey:24LL]);
XCTAssertEqual(value, 703);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -3120,19 +3143,20 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt64EnumDictionary *dict2 =
- [GPBInt64EnumDictionary dictionaryWithDictionary:dict];
+ [[GPBInt64EnumDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
XCTAssertEqual(dict.validationFunc, dict2.validationFunc); // Pointer comparison
+ [dict2 release];
[dict release];
}
- (void)testUnknownAdds {
GPBInt64EnumDictionary *dict =
- [GPBInt64EnumDictionary dictionaryWithValidationFunction:TestingEnum_IsValidValue];
+ [[GPBInt64EnumDictionary alloc] initWithValidationFunction:TestingEnum_IsValidValue];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -3172,6 +3196,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getRawValue:&value forKey:24LL]);
XCTAssertEqual(value, 803);
[dict2 release];
+ [dict release];
}
- (void)testUnknownRemove {
@@ -3375,7 +3400,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBInt64ObjectDictionary<NSString*> *dict = [GPBInt64ObjectDictionary dictionaryWithObject:@"abc" forKey:21LL];
+ GPBInt64ObjectDictionary<NSString*> *dict = [[GPBInt64ObjectDictionary alloc] init];
+ [dict setObject:@"abc" forKey:21LL];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
XCTAssertEqualObjects([dict objectForKey:21LL], @"abc");
@@ -3385,6 +3411,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqualObjects(aObject, @"abc");
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -3520,17 +3547,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBInt64ObjectDictionary<NSString*> *dict2 =
- [GPBInt64ObjectDictionary dictionaryWithDictionary:dict];
+ [[GPBInt64ObjectDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBInt64ObjectDictionary<NSString*> *dict = [GPBInt64ObjectDictionary dictionary];
+ GPBInt64ObjectDictionary<NSString*> *dict = [[GPBInt64ObjectDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -3552,6 +3580,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqualObjects([dict objectForKey:23LL], @"ghi");
XCTAssertEqualObjects([dict objectForKey:24LL], @"jkl");
[dict2 release];
+ [dict release];
}
- (void)testRemove {
diff --git a/objectivec/Tests/GPBDictionaryTests+String.m b/objectivec/Tests/GPBDictionaryTests+String.m
index 5df1d51d..82d7952b 100644
--- a/objectivec/Tests/GPBDictionaryTests+String.m
+++ b/objectivec/Tests/GPBDictionaryTests+String.m
@@ -45,7 +45,6 @@
// To let the testing macros work, add some extra methods to simplify things.
@interface GPBStringEnumDictionary (TestingTweak)
-+ (instancetype)dictionaryWithEnum:(int32_t)value forKey:(NSString *)key;
- (instancetype)initWithEnums:(const int32_t [])values
forKeys:(const NSString * [])keys
count:(NSUInteger)count;
@@ -64,14 +63,6 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
@implementation GPBStringEnumDictionary (TestingTweak)
-+ (instancetype)dictionaryWithEnum:(int32_t)value forKey:(NSString *)key {
- // Cast is needed to compiler knows what class we are invoking initWithValues: on to get the
- // type correct.
- return [[(GPBStringEnumDictionary*)[self alloc] initWithValidationFunction:TestingEnum_IsValidValue
- rawValues:&value
- forKeys:&key
- count:1] autorelease];
-}
- (instancetype)initWithEnums:(const int32_t [])values
forKeys:(const NSString * [])keys
count:(NSUInteger)count {
@@ -103,7 +94,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBStringUInt32Dictionary *dict = [GPBStringUInt32Dictionary dictionaryWithUInt32:100U forKey:@"foo"];
+ GPBStringUInt32Dictionary *dict = [[GPBStringUInt32Dictionary alloc] init];
+ [dict setUInt32:100U forKey:@"foo"];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
uint32_t value;
@@ -116,6 +108,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 100U);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -258,17 +251,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBStringUInt32Dictionary *dict2 =
- [GPBStringUInt32Dictionary dictionaryWithDictionary:dict];
+ [[GPBStringUInt32Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBStringUInt32Dictionary *dict = [GPBStringUInt32Dictionary dictionary];
+ GPBStringUInt32Dictionary *dict = [[GPBStringUInt32Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -299,6 +293,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getUInt32:&value forKey:@"mumble"]);
XCTAssertEqual(value, 103U);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -460,7 +455,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBStringInt32Dictionary *dict = [GPBStringInt32Dictionary dictionaryWithInt32:200 forKey:@"foo"];
+ GPBStringInt32Dictionary *dict = [[GPBStringInt32Dictionary alloc] init];
+ [dict setInt32:200 forKey:@"foo"];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
int32_t value;
@@ -473,6 +469,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 200);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -615,17 +612,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBStringInt32Dictionary *dict2 =
- [GPBStringInt32Dictionary dictionaryWithDictionary:dict];
+ [[GPBStringInt32Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBStringInt32Dictionary *dict = [GPBStringInt32Dictionary dictionary];
+ GPBStringInt32Dictionary *dict = [[GPBStringInt32Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -656,6 +654,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getInt32:&value forKey:@"mumble"]);
XCTAssertEqual(value, 203);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -817,7 +816,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBStringUInt64Dictionary *dict = [GPBStringUInt64Dictionary dictionaryWithUInt64:300U forKey:@"foo"];
+ GPBStringUInt64Dictionary *dict = [[GPBStringUInt64Dictionary alloc] init];
+ [dict setUInt64:300U forKey:@"foo"];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
uint64_t value;
@@ -830,6 +830,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 300U);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -972,17 +973,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBStringUInt64Dictionary *dict2 =
- [GPBStringUInt64Dictionary dictionaryWithDictionary:dict];
+ [[GPBStringUInt64Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBStringUInt64Dictionary *dict = [GPBStringUInt64Dictionary dictionary];
+ GPBStringUInt64Dictionary *dict = [[GPBStringUInt64Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -1013,6 +1015,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getUInt64:&value forKey:@"mumble"]);
XCTAssertEqual(value, 303U);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -1174,7 +1177,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBStringInt64Dictionary *dict = [GPBStringInt64Dictionary dictionaryWithInt64:400 forKey:@"foo"];
+ GPBStringInt64Dictionary *dict = [[GPBStringInt64Dictionary alloc] init];
+ [dict setInt64:400 forKey:@"foo"];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
int64_t value;
@@ -1187,6 +1191,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 400);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -1329,17 +1334,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBStringInt64Dictionary *dict2 =
- [GPBStringInt64Dictionary dictionaryWithDictionary:dict];
+ [[GPBStringInt64Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBStringInt64Dictionary *dict = [GPBStringInt64Dictionary dictionary];
+ GPBStringInt64Dictionary *dict = [[GPBStringInt64Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -1370,6 +1376,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getInt64:&value forKey:@"mumble"]);
XCTAssertEqual(value, 403);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -1531,7 +1538,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBStringBoolDictionary *dict = [GPBStringBoolDictionary dictionaryWithBool:YES forKey:@"foo"];
+ GPBStringBoolDictionary *dict = [[GPBStringBoolDictionary alloc] init];
+ [dict setBool:YES forKey:@"foo"];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
BOOL value;
@@ -1544,6 +1552,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, YES);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -1686,17 +1695,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBStringBoolDictionary *dict2 =
- [GPBStringBoolDictionary dictionaryWithDictionary:dict];
+ [[GPBStringBoolDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBStringBoolDictionary *dict = [GPBStringBoolDictionary dictionary];
+ GPBStringBoolDictionary *dict = [[GPBStringBoolDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -1727,6 +1737,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getBool:&value forKey:@"mumble"]);
XCTAssertEqual(value, NO);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -1888,7 +1899,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBStringFloatDictionary *dict = [GPBStringFloatDictionary dictionaryWithFloat:500.f forKey:@"foo"];
+ GPBStringFloatDictionary *dict = [[GPBStringFloatDictionary alloc] init];
+ [dict setFloat:500.f forKey:@"foo"];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
float value;
@@ -1901,6 +1913,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 500.f);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -2043,17 +2056,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBStringFloatDictionary *dict2 =
- [GPBStringFloatDictionary dictionaryWithDictionary:dict];
+ [[GPBStringFloatDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBStringFloatDictionary *dict = [GPBStringFloatDictionary dictionary];
+ GPBStringFloatDictionary *dict = [[GPBStringFloatDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -2084,6 +2098,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getFloat:&value forKey:@"mumble"]);
XCTAssertEqual(value, 503.f);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -2245,7 +2260,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBStringDoubleDictionary *dict = [GPBStringDoubleDictionary dictionaryWithDouble:600. forKey:@"foo"];
+ GPBStringDoubleDictionary *dict = [[GPBStringDoubleDictionary alloc] init];
+ [dict setDouble:600. forKey:@"foo"];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
double value;
@@ -2258,6 +2274,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 600.);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -2400,17 +2417,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBStringDoubleDictionary *dict2 =
- [GPBStringDoubleDictionary dictionaryWithDictionary:dict];
+ [[GPBStringDoubleDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBStringDoubleDictionary *dict = [GPBStringDoubleDictionary dictionary];
+ GPBStringDoubleDictionary *dict = [[GPBStringDoubleDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -2441,6 +2459,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getDouble:&value forKey:@"mumble"]);
XCTAssertEqual(value, 603.);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -2602,7 +2621,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBStringEnumDictionary *dict = [GPBStringEnumDictionary dictionaryWithEnum:700 forKey:@"foo"];
+ GPBStringEnumDictionary *dict = [[GPBStringEnumDictionary alloc] init];
+ [dict setEnum:700 forKey:@"foo"];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
int32_t value;
@@ -2615,6 +2635,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 700);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -2757,17 +2778,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBStringEnumDictionary *dict2 =
- [GPBStringEnumDictionary dictionaryWithDictionary:dict];
+ [[GPBStringEnumDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBStringEnumDictionary *dict = [GPBStringEnumDictionary dictionary];
+ GPBStringEnumDictionary *dict = [[GPBStringEnumDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -2798,6 +2820,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getEnum:&value forKey:@"mumble"]);
XCTAssertEqual(value, 703);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -3120,19 +3143,20 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBStringEnumDictionary *dict2 =
- [GPBStringEnumDictionary dictionaryWithDictionary:dict];
+ [[GPBStringEnumDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
XCTAssertEqual(dict.validationFunc, dict2.validationFunc); // Pointer comparison
+ [dict2 release];
[dict release];
}
- (void)testUnknownAdds {
GPBStringEnumDictionary *dict =
- [GPBStringEnumDictionary dictionaryWithValidationFunction:TestingEnum_IsValidValue];
+ [[GPBStringEnumDictionary alloc] initWithValidationFunction:TestingEnum_IsValidValue];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -3172,6 +3196,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getRawValue:&value forKey:@"mumble"]);
XCTAssertEqual(value, 803);
[dict2 release];
+ [dict release];
}
- (void)testUnknownRemove {
diff --git a/objectivec/Tests/GPBDictionaryTests+UInt32.m b/objectivec/Tests/GPBDictionaryTests+UInt32.m
index 1d3f6f78..5314c58a 100644
--- a/objectivec/Tests/GPBDictionaryTests+UInt32.m
+++ b/objectivec/Tests/GPBDictionaryTests+UInt32.m
@@ -45,7 +45,6 @@
// To let the testing macros work, add some extra methods to simplify things.
@interface GPBUInt32EnumDictionary (TestingTweak)
-+ (instancetype)dictionaryWithEnum:(int32_t)value forKey:(uint32_t)key;
- (instancetype)initWithEnums:(const int32_t [])values
forKeys:(const uint32_t [])keys
count:(NSUInteger)count;
@@ -64,14 +63,6 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
@implementation GPBUInt32EnumDictionary (TestingTweak)
-+ (instancetype)dictionaryWithEnum:(int32_t)value forKey:(uint32_t)key {
- // Cast is needed to compiler knows what class we are invoking initWithValues: on to get the
- // type correct.
- return [[(GPBUInt32EnumDictionary*)[self alloc] initWithValidationFunction:TestingEnum_IsValidValue
- rawValues:&value
- forKeys:&key
- count:1] autorelease];
-}
- (instancetype)initWithEnums:(const int32_t [])values
forKeys:(const uint32_t [])keys
count:(NSUInteger)count {
@@ -103,7 +94,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBUInt32UInt32Dictionary *dict = [GPBUInt32UInt32Dictionary dictionaryWithUInt32:100U forKey:1U];
+ GPBUInt32UInt32Dictionary *dict = [[GPBUInt32UInt32Dictionary alloc] init];
+ [dict setUInt32:100U forKey:1U];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
uint32_t value;
@@ -116,6 +108,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 100U);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -258,17 +251,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt32UInt32Dictionary *dict2 =
- [GPBUInt32UInt32Dictionary dictionaryWithDictionary:dict];
+ [[GPBUInt32UInt32Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBUInt32UInt32Dictionary *dict = [GPBUInt32UInt32Dictionary dictionary];
+ GPBUInt32UInt32Dictionary *dict = [[GPBUInt32UInt32Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -299,6 +293,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getUInt32:&value forKey:4U]);
XCTAssertEqual(value, 103U);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -460,7 +455,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBUInt32Int32Dictionary *dict = [GPBUInt32Int32Dictionary dictionaryWithInt32:200 forKey:1U];
+ GPBUInt32Int32Dictionary *dict = [[GPBUInt32Int32Dictionary alloc] init];
+ [dict setInt32:200 forKey:1U];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
int32_t value;
@@ -473,6 +469,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 200);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -615,17 +612,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt32Int32Dictionary *dict2 =
- [GPBUInt32Int32Dictionary dictionaryWithDictionary:dict];
+ [[GPBUInt32Int32Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBUInt32Int32Dictionary *dict = [GPBUInt32Int32Dictionary dictionary];
+ GPBUInt32Int32Dictionary *dict = [[GPBUInt32Int32Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -656,6 +654,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getInt32:&value forKey:4U]);
XCTAssertEqual(value, 203);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -817,7 +816,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBUInt32UInt64Dictionary *dict = [GPBUInt32UInt64Dictionary dictionaryWithUInt64:300U forKey:1U];
+ GPBUInt32UInt64Dictionary *dict = [[GPBUInt32UInt64Dictionary alloc] init];
+ [dict setUInt64:300U forKey:1U];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
uint64_t value;
@@ -830,6 +830,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 300U);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -972,17 +973,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt32UInt64Dictionary *dict2 =
- [GPBUInt32UInt64Dictionary dictionaryWithDictionary:dict];
+ [[GPBUInt32UInt64Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBUInt32UInt64Dictionary *dict = [GPBUInt32UInt64Dictionary dictionary];
+ GPBUInt32UInt64Dictionary *dict = [[GPBUInt32UInt64Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -1013,6 +1015,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getUInt64:&value forKey:4U]);
XCTAssertEqual(value, 303U);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -1174,7 +1177,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBUInt32Int64Dictionary *dict = [GPBUInt32Int64Dictionary dictionaryWithInt64:400 forKey:1U];
+ GPBUInt32Int64Dictionary *dict = [[GPBUInt32Int64Dictionary alloc] init];
+ [dict setInt64:400 forKey:1U];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
int64_t value;
@@ -1187,6 +1191,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 400);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -1329,17 +1334,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt32Int64Dictionary *dict2 =
- [GPBUInt32Int64Dictionary dictionaryWithDictionary:dict];
+ [[GPBUInt32Int64Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBUInt32Int64Dictionary *dict = [GPBUInt32Int64Dictionary dictionary];
+ GPBUInt32Int64Dictionary *dict = [[GPBUInt32Int64Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -1370,6 +1376,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getInt64:&value forKey:4U]);
XCTAssertEqual(value, 403);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -1531,7 +1538,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBUInt32BoolDictionary *dict = [GPBUInt32BoolDictionary dictionaryWithBool:YES forKey:1U];
+ GPBUInt32BoolDictionary *dict = [[GPBUInt32BoolDictionary alloc] init];
+ [dict setBool:YES forKey:1U];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
BOOL value;
@@ -1544,6 +1552,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, YES);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -1686,17 +1695,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt32BoolDictionary *dict2 =
- [GPBUInt32BoolDictionary dictionaryWithDictionary:dict];
+ [[GPBUInt32BoolDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBUInt32BoolDictionary *dict = [GPBUInt32BoolDictionary dictionary];
+ GPBUInt32BoolDictionary *dict = [[GPBUInt32BoolDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -1727,6 +1737,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getBool:&value forKey:4U]);
XCTAssertEqual(value, NO);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -1888,7 +1899,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBUInt32FloatDictionary *dict = [GPBUInt32FloatDictionary dictionaryWithFloat:500.f forKey:1U];
+ GPBUInt32FloatDictionary *dict = [[GPBUInt32FloatDictionary alloc] init];
+ [dict setFloat:500.f forKey:1U];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
float value;
@@ -1901,6 +1913,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 500.f);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -2043,17 +2056,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt32FloatDictionary *dict2 =
- [GPBUInt32FloatDictionary dictionaryWithDictionary:dict];
+ [[GPBUInt32FloatDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBUInt32FloatDictionary *dict = [GPBUInt32FloatDictionary dictionary];
+ GPBUInt32FloatDictionary *dict = [[GPBUInt32FloatDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -2084,6 +2098,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getFloat:&value forKey:4U]);
XCTAssertEqual(value, 503.f);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -2245,7 +2260,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBUInt32DoubleDictionary *dict = [GPBUInt32DoubleDictionary dictionaryWithDouble:600. forKey:1U];
+ GPBUInt32DoubleDictionary *dict = [[GPBUInt32DoubleDictionary alloc] init];
+ [dict setDouble:600. forKey:1U];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
double value;
@@ -2258,6 +2274,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 600.);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -2400,17 +2417,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt32DoubleDictionary *dict2 =
- [GPBUInt32DoubleDictionary dictionaryWithDictionary:dict];
+ [[GPBUInt32DoubleDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBUInt32DoubleDictionary *dict = [GPBUInt32DoubleDictionary dictionary];
+ GPBUInt32DoubleDictionary *dict = [[GPBUInt32DoubleDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -2441,6 +2459,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getDouble:&value forKey:4U]);
XCTAssertEqual(value, 603.);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -2602,7 +2621,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBUInt32EnumDictionary *dict = [GPBUInt32EnumDictionary dictionaryWithEnum:700 forKey:1U];
+ GPBUInt32EnumDictionary *dict = [[GPBUInt32EnumDictionary alloc] init];
+ [dict setEnum:700 forKey:1U];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
int32_t value;
@@ -2615,6 +2635,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 700);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -2757,17 +2778,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt32EnumDictionary *dict2 =
- [GPBUInt32EnumDictionary dictionaryWithDictionary:dict];
+ [[GPBUInt32EnumDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBUInt32EnumDictionary *dict = [GPBUInt32EnumDictionary dictionary];
+ GPBUInt32EnumDictionary *dict = [[GPBUInt32EnumDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -2798,6 +2820,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getEnum:&value forKey:4U]);
XCTAssertEqual(value, 703);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -3120,19 +3143,20 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt32EnumDictionary *dict2 =
- [GPBUInt32EnumDictionary dictionaryWithDictionary:dict];
+ [[GPBUInt32EnumDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
XCTAssertEqual(dict.validationFunc, dict2.validationFunc); // Pointer comparison
+ [dict2 release];
[dict release];
}
- (void)testUnknownAdds {
GPBUInt32EnumDictionary *dict =
- [GPBUInt32EnumDictionary dictionaryWithValidationFunction:TestingEnum_IsValidValue];
+ [[GPBUInt32EnumDictionary alloc] initWithValidationFunction:TestingEnum_IsValidValue];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -3172,6 +3196,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getRawValue:&value forKey:4U]);
XCTAssertEqual(value, 803);
[dict2 release];
+ [dict release];
}
- (void)testUnknownRemove {
@@ -3375,7 +3400,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBUInt32ObjectDictionary<NSString*> *dict = [GPBUInt32ObjectDictionary dictionaryWithObject:@"abc" forKey:1U];
+ GPBUInt32ObjectDictionary<NSString*> *dict = [[GPBUInt32ObjectDictionary alloc] init];
+ [dict setObject:@"abc" forKey:1U];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
XCTAssertEqualObjects([dict objectForKey:1U], @"abc");
@@ -3385,6 +3411,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqualObjects(aObject, @"abc");
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -3520,17 +3547,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt32ObjectDictionary<NSString*> *dict2 =
- [GPBUInt32ObjectDictionary dictionaryWithDictionary:dict];
+ [[GPBUInt32ObjectDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBUInt32ObjectDictionary<NSString*> *dict = [GPBUInt32ObjectDictionary dictionary];
+ GPBUInt32ObjectDictionary<NSString*> *dict = [[GPBUInt32ObjectDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -3552,6 +3580,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqualObjects([dict objectForKey:3U], @"ghi");
XCTAssertEqualObjects([dict objectForKey:4U], @"jkl");
[dict2 release];
+ [dict release];
}
- (void)testRemove {
diff --git a/objectivec/Tests/GPBDictionaryTests+UInt64.m b/objectivec/Tests/GPBDictionaryTests+UInt64.m
index 94c116f6..ccd063f5 100644
--- a/objectivec/Tests/GPBDictionaryTests+UInt64.m
+++ b/objectivec/Tests/GPBDictionaryTests+UInt64.m
@@ -45,7 +45,6 @@
// To let the testing macros work, add some extra methods to simplify things.
@interface GPBUInt64EnumDictionary (TestingTweak)
-+ (instancetype)dictionaryWithEnum:(int32_t)value forKey:(uint64_t)key;
- (instancetype)initWithEnums:(const int32_t [])values
forKeys:(const uint64_t [])keys
count:(NSUInteger)count;
@@ -64,14 +63,6 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
@implementation GPBUInt64EnumDictionary (TestingTweak)
-+ (instancetype)dictionaryWithEnum:(int32_t)value forKey:(uint64_t)key {
- // Cast is needed to compiler knows what class we are invoking initWithValues: on to get the
- // type correct.
- return [[(GPBUInt64EnumDictionary*)[self alloc] initWithValidationFunction:TestingEnum_IsValidValue
- rawValues:&value
- forKeys:&key
- count:1] autorelease];
-}
- (instancetype)initWithEnums:(const int32_t [])values
forKeys:(const uint64_t [])keys
count:(NSUInteger)count {
@@ -103,7 +94,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBUInt64UInt32Dictionary *dict = [GPBUInt64UInt32Dictionary dictionaryWithUInt32:100U forKey:31ULL];
+ GPBUInt64UInt32Dictionary *dict = [[GPBUInt64UInt32Dictionary alloc] init];
+ [dict setUInt32:100U forKey:31ULL];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
uint32_t value;
@@ -116,6 +108,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 100U);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -258,17 +251,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt64UInt32Dictionary *dict2 =
- [GPBUInt64UInt32Dictionary dictionaryWithDictionary:dict];
+ [[GPBUInt64UInt32Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBUInt64UInt32Dictionary *dict = [GPBUInt64UInt32Dictionary dictionary];
+ GPBUInt64UInt32Dictionary *dict = [[GPBUInt64UInt32Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -299,6 +293,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getUInt32:&value forKey:34ULL]);
XCTAssertEqual(value, 103U);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -460,7 +455,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBUInt64Int32Dictionary *dict = [GPBUInt64Int32Dictionary dictionaryWithInt32:200 forKey:31ULL];
+ GPBUInt64Int32Dictionary *dict = [[GPBUInt64Int32Dictionary alloc] init];
+ [dict setInt32:200 forKey:31ULL];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
int32_t value;
@@ -473,6 +469,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 200);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -615,17 +612,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt64Int32Dictionary *dict2 =
- [GPBUInt64Int32Dictionary dictionaryWithDictionary:dict];
+ [[GPBUInt64Int32Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBUInt64Int32Dictionary *dict = [GPBUInt64Int32Dictionary dictionary];
+ GPBUInt64Int32Dictionary *dict = [[GPBUInt64Int32Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -656,6 +654,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getInt32:&value forKey:34ULL]);
XCTAssertEqual(value, 203);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -817,7 +816,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBUInt64UInt64Dictionary *dict = [GPBUInt64UInt64Dictionary dictionaryWithUInt64:300U forKey:31ULL];
+ GPBUInt64UInt64Dictionary *dict = [[GPBUInt64UInt64Dictionary alloc] init];
+ [dict setUInt64:300U forKey:31ULL];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
uint64_t value;
@@ -830,6 +830,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 300U);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -972,17 +973,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt64UInt64Dictionary *dict2 =
- [GPBUInt64UInt64Dictionary dictionaryWithDictionary:dict];
+ [[GPBUInt64UInt64Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBUInt64UInt64Dictionary *dict = [GPBUInt64UInt64Dictionary dictionary];
+ GPBUInt64UInt64Dictionary *dict = [[GPBUInt64UInt64Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -1013,6 +1015,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getUInt64:&value forKey:34ULL]);
XCTAssertEqual(value, 303U);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -1174,7 +1177,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBUInt64Int64Dictionary *dict = [GPBUInt64Int64Dictionary dictionaryWithInt64:400 forKey:31ULL];
+ GPBUInt64Int64Dictionary *dict = [[GPBUInt64Int64Dictionary alloc] init];
+ [dict setInt64:400 forKey:31ULL];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
int64_t value;
@@ -1187,6 +1191,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 400);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -1329,17 +1334,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt64Int64Dictionary *dict2 =
- [GPBUInt64Int64Dictionary dictionaryWithDictionary:dict];
+ [[GPBUInt64Int64Dictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBUInt64Int64Dictionary *dict = [GPBUInt64Int64Dictionary dictionary];
+ GPBUInt64Int64Dictionary *dict = [[GPBUInt64Int64Dictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -1370,6 +1376,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getInt64:&value forKey:34ULL]);
XCTAssertEqual(value, 403);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -1531,7 +1538,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBUInt64BoolDictionary *dict = [GPBUInt64BoolDictionary dictionaryWithBool:YES forKey:31ULL];
+ GPBUInt64BoolDictionary *dict = [[GPBUInt64BoolDictionary alloc] init];
+ [dict setBool:YES forKey:31ULL];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
BOOL value;
@@ -1544,6 +1552,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, YES);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -1686,17 +1695,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt64BoolDictionary *dict2 =
- [GPBUInt64BoolDictionary dictionaryWithDictionary:dict];
+ [[GPBUInt64BoolDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBUInt64BoolDictionary *dict = [GPBUInt64BoolDictionary dictionary];
+ GPBUInt64BoolDictionary *dict = [[GPBUInt64BoolDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -1727,6 +1737,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getBool:&value forKey:34ULL]);
XCTAssertEqual(value, NO);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -1888,7 +1899,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBUInt64FloatDictionary *dict = [GPBUInt64FloatDictionary dictionaryWithFloat:500.f forKey:31ULL];
+ GPBUInt64FloatDictionary *dict = [[GPBUInt64FloatDictionary alloc] init];
+ [dict setFloat:500.f forKey:31ULL];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
float value;
@@ -1901,6 +1913,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 500.f);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -2043,17 +2056,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt64FloatDictionary *dict2 =
- [GPBUInt64FloatDictionary dictionaryWithDictionary:dict];
+ [[GPBUInt64FloatDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBUInt64FloatDictionary *dict = [GPBUInt64FloatDictionary dictionary];
+ GPBUInt64FloatDictionary *dict = [[GPBUInt64FloatDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -2084,6 +2098,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getFloat:&value forKey:34ULL]);
XCTAssertEqual(value, 503.f);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -2245,7 +2260,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBUInt64DoubleDictionary *dict = [GPBUInt64DoubleDictionary dictionaryWithDouble:600. forKey:31ULL];
+ GPBUInt64DoubleDictionary *dict = [[GPBUInt64DoubleDictionary alloc] init];
+ [dict setDouble:600. forKey:31ULL];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
double value;
@@ -2258,6 +2274,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 600.);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -2400,17 +2417,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt64DoubleDictionary *dict2 =
- [GPBUInt64DoubleDictionary dictionaryWithDictionary:dict];
+ [[GPBUInt64DoubleDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBUInt64DoubleDictionary *dict = [GPBUInt64DoubleDictionary dictionary];
+ GPBUInt64DoubleDictionary *dict = [[GPBUInt64DoubleDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -2441,6 +2459,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getDouble:&value forKey:34ULL]);
XCTAssertEqual(value, 603.);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -2602,7 +2621,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBUInt64EnumDictionary *dict = [GPBUInt64EnumDictionary dictionaryWithEnum:700 forKey:31ULL];
+ GPBUInt64EnumDictionary *dict = [[GPBUInt64EnumDictionary alloc] init];
+ [dict setEnum:700 forKey:31ULL];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
int32_t value;
@@ -2615,6 +2635,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqual(aValue, 700);
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -2757,17 +2778,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt64EnumDictionary *dict2 =
- [GPBUInt64EnumDictionary dictionaryWithDictionary:dict];
+ [[GPBUInt64EnumDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBUInt64EnumDictionary *dict = [GPBUInt64EnumDictionary dictionary];
+ GPBUInt64EnumDictionary *dict = [[GPBUInt64EnumDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -2798,6 +2820,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getEnum:&value forKey:34ULL]);
XCTAssertEqual(value, 703);
[dict2 release];
+ [dict release];
}
- (void)testRemove {
@@ -3120,19 +3143,20 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt64EnumDictionary *dict2 =
- [GPBUInt64EnumDictionary dictionaryWithDictionary:dict];
+ [[GPBUInt64EnumDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
XCTAssertEqual(dict.validationFunc, dict2.validationFunc); // Pointer comparison
+ [dict2 release];
[dict release];
}
- (void)testUnknownAdds {
GPBUInt64EnumDictionary *dict =
- [GPBUInt64EnumDictionary dictionaryWithValidationFunction:TestingEnum_IsValidValue];
+ [[GPBUInt64EnumDictionary alloc] initWithValidationFunction:TestingEnum_IsValidValue];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -3172,6 +3196,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertTrue([dict getRawValue:&value forKey:34ULL]);
XCTAssertEqual(value, 803);
[dict2 release];
+ [dict release];
}
- (void)testUnknownRemove {
@@ -3375,7 +3400,8 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
}
- (void)testOne {
- GPBUInt64ObjectDictionary<NSString*> *dict = [GPBUInt64ObjectDictionary dictionaryWithObject:@"abc" forKey:31ULL];
+ GPBUInt64ObjectDictionary<NSString*> *dict = [[GPBUInt64ObjectDictionary alloc] init];
+ [dict setObject:@"abc" forKey:31ULL];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 1U);
XCTAssertEqualObjects([dict objectForKey:31ULL], @"abc");
@@ -3385,6 +3411,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqualObjects(aObject, @"abc");
XCTAssertNotEqual(stop, NULL);
}];
+ [dict release];
}
- (void)testBasics {
@@ -3520,17 +3547,18 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertNotNil(dict);
GPBUInt64ObjectDictionary<NSString*> *dict2 =
- [GPBUInt64ObjectDictionary dictionaryWithDictionary:dict];
+ [[GPBUInt64ObjectDictionary alloc] initWithDictionary:dict];
XCTAssertNotNil(dict2);
// Should be new pointer, but equal objects.
XCTAssertNotEqual(dict, dict2);
XCTAssertEqualObjects(dict, dict2);
+ [dict2 release];
[dict release];
}
- (void)testAdds {
- GPBUInt64ObjectDictionary<NSString*> *dict = [GPBUInt64ObjectDictionary dictionary];
+ GPBUInt64ObjectDictionary<NSString*> *dict = [[GPBUInt64ObjectDictionary alloc] init];
XCTAssertNotNil(dict);
XCTAssertEqual(dict.count, 0U);
@@ -3552,6 +3580,7 @@ static BOOL TestingEnum_IsValidValue(int32_t value) {
XCTAssertEqualObjects([dict objectForKey:33ULL], @"ghi");
XCTAssertEqualObjects([dict objectForKey:34ULL], @"jkl");
[dict2 release];
+ [dict release];
}
- (void)testRemove {
diff --git a/objectivec/Tests/GPBDictionaryTests.m b/objectivec/Tests/GPBDictionaryTests.m
new file mode 100644
index 00000000..52b4b328
--- /dev/null
+++ b/objectivec/Tests/GPBDictionaryTests.m
@@ -0,0 +1,186 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2017 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.
+
+#import <Foundation/Foundation.h>
+#import <XCTest/XCTest.h>
+
+#import "GPBDictionary.h"
+#import "GPBDictionary_PackagePrivate.h"
+
+#import "GPBTestUtilities.h"
+
+#pragma mark - GPBAutocreatedDictionary Tests
+
+// These are hand written tests to double check some behaviors of the
+// GPBAutocreatedDictionary. The GPBDictionary+[type]Tests files are generate
+// tests.
+
+// NOTE: GPBAutocreatedDictionary is private to the library, users of the
+// library should never have to directly deal with this class.
+
+@interface GPBAutocreatedDictionaryTests : XCTestCase
+@end
+
+@implementation GPBAutocreatedDictionaryTests
+
+- (void)testEquality {
+ GPBAutocreatedDictionary *dict = [[GPBAutocreatedDictionary alloc] init];
+
+ XCTAssertTrue([dict isEqual:@{}]);
+ XCTAssertTrue([dict isEqualToDictionary:@{}]);
+
+ XCTAssertFalse([dict isEqual:@{ @"foo" : @"bar" }]);
+ XCTAssertFalse([dict isEqualToDictionary:@{ @"foo" : @"bar" }]);
+
+ [dict setObject:@"bar" forKey:@"foo"];
+
+ XCTAssertFalse([dict isEqual:@{}]);
+ XCTAssertFalse([dict isEqualToDictionary:@{}]);
+ XCTAssertTrue([dict isEqual:@{ @"foo" : @"bar" }]);
+ XCTAssertTrue([dict isEqualToDictionary:@{ @"foo" : @"bar" }]);
+ XCTAssertFalse([dict isEqual:@{ @"bar" : @"baz" }]);
+ XCTAssertFalse([dict isEqualToDictionary:@{ @"bar" : @"baz" }]);
+
+ GPBAutocreatedDictionary *dict2 = [[GPBAutocreatedDictionary alloc] init];
+
+ XCTAssertFalse([dict isEqual:dict2]);
+ XCTAssertFalse([dict isEqualToDictionary:dict2]);
+
+ [dict2 setObject:@"mumble" forKey:@"foo"];
+ XCTAssertFalse([dict isEqual:dict2]);
+ XCTAssertFalse([dict isEqualToDictionary:dict2]);
+
+ [dict2 setObject:@"bar" forKey:@"foo"];
+ XCTAssertTrue([dict isEqual:dict2]);
+ XCTAssertTrue([dict isEqualToDictionary:dict2]);
+
+ [dict2 release];
+ [dict release];
+}
+
+- (void)testCopy {
+ {
+ GPBAutocreatedDictionary *dict = [[GPBAutocreatedDictionary alloc] init];
+
+ NSDictionary *cpy = [dict copy];
+ XCTAssertTrue(cpy != dict); // Ptr compare
+ XCTAssertTrue([cpy isKindOfClass:[NSDictionary class]]);
+ XCTAssertFalse([cpy isKindOfClass:[GPBAutocreatedDictionary class]]);
+ XCTAssertEqual(cpy.count, (NSUInteger)0);
+
+ NSDictionary *cpy2 = [dict copy];
+ XCTAssertTrue(cpy2 != dict); // Ptr compare
+ XCTAssertTrue(cpy2 != cpy); // Ptr compare
+ XCTAssertTrue([cpy2 isKindOfClass:[NSDictionary class]]);
+ XCTAssertFalse([cpy2 isKindOfClass:[GPBAutocreatedDictionary class]]);
+ XCTAssertEqual(cpy2.count, (NSUInteger)0);
+
+ [cpy2 release];
+ [cpy release];
+ [dict release];
+ }
+
+ {
+ GPBAutocreatedDictionary *dict = [[GPBAutocreatedDictionary alloc] init];
+
+ NSMutableDictionary *cpy = [dict mutableCopy];
+ XCTAssertTrue(cpy != dict); // Ptr compare
+ XCTAssertTrue([cpy isKindOfClass:[NSMutableDictionary class]]);
+ XCTAssertFalse([cpy isKindOfClass:[GPBAutocreatedDictionary class]]);
+ XCTAssertEqual(cpy.count, (NSUInteger)0);
+
+ NSMutableDictionary *cpy2 = [dict mutableCopy];
+ XCTAssertTrue(cpy2 != dict); // Ptr compare
+ XCTAssertTrue(cpy2 != cpy); // Ptr compare
+ XCTAssertTrue([cpy2 isKindOfClass:[NSMutableDictionary class]]);
+ XCTAssertFalse([cpy2 isKindOfClass:[GPBAutocreatedDictionary class]]);
+ XCTAssertEqual(cpy2.count, (NSUInteger)0);
+
+ [cpy2 release];
+ [cpy release];
+ [dict release];
+ }
+
+ {
+ GPBAutocreatedDictionary *dict = [[GPBAutocreatedDictionary alloc] init];
+ dict[@"foo"] = @"bar";
+ dict[@"baz"] = @"mumble";
+
+ NSDictionary *cpy = [dict copy];
+ XCTAssertTrue(cpy != dict); // Ptr compare
+ XCTAssertTrue([cpy isKindOfClass:[NSDictionary class]]);
+ XCTAssertFalse([cpy isKindOfClass:[GPBAutocreatedDictionary class]]);
+ XCTAssertEqual(cpy.count, (NSUInteger)2);
+ XCTAssertEqualObjects(cpy[@"foo"], @"bar");
+ XCTAssertEqualObjects(cpy[@"baz"], @"mumble");
+
+ NSDictionary *cpy2 = [dict copy];
+ XCTAssertTrue(cpy2 != dict); // Ptr compare
+ XCTAssertTrue(cpy2 != cpy); // Ptr compare
+ XCTAssertTrue([cpy2 isKindOfClass:[NSDictionary class]]);
+ XCTAssertFalse([cpy2 isKindOfClass:[GPBAutocreatedDictionary class]]);
+ XCTAssertEqual(cpy2.count, (NSUInteger)2);
+ XCTAssertEqualObjects(cpy2[@"foo"], @"bar");
+ XCTAssertEqualObjects(cpy2[@"baz"], @"mumble");
+
+ [cpy2 release];
+ [cpy release];
+ [dict release];
+ }
+
+ {
+ GPBAutocreatedDictionary *dict = [[GPBAutocreatedDictionary alloc] init];
+ dict[@"foo"] = @"bar";
+ dict[@"baz"] = @"mumble";
+
+ NSMutableDictionary *cpy = [dict mutableCopy];
+ XCTAssertTrue(cpy != dict); // Ptr compare
+ XCTAssertTrue([cpy isKindOfClass:[NSMutableDictionary class]]);
+ XCTAssertFalse([cpy isKindOfClass:[GPBAutocreatedDictionary class]]);
+ XCTAssertEqual(cpy.count, (NSUInteger)2);
+ XCTAssertEqualObjects(cpy[@"foo"], @"bar");
+ XCTAssertEqualObjects(cpy[@"baz"], @"mumble");
+
+ NSMutableDictionary *cpy2 = [dict mutableCopy];
+ XCTAssertTrue(cpy2 != dict); // Ptr compare
+ XCTAssertTrue(cpy2 != cpy); // Ptr compare
+ XCTAssertTrue([cpy2 isKindOfClass:[NSMutableDictionary class]]);
+ XCTAssertFalse([cpy2 isKindOfClass:[GPBAutocreatedDictionary class]]);
+ XCTAssertEqual(cpy2.count, (NSUInteger)2);
+ XCTAssertEqualObjects(cpy2[@"foo"], @"bar");
+ XCTAssertEqualObjects(cpy2[@"baz"], @"mumble");
+
+ [cpy2 release];
+ [cpy release];
+ [dict release];
+ }
+}
+
+@end
diff --git a/objectivec/Tests/GPBDictionaryTests.pddm b/objectivec/Tests/GPBDictionaryTests.pddm
index d6aa7211..17f12c28 100644
--- a/objectivec/Tests/GPBDictionaryTests.pddm
+++ b/objectivec/Tests/GPBDictionaryTests.pddm
@@ -78,7 +78,8 @@
//%}
//%
//%- (void)testOne {
-//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict = [GPB##KEY_NAME##VALUE_NAME##Dictionary dictionaryWith##VALUE_NAME$u##:VAL1 forKey:KEY1];
+//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict = [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] init];
+//% [dict set##VALUE_NAME$u##:VAL1 forKey:KEY1];
//% XCTAssertNotNil(dict);
//% XCTAssertEqual(dict.count, 1U);
//%DECLARE_VALUE_STORAGE##VHELPER(VALUE_TYPE, VNAME)TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY1, VAL1)
@@ -88,6 +89,7 @@
//% XCTAssertEqual##VSUFFIX(a##VNAME$u, VAL1);
//% XCTAssertNotEqual(stop, NULL);
//% }];
+//% [dict release];
//%}
//%
//%- (void)testBasics {
@@ -223,17 +225,18 @@
//% XCTAssertNotNil(dict);
//%
//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict2 =
-//% [GPB##KEY_NAME##VALUE_NAME##Dictionary dictionaryWithDictionary:dict];
+//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWithDictionary:dict];
//% XCTAssertNotNil(dict2);
//%
//% // Should be new pointer, but equal objects.
//% XCTAssertNotEqual(dict, dict2);
//% XCTAssertEqualObjects(dict, dict2);
+//% [dict2 release];
//% [dict release];
//%}
//%
//%- (void)testAdds {
-//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict = [GPB##KEY_NAME##VALUE_NAME##Dictionary dictionary];
+//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict = [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] init];
//% XCTAssertNotNil(dict);
//%
//% XCTAssertEqual(dict.count, 0U);
@@ -255,6 +258,7 @@
//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY3, VAL3)
//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY4, VAL4)
//% [dict2 release];
+//% [dict release];
//%}
//%
//%- (void)testRemove {
@@ -522,19 +526,20 @@
//% XCTAssertNotNil(dict);
//%
//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict2 =
-//% [GPB##KEY_NAME##VALUE_NAME##Dictionary dictionaryWithDictionary:dict];
+//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWithDictionary:dict];
//% XCTAssertNotNil(dict2);
//%
//% // Should be new pointer, but equal objects.
//% XCTAssertNotEqual(dict, dict2);
//% XCTAssertEqualObjects(dict, dict2);
//% XCTAssertEqual(dict.validationFunc, dict2.validationFunc); // Pointer comparison
+//% [dict2 release];
//% [dict release];
//%}
//%
//%- (void)testUnknownAdds {
//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict =
-//% [GPB##KEY_NAME##VALUE_NAME##Dictionary dictionaryWithValidationFunction:TestingEnum_IsValidValue];
+//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWithValidationFunction:TestingEnum_IsValidValue];
//% XCTAssertNotNil(dict);
//%
//% XCTAssertEqual(dict.count, 0U);
@@ -561,6 +566,7 @@
//%TEST_VALUE##VHELPER(VALUE_NAME, dict, value, KEY4, kGPBUnrecognizedEnumeratorValue)
//%TEST_RAW_VALUE##VHELPER(dict, value, KEY4, VAL4)
//% [dict2 release];
+//% [dict release];
//%}
//%
//%- (void)testUnknownRemove {
@@ -729,7 +735,6 @@
//%PDDM-DEFINE TEST_HELPERS(KEY_NAME, KEY_TYPE, KisP)
//%// To let the testing macros work, add some extra methods to simplify things.
//%@interface GPB##KEY_NAME##EnumDictionary (TestingTweak)
-//%+ (instancetype)dictionaryWithEnum:(int32_t)value forKey:(KEY_TYPE##KisP$S##KisP)key;
//%- (instancetype)initWithEnums:(const int32_t [])values
//% forKeys:(const KEY_TYPE##KisP$S##KisP [])keys
//% count:(NSUInteger)count;
@@ -748,14 +753,6 @@
//%}
//%
//%@implementation GPB##KEY_NAME##EnumDictionary (TestingTweak)
-//%+ (instancetype)dictionaryWithEnum:(int32_t)value forKey:(KEY_TYPE##KisP$S##KisP)key {
-//% // Cast is needed to compiler knows what class we are invoking initWithValues: on to get the
-//% // type correct.
-//% return [[(GPB##KEY_NAME##EnumDictionary*)[self alloc] initWithValidationFunction:TestingEnum_IsValidValue
-//% KEY_NAME$S rawValues:&value
-//% KEY_NAME$S forKeys:&key
-//% KEY_NAME$S count:1] autorelease];
-//%}
//%- (instancetype)initWithEnums:(const int32_t [])values
//% forKeys:(const KEY_TYPE##KisP$S##KisP [])keys
//% count:(NSUInteger)count {
@@ -801,7 +798,8 @@
//%}
//%
//%- (void)testOne {
-//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict = [GPB##KEY_NAME##VALUE_NAME##Dictionary dictionaryWith##VALUE_NAME$u##:VAL1 forKey:KEY1];
+//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict = [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] init];
+//% [dict set##VALUE_NAME$u##:VAL1 forKey:KEY1];
//% XCTAssertNotNil(dict);
//% XCTAssertEqual(dict.count, 1U);
//%DECLARE_VALUE_STORAGE##VHELPER(VALUE_TYPE, VNAME)TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY1, VAL1)
@@ -811,6 +809,7 @@
//% XCTAssertEqual##VSUFFIX(a##VNAME$u, VAL1);
//% XCTAssertNotEqual(stop, NULL);
//% }];
+//% [dict release];
//%}
//%
//%- (void)testBasics {
@@ -944,17 +943,18 @@
//% XCTAssertNotNil(dict);
//%
//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict2 =
-//% [GPB##KEY_NAME##VALUE_NAME##Dictionary dictionaryWithDictionary:dict];
+//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWithDictionary:dict];
//% XCTAssertNotNil(dict2);
//%
//% // Should be new pointer, but equal objects.
//% XCTAssertNotEqual(dict, dict2);
//% XCTAssertEqualObjects(dict, dict2);
+//% [dict2 release];
//% [dict release];
//%}
//%
//%- (void)testAdds {
-//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict = [GPB##KEY_NAME##VALUE_NAME##Dictionary dictionary];
+//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict = [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] init];
//% XCTAssertNotNil(dict);
//%
//% XCTAssertEqual(dict.count, 0U);
@@ -974,6 +974,7 @@
//%DECLARE_VALUE_STORAGE##VHELPER(VALUE_TYPE, VNAME)TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY1, VAL1)
//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY2, VAL2)
//% [dict2 release];
+//% [dict release];
//%}
//%
//%- (void)testRemove {
diff --git a/objectivec/Tests/GPBExtensionRegistryTest.m b/objectivec/Tests/GPBExtensionRegistryTest.m
new file mode 100644
index 00000000..b1168826
--- /dev/null
+++ b/objectivec/Tests/GPBExtensionRegistryTest.m
@@ -0,0 +1,138 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2017 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.
+
+#import "GPBTestUtilities.h"
+
+#import "GPBExtensionRegistry.h"
+#import "google/protobuf/Unittest.pbobjc.h"
+
+@interface GPBExtensionRegistryTest : GPBTestCase
+@end
+
+@implementation GPBExtensionRegistryTest
+
+- (void)testBasics {
+ GPBExtensionRegistry *reg = [[[GPBExtensionRegistry alloc] init] autorelease];
+ XCTAssertNotNil(reg);
+
+ XCTAssertNil([reg extensionForDescriptor:[TestAllExtensions descriptor]
+ fieldNumber:1]);
+ XCTAssertNil([reg extensionForDescriptor:[TestAllTypes descriptor]
+ fieldNumber:1]);
+
+ [reg addExtension:[UnittestRoot optionalInt32Extension]];
+ [reg addExtension:[UnittestRoot packedInt64Extension]];
+
+ XCTAssertTrue([reg extensionForDescriptor:[TestAllExtensions descriptor] fieldNumber:1] ==
+ [UnittestRoot optionalInt32Extension]); // ptr equality
+ XCTAssertNil([reg extensionForDescriptor:[TestAllTypes descriptor]
+ fieldNumber:1]);
+ XCTAssertTrue([reg extensionForDescriptor:[TestPackedExtensions descriptor] fieldNumber:91] ==
+ [UnittestRoot packedInt64Extension]); // ptr equality
+}
+
+- (void)testCopy {
+ GPBExtensionRegistry *reg1 = [[[GPBExtensionRegistry alloc] init] autorelease];
+ [reg1 addExtension:[UnittestRoot optionalInt32Extension]];
+
+ GPBExtensionRegistry *reg2 = [[reg1 copy] autorelease];
+ XCTAssertNotNil(reg2);
+
+ XCTAssertTrue([reg1 extensionForDescriptor:[TestAllExtensions descriptor] fieldNumber:1] ==
+ [UnittestRoot optionalInt32Extension]); // ptr equality
+ XCTAssertTrue([reg2 extensionForDescriptor:[TestAllExtensions descriptor] fieldNumber:1] ==
+ [UnittestRoot optionalInt32Extension]); // ptr equality
+
+ // Message class that had registered extension(s) at the -copy time.
+
+ [reg1 addExtension:[UnittestRoot optionalBoolExtension]];
+ [reg2 addExtension:[UnittestRoot optionalStringExtension]];
+
+ XCTAssertTrue([reg1 extensionForDescriptor:[TestAllExtensions descriptor] fieldNumber:13] ==
+ [UnittestRoot optionalBoolExtension]); // ptr equality
+ XCTAssertNil([reg1 extensionForDescriptor:[TestAllExtensions descriptor] fieldNumber:14]);
+ XCTAssertNil([reg2 extensionForDescriptor:[TestAllExtensions descriptor] fieldNumber:13]);
+ XCTAssertTrue([reg2 extensionForDescriptor:[TestAllExtensions descriptor] fieldNumber:14] ==
+ [UnittestRoot optionalStringExtension]); // ptr equality
+
+ // Message class that did not have any registered extensions at the -copy time.
+
+ [reg1 addExtension:[UnittestRoot packedInt64Extension]];
+ [reg2 addExtension:[UnittestRoot packedSint32Extension]];
+
+ XCTAssertTrue([reg1 extensionForDescriptor:[TestPackedExtensions descriptor] fieldNumber:91] ==
+ [UnittestRoot packedInt64Extension]); // ptr equality
+ XCTAssertNil([reg1 extensionForDescriptor:[TestPackedExtensions descriptor] fieldNumber:94]);
+ XCTAssertNil([reg2 extensionForDescriptor:[TestPackedExtensions descriptor] fieldNumber:91]);
+ XCTAssertTrue([reg2 extensionForDescriptor:[TestPackedExtensions descriptor] fieldNumber:94] ==
+ [UnittestRoot packedSint32Extension]); // ptr equality
+
+}
+
+- (void)testAddExtensions {
+ GPBExtensionRegistry *reg1 = [[[GPBExtensionRegistry alloc] init] autorelease];
+ [reg1 addExtension:[UnittestRoot optionalInt32Extension]];
+
+ GPBExtensionRegistry *reg2 = [[[GPBExtensionRegistry alloc] init] autorelease];
+
+ XCTAssertNil([reg2 extensionForDescriptor:[TestAllExtensions descriptor]
+ fieldNumber:1]);
+
+ [reg2 addExtensions:reg1];
+
+ XCTAssertTrue([reg2 extensionForDescriptor:[TestAllExtensions descriptor] fieldNumber:1] ==
+ [UnittestRoot optionalInt32Extension]); // ptr equality
+
+ // Confirm adding to the first doesn't add to the second.
+
+ [reg1 addExtension:[UnittestRoot optionalBoolExtension]];
+ [reg1 addExtension:[UnittestRoot packedInt64Extension]];
+
+ XCTAssertTrue([reg1 extensionForDescriptor:[TestAllExtensions descriptor] fieldNumber:13] ==
+ [UnittestRoot optionalBoolExtension]); // ptr equality
+ XCTAssertTrue([reg1 extensionForDescriptor:[TestPackedExtensions descriptor] fieldNumber:91] ==
+ [UnittestRoot packedInt64Extension]); // ptr equality
+ XCTAssertNil([reg2 extensionForDescriptor:[TestAllExtensions descriptor] fieldNumber:13]);
+ XCTAssertNil([reg2 extensionForDescriptor:[TestPackedExtensions descriptor] fieldNumber:91]);
+
+ // Confirm adding to the second doesn't add to the first.
+
+ [reg2 addExtension:[UnittestRoot optionalStringExtension]];
+ [reg2 addExtension:[UnittestRoot packedSint32Extension]];
+
+ XCTAssertNil([reg1 extensionForDescriptor:[TestAllExtensions descriptor] fieldNumber:14]);
+ XCTAssertNil([reg1 extensionForDescriptor:[TestPackedExtensions descriptor] fieldNumber:94]);
+ XCTAssertTrue([reg2 extensionForDescriptor:[TestAllExtensions descriptor] fieldNumber:14] ==
+ [UnittestRoot optionalStringExtension]); // ptr equality
+ XCTAssertTrue([reg2 extensionForDescriptor:[TestPackedExtensions descriptor] fieldNumber:94] ==
+ [UnittestRoot packedSint32Extension]); // ptr equality
+}
+
+@end
diff --git a/objectivec/Tests/GPBMessageTests+Serialization.m b/objectivec/Tests/GPBMessageTests+Serialization.m
index 763af2b0..921feab7 100644
--- a/objectivec/Tests/GPBMessageTests+Serialization.m
+++ b/objectivec/Tests/GPBMessageTests+Serialization.m
@@ -42,10 +42,6 @@
#import "google/protobuf/UnittestRuntimeProto2.pbobjc.h"
#import "google/protobuf/UnittestRuntimeProto3.pbobjc.h"
-static NSData *DataFromCStr(const char *str) {
- return [NSData dataWithBytes:str length:strlen(str)];
-}
-
@interface MessageSerializationTests : GPBTestCase
@end
@@ -113,35 +109,6 @@ static NSData *DataFromCStr(const char *str) {
[msg release];
}
-- (void)testProto3DroppingUnknownFields {
- DropUnknownsFooWithExtraFields *fooWithExtras =
- [[DropUnknownsFooWithExtraFields alloc] init];
-
- fooWithExtras.int32Value = 1;
- fooWithExtras.enumValue = DropUnknownsFooWithExtraFields_NestedEnum_Baz;
- fooWithExtras.extraInt32Value = 2;
-
- NSData *data = [fooWithExtras data];
- XCTAssertNotNil(data);
- DropUnknownsFoo *foo = [DropUnknownsFoo parseFromData:data error:NULL];
-
- XCTAssertEqual(foo.int32Value, 1);
- XCTAssertEqual(foo.enumValue, DropUnknownsFoo_NestedEnum_Baz);
- // Nothing should end up in the unknowns.
- XCTAssertEqual([foo.unknownFields countOfFields], 0U);
-
- [fooWithExtras release];
- data = [foo data];
- fooWithExtras =
- [DropUnknownsFooWithExtraFields parseFromData:data error:NULL];
- XCTAssertEqual(fooWithExtras.int32Value, 1);
- XCTAssertEqual(fooWithExtras.enumValue,
- DropUnknownsFooWithExtraFields_NestedEnum_Baz);
- // And the extra value is gone (back to the default).
- XCTAssertEqual(fooWithExtras.extraInt32Value, 0);
- XCTAssertEqual([foo.unknownFields countOfFields], 0U);
-}
-
- (void)testProto2UnknownEnumToUnknownField {
Message3 *orig = [[Message3 alloc] init];
@@ -946,17 +913,60 @@ static NSData *DataFromCStr(const char *str) {
XCTAssertEqual(error.code, GPBCodedInputStreamErrorInvalidTag);
}
+- (void)testZeroFieldNum {
+ // These are ConformanceTestSuite::TestIllegalTags.
+
+ const char *tests[] = {
+ "\1DEADBEEF",
+ "\2\1\1",
+ "\3\4",
+ "\5DEAD"
+ };
+
+ for (size_t i = 0; i < GPBARRAYSIZE(tests); ++i) {
+ NSData *data = DataFromCStr(tests[i]);
+
+ {
+ // Message from proto2 syntax file
+ NSError *error = nil;
+ Message2 *msg = [Message2 parseFromData:data error:&error];
+ XCTAssertNil(msg, @"i = %zd", i);
+ XCTAssertNotNil(error, @"i = %zd", i);
+ XCTAssertEqualObjects(error.domain, GPBCodedInputStreamErrorDomain, @"i = %zd", i);
+ XCTAssertEqual(error.code, GPBCodedInputStreamErrorInvalidTag, @"i = %zd", i);
+ }
+
+ {
+ // Message from proto3 syntax file
+ NSError *error = nil;
+ Message3 *msg = [Message3 parseFromData:data error:&error];
+ XCTAssertNil(msg, @"i = %zd", i);
+ XCTAssertNotNil(error, @"i = %zd", i);
+ XCTAssertEqualObjects(error.domain, GPBCodedInputStreamErrorDomain, @"i = %zd", i);
+ XCTAssertEqual(error.code, GPBCodedInputStreamErrorInvalidTag, @"i = %zd", i);
+ }
+ }
+}
+
- (void)testErrorRecursionDepthReached {
NSData *data = DataFromCStr(
- "\x0A\x86\x01\x0A\x83\x01\x0A\x80\x01\x0A\x7E\x0A\x7C\x0A\x7A\x0A\x78"
- "\x0A\x76\x0A\x74\x0A\x72\x0A\x70\x0A\x6E\x0A\x6C\x0A\x6A\x0A\x68"
- "\x0A\x66\x0A\x64\x0A\x62\x0A\x60\x0A\x5E\x0A\x5C\x0A\x5A\x0A\x58"
- "\x0A\x56\x0A\x54\x0A\x52\x0A\x50\x0A\x4E\x0A\x4C\x0A\x4A\x0A\x48"
- "\x0A\x46\x0A\x44\x0A\x42\x0A\x40\x0A\x3E\x0A\x3C\x0A\x3A\x0A\x38"
- "\x0A\x36\x0A\x34\x0A\x32\x0A\x30\x0A\x2E\x0A\x2C\x0A\x2A\x0A\x28"
- "\x0A\x26\x0A\x24\x0A\x22\x0A\x20\x0A\x1E\x0A\x1C\x0A\x1A\x0A\x18"
- "\x0A\x16\x0A\x14\x0A\x12\x0A\x10\x0A\x0E\x0A\x0C\x0A\x0A\x0A\x08"
- "\x0A\x06\x12\x04\x72\x02\x4B\x50");
+ "\x0A\xF2\x01\x0A\xEF\x01\x0A\xEC\x01\x0A\xE9\x01\x0A\xE6\x01"
+ "\x0A\xE3\x01\x0A\xE0\x01\x0A\xDD\x01\x0A\xDA\x01\x0A\xD7\x01"
+ "\x0A\xD4\x01\x0A\xD1\x01\x0A\xCE\x01\x0A\xCB\x01\x0A\xC8\x01"
+ "\x0A\xC5\x01\x0A\xC2\x01\x0A\xBF\x01\x0A\xBC\x01\x0A\xB9\x01"
+ "\x0A\xB6\x01\x0A\xB3\x01\x0A\xB0\x01\x0A\xAD\x01\x0A\xAA\x01"
+ "\x0A\xA7\x01\x0A\xA4\x01\x0A\xA1\x01\x0A\x9E\x01\x0A\x9B\x01"
+ "\x0A\x98\x01\x0A\x95\x01\x0A\x92\x01\x0A\x8F\x01\x0A\x8C\x01"
+ "\x0A\x89\x01\x0A\x86\x01\x0A\x83\x01\x0A\x80\x01\x0A\x7E"
+ "\x0A\x7C\x0A\x7A\x0A\x78\x0A\x76\x0A\x74\x0A\x72\x0A\x70"
+ "\x0A\x6E\x0A\x6C\x0A\x6A\x0A\x68\x0A\x66\x0A\x64\x0A\x62"
+ "\x0A\x60\x0A\x5E\x0A\x5C\x0A\x5A\x0A\x58\x0A\x56\x0A\x54"
+ "\x0A\x52\x0A\x50\x0A\x4E\x0A\x4C\x0A\x4A\x0A\x48\x0A\x46"
+ "\x0A\x44\x0A\x42\x0A\x40\x0A\x3E\x0A\x3C\x0A\x3A\x0A\x38"
+ "\x0A\x36\x0A\x34\x0A\x32\x0A\x30\x0A\x2E\x0A\x2C\x0A\x2A"
+ "\x0A\x28\x0A\x26\x0A\x24\x0A\x22\x0A\x20\x0A\x1E\x0A\x1C"
+ "\x0A\x1A\x0A\x18\x0A\x16\x0A\x14\x0A\x12\x0A\x10\x0A\x0E"
+ "\x0A\x0C\x0A\x0A\x0A\x08\x0A\x06\x12\x04\x72\x02\x4B\x50");
NSError *error = nil;
NestedTestAllTypes *msg = [NestedTestAllTypes parseFromData:data
error:&error];
@@ -966,6 +976,16 @@ static NSData *DataFromCStr(const char *str) {
XCTAssertEqual(error.code, GPBCodedInputStreamErrorRecursionDepthExceeded);
}
+- (void)testParseDelimitedDataWithNegativeSize {
+ NSData *data = DataFromCStr("\xFF\xFF\xFF\xFF\x0F");
+ GPBCodedInputStream *input = [GPBCodedInputStream streamWithData:data];
+ NSError *error;
+ [GPBMessage parseDelimitedFromCodedInputStream:input
+ extensionRegistry:nil
+ error:&error];
+ XCTAssertNil(error);
+}
+
#ifdef DEBUG
- (void)testErrorMissingRequiredField {
NSData *data = DataFromCStr("");
@@ -1094,10 +1114,10 @@ static NSData *DataFromCStr(const char *str) {
- (void)testMap_Proto2UnknownEnum {
TestEnumMapPlusExtra *orig = [[TestEnumMapPlusExtra alloc] init];
- orig.knownMapField = [GPBInt32EnumDictionary
- dictionaryWithValidationFunction:Proto2MapEnumPlusExtra_IsValidValue];
- orig.unknownMapField = [GPBInt32EnumDictionary
- dictionaryWithValidationFunction:Proto2MapEnumPlusExtra_IsValidValue];
+ orig.knownMapField = [[[GPBInt32EnumDictionary alloc]
+ initWithValidationFunction:Proto2MapEnumPlusExtra_IsValidValue] autorelease];
+ orig.unknownMapField = [[[GPBInt32EnumDictionary alloc]
+ initWithValidationFunction:Proto2MapEnumPlusExtra_IsValidValue] autorelease];
[orig.knownMapField setEnum:Proto2MapEnumPlusExtra_EProto2MapEnumFoo
forKey:0];
[orig.unknownMapField setEnum:Proto2MapEnumPlusExtra_EProto2MapEnumExtra
@@ -1141,22 +1161,27 @@ static NSData *DataFromCStr(const char *str) {
[msg.mapInt32Int32 setInt32:101 forKey:2001];
[msg.mapInt64Int64 setInt64:1002 forKey:202];
[msg.mapInt64Int64 setInt64:103 forKey:2003];
+ [msg.mapInt64Int64 setInt64:4294967296 forKey:4294967297];
[msg.mapUint32Uint32 setUInt32:1004 forKey:204];
[msg.mapUint32Uint32 setUInt32:105 forKey:2005];
[msg.mapUint64Uint64 setUInt64:1006 forKey:206];
[msg.mapUint64Uint64 setUInt64:107 forKey:2007];
+ [msg.mapUint64Uint64 setUInt64:4294967298 forKey:4294967299];
[msg.mapSint32Sint32 setInt32:1008 forKey:208];
[msg.mapSint32Sint32 setInt32:109 forKey:2009];
[msg.mapSint64Sint64 setInt64:1010 forKey:210];
[msg.mapSint64Sint64 setInt64:111 forKey:2011];
+ [msg.mapSint64Sint64 setInt64:4294967300 forKey:4294967301];
[msg.mapFixed32Fixed32 setUInt32:1012 forKey:212];
[msg.mapFixed32Fixed32 setUInt32:113 forKey:2013];
[msg.mapFixed64Fixed64 setUInt64:1014 forKey:214];
[msg.mapFixed64Fixed64 setUInt64:115 forKey:2015];
+ [msg.mapFixed64Fixed64 setUInt64:4294967302 forKey:4294967303];
[msg.mapSfixed32Sfixed32 setInt32:1016 forKey:216];
[msg.mapSfixed32Sfixed32 setInt32:117 forKey:2017];
[msg.mapSfixed64Sfixed64 setInt64:1018 forKey:218];
[msg.mapSfixed64Sfixed64 setInt64:119 forKey:2019];
+ [msg.mapSfixed64Sfixed64 setInt64:4294967304 forKey:4294967305];
[msg.mapInt32Float setFloat:1020.f forKey:220];
[msg.mapInt32Float setFloat:121.f forKey:2021];
[msg.mapInt32Double setDouble:1022. forKey:222];
diff --git a/objectivec/Tests/GPBMessageTests.m b/objectivec/Tests/GPBMessageTests.m
index a3c5a6b4..4d75f1e1 100644
--- a/objectivec/Tests/GPBMessageTests.m
+++ b/objectivec/Tests/GPBMessageTests.m
@@ -1082,6 +1082,20 @@
[repeatedStringArray release];
}
+- (void)testSetOverAutocreatedArrayAndSetAgain {
+ // Ensure when dealing with replacing an array it is handled being either
+ // an autocreated one or a straight NSArray.
+
+ // The real test here is that nothing crashes while doing the work.
+ TestAllTypes *message = [TestAllTypes message];
+ [message.repeatedStringArray addObject:@"foo"];
+ XCTAssertEqual(message.repeatedStringArray_Count, (NSUInteger)1);
+ message.repeatedStringArray = [NSMutableArray arrayWithObjects:@"bar", @"bar2", nil];
+ XCTAssertEqual(message.repeatedStringArray_Count, (NSUInteger)2);
+ message.repeatedStringArray = [NSMutableArray arrayWithObject:@"baz"];
+ XCTAssertEqual(message.repeatedStringArray_Count, (NSUInteger)1);
+}
+
- (void)testReplaceAutocreatedArray {
// Replacing array should orphan the old one and cause its creator to become
// visible.
@@ -1224,7 +1238,8 @@
// with different objects that are equal).
TestRecursiveMessageWithRepeatedField *message3 =
[TestRecursiveMessageWithRepeatedField message];
- message3.iToI = [GPBInt32Int32Dictionary dictionaryWithInt32:10 forKey:20];
+ message3.iToI = [[[GPBInt32Int32Dictionary alloc] init] autorelease];
+ [message3.iToI setInt32:10 forKey:20];
message3.strToStr =
[NSMutableDictionary dictionaryWithObject:@"abc" forKey:@"123"];
XCTAssertNotNil(message.iToI);
@@ -1281,6 +1296,23 @@
[strToStr release];
}
+- (void)testSetOverAutocreatedMapAndSetAgain {
+ // Ensure when dealing with replacing a map it is handled being either
+ // an autocreated one or a straight NSDictionary.
+
+ // The real test here is that nothing crashes while doing the work.
+ TestRecursiveMessageWithRepeatedField *message =
+ [TestRecursiveMessageWithRepeatedField message];
+ message.strToStr[@"foo"] = @"bar";
+ XCTAssertEqual(message.strToStr_Count, (NSUInteger)1);
+ message.strToStr =
+ [NSMutableDictionary dictionaryWithObjectsAndKeys:@"bar", @"key1", @"baz", @"key2", nil];
+ XCTAssertEqual(message.strToStr_Count, (NSUInteger)2);
+ message.strToStr =
+ [NSMutableDictionary dictionaryWithObject:@"baz" forKey:@"mumble"];
+ XCTAssertEqual(message.strToStr_Count, (NSUInteger)1);
+}
+
- (void)testReplaceAutocreatedMap {
// Replacing map should orphan the old one and cause its creator to become
// visible.
@@ -1292,7 +1324,8 @@
XCTAssertFalse([message hasA]);
GPBInt32Int32Dictionary *iToI = [message.a.iToI retain];
XCTAssertEqual(iToI->_autocreator, message.a); // Pointer comparision
- message.a.iToI = [GPBInt32Int32Dictionary dictionaryWithInt32:6 forKey:7];
+ message.a.iToI = [[[GPBInt32Int32Dictionary alloc] init] autorelease];
+ [message.a.iToI setInt32:6 forKey:7];
XCTAssertTrue([message hasA]);
XCTAssertNotEqual(message.a.iToI, iToI); // Pointer comparision
XCTAssertNil(iToI->_autocreator);
diff --git a/objectivec/Tests/GPBPerfTests.m b/objectivec/Tests/GPBPerfTests.m
index 1259d146..8dd0ffc5 100644
--- a/objectivec/Tests/GPBPerfTests.m
+++ b/objectivec/Tests/GPBPerfTests.m
@@ -64,6 +64,112 @@ static const uint32_t kRepeatedCount = 100;
}];
}
+- (void)testMessageSerialParsingPerformance {
+ // This and the next test are meant to monitor that the parsing functionality of protos does not
+ // lock across threads when parsing different instances. The Serial version of the test should run
+ // around ~2 times slower than the Parallel version since it's parsing the protos in the same
+ // thread.
+ TestAllTypes *allTypesMessage = [TestAllTypes message];
+ [self setAllFields:allTypesMessage repeatedCount:2];
+ NSData *allTypesData = allTypesMessage.data;
+
+ [self measureBlock:^{
+ for (int i = 0; i < 500; ++i) {
+ [TestAllTypes parseFromData:allTypesData error:NULL];
+ [TestAllTypes parseFromData:allTypesData error:NULL];
+ }
+ }];
+}
+
+- (void)testMessageParallelParsingPerformance {
+ // This and the previous test are meant to monitor that the parsing functionality of protos does
+ // not lock across threads when parsing different instances. The Serial version of the test should
+ // run around ~2 times slower than the Parallel version since it's parsing the protos in the same
+ // thread.
+ TestAllTypes *allTypesMessage = [TestAllTypes message];
+ [self setAllFields:allTypesMessage repeatedCount:2];
+ NSData *allTypesData = allTypesMessage.data;
+
+ dispatch_queue_t concurrentQueue = dispatch_queue_create("perfQueue", DISPATCH_QUEUE_CONCURRENT);
+
+ [self measureBlock:^{
+ for (int i = 0; i < 500; ++i) {
+ dispatch_group_t group = dispatch_group_create();
+
+ dispatch_group_async(group, concurrentQueue, ^{
+ [TestAllTypes parseFromData:allTypesData error:NULL];
+ });
+
+ dispatch_group_async(group, concurrentQueue, ^{
+ [TestAllTypes parseFromData:allTypesData error:NULL];
+ });
+
+ dispatch_group_notify(group, concurrentQueue, ^{});
+
+ dispatch_release(group);
+ }
+ }];
+
+ dispatch_release(concurrentQueue);
+}
+
+- (void)testMessageSerialExtensionsParsingPerformance {
+ // This and the next test are meant to monitor that the parsing functionality of protos does not
+ // lock across threads when parsing different instances when using extensions. The Serial version
+ // of the test should run around ~2 times slower than the Parallel version since it's parsing the
+ // protos in the same thread.
+ TestAllExtensions *allExtensionsMessage = [TestAllExtensions message];
+ [self setAllExtensions:allExtensionsMessage repeatedCount:2];
+ NSData *allExtensionsData = allExtensionsMessage.data;
+
+ [self measureBlock:^{
+ for (int i = 0; i < 500; ++i) {
+ [TestAllExtensions parseFromData:allExtensionsData
+ extensionRegistry:[self extensionRegistry]
+ error:NULL];
+ [TestAllExtensions parseFromData:allExtensionsData
+ extensionRegistry:[self extensionRegistry]
+ error:NULL];
+ }
+ }];
+}
+
+- (void)testMessageParallelExtensionsParsingPerformance {
+ // This and the previous test are meant to monitor that the parsing functionality of protos does
+ // not lock across threads when parsing different instances when using extensions. The Serial
+ // version of the test should run around ~2 times slower than the Parallel version since it's
+ // parsing the protos in the same thread.
+ TestAllExtensions *allExtensionsMessage = [TestAllExtensions message];
+ [self setAllExtensions:allExtensionsMessage repeatedCount:2];
+ NSData *allExtensionsData = allExtensionsMessage.data;
+
+ dispatch_queue_t concurrentQueue = dispatch_queue_create("perfQueue", DISPATCH_QUEUE_CONCURRENT);
+
+ [self measureBlock:^{
+ for (int i = 0; i < 500; ++i) {
+ dispatch_group_t group = dispatch_group_create();
+
+ dispatch_group_async(group, concurrentQueue, ^{
+ [TestAllExtensions parseFromData:allExtensionsData
+ extensionRegistry:[UnittestRoot extensionRegistry]
+ error:NULL];
+ });
+
+ dispatch_group_async(group, concurrentQueue, ^{
+ [TestAllExtensions parseFromData:allExtensionsData
+ extensionRegistry:[UnittestRoot extensionRegistry]
+ error:NULL];
+ });
+
+ dispatch_group_notify(group, concurrentQueue, ^{});
+
+ dispatch_release(group);
+ }
+ }];
+
+ dispatch_release(concurrentQueue);
+}
+
- (void)testExtensionsPerformance {
[self measureBlock:^{
for (int i = 0; i < 200; ++i) {
diff --git a/objectivec/Tests/GPBTestUtilities.h b/objectivec/Tests/GPBTestUtilities.h
index 44c80844..780184b0 100644
--- a/objectivec/Tests/GPBTestUtilities.h
+++ b/objectivec/Tests/GPBTestUtilities.h
@@ -39,6 +39,9 @@
@class TestUnpackedExtensions;
@class GPBExtensionRegistry;
+static inline NSData *DataFromCStr(const char *str) {
+ return [NSData dataWithBytes:str length:strlen(str)];
+}
// Helper for uses of C arrays in tests cases.
#ifndef GPBARRAYSIZE
diff --git a/objectivec/Tests/GPBUnknownFieldSetTest.m b/objectivec/Tests/GPBUnknownFieldSetTest.m
index b2b5b21e..8e03a427 100644
--- a/objectivec/Tests/GPBUnknownFieldSetTest.m
+++ b/objectivec/Tests/GPBUnknownFieldSetTest.m
@@ -60,6 +60,95 @@
unknownFields_ = emptyMessage_.unknownFields;
}
+- (void)testInvalidFieldNumber {
+ GPBUnknownFieldSet *set = [[[GPBUnknownFieldSet alloc] init] autorelease];
+ GPBUnknownField* field = [[[GPBUnknownField alloc] initWithNumber:0] autorelease];
+ XCTAssertThrowsSpecificNamed([set addField:field], NSException, NSInvalidArgumentException);
+}
+
+- (void)testEqualityAndHash {
+ // Empty
+
+ GPBUnknownFieldSet *set1 = [[[GPBUnknownFieldSet alloc] init] autorelease];
+ XCTAssertTrue([set1 isEqual:set1]);
+ XCTAssertFalse([set1 isEqual:@"foo"]);
+ GPBUnknownFieldSet *set2 = [[[GPBUnknownFieldSet alloc] init] autorelease];
+ XCTAssertEqualObjects(set1, set2);
+ XCTAssertEqual([set1 hash], [set2 hash]);
+
+ // Varint
+
+ GPBUnknownField* field1 = [[[GPBUnknownField alloc] initWithNumber:1] autorelease];
+ [field1 addVarint:1];
+ [set1 addField:field1];
+ XCTAssertNotEqualObjects(set1, set2);
+ GPBUnknownField* field2 = [[[GPBUnknownField alloc] initWithNumber:1] autorelease];
+ [field2 addVarint:1];
+ [set2 addField:field2];
+ XCTAssertEqualObjects(set1, set2);
+ XCTAssertEqual([set1 hash], [set2 hash]);
+
+ // Fixed32
+
+ field1 = [[[GPBUnknownField alloc] initWithNumber:2] autorelease];
+ [field1 addFixed32:2];
+ [set1 addField:field1];
+ XCTAssertNotEqualObjects(set1, set2);
+ field2 = [[[GPBUnknownField alloc] initWithNumber:2] autorelease];
+ [field2 addFixed32:2];
+ [set2 addField:field2];
+ XCTAssertEqualObjects(set1, set2);
+ XCTAssertEqual([set1 hash], [set2 hash]);
+
+ // Fixed64
+
+ field1 = [[[GPBUnknownField alloc] initWithNumber:3] autorelease];
+ [field1 addFixed64:3];
+ [set1 addField:field1];
+ XCTAssertNotEqualObjects(set1, set2);
+ field2 = [[[GPBUnknownField alloc] initWithNumber:3] autorelease];
+ [field2 addFixed64:3];
+ [set2 addField:field2];
+ XCTAssertEqualObjects(set1, set2);
+ XCTAssertEqual([set1 hash], [set2 hash]);
+
+ // LengthDelimited
+
+ field1 = [[[GPBUnknownField alloc] initWithNumber:4] autorelease];
+ [field1 addLengthDelimited:DataFromCStr("foo")];
+ [set1 addField:field1];
+ XCTAssertNotEqualObjects(set1, set2);
+ field2 = [[[GPBUnknownField alloc] initWithNumber:4] autorelease];
+ [field2 addLengthDelimited:DataFromCStr("foo")];
+ [set2 addField:field2];
+ XCTAssertEqualObjects(set1, set2);
+ XCTAssertEqual([set1 hash], [set2 hash]);
+
+ // Group
+
+ GPBUnknownFieldSet *group1 = [[[GPBUnknownFieldSet alloc] init] autorelease];
+ GPBUnknownField* fieldGroup1 = [[[GPBUnknownField alloc] initWithNumber:10] autorelease];
+ [fieldGroup1 addVarint:1];
+ [group1 addField:fieldGroup1];
+ GPBUnknownFieldSet *group2 = [[[GPBUnknownFieldSet alloc] init] autorelease];
+ GPBUnknownField* fieldGroup2 = [[[GPBUnknownField alloc] initWithNumber:10] autorelease];
+ [fieldGroup2 addVarint:1];
+ [group2 addField:fieldGroup2];
+
+ field1 = [[[GPBUnknownField alloc] initWithNumber:5] autorelease];
+ [field1 addGroup:group1];
+ [set1 addField:field1];
+ XCTAssertNotEqualObjects(set1, set2);
+ field2 = [[[GPBUnknownField alloc] initWithNumber:5] autorelease];
+ [field2 addGroup:group2];
+ [set2 addField:field2];
+ XCTAssertEqualObjects(set1, set2);
+ XCTAssertEqual([set1 hash], [set2 hash]);
+
+ // Exercise description for completeness.
+ XCTAssertTrue(set1.description.length > 10);
+}
+
// Constructs a protocol buffer which contains fields with all the same
// numbers as allFieldsData except that each field is some other wire
// type.
@@ -112,6 +201,24 @@
field = [[[GPBUnknownField alloc] initWithNumber:3] autorelease];
[field addVarint:4];
[set1 addField:field];
+ field = [[[GPBUnknownField alloc] initWithNumber:4] autorelease];
+ [field addFixed32:6];
+ [set1 addField:field];
+ field = [[[GPBUnknownField alloc] initWithNumber:5] autorelease];
+ [field addFixed64:20];
+ [set1 addField:field];
+ field = [[[GPBUnknownField alloc] initWithNumber:10] autorelease];
+ [field addLengthDelimited:DataFromCStr("data1")];
+ [set1 addField:field];
+
+ GPBUnknownFieldSet *group1 = [[[GPBUnknownFieldSet alloc] init] autorelease];
+ GPBUnknownField* fieldGroup1 = [[[GPBUnknownField alloc] initWithNumber:200] autorelease];
+ [fieldGroup1 addVarint:100];
+ [group1 addField:fieldGroup1];
+
+ field = [[[GPBUnknownField alloc] initWithNumber:11] autorelease];
+ [field addGroup:group1];
+ [set1 addField:field];
GPBUnknownFieldSet* set2 = [[[GPBUnknownFieldSet alloc] init] autorelease];
field = [[[GPBUnknownField alloc] initWithNumber:1] autorelease];
@@ -120,22 +227,63 @@
field = [[[GPBUnknownField alloc] initWithNumber:3] autorelease];
[field addVarint:3];
[set2 addField:field];
+ field = [[[GPBUnknownField alloc] initWithNumber:4] autorelease];
+ [field addFixed32:7];
+ [set2 addField:field];
+ field = [[[GPBUnknownField alloc] initWithNumber:5] autorelease];
+ [field addFixed64:30];
+ [set2 addField:field];
+ field = [[[GPBUnknownField alloc] initWithNumber:10] autorelease];
+ [field addLengthDelimited:DataFromCStr("data2")];
+ [set2 addField:field];
+
+ GPBUnknownFieldSet *group2 = [[[GPBUnknownFieldSet alloc] init] autorelease];
+ GPBUnknownField* fieldGroup2 = [[[GPBUnknownField alloc] initWithNumber:201] autorelease];
+ [fieldGroup2 addVarint:99];
+ [group2 addField:fieldGroup2];
+
+ field = [[[GPBUnknownField alloc] initWithNumber:11] autorelease];
+ [field addGroup:group2];
+ [set2 addField:field];
GPBUnknownFieldSet* set3 = [[[GPBUnknownFieldSet alloc] init] autorelease];
field = [[[GPBUnknownField alloc] initWithNumber:1] autorelease];
[field addVarint:1];
[set3 addField:field];
- field = [[[GPBUnknownField alloc] initWithNumber:3] autorelease];
- [field addVarint:4];
- [set3 addField:field];
-
- GPBUnknownFieldSet* set4 = [[[GPBUnknownFieldSet alloc] init] autorelease];
field = [[[GPBUnknownField alloc] initWithNumber:2] autorelease];
[field addVarint:2];
- [set4 addField:field];
+ [set3 addField:field];
field = [[[GPBUnknownField alloc] initWithNumber:3] autorelease];
+ [field addVarint:4];
+ [set3 addField:field];
[field addVarint:3];
- [set4 addField:field];
+ [set3 addField:field];
+ field = [[[GPBUnknownField alloc] initWithNumber:4] autorelease];
+ [field addFixed32:6];
+ [field addFixed32:7];
+ [set3 addField:field];
+ field = [[[GPBUnknownField alloc] initWithNumber:5] autorelease];
+ [field addFixed64:20];
+ [field addFixed64:30];
+ [set3 addField:field];
+ field = [[[GPBUnknownField alloc] initWithNumber:10] autorelease];
+ [field addLengthDelimited:DataFromCStr("data1")];
+ [field addLengthDelimited:DataFromCStr("data2")];
+ [set3 addField:field];
+
+ GPBUnknownFieldSet *group3a = [[[GPBUnknownFieldSet alloc] init] autorelease];
+ GPBUnknownField* fieldGroup3a1 = [[[GPBUnknownField alloc] initWithNumber:200] autorelease];
+ [fieldGroup3a1 addVarint:100];
+ [group3a addField:fieldGroup3a1];
+ GPBUnknownFieldSet *group3b = [[[GPBUnknownFieldSet alloc] init] autorelease];
+ GPBUnknownField* fieldGroup3b2 = [[[GPBUnknownField alloc] initWithNumber:201] autorelease];
+ [fieldGroup3b2 addVarint:99];
+ [group3b addField:fieldGroup3b2];
+
+ field = [[[GPBUnknownField alloc] initWithNumber:11] autorelease];
+ [field addGroup:group1];
+ [field addGroup:group3b];
+ [set3 addField:field];
TestEmptyMessage* source1 = [TestEmptyMessage message];
[source1 setUnknownFields:set1];
@@ -143,8 +291,6 @@
[source2 setUnknownFields:set2];
TestEmptyMessage* source3 = [TestEmptyMessage message];
[source3 setUnknownFields:set3];
- TestEmptyMessage* source4 = [TestEmptyMessage message];
- [source4 setUnknownFields:set4];
TestEmptyMessage* destination1 = [TestEmptyMessage message];
[destination1 mergeFrom:source1];
@@ -152,9 +298,10 @@
TestEmptyMessage* destination2 = [TestEmptyMessage message];
[destination2 mergeFrom:source3];
- [destination2 mergeFrom:source4];
XCTAssertEqualObjects(destination1.data, destination2.data);
+ XCTAssertEqualObjects(destination1.data, source3.data);
+ XCTAssertEqualObjects(destination2.data, source3.data);
}
- (void)testClearMessage {
@@ -240,6 +387,107 @@
XCTAssertEqual(0x7FFFFFFFFFFFFFFFULL, [field2.varintList valueAtIndex:0]);
}
+#pragma mark - Field tests
+// Some tests directly on fields since the dictionary in FieldSet can gate
+// testing some of these.
+
+- (void)testFieldEqualityAndHash {
+ GPBUnknownField* field1 = [[[GPBUnknownField alloc] initWithNumber:1] autorelease];
+ XCTAssertTrue([field1 isEqual:field1]);
+ XCTAssertFalse([field1 isEqual:@"foo"]);
+ GPBUnknownField* field2 = [[[GPBUnknownField alloc] initWithNumber:2] autorelease];
+ XCTAssertNotEqualObjects(field1, field2);
+
+ field2 = [[[GPBUnknownField alloc] initWithNumber:1] autorelease];
+ XCTAssertEqualObjects(field1, field2);
+ XCTAssertEqual([field1 hash], [field2 hash]);
+
+ // Varint
+
+ [field1 addVarint:10];
+ XCTAssertNotEqualObjects(field1, field2);
+ [field2 addVarint:10];
+ XCTAssertEqualObjects(field1, field2);
+ XCTAssertEqual([field1 hash], [field2 hash]);
+ [field1 addVarint:11];
+ XCTAssertNotEqualObjects(field1, field2);
+ [field2 addVarint:11];
+ XCTAssertEqualObjects(field1, field2);
+ XCTAssertEqual([field1 hash], [field2 hash]);
+
+ // Fixed32
+
+ [field1 addFixed32:20];
+ XCTAssertNotEqualObjects(field1, field2);
+ [field2 addFixed32:20];
+ XCTAssertEqualObjects(field1, field2);
+ XCTAssertEqual([field1 hash], [field2 hash]);
+ [field1 addFixed32:21];
+ XCTAssertNotEqualObjects(field1, field2);
+ [field2 addFixed32:21];
+ XCTAssertEqualObjects(field1, field2);
+ XCTAssertEqual([field1 hash], [field2 hash]);
+
+ // Fixed64
+
+ [field1 addFixed64:30];
+ XCTAssertNotEqualObjects(field1, field2);
+ [field2 addFixed64:30];
+ XCTAssertEqualObjects(field1, field2);
+ XCTAssertEqual([field1 hash], [field2 hash]);
+ [field1 addFixed64:31];
+ XCTAssertNotEqualObjects(field1, field2);
+ [field2 addFixed64:31];
+ XCTAssertEqualObjects(field1, field2);
+ XCTAssertEqual([field1 hash], [field2 hash]);
+
+ // LengthDelimited
+
+ [field1 addLengthDelimited:DataFromCStr("foo")];
+ XCTAssertNotEqualObjects(field1, field2);
+ [field2 addLengthDelimited:DataFromCStr("foo")];
+ XCTAssertEqualObjects(field1, field2);
+ XCTAssertEqual([field1 hash], [field2 hash]);
+ [field1 addLengthDelimited:DataFromCStr("bar")];
+ XCTAssertNotEqualObjects(field1, field2);
+ [field2 addLengthDelimited:DataFromCStr("bar")];
+ XCTAssertEqualObjects(field1, field2);
+ XCTAssertEqual([field1 hash], [field2 hash]);
+
+ // Group
+
+ GPBUnknownFieldSet *group = [[[GPBUnknownFieldSet alloc] init] autorelease];
+ GPBUnknownField* fieldGroup = [[[GPBUnknownField alloc] initWithNumber:100] autorelease];
+ [fieldGroup addVarint:100];
+ [group addField:fieldGroup];
+ [field1 addGroup:group];
+ XCTAssertNotEqualObjects(field1, field2);
+ group = [[[GPBUnknownFieldSet alloc] init] autorelease];
+ fieldGroup = [[[GPBUnknownField alloc] initWithNumber:100] autorelease];
+ [fieldGroup addVarint:100];
+ [group addField:fieldGroup];
+ [field2 addGroup:group];
+ XCTAssertEqualObjects(field1, field2);
+ XCTAssertEqual([field1 hash], [field2 hash]);
+
+ group = [[[GPBUnknownFieldSet alloc] init] autorelease];
+ fieldGroup = [[[GPBUnknownField alloc] initWithNumber:101] autorelease];
+ [fieldGroup addVarint:101];
+ [group addField:fieldGroup];
+ [field1 addGroup:group];
+ XCTAssertNotEqualObjects(field1, field2);
+ group = [[[GPBUnknownFieldSet alloc] init] autorelease];
+ fieldGroup = [[[GPBUnknownField alloc] initWithNumber:101] autorelease];
+ [fieldGroup addVarint:101];
+ [group addField:fieldGroup];
+ [field2 addGroup:group];
+ XCTAssertEqualObjects(field1, field2);
+ XCTAssertEqual([field1 hash], [field2 hash]);
+
+ // Exercise description for completeness.
+ XCTAssertTrue(field1.description.length > 10);
+}
+
- (void)testMergingFields {
GPBUnknownField* field1 = [[[GPBUnknownField alloc] initWithNumber:1] autorelease];
[field1 addVarint:1];
@@ -247,9 +495,8 @@
[field1 addFixed64:3];
[field1 addLengthDelimited:[NSData dataWithBytes:"hello" length:5]];
[field1 addGroup:[[unknownFields_ copy] autorelease]];
- GPBUnknownField* field2 = [[[GPBUnknownField alloc] initWithNumber:2] autorelease];
+ GPBUnknownField* field2 = [[[GPBUnknownField alloc] initWithNumber:1] autorelease];
[field2 mergeFromField:field1];
- XCTAssertEqualObjects(field1, field2);
}
@end
diff --git a/objectivec/Tests/GPBUtilitiesTests.m b/objectivec/Tests/GPBUtilitiesTests.m
index dfaca660..2e206a54 100644
--- a/objectivec/Tests/GPBUtilitiesTests.m
+++ b/objectivec/Tests/GPBUtilitiesTests.m
@@ -39,6 +39,7 @@
#import "GPBDescriptor.h"
#import "GPBDescriptor_PackagePrivate.h"
#import "GPBMessage.h"
+#import "GPBUnknownField_PackagePrivate.h"
#import "google/protobuf/MapUnittest.pbobjc.h"
#import "google/protobuf/Unittest.pbobjc.h"
@@ -197,4 +198,203 @@
}
}
+// Helper to make an unknown field set with something in it.
+static GPBUnknownFieldSet *UnknownFieldsSetHelper(int num) {
+ GPBUnknownFieldSet *result =
+ [[[GPBUnknownFieldSet alloc] init] autorelease];
+
+ GPBUnknownField *field =
+ [[[GPBUnknownField alloc] initWithNumber:num] autorelease];
+ [field addVarint:num];
+ [result addField:field];
+
+ return result;
+}
+
+- (void)testDropMessageUnknownFieldsRecursively {
+ TestAllExtensions *message = [TestAllExtensions message];
+
+ // Give it unknownFields.
+ message.unknownFields = UnknownFieldsSetHelper(777);
+
+ // Given it extensions that include a message with unknown fields of its own.
+ {
+ // Int
+ [message setExtension:[UnittestRoot optionalInt32Extension] value:@5];
+
+ // Group
+ OptionalGroup_extension *optionalGroup = [OptionalGroup_extension message];
+ optionalGroup.a = 123;
+ optionalGroup.unknownFields = UnknownFieldsSetHelper(779);
+ [message setExtension:[UnittestRoot optionalGroupExtension]
+ value:optionalGroup];
+
+ // Message
+ TestAllTypes_NestedMessage *nestedMessage =
+ [TestAllTypes_NestedMessage message];
+ nestedMessage.bb = 456;
+ nestedMessage.unknownFields = UnknownFieldsSetHelper(778);
+ [message setExtension:[UnittestRoot optionalNestedMessageExtension]
+ value:nestedMessage];
+
+ // Repeated Group
+ RepeatedGroup_extension *repeatedGroup =
+ [[RepeatedGroup_extension alloc] init];
+ repeatedGroup.a = 567;
+ repeatedGroup.unknownFields = UnknownFieldsSetHelper(780);
+ [message addExtension:[UnittestRoot repeatedGroupExtension]
+ value:repeatedGroup];
+ [repeatedGroup release];
+
+ // Repeated Message
+ nestedMessage = [[TestAllTypes_NestedMessage alloc] init];
+ nestedMessage.bb = 678;
+ nestedMessage.unknownFields = UnknownFieldsSetHelper(781);
+ [message addExtension:[UnittestRoot repeatedNestedMessageExtension]
+ value:nestedMessage];
+ [nestedMessage release];
+ }
+
+ // Confirm everything is there.
+
+ XCTAssertNotNil(message);
+ XCTAssertNotNil(message.unknownFields);
+ XCTAssertTrue([message hasExtension:[UnittestRoot optionalInt32Extension]]);
+
+ {
+ XCTAssertTrue([message hasExtension:[UnittestRoot optionalGroupExtension]]);
+ OptionalGroup_extension *optionalGroup =
+ [message getExtension:[UnittestRoot optionalGroupExtension]];
+ XCTAssertNotNil(optionalGroup);
+ XCTAssertEqual(optionalGroup.a, 123);
+ XCTAssertNotNil(optionalGroup.unknownFields);
+ }
+
+ {
+ XCTAssertTrue([message hasExtension:[UnittestRoot optionalNestedMessageExtension]]);
+ TestAllTypes_NestedMessage *nestedMessage =
+ [message getExtension:[UnittestRoot optionalNestedMessageExtension]];
+ XCTAssertNotNil(nestedMessage);
+ XCTAssertEqual(nestedMessage.bb, 456);
+ XCTAssertNotNil(nestedMessage.unknownFields);
+ }
+
+ {
+ XCTAssertTrue([message hasExtension:[UnittestRoot repeatedGroupExtension]]);
+ NSArray *repeatedGroups = [message getExtension:[UnittestRoot repeatedGroupExtension]];
+ XCTAssertEqual(repeatedGroups.count, (NSUInteger)1);
+ RepeatedGroup_extension *repeatedGroup = repeatedGroups.firstObject;
+ XCTAssertNotNil(repeatedGroup);
+ XCTAssertEqual(repeatedGroup.a, 567);
+ XCTAssertNotNil(repeatedGroup.unknownFields);
+ }
+
+ {
+ XCTAssertTrue([message hasExtension:[UnittestRoot repeatedNestedMessageExtension]]);
+ NSArray *repeatedNestedMessages = [message getExtension:[UnittestRoot repeatedNestedMessageExtension]];
+ XCTAssertEqual(repeatedNestedMessages.count, (NSUInteger)1);
+ TestAllTypes_NestedMessage *repeatedNestedMessage = repeatedNestedMessages.firstObject;
+ XCTAssertNotNil(repeatedNestedMessage);
+ XCTAssertEqual(repeatedNestedMessage.bb, 678);
+ XCTAssertNotNil(repeatedNestedMessage.unknownFields);
+ }
+
+ // Drop them.
+ GPBMessageDropUnknownFieldsRecursively(message);
+
+ // Confirm unknowns are gone from within the messages.
+
+ XCTAssertNotNil(message);
+ XCTAssertNil(message.unknownFields);
+ XCTAssertTrue([message hasExtension:[UnittestRoot optionalInt32Extension]]);
+
+ {
+ XCTAssertTrue([message hasExtension:[UnittestRoot optionalGroupExtension]]);
+ OptionalGroup_extension *optionalGroup =
+ [message getExtension:[UnittestRoot optionalGroupExtension]];
+ XCTAssertNotNil(optionalGroup);
+ XCTAssertEqual(optionalGroup.a, 123);
+ XCTAssertNil(optionalGroup.unknownFields);
+ }
+
+ {
+ XCTAssertTrue([message hasExtension:[UnittestRoot optionalNestedMessageExtension]]);
+ TestAllTypes_NestedMessage *nestedMessage =
+ [message getExtension:[UnittestRoot optionalNestedMessageExtension]];
+ XCTAssertNotNil(nestedMessage);
+ XCTAssertEqual(nestedMessage.bb, 456);
+ XCTAssertNil(nestedMessage.unknownFields);
+ }
+
+ {
+ XCTAssertTrue([message hasExtension:[UnittestRoot repeatedGroupExtension]]);
+ NSArray *repeatedGroups = [message getExtension:[UnittestRoot repeatedGroupExtension]];
+ XCTAssertEqual(repeatedGroups.count, (NSUInteger)1);
+ RepeatedGroup_extension *repeatedGroup = repeatedGroups.firstObject;
+ XCTAssertNotNil(repeatedGroup);
+ XCTAssertEqual(repeatedGroup.a, 567);
+ XCTAssertNil(repeatedGroup.unknownFields);
+ }
+
+ {
+ XCTAssertTrue([message hasExtension:[UnittestRoot repeatedNestedMessageExtension]]);
+ NSArray *repeatedNestedMessages = [message getExtension:[UnittestRoot repeatedNestedMessageExtension]];
+ XCTAssertEqual(repeatedNestedMessages.count, (NSUInteger)1);
+ TestAllTypes_NestedMessage *repeatedNestedMessage = repeatedNestedMessages.firstObject;
+ XCTAssertNotNil(repeatedNestedMessage);
+ XCTAssertEqual(repeatedNestedMessage.bb, 678);
+ XCTAssertNil(repeatedNestedMessage.unknownFields);
+ }
+
+}
+
+- (void)testDropMessageUnknownFieldsRecursively_Maps {
+ TestMap *message = [TestMap message];
+
+ {
+ ForeignMessage *foreignMessage = [ForeignMessage message];
+ foreignMessage.unknownFields = UnknownFieldsSetHelper(100);
+ [message.mapInt32ForeignMessage setObject:foreignMessage forKey:100];
+
+ foreignMessage = [ForeignMessage message];
+ foreignMessage.unknownFields = UnknownFieldsSetHelper(101);
+ [message.mapStringForeignMessage setObject:foreignMessage forKey:@"101"];
+ }
+
+ // Confirm everything is there.
+
+ XCTAssertNotNil(message);
+
+ {
+ ForeignMessage *foreignMessage = [message.mapInt32ForeignMessage objectForKey:100];
+ XCTAssertNotNil(foreignMessage);
+ XCTAssertNotNil(foreignMessage.unknownFields);
+ }
+
+ {
+ ForeignMessage *foreignMessage = [message.mapStringForeignMessage objectForKey:@"101"];
+ XCTAssertNotNil(foreignMessage);
+ XCTAssertNotNil(foreignMessage.unknownFields);
+ }
+
+ GPBMessageDropUnknownFieldsRecursively(message);
+
+ // Confirm unknowns are gone from within the messages.
+
+ XCTAssertNotNil(message);
+
+ {
+ ForeignMessage *foreignMessage = [message.mapInt32ForeignMessage objectForKey:100];
+ XCTAssertNotNil(foreignMessage);
+ XCTAssertNil(foreignMessage.unknownFields);
+ }
+
+ {
+ ForeignMessage *foreignMessage = [message.mapStringForeignMessage objectForKey:@"101"];
+ XCTAssertNotNil(foreignMessage);
+ XCTAssertNil(foreignMessage.unknownFields);
+ }
+
+}
+
@end
diff --git a/objectivec/Tests/GPBWellKnownTypesTest.m b/objectivec/Tests/GPBWellKnownTypesTest.m
index 041841dd..592d5afd 100644
--- a/objectivec/Tests/GPBWellKnownTypesTest.m
+++ b/objectivec/Tests/GPBWellKnownTypesTest.m
@@ -32,11 +32,9 @@
#import <XCTest/XCTest.h>
+#import "GPBTestUtilities.h"
#import "google/protobuf/AnyTest.pbobjc.h"
-// A basically random interval into the future for testing with.
-static const NSTimeInterval kFutureOffsetInterval = 15000;
-
// Nanosecond time accuracy
static const NSTimeInterval kTimeAccuracy = 1e-9;
@@ -46,59 +44,117 @@ static const NSTimeInterval kTimeAccuracy = 1e-9;
@implementation WellKnownTypesTest
- (void)testTimeStamp {
- // Test Creation.
- NSDate *date = [NSDate date];
- GPBTimestamp *timeStamp = [[GPBTimestamp alloc] initWithDate:date];
- NSDate *timeStampDate = timeStamp.date;
-
- // Comparing timeIntervals instead of directly comparing dates because date
- // equality requires the time intervals to be exactly the same, and the
- // timeintervals go through a bit of floating point error as they are
- // converted back and forth from the internal representation.
- XCTAssertEqualWithAccuracy(date.timeIntervalSince1970,
- timeStampDate.timeIntervalSince1970,
- kTimeAccuracy);
-
- NSTimeInterval time = [date timeIntervalSince1970];
- GPBTimestamp *timeStamp2 =
- [[GPBTimestamp alloc] initWithTimeIntervalSince1970:time];
- NSTimeInterval durationTime = timeStamp2.timeIntervalSince1970;
- XCTAssertEqualWithAccuracy(time, durationTime, kTimeAccuracy);
- [timeStamp release];
-
- // Test Mutation.
- date = [NSDate dateWithTimeIntervalSinceNow:kFutureOffsetInterval];
- timeStamp2.date = date;
- timeStampDate = timeStamp2.date;
- XCTAssertEqualWithAccuracy(date.timeIntervalSince1970,
- timeStampDate.timeIntervalSince1970,
- kTimeAccuracy);
-
- time = date.timeIntervalSince1970;
- timeStamp2.timeIntervalSince1970 = time;
- durationTime = timeStamp2.timeIntervalSince1970;
- XCTAssertEqualWithAccuracy(time, durationTime, kTimeAccuracy);
- [timeStamp2 release];
+ // Test negative and positive values.
+ NSTimeInterval values[] = {
+ -428027599.483999967, -1234567.0, -0.5, 0, 0.75, 54321.0, 2468086,483999967
+ };
+ for (size_t i = 0; i < GPBARRAYSIZE(values); ++i) {
+ NSTimeInterval value = values[i];
+
+ // Test Creation - date.
+ NSDate *date = [NSDate dateWithTimeIntervalSince1970:value];
+ GPBTimestamp *timeStamp = [[GPBTimestamp alloc] initWithDate:date];
+
+ XCTAssertGreaterThanOrEqual(timeStamp.nanos, 0,
+ @"Offset %f - Date: %@", (double)value, date);
+ XCTAssertLessThan(timeStamp.nanos, 1e9,
+ @"Offset %f - Date: %@", (double)value, date);
+
+ // Comparing timeIntervals instead of directly comparing dates because date
+ // equality requires the time intervals to be exactly the same, and the
+ // timeintervals go through a bit of floating point error as they are
+ // converted back and forth from the internal representation.
+ XCTAssertEqualWithAccuracy(value, timeStamp.date.timeIntervalSince1970,
+ kTimeAccuracy,
+ @"Offset %f - Date: %@", (double)value, date);
+ [timeStamp release];
+
+ // Test Creation - timeIntervalSince1970.
+ timeStamp = [[GPBTimestamp alloc] initWithTimeIntervalSince1970:value];
+
+ XCTAssertGreaterThanOrEqual(timeStamp.nanos, 0,
+ @"Offset %f - Date: %@", (double)value, date);
+ XCTAssertLessThan(timeStamp.nanos, 1e9,
+ @"Offset %f - Date: %@", (double)value, date);
+
+ XCTAssertEqualWithAccuracy(value, timeStamp.timeIntervalSince1970,
+ kTimeAccuracy,
+ @"Offset %f - Date: %@", (double)value, date);
+ [timeStamp release];
+
+ // Test Mutation - date.
+ timeStamp = [[GPBTimestamp alloc] init];
+ timeStamp.date = date;
+
+ XCTAssertGreaterThanOrEqual(timeStamp.nanos, 0,
+ @"Offset %f - Date: %@", (double)value, date);
+ XCTAssertLessThan(timeStamp.nanos, 1e9,
+ @"Offset %f - Date: %@", (double)value, date);
+
+ XCTAssertEqualWithAccuracy(value, timeStamp.date.timeIntervalSince1970,
+ kTimeAccuracy,
+ @"Offset %f - Date: %@", (double)value, date);
+ [timeStamp release];
+
+ // Test Mutation - timeIntervalSince1970.
+ timeStamp = [[GPBTimestamp alloc] init];
+ timeStamp.timeIntervalSince1970 = value;
+
+ XCTAssertGreaterThanOrEqual(timeStamp.nanos, 0,
+ @"Offset %f - Date: %@", (double)value, date);
+ XCTAssertLessThan(timeStamp.nanos, 1e9,
+ @"Offset %f - Date: %@", (double)value, date);
+
+ XCTAssertEqualWithAccuracy(value, timeStamp.date.timeIntervalSince1970,
+ kTimeAccuracy,
+ @"Offset %f - Date: %@", (double)value, date);
+
+ [timeStamp release];
+ }
}
- (void)testDuration {
- // Test Creation.
- NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
- GPBDuration *duration =
- [[GPBDuration alloc] initWithTimeIntervalSince1970:time];
- NSTimeInterval durationTime = duration.timeIntervalSince1970;
- XCTAssertEqualWithAccuracy(time, durationTime, kTimeAccuracy);
- [duration release];
-
- // Test Mutation.
- GPBDuration *duration2 =
- [[GPBDuration alloc] initWithTimeIntervalSince1970:time];
- NSDate *date = [NSDate dateWithTimeIntervalSinceNow:kFutureOffsetInterval];
- time = date.timeIntervalSince1970;
- duration2.timeIntervalSince1970 = time;
- durationTime = duration2.timeIntervalSince1970;
- XCTAssertEqualWithAccuracy(time, durationTime, kTimeAccuracy);
- [duration2 release];
+ // Test negative and positive values.
+ NSTimeInterval values[] = { -1000.0001, -500.0, -0.5, 0, 0.75, 1000.0, 2000.0002 };
+ for (size_t i = 0; i < GPBARRAYSIZE(values); ++i) {
+ NSTimeInterval value = values[i];
+
+ // Test Creation.
+ GPBDuration *duration =
+ [[GPBDuration alloc] initWithTimeInterval:value];
+ XCTAssertEqualWithAccuracy(value, duration.timeInterval, kTimeAccuracy,
+ @"For interval %f", (double)value);
+ if (value > 0) {
+ XCTAssertGreaterThanOrEqual(duration.seconds, 0,
+ @"For interval %f", (double)value);
+ XCTAssertGreaterThanOrEqual(duration.nanos, 0,
+ @"For interval %f", (double)value);
+ } else {
+ XCTAssertLessThanOrEqual(duration.seconds, 0,
+ @"For interval %f", (double)value);
+ XCTAssertLessThanOrEqual(duration.nanos, 0,
+ @"For interval %f", (double)value);
+ }
+ [duration release];
+
+ // Test Mutation.
+ duration = [[GPBDuration alloc] init];
+ duration.timeInterval = value;
+ XCTAssertEqualWithAccuracy(value, duration.timeInterval, kTimeAccuracy,
+ @"For interval %f", (double)value);
+ if (value > 0) {
+ XCTAssertGreaterThanOrEqual(duration.seconds, 0,
+ @"For interval %f", (double)value);
+ XCTAssertGreaterThanOrEqual(duration.nanos, 0,
+ @"For interval %f", (double)value);
+ } else {
+ XCTAssertLessThanOrEqual(duration.seconds, 0,
+ @"For interval %f", (double)value);
+ XCTAssertLessThanOrEqual(duration.nanos, 0,
+ @"For interval %f", (double)value);
+ }
+ [duration release];
+ }
}
- (void)testAnyHelpers {
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/Contents.json b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/Contents.json
index 0cbf9acc..9f4a9e59 100644
--- a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/Contents.json
+++ b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/Contents.json
@@ -1,72 +1,103 @@
{
"images" : [
{
+ "size" : "20x20",
"idiom" : "iphone",
+ "filename" : "appicon_40.png",
+ "scale" : "2x"
+ },
+ {
+ "size" : "20x20",
+ "idiom" : "iphone",
+ "filename" : "appicon_60.png",
+ "scale" : "3x"
+ },
+ {
"size" : "29x29",
+ "idiom" : "iphone",
+ "filename" : "appicon_29.png",
"scale" : "1x"
},
{
- "idiom" : "iphone",
"size" : "29x29",
+ "idiom" : "iphone",
+ "filename" : "appicon_58.png",
"scale" : "2x"
},
{
- "idiom" : "iphone",
"size" : "29x29",
+ "idiom" : "iphone",
+ "filename" : "appicon_87.png",
"scale" : "3x"
},
{
- "idiom" : "iphone",
"size" : "40x40",
+ "idiom" : "iphone",
+ "filename" : "appicon_80.png",
"scale" : "2x"
},
{
- "idiom" : "iphone",
"size" : "40x40",
+ "idiom" : "iphone",
+ "filename" : "appicon_120.png",
"scale" : "3x"
},
{
- "size" : "57x57",
"idiom" : "iphone",
- "filename" : "iPhone6.png",
+ "size" : "57x57",
"scale" : "1x"
},
{
- "size" : "57x57",
"idiom" : "iphone",
- "filename" : "iPhone6_2x.png",
+ "size" : "57x57",
"scale" : "2x"
},
{
"size" : "60x60",
"idiom" : "iphone",
- "filename" : "iPhone7_2x.png",
+ "filename" : "appicon_120.png",
"scale" : "2x"
},
{
"size" : "60x60",
"idiom" : "iphone",
- "filename" : "iPhone7_3x.png",
+ "filename" : "appicon_180.png",
"scale" : "3x"
},
{
+ "size" : "20x20",
"idiom" : "ipad",
- "size" : "29x29",
+ "filename" : "appicon_20.png",
"scale" : "1x"
},
{
+ "size" : "20x20",
"idiom" : "ipad",
- "size" : "29x29",
+ "filename" : "appicon_40.png",
"scale" : "2x"
},
{
+ "size" : "29x29",
"idiom" : "ipad",
- "size" : "40x40",
+ "filename" : "appicon_29.png",
"scale" : "1x"
},
{
+ "size" : "29x29",
"idiom" : "ipad",
+ "filename" : "appicon_58.png",
+ "scale" : "2x"
+ },
+ {
"size" : "40x40",
+ "idiom" : "ipad",
+ "filename" : "appicon_40.png",
+ "scale" : "1x"
+ },
+ {
+ "size" : "40x40",
+ "idiom" : "ipad",
+ "filename" : "appicon_80.png",
"scale" : "2x"
},
{
@@ -80,32 +111,37 @@
"scale" : "2x"
},
{
- "size" : "72x72",
"idiom" : "ipad",
- "filename" : "iPad6.png",
+ "size" : "72x72",
"scale" : "1x"
},
{
- "size" : "72x72",
"idiom" : "ipad",
- "filename" : "iPad6_2x.png",
+ "size" : "72x72",
"scale" : "2x"
},
{
"size" : "76x76",
"idiom" : "ipad",
- "filename" : "iPad7.png",
+ "filename" : "appicon_76.png",
"scale" : "1x"
},
{
"size" : "76x76",
"idiom" : "ipad",
- "filename" : "iPad7_2x.png",
+ "filename" : "appicon_152.png",
+ "scale" : "2x"
+ },
+ {
+ "size" : "83.5x83.5",
+ "idiom" : "ipad",
+ "filename" : "appicon_167.png",
"scale" : "2x"
},
{
- "idiom" : "car",
- "size" : "120x120",
+ "size" : "1024x1024",
+ "idiom" : "ios-marketing",
+ "filename" : "appicon_1024.png",
"scale" : "1x"
}
],
@@ -113,4 +149,4 @@
"version" : 1,
"author" : "xcode"
}
-}
+} \ No newline at end of file
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_1024.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_1024.png
new file mode 100644
index 00000000..6b6a102e
--- /dev/null
+++ b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_1024.png
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_120.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_120.png
new file mode 100644
index 00000000..1bac2e58
--- /dev/null
+++ b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_120.png
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_152.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_152.png
new file mode 100644
index 00000000..80f13301
--- /dev/null
+++ b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_152.png
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_167.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_167.png
new file mode 100644
index 00000000..99f0745e
--- /dev/null
+++ b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_167.png
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_180.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_180.png
new file mode 100644
index 00000000..ae123712
--- /dev/null
+++ b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_180.png
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_20.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_20.png
new file mode 100644
index 00000000..8e530c49
--- /dev/null
+++ b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_20.png
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_29.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_29.png
new file mode 100644
index 00000000..1826feb9
--- /dev/null
+++ b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_29.png
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_40.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_40.png
new file mode 100644
index 00000000..f2e2ded1
--- /dev/null
+++ b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_40.png
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_58.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_58.png
new file mode 100644
index 00000000..0ec6d003
--- /dev/null
+++ b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_58.png
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_60.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_60.png
new file mode 100644
index 00000000..8664e8b0
--- /dev/null
+++ b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_60.png
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_76.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_76.png
new file mode 100644
index 00000000..d4bb05b9
--- /dev/null
+++ b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_76.png
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_80.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_80.png
new file mode 100644
index 00000000..8fa6a8e7
--- /dev/null
+++ b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_80.png
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_87.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_87.png
new file mode 100644
index 00000000..b41bc67b
--- /dev/null
+++ b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/appicon_87.png
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad6.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad6.png
deleted file mode 100644
index 43da2ee4..00000000
--- a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad6.png
+++ /dev/null
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad6_2x.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad6_2x.png
deleted file mode 100644
index 2ec93704..00000000
--- a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad6_2x.png
+++ /dev/null
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad7.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad7.png
deleted file mode 100644
index aec8bc1b..00000000
--- a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad7.png
+++ /dev/null
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad7_2x.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad7_2x.png
deleted file mode 100644
index e39cc3e7..00000000
--- a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPad7_2x.png
+++ /dev/null
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone6.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone6.png
deleted file mode 100644
index 5572d79f..00000000
--- a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone6.png
+++ /dev/null
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone6_2x.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone6_2x.png
deleted file mode 100644
index 2424997f..00000000
--- a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone6_2x.png
+++ /dev/null
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone7_2x.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone7_2x.png
deleted file mode 100644
index 10bfc3cf..00000000
--- a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone7_2x.png
+++ /dev/null
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone7_3x.png b/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone7_3x.png
deleted file mode 100644
index 8d16f14d..00000000
--- a/objectivec/Tests/iOSTestHarness/Images.xcassets/AppIcon.appiconset/iPhone7_3x.png
+++ /dev/null
Binary files differ
diff --git a/objectivec/Tests/iOSTestHarness/Images.xcassets/LaunchImage.launchimage/Contents.json b/objectivec/Tests/iOSTestHarness/Images.xcassets/LaunchImage.launchimage/Contents.json
index 5a296668..a0ad363c 100644
--- a/objectivec/Tests/iOSTestHarness/Images.xcassets/LaunchImage.launchimage/Contents.json
+++ b/objectivec/Tests/iOSTestHarness/Images.xcassets/LaunchImage.launchimage/Contents.json
@@ -3,43 +3,30 @@
{
"orientation" : "portrait",
"idiom" : "ipad",
- "minimum-system-version" : "7.0",
"extent" : "full-screen",
- "scale" : "2x"
- },
- {
- "orientation" : "landscape",
- "idiom" : "ipad",
"minimum-system-version" : "7.0",
- "extent" : "full-screen",
"scale" : "1x"
},
{
"orientation" : "landscape",
"idiom" : "ipad",
- "minimum-system-version" : "7.0",
"extent" : "full-screen",
- "scale" : "2x"
- },
- {
- "orientation" : "portrait",
- "idiom" : "iphone",
"minimum-system-version" : "7.0",
- "scale" : "2x"
+ "scale" : "1x"
},
{
"orientation" : "portrait",
- "idiom" : "iphone",
+ "idiom" : "ipad",
+ "extent" : "full-screen",
"minimum-system-version" : "7.0",
- "subtype" : "retina4",
"scale" : "2x"
},
{
- "orientation" : "portrait",
+ "orientation" : "landscape",
"idiom" : "ipad",
- "minimum-system-version" : "7.0",
"extent" : "full-screen",
- "scale" : "1x"
+ "minimum-system-version" : "7.0",
+ "scale" : "2x"
}
],
"info" : {
diff --git a/objectivec/google/protobuf/Any.pbobjc.h b/objectivec/google/protobuf/Any.pbobjc.h
index d236e4b2..b17e76f0 100644
--- a/objectivec/google/protobuf/Any.pbobjc.h
+++ b/objectivec/google/protobuf/Any.pbobjc.h
@@ -87,6 +87,16 @@ typedef GPB_ENUM(GPBAny_FieldNumber) {
* any.Unpack(foo)
* ...
*
+ * Example 4: Pack and unpack a message in Go
+ *
+ * foo := &pb.Foo{...}
+ * any, err := ptypes.MarshalAny(foo)
+ * ...
+ * foo := &pb.Foo{}
+ * if err := ptypes.UnmarshalAny(any, foo); err != nil {
+ * ...
+ * }
+ *
* The pack methods provided by protobuf library will by default use
* 'type.googleapis.com/full.type.name' as the type URL and the unpack
* methods only use the fully qualified type name after the last '/'
diff --git a/objectivec/google/protobuf/Api.pbobjc.h b/objectivec/google/protobuf/Api.pbobjc.h
index 742a8122..095fc2cd 100644
--- a/objectivec/google/protobuf/Api.pbobjc.h
+++ b/objectivec/google/protobuf/Api.pbobjc.h
@@ -63,34 +63,41 @@ typedef GPB_ENUM(GPBApi_FieldNumber) {
};
/**
- * Api is a light-weight descriptor for a protocol buffer service.
+ * Api is a light-weight descriptor for an API Interface.
+ *
+ * Interfaces are also described as "protocol buffer services" in some contexts,
+ * such as by the "service" keyword in a .proto file, but they are different
+ * from API Services, which represent a concrete implementation of an interface
+ * as opposed to simply a description of methods and bindings. They are also
+ * sometimes simply referred to as "APIs" in other contexts, such as the name of
+ * this message itself. See https://cloud.google.com/apis/design/glossary for
+ * detailed terminology.
**/
@interface GPBApi : GPBMessage
/**
- * The fully qualified name of this api, including package name
- * followed by the api's simple name.
+ * The fully qualified name of this interface, including package name
+ * followed by the interface's simple name.
**/
@property(nonatomic, readwrite, copy, null_resettable) NSString *name;
-/** The methods of this api, in unspecified order. */
+/** The methods of this interface, in unspecified order. */
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<GPBMethod*> *methodsArray;
/** The number of items in @c methodsArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger methodsArray_Count;
-/** Any metadata attached to the API. */
+/** Any metadata attached to the interface. */
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<GPBOption*> *optionsArray;
/** The number of items in @c optionsArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger optionsArray_Count;
/**
- * A version string for this api. If specified, must have the form
- * `major-version.minor-version`, as in `1.10`. If the minor version
- * is omitted, it defaults to zero. If the entire version field is
- * empty, the major version is derived from the package name, as
- * outlined below. If the field is not empty, the version in the
- * package name will be verified to be consistent with what is
- * provided here.
+ * A version string for this interface. If specified, must have the form
+ * `major-version.minor-version`, as in `1.10`. If the minor version is
+ * omitted, it defaults to zero. If the entire version field is empty, the
+ * major version is derived from the package name, as outlined below. If the
+ * field is not empty, the version in the package name will be verified to be
+ * consistent with what is provided here.
*
* The versioning schema uses [semantic
* versioning](http://semver.org) where the major version number
@@ -100,10 +107,10 @@ typedef GPB_ENUM(GPBApi_FieldNumber) {
* chosen based on the product plan.
*
* The major version is also reflected in the package name of the
- * API, which must end in `v<major-version>`, as in
+ * interface, which must end in `v<major-version>`, as in
* `google.feature.v1`. For major versions 0 and 1, the suffix can
* be omitted. Zero major versions must only be used for
- * experimental, none-GA apis.
+ * experimental, non-GA interfaces.
**/
@property(nonatomic, readwrite, copy, null_resettable) NSString *version;
@@ -115,7 +122,7 @@ typedef GPB_ENUM(GPBApi_FieldNumber) {
/** Test to see if @c sourceContext has been set. */
@property(nonatomic, readwrite) BOOL hasSourceContext;
-/** Included APIs. See [Mixin][]. */
+/** Included interfaces. See [Mixin][]. */
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<GPBMixin*> *mixinsArray;
/** The number of items in @c mixinsArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger mixinsArray_Count;
@@ -150,7 +157,7 @@ typedef GPB_ENUM(GPBMethod_FieldNumber) {
};
/**
- * Method represents a method of an api.
+ * Method represents a method of an API interface.
**/
@interface GPBMethod : GPBMessage
@@ -199,9 +206,9 @@ typedef GPB_ENUM(GPBMixin_FieldNumber) {
};
/**
- * Declares an API to be included in this API. The including API must
- * redeclare all the methods from the included API, but documentation
- * and options are inherited as follows:
+ * Declares an API Interface to be included in this interface. The including
+ * interface must redeclare all the methods from the included interface, but
+ * documentation and options are inherited as follows:
*
* - If after comment and whitespace stripping, the documentation
* string of the redeclared method is empty, it will be inherited
@@ -213,7 +220,8 @@ typedef GPB_ENUM(GPBMixin_FieldNumber) {
*
* - If an http annotation is inherited, the path pattern will be
* modified as follows. Any version prefix will be replaced by the
- * version of the including API plus the [root][] path if specified.
+ * version of the including interface plus the [root][] path if
+ * specified.
*
* Example of a simple mixin:
*
@@ -279,7 +287,7 @@ typedef GPB_ENUM(GPBMixin_FieldNumber) {
**/
@interface GPBMixin : GPBMessage
-/** The fully qualified name of the API which is included. */
+/** The fully qualified name of the interface which is included. */
@property(nonatomic, readwrite, copy, null_resettable) NSString *name;
/**
diff --git a/objectivec/google/protobuf/Duration.pbobjc.h b/objectivec/google/protobuf/Duration.pbobjc.h
index e70138a0..d9a388ac 100644
--- a/objectivec/google/protobuf/Duration.pbobjc.h
+++ b/objectivec/google/protobuf/Duration.pbobjc.h
@@ -59,6 +59,8 @@ typedef GPB_ENUM(GPBDuration_FieldNumber) {
* two Timestamp values is a Duration and it can be added or subtracted
* from a Timestamp. Range is approximately +-10,000 years.
*
+ * # Examples
+ *
* Example 1: Compute Duration from two Timestamps in pseudo code.
*
* Timestamp start = ...;
@@ -98,12 +100,23 @@ typedef GPB_ENUM(GPBDuration_FieldNumber) {
* td = datetime.timedelta(days=3, minutes=10)
* duration = Duration()
* duration.FromTimedelta(td)
+ *
+ * # JSON Mapping
+ *
+ * In JSON format, the Duration type is encoded as a string rather than an
+ * object, where the string ends in the suffix "s" (indicating seconds) and
+ * is preceded by the number of seconds, with nanoseconds expressed as
+ * fractional seconds. For example, 3 seconds with 0 nanoseconds should be
+ * encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should
+ * be expressed in JSON format as "3.000000001s", and 3 seconds and 1
+ * microsecond should be expressed in JSON format as "3.000001s".
**/
@interface GPBDuration : GPBMessage
/**
* Signed seconds of the span of time. Must be from -315,576,000,000
- * to +315,576,000,000 inclusive.
+ * to +315,576,000,000 inclusive. Note: these bounds are computed from:
+ * 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years
**/
@property(nonatomic, readwrite) int64_t seconds;
diff --git a/objectivec/google/protobuf/FieldMask.pbobjc.h b/objectivec/google/protobuf/FieldMask.pbobjc.h
index 07e60818..75cf856c 100644
--- a/objectivec/google/protobuf/FieldMask.pbobjc.h
+++ b/objectivec/google/protobuf/FieldMask.pbobjc.h
@@ -252,6 +252,12 @@ typedef GPB_ENUM(GPBFieldMask_FieldNumber) {
*
* Note that oneof type names ("test_oneof" in this case) cannot be used in
* paths.
+ *
+ * ## Field Mask Verification
+ *
+ * The implementation of the all the API methods, which have any FieldMask type
+ * field in the request, should verify the included field paths, and return
+ * `INVALID_ARGUMENT` error if any path is duplicated or unmappable.
**/
@interface GPBFieldMask : GPBMessage
diff --git a/objectivec/google/protobuf/Timestamp.pbobjc.h b/objectivec/google/protobuf/Timestamp.pbobjc.h
index 9c83d094..0b670c35 100644
--- a/objectivec/google/protobuf/Timestamp.pbobjc.h
+++ b/objectivec/google/protobuf/Timestamp.pbobjc.h
@@ -64,6 +64,8 @@ typedef GPB_ENUM(GPBTimestamp_FieldNumber) {
* and from RFC 3339 date strings.
* See [https://www.ietf.org/rfc/rfc3339.txt](https://www.ietf.org/rfc/rfc3339.txt).
*
+ * # Examples
+ *
* Example 1: Compute Timestamp from POSIX `time()`.
*
* Timestamp timestamp;
@@ -103,6 +105,29 @@ typedef GPB_ENUM(GPBTimestamp_FieldNumber) {
*
* timestamp = Timestamp()
* timestamp.GetCurrentTime()
+ *
+ * # JSON Mapping
+ *
+ * In JSON format, the Timestamp type is encoded as a string in the
+ * [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the
+ * format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z"
+ * where {year} is always expressed using four digits while {month}, {day},
+ * {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional
+ * seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution),
+ * are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone
+ * is required, though only UTC (as indicated by "Z") is presently supported.
+ *
+ * For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past
+ * 01:30 UTC on January 15, 2017.
+ *
+ * In JavaScript, one can convert a Date object to this format using the
+ * standard [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString]
+ * method. In Python, a standard `datetime.datetime` object can be converted
+ * to this format using [`strftime`](https://docs.python.org/2/library/time.html#time.strftime)
+ * with the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one
+ * can use the Joda Time's [`ISODateTimeFormat.dateTime()`](
+ * http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime--)
+ * to obtain a formatter capable of generating timestamps in this format.
**/
@interface GPBTimestamp : GPBMessage
diff --git a/objectivec/google/protobuf/Type.pbobjc.h b/objectivec/google/protobuf/Type.pbobjc.h
index 06e75480..17986970 100644
--- a/objectivec/google/protobuf/Type.pbobjc.h
+++ b/objectivec/google/protobuf/Type.pbobjc.h
@@ -411,10 +411,20 @@ typedef GPB_ENUM(GPBOption_FieldNumber) {
**/
@interface GPBOption : GPBMessage
-/** The option's name. For example, `"java_package"`. */
+/**
+ * The option's name. For protobuf built-in options (options defined in
+ * descriptor.proto), this is the short name. For example, `"map_entry"`.
+ * For custom options, it should be the fully-qualified name. For example,
+ * `"google.api.http"`.
+ **/
@property(nonatomic, readwrite, copy, null_resettable) NSString *name;
-/** The option's value. For example, `"com.google.protobuf"`. */
+/**
+ * The option's value packed in an Any message. If the value is a primitive,
+ * the corresponding wrapper type defined in google/protobuf/wrappers.proto
+ * should be used. If the value is an enum, it should be stored as an int32
+ * value using the google.protobuf.Int32Value type.
+ **/
@property(nonatomic, readwrite, strong, null_resettable) GPBAny *value;
/** Test to see if @c value has been set. */
@property(nonatomic, readwrite) BOOL hasValue;
diff --git a/php/README.md b/php/README.md
index ec92d329..da7884ea 100644
--- a/php/README.md
+++ b/php/README.md
@@ -16,7 +16,7 @@ generation functionality.
To use PHP runtime library requires:
-- C extension: PHP 5.5.x or 5.6.x.
+- C extension: PHP 5.5, 5.6, or 7.
- PHP package: PHP 5.5, 5.6 or 7.
## Installation
@@ -80,8 +80,6 @@ protoc --php_out=out_dir test.proto
## Usage
-For general guide:
- https://developers.google.com/protocol-buffers/phptutorial/
For generated code:
https://developers.google.com/protocol-buffers/docs/reference/php-generated
diff --git a/php/composer.json b/php/composer.json
index 3dae2865..34e0447c 100644
--- a/php/composer.json
+++ b/php/composer.json
@@ -13,15 +13,9 @@
},
"autoload": {
"psr-4": {
- "Foo\\": "tests/generated/Foo",
- "Bar\\": "tests/generated/Bar",
- "Google\\Protobuf\\": "tests/generated/Google/Protobuf",
- "Google\\Protobuf\\Internal\\": "src/Google/Protobuf/Internal",
- "GPBMetadata\\": "tests/generated/GPBMetadata",
- "GPBMetadata\\Google\\Protobuf\\Internal\\": "src/GPBMetadata/Google/Protobuf/Internal"
- },
- "files": [
- "src/Google/Protobuf/descriptor.php"
- ]
+ "Google\\Protobuf\\": "src/Google/Protobuf",
+ "GPBMetadata\\Google\\Protobuf\\": "src/GPBMetadata/Google/Protobuf",
+ "": "tests/generated"
+ }
}
}
diff --git a/php/ext/google/protobuf/array.c b/php/ext/google/protobuf/array.c
index e4a88c39..e69bef42 100644
--- a/php/ext/google/protobuf/array.c
+++ b/php/ext/google/protobuf/array.c
@@ -69,19 +69,20 @@ static zend_function_entry repeated_field_iter_methods[] = {
// Forward declare static functions.
-static zend_object_value repeated_field_create(zend_class_entry *ce TSRMLS_DC);
-static void repeated_field_free(void *object TSRMLS_DC);
static int repeated_field_array_init(zval *array, upb_fieldtype_t type,
uint size ZEND_FILE_LINE_DC);
-static void repeated_field_free_element(void *object);
static void repeated_field_write_dimension(zval *object, zval *offset,
zval *value TSRMLS_DC);
static int repeated_field_has_dimension(zval *object, zval *offset TSRMLS_DC);
-static HashTable *repeated_field_get_gc(zval *object, zval ***table,
+static HashTable *repeated_field_get_gc(zval *object, CACHED_VALUE **table,
int *n TSRMLS_DC);
-
+#if PHP_MAJOR_VERSION < 7
+static zend_object_value repeated_field_create(zend_class_entry *ce TSRMLS_DC);
static zend_object_value repeated_field_iter_create(zend_class_entry *ce TSRMLS_DC);
-static void repeated_field_iter_free(void *object TSRMLS_DC);
+#else
+static zend_object *repeated_field_create(zend_class_entry *ce TSRMLS_DC);
+static zend_object *repeated_field_iter_create(zend_class_entry *ce TSRMLS_DC);
+#endif
// -----------------------------------------------------------------------------
// RepeatedField creation/desctruction
@@ -90,75 +91,86 @@ static void repeated_field_iter_free(void *object TSRMLS_DC);
zend_class_entry* repeated_field_type;
zend_class_entry* repeated_field_iter_type;
zend_object_handlers* repeated_field_handlers;
-
-void repeated_field_init(TSRMLS_D) {
- zend_class_entry class_type;
- const char* class_name = "Google\\Protobuf\\Internal\\RepeatedField";
- INIT_CLASS_ENTRY_EX(class_type, class_name, strlen(class_name),
- repeated_field_methods);
-
- repeated_field_type = zend_register_internal_class(&class_type TSRMLS_CC);
- repeated_field_type->create_object = repeated_field_create;
-
- zend_class_implements(repeated_field_type TSRMLS_CC, 3, spl_ce_ArrayAccess,
- zend_ce_aggregate, spl_ce_Countable);
-
- repeated_field_handlers = PEMALLOC(zend_object_handlers);
- memcpy(repeated_field_handlers, zend_get_std_object_handlers(),
- sizeof(zend_object_handlers));
- repeated_field_handlers->get_gc = repeated_field_get_gc;
+zend_object_handlers* repeated_field_iter_handlers;
+
+// Define object free method.
+PHP_PROTO_OBJECT_FREE_START(RepeatedField, repeated_field)
+#if PHP_MAJOR_VERSION < 7
+php_proto_zval_ptr_dtor(intern->array);
+#else
+php_proto_zval_ptr_dtor(&intern->array);
+#endif
+PHP_PROTO_OBJECT_FREE_END
+
+PHP_PROTO_OBJECT_DTOR_START(RepeatedField, repeated_field)
+PHP_PROTO_OBJECT_DTOR_END
+
+// Define object create method.
+PHP_PROTO_OBJECT_CREATE_START(RepeatedField, repeated_field)
+#if PHP_MAJOR_VERSION < 7
+intern->array = NULL;
+#endif
+intern->type = 0;
+intern->msg_ce = NULL;
+PHP_PROTO_OBJECT_CREATE_END(RepeatedField, repeated_field)
+
+// Init class entry.
+PHP_PROTO_INIT_CLASS_START("Google\\Protobuf\\Internal\\RepeatedField",
+ RepeatedField, repeated_field)
+zend_class_implements(repeated_field_type TSRMLS_CC, 3, spl_ce_ArrayAccess,
+ zend_ce_aggregate, spl_ce_Countable);
+repeated_field_handlers->write_dimension = repeated_field_write_dimension;
+repeated_field_handlers->get_gc = repeated_field_get_gc;
+PHP_PROTO_INIT_CLASS_END
+
+// Define array element free function.
+#if PHP_MAJOR_VERSION < 7
+static inline void php_proto_array_string_release(void *value) {
+ zval_ptr_dtor(value);
}
-static zend_object_value repeated_field_create(zend_class_entry *ce TSRMLS_DC) {
- zend_object_value retval = {0};
- RepeatedField *intern;
-
- intern = emalloc(sizeof(RepeatedField));
- memset(intern, 0, sizeof(RepeatedField));
-
- zend_object_std_init(&intern->std, ce TSRMLS_CC);
- object_properties_init(&intern->std, ce);
-
- intern->array = NULL;
- intern->type = 0;
- intern->msg_ce = NULL;
-
- retval.handle = zend_objects_store_put(
- intern, (zend_objects_store_dtor_t)zend_objects_destroy_object,
- (zend_objects_free_object_storage_t)repeated_field_free, NULL TSRMLS_CC);
- retval.handlers = repeated_field_handlers;
-
- return retval;
+static inline void php_proto_array_object_release(void *value) {
+ zval_ptr_dtor(value);
}
-
-static void repeated_field_free(void *object TSRMLS_DC) {
- RepeatedField *intern = object;
- zend_object_std_dtor(&intern->std TSRMLS_CC);
- zval_ptr_dtor(&intern->array);
- efree(object);
+static inline void php_proto_array_default_release(void *value) {
+}
+#else
+static inline void php_proto_array_string_release(zval *value) {
+ void* ptr = Z_PTR_P(value);
+ zend_string* object = *(zend_string**)ptr;
+ zend_string_release(object);
+ efree(ptr);
+}
+static inline void php_proto_array_object_release(zval *value) {
+ zval_ptr_dtor(value);
}
+static void php_proto_array_default_release(zval* value) {
+ void* ptr = Z_PTR_P(value);
+ efree(ptr);
+}
+#endif
static int repeated_field_array_init(zval *array, upb_fieldtype_t type,
uint size ZEND_FILE_LINE_DC) {
- ALLOC_HASHTABLE(Z_ARRVAL_P(array));
+ PHP_PROTO_ALLOC_ARRAY(array);
switch (type) {
case UPB_TYPE_STRING:
case UPB_TYPE_BYTES:
+ zend_hash_init(Z_ARRVAL_P(array), size, NULL,
+ php_proto_array_string_release, 0);
+ break;
case UPB_TYPE_MESSAGE:
- zend_hash_init(Z_ARRVAL_P(array), size, NULL, ZVAL_PTR_DTOR, 0);
+ zend_hash_init(Z_ARRVAL_P(array), size, NULL,
+ php_proto_array_object_release, 0);
break;
default:
- zend_hash_init(Z_ARRVAL_P(array), size, NULL, repeated_field_free_element,
- 0);
+ zend_hash_init(Z_ARRVAL_P(array), size, NULL,
+ php_proto_array_default_release, 0);
}
- Z_TYPE_P(array) = IS_ARRAY;
return SUCCESS;
}
-static void repeated_field_free_element(void *object) {
-}
-
// -----------------------------------------------------------------------------
// RepeatedField Handlers
// -----------------------------------------------------------------------------
@@ -167,23 +179,25 @@ static void repeated_field_write_dimension(zval *object, zval *offset,
zval *value TSRMLS_DC) {
uint64_t index;
- RepeatedField *intern = zend_object_store_get_object(object TSRMLS_CC);
- HashTable *ht = HASH_OF(intern->array);
+ RepeatedField *intern = UNBOX(RepeatedField, object);
+ HashTable *ht = PHP_PROTO_HASH_OF(intern->array);
int size = native_slot_size(intern->type);
unsigned char memory[NATIVE_SLOT_MAX_SIZE];
memset(memory, 0, NATIVE_SLOT_MAX_SIZE);
- if (!native_slot_set(intern->type, intern->msg_ce, memory, value TSRMLS_CC)) {
+ if (!native_slot_set_by_array(intern->type, intern->msg_ce, memory,
+ value TSRMLS_CC)) {
return;
}
if (!offset || Z_TYPE_P(offset) == IS_NULL) {
- index = zend_hash_num_elements(HASH_OF(intern->array));
+ index = zend_hash_num_elements(PHP_PROTO_HASH_OF(intern->array));
} else {
if (protobuf_convert_to_uint64(offset, &index)) {
if (!zend_hash_index_exists(ht, index)) {
- zend_error(E_USER_ERROR, "Element at %llu doesn't exist.\n", index);
+ zend_error(E_USER_ERROR, "Element at %llu doesn't exist.\n",
+ (long long unsigned int)index);
return;
}
} else {
@@ -191,15 +205,23 @@ static void repeated_field_write_dimension(zval *object, zval *offset,
}
}
- zend_hash_index_update(ht, index, memory, size, NULL);
+ if (intern->type == UPB_TYPE_MESSAGE) {
+ php_proto_zend_hash_index_update_zval(ht, index, *(zval**)memory);
+ } else {
+ php_proto_zend_hash_index_update_mem(ht, index, memory, size, NULL);
+ }
}
+#if PHP_MAJOR_VERSION < 7
static HashTable *repeated_field_get_gc(zval *object, zval ***table,
int *n TSRMLS_DC) {
+#else
+static HashTable *repeated_field_get_gc(zval *object, zval **table, int *n) {
+#endif
*table = NULL;
*n = 0;
- RepeatedField *intern = zend_object_store_get_object(object TSRMLS_CC);
- return HASH_OF(intern->array);
+ RepeatedField *intern = UNBOX(RepeatedField, object);
+ return PHP_PROTO_HASH_OF(intern->array);
}
// -----------------------------------------------------------------------------
@@ -207,42 +229,61 @@ static HashTable *repeated_field_get_gc(zval *object, zval ***table,
// -----------------------------------------------------------------------------
void *repeated_field_index_native(RepeatedField *intern, int index TSRMLS_DC) {
- HashTable *ht = HASH_OF(intern->array);
+ HashTable *ht = PHP_PROTO_HASH_OF(intern->array);
void *value;
- if (zend_hash_index_find(ht, index, (void **)&value) == FAILURE) {
- zend_error(E_USER_ERROR, "Element at %d doesn't exist.\n", index);
- return NULL;
+ if (intern->type == UPB_TYPE_MESSAGE) {
+ if (php_proto_zend_hash_index_find_zval(ht, index, (void **)&value) ==
+ FAILURE) {
+ zend_error(E_USER_ERROR, "Element at %d doesn't exist.\n", index);
+ return NULL;
+ }
+ } else {
+ if (php_proto_zend_hash_index_find_mem(ht, index, (void **)&value) ==
+ FAILURE) {
+ zend_error(E_USER_ERROR, "Element at %d doesn't exist.\n", index);
+ return NULL;
+ }
}
return value;
}
-void repeated_field_push_native(RepeatedField *intern, void *value TSRMLS_DC) {
- HashTable *ht = HASH_OF(intern->array);
+void repeated_field_push_native(RepeatedField *intern, void *value) {
+ HashTable *ht = PHP_PROTO_HASH_OF(intern->array);
int size = native_slot_size(intern->type);
- zend_hash_next_index_insert(ht, (void **)value, size, NULL);
+ if (intern->type == UPB_TYPE_MESSAGE) {
+ php_proto_zend_hash_next_index_insert_zval(ht, value);
+ } else {
+ php_proto_zend_hash_next_index_insert_mem(ht, (void **)value, size, NULL);
+ }
}
-void repeated_field_create_with_type(zend_class_entry *ce,
- const upb_fielddef *field,
- zval **repeated_field TSRMLS_DC) {
- MAKE_STD_ZVAL(*repeated_field);
- Z_TYPE_PP(repeated_field) = IS_OBJECT;
- Z_OBJVAL_PP(repeated_field) =
- repeated_field_type->create_object(repeated_field_type TSRMLS_CC);
+void repeated_field_create_with_field(
+ zend_class_entry *ce, const upb_fielddef *field,
+ CACHED_VALUE *repeated_field PHP_PROTO_TSRMLS_DC) {
+ upb_fieldtype_t type = upb_fielddef_type(field);
+ const zend_class_entry *msg_ce = field_type_class(field PHP_PROTO_TSRMLS_CC);
+ repeated_field_create_with_type(ce, type, msg_ce,
+ repeated_field PHP_PROTO_TSRMLS_CC);
+}
+
+void repeated_field_create_with_type(
+ zend_class_entry *ce, upb_fieldtype_t type, const zend_class_entry *msg_ce,
+ CACHED_VALUE *repeated_field PHP_PROTO_TSRMLS_DC) {
+ CREATE_OBJ_ON_ALLOCATED_ZVAL_PTR(CACHED_PTR_TO_ZVAL_PTR(repeated_field),
+ repeated_field_type);
RepeatedField *intern =
- zend_object_store_get_object(*repeated_field TSRMLS_CC);
- intern->type = upb_fielddef_type(field);
- if (intern->type == UPB_TYPE_MESSAGE) {
- const upb_msgdef *msg = upb_fielddef_msgsubdef(field);
- zval *desc_php = get_def_obj(msg);
- Descriptor *desc = zend_object_store_get_object(desc_php TSRMLS_CC);
- intern->msg_ce = desc->klass;
- }
+ UNBOX(RepeatedField, CACHED_TO_ZVAL_PTR(*repeated_field));
+ intern->type = type;
+ intern->msg_ce = msg_ce;
+#if PHP_MAJOR_VERSION < 7
MAKE_STD_ZVAL(intern->array);
repeated_field_array_init(intern->array, intern->type, 0 ZEND_FILE_LINE_CC);
+#else
+ repeated_field_array_init(&intern->array, intern->type, 0 ZEND_FILE_LINE_CC);
+#endif
// TODO(teboring): Link class entry for message and enum
}
@@ -266,12 +307,16 @@ PHP_METHOD(RepeatedField, __construct) {
return;
}
- RepeatedField *intern = zend_object_store_get_object(getThis() TSRMLS_CC);
+ RepeatedField *intern = UNBOX(RepeatedField, getThis());
intern->type = to_fieldtype(type);
intern->msg_ce = klass;
+#if PHP_MAJOR_VERSION < 7
MAKE_STD_ZVAL(intern->array);
repeated_field_array_init(intern->array, intern->type, 0 ZEND_FILE_LINE_CC);
+#else
+ repeated_field_array_init(&intern->array, intern->type, 0 ZEND_FILE_LINE_CC);
+#endif
if (intern->type == UPB_TYPE_MESSAGE && klass == NULL) {
zend_error(E_USER_ERROR, "Message type must have concrete class.");
@@ -308,10 +353,10 @@ PHP_METHOD(RepeatedField, offsetExists) {
return;
}
- RepeatedField *intern = zend_object_store_get_object(getThis() TSRMLS_CC);
+ RepeatedField *intern = UNBOX(RepeatedField, getThis());
RETURN_BOOL(index >= 0 &&
- index < zend_hash_num_elements(HASH_OF(intern->array)));
+ index < zend_hash_num_elements(PHP_PROTO_HASH_OF(intern->array)));
}
/**
@@ -331,15 +376,24 @@ PHP_METHOD(RepeatedField, offsetGet) {
return;
}
- RepeatedField *intern = zend_object_store_get_object(getThis() TSRMLS_CC);
- HashTable *table = HASH_OF(intern->array);
+ RepeatedField *intern = UNBOX(RepeatedField, getThis());
+ HashTable *table = PHP_PROTO_HASH_OF(intern->array);
- if (zend_hash_index_find(table, index, (void **)&memory) == FAILURE) {
- zend_error(E_USER_ERROR, "Element at %ld doesn't exist.\n", index);
- return;
+ if (intern->type == UPB_TYPE_MESSAGE) {
+ if (php_proto_zend_hash_index_find_zval(table, index, (void **)&memory) ==
+ FAILURE) {
+ zend_error(E_USER_ERROR, "Element at %ld doesn't exist.\n", index);
+ return;
+ }
+ } else {
+ if (php_proto_zend_hash_index_find_mem(table, index, (void **)&memory) ==
+ FAILURE) {
+ zend_error(E_USER_ERROR, "Element at %ld doesn't exist.\n", index);
+ return;
+ }
}
-
- native_slot_get(intern->type, memory, return_value_ptr TSRMLS_CC);
+ native_slot_get_by_array(intern->type, memory,
+ ZVAL_PTR_TO_CACHED_PTR(return_value) TSRMLS_CC);
}
/**
@@ -374,16 +428,16 @@ PHP_METHOD(RepeatedField, offsetUnset) {
return;
}
- RepeatedField *intern = zend_object_store_get_object(getThis() TSRMLS_CC);
+ RepeatedField *intern = UNBOX(RepeatedField, getThis());
// Only the element at the end of the array can be removed.
if (index == -1 ||
- index != (zend_hash_num_elements(HASH_OF(intern->array)) - 1)) {
+ index != (zend_hash_num_elements(PHP_PROTO_HASH_OF(intern->array)) - 1)) {
zend_error(E_USER_ERROR, "Cannot remove element at %ld.\n", index);
return;
}
- zend_hash_index_del(HASH_OF(intern->array), index);
+ zend_hash_index_del(PHP_PROTO_HASH_OF(intern->array), index);
}
/**
@@ -392,13 +446,13 @@ PHP_METHOD(RepeatedField, offsetUnset) {
* @return long The number of stored elements.
*/
PHP_METHOD(RepeatedField, count) {
- RepeatedField *intern = zend_object_store_get_object(getThis() TSRMLS_CC);
+ RepeatedField *intern = UNBOX(RepeatedField, getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
- RETURN_LONG(zend_hash_num_elements(HASH_OF(intern->array)));
+ RETURN_LONG(zend_hash_num_elements(PHP_PROTO_HASH_OF(intern->array)));
}
/**
@@ -407,105 +461,85 @@ PHP_METHOD(RepeatedField, count) {
* @return object Beginning iterator.
*/
PHP_METHOD(RepeatedField, getIterator) {
- zval *iter_php = NULL;
- MAKE_STD_ZVAL(iter_php);
- Z_TYPE_P(iter_php) = IS_OBJECT;
- Z_OBJVAL_P(iter_php) = repeated_field_iter_type->create_object(
- repeated_field_iter_type TSRMLS_CC);
-
- RepeatedField *intern = zend_object_store_get_object(getThis() TSRMLS_CC);
- RepeatedFieldIter *iter = zend_object_store_get_object(iter_php TSRMLS_CC);
+ CREATE_OBJ_ON_ALLOCATED_ZVAL_PTR(return_value,
+ repeated_field_iter_type);
+
+ RepeatedField *intern = UNBOX(RepeatedField, getThis());
+ RepeatedFieldIter *iter = UNBOX(RepeatedFieldIter, return_value);
iter->repeated_field = intern;
iter->position = 0;
-
- RETURN_ZVAL(iter_php, 1, 1);
}
// -----------------------------------------------------------------------------
// RepeatedFieldIter creation/desctruction
// -----------------------------------------------------------------------------
-void repeated_field_iter_init(TSRMLS_D) {
- zend_class_entry class_type;
- const char* class_name = "Google\\Protobuf\\Internal\\RepeatedFieldIter";
- INIT_CLASS_ENTRY_EX(class_type, class_name, strlen(class_name),
- repeated_field_iter_methods);
-
- repeated_field_iter_type =
- zend_register_internal_class(&class_type TSRMLS_CC);
- repeated_field_iter_type->create_object = repeated_field_iter_create;
-
- zend_class_implements(repeated_field_iter_type TSRMLS_CC, 1,
- zend_ce_iterator);
-}
-
-static zend_object_value repeated_field_iter_create(
- zend_class_entry *ce TSRMLS_DC) {
- zend_object_value retval = {0};
- RepeatedFieldIter *intern;
-
- intern = emalloc(sizeof(RepeatedFieldIter));
- memset(intern, 0, sizeof(RepeatedFieldIter));
-
- zend_object_std_init(&intern->std, ce TSRMLS_CC);
- object_properties_init(&intern->std, ce);
+// Define object free method.
+PHP_PROTO_OBJECT_FREE_START(RepeatedFieldIter, repeated_field_iter)
+PHP_PROTO_OBJECT_FREE_END
- intern->repeated_field = NULL;
- intern->position = 0;
-
- retval.handle = zend_objects_store_put(
- intern, (zend_objects_store_dtor_t)zend_objects_destroy_object,
- (zend_objects_free_object_storage_t)repeated_field_iter_free,
- NULL TSRMLS_CC);
- retval.handlers = zend_get_std_object_handlers();
+PHP_PROTO_OBJECT_DTOR_START(RepeatedFieldIter, repeated_field_iter)
+PHP_PROTO_OBJECT_DTOR_END
- return retval;
-}
+// Define object create method.
+PHP_PROTO_OBJECT_CREATE_START(RepeatedFieldIter, repeated_field_iter)
+intern->repeated_field = NULL;
+intern->position = 0;
+PHP_PROTO_OBJECT_CREATE_END(RepeatedFieldIter, repeated_field_iter)
-static void repeated_field_iter_free(void *object TSRMLS_DC) {
- RepeatedFieldIter *intern = object;
- zend_object_std_dtor(&intern->std TSRMLS_CC);
- efree(object);
-}
+// Init class entry.
+PHP_PROTO_INIT_CLASS_START("Google\\Protobuf\\Internal\\RepeatedFieldIter",
+ RepeatedFieldIter, repeated_field_iter)
+zend_class_implements(repeated_field_iter_type TSRMLS_CC, 1, zend_ce_iterator);
+PHP_PROTO_INIT_CLASS_END
// -----------------------------------------------------------------------------
// PHP RepeatedFieldIter Methods
// -----------------------------------------------------------------------------
PHP_METHOD(RepeatedFieldIter, rewind) {
- RepeatedFieldIter *intern = zend_object_store_get_object(getThis() TSRMLS_CC);
+ RepeatedFieldIter *intern = UNBOX(RepeatedFieldIter, getThis());
intern->position = 0;
}
PHP_METHOD(RepeatedFieldIter, current) {
- RepeatedFieldIter *intern = zend_object_store_get_object(getThis() TSRMLS_CC);
+ RepeatedFieldIter *intern = UNBOX(RepeatedFieldIter, getThis());
RepeatedField *repeated_field = intern->repeated_field;
long index;
void *memory;
- HashTable *table = HASH_OF(repeated_field->array);
+ HashTable *table = PHP_PROTO_HASH_OF(repeated_field->array);
- if (zend_hash_index_find(table, intern->position, (void **)&memory) ==
- FAILURE) {
- zend_error(E_USER_ERROR, "Element at %ld doesn't exist.\n", index);
- return;
+ if (repeated_field->type == UPB_TYPE_MESSAGE) {
+ if (php_proto_zend_hash_index_find_zval(table, intern->position,
+ (void **)&memory) == FAILURE) {
+ zend_error(E_USER_ERROR, "Element at %d doesn't exist.\n", index);
+ return;
+ }
+ } else {
+ if (php_proto_zend_hash_index_find_mem(table, intern->position,
+ (void **)&memory) == FAILURE) {
+ zend_error(E_USER_ERROR, "Element at %d doesn't exist.\n", index);
+ return;
+ }
}
- native_slot_get(repeated_field->type, memory, return_value_ptr TSRMLS_CC);
+ native_slot_get_by_array(repeated_field->type, memory,
+ ZVAL_PTR_TO_CACHED_PTR(return_value) TSRMLS_CC);
}
PHP_METHOD(RepeatedFieldIter, key) {
- RepeatedFieldIter *intern = zend_object_store_get_object(getThis() TSRMLS_CC);
+ RepeatedFieldIter *intern = UNBOX(RepeatedFieldIter, getThis());
RETURN_LONG(intern->position);
}
PHP_METHOD(RepeatedFieldIter, next) {
- RepeatedFieldIter *intern = zend_object_store_get_object(getThis() TSRMLS_CC);
+ RepeatedFieldIter *intern = UNBOX(RepeatedFieldIter, getThis());
++intern->position;
}
PHP_METHOD(RepeatedFieldIter, valid) {
- RepeatedFieldIter *intern = zend_object_store_get_object(getThis() TSRMLS_CC);
- RETURN_BOOL(zend_hash_num_elements(HASH_OF(intern->repeated_field->array)) >
- intern->position);
+ RepeatedFieldIter *intern = UNBOX(RepeatedFieldIter, getThis());
+ RETURN_BOOL(zend_hash_num_elements(PHP_PROTO_HASH_OF(
+ intern->repeated_field->array)) > intern->position);
}
diff --git a/php/ext/google/protobuf/def.c b/php/ext/google/protobuf/def.c
index 6ea2cc93..13f7cdd6 100644
--- a/php/ext/google/protobuf/def.c
+++ b/php/ext/google/protobuf/def.c
@@ -31,21 +31,30 @@
#include "protobuf.h"
// Forward declare.
-static zend_object_value descriptor_create(zend_class_entry *ce TSRMLS_DC);
static void descriptor_init_c_instance(Descriptor* intern TSRMLS_DC);
static void descriptor_free_c(Descriptor* object TSRMLS_DC);
-static void descriptor_free(void* object TSRMLS_DC);
-static zend_object_value enum_descriptor_create(zend_class_entry *ce TSRMLS_DC);
+static void field_descriptor_init_c_instance(FieldDescriptor* intern TSRMLS_DC);
+static void field_descriptor_free_c(FieldDescriptor* object TSRMLS_DC);
+
static void enum_descriptor_init_c_instance(EnumDescriptor* intern TSRMLS_DC);
static void enum_descriptor_free_c(EnumDescriptor* object TSRMLS_DC);
-static void enum_descriptor_free(void* object TSRMLS_DC);
-static zend_object_value descriptor_pool_create(zend_class_entry *ce TSRMLS_DC);
+static void enum_value_descriptor_init_c_instance(
+ EnumValueDescriptor *intern TSRMLS_DC);
+static void enum_value_descriptor_free_c(EnumValueDescriptor *object TSRMLS_DC);
+
static void descriptor_pool_free_c(DescriptorPool* object TSRMLS_DC);
-static void descriptor_pool_free(void* object TSRMLS_DC);
static void descriptor_pool_init_c_instance(DescriptorPool* pool TSRMLS_DC);
+static void internal_descriptor_pool_free_c(
+ InternalDescriptorPool *object TSRMLS_DC);
+static void internal_descriptor_pool_init_c_instance(
+ InternalDescriptorPool *pool TSRMLS_DC);
+
+static void oneof_descriptor_free_c(Oneof* object TSRMLS_DC);
+static void oneof_descriptor_init_c_instance(Oneof* pool TSRMLS_DC);
+
// -----------------------------------------------------------------------------
// Common Utilities
// -----------------------------------------------------------------------------
@@ -103,42 +112,6 @@ static void append_map_entry_name(char *result, const char *field_name,
check_upb_status(&status, msg); \
} while (0)
-// Define PHP class
-#define DEFINE_PROTOBUF_INIT_CLASS(name_lower, string_name) \
- void name_lower##_init(TSRMLS_D) { \
- zend_class_entry class_type; \
- INIT_CLASS_ENTRY(class_type, string_name, name_lower##_methods); \
- name_lower##_type = zend_register_internal_class(&class_type TSRMLS_CC); \
- name_lower##_type->create_object = name_lower##_create; \
- }
-
-#define DEFINE_PROTOBUF_CREATE(name, name_lower) \
- static zend_object_value name_lower##_create( \
- zend_class_entry* ce TSRMLS_DC) { \
- zend_object_value return_value; \
- name* intern = (name*)emalloc(sizeof(name)); \
- memset(intern, 0, sizeof(name)); \
- name_lower##_init_c_instance(intern TSRMLS_CC); \
- return_value.handle = zend_objects_store_put( \
- intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, \
- name_lower##_free, NULL TSRMLS_CC); \
- return_value.handlers = zend_get_std_object_handlers(); \
- return return_value; \
- }
-
-#define DEFINE_PROTOBUF_FREE(name, name_lower) \
- static void name_lower##_free(void* object TSRMLS_DC) { \
- name* intern = (name*)object; \
- name_lower##_free_c(intern TSRMLS_CC); \
- efree(object); \
- }
-
-#define DEFINE_CLASS(name, name_lower, string_name) \
- zend_class_entry* name_lower##_type; \
- DEFINE_PROTOBUF_FREE(name, name_lower) \
- DEFINE_PROTOBUF_CREATE(name, name_lower) \
- DEFINE_PROTOBUF_INIT_CLASS(name_lower, string_name)
-
// -----------------------------------------------------------------------------
// GPBType
// -----------------------------------------------------------------------------
@@ -177,51 +150,529 @@ void gpb_type_init(TSRMLS_D) {
}
// -----------------------------------------------------------------------------
+// Descriptor
+// -----------------------------------------------------------------------------
+
+static zend_function_entry descriptor_methods[] = {
+ PHP_ME(Descriptor, getClass, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Descriptor, getFullName, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Descriptor, getField, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Descriptor, getFieldCount, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Descriptor, getOneofDecl, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Descriptor, getOneofDeclCount, NULL, ZEND_ACC_PUBLIC)
+ ZEND_FE_END
+};
+
+DEFINE_CLASS(Descriptor, descriptor, "Google\\Protobuf\\Descriptor");
+
+static void descriptor_free_c(Descriptor *self TSRMLS_DC) {
+ if (self->layout) {
+ free_layout(self->layout);
+ }
+ if (self->fill_handlers) {
+ upb_handlers_unref(self->fill_handlers, &self->fill_handlers);
+ }
+ if (self->fill_method) {
+ upb_pbdecodermethod_unref(self->fill_method, &self->fill_method);
+ }
+ if (self->json_fill_method) {
+ upb_json_parsermethod_unref(self->json_fill_method,
+ &self->json_fill_method);
+ }
+ if (self->pb_serialize_handlers) {
+ upb_handlers_unref(self->pb_serialize_handlers,
+ &self->pb_serialize_handlers);
+ }
+ if (self->json_serialize_handlers) {
+ upb_handlers_unref(self->json_serialize_handlers,
+ &self->json_serialize_handlers);
+ }
+ if (self->json_serialize_handlers_preserve) {
+ upb_handlers_unref(self->json_serialize_handlers_preserve,
+ &self->json_serialize_handlers_preserve);
+ }
+}
+
+static void descriptor_init_c_instance(Descriptor *desc TSRMLS_DC) {
+ desc->msgdef = NULL;
+ desc->layout = NULL;
+ desc->klass = NULL;
+ desc->fill_handlers = NULL;
+ desc->fill_method = NULL;
+ desc->json_fill_method = NULL;
+ desc->pb_serialize_handlers = NULL;
+ desc->json_serialize_handlers = NULL;
+ desc->json_serialize_handlers_preserve = NULL;
+}
+
+PHP_METHOD(Descriptor, getClass) {
+ Descriptor *intern = UNBOX(Descriptor, getThis());
+#if PHP_MAJOR_VERSION < 7
+ const char* classname = intern->klass->name;
+#else
+ const char* classname = ZSTR_VAL(intern->klass->name);
+#endif
+ PHP_PROTO_RETVAL_STRINGL(classname, strlen(classname), 1);
+}
+
+PHP_METHOD(Descriptor, getFullName) {
+ Descriptor *intern = UNBOX(Descriptor, getThis());
+ const char* fullname = upb_msgdef_fullname(intern->msgdef);
+ PHP_PROTO_RETVAL_STRINGL(fullname, strlen(fullname), 1);
+}
+
+PHP_METHOD(Descriptor, getField) {
+ long index;
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &index) ==
+ FAILURE) {
+ zend_error(E_USER_ERROR, "Expect integer for index.\n");
+ return;
+ }
+
+ Descriptor *intern = UNBOX(Descriptor, getThis());
+ int field_num = upb_msgdef_numfields(intern->msgdef);
+ if (index < 0 || index >= field_num) {
+ zend_error(E_USER_ERROR, "Cannot get element at %ld.\n", index);
+ return;
+ }
+
+ upb_msg_field_iter iter;
+ int i;
+ for(upb_msg_field_begin(&iter, intern->msgdef), i = 0;
+ !upb_msg_field_done(&iter) && i < index;
+ upb_msg_field_next(&iter), i++);
+ const upb_fielddef *field = upb_msg_iter_field(&iter);
+
+ PHP_PROTO_HASHTABLE_VALUE field_hashtable_value = get_def_obj(field);
+ if (field_hashtable_value == NULL) {
+#if PHP_MAJOR_VERSION < 7
+ MAKE_STD_ZVAL(field_hashtable_value);
+ ZVAL_OBJ(field_hashtable_value, field_descriptor_type->create_object(
+ field_descriptor_type TSRMLS_CC));
+#else
+ field_hashtable_value =
+ field_descriptor_type->create_object(field_descriptor_type TSRMLS_CC);
+#endif
+ FieldDescriptor *field_php =
+ UNBOX_HASHTABLE_VALUE(FieldDescriptor, field_hashtable_value);
+ field_php->fielddef = field;
+ add_def_obj(field, field_hashtable_value);
+ }
+
+#if PHP_MAJOR_VERSION < 7
+ RETURN_ZVAL(field_hashtable_value, 1, 0);
+#else
+ ++GC_REFCOUNT(field_hashtable_value);
+ RETURN_OBJ(field_hashtable_value);
+#endif
+}
+
+PHP_METHOD(Descriptor, getFieldCount) {
+ Descriptor *intern = UNBOX(Descriptor, getThis());
+ RETURN_LONG(upb_msgdef_numfields(intern->msgdef));
+}
+
+PHP_METHOD(Descriptor, getOneofDecl) {
+ long index;
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &index) ==
+ FAILURE) {
+ zend_error(E_USER_ERROR, "Expect integer for index.\n");
+ return;
+ }
+
+ Descriptor *intern = UNBOX(Descriptor, getThis());
+ int field_num = upb_msgdef_numoneofs(intern->msgdef);
+ if (index < 0 || index >= field_num) {
+ zend_error(E_USER_ERROR, "Cannot get element at %ld.\n", index);
+ return;
+ }
+
+ upb_msg_oneof_iter iter;
+ int i;
+ for(upb_msg_oneof_begin(&iter, intern->msgdef), i = 0;
+ !upb_msg_oneof_done(&iter) && i < index;
+ upb_msg_oneof_next(&iter), i++);
+ upb_oneofdef *oneof = upb_msg_iter_oneof(&iter);
+
+ ZVAL_OBJ(return_value, oneof_descriptor_type->create_object(
+ oneof_descriptor_type TSRMLS_CC));
+ Oneof *oneof_php = UNBOX(Oneof, return_value);
+ oneof_php->oneofdef = oneof;
+}
+
+PHP_METHOD(Descriptor, getOneofDeclCount) {
+ Descriptor *intern = UNBOX(Descriptor, getThis());
+ RETURN_LONG(upb_msgdef_numoneofs(intern->msgdef));
+}
+
+// -----------------------------------------------------------------------------
+// EnumDescriptor
+// -----------------------------------------------------------------------------
+
+static zend_function_entry enum_descriptor_methods[] = {
+ PHP_ME(EnumDescriptor, getValue, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(EnumDescriptor, getValueCount, NULL, ZEND_ACC_PUBLIC)
+ ZEND_FE_END
+};
+
+DEFINE_CLASS(EnumDescriptor, enum_descriptor,
+ "Google\\Protobuf\\EnumDescriptor");
+
+static void enum_descriptor_free_c(EnumDescriptor *self TSRMLS_DC) {
+}
+
+static void enum_descriptor_init_c_instance(EnumDescriptor *self TSRMLS_DC) {
+ self->enumdef = NULL;
+ self->klass = NULL;
+}
+
+PHP_METHOD(EnumDescriptor, getValue) {
+ long index;
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &index) ==
+ FAILURE) {
+ zend_error(E_USER_ERROR, "Expect integer for index.\n");
+ return;
+ }
+
+ EnumDescriptor *intern = UNBOX(EnumDescriptor, getThis());
+ int field_num = upb_enumdef_numvals(intern->enumdef);
+ if (index < 0 || index >= field_num) {
+ zend_error(E_USER_ERROR, "Cannot get element at %ld.\n", index);
+ return;
+ }
+
+ upb_enum_iter iter;
+ int i;
+ for(upb_enum_begin(&iter, intern->enumdef), i = 0;
+ !upb_enum_done(&iter) && i < index;
+ upb_enum_next(&iter), i++);
+
+ ZVAL_OBJ(return_value, enum_value_descriptor_type->create_object(
+ enum_value_descriptor_type TSRMLS_CC));
+ EnumValueDescriptor *enum_value_php =
+ UNBOX(EnumValueDescriptor, return_value);
+ enum_value_php->name = upb_enum_iter_name(&iter);
+ enum_value_php->number = upb_enum_iter_number(&iter);
+}
+
+PHP_METHOD(EnumDescriptor, getValueCount) {
+ EnumDescriptor *intern = UNBOX(EnumDescriptor, getThis());
+ RETURN_LONG(upb_enumdef_numvals(intern->enumdef));
+}
+
+// -----------------------------------------------------------------------------
+// EnumValueDescriptor
+// -----------------------------------------------------------------------------
+
+static zend_function_entry enum_value_descriptor_methods[] = {
+ PHP_ME(EnumValueDescriptor, getName, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(EnumValueDescriptor, getNumber, NULL, ZEND_ACC_PUBLIC)
+ ZEND_FE_END
+};
+
+DEFINE_CLASS(EnumValueDescriptor, enum_value_descriptor,
+ "Google\\Protobuf\\EnumValueDescriptor");
+
+static void enum_value_descriptor_free_c(EnumValueDescriptor *self TSRMLS_DC) {
+}
+
+static void enum_value_descriptor_init_c_instance(EnumValueDescriptor *self TSRMLS_DC) {
+ self->name = NULL;
+ self->number = 0;
+}
+
+PHP_METHOD(EnumValueDescriptor, getName) {
+ EnumValueDescriptor *intern = UNBOX(EnumValueDescriptor, getThis());
+ PHP_PROTO_RETVAL_STRINGL(intern->name, strlen(intern->name), 1);
+}
+
+PHP_METHOD(EnumValueDescriptor, getNumber) {
+ EnumValueDescriptor *intern = UNBOX(EnumValueDescriptor, getThis());
+ RETURN_LONG(intern->number);
+}
+
+// -----------------------------------------------------------------------------
+// FieldDescriptor
+// -----------------------------------------------------------------------------
+
+static zend_function_entry field_descriptor_methods[] = {
+ PHP_ME(FieldDescriptor, getName, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(FieldDescriptor, getNumber, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(FieldDescriptor, getLabel, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(FieldDescriptor, getType, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(FieldDescriptor, isMap, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(FieldDescriptor, getEnumType, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(FieldDescriptor, getMessageType, NULL, ZEND_ACC_PUBLIC)
+ ZEND_FE_END
+};
+
+DEFINE_CLASS(FieldDescriptor, field_descriptor,
+ "Google\\Protobuf\\FieldDescriptor");
+
+static void field_descriptor_free_c(FieldDescriptor *self TSRMLS_DC) {
+}
+
+static void field_descriptor_init_c_instance(FieldDescriptor *self TSRMLS_DC) {
+ self->fielddef = NULL;
+}
+
+upb_fieldtype_t to_fieldtype(upb_descriptortype_t type) {
+ switch (type) {
+#define CASE(descriptor_type, type) \
+ case UPB_DESCRIPTOR_TYPE_##descriptor_type: \
+ return UPB_TYPE_##type;
+
+ CASE(FLOAT, FLOAT);
+ CASE(DOUBLE, DOUBLE);
+ CASE(BOOL, BOOL);
+ CASE(STRING, STRING);
+ CASE(BYTES, BYTES);
+ CASE(MESSAGE, MESSAGE);
+ CASE(GROUP, MESSAGE);
+ CASE(ENUM, ENUM);
+ CASE(INT32, INT32);
+ CASE(INT64, INT64);
+ CASE(UINT32, UINT32);
+ CASE(UINT64, UINT64);
+ CASE(SINT32, INT32);
+ CASE(SINT64, INT64);
+ CASE(FIXED32, UINT32);
+ CASE(FIXED64, UINT64);
+ CASE(SFIXED32, INT32);
+ CASE(SFIXED64, INT64);
+
+#undef CONVERT
+
+ }
+
+ zend_error(E_ERROR, "Unknown field type.");
+ return 0;
+}
+
+PHP_METHOD(FieldDescriptor, getName) {
+ FieldDescriptor *intern = UNBOX(FieldDescriptor, getThis());
+ const char* name = upb_fielddef_name(intern->fielddef);
+ PHP_PROTO_RETVAL_STRINGL(name, strlen(name), 1);
+}
+
+PHP_METHOD(FieldDescriptor, getNumber) {
+ FieldDescriptor *intern = UNBOX(FieldDescriptor, getThis());
+ RETURN_LONG(upb_fielddef_number(intern->fielddef));
+}
+
+PHP_METHOD(FieldDescriptor, getLabel) {
+ FieldDescriptor *intern = UNBOX(FieldDescriptor, getThis());
+ RETURN_LONG(upb_fielddef_label(intern->fielddef));
+}
+
+PHP_METHOD(FieldDescriptor, getType) {
+ FieldDescriptor *intern = UNBOX(FieldDescriptor, getThis());
+ RETURN_LONG(upb_fielddef_descriptortype(intern->fielddef));
+}
+
+PHP_METHOD(FieldDescriptor, isMap) {
+ FieldDescriptor *intern = UNBOX(FieldDescriptor, getThis());
+ RETURN_BOOL(upb_fielddef_ismap(intern->fielddef));
+}
+
+PHP_METHOD(FieldDescriptor, getEnumType) {
+ FieldDescriptor *intern = UNBOX(FieldDescriptor, getThis());
+ const upb_enumdef *enumdef = upb_fielddef_enumsubdef(intern->fielddef);
+ if (enumdef == NULL) {
+ char error_msg[100];
+ sprintf(error_msg, "Cannot get enum type for non-enum field '%s'",
+ upb_fielddef_name(intern->fielddef));
+ zend_throw_exception(NULL, error_msg, 0 TSRMLS_CC);
+ return;
+ }
+ PHP_PROTO_HASHTABLE_VALUE desc = get_def_obj(enumdef);
+
+#if PHP_MAJOR_VERSION < 7
+ RETURN_ZVAL(desc, 1, 0);
+#else
+ ++GC_REFCOUNT(desc);
+ RETURN_OBJ(desc);
+#endif
+}
+
+PHP_METHOD(FieldDescriptor, getMessageType) {
+ FieldDescriptor *intern = UNBOX(FieldDescriptor, getThis());
+ const upb_msgdef *msgdef = upb_fielddef_msgsubdef(intern->fielddef);
+ if (msgdef == NULL) {
+ char error_msg[100];
+ sprintf(error_msg, "Cannot get message type for non-message field '%s'",
+ upb_fielddef_name(intern->fielddef));
+ zend_throw_exception(NULL, error_msg, 0 TSRMLS_CC);
+ return;
+ }
+ PHP_PROTO_HASHTABLE_VALUE desc = get_def_obj(msgdef);
+
+#if PHP_MAJOR_VERSION < 7
+ RETURN_ZVAL(desc, 1, 0);
+#else
+ ++GC_REFCOUNT(desc);
+ RETURN_OBJ(desc);
+#endif
+}
+
+// -----------------------------------------------------------------------------
+// Oneof
+// -----------------------------------------------------------------------------
+
+static zend_function_entry oneof_descriptor_methods[] = {
+ PHP_ME(Oneof, getName, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Oneof, getField, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Oneof, getFieldCount, NULL, ZEND_ACC_PUBLIC)
+ ZEND_FE_END
+};
+
+DEFINE_CLASS(Oneof, oneof_descriptor,
+ "Google\\Protobuf\\OneofDescriptor");
+
+static void oneof_descriptor_free_c(Oneof *self TSRMLS_DC) {
+}
+
+static void oneof_descriptor_init_c_instance(Oneof *self TSRMLS_DC) {
+ self->oneofdef = NULL;
+}
+
+PHP_METHOD(Oneof, getName) {
+ Oneof *intern = UNBOX(Oneof, getThis());
+ const char *name = upb_oneofdef_name(intern->oneofdef);
+ PHP_PROTO_RETVAL_STRINGL(name, strlen(name), 1);
+}
+
+PHP_METHOD(Oneof, getField) {
+ long index;
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &index) ==
+ FAILURE) {
+ zend_error(E_USER_ERROR, "Expect integer for index.\n");
+ return;
+ }
+
+ Oneof *intern = UNBOX(Oneof, getThis());
+ int field_num = upb_oneofdef_numfields(intern->oneofdef);
+ if (index < 0 || index >= field_num) {
+ zend_error(E_USER_ERROR, "Cannot get element at %ld.\n", index);
+ return;
+ }
+
+ upb_oneof_iter iter;
+ int i;
+ for(upb_oneof_begin(&iter, intern->oneofdef), i = 0;
+ !upb_oneof_done(&iter) && i < index;
+ upb_oneof_next(&iter), i++);
+ const upb_fielddef *field = upb_oneof_iter_field(&iter);
+
+ PHP_PROTO_HASHTABLE_VALUE field_hashtable_value = get_def_obj(field);
+ if (field_hashtable_value == NULL) {
+#if PHP_MAJOR_VERSION < 7
+ MAKE_STD_ZVAL(field_hashtable_value);
+ ZVAL_OBJ(field_hashtable_value, field_descriptor_type->create_object(
+ field_descriptor_type TSRMLS_CC));
+#else
+ field_hashtable_value =
+ field_descriptor_type->create_object(field_descriptor_type TSRMLS_CC);
+#endif
+ FieldDescriptor *field_php =
+ UNBOX_HASHTABLE_VALUE(FieldDescriptor, field_hashtable_value);
+ field_php->fielddef = field;
+ add_def_obj(field, field_hashtable_value);
+ }
+
+#if PHP_MAJOR_VERSION < 7
+ RETURN_ZVAL(field_hashtable_value, 1, 0);
+#else
+ ++GC_REFCOUNT(field_hashtable_value);
+ RETURN_OBJ(field_hashtable_value);
+#endif
+}
+
+PHP_METHOD(Oneof, getFieldCount) {
+ Oneof *intern = UNBOX(Oneof, getThis());
+ RETURN_LONG(upb_oneofdef_numfields(intern->oneofdef));
+}
+
+// -----------------------------------------------------------------------------
// DescriptorPool
// -----------------------------------------------------------------------------
static zend_function_entry descriptor_pool_methods[] = {
PHP_ME(DescriptorPool, getGeneratedPool, NULL,
ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
- PHP_ME(DescriptorPool, internalAddGeneratedFile, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(DescriptorPool, getDescriptorByClassName, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(DescriptorPool, getEnumDescriptorByClassName, NULL, ZEND_ACC_PUBLIC)
+ ZEND_FE_END
+};
+
+static zend_function_entry internal_descriptor_pool_methods[] = {
+ PHP_ME(InternalDescriptorPool, getGeneratedPool, NULL,
+ ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
+ PHP_ME(InternalDescriptorPool, internalAddGeneratedFile, NULL, ZEND_ACC_PUBLIC)
ZEND_FE_END
};
DEFINE_CLASS(DescriptorPool, descriptor_pool,
+ "Google\\Protobuf\\DescriptorPool");
+DEFINE_CLASS(InternalDescriptorPool, internal_descriptor_pool,
"Google\\Protobuf\\Internal\\DescriptorPool");
-zval* generated_pool_php; // wrapper of generated pool
-DescriptorPool *generated_pool; // The actual generated pool
-
-static void init_generated_pool_once(TSRMLS_D) {
- if (generated_pool_php == NULL) {
+// wrapper of generated pool
+#if PHP_MAJOR_VERSION < 7
+zval* generated_pool_php;
+zval* internal_generated_pool_php;
+#else
+zend_object *generated_pool_php;
+zend_object *internal_generated_pool_php;
+#endif
+InternalDescriptorPool *generated_pool; // The actual generated pool
+
+void init_generated_pool_once(TSRMLS_D) {
+ if (generated_pool == NULL) {
+#if PHP_MAJOR_VERSION < 7
MAKE_STD_ZVAL(generated_pool_php);
- Z_TYPE_P(generated_pool_php) = IS_OBJECT;
- generated_pool = ALLOC(DescriptorPool);
- descriptor_pool_init_c_instance(generated_pool TSRMLS_CC);
- Z_OBJ_HANDLE_P(generated_pool_php) = zend_objects_store_put(
- generated_pool, NULL,
- (zend_objects_free_object_storage_t)descriptor_pool_free,
- NULL TSRMLS_CC);
- Z_OBJ_HT_P(generated_pool_php) = zend_get_std_object_handlers();
+ MAKE_STD_ZVAL(internal_generated_pool_php);
+ ZVAL_OBJ(internal_generated_pool_php,
+ internal_descriptor_pool_type->create_object(
+ internal_descriptor_pool_type TSRMLS_CC));
+ generated_pool = UNBOX(InternalDescriptorPool, internal_generated_pool_php);
+ ZVAL_OBJ(generated_pool_php, descriptor_pool_type->create_object(
+ descriptor_pool_type TSRMLS_CC));
+#else
+ internal_generated_pool_php = internal_descriptor_pool_type->create_object(
+ internal_descriptor_pool_type TSRMLS_CC);
+ generated_pool = (InternalDescriptorPool *)((char *)internal_generated_pool_php -
+ XtOffsetOf(InternalDescriptorPool, std));
+ generated_pool_php =
+ descriptor_pool_type->create_object(descriptor_pool_type TSRMLS_CC);
+#endif
}
}
-static void descriptor_pool_init_c_instance(DescriptorPool *pool TSRMLS_DC) {
- zend_object_std_init(&pool->std, descriptor_pool_type TSRMLS_CC);
- pool->symtab = upb_symtab_new(&pool->symtab);
+static void internal_descriptor_pool_init_c_instance(
+ InternalDescriptorPool *pool TSRMLS_DC) {
+ pool->symtab = upb_symtab_new();
ALLOC_HASHTABLE(pool->pending_list);
zend_hash_init(pool->pending_list, 1, NULL, ZVAL_PTR_DTOR, 0);
}
-static void descriptor_pool_free_c(DescriptorPool *pool TSRMLS_DC) {
- upb_symtab_unref(pool->symtab, &pool->symtab);
+static void internal_descriptor_pool_free_c(
+ InternalDescriptorPool *pool TSRMLS_DC) {
+ upb_symtab_free(pool->symtab);
zend_hash_destroy(pool->pending_list);
FREE_HASHTABLE(pool->pending_list);
}
+static void descriptor_pool_init_c_instance(DescriptorPool *pool TSRMLS_DC) {
+ assert(generated_pool != NULL);
+ pool->intern = generated_pool;
+}
+
+static void descriptor_pool_free_c(DescriptorPool *pool TSRMLS_DC) {
+}
+
static void validate_enumdef(const upb_enumdef *enumdef) {
// Verify that an entry exists with integer value 0. (This is the default
// value.)
@@ -247,60 +698,130 @@ static void validate_msgdef(const upb_msgdef* msgdef) {
PHP_METHOD(DescriptorPool, getGeneratedPool) {
init_generated_pool_once(TSRMLS_C);
+#if PHP_MAJOR_VERSION < 7
RETURN_ZVAL(generated_pool_php, 1, 0);
+#else
+ ++GC_REFCOUNT(generated_pool_php);
+ RETURN_OBJ(generated_pool_php);
+#endif
}
-static void convert_to_class_name_inplace(char *class_name,
- const char* fullname,
- const char* package_name) {
- size_t i;
- bool first_char = false;
+PHP_METHOD(InternalDescriptorPool, getGeneratedPool) {
+ init_generated_pool_once(TSRMLS_C);
+#if PHP_MAJOR_VERSION < 7
+ RETURN_ZVAL(internal_generated_pool_php, 1, 0);
+#else
+ ++GC_REFCOUNT(internal_generated_pool_php);
+ RETURN_OBJ(internal_generated_pool_php);
+#endif
+}
+
+static void classname_no_prefix(const char *fullname, const char *package_name,
+ char *class_name) {
+ size_t i = 0, j;
+ bool first_char = true, is_reserved = false;
size_t pkg_name_len = package_name == NULL ? 0 : strlen(package_name);
+ size_t message_name_start = package_name == NULL ? 0 : pkg_name_len + 1;
+ size_t message_len = (strlen(fullname) - message_name_start);
- // In php, class name cannot be Empty.
- if (strcmp("google.protobuf.Empty", fullname) == 0) {
- fullname = "google.protobuf.GPBEmpty";
+ // Submessage is concatenated with its containing messages by '_'.
+ for (j = message_name_start; j < message_name_start + message_len; j++) {
+ if (fullname[j] == '.') {
+ class_name[i++] = '_';
+ } else {
+ class_name[i++] = fullname[j];
+ }
}
+}
- if (pkg_name_len == 0) {
- strcpy(class_name, fullname);
- } else {
- class_name[0] = '.';
- strcpy(&class_name[1], fullname);
- for (i = 0; i <= pkg_name_len + 1; i++) {
- // PHP package uses camel case.
- if (!first_char && class_name[i] != '.') {
- first_char = true;
- class_name[i] += 'A' - 'a';
+static const char *classname_prefix(const char *classname,
+ const char *prefix_given,
+ const char *package_name) {
+ size_t i;
+ bool is_reserved = false;
+
+ if (prefix_given != NULL && strcmp(prefix_given, "") != 0) {
+ return prefix_given;
+ }
+
+ char* lower = ALLOC_N(char, strlen(classname) + 1);
+ i = 0;
+ while(classname[i]) {
+ lower[i] = (char)tolower(classname[i]);
+ i++;
+ }
+ lower[i] = 0;
+
+ is_reserved = is_reserved_name(lower);
+ FREE(lower);
+
+ if (is_reserved) {
+ if (package_name != NULL && strcmp("google.protobuf", package_name) == 0) {
+ return "GPB";
+ } else {
+ return "PB";
+ }
+ }
+
+ return "";
+}
+
+static void convert_to_class_name_inplace(const char *package,
+ const char *namespace_given,
+ const char *prefix, char *classname) {
+ size_t prefix_len = prefix == NULL ? 0 : strlen(prefix);
+ size_t classname_len = strlen(classname);
+ int i = 0, j;
+ bool first_char = true;
+
+ size_t package_len = package == NULL ? 0 : strlen(package);
+ size_t namespace_given_len =
+ namespace_given == NULL ? 0 : strlen(namespace_given);
+ bool use_namespace_given = namespace_given != NULL;
+ size_t namespace_len =
+ use_namespace_given ? namespace_given_len : package_len;
+
+ int offset = namespace_len != 0 ? 2 : 0;
+
+ for (j = 0; j < classname_len; j++) {
+ classname[namespace_len + prefix_len + classname_len + offset - 1 - j] =
+ classname[classname_len - j - 1];
+ }
+
+ if (namespace_len != 0) {
+ classname[i++] = '\\';
+ for (j = 0; j < namespace_len; j++) {
+ if (use_namespace_given) {
+ classname[i++] = namespace_given[j];
+ continue;
}
// php packages are divided by '\'.
- if (class_name[i] == '.') {
+ if (package[j] == '.') {
+ classname[i++] = '\\';
+ first_char = true;
+ } else if (first_char) {
+ // PHP package uses camel case.
+ if (package[j] < 'A' || package[j] > 'Z') {
+ classname[i++] = package[j] + 'A' - 'a';
+ } else {
+ classname[i++] = package[j];
+ }
first_char = false;
- class_name[i] = '\\';
+ } else {
+ classname[i++] = package[j];
}
}
+ classname[i++] = '\\';
}
- // Submessage is concatenated with its containing messages by '_'.
- for (i = pkg_name_len; i < strlen(class_name); i++) {
- if (class_name[i] == '.') {
- class_name[i] = '_';
- }
- }
+ memcpy(classname + i, prefix, prefix_len);
}
-PHP_METHOD(DescriptorPool, internalAddGeneratedFile) {
- char *data = NULL;
- int data_len;
+void internal_add_generated_file(const char *data, PHP_PROTO_SIZE data_len,
+ InternalDescriptorPool *pool TSRMLS_DC) {
upb_filedef **files;
size_t i;
- if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &data, &data_len) ==
- FAILURE) {
- return;
- }
-
- DescriptorPool *pool = UNBOX(DescriptorPool, getThis());
CHECK_UPB(files = upb_loaddescriptor(data, data_len, &pool, &status),
"Parse binary descriptors to internal descriptors failed");
@@ -320,11 +841,7 @@ PHP_METHOD(DescriptorPool, internalAddGeneratedFile) {
switch (upb_def_type(def)) {
#define CASE_TYPE(def_type, def_type_lower, desc_type, desc_type_lower) \
case UPB_DEF_##def_type: { \
- desc_type *desc; \
- zval *desc_php; \
- CREATE(desc_type, desc, desc_type_lower##_init_c_instance); \
- BOX(desc_type, desc_php, desc, desc_type_lower##_free); \
- Z_DELREF_P(desc_php); \
+ CREATE_HASHTABLE_VALUE(desc, desc_php, desc_type, desc_type_lower##_type); \
const upb_##def_type_lower *def_type_lower = \
upb_downcast_##def_type_lower(def); \
desc->def_type_lower = def_type_lower; \
@@ -339,20 +856,33 @@ PHP_METHOD(DescriptorPool, internalAddGeneratedFile) {
* bytes allocated, one for '.', one for trailing 0, and 3 for 'GPB' if \
* given message is google.protobuf.Empty.*/ \
const char *fullname = upb_##def_type_lower##_fullname(def_type_lower); \
- char *klass_name = ecalloc(sizeof(char), 5 + strlen(fullname)); \
- convert_to_class_name_inplace(klass_name, fullname, \
- upb_filedef_package(files[0])); \
- zend_class_entry **pce; \
- if (zend_lookup_class(klass_name, strlen(klass_name), &pce TSRMLS_CC) == \
+ const char *php_namespace = upb_filedef_phpnamespace(files[0]); \
+ const char *prefix_given = upb_filedef_phpprefix(files[0]); \
+ size_t classname_len = strlen(fullname) + 5; \
+ if (prefix_given != NULL) { \
+ classname_len += strlen(prefix_given); \
+ } \
+ if (php_namespace != NULL) { \
+ classname_len += strlen(php_namespace); \
+ } \
+ char *classname = ecalloc(sizeof(char), classname_len); \
+ const char *package = upb_filedef_package(files[0]); \
+ classname_no_prefix(fullname, package, classname); \
+ const char *prefix = classname_prefix(classname, prefix_given, package); \
+ convert_to_class_name_inplace(package, php_namespace, prefix, classname); \
+ PHP_PROTO_CE_DECLARE pce; \
+ if (php_proto_zend_lookup_class(classname, strlen(classname), &pce) == \
FAILURE) { \
zend_error(E_ERROR, "Generated message class %s hasn't been defined", \
- klass_name); \
+ classname); \
return; \
} else { \
- desc->klass = *pce; \
+ desc->klass = PHP_PROTO_CE_UNREF(pce); \
} \
add_ce_obj(desc->klass, desc_php); \
- efree(klass_name); \
+ add_proto_obj(upb_##def_type_lower##_fullname(desc->def_type_lower), \
+ desc_php); \
+ efree(classname); \
break; \
}
@@ -369,7 +899,7 @@ PHP_METHOD(DescriptorPool, internalAddGeneratedFile) {
const upb_def *def = upb_filedef_def(files[0], i);
if (upb_def_type(def) == UPB_DEF_MSG) {
const upb_msgdef *msgdef = upb_downcast_msgdef(def);
- zval *desc_php = get_def_obj(msgdef);
+ PHP_PROTO_HASHTABLE_VALUE desc_php = get_def_obj(msgdef);
build_class_from_descriptor(desc_php TSRMLS_CC);
}
}
@@ -378,95 +908,91 @@ PHP_METHOD(DescriptorPool, internalAddGeneratedFile) {
upb_gfree(files);
}
-// -----------------------------------------------------------------------------
-// Descriptor
-// -----------------------------------------------------------------------------
+PHP_METHOD(InternalDescriptorPool, internalAddGeneratedFile) {
+ char *data = NULL;
+ PHP_PROTO_SIZE data_len;
+ upb_filedef **files;
+ size_t i;
-static zend_function_entry descriptor_methods[] = {
- ZEND_FE_END
-};
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &data, &data_len) ==
+ FAILURE) {
+ return;
+ }
-DEFINE_CLASS(Descriptor, descriptor, "Google\\Protobuf\\Internal\\Descriptor");
+ InternalDescriptorPool *pool = UNBOX(InternalDescriptorPool, getThis());
+ internal_add_generated_file(data, data_len, pool TSRMLS_CC);
+}
-static void descriptor_free_c(Descriptor *self TSRMLS_DC) {
- if (self->layout) {
- free_layout(self->layout);
- }
- if (self->fill_handlers) {
- upb_handlers_unref(self->fill_handlers, &self->fill_handlers);
- }
- if (self->fill_method) {
- upb_pbdecodermethod_unref(self->fill_method, &self->fill_method);
- }
- if (self->pb_serialize_handlers) {
- upb_handlers_unref(self->pb_serialize_handlers,
- &self->pb_serialize_handlers);
+PHP_METHOD(DescriptorPool, getDescriptorByClassName) {
+ DescriptorPool *public_pool = UNBOX(DescriptorPool, getThis());
+ InternalDescriptorPool *pool = public_pool->intern;
+
+ char *classname = NULL;
+ PHP_PROTO_SIZE classname_len;
+
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &classname,
+ &classname_len) == FAILURE) {
+ return;
}
-}
-static void descriptor_init_c_instance(Descriptor *desc TSRMLS_DC) {
- zend_object_std_init(&desc->std, descriptor_type TSRMLS_CC);
- desc->msgdef = NULL;
- desc->layout = NULL;
- desc->klass = NULL;
- desc->fill_handlers = NULL;
- desc->fill_method = NULL;
- desc->pb_serialize_handlers = NULL;
-}
+ PHP_PROTO_CE_DECLARE pce;
+ if (php_proto_zend_lookup_class(classname, classname_len, &pce) ==
+ FAILURE) {
+ RETURN_NULL();
+ }
-// -----------------------------------------------------------------------------
-// EnumDescriptor
-// -----------------------------------------------------------------------------
+ PHP_PROTO_HASHTABLE_VALUE desc = get_ce_obj(PHP_PROTO_CE_UNREF(pce));
+ if (desc == NULL) {
+ RETURN_NULL();
+ }
-static zend_function_entry enum_descriptor_methods[] = {
- ZEND_FE_END
-};
+ zend_class_entry* instance_ce = HASHTABLE_VALUE_CE(desc);
-DEFINE_CLASS(EnumDescriptor, enum_descriptor,
- "Google\\Protobuf\\Internal\\EnumDescriptor");
+ if (!instanceof_function(instance_ce, descriptor_type TSRMLS_CC)) {
+ RETURN_NULL();
+ }
-static void enum_descriptor_free_c(EnumDescriptor *self TSRMLS_DC) {
+#if PHP_MAJOR_VERSION < 7
+ RETURN_ZVAL(desc, 1, 0);
+#else
+ ++GC_REFCOUNT(desc);
+ RETURN_OBJ(desc);
+#endif
}
-static void enum_descriptor_init_c_instance(EnumDescriptor *self TSRMLS_DC) {
- zend_object_std_init(&self->std, enum_descriptor_type TSRMLS_CC);
- self->enumdef = NULL;
- self->klass = NULL;
-}
+PHP_METHOD(DescriptorPool, getEnumDescriptorByClassName) {
+ DescriptorPool *public_pool = UNBOX(DescriptorPool, getThis());
+ InternalDescriptorPool *pool = public_pool->intern;
-// -----------------------------------------------------------------------------
-// FieldDescriptor
-// -----------------------------------------------------------------------------
+ char *classname = NULL;
+ PHP_PROTO_SIZE classname_len;
-upb_fieldtype_t to_fieldtype(upb_descriptortype_t type) {
- switch (type) {
-#define CASE(descriptor_type, type) \
- case UPB_DESCRIPTOR_TYPE_##descriptor_type: \
- return UPB_TYPE_##type;
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &classname,
+ &classname_len) == FAILURE) {
+ return;
+ }
- CASE(FLOAT, FLOAT);
- CASE(DOUBLE, DOUBLE);
- CASE(BOOL, BOOL);
- CASE(STRING, STRING);
- CASE(BYTES, BYTES);
- CASE(MESSAGE, MESSAGE);
- CASE(GROUP, MESSAGE);
- CASE(ENUM, ENUM);
- CASE(INT32, INT32);
- CASE(INT64, INT64);
- CASE(UINT32, UINT32);
- CASE(UINT64, UINT64);
- CASE(SINT32, INT32);
- CASE(SINT64, INT64);
- CASE(FIXED32, UINT32);
- CASE(FIXED64, UINT64);
- CASE(SFIXED32, INT32);
- CASE(SFIXED64, INT64);
+ PHP_PROTO_CE_DECLARE pce;
+ if (php_proto_zend_lookup_class(classname, classname_len, &pce) ==
+ FAILURE) {
+ RETURN_NULL();
+ }
-#undef CONVERT
+ PHP_PROTO_HASHTABLE_VALUE desc = get_ce_obj(PHP_PROTO_CE_UNREF(pce));
+ if (desc == NULL) {
+ RETURN_NULL();
+ }
+
+ zend_class_entry* instance_ce = HASHTABLE_VALUE_CE(desc);
+ if (!instanceof_function(instance_ce, enum_descriptor_type TSRMLS_CC)) {
+ RETURN_NULL();
}
- zend_error(E_ERROR, "Unknown field type.");
- return 0;
+#if PHP_MAJOR_VERSION < 7
+ RETURN_ZVAL(desc, 1, 0);
+#else
+ ++GC_REFCOUNT(desc);
+ RETURN_OBJ(desc);
+#endif
}
diff --git a/php/ext/google/protobuf/encode_decode.c b/php/ext/google/protobuf/encode_decode.c
index eafe1ae8..7e2b3ae6 100644
--- a/php/ext/google/protobuf/encode_decode.c
+++ b/php/ext/google/protobuf/encode_decode.c
@@ -103,6 +103,7 @@ static void stackenv_uninit(stackenv* se);
// Callback invoked by upb if any error occurs during parsing or serialization.
static bool env_error_func(void* ud, const upb_status* status) {
+ char err_msg[100] = "";
stackenv* se = ud;
// Free the env -- zend_error will longjmp up the stack past the
// encode/decode function so it would not otherwise have been freed.
@@ -110,7 +111,9 @@ static bool env_error_func(void* ud, const upb_status* status) {
// TODO(teboring): have a way to verify that this is actually a parse error,
// instead of just throwing "parse error" unconditionally.
- zend_error(E_ERROR, se->php_error_template, upb_status_errmsg(status));
+ sprintf(err_msg, se->php_error_template, upb_status_errmsg(status));
+ TSRMLS_FETCH();
+ zend_throw_exception(NULL, err_msg, 0 TSRMLS_CC);
// Never reached.
return false;
}
@@ -139,6 +142,23 @@ static const void* newhandlerdata(upb_handlers* h, uint32_t ofs) {
return hd_ofs;
}
+typedef size_t (*encodeunknown_handlerfunc)(void* _sink, const void* hd,
+ const char* ptr, size_t len,
+ const upb_bufhandle* handle);
+
+typedef struct {
+ encodeunknown_handlerfunc handler;
+} unknownfields_handlerdata_t;
+
+// Creates a handlerdata for unknown fields.
+static const void *newunknownfieldshandlerdata(upb_handlers* h) {
+ unknownfields_handlerdata_t* hd =
+ (unknownfields_handlerdata_t*)malloc(sizeof(unknownfields_handlerdata_t));
+ hd->handler = stringsink_string;
+ upb_handlers_addcleanup(h, hd, free);
+ return hd;
+}
+
typedef struct {
size_t ofs;
const upb_msgdef *md;
@@ -161,18 +181,21 @@ typedef struct {
int property_ofs; // properties table cache
uint32_t oneof_case_num; // oneof-case number to place in oneof_case field
const upb_msgdef *md; // msgdef, for oneof submessage handler
+ const upb_msgdef *parent_md; // msgdef, for parent submessage
} oneof_handlerdata_t;
static const void *newoneofhandlerdata(upb_handlers *h,
uint32_t ofs,
uint32_t case_ofs,
int property_ofs,
+ const upb_msgdef *m,
const upb_fielddef *f) {
oneof_handlerdata_t* hd =
(oneof_handlerdata_t*)malloc(sizeof(oneof_handlerdata_t));
hd->ofs = ofs;
hd->case_ofs = case_ofs;
hd->property_ofs = property_ofs;
+ hd->parent_md = m;
// We reuse the field tag number as a oneof union discriminant tag. Note that
// we don't expose these numbers to the user, so the only requirement is that
// we have some unique ID for each union case/possibility. The field tag
@@ -194,19 +217,18 @@ static const void *newoneofhandlerdata(upb_handlers *h,
static void *startseq_handler(void* closure, const void* hd) {
MessageHeader* msg = closure;
const size_t *ofs = hd;
- return (void*)(*DEREF(msg, *ofs, zval**));
+ return CACHED_PTR_TO_ZVAL_PTR(DEREF(message_data(msg), *ofs, CACHED_VALUE*));
}
// Handlers that append primitive values to a repeated field.
-#define DEFINE_APPEND_HANDLER(type, ctype) \
- static bool append##type##_handler(void* closure, const void* hd, \
- ctype val) { \
- zval* array = (zval*)closure; \
- TSRMLS_FETCH(); \
- RepeatedField* intern = \
- (RepeatedField*)zend_object_store_get_object(array TSRMLS_CC); \
- repeated_field_push_native(intern, &val TSRMLS_CC); \
- return true; \
+#define DEFINE_APPEND_HANDLER(type, ctype) \
+ static bool append##type##_handler(void* closure, const void* hd, \
+ ctype val) { \
+ zval* array = (zval*)closure; \
+ TSRMLS_FETCH(); \
+ RepeatedField* intern = UNBOX(RepeatedField, array); \
+ repeated_field_push_native(intern, &val); \
+ return true; \
}
DEFINE_APPEND_HANDLER(bool, bool)
@@ -223,15 +245,19 @@ static void* appendstr_handler(void *closure,
size_t size_hint) {
zval* array = (zval*)closure;
TSRMLS_FETCH();
- RepeatedField* intern =
- (RepeatedField*)zend_object_store_get_object(array TSRMLS_CC);
+ RepeatedField* intern = UNBOX(RepeatedField, array);
+#if PHP_MAJOR_VERSION < 7
zval* str;
MAKE_STD_ZVAL(str);
- ZVAL_STRING(str, "", 1);
-
- repeated_field_push_native(intern, &str TSRMLS_CC);
+ PHP_PROTO_ZVAL_STRING(str, "", 1);
+ repeated_field_push_native(intern, &str);
return (void*)str;
+#else
+ zend_string* str = zend_string_init("", 0, 1);
+ repeated_field_push_native(intern, &str);
+ return intern;
+#endif
}
// Appends a 'bytes' string to a repeated field.
@@ -240,24 +266,60 @@ static void* appendbytes_handler(void *closure,
size_t size_hint) {
zval* array = (zval*)closure;
TSRMLS_FETCH();
- RepeatedField* intern =
- (RepeatedField*)zend_object_store_get_object(array TSRMLS_CC);
+ RepeatedField* intern = UNBOX(RepeatedField, array);
+#if PHP_MAJOR_VERSION < 7
zval* str;
MAKE_STD_ZVAL(str);
- ZVAL_STRING(str, "", 1);
-
- repeated_field_push_native(intern, &str TSRMLS_CC);
+ PHP_PROTO_ZVAL_STRING(str, "", 1);
+ repeated_field_push_native(intern, &str);
return (void*)str;
+#else
+ zend_string* str = zend_string_init("", 0, 1);
+ repeated_field_push_native(intern, &str);
+ return intern;
+#endif
}
+// Handlers that append primitive values to a repeated field.
+#define DEFINE_SINGULAR_HANDLER(type, ctype) \
+ static bool type##_handler(void* closure, const void* hd, \
+ ctype val) { \
+ MessageHeader* msg = (MessageHeader*)closure; \
+ const size_t *ofs = hd; \
+ DEREF(message_data(msg), *ofs, ctype) = val; \
+ return true; \
+ }
+
+DEFINE_SINGULAR_HANDLER(bool, bool)
+DEFINE_SINGULAR_HANDLER(int32, int32_t)
+DEFINE_SINGULAR_HANDLER(uint32, uint32_t)
+DEFINE_SINGULAR_HANDLER(float, float)
+DEFINE_SINGULAR_HANDLER(int64, int64_t)
+DEFINE_SINGULAR_HANDLER(uint64, uint64_t)
+DEFINE_SINGULAR_HANDLER(double, double)
+
+#undef DEFINE_SINGULAR_HANDLER
+
+#if PHP_MAJOR_VERSION < 7
static void *empty_php_string(zval** value_ptr) {
SEPARATE_ZVAL_IF_NOT_REF(value_ptr);
- zval* str = *value_ptr;
- zval_dtor(str);
- ZVAL_STRINGL(str, "", 0, 1);
- return (void*)str;
+ if (Z_TYPE_PP(value_ptr) == IS_STRING &&
+ !IS_INTERNED(Z_STRVAL_PP(value_ptr))) {
+ FREE(Z_STRVAL_PP(value_ptr));
+ }
+ ZVAL_EMPTY_STRING(*value_ptr);
+ return (void*)(*value_ptr);
+}
+#else
+static void *empty_php_string(zval* value_ptr) {
+ if (Z_TYPE_P(value_ptr) == IS_STRING) {
+ zend_string_release(Z_STR_P(value_ptr));
+ }
+ ZVAL_EMPTY_STRING(value_ptr);
+ return value_ptr;
}
+#endif
// Sets a non-repeated string field in a message.
static void* str_handler(void *closure,
@@ -265,7 +327,7 @@ static void* str_handler(void *closure,
size_t size_hint) {
MessageHeader* msg = closure;
const size_t *ofs = hd;
- return empty_php_string(DEREF(msg, *ofs, zval**));
+ return empty_php_string(DEREF(message_data(msg), *ofs, CACHED_VALUE*));
}
// Sets a non-repeated 'bytes' field in a message.
@@ -274,52 +336,73 @@ static void* bytes_handler(void *closure,
size_t size_hint) {
MessageHeader* msg = closure;
const size_t *ofs = hd;
- return empty_php_string(DEREF(msg, *ofs, zval**));
+ return empty_php_string(DEREF(message_data(msg), *ofs, CACHED_VALUE*));
}
static size_t stringdata_handler(void* closure, const void* hd,
const char* str, size_t len,
const upb_bufhandle* handle) {
zval* php_str = (zval*)closure;
+#if PHP_MAJOR_VERSION < 7
+ // Oneof string/bytes fields may have NULL initial value, which doesn't need
+ // to be freed.
+ if (Z_TYPE_P(php_str) == IS_STRING && !IS_INTERNED(Z_STRVAL_P(php_str))) {
+ FREE(Z_STRVAL_P(php_str));
+ }
+ ZVAL_STRINGL(php_str, str, len, 1);
+#else
+ if (Z_TYPE_P(php_str) == IS_STRING) {
+ zend_string_release(Z_STR_P(php_str));
+ }
+ ZVAL_NEW_STR(php_str, zend_string_init(str, len, 0));
+#endif
+ return len;
+}
- char* old_str = Z_STRVAL_P(php_str);
- size_t old_len = Z_STRLEN_P(php_str);
- assert(old_str != NULL);
-
- char* new_str = emalloc(old_len + len + 1);
+#if PHP_MAJOR_VERSION >= 7
+static size_t zendstringdata_handler(void* closure, const void* hd,
+ const char* str, size_t len,
+ const upb_bufhandle* handle) {
+ RepeatedField* intern = (RepeatedField*)closure;
- memcpy(new_str, old_str, old_len);
- memcpy(new_str + old_len, str, len);
- new_str[old_len + len] = 0;
- FREE(old_str);
+ unsigned char memory[NATIVE_SLOT_MAX_SIZE];
+ memset(memory, 0, NATIVE_SLOT_MAX_SIZE);
+ *(zend_string**)memory = zend_string_init(str, len, 0);
- Z_STRVAL_P(php_str) = new_str;
- Z_STRLEN_P(php_str) = old_len + len;
+ HashTable *ht = PHP_PROTO_HASH_OF(intern->array);
+ int index = zend_hash_num_elements(ht) - 1;
+ php_proto_zend_hash_index_update_mem(
+ ht, index, memory, sizeof(zend_string*), NULL);
return len;
}
+#endif
// Appends a submessage to a repeated field.
static void *appendsubmsg_handler(void *closure, const void *hd) {
zval* array = (zval*)closure;
TSRMLS_FETCH();
- RepeatedField* intern =
- (RepeatedField*)zend_object_store_get_object(array TSRMLS_CC);
+ RepeatedField* intern = UNBOX(RepeatedField, array);
const submsg_handlerdata_t *submsgdata = hd;
- zval* subdesc_php = get_def_obj((void*)submsgdata->md);
- Descriptor* subdesc = zend_object_store_get_object(subdesc_php TSRMLS_CC);
+ Descriptor* subdesc =
+ UNBOX_HASHTABLE_VALUE(Descriptor, get_def_obj((void*)submsgdata->md));
zend_class_entry* subklass = subdesc->klass;
MessageHeader* submsg;
+#if PHP_MAJOR_VERSION < 7
zval* val = NULL;
MAKE_STD_ZVAL(val);
- Z_TYPE_P(val) = IS_OBJECT;
- Z_OBJVAL_P(val) = subklass->create_object(subklass TSRMLS_CC);
-
- repeated_field_push_native(intern, &val TSRMLS_CC);
+ ZVAL_OBJ(val, subklass->create_object(subklass TSRMLS_CC));
+ repeated_field_push_native(intern, &val);
+ submsg = UNBOX(MessageHeader, val);
+#else
+ zend_object* obj = subklass->create_object(subklass TSRMLS_CC);
+ repeated_field_push_native(intern, &obj);
+ submsg = (MessageHeader*)((char*)obj - XtOffsetOf(MessageHeader, std));
+#endif
+ custom_data_init(subklass, submsg PHP_PROTO_TSRMLS_CC);
- submsg = zend_object_store_get_object(val TSRMLS_CC);
return submsg;
}
@@ -327,26 +410,35 @@ static void *appendsubmsg_handler(void *closure, const void *hd) {
static void *submsg_handler(void *closure, const void *hd) {
MessageHeader* msg = closure;
const submsg_handlerdata_t* submsgdata = hd;
- zval* subdesc_php = get_def_obj((void*)submsgdata->md);
TSRMLS_FETCH();
- Descriptor* subdesc = zend_object_store_get_object(subdesc_php TSRMLS_CC);
+ Descriptor* subdesc =
+ UNBOX_HASHTABLE_VALUE(Descriptor, get_def_obj((void*)submsgdata->md));
zend_class_entry* subklass = subdesc->klass;
zval* submsg_php;
MessageHeader* submsg;
- if (Z_TYPE_P(*DEREF(msg, submsgdata->ofs, zval**)) == IS_NULL) {
+ if (Z_TYPE_P(CACHED_PTR_TO_ZVAL_PTR(DEREF(message_data(msg), submsgdata->ofs,
+ CACHED_VALUE*))) == IS_NULL) {
+#if PHP_MAJOR_VERSION < 7
zval* val = NULL;
MAKE_STD_ZVAL(val);
- Z_TYPE_P(val) = IS_OBJECT;
- Z_OBJVAL_P(val) = subklass->create_object(subklass TSRMLS_CC);
-
- zval_ptr_dtor(DEREF(msg, submsgdata->ofs, zval**));
- *DEREF(msg, submsgdata->ofs, zval**) = val;
+ ZVAL_OBJ(val, subklass->create_object(subklass TSRMLS_CC));
+ MessageHeader* intern = UNBOX(MessageHeader, val);
+ custom_data_init(subklass, intern PHP_PROTO_TSRMLS_CC);
+ php_proto_zval_ptr_dtor(*DEREF(message_data(msg), submsgdata->ofs, zval**));
+ *DEREF(message_data(msg), submsgdata->ofs, zval**) = val;
+#else
+ zend_object* obj = subklass->create_object(subklass TSRMLS_CC);
+ ZVAL_OBJ(DEREF(message_data(msg), submsgdata->ofs, zval*), obj);
+ MessageHeader* intern = UNBOX_HASHTABLE_VALUE(MessageHeader, obj);
+ custom_data_init(subklass, intern PHP_PROTO_TSRMLS_CC);
+#endif
}
- submsg_php = *DEREF(msg, submsgdata->ofs, zval**);
+ submsg_php = CACHED_PTR_TO_ZVAL_PTR(
+ DEREF(message_data(msg), submsgdata->ofs, CACHED_VALUE*));
- submsg = zend_object_store_get_object(submsg_php TSRMLS_CC);
+ submsg = UNBOX(MessageHeader, submsg_php);
return submsg;
}
@@ -369,32 +461,52 @@ typedef struct {
// submessage. When the submessage ends, another handler is called to insert the
// value into the map.
typedef struct {
- zval* map;
char key_storage[NATIVE_SLOT_MAX_SIZE];
char value_storage[NATIVE_SLOT_MAX_SIZE];
-} map_parse_frame_t;
+} map_parse_frame_data_t;
-static void map_slot_init(void* memory, upb_fieldtype_t type) {
+PHP_PROTO_WRAP_OBJECT_START(map_parse_frame_t)
+ map_parse_frame_data_t* data; // Place needs to be consistent with
+ // MessageHeader.
+ zval* map;
+ // In php7, we cannot allocate zval dynamically. So we need to add zval here
+ // to help decoding.
+ zval key_zval;
+ zval value_zval;
+PHP_PROTO_WRAP_OBJECT_END
+typedef struct map_parse_frame_t map_parse_frame_t;
+
+static void map_slot_init(void* memory, upb_fieldtype_t type, zval* cache) {
switch (type) {
case UPB_TYPE_STRING:
case UPB_TYPE_BYTES: {
+#if PHP_MAJOR_VERSION < 7
// Store zval** in memory in order to be consistent with the layout of
// singular fields.
zval** holder = ALLOC(zval*);
zval* tmp;
MAKE_STD_ZVAL(tmp);
- ZVAL_STRINGL(tmp, "", 0, 1);
+ PHP_PROTO_ZVAL_STRINGL(tmp, "", 0, 1);
*holder = tmp;
*(zval***)memory = holder;
+#else
+ *(zval**)memory = cache;
+ PHP_PROTO_ZVAL_STRINGL(*(zval**)memory, "", 0, 1);
+#endif
break;
}
case UPB_TYPE_MESSAGE: {
+#if PHP_MAJOR_VERSION < 7
zval** holder = ALLOC(zval*);
zval* tmp;
MAKE_STD_ZVAL(tmp);
ZVAL_NULL(tmp);
*holder = tmp;
*(zval***)memory = holder;
+#else
+ *(zval**)memory = cache;
+ ZVAL_NULL(*(zval**)memory);
+#endif
break;
}
default:
@@ -407,9 +519,13 @@ static void map_slot_uninit(void* memory, upb_fieldtype_t type) {
case UPB_TYPE_MESSAGE:
case UPB_TYPE_STRING:
case UPB_TYPE_BYTES: {
+#if PHP_MAJOR_VERSION < 7
zval** holder = *(zval***)memory;
- zval_ptr_dtor(holder);
+ php_proto_zval_ptr_dtor(*holder);
FREE(holder);
+#else
+ php_proto_zval_ptr_dtor(*(zval**)memory);
+#endif
break;
}
default:
@@ -421,7 +537,11 @@ static void map_slot_key(upb_fieldtype_t type, const void* from,
const char** keyval,
size_t* length) {
if (type == UPB_TYPE_STRING) {
+#if PHP_MAJOR_VERSION < 7
zval* key_php = **(zval***)from;
+#else
+ zval* key_php = *(zval**)from;
+#endif
*keyval = Z_STRVAL_P(key_php);
*length = Z_STRLEN_P(key_php);
} else {
@@ -431,7 +551,7 @@ static void map_slot_key(upb_fieldtype_t type, const void* from,
}
static void map_slot_value(upb_fieldtype_t type, const void* from,
- upb_value* v) {
+ upb_value* v) {
size_t len;
void* to = upb_value_memory(v);
#ifndef NDEBUG
@@ -441,6 +561,7 @@ static void map_slot_value(upb_fieldtype_t type, const void* from,
memset(to, 0, native_slot_size(type));
switch (type) {
+#if PHP_MAJOR_VERSION < 7
case UPB_TYPE_STRING:
case UPB_TYPE_BYTES:
case UPB_TYPE_MESSAGE: {
@@ -448,6 +569,17 @@ static void map_slot_value(upb_fieldtype_t type, const void* from,
Z_ADDREF_PP((zval**)to);
break;
}
+#else
+ case UPB_TYPE_STRING:
+ case UPB_TYPE_BYTES:
+ *(zend_string**)to = Z_STR_P(*(zval**)from);
+ zend_string_addref(*(zend_string**)to);
+ break;
+ case UPB_TYPE_MESSAGE:
+ *(zend_object**)to = Z_OBJ_P(*(zval**)from);
+ ++GC_REFCOUNT(*(zend_object**)to);
+ break;
+#endif
default:
len = native_slot_size(type);
memcpy(to, from, len);
@@ -459,13 +591,17 @@ static void map_slot_value(upb_fieldtype_t type, const void* from,
static void *startmapentry_handler(void *closure, const void *hd) {
MessageHeader* msg = closure;
const map_handlerdata_t* mapdata = hd;
- zval* map = *DEREF(msg, mapdata->ofs, zval**);
+ zval* map = CACHED_PTR_TO_ZVAL_PTR(
+ DEREF(message_data(msg), mapdata->ofs, CACHED_VALUE*));
map_parse_frame_t* frame = ALLOC(map_parse_frame_t);
+ frame->data = ALLOC(map_parse_frame_data_t);
frame->map = map;
- map_slot_init(&frame->key_storage, mapdata->key_field_type);
- map_slot_init(&frame->value_storage, mapdata->value_field_type);
+ map_slot_init(&frame->data->key_storage, mapdata->key_field_type,
+ &frame->key_zval);
+ map_slot_init(&frame->data->value_storage, mapdata->value_field_type,
+ &frame->value_zval);
return frame;
}
@@ -477,19 +613,20 @@ static bool endmap_handler(void* closure, const void* hd, upb_status* s) {
const map_handlerdata_t* mapdata = hd;
TSRMLS_FETCH();
- Map *map = (Map *)zend_object_store_get_object(frame->map TSRMLS_CC);
+ Map *map = UNBOX(Map, frame->map);
const char* keyval = NULL;
upb_value v;
size_t length;
- map_slot_key(map->key_type, &frame->key_storage, &keyval, &length);
- map_slot_value(map->value_type, &frame->value_storage, &v);
+ map_slot_key(map->key_type, &frame->data->key_storage, &keyval, &length);
+ map_slot_value(map->value_type, &frame->data->value_storage, &v);
map_index_set(map, keyval, length, v);
- map_slot_uninit(&frame->key_storage, mapdata->key_field_type);
- map_slot_uninit(&frame->value_storage, mapdata->value_field_type);
+ map_slot_uninit(&frame->data->key_storage, mapdata->key_field_type);
+ map_slot_uninit(&frame->data->value_storage, mapdata->value_field_type);
+ FREE(frame->data);
FREE(frame);
return true;
@@ -525,14 +662,15 @@ static map_handlerdata_t* new_map_handlerdata(
}
// Handlers that set primitive values in oneofs.
-#define DEFINE_ONEOF_HANDLER(type, ctype) \
- static bool oneof##type##_handler(void *closure, const void *hd, \
- ctype val) { \
- const oneof_handlerdata_t *oneofdata = hd; \
- DEREF(closure, oneofdata->case_ofs, uint32_t) = \
- oneofdata->oneof_case_num; \
- DEREF(closure, oneofdata->ofs, ctype) = val; \
- return true; \
+#define DEFINE_ONEOF_HANDLER(type, ctype) \
+ static bool oneof##type##_handler(void* closure, const void* hd, \
+ ctype val) { \
+ const oneof_handlerdata_t* oneofdata = hd; \
+ MessageHeader* msg = (MessageHeader*)closure; \
+ DEREF(message_data(closure), oneofdata->case_ofs, uint32_t) = \
+ oneofdata->oneof_case_num; \
+ DEREF(message_data(closure), oneofdata->ofs, ctype) = val; \
+ return true; \
}
DEFINE_ONEOF_HANDLER(bool, bool)
@@ -545,74 +683,100 @@ DEFINE_ONEOF_HANDLER(double, double)
#undef DEFINE_ONEOF_HANDLER
-// Handlers for strings in a oneof.
-static void *oneofstr_handler(void *closure,
- const void *hd,
- size_t size_hint) {
- MessageHeader* msg = closure;
- const oneof_handlerdata_t *oneofdata = hd;
+static void oneof_cleanup(MessageHeader* msg,
+ const oneof_handlerdata_t* oneofdata) {
+ uint32_t old_case_num =
+ DEREF(message_data(msg), oneofdata->case_ofs, uint32_t);
+ if (old_case_num == 0) {
+ return;
+ }
- DEREF(msg, oneofdata->case_ofs, uint32_t) =
- oneofdata->oneof_case_num;
- DEREF(msg, oneofdata->ofs, zval**) =
- &(msg->std.properties_table)[oneofdata->property_ofs];
+ const upb_fielddef* old_field =
+ upb_msgdef_itof(oneofdata->parent_md, old_case_num);
+ bool need_clean = false;
+
+ switch (upb_fielddef_type(old_field)) {
+ case UPB_TYPE_STRING:
+ case UPB_TYPE_BYTES:
+ need_clean = true;
+ break;
+ case UPB_TYPE_MESSAGE:
+ if (oneofdata->oneof_case_num != old_case_num) {
+ need_clean = true;
+ }
+ break;
+ default:
+ break;
+ }
- return empty_php_string(DEREF(msg, oneofdata->ofs, zval**));
+ if (need_clean) {
+#if PHP_MAJOR_VERSION < 7
+ SEPARATE_ZVAL_IF_NOT_REF(
+ DEREF(message_data(msg), oneofdata->ofs, CACHED_VALUE*));
+ php_proto_zval_ptr_dtor(
+ *DEREF(message_data(msg), oneofdata->ofs, CACHED_VALUE*));
+ MAKE_STD_ZVAL(*DEREF(message_data(msg), oneofdata->ofs, CACHED_VALUE*));
+ ZVAL_NULL(*DEREF(message_data(msg), oneofdata->ofs, CACHED_VALUE*));
+#endif
+ }
}
+// Handlers for string/bytes in a oneof.
static void *oneofbytes_handler(void *closure,
const void *hd,
size_t size_hint) {
MessageHeader* msg = closure;
const oneof_handlerdata_t *oneofdata = hd;
- DEREF(msg, oneofdata->case_ofs, uint32_t) =
+ oneof_cleanup(msg, oneofdata);
+
+ DEREF(message_data(msg), oneofdata->case_ofs, uint32_t) =
oneofdata->oneof_case_num;
- DEREF(msg, oneofdata->ofs, zval**) =
- &(msg->std.properties_table)[oneofdata->property_ofs];
+ DEREF(message_data(msg), oneofdata->ofs, CACHED_VALUE*) =
+ OBJ_PROP(&msg->std, oneofdata->property_ofs);
+
+ return empty_php_string(DEREF(
+ message_data(msg), oneofdata->ofs, CACHED_VALUE*));
+}
+static void *oneofstr_handler(void *closure,
+ const void *hd,
+ size_t size_hint) {
// TODO(teboring): Add it back.
// rb_enc_associate(str, kRubyString8bitEncoding);
-
- SEPARATE_ZVAL_IF_NOT_REF(DEREF(msg, oneofdata->ofs, zval**));
- zval* str = *DEREF(msg, oneofdata->ofs, zval**);
- zval_dtor(str);
- ZVAL_STRINGL(str, "", 0, 1);
- return (void*)str;
+ return oneofbytes_handler(closure, hd, size_hint);
}
// Handler for a submessage field in a oneof.
static void* oneofsubmsg_handler(void* closure, const void* hd) {
MessageHeader* msg = closure;
const oneof_handlerdata_t *oneofdata = hd;
- uint32_t oldcase = DEREF(msg, oneofdata->case_ofs, uint32_t);
- zval* subdesc_php = get_def_obj((void*)oneofdata->md);
+ uint32_t oldcase = DEREF(message_data(msg), oneofdata->case_ofs, uint32_t);
TSRMLS_FETCH();
- Descriptor* subdesc = zend_object_store_get_object(subdesc_php TSRMLS_CC);
+ Descriptor* subdesc =
+ UNBOX_HASHTABLE_VALUE(Descriptor, get_def_obj((void*)oneofdata->md));
zend_class_entry* subklass = subdesc->klass;
zval* submsg_php;
MessageHeader* submsg;
if (oldcase != oneofdata->oneof_case_num) {
- DEREF(msg, oneofdata->ofs, zval**) =
- &(msg->std.properties_table)[oneofdata->property_ofs];
+ oneof_cleanup(msg, oneofdata);
+
+ // Create new message.
+ DEREF(message_data(msg), oneofdata->ofs, CACHED_VALUE*) =
+ OBJ_PROP(&msg->std, oneofdata->property_ofs);
+ ZVAL_OBJ(CACHED_PTR_TO_ZVAL_PTR(
+ DEREF(message_data(msg), oneofdata->ofs, CACHED_VALUE*)),
+ subklass->create_object(subklass TSRMLS_CC));
}
- if (Z_TYPE_P(*DEREF(msg, oneofdata->ofs, zval**)) == IS_NULL) {
- zval* val = NULL;
- MAKE_STD_ZVAL(val);
- Z_TYPE_P(val) = IS_OBJECT;
- Z_OBJVAL_P(val) = subklass->create_object(subklass TSRMLS_CC);
-
- zval_ptr_dtor(DEREF(msg, oneofdata->ofs, zval**));
- *DEREF(msg, oneofdata->ofs, zval**) = val;
- }
-
- DEREF(msg, oneofdata->case_ofs, uint32_t) =
+ DEREF(message_data(msg), oneofdata->case_ofs, uint32_t) =
oneofdata->oneof_case_num;
- submsg_php = *DEREF(msg, oneofdata->ofs, zval**);
- submsg = zend_object_store_get_object(submsg_php TSRMLS_CC);
+ submsg_php = CACHED_PTR_TO_ZVAL_PTR(
+ DEREF(message_data(msg), oneofdata->ofs, CACHED_VALUE*));
+ submsg = UNBOX(MessageHeader, submsg_php);
+ custom_data_init(subklass, submsg PHP_PROTO_TSRMLS_CC);
return submsg;
}
@@ -649,7 +813,11 @@ static void add_handlers_for_repeated_field(upb_handlers *h,
upb_handlers_setstartstr(h, f, is_bytes ?
appendbytes_handler : appendstr_handler,
NULL);
+#if PHP_MAJOR_VERSION < 7
upb_handlers_setstring(h, f, stringdata_handler, NULL);
+#else
+ upb_handlers_setstring(h, f, zendstringdata_handler, NULL);
+#endif
break;
}
case UPB_TYPE_MESSAGE: {
@@ -667,16 +835,26 @@ static void add_handlers_for_singular_field(upb_handlers *h,
const upb_fielddef *f,
size_t offset) {
switch (upb_fielddef_type(f)) {
- case UPB_TYPE_BOOL:
- case UPB_TYPE_INT32:
- case UPB_TYPE_UINT32:
- case UPB_TYPE_ENUM:
- case UPB_TYPE_FLOAT:
- case UPB_TYPE_INT64:
- case UPB_TYPE_UINT64:
- case UPB_TYPE_DOUBLE:
- upb_shim_set(h, f, offset, -1);
- break;
+
+#define SET_HANDLER(utype, ltype) \
+ case utype: { \
+ upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER; \
+ upb_handlerattr_sethandlerdata(&attr, newhandlerdata(h, offset)); \
+ upb_handlers_set##ltype(h, f, ltype##_handler, &attr); \
+ break; \
+ }
+
+ SET_HANDLER(UPB_TYPE_BOOL, bool);
+ SET_HANDLER(UPB_TYPE_INT32, int32);
+ SET_HANDLER(UPB_TYPE_UINT32, uint32);
+ SET_HANDLER(UPB_TYPE_ENUM, int32);
+ SET_HANDLER(UPB_TYPE_FLOAT, float);
+ SET_HANDLER(UPB_TYPE_INT64, int64);
+ SET_HANDLER(UPB_TYPE_UINT64, uint64);
+ SET_HANDLER(UPB_TYPE_DOUBLE, double);
+
+#undef SET_HANDLER
+
case UPB_TYPE_STRING:
case UPB_TYPE_BYTES: {
bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
@@ -727,13 +905,16 @@ static void add_handlers_for_mapentry(const upb_msgdef* msgdef, upb_handlers* h,
upb_handlers_setendmsg(h, endmap_handler, &attr);
add_handlers_for_singular_field(h, key_field,
- offsetof(map_parse_frame_t, key_storage));
+ offsetof(map_parse_frame_data_t,
+ key_storage));
add_handlers_for_singular_field(h, value_field,
- offsetof(map_parse_frame_t, value_storage));
+ offsetof(map_parse_frame_data_t,
+ value_storage));
}
// Set up handlers for a oneof field.
static void add_handlers_for_oneof_field(upb_handlers *h,
+ const upb_msgdef *m,
const upb_fielddef *f,
size_t offset,
size_t oneof_case_offset,
@@ -742,7 +923,7 @@ static void add_handlers_for_oneof_field(upb_handlers *h,
upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
upb_handlerattr_sethandlerdata(
&attr, newoneofhandlerdata(h, offset, oneof_case_offset,
- property_cache_offset, f));
+ property_cache_offset, m, f));
switch (upb_fielddef_type(f)) {
@@ -780,12 +961,30 @@ static void add_handlers_for_oneof_field(upb_handlers *h,
upb_handlerattr_uninit(&attr);
}
+static bool add_unknown_handler(void* closure, const void* hd, const char* buf,
+ size_t size) {
+ encodeunknown_handlerfunc handler =
+ ((unknownfields_handlerdata_t*)hd)->handler;
+
+ MessageHeader* msg = (MessageHeader*)closure;
+ stringsink* unknown = DEREF(message_data(msg), 0, stringsink*);
+ if (unknown == NULL) {
+ DEREF(message_data(msg), 0, stringsink*) = ALLOC(stringsink);
+ unknown = DEREF(message_data(msg), 0, stringsink*);
+ stringsink_init(unknown);
+ }
+
+ handler(unknown, NULL, buf, size, NULL);
+
+ return true;
+}
+
static void add_handlers_for_message(const void* closure,
upb_handlers* h) {
const upb_msgdef* msgdef = upb_handlers_msgdef(h);
TSRMLS_FETCH();
- Descriptor* desc = (Descriptor*)zend_object_store_get_object(
- get_def_obj((void*)msgdef) TSRMLS_CC);
+ Descriptor* desc =
+ UNBOX_HASHTABLE_VALUE(Descriptor, get_def_obj((void*)msgdef));
upb_msg_field_iter i;
// If this is a mapentry message type, set up a special set of handlers and
@@ -803,21 +1002,23 @@ static void add_handlers_for_message(const void* closure,
desc->layout = create_layout(desc->msgdef);
}
+ upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
+ upb_handlerattr_sethandlerdata(&attr, newunknownfieldshandlerdata(h));
+ upb_handlers_setunknown(h, add_unknown_handler, &attr);
+
for (upb_msg_field_begin(&i, desc->msgdef);
!upb_msg_field_done(&i);
upb_msg_field_next(&i)) {
const upb_fielddef *f = upb_msg_iter_field(&i);
- size_t offset = desc->layout->fields[upb_fielddef_index(f)].offset +
- sizeof(MessageHeader);
+ size_t offset = desc->layout->fields[upb_fielddef_index(f)].offset;
if (upb_fielddef_containingoneof(f)) {
size_t oneof_case_offset =
- desc->layout->fields[upb_fielddef_index(f)].case_offset +
- sizeof(MessageHeader);
+ desc->layout->fields[upb_fielddef_index(f)].case_offset;
int property_cache_index =
desc->layout->fields[upb_fielddef_index(f)].cache_index;
- add_handlers_for_oneof_field(h, f, offset, oneof_case_offset,
- property_cache_index);
+ add_handlers_for_oneof_field(h, desc->msgdef, f, offset,
+ oneof_case_offset, property_cache_index);
} else if (is_map_field(f)) {
add_handlers_for_mapfield(h, f, offset, desc);
} else if (upb_fielddef_isseq(f)) {
@@ -866,12 +1067,22 @@ static const upb_pbdecodermethod *msgdef_decodermethod(Descriptor* desc) {
return desc->fill_method;
}
+static const upb_json_parsermethod *msgdef_jsonparsermethod(Descriptor* desc) {
+ if (desc->json_fill_method == NULL) {
+ desc->json_fill_method =
+ upb_json_parsermethod_new(desc->msgdef, &desc->json_fill_method);
+ }
+ return desc->json_fill_method;
+}
+
// -----------------------------------------------------------------------------
// Serializing.
// -----------------------------------------------------------------------------
static void putmsg(zval* msg, const Descriptor* desc, upb_sink* sink,
int depth TSRMLS_DC);
+static void putrawmsg(MessageHeader* msg, const Descriptor* desc,
+ upb_sink* sink, int depth TSRMLS_DC);
static void putstr(zval* str, const upb_fielddef* f, upb_sink* sink);
@@ -880,11 +1091,13 @@ static void putrawstr(const char* str, int len, const upb_fielddef* f,
static void putsubmsg(zval* submsg, const upb_fielddef* f, upb_sink* sink,
int depth TSRMLS_DC);
+static void putrawsubmsg(MessageHeader* submsg, const upb_fielddef* f,
+ upb_sink* sink, int depth TSRMLS_DC);
static void putarray(zval* array, const upb_fielddef* f, upb_sink* sink,
int depth TSRMLS_DC);
-static void putmap(zval* map, const upb_fielddef* f, upb_sink* sink, int depth
- TSRMLS_DC);
+static void putmap(zval* map, const upb_fielddef* f, upb_sink* sink,
+ int depth TSRMLS_DC);
static upb_selector_t getsel(const upb_fielddef* f, upb_handlertype_t type) {
upb_selector_t ret;
@@ -922,8 +1135,14 @@ static void put_optional_value(const void* memory, int len, const upb_fielddef*
putrawstr(memory, len, f, sink);
break;
case UPB_TYPE_MESSAGE: {
- zval* submsg = *(zval**)memory;
- putsubmsg(submsg, f, sink, depth TSRMLS_CC);
+#if PHP_MAJOR_VERSION < 7
+ MessageHeader *submsg = UNBOX(MessageHeader, *(zval**)memory);
+#else
+ MessageHeader *submsg =
+ (MessageHeader*)((char*)(*(zend_object**)memory) -
+ XtOffsetOf(MessageHeader, std));
+#endif
+ putrawsubmsg(submsg, f, sink, depth TSRMLS_CC);
break;
}
default:
@@ -936,7 +1155,11 @@ static const char* raw_value(void* memory, const upb_fielddef* f) {
switch (upb_fielddef_type(f)) {
case UPB_TYPE_STRING:
case UPB_TYPE_BYTES:
+#if PHP_MAJOR_VERSION < 7
return Z_STRVAL_PP((zval**)memory);
+#else
+ return ZSTR_VAL(*(zend_string**)memory);
+#endif
break;
default:
return memory;
@@ -947,8 +1170,11 @@ static int raw_value_len(void* memory, int len, const upb_fielddef* f) {
switch (upb_fielddef_type(f)) {
case UPB_TYPE_STRING:
case UPB_TYPE_BYTES:
+#if PHP_MAJOR_VERSION < 7
return Z_STRLEN_PP((zval**)memory);
- break;
+#else
+ return ZSTR_LEN(*(zend_string**)memory);
+#endif
default:
return len;
}
@@ -956,15 +1182,16 @@ static int raw_value_len(void* memory, int len, const upb_fielddef* f) {
static void putmap(zval* map, const upb_fielddef* f, upb_sink* sink,
int depth TSRMLS_DC) {
- Map* self;
upb_sink subsink;
const upb_fielddef* key_field;
const upb_fielddef* value_field;
MapIter it;
- int len;
+ int len, size;
- if (map == NULL) return;
- self = UNBOX(Map, map);
+ assert(map != NULL);
+ Map* intern = UNBOX(Map, map);
+ size = upb_strtable_count(&intern->table);
+ if (size == 0) return;
upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
@@ -999,6 +1226,12 @@ static void putmap(zval* map, const upb_fielddef* f, upb_sink* sink,
static void putmsg(zval* msg_php, const Descriptor* desc, upb_sink* sink,
int depth TSRMLS_DC) {
+ MessageHeader* msg = UNBOX(MessageHeader, msg_php);
+ putrawmsg(msg, desc, sink, depth TSRMLS_CC);
+}
+
+static void putrawmsg(MessageHeader* msg, const Descriptor* desc,
+ upb_sink* sink, int depth TSRMLS_DC) {
upb_msg_field_iter i;
upb_status status;
@@ -1011,53 +1244,57 @@ static void putmsg(zval* msg_php, const Descriptor* desc, upb_sink* sink,
"Maximum recursion depth exceeded during encoding.");
}
- MessageHeader* msg = zend_object_store_get_object(msg_php TSRMLS_CC);
-
for (upb_msg_field_begin(&i, desc->msgdef); !upb_msg_field_done(&i);
upb_msg_field_next(&i)) {
upb_fielddef* f = upb_msg_iter_field(&i);
- uint32_t offset = desc->layout->fields[upb_fielddef_index(f)].offset +
- sizeof(MessageHeader);
+ uint32_t offset = desc->layout->fields[upb_fielddef_index(f)].offset;
+ bool containing_oneof = false;
if (upb_fielddef_containingoneof(f)) {
uint32_t oneof_case_offset =
- desc->layout->fields[upb_fielddef_index(f)].case_offset +
- sizeof(MessageHeader);
+ desc->layout->fields[upb_fielddef_index(f)].case_offset;
// For a oneof, check that this field is actually present -- skip all the
// below if not.
- if (DEREF(msg, oneof_case_offset, uint32_t) != upb_fielddef_number(f)) {
+ if (DEREF(message_data(msg), oneof_case_offset, uint32_t) !=
+ upb_fielddef_number(f)) {
continue;
}
// Otherwise, fall through to the appropriate singular-field handler
// below.
+ containing_oneof = true;
}
if (is_map_field(f)) {
- zval* map = *DEREF(msg, offset, zval**);
+ zval* map = CACHED_PTR_TO_ZVAL_PTR(
+ DEREF(message_data(msg), offset, CACHED_VALUE*));
if (map != NULL) {
putmap(map, f, sink, depth TSRMLS_CC);
}
} else if (upb_fielddef_isseq(f)) {
- zval* array = *DEREF(msg, offset, zval**);
+ zval* array = CACHED_PTR_TO_ZVAL_PTR(
+ DEREF(message_data(msg), offset, CACHED_VALUE*));
if (array != NULL) {
putarray(array, f, sink, depth TSRMLS_CC);
}
} else if (upb_fielddef_isstring(f)) {
- zval* str = *DEREF(msg, offset, zval**);
- if (Z_STRLEN_P(str) > 0) {
+ zval* str = CACHED_PTR_TO_ZVAL_PTR(
+ DEREF(message_data(msg), offset, CACHED_VALUE*));
+ if (containing_oneof || Z_STRLEN_P(str) > 0) {
putstr(str, f, sink);
}
} else if (upb_fielddef_issubmsg(f)) {
- putsubmsg(*DEREF(msg, offset, zval**), f, sink, depth TSRMLS_CC);
+ putsubmsg(CACHED_PTR_TO_ZVAL_PTR(
+ DEREF(message_data(msg), offset, CACHED_VALUE*)),
+ f, sink, depth TSRMLS_CC);
} else {
upb_selector_t sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
-#define T(upbtypeconst, upbtype, ctype, default_value) \
- case upbtypeconst: { \
- ctype value = DEREF(msg, offset, ctype); \
- if (value != default_value) { \
- upb_sink_put##upbtype(sink, sel, value); \
- } \
+#define T(upbtypeconst, upbtype, ctype, default_value) \
+ case upbtypeconst: { \
+ ctype value = DEREF(message_data(msg), offset, ctype); \
+ if (containing_oneof || value != default_value) { \
+ upb_sink_put##upbtype(sink, sel, value); \
+ } \
} break;
switch (upb_fielddef_type(f)) {
@@ -1065,10 +1302,10 @@ static void putmsg(zval* msg_php, const Descriptor* desc, upb_sink* sink,
T(UPB_TYPE_DOUBLE, double, double, 0.0)
T(UPB_TYPE_BOOL, bool, uint8_t, 0)
case UPB_TYPE_ENUM:
- T(UPB_TYPE_INT32, int32, int32_t, 0)
- T(UPB_TYPE_UINT32, uint32, uint32_t, 0)
- T(UPB_TYPE_INT64, int64, int64_t, 0)
- T(UPB_TYPE_UINT64, uint64, uint64_t, 0)
+ T(UPB_TYPE_INT32, int32, int32_t, 0)
+ T(UPB_TYPE_UINT32, uint32, uint32_t, 0)
+ T(UPB_TYPE_INT64, int64, int64_t, 0)
+ T(UPB_TYPE_UINT64, uint64, uint64_t, 0)
case UPB_TYPE_STRING:
case UPB_TYPE_BYTES:
@@ -1080,6 +1317,11 @@ static void putmsg(zval* msg_php, const Descriptor* desc, upb_sink* sink,
}
}
+ stringsink* unknown = DEREF(message_data(msg), 0, stringsink*);
+ if (unknown != NULL) {
+ upb_sink_putunknown(sink, unknown->ptr, unknown->len);
+ }
+
upb_sink_endmsg(sink, &status);
}
@@ -1090,18 +1332,23 @@ static void putstr(zval* str, const upb_fielddef *f, upb_sink *sink) {
assert(Z_TYPE_P(str) == IS_STRING);
- // Ensure that the string has the correct encoding. We also check at field-set
- // time, but the user may have mutated the string object since then.
- if (upb_fielddef_type(f) == UPB_TYPE_STRING &&
- !is_structurally_valid_utf8(Z_STRVAL_P(str), Z_STRLEN_P(str))) {
- zend_error(E_USER_ERROR, "Given string is not UTF8 encoded.");
- return;
- }
-
upb_sink_startstr(sink, getsel(f, UPB_HANDLER_STARTSTR), Z_STRLEN_P(str),
&subsink);
- upb_sink_putstring(&subsink, getsel(f, UPB_HANDLER_STRING), Z_STRVAL_P(str),
- Z_STRLEN_P(str), NULL);
+
+ // For oneof string field, we may get here with string length is zero.
+ if (Z_STRLEN_P(str) > 0) {
+ // Ensure that the string has the correct encoding. We also check at
+ // field-set time, but the user may have mutated the string object since
+ // then.
+ if (upb_fielddef_type(f) == UPB_TYPE_STRING &&
+ !is_structurally_valid_utf8(Z_STRVAL_P(str), Z_STRLEN_P(str))) {
+ zend_error(E_USER_ERROR, "Given string is not UTF8 encoded.");
+ return;
+ }
+ upb_sink_putstring(&subsink, getsel(f, UPB_HANDLER_STRING), Z_STRVAL_P(str),
+ Z_STRLEN_P(str), NULL);
+ }
+
upb_sink_endstr(sink, getsel(f, UPB_HANDLER_ENDSTR));
}
@@ -1124,18 +1371,23 @@ static void putrawstr(const char* str, int len, const upb_fielddef* f,
upb_sink_endstr(sink, getsel(f, UPB_HANDLER_ENDSTR));
}
-static void putsubmsg(zval* submsg, const upb_fielddef* f, upb_sink* sink,
+static void putsubmsg(zval* submsg_php, const upb_fielddef* f, upb_sink* sink,
int depth TSRMLS_DC) {
- upb_sink subsink;
+ if (Z_TYPE_P(submsg_php) == IS_NULL) return;
- if (Z_TYPE_P(submsg) == IS_NULL) return;
+ MessageHeader *submsg = UNBOX(MessageHeader, submsg_php);
+ putrawsubmsg(submsg, f, sink, depth TSRMLS_CC);
+}
+
+static void putrawsubmsg(MessageHeader* submsg, const upb_fielddef* f,
+ upb_sink* sink, int depth TSRMLS_DC) {
+ upb_sink subsink;
- zval* php_descriptor = get_def_obj(upb_fielddef_msgsubdef(f));
Descriptor* subdesc =
- (Descriptor*)zend_object_store_get_object(php_descriptor TSRMLS_CC);
+ UNBOX_HASHTABLE_VALUE(Descriptor, get_def_obj(upb_fielddef_msgsubdef(f)));
upb_sink_startsubmsg(sink, getsel(f, UPB_HANDLER_STARTSUBMSG), &subsink);
- putmsg(submsg, subdesc, &subsink, depth + 1 TSRMLS_CC);
+ putrawmsg(submsg, subdesc, &subsink, depth + 1 TSRMLS_CC);
upb_sink_endsubmsg(sink, getsel(f, UPB_HANDLER_ENDSUBMSG));
}
@@ -1147,9 +1399,10 @@ static void putarray(zval* array, const upb_fielddef* f, upb_sink* sink,
int size, i;
assert(array != NULL);
- RepeatedField* intern =
- (RepeatedField*)zend_object_store_get_object(array TSRMLS_CC);
- size = zend_hash_num_elements(HASH_OF(intern->array));
+ RepeatedField* intern = UNBOX(RepeatedField, array);
+ HashTable *ht = PHP_PROTO_HASH_OF(intern->array);
+ size = zend_hash_num_elements(ht);
+ // size = zend_hash_num_elements(PHP_PROTO_HASH_OF(intern->array));
if (size == 0) return;
upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
@@ -1176,12 +1429,28 @@ static void putarray(zval* array, const upb_fielddef* f, upb_sink* sink,
T(UPB_TYPE_UINT64, uint64, uint64_t)
case UPB_TYPE_STRING:
- case UPB_TYPE_BYTES:
- putstr(*((zval**)memory), f, &subsink);
+ case UPB_TYPE_BYTES: {
+#if PHP_MAJOR_VERSION < 7
+ const char* rawstr = Z_STRVAL_P(*(zval**)memory);
+ int len = Z_STRLEN_P(*(zval**)memory);
+#else
+ const char* rawstr = ZSTR_VAL(*(zend_string**)memory);
+ int len = ZSTR_LEN(*(zend_string**)memory);
+#endif
+ putrawstr(rawstr, len, f, &subsink);
break;
- case UPB_TYPE_MESSAGE:
- putsubmsg(*((zval**)memory), f, &subsink, depth TSRMLS_CC);
+ }
+ case UPB_TYPE_MESSAGE: {
+#if PHP_MAJOR_VERSION < 7
+ MessageHeader *submsg = UNBOX(MessageHeader, *(zval**)memory);
+#else
+ MessageHeader *submsg =
+ (MessageHeader*)((char*)(Z_OBJ_P((zval*)memory)) -
+ XtOffsetOf(MessageHeader, std));
+#endif
+ putrawsubmsg(submsg, f, &subsink, depth TSRMLS_CC);
break;
+ }
#undef T
}
@@ -1197,14 +1466,32 @@ static const upb_handlers* msgdef_pb_serialize_handlers(Descriptor* desc) {
return desc->pb_serialize_handlers;
}
+static const upb_handlers* msgdef_json_serialize_handlers(
+ Descriptor* desc, bool preserve_proto_fieldnames) {
+ if (preserve_proto_fieldnames) {
+ if (desc->json_serialize_handlers == NULL) {
+ desc->json_serialize_handlers =
+ upb_json_printer_newhandlers(
+ desc->msgdef, true, &desc->json_serialize_handlers);
+ }
+ return desc->json_serialize_handlers;
+ } else {
+ if (desc->json_serialize_handlers_preserve == NULL) {
+ desc->json_serialize_handlers_preserve =
+ upb_json_printer_newhandlers(
+ desc->msgdef, false, &desc->json_serialize_handlers_preserve);
+ }
+ return desc->json_serialize_handlers_preserve;
+ }
+}
+
// -----------------------------------------------------------------------------
// PHP encode/decode methods
// -----------------------------------------------------------------------------
-PHP_METHOD(Message, encode) {
- zval* php_descriptor = get_ce_obj(Z_OBJCE_P(getThis()));
+void serialize_to_string(zval* val, zval* return_value TSRMLS_DC) {
Descriptor* desc =
- (Descriptor*)zend_object_store_get_object(php_descriptor TSRMLS_CC);
+ UNBOX_HASHTABLE_VALUE(Descriptor, get_ce_obj(Z_OBJCE_P(val)));
stringsink sink;
stringsink_init(&sink);
@@ -1218,39 +1505,111 @@ PHP_METHOD(Message, encode) {
stackenv_init(&se, "Error occurred during encoding: %s");
encoder = upb_pb_encoder_create(&se.env, serialize_handlers, &sink.sink);
- putmsg(getThis(), desc, upb_pb_encoder_input(encoder), 0 TSRMLS_CC);
+ putmsg(val, desc, upb_pb_encoder_input(encoder), 0 TSRMLS_CC);
- RETVAL_STRINGL(sink.ptr, sink.len, 1);
+ PHP_PROTO_RETVAL_STRINGL(sink.ptr, sink.len, 1);
stackenv_uninit(&se);
stringsink_uninit(&sink);
}
}
-PHP_METHOD(Message, decode) {
- zval* php_descriptor = get_ce_obj(Z_OBJCE_P(getThis()));
+PHP_METHOD(Message, serializeToString) {
+ serialize_to_string(getThis(), return_value TSRMLS_CC);
+}
+
+void merge_from_string(const char* data, int data_len, const Descriptor* desc,
+ MessageHeader* msg) {
+ const upb_pbdecodermethod* method = msgdef_decodermethod(desc);
+ const upb_handlers* h = upb_pbdecodermethod_desthandlers(method);
+ stackenv se;
+ upb_sink sink;
+ upb_pbdecoder* decoder;
+ stackenv_init(&se, "Error occurred during parsing: %s");
+
+ upb_sink_reset(&sink, h, msg);
+ decoder = upb_pbdecoder_create(&se.env, method, &sink);
+ upb_bufsrc_putbuf(data, data_len, upb_pbdecoder_input(decoder));
+
+ stackenv_uninit(&se);
+}
+
+PHP_METHOD(Message, mergeFromString) {
Descriptor* desc =
- (Descriptor*)zend_object_store_get_object(php_descriptor TSRMLS_CC);
- MessageHeader* msg = zend_object_store_get_object(getThis() TSRMLS_CC);
+ UNBOX_HASHTABLE_VALUE(Descriptor, get_ce_obj(Z_OBJCE_P(getThis())));
+ MessageHeader* msg = UNBOX(MessageHeader, getThis());
char *data = NULL;
- int data_len;
+ PHP_PROTO_SIZE data_len;
+
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &data, &data_len) ==
FAILURE) {
return;
}
+ merge_from_string(data, data_len, desc, msg);
+}
+
+PHP_METHOD(Message, serializeToJsonString) {
+ Descriptor* desc =
+ UNBOX_HASHTABLE_VALUE(Descriptor, get_ce_obj(Z_OBJCE_P(getThis())));
+
+ zend_bool preserve_proto_fieldnames = false;
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b",
+ &preserve_proto_fieldnames) == FAILURE) {
+ return;
+ }
+
+ stringsink sink;
+ stringsink_init(&sink);
+
+ {
+ const upb_handlers* serialize_handlers =
+ msgdef_json_serialize_handlers(desc, preserve_proto_fieldnames);
+ upb_json_printer* printer;
+ stackenv se;
+
+ stackenv_init(&se, "Error occurred during encoding: %s");
+ printer = upb_json_printer_create(&se.env, serialize_handlers, &sink.sink);
+
+ putmsg(getThis(), desc, upb_json_printer_input(printer), 0 TSRMLS_CC);
+
+ PHP_PROTO_RETVAL_STRINGL(sink.ptr, sink.len, 1);
+
+ stackenv_uninit(&se);
+ stringsink_uninit(&sink);
+ }
+}
+
+PHP_METHOD(Message, mergeFromJsonString) {
+ Descriptor* desc =
+ UNBOX_HASHTABLE_VALUE(Descriptor, get_ce_obj(Z_OBJCE_P(getThis())));
+ MessageHeader* msg = UNBOX(MessageHeader, getThis());
+
+ char *data = NULL;
+ PHP_PROTO_SIZE data_len;
+
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &data, &data_len) ==
+ FAILURE) {
+ return;
+ }
+
+ // TODO(teboring): Check and respect string encoding. If not UTF-8, we need to
+ // convert, because string handlers pass data directly to message string
+ // fields.
+
+ // TODO(teboring): Clear message.
+
{
- const upb_pbdecodermethod* method = msgdef_decodermethod(desc);
- const upb_handlers* h = upb_pbdecodermethod_desthandlers(method);
+ const upb_json_parsermethod* method = msgdef_jsonparsermethod(desc);
stackenv se;
upb_sink sink;
- upb_pbdecoder* decoder;
+ upb_json_parser* parser;
stackenv_init(&se, "Error occurred during parsing: %s");
- upb_sink_reset(&sink, h, msg);
- decoder = upb_pbdecoder_create(&se.env, method, &sink);
- upb_bufsrc_putbuf(data, data_len, upb_pbdecoder_input(decoder));
+ upb_sink_reset(&sink, get_fill_handlers(desc), msg);
+ parser = upb_json_parser_create(&se.env, method, &sink);
+ upb_bufsrc_putbuf(data, data_len, upb_json_parser_input(parser));
stackenv_uninit(&se);
}
diff --git a/php/ext/google/protobuf/map.c b/php/ext/google/protobuf/map.c
index 35747b05..2680b547 100644
--- a/php/ext/google/protobuf/map.c
+++ b/php/ext/google/protobuf/map.c
@@ -103,16 +103,16 @@ static bool table_key(Map* self, zval* key,
*out_length = Z_STRLEN_P(key);
break;
-#define CASE_TYPE(upb_type, type, c_type, php_type) \
- case UPB_TYPE_##upb_type: { \
- c_type type##_value; \
- if (!protobuf_convert_to_##type(key, &type##_value)) { \
- return false; \
- } \
- native_slot_set(self->key_type, NULL, buf, key TSRMLS_CC); \
- *out_key = buf; \
- *out_length = native_slot_size(self->key_type); \
- break; \
+#define CASE_TYPE(upb_type, type, c_type, php_type) \
+ case UPB_TYPE_##upb_type: { \
+ c_type type##_value; \
+ if (!protobuf_convert_to_##type(key, &type##_value)) { \
+ return false; \
+ } \
+ native_slot_set_by_array(self->key_type, NULL, buf, key TSRMLS_CC); \
+ *out_key = buf; \
+ *out_length = native_slot_size(self->key_type); \
+ break; \
}
CASE_TYPE(BOOL, bool, int8_t, BOOL)
CASE_TYPE(INT32, int32, int32_t, LONG)
@@ -143,23 +143,31 @@ static zend_function_entry map_field_methods[] = {
PHP_ME(MapField, offsetSet, arginfo_offsetSet, ZEND_ACC_PUBLIC)
PHP_ME(MapField, offsetUnset, arginfo_offsetGet, ZEND_ACC_PUBLIC)
PHP_ME(MapField, count, arginfo_void, ZEND_ACC_PUBLIC)
+ PHP_ME(MapField, getIterator, arginfo_void, ZEND_ACC_PUBLIC)
ZEND_FE_END
};
+// Forward declare static functions.
+
+static void map_field_write_dimension(zval *object, zval *key,
+ zval *value TSRMLS_DC);
+
// -----------------------------------------------------------------------------
// MapField creation/desctruction
// -----------------------------------------------------------------------------
zend_class_entry* map_field_type;
+zend_class_entry* map_field_iter_type;
+
zend_object_handlers* map_field_handlers;
+zend_object_handlers* map_field_iter_handlers;
static void map_begin_internal(Map *map, MapIter *iter) {
iter->self = map;
upb_strtable_begin(&iter->it, &map->table);
}
-static HashTable *map_field_get_gc(zval *object, zval ***table,
- int *n TSRMLS_DC) {
+static HashTable *map_field_get_gc(zval *object, CACHED_VALUE **table, int *n) {
// TODO(teboring): Unfortunately, zend engine does not support garbage
// collection for custom array. We have to use zend engine's native array
// instead.
@@ -168,91 +176,92 @@ static HashTable *map_field_get_gc(zval *object, zval ***table,
return NULL;
}
-void map_field_init(TSRMLS_D) {
- zend_class_entry class_type;
- const char* class_name = "Google\\Protobuf\\Internal\\MapField";
- INIT_CLASS_ENTRY_EX(class_type, class_name, strlen(class_name),
- map_field_methods);
-
- map_field_type = zend_register_internal_class(&class_type TSRMLS_CC);
- map_field_type->create_object = map_field_create;
-
- zend_class_implements(map_field_type TSRMLS_CC, 2, spl_ce_ArrayAccess,
- spl_ce_Countable);
-
- map_field_handlers = PEMALLOC(zend_object_handlers);
- memcpy(map_field_handlers, zend_get_std_object_handlers(),
- sizeof(zend_object_handlers));
- map_field_handlers->get_gc = map_field_get_gc;
+// Define map value element free function.
+#if PHP_MAJOR_VERSION < 7
+static inline void php_proto_map_string_release(void *value) {
+ zval_ptr_dtor(value);
}
-zend_object_value map_field_create(zend_class_entry *ce TSRMLS_DC) {
- zend_object_value retval = {0};
- Map *intern;
-
- intern = emalloc(sizeof(Map));
- memset(intern, 0, sizeof(Map));
-
- zend_object_std_init(&intern->std, ce TSRMLS_CC);
- object_properties_init(&intern->std, ce);
-
- // Table value type is always UINT64: this ensures enough space to store the
- // native_slot value.
- if (!upb_strtable_init(&intern->table, UPB_CTYPE_UINT64)) {
- zend_error(E_USER_ERROR, "Could not allocate table.");
+static inline void php_proto_map_object_release(void *value) {
+ zval_ptr_dtor(value);
+}
+#else
+static inline void php_proto_map_string_release(void *value) {
+ zend_string* object = *(zend_string**)value;
+ zend_string_release(object);
+}
+static inline void php_proto_map_object_release(void *value) {
+ zend_object* object = *(zend_object**)value;
+ if(--GC_REFCOUNT(object) == 0) {
+ zend_objects_store_del(object);
}
-
- retval.handle = zend_objects_store_put(
- intern, (zend_objects_store_dtor_t)zend_objects_destroy_object,
- (zend_objects_free_object_storage_t)map_field_free, NULL TSRMLS_CC);
- retval.handlers = map_field_handlers;
-
- return retval;
}
+#endif
-void map_field_free(void *object TSRMLS_DC) {
- Map *map = (Map *)object;
-
- switch (map->value_type) {
+// Define object free method.
+PHP_PROTO_OBJECT_FREE_START(Map, map_field)
+MapIter it;
+int len;
+for (map_begin_internal(intern, &it); !map_done(&it); map_next(&it)) {
+ upb_value value = map_iter_value(&it, &len);
+ void *mem = upb_value_memory(&value);
+ switch (intern->value_type) {
case UPB_TYPE_MESSAGE:
+ php_proto_map_object_release(mem);
+ break;
case UPB_TYPE_STRING:
- case UPB_TYPE_BYTES: {
- MapIter it;
- int len;
- for (map_begin_internal(map, &it); !map_done(&it); map_next(&it)) {
- upb_value value = map_iter_value(&it, &len);
- void *mem = upb_value_memory(&value);
- zval_ptr_dtor(mem);
- }
+ case UPB_TYPE_BYTES:
+ php_proto_map_string_release(mem);
break;
- }
default:
break;
}
-
- upb_strtable_uninit(&map->table);
- zend_object_std_dtor(&map->std TSRMLS_CC);
- efree(object);
}
-
-void map_field_create_with_type(zend_class_entry *ce, const upb_fielddef *field,
- zval **map_field TSRMLS_DC) {
- MAKE_STD_ZVAL(*map_field);
- Z_TYPE_PP(map_field) = IS_OBJECT;
- Z_OBJVAL_PP(map_field) =
- map_field_type->create_object(map_field_type TSRMLS_CC);
-
- Map* intern =
- (Map*)zend_object_store_get_object(*map_field TSRMLS_CC);
-
+upb_strtable_uninit(&intern->table);
+PHP_PROTO_OBJECT_FREE_END
+
+PHP_PROTO_OBJECT_DTOR_START(Map, map_field)
+PHP_PROTO_OBJECT_DTOR_END
+
+// Define object create method.
+PHP_PROTO_OBJECT_CREATE_START(Map, map_field)
+// Table value type is always UINT64: this ensures enough space to store the
+// native_slot value.
+if (!upb_strtable_init(&intern->table, UPB_CTYPE_UINT64)) {
+ zend_error(E_USER_ERROR, "Could not allocate table.");
+}
+PHP_PROTO_OBJECT_CREATE_END(Map, map_field)
+
+// Init class entry.
+PHP_PROTO_INIT_CLASS_START("Google\\Protobuf\\Internal\\MapField", Map,
+ map_field)
+zend_class_implements(map_field_type TSRMLS_CC, 3, spl_ce_ArrayAccess,
+ zend_ce_aggregate, spl_ce_Countable);
+map_field_handlers->write_dimension = map_field_write_dimension;
+map_field_handlers->get_gc = map_field_get_gc;
+PHP_PROTO_INIT_CLASS_END
+
+void map_field_create_with_field(const zend_class_entry *ce,
+ const upb_fielddef *field,
+ CACHED_VALUE *map_field PHP_PROTO_TSRMLS_DC) {
const upb_fielddef *key_field = map_field_key(field);
const upb_fielddef *value_field = map_field_value(field);
- intern->key_type = upb_fielddef_type(key_field);
- intern->value_type = upb_fielddef_type(value_field);
- intern->msg_ce = field_type_class(value_field TSRMLS_CC);
+ map_field_create_with_type(
+ ce, upb_fielddef_type(key_field), upb_fielddef_type(value_field),
+ field_type_class(value_field TSRMLS_CC), map_field PHP_PROTO_TSRMLS_CC);
}
-static void map_field_free_element(void *object) {
+void map_field_create_with_type(const zend_class_entry *ce,
+ upb_fieldtype_t key_type,
+ upb_fieldtype_t value_type,
+ const zend_class_entry *msg_ce,
+ CACHED_VALUE *map_field PHP_PROTO_TSRMLS_DC) {
+ CREATE_OBJ_ON_ALLOCATED_ZVAL_PTR(CACHED_PTR_TO_ZVAL_PTR(map_field),
+ map_field_type);
+ Map *intern = UNBOX(Map, CACHED_TO_ZVAL_PTR(*map_field));
+ intern->key_type = key_type;
+ intern->value_type = value_type;
+ intern->msg_ce = msg_ce;
}
// -----------------------------------------------------------------------------
@@ -260,9 +269,8 @@ static void map_field_free_element(void *object) {
// -----------------------------------------------------------------------------
static bool map_field_read_dimension(zval *object, zval *key, int type,
- zval **retval TSRMLS_DC) {
- Map *intern =
- (Map *)zend_object_store_get_object(object TSRMLS_CC);
+ CACHED_VALUE *retval TSRMLS_DC) {
+ Map *intern = UNBOX(Map, object);
char keybuf[TABLE_KEY_BUF_LENGTH];
const char* keyval = NULL;
@@ -277,7 +285,7 @@ static bool map_field_read_dimension(zval *object, zval *key, int type,
if (upb_strtable_lookup2(&intern->table, keyval, length, &v)) {
void* mem = upb_value_memory(&v);
- native_slot_get(intern->value_type, mem, retval TSRMLS_CC);
+ native_slot_get_by_map_value(intern->value_type, mem, retval TSRMLS_CC);
return true;
} else {
zend_error(E_USER_ERROR, "Given key doesn't exist.");
@@ -295,9 +303,9 @@ bool map_index_set(Map *intern, const char* keyval, int length, upb_value v) {
return true;
}
-static bool map_field_write_dimension(zval *object, zval *key,
+static void map_field_write_dimension(zval *object, zval *key,
zval *value TSRMLS_DC) {
- Map *intern = (Map *)zend_object_store_get_object(object TSRMLS_CC);
+ Map *intern = UNBOX(Map, object);
char keybuf[TABLE_KEY_BUF_LENGTH];
const char* keyval = NULL;
@@ -305,14 +313,14 @@ static bool map_field_write_dimension(zval *object, zval *key,
upb_value v;
void* mem;
if (!table_key(intern, key, keybuf, &keyval, &length TSRMLS_CC)) {
- return false;
+ return;
}
mem = upb_value_memory(&v);
memset(mem, 0, native_slot_size(intern->value_type));
- if (!native_slot_set(intern->value_type, intern->msg_ce, mem, value
- TSRMLS_CC)) {
- return false;
+ if (!native_slot_set_by_map(intern->value_type, intern->msg_ce, mem,
+ value TSRMLS_CC)) {
+ return;
}
#ifndef NDEBUG
v.ctype = UPB_CTYPE_UINT64;
@@ -322,14 +330,12 @@ static bool map_field_write_dimension(zval *object, zval *key,
upb_strtable_remove2(&intern->table, keyval, length, NULL);
if (!upb_strtable_insert2(&intern->table, keyval, length, v)) {
zend_error(E_USER_ERROR, "Could not insert into table");
- return false;
+ return;
}
-
- return true;
}
static bool map_field_unset_dimension(zval *object, zval *key TSRMLS_DC) {
- Map *intern = (Map *)zend_object_store_get_object(object TSRMLS_CC);
+ Map *intern = UNBOX(Map, object);
char keybuf[TABLE_KEY_BUF_LENGTH];
const char* keyval = NULL;
@@ -360,8 +366,7 @@ PHP_METHOD(MapField, __construct) {
return;
}
- Map* intern =
- (Map*)zend_object_store_get_object(getThis() TSRMLS_CC);
+ Map *intern = UNBOX(Map, getThis());
intern->key_type = to_fieldtype(key_type);
intern->value_type = to_fieldtype(value_type);
intern->msg_ce = klass;
@@ -389,7 +394,7 @@ PHP_METHOD(MapField, offsetExists) {
return;
}
- Map *intern = (Map *)zend_object_store_get_object(getThis() TSRMLS_CC);
+ Map *intern = UNBOX(Map, getThis());
char keybuf[TABLE_KEY_BUF_LENGTH];
const char* keyval = NULL;
@@ -412,7 +417,7 @@ PHP_METHOD(MapField, offsetGet) {
return;
}
map_field_read_dimension(getThis(), index, BP_VAR_R,
- return_value_ptr TSRMLS_CC);
+ ZVAL_PTR_TO_CACHED_PTR(return_value) TSRMLS_CC);
}
PHP_METHOD(MapField, offsetSet) {
@@ -434,8 +439,7 @@ PHP_METHOD(MapField, offsetUnset) {
}
PHP_METHOD(MapField, count) {
- Map *intern =
- (Map *)zend_object_store_get_object(getThis() TSRMLS_CC);
+ Map *intern = UNBOX(Map, getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
@@ -444,6 +448,15 @@ PHP_METHOD(MapField, count) {
RETURN_LONG(upb_strtable_count(&intern->table));
}
+PHP_METHOD(MapField, getIterator) {
+ CREATE_OBJ_ON_ALLOCATED_ZVAL_PTR(return_value,
+ map_field_iter_type);
+
+ Map *intern = UNBOX(Map, getThis());
+ MapIter *iter = UNBOX(MapIter, return_value);
+ map_begin(getThis(), iter TSRMLS_CC);
+}
+
// -----------------------------------------------------------------------------
// Map Iterator
// -----------------------------------------------------------------------------
@@ -470,3 +483,79 @@ upb_value map_iter_value(MapIter *iter, int *len) {
*len = native_slot_size(iter->self->value_type);
return upb_strtable_iter_value(&iter->it);
}
+
+// -----------------------------------------------------------------------------
+// MapFieldIter methods
+// -----------------------------------------------------------------------------
+static zend_function_entry map_field_iter_methods[] = {
+ PHP_ME(MapFieldIter, rewind, arginfo_void, ZEND_ACC_PUBLIC)
+ PHP_ME(MapFieldIter, current, arginfo_void, ZEND_ACC_PUBLIC)
+ PHP_ME(MapFieldIter, key, arginfo_void, ZEND_ACC_PUBLIC)
+ PHP_ME(MapFieldIter, next, arginfo_void, ZEND_ACC_PUBLIC)
+ PHP_ME(MapFieldIter, valid, arginfo_void, ZEND_ACC_PUBLIC)
+ ZEND_FE_END
+};
+
+// -----------------------------------------------------------------------------
+// MapFieldIter creation/desctruction
+// -----------------------------------------------------------------------------
+
+// Define object free method.
+PHP_PROTO_OBJECT_FREE_START(MapIter, map_field_iter)
+PHP_PROTO_OBJECT_FREE_END
+
+PHP_PROTO_OBJECT_DTOR_START(MapIter, map_field_iter)
+PHP_PROTO_OBJECT_DTOR_END
+
+// Define object create method.
+PHP_PROTO_OBJECT_CREATE_START(MapIter, map_field_iter)
+intern->self = NULL;
+PHP_PROTO_OBJECT_CREATE_END(MapIter, map_field_iter)
+
+// Init class entry.
+PHP_PROTO_INIT_CLASS_START("Google\\Protobuf\\Internal\\MapFieldIter",
+ MapIter, map_field_iter)
+zend_class_implements(map_field_iter_type TSRMLS_CC, 1, zend_ce_iterator);
+PHP_PROTO_INIT_CLASS_END
+
+// -----------------------------------------------------------------------------
+// PHP MapFieldIter Methods
+// -----------------------------------------------------------------------------
+
+PHP_METHOD(MapFieldIter, rewind) {
+ MapIter *intern = UNBOX(MapIter, getThis());
+ map_begin_internal(intern->self, intern);
+}
+
+PHP_METHOD(MapFieldIter, current) {
+ MapIter *intern = UNBOX(MapIter, getThis());
+ Map *map_field = intern->self;
+
+ int value_length = 0;
+ upb_value value = map_iter_value(intern, &value_length);
+
+ void* mem = upb_value_memory(&value);
+ native_slot_get_by_map_value(map_field->value_type, mem,
+ ZVAL_PTR_TO_CACHED_PTR(return_value) TSRMLS_CC);
+}
+
+PHP_METHOD(MapFieldIter, key) {
+ MapIter *intern = UNBOX(MapIter, getThis());
+ Map *map_field = intern->self;
+
+ int key_length = 0;
+ const char* key = map_iter_key(intern, &key_length);
+
+ native_slot_get_by_map_key(map_field->key_type, key, key_length,
+ ZVAL_PTR_TO_CACHED_PTR(return_value) TSRMLS_CC);
+}
+
+PHP_METHOD(MapFieldIter, next) {
+ MapIter *intern = UNBOX(MapIter, getThis());
+ map_next(intern);
+}
+
+PHP_METHOD(MapFieldIter, valid) {
+ MapIter *intern = UNBOX(MapIter, getThis());
+ RETURN_BOOL(!map_done(intern));
+}
diff --git a/php/ext/google/protobuf/message.c b/php/ext/google/protobuf/message.c
index 16e397f5..3fce2c17 100644
--- a/php/ext/google/protobuf/message.c
+++ b/php/ext/google/protobuf/message.c
@@ -29,117 +29,207 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <php.h>
+#include <ext/date/php_date.h>
#include <stdlib.h>
#include "protobuf.h"
+#include "utf8.h"
-static zend_class_entry* message_type;
+zend_class_entry* message_type;
zend_object_handlers* message_handlers;
+static const char TYPE_URL_PREFIX[] = "type.googleapis.com/";
+static void hex_to_binary(const char* hex, char** binary, int* binary_len);
static zend_function_entry message_methods[] = {
- PHP_ME(Message, encode, NULL, ZEND_ACC_PUBLIC)
- PHP_ME(Message, decode, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Message, clear, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Message, serializeToString, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Message, mergeFromString, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Message, serializeToJsonString, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Message, mergeFromJsonString, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Message, mergeFrom, NULL, ZEND_ACC_PUBLIC)
PHP_ME(Message, readOneof, NULL, ZEND_ACC_PROTECTED)
PHP_ME(Message, writeOneof, NULL, ZEND_ACC_PROTECTED)
+ PHP_ME(Message, whichOneof, NULL, ZEND_ACC_PROTECTED)
PHP_ME(Message, __construct, NULL, ZEND_ACC_PROTECTED)
{NULL, NULL, NULL}
};
// Forward declare static functions.
+#if PHP_MAJOR_VERSION < 7
static void message_set_property(zval* object, zval* member, zval* value,
- const zend_literal* key TSRMLS_DC);
+ php_proto_zend_literal key TSRMLS_DC);
static zval* message_get_property(zval* object, zval* member, int type,
const zend_literal* key TSRMLS_DC);
static zval** message_get_property_ptr_ptr(zval* object, zval* member, int type,
- const zend_literal* key TSRMLS_DC);
-
-static zend_object_value message_create(zend_class_entry* ce TSRMLS_DC);
-static void message_free(void* object TSRMLS_DC);
+ php_proto_zend_literal key TSRMLS_DC);
+static HashTable* message_get_gc(zval* object, zval*** table, int* n TSRMLS_DC);
+#else
+static void message_set_property(zval* object, zval* member, zval* value,
+ void** cache_slot);
+static zval* message_get_property(zval* object, zval* member, int type,
+ void** cache_slot, zval* rv);
+static zval* message_get_property_ptr_ptr(zval* object, zval* member, int type,
+ void** cache_slot);
+static HashTable* message_get_gc(zval* object, zval** table, int* n);
+#endif
+static HashTable* message_get_properties(zval* object TSRMLS_DC);
// -----------------------------------------------------------------------------
// PHP Message Handlers
// -----------------------------------------------------------------------------
-void message_init(TSRMLS_D) {
- zend_class_entry class_type;
- INIT_CLASS_ENTRY(class_type, "Google\\Protobuf\\Internal\\Message",
- message_methods);
- message_type = zend_register_internal_class(&class_type TSRMLS_CC);
+// Define object free method.
+PHP_PROTO_OBJECT_FREE_START(MessageHeader, message)
+ if (*(void**)intern->data != NULL) {
+ stringsink_uninit(*(void**)intern->data);
+ FREE(*(void**)intern->data);
+ }
+ FREE(intern->data);
+PHP_PROTO_OBJECT_FREE_END
+
+PHP_PROTO_OBJECT_DTOR_START(MessageHeader, message)
+PHP_PROTO_OBJECT_DTOR_END
+
+// Define object create method.
+PHP_PROTO_OBJECT_CREATE_START(MessageHeader, message)
+// Because php call this create func before calling the sub-message's
+// constructor defined in PHP, it's possible that the decriptor of this class
+// hasn't been added to descritpor pool (when the class is first
+// instantiated). In that case, we will defer the initialization of the custom
+// data to the parent Message's constructor, which will be called by
+// sub-message's constructors after the descriptor has been added.
+PHP_PROTO_OBJECT_CREATE_END(MessageHeader, message)
- message_handlers = PEMALLOC(zend_object_handlers);
- memcpy(message_handlers, zend_get_std_object_handlers(),
- sizeof(zend_object_handlers));
+// Init class entry.
+PHP_PROTO_INIT_CLASS_START("Google\\Protobuf\\Internal\\Message",
+ MessageHeader, message)
message_handlers->write_property = message_set_property;
message_handlers->read_property = message_get_property;
message_handlers->get_property_ptr_ptr = message_get_property_ptr_ptr;
+ message_handlers->get_properties = message_get_properties;
+ message_handlers->get_gc = message_get_gc;
+PHP_PROTO_INIT_CLASS_END
+
+static void message_set_property_internal(zval* object, zval* member,
+ zval* value TSRMLS_DC) {
+ const upb_fielddef* field;
+
+ MessageHeader* self = UNBOX(MessageHeader, object);
+
+ field = upb_msgdef_ntofz(self->descriptor->msgdef, Z_STRVAL_P(member));
+ if (field == NULL) {
+ zend_error(E_USER_ERROR, "Unknown field: %s", Z_STRVAL_P(member));
+ }
+
+ layout_set(self->descriptor->layout, self, field, value TSRMLS_CC);
}
+#if PHP_MAJOR_VERSION < 7
static void message_set_property(zval* object, zval* member, zval* value,
- const zend_literal* key TSRMLS_DC) {
+ php_proto_zend_literal key TSRMLS_DC) {
+#else
+static void message_set_property(zval* object, zval* member, zval* value,
+ void** cache_slot) {
+#endif
if (Z_TYPE_P(member) != IS_STRING) {
zend_error(E_USER_ERROR, "Unexpected type for field name");
return;
}
+#if PHP_MAJOR_VERSION < 7 || (PHP_MAJOR_VERSION == 7 && PHP_MINOR_VERSION == 0)
if (Z_OBJCE_P(object) != EG(scope)) {
+#else
+ if (Z_OBJCE_P(object) != zend_get_executed_scope()) {
+#endif
// User cannot set property directly (e.g., $m->a = 1)
zend_error(E_USER_ERROR, "Cannot access private property.");
return;
}
+ message_set_property_internal(object, member, value TSRMLS_CC);
+}
+
+static zval* message_get_property_internal(zval* object,
+ zval* member TSRMLS_DC) {
+ MessageHeader* self = UNBOX(MessageHeader, object);
const upb_fielddef* field;
+ field = upb_msgdef_ntofz(self->descriptor->msgdef, Z_STRVAL_P(member));
+ if (field == NULL) {
+ return PHP_PROTO_GLOBAL_UNINITIALIZED_ZVAL;
+ }
- MessageHeader* self = zend_object_store_get_object(object TSRMLS_CC);
+ zend_property_info* property_info;
+#if PHP_MAJOR_VERSION < 7
+ property_info =
+ zend_get_property_info(Z_OBJCE_P(object), member, true TSRMLS_CC);
+#else
+ property_info =
+ zend_get_property_info(Z_OBJCE_P(object), Z_STR_P(member), true);
+#endif
+ return layout_get(
+ self->descriptor->layout, message_data(self), field,
+ OBJ_PROP(Z_OBJ_P(object), property_info->offset) TSRMLS_CC);
+}
+static void message_get_oneof_property_internal(zval* object, zval* member,
+ zval* return_value TSRMLS_DC) {
+ MessageHeader* self = UNBOX(MessageHeader, object);
+ const upb_fielddef* field;
field = upb_msgdef_ntofz(self->descriptor->msgdef, Z_STRVAL_P(member));
if (field == NULL) {
- zend_error(E_USER_ERROR, "Unknown field: %s", Z_STRVAL_P(member));
+ return;
}
- layout_set(self->descriptor->layout, self, field, value TSRMLS_CC);
+ layout_get(self->descriptor->layout, message_data(self), field,
+ ZVAL_PTR_TO_CACHED_PTR(return_value) TSRMLS_CC);
}
+#if PHP_MAJOR_VERSION < 7
static zval* message_get_property(zval* object, zval* member, int type,
const zend_literal* key TSRMLS_DC) {
+#else
+static zval* message_get_property(zval* object, zval* member, int type,
+ void** cache_slot, zval* rv) {
+#endif
if (Z_TYPE_P(member) != IS_STRING) {
zend_error(E_USER_ERROR, "Property name has to be a string.");
- return EG(uninitialized_zval_ptr);
+ return PHP_PROTO_GLOBAL_UNINITIALIZED_ZVAL;
}
+#if PHP_MAJOR_VERSION < 7 || (PHP_MAJOR_VERSION == 7 && PHP_MINOR_VERSION == 0)
if (Z_OBJCE_P(object) != EG(scope)) {
+#else
+ if (Z_OBJCE_P(object) != zend_get_executed_scope()) {
+#endif
// User cannot get property directly (e.g., $a = $m->a)
zend_error(E_USER_ERROR, "Cannot access private property.");
- return EG(uninitialized_zval_ptr);
+ return PHP_PROTO_GLOBAL_UNINITIALIZED_ZVAL;
}
- zend_property_info* property_info = NULL;
-
- // All properties should have been declared in the generated code and have
- // corresponding zvals in properties_table.
- ulong h = zend_get_hash_value(Z_STRVAL_P(member), Z_STRLEN_P(member) + 1);
- if (zend_hash_quick_find(&Z_OBJCE_P(object)->properties_info,
- Z_STRVAL_P(member), Z_STRLEN_P(member) + 1, h,
- (void**)&property_info) != SUCCESS) {
- zend_error(E_USER_ERROR, "Property does not exist.");
- return EG(uninitialized_zval_ptr);
- }
+ return message_get_property_internal(object, member TSRMLS_CC);
+}
- MessageHeader* self =
- (MessageHeader*)zend_object_store_get_object(object TSRMLS_CC);
+#if PHP_MAJOR_VERSION < 7
+static zval** message_get_property_ptr_ptr(zval* object, zval* member, int type,
+ php_proto_zend_literal key
+ TSRMLS_DC) {
+#else
+static zval* message_get_property_ptr_ptr(zval* object, zval* member, int type,
+ void** cache_slot) {
+#endif
+ return NULL;
+}
- const upb_fielddef* field;
- field = upb_msgdef_ntofz(self->descriptor->msgdef, Z_STRVAL_P(member));
- if (field == NULL) {
- return EG(uninitialized_zval_ptr);
- }
- return layout_get(
- self->descriptor->layout, message_data(self), field,
- &Z_OBJ_P(object)->properties_table[property_info->offset] TSRMLS_CC);
+static HashTable* message_get_properties(zval* object TSRMLS_DC) {
+ return NULL;
}
-static zval** message_get_property_ptr_ptr(zval* object, zval* member, int type,
- const zend_literal* key TSRMLS_DC) {
+static HashTable* message_get_gc(zval* object, CACHED_VALUE** table,
+ int* n TSRMLS_DC) {
+ zend_object* zobj = Z_OBJ_P(object);
+ *table = zobj->properties_table;
+ *n = zobj->ce->default_properties_count;
return NULL;
}
@@ -147,50 +237,25 @@ static zval** message_get_property_ptr_ptr(zval* object, zval* member, int type,
// C Message Utilities
// -----------------------------------------------------------------------------
-void* message_data(void* msg) {
- return ((uint8_t*)msg) + sizeof(MessageHeader);
+void* message_data(MessageHeader* msg) {
+ return msg->data;
}
-static void message_free(void* object TSRMLS_DC) {
- MessageHeader* msg = (MessageHeader*)object;
- int i;
-
- for (i = 0; i < msg->std.ce->default_properties_count; i++) {
- zval_ptr_dtor(&msg->std.properties_table[i]);
- }
- efree(msg->std.properties_table);
- efree(msg);
-}
-
-static zend_object_value message_create(zend_class_entry* ce TSRMLS_DC) {
- zend_object_value return_value;
-
- zval* php_descriptor = get_ce_obj(ce);
-
- Descriptor* desc = zend_object_store_get_object(php_descriptor TSRMLS_CC);
- MessageHeader* msg = (MessageHeader*)ALLOC_N(
- uint8_t, sizeof(MessageHeader) + desc->layout->size);
- memset(message_data(msg), 0, desc->layout->size);
-
+void custom_data_init(const zend_class_entry* ce,
+ MessageHeader* intern PHP_PROTO_TSRMLS_DC) {
+ Descriptor* desc = UNBOX_HASHTABLE_VALUE(Descriptor, get_ce_obj(ce));
+ intern->data = ALLOC_N(uint8_t, desc->layout->size);
+ memset(message_data(intern), 0, desc->layout->size);
// We wrap first so that everything in the message object is GC-rooted in
// case a collection happens during object creation in layout_init().
- msg->descriptor = desc;
-
- zend_object_std_init(&msg->std, ce TSRMLS_CC);
- object_properties_init(&msg->std, ce);
- layout_init(desc->layout, message_data(msg),
- msg->std.properties_table TSRMLS_CC);
-
- return_value.handle = zend_objects_store_put(
- msg, (zend_objects_store_dtor_t)zend_objects_destroy_object, message_free,
- NULL TSRMLS_CC);
-
- return_value.handlers = message_handlers;
- return return_value;
+ intern->descriptor = desc;
+ layout_init(desc->layout, message_data(intern),
+ &intern->std PHP_PROTO_TSRMLS_CC);
}
-void build_class_from_descriptor(zval* php_descriptor TSRMLS_DC) {
- Descriptor* desc = UNBOX(Descriptor, php_descriptor);
+void build_class_from_descriptor(
+ PHP_PROTO_HASHTABLE_VALUE php_descriptor TSRMLS_DC) {
+ Descriptor* desc = UNBOX_HASHTABLE_VALUE(Descriptor, php_descriptor);
// Map entries don't have existing php class.
if (upb_msgdef_mapentry(desc->msgdef)) {
@@ -215,46 +280,1794 @@ void build_class_from_descriptor(zval* php_descriptor TSRMLS_DC) {
// modified. As a result, the first created instance will be a normal zend
// object. Here, we manually modify it to our message in such a case.
PHP_METHOD(Message, __construct) {
- if (Z_OBJVAL_P(getThis()).handlers != message_handlers) {
- zend_class_entry* ce = Z_OBJCE_P(getThis());
- zval_dtor(getThis());
- Z_OBJVAL_P(getThis()) = message_create(ce TSRMLS_CC);
+ zend_class_entry* ce = Z_OBJCE_P(getThis());
+ if (EXPECTED(class_added(ce))) {
+ MessageHeader* intern = UNBOX(MessageHeader, getThis());
+ custom_data_init(ce, intern PHP_PROTO_TSRMLS_CC);
}
}
+PHP_METHOD(Message, clear) {
+ MessageHeader* msg = UNBOX(MessageHeader, getThis());
+ Descriptor* desc = msg->descriptor;
+ zend_class_entry* ce = desc->klass;
+
+ object_properties_init(&msg->std, ce);
+ layout_init(desc->layout, message_data(msg), &msg->std TSRMLS_CC);
+}
+
+PHP_METHOD(Message, mergeFrom) {
+ zval* value;
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O", &value,
+ message_type) == FAILURE) {
+ return;
+ }
+
+ MessageHeader* from = UNBOX(MessageHeader, value);
+ MessageHeader* to = UNBOX(MessageHeader, getThis());
+
+ if(from->descriptor != to->descriptor) {
+ zend_error(E_USER_ERROR, "Cannot merge messages with different class.");
+ return;
+ }
+
+ layout_merge(from->descriptor->layout, from, to TSRMLS_CC);
+}
+
PHP_METHOD(Message, readOneof) {
- long index;
+ PHP_PROTO_LONG index;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &index) ==
FAILURE) {
return;
}
- MessageHeader* msg =
- (MessageHeader*)zend_object_store_get_object(getThis() TSRMLS_CC);
+ MessageHeader* msg = UNBOX(MessageHeader, getThis());
const upb_fielddef* field = upb_msgdef_itof(msg->descriptor->msgdef, index);
- int property_cache_index =
- msg->descriptor->layout->fields[upb_fielddef_index(field)].cache_index;
- zval** cache_ptr = &(msg->std.properties_table)[property_cache_index];
-
+ // Unlike singular fields, oneof fields share cached property. So we cannot
+ // let lay_get modify the cached property. Instead, we pass in the return
+ // value directly.
layout_get(msg->descriptor->layout, message_data(msg), field,
- &return_value TSRMLS_CC);
+ ZVAL_PTR_TO_CACHED_PTR(return_value) TSRMLS_CC);
}
PHP_METHOD(Message, writeOneof) {
- long index;
+ PHP_PROTO_LONG index;
zval* value;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "lz", &index, &value) ==
FAILURE) {
return;
}
- MessageHeader* msg =
- (MessageHeader*)zend_object_store_get_object(getThis() TSRMLS_CC);
+ MessageHeader* msg = UNBOX(MessageHeader, getThis());
const upb_fielddef* field = upb_msgdef_itof(msg->descriptor->msgdef, index);
layout_set(msg->descriptor->layout, msg, field, value TSRMLS_CC);
}
+
+PHP_METHOD(Message, whichOneof) {
+ char* oneof_name;
+ PHP_PROTO_SIZE length;
+
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &oneof_name,
+ &length) == FAILURE) {
+ return;
+ }
+
+ MessageHeader* msg = UNBOX(MessageHeader, getThis());
+
+ const upb_oneofdef* oneof =
+ upb_msgdef_ntoo(msg->descriptor->msgdef, oneof_name, length);
+ const char* oneof_case_name = layout_get_oneof_case(
+ msg->descriptor->layout, message_data(msg), oneof TSRMLS_CC);
+ PHP_PROTO_RETURN_STRING(oneof_case_name, 1);
+}
+
+// -----------------------------------------------------------------------------
+// Well Known Types Support
+// -----------------------------------------------------------------------------
+
+#define PHP_PROTO_FIELD_ACCESSORS(UPPER_CLASS, LOWER_CLASS, UPPER_FIELD, \
+ LOWER_FIELD) \
+ PHP_METHOD(UPPER_CLASS, get##UPPER_FIELD) { \
+ zval member; \
+ PHP_PROTO_ZVAL_STRING(&member, LOWER_FIELD, 1); \
+ PHP_PROTO_FAKE_SCOPE_BEGIN(LOWER_CLASS##_type); \
+ zval* value = message_get_property_internal(getThis(), &member TSRMLS_CC); \
+ PHP_PROTO_FAKE_SCOPE_END; \
+ PHP_PROTO_RETVAL_ZVAL(value); \
+ } \
+ PHP_METHOD(UPPER_CLASS, set##UPPER_FIELD) { \
+ zval* value = NULL; \
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &value) == \
+ FAILURE) { \
+ return; \
+ } \
+ zval member; \
+ PHP_PROTO_ZVAL_STRING(&member, LOWER_FIELD, 1); \
+ message_set_property_internal(getThis(), &member, value TSRMLS_CC); \
+ PHP_PROTO_RETVAL_ZVAL(getThis()); \
+ }
+
+#define PHP_PROTO_ONEOF_FIELD_ACCESSORS(UPPER_CLASS, LOWER_CLASS, UPPER_FIELD, \
+ LOWER_FIELD) \
+ PHP_METHOD(UPPER_CLASS, get##UPPER_FIELD) { \
+ zval member; \
+ PHP_PROTO_ZVAL_STRING(&member, LOWER_FIELD, 1); \
+ PHP_PROTO_FAKE_SCOPE_BEGIN(LOWER_CLASS##_type); \
+ message_get_oneof_property_internal(getThis(), &member, \
+ return_value TSRMLS_CC); \
+ PHP_PROTO_FAKE_SCOPE_END; \
+ } \
+ PHP_METHOD(UPPER_CLASS, set##UPPER_FIELD) { \
+ zval* value = NULL; \
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &value) == \
+ FAILURE) { \
+ return; \
+ } \
+ zval member; \
+ PHP_PROTO_ZVAL_STRING(&member, LOWER_FIELD, 1); \
+ message_set_property_internal(getThis(), &member, value TSRMLS_CC); \
+ PHP_PROTO_RETVAL_ZVAL(getThis()); \
+ }
+
+#define PHP_PROTO_ONEOF_ACCESSORS(UPPER_CLASS, LOWER_CLASS, UPPER_FIELD, \
+ LOWER_FIELD) \
+ PHP_METHOD(UPPER_CLASS, get##UPPER_FIELD) { \
+ MessageHeader* msg = UNBOX(MessageHeader, getThis()); \
+ PHP_PROTO_FAKE_SCOPE_BEGIN(LOWER_CLASS##_type); \
+ const upb_oneofdef* oneof = upb_msgdef_ntoo( \
+ msg->descriptor->msgdef, LOWER_FIELD, strlen(LOWER_FIELD)); \
+ const char* oneof_case_name = layout_get_oneof_case( \
+ msg->descriptor->layout, message_data(msg), oneof TSRMLS_CC); \
+ PHP_PROTO_FAKE_SCOPE_END; \
+ PHP_PROTO_RETURN_STRING(oneof_case_name, 1); \
+ }
+
+// Forward declare file init functions
+static void init_file_any(TSRMLS_D);
+static void init_file_api(TSRMLS_D);
+static void init_file_duration(TSRMLS_D);
+static void init_file_field_mask(TSRMLS_D);
+static void init_file_empty(TSRMLS_D);
+static void init_file_source_context(TSRMLS_D);
+static void init_file_struct(TSRMLS_D);
+static void init_file_timestamp(TSRMLS_D);
+static void init_file_type(TSRMLS_D);
+static void init_file_wrappers(TSRMLS_D);
+
+// Define file init functions
+static void init_file_any(TSRMLS_D) {
+ static bool is_initialized = false;
+ if (is_initialized) return;
+ init_generated_pool_once(TSRMLS_C);
+ const char* generated_file =
+ "0acd010a19676f6f676c652f70726f746f6275662f616e792e70726f746f"
+ "120f676f6f676c652e70726f746f62756622260a03416e7912100a087479"
+ "70655f75726c180120012809120d0a0576616c756518022001280c426f0a"
+ "13636f6d2e676f6f676c652e70726f746f6275664208416e7950726f746f"
+ "50015a256769746875622e636f6d2f676f6c616e672f70726f746f627566"
+ "2f7074797065732f616e79a20203475042aa021e476f6f676c652e50726f"
+ "746f6275662e57656c6c4b6e6f776e5479706573620670726f746f33";
+ char* binary;
+ int binary_len;
+ hex_to_binary(generated_file, &binary, &binary_len);
+ internal_add_generated_file(binary, binary_len, generated_pool TSRMLS_CC);
+ FREE(binary);
+ is_initialized = true;
+}
+
+static void init_file_api(TSRMLS_D) {
+ static bool is_initialized = false;
+ if (is_initialized) return;
+ init_file_source_context(TSRMLS_C);
+ init_file_type(TSRMLS_C);
+ init_generated_pool_once(TSRMLS_C);
+ const char* generated_file =
+ "0aee050a19676f6f676c652f70726f746f6275662f6170692e70726f746f"
+ "120f676f6f676c652e70726f746f6275661a24676f6f676c652f70726f74"
+ "6f6275662f736f757263655f636f6e746578742e70726f746f1a1a676f6f"
+ "676c652f70726f746f6275662f747970652e70726f746f2281020a034170"
+ "69120c0a046e616d6518012001280912280a076d6574686f647318022003"
+ "280b32172e676f6f676c652e70726f746f6275662e4d6574686f6412280a"
+ "076f7074696f6e7318032003280b32172e676f6f676c652e70726f746f62"
+ "75662e4f7074696f6e120f0a0776657273696f6e18042001280912360a0e"
+ "736f757263655f636f6e7465787418052001280b321e2e676f6f676c652e"
+ "70726f746f6275662e536f75726365436f6e7465787412260a066d697869"
+ "6e7318062003280b32162e676f6f676c652e70726f746f6275662e4d6978"
+ "696e12270a0673796e74617818072001280e32172e676f6f676c652e7072"
+ "6f746f6275662e53796e74617822d5010a064d6574686f64120c0a046e61"
+ "6d6518012001280912180a10726571756573745f747970655f75726c1802"
+ "2001280912190a11726571756573745f73747265616d696e671803200128"
+ "0812190a11726573706f6e73655f747970655f75726c180420012809121a"
+ "0a12726573706f6e73655f73747265616d696e6718052001280812280a07"
+ "6f7074696f6e7318062003280b32172e676f6f676c652e70726f746f6275"
+ "662e4f7074696f6e12270a0673796e74617818072001280e32172e676f6f"
+ "676c652e70726f746f6275662e53796e74617822230a054d6978696e120c"
+ "0a046e616d65180120012809120c0a04726f6f7418022001280942750a13"
+ "636f6d2e676f6f676c652e70726f746f627566420841706950726f746f50"
+ "015a2b676f6f676c652e676f6c616e672e6f72672f67656e70726f746f2f"
+ "70726f746f6275662f6170693b617069a20203475042aa021e476f6f676c"
+ "652e50726f746f6275662e57656c6c4b6e6f776e5479706573620670726f"
+ "746f33";
+ char* binary;
+ int binary_len;
+ hex_to_binary(generated_file, &binary, &binary_len);
+ internal_add_generated_file(binary, binary_len, generated_pool TSRMLS_CC);
+ FREE(binary);
+ is_initialized = true;
+}
+
+static void init_file_duration(TSRMLS_D) {
+ static bool is_initialized = false;
+ if (is_initialized) return;
+ init_generated_pool_once(TSRMLS_C);
+ const char* generated_file =
+ "0ae3010a1e676f6f676c652f70726f746f6275662f6475726174696f6e2e"
+ "70726f746f120f676f6f676c652e70726f746f627566222a0a0844757261"
+ "74696f6e120f0a077365636f6e6473180120012803120d0a056e616e6f73"
+ "180220012805427c0a13636f6d2e676f6f676c652e70726f746f62756642"
+ "0d4475726174696f6e50726f746f50015a2a6769746875622e636f6d2f67"
+ "6f6c616e672f70726f746f6275662f7074797065732f6475726174696f6e"
+ "f80101a20203475042aa021e476f6f676c652e50726f746f6275662e5765"
+ "6c6c4b6e6f776e5479706573620670726f746f33";
+ char* binary;
+ int binary_len;
+ hex_to_binary(generated_file, &binary, &binary_len);
+ internal_add_generated_file(binary, binary_len, generated_pool TSRMLS_CC);
+ FREE(binary);
+ is_initialized = true;
+}
+
+static void init_file_field_mask(TSRMLS_D) {
+ static bool is_initialized = false;
+ if (is_initialized) return;
+ init_generated_pool_once(TSRMLS_C);
+ const char* generated_file =
+ "0ae3010a20676f6f676c652f70726f746f6275662f6669656c645f6d6173"
+ "6b2e70726f746f120f676f6f676c652e70726f746f627566221a0a094669"
+ "656c644d61736b120d0a0570617468731801200328094289010a13636f6d"
+ "2e676f6f676c652e70726f746f627566420e4669656c644d61736b50726f"
+ "746f50015a39676f6f676c652e676f6c616e672e6f72672f67656e70726f"
+ "746f2f70726f746f6275662f6669656c645f6d61736b3b6669656c645f6d"
+ "61736ba20203475042aa021e476f6f676c652e50726f746f6275662e5765"
+ "6c6c4b6e6f776e5479706573620670726f746f33";
+ char* binary;
+ int binary_len;
+ hex_to_binary(generated_file, &binary, &binary_len);
+ internal_add_generated_file(binary, binary_len, generated_pool TSRMLS_CC);
+ FREE(binary);
+ is_initialized = true;
+}
+
+static void init_file_empty(TSRMLS_D) {
+ static bool is_initialized = false;
+ if (is_initialized) return;
+ init_generated_pool_once(TSRMLS_C);
+ const char* generated_file =
+ "0ab7010a1b676f6f676c652f70726f746f6275662f656d7074792e70726f"
+ "746f120f676f6f676c652e70726f746f62756622070a05456d7074794276"
+ "0a13636f6d2e676f6f676c652e70726f746f627566420a456d7074795072"
+ "6f746f50015a276769746875622e636f6d2f676f6c616e672f70726f746f"
+ "6275662f7074797065732f656d707479f80101a20203475042aa021e476f"
+ "6f676c652e50726f746f6275662e57656c6c4b6e6f776e54797065736206"
+ "70726f746f33";
+ char* binary;
+ int binary_len;
+ hex_to_binary(generated_file, &binary, &binary_len);
+ internal_add_generated_file(binary, binary_len, generated_pool TSRMLS_CC);
+ FREE(binary);
+ is_initialized = true;
+}
+
+static void init_file_source_context(TSRMLS_D) {
+ static bool is_initialized = false;
+ if (is_initialized) return;
+ init_generated_pool_once(TSRMLS_C);
+ const char* generated_file =
+ "0afb010a24676f6f676c652f70726f746f6275662f736f757263655f636f"
+ "6e746578742e70726f746f120f676f6f676c652e70726f746f6275662222"
+ "0a0d536f75726365436f6e7465787412110a0966696c655f6e616d651801"
+ "200128094295010a13636f6d2e676f6f676c652e70726f746f6275664212"
+ "536f75726365436f6e7465787450726f746f50015a41676f6f676c652e67"
+ "6f6c616e672e6f72672f67656e70726f746f2f70726f746f6275662f736f"
+ "757263655f636f6e746578743b736f757263655f636f6e74657874a20203"
+ "475042aa021e476f6f676c652e50726f746f6275662e57656c6c4b6e6f77"
+ "6e5479706573620670726f746f33";
+ char* binary;
+ int binary_len;
+ hex_to_binary(generated_file, &binary, &binary_len);
+ internal_add_generated_file(binary, binary_len, generated_pool TSRMLS_CC);
+ FREE(binary);
+ is_initialized = true;
+}
+
+static void init_file_struct(TSRMLS_D) {
+ static bool is_initialized = false;
+ if (is_initialized) return;
+ init_generated_pool_once(TSRMLS_C);
+ const char* generated_file =
+ "0a81050a1c676f6f676c652f70726f746f6275662f7374727563742e7072"
+ "6f746f120f676f6f676c652e70726f746f6275662284010a065374727563"
+ "7412330a066669656c647318012003280b32232e676f6f676c652e70726f"
+ "746f6275662e5374727563742e4669656c6473456e7472791a450a0b4669"
+ "656c6473456e747279120b0a036b657918012001280912250a0576616c75"
+ "6518022001280b32162e676f6f676c652e70726f746f6275662e56616c75"
+ "653a02380122ea010a0556616c756512300a0a6e756c6c5f76616c756518"
+ "012001280e321a2e676f6f676c652e70726f746f6275662e4e756c6c5661"
+ "6c7565480012160a0c6e756d6265725f76616c7565180220012801480012"
+ "160a0c737472696e675f76616c7565180320012809480012140a0a626f6f"
+ "6c5f76616c75651804200128084800122f0a0c7374727563745f76616c75"
+ "6518052001280b32172e676f6f676c652e70726f746f6275662e53747275"
+ "6374480012300a0a6c6973745f76616c756518062001280b321a2e676f6f"
+ "676c652e70726f746f6275662e4c69737456616c7565480042060a046b69"
+ "6e6422330a094c69737456616c756512260a0676616c7565731801200328"
+ "0b32162e676f6f676c652e70726f746f6275662e56616c75652a1b0a094e"
+ "756c6c56616c7565120e0a0a4e554c4c5f56414c554510004281010a1363"
+ "6f6d2e676f6f676c652e70726f746f627566420b53747275637450726f74"
+ "6f50015a316769746875622e636f6d2f676f6c616e672f70726f746f6275"
+ "662f7074797065732f7374727563743b7374727563747062f80101a20203"
+ "475042aa021e476f6f676c652e50726f746f6275662e57656c6c4b6e6f77"
+ "6e5479706573620670726f746f33";
+ char* binary;
+ int binary_len;
+ hex_to_binary(generated_file, &binary, &binary_len);
+ internal_add_generated_file(binary, binary_len, generated_pool TSRMLS_CC);
+ FREE(binary);
+ is_initialized = true;
+}
+
+static void init_file_timestamp(TSRMLS_D) {
+ static bool is_initialized = false;
+ if (is_initialized) return;
+ init_generated_pool_once(TSRMLS_C);
+ const char* generated_file =
+ "0ae7010a1f676f6f676c652f70726f746f6275662f74696d657374616d70"
+ "2e70726f746f120f676f6f676c652e70726f746f627566222b0a0954696d"
+ "657374616d70120f0a077365636f6e6473180120012803120d0a056e616e"
+ "6f73180220012805427e0a13636f6d2e676f6f676c652e70726f746f6275"
+ "66420e54696d657374616d7050726f746f50015a2b6769746875622e636f"
+ "6d2f676f6c616e672f70726f746f6275662f7074797065732f74696d6573"
+ "74616d70f80101a20203475042aa021e476f6f676c652e50726f746f6275"
+ "662e57656c6c4b6e6f776e5479706573620670726f746f33";
+ char* binary;
+ int binary_len;
+ hex_to_binary(generated_file, &binary, &binary_len);
+ internal_add_generated_file(binary, binary_len, generated_pool TSRMLS_CC);
+ FREE(binary);
+ is_initialized = true;
+}
+
+static void init_file_type(TSRMLS_D) {
+ static bool is_initialized = false;
+ if (is_initialized) return;
+ init_file_any(TSRMLS_C);
+ init_file_source_context(TSRMLS_C);
+ init_generated_pool_once(TSRMLS_C);
+ const char* generated_file =
+ "0aba0c0a1a676f6f676c652f70726f746f6275662f747970652e70726f74"
+ "6f120f676f6f676c652e70726f746f6275661a19676f6f676c652f70726f"
+ "746f6275662f616e792e70726f746f1a24676f6f676c652f70726f746f62"
+ "75662f736f757263655f636f6e746578742e70726f746f22d7010a045479"
+ "7065120c0a046e616d6518012001280912260a066669656c647318022003"
+ "280b32162e676f6f676c652e70726f746f6275662e4669656c64120e0a06"
+ "6f6e656f667318032003280912280a076f7074696f6e7318042003280b32"
+ "172e676f6f676c652e70726f746f6275662e4f7074696f6e12360a0e736f"
+ "757263655f636f6e7465787418052001280b321e2e676f6f676c652e7072"
+ "6f746f6275662e536f75726365436f6e7465787412270a0673796e746178"
+ "18062001280e32172e676f6f676c652e70726f746f6275662e53796e7461"
+ "7822d5050a054669656c6412290a046b696e6418012001280e321b2e676f"
+ "6f676c652e70726f746f6275662e4669656c642e4b696e6412370a0b6361"
+ "7264696e616c69747918022001280e32222e676f6f676c652e70726f746f"
+ "6275662e4669656c642e43617264696e616c697479120e0a066e756d6265"
+ "72180320012805120c0a046e616d6518042001280912100a08747970655f"
+ "75726c18062001280912130a0b6f6e656f665f696e646578180720012805"
+ "120e0a067061636b656418082001280812280a076f7074696f6e73180920"
+ "03280b32172e676f6f676c652e70726f746f6275662e4f7074696f6e1211"
+ "0a096a736f6e5f6e616d65180a2001280912150a0d64656661756c745f76"
+ "616c7565180b2001280922c8020a044b696e6412100a0c545950455f554e"
+ "4b4e4f574e1000120f0a0b545950455f444f55424c451001120e0a0a5459"
+ "50455f464c4f41541002120e0a0a545950455f494e5436341003120f0a0b"
+ "545950455f55494e5436341004120e0a0a545950455f494e543332100512"
+ "100a0c545950455f46495845443634100612100a0c545950455f46495845"
+ "4433321007120d0a09545950455f424f4f4c1008120f0a0b545950455f53"
+ "5452494e471009120e0a0a545950455f47524f5550100a12100a0c545950"
+ "455f4d455353414745100b120e0a0a545950455f4259544553100c120f0a"
+ "0b545950455f55494e543332100d120d0a09545950455f454e554d100e12"
+ "110a0d545950455f5346495845443332100f12110a0d545950455f534649"
+ "58454436341010120f0a0b545950455f53494e5433321011120f0a0b5459"
+ "50455f53494e543634101222740a0b43617264696e616c69747912170a13"
+ "43415244494e414c4954595f554e4b4e4f574e100012180a144341524449"
+ "4e414c4954595f4f5054494f4e414c100112180a1443415244494e414c49"
+ "54595f5245515549524544100212180a1443415244494e414c4954595f52"
+ "45504541544544100322ce010a04456e756d120c0a046e616d6518012001"
+ "2809122d0a09656e756d76616c756518022003280b321a2e676f6f676c65"
+ "2e70726f746f6275662e456e756d56616c756512280a076f7074696f6e73"
+ "18032003280b32172e676f6f676c652e70726f746f6275662e4f7074696f"
+ "6e12360a0e736f757263655f636f6e7465787418042001280b321e2e676f"
+ "6f676c652e70726f746f6275662e536f75726365436f6e7465787412270a"
+ "0673796e74617818052001280e32172e676f6f676c652e70726f746f6275"
+ "662e53796e74617822530a09456e756d56616c7565120c0a046e616d6518"
+ "0120012809120e0a066e756d62657218022001280512280a076f7074696f"
+ "6e7318032003280b32172e676f6f676c652e70726f746f6275662e4f7074"
+ "696f6e223b0a064f7074696f6e120c0a046e616d6518012001280912230a"
+ "0576616c756518022001280b32142e676f6f676c652e70726f746f627566"
+ "2e416e792a2e0a0653796e74617812110a0d53594e5441585f50524f544f"
+ "32100012110a0d53594e5441585f50524f544f331001427d0a13636f6d2e"
+ "676f6f676c652e70726f746f62756642095479706550726f746f50015a2f"
+ "676f6f676c652e676f6c616e672e6f72672f67656e70726f746f2f70726f"
+ "746f6275662f70747970653b7074797065f80101a20203475042aa021e47"
+ "6f6f676c652e50726f746f6275662e57656c6c4b6e6f776e547970657362"
+ "0670726f746f33";
+ char* binary;
+ int binary_len;
+ hex_to_binary(generated_file, &binary, &binary_len);
+ internal_add_generated_file(binary, binary_len, generated_pool TSRMLS_CC);
+ FREE(binary);
+ is_initialized = true;
+}
+
+static void init_file_wrappers(TSRMLS_D) {
+ static bool is_initialized = false;
+ if (is_initialized) return;
+ init_generated_pool_once(TSRMLS_C);
+ const char* generated_file =
+ "0abf030a1e676f6f676c652f70726f746f6275662f77726170706572732e"
+ "70726f746f120f676f6f676c652e70726f746f627566221c0a0b446f7562"
+ "6c6556616c7565120d0a0576616c7565180120012801221b0a0a466c6f61"
+ "7456616c7565120d0a0576616c7565180120012802221b0a0a496e743634"
+ "56616c7565120d0a0576616c7565180120012803221c0a0b55496e743634"
+ "56616c7565120d0a0576616c7565180120012804221b0a0a496e74333256"
+ "616c7565120d0a0576616c7565180120012805221c0a0b55496e74333256"
+ "616c7565120d0a0576616c756518012001280d221a0a09426f6f6c56616c"
+ "7565120d0a0576616c7565180120012808221c0a0b537472696e6756616c"
+ "7565120d0a0576616c7565180120012809221b0a0a427974657356616c75"
+ "65120d0a0576616c756518012001280c427c0a13636f6d2e676f6f676c65"
+ "2e70726f746f627566420d577261707065727350726f746f50015a2a6769"
+ "746875622e636f6d2f676f6c616e672f70726f746f6275662f7074797065"
+ "732f7772617070657273f80101a20203475042aa021e476f6f676c652e50"
+ "726f746f6275662e57656c6c4b6e6f776e5479706573620670726f746f33";
+ char* binary;
+ int binary_len;
+ hex_to_binary(generated_file, &binary, &binary_len);
+ internal_add_generated_file(binary, binary_len, generated_pool TSRMLS_CC);
+ FREE(binary);
+ is_initialized = true;
+}
+
+// -----------------------------------------------------------------------------
+// Define enum
+// -----------------------------------------------------------------------------
+
+// -----------------------------------------------------------------------------
+// Field_Cardinality
+// -----------------------------------------------------------------------------
+
+static zend_function_entry field_cardinality_methods[] = {
+ {NULL, NULL, NULL}
+};
+
+zend_class_entry* field_cardinality_type;
+
+// Init class entry.
+PHP_PROTO_INIT_ENUMCLASS_START("Google\\Protobuf\\Field_Cardinality",
+ Field_Cardinality, field_cardinality)
+ zend_declare_class_constant_long(field_cardinality_type,
+ "CARDINALITY_UNKNOWN", 19, 0 TSRMLS_CC);
+ zend_declare_class_constant_long(field_cardinality_type,
+ "CARDINALITY_OPTIONAL", 20, 1 TSRMLS_CC);
+ zend_declare_class_constant_long(field_cardinality_type,
+ "CARDINALITY_REQUIRED", 20, 2 TSRMLS_CC);
+ zend_declare_class_constant_long(field_cardinality_type,
+ "CARDINALITY_REPEATED", 20, 3 TSRMLS_CC);
+PHP_PROTO_INIT_ENUMCLASS_END
+
+// -----------------------------------------------------------------------------
+// Field_Kind
+// -----------------------------------------------------------------------------
+
+static zend_function_entry field_kind_methods[] = {
+ {NULL, NULL, NULL}
+};
+
+zend_class_entry* field_kind_type;
+
+// Init class entry.
+PHP_PROTO_INIT_ENUMCLASS_START("Google\\Protobuf\\Field_Kind",
+ Field_Kind, field_kind)
+ zend_declare_class_constant_long(field_kind_type,
+ "TYPE_UNKNOWN", 12, 0 TSRMLS_CC);
+ zend_declare_class_constant_long(field_kind_type,
+ "TYPE_DOUBLE", 11, 1 TSRMLS_CC);
+ zend_declare_class_constant_long(field_kind_type,
+ "TYPE_FLOAT", 10, 2 TSRMLS_CC);
+ zend_declare_class_constant_long(field_kind_type,
+ "TYPE_INT64", 10, 3 TSRMLS_CC);
+ zend_declare_class_constant_long(field_kind_type,
+ "TYPE_UINT64", 11, 4 TSRMLS_CC);
+ zend_declare_class_constant_long(field_kind_type,
+ "TYPE_INT32", 10, 5 TSRMLS_CC);
+ zend_declare_class_constant_long(field_kind_type,
+ "TYPE_FIXED64", 12, 6 TSRMLS_CC);
+ zend_declare_class_constant_long(field_kind_type,
+ "TYPE_FIXED32", 12, 7 TSRMLS_CC);
+ zend_declare_class_constant_long(field_kind_type,
+ "TYPE_BOOL", 9, 8 TSRMLS_CC);
+ zend_declare_class_constant_long(field_kind_type,
+ "TYPE_STRING", 11, 9 TSRMLS_CC);
+ zend_declare_class_constant_long(field_kind_type,
+ "TYPE_GROUP", 10, 10 TSRMLS_CC);
+ zend_declare_class_constant_long(field_kind_type,
+ "TYPE_MESSAGE", 12, 11 TSRMLS_CC);
+ zend_declare_class_constant_long(field_kind_type,
+ "TYPE_BYTES", 10, 12 TSRMLS_CC);
+ zend_declare_class_constant_long(field_kind_type,
+ "TYPE_UINT32", 11, 13 TSRMLS_CC);
+ zend_declare_class_constant_long(field_kind_type,
+ "TYPE_ENUM", 9, 14 TSRMLS_CC);
+ zend_declare_class_constant_long(field_kind_type,
+ "TYPE_SFIXED32", 13, 15 TSRMLS_CC);
+ zend_declare_class_constant_long(field_kind_type,
+ "TYPE_SFIXED64", 13, 16 TSRMLS_CC);
+ zend_declare_class_constant_long(field_kind_type,
+ "TYPE_SINT32", 11, 17 TSRMLS_CC);
+ zend_declare_class_constant_long(field_kind_type,
+ "TYPE_SINT64", 11, 18 TSRMLS_CC);
+PHP_PROTO_INIT_ENUMCLASS_END
+
+// -----------------------------------------------------------------------------
+// NullValue
+// -----------------------------------------------------------------------------
+
+static zend_function_entry null_value_methods[] = {
+ {NULL, NULL, NULL}
+};
+
+zend_class_entry* null_value_type;
+
+// Init class entry.
+PHP_PROTO_INIT_ENUMCLASS_START("Google\\Protobuf\\NullValue",
+ NullValue, null_value)
+ zend_declare_class_constant_long(null_value_type,
+ "NULL_VALUE", 10, 0 TSRMLS_CC);
+PHP_PROTO_INIT_ENUMCLASS_END
+
+// -----------------------------------------------------------------------------
+// Syntax
+// -----------------------------------------------------------------------------
+
+static zend_function_entry syntax_methods[] = {
+ {NULL, NULL, NULL}
+};
+
+zend_class_entry* syntax_type;
+
+// Init class entry.
+PHP_PROTO_INIT_ENUMCLASS_START("Google\\Protobuf\\Syntax",
+ Syntax, syntax)
+ zend_declare_class_constant_long(syntax_type,
+ "SYNTAX_PROTO2", 13, 0 TSRMLS_CC);
+ zend_declare_class_constant_long(syntax_type,
+ "SYNTAX_PROTO3", 13, 1 TSRMLS_CC);
+PHP_PROTO_INIT_ENUMCLASS_END
+
+
+
+// -----------------------------------------------------------------------------
+// Define message
+// -----------------------------------------------------------------------------
+
+// -----------------------------------------------------------------------------
+// Any
+// -----------------------------------------------------------------------------
+
+static zend_function_entry any_methods[] = {
+ PHP_ME(Any, __construct, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Any, getTypeUrl, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Any, setTypeUrl, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Any, getValue, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Any, setValue, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Any, pack, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Any, unpack, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Any, is, NULL, ZEND_ACC_PUBLIC)
+ {NULL, NULL, NULL}
+};
+
+zend_class_entry* any_type;
+
+// Init class entry.
+PHP_PROTO_INIT_SUBMSGCLASS_START("Google\\Protobuf\\Any", Any, any)
+ zend_class_implements(any_type TSRMLS_CC, 1, message_type);
+ zend_declare_property_string(any_type, "type_url", strlen("type_url"),
+ "" ,ZEND_ACC_PRIVATE TSRMLS_CC);
+ zend_declare_property_string(any_type, "value", strlen("value"),
+ "" ,ZEND_ACC_PRIVATE TSRMLS_CC);
+PHP_PROTO_INIT_SUBMSGCLASS_END
+
+static void hex_to_binary(const char* hex, char** binary, int* binary_len) {
+ int i;
+ int hex_len = strlen(hex);
+ *binary_len = hex_len / 2;
+ *binary = ALLOC_N(char, *binary_len);
+ for (i = 0; i < *binary_len; i++) {
+ char value = 0;
+ if (hex[i * 2] >= '0' && hex[i * 2] <= '9') {
+ value += (hex[i * 2] - '0') * 16;
+ } else {
+ value += (hex[i * 2] - 'a' + 10) * 16;
+ }
+ if (hex[i * 2 + 1] >= '0' && hex[i * 2 + 1] <= '9') {
+ value += hex[i * 2 + 1] - '0';
+ } else {
+ value += hex[i * 2 + 1] - 'a' + 10;
+ }
+ (*binary)[i] = value;
+ }
+}
+
+PHP_METHOD(Any, __construct) {
+ init_file_any(TSRMLS_C);
+ MessageHeader* intern = UNBOX(MessageHeader, getThis());
+ custom_data_init(any_type, intern PHP_PROTO_TSRMLS_CC);
+}
+
+PHP_PROTO_FIELD_ACCESSORS(Any, any, TypeUrl, "type_url")
+PHP_PROTO_FIELD_ACCESSORS(Any, any, Value, "value")
+
+PHP_METHOD(Any, unpack) {
+ // Get type url.
+ zval type_url_member;
+ PHP_PROTO_ZVAL_STRING(&type_url_member, "type_url", 1);
+ PHP_PROTO_FAKE_SCOPE_BEGIN(any_type);
+ zval* type_url_php = php_proto_message_read_property(
+ getThis(), &type_url_member PHP_PROTO_TSRMLS_CC);
+ PHP_PROTO_FAKE_SCOPE_END;
+
+ // Get fully-qualified name from type url.
+ size_t url_prefix_len = strlen(TYPE_URL_PREFIX);
+ const char* type_url = Z_STRVAL_P(type_url_php);
+ size_t type_url_len = Z_STRLEN_P(type_url_php);
+
+ if (url_prefix_len > type_url_len ||
+ strncmp(TYPE_URL_PREFIX, type_url, url_prefix_len) != 0) {
+ zend_throw_exception(
+ NULL, "Type url needs to be type.googleapis.com/fully-qulified",
+ 0 TSRMLS_CC);
+ return;
+ }
+
+ const char* fully_qualified_name = type_url + url_prefix_len;
+ PHP_PROTO_HASHTABLE_VALUE desc_php = get_proto_obj(fully_qualified_name);
+ if (desc_php == NULL) {
+ zend_throw_exception(
+ NULL, "Specified message in any hasn't been added to descriptor pool",
+ 0 TSRMLS_CC);
+ return;
+ }
+ Descriptor* desc = UNBOX_HASHTABLE_VALUE(Descriptor, desc_php);
+ zend_class_entry* klass = desc->klass;
+ ZVAL_OBJ(return_value, klass->create_object(klass TSRMLS_CC));
+ MessageHeader* msg = UNBOX(MessageHeader, return_value);
+ custom_data_init(klass, msg PHP_PROTO_TSRMLS_CC);
+
+ // Get value.
+ zval value_member;
+ PHP_PROTO_ZVAL_STRING(&value_member, "value", 1);
+ PHP_PROTO_FAKE_SCOPE_RESTART(any_type);
+ zval* value = php_proto_message_read_property(
+ getThis(), &value_member PHP_PROTO_TSRMLS_CC);
+ PHP_PROTO_FAKE_SCOPE_END;
+
+ merge_from_string(Z_STRVAL_P(value), Z_STRLEN_P(value), desc, msg);
+}
+
+PHP_METHOD(Any, pack) {
+ zval* val;
+
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "o", &val) ==
+ FAILURE) {
+ return;
+ }
+
+ if (!instanceof_function(Z_OBJCE_P(val), message_type TSRMLS_CC)) {
+ zend_error(E_USER_ERROR, "Given value is not an instance of Message.");
+ return;
+ }
+
+ // Set value by serialized data.
+ zval data;
+ serialize_to_string(val, &data TSRMLS_CC);
+
+ zval member;
+ PHP_PROTO_ZVAL_STRING(&member, "value", 1);
+
+ PHP_PROTO_FAKE_SCOPE_BEGIN(any_type);
+ message_handlers->write_property(getThis(), &member, &data,
+ NULL PHP_PROTO_TSRMLS_CC);
+ PHP_PROTO_FAKE_SCOPE_END;
+
+ // Set type url.
+ Descriptor* desc =
+ UNBOX_HASHTABLE_VALUE(Descriptor, get_ce_obj(Z_OBJCE_P(val)));
+ const char* fully_qualified_name = upb_msgdef_fullname(desc->msgdef);
+ size_t type_url_len =
+ strlen(TYPE_URL_PREFIX) + strlen(fully_qualified_name) + 1;
+ char* type_url = ALLOC_N(char, type_url_len);
+ sprintf(type_url, "%s%s", TYPE_URL_PREFIX, fully_qualified_name);
+ zval type_url_php;
+ PHP_PROTO_ZVAL_STRING(&type_url_php, type_url, 1);
+ PHP_PROTO_ZVAL_STRING(&member, "type_url", 1);
+
+ PHP_PROTO_FAKE_SCOPE_RESTART(any_type);
+ message_handlers->write_property(getThis(), &member, &type_url_php,
+ NULL PHP_PROTO_TSRMLS_CC);
+ PHP_PROTO_FAKE_SCOPE_END;
+ FREE(type_url);
+}
+
+PHP_METHOD(Any, is) {
+ zend_class_entry *klass = NULL;
+
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "C", &klass) ==
+ FAILURE) {
+ return;
+ }
+
+ PHP_PROTO_HASHTABLE_VALUE desc_php = get_ce_obj(klass);
+ if (desc_php == NULL) {
+ RETURN_BOOL(false);
+ }
+
+ // Create corresponded type url.
+ Descriptor* desc =
+ UNBOX_HASHTABLE_VALUE(Descriptor, get_ce_obj(klass));
+ const char* fully_qualified_name = upb_msgdef_fullname(desc->msgdef);
+ size_t type_url_len =
+ strlen(TYPE_URL_PREFIX) + strlen(fully_qualified_name) + 1;
+ char* type_url = ALLOC_N(char, type_url_len);
+ sprintf(type_url, "%s%s", TYPE_URL_PREFIX, fully_qualified_name);
+
+ // Fetch stored type url.
+ zval member;
+ PHP_PROTO_ZVAL_STRING(&member, "type_url", 1);
+ PHP_PROTO_FAKE_SCOPE_BEGIN(any_type);
+ zval* value =
+ php_proto_message_read_property(getThis(), &member PHP_PROTO_TSRMLS_CC);
+ PHP_PROTO_FAKE_SCOPE_END;
+
+ // Compare two type url.
+ bool is = strcmp(type_url, Z_STRVAL_P(value)) == 0;
+ FREE(type_url);
+
+ RETURN_BOOL(is);
+}
+
+// -----------------------------------------------------------------------------
+// Duration
+// -----------------------------------------------------------------------------
+
+static zend_function_entry duration_methods[] = {
+ PHP_ME(Duration, __construct, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Duration, getSeconds, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Duration, setSeconds, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Duration, getNanos, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Duration, setNanos, NULL, ZEND_ACC_PUBLIC)
+ {NULL, NULL, NULL}
+};
+
+zend_class_entry* duration_type;
+
+// Init class entry.
+PHP_PROTO_INIT_SUBMSGCLASS_START("Google\\Protobuf\\Duration",
+ Duration, duration)
+ zend_class_implements(duration_type TSRMLS_CC, 1, message_type);
+ zend_declare_property_long(duration_type, "seconds", strlen("seconds"),
+ 0 ,ZEND_ACC_PRIVATE TSRMLS_CC);
+ zend_declare_property_long(duration_type, "nanos", strlen("nanos"),
+ 0 ,ZEND_ACC_PRIVATE TSRMLS_CC);
+PHP_PROTO_INIT_SUBMSGCLASS_END
+
+PHP_METHOD(Duration, __construct) {
+ init_file_duration(TSRMLS_C);
+ MessageHeader* intern = UNBOX(MessageHeader, getThis());
+ custom_data_init(duration_type, intern PHP_PROTO_TSRMLS_CC);
+}
+
+PHP_PROTO_FIELD_ACCESSORS(Duration, duration, Seconds, "seconds")
+PHP_PROTO_FIELD_ACCESSORS(Duration, duration, Nanos, "nanos")
+
+// -----------------------------------------------------------------------------
+// Timestamp
+// -----------------------------------------------------------------------------
+
+static zend_function_entry timestamp_methods[] = {
+ PHP_ME(Timestamp, __construct, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Timestamp, fromDateTime, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Timestamp, toDateTime, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Timestamp, getSeconds, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Timestamp, setSeconds, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Timestamp, getNanos, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Timestamp, setNanos, NULL, ZEND_ACC_PUBLIC)
+ {NULL, NULL, NULL}
+};
+
+zend_class_entry* timestamp_type;
+
+// Init class entry.
+PHP_PROTO_INIT_SUBMSGCLASS_START("Google\\Protobuf\\Timestamp",
+ Timestamp, timestamp)
+ zend_class_implements(timestamp_type TSRMLS_CC, 1, message_type);
+ zend_declare_property_long(timestamp_type, "seconds", strlen("seconds"),
+ 0 ,ZEND_ACC_PRIVATE TSRMLS_CC);
+ zend_declare_property_long(timestamp_type, "nanos", strlen("nanos"),
+ 0 ,ZEND_ACC_PRIVATE TSRMLS_CC);
+PHP_PROTO_INIT_SUBMSGCLASS_END
+
+PHP_METHOD(Timestamp, __construct) {
+ init_file_timestamp(TSRMLS_C);
+ MessageHeader* intern = UNBOX(MessageHeader, getThis());
+ custom_data_init(timestamp_type, intern PHP_PROTO_TSRMLS_CC);
+}
+
+PHP_PROTO_FIELD_ACCESSORS(Timestamp, timestamp, Seconds, "seconds")
+PHP_PROTO_FIELD_ACCESSORS(Timestamp, timestamp, Nanos, "nanos")
+
+PHP_METHOD(Timestamp, fromDateTime) {
+ zval* datetime;
+ zval member;
+
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O", &datetime,
+ php_date_get_date_ce()) == FAILURE) {
+ return;
+ }
+
+ php_date_obj* dateobj = UNBOX(php_date_obj, datetime);
+ if (!dateobj->time->sse_uptodate) {
+ timelib_update_ts(dateobj->time, NULL);
+ }
+
+ int64_t timestamp = dateobj->time->sse;
+
+ // Set seconds
+ MessageHeader* self = UNBOX(MessageHeader, getThis());
+ const upb_fielddef* field =
+ upb_msgdef_ntofz(self->descriptor->msgdef, "seconds");
+ void* storage = message_data(self);
+ void* memory = slot_memory(self->descriptor->layout, storage, field);
+ *(int64_t*)memory = dateobj->time->sse;
+
+ // Set nanos
+ field = upb_msgdef_ntofz(self->descriptor->msgdef, "nanos");
+ storage = message_data(self);
+ memory = slot_memory(self->descriptor->layout, storage, field);
+ *(int32_t*)memory = 0;
+}
+
+PHP_METHOD(Timestamp, toDateTime) {
+ zval datetime;
+ php_date_instantiate(php_date_get_date_ce(), &datetime TSRMLS_CC);
+ php_date_obj* dateobj = UNBOX(php_date_obj, &datetime);
+
+ // Get seconds
+ MessageHeader* self = UNBOX(MessageHeader, getThis());
+ const upb_fielddef* field =
+ upb_msgdef_ntofz(self->descriptor->msgdef, "seconds");
+ void* storage = message_data(self);
+ void* memory = slot_memory(self->descriptor->layout, storage, field);
+ int64_t seconds = *(int64_t*)memory;
+
+ // Get nanos
+ field = upb_msgdef_ntofz(self->descriptor->msgdef, "nanos");
+ memory = slot_memory(self->descriptor->layout, storage, field);
+ int32_t nanos = *(int32_t*)memory;
+
+ // Get formated time string.
+ char formated_time[50];
+ time_t raw_time = seconds;
+ struct tm *utc_time = gmtime(&raw_time);
+ strftime(formated_time, sizeof(formated_time), "%Y-%m-%dT%H:%M:%SUTC",
+ utc_time);
+
+ if (!php_date_initialize(dateobj, formated_time, strlen(formated_time), NULL,
+ NULL, 0 TSRMLS_CC)) {
+ zval_dtor(&datetime);
+ RETURN_NULL();
+ }
+
+ zval* datetime_ptr = &datetime;
+ PHP_PROTO_RETVAL_ZVAL(datetime_ptr);
+}
+
+// -----------------------------------------------------------------------------
+// Api
+// -----------------------------------------------------------------------------
+
+static zend_function_entry api_methods[] = {
+ PHP_ME(Api, __construct, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Api, getName, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Api, setName, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Api, getMethods, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Api, setMethods, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Api, getOptions, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Api, setOptions, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Api, getVersion, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Api, setVersion, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Api, getSourceContext, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Api, setSourceContext, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Api, getMixins, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Api, setMixins, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Api, getSyntax, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Api, setSyntax, NULL, ZEND_ACC_PUBLIC)
+ {NULL, NULL, NULL}
+};
+
+zend_class_entry* api_type;
+
+// Init class entry.
+PHP_PROTO_INIT_SUBMSGCLASS_START("Google\\Protobuf\\Api",
+ Api, api)
+ zend_class_implements(api_type TSRMLS_CC, 1, message_type);
+ zend_declare_property_null(api_type, "name", strlen("name"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+ zend_declare_property_null(api_type, "methods", strlen("methods"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+ zend_declare_property_null(api_type, "options", strlen("options"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+ zend_declare_property_null(api_type, "version", strlen("version"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+ zend_declare_property_null(api_type, "source_context", strlen("source_context"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+ zend_declare_property_null(api_type, "mixins", strlen("mixins"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+ zend_declare_property_null(api_type, "syntax", strlen("syntax"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+PHP_PROTO_INIT_SUBMSGCLASS_END
+
+PHP_METHOD(Api, __construct) {
+ init_file_api(TSRMLS_C);
+ MessageHeader* intern = UNBOX(MessageHeader, getThis());
+ custom_data_init(api_type, intern PHP_PROTO_TSRMLS_CC);
+}
+
+PHP_PROTO_FIELD_ACCESSORS(Api, api, Name, "name")
+PHP_PROTO_FIELD_ACCESSORS(Api, api, Methods, "methods")
+PHP_PROTO_FIELD_ACCESSORS(Api, api, Options, "options")
+PHP_PROTO_FIELD_ACCESSORS(Api, api, Version, "version")
+PHP_PROTO_FIELD_ACCESSORS(Api, api, SourceContext, "source_context")
+PHP_PROTO_FIELD_ACCESSORS(Api, api, Mixins, "mixins")
+PHP_PROTO_FIELD_ACCESSORS(Api, api, Syntax, "syntax")
+
+// -----------------------------------------------------------------------------
+// BoolValue
+// -----------------------------------------------------------------------------
+
+static zend_function_entry bool_value_methods[] = {
+ PHP_ME(BoolValue, __construct, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(BoolValue, getValue, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(BoolValue, setValue, NULL, ZEND_ACC_PUBLIC)
+ {NULL, NULL, NULL}
+};
+
+zend_class_entry* bool_value_type;
+
+// Init class entry.
+PHP_PROTO_INIT_SUBMSGCLASS_START("Google\\Protobuf\\BoolValue",
+ BoolValue, bool_value)
+ zend_class_implements(bool_value_type TSRMLS_CC, 1, message_type);
+ zend_declare_property_null(bool_value_type, "value", strlen("value"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+PHP_PROTO_INIT_SUBMSGCLASS_END
+
+PHP_METHOD(BoolValue, __construct) {
+ init_file_wrappers(TSRMLS_C);
+ MessageHeader* intern = UNBOX(MessageHeader, getThis());
+ custom_data_init(bool_value_type, intern PHP_PROTO_TSRMLS_CC);
+}
+
+PHP_PROTO_FIELD_ACCESSORS(BoolValue, bool_value, Value, "value")
+
+// -----------------------------------------------------------------------------
+// BytesValue
+// -----------------------------------------------------------------------------
+
+static zend_function_entry bytes_value_methods[] = {
+ PHP_ME(BytesValue, __construct, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(BytesValue, getValue, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(BytesValue, setValue, NULL, ZEND_ACC_PUBLIC)
+ {NULL, NULL, NULL}
+};
+
+zend_class_entry* bytes_value_type;
+
+// Init class entry.
+PHP_PROTO_INIT_SUBMSGCLASS_START("Google\\Protobuf\\BytesValue",
+ BytesValue, bytes_value)
+ zend_class_implements(bytes_value_type TSRMLS_CC, 1, message_type);
+ zend_declare_property_null(bytes_value_type, "value", strlen("value"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+PHP_PROTO_INIT_SUBMSGCLASS_END
+
+PHP_METHOD(BytesValue, __construct) {
+ init_file_wrappers(TSRMLS_C);
+ MessageHeader* intern = UNBOX(MessageHeader, getThis());
+ custom_data_init(bytes_value_type, intern PHP_PROTO_TSRMLS_CC);
+}
+
+PHP_PROTO_FIELD_ACCESSORS(BytesValue, bytes_value, Value, "value")
+
+// -----------------------------------------------------------------------------
+// DoubleValue
+// -----------------------------------------------------------------------------
+
+static zend_function_entry double_value_methods[] = {
+ PHP_ME(DoubleValue, __construct, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(DoubleValue, getValue, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(DoubleValue, setValue, NULL, ZEND_ACC_PUBLIC)
+ {NULL, NULL, NULL}
+};
+
+zend_class_entry* double_value_type;
+
+// Init class entry.
+PHP_PROTO_INIT_SUBMSGCLASS_START("Google\\Protobuf\\DoubleValue",
+ DoubleValue, double_value)
+ zend_class_implements(double_value_type TSRMLS_CC, 1, message_type);
+ zend_declare_property_null(double_value_type, "value", strlen("value"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+PHP_PROTO_INIT_SUBMSGCLASS_END
+
+PHP_METHOD(DoubleValue, __construct) {
+ init_file_wrappers(TSRMLS_C);
+ MessageHeader* intern = UNBOX(MessageHeader, getThis());
+ custom_data_init(double_value_type, intern PHP_PROTO_TSRMLS_CC);
+}
+
+PHP_PROTO_FIELD_ACCESSORS(DoubleValue, double_value, Value, "value")
+
+// -----------------------------------------------------------------------------
+// Enum
+// -----------------------------------------------------------------------------
+
+static zend_function_entry enum_methods[] = {
+ PHP_ME(Enum, __construct, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Enum, getName, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Enum, setName, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Enum, getEnumvalue, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Enum, setEnumvalue, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Enum, getOptions, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Enum, setOptions, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Enum, getSourceContext, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Enum, setSourceContext, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Enum, getSyntax, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Enum, setSyntax, NULL, ZEND_ACC_PUBLIC)
+ {NULL, NULL, NULL}
+};
+
+zend_class_entry* enum_type;
+
+// Init class entry.
+PHP_PROTO_INIT_SUBMSGCLASS_START("Google\\Protobuf\\Enum",
+ Enum, enum)
+ zend_class_implements(enum_type TSRMLS_CC, 1, message_type);
+ zend_declare_property_null(enum_type, "name", strlen("name"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+ zend_declare_property_null(enum_type, "enumvalue", strlen("enumvalue"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+ zend_declare_property_null(enum_type, "options", strlen("options"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+ zend_declare_property_null(enum_type, "source_context", strlen("source_context"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+ zend_declare_property_null(enum_type, "syntax", strlen("syntax"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+PHP_PROTO_INIT_SUBMSGCLASS_END
+
+PHP_METHOD(Enum, __construct) {
+ init_file_type(TSRMLS_C);
+ MessageHeader* intern = UNBOX(MessageHeader, getThis());
+ custom_data_init(enum_type, intern PHP_PROTO_TSRMLS_CC);
+}
+
+PHP_PROTO_FIELD_ACCESSORS(Enum, enum, Name, "name")
+PHP_PROTO_FIELD_ACCESSORS(Enum, enum, Enumvalue, "enumvalue")
+PHP_PROTO_FIELD_ACCESSORS(Enum, enum, Options, "options")
+PHP_PROTO_FIELD_ACCESSORS(Enum, enum, SourceContext, "source_context")
+PHP_PROTO_FIELD_ACCESSORS(Enum, enum, Syntax, "syntax")
+
+// -----------------------------------------------------------------------------
+// EnumValue
+// -----------------------------------------------------------------------------
+
+static zend_function_entry enum_value_methods[] = {
+ PHP_ME(EnumValue, __construct, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(EnumValue, getName, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(EnumValue, setName, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(EnumValue, getNumber, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(EnumValue, setNumber, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(EnumValue, getOptions, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(EnumValue, setOptions, NULL, ZEND_ACC_PUBLIC)
+ {NULL, NULL, NULL}
+};
+
+zend_class_entry* enum_value_type;
+
+// Init class entry.
+PHP_PROTO_INIT_SUBMSGCLASS_START("Google\\Protobuf\\EnumValue",
+ EnumValue, enum_value)
+ zend_class_implements(enum_value_type TSRMLS_CC, 1, message_type);
+ zend_declare_property_null(enum_value_type, "name", strlen("name"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+ zend_declare_property_null(enum_value_type, "number", strlen("number"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+ zend_declare_property_null(enum_value_type, "options", strlen("options"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+PHP_PROTO_INIT_SUBMSGCLASS_END
+
+PHP_METHOD(EnumValue, __construct) {
+ init_file_type(TSRMLS_C);
+ MessageHeader* intern = UNBOX(MessageHeader, getThis());
+ custom_data_init(enum_value_type, intern PHP_PROTO_TSRMLS_CC);
+}
+
+PHP_PROTO_FIELD_ACCESSORS(EnumValue, enum_value, Name, "name")
+PHP_PROTO_FIELD_ACCESSORS(EnumValue, enum_value, Number, "number")
+PHP_PROTO_FIELD_ACCESSORS(EnumValue, enum_value, Options, "options")
+
+// -----------------------------------------------------------------------------
+// FieldMask
+// -----------------------------------------------------------------------------
+
+static zend_function_entry field_mask_methods[] = {
+ PHP_ME(FieldMask, __construct, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(FieldMask, getPaths, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(FieldMask, setPaths, NULL, ZEND_ACC_PUBLIC)
+ {NULL, NULL, NULL}
+};
+
+zend_class_entry* field_mask_type;
+
+// Init class entry.
+PHP_PROTO_INIT_SUBMSGCLASS_START("Google\\Protobuf\\FieldMask",
+ FieldMask, field_mask)
+ zend_class_implements(field_mask_type TSRMLS_CC, 1, message_type);
+ zend_declare_property_null(field_mask_type, "paths", strlen("paths"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+PHP_PROTO_INIT_SUBMSGCLASS_END
+
+PHP_METHOD(FieldMask, __construct) {
+ init_file_field_mask(TSRMLS_C);
+ MessageHeader* intern = UNBOX(MessageHeader, getThis());
+ custom_data_init(field_mask_type, intern PHP_PROTO_TSRMLS_CC);
+}
+
+PHP_PROTO_FIELD_ACCESSORS(FieldMask, field_mask, Paths, "paths")
+
+// -----------------------------------------------------------------------------
+// Field
+// -----------------------------------------------------------------------------
+
+static zend_function_entry field_methods[] = {
+ PHP_ME(Field, __construct, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Field, getKind, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Field, setKind, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Field, getCardinality, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Field, setCardinality, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Field, getNumber, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Field, setNumber, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Field, getName, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Field, setName, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Field, getTypeUrl, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Field, setTypeUrl, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Field, getOneofIndex, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Field, setOneofIndex, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Field, getPacked, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Field, setPacked, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Field, getOptions, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Field, setOptions, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Field, getJsonName, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Field, setJsonName, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Field, getDefaultValue, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Field, setDefaultValue, NULL, ZEND_ACC_PUBLIC)
+ {NULL, NULL, NULL}
+};
+
+zend_class_entry* field_type;
+
+// Init class entry.
+PHP_PROTO_INIT_SUBMSGCLASS_START("Google\\Protobuf\\Field",
+ Field, field)
+ zend_class_implements(field_type TSRMLS_CC, 1, message_type);
+ zend_declare_property_null(field_type, "kind", strlen("kind"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+ zend_declare_property_null(field_type, "cardinality", strlen("cardinality"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+ zend_declare_property_null(field_type, "number", strlen("number"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+ zend_declare_property_null(field_type, "name", strlen("name"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+ zend_declare_property_null(field_type, "type_url", strlen("type_url"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+ zend_declare_property_null(field_type, "oneof_index", strlen("oneof_index"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+ zend_declare_property_null(field_type, "packed", strlen("packed"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+ zend_declare_property_null(field_type, "options", strlen("options"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+ zend_declare_property_null(field_type, "json_name", strlen("json_name"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+ zend_declare_property_null(field_type, "default_value", strlen("default_value"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+PHP_PROTO_INIT_SUBMSGCLASS_END
+
+PHP_METHOD(Field, __construct) {
+ init_file_type(TSRMLS_C);
+ MessageHeader* intern = UNBOX(MessageHeader, getThis());
+ custom_data_init(field_type, intern PHP_PROTO_TSRMLS_CC);
+}
+
+PHP_PROTO_FIELD_ACCESSORS(Field, field, Kind, "kind")
+PHP_PROTO_FIELD_ACCESSORS(Field, field, Cardinality, "cardinality")
+PHP_PROTO_FIELD_ACCESSORS(Field, field, Number, "number")
+PHP_PROTO_FIELD_ACCESSORS(Field, field, Name, "name")
+PHP_PROTO_FIELD_ACCESSORS(Field, field, TypeUrl, "type_url")
+PHP_PROTO_FIELD_ACCESSORS(Field, field, OneofIndex, "oneof_index")
+PHP_PROTO_FIELD_ACCESSORS(Field, field, Packed, "packed")
+PHP_PROTO_FIELD_ACCESSORS(Field, field, Options, "options")
+PHP_PROTO_FIELD_ACCESSORS(Field, field, JsonName, "json_name")
+PHP_PROTO_FIELD_ACCESSORS(Field, field, DefaultValue, "default_value")
+
+// -----------------------------------------------------------------------------
+// FloatValue
+// -----------------------------------------------------------------------------
+
+static zend_function_entry float_value_methods[] = {
+ PHP_ME(FloatValue, __construct, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(FloatValue, getValue, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(FloatValue, setValue, NULL, ZEND_ACC_PUBLIC)
+ {NULL, NULL, NULL}
+};
+
+zend_class_entry* float_value_type;
+
+// Init class entry.
+PHP_PROTO_INIT_SUBMSGCLASS_START("Google\\Protobuf\\FloatValue",
+ FloatValue, float_value)
+ zend_class_implements(float_value_type TSRMLS_CC, 1, message_type);
+ zend_declare_property_null(float_value_type, "value", strlen("value"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+PHP_PROTO_INIT_SUBMSGCLASS_END
+
+PHP_METHOD(FloatValue, __construct) {
+ init_file_wrappers(TSRMLS_C);
+ MessageHeader* intern = UNBOX(MessageHeader, getThis());
+ custom_data_init(float_value_type, intern PHP_PROTO_TSRMLS_CC);
+}
+
+PHP_PROTO_FIELD_ACCESSORS(FloatValue, float_value, Value, "value")
+
+// -----------------------------------------------------------------------------
+// GPBEmpty
+// -----------------------------------------------------------------------------
+
+static zend_function_entry empty_methods[] = {
+ PHP_ME(GPBEmpty, __construct, NULL, ZEND_ACC_PUBLIC)
+ {NULL, NULL, NULL}
+};
+
+zend_class_entry* empty_type;
+
+// Init class entry.
+PHP_PROTO_INIT_SUBMSGCLASS_START("Google\\Protobuf\\GPBEmpty",
+ GPBEmpty, empty)
+ zend_class_implements(empty_type TSRMLS_CC, 1, message_type);
+PHP_PROTO_INIT_SUBMSGCLASS_END
+
+PHP_METHOD(GPBEmpty, __construct) {
+ init_file_empty(TSRMLS_C);
+ MessageHeader* intern = UNBOX(MessageHeader, getThis());
+ custom_data_init(empty_type, intern PHP_PROTO_TSRMLS_CC);
+}
+
+
+// -----------------------------------------------------------------------------
+// Int32Value
+// -----------------------------------------------------------------------------
+
+static zend_function_entry int32_value_methods[] = {
+ PHP_ME(Int32Value, __construct, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Int32Value, getValue, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Int32Value, setValue, NULL, ZEND_ACC_PUBLIC)
+ {NULL, NULL, NULL}
+};
+
+zend_class_entry* int32_value_type;
+
+// Init class entry.
+PHP_PROTO_INIT_SUBMSGCLASS_START("Google\\Protobuf\\Int32Value",
+ Int32Value, int32_value)
+ zend_class_implements(int32_value_type TSRMLS_CC, 1, message_type);
+ zend_declare_property_null(int32_value_type, "value", strlen("value"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+PHP_PROTO_INIT_SUBMSGCLASS_END
+
+PHP_METHOD(Int32Value, __construct) {
+ init_file_wrappers(TSRMLS_C);
+ MessageHeader* intern = UNBOX(MessageHeader, getThis());
+ custom_data_init(int32_value_type, intern PHP_PROTO_TSRMLS_CC);
+}
+
+PHP_PROTO_FIELD_ACCESSORS(Int32Value, int32_value, Value, "value")
+
+// -----------------------------------------------------------------------------
+// Int64Value
+// -----------------------------------------------------------------------------
+
+static zend_function_entry int64_value_methods[] = {
+ PHP_ME(Int64Value, __construct, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Int64Value, getValue, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Int64Value, setValue, NULL, ZEND_ACC_PUBLIC)
+ {NULL, NULL, NULL}
+};
+
+zend_class_entry* int64_value_type;
+
+// Init class entry.
+PHP_PROTO_INIT_SUBMSGCLASS_START("Google\\Protobuf\\Int64Value",
+ Int64Value, int64_value)
+ zend_class_implements(int64_value_type TSRMLS_CC, 1, message_type);
+ zend_declare_property_null(int64_value_type, "value", strlen("value"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+PHP_PROTO_INIT_SUBMSGCLASS_END
+
+PHP_METHOD(Int64Value, __construct) {
+ init_file_wrappers(TSRMLS_C);
+ MessageHeader* intern = UNBOX(MessageHeader, getThis());
+ custom_data_init(int64_value_type, intern PHP_PROTO_TSRMLS_CC);
+}
+
+PHP_PROTO_FIELD_ACCESSORS(Int64Value, int64_value, Value, "value")
+
+// -----------------------------------------------------------------------------
+// ListValue
+// -----------------------------------------------------------------------------
+
+static zend_function_entry list_value_methods[] = {
+ PHP_ME(ListValue, __construct, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(ListValue, getValues, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(ListValue, setValues, NULL, ZEND_ACC_PUBLIC)
+ {NULL, NULL, NULL}
+};
+
+zend_class_entry* list_value_type;
+
+// Init class entry.
+PHP_PROTO_INIT_SUBMSGCLASS_START("Google\\Protobuf\\ListValue",
+ ListValue, list_value)
+ zend_class_implements(list_value_type TSRMLS_CC, 1, message_type);
+ zend_declare_property_null(list_value_type, "values", strlen("values"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+PHP_PROTO_INIT_SUBMSGCLASS_END
+
+PHP_METHOD(ListValue, __construct) {
+ init_file_struct(TSRMLS_C);
+ MessageHeader* intern = UNBOX(MessageHeader, getThis());
+ custom_data_init(list_value_type, intern PHP_PROTO_TSRMLS_CC);
+}
+
+PHP_PROTO_FIELD_ACCESSORS(ListValue, list_value, Values, "values")
+
+// -----------------------------------------------------------------------------
+// Method
+// -----------------------------------------------------------------------------
+
+static zend_function_entry method_methods[] = {
+ PHP_ME(Method, __construct, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Method, getName, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Method, setName, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Method, getRequestTypeUrl, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Method, setRequestTypeUrl, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Method, getRequestStreaming, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Method, setRequestStreaming, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Method, getResponseTypeUrl, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Method, setResponseTypeUrl, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Method, getResponseStreaming, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Method, setResponseStreaming, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Method, getOptions, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Method, setOptions, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Method, getSyntax, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Method, setSyntax, NULL, ZEND_ACC_PUBLIC)
+ {NULL, NULL, NULL}
+};
+
+zend_class_entry* method_type;
+
+// Init class entry.
+PHP_PROTO_INIT_SUBMSGCLASS_START("Google\\Protobuf\\Method",
+ Method, method)
+ zend_class_implements(method_type TSRMLS_CC, 1, message_type);
+ zend_declare_property_null(method_type, "name", strlen("name"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+ zend_declare_property_null(method_type, "request_type_url", strlen("request_type_url"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+ zend_declare_property_null(method_type, "request_streaming", strlen("request_streaming"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+ zend_declare_property_null(method_type, "response_type_url", strlen("response_type_url"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+ zend_declare_property_null(method_type, "response_streaming", strlen("response_streaming"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+ zend_declare_property_null(method_type, "options", strlen("options"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+ zend_declare_property_null(method_type, "syntax", strlen("syntax"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+PHP_PROTO_INIT_SUBMSGCLASS_END
+
+PHP_METHOD(Method, __construct) {
+ init_file_api(TSRMLS_C);
+ MessageHeader* intern = UNBOX(MessageHeader, getThis());
+ custom_data_init(method_type, intern PHP_PROTO_TSRMLS_CC);
+}
+
+PHP_PROTO_FIELD_ACCESSORS(Method, method, Name, "name")
+PHP_PROTO_FIELD_ACCESSORS(Method, method, RequestTypeUrl, "request_type_url")
+PHP_PROTO_FIELD_ACCESSORS(Method, method, RequestStreaming, "request_streaming")
+PHP_PROTO_FIELD_ACCESSORS(Method, method, ResponseTypeUrl, "response_type_url")
+PHP_PROTO_FIELD_ACCESSORS(Method, method, ResponseStreaming, "response_streaming")
+PHP_PROTO_FIELD_ACCESSORS(Method, method, Options, "options")
+PHP_PROTO_FIELD_ACCESSORS(Method, method, Syntax, "syntax")
+
+// -----------------------------------------------------------------------------
+// Mixin
+// -----------------------------------------------------------------------------
+
+static zend_function_entry mixin_methods[] = {
+ PHP_ME(Mixin, __construct, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Mixin, getName, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Mixin, setName, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Mixin, getRoot, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Mixin, setRoot, NULL, ZEND_ACC_PUBLIC)
+ {NULL, NULL, NULL}
+};
+
+zend_class_entry* mixin_type;
+
+// Init class entry.
+PHP_PROTO_INIT_SUBMSGCLASS_START("Google\\Protobuf\\Mixin",
+ Mixin, mixin)
+ zend_class_implements(mixin_type TSRMLS_CC, 1, message_type);
+ zend_declare_property_null(mixin_type, "name", strlen("name"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+ zend_declare_property_null(mixin_type, "root", strlen("root"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+PHP_PROTO_INIT_SUBMSGCLASS_END
+
+PHP_METHOD(Mixin, __construct) {
+ init_file_api(TSRMLS_C);
+ MessageHeader* intern = UNBOX(MessageHeader, getThis());
+ custom_data_init(mixin_type, intern PHP_PROTO_TSRMLS_CC);
+}
+
+PHP_PROTO_FIELD_ACCESSORS(Mixin, mixin, Name, "name")
+PHP_PROTO_FIELD_ACCESSORS(Mixin, mixin, Root, "root")
+
+// -----------------------------------------------------------------------------
+// Option
+// -----------------------------------------------------------------------------
+
+static zend_function_entry option_methods[] = {
+ PHP_ME(Option, __construct, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Option, getName, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Option, setName, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Option, getValue, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Option, setValue, NULL, ZEND_ACC_PUBLIC)
+ {NULL, NULL, NULL}
+};
+
+zend_class_entry* option_type;
+
+// Init class entry.
+PHP_PROTO_INIT_SUBMSGCLASS_START("Google\\Protobuf\\Option",
+ Option, option)
+ zend_class_implements(option_type TSRMLS_CC, 1, message_type);
+ zend_declare_property_null(option_type, "name", strlen("name"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+ zend_declare_property_null(option_type, "value", strlen("value"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+PHP_PROTO_INIT_SUBMSGCLASS_END
+
+PHP_METHOD(Option, __construct) {
+ init_file_type(TSRMLS_C);
+ MessageHeader* intern = UNBOX(MessageHeader, getThis());
+ custom_data_init(option_type, intern PHP_PROTO_TSRMLS_CC);
+}
+
+PHP_PROTO_FIELD_ACCESSORS(Option, option, Name, "name")
+PHP_PROTO_FIELD_ACCESSORS(Option, option, Value, "value")
+
+// -----------------------------------------------------------------------------
+// SourceContext
+// -----------------------------------------------------------------------------
+
+static zend_function_entry source_context_methods[] = {
+ PHP_ME(SourceContext, __construct, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(SourceContext, getFileName, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(SourceContext, setFileName, NULL, ZEND_ACC_PUBLIC)
+ {NULL, NULL, NULL}
+};
+
+zend_class_entry* source_context_type;
+
+// Init class entry.
+PHP_PROTO_INIT_SUBMSGCLASS_START("Google\\Protobuf\\SourceContext",
+ SourceContext, source_context)
+ zend_class_implements(source_context_type TSRMLS_CC, 1, message_type);
+ zend_declare_property_null(source_context_type, "file_name", strlen("file_name"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+PHP_PROTO_INIT_SUBMSGCLASS_END
+
+PHP_METHOD(SourceContext, __construct) {
+ init_file_source_context(TSRMLS_C);
+ MessageHeader* intern = UNBOX(MessageHeader, getThis());
+ custom_data_init(source_context_type, intern PHP_PROTO_TSRMLS_CC);
+}
+
+PHP_PROTO_FIELD_ACCESSORS(SourceContext, source_context, FileName, "file_name")
+
+// -----------------------------------------------------------------------------
+// StringValue
+// -----------------------------------------------------------------------------
+
+static zend_function_entry string_value_methods[] = {
+ PHP_ME(StringValue, __construct, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(StringValue, getValue, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(StringValue, setValue, NULL, ZEND_ACC_PUBLIC)
+ {NULL, NULL, NULL}
+};
+
+zend_class_entry* string_value_type;
+
+// Init class entry.
+PHP_PROTO_INIT_SUBMSGCLASS_START("Google\\Protobuf\\StringValue",
+ StringValue, string_value)
+ zend_class_implements(string_value_type TSRMLS_CC, 1, message_type);
+ zend_declare_property_null(string_value_type, "value", strlen("value"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+PHP_PROTO_INIT_SUBMSGCLASS_END
+
+PHP_METHOD(StringValue, __construct) {
+ init_file_wrappers(TSRMLS_C);
+ MessageHeader* intern = UNBOX(MessageHeader, getThis());
+ custom_data_init(string_value_type, intern PHP_PROTO_TSRMLS_CC);
+}
+
+PHP_PROTO_FIELD_ACCESSORS(StringValue, string_value, Value, "value")
+
+// -----------------------------------------------------------------------------
+// Struct
+// -----------------------------------------------------------------------------
+
+static zend_function_entry struct_methods[] = {
+ PHP_ME(Struct, __construct, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Struct, getFields, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Struct, setFields, NULL, ZEND_ACC_PUBLIC)
+ {NULL, NULL, NULL}
+};
+
+zend_class_entry* struct_type;
+
+// Init class entry.
+PHP_PROTO_INIT_SUBMSGCLASS_START("Google\\Protobuf\\Struct",
+ Struct, struct)
+ zend_class_implements(struct_type TSRMLS_CC, 1, message_type);
+ zend_declare_property_null(struct_type, "fields", strlen("fields"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+PHP_PROTO_INIT_SUBMSGCLASS_END
+
+PHP_METHOD(Struct, __construct) {
+ init_file_struct(TSRMLS_C);
+ MessageHeader* intern = UNBOX(MessageHeader, getThis());
+ custom_data_init(struct_type, intern PHP_PROTO_TSRMLS_CC);
+}
+
+PHP_PROTO_FIELD_ACCESSORS(Struct, struct, Fields, "fields")
+
+// -----------------------------------------------------------------------------
+// Type
+// -----------------------------------------------------------------------------
+
+static zend_function_entry type_methods[] = {
+ PHP_ME(Type, __construct, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Type, getName, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Type, setName, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Type, getFields, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Type, setFields, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Type, getOneofs, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Type, setOneofs, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Type, getOptions, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Type, setOptions, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Type, getSourceContext, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Type, setSourceContext, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Type, getSyntax, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Type, setSyntax, NULL, ZEND_ACC_PUBLIC)
+ {NULL, NULL, NULL}
+};
+
+zend_class_entry* type_type;
+
+// Init class entry.
+PHP_PROTO_INIT_SUBMSGCLASS_START("Google\\Protobuf\\Type",
+ Type, type)
+ zend_class_implements(type_type TSRMLS_CC, 1, message_type);
+ zend_declare_property_null(type_type, "name", strlen("name"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+ zend_declare_property_null(type_type, "fields", strlen("fields"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+ zend_declare_property_null(type_type, "oneofs", strlen("oneofs"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+ zend_declare_property_null(type_type, "options", strlen("options"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+ zend_declare_property_null(type_type, "source_context", strlen("source_context"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+ zend_declare_property_null(type_type, "syntax", strlen("syntax"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+PHP_PROTO_INIT_SUBMSGCLASS_END
+
+PHP_METHOD(Type, __construct) {
+ init_file_type(TSRMLS_C);
+ MessageHeader* intern = UNBOX(MessageHeader, getThis());
+ custom_data_init(type_type, intern PHP_PROTO_TSRMLS_CC);
+}
+
+PHP_PROTO_FIELD_ACCESSORS(Type, type, Name, "name")
+PHP_PROTO_FIELD_ACCESSORS(Type, type, Fields, "fields")
+PHP_PROTO_FIELD_ACCESSORS(Type, type, Oneofs, "oneofs")
+PHP_PROTO_FIELD_ACCESSORS(Type, type, Options, "options")
+PHP_PROTO_FIELD_ACCESSORS(Type, type, SourceContext, "source_context")
+PHP_PROTO_FIELD_ACCESSORS(Type, type, Syntax, "syntax")
+
+// -----------------------------------------------------------------------------
+// UInt32Value
+// -----------------------------------------------------------------------------
+
+static zend_function_entry u_int32_value_methods[] = {
+ PHP_ME(UInt32Value, __construct, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(UInt32Value, getValue, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(UInt32Value, setValue, NULL, ZEND_ACC_PUBLIC)
+ {NULL, NULL, NULL}
+};
+
+zend_class_entry* u_int32_value_type;
+
+// Init class entry.
+PHP_PROTO_INIT_SUBMSGCLASS_START("Google\\Protobuf\\UInt32Value",
+ UInt32Value, u_int32_value)
+ zend_class_implements(u_int32_value_type TSRMLS_CC, 1, message_type);
+ zend_declare_property_null(u_int32_value_type, "value", strlen("value"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+PHP_PROTO_INIT_SUBMSGCLASS_END
+
+PHP_METHOD(UInt32Value, __construct) {
+ init_file_wrappers(TSRMLS_C);
+ MessageHeader* intern = UNBOX(MessageHeader, getThis());
+ custom_data_init(u_int32_value_type, intern PHP_PROTO_TSRMLS_CC);
+}
+
+PHP_PROTO_FIELD_ACCESSORS(UInt32Value, u_int32_value, Value, "value")
+
+// -----------------------------------------------------------------------------
+// UInt64Value
+// -----------------------------------------------------------------------------
+
+static zend_function_entry u_int64_value_methods[] = {
+ PHP_ME(UInt64Value, __construct, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(UInt64Value, getValue, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(UInt64Value, setValue, NULL, ZEND_ACC_PUBLIC)
+ {NULL, NULL, NULL}
+};
+
+zend_class_entry* u_int64_value_type;
+
+// Init class entry.
+PHP_PROTO_INIT_SUBMSGCLASS_START("Google\\Protobuf\\UInt64Value",
+ UInt64Value, u_int64_value)
+ zend_class_implements(u_int64_value_type TSRMLS_CC, 1, message_type);
+ zend_declare_property_null(u_int64_value_type, "value", strlen("value"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+PHP_PROTO_INIT_SUBMSGCLASS_END
+
+PHP_METHOD(UInt64Value, __construct) {
+ init_file_wrappers(TSRMLS_C);
+ MessageHeader* intern = UNBOX(MessageHeader, getThis());
+ custom_data_init(u_int64_value_type, intern PHP_PROTO_TSRMLS_CC);
+}
+
+PHP_PROTO_FIELD_ACCESSORS(UInt64Value, u_int64_value, Value, "value")
+
+// -----------------------------------------------------------------------------
+// Value
+// -----------------------------------------------------------------------------
+
+static zend_function_entry value_methods[] = {
+ PHP_ME(Value, __construct, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Value, getNullValue, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Value, setNullValue, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Value, getNumberValue, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Value, setNumberValue, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Value, getStringValue, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Value, setStringValue, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Value, getBoolValue, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Value, setBoolValue, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Value, getStructValue, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Value, setStructValue, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Value, getListValue, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Value, setListValue, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Value, getKind, NULL, ZEND_ACC_PUBLIC)
+ {NULL, NULL, NULL}
+};
+
+zend_class_entry* value_type;
+
+// Init class entry.
+PHP_PROTO_INIT_SUBMSGCLASS_START("Google\\Protobuf\\Value",
+ Value, value)
+ zend_class_implements(value_type TSRMLS_CC, 1, message_type);
+ zend_declare_property_null(value_type, "kind", strlen("kind"),
+ ZEND_ACC_PRIVATE TSRMLS_CC);
+PHP_PROTO_INIT_SUBMSGCLASS_END
+
+PHP_METHOD(Value, __construct) {
+ init_file_struct(TSRMLS_C);
+ MessageHeader* intern = UNBOX(MessageHeader, getThis());
+ custom_data_init(value_type, intern PHP_PROTO_TSRMLS_CC);
+}
+
+PHP_PROTO_ONEOF_FIELD_ACCESSORS(Value, value, NullValue, "null_value")
+PHP_PROTO_ONEOF_FIELD_ACCESSORS(Value, value, NumberValue, "number_value")
+PHP_PROTO_ONEOF_FIELD_ACCESSORS(Value, value, StringValue, "string_value")
+PHP_PROTO_ONEOF_FIELD_ACCESSORS(Value, value, BoolValue, "bool_value")
+PHP_PROTO_ONEOF_FIELD_ACCESSORS(Value, value, StructValue, "struct_value")
+PHP_PROTO_ONEOF_FIELD_ACCESSORS(Value, value, ListValue, "list_value")
+PHP_PROTO_ONEOF_ACCESSORS(Value, value, Kind, "kind")
+
+// -----------------------------------------------------------------------------
+// GPBMetadata files for well known types
+// -----------------------------------------------------------------------------
+
+#define DEFINE_GPBMETADATA_FILE(LOWERNAME, CAMELNAME, CLASSNAME) \
+ zend_class_entry* gpb_metadata_##LOWERNAME##_type; \
+ static zend_function_entry gpb_metadata_##LOWERNAME##_methods[] = { \
+ PHP_ME(GPBMetadata_##CAMELNAME, initOnce, NULL, \
+ ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) \
+ ZEND_FE_END \
+ }; \
+ void gpb_metadata_##LOWERNAME##_init(TSRMLS_D) { \
+ zend_class_entry class_type; \
+ INIT_CLASS_ENTRY(class_type, CLASSNAME, \
+ gpb_metadata_##LOWERNAME##_methods); \
+ gpb_metadata_##LOWERNAME##_type = \
+ zend_register_internal_class(&class_type TSRMLS_CC); \
+ } \
+ PHP_METHOD(GPBMetadata_##CAMELNAME, initOnce) { \
+ init_file_##LOWERNAME(TSRMLS_C); \
+ }
+
+DEFINE_GPBMETADATA_FILE(any, Any, "GPBMetadata\\Google\\Protobuf\\Any");
+DEFINE_GPBMETADATA_FILE(api, Api, "GPBMetadata\\Google\\Protobuf\\Api");
+DEFINE_GPBMETADATA_FILE(duration, Duration,
+ "GPBMetadata\\Google\\Protobuf\\Duration");
+DEFINE_GPBMETADATA_FILE(field_mask, FieldMask,
+ "GPBMetadata\\Google\\Protobuf\\FieldMask");
+DEFINE_GPBMETADATA_FILE(empty, Empty,
+ "GPBMetadata\\Google\\Protobuf\\GPBEmpty");
+DEFINE_GPBMETADATA_FILE(source_context, SourceContext,
+ "GPBMetadata\\Google\\Protobuf\\SourceContext");
+DEFINE_GPBMETADATA_FILE(struct, Struct,
+ "GPBMetadata\\Google\\Protobuf\\Struct");
+DEFINE_GPBMETADATA_FILE(timestamp, Timestamp,
+ "GPBMetadata\\Google\\Protobuf\\Timestamp");
+DEFINE_GPBMETADATA_FILE(type, Type, "GPBMetadata\\Google\\Protobuf\\Type");
+DEFINE_GPBMETADATA_FILE(wrappers, Wrappers,
+ "GPBMetadata\\Google\\Protobuf\\Wrappers");
+
+#undef DEFINE_GPBMETADATA_FILE
diff --git a/php/ext/google/protobuf/package.xml b/php/ext/google/protobuf/package.xml
index 01aad411..4a473801 100644
--- a/php/ext/google/protobuf/package.xml
+++ b/php/ext/google/protobuf/package.xml
@@ -10,19 +10,19 @@
<email>protobuf-opensource@google.com</email>
<active>yes</active>
</lead>
- <date>2016-09-23</date>
- <time>16:06:07</time>
+ <date>2017-09-14</date>
+ <time>11:02:07</time>
<version>
- <release>3.1.0a1</release>
- <api>3.1.0a1</api>
+ <release>3.4.1</release>
+ <api>3.4.1</api>
</version>
<stability>
- <release>alpha</release>
- <api>alpha</api>
+ <release>stable</release>
+ <api>stable</api>
</stability>
- <license uri="http://www.opensource.org/licenses/bsd-license.php">New BSD License</license>
+ <license uri="https://opensource.org/licenses/BSD-3-Clause">3-Clause BSD License</license>
<notes>
-First alpha release.
+GA release.
</notes>
<contents>
<dir baseinstalldir="/" name="/">
@@ -40,6 +40,7 @@ First alpha release.
<file baseinstalldir="/" name="upb.h" role="src" />
<file baseinstalldir="/" name="utf8.c" role="src" />
<file baseinstalldir="/" name="utf8.h" role="src" />
+ <file baseinstalldir="/" name="LICENSE" role="doc" />
</dir>
</contents>
<dependencies>
@@ -66,10 +67,106 @@ First alpha release.
</stability>
<date>2016-09-23</date>
<time>16:06:07</time>
- <license uri="http://www.opensource.org/licenses/bsd-license.php">New BSD License</license>
+ <license uri="https://opensource.org/licenses/BSD-3-Clause">3-Clause BSD License</license>
<notes>
First alpha release
</notes>
</release>
+ <release>
+ <version>
+ <release>3.2.0a1</release>
+ <api>3.2.0a1</api>
+ </version>
+ <stability>
+ <release>alpha</release>
+ <api>alpha</api>
+ </stability>
+ <date>2017-01-13</date>
+ <time>16:06:07</time>
+ <license uri="https://opensource.org/licenses/BSD-3-Clause">3-Clause BSD License</license>
+ <notes>
+Second alpha release.
+ </notes>
+ </release>
+ <release>
+ <version>
+ <release>3.3.0</release>
+ <api>3.3.0</api>
+ </version>
+ <stability>
+ <release>stable</release>
+ <api>stable</api>
+ </stability>
+ <date>2017-04-28</date>
+ <time>16:06:07</time>
+ <license uri="https://opensource.org/licenses/BSD-3-Clause">3-Clause BSD License</license>
+ <notes>
+GA release.
+ </notes>
+ </release>
+ <release>
+ <version>
+ <release>3.3.1</release>
+ <api>3.3.0</api>
+ </version>
+ <stability>
+ <release>stable</release>
+ <api>stable</api>
+ </stability>
+ <date>2017-05-08</date>
+ <time>15:33:07</time>
+ <license uri="https://opensource.org/licenses/BSD-3-Clause">3-Clause BSD License</license>
+ <notes>
+GA release.
+ </notes>
+ </release>
+ <release>
+ <version>
+ <release>3.3.2</release>
+ <api>3.3.0</api>
+ </version>
+ <stability>
+ <release>stable</release>
+ <api>stable</api>
+ </stability>
+ <date>2017-06-21</date>
+ <time>15:33:07</time>
+ <license uri="https://opensource.org/licenses/BSD-3-Clause">3-Clause BSD License</license>
+ <notes>
+GA release.
+ </notes>
+ </release>
+ <release>
+ <version>
+ <release>3.4.0</release>
+ <api>3.4.0</api>
+ </version>
+ <stability>
+ <release>stable</release>
+ <api>stable</api>
+ </stability>
+ <date>2017-08-16</date>
+ <time>15:33:07</time>
+ <license uri="https://opensource.org/licenses/BSD-3-Clause">3-Clause BSD License</license>
+ <notes>
+GA release.
+ </notes>
+ </release>
+ <release>
+ <version>
+ <release>3.4.1</release>
+ <api>3.4.1</api>
+ </version>
+ <stability>
+ <release>stable</release>
+ <api>stable</api>
+ </stability>
+ <date>2017-09-14</date>
+ <time>11:02:07</time>
+ <license uri="https://opensource.org/licenses/BSD-3-Clause">3-Clause BSD License</license>
+ <notes>
+GA release.
+ </notes>
+ </release>
</changelog>
</package>
diff --git a/php/ext/google/protobuf/protobuf.c b/php/ext/google/protobuf/protobuf.c
index ea85b999..265d636e 100644
--- a/php/ext/google/protobuf/protobuf.c
+++ b/php/ext/google/protobuf/protobuf.c
@@ -46,6 +46,10 @@ static HashTable* upb_def_to_php_obj_map;
// Global map from message/enum's php class entry to corresponding wrapper
// Descriptor/EnumDescriptor instances.
static HashTable* ce_to_php_obj_map;
+// Global map from message/enum's proto fully-qualified name to corresponding
+// wrapper Descriptor/EnumDescriptor instances.
+static HashTable* proto_to_php_obj_map;
+static HashTable* reserved_names;
// -----------------------------------------------------------------------------
// Global maps.
@@ -55,39 +59,119 @@ static void add_to_table(HashTable* t, const void* def, void* value) {
uint nIndex = (ulong)def & t->nTableMask;
zval* pDest = NULL;
- zend_hash_index_update(t, (zend_ulong)def, &value, sizeof(zval*), (void**)&pDest);
+ php_proto_zend_hash_index_update_mem(t, (zend_ulong)def, &value,
+ sizeof(zval*), (void**)&pDest);
}
static void* get_from_table(const HashTable* t, const void* def) {
void** value;
- if (zend_hash_index_find(t, (zend_ulong)def, (void**)&value) == FAILURE) {
- zend_error(E_ERROR, "PHP object not found for given definition.\n");
+ if (php_proto_zend_hash_index_find_mem(t, (zend_ulong)def, (void**)&value) ==
+ FAILURE) {
return NULL;
}
return *value;
}
+static bool exist_in_table(const HashTable* t, const void* def) {
+ void** value;
+ return (php_proto_zend_hash_index_find_mem(t, (zend_ulong)def,
+ (void**)&value) == SUCCESS);
+}
+
static void add_to_list(HashTable* t, void* value) {
zval* pDest = NULL;
- zend_hash_next_index_insert(t, &value, sizeof(void*), (void**)&pDest);
+ php_proto_zend_hash_next_index_insert_mem(t, &value, sizeof(void*),
+ (void**)&pDest);
}
-void add_def_obj(const void* def, zval* value) {
+static void add_to_strtable(HashTable* t, const char* key, int key_size,
+ void* value) {
+ zval* pDest = NULL;
+ php_proto_zend_hash_update_mem(t, key, key_size, &value, sizeof(void*),
+ (void**)&pDest);
+}
+
+static void* get_from_strtable(const HashTable* t, const char* key, int key_size) {
+ void** value;
+ if (php_proto_zend_hash_find_mem(t, key, key_size, (void**)&value) ==
+ FAILURE) {
+ return NULL;
+ }
+ return *value;
+}
+
+void add_def_obj(const void* def, PHP_PROTO_HASHTABLE_VALUE value) {
+#if PHP_MAJOR_VERSION < 7
Z_ADDREF_P(value);
+#else
+ ++GC_REFCOUNT(value);
+#endif
add_to_table(upb_def_to_php_obj_map, def, value);
}
-zval* get_def_obj(const void* def) {
- return (zval*)get_from_table(upb_def_to_php_obj_map, def);
+PHP_PROTO_HASHTABLE_VALUE get_def_obj(const void* def) {
+ return (PHP_PROTO_HASHTABLE_VALUE)get_from_table(upb_def_to_php_obj_map, def);
}
-void add_ce_obj(const void* ce, zval* value) {
+void add_ce_obj(const void* ce, PHP_PROTO_HASHTABLE_VALUE value) {
+#if PHP_MAJOR_VERSION < 7
Z_ADDREF_P(value);
+#else
+ ++GC_REFCOUNT(value);
+#endif
add_to_table(ce_to_php_obj_map, ce, value);
}
-zval* get_ce_obj(const void* ce) {
- return (zval*)get_from_table(ce_to_php_obj_map, ce);
+PHP_PROTO_HASHTABLE_VALUE get_ce_obj(const void* ce) {
+ return (PHP_PROTO_HASHTABLE_VALUE)get_from_table(ce_to_php_obj_map, ce);
+}
+
+bool class_added(const void* ce) {
+ return exist_in_table(ce_to_php_obj_map, ce);
+}
+
+void add_proto_obj(const char* proto, PHP_PROTO_HASHTABLE_VALUE value) {
+#if PHP_MAJOR_VERSION < 7
+ Z_ADDREF_P(value);
+#else
+ ++GC_REFCOUNT(value);
+#endif
+ add_to_strtable(proto_to_php_obj_map, proto, strlen(proto), value);
+}
+
+PHP_PROTO_HASHTABLE_VALUE get_proto_obj(const char* proto) {
+ return (PHP_PROTO_HASHTABLE_VALUE)get_from_strtable(proto_to_php_obj_map,
+ proto, strlen(proto));
+}
+
+// -----------------------------------------------------------------------------
+// Reserved Name.
+// -----------------------------------------------------------------------------
+
+// Although we already have kReservedNames, we still add them to hash table to
+// speed up look up.
+const char *const kReservedNames[] = {
+ "abstract", "and", "array", "as", "break",
+ "callable", "case", "catch", "class", "clone",
+ "const", "continue", "declare", "default", "die",
+ "do", "echo", "else", "elseif", "empty",
+ "enddeclare", "endfor", "endforeach", "endif", "endswitch",
+ "endwhile", "eval", "exit", "extends", "final",
+ "for", "foreach", "function", "global", "goto",
+ "if", "implements", "include", "include_once", "instanceof",
+ "insteadof", "interface", "isset", "list", "namespace",
+ "new", "or", "print", "private", "protected",
+ "public", "require", "require_once", "return", "static",
+ "switch", "throw", "trait", "try", "unset",
+ "use", "var", "while", "xor", "int",
+ "float", "bool", "string", "true", "false",
+ "null", "void", "iterable"};
+const int kReservedNamesSize = 73;
+
+bool is_reserved_name(const char* name) {
+ void** value;
+ return (php_proto_zend_hash_find(reserved_names, name, strlen(name),
+ (void**)&value) == SUCCESS);
}
// -----------------------------------------------------------------------------
@@ -125,15 +209,39 @@ static PHP_GINIT_FUNCTION(protobuf) {
static PHP_GSHUTDOWN_FUNCTION(protobuf) {
}
+#if PHP_MAJOR_VERSION >= 7
+static void php_proto_hashtable_descriptor_release(zval* value) {
+ void* ptr = Z_PTR_P(value);
+ zend_object* object = *(zend_object**)ptr;
+ if(--GC_REFCOUNT(object) == 0) {
+ zend_objects_store_del(object);
+ }
+ efree(ptr);
+}
+#endif
+
static PHP_RINIT_FUNCTION(protobuf) {
+ int i = 0;
+
ALLOC_HASHTABLE(upb_def_to_php_obj_map);
- zend_hash_init(upb_def_to_php_obj_map, 16, NULL, ZVAL_PTR_DTOR, 0);
+ zend_hash_init(upb_def_to_php_obj_map, 16, NULL, HASHTABLE_VALUE_DTOR, 0);
ALLOC_HASHTABLE(ce_to_php_obj_map);
- zend_hash_init(ce_to_php_obj_map, 16, NULL, ZVAL_PTR_DTOR, 0);
+ zend_hash_init(ce_to_php_obj_map, 16, NULL, HASHTABLE_VALUE_DTOR, 0);
+
+ ALLOC_HASHTABLE(proto_to_php_obj_map);
+ zend_hash_init(proto_to_php_obj_map, 16, NULL, HASHTABLE_VALUE_DTOR, 0);
+
+ ALLOC_HASHTABLE(reserved_names);
+ zend_hash_init(reserved_names, 16, NULL, NULL, 0);
+ for (i = 0; i < kReservedNamesSize; i++) {
+ php_proto_zend_hash_update(reserved_names, kReservedNames[i],
+ strlen(kReservedNames[i]));
+ }
generated_pool = NULL;
generated_pool_php = NULL;
+ internal_generated_pool_php = NULL;
return 0;
}
@@ -145,32 +253,104 @@ static PHP_RSHUTDOWN_FUNCTION(protobuf) {
zend_hash_destroy(ce_to_php_obj_map);
FREE_HASHTABLE(ce_to_php_obj_map);
+ zend_hash_destroy(proto_to_php_obj_map);
+ FREE_HASHTABLE(proto_to_php_obj_map);
+
+ zend_hash_destroy(reserved_names);
+ FREE_HASHTABLE(reserved_names);
+
+#if PHP_MAJOR_VERSION < 7
if (generated_pool_php != NULL) {
zval_dtor(generated_pool_php);
FREE_ZVAL(generated_pool_php);
}
+ if (internal_generated_pool_php != NULL) {
+ zval_dtor(internal_generated_pool_php);
+ FREE_ZVAL(internal_generated_pool_php);
+ }
+#else
+ if (generated_pool_php != NULL) {
+ zval tmp;
+ ZVAL_OBJ(&tmp, generated_pool_php);
+ zval_dtor(&tmp);
+ }
+ if (internal_generated_pool_php != NULL) {
+ zval tmp;
+ ZVAL_OBJ(&tmp, internal_generated_pool_php);
+ zval_dtor(&tmp);
+ }
+#endif
return 0;
}
static PHP_MINIT_FUNCTION(protobuf) {
- map_field_init(TSRMLS_C);
- repeated_field_init(TSRMLS_C);
- repeated_field_iter_init(TSRMLS_C);
- gpb_type_init(TSRMLS_C);
- message_init(TSRMLS_C);
descriptor_pool_init(TSRMLS_C);
descriptor_init(TSRMLS_C);
enum_descriptor_init(TSRMLS_C);
+ enum_value_descriptor_init(TSRMLS_C);
+ field_descriptor_init(TSRMLS_C);
+ gpb_type_init(TSRMLS_C);
+ internal_descriptor_pool_init(TSRMLS_C);
+ map_field_init(TSRMLS_C);
+ map_field_iter_init(TSRMLS_C);
+ message_init(TSRMLS_C);
+ oneof_descriptor_init(TSRMLS_C);
+ repeated_field_init(TSRMLS_C);
+ repeated_field_iter_init(TSRMLS_C);
util_init(TSRMLS_C);
+ gpb_metadata_any_init(TSRMLS_C);
+ gpb_metadata_api_init(TSRMLS_C);
+ gpb_metadata_duration_init(TSRMLS_C);
+ gpb_metadata_field_mask_init(TSRMLS_C);
+ gpb_metadata_empty_init(TSRMLS_C);
+ gpb_metadata_source_context_init(TSRMLS_C);
+ gpb_metadata_struct_init(TSRMLS_C);
+ gpb_metadata_timestamp_init(TSRMLS_C);
+ gpb_metadata_type_init(TSRMLS_C);
+ gpb_metadata_wrappers_init(TSRMLS_C);
+
+ any_init(TSRMLS_C);
+ api_init(TSRMLS_C);
+ bool_value_init(TSRMLS_C);
+ bytes_value_init(TSRMLS_C);
+ double_value_init(TSRMLS_C);
+ duration_init(TSRMLS_C);
+ enum_init(TSRMLS_C);
+ enum_value_init(TSRMLS_C);
+ field_cardinality_init(TSRMLS_C);
+ field_init(TSRMLS_C);
+ field_kind_init(TSRMLS_C);
+ field_mask_init(TSRMLS_C);
+ float_value_init(TSRMLS_C);
+ empty_init(TSRMLS_C);
+ int32_value_init(TSRMLS_C);
+ int64_value_init(TSRMLS_C);
+ list_value_init(TSRMLS_C);
+ method_init(TSRMLS_C);
+ mixin_init(TSRMLS_C);
+ null_value_init(TSRMLS_C);
+ option_init(TSRMLS_C);
+ source_context_init(TSRMLS_C);
+ string_value_init(TSRMLS_C);
+ struct_init(TSRMLS_C);
+ syntax_init(TSRMLS_C);
+ timestamp_init(TSRMLS_C);
+ type_init(TSRMLS_C);
+ u_int32_value_init(TSRMLS_C);
+ u_int64_value_init(TSRMLS_C);
+ value_init(TSRMLS_C);
+
return 0;
}
static PHP_MSHUTDOWN_FUNCTION(protobuf) {
PEFREE(message_handlers);
PEFREE(repeated_field_handlers);
+ PEFREE(repeated_field_iter_handlers);
PEFREE(map_field_handlers);
+ PEFREE(map_field_iter_handlers);
return 0;
}
diff --git a/php/ext/google/protobuf/protobuf.h b/php/ext/google/protobuf/protobuf.h
index 8022a9aa..18343772 100644
--- a/php/ext/google/protobuf/protobuf.h
+++ b/php/ext/google/protobuf/protobuf.h
@@ -37,36 +37,628 @@
#include "upb.h"
#define PHP_PROTOBUF_EXTNAME "protobuf"
-#define PHP_PROTOBUF_VERSION "3.1.0a1"
+#define PHP_PROTOBUF_VERSION "3.4.1"
#define MAX_LENGTH_OF_INT64 20
#define SIZEOF_INT64 8
// -----------------------------------------------------------------------------
+// PHP7 Wrappers
+// ----------------------------------------------------------------------------
+
+#if PHP_MAJOR_VERSION < 7
+
+#define php_proto_zend_literal const zend_literal*
+#define PHP_PROTO_CASE_IS_BOOL IS_BOOL
+#define PHP_PROTO_SIZE int
+#define PHP_PROTO_LONG long
+#define PHP_PROTO_TSRMLS_DC TSRMLS_DC
+#define PHP_PROTO_TSRMLS_CC TSRMLS_CC
+
+// PHP String
+
+#define PHP_PROTO_ZVAL_STRING(zval_ptr, s, copy) \
+ ZVAL_STRING(zval_ptr, s, copy)
+#define PHP_PROTO_ZVAL_STRINGL(zval_ptr, s, len, copy) \
+ ZVAL_STRINGL(zval_ptr, s, len, copy)
+#define PHP_PROTO_RETURN_STRING(s, copy) RETURN_STRING(s, copy)
+#define PHP_PROTO_RETURN_STRINGL(s, len, copy) RETURN_STRINGL(s, len, copy)
+#define PHP_PROTO_RETVAL_STRINGL(s, len, copy) RETVAL_STRINGL(s, len, copy)
+#define php_proto_zend_make_printable_zval(from, to) \
+ { \
+ int use_copy; \
+ zend_make_printable_zval(from, to, &use_copy); \
+ }
+
+// PHP Array
+
+#define PHP_PROTO_HASH_OF(array) Z_ARRVAL_P(array)
+
+#define php_proto_zend_hash_index_update_zval(ht, h, pData) \
+ zend_hash_index_update(ht, h, &(pData), sizeof(void*), NULL)
+
+#define php_proto_zend_hash_update_zval(ht, key, key_len, value) \
+ zend_hash_update(ht, key, key_len, value, sizeof(void*), NULL)
+
+#define php_proto_zend_hash_update(ht, key, key_len) \
+ zend_hash_update(ht, key, key_len, 0, 0, NULL)
+
+#define php_proto_zend_hash_index_update_mem(ht, h, pData, nDataSize, pDest) \
+ zend_hash_index_update(ht, h, pData, nDataSize, pDest)
+
+#define php_proto_zend_hash_update_mem(ht, key, key_len, pData, nDataSize, \
+ pDest) \
+ zend_hash_update(ht, key, key_len, pData, nDataSize, pDest)
+
+#define php_proto_zend_hash_index_find_zval(ht, h, pDest) \
+ zend_hash_index_find(ht, h, pDest)
+
+#define php_proto_zend_hash_find(ht, key, key_len, pDest) \
+ zend_hash_find(ht, key, key_len, pDest)
+
+#define php_proto_zend_hash_index_find_mem(ht, h, pDest) \
+ zend_hash_index_find(ht, h, pDest)
+
+#define php_proto_zend_hash_find_zval(ht, key, key_len, pDest) \
+ zend_hash_find(ht, key, key_len, pDest)
+
+#define php_proto_zend_hash_find_mem(ht, key, key_len, pDest) \
+ zend_hash_find(ht, key, key_len, pDest)
+
+#define php_proto_zend_hash_next_index_insert_zval(ht, pData) \
+ zend_hash_next_index_insert(ht, pData, sizeof(void*), NULL)
+
+#define php_proto_zend_hash_next_index_insert_mem(ht, pData, nDataSize, pDest) \
+ zend_hash_next_index_insert(ht, pData, nDataSize, pDest)
+
+#define php_proto_zend_hash_get_current_data_ex(ht, pDest, pos) \
+ zend_hash_get_current_data_ex(ht, pDest, pos)
+
+// PHP Object
+
+#define PHP_PROTO_WRAP_OBJECT_START(name) \
+ struct name { \
+ zend_object std;
+#define PHP_PROTO_WRAP_OBJECT_END \
+ };
+
+#define PHP_PROTO_INIT_SUBMSGCLASS_START(CLASSNAME, CAMELNAME, LOWWERNAME) \
+ void LOWWERNAME##_init(TSRMLS_D) { \
+ zend_class_entry class_type; \
+ const char* class_name = CLASSNAME; \
+ INIT_CLASS_ENTRY_EX(class_type, CLASSNAME, strlen(CLASSNAME), \
+ LOWWERNAME##_methods); \
+ LOWWERNAME##_type = zend_register_internal_class(&class_type TSRMLS_CC); \
+ LOWWERNAME##_type->create_object = message_create;
+#define PHP_PROTO_INIT_SUBMSGCLASS_END \
+ }
+
+#define PHP_PROTO_INIT_ENUMCLASS_START(CLASSNAME, CAMELNAME, LOWWERNAME) \
+ void LOWWERNAME##_init(TSRMLS_D) { \
+ zend_class_entry class_type; \
+ const char* class_name = CLASSNAME; \
+ INIT_CLASS_ENTRY_EX(class_type, CLASSNAME, strlen(CLASSNAME), \
+ LOWWERNAME##_methods); \
+ LOWWERNAME##_type = zend_register_internal_class(&class_type TSRMLS_CC);
+#define PHP_PROTO_INIT_ENUMCLASS_END \
+ }
+
+#define PHP_PROTO_INIT_CLASS_START(CLASSNAME, CAMELNAME, LOWWERNAME) \
+ void LOWWERNAME##_init(TSRMLS_D) { \
+ zend_class_entry class_type; \
+ const char* class_name = CLASSNAME; \
+ INIT_CLASS_ENTRY_EX(class_type, CLASSNAME, strlen(CLASSNAME), \
+ LOWWERNAME##_methods); \
+ LOWWERNAME##_type = zend_register_internal_class(&class_type TSRMLS_CC); \
+ LOWWERNAME##_type->create_object = LOWWERNAME##_create; \
+ LOWWERNAME##_handlers = PEMALLOC(zend_object_handlers); \
+ memcpy(LOWWERNAME##_handlers, zend_get_std_object_handlers(), \
+ sizeof(zend_object_handlers));
+#define PHP_PROTO_INIT_CLASS_END \
+ }
+
+#define PHP_PROTO_OBJECT_CREATE_START(NAME, LOWWERNAME) \
+ static zend_object_value LOWWERNAME##_create( \
+ zend_class_entry* ce TSRMLS_DC) { \
+ PHP_PROTO_ALLOC_CLASS_OBJECT(NAME, ce); \
+ zend_object_std_init(&intern->std, ce TSRMLS_CC); \
+ object_properties_init(&intern->std, ce);
+#define PHP_PROTO_OBJECT_CREATE_END(NAME, LOWWERNAME) \
+ PHP_PROTO_FREE_CLASS_OBJECT(NAME, LOWWERNAME##_free, LOWWERNAME##_handlers); \
+ }
+
+#define PHP_PROTO_OBJECT_FREE_START(classname, lowername) \
+ void lowername##_free(void* object TSRMLS_DC) { \
+ classname* intern = object;
+#define PHP_PROTO_OBJECT_FREE_END \
+ zend_object_std_dtor(&intern->std TSRMLS_CC); \
+ efree(intern); \
+ }
+
+#define PHP_PROTO_OBJECT_DTOR_START(classname, lowername)
+#define PHP_PROTO_OBJECT_DTOR_END
+
+#define CACHED_VALUE zval*
+#define CACHED_TO_ZVAL_PTR(VALUE) (VALUE)
+#define CACHED_PTR_TO_ZVAL_PTR(VALUE) (*VALUE)
+#define ZVAL_PTR_TO_CACHED_PTR(VALUE) (&VALUE)
+
+#define CREATE_OBJ_ON_ALLOCATED_ZVAL_PTR(zval_ptr, class_type) \
+ ZVAL_OBJ(zval_ptr, class_type->create_object(class_type TSRMLS_CC));
+
+#define PHP_PROTO_SEPARATE_ZVAL_IF_NOT_REF(value) \
+ SEPARATE_ZVAL_IF_NOT_REF(value)
+
+#define PHP_PROTO_GLOBAL_UNINITIALIZED_ZVAL EG(uninitialized_zval_ptr)
+
+#define OBJ_PROP(OBJECT, OFFSET) &((OBJECT)->properties_table[OFFSET])
+
+#define php_proto_zval_ptr_dtor(zval_ptr) \
+ zval_ptr_dtor(&(zval_ptr))
+
+#define PHP_PROTO_ALLOC_CLASS_OBJECT(class_object, class_type) \
+ class_object* intern; \
+ intern = (class_object*)emalloc(sizeof(class_object)); \
+ memset(intern, 0, sizeof(class_object));
+
+#define PHP_PROTO_FREE_CLASS_OBJECT(class_object, class_object_free, handler) \
+ zend_object_value retval = {0}; \
+ retval.handle = zend_objects_store_put( \
+ intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, \
+ class_object_free, NULL TSRMLS_CC); \
+ retval.handlers = handler; \
+ return retval;
+
+#define PHP_PROTO_ALLOC_ARRAY(zval_ptr) \
+ ALLOC_HASHTABLE(Z_ARRVAL_P(zval_ptr)); \
+ Z_TYPE_P(zval_ptr) = IS_ARRAY;
+
+#define ZVAL_OBJ(zval_ptr, call_create) \
+ Z_TYPE_P(zval_ptr) = IS_OBJECT; \
+ Z_OBJVAL_P(zval_ptr) = call_create;
+
+#define UNBOX(class_name, val) \
+ (class_name*)zend_object_store_get_object(val TSRMLS_CC);
+
+#define UNBOX_HASHTABLE_VALUE(class_name, val) UNBOX(class_name, val)
+
+#define HASHTABLE_VALUE_DTOR ZVAL_PTR_DTOR
+
+#define PHP_PROTO_HASHTABLE_VALUE zval*
+#define HASHTABLE_VALUE_CE(val) Z_OBJCE_P(val)
+
+#define CREATE_HASHTABLE_VALUE(OBJ, WRAPPED_OBJ, OBJ_TYPE, OBJ_CLASS_ENTRY) \
+ OBJ_TYPE* OBJ; \
+ PHP_PROTO_HASHTABLE_VALUE WRAPPED_OBJ; \
+ MAKE_STD_ZVAL(WRAPPED_OBJ); \
+ ZVAL_OBJ(WRAPPED_OBJ, \
+ OBJ_CLASS_ENTRY->create_object(OBJ_CLASS_ENTRY TSRMLS_CC)); \
+ OBJ = UNBOX_HASHTABLE_VALUE(OBJ_TYPE, WRAPPED_OBJ); \
+ Z_DELREF_P(desc_php);
+
+#define PHP_PROTO_CE_DECLARE zend_class_entry**
+#define PHP_PROTO_CE_UNREF(ce) (*ce)
+
+#define php_proto_zend_lookup_class(name, name_length, ce) \
+ zend_lookup_class(name, name_length, ce TSRMLS_CC)
+
+#define PHP_PROTO_RETVAL_ZVAL(value) ZVAL_ZVAL(return_value, value, 1, 0)
+
+#else // PHP_MAJOR_VERSION >= 7
+
+#define php_proto_zend_literal void**
+#define PHP_PROTO_CASE_IS_BOOL IS_TRUE: case IS_FALSE
+#define PHP_PROTO_SIZE size_t
+#define PHP_PROTO_LONG zend_long
+#define PHP_PROTO_TSRMLS_DC
+#define PHP_PROTO_TSRMLS_CC
+
+// PHP String
+
+#define PHP_PROTO_ZVAL_STRING(zval_ptr, s, copy) \
+ ZVAL_STRING(zval_ptr, s)
+#define PHP_PROTO_ZVAL_STRINGL(zval_ptr, s, len, copy) \
+ ZVAL_STRINGL(zval_ptr, s, len)
+#define PHP_PROTO_RETURN_STRING(s, copy) RETURN_STRING(s)
+#define PHP_PROTO_RETURN_STRINGL(s, len, copy) RETURN_STRINGL(s, len)
+#define PHP_PROTO_RETVAL_STRINGL(s, len, copy) RETVAL_STRINGL(s, len)
+#define php_proto_zend_make_printable_zval(from, to) \
+ zend_make_printable_zval(from, to)
+
+// PHP Array
+
+#define PHP_PROTO_HASH_OF(array) Z_ARRVAL_P(&array)
+
+static inline int php_proto_zend_hash_index_update_zval(HashTable* ht, ulong h,
+ zval* pData) {
+ void* result = NULL;
+ result = zend_hash_index_update(ht, h, pData);
+ return result != NULL ? SUCCESS : FAILURE;
+}
+
+static inline int php_proto_zend_hash_update(HashTable* ht, const char* key,
+ size_t key_len) {
+ void* result = NULL;
+ zval temp;
+ ZVAL_LONG(&temp, 0);
+ result = zend_hash_str_update(ht, key, key_len, &temp);
+ return result != NULL ? SUCCESS : FAILURE;
+}
+
+static inline int php_proto_zend_hash_index_update_mem(HashTable* ht, ulong h,
+ void* pData, uint nDataSize,
+ void** pDest) {
+ void* result = NULL;
+ result = zend_hash_index_update_mem(ht, h, pData, nDataSize);
+ if (pDest != NULL) *pDest = result;
+ return result != NULL ? SUCCESS : FAILURE;
+}
+
+static inline int php_proto_zend_hash_update_zval(HashTable* ht,
+ const char* key, uint key_len,
+ zval* pData) {
+ zend_string* internal_key = zend_string_init(key, key_len, 0);
+ zend_hash_update(ht, internal_key, pData);
+}
+
+static inline int php_proto_zend_hash_update_mem(HashTable* ht, const char* key,
+ uint key_len, void* pData,
+ uint nDataSize, void** pDest) {
+ zend_string* internal_key = zend_string_init(key, key_len, 0);
+ void* result = zend_hash_update_mem(ht, internal_key, pData, nDataSize);
+ zend_string_release(internal_key);
+ if (pDest != NULL) *pDest = result;
+ return result != NULL ? SUCCESS : FAILURE;
+}
+
+static inline int php_proto_zend_hash_index_find_zval(const HashTable* ht,
+ ulong h, void** pDest) {
+ zval* result = zend_hash_index_find(ht, h);
+ if (pDest != NULL) *pDest = result;
+ return result != NULL ? SUCCESS : FAILURE;
+}
+
+static inline int php_proto_zend_hash_find(const HashTable* ht, const char* key,
+ size_t key_len, void** pDest) {
+ void* result = NULL;
+ result = zend_hash_str_find(ht, key, key_len);
+ return result != NULL ? SUCCESS : FAILURE;
+}
+
+static inline int php_proto_zend_hash_index_find_mem(const HashTable* ht,
+ ulong h, void** pDest) {
+ void* result = NULL;
+ result = zend_hash_index_find_ptr(ht, h);
+ if (pDest != NULL) *pDest = result;
+ return result != NULL ? SUCCESS : FAILURE;
+}
+
+static inline int php_proto_zend_hash_find_zval(const HashTable* ht,
+ const char* key, uint key_len,
+ void** pDest) {
+ zend_string* internal_key = zend_string_init(key, key_len, 1);
+ zval* result = zend_hash_find(ht, internal_key);
+ if (pDest != NULL) *pDest = result;
+ return result != NULL ? SUCCESS : FAILURE;
+}
+
+static inline int php_proto_zend_hash_find_mem(const HashTable* ht,
+ const char* key, uint key_len,
+ void** pDest) {
+ zend_string* internal_key = zend_string_init(key, key_len, 1);
+ void* result = zend_hash_find_ptr(ht, internal_key);
+ zend_string_release(internal_key);
+ if (pDest != NULL) *pDest = result;
+ return result != NULL ? SUCCESS : FAILURE;
+}
+
+static inline int php_proto_zend_hash_next_index_insert_zval(HashTable* ht,
+ void* pData) {
+ zval tmp;
+ ZVAL_OBJ(&tmp, *(zend_object**)pData);
+ zval* result = zend_hash_next_index_insert(ht, &tmp);
+ return result != NULL ? SUCCESS : FAILURE;
+}
+
+static inline int php_proto_zend_hash_next_index_insert_mem(HashTable* ht,
+ void* pData,
+ uint nDataSize,
+ void** pDest) {
+ void* result = NULL;
+ result = zend_hash_next_index_insert_mem(ht, pData, nDataSize);
+ if (pDest != NULL) *pDest = result;
+ return result != NULL ? SUCCESS : FAILURE;
+}
+
+static inline int php_proto_zend_hash_get_current_data_ex(HashTable* ht,
+ void** pDest,
+ HashPosition* pos) {
+ void* result = NULL;
+ result = zend_hash_get_current_data_ex(ht, pos);
+ if (pDest != NULL) *pDest = result;
+ return result != NULL ? SUCCESS : FAILURE;
+}
+
+// PHP Object
+
+#define PHP_PROTO_WRAP_OBJECT_START(name) struct name {
+#define PHP_PROTO_WRAP_OBJECT_END \
+ zend_object std; \
+ };
+
+#define PHP_PROTO_INIT_SUBMSGCLASS_START(CLASSNAME, CAMELNAME, LOWWERNAME) \
+ void LOWWERNAME##_init(TSRMLS_D) { \
+ zend_class_entry class_type; \
+ const char* class_name = CLASSNAME; \
+ INIT_CLASS_ENTRY_EX(class_type, CLASSNAME, strlen(CLASSNAME), \
+ LOWWERNAME##_methods); \
+ LOWWERNAME##_type = zend_register_internal_class(&class_type TSRMLS_CC); \
+ LOWWERNAME##_type->create_object = message_create;
+#define PHP_PROTO_INIT_SUBMSGCLASS_END \
+ }
+
+#define PHP_PROTO_INIT_ENUMCLASS_START(CLASSNAME, CAMELNAME, LOWWERNAME) \
+ void LOWWERNAME##_init(TSRMLS_D) { \
+ zend_class_entry class_type; \
+ const char* class_name = CLASSNAME; \
+ INIT_CLASS_ENTRY_EX(class_type, CLASSNAME, strlen(CLASSNAME), \
+ LOWWERNAME##_methods); \
+ LOWWERNAME##_type = zend_register_internal_class(&class_type TSRMLS_CC);
+#define PHP_PROTO_INIT_ENUMCLASS_END \
+ }
+
+#define PHP_PROTO_INIT_CLASS_START(CLASSNAME, CAMELNAME, LOWWERNAME) \
+ void LOWWERNAME##_init(TSRMLS_D) { \
+ zend_class_entry class_type; \
+ const char* class_name = CLASSNAME; \
+ INIT_CLASS_ENTRY_EX(class_type, CLASSNAME, strlen(CLASSNAME), \
+ LOWWERNAME##_methods); \
+ LOWWERNAME##_type = zend_register_internal_class(&class_type TSRMLS_CC); \
+ LOWWERNAME##_type->create_object = LOWWERNAME##_create; \
+ LOWWERNAME##_handlers = PEMALLOC(zend_object_handlers); \
+ memcpy(LOWWERNAME##_handlers, zend_get_std_object_handlers(), \
+ sizeof(zend_object_handlers)); \
+ LOWWERNAME##_handlers->free_obj = LOWWERNAME##_free; \
+ LOWWERNAME##_handlers->dtor_obj = LOWWERNAME##_dtor; \
+ LOWWERNAME##_handlers->offset = XtOffsetOf(CAMELNAME, std);
+#define PHP_PROTO_INIT_CLASS_END \
+ }
+
+#define PHP_PROTO_OBJECT_FREE_START(classname, lowername) \
+ void lowername##_free(zend_object* object) { \
+ classname* intern = \
+ (classname*)((char*)object - XtOffsetOf(classname, std));
+#define PHP_PROTO_OBJECT_FREE_END \
+ }
+
+#define PHP_PROTO_OBJECT_DTOR_START(classname, lowername) \
+ void lowername##_dtor(zend_object* object) { \
+ classname* intern = \
+ (classname*)((char*)object - XtOffsetOf(classname, std));
+#define PHP_PROTO_OBJECT_DTOR_END \
+ zend_object_std_dtor(object TSRMLS_CC); \
+ }
+
+#define PHP_PROTO_OBJECT_CREATE_START(NAME, LOWWERNAME) \
+ static zend_object* LOWWERNAME##_create(zend_class_entry* ce TSRMLS_DC) { \
+ PHP_PROTO_ALLOC_CLASS_OBJECT(NAME, ce); \
+ zend_object_std_init(&intern->std, ce TSRMLS_CC); \
+ object_properties_init(&intern->std, ce);
+#define PHP_PROTO_OBJECT_CREATE_END(NAME, LOWWERNAME) \
+ PHP_PROTO_FREE_CLASS_OBJECT(NAME, LOWWERNAME##_free, LOWWERNAME##_handlers); \
+ }
+
+#define CACHED_VALUE zval
+#define CACHED_TO_ZVAL_PTR(VALUE) (&VALUE)
+#define CACHED_PTR_TO_ZVAL_PTR(VALUE) (VALUE)
+#define ZVAL_PTR_TO_CACHED_PTR(VALUE) (VALUE)
+
+#define CREATE_OBJ_ON_ALLOCATED_ZVAL_PTR(zval_ptr, class_type) \
+ ZVAL_OBJ(zval_ptr, class_type->create_object(class_type));
+
+#define PHP_PROTO_SEPARATE_ZVAL_IF_NOT_REF(value) ;
+
+#define PHP_PROTO_GLOBAL_UNINITIALIZED_ZVAL &EG(uninitialized_zval)
+
+#define php_proto_zval_ptr_dtor(zval_ptr) \
+ zval_ptr_dtor(zval_ptr)
+
+#define PHP_PROTO_ALLOC_CLASS_OBJECT(class_object, class_type) \
+ class_object* intern; \
+ int size = sizeof(class_object) + zend_object_properties_size(class_type); \
+ intern = ecalloc(1, size); \
+ memset(intern, 0, size);
+
+#define PHP_PROTO_FREE_CLASS_OBJECT(class_object, class_object_free, handler) \
+ intern->std.handlers = handler; \
+ return &intern->std;
+
+#define PHP_PROTO_ALLOC_ARRAY(zval_ptr) \
+ ZVAL_NEW_ARR(zval_ptr)
+
+#define UNBOX(class_name, val) \
+ (class_name*)((char*)Z_OBJ_P(val) - XtOffsetOf(class_name, std));
+
+#define UNBOX_HASHTABLE_VALUE(class_name, val) \
+ (class_name*)((char*)val - XtOffsetOf(class_name, std))
+
+#define HASHTABLE_VALUE_DTOR php_proto_hashtable_descriptor_release
+
+#define PHP_PROTO_HASHTABLE_VALUE zend_object*
+#define HASHTABLE_VALUE_CE(val) val->ce
+
+#define CREATE_HASHTABLE_VALUE(OBJ, WRAPPED_OBJ, OBJ_TYPE, OBJ_CLASS_ENTRY) \
+ OBJ_TYPE* OBJ; \
+ PHP_PROTO_HASHTABLE_VALUE WRAPPED_OBJ; \
+ WRAPPED_OBJ = OBJ_CLASS_ENTRY->create_object(OBJ_CLASS_ENTRY); \
+ OBJ = UNBOX_HASHTABLE_VALUE(OBJ_TYPE, WRAPPED_OBJ); \
+ --GC_REFCOUNT(WRAPPED_OBJ);
+
+#define PHP_PROTO_CE_DECLARE zend_class_entry*
+#define PHP_PROTO_CE_UNREF(ce) (ce)
+
+static inline int php_proto_zend_lookup_class(
+ const char* name, int name_length, zend_class_entry** ce TSRMLS_DC) {
+ zend_string *zstr_name = zend_string_init(name, name_length, 0);
+ *ce = zend_lookup_class(zstr_name);
+ zend_string_release(zstr_name);
+ return *ce != NULL ? SUCCESS : FAILURE;
+}
+
+#define PHP_PROTO_RETVAL_ZVAL(value) ZVAL_COPY(return_value, value)
+
+#endif // PHP_MAJOR_VERSION >= 7
+
+#if PHP_MAJOR_VERSION < 7 || (PHP_MAJOR_VERSION == 7 && PHP_MINOR_VERSION == 0)
+#define PHP_PROTO_FAKE_SCOPE_BEGIN(klass) \
+ zend_class_entry* old_scope = EG(scope); \
+ EG(scope) = klass;
+#define PHP_PROTO_FAKE_SCOPE_RESTART(klass) \
+ old_scope = EG(scope); \
+ EG(scope) = klass;
+#define PHP_PROTO_FAKE_SCOPE_END EG(scope) = old_scope;
+#else
+#define PHP_PROTO_FAKE_SCOPE_BEGIN(klass) \
+ zend_class_entry* old_scope = EG(fake_scope); \
+ EG(fake_scope) = klass;
+#define PHP_PROTO_FAKE_SCOPE_RESTART(klass) \
+ old_scope = EG(fake_scope); \
+ EG(fake_scope) = klass;
+#define PHP_PROTO_FAKE_SCOPE_END EG(fake_scope) = old_scope;
+#endif
+
+// Define PHP class
+#define DEFINE_PROTOBUF_INIT_CLASS(CLASSNAME, CAMELNAME, LOWERNAME) \
+ PHP_PROTO_INIT_CLASS_START(CLASSNAME, CAMELNAME, LOWERNAME) \
+ PHP_PROTO_INIT_CLASS_END
+
+#define DEFINE_PROTOBUF_CREATE(NAME, LOWERNAME) \
+ PHP_PROTO_OBJECT_CREATE_START(NAME, LOWERNAME) \
+ LOWERNAME##_init_c_instance(intern TSRMLS_CC); \
+ PHP_PROTO_OBJECT_CREATE_END(NAME, LOWERNAME)
+
+#define DEFINE_PROTOBUF_FREE(CAMELNAME, LOWERNAME) \
+ PHP_PROTO_OBJECT_FREE_START(CAMELNAME, LOWERNAME) \
+ LOWERNAME##_free_c(intern TSRMLS_CC); \
+ PHP_PROTO_OBJECT_FREE_END
+
+#define DEFINE_PROTOBUF_DTOR(CAMELNAME, LOWERNAME) \
+ PHP_PROTO_OBJECT_DTOR_START(CAMELNAME, LOWERNAME) \
+ PHP_PROTO_OBJECT_DTOR_END
+
+#define DEFINE_CLASS(NAME, LOWERNAME, string_name) \
+ zend_class_entry *LOWERNAME##_type; \
+ zend_object_handlers *LOWERNAME##_handlers; \
+ DEFINE_PROTOBUF_FREE(NAME, LOWERNAME) \
+ DEFINE_PROTOBUF_DTOR(NAME, LOWERNAME) \
+ DEFINE_PROTOBUF_CREATE(NAME, LOWERNAME) \
+ DEFINE_PROTOBUF_INIT_CLASS(string_name, NAME, LOWERNAME)
+
+// -----------------------------------------------------------------------------
// Forward Declaration
// ----------------------------------------------------------------------------
-struct DescriptorPool;
+struct Any;
+struct Api;
+struct BoolValue;
+struct BytesValue;
struct Descriptor;
+struct DescriptorPool;
+struct DoubleValue;
+struct Duration;
+struct Enum;
struct EnumDescriptor;
+struct EnumValue;
+struct EnumValueDescriptor;
+struct Field;
struct FieldDescriptor;
+struct FieldMask;
+struct Field_Cardinality;
+struct Field_Kind;
+struct FloatValue;
+struct GPBEmpty;
+struct Int32Value;
+struct Int64Value;
+struct InternalDescriptorPool;
+struct ListValue;
+struct Map;
+struct MapIter;
struct MessageField;
struct MessageHeader;
struct MessageLayout;
+struct Method;
+struct Mixin;
+struct NullValue;
+struct Oneof;
+struct Option;
struct RepeatedField;
struct RepeatedFieldIter;
-struct MapField;
-
-typedef struct DescriptorPool DescriptorPool;
+struct SourceContext;
+struct StringValue;
+struct Struct;
+struct Syntax;
+struct Timestamp;
+struct Type;
+struct UInt32Value;
+struct UInt64Value;
+struct Value;
+
+typedef struct Any Any;
+typedef struct Api Api;
+typedef struct BoolValue BoolValue;
+typedef struct BytesValue BytesValue;
typedef struct Descriptor Descriptor;
+typedef struct Descriptor Descriptor;
+typedef struct DescriptorPool DescriptorPool;
+typedef struct DoubleValue DoubleValue;
+typedef struct Duration Duration;
+typedef struct Enum Enum;
typedef struct EnumDescriptor EnumDescriptor;
+typedef struct EnumDescriptor EnumDescriptor;
+typedef struct EnumValue EnumValue;
+typedef struct EnumValueDescriptor EnumValueDescriptor;
+typedef struct EnumValueDescriptor EnumValueDescriptor;
+typedef struct Field Field;
+typedef struct FieldDescriptor FieldDescriptor;
typedef struct FieldDescriptor FieldDescriptor;
+typedef struct FieldMask FieldMask;
+typedef struct Field_Cardinality Field_Cardinality;
+typedef struct Field_Kind Field_Kind;
+typedef struct FloatValue FloatValue;
+typedef struct GPBEmpty GPBEmpty;
+typedef struct Int32Value Int32Value;
+typedef struct Int64Value Int64Value;
+typedef struct InternalDescriptorPool InternalDescriptorPool;
+typedef struct ListValue ListValue;
+typedef struct Map Map;
+typedef struct Map Map;
+typedef struct MapIter MapIter;
+typedef struct MapIter MapIter;
typedef struct MessageField MessageField;
+typedef struct MessageField MessageField;
+typedef struct MessageHeader MessageHeader;
typedef struct MessageHeader MessageHeader;
typedef struct MessageLayout MessageLayout;
+typedef struct MessageLayout MessageLayout;
+typedef struct Method Method;
+typedef struct Mixin Mixin;
+typedef struct NullValue NullValue;
+typedef struct Oneof Oneof;
+typedef struct Oneof Oneof;
+typedef struct Option Option;
+typedef struct RepeatedField RepeatedField;
typedef struct RepeatedField RepeatedField;
typedef struct RepeatedFieldIter RepeatedFieldIter;
-typedef struct MapField MapField;
+typedef struct RepeatedFieldIter RepeatedFieldIter;
+typedef struct SourceContext SourceContext;
+typedef struct StringValue StringValue;
+typedef struct Struct Struct;
+typedef struct Syntax Syntax;
+typedef struct Timestamp Timestamp;
+typedef struct Type Type;
+typedef struct UInt32Value UInt32Value;
+typedef struct UInt64Value UInt64Value;
+typedef struct Value Value;
// -----------------------------------------------------------------------------
// Globals.
@@ -76,25 +668,76 @@ ZEND_BEGIN_MODULE_GLOBALS(protobuf)
ZEND_END_MODULE_GLOBALS(protobuf)
// Init module and PHP classes.
+void any_init(TSRMLS_D);
+void api_init(TSRMLS_D);
+void bool_value_init(TSRMLS_D);
+void bytes_value_init(TSRMLS_D);
void descriptor_init(TSRMLS_D);
-void enum_descriptor_init(TSRMLS_D);
void descriptor_pool_init(TSRMLS_D);
+void double_value_init(TSRMLS_D);
+void duration_init(TSRMLS_D);
+void empty_init(TSRMLS_D);
+void enum_descriptor_init(TSRMLS_D);
+void enum_init(TSRMLS_D);
+void enum_value_init(TSRMLS_D);
+void field_cardinality_init(TSRMLS_D);
+void field_descriptor_init(TSRMLS_D);
+void field_init(TSRMLS_D);
+void field_kind_init(TSRMLS_D);
+void field_mask_init(TSRMLS_D);
+void float_value_init(TSRMLS_D);
void gpb_type_init(TSRMLS_D);
+void int32_value_init(TSRMLS_D);
+void int64_value_init(TSRMLS_D);
+void internal_descriptor_pool_init(TSRMLS_D);
+void list_value_init(TSRMLS_D);
void map_field_init(TSRMLS_D);
+void map_field_iter_init(TSRMLS_D);
+void message_init(TSRMLS_D);
+void method_init(TSRMLS_D);
+void mixin_init(TSRMLS_D);
+void null_value_init(TSRMLS_D);
+void oneof_descriptor_init(TSRMLS_D);
+void option_init(TSRMLS_D);
void repeated_field_init(TSRMLS_D);
void repeated_field_iter_init(TSRMLS_D);
+void source_context_init(TSRMLS_D);
+void string_value_init(TSRMLS_D);
+void struct_init(TSRMLS_D);
+void syntax_init(TSRMLS_D);
+void timestamp_init(TSRMLS_D);
+void type_init(TSRMLS_D);
+void uint32_value_init(TSRMLS_D);
+void uint64_value_init(TSRMLS_D);
void util_init(TSRMLS_D);
-void message_init(TSRMLS_D);
+void value_init(TSRMLS_D);
+
+void gpb_metadata_any_init(TSRMLS_D);
+void gpb_metadata_api_init(TSRMLS_D);
+void gpb_metadata_duration_init(TSRMLS_D);
+void gpb_metadata_field_mask_init(TSRMLS_D);
+void gpb_metadata_empty_init(TSRMLS_D);
+void gpb_metadata_source_context_init(TSRMLS_D);
+void gpb_metadata_struct_init(TSRMLS_D);
+void gpb_metadata_timestamp_init(TSRMLS_D);
+void gpb_metadata_type_init(TSRMLS_D);
+void gpb_metadata_wrappers_init(TSRMLS_D);
// Global map from upb {msg,enum}defs to wrapper Descriptor/EnumDescriptor
// instances.
-void add_def_obj(const void* def, zval* value);
-zval* get_def_obj(const void* def);
+void add_def_obj(const void* def, PHP_PROTO_HASHTABLE_VALUE value);
+PHP_PROTO_HASHTABLE_VALUE get_def_obj(const void* def);
// Global map from PHP class entries to wrapper Descriptor/EnumDescriptor
// instances.
-void add_ce_obj(const void* ce, zval* value);
-zval* get_ce_obj(const void* ce);
+void add_ce_obj(const void* ce, PHP_PROTO_HASHTABLE_VALUE value);
+PHP_PROTO_HASHTABLE_VALUE get_ce_obj(const void* ce);
+bool class_added(const void* ce);
+
+// Global map from message/enum's proto fully-qualified name to corresponding
+// wrapper Descriptor/EnumDescriptor instances.
+void add_proto_obj(const char* proto, PHP_PROTO_HASHTABLE_VALUE value);
+PHP_PROTO_HASHTABLE_VALUE get_proto_obj(const char* proto);
extern zend_class_entry* map_field_type;
extern zend_class_entry* repeated_field_type;
@@ -103,57 +746,112 @@ extern zend_class_entry* repeated_field_type;
// Descriptor.
// -----------------------------------------------------------------------------
-struct DescriptorPool {
- zend_object std;
- upb_symtab* symtab;
- HashTable* pending_list;
-};
+PHP_PROTO_WRAP_OBJECT_START(DescriptorPool)
+ InternalDescriptorPool* intern;
+PHP_PROTO_WRAP_OBJECT_END
PHP_METHOD(DescriptorPool, getGeneratedPool);
-PHP_METHOD(DescriptorPool, internalAddGeneratedFile);
+PHP_METHOD(DescriptorPool, getDescriptorByClassName);
+PHP_METHOD(DescriptorPool, getEnumDescriptorByClassName);
-extern zval* generated_pool_php; // wrapper of generated pool
-extern DescriptorPool* generated_pool; // The actual generated pool
-
-struct Descriptor {
- zend_object std;
+PHP_PROTO_WRAP_OBJECT_START(InternalDescriptorPool)
+ upb_symtab* symtab;
+ HashTable* pending_list;
+PHP_PROTO_WRAP_OBJECT_END
+
+PHP_METHOD(InternalDescriptorPool, getGeneratedPool);
+PHP_METHOD(InternalDescriptorPool, internalAddGeneratedFile);
+
+void internal_add_generated_file(const char* data, PHP_PROTO_SIZE data_len,
+ InternalDescriptorPool* pool TSRMLS_DC);
+void init_generated_pool_once(TSRMLS_D);
+
+// wrapper of generated pool
+#if PHP_MAJOR_VERSION < 7
+extern zval* generated_pool_php;
+extern zval* internal_generated_pool_php;
+void descriptor_pool_free(void* object TSRMLS_DC);
+void internal_descriptor_pool_free(void* object TSRMLS_DC);
+#else
+extern zend_object *generated_pool_php;
+extern zend_object *internal_generated_pool_php;
+void descriptor_pool_free(zend_object* object);
+void internal_descriptor_pool_free(zend_object* object);
+#endif
+extern InternalDescriptorPool* generated_pool; // The actual generated pool
+
+PHP_PROTO_WRAP_OBJECT_START(Descriptor)
const upb_msgdef* msgdef;
MessageLayout* layout;
zend_class_entry* klass; // begins as NULL
const upb_handlers* fill_handlers;
const upb_pbdecodermethod* fill_method;
+ const upb_json_parsermethod* json_fill_method;
const upb_handlers* pb_serialize_handlers;
-};
+ const upb_handlers* json_serialize_handlers;
+ const upb_handlers* json_serialize_handlers_preserve;
+PHP_PROTO_WRAP_OBJECT_END
+
+PHP_METHOD(Descriptor, getClass);
+PHP_METHOD(Descriptor, getFullName);
+PHP_METHOD(Descriptor, getField);
+PHP_METHOD(Descriptor, getFieldCount);
+PHP_METHOD(Descriptor, getOneofDecl);
+PHP_METHOD(Descriptor, getOneofDeclCount);
extern zend_class_entry* descriptor_type;
void descriptor_name_set(Descriptor *desc, const char *name);
-struct FieldDescriptor {
- zend_object std;
+PHP_PROTO_WRAP_OBJECT_START(FieldDescriptor)
const upb_fielddef* fielddef;
-};
+PHP_PROTO_WRAP_OBJECT_END
+
+PHP_METHOD(FieldDescriptor, getName);
+PHP_METHOD(FieldDescriptor, getNumber);
+PHP_METHOD(FieldDescriptor, getLabel);
+PHP_METHOD(FieldDescriptor, getType);
+PHP_METHOD(FieldDescriptor, isMap);
+PHP_METHOD(FieldDescriptor, getEnumType);
+PHP_METHOD(FieldDescriptor, getMessageType);
+
+extern zend_class_entry* field_descriptor_type;
-struct EnumDescriptor {
- zend_object std;
+PHP_PROTO_WRAP_OBJECT_START(EnumDescriptor)
const upb_enumdef* enumdef;
zend_class_entry* klass; // begins as NULL
- // VALUE module; // begins as nil
-};
+PHP_PROTO_WRAP_OBJECT_END
+
+PHP_METHOD(EnumDescriptor, getValue);
+PHP_METHOD(EnumDescriptor, getValueCount);
extern zend_class_entry* enum_descriptor_type;
+PHP_PROTO_WRAP_OBJECT_START(EnumValueDescriptor)
+ const char* name;
+ int32_t number;
+PHP_PROTO_WRAP_OBJECT_END
+
+PHP_METHOD(EnumValueDescriptor, getName);
+PHP_METHOD(EnumValueDescriptor, getNumber);
+
+extern zend_class_entry* enum_value_descriptor_type;
+
// -----------------------------------------------------------------------------
// Message class creation.
// -----------------------------------------------------------------------------
-void* message_data(void* msg);
+void* message_data(MessageHeader* msg);
+void custom_data_init(const zend_class_entry* ce,
+ MessageHeader* msg PHP_PROTO_TSRMLS_DC);
// Build PHP class for given descriptor. Instead of building from scratch, this
// function modifies existing class which has been partially defined in PHP
// code.
-void build_class_from_descriptor(zval* php_descriptor TSRMLS_DC);
+void build_class_from_descriptor(
+ PHP_PROTO_HASHTABLE_VALUE php_descriptor TSRMLS_DC);
+extern zend_class_entry* message_type;
extern zend_object_handlers* message_handlers;
// -----------------------------------------------------------------------------
@@ -223,24 +921,32 @@ struct MessageLayout {
size_t size;
};
-struct MessageHeader {
- zend_object std; // Stores properties table and class info of PHP instance.
- // This is needed for MessageHeader to be accessed via PHP.
+PHP_PROTO_WRAP_OBJECT_START(MessageHeader)
+ void* data; // Point to the real message data.
+ // Place needs to be consistent with map_parse_frame_data_t.
Descriptor* descriptor; // Kept alive by self.class.descriptor reference.
- // The real message data is appended after MessageHeader.
-};
+PHP_PROTO_WRAP_OBJECT_END
MessageLayout* create_layout(const upb_msgdef* msgdef);
void layout_init(MessageLayout* layout, void* storage,
- zval** properties_table TSRMLS_DC);
+ zend_object* object PHP_PROTO_TSRMLS_DC);
zval* layout_get(MessageLayout* layout, const void* storage,
- const upb_fielddef* field, zval** cache TSRMLS_DC);
+ const upb_fielddef* field, CACHED_VALUE* cache TSRMLS_DC);
void layout_set(MessageLayout* layout, MessageHeader* header,
const upb_fielddef* field, zval* val TSRMLS_DC);
+void layout_merge(MessageLayout* layout, MessageHeader* from,
+ MessageHeader* to TSRMLS_DC);
+const char* layout_get_oneof_case(MessageLayout* layout, const void* storage,
+ const upb_oneofdef* oneof TSRMLS_DC);
void free_layout(MessageLayout* layout);
+void* slot_memory(MessageLayout* layout, const void* storage,
+ const upb_fielddef* field);
+PHP_METHOD(Message, clear);
+PHP_METHOD(Message, mergeFrom);
PHP_METHOD(Message, readOneof);
PHP_METHOD(Message, writeOneof);
+PHP_METHOD(Message, whichOneof);
PHP_METHOD(Message, __construct);
// -----------------------------------------------------------------------------
@@ -255,9 +961,14 @@ PHP_METHOD(Message, __construct);
// This is called from the message class creation code.
const upb_pbdecodermethod *new_fillmsg_decodermethod(Descriptor *desc,
const void *owner);
+void serialize_to_string(zval* val, zval* return_value TSRMLS_DC);
+void merge_from_string(const char* data, int data_len, const Descriptor* desc,
+ MessageHeader* msg);
-PHP_METHOD(Message, encode);
-PHP_METHOD(Message, decode);
+PHP_METHOD(Message, serializeToString);
+PHP_METHOD(Message, mergeFromString);
+PHP_METHOD(Message, serializeToJsonString);
+PHP_METHOD(Message, mergeFromJsonString);
// -----------------------------------------------------------------------------
// Type check / conversion.
@@ -272,6 +983,11 @@ bool protobuf_convert_to_double(zval* from, double* to);
bool protobuf_convert_to_bool(zval* from, int8_t* to);
bool protobuf_convert_to_string(zval* from);
+void check_repeated_field(const zend_class_entry* klass, PHP_PROTO_LONG type,
+ zval* val, zval* return_value);
+void check_map_field(const zend_class_entry* klass, PHP_PROTO_LONG key_type,
+ PHP_PROTO_LONG value_type, zval* val, zval* return_value);
+
PHP_METHOD(Util, checkInt32);
PHP_METHOD(Util, checkUint32);
PHP_METHOD(Util, checkInt64);
@@ -283,6 +999,7 @@ PHP_METHOD(Util, checkBool);
PHP_METHOD(Util, checkString);
PHP_METHOD(Util, checkBytes);
PHP_METHOD(Util, checkMessage);
+PHP_METHOD(Util, checkMapField);
PHP_METHOD(Util, checkRepeatedField);
// -----------------------------------------------------------------------------
@@ -294,7 +1011,14 @@ PHP_METHOD(Util, checkRepeatedField);
size_t native_slot_size(upb_fieldtype_t type);
bool native_slot_set(upb_fieldtype_t type, const zend_class_entry* klass,
void* memory, zval* value TSRMLS_DC);
-void native_slot_init(upb_fieldtype_t type, void* memory, zval** cache);
+// String/Message is stored differently in array/map from normal message fields.
+// So we need to make a special method to handle that.
+bool native_slot_set_by_array(upb_fieldtype_t type,
+ const zend_class_entry* klass, void* memory,
+ zval* value TSRMLS_DC);
+bool native_slot_set_by_map(upb_fieldtype_t type, const zend_class_entry* klass,
+ void* memory, zval* value TSRMLS_DC);
+void native_slot_init(upb_fieldtype_t type, void* memory, CACHED_VALUE* cache);
// For each property, in order to avoid conversion between the zval object and
// the actual data type during parsing/serialization, the containing message
// object use the custom memory layout to store the actual data type for each
@@ -303,27 +1027,36 @@ void native_slot_init(upb_fieldtype_t type, void* memory, zval** cache);
// for providing such a zval object. Instead the caller needs to provide one
// (cache) and update it with the actual data (memory).
void native_slot_get(upb_fieldtype_t type, const void* memory,
- zval** cache TSRMLS_DC);
-void native_slot_get_default(upb_fieldtype_t type, zval** cache TSRMLS_DC);
+ CACHED_VALUE* cache TSRMLS_DC);
+// String/Message is stored differently in array/map from normal message fields.
+// So we need to make a special method to handle that.
+void native_slot_get_by_array(upb_fieldtype_t type, const void* memory,
+ CACHED_VALUE* cache TSRMLS_DC);
+void native_slot_get_by_map_key(upb_fieldtype_t type, const void* memory,
+ int length, CACHED_VALUE* cache TSRMLS_DC);
+void native_slot_get_by_map_value(upb_fieldtype_t type, const void* memory,
+ CACHED_VALUE* cache TSRMLS_DC);
+void native_slot_get_default(upb_fieldtype_t type,
+ CACHED_VALUE* cache TSRMLS_DC);
// -----------------------------------------------------------------------------
// Map Field.
// -----------------------------------------------------------------------------
extern zend_object_handlers* map_field_handlers;
+extern zend_object_handlers* map_field_iter_handlers;
-typedef struct {
- zend_object std;
+PHP_PROTO_WRAP_OBJECT_START(Map)
upb_fieldtype_t key_type;
upb_fieldtype_t value_type;
const zend_class_entry* msg_ce; // class entry for value message
upb_strtable table;
-} Map;
+PHP_PROTO_WRAP_OBJECT_END
-typedef struct {
+PHP_PROTO_WRAP_OBJECT_START(MapIter)
Map* self;
upb_strtable_iter it;
-} MapIter;
+PHP_PROTO_WRAP_OBJECT_END
void map_begin(zval* self, MapIter* iter TSRMLS_DC);
void map_next(MapIter* iter);
@@ -335,10 +1068,14 @@ upb_value map_iter_value(MapIter* iter, int* len);
const upb_fielddef* map_entry_key(const upb_msgdef* msgdef);
const upb_fielddef* map_entry_value(const upb_msgdef* msgdef);
-zend_object_value map_field_create(zend_class_entry *ce TSRMLS_DC);
-void map_field_create_with_type(zend_class_entry *ce, const upb_fielddef *field,
- zval **map_field TSRMLS_DC);
-void map_field_free(void* object TSRMLS_DC);
+void map_field_create_with_field(const zend_class_entry* ce,
+ const upb_fielddef* field,
+ CACHED_VALUE* map_field PHP_PROTO_TSRMLS_DC);
+void map_field_create_with_type(const zend_class_entry* ce,
+ upb_fieldtype_t key_type,
+ upb_fieldtype_t value_type,
+ const zend_class_entry* msg_ce,
+ CACHED_VALUE* map_field PHP_PROTO_TSRMLS_DC);
void* upb_value_memory(upb_value* v);
#define MAP_KEY_FIELD 1
@@ -358,36 +1095,49 @@ PHP_METHOD(MapField, offsetGet);
PHP_METHOD(MapField, offsetSet);
PHP_METHOD(MapField, offsetUnset);
PHP_METHOD(MapField, count);
+PHP_METHOD(MapField, getIterator);
+
+PHP_METHOD(MapFieldIter, rewind);
+PHP_METHOD(MapFieldIter, current);
+PHP_METHOD(MapFieldIter, key);
+PHP_METHOD(MapFieldIter, next);
+PHP_METHOD(MapFieldIter, valid);
// -----------------------------------------------------------------------------
// Repeated Field.
// -----------------------------------------------------------------------------
extern zend_object_handlers* repeated_field_handlers;
+extern zend_object_handlers* repeated_field_iter_handlers;
-struct RepeatedField {
- zend_object std;
+PHP_PROTO_WRAP_OBJECT_START(RepeatedField)
+#if PHP_MAJOR_VERSION < 7
zval* array;
+#else
+ zval array;
+#endif
upb_fieldtype_t type;
const zend_class_entry* msg_ce; // class entry for containing message
// (for message field only).
-};
+PHP_PROTO_WRAP_OBJECT_END
-struct RepeatedFieldIter {
- zend_object std;
+PHP_PROTO_WRAP_OBJECT_START(RepeatedFieldIter)
RepeatedField* repeated_field;
long position;
-};
-
-void repeated_field_create_with_type(zend_class_entry* ce,
- const upb_fielddef* field,
- zval** repeated_field TSRMLS_DC);
+PHP_PROTO_WRAP_OBJECT_END
+
+void repeated_field_create_with_field(
+ zend_class_entry* ce, const upb_fielddef* field,
+ CACHED_VALUE* repeated_field PHP_PROTO_TSRMLS_DC);
+void repeated_field_create_with_type(
+ zend_class_entry* ce, upb_fieldtype_t type, const zend_class_entry* msg_ce,
+ CACHED_VALUE* repeated_field PHP_PROTO_TSRMLS_DC);
// Return the element at the index position from the repeated field. There is
// not restriction on the type of stored elements.
void *repeated_field_index_native(RepeatedField *intern, int index TSRMLS_DC);
// Add the element to the end of the repeated field. There is not restriction on
// the type of stored elements.
-void repeated_field_push_native(RepeatedField *intern, void *value TSRMLS_DC);
+void repeated_field_push_native(RepeatedField *intern, void *value);
PHP_METHOD(RepeatedField, __construct);
PHP_METHOD(RepeatedField, append);
@@ -408,12 +1158,17 @@ PHP_METHOD(RepeatedFieldIter, valid);
// Oneof Field.
// -----------------------------------------------------------------------------
-typedef struct {
- zend_object std;
+PHP_PROTO_WRAP_OBJECT_START(Oneof)
upb_oneofdef* oneofdef;
int index; // Index of field in oneof. -1 if not set.
char value[NATIVE_SLOT_MAX_SIZE];
-} Oneof;
+PHP_PROTO_WRAP_OBJECT_END
+
+PHP_METHOD(Oneof, getName);
+PHP_METHOD(Oneof, getField);
+PHP_METHOD(Oneof, getFieldCount);
+
+extern zend_class_entry* oneof_descriptor_type;
// Oneof case slot value to indicate that no oneof case is set. The value `0` is
// safe because field numbers are used as case identifiers, and no field can
@@ -421,28 +1176,255 @@ typedef struct {
#define ONEOF_CASE_NONE 0
// -----------------------------------------------------------------------------
+// Well Known Type.
+// -----------------------------------------------------------------------------
+
+PHP_METHOD(GPBMetadata_Any, initOnce);
+PHP_METHOD(GPBMetadata_Api, initOnce);
+PHP_METHOD(GPBMetadata_Duration, initOnce);
+PHP_METHOD(GPBMetadata_FieldMask, initOnce);
+PHP_METHOD(GPBMetadata_Empty, initOnce);
+PHP_METHOD(GPBMetadata_SourceContext, initOnce);
+PHP_METHOD(GPBMetadata_Struct, initOnce);
+PHP_METHOD(GPBMetadata_Timestamp, initOnce);
+PHP_METHOD(GPBMetadata_Type, initOnce);
+PHP_METHOD(GPBMetadata_Wrappers, initOnce);
+
+PHP_METHOD(Any, __construct);
+PHP_METHOD(Any, getTypeUrl);
+PHP_METHOD(Any, setTypeUrl);
+PHP_METHOD(Any, getValue);
+PHP_METHOD(Any, setValue);
+PHP_METHOD(Any, unpack);
+PHP_METHOD(Any, pack);
+PHP_METHOD(Any, is);
+
+PHP_METHOD(Duration, __construct);
+PHP_METHOD(Duration, getSeconds);
+PHP_METHOD(Duration, setSeconds);
+PHP_METHOD(Duration, getNanos);
+PHP_METHOD(Duration, setNanos);
+
+PHP_METHOD(Timestamp, __construct);
+PHP_METHOD(Timestamp, fromDateTime);
+PHP_METHOD(Timestamp, toDateTime);
+PHP_METHOD(Timestamp, getSeconds);
+PHP_METHOD(Timestamp, setSeconds);
+PHP_METHOD(Timestamp, getNanos);
+PHP_METHOD(Timestamp, setNanos);
+
+PHP_METHOD(Api, __construct);
+PHP_METHOD(Api, getName);
+PHP_METHOD(Api, setName);
+PHP_METHOD(Api, getMethods);
+PHP_METHOD(Api, setMethods);
+PHP_METHOD(Api, getOptions);
+PHP_METHOD(Api, setOptions);
+PHP_METHOD(Api, getVersion);
+PHP_METHOD(Api, setVersion);
+PHP_METHOD(Api, getSourceContext);
+PHP_METHOD(Api, setSourceContext);
+PHP_METHOD(Api, getMixins);
+PHP_METHOD(Api, setMixins);
+PHP_METHOD(Api, getSyntax);
+PHP_METHOD(Api, setSyntax);
+
+PHP_METHOD(BoolValue, __construct);
+PHP_METHOD(BoolValue, getValue);
+PHP_METHOD(BoolValue, setValue);
+
+PHP_METHOD(BytesValue, __construct);
+PHP_METHOD(BytesValue, getValue);
+PHP_METHOD(BytesValue, setValue);
+
+PHP_METHOD(DoubleValue, __construct);
+PHP_METHOD(DoubleValue, getValue);
+PHP_METHOD(DoubleValue, setValue);
+
+PHP_METHOD(Enum, __construct);
+PHP_METHOD(Enum, getName);
+PHP_METHOD(Enum, setName);
+PHP_METHOD(Enum, getEnumvalue);
+PHP_METHOD(Enum, setEnumvalue);
+PHP_METHOD(Enum, getOptions);
+PHP_METHOD(Enum, setOptions);
+PHP_METHOD(Enum, getSourceContext);
+PHP_METHOD(Enum, setSourceContext);
+PHP_METHOD(Enum, getSyntax);
+PHP_METHOD(Enum, setSyntax);
+
+PHP_METHOD(EnumValue, __construct);
+PHP_METHOD(EnumValue, getName);
+PHP_METHOD(EnumValue, setName);
+PHP_METHOD(EnumValue, getNumber);
+PHP_METHOD(EnumValue, setNumber);
+PHP_METHOD(EnumValue, getOptions);
+PHP_METHOD(EnumValue, setOptions);
+
+PHP_METHOD(FieldMask, __construct);
+PHP_METHOD(FieldMask, getPaths);
+PHP_METHOD(FieldMask, setPaths);
+
+PHP_METHOD(Field, __construct);
+PHP_METHOD(Field, getKind);
+PHP_METHOD(Field, setKind);
+PHP_METHOD(Field, getCardinality);
+PHP_METHOD(Field, setCardinality);
+PHP_METHOD(Field, getNumber);
+PHP_METHOD(Field, setNumber);
+PHP_METHOD(Field, getName);
+PHP_METHOD(Field, setName);
+PHP_METHOD(Field, getTypeUrl);
+PHP_METHOD(Field, setTypeUrl);
+PHP_METHOD(Field, getOneofIndex);
+PHP_METHOD(Field, setOneofIndex);
+PHP_METHOD(Field, getPacked);
+PHP_METHOD(Field, setPacked);
+PHP_METHOD(Field, getOptions);
+PHP_METHOD(Field, setOptions);
+PHP_METHOD(Field, getJsonName);
+PHP_METHOD(Field, setJsonName);
+PHP_METHOD(Field, getDefaultValue);
+PHP_METHOD(Field, setDefaultValue);
+
+PHP_METHOD(FloatValue, __construct);
+PHP_METHOD(FloatValue, getValue);
+PHP_METHOD(FloatValue, setValue);
+
+PHP_METHOD(GPBEmpty, __construct);
+
+PHP_METHOD(Int32Value, __construct);
+PHP_METHOD(Int32Value, getValue);
+PHP_METHOD(Int32Value, setValue);
+
+PHP_METHOD(Int64Value, __construct);
+PHP_METHOD(Int64Value, getValue);
+PHP_METHOD(Int64Value, setValue);
+
+PHP_METHOD(ListValue, __construct);
+PHP_METHOD(ListValue, getValues);
+PHP_METHOD(ListValue, setValues);
+
+PHP_METHOD(Method, __construct);
+PHP_METHOD(Method, getName);
+PHP_METHOD(Method, setName);
+PHP_METHOD(Method, getRequestTypeUrl);
+PHP_METHOD(Method, setRequestTypeUrl);
+PHP_METHOD(Method, getRequestStreaming);
+PHP_METHOD(Method, setRequestStreaming);
+PHP_METHOD(Method, getResponseTypeUrl);
+PHP_METHOD(Method, setResponseTypeUrl);
+PHP_METHOD(Method, getResponseStreaming);
+PHP_METHOD(Method, setResponseStreaming);
+PHP_METHOD(Method, getOptions);
+PHP_METHOD(Method, setOptions);
+PHP_METHOD(Method, getSyntax);
+PHP_METHOD(Method, setSyntax);
+
+PHP_METHOD(Mixin, __construct);
+PHP_METHOD(Mixin, getName);
+PHP_METHOD(Mixin, setName);
+PHP_METHOD(Mixin, getRoot);
+PHP_METHOD(Mixin, setRoot);
+
+PHP_METHOD(Option, __construct);
+PHP_METHOD(Option, getName);
+PHP_METHOD(Option, setName);
+PHP_METHOD(Option, getValue);
+PHP_METHOD(Option, setValue);
+
+PHP_METHOD(SourceContext, __construct);
+PHP_METHOD(SourceContext, getFileName);
+PHP_METHOD(SourceContext, setFileName);
+
+PHP_METHOD(StringValue, __construct);
+PHP_METHOD(StringValue, getValue);
+PHP_METHOD(StringValue, setValue);
+
+PHP_METHOD(Struct, __construct);
+PHP_METHOD(Struct, getFields);
+PHP_METHOD(Struct, setFields);
+
+PHP_METHOD(Type, __construct);
+PHP_METHOD(Type, getName);
+PHP_METHOD(Type, setName);
+PHP_METHOD(Type, getFields);
+PHP_METHOD(Type, setFields);
+PHP_METHOD(Type, getOneofs);
+PHP_METHOD(Type, setOneofs);
+PHP_METHOD(Type, getOptions);
+PHP_METHOD(Type, setOptions);
+PHP_METHOD(Type, getSourceContext);
+PHP_METHOD(Type, setSourceContext);
+PHP_METHOD(Type, getSyntax);
+PHP_METHOD(Type, setSyntax);
+
+PHP_METHOD(UInt32Value, __construct);
+PHP_METHOD(UInt32Value, getValue);
+PHP_METHOD(UInt32Value, setValue);
+
+PHP_METHOD(UInt64Value, __construct);
+PHP_METHOD(UInt64Value, getValue);
+PHP_METHOD(UInt64Value, setValue);
+
+PHP_METHOD(Value, __construct);
+PHP_METHOD(Value, getNullValue);
+PHP_METHOD(Value, setNullValue);
+PHP_METHOD(Value, getNumberValue);
+PHP_METHOD(Value, setNumberValue);
+PHP_METHOD(Value, getStringValue);
+PHP_METHOD(Value, setStringValue);
+PHP_METHOD(Value, getBoolValue);
+PHP_METHOD(Value, setBoolValue);
+PHP_METHOD(Value, getStructValue);
+PHP_METHOD(Value, setStructValue);
+PHP_METHOD(Value, getListValue);
+PHP_METHOD(Value, setListValue);
+PHP_METHOD(Value, getKind);
+
+extern zend_class_entry* any_type;
+extern zend_class_entry* api_type;
+extern zend_class_entry* bool_value_type;
+extern zend_class_entry* bytes_value_type;
+extern zend_class_entry* double_value_type;
+extern zend_class_entry* duration_type;
+extern zend_class_entry* empty_type;
+extern zend_class_entry* enum_type;
+extern zend_class_entry* enum_value_type;
+extern zend_class_entry* field_cardinality_type;
+extern zend_class_entry* field_kind_type;
+extern zend_class_entry* field_mask_type;
+extern zend_class_entry* field_type;
+extern zend_class_entry* float_value_type;
+extern zend_class_entry* int32_value_type;
+extern zend_class_entry* int64_value_type;
+extern zend_class_entry* list_value_type;
+extern zend_class_entry* method_type;
+extern zend_class_entry* mixin_type;
+extern zend_class_entry* null_value_type;
+extern zend_class_entry* option_type;
+extern zend_class_entry* source_context_type;
+extern zend_class_entry* string_value_type;
+extern zend_class_entry* struct_type;
+extern zend_class_entry* syntax_type;
+extern zend_class_entry* timestamp_type;
+extern zend_class_entry* type_type;
+extern zend_class_entry* uint32_value_type;
+extern zend_class_entry* uint64_value_type;
+extern zend_class_entry* value_type;
+
+// -----------------------------------------------------------------------------
// Upb.
// -----------------------------------------------------------------------------
upb_fieldtype_t to_fieldtype(upb_descriptortype_t type);
-const zend_class_entry *field_type_class(const upb_fielddef *field TSRMLS_DC);
+const zend_class_entry* field_type_class(
+ const upb_fielddef* field PHP_PROTO_TSRMLS_DC);
// -----------------------------------------------------------------------------
// Utilities.
// -----------------------------------------------------------------------------
-// PHP <-> C conversion.
-#define UNBOX(class_name, val) \
- (class_name*)zend_object_store_get_object(val TSRMLS_CC);
-
-#define BOX(class_name, wrapper, intern, free_func) \
- MAKE_STD_ZVAL(wrapper); \
- Z_TYPE_P(wrapper) = IS_OBJECT; \
- Z_OBJVAL_P(wrapper) \
- .handle = \
- zend_objects_store_put(intern, NULL, free_func, NULL TSRMLS_CC); \
- Z_OBJVAL_P(wrapper).handlers = zend_get_std_object_handlers();
-
// Memory management
#define ALLOC(class_name) (class_name*) emalloc(sizeof(class_name))
#define PEMALLOC(class_name) (class_name*) pemalloc(sizeof(class_name), 1)
@@ -450,19 +1432,31 @@ const zend_class_entry *field_type_class(const upb_fielddef *field TSRMLS_DC);
#define FREE(object) efree(object)
#define PEFREE(object) pefree(object, 1)
-// Create PHP internal instance.
-#define CREATE(class_name, intern, init_func) \
- intern = ALLOC(class_name); \
- memset(intern, 0, sizeof(class_name)); \
- init_func(intern TSRMLS_CC);
-
// String argument.
#define STR(str) (str), strlen(str)
// Zend Value
+#if PHP_MAJOR_VERSION < 7
#define Z_OBJ_P(zval_p) \
((zend_object*)(EG(objects_store) \
.object_buckets[Z_OBJ_HANDLE_P(zval_p)] \
.bucket.obj.object))
+#endif
+
+// Message handler
+static inline zval* php_proto_message_read_property(
+ zval* msg, zval* member PHP_PROTO_TSRMLS_DC) {
+#if PHP_MAJOR_VERSION < 7
+ return message_handlers->read_property(msg, member, BP_VAR_R,
+ NULL PHP_PROTO_TSRMLS_CC);
+#else
+ return message_handlers->read_property(msg, member, BP_VAR_R, NULL,
+ NULL PHP_PROTO_TSRMLS_CC);
+#endif
+}
+
+// Reserved name
+bool is_reserved_name(const char* name);
+bool is_valid_constant_name(const char* name);
#endif // __GOOGLE_PROTOBUF_PHP_PROTOBUF_H__
diff --git a/php/ext/google/protobuf/storage.c b/php/ext/google/protobuf/storage.c
index 8a2b3a22..e7910c85 100644
--- a/php/ext/google/protobuf/storage.c
+++ b/php/ext/google/protobuf/storage.c
@@ -57,8 +57,35 @@ size_t native_slot_size(upb_fieldtype_t type) {
}
}
+static bool native_slot_is_default(upb_fieldtype_t type, const void* memory) {
+ switch (type) {
+#define CASE_TYPE(upb_type, c_type) \
+ case UPB_TYPE_##upb_type: { \
+ return DEREF(memory, c_type) == 0; \
+ }
+ CASE_TYPE(INT32, int32_t )
+ CASE_TYPE(UINT32, uint32_t)
+ CASE_TYPE(ENUM, int32_t )
+ CASE_TYPE(INT64, int64_t )
+ CASE_TYPE(UINT64, uint64_t)
+ CASE_TYPE(FLOAT, float )
+ CASE_TYPE(DOUBLE, double )
+ CASE_TYPE(BOOL, int8_t )
+
+#undef CASE_TYPE
+ case UPB_TYPE_STRING:
+ case UPB_TYPE_BYTES:
+ return Z_STRLEN_P(CACHED_PTR_TO_ZVAL_PTR(DEREF(memory, CACHED_VALUE*))) ==
+ 0;
+ case UPB_TYPE_MESSAGE:
+ return Z_TYPE_P(CACHED_PTR_TO_ZVAL_PTR(DEREF(memory, CACHED_VALUE*))) ==
+ IS_NULL;
+ default: return false;
+ }
+}
+
bool native_slot_set(upb_fieldtype_t type, const zend_class_entry* klass,
- void* memory, zval* value TSRMLS_DC) {
+ void* memory, zval* value PHP_PROTO_TSRMLS_DC) {
switch (type) {
case UPB_TYPE_STRING:
case UPB_TYPE_BYTES: {
@@ -70,14 +97,14 @@ bool native_slot_set(upb_fieldtype_t type, const zend_class_entry* klass,
zend_error(E_USER_ERROR, "Given string is not UTF8 encoded.");
return false;
}
- if (*(zval**)memory != NULL) {
+
+ zval* cached_zval = CACHED_PTR_TO_ZVAL_PTR((CACHED_VALUE*)memory);
+ if (EXPECTED(cached_zval != NULL)) {
+#if PHP_MAJOR_VERSION < 7
REPLACE_ZVAL_VALUE((zval**)memory, value, 1);
- } else {
- // Handles repeated/map string field. Memory provided by
- // RepeatedField/Map is not initialized.
- MAKE_STD_ZVAL(DEREF(memory, zval*));
- ZVAL_STRINGL(DEREF(memory, zval*), Z_STRVAL_P(value), Z_STRLEN_P(value),
- 1);
+#else
+ zend_assign_to_variable(cached_zval, value, IS_CV);
+#endif
}
break;
}
@@ -90,13 +117,18 @@ bool native_slot_set(upb_fieldtype_t type, const zend_class_entry* klass,
zend_error(E_USER_ERROR, "Given message does not have correct class.");
return false;
}
- if (EXPECTED(DEREF(memory, zval*) != value)) {
- if (DEREF(memory, zval*) != NULL) {
- zval_ptr_dtor((zval**)memory);
- }
- DEREF(memory, zval*) = value;
- Z_ADDREF_P(value);
+
+ zval* property_ptr = CACHED_PTR_TO_ZVAL_PTR((CACHED_VALUE*)memory);
+ if (EXPECTED(property_ptr != value)) {
+ php_proto_zval_ptr_dtor(property_ptr);
}
+
+#if PHP_MAJOR_VERSION < 7
+ DEREF(memory, zval*) = value;
+ Z_ADDREF_P(value);
+#else
+ ZVAL_ZVAL(property_ptr, value, 1, 0);
+#endif
break;
}
@@ -126,7 +158,110 @@ bool native_slot_set(upb_fieldtype_t type, const zend_class_entry* klass,
return true;
}
-void native_slot_init(upb_fieldtype_t type, void* memory, zval** cache) {
+bool native_slot_set_by_array(upb_fieldtype_t type,
+ const zend_class_entry* klass, void* memory,
+ zval* value TSRMLS_DC) {
+ switch (type) {
+ case UPB_TYPE_STRING:
+ case UPB_TYPE_BYTES: {
+ if (!protobuf_convert_to_string(value)) {
+ return false;
+ }
+ if (type == UPB_TYPE_STRING &&
+ !is_structurally_valid_utf8(Z_STRVAL_P(value), Z_STRLEN_P(value))) {
+ zend_error(E_USER_ERROR, "Given string is not UTF8 encoded.");
+ return false;
+ }
+
+ // Handles repeated/map string field. Memory provided by
+ // RepeatedField/Map is not initialized.
+#if PHP_MAJOR_VERSION < 7
+ MAKE_STD_ZVAL(DEREF(memory, zval*));
+ PHP_PROTO_ZVAL_STRINGL(DEREF(memory, zval*), Z_STRVAL_P(value),
+ Z_STRLEN_P(value), 1);
+#else
+ *(zend_string**)memory = zend_string_dup(Z_STR_P(value), 0);
+#endif
+ break;
+ }
+ case UPB_TYPE_MESSAGE: {
+ if (Z_TYPE_P(value) != IS_OBJECT) {
+ zend_error(E_USER_ERROR, "Given value is not message.");
+ return false;
+ }
+ if (Z_TYPE_P(value) == IS_OBJECT && klass != Z_OBJCE_P(value)) {
+ zend_error(E_USER_ERROR, "Given message does not have correct class.");
+ return false;
+ }
+#if PHP_MAJOR_VERSION < 7
+ if (EXPECTED(DEREF(memory, zval*) != value)) {
+ DEREF(memory, zval*) = value;
+ Z_ADDREF_P(value);
+ }
+#else
+ DEREF(memory, zval*) = value;
+ ++GC_REFCOUNT(Z_OBJ_P(value));
+#endif
+ break;
+ }
+ default:
+ return native_slot_set(type, klass, memory, value TSRMLS_CC);
+ }
+ return true;
+}
+
+bool native_slot_set_by_map(upb_fieldtype_t type, const zend_class_entry* klass,
+ void* memory, zval* value TSRMLS_DC) {
+ switch (type) {
+ case UPB_TYPE_STRING:
+ case UPB_TYPE_BYTES: {
+ if (!protobuf_convert_to_string(value)) {
+ return false;
+ }
+ if (type == UPB_TYPE_STRING &&
+ !is_structurally_valid_utf8(Z_STRVAL_P(value), Z_STRLEN_P(value))) {
+ zend_error(E_USER_ERROR, "Given string is not UTF8 encoded.");
+ return false;
+ }
+
+ // Handles repeated/map string field. Memory provided by
+ // RepeatedField/Map is not initialized.
+#if PHP_MAJOR_VERSION < 7
+ MAKE_STD_ZVAL(DEREF(memory, zval*));
+ PHP_PROTO_ZVAL_STRINGL(DEREF(memory, zval*), Z_STRVAL_P(value),
+ Z_STRLEN_P(value), 1);
+#else
+ *(zend_string**)memory = zend_string_dup(Z_STR_P(value), 0);
+#endif
+ break;
+ }
+ case UPB_TYPE_MESSAGE: {
+ if (Z_TYPE_P(value) != IS_OBJECT) {
+ zend_error(E_USER_ERROR, "Given value is not message.");
+ return false;
+ }
+ if (Z_TYPE_P(value) == IS_OBJECT && klass != Z_OBJCE_P(value)) {
+ zend_error(E_USER_ERROR, "Given message does not have correct class.");
+ return false;
+ }
+#if PHP_MAJOR_VERSION < 7
+ if (EXPECTED(DEREF(memory, zval*) != value)) {
+ DEREF(memory, zval*) = value;
+ Z_ADDREF_P(value);
+ }
+#else
+ DEREF(memory, zend_object*) = Z_OBJ_P(value);
+ ++GC_REFCOUNT(Z_OBJ_P(value));
+#endif
+ break;
+ }
+ default:
+ return native_slot_set(type, klass, memory, value TSRMLS_CC);
+ }
+ return true;
+}
+
+void native_slot_init(upb_fieldtype_t type, void* memory, CACHED_VALUE* cache) {
zval* tmp = NULL;
switch (type) {
case UPB_TYPE_FLOAT:
@@ -141,7 +276,7 @@ void native_slot_init(upb_fieldtype_t type, void* memory, zval** cache) {
case UPB_TYPE_STRING:
case UPB_TYPE_BYTES:
case UPB_TYPE_MESSAGE:
- DEREF(memory, zval**) = cache;
+ DEREF(memory, CACHED_VALUE*) = cache;
break;
case UPB_TYPE_ENUM:
case UPB_TYPE_INT32:
@@ -162,38 +297,38 @@ void native_slot_init(upb_fieldtype_t type, void* memory, zval** cache) {
}
void native_slot_get(upb_fieldtype_t type, const void* memory,
- zval** cache TSRMLS_DC) {
+ CACHED_VALUE* cache TSRMLS_DC) {
switch (type) {
-#define CASE(upb_type, php_type, c_type) \
- case UPB_TYPE_##upb_type: \
- SEPARATE_ZVAL_IF_NOT_REF(cache); \
- ZVAL_##php_type(*cache, DEREF(memory, c_type)); \
- return;
+#define CASE(upb_type, php_type, c_type) \
+ case UPB_TYPE_##upb_type: \
+ PHP_PROTO_SEPARATE_ZVAL_IF_NOT_REF(cache); \
+ ZVAL_##php_type(CACHED_PTR_TO_ZVAL_PTR(cache), DEREF(memory, c_type)); \
+ return;
-CASE(FLOAT, DOUBLE, float)
-CASE(DOUBLE, DOUBLE, double)
-CASE(BOOL, BOOL, int8_t)
-CASE(INT32, LONG, int32_t)
-CASE(ENUM, LONG, uint32_t)
+ CASE(FLOAT, DOUBLE, float)
+ CASE(DOUBLE, DOUBLE, double)
+ CASE(BOOL, BOOL, int8_t)
+ CASE(INT32, LONG, int32_t)
+ CASE(ENUM, LONG, uint32_t)
#undef CASE
#if SIZEOF_LONG == 4
-#define CASE(upb_type, c_type) \
- case UPB_TYPE_##upb_type: { \
- SEPARATE_ZVAL_IF_NOT_REF(cache); \
- char buffer[MAX_LENGTH_OF_INT64]; \
- sprintf(buffer, "%lld", DEREF(memory, c_type)); \
- ZVAL_STRING(*cache, buffer, 1); \
- return; \
- }
+#define CASE(upb_type, c_type) \
+ case UPB_TYPE_##upb_type: { \
+ PHP_PROTO_SEPARATE_ZVAL_IF_NOT_REF(cache); \
+ char buffer[MAX_LENGTH_OF_INT64]; \
+ sprintf(buffer, "%lld", DEREF(memory, c_type)); \
+ PHP_PROTO_ZVAL_STRING(CACHED_PTR_TO_ZVAL_PTR(cache), buffer, 1); \
+ return; \
+ }
#else
-#define CASE(upb_type, c_type) \
- case UPB_TYPE_##upb_type: { \
- SEPARATE_ZVAL_IF_NOT_REF(cache); \
- ZVAL_LONG(*cache, DEREF(memory, c_type)); \
- return; \
- }
+#define CASE(upb_type, c_type) \
+ case UPB_TYPE_##upb_type: { \
+ PHP_PROTO_SEPARATE_ZVAL_IF_NOT_REF(cache); \
+ ZVAL_LONG(CACHED_PTR_TO_ZVAL_PTR(cache), DEREF(memory, c_type)); \
+ return; \
+ }
#endif
CASE(UINT64, uint64_t)
CASE(INT64, int64_t)
@@ -202,32 +337,34 @@ CASE(INT64, int64_t)
case UPB_TYPE_UINT32: {
// Prepend bit-1 for negative numbers, so that uint32 value will be
// consistent on both 32-bit and 64-bit architectures.
- SEPARATE_ZVAL_IF_NOT_REF(cache);
+ PHP_PROTO_SEPARATE_ZVAL_IF_NOT_REF(cache);
int value = DEREF(memory, int32_t);
if (sizeof(int) == 8) {
value |= (-((value >> 31) & 0x1) & 0xFFFFFFFF00000000);
}
- ZVAL_LONG(*cache, value);
+ ZVAL_LONG(CACHED_PTR_TO_ZVAL_PTR(cache), value);
return;
}
case UPB_TYPE_STRING:
case UPB_TYPE_BYTES: {
- // For optional string/bytes fields, the cache is owned by the containing
- // message and should have been updated during setting/decoding. However,
- // for repeated string/bytes fields, the cache is provided by zend engine
- // and has not been updated.
- zval* value = DEREF(memory, zval*);
- if (*cache != value) {
- ZVAL_STRINGL(*cache, Z_STRVAL_P(value), Z_STRLEN_P(value), 1);
+ // For optional string/bytes/message fields, the cache is owned by the
+ // containing message and should have been updated during
+ // setting/decoding. However, oneof accessor call this function by
+ // providing the return value directly, which is not the same as the cache
+ // value.
+ zval* value = CACHED_PTR_TO_ZVAL_PTR((CACHED_VALUE*)memory);
+ if (CACHED_PTR_TO_ZVAL_PTR(cache) != value) {
+ PHP_PROTO_ZVAL_STRINGL(CACHED_PTR_TO_ZVAL_PTR(cache), Z_STRVAL_P(value),
+ Z_STRLEN_P(value), 1);
}
break;
}
case UPB_TYPE_MESSAGE: {
// Same as above for string/bytes fields.
- zval* value = DEREF(memory, zval*);
- if (*cache != value) {
- ZVAL_ZVAL(*cache, value, 1, 0);
+ zval* value = CACHED_PTR_TO_ZVAL_PTR((CACHED_VALUE*)memory);
+ if (CACHED_PTR_TO_ZVAL_PTR(cache) != value) {
+ ZVAL_ZVAL(CACHED_PTR_TO_ZVAL_PTR(cache), value, 1, 0);
}
return;
}
@@ -236,34 +373,117 @@ CASE(INT64, int64_t)
}
}
-void native_slot_get_default(upb_fieldtype_t type, zval** cache TSRMLS_DC) {
+void native_slot_get_by_array(upb_fieldtype_t type, const void* memory,
+ CACHED_VALUE* cache TSRMLS_DC) {
+ switch (type) {
+ case UPB_TYPE_STRING:
+ case UPB_TYPE_BYTES: {
+#if PHP_MAJOR_VERSION < 7
+ zval* value = CACHED_PTR_TO_ZVAL_PTR((CACHED_VALUE*)memory);
+ if (EXPECTED(CACHED_PTR_TO_ZVAL_PTR(cache) != value)) {
+ PHP_PROTO_ZVAL_STRINGL(CACHED_PTR_TO_ZVAL_PTR(cache),
+ Z_STRVAL_P(value), Z_STRLEN_P(value), 1);
+ }
+#else
+ ZVAL_NEW_STR(cache, zend_string_dup(*(zend_string**)memory, 0));
+#endif
+ return;
+ }
+ case UPB_TYPE_MESSAGE: {
+#if PHP_MAJOR_VERSION < 7
+ zval* value = CACHED_PTR_TO_ZVAL_PTR((CACHED_VALUE*)memory);
+ if (EXPECTED(CACHED_PTR_TO_ZVAL_PTR(cache) != value)) {
+ ZVAL_ZVAL(CACHED_PTR_TO_ZVAL_PTR(cache), value, 1, 0);
+ }
+#else
+ ZVAL_COPY(CACHED_PTR_TO_ZVAL_PTR(cache), memory);
+#endif
+ return;
+ }
+ default:
+ native_slot_get(type, memory, cache TSRMLS_CC);
+ }
+}
+
+void native_slot_get_by_map_key(upb_fieldtype_t type, const void* memory,
+ int length, CACHED_VALUE* cache TSRMLS_DC) {
+ switch (type) {
+ case UPB_TYPE_STRING:
+ case UPB_TYPE_BYTES: {
+ PHP_PROTO_ZVAL_STRINGL(CACHED_PTR_TO_ZVAL_PTR(cache), memory, length, 1);
+ return;
+ }
+ default:
+ native_slot_get(type, memory, cache TSRMLS_CC);
+ }
+}
+
+void native_slot_get_by_map_value(upb_fieldtype_t type, const void* memory,
+ CACHED_VALUE* cache TSRMLS_DC) {
+ switch (type) {
+ case UPB_TYPE_MESSAGE: {
+#if PHP_MAJOR_VERSION < 7
+ zval* value = CACHED_PTR_TO_ZVAL_PTR((CACHED_VALUE*)memory);
+ if (EXPECTED(CACHED_PTR_TO_ZVAL_PTR(cache) != value)) {
+ ZVAL_ZVAL(CACHED_PTR_TO_ZVAL_PTR(cache), value, 1, 0);
+ }
+#else
+ ++GC_REFCOUNT(*(zend_object**)memory);
+ ZVAL_OBJ(cache, *(zend_object**)memory);
+#endif
+ return;
+ }
+ default:
+ native_slot_get_by_array(type, memory, cache TSRMLS_CC);
+ }
+}
+
+void native_slot_get_default(upb_fieldtype_t type,
+ CACHED_VALUE* cache TSRMLS_DC) {
switch (type) {
-#define CASE(upb_type, php_type) \
- case UPB_TYPE_##upb_type: \
- SEPARATE_ZVAL_IF_NOT_REF(cache); \
- ZVAL_##php_type(*cache, 0); \
+#define CASE(upb_type, php_type) \
+ case UPB_TYPE_##upb_type: \
+ PHP_PROTO_SEPARATE_ZVAL_IF_NOT_REF(cache); \
+ ZVAL_##php_type(CACHED_PTR_TO_ZVAL_PTR(cache), 0); \
return;
CASE(FLOAT, DOUBLE)
CASE(DOUBLE, DOUBLE)
CASE(BOOL, BOOL)
CASE(INT32, LONG)
- CASE(INT64, LONG)
CASE(UINT32, LONG)
- CASE(UINT64, LONG)
CASE(ENUM, LONG)
#undef CASE
+#if SIZEOF_LONG == 4
+#define CASE(upb_type) \
+ case UPB_TYPE_##upb_type: { \
+ PHP_PROTO_SEPARATE_ZVAL_IF_NOT_REF(cache); \
+ PHP_PROTO_ZVAL_STRING(CACHED_PTR_TO_ZVAL_PTR(cache), "0", 1); \
+ return; \
+ }
+#else
+#define CASE(upb_type) \
+ case UPB_TYPE_##upb_type: { \
+ PHP_PROTO_SEPARATE_ZVAL_IF_NOT_REF(cache); \
+ ZVAL_LONG(CACHED_PTR_TO_ZVAL_PTR(cache), 0); \
+ return; \
+ }
+#endif
+CASE(UINT64)
+CASE(INT64)
+#undef CASE
+
case UPB_TYPE_STRING:
case UPB_TYPE_BYTES: {
- SEPARATE_ZVAL_IF_NOT_REF(cache);
- ZVAL_STRINGL(*cache, "", 0, 1);
+ PHP_PROTO_SEPARATE_ZVAL_IF_NOT_REF(cache);
+ PHP_PROTO_ZVAL_STRINGL(CACHED_PTR_TO_ZVAL_PTR(cache), "", 0, 1);
break;
}
case UPB_TYPE_MESSAGE: {
- SEPARATE_ZVAL_IF_NOT_REF(cache);
- ZVAL_NULL(*cache);
+ PHP_PROTO_SEPARATE_ZVAL_IF_NOT_REF(cache);
+ ZVAL_NULL(CACHED_PTR_TO_ZVAL_PTR(cache));
return;
}
default:
@@ -317,14 +537,15 @@ const upb_fielddef* map_entry_value(const upb_msgdef* msgdef) {
return value_field;
}
-const zend_class_entry* field_type_class(const upb_fielddef* field TSRMLS_DC) {
+const zend_class_entry* field_type_class(
+ const upb_fielddef* field PHP_PROTO_TSRMLS_DC) {
if (upb_fielddef_type(field) == UPB_TYPE_MESSAGE) {
- zval* desc_php = get_def_obj(upb_fielddef_subdef(field));
- Descriptor* desc = zend_object_store_get_object(desc_php TSRMLS_CC);
+ Descriptor* desc = UNBOX_HASHTABLE_VALUE(
+ Descriptor, get_def_obj(upb_fielddef_subdef(field)));
return desc->klass;
} else if (upb_fielddef_type(field) == UPB_TYPE_ENUM) {
- zval* desc_php = get_def_obj(upb_fielddef_subdef(field));
- EnumDescriptor* desc = zend_object_store_get_object(desc_php TSRMLS_CC);
+ EnumDescriptor* desc = UNBOX_HASHTABLE_VALUE(
+ EnumDescriptor, get_def_obj(upb_fielddef_subdef(field)));
return desc->klass;
}
return NULL;
@@ -339,11 +560,6 @@ static size_t align_up_to(size_t offset, size_t granularity) {
return (offset + granularity - 1) & ~(granularity - 1);
}
-static void* slot_memory(MessageLayout* layout, const void* storage,
- const upb_fielddef* field) {
- return ((uint8_t*)storage) + layout->fields[upb_fielddef_index(field)].offset;
-}
-
static uint32_t* slot_oneof_case(MessageLayout* layout, const void* storage,
const upb_fielddef* field) {
return (uint32_t*)(((uint8_t*)storage) +
@@ -355,6 +571,11 @@ static int slot_property_cache(MessageLayout* layout, const void* storage,
return layout->fields[upb_fielddef_index(field)].cache_index;
}
+void* slot_memory(MessageLayout* layout, const void* storage,
+ const upb_fielddef* field) {
+ return ((uint8_t*)storage) + layout->fields[upb_fielddef_index(field)].offset;
+}
+
MessageLayout* create_layout(const upb_msgdef* msgdef) {
MessageLayout* layout = ALLOC(MessageLayout);
int nfields = upb_msgdef_numfields(msgdef);
@@ -363,6 +584,11 @@ MessageLayout* create_layout(const upb_msgdef* msgdef) {
size_t off = 0;
int i = 0;
+ // Reserve space for unknown fields.
+ off += sizeof(void*);
+
+ TSRMLS_FETCH();
+ Descriptor* desc = UNBOX_HASHTABLE_VALUE(Descriptor, get_def_obj(msgdef));
layout->fields = ALLOC_N(MessageField, nfields);
for (upb_msg_field_begin(&it, msgdef); !upb_msg_field_done(&it);
@@ -388,7 +614,37 @@ MessageLayout* create_layout(const upb_msgdef* msgdef) {
layout->fields[upb_fielddef_index(field)].offset = off;
layout->fields[upb_fielddef_index(field)].case_offset =
MESSAGE_FIELD_NO_CASE;
- layout->fields[upb_fielddef_index(field)].cache_index = i++;
+
+ const char* fieldname = upb_fielddef_name(field);
+
+#if PHP_MAJOR_VERSION < 7 || (PHP_MAJOR_VERSION == 7 && PHP_MINOR_VERSION == 0)
+ zend_class_entry* old_scope = EG(scope);
+ EG(scope) = desc->klass;
+#else
+ zend_class_entry* old_scope = EG(fake_scope);
+ EG(fake_scope) = desc->klass;
+#endif
+
+#if PHP_MAJOR_VERSION < 7
+ zval member;
+ ZVAL_STRINGL(&member, fieldname, strlen(fieldname), 0);
+ zend_property_info* property_info =
+ zend_get_property_info(desc->klass, &member, true TSRMLS_CC);
+#else
+ zend_string* member = zend_string_init(fieldname, strlen(fieldname), 1);
+ zend_property_info* property_info =
+ zend_get_property_info(desc->klass, member, true);
+ zend_string_release(member);
+#endif
+
+#if PHP_MAJOR_VERSION < 7 || (PHP_MAJOR_VERSION == 7 && PHP_MINOR_VERSION == 0)
+ EG(scope) = old_scope;
+#else
+ EG(fake_scope) = old_scope;
+#endif
+
+ layout->fields[upb_fielddef_index(field)].cache_index =
+ property_info->offset;
off += field_size;
}
@@ -416,11 +672,40 @@ MessageLayout* create_layout(const upb_msgdef* msgdef) {
// Align the offset .
off = align_up_to( off, field_size);
// Assign all fields in the oneof this same offset.
+ const char* oneofname = upb_oneofdef_name(oneof);
for (upb_oneof_begin(&fit, oneof); !upb_oneof_done(&fit);
upb_oneof_next(&fit)) {
const upb_fielddef* field = upb_oneof_iter_field(&fit);
layout->fields[upb_fielddef_index(field)].offset = off;
- layout->fields[upb_fielddef_index(field)].cache_index = i;
+
+#if PHP_MAJOR_VERSION < 7 || (PHP_MAJOR_VERSION == 7 && PHP_MINOR_VERSION == 0)
+ zend_class_entry* old_scope = EG(scope);
+ EG(scope) = desc->klass;
+#else
+ zend_class_entry* old_scope = EG(fake_scope);
+ EG(fake_scope) = desc->klass;
+#endif
+
+#if PHP_MAJOR_VERSION < 7
+ zval member;
+ ZVAL_STRINGL(&member, oneofname, strlen(oneofname), 0);
+ zend_property_info* property_info =
+ zend_get_property_info(desc->klass, &member, true TSRMLS_CC);
+#else
+ zend_string* member = zend_string_init(oneofname, strlen(oneofname), 1);
+ zend_property_info* property_info =
+ zend_get_property_info(desc->klass, member, true);
+ zend_string_release(member);
+#endif
+
+#if PHP_MAJOR_VERSION < 7 || (PHP_MAJOR_VERSION == 7 && PHP_MINOR_VERSION == 0)
+ EG(scope) = old_scope;
+#else
+ EG(fake_scope) = old_scope;
+#endif
+
+ layout->fields[upb_fielddef_index(field)].cache_index =
+ property_info->offset;
}
i++;
off += field_size;
@@ -459,29 +744,40 @@ void free_layout(MessageLayout* layout) {
}
void layout_init(MessageLayout* layout, void* storage,
- zval** properties_table TSRMLS_DC) {
+ zend_object* object PHP_PROTO_TSRMLS_DC) {
int i;
upb_msg_field_iter it;
+
+ // Init unknown fields
+ memset(storage, 0, sizeof(void*));
+
for (upb_msg_field_begin(&it, layout->msgdef), i = 0; !upb_msg_field_done(&it);
upb_msg_field_next(&it), i++) {
const upb_fielddef* field = upb_msg_iter_field(&it);
void* memory = slot_memory(layout, storage, field);
uint32_t* oneof_case = slot_oneof_case(layout, storage, field);
int cache_index = slot_property_cache(layout, storage, field);
- zval** property_ptr = &properties_table[cache_index];
+ CACHED_VALUE* property_ptr = OBJ_PROP(object, cache_index);
if (upb_fielddef_containingoneof(field)) {
memset(memory, 0, NATIVE_SLOT_MAX_SIZE);
*oneof_case = ONEOF_CASE_NONE;
} else if (is_map_field(field)) {
zval_ptr_dtor(property_ptr);
- map_field_create_with_type(map_field_type, field, property_ptr TSRMLS_CC);
- DEREF(memory, zval**) = property_ptr;
+#if PHP_MAJOR_VERSION < 7
+ MAKE_STD_ZVAL(*property_ptr);
+#endif
+ map_field_create_with_field(map_field_type, field,
+ property_ptr PHP_PROTO_TSRMLS_CC);
+ DEREF(memory, CACHED_VALUE*) = property_ptr;
} else if (upb_fielddef_label(field) == UPB_LABEL_REPEATED) {
zval_ptr_dtor(property_ptr);
- repeated_field_create_with_type(repeated_field_type, field,
- property_ptr TSRMLS_CC);
- DEREF(memory, zval**) = property_ptr;
+#if PHP_MAJOR_VERSION < 7
+ MAKE_STD_ZVAL(*property_ptr);
+#endif
+ repeated_field_create_with_field(repeated_field_type, field,
+ property_ptr PHP_PROTO_TSRMLS_CC);
+ DEREF(memory, CACHED_VALUE*) = property_ptr;
} else {
native_slot_init(upb_fielddef_type(field), memory, property_ptr);
}
@@ -495,7 +791,7 @@ static void* value_memory(const upb_fielddef* field, void* memory) {
case UPB_TYPE_STRING:
case UPB_TYPE_BYTES:
case UPB_TYPE_MESSAGE:
- memory = DEREF(memory, zval**);
+ memory = DEREF(memory, CACHED_VALUE*);
break;
default:
// No operation
@@ -505,7 +801,7 @@ static void* value_memory(const upb_fielddef* field, void* memory) {
}
zval* layout_get(MessageLayout* layout, const void* storage,
- const upb_fielddef* field, zval** cache TSRMLS_DC) {
+ const upb_fielddef* field, CACHED_VALUE* cache TSRMLS_DC) {
void* memory = slot_memory(layout, storage, field);
uint32_t* oneof_case = slot_oneof_case(layout, storage, field);
@@ -516,18 +812,18 @@ zval* layout_get(MessageLayout* layout, const void* storage,
native_slot_get(upb_fielddef_type(field), value_memory(field, memory),
cache TSRMLS_CC);
}
- return *cache;
+ return CACHED_PTR_TO_ZVAL_PTR(cache);
} else if (upb_fielddef_label(field) == UPB_LABEL_REPEATED) {
- return *cache;
+ return CACHED_PTR_TO_ZVAL_PTR(cache);
} else {
native_slot_get(upb_fielddef_type(field), value_memory(field, memory),
cache TSRMLS_CC);
- return *cache;
+ return CACHED_PTR_TO_ZVAL_PTR(cache);
}
}
void layout_set(MessageLayout* layout, MessageHeader* header,
- const upb_fielddef* field, zval* val TSRMLS_DC) {
+ const upb_fielddef* field, zval* val TSRMLS_DC) {
void* storage = message_data(header);
void* memory = slot_memory(layout, storage, field);
uint32_t* oneof_case = slot_oneof_case(layout, storage, field);
@@ -541,8 +837,7 @@ void layout_set(MessageLayout* layout, MessageHeader* header,
switch (type) {
case UPB_TYPE_MESSAGE: {
const upb_msgdef* msg = upb_fielddef_msgsubdef(field);
- zval* desc_php = get_def_obj(msg);
- Descriptor* desc = zend_object_store_get_object(desc_php TSRMLS_CC);
+ Descriptor* desc = UNBOX_HASHTABLE_VALUE(Descriptor, get_def_obj(msg));
ce = desc->klass;
// Intentionally fall through.
}
@@ -551,9 +846,9 @@ void layout_set(MessageLayout* layout, MessageHeader* header,
int property_cache_index =
header->descriptor->layout->fields[upb_fielddef_index(field)]
.cache_index;
- DEREF(memory, zval**) =
- &(header->std.properties_table)[property_cache_index];
- memory = DEREF(memory, zval**);
+ DEREF(memory, CACHED_VALUE*) =
+ OBJ_PROP(&header->std, property_cache_index);
+ memory = DEREF(memory, CACHED_VALUE*);
break;
}
default:
@@ -564,21 +859,287 @@ void layout_set(MessageLayout* layout, MessageHeader* header,
*oneof_case = upb_fielddef_number(field);
} else if (upb_fielddef_label(field) == UPB_LABEL_REPEATED) {
// Works for both repeated and map fields
- memory = DEREF(memory, zval**);
- if (EXPECTED(DEREF(memory, zval*) != val)) {
- zval_ptr_dtor(memory);
- DEREF(memory, zval*) = val;
- Z_ADDREF_P(val);
+ memory = DEREF(memory, void**);
+ zval* property_ptr = CACHED_PTR_TO_ZVAL_PTR((CACHED_VALUE*)memory);
+
+ if (EXPECTED(property_ptr != val)) {
+ zend_class_entry *subce = NULL;
+ zval converted_value;
+
+ if (upb_fielddef_ismap(field)) {
+ const upb_msgdef* mapmsg = upb_fielddef_msgsubdef(field);
+ const upb_fielddef* keyfield = upb_msgdef_ntof(mapmsg, "key", 3);
+ const upb_fielddef* valuefield = upb_msgdef_ntof(mapmsg, "value", 5);
+ if (upb_fielddef_descriptortype(valuefield) ==
+ UPB_DESCRIPTOR_TYPE_MESSAGE) {
+ const upb_msgdef* submsg = upb_fielddef_msgsubdef(valuefield);
+ Descriptor* subdesc =
+ UNBOX_HASHTABLE_VALUE(Descriptor, get_def_obj(submsg));
+ subce = subdesc->klass;
+ }
+ check_map_field(subce, upb_fielddef_descriptortype(keyfield),
+ upb_fielddef_descriptortype(valuefield), val,
+ &converted_value);
+ } else {
+ if (upb_fielddef_type(field) == UPB_TYPE_MESSAGE) {
+ const upb_msgdef* submsg = upb_fielddef_msgsubdef(field);
+ Descriptor* subdesc =
+ UNBOX_HASHTABLE_VALUE(Descriptor, get_def_obj(submsg));
+ subce = subdesc->klass;
+ }
+
+ check_repeated_field(subce, upb_fielddef_descriptortype(field), val,
+ &converted_value);
+ }
+#if PHP_MAJOR_VERSION < 7
+ REPLACE_ZVAL_VALUE((zval**)memory, &converted_value, 1);
+#else
+ php_proto_zval_ptr_dtor(property_ptr);
+ ZVAL_ZVAL(property_ptr, &converted_value, 1, 0);
+#endif
+ zval_dtor(&converted_value);
}
} else {
upb_fieldtype_t type = upb_fielddef_type(field);
zend_class_entry *ce = NULL;
if (type == UPB_TYPE_MESSAGE) {
const upb_msgdef* msg = upb_fielddef_msgsubdef(field);
- zval* desc_php = get_def_obj(msg);
- Descriptor* desc = zend_object_store_get_object(desc_php TSRMLS_CC);
+ Descriptor* desc = UNBOX_HASHTABLE_VALUE(Descriptor, get_def_obj(msg));
ce = desc->klass;
}
native_slot_set(type, ce, value_memory(field, memory), val TSRMLS_CC);
}
}
+
+static void native_slot_merge(const upb_fielddef* field, const void* from_memory,
+ void* to_memory PHP_PROTO_TSRMLS_DC) {
+ upb_fieldtype_t type = upb_fielddef_type(field);
+ zend_class_entry* ce = NULL;
+ if (!native_slot_is_default(type, from_memory)) {
+ switch (type) {
+#define CASE_TYPE(upb_type, c_type) \
+ case UPB_TYPE_##upb_type: { \
+ DEREF(to_memory, c_type) = DEREF(from_memory, c_type); \
+ break; \
+ }
+ CASE_TYPE(INT32, int32_t)
+ CASE_TYPE(UINT32, uint32_t)
+ CASE_TYPE(ENUM, int32_t)
+ CASE_TYPE(INT64, int64_t)
+ CASE_TYPE(UINT64, uint64_t)
+ CASE_TYPE(FLOAT, float)
+ CASE_TYPE(DOUBLE, double)
+ CASE_TYPE(BOOL, int8_t)
+
+#undef CASE_TYPE
+ case UPB_TYPE_STRING:
+ case UPB_TYPE_BYTES:
+ native_slot_set(type, NULL, value_memory(field, to_memory),
+ CACHED_PTR_TO_ZVAL_PTR(DEREF(
+ from_memory, CACHED_VALUE*)) PHP_PROTO_TSRMLS_CC);
+ break;
+ case UPB_TYPE_MESSAGE: {
+ const upb_msgdef* msg = upb_fielddef_msgsubdef(field);
+ Descriptor* desc = UNBOX_HASHTABLE_VALUE(Descriptor, get_def_obj(msg));
+ ce = desc->klass;
+ if (native_slot_is_default(type, to_memory)) {
+#if PHP_MAJOR_VERSION < 7
+ SEPARATE_ZVAL_IF_NOT_REF((zval**)value_memory(field, to_memory));
+#endif
+ CREATE_OBJ_ON_ALLOCATED_ZVAL_PTR(
+ CACHED_PTR_TO_ZVAL_PTR(DEREF(to_memory, CACHED_VALUE*)), ce);
+ MessageHeader* submsg =
+ UNBOX(MessageHeader,
+ CACHED_PTR_TO_ZVAL_PTR(DEREF(to_memory, CACHED_VALUE*)));
+ custom_data_init(ce, submsg PHP_PROTO_TSRMLS_CC);
+ }
+
+ MessageHeader* sub_from =
+ UNBOX(MessageHeader,
+ CACHED_PTR_TO_ZVAL_PTR(DEREF(from_memory, CACHED_VALUE*)));
+ MessageHeader* sub_to =
+ UNBOX(MessageHeader,
+ CACHED_PTR_TO_ZVAL_PTR(DEREF(to_memory, CACHED_VALUE*)));
+
+ layout_merge(desc->layout, sub_from, sub_to PHP_PROTO_TSRMLS_CC);
+ break;
+ }
+ }
+ }
+}
+
+static void native_slot_merge_by_array(const upb_fielddef* field, const void* from_memory,
+ void* to_memory PHP_PROTO_TSRMLS_DC) {
+ upb_fieldtype_t type = upb_fielddef_type(field);
+ switch (type) {
+ case UPB_TYPE_STRING:
+ case UPB_TYPE_BYTES: {
+#if PHP_MAJOR_VERSION < 7
+ MAKE_STD_ZVAL(DEREF(to_memory, zval*));
+ PHP_PROTO_ZVAL_STRINGL(DEREF(to_memory, zval*),
+ Z_STRVAL_P(*(zval**)from_memory),
+ Z_STRLEN_P(*(zval**)from_memory), 1);
+#else
+ DEREF(to_memory, zend_string*) =
+ zend_string_dup(*(zend_string**)from_memory, 0);
+#endif
+ break;
+ }
+ case UPB_TYPE_MESSAGE: {
+ const upb_msgdef* msg = upb_fielddef_msgsubdef(field);
+ Descriptor* desc = UNBOX_HASHTABLE_VALUE(Descriptor, get_def_obj(msg));
+ zend_class_entry* ce = desc->klass;
+#if PHP_MAJOR_VERSION < 7
+ MAKE_STD_ZVAL(DEREF(to_memory, zval*));
+ CREATE_OBJ_ON_ALLOCATED_ZVAL_PTR(DEREF(to_memory, zval*), ce);
+#else
+ DEREF(to_memory, zend_object*) = ce->create_object(ce TSRMLS_CC);
+#endif
+ MessageHeader* sub_from = UNBOX_HASHTABLE_VALUE(
+ MessageHeader, DEREF(from_memory, PHP_PROTO_HASHTABLE_VALUE));
+ MessageHeader* sub_to = UNBOX_HASHTABLE_VALUE(
+ MessageHeader, DEREF(to_memory, PHP_PROTO_HASHTABLE_VALUE));
+ custom_data_init(ce, sub_to PHP_PROTO_TSRMLS_CC);
+
+ layout_merge(desc->layout, sub_from, sub_to PHP_PROTO_TSRMLS_CC);
+ break;
+ }
+ default:
+ native_slot_merge(field, from_memory, to_memory PHP_PROTO_TSRMLS_CC);
+ break;
+ }
+}
+
+void layout_merge(MessageLayout* layout, MessageHeader* from,
+ MessageHeader* to PHP_PROTO_TSRMLS_DC) {
+ int i, j;
+ upb_msg_field_iter it;
+
+ for (upb_msg_field_begin(&it, layout->msgdef), i = 0; !upb_msg_field_done(&it);
+ upb_msg_field_next(&it), i++) {
+ const upb_fielddef* field = upb_msg_iter_field(&it);
+
+ void* to_memory = slot_memory(layout, message_data(to), field);
+ void* from_memory = slot_memory(layout, message_data(from), field);
+
+ if (upb_fielddef_containingoneof(field)) {
+ uint32_t oneof_case_offset =
+ layout->fields[upb_fielddef_index(field)].case_offset;
+ // For a oneof, check that this field is actually present -- skip all the
+ // below if not.
+ if (DEREF((message_data(from) + oneof_case_offset), uint32_t) !=
+ upb_fielddef_number(field)) {
+ continue;
+ }
+ uint32_t* from_oneof_case = slot_oneof_case(layout, message_data(from), field);
+ uint32_t* to_oneof_case = slot_oneof_case(layout, message_data(to), field);
+
+ // For non-singular fields, the related memory needs to point to the
+ // actual zval in properties table first.
+ switch (upb_fielddef_type(field)) {
+ case UPB_TYPE_MESSAGE:
+ case UPB_TYPE_STRING:
+ case UPB_TYPE_BYTES: {
+ int property_cache_index =
+ layout->fields[upb_fielddef_index(field)].cache_index;
+ DEREF(to_memory, CACHED_VALUE*) =
+ OBJ_PROP(&to->std, property_cache_index);
+ break;
+ }
+ default:
+ break;
+ }
+
+ *to_oneof_case = *from_oneof_case;
+
+ // Otherwise, fall through to the appropriate singular-field handler
+ // below.
+ }
+
+ if (is_map_field(field)) {
+ int size, key_length, value_length;
+ MapIter map_it;
+
+ zval* to_map_php =
+ CACHED_PTR_TO_ZVAL_PTR(DEREF(to_memory, CACHED_VALUE*));
+ zval* from_map_php =
+ CACHED_PTR_TO_ZVAL_PTR(DEREF(from_memory, CACHED_VALUE*));
+ Map* to_map = UNBOX(Map, to_map_php);
+ Map* from_map = UNBOX(Map, from_map_php);
+
+ size = upb_strtable_count(&from_map->table);
+ if (size == 0) continue;
+
+ const upb_msgdef *mapentry_def = upb_fielddef_msgsubdef(field);
+ const upb_fielddef *value_field = upb_msgdef_itof(mapentry_def, 2);
+
+ for (map_begin(from_map_php, &map_it TSRMLS_CC); !map_done(&map_it);
+ map_next(&map_it)) {
+ const char* key = map_iter_key(&map_it, &key_length);
+ upb_value from_value = map_iter_value(&map_it, &value_length);
+ upb_value to_value;
+ void* from_mem = upb_value_memory(&from_value);
+ void* to_mem = upb_value_memory(&to_value);
+ memset(to_mem, 0, native_slot_size(to_map->value_type));
+
+ native_slot_merge_by_array(value_field, from_mem,
+ to_mem PHP_PROTO_TSRMLS_CC);
+
+ map_index_set(to_map, key, key_length, to_value);
+ }
+
+ } else if (upb_fielddef_label(field) == UPB_LABEL_REPEATED) {
+ zval* to_array_php = CACHED_PTR_TO_ZVAL_PTR(DEREF(to_memory, CACHED_VALUE*));
+ zval* from_array_php = CACHED_PTR_TO_ZVAL_PTR(DEREF(from_memory, CACHED_VALUE*));
+ RepeatedField* to_array = UNBOX(RepeatedField, to_array_php);
+ RepeatedField* from_array = UNBOX(RepeatedField, from_array_php);
+
+ int size = zend_hash_num_elements(PHP_PROTO_HASH_OF(from_array->array));
+ if (size > 0) {
+ for (j = 0; j < size; j++) {
+ void* from_memory = NULL;
+ void* to_memory =
+ ALLOC_N(char, native_slot_size(upb_fielddef_type(field)));
+ memset(to_memory, 0, native_slot_size(upb_fielddef_type(field)));
+
+ if (to_array->type == UPB_TYPE_MESSAGE) {
+ php_proto_zend_hash_index_find_zval(
+ PHP_PROTO_HASH_OF(from_array->array), j, (void**)&from_memory);
+#if PHP_MAJOR_VERSION >= 7
+ from_memory = &Z_OBJ_P((zval*)from_memory);
+#endif
+ } else {
+ php_proto_zend_hash_index_find_mem(
+ PHP_PROTO_HASH_OF(from_array->array), j, (void**)&from_memory);
+ }
+
+ native_slot_merge_by_array(field, from_memory,
+ to_memory PHP_PROTO_TSRMLS_CC);
+ repeated_field_push_native(to_array, to_memory);
+ FREE(to_memory);
+ }
+ }
+ } else {
+ native_slot_merge(field, from_memory, to_memory PHP_PROTO_TSRMLS_CC);
+ }
+ }
+}
+
+const char* layout_get_oneof_case(MessageLayout* layout, const void* storage,
+ const upb_oneofdef* oneof TSRMLS_DC) {
+ upb_oneof_iter i;
+ const upb_fielddef* first_field;
+
+ // Oneof is guaranteed to have at least one field. Get the first field.
+ for(upb_oneof_begin(&i, oneof); !upb_oneof_done(&i); upb_oneof_next(&i)) {
+ first_field = upb_oneof_iter_field(&i);
+ break;
+ }
+
+ uint32_t* oneof_case = slot_oneof_case(layout, storage, first_field);
+ if (*oneof_case == 0) {
+ return "";
+ }
+ const upb_fielddef* field = upb_oneofdef_itof(oneof, *oneof_case);
+ return upb_fielddef_name(field);
+}
diff --git a/php/ext/google/protobuf/type_check.c b/php/ext/google/protobuf/type_check.c
index d12d0025..f588774c 100644
--- a/php/ext/google/protobuf/type_check.c
+++ b/php/ext/google/protobuf/type_check.c
@@ -51,6 +51,13 @@ ZEND_BEGIN_ARG_INFO_EX(arg_check_repeated, 0, 0, 2)
ZEND_ARG_INFO(0, klass)
ZEND_END_ARG_INFO()
+ZEND_BEGIN_ARG_INFO_EX(arg_check_map, 0, 0, 3)
+ ZEND_ARG_INFO(1, val)
+ ZEND_ARG_INFO(0, key_type)
+ ZEND_ARG_INFO(0, value_type)
+ ZEND_ARG_INFO(0, klass)
+ZEND_END_ARG_INFO()
+
static zend_function_entry util_methods[] = {
PHP_ME(Util, checkInt32, arg_check_optional, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
PHP_ME(Util, checkUint32, arg_check_optional, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
@@ -63,6 +70,7 @@ static zend_function_entry util_methods[] = {
PHP_ME(Util, checkString, arg_check_optional, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
PHP_ME(Util, checkBytes, arg_check_optional, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
PHP_ME(Util, checkMessage, arg_check_message, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
+ PHP_ME(Util, checkMapField, arg_check_map, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
PHP_ME(Util, checkRepeatedField, arg_check_repeated,
ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
ZEND_FE_END
@@ -317,9 +325,18 @@ CONVERT_TO_FLOAT(double);
bool protobuf_convert_to_bool(zval* from, int8_t* to) {
switch (Z_TYPE_P(from)) {
+#if PHP_MAJOR_VERSION < 7
case IS_BOOL:
*to = (int8_t)Z_BVAL_P(from);
break;
+#else
+ case IS_TRUE:
+ *to = 1;
+ break;
+ case IS_FALSE:
+ *to = 0;
+ break;
+#endif
case IS_LONG:
*to = (int8_t)(Z_LVAL_P(from) != 0);
break;
@@ -349,12 +366,16 @@ bool protobuf_convert_to_string(zval* from) {
case IS_STRING: {
return true;
}
+#if PHP_MAJOR_VERSION < 7
case IS_BOOL:
+#else
+ case IS_TRUE:
+ case IS_FALSE:
+#endif
case IS_LONG:
case IS_DOUBLE: {
- int use_copy;
zval tmp;
- zend_make_printable_zval(from, &tmp, &use_copy);
+ php_proto_zend_make_printable_zval(from, &tmp);
ZVAL_COPY_VALUE(from, &tmp);
return true;
}
@@ -407,24 +428,149 @@ PHP_METHOD(Util, checkMessage) {
RETURN_ZVAL(val, 1, 0);
}
+void check_repeated_field(const zend_class_entry* klass, PHP_PROTO_LONG type,
+ zval* val, zval* return_value) {
+#if PHP_MAJOR_VERSION >= 7
+ if (Z_ISREF_P(val)) {
+ ZVAL_DEREF(val);
+ }
+#endif
+
+ TSRMLS_FETCH();
+ if (Z_TYPE_P(val) == IS_ARRAY) {
+ HashTable* table = HASH_OF(val);
+ HashPosition pointer;
+ void* memory;
+
+#if PHP_MAJOR_VERSION < 7
+ zval* repeated_field;
+ MAKE_STD_ZVAL(repeated_field);
+#else
+ zval repeated_field;
+#endif
+
+ repeated_field_create_with_type(repeated_field_type, to_fieldtype(type),
+ klass, &repeated_field TSRMLS_CC);
+
+ for (zend_hash_internal_pointer_reset_ex(table, &pointer);
+ php_proto_zend_hash_get_current_data_ex(table, (void**)&memory,
+ &pointer) == SUCCESS;
+ zend_hash_move_forward_ex(table, &pointer)) {
+ repeated_field_handlers->write_dimension(
+ CACHED_TO_ZVAL_PTR(repeated_field), NULL,
+ CACHED_PTR_TO_ZVAL_PTR((CACHED_VALUE*)memory) TSRMLS_CC);
+ }
+
+ Z_DELREF_P(CACHED_TO_ZVAL_PTR(repeated_field));
+ RETURN_ZVAL(CACHED_TO_ZVAL_PTR(repeated_field), 1, 0);
+
+ } else if (Z_TYPE_P(val) == IS_OBJECT) {
+ if (!instanceof_function(Z_OBJCE_P(val), repeated_field_type TSRMLS_CC)) {
+ zend_error(E_USER_ERROR, "Given value is not an instance of %s.",
+ repeated_field_type->name);
+ return;
+ }
+ RepeatedField* intern = UNBOX(RepeatedField, val);
+ if (to_fieldtype(type) != intern->type) {
+ zend_error(E_USER_ERROR, "Incorrect repeated field type.");
+ return;
+ }
+ if (klass != NULL && intern->msg_ce != klass) {
+ zend_error(E_USER_ERROR,
+ "Expect a repeated field of %s, but %s is given.", klass->name,
+ intern->msg_ce->name);
+ return;
+ }
+ RETURN_ZVAL(val, 1, 0);
+ } else {
+ zend_error(E_USER_ERROR, "Incorrect repeated field type.");
+ return;
+ }
+}
+
PHP_METHOD(Util, checkRepeatedField) {
zval* val;
- long type;
+ PHP_PROTO_LONG type;
const zend_class_entry* klass = NULL;
- if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Ol|C", &val,
- repeated_field_type, &type, &klass) == FAILURE) {
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zl|C", &val, &type,
+ &klass) == FAILURE) {
return;
}
+ RETURN_ZVAL(val, 1, 0);
+}
- RepeatedField *intern =
- (RepeatedField *)zend_object_store_get_object(val TSRMLS_CC);
- if (to_fieldtype(type) != intern->type) {
- zend_error(E_USER_ERROR, "Incorrect repeated field type.");
+void check_map_field(const zend_class_entry* klass, PHP_PROTO_LONG key_type,
+ PHP_PROTO_LONG value_type, zval* val, zval* return_value) {
+#if PHP_MAJOR_VERSION >= 7
+ if (Z_ISREF_P(val)) {
+ ZVAL_DEREF(val);
+ }
+#endif
+
+ TSRMLS_FETCH();
+ if (Z_TYPE_P(val) == IS_ARRAY) {
+ HashTable* table = Z_ARRVAL_P(val);
+ HashPosition pointer;
+ zval key;
+ void* value;
+
+#if PHP_MAJOR_VERSION < 7
+ zval* map_field;
+ MAKE_STD_ZVAL(map_field);
+#else
+ zval map_field;
+#endif
+
+ map_field_create_with_type(map_field_type, to_fieldtype(key_type),
+ to_fieldtype(value_type), klass,
+ &map_field TSRMLS_CC);
+
+ for (zend_hash_internal_pointer_reset_ex(table, &pointer);
+ php_proto_zend_hash_get_current_data_ex(table, (void**)&value,
+ &pointer) == SUCCESS;
+ zend_hash_move_forward_ex(table, &pointer)) {
+ zend_hash_get_current_key_zval_ex(table, &key, &pointer);
+ map_field_handlers->write_dimension(
+ CACHED_TO_ZVAL_PTR(map_field), &key,
+ CACHED_PTR_TO_ZVAL_PTR((CACHED_VALUE*)value) TSRMLS_CC);
+ }
+
+ Z_DELREF_P(CACHED_TO_ZVAL_PTR(map_field));
+ RETURN_ZVAL(CACHED_TO_ZVAL_PTR(map_field), 1, 0);
+ } else if (Z_TYPE_P(val) == IS_OBJECT) {
+ if (!instanceof_function(Z_OBJCE_P(val), map_field_type TSRMLS_CC)) {
+ zend_error(E_USER_ERROR, "Given value is not an instance of %s.",
+ map_field_type->name);
+ return;
+ }
+ Map* intern = UNBOX(Map, val);
+ if (to_fieldtype(key_type) != intern->key_type) {
+ zend_error(E_USER_ERROR, "Incorrect map field key type.");
+ return;
+ }
+ if (to_fieldtype(value_type) != intern->value_type) {
+ zend_error(E_USER_ERROR, "Incorrect map field value type.");
+ return;
+ }
+ if (klass != NULL && intern->msg_ce != klass) {
+ zend_error(E_USER_ERROR, "Expect a map field of %s, but %s is given.",
+ klass->name, intern->msg_ce->name);
+ return;
+ }
+ RETURN_ZVAL(val, 1, 0);
+ } else {
+ zend_error(E_USER_ERROR, "Incorrect map field type.");
return;
}
- if (klass != NULL && intern->msg_ce != klass) {
- zend_error(E_USER_ERROR, "Expect a repeated field of %s, but %s is given.",
- klass->name, intern->msg_ce->name);
+}
+
+PHP_METHOD(Util, checkMapField) {
+ zval* val;
+ PHP_PROTO_LONG key_type, value_type;
+ const zend_class_entry* klass = NULL;
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zll|C", &val, &key_type,
+ &value_type, &klass) == FAILURE) {
return;
}
+ RETURN_ZVAL(val, 1, 0);
}
diff --git a/php/ext/google/protobuf/upb.c b/php/ext/google/protobuf/upb.c
index 98daafc0..c02a5ce4 100644
--- a/php/ext/google/protobuf/upb.c
+++ b/php/ext/google/protobuf/upb.c
@@ -1,36 +1,586 @@
-// 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.
-
+// Amalgamated source file
#include "upb.h"
+/* Maps descriptor type -> upb field type. */
+static const uint8_t upb_desctype_to_fieldtype[] = {
+ UPB_WIRE_TYPE_END_GROUP, /* ENDGROUP */
+ UPB_TYPE_DOUBLE, /* DOUBLE */
+ UPB_TYPE_FLOAT, /* FLOAT */
+ UPB_TYPE_INT64, /* INT64 */
+ UPB_TYPE_UINT64, /* UINT64 */
+ UPB_TYPE_INT32, /* INT32 */
+ UPB_TYPE_UINT64, /* FIXED64 */
+ UPB_TYPE_UINT32, /* FIXED32 */
+ UPB_TYPE_BOOL, /* BOOL */
+ UPB_TYPE_STRING, /* STRING */
+ UPB_TYPE_MESSAGE, /* GROUP */
+ UPB_TYPE_MESSAGE, /* MESSAGE */
+ UPB_TYPE_BYTES, /* BYTES */
+ UPB_TYPE_UINT32, /* UINT32 */
+ UPB_TYPE_ENUM, /* ENUM */
+ UPB_TYPE_INT32, /* SFIXED32 */
+ UPB_TYPE_INT64, /* SFIXED64 */
+ UPB_TYPE_INT32, /* SINT32 */
+ UPB_TYPE_INT64, /* SINT64 */
+};
+
+/* Data pertaining to the parse. */
+typedef struct {
+ upb_env *env;
+ /* Current decoding pointer. Points to the beginning of a field until we
+ * have finished decoding the whole field. */
+ const char *ptr;
+} upb_decstate;
+
+/* Data pertaining to a single message frame. */
+typedef struct {
+ const char *limit;
+ int32_t group_number; /* 0 if we are not parsing a group. */
+
+ /* These members are unset for an unknown group frame. */
+ char *msg;
+ const upb_msglayout_msginit_v1 *m;
+} upb_decframe;
+
+#define CHK(x) if (!(x)) { return false; }
+
+static bool upb_skip_unknowngroup(upb_decstate *d, int field_number,
+ const char *limit);
+static bool upb_decode_message(upb_decstate *d, const char *limit,
+ int group_number, char *msg,
+ const upb_msglayout_msginit_v1 *l);
+
+static bool upb_decode_varint(const char **ptr, const char *limit,
+ uint64_t *val) {
+ uint8_t byte;
+ int bitpos = 0;
+ const char *p = *ptr;
+ *val = 0;
+
+ do {
+ CHK(bitpos < 70 && p < limit);
+ byte = *p;
+ *val |= (uint64_t)(byte & 0x7F) << bitpos;
+ p++;
+ bitpos += 7;
+ } while (byte & 0x80);
+
+ *ptr = p;
+ return true;
+}
+
+static bool upb_decode_varint32(const char **ptr, const char *limit,
+ uint32_t *val) {
+ uint64_t u64;
+ CHK(upb_decode_varint(ptr, limit, &u64) && u64 <= UINT32_MAX);
+ *val = u64;
+ return true;
+}
+
+static bool upb_decode_64bit(const char **ptr, const char *limit,
+ uint64_t *val) {
+ CHK(limit - *ptr >= 8);
+ memcpy(val, *ptr, 8);
+ *ptr += 8;
+ return true;
+}
+
+static bool upb_decode_32bit(const char **ptr, const char *limit,
+ uint32_t *val) {
+ CHK(limit - *ptr >= 4);
+ memcpy(val, *ptr, 4);
+ *ptr += 4;
+ return true;
+}
+
+static bool upb_decode_tag(const char **ptr, const char *limit,
+ int *field_number, int *wire_type) {
+ uint32_t tag = 0;
+ CHK(upb_decode_varint32(ptr, limit, &tag));
+ *field_number = tag >> 3;
+ *wire_type = tag & 7;
+ return true;
+}
+
+static int32_t upb_zzdecode_32(uint32_t n) {
+ return (n >> 1) ^ -(int32_t)(n & 1);
+}
+
+static int64_t upb_zzdecode_64(uint64_t n) {
+ return (n >> 1) ^ -(int64_t)(n & 1);
+}
+
+static bool upb_decode_string(const char **ptr, const char *limit,
+ upb_stringview *val) {
+ uint32_t len;
+
+ CHK(upb_decode_varint32(ptr, limit, &len) &&
+ len < INT32_MAX &&
+ limit - *ptr >= (int32_t)len);
+
+ *val = upb_stringview_make(*ptr, len);
+ *ptr += len;
+ return true;
+}
+
+static void upb_set32(void *msg, size_t ofs, uint32_t val) {
+ memcpy((char*)msg + ofs, &val, sizeof(val));
+}
+
+static bool upb_append_unknown(upb_decstate *d, upb_decframe *frame,
+ const char *start) {
+ UPB_UNUSED(d);
+ UPB_UNUSED(frame);
+ UPB_UNUSED(start);
+ return true;
+}
+
+static bool upb_skip_unknownfielddata(upb_decstate *d, upb_decframe *frame,
+ int field_number, int wire_type) {
+ switch (wire_type) {
+ case UPB_WIRE_TYPE_VARINT: {
+ uint64_t val;
+ return upb_decode_varint(&d->ptr, frame->limit, &val);
+ }
+ case UPB_WIRE_TYPE_32BIT: {
+ uint32_t val;
+ return upb_decode_32bit(&d->ptr, frame->limit, &val);
+ }
+ case UPB_WIRE_TYPE_64BIT: {
+ uint64_t val;
+ return upb_decode_64bit(&d->ptr, frame->limit, &val);
+ }
+ case UPB_WIRE_TYPE_DELIMITED: {
+ upb_stringview val;
+ return upb_decode_string(&d->ptr, frame->limit, &val);
+ }
+ case UPB_WIRE_TYPE_START_GROUP:
+ return upb_skip_unknowngroup(d, field_number, frame->limit);
+ case UPB_WIRE_TYPE_END_GROUP:
+ CHK(field_number == frame->group_number);
+ frame->limit = d->ptr;
+ return true;
+ }
+ return false;
+}
+
+static bool upb_array_grow(upb_array *arr, size_t elements) {
+ size_t needed = arr->len + elements;
+ size_t new_size = UPB_MAX(arr->size, 8);
+ size_t new_bytes;
+ size_t old_bytes;
+ void *new_data;
+
+ while (new_size < needed) {
+ new_size *= 2;
+ }
+
+ old_bytes = arr->len * arr->element_size;
+ new_bytes = new_size * arr->element_size;
+ new_data = upb_realloc(arr->alloc, arr->data, old_bytes, new_bytes);
+ CHK(new_data);
+
+ arr->data = new_data;
+ arr->size = new_size;
+ return true;
+}
+
+static void *upb_array_reserve(upb_array *arr, size_t elements) {
+ if (arr->size - arr->len < elements) {
+ CHK(upb_array_grow(arr, elements));
+ }
+ return (char*)arr->data + (arr->len * arr->element_size);
+}
+
+static void *upb_array_add(upb_array *arr, size_t elements) {
+ void *ret = upb_array_reserve(arr, elements);
+ arr->len += elements;
+ return ret;
+}
+
+static upb_array *upb_getarr(upb_decframe *frame,
+ const upb_msglayout_fieldinit_v1 *field) {
+ UPB_ASSERT(field->label == UPB_LABEL_REPEATED);
+ return *(upb_array**)&frame->msg[field->offset];
+}
+
+static upb_array *upb_getorcreatearr(upb_decstate *d,
+ upb_decframe *frame,
+ const upb_msglayout_fieldinit_v1 *field) {
+ upb_array *arr = upb_getarr(frame, field);
+
+ if (!arr) {
+ arr = upb_env_malloc(d->env, sizeof(*arr));
+ if (!arr) {
+ return NULL;
+ }
+ upb_array_init(arr, upb_desctype_to_fieldtype[field->type],
+ upb_arena_alloc(upb_env_arena(d->env)));
+ *(upb_array**)&frame->msg[field->offset] = arr;
+ }
+
+ return arr;
+}
+
+static void upb_sethasbit(upb_decframe *frame,
+ const upb_msglayout_fieldinit_v1 *field) {
+ UPB_ASSERT(field->hasbit != UPB_NO_HASBIT);
+ frame->msg[field->hasbit / 8] |= (1 << (field->hasbit % 8));
+}
+
+static void upb_setoneofcase(upb_decframe *frame,
+ const upb_msglayout_fieldinit_v1 *field) {
+ UPB_ASSERT(field->oneof_index != UPB_NOT_IN_ONEOF);
+ upb_set32(frame->msg, frame->m->oneofs[field->oneof_index].case_offset,
+ field->number);
+}
+
+static char *upb_decode_prepareslot(upb_decstate *d,
+ upb_decframe *frame,
+ const upb_msglayout_fieldinit_v1 *field) {
+ char *field_mem = frame->msg + field->offset;
+ upb_array *arr;
+
+ if (field->label == UPB_LABEL_REPEATED) {
+ arr = upb_getorcreatearr(d, frame, field);
+ field_mem = upb_array_reserve(arr, 1);
+ }
+
+ return field_mem;
+}
+
+static void upb_decode_setpresent(upb_decframe *frame,
+ const upb_msglayout_fieldinit_v1 *field) {
+ if (field->label == UPB_LABEL_REPEATED) {
+ upb_array *arr = upb_getarr(frame, field);
+ UPB_ASSERT(arr->len < arr->size);
+ arr->len++;
+ } else if (field->oneof_index != UPB_NOT_IN_ONEOF) {
+ upb_setoneofcase(frame, field);
+ } else if (field->hasbit != UPB_NO_HASBIT) {
+ upb_sethasbit(frame, field);
+ }
+}
+
+static bool upb_decode_submsg(upb_decstate *d,
+ upb_decframe *frame,
+ const char *limit,
+ const upb_msglayout_fieldinit_v1 *field,
+ int group_number) {
+ char *submsg = *(void**)&frame->msg[field->offset];
+ const upb_msglayout_msginit_v1 *subm;
+
+ UPB_ASSERT(field->submsg_index != UPB_NO_SUBMSG);
+ subm = frame->m->submsgs[field->submsg_index];
+ UPB_ASSERT(subm);
+
+ if (!submsg) {
+ submsg = upb_env_malloc(d->env, upb_msg_sizeof((upb_msglayout *)subm));
+ CHK(submsg);
+ submsg = upb_msg_init(
+ submsg, (upb_msglayout*)subm, upb_arena_alloc(upb_env_arena(d->env)));
+ *(void**)&frame->msg[field->offset] = submsg;
+ }
+
+ upb_decode_message(d, limit, group_number, submsg, subm);
+
+ return true;
+}
+
+static bool upb_decode_varintfield(upb_decstate *d, upb_decframe *frame,
+ const char *field_start,
+ const upb_msglayout_fieldinit_v1 *field) {
+ uint64_t val;
+ void *field_mem;
+
+ field_mem = upb_decode_prepareslot(d, frame, field);
+ CHK(field_mem);
+ CHK(upb_decode_varint(&d->ptr, frame->limit, &val));
+
+ switch ((upb_descriptortype_t)field->type) {
+ case UPB_DESCRIPTOR_TYPE_INT64:
+ case UPB_DESCRIPTOR_TYPE_UINT64:
+ memcpy(field_mem, &val, sizeof(val));
+ break;
+ case UPB_DESCRIPTOR_TYPE_INT32:
+ case UPB_DESCRIPTOR_TYPE_UINT32:
+ case UPB_DESCRIPTOR_TYPE_ENUM: {
+ uint32_t val32 = val;
+ memcpy(field_mem, &val32, sizeof(val32));
+ break;
+ }
+ case UPB_DESCRIPTOR_TYPE_BOOL: {
+ bool valbool = val != 0;
+ memcpy(field_mem, &valbool, sizeof(valbool));
+ break;
+ }
+ case UPB_DESCRIPTOR_TYPE_SINT32: {
+ int32_t decoded = upb_zzdecode_32(val);
+ memcpy(field_mem, &decoded, sizeof(decoded));
+ break;
+ }
+ case UPB_DESCRIPTOR_TYPE_SINT64: {
+ int64_t decoded = upb_zzdecode_64(val);
+ memcpy(field_mem, &decoded, sizeof(decoded));
+ break;
+ }
+ default:
+ return upb_append_unknown(d, frame, field_start);
+ }
+
+ upb_decode_setpresent(frame, field);
+ return true;
+}
+
+static bool upb_decode_64bitfield(upb_decstate *d, upb_decframe *frame,
+ const char *field_start,
+ const upb_msglayout_fieldinit_v1 *field) {
+ void *field_mem;
+ uint64_t val;
+
+ field_mem = upb_decode_prepareslot(d, frame, field);
+ CHK(field_mem);
+ CHK(upb_decode_64bit(&d->ptr, frame->limit, &val));
+
+ switch ((upb_descriptortype_t)field->type) {
+ case UPB_DESCRIPTOR_TYPE_DOUBLE:
+ case UPB_DESCRIPTOR_TYPE_FIXED64:
+ case UPB_DESCRIPTOR_TYPE_SFIXED64:
+ memcpy(field_mem, &val, sizeof(val));
+ break;
+ default:
+ return upb_append_unknown(d, frame, field_start);
+ }
+
+ upb_decode_setpresent(frame, field);
+ return true;
+}
+
+static bool upb_decode_32bitfield(upb_decstate *d, upb_decframe *frame,
+ const char *field_start,
+ const upb_msglayout_fieldinit_v1 *field) {
+ void *field_mem;
+ uint32_t val;
+
+ field_mem = upb_decode_prepareslot(d, frame, field);
+ CHK(field_mem);
+ CHK(upb_decode_32bit(&d->ptr, frame->limit, &val));
+
+ switch ((upb_descriptortype_t)field->type) {
+ case UPB_DESCRIPTOR_TYPE_FLOAT:
+ case UPB_DESCRIPTOR_TYPE_FIXED32:
+ case UPB_DESCRIPTOR_TYPE_SFIXED32:
+ memcpy(field_mem, &val, sizeof(val));
+ break;
+ default:
+ return upb_append_unknown(d, frame, field_start);
+ }
+
+ upb_decode_setpresent(frame, field);
+ return true;
+}
+
+static bool upb_decode_fixedpacked(upb_array *arr, upb_stringview data,
+ int elem_size) {
+ int elements = data.size / elem_size;
+ void *field_mem;
+
+ CHK((size_t)(elements * elem_size) == data.size);
+ field_mem = upb_array_add(arr, elements);
+ CHK(field_mem);
+ memcpy(field_mem, data.data, data.size);
+ return true;
+}
+
+static bool upb_decode_toarray(upb_decstate *d, upb_decframe *frame,
+ const char *field_start,
+ const upb_msglayout_fieldinit_v1 *field,
+ upb_stringview val) {
+ upb_array *arr = upb_getorcreatearr(d, frame, field);
+
+#define VARINT_CASE(ctype, decode) { \
+ const char *ptr = val.data; \
+ const char *limit = ptr + val.size; \
+ while (ptr < limit) { \
+ uint64_t val; \
+ void *field_mem; \
+ ctype decoded; \
+ CHK(upb_decode_varint(&ptr, limit, &val)); \
+ decoded = (decode)(val); \
+ field_mem = upb_array_add(arr, 1); \
+ CHK(field_mem); \
+ memcpy(field_mem, &decoded, sizeof(ctype)); \
+ } \
+ return true; \
+}
+
+ switch ((upb_descriptortype_t)field->type) {
+ case UPB_DESCRIPTOR_TYPE_STRING:
+ case UPB_DESCRIPTOR_TYPE_BYTES: {
+ void *field_mem = upb_array_add(arr, 1);
+ CHK(field_mem);
+ memcpy(field_mem, &val, sizeof(val));
+ return true;
+ }
+ case UPB_DESCRIPTOR_TYPE_FLOAT:
+ case UPB_DESCRIPTOR_TYPE_FIXED32:
+ case UPB_DESCRIPTOR_TYPE_SFIXED32:
+ return upb_decode_fixedpacked(arr, val, sizeof(int32_t));
+ case UPB_DESCRIPTOR_TYPE_DOUBLE:
+ case UPB_DESCRIPTOR_TYPE_FIXED64:
+ case UPB_DESCRIPTOR_TYPE_SFIXED64:
+ return upb_decode_fixedpacked(arr, val, sizeof(int64_t));
+ case UPB_DESCRIPTOR_TYPE_INT32:
+ case UPB_DESCRIPTOR_TYPE_UINT32:
+ case UPB_DESCRIPTOR_TYPE_ENUM:
+ /* TODO: proto2 enum field that isn't in the enum. */
+ VARINT_CASE(uint32_t, uint32_t);
+ case UPB_DESCRIPTOR_TYPE_INT64:
+ case UPB_DESCRIPTOR_TYPE_UINT64:
+ VARINT_CASE(uint64_t, uint64_t);
+ case UPB_DESCRIPTOR_TYPE_BOOL:
+ VARINT_CASE(bool, bool);
+ case UPB_DESCRIPTOR_TYPE_SINT32:
+ VARINT_CASE(int32_t, upb_zzdecode_32);
+ case UPB_DESCRIPTOR_TYPE_SINT64:
+ VARINT_CASE(int64_t, upb_zzdecode_64);
+ case UPB_DESCRIPTOR_TYPE_MESSAGE:
+ CHK(val.size <= (size_t)(frame->limit - val.data));
+ return upb_decode_submsg(d, frame, val.data + val.size, field, 0);
+ case UPB_DESCRIPTOR_TYPE_GROUP:
+ return upb_append_unknown(d, frame, field_start);
+ }
+#undef VARINT_CASE
+ UPB_UNREACHABLE();
+}
+
+static bool upb_decode_delimitedfield(upb_decstate *d, upb_decframe *frame,
+ const char *field_start,
+ const upb_msglayout_fieldinit_v1 *field) {
+ upb_stringview val;
+
+ CHK(upb_decode_string(&d->ptr, frame->limit, &val));
+
+ if (field->label == UPB_LABEL_REPEATED) {
+ return upb_decode_toarray(d, frame, field_start, field, val);
+ } else {
+ switch ((upb_descriptortype_t)field->type) {
+ case UPB_DESCRIPTOR_TYPE_STRING:
+ case UPB_DESCRIPTOR_TYPE_BYTES: {
+ void *field_mem = upb_decode_prepareslot(d, frame, field);
+ CHK(field_mem);
+ memcpy(field_mem, &val, sizeof(val));
+ break;
+ }
+ case UPB_DESCRIPTOR_TYPE_MESSAGE:
+ CHK(val.size <= (size_t)(frame->limit - val.data));
+ CHK(upb_decode_submsg(d, frame, val.data + val.size, field, 0));
+ break;
+ default:
+ /* TODO(haberman): should we accept the last element of a packed? */
+ return upb_append_unknown(d, frame, field_start);
+ }
+ upb_decode_setpresent(frame, field);
+ return true;
+ }
+}
+
+static const upb_msglayout_fieldinit_v1 *upb_find_field(
+ const upb_msglayout_msginit_v1 *l, uint32_t field_number) {
+ /* Lots of optimization opportunities here. */
+ int i;
+ for (i = 0; i < l->field_count; i++) {
+ if (l->fields[i].number == field_number) {
+ return &l->fields[i];
+ }
+ }
+
+ return NULL; /* Unknown field. */
+}
+
+static bool upb_decode_field(upb_decstate *d, upb_decframe *frame) {
+ int field_number;
+ int wire_type;
+ const char *field_start = d->ptr;
+ const upb_msglayout_fieldinit_v1 *field;
+
+ CHK(upb_decode_tag(&d->ptr, frame->limit, &field_number, &wire_type));
+ field = upb_find_field(frame->m, field_number);
+
+ if (field) {
+ switch (wire_type) {
+ case UPB_WIRE_TYPE_VARINT:
+ return upb_decode_varintfield(d, frame, field_start, field);
+ case UPB_WIRE_TYPE_32BIT:
+ return upb_decode_32bitfield(d, frame, field_start, field);
+ case UPB_WIRE_TYPE_64BIT:
+ return upb_decode_64bitfield(d, frame, field_start, field);
+ case UPB_WIRE_TYPE_DELIMITED:
+ return upb_decode_delimitedfield(d, frame, field_start, field);
+ case UPB_WIRE_TYPE_START_GROUP:
+ CHK(field->type == UPB_DESCRIPTOR_TYPE_GROUP);
+ return upb_decode_submsg(d, frame, frame->limit, field, field_number);
+ case UPB_WIRE_TYPE_END_GROUP:
+ CHK(frame->group_number == field_number)
+ frame->limit = d->ptr;
+ return true;
+ default:
+ return false;
+ }
+ } else {
+ CHK(field_number != 0);
+ return upb_skip_unknownfielddata(d, frame, field_number, wire_type);
+ }
+}
+
+static bool upb_skip_unknowngroup(upb_decstate *d, int field_number,
+ const char *limit) {
+ upb_decframe frame;
+ frame.msg = NULL;
+ frame.m = NULL;
+ frame.group_number = field_number;
+ frame.limit = limit;
+
+ while (d->ptr < frame.limit) {
+ int wire_type;
+ int field_number;
+
+ CHK(upb_decode_tag(&d->ptr, frame.limit, &field_number, &wire_type));
+ CHK(upb_skip_unknownfielddata(d, &frame, field_number, wire_type));
+ }
+
+ return true;
+}
+
+static bool upb_decode_message(upb_decstate *d, const char *limit,
+ int group_number, char *msg,
+ const upb_msglayout_msginit_v1 *l) {
+ upb_decframe frame;
+ frame.group_number = group_number;
+ frame.limit = limit;
+ frame.msg = msg;
+ frame.m = l;
+
+ while (d->ptr < frame.limit) {
+ CHK(upb_decode_field(d, &frame));
+ }
+
+ return true;
+}
+
+bool upb_decode(upb_stringview buf, void *msg,
+ const upb_msglayout_msginit_v1 *l, upb_env *env) {
+ upb_decstate state;
+ state.ptr = buf.data;
+ state.env = env;
+
+ return upb_decode_message(&state, buf.data + buf.size, 0, msg, l);
+}
+
+#undef CHK
+
+
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
@@ -150,21 +700,6 @@ bool upb_def_setfullname(upb_def *def, const char *fullname, upb_status *s) {
const upb_filedef *upb_def_file(const upb_def *d) { return d->file; }
-upb_def *upb_def_dup(const upb_def *def, const void *o) {
- switch (def->type) {
- case UPB_DEF_MSG:
- return upb_msgdef_upcast_mutable(
- upb_msgdef_dup(upb_downcast_msgdef(def), o));
- case UPB_DEF_FIELD:
- return upb_fielddef_upcast_mutable(
- upb_fielddef_dup(upb_downcast_fielddef(def), o));
- case UPB_DEF_ENUM:
- return upb_enumdef_upcast_mutable(
- upb_enumdef_dup(upb_downcast_enumdef(def), o));
- default: UPB_ASSERT(false); return NULL;
- }
-}
-
static bool upb_def_init(upb_def *def, upb_deftype_t type,
const struct upb_refcounted_vtbl *vtbl,
const void *owner) {
@@ -311,6 +846,7 @@ static bool assign_msg_indices(upb_msgdef *m, upb_status *s) {
/* Sort fields. upb internally relies on UPB_TYPE_MESSAGE fields having the
* lowest indexes, but we do not publicly guarantee this. */
upb_msg_field_iter j;
+ upb_msg_oneof_iter k;
int i;
uint32_t selector;
int n = upb_msgdef_numfields(m);
@@ -369,6 +905,7 @@ static bool assign_msg_indices(upb_msgdef *m, upb_status *s) {
v = upb_value_bool(true);
upb_inttable_insert(&t, UPB_STARTMSG_SELECTOR, v);
upb_inttable_insert(&t, UPB_ENDMSG_SELECTOR, v);
+ upb_inttable_insert(&t, UPB_UNKNOWN_SELECTOR, v);
for(upb_msg_field_begin(&j, m);
!upb_msg_field_done(&j);
upb_msg_field_next(&j)) {
@@ -395,6 +932,13 @@ static bool assign_msg_indices(upb_msgdef *m, upb_status *s) {
#undef TRY
#endif
+ for(upb_msg_oneof_begin(&k, m), i = 0;
+ !upb_msg_oneof_done(&k);
+ upb_msg_oneof_next(&k), i++) {
+ upb_oneofdef *o = upb_msg_iter_oneof(&k);
+ o->index = i;
+ }
+
upb_gfree(fields);
return true;
}
@@ -413,13 +957,14 @@ bool _upb_def_validate(upb_def *const*defs, size_t n, upb_status *s) {
} else if (def->type == UPB_DEF_FIELD) {
upb_status_seterrmsg(s, "standalone fielddefs can not be frozen");
goto err;
- } else if (def->type == UPB_DEF_ENUM) {
- if (!upb_validate_enumdef(upb_dyncast_enumdef(def), s)) {
- goto err;
- }
} else {
/* Set now to detect transitive closure in the second pass. */
def->came_from_user = true;
+
+ if (def->type == UPB_DEF_ENUM &&
+ !upb_validate_enumdef(upb_dyncast_enumdef(def), s)) {
+ goto err;
+ }
}
}
@@ -512,21 +1057,6 @@ err2:
return NULL;
}
-upb_enumdef *upb_enumdef_dup(const upb_enumdef *e, const void *owner) {
- upb_enum_iter i;
- upb_enumdef *new_e = upb_enumdef_new(owner);
- if (!new_e) return NULL;
- for(upb_enum_begin(&i, e); !upb_enum_done(&i); upb_enum_next(&i)) {
- bool success = upb_enumdef_addval(
- new_e, upb_enum_iter_name(&i),upb_enum_iter_number(&i), NULL);
- if (!success) {
- upb_enumdef_unref(new_e, owner);
- return NULL;
- }
- }
- return new_e;
-}
-
bool upb_enumdef_freeze(upb_enumdef *e, upb_status *status) {
upb_def *d = upb_enumdef_upcast_mutable(e);
return upb_def_freeze(&d, 1, status);
@@ -761,42 +1291,6 @@ upb_fielddef *upb_fielddef_new(const void *o) {
return f;
}
-upb_fielddef *upb_fielddef_dup(const upb_fielddef *f, const void *owner) {
- const char *srcname;
- upb_fielddef *newf = upb_fielddef_new(owner);
- if (!newf) return NULL;
- upb_fielddef_settype(newf, upb_fielddef_type(f));
- upb_fielddef_setlabel(newf, upb_fielddef_label(f));
- upb_fielddef_setnumber(newf, upb_fielddef_number(f), NULL);
- upb_fielddef_setname(newf, upb_fielddef_name(f), NULL);
- if (f->default_is_string && f->defaultval.bytes) {
- str_t *s = f->defaultval.bytes;
- upb_fielddef_setdefaultstr(newf, s->str, s->len, NULL);
- } else {
- newf->default_is_string = f->default_is_string;
- newf->defaultval = f->defaultval;
- }
-
- if (f->subdef_is_symbolic) {
- srcname = f->sub.name; /* Might be NULL. */
- } else {
- srcname = f->sub.def ? upb_def_fullname(f->sub.def) : NULL;
- }
- if (srcname) {
- char *newname = upb_gmalloc(strlen(f->sub.def->fullname) + 2);
- if (!newname) {
- upb_fielddef_unref(newf, owner);
- return NULL;
- }
- strcpy(newname, ".");
- strcat(newname, f->sub.def->fullname);
- upb_fielddef_setsubdefname(newf, newname, NULL);
- upb_gfree(newname);
- }
-
- return newf;
-}
-
bool upb_fielddef_typeisset(const upb_fielddef *f) {
return f->type_is_set_;
}
@@ -1476,42 +1970,6 @@ err2:
return NULL;
}
-upb_msgdef *upb_msgdef_dup(const upb_msgdef *m, const void *owner) {
- bool ok;
- upb_msg_field_iter i;
- upb_msg_oneof_iter o;
-
- upb_msgdef *newm = upb_msgdef_new(owner);
- if (!newm) return NULL;
- ok = upb_def_setfullname(upb_msgdef_upcast_mutable(newm),
- upb_def_fullname(upb_msgdef_upcast(m)),
- NULL);
- newm->map_entry = m->map_entry;
- newm->syntax = m->syntax;
- UPB_ASSERT(ok);
- for(upb_msg_field_begin(&i, m);
- !upb_msg_field_done(&i);
- upb_msg_field_next(&i)) {
- upb_fielddef *f = upb_fielddef_dup(upb_msg_iter_field(&i), &f);
- /* Fields in oneofs are dup'd below. */
- if (upb_fielddef_containingoneof(f)) continue;
- if (!f || !upb_msgdef_addfield(newm, f, &f, NULL)) {
- upb_msgdef_unref(newm, owner);
- return NULL;
- }
- }
- for(upb_msg_oneof_begin(&o, m);
- !upb_msg_oneof_done(&o);
- upb_msg_oneof_next(&o)) {
- upb_oneofdef *f = upb_oneofdef_dup(upb_msg_iter_oneof(&o), &f);
- if (!f || !upb_msgdef_addoneof(newm, f, &f, NULL)) {
- upb_msgdef_unref(newm, owner);
- return NULL;
- }
- }
- return newm;
-}
-
bool upb_msgdef_freeze(upb_msgdef *m, upb_status *status) {
upb_def *d = upb_msgdef_upcast_mutable(m);
return upb_def_freeze(&d, 1, status);
@@ -1812,23 +2270,6 @@ err2:
return NULL;
}
-upb_oneofdef *upb_oneofdef_dup(const upb_oneofdef *o, const void *owner) {
- bool ok;
- upb_oneof_iter i;
- upb_oneofdef *newo = upb_oneofdef_new(owner);
- if (!newo) return NULL;
- ok = upb_oneofdef_setname(newo, upb_oneofdef_name(o), NULL);
- UPB_ASSERT(ok);
- for (upb_oneof_begin(&i, o); !upb_oneof_done(&i); upb_oneof_next(&i)) {
- upb_fielddef *f = upb_fielddef_dup(upb_oneof_iter_field(&i), &f);
- if (!f || !upb_oneofdef_addfield(newo, f, &f, NULL)) {
- upb_oneofdef_unref(newo, owner);
- return NULL;
- }
- }
- return newo;
-}
-
const char *upb_oneofdef_name(const upb_oneofdef *o) { return o->name; }
bool upb_oneofdef_setname(upb_oneofdef *o, const char *name, upb_status *s) {
@@ -1861,6 +2302,10 @@ int upb_oneofdef_numfields(const upb_oneofdef *o) {
return upb_strtable_count(&o->ntof);
}
+uint32_t upb_oneofdef_index(const upb_oneofdef *o) {
+ return o->index;
+}
+
bool upb_oneofdef_addfield(upb_oneofdef *o, upb_fielddef *f,
const void *ref_donor,
upb_status *s) {
@@ -1993,6 +2438,8 @@ static void freefiledef(upb_refcounted *r) {
upb_inttable_uninit(&f->deps);
upb_gfree((void*)f->name);
upb_gfree((void*)f->package);
+ upb_gfree((void*)f->phpprefix);
+ upb_gfree((void*)f->phpnamespace);
upb_gfree(f);
}
@@ -2007,6 +2454,8 @@ upb_filedef *upb_filedef_new(const void *owner) {
f->package = NULL;
f->name = NULL;
+ f->phpprefix = NULL;
+ f->phpnamespace = NULL;
f->syntax = UPB_SYNTAX_PROTO2;
if (!upb_refcounted_init(upb_filedef_upcast_mutable(f), &upb_filedef_vtbl,
@@ -2041,6 +2490,14 @@ const char *upb_filedef_package(const upb_filedef *f) {
return f->package;
}
+const char *upb_filedef_phpprefix(const upb_filedef *f) {
+ return f->phpprefix;
+}
+
+const char *upb_filedef_phpnamespace(const upb_filedef *f) {
+ return f->phpnamespace;
+}
+
upb_syntax_t upb_filedef_syntax(const upb_filedef *f) {
return f->syntax;
}
@@ -2097,6 +2554,30 @@ bool upb_filedef_setpackage(upb_filedef *f, const char *package,
return true;
}
+bool upb_filedef_setphpprefix(upb_filedef *f, const char *phpprefix,
+ upb_status *s) {
+ phpprefix = upb_gstrdup(phpprefix);
+ if (!phpprefix) {
+ upb_upberr_setoom(s);
+ return false;
+ }
+ upb_gfree((void*)f->phpprefix);
+ f->phpprefix = phpprefix;
+ return true;
+}
+
+bool upb_filedef_setphpnamespace(upb_filedef *f, const char *phpnamespace,
+ upb_status *s) {
+ phpnamespace = upb_gstrdup(phpnamespace);
+ if (!phpnamespace) {
+ upb_upberr_setoom(s);
+ return false;
+ }
+ upb_gfree((void*)f->phpnamespace);
+ f->phpnamespace = phpnamespace;
+ return true;
+}
+
bool upb_filedef_setsyntax(upb_filedef *f, upb_syntax_t syntax,
upb_status *s) {
UPB_UNUSED(s);
@@ -2156,6 +2637,699 @@ bool upb_filedef_adddep(upb_filedef *f, const upb_filedef *dep) {
return false;
}
}
+
+void upb_symtab_free(upb_symtab *s) {
+ upb_strtable_iter i;
+ upb_strtable_begin(&i, &s->symtab);
+ for (; !upb_strtable_done(&i); upb_strtable_next(&i)) {
+ const upb_def *def = upb_value_getptr(upb_strtable_iter_value(&i));
+ upb_def_unref(def, s);
+ }
+ upb_strtable_uninit(&s->symtab);
+ upb_gfree(s);
+}
+
+upb_symtab *upb_symtab_new() {
+ upb_symtab *s = upb_gmalloc(sizeof(*s));
+ if (!s) {
+ return NULL;
+ }
+
+ upb_strtable_init(&s->symtab, UPB_CTYPE_PTR);
+ return s;
+}
+
+const upb_def *upb_symtab_lookup(const upb_symtab *s, const char *sym) {
+ upb_value v;
+ upb_def *ret = upb_strtable_lookup(&s->symtab, sym, &v) ?
+ upb_value_getptr(v) : NULL;
+ return ret;
+}
+
+const upb_msgdef *upb_symtab_lookupmsg(const upb_symtab *s, const char *sym) {
+ upb_value v;
+ upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
+ upb_value_getptr(v) : NULL;
+ return def ? upb_dyncast_msgdef(def) : NULL;
+}
+
+const upb_enumdef *upb_symtab_lookupenum(const upb_symtab *s, const char *sym) {
+ upb_value v;
+ upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
+ upb_value_getptr(v) : NULL;
+ return def ? upb_dyncast_enumdef(def) : NULL;
+}
+
+/* Given a symbol and the base symbol inside which it is defined, find the
+ * symbol's definition in t. */
+static upb_def *upb_resolvename(const upb_strtable *t,
+ const char *base, const char *sym) {
+ if(strlen(sym) == 0) return NULL;
+ if(sym[0] == '.') {
+ /* Symbols starting with '.' are absolute, so we do a single lookup.
+ * Slice to omit the leading '.' */
+ upb_value v;
+ return upb_strtable_lookup(t, sym + 1, &v) ? upb_value_getptr(v) : NULL;
+ } else {
+ /* Remove components from base until we find an entry or run out.
+ * TODO: This branch is totally broken, but currently not used. */
+ (void)base;
+ UPB_ASSERT(false);
+ return NULL;
+ }
+}
+
+const upb_def *upb_symtab_resolve(const upb_symtab *s, const char *base,
+ const char *sym) {
+ upb_def *ret = upb_resolvename(&s->symtab, base, sym);
+ return ret;
+}
+
+/* TODO(haberman): we need a lot more testing of error conditions. */
+static bool symtab_add(upb_symtab *s, upb_def *const*defs, size_t n,
+ void *ref_donor, upb_refcounted *freeze_also,
+ upb_status *status) {
+ size_t i;
+ size_t add_n;
+ size_t freeze_n;
+ upb_strtable_iter iter;
+ upb_refcounted **add_objs = NULL;
+ upb_def **add_defs = NULL;
+ size_t add_objs_size;
+ upb_strtable addtab;
+
+ if (n == 0 && !freeze_also) {
+ return true;
+ }
+
+ if (!upb_strtable_init(&addtab, UPB_CTYPE_PTR)) {
+ upb_status_seterrmsg(status, "out of memory");
+ return false;
+ }
+
+ /* Add new defs to our "add" set. */
+ for (i = 0; i < n; i++) {
+ upb_def *def = defs[i];
+ const char *fullname;
+ upb_fielddef *f;
+
+ if (upb_def_isfrozen(def)) {
+ upb_status_seterrmsg(status, "added defs must be mutable");
+ goto err;
+ }
+ UPB_ASSERT(!upb_def_isfrozen(def));
+ fullname = upb_def_fullname(def);
+ if (!fullname) {
+ upb_status_seterrmsg(
+ status, "Anonymous defs cannot be added to a symtab");
+ goto err;
+ }
+
+ f = upb_dyncast_fielddef_mutable(def);
+
+ if (f) {
+ if (!upb_fielddef_containingtypename(f)) {
+ upb_status_seterrmsg(status,
+ "Standalone fielddefs must have a containing type "
+ "(extendee) name set");
+ goto err;
+ }
+ } else {
+ if (upb_strtable_lookup(&addtab, fullname, NULL)) {
+ upb_status_seterrf(status, "Conflicting defs named '%s'", fullname);
+ goto err;
+ }
+ if (upb_strtable_lookup(&s->symtab, fullname, NULL)) {
+ upb_status_seterrf(status, "Symtab already has a def named '%s'",
+ fullname);
+ goto err;
+ }
+ if (!upb_strtable_insert(&addtab, fullname, upb_value_ptr(def)))
+ goto oom_err;
+ upb_def_donateref(def, ref_donor, s);
+ }
+
+ if (upb_dyncast_fielddef_mutable(def)) {
+ /* TODO(haberman): allow adding extensions attached to files. */
+ upb_status_seterrf(status, "Can't add extensions to symtab.\n");
+ goto err;
+ }
+ }
+
+ /* Now using the table, resolve symbolic references for subdefs. */
+ upb_strtable_begin(&iter, &addtab);
+ for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
+ const char *base;
+ upb_def *def = upb_value_getptr(upb_strtable_iter_value(&iter));
+ upb_msgdef *m = upb_dyncast_msgdef_mutable(def);
+ upb_msg_field_iter j;
+
+ if (!m) continue;
+ /* Type names are resolved relative to the message in which they appear. */
+ base = upb_msgdef_fullname(m);
+
+ for(upb_msg_field_begin(&j, m);
+ !upb_msg_field_done(&j);
+ upb_msg_field_next(&j)) {
+ upb_fielddef *f = upb_msg_iter_field(&j);
+ const char *name = upb_fielddef_subdefname(f);
+ if (name && !upb_fielddef_subdef(f)) {
+ /* Try the lookup in the current set of to-be-added defs first. If not
+ * there, try existing defs. */
+ upb_def *subdef = upb_resolvename(&addtab, base, name);
+ if (subdef == NULL) {
+ subdef = upb_resolvename(&s->symtab, base, name);
+ }
+ if (subdef == NULL) {
+ upb_status_seterrf(
+ status, "couldn't resolve name '%s' in message '%s'", name, base);
+ goto err;
+ } else if (!upb_fielddef_setsubdef(f, subdef, status)) {
+ goto err;
+ }
+ }
+ }
+ }
+
+ /* We need an array of the defs in addtab, for passing to
+ * upb_refcounted_freeze(). */
+ add_objs_size = upb_strtable_count(&addtab);
+ if (freeze_also) {
+ add_objs_size++;
+ }
+
+ add_defs = upb_gmalloc(sizeof(void*) * add_objs_size);
+ if (add_defs == NULL) goto oom_err;
+ upb_strtable_begin(&iter, &addtab);
+ for (add_n = 0; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
+ add_defs[add_n++] = upb_value_getptr(upb_strtable_iter_value(&iter));
+ }
+
+ /* Validate defs. */
+ if (!_upb_def_validate(add_defs, add_n, status)) {
+ goto err;
+ }
+
+ /* Cheat a little and give the array a new type.
+ * This is probably undefined behavior, but this code will be deleted soon. */
+ add_objs = (upb_refcounted**)add_defs;
+
+ freeze_n = add_n;
+ if (freeze_also) {
+ add_objs[freeze_n++] = freeze_also;
+ }
+
+ if (!upb_refcounted_freeze(add_objs, freeze_n, status,
+ UPB_MAX_MESSAGE_DEPTH * 2)) {
+ goto err;
+ }
+
+ /* This must be delayed until all errors have been detected, since error
+ * recovery code uses this table to cleanup defs. */
+ upb_strtable_uninit(&addtab);
+
+ /* TODO(haberman) we don't properly handle errors after this point (like
+ * OOM in upb_strtable_insert() below). */
+ for (i = 0; i < add_n; i++) {
+ upb_def *def = (upb_def*)add_objs[i];
+ const char *name = upb_def_fullname(def);
+ bool success;
+ success = upb_strtable_insert(&s->symtab, name, upb_value_ptr(def));
+ UPB_ASSERT(success);
+ }
+ upb_gfree(add_defs);
+ return true;
+
+oom_err:
+ upb_status_seterrmsg(status, "out of memory");
+err: {
+ /* We need to donate the refs back. */
+ upb_strtable_begin(&iter, &addtab);
+ for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
+ upb_def *def = upb_value_getptr(upb_strtable_iter_value(&iter));
+ upb_def_donateref(def, s, ref_donor);
+ }
+ }
+ upb_strtable_uninit(&addtab);
+ upb_gfree(add_defs);
+ UPB_ASSERT(!upb_ok(status));
+ return false;
+}
+
+bool upb_symtab_add(upb_symtab *s, upb_def *const*defs, size_t n,
+ void *ref_donor, upb_status *status) {
+ return symtab_add(s, defs, n, ref_donor, NULL, status);
+}
+
+bool upb_symtab_addfile(upb_symtab *s, upb_filedef *file, upb_status *status) {
+ size_t n;
+ size_t i;
+ upb_def **defs;
+ bool ret;
+
+ n = upb_filedef_defcount(file);
+ if (n == 0) {
+ return true;
+ }
+ defs = upb_gmalloc(sizeof(*defs) * n);
+
+ if (defs == NULL) {
+ upb_status_seterrmsg(status, "Out of memory");
+ return false;
+ }
+
+ for (i = 0; i < n; i++) {
+ defs[i] = upb_filedef_mutabledef(file, i);
+ }
+
+ ret = symtab_add(s, defs, n, NULL, upb_filedef_upcast_mutable(file), status);
+
+ upb_gfree(defs);
+ return ret;
+}
+
+/* Iteration. */
+
+static void advance_to_matching(upb_symtab_iter *iter) {
+ if (iter->type == UPB_DEF_ANY)
+ return;
+
+ while (!upb_strtable_done(&iter->iter) &&
+ iter->type != upb_symtab_iter_def(iter)->type) {
+ upb_strtable_next(&iter->iter);
+ }
+}
+
+void upb_symtab_begin(upb_symtab_iter *iter, const upb_symtab *s,
+ upb_deftype_t type) {
+ upb_strtable_begin(&iter->iter, &s->symtab);
+ iter->type = type;
+ advance_to_matching(iter);
+}
+
+void upb_symtab_next(upb_symtab_iter *iter) {
+ upb_strtable_next(&iter->iter);
+ advance_to_matching(iter);
+}
+
+bool upb_symtab_done(const upb_symtab_iter *iter) {
+ return upb_strtable_done(&iter->iter);
+}
+
+const upb_def *upb_symtab_iter_def(const upb_symtab_iter *iter) {
+ return upb_value_getptr(upb_strtable_iter_value(&iter->iter));
+}
+/* We encode backwards, to avoid pre-computing lengths (one-pass encode). */
+
+
+#define UPB_PB_VARINT_MAX_LEN 10
+#define CHK(x) do { if (!(x)) { return false; } } while(0)
+
+/* Maps descriptor type -> upb field type. */
+static const uint8_t upb_desctype_to_fieldtype2[] = {
+ UPB_WIRE_TYPE_END_GROUP, /* ENDGROUP */
+ UPB_TYPE_DOUBLE, /* DOUBLE */
+ UPB_TYPE_FLOAT, /* FLOAT */
+ UPB_TYPE_INT64, /* INT64 */
+ UPB_TYPE_UINT64, /* UINT64 */
+ UPB_TYPE_INT32, /* INT32 */
+ UPB_TYPE_UINT64, /* FIXED64 */
+ UPB_TYPE_UINT32, /* FIXED32 */
+ UPB_TYPE_BOOL, /* BOOL */
+ UPB_TYPE_STRING, /* STRING */
+ UPB_TYPE_MESSAGE, /* GROUP */
+ UPB_TYPE_MESSAGE, /* MESSAGE */
+ UPB_TYPE_BYTES, /* BYTES */
+ UPB_TYPE_UINT32, /* UINT32 */
+ UPB_TYPE_ENUM, /* ENUM */
+ UPB_TYPE_INT32, /* SFIXED32 */
+ UPB_TYPE_INT64, /* SFIXED64 */
+ UPB_TYPE_INT32, /* SINT32 */
+ UPB_TYPE_INT64, /* SINT64 */
+};
+
+static size_t upb_encode_varint(uint64_t val, char *buf) {
+ size_t i;
+ if (val < 128) { buf[0] = val; return 1; }
+ i = 0;
+ while (val) {
+ uint8_t byte = val & 0x7fU;
+ val >>= 7;
+ if (val) byte |= 0x80U;
+ buf[i++] = byte;
+ }
+ return i;
+}
+
+static uint32_t upb_zzencode_32(int32_t n) { return (n << 1) ^ (n >> 31); }
+static uint64_t upb_zzencode_64(int64_t n) { return (n << 1) ^ (n >> 63); }
+
+typedef struct {
+ upb_env *env;
+ char *buf, *ptr, *limit;
+} upb_encstate;
+
+static size_t upb_roundup_pow2(size_t bytes) {
+ size_t ret = 128;
+ while (ret < bytes) {
+ ret *= 2;
+ }
+ return ret;
+}
+
+static bool upb_encode_growbuffer(upb_encstate *e, size_t bytes) {
+ size_t old_size = e->limit - e->buf;
+ size_t new_size = upb_roundup_pow2(bytes + (e->limit - e->ptr));
+ char *new_buf = upb_env_realloc(e->env, e->buf, old_size, new_size);
+ CHK(new_buf);
+
+ /* We want previous data at the end, realloc() put it at the beginning. */
+ memmove(e->limit - old_size, e->buf, old_size);
+
+ e->ptr = new_buf + new_size - (e->limit - e->ptr);
+ e->limit = new_buf + new_size;
+ e->buf = new_buf;
+ return true;
+}
+
+/* Call to ensure that at least "bytes" bytes are available for writing at
+ * e->ptr. Returns false if the bytes could not be allocated. */
+static bool upb_encode_reserve(upb_encstate *e, size_t bytes) {
+ CHK(UPB_LIKELY((size_t)(e->ptr - e->buf) >= bytes) ||
+ upb_encode_growbuffer(e, bytes));
+
+ e->ptr -= bytes;
+ return true;
+}
+
+/* Writes the given bytes to the buffer, handling reserve/advance. */
+static bool upb_put_bytes(upb_encstate *e, const void *data, size_t len) {
+ CHK(upb_encode_reserve(e, len));
+ memcpy(e->ptr, data, len);
+ return true;
+}
+
+static bool upb_put_fixed64(upb_encstate *e, uint64_t val) {
+ /* TODO(haberman): byte-swap for big endian. */
+ return upb_put_bytes(e, &val, sizeof(uint64_t));
+}
+
+static bool upb_put_fixed32(upb_encstate *e, uint32_t val) {
+ /* TODO(haberman): byte-swap for big endian. */
+ return upb_put_bytes(e, &val, sizeof(uint32_t));
+}
+
+static bool upb_put_varint(upb_encstate *e, uint64_t val) {
+ size_t len;
+ char *start;
+ CHK(upb_encode_reserve(e, UPB_PB_VARINT_MAX_LEN));
+ len = upb_encode_varint(val, e->ptr);
+ start = e->ptr + UPB_PB_VARINT_MAX_LEN - len;
+ memmove(start, e->ptr, len);
+ e->ptr = start;
+ return true;
+}
+
+static bool upb_put_double(upb_encstate *e, double d) {
+ uint64_t u64;
+ UPB_ASSERT(sizeof(double) == sizeof(uint64_t));
+ memcpy(&u64, &d, sizeof(uint64_t));
+ return upb_put_fixed64(e, u64);
+}
+
+static bool upb_put_float(upb_encstate *e, float d) {
+ uint32_t u32;
+ UPB_ASSERT(sizeof(float) == sizeof(uint32_t));
+ memcpy(&u32, &d, sizeof(uint32_t));
+ return upb_put_fixed32(e, u32);
+}
+
+static uint32_t upb_readcase(const char *msg, const upb_msglayout_msginit_v1 *m,
+ int oneof_index) {
+ uint32_t ret;
+ memcpy(&ret, msg + m->oneofs[oneof_index].case_offset, sizeof(ret));
+ return ret;
+}
+
+static bool upb_readhasbit(const char *msg,
+ const upb_msglayout_fieldinit_v1 *f) {
+ UPB_ASSERT(f->hasbit != UPB_NO_HASBIT);
+ return msg[f->hasbit / 8] & (1 << (f->hasbit % 8));
+}
+
+static bool upb_put_tag(upb_encstate *e, int field_number, int wire_type) {
+ return upb_put_varint(e, (field_number << 3) | wire_type);
+}
+
+static bool upb_put_fixedarray(upb_encstate *e, const upb_array *arr,
+ size_t size) {
+ size_t bytes = arr->len * size;
+ return upb_put_bytes(e, arr->data, bytes) && upb_put_varint(e, bytes);
+}
+
+bool upb_encode_message(upb_encstate *e, const char *msg,
+ const upb_msglayout_msginit_v1 *m,
+ size_t *size);
+
+static bool upb_encode_array(upb_encstate *e, const char *field_mem,
+ const upb_msglayout_msginit_v1 *m,
+ const upb_msglayout_fieldinit_v1 *f) {
+ const upb_array *arr = *(const upb_array**)field_mem;
+
+ if (arr == NULL || arr->len == 0) {
+ return true;
+ }
+
+ UPB_ASSERT(arr->type == upb_desctype_to_fieldtype2[f->type]);
+
+#define VARINT_CASE(ctype, encode) { \
+ ctype *start = arr->data; \
+ ctype *ptr = start + arr->len; \
+ size_t pre_len = e->limit - e->ptr; \
+ do { \
+ ptr--; \
+ CHK(upb_put_varint(e, encode)); \
+ } while (ptr != start); \
+ CHK(upb_put_varint(e, e->limit - e->ptr - pre_len)); \
+} \
+break; \
+do { ; } while(0)
+
+ switch (f->type) {
+ case UPB_DESCRIPTOR_TYPE_DOUBLE:
+ CHK(upb_put_fixedarray(e, arr, sizeof(double)));
+ break;
+ case UPB_DESCRIPTOR_TYPE_FLOAT:
+ CHK(upb_put_fixedarray(e, arr, sizeof(float)));
+ break;
+ case UPB_DESCRIPTOR_TYPE_SFIXED64:
+ case UPB_DESCRIPTOR_TYPE_FIXED64:
+ CHK(upb_put_fixedarray(e, arr, sizeof(uint64_t)));
+ break;
+ case UPB_DESCRIPTOR_TYPE_FIXED32:
+ case UPB_DESCRIPTOR_TYPE_SFIXED32:
+ CHK(upb_put_fixedarray(e, arr, sizeof(uint32_t)));
+ break;
+ case UPB_DESCRIPTOR_TYPE_INT64:
+ case UPB_DESCRIPTOR_TYPE_UINT64:
+ VARINT_CASE(uint64_t, *ptr);
+ case UPB_DESCRIPTOR_TYPE_UINT32:
+ case UPB_DESCRIPTOR_TYPE_INT32:
+ case UPB_DESCRIPTOR_TYPE_ENUM:
+ VARINT_CASE(uint32_t, *ptr);
+ case UPB_DESCRIPTOR_TYPE_BOOL:
+ VARINT_CASE(bool, *ptr);
+ case UPB_DESCRIPTOR_TYPE_SINT32:
+ VARINT_CASE(int32_t, upb_zzencode_32(*ptr));
+ case UPB_DESCRIPTOR_TYPE_SINT64:
+ VARINT_CASE(int64_t, upb_zzencode_64(*ptr));
+ case UPB_DESCRIPTOR_TYPE_STRING:
+ case UPB_DESCRIPTOR_TYPE_BYTES: {
+ upb_stringview *start = arr->data;
+ upb_stringview *ptr = start + arr->len;
+ do {
+ ptr--;
+ CHK(upb_put_bytes(e, ptr->data, ptr->size) &&
+ upb_put_varint(e, ptr->size) &&
+ upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
+ } while (ptr != start);
+ return true;
+ }
+ case UPB_DESCRIPTOR_TYPE_GROUP: {
+ void **start = arr->data;
+ void **ptr = start + arr->len;
+ const upb_msglayout_msginit_v1 *subm = m->submsgs[f->submsg_index];
+ do {
+ size_t size;
+ ptr--;
+ CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_END_GROUP) &&
+ upb_encode_message(e, *ptr, subm, &size) &&
+ upb_put_tag(e, f->number, UPB_WIRE_TYPE_START_GROUP));
+ } while (ptr != start);
+ return true;
+ }
+ case UPB_DESCRIPTOR_TYPE_MESSAGE: {
+ void **start = arr->data;
+ void **ptr = start + arr->len;
+ const upb_msglayout_msginit_v1 *subm = m->submsgs[f->submsg_index];
+ do {
+ size_t size;
+ ptr--;
+ CHK(upb_encode_message(e, *ptr, subm, &size) &&
+ upb_put_varint(e, size) &&
+ upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
+ } while (ptr != start);
+ return true;
+ }
+ }
+#undef VARINT_CASE
+
+ /* We encode all primitive arrays as packed, regardless of what was specified
+ * in the .proto file. Could special case 1-sized arrays. */
+ CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
+ return true;
+}
+
+static bool upb_encode_scalarfield(upb_encstate *e, const char *field_mem,
+ const upb_msglayout_msginit_v1 *m,
+ const upb_msglayout_fieldinit_v1 *f,
+ bool is_proto3) {
+ bool skip_zero_value = is_proto3 && f->oneof_index == UPB_NOT_IN_ONEOF;
+
+#define CASE(ctype, type, wire_type, encodeval) do { \
+ ctype val = *(ctype*)field_mem; \
+ if (skip_zero_value && val == 0) { \
+ return true; \
+ } \
+ return upb_put_ ## type(e, encodeval) && \
+ upb_put_tag(e, f->number, wire_type); \
+} while(0)
+
+ switch (f->type) {
+ case UPB_DESCRIPTOR_TYPE_DOUBLE:
+ CASE(double, double, UPB_WIRE_TYPE_64BIT, val);
+ case UPB_DESCRIPTOR_TYPE_FLOAT:
+ CASE(float, float, UPB_WIRE_TYPE_32BIT, val);
+ case UPB_DESCRIPTOR_TYPE_INT64:
+ case UPB_DESCRIPTOR_TYPE_UINT64:
+ CASE(uint64_t, varint, UPB_WIRE_TYPE_VARINT, val);
+ case UPB_DESCRIPTOR_TYPE_UINT32:
+ case UPB_DESCRIPTOR_TYPE_INT32:
+ case UPB_DESCRIPTOR_TYPE_ENUM:
+ CASE(uint32_t, varint, UPB_WIRE_TYPE_VARINT, val);
+ case UPB_DESCRIPTOR_TYPE_SFIXED64:
+ case UPB_DESCRIPTOR_TYPE_FIXED64:
+ CASE(uint64_t, fixed64, UPB_WIRE_TYPE_64BIT, val);
+ case UPB_DESCRIPTOR_TYPE_FIXED32:
+ case UPB_DESCRIPTOR_TYPE_SFIXED32:
+ CASE(uint32_t, fixed32, UPB_WIRE_TYPE_32BIT, val);
+ case UPB_DESCRIPTOR_TYPE_BOOL:
+ CASE(bool, varint, UPB_WIRE_TYPE_VARINT, val);
+ case UPB_DESCRIPTOR_TYPE_SINT32:
+ CASE(int32_t, varint, UPB_WIRE_TYPE_VARINT, upb_zzencode_32(val));
+ case UPB_DESCRIPTOR_TYPE_SINT64:
+ CASE(int64_t, varint, UPB_WIRE_TYPE_VARINT, upb_zzencode_64(val));
+ case UPB_DESCRIPTOR_TYPE_STRING:
+ case UPB_DESCRIPTOR_TYPE_BYTES: {
+ upb_stringview view = *(upb_stringview*)field_mem;
+ if (skip_zero_value && view.size == 0) {
+ return true;
+ }
+ return upb_put_bytes(e, view.data, view.size) &&
+ upb_put_varint(e, view.size) &&
+ upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED);
+ }
+ case UPB_DESCRIPTOR_TYPE_GROUP: {
+ size_t size;
+ void *submsg = *(void**)field_mem;
+ const upb_msglayout_msginit_v1 *subm = m->submsgs[f->submsg_index];
+ if (skip_zero_value && submsg == NULL) {
+ return true;
+ }
+ return upb_put_tag(e, f->number, UPB_WIRE_TYPE_END_GROUP) &&
+ upb_encode_message(e, submsg, subm, &size) &&
+ upb_put_tag(e, f->number, UPB_WIRE_TYPE_START_GROUP);
+ }
+ case UPB_DESCRIPTOR_TYPE_MESSAGE: {
+ size_t size;
+ void *submsg = *(void**)field_mem;
+ const upb_msglayout_msginit_v1 *subm = m->submsgs[f->submsg_index];
+ if (skip_zero_value && submsg == NULL) {
+ return true;
+ }
+ return upb_encode_message(e, submsg, subm, &size) &&
+ upb_put_varint(e, size) &&
+ upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED);
+ }
+ }
+#undef CASE
+ UPB_UNREACHABLE();
+}
+
+bool upb_encode_hasscalarfield(const char *msg,
+ const upb_msglayout_msginit_v1 *m,
+ const upb_msglayout_fieldinit_v1 *f) {
+ if (f->oneof_index != UPB_NOT_IN_ONEOF) {
+ return upb_readcase(msg, m, f->oneof_index) == f->number;
+ } else if (m->is_proto2) {
+ return upb_readhasbit(msg, f);
+ } else {
+ /* For proto3, we'll test for the field being empty later. */
+ return true;
+ }
+}
+
+bool upb_encode_message(upb_encstate* e, const char *msg,
+ const upb_msglayout_msginit_v1 *m,
+ size_t *size) {
+ int i;
+ char *buf_end = e->ptr;
+
+ if (msg == NULL) {
+ return true;
+ }
+
+ for (i = m->field_count - 1; i >= 0; i--) {
+ const upb_msglayout_fieldinit_v1 *f = &m->fields[i];
+
+ if (f->label == UPB_LABEL_REPEATED) {
+ CHK(upb_encode_array(e, msg + f->offset, m, f));
+ } else {
+ if (upb_encode_hasscalarfield(msg, m, f)) {
+ CHK(upb_encode_scalarfield(e, msg + f->offset, m, f, !m->is_proto2));
+ }
+ }
+ }
+
+ *size = buf_end - e->ptr;
+ return true;
+}
+
+char *upb_encode(const void *msg, const upb_msglayout_msginit_v1 *m,
+ upb_env *env, size_t *size) {
+ upb_encstate e;
+ e.env = env;
+ e.buf = NULL;
+ e.limit = NULL;
+ e.ptr = NULL;
+
+ if (!upb_encode_message(&e, msg, m, size)) {
+ *size = 0;
+ return NULL;
+ }
+
+ *size = e.limit - e.ptr;
+
+ if (*size == 0) {
+ static char ch;
+ return &ch;
+ } else {
+ UPB_ASSERT(e.ptr);
+ return e.ptr;
+ }
+}
+
+#undef CHK
/*
** TODO(haberman): it's unclear whether a lot of the consistency checks should
** UPB_ASSERT() or return false.
@@ -2527,6 +3701,12 @@ SETTER(endseq, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSEQ)
#undef SETTER
+bool upb_handlers_setunknown(upb_handlers *h, upb_unknown_handlerfunc *func,
+ upb_handlerattr *attr) {
+ return doset(h, UPB_UNKNOWN_SELECTOR, NULL, UPB_HANDLER_INT32,
+ (upb_func *)func, attr);
+}
+
bool upb_handlers_setstartmsg(upb_handlers *h, upb_startmsg_handlerfunc *func,
upb_handlerattr *attr) {
return doset(h, UPB_STARTMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
@@ -2851,6 +4031,1191 @@ bool upb_byteshandler_setendstr(upb_byteshandler *h,
h->table[UPB_ENDSTR_SELECTOR].attr.handler_data_ = d;
return true;
}
+
+
+static bool is_power_of_two(size_t val) {
+ return (val & (val - 1)) == 0;
+}
+
+/* Align up to the given power of 2. */
+static size_t align_up(size_t val, size_t align) {
+ UPB_ASSERT(is_power_of_two(align));
+ return (val + align - 1) & ~(align - 1);
+}
+
+static size_t div_round_up(size_t n, size_t d) {
+ return (n + d - 1) / d;
+}
+
+bool upb_fieldtype_mapkeyok(upb_fieldtype_t type) {
+ return type == UPB_TYPE_BOOL || type == UPB_TYPE_INT32 ||
+ type == UPB_TYPE_UINT32 || type == UPB_TYPE_INT64 ||
+ type == UPB_TYPE_UINT64 || type == UPB_TYPE_STRING;
+}
+
+void *upb_array_pack(const upb_array *arr, void *p, size_t *ofs, size_t size);
+void *upb_map_pack(const upb_map *map, void *p, size_t *ofs, size_t size);
+
+#define PTR_AT(msg, ofs, type) (type*)((char*)msg + ofs)
+#define VOIDPTR_AT(msg, ofs) PTR_AT(msg, ofs, void)
+#define ENCODE_MAX_NESTING 64
+#define CHECK_TRUE(x) if (!(x)) { return false; }
+
+/** upb_msgval ****************************************************************/
+
+#define upb_alignof(t) offsetof(struct { char c; t x; }, x)
+
+/* These functions will generate real memcpy() calls on ARM sadly, because
+ * the compiler assumes they might not be aligned. */
+
+static upb_msgval upb_msgval_read(const void *p, size_t ofs,
+ uint8_t size) {
+ upb_msgval val;
+ p = (char*)p + ofs;
+ memcpy(&val, p, size);
+ return val;
+}
+
+static void upb_msgval_write(void *p, size_t ofs, upb_msgval val,
+ uint8_t size) {
+ p = (char*)p + ofs;
+ memcpy(p, &val, size);
+}
+
+static size_t upb_msgval_sizeof(upb_fieldtype_t type) {
+ switch (type) {
+ case UPB_TYPE_DOUBLE:
+ case UPB_TYPE_INT64:
+ case UPB_TYPE_UINT64:
+ return 8;
+ case UPB_TYPE_ENUM:
+ case UPB_TYPE_INT32:
+ case UPB_TYPE_UINT32:
+ case UPB_TYPE_FLOAT:
+ return 4;
+ case UPB_TYPE_BOOL:
+ return 1;
+ case UPB_TYPE_BYTES:
+ case UPB_TYPE_MESSAGE:
+ return sizeof(void*);
+ case UPB_TYPE_STRING:
+ return sizeof(upb_stringview);
+ }
+ UPB_UNREACHABLE();
+}
+
+static uint8_t upb_msg_fieldsize(const upb_msglayout_fieldinit_v1 *field) {
+ if (field->label == UPB_LABEL_REPEATED) {
+ return sizeof(void*);
+ } else {
+ return upb_msgval_sizeof(field->type);
+ }
+}
+
+static uint8_t upb_msg_fielddefsize(const upb_fielddef *f) {
+ if (upb_fielddef_isseq(f)) {
+ return sizeof(void*);
+ } else {
+ return upb_msgval_sizeof(upb_fielddef_type(f));
+ }
+}
+
+/* TODO(haberman): this is broken right now because upb_msgval can contain
+ * a char* / size_t pair, which is too big for a upb_value. To fix this
+ * we'll probably need to dynamically allocate a upb_msgval and store a
+ * pointer to that in the tables for extensions/maps. */
+static upb_value upb_toval(upb_msgval val) {
+ upb_value ret;
+ UPB_UNUSED(val);
+ memset(&ret, 0, sizeof(upb_value)); /* XXX */
+ return ret;
+}
+
+static upb_msgval upb_msgval_fromval(upb_value val) {
+ upb_msgval ret;
+ UPB_UNUSED(val);
+ memset(&ret, 0, sizeof(upb_msgval)); /* XXX */
+ return ret;
+}
+
+static upb_ctype_t upb_fieldtotabtype(upb_fieldtype_t type) {
+ switch (type) {
+ case UPB_TYPE_FLOAT: return UPB_CTYPE_FLOAT;
+ case UPB_TYPE_DOUBLE: return UPB_CTYPE_DOUBLE;
+ case UPB_TYPE_BOOL: return UPB_CTYPE_BOOL;
+ case UPB_TYPE_BYTES:
+ case UPB_TYPE_MESSAGE:
+ case UPB_TYPE_STRING: return UPB_CTYPE_CONSTPTR;
+ case UPB_TYPE_ENUM:
+ case UPB_TYPE_INT32: return UPB_CTYPE_INT32;
+ case UPB_TYPE_UINT32: return UPB_CTYPE_UINT32;
+ case UPB_TYPE_INT64: return UPB_CTYPE_INT64;
+ case UPB_TYPE_UINT64: return UPB_CTYPE_UINT64;
+ default: UPB_ASSERT(false); return 0;
+ }
+}
+
+static upb_msgval upb_msgval_fromdefault(const upb_fielddef *f) {
+ switch (upb_fielddef_type(f)) {
+ case UPB_TYPE_FLOAT:
+ return upb_msgval_float(upb_fielddef_defaultfloat(f));
+ case UPB_TYPE_DOUBLE:
+ return upb_msgval_double(upb_fielddef_defaultdouble(f));
+ case UPB_TYPE_BOOL:
+ return upb_msgval_bool(upb_fielddef_defaultbool(f));
+ case UPB_TYPE_STRING:
+ case UPB_TYPE_BYTES: {
+ size_t len;
+ const char *ptr = upb_fielddef_defaultstr(f, &len);
+ return upb_msgval_makestr(ptr, len);
+ }
+ case UPB_TYPE_MESSAGE:
+ return upb_msgval_msg(NULL);
+ case UPB_TYPE_ENUM:
+ case UPB_TYPE_INT32:
+ return upb_msgval_int32(upb_fielddef_defaultint32(f));
+ case UPB_TYPE_UINT32:
+ return upb_msgval_uint32(upb_fielddef_defaultuint32(f));
+ case UPB_TYPE_INT64:
+ return upb_msgval_int64(upb_fielddef_defaultint64(f));
+ case UPB_TYPE_UINT64:
+ return upb_msgval_uint64(upb_fielddef_defaultuint64(f));
+ default:
+ UPB_ASSERT(false);
+ return upb_msgval_msg(NULL);
+ }
+}
+
+
+/** upb_msglayout *************************************************************/
+
+struct upb_msglayout {
+ struct upb_msglayout_msginit_v1 data;
+};
+
+static void upb_msglayout_free(upb_msglayout *l) {
+ upb_gfree(l->data.default_msg);
+ upb_gfree(l);
+}
+
+static size_t upb_msglayout_place(upb_msglayout *l, size_t size) {
+ size_t ret;
+
+ l->data.size = align_up(l->data.size, size);
+ ret = l->data.size;
+ l->data.size += size;
+ return ret;
+}
+
+static uint32_t upb_msglayout_offset(const upb_msglayout *l,
+ const upb_fielddef *f) {
+ return l->data.fields[upb_fielddef_index(f)].offset;
+}
+
+static uint32_t upb_msglayout_hasbit(const upb_msglayout *l,
+ const upb_fielddef *f) {
+ return l->data.fields[upb_fielddef_index(f)].hasbit;
+}
+
+static bool upb_msglayout_initdefault(upb_msglayout *l, const upb_msgdef *m) {
+ upb_msg_field_iter it;
+
+ if (upb_msgdef_syntax(m) == UPB_SYNTAX_PROTO2 && l->data.size) {
+ /* Allocate default message and set default values in it. */
+ l->data.default_msg = upb_gmalloc(l->data.size);
+ if (!l->data.default_msg) {
+ return false;
+ }
+
+ memset(l->data.default_msg, 0, l->data.size);
+
+ for (upb_msg_field_begin(&it, m); !upb_msg_field_done(&it);
+ upb_msg_field_next(&it)) {
+ const upb_fielddef* f = upb_msg_iter_field(&it);
+
+ if (upb_fielddef_containingoneof(f)) {
+ continue;
+ }
+
+ /* TODO(haberman): handle strings. */
+ if (!upb_fielddef_isstring(f) &&
+ !upb_fielddef_issubmsg(f) &&
+ !upb_fielddef_isseq(f)) {
+ upb_msg_set(l->data.default_msg,
+ upb_fielddef_index(f),
+ upb_msgval_fromdefault(f),
+ l);
+ }
+ }
+ }
+
+ return true;
+}
+
+static upb_msglayout *upb_msglayout_new(const upb_msgdef *m) {
+ upb_msg_field_iter it;
+ upb_msg_oneof_iter oit;
+ upb_msglayout *l;
+ size_t hasbit;
+ size_t submsg_count = 0;
+ const upb_msglayout_msginit_v1 **submsgs;
+ upb_msglayout_fieldinit_v1 *fields;
+ upb_msglayout_oneofinit_v1 *oneofs;
+
+ for (upb_msg_field_begin(&it, m);
+ !upb_msg_field_done(&it);
+ upb_msg_field_next(&it)) {
+ const upb_fielddef* f = upb_msg_iter_field(&it);
+ if (upb_fielddef_issubmsg(f)) {
+ submsg_count++;
+ }
+ }
+
+ l = upb_gmalloc(sizeof(*l));
+ if (!l) return NULL;
+
+ memset(l, 0, sizeof(*l));
+
+ fields = upb_gmalloc(upb_msgdef_numfields(m) * sizeof(*fields));
+ submsgs = upb_gmalloc(submsg_count * sizeof(*submsgs));
+ oneofs = upb_gmalloc(upb_msgdef_numoneofs(m) * sizeof(*oneofs));
+
+ if ((!fields && upb_msgdef_numfields(m)) ||
+ (!submsgs && submsg_count) ||
+ (!oneofs && upb_msgdef_numoneofs(m))) {
+ /* OOM. */
+ upb_gfree(l);
+ upb_gfree(fields);
+ upb_gfree(submsgs);
+ upb_gfree(oneofs);
+ return NULL;
+ }
+
+ l->data.field_count = upb_msgdef_numfields(m);
+ l->data.oneof_count = upb_msgdef_numoneofs(m);
+ l->data.fields = fields;
+ l->data.submsgs = submsgs;
+ l->data.oneofs = oneofs;
+ l->data.is_proto2 = (upb_msgdef_syntax(m) == UPB_SYNTAX_PROTO2);
+
+ /* Allocate data offsets in three stages:
+ *
+ * 1. hasbits.
+ * 2. regular fields.
+ * 3. oneof fields.
+ *
+ * OPT: There is a lot of room for optimization here to minimize the size.
+ */
+
+ /* Allocate hasbits and set basic field attributes. */
+ for (upb_msg_field_begin(&it, m), hasbit = 0;
+ !upb_msg_field_done(&it);
+ upb_msg_field_next(&it)) {
+ const upb_fielddef* f = upb_msg_iter_field(&it);
+ upb_msglayout_fieldinit_v1 *field = &fields[upb_fielddef_index(f)];
+
+ field->number = upb_fielddef_number(f);
+ field->type = upb_fielddef_type(f);
+ field->label = upb_fielddef_label(f);
+
+ if (upb_fielddef_containingoneof(f)) {
+ field->oneof_index = upb_oneofdef_index(upb_fielddef_containingoneof(f));
+ } else {
+ field->oneof_index = UPB_NOT_IN_ONEOF;
+ }
+
+ if (upb_fielddef_haspresence(f) && !upb_fielddef_containingoneof(f)) {
+ field->hasbit = hasbit++;
+ }
+ }
+
+ /* Account for space used by hasbits. */
+ l->data.size = div_round_up(hasbit, 8);
+
+ /* Allocate non-oneof fields. */
+ for (upb_msg_field_begin(&it, m); !upb_msg_field_done(&it);
+ upb_msg_field_next(&it)) {
+ const upb_fielddef* f = upb_msg_iter_field(&it);
+ size_t field_size = upb_msg_fielddefsize(f);
+ size_t index = upb_fielddef_index(f);
+
+ if (upb_fielddef_containingoneof(f)) {
+ /* Oneofs are handled separately below. */
+ continue;
+ }
+
+ fields[index].offset = upb_msglayout_place(l, field_size);
+ }
+
+ /* Allocate oneof fields. Each oneof field consists of a uint32 for the case
+ * and space for the actual data. */
+ for (upb_msg_oneof_begin(&oit, m); !upb_msg_oneof_done(&oit);
+ upb_msg_oneof_next(&oit)) {
+ const upb_oneofdef* o = upb_msg_iter_oneof(&oit);
+ upb_oneof_iter fit;
+
+ size_t case_size = sizeof(uint32_t); /* Could potentially optimize this. */
+ upb_msglayout_oneofinit_v1 *oneof = &oneofs[upb_oneofdef_index(o)];
+ size_t field_size = 0;
+
+ /* Calculate field size: the max of all field sizes. */
+ for (upb_oneof_begin(&fit, o);
+ !upb_oneof_done(&fit);
+ upb_oneof_next(&fit)) {
+ const upb_fielddef* f = upb_oneof_iter_field(&fit);
+ field_size = UPB_MAX(field_size, upb_msg_fielddefsize(f));
+ }
+
+ /* Align and allocate case offset. */
+ oneof->case_offset = upb_msglayout_place(l, case_size);
+ oneof->data_offset = upb_msglayout_place(l, field_size);
+ }
+
+ /* Size of the entire structure should be a multiple of its greatest
+ * alignment. TODO: track overall alignment for real? */
+ l->data.size = align_up(l->data.size, 8);
+
+ if (upb_msglayout_initdefault(l, m)) {
+ return l;
+ } else {
+ upb_msglayout_free(l);
+ return NULL;
+ }
+}
+
+
+/** upb_msgfactory ************************************************************/
+
+struct upb_msgfactory {
+ const upb_symtab *symtab; /* We own a ref. */
+ upb_inttable layouts;
+ upb_inttable mergehandlers;
+};
+
+upb_msgfactory *upb_msgfactory_new(const upb_symtab *symtab) {
+ upb_msgfactory *ret = upb_gmalloc(sizeof(*ret));
+
+ ret->symtab = symtab;
+ upb_inttable_init(&ret->layouts, UPB_CTYPE_PTR);
+ upb_inttable_init(&ret->mergehandlers, UPB_CTYPE_CONSTPTR);
+
+ return ret;
+}
+
+void upb_msgfactory_free(upb_msgfactory *f) {
+ upb_inttable_iter i;
+ upb_inttable_begin(&i, &f->layouts);
+ for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
+ upb_msglayout *l = upb_value_getptr(upb_inttable_iter_value(&i));
+ upb_msglayout_free(l);
+ }
+
+ upb_inttable_begin(&i, &f->mergehandlers);
+ for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
+ const upb_handlers *h = upb_value_getconstptr(upb_inttable_iter_value(&i));
+ upb_handlers_unref(h, f);
+ }
+
+ upb_inttable_uninit(&f->layouts);
+ upb_inttable_uninit(&f->mergehandlers);
+ upb_gfree(f);
+}
+
+const upb_symtab *upb_msgfactory_symtab(const upb_msgfactory *f) {
+ return f->symtab;
+}
+
+const upb_msglayout *upb_msgfactory_getlayout(upb_msgfactory *f,
+ const upb_msgdef *m) {
+ upb_value v;
+ UPB_ASSERT(upb_symtab_lookupmsg(f->symtab, upb_msgdef_fullname(m)) == m);
+ UPB_ASSERT(!upb_msgdef_mapentry(m));
+
+ if (upb_inttable_lookupptr(&f->layouts, m, &v)) {
+ UPB_ASSERT(upb_value_getptr(v));
+ return upb_value_getptr(v);
+ } else {
+ upb_msgfactory *mutable_f = (void*)f;
+ upb_msglayout *l = upb_msglayout_new(m);
+ upb_inttable_insertptr(&mutable_f->layouts, m, upb_value_ptr(l));
+ UPB_ASSERT(l);
+ return l;
+ }
+}
+
+/* Our handlers that we don't expose externally. */
+
+void *upb_msg_startstr(void *msg, const void *hd, size_t size_hint) {
+ uint32_t ofs = (uintptr_t)hd;
+ upb_alloc *alloc = upb_msg_alloc(msg);
+ upb_msgval val;
+ UPB_UNUSED(size_hint);
+
+ val = upb_msgval_read(msg, ofs, upb_msgval_sizeof(UPB_TYPE_STRING));
+
+ upb_free(alloc, (void*)val.str.data);
+ val.str.data = NULL;
+ val.str.size = 0;
+
+ upb_msgval_write(msg, ofs, val, upb_msgval_sizeof(UPB_TYPE_STRING));
+ return msg;
+}
+
+size_t upb_msg_str(void *msg, const void *hd, const char *ptr, size_t size,
+ const upb_bufhandle *handle) {
+ uint32_t ofs = (uintptr_t)hd;
+ upb_alloc *alloc = upb_msg_alloc(msg);
+ upb_msgval val;
+ size_t newsize;
+ UPB_UNUSED(handle);
+
+ val = upb_msgval_read(msg, ofs, upb_msgval_sizeof(UPB_TYPE_STRING));
+
+ newsize = val.str.size + size;
+ val.str.data = upb_realloc(alloc, (void*)val.str.data, val.str.size, newsize);
+
+ if (!val.str.data) {
+ return false;
+ }
+
+ memcpy((char*)val.str.data + val.str.size, ptr, size);
+ val.str.size = newsize;
+ upb_msgval_write(msg, ofs, val, upb_msgval_sizeof(UPB_TYPE_STRING));
+ return size;
+}
+
+static void callback(const void *closure, upb_handlers *h) {
+ upb_msgfactory *factory = (upb_msgfactory*)closure;
+ const upb_msgdef *md = upb_handlers_msgdef(h);
+ const upb_msglayout* layout = upb_msgfactory_getlayout(factory, md);
+ upb_msg_field_iter i;
+ UPB_UNUSED(factory);
+
+ for(upb_msg_field_begin(&i, md);
+ !upb_msg_field_done(&i);
+ upb_msg_field_next(&i)) {
+ const upb_fielddef *f = upb_msg_iter_field(&i);
+ size_t offset = upb_msglayout_offset(layout, f);
+ upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
+ upb_handlerattr_sethandlerdata(&attr, (void*)offset);
+
+ if (upb_fielddef_isseq(f)) {
+ } else if (upb_fielddef_isstring(f)) {
+ upb_handlers_setstartstr(h, f, upb_msg_startstr, &attr);
+ upb_handlers_setstring(h, f, upb_msg_str, &attr);
+ } else {
+ upb_msg_setscalarhandler(
+ h, f, offset, upb_msglayout_hasbit(layout, f));
+ }
+ }
+}
+
+const upb_handlers *upb_msgfactory_getmergehandlers(upb_msgfactory *f,
+ const upb_msgdef *m) {
+ upb_msgfactory *mutable_f = (void*)f;
+
+ /* TODO(haberman): properly cache these. */
+ const upb_handlers *ret = upb_handlers_newfrozen(m, f, callback, f);
+ upb_inttable_push(&mutable_f->mergehandlers, upb_value_constptr(ret));
+
+ return ret;
+}
+
+const upb_visitorplan *upb_msgfactory_getvisitorplan(upb_msgfactory *f,
+ const upb_handlers *h) {
+ const upb_msgdef *md = upb_handlers_msgdef(h);
+ return (const upb_visitorplan*)upb_msgfactory_getlayout(f, md);
+}
+
+
+/** upb_visitor ***************************************************************/
+
+struct upb_visitor {
+ const upb_msglayout *layout;
+ upb_sink *sink;
+};
+
+static upb_selector_t getsel2(const upb_fielddef *f, upb_handlertype_t type) {
+ upb_selector_t ret;
+ bool ok = upb_handlers_getselector(f, type, &ret);
+ UPB_ASSERT(ok);
+ return ret;
+}
+
+static bool upb_visitor_hasfield(const upb_msg *msg, const upb_fielddef *f,
+ const upb_msglayout *layout) {
+ int field_index = upb_fielddef_index(f);
+ if (upb_fielddef_isseq(f)) {
+ return upb_msgval_getarr(upb_msg_get(msg, field_index, layout)) != NULL;
+ } else if (upb_msgdef_syntax(upb_fielddef_containingtype(f)) ==
+ UPB_SYNTAX_PROTO2) {
+ return upb_msg_has(msg, field_index, layout);
+ } else {
+ upb_msgval val = upb_msg_get(msg, field_index, layout);
+ switch (upb_fielddef_type(f)) {
+ case UPB_TYPE_FLOAT:
+ return upb_msgval_getfloat(val) != 0;
+ case UPB_TYPE_DOUBLE:
+ return upb_msgval_getdouble(val) != 0;
+ case UPB_TYPE_BOOL:
+ return upb_msgval_getbool(val);
+ case UPB_TYPE_ENUM:
+ case UPB_TYPE_INT32:
+ return upb_msgval_getint32(val) != 0;
+ case UPB_TYPE_UINT32:
+ return upb_msgval_getuint32(val) != 0;
+ case UPB_TYPE_INT64:
+ return upb_msgval_getint64(val) != 0;
+ case UPB_TYPE_UINT64:
+ return upb_msgval_getuint64(val) != 0;
+ case UPB_TYPE_STRING:
+ case UPB_TYPE_BYTES:
+ return upb_msgval_getstr(val).size > 0;
+ case UPB_TYPE_MESSAGE:
+ return upb_msgval_getmsg(val) != NULL;
+ }
+ UPB_UNREACHABLE();
+ }
+}
+
+static bool upb_visitor_visitmsg2(const upb_msg *msg,
+ const upb_msglayout *layout, upb_sink *sink,
+ int depth) {
+ const upb_msgdef *md = upb_handlers_msgdef(sink->handlers);
+ upb_msg_field_iter i;
+ upb_status status;
+
+ upb_sink_startmsg(sink);
+
+ /* Protect against cycles (possible because users may freely reassign message
+ * and repeated fields) by imposing a maximum recursion depth. */
+ if (depth > ENCODE_MAX_NESTING) {
+ return false;
+ }
+
+ for (upb_msg_field_begin(&i, md);
+ !upb_msg_field_done(&i);
+ upb_msg_field_next(&i)) {
+ upb_fielddef *f = upb_msg_iter_field(&i);
+ upb_msgval val;
+
+ if (!upb_visitor_hasfield(msg, f, layout)) {
+ continue;
+ }
+
+ val = upb_msg_get(msg, upb_fielddef_index(f), layout);
+
+ if (upb_fielddef_isseq(f)) {
+ const upb_array *arr = upb_msgval_getarr(val);
+ UPB_ASSERT(arr);
+ /* TODO: putary(ary, f, sink, depth);*/
+ } else if (upb_fielddef_issubmsg(f)) {
+ const upb_map *map = upb_msgval_getmap(val);
+ UPB_ASSERT(map);
+ /* TODO: putmap(map, f, sink, depth);*/
+ } else if (upb_fielddef_isstring(f)) {
+ /* TODO putstr(); */
+ } else {
+ upb_selector_t sel = getsel2(f, upb_handlers_getprimitivehandlertype(f));
+ UPB_ASSERT(upb_fielddef_isprimitive(f));
+
+ switch (upb_fielddef_type(f)) {
+ case UPB_TYPE_FLOAT:
+ CHECK_TRUE(upb_sink_putfloat(sink, sel, upb_msgval_getfloat(val)));
+ break;
+ case UPB_TYPE_DOUBLE:
+ CHECK_TRUE(upb_sink_putdouble(sink, sel, upb_msgval_getdouble(val)));
+ break;
+ case UPB_TYPE_BOOL:
+ CHECK_TRUE(upb_sink_putbool(sink, sel, upb_msgval_getbool(val)));
+ break;
+ case UPB_TYPE_ENUM:
+ case UPB_TYPE_INT32:
+ CHECK_TRUE(upb_sink_putint32(sink, sel, upb_msgval_getint32(val)));
+ break;
+ case UPB_TYPE_UINT32:
+ CHECK_TRUE(upb_sink_putuint32(sink, sel, upb_msgval_getuint32(val)));
+ break;
+ case UPB_TYPE_INT64:
+ CHECK_TRUE(upb_sink_putint64(sink, sel, upb_msgval_getint64(val)));
+ break;
+ case UPB_TYPE_UINT64:
+ CHECK_TRUE(upb_sink_putuint64(sink, sel, upb_msgval_getuint64(val)));
+ break;
+ case UPB_TYPE_STRING:
+ case UPB_TYPE_BYTES:
+ case UPB_TYPE_MESSAGE:
+ UPB_UNREACHABLE();
+ }
+ }
+ }
+
+ upb_sink_endmsg(sink, &status);
+ return true;
+}
+
+upb_visitor *upb_visitor_create(upb_env *e, const upb_visitorplan *vp,
+ upb_sink *output) {
+ upb_visitor *visitor = upb_env_malloc(e, sizeof(*visitor));
+ visitor->layout = (const upb_msglayout*)vp;
+ visitor->sink = output;
+ return visitor;
+}
+
+bool upb_visitor_visitmsg(upb_visitor *visitor, const upb_msg *msg) {
+ return upb_visitor_visitmsg2(msg, visitor->layout, visitor->sink, 0);
+}
+
+
+/** upb_msg *******************************************************************/
+
+/* If we always read/write as a consistent type to each address, this shouldn't
+ * violate aliasing.
+ */
+#define DEREF(msg, ofs, type) *PTR_AT(msg, ofs, type)
+
+/* Internal members of a upb_msg. We can change this without breaking binary
+ * compatibility. We put these before the user's data. The user's upb_msg*
+ * points after the upb_msg_internal. */
+
+/* Used when a message is not extendable. */
+typedef struct {
+ /* TODO(haberman): add unknown fields. */
+ upb_alloc *alloc;
+} upb_msg_internal;
+
+/* Used when a message is extendable. */
+typedef struct {
+ upb_inttable *extdict;
+ upb_msg_internal base;
+} upb_msg_internal_withext;
+
+static int upb_msg_internalsize(const upb_msglayout *l) {
+ return sizeof(upb_msg_internal) - l->data.extendable * sizeof(void*);
+}
+
+static upb_msg_internal *upb_msg_getinternal(upb_msg *msg) {
+ return VOIDPTR_AT(msg, -sizeof(upb_msg_internal));
+}
+
+static const upb_msg_internal *upb_msg_getinternal_const(const upb_msg *msg) {
+ return VOIDPTR_AT(msg, -sizeof(upb_msg_internal));
+}
+
+static upb_msg_internal_withext *upb_msg_getinternalwithext(
+ upb_msg *msg, const upb_msglayout *l) {
+ UPB_ASSERT(l->data.extendable);
+ return VOIDPTR_AT(msg, -sizeof(upb_msg_internal_withext));
+}
+
+static const upb_msglayout_fieldinit_v1 *upb_msg_checkfield(
+ int field_index, const upb_msglayout *l) {
+ UPB_ASSERT(field_index >= 0 && field_index < l->data.field_count);
+ return &l->data.fields[field_index];
+}
+
+static bool upb_msg_inoneof(const upb_msglayout_fieldinit_v1 *field) {
+ return field->oneof_index != UPB_NOT_IN_ONEOF;
+}
+
+static uint32_t *upb_msg_oneofcase(const upb_msg *msg, int field_index,
+ const upb_msglayout *l) {
+ const upb_msglayout_fieldinit_v1 *field = upb_msg_checkfield(field_index, l);
+ UPB_ASSERT(upb_msg_inoneof(field));
+ return PTR_AT(msg, l->data.oneofs[field->oneof_index].case_offset, uint32_t);
+}
+
+size_t upb_msg_sizeof(const upb_msglayout *l) {
+ return l->data.size + upb_msg_internalsize(l);
+}
+
+upb_msg *upb_msg_init(void *mem, const upb_msglayout *l, upb_alloc *a) {
+ upb_msg *msg = VOIDPTR_AT(mem, upb_msg_internalsize(l));
+
+ /* Initialize normal members. */
+ if (l->data.default_msg) {
+ memcpy(msg, l->data.default_msg, l->data.size);
+ } else {
+ memset(msg, 0, l->data.size);
+ }
+
+ /* Initialize internal members. */
+ upb_msg_getinternal(msg)->alloc = a;
+
+ if (l->data.extendable) {
+ upb_msg_getinternalwithext(msg, l)->extdict = NULL;
+ }
+
+ return msg;
+}
+
+void *upb_msg_uninit(upb_msg *msg, const upb_msglayout *l) {
+ if (l->data.extendable) {
+ upb_inttable *ext_dict = upb_msg_getinternalwithext(msg, l)->extdict;
+ if (ext_dict) {
+ upb_inttable_uninit2(ext_dict, upb_msg_alloc(msg));
+ upb_free(upb_msg_alloc(msg), ext_dict);
+ }
+ }
+
+ return VOIDPTR_AT(msg, -upb_msg_internalsize(l));
+}
+
+upb_msg *upb_msg_new(const upb_msglayout *l, upb_alloc *a) {
+ void *mem = upb_malloc(a, upb_msg_sizeof(l));
+ return mem ? upb_msg_init(mem, l, a) : NULL;
+}
+
+void upb_msg_free(upb_msg *msg, const upb_msglayout *l) {
+ upb_free(upb_msg_alloc(msg), upb_msg_uninit(msg, l));
+}
+
+upb_alloc *upb_msg_alloc(const upb_msg *msg) {
+ return upb_msg_getinternal_const(msg)->alloc;
+}
+
+bool upb_msg_has(const upb_msg *msg,
+ int field_index,
+ const upb_msglayout *l) {
+ const upb_msglayout_fieldinit_v1 *field = upb_msg_checkfield(field_index, l);
+
+ UPB_ASSERT(l->data.is_proto2);
+
+ if (upb_msg_inoneof(field)) {
+ /* Oneofs are set when the oneof number is set to this field. */
+ return *upb_msg_oneofcase(msg, field_index, l) == field->number;
+ } else {
+ /* Other fields are set when their hasbit is set. */
+ uint32_t hasbit = l->data.fields[field_index].hasbit;
+ return DEREF(msg, hasbit / 8, char) | (1 << (hasbit % 8));
+ }
+}
+
+upb_msgval upb_msg_get(const upb_msg *msg, int field_index,
+ const upb_msglayout *l) {
+ const upb_msglayout_fieldinit_v1 *field = upb_msg_checkfield(field_index, l);
+ int size = upb_msg_fieldsize(field);
+
+ if (upb_msg_inoneof(field)) {
+ if (*upb_msg_oneofcase(msg, field_index, l) == field->number) {
+ size_t ofs = l->data.oneofs[field->oneof_index].data_offset;
+ return upb_msgval_read(msg, ofs, size);
+ } else {
+ /* Return default. */
+ return upb_msgval_read(l->data.default_msg, field->offset, size);
+ }
+ } else {
+ return upb_msgval_read(msg, field->offset, size);
+ }
+}
+
+void upb_msg_set(upb_msg *msg, int field_index, upb_msgval val,
+ const upb_msglayout *l) {
+ const upb_msglayout_fieldinit_v1 *field = upb_msg_checkfield(field_index, l);
+ int size = upb_msg_fieldsize(field);
+
+ if (upb_msg_inoneof(field)) {
+ size_t ofs = l->data.oneofs[field->oneof_index].data_offset;
+ *upb_msg_oneofcase(msg, field_index, l) = field->number;
+ upb_msgval_write(msg, ofs, val, size);
+ } else {
+ upb_msgval_write(msg, field->offset, val, size);
+ }
+}
+
+
+/** upb_array *****************************************************************/
+
+#define DEREF_ARR(arr, i, type) ((type*)arr->data)[i]
+
+size_t upb_array_sizeof(upb_fieldtype_t type) {
+ UPB_UNUSED(type);
+ return sizeof(upb_array);
+}
+
+void upb_array_init(upb_array *arr, upb_fieldtype_t type, upb_alloc *alloc) {
+ arr->type = type;
+ arr->data = NULL;
+ arr->len = 0;
+ arr->size = 0;
+ arr->element_size = upb_msgval_sizeof(type);
+ arr->alloc = alloc;
+}
+
+void upb_array_uninit(upb_array *arr) {
+ upb_free(arr->alloc, arr->data);
+}
+
+upb_array *upb_array_new(upb_fieldtype_t type, upb_alloc *a) {
+ upb_array *ret = upb_malloc(a, upb_array_sizeof(type));
+
+ if (ret) {
+ upb_array_init(ret, type, a);
+ }
+
+ return ret;
+}
+
+void upb_array_free(upb_array *arr) {
+ upb_array_uninit(arr);
+ upb_free(arr->alloc, arr);
+}
+
+size_t upb_array_size(const upb_array *arr) {
+ return arr->len;
+}
+
+upb_fieldtype_t upb_array_type(const upb_array *arr) {
+ return arr->type;
+}
+
+upb_msgval upb_array_get(const upb_array *arr, size_t i) {
+ UPB_ASSERT(i < arr->len);
+ return upb_msgval_read(arr->data, i * arr->element_size, arr->element_size);
+}
+
+bool upb_array_set(upb_array *arr, size_t i, upb_msgval val) {
+ UPB_ASSERT(i <= arr->len);
+
+ if (i == arr->len) {
+ /* Extending the array. */
+
+ if (i == arr->size) {
+ /* Need to reallocate. */
+ size_t new_size = UPB_MAX(arr->size * 2, 8);
+ size_t new_bytes = new_size * arr->element_size;
+ size_t old_bytes = arr->size * arr->element_size;
+ upb_msgval *new_data =
+ upb_realloc(arr->alloc, arr->data, old_bytes, new_bytes);
+
+ if (!new_data) {
+ return false;
+ }
+
+ arr->data = new_data;
+ arr->size = new_size;
+ }
+
+ arr->len = i + 1;
+ }
+
+ upb_msgval_write(arr->data, i * arr->element_size, val, arr->element_size);
+ return true;
+}
+
+
+/** upb_map *******************************************************************/
+
+struct upb_map {
+ upb_fieldtype_t key_type;
+ upb_fieldtype_t val_type;
+ /* We may want to optimize this to use inttable where possible, for greater
+ * efficiency and lower memory footprint. */
+ upb_strtable strtab;
+ upb_alloc *alloc;
+};
+
+static void upb_map_tokey(upb_fieldtype_t type, upb_msgval *key,
+ const char **out_key, size_t *out_len) {
+ switch (type) {
+ case UPB_TYPE_STRING:
+ /* Point to string data of the input key. */
+ *out_key = key->str.data;
+ *out_len = key->str.size;
+ return;
+ case UPB_TYPE_BOOL:
+ case UPB_TYPE_INT32:
+ case UPB_TYPE_UINT32:
+ case UPB_TYPE_INT64:
+ case UPB_TYPE_UINT64:
+ /* Point to the key itself. XXX: big-endian. */
+ *out_key = (const char*)key;
+ *out_len = upb_msgval_sizeof(type);
+ return;
+ case UPB_TYPE_BYTES:
+ case UPB_TYPE_DOUBLE:
+ case UPB_TYPE_ENUM:
+ case UPB_TYPE_FLOAT:
+ case UPB_TYPE_MESSAGE:
+ break; /* Cannot be a map key. */
+ }
+ UPB_UNREACHABLE();
+}
+
+static upb_msgval upb_map_fromkey(upb_fieldtype_t type, const char *key,
+ size_t len) {
+ switch (type) {
+ case UPB_TYPE_STRING:
+ return upb_msgval_makestr(key, len);
+ case UPB_TYPE_BOOL:
+ case UPB_TYPE_INT32:
+ case UPB_TYPE_UINT32:
+ case UPB_TYPE_INT64:
+ case UPB_TYPE_UINT64:
+ return upb_msgval_read(key, 0, upb_msgval_sizeof(type));
+ case UPB_TYPE_BYTES:
+ case UPB_TYPE_DOUBLE:
+ case UPB_TYPE_ENUM:
+ case UPB_TYPE_FLOAT:
+ case UPB_TYPE_MESSAGE:
+ break; /* Cannot be a map key. */
+ }
+ UPB_UNREACHABLE();
+}
+
+size_t upb_map_sizeof(upb_fieldtype_t ktype, upb_fieldtype_t vtype) {
+ /* Size does not currently depend on key/value type. */
+ UPB_UNUSED(ktype);
+ UPB_UNUSED(vtype);
+ return sizeof(upb_map);
+}
+
+bool upb_map_init(upb_map *map, upb_fieldtype_t ktype, upb_fieldtype_t vtype,
+ upb_alloc *a) {
+ upb_ctype_t vtabtype = upb_fieldtotabtype(vtype);
+ UPB_ASSERT(upb_fieldtype_mapkeyok(ktype));
+ map->key_type = ktype;
+ map->val_type = vtype;
+ map->alloc = a;
+
+ if (!upb_strtable_init2(&map->strtab, vtabtype, a)) {
+ return false;
+ }
+
+ return true;
+}
+
+void upb_map_uninit(upb_map *map) {
+ upb_strtable_uninit2(&map->strtab, map->alloc);
+}
+
+upb_map *upb_map_new(upb_fieldtype_t ktype, upb_fieldtype_t vtype,
+ upb_alloc *a) {
+ upb_map *map = upb_malloc(a, upb_map_sizeof(ktype, vtype));
+
+ if (!map) {
+ return NULL;
+ }
+
+ if (!upb_map_init(map, ktype, vtype, a)) {
+ return NULL;
+ }
+
+ return map;
+}
+
+void upb_map_free(upb_map *map) {
+ upb_map_uninit(map);
+ upb_free(map->alloc, map);
+}
+
+size_t upb_map_size(const upb_map *map) {
+ return upb_strtable_count(&map->strtab);
+}
+
+upb_fieldtype_t upb_map_keytype(const upb_map *map) {
+ return map->key_type;
+}
+
+upb_fieldtype_t upb_map_valuetype(const upb_map *map) {
+ return map->val_type;
+}
+
+bool upb_map_get(const upb_map *map, upb_msgval key, upb_msgval *val) {
+ upb_value tabval;
+ const char *key_str;
+ size_t key_len;
+ bool ret;
+
+ upb_map_tokey(map->key_type, &key, &key_str, &key_len);
+ ret = upb_strtable_lookup2(&map->strtab, key_str, key_len, &tabval);
+ if (ret) {
+ memcpy(val, &tabval, sizeof(tabval));
+ }
+
+ return ret;
+}
+
+bool upb_map_set(upb_map *map, upb_msgval key, upb_msgval val,
+ upb_msgval *removed) {
+ const char *key_str;
+ size_t key_len;
+ upb_value tabval = upb_toval(val);
+ upb_value removedtabval;
+ upb_alloc *a = map->alloc;
+
+ upb_map_tokey(map->key_type, &key, &key_str, &key_len);
+
+ /* TODO(haberman): add overwrite operation to minimize number of lookups. */
+ if (upb_strtable_lookup2(&map->strtab, key_str, key_len, NULL)) {
+ upb_strtable_remove3(&map->strtab, key_str, key_len, &removedtabval, a);
+ memcpy(&removed, &removedtabval, sizeof(removed));
+ }
+
+ return upb_strtable_insert3(&map->strtab, key_str, key_len, tabval, a);
+}
+
+bool upb_map_del(upb_map *map, upb_msgval key) {
+ const char *key_str;
+ size_t key_len;
+ upb_alloc *a = map->alloc;
+
+ upb_map_tokey(map->key_type, &key, &key_str, &key_len);
+ return upb_strtable_remove3(&map->strtab, key_str, key_len, NULL, a);
+}
+
+
+/** upb_mapiter ***************************************************************/
+
+struct upb_mapiter {
+ upb_strtable_iter iter;
+ upb_fieldtype_t key_type;
+};
+
+size_t upb_mapiter_sizeof() {
+ return sizeof(upb_mapiter);
+}
+
+void upb_mapiter_begin(upb_mapiter *i, const upb_map *map) {
+ upb_strtable_begin(&i->iter, &map->strtab);
+ i->key_type = map->key_type;
+}
+
+upb_mapiter *upb_mapiter_new(const upb_map *t, upb_alloc *a) {
+ upb_mapiter *ret = upb_malloc(a, upb_mapiter_sizeof());
+
+ if (!ret) {
+ return NULL;
+ }
+
+ upb_mapiter_begin(ret, t);
+ return ret;
+}
+
+void upb_mapiter_free(upb_mapiter *i, upb_alloc *a) {
+ upb_free(a, i);
+}
+
+void upb_mapiter_next(upb_mapiter *i) {
+ upb_strtable_next(&i->iter);
+}
+
+bool upb_mapiter_done(const upb_mapiter *i) {
+ return upb_strtable_done(&i->iter);
+}
+
+upb_msgval upb_mapiter_key(const upb_mapiter *i) {
+ return upb_map_fromkey(i->key_type, upb_strtable_iter_key(&i->iter),
+ upb_strtable_iter_keylength(&i->iter));
+}
+
+upb_msgval upb_mapiter_value(const upb_mapiter *i) {
+ return upb_msgval_fromval(upb_strtable_iter_value(&i->iter));
+}
+
+void upb_mapiter_setdone(upb_mapiter *i) {
+ upb_strtable_iter_setdone(&i->iter);
+}
+
+bool upb_mapiter_isequal(const upb_mapiter *i1, const upb_mapiter *i2) {
+ return upb_strtable_iter_isequal(&i1->iter, &i2->iter);
+}
+
+
+/** Handlers for upb_msg ******************************************************/
+
+typedef struct {
+ size_t offset;
+ int32_t hasbit;
+} upb_msg_handlerdata;
+
+/* Fallback implementation if the handler is not specialized by the producer. */
+#define MSG_WRITER(type, ctype) \
+ bool upb_msg_set ## type (void *c, const void *hd, ctype val) { \
+ uint8_t *m = c; \
+ const upb_msg_handlerdata *d = hd; \
+ if (d->hasbit > 0) \
+ *(uint8_t*)&m[d->hasbit / 8] |= 1 << (d->hasbit % 8); \
+ *(ctype*)&m[d->offset] = val; \
+ return true; \
+ } \
+
+MSG_WRITER(double, double)
+MSG_WRITER(float, float)
+MSG_WRITER(int32, int32_t)
+MSG_WRITER(int64, int64_t)
+MSG_WRITER(uint32, uint32_t)
+MSG_WRITER(uint64, uint64_t)
+MSG_WRITER(bool, bool)
+
+bool upb_msg_setscalarhandler(upb_handlers *h, const upb_fielddef *f,
+ size_t offset, int32_t hasbit) {
+ upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
+ bool ok;
+
+ upb_msg_handlerdata *d = upb_gmalloc(sizeof(*d));
+ if (!d) return false;
+ d->offset = offset;
+ d->hasbit = hasbit;
+
+ upb_handlerattr_sethandlerdata(&attr, d);
+ upb_handlerattr_setalwaysok(&attr, true);
+ upb_handlers_addcleanup(h, d, upb_gfree);
+
+#define TYPE(u, l) \
+ case UPB_TYPE_##u: \
+ ok = upb_handlers_set##l(h, f, upb_msg_set##l, &attr); break;
+
+ ok = false;
+
+ switch (upb_fielddef_type(f)) {
+ TYPE(INT64, int64);
+ TYPE(INT32, int32);
+ TYPE(ENUM, int32);
+ TYPE(UINT64, uint64);
+ TYPE(UINT32, uint32);
+ TYPE(DOUBLE, double);
+ TYPE(FLOAT, float);
+ TYPE(BOOL, bool);
+ default: UPB_ASSERT(false); break;
+ }
+#undef TYPE
+
+ upb_handlerattr_uninit(&attr);
+ return ok;
+}
+
+bool upb_msg_getscalarhandlerdata(const upb_handlers *h,
+ upb_selector_t s,
+ upb_fieldtype_t *type,
+ size_t *offset,
+ int32_t *hasbit) {
+ const upb_msg_handlerdata *d;
+ upb_func *f = upb_handlers_gethandler(h, s);
+
+ if ((upb_int64_handlerfunc*)f == upb_msg_setint64) {
+ *type = UPB_TYPE_INT64;
+ } else if ((upb_int32_handlerfunc*)f == upb_msg_setint32) {
+ *type = UPB_TYPE_INT32;
+ } else if ((upb_uint64_handlerfunc*)f == upb_msg_setuint64) {
+ *type = UPB_TYPE_UINT64;
+ } else if ((upb_uint32_handlerfunc*)f == upb_msg_setuint32) {
+ *type = UPB_TYPE_UINT32;
+ } else if ((upb_double_handlerfunc*)f == upb_msg_setdouble) {
+ *type = UPB_TYPE_DOUBLE;
+ } else if ((upb_float_handlerfunc*)f == upb_msg_setfloat) {
+ *type = UPB_TYPE_FLOAT;
+ } else if ((upb_bool_handlerfunc*)f == upb_msg_setbool) {
+ *type = UPB_TYPE_BOOL;
+ } else {
+ return false;
+ }
+
+ d = upb_handlers_gethandlerdata(h, s);
+ *offset = d->offset;
+ *hasbit = d->hasbit;
+ return true;
+}
/*
** upb::RefCounted Implementation
**
@@ -3703,579 +6068,91 @@ bool upb_refcounted_freeze(upb_refcounted *const*roots, int n, upb_status *s,
}
-/* Fallback implementation if the shim is not specialized by the JIT. */
-#define SHIM_WRITER(type, ctype) \
- bool upb_shim_set ## type (void *c, const void *hd, ctype val) { \
- uint8_t *m = c; \
- const upb_shim_data *d = hd; \
- if (d->hasbit > 0) \
- *(uint8_t*)&m[d->hasbit / 8] |= 1 << (d->hasbit % 8); \
- *(ctype*)&m[d->offset] = val; \
- return true; \
- } \
-
-SHIM_WRITER(double, double)
-SHIM_WRITER(float, float)
-SHIM_WRITER(int32, int32_t)
-SHIM_WRITER(int64, int64_t)
-SHIM_WRITER(uint32, uint32_t)
-SHIM_WRITER(uint64, uint64_t)
-SHIM_WRITER(bool, bool)
-#undef SHIM_WRITER
-
-bool upb_shim_set(upb_handlers *h, const upb_fielddef *f, size_t offset,
- int32_t hasbit) {
- upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
- bool ok;
-
- upb_shim_data *d = upb_gmalloc(sizeof(*d));
- if (!d) return false;
- d->offset = offset;
- d->hasbit = hasbit;
-
- upb_handlerattr_sethandlerdata(&attr, d);
- upb_handlerattr_setalwaysok(&attr, true);
- upb_handlers_addcleanup(h, d, upb_gfree);
-
-#define TYPE(u, l) \
- case UPB_TYPE_##u: \
- ok = upb_handlers_set##l(h, f, upb_shim_set##l, &attr); break;
-
- ok = false;
-
- switch (upb_fielddef_type(f)) {
- TYPE(INT64, int64);
- TYPE(INT32, int32);
- TYPE(ENUM, int32);
- TYPE(UINT64, uint64);
- TYPE(UINT32, uint32);
- TYPE(DOUBLE, double);
- TYPE(FLOAT, float);
- TYPE(BOOL, bool);
- default: UPB_ASSERT(false); break;
- }
-#undef TYPE
-
- upb_handlerattr_uninit(&attr);
- return ok;
-}
-
-const upb_shim_data *upb_shim_getdata(const upb_handlers *h, upb_selector_t s,
- upb_fieldtype_t *type) {
- upb_func *f = upb_handlers_gethandler(h, s);
-
- if ((upb_int64_handlerfunc*)f == upb_shim_setint64) {
- *type = UPB_TYPE_INT64;
- } else if ((upb_int32_handlerfunc*)f == upb_shim_setint32) {
- *type = UPB_TYPE_INT32;
- } else if ((upb_uint64_handlerfunc*)f == upb_shim_setuint64) {
- *type = UPB_TYPE_UINT64;
- } else if ((upb_uint32_handlerfunc*)f == upb_shim_setuint32) {
- *type = UPB_TYPE_UINT32;
- } else if ((upb_double_handlerfunc*)f == upb_shim_setdouble) {
- *type = UPB_TYPE_DOUBLE;
- } else if ((upb_float_handlerfunc*)f == upb_shim_setfloat) {
- *type = UPB_TYPE_FLOAT;
- } else if ((upb_bool_handlerfunc*)f == upb_shim_setbool) {
- *type = UPB_TYPE_BOOL;
- } else {
- return NULL;
- }
-
- return (const upb_shim_data*)upb_handlers_gethandlerdata(h, s);
-}
-
-
-#include <string.h>
-
-static void upb_symtab_free(upb_refcounted *r) {
- upb_symtab *s = (upb_symtab*)r;
- upb_strtable_iter i;
- upb_strtable_begin(&i, &s->symtab);
- for (; !upb_strtable_done(&i); upb_strtable_next(&i)) {
- const upb_def *def = upb_value_getptr(upb_strtable_iter_value(&i));
- upb_def_unref(def, s);
- }
- upb_strtable_uninit(&s->symtab);
- upb_gfree(s);
-}
-
-upb_symtab *upb_symtab_new(const void *owner) {
- static const struct upb_refcounted_vtbl vtbl = {NULL, &upb_symtab_free};
-
- upb_symtab *s = upb_gmalloc(sizeof(*s));
- if (!s) {
- return NULL;
+bool upb_bufsrc_putbuf(const char *buf, size_t len, upb_bytessink *sink) {
+ void *subc;
+ bool ret;
+ upb_bufhandle handle;
+ upb_bufhandle_init(&handle);
+ upb_bufhandle_setbuf(&handle, buf, 0);
+ ret = upb_bytessink_start(sink, len, &subc);
+ if (ret && len != 0) {
+ ret = (upb_bytessink_putbuf(sink, subc, buf, len, &handle) >= len);
}
-
- upb_refcounted_init(upb_symtab_upcast_mutable(s), &vtbl, owner);
- upb_strtable_init(&s->symtab, UPB_CTYPE_PTR);
- return s;
-}
-
-void upb_symtab_freeze(upb_symtab *s) {
- upb_refcounted *r;
- bool ok;
-
- UPB_ASSERT(!upb_symtab_isfrozen(s));
- r = upb_symtab_upcast_mutable(s);
- /* The symtab does not take ref2's (see refcounted.h) on the defs, because
- * defs cannot refer back to the table and therefore cannot create cycles. So
- * 0 will suffice for maxdepth here. */
- ok = upb_refcounted_freeze(&r, 1, NULL, 0);
- UPB_ASSERT(ok);
-}
-
-const upb_def *upb_symtab_lookup(const upb_symtab *s, const char *sym) {
- upb_value v;
- upb_def *ret = upb_strtable_lookup(&s->symtab, sym, &v) ?
- upb_value_getptr(v) : NULL;
- return ret;
-}
-
-const upb_msgdef *upb_symtab_lookupmsg(const upb_symtab *s, const char *sym) {
- upb_value v;
- upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
- upb_value_getptr(v) : NULL;
- return def ? upb_dyncast_msgdef(def) : NULL;
-}
-
-const upb_enumdef *upb_symtab_lookupenum(const upb_symtab *s, const char *sym) {
- upb_value v;
- upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
- upb_value_getptr(v) : NULL;
- return def ? upb_dyncast_enumdef(def) : NULL;
-}
-
-/* Given a symbol and the base symbol inside which it is defined, find the
- * symbol's definition in t. */
-static upb_def *upb_resolvename(const upb_strtable *t,
- const char *base, const char *sym) {
- if(strlen(sym) == 0) return NULL;
- if(sym[0] == '.') {
- /* Symbols starting with '.' are absolute, so we do a single lookup.
- * Slice to omit the leading '.' */
- upb_value v;
- return upb_strtable_lookup(t, sym + 1, &v) ? upb_value_getptr(v) : NULL;
- } else {
- /* Remove components from base until we find an entry or run out.
- * TODO: This branch is totally broken, but currently not used. */
- (void)base;
- UPB_ASSERT(false);
- return NULL;
+ if (ret) {
+ ret = upb_bytessink_end(sink);
}
-}
-
-const upb_def *upb_symtab_resolve(const upb_symtab *s, const char *base,
- const char *sym) {
- upb_def *ret = upb_resolvename(&s->symtab, base, sym);
+ upb_bufhandle_uninit(&handle);
return ret;
}
-/* Starts a depth-first traversal at "def", recursing into any subdefs
- * (ie. submessage types). Adds duplicates of existing defs to addtab
- * wherever necessary, so that the resulting symtab will be consistent once
- * addtab is added.
- *
- * More specifically, if any def D is found in the DFS that:
- *
- * 1. can reach a def that is being replaced by something in addtab, AND
- *
- * 2. is not itself being replaced already (ie. this name doesn't already
- * exist in addtab)
- *
- * ...then a duplicate (new copy) of D will be added to addtab.
- *
- * Returns true if this happened for any def reachable from "def."
- *
- * It is slightly tricky to do this correctly in the presence of cycles. If we
- * detect that our DFS has hit a cycle, we might not yet know if any SCCs on
- * our stack can reach a def in addtab or not. Once we figure this out, that
- * answer needs to apply to *all* defs in these SCCs, even if we visited them
- * already. So a straight up one-pass cycle-detecting DFS won't work.
- *
- * To work around this problem, we traverse each SCC (which we already
- * computed, since these defs are frozen) as a single node. We first compute
- * whether the SCC as a whole can reach any def in addtab, then we dup (or not)
- * the entire SCC. This requires breaking the encapsulation of upb_refcounted,
- * since that is where we get the data about what SCC we are in. */
-static bool upb_resolve_dfs(const upb_def *def, upb_strtable *addtab,
- const void *new_owner, upb_inttable *seen,
- upb_status *s) {
- upb_value v;
- bool need_dup;
- const upb_def *base;
- const void* memoize_key;
-
- /* Memoize results of this function for efficiency (since we're traversing a
- * DAG this is not needed to limit the depth of the search).
- *
- * We memoize by SCC instead of by individual def. */
- memoize_key = def->base.group;
-
- if (upb_inttable_lookupptr(seen, memoize_key, &v))
- return upb_value_getbool(v);
-
- /* Visit submessages for all messages in the SCC. */
- need_dup = false;
- base = def;
- do {
- upb_value v;
- const upb_msgdef *m;
-
- UPB_ASSERT(upb_def_isfrozen(def));
- if (def->type == UPB_DEF_FIELD) continue;
- if (upb_strtable_lookup(addtab, upb_def_fullname(def), &v)) {
- need_dup = true;
- }
-
- /* For messages, continue the recursion by visiting all subdefs, but only
- * ones in different SCCs. */
- m = upb_dyncast_msgdef(def);
- if (m) {
- upb_msg_field_iter i;
- for(upb_msg_field_begin(&i, m);
- !upb_msg_field_done(&i);
- upb_msg_field_next(&i)) {
- upb_fielddef *f = upb_msg_iter_field(&i);
- const upb_def *subdef;
-
- if (!upb_fielddef_hassubdef(f)) continue;
- subdef = upb_fielddef_subdef(f);
-
- /* Skip subdefs in this SCC. */
- if (def->base.group == subdef->base.group) continue;
-
- /* |= to avoid short-circuit; we need its side-effects. */
- need_dup |= upb_resolve_dfs(subdef, addtab, new_owner, seen, s);
- if (!upb_ok(s)) return false;
- }
- }
- } while ((def = (upb_def*)def->base.next) != base);
-
- if (need_dup) {
- /* Dup all defs in this SCC that don't already have entries in addtab. */
- def = base;
- do {
- const char *name;
-
- if (def->type == UPB_DEF_FIELD) continue;
- name = upb_def_fullname(def);
- if (!upb_strtable_lookup(addtab, name, NULL)) {
- upb_def *newdef = upb_def_dup(def, new_owner);
- if (!newdef) goto oom;
- newdef->came_from_user = false;
- if (!upb_strtable_insert(addtab, name, upb_value_ptr(newdef)))
- goto oom;
- }
- } while ((def = (upb_def*)def->base.next) != base);
- }
-
- upb_inttable_insertptr(seen, memoize_key, upb_value_bool(need_dup));
- return need_dup;
-
-oom:
- upb_status_seterrmsg(s, "out of memory");
- return false;
-}
-
-/* TODO(haberman): we need a lot more testing of error conditions.
- * The came_from_user stuff in particular is not tested. */
-static bool symtab_add(upb_symtab *s, upb_def *const*defs, size_t n,
- void *ref_donor, upb_refcounted *freeze_also,
- upb_status *status) {
- size_t i;
- size_t add_n;
- size_t freeze_n;
- upb_strtable_iter iter;
- upb_refcounted **add_objs = NULL;
- upb_def **add_defs = NULL;
- size_t add_objs_size;
- upb_strtable addtab;
- upb_inttable seen;
-
- if (n == 0 && !freeze_also) {
- return true;
- }
-
- UPB_ASSERT(!upb_symtab_isfrozen(s));
- if (!upb_strtable_init(&addtab, UPB_CTYPE_PTR)) {
- upb_status_seterrmsg(status, "out of memory");
- return false;
- }
-
- /* Add new defs to our "add" set. */
- for (i = 0; i < n; i++) {
- upb_def *def = defs[i];
- const char *fullname;
- upb_fielddef *f;
-
- if (upb_def_isfrozen(def)) {
- upb_status_seterrmsg(status, "added defs must be mutable");
- goto err;
- }
- UPB_ASSERT(!upb_def_isfrozen(def));
- fullname = upb_def_fullname(def);
- if (!fullname) {
- upb_status_seterrmsg(
- status, "Anonymous defs cannot be added to a symtab");
- goto err;
- }
-
- f = upb_dyncast_fielddef_mutable(def);
-
- if (f) {
- if (!upb_fielddef_containingtypename(f)) {
- upb_status_seterrmsg(status,
- "Standalone fielddefs must have a containing type "
- "(extendee) name set");
- goto err;
- }
- } else {
- if (upb_strtable_lookup(&addtab, fullname, NULL)) {
- upb_status_seterrf(status, "Conflicting defs named '%s'", fullname);
- goto err;
- }
- /* We need this to back out properly, because if there is a failure we
- * need to donate the ref back to the caller. */
- def->came_from_user = true;
- upb_def_donateref(def, ref_donor, s);
- if (!upb_strtable_insert(&addtab, fullname, upb_value_ptr(def)))
- goto oom_err;
- }
- }
-
- /* Add standalone fielddefs (ie. extensions) to the appropriate messages.
- * If the appropriate message only exists in the existing symtab, duplicate
- * it so we have a mutable copy we can add the fields to. */
- for (i = 0; i < n; i++) {
- upb_def *def = defs[i];
- upb_fielddef *f = upb_dyncast_fielddef_mutable(def);
- const char *msgname;
- upb_value v;
- upb_msgdef *m;
-
- if (!f) continue;
- msgname = upb_fielddef_containingtypename(f);
- /* We validated this earlier in this function. */
- UPB_ASSERT(msgname);
-
- /* If the extendee name is absolutely qualified, move past the initial ".".
- * TODO(haberman): it is not obvious what it would mean if this was not
- * absolutely qualified. */
- if (msgname[0] == '.') {
- msgname++;
- }
-
- if (upb_strtable_lookup(&addtab, msgname, &v)) {
- /* Extendee is in the set of defs the user asked us to add. */
- m = upb_value_getptr(v);
- } else {
- /* Need to find and dup the extendee from the existing symtab. */
- const upb_msgdef *frozen_m = upb_symtab_lookupmsg(s, msgname);
- if (!frozen_m) {
- upb_status_seterrf(status,
- "Tried to extend message %s that does not exist "
- "in this SymbolTable.",
- msgname);
- goto err;
- }
- m = upb_msgdef_dup(frozen_m, s);
- if (!m) goto oom_err;
- if (!upb_strtable_insert(&addtab, msgname, upb_value_ptr(m))) {
- upb_msgdef_unref(m, s);
- goto oom_err;
- }
- }
-
- if (!upb_msgdef_addfield(m, f, ref_donor, status)) {
- goto err;
- }
- }
-
- /* Add dups of any existing def that can reach a def with the same name as
- * anything in our "add" set. */
- if (!upb_inttable_init(&seen, UPB_CTYPE_BOOL)) goto oom_err;
- upb_strtable_begin(&iter, &s->symtab);
- for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
- upb_def *def = upb_value_getptr(upb_strtable_iter_value(&iter));
- upb_resolve_dfs(def, &addtab, s, &seen, status);
- if (!upb_ok(status)) goto err;
- }
- upb_inttable_uninit(&seen);
-
- /* Now using the table, resolve symbolic references for subdefs. */
- upb_strtable_begin(&iter, &addtab);
- for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
- const char *base;
- upb_def *def = upb_value_getptr(upb_strtable_iter_value(&iter));
- upb_msgdef *m = upb_dyncast_msgdef_mutable(def);
- upb_msg_field_iter j;
-
- if (!m) continue;
- /* Type names are resolved relative to the message in which they appear. */
- base = upb_msgdef_fullname(m);
-
- for(upb_msg_field_begin(&j, m);
- !upb_msg_field_done(&j);
- upb_msg_field_next(&j)) {
- upb_fielddef *f = upb_msg_iter_field(&j);
- const char *name = upb_fielddef_subdefname(f);
- if (name && !upb_fielddef_subdef(f)) {
- /* Try the lookup in the current set of to-be-added defs first. If not
- * there, try existing defs. */
- upb_def *subdef = upb_resolvename(&addtab, base, name);
- if (subdef == NULL) {
- subdef = upb_resolvename(&s->symtab, base, name);
- }
- if (subdef == NULL) {
- upb_status_seterrf(
- status, "couldn't resolve name '%s' in message '%s'", name, base);
- goto err;
- } else if (!upb_fielddef_setsubdef(f, subdef, status)) {
- goto err;
- }
- }
- }
- }
-
- /* We need an array of the defs in addtab, for passing to
- * upb_refcounted_freeze(). */
- add_objs_size = upb_strtable_count(&addtab);
- if (freeze_also) {
- add_objs_size++;
- }
-
- add_defs = upb_gmalloc(sizeof(void*) * add_objs_size);
- if (add_defs == NULL) goto oom_err;
- upb_strtable_begin(&iter, &addtab);
- for (add_n = 0; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
- add_defs[add_n++] = upb_value_getptr(upb_strtable_iter_value(&iter));
- }
-
- /* Validate defs. */
- if (!_upb_def_validate(add_defs, add_n, status)) {
- goto err;
- }
-
- /* Cheat a little and give the array a new type.
- * This is probably undefined behavior, but this code will be deleted soon. */
- add_objs = (upb_refcounted**)add_defs;
-
- freeze_n = add_n;
- if (freeze_also) {
- add_objs[freeze_n++] = freeze_also;
- }
-
- if (!upb_refcounted_freeze(add_objs, freeze_n, status,
- UPB_MAX_MESSAGE_DEPTH * 2)) {
- goto err;
- }
-
- /* This must be delayed until all errors have been detected, since error
- * recovery code uses this table to cleanup defs. */
- upb_strtable_uninit(&addtab);
-
- /* TODO(haberman) we don't properly handle errors after this point (like
- * OOM in upb_strtable_insert() below). */
- for (i = 0; i < add_n; i++) {
- upb_def *def = (upb_def*)add_objs[i];
- const char *name = upb_def_fullname(def);
- upb_value v;
- bool success;
-
- if (upb_strtable_remove(&s->symtab, name, &v)) {
- const upb_def *def = upb_value_getptr(v);
- upb_def_unref(def, s);
- }
- success = upb_strtable_insert(&s->symtab, name, upb_value_ptr(def));
- UPB_ASSERT(success == true);
- }
- upb_gfree(add_defs);
- return true;
-
-oom_err:
- upb_status_seterrmsg(status, "out of memory");
-err: {
- /* For defs the user passed in, we need to donate the refs back. For defs
- * we dup'd, we need to just unref them. */
- upb_strtable_begin(&iter, &addtab);
- for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
- upb_def *def = upb_value_getptr(upb_strtable_iter_value(&iter));
- bool came_from_user = def->came_from_user;
- def->came_from_user = false;
- if (came_from_user) {
- upb_def_donateref(def, s, ref_donor);
- } else {
- upb_def_unref(def, s);
- }
- }
- }
- upb_strtable_uninit(&addtab);
- upb_gfree(add_defs);
- UPB_ASSERT(!upb_ok(status));
- return false;
-}
+struct upb_bufsink {
+ upb_byteshandler handler;
+ upb_bytessink sink;
+ upb_env *env;
+ char *ptr;
+ size_t len, size;
+};
-bool upb_symtab_add(upb_symtab *s, upb_def *const*defs, size_t n,
- void *ref_donor, upb_status *status) {
- return symtab_add(s, defs, n, ref_donor, NULL, status);
+static void *upb_bufsink_start(void *_sink, const void *hd, size_t size_hint) {
+ upb_bufsink *sink = _sink;
+ UPB_UNUSED(hd);
+ UPB_UNUSED(size_hint);
+ sink->len = 0;
+ return sink;
}
-bool upb_symtab_addfile(upb_symtab *s, upb_filedef *file, upb_status *status) {
- size_t n;
- size_t i;
- upb_def **defs;
- bool ret;
+static size_t upb_bufsink_string(void *_sink, const void *hd, const char *ptr,
+ size_t len, const upb_bufhandle *handle) {
+ upb_bufsink *sink = _sink;
+ size_t new_size = sink->size;
- n = upb_filedef_defcount(file);
- defs = upb_gmalloc(sizeof(*defs) * n);
+ UPB_ASSERT(new_size > 0);
+ UPB_UNUSED(hd);
+ UPB_UNUSED(handle);
- if (defs == NULL) {
- upb_status_seterrmsg(status, "Out of memory");
- return false;
+ while (sink->len + len > new_size) {
+ new_size *= 2;
}
- for (i = 0; i < n; i++) {
- defs[i] = upb_filedef_mutabledef(file, i);
+ if (new_size != sink->size) {
+ sink->ptr = upb_env_realloc(sink->env, sink->ptr, sink->size, new_size);
+ sink->size = new_size;
}
- ret = symtab_add(s, defs, n, NULL, upb_filedef_upcast_mutable(file), status);
+ memcpy(sink->ptr + sink->len, ptr, len);
+ sink->len += len;
- upb_gfree(defs);
- return ret;
+ return len;
}
-/* Iteration. */
+upb_bufsink *upb_bufsink_new(upb_env *env) {
+ upb_bufsink *sink = upb_env_malloc(env, sizeof(upb_bufsink));
+ upb_byteshandler_init(&sink->handler);
+ upb_byteshandler_setstartstr(&sink->handler, upb_bufsink_start, NULL);
+ upb_byteshandler_setstring(&sink->handler, upb_bufsink_string, NULL);
-static void advance_to_matching(upb_symtab_iter *iter) {
- if (iter->type == UPB_DEF_ANY)
- return;
+ upb_bytessink_reset(&sink->sink, &sink->handler, sink);
- while (!upb_strtable_done(&iter->iter) &&
- iter->type != upb_symtab_iter_def(iter)->type) {
- upb_strtable_next(&iter->iter);
- }
-}
+ sink->env = env;
+ sink->size = 32;
+ sink->ptr = upb_env_malloc(env, sink->size);
+ sink->len = 0;
-void upb_symtab_begin(upb_symtab_iter *iter, const upb_symtab *s,
- upb_deftype_t type) {
- upb_strtable_begin(&iter->iter, &s->symtab);
- iter->type = type;
- advance_to_matching(iter);
+ return sink;
}
-void upb_symtab_next(upb_symtab_iter *iter) {
- upb_strtable_next(&iter->iter);
- advance_to_matching(iter);
+void upb_bufsink_free(upb_bufsink *sink) {
+ upb_env_free(sink->env, sink->ptr);
+ upb_env_free(sink->env, sink);
}
-bool upb_symtab_done(const upb_symtab_iter *iter) {
- return upb_strtable_done(&iter->iter);
+upb_bytessink *upb_bufsink_sink(upb_bufsink *sink) {
+ return &sink->sink;
}
-const upb_def *upb_symtab_iter_def(const upb_symtab_iter *iter) {
- return upb_value_getptr(upb_strtable_iter_value(&iter->iter));
+const char *upb_bufsink_getdata(const upb_bufsink *sink, size_t *len) {
+ *len = sink->len;
+ return sink->ptr;
}
/*
** upb_table Implementation
@@ -5285,7 +7162,7 @@ upb_alloc upb_alloc_global = {&upb_global_allocfunc};
/* Be conservative and choose 16 in case anyone is using SSE. */
static const size_t maxalign = 16;
-static size_t align_up(size_t size) {
+static size_t align_up_max(size_t size) {
return ((size + maxalign - 1) / maxalign) * maxalign;
}
@@ -5309,7 +7186,7 @@ static void upb_arena_addblock(upb_arena *a, void *ptr, size_t size,
block->next = a->block_head;
block->size = size;
- block->used = align_up(sizeof(mem_block));
+ block->used = align_up_max(sizeof(mem_block));
block->owned = owned;
a->block_head = block;
@@ -5342,7 +7219,7 @@ static void *upb_arena_doalloc(upb_alloc *alloc, void *ptr, size_t oldsize,
return NULL; /* We are an arena, don't need individual frees. */
}
- size = align_up(size);
+ size = align_up_max(size);
/* TODO(haberman): special-case if this is a realloc of the last alloc? */
@@ -5412,6 +7289,10 @@ void upb_arena_uninit(upb_arena *a) {
block = next;
}
+
+ /* Protect against multiple-uninit. */
+ a->cleanup_head = NULL;
+ a->block_head = NULL;
}
bool upb_arena_addcleanup(upb_arena *a, upb_cleanup_func *func, void *ud) {
@@ -5514,162 +7395,164 @@ size_t upb_env_bytesallocated(const upb_env *e) {
static const upb_msgdef msgs[22];
-static const upb_fielddef fields[105];
+static const upb_fielddef fields[107];
static const upb_enumdef enums[5];
static const upb_tabent strentries[236];
static const upb_tabent intentries[18];
-static const upb_tabval arrays[184];
+static const upb_tabval arrays[187];
#ifdef UPB_DEBUG_REFS
-static upb_inttable reftables[264];
+static upb_inttable reftables[268];
#endif
static const upb_msgdef msgs[22] = {
- UPB_MSGDEF_INIT("google.protobuf.DescriptorProto", 40, 8, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[0], 11, 10), UPB_STRTABLE_INIT(10, 15, UPB_CTYPE_PTR, 4, &strentries[0]), false, UPB_SYNTAX_PROTO2, &reftables[0], &reftables[1]),
- UPB_MSGDEF_INIT("google.protobuf.DescriptorProto.ExtensionRange", 4, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[11], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[16]), false, UPB_SYNTAX_PROTO2, &reftables[2], &reftables[3]),
- UPB_MSGDEF_INIT("google.protobuf.DescriptorProto.ReservedRange", 4, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[14], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[20]), false, UPB_SYNTAX_PROTO2, &reftables[4], &reftables[5]),
- UPB_MSGDEF_INIT("google.protobuf.EnumDescriptorProto", 11, 2, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[17], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[24]), false, UPB_SYNTAX_PROTO2, &reftables[6], &reftables[7]),
- UPB_MSGDEF_INIT("google.protobuf.EnumOptions", 8, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[0], &arrays[21], 4, 2), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[28]), false, UPB_SYNTAX_PROTO2, &reftables[8], &reftables[9]),
- UPB_MSGDEF_INIT("google.protobuf.EnumValueDescriptorProto", 8, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[25], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[32]), false, UPB_SYNTAX_PROTO2, &reftables[10], &reftables[11]),
- UPB_MSGDEF_INIT("google.protobuf.EnumValueOptions", 7, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[2], &arrays[29], 2, 1), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[36]), false, UPB_SYNTAX_PROTO2, &reftables[12], &reftables[13]),
- UPB_MSGDEF_INIT("google.protobuf.FieldDescriptorProto", 23, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[31], 11, 10), UPB_STRTABLE_INIT(10, 15, UPB_CTYPE_PTR, 4, &strentries[40]), false, UPB_SYNTAX_PROTO2, &reftables[14], &reftables[15]),
- UPB_MSGDEF_INIT("google.protobuf.FieldOptions", 12, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[4], &arrays[42], 11, 6), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[56]), false, UPB_SYNTAX_PROTO2, &reftables[16], &reftables[17]),
- UPB_MSGDEF_INIT("google.protobuf.FileDescriptorProto", 42, 6, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[53], 13, 12), UPB_STRTABLE_INIT(12, 15, UPB_CTYPE_PTR, 4, &strentries[72]), false, UPB_SYNTAX_PROTO2, &reftables[18], &reftables[19]),
- UPB_MSGDEF_INIT("google.protobuf.FileDescriptorSet", 6, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[66], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[88]), false, UPB_SYNTAX_PROTO2, &reftables[20], &reftables[21]),
- UPB_MSGDEF_INIT("google.protobuf.FileOptions", 31, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[6], &arrays[68], 39, 15), UPB_STRTABLE_INIT(16, 31, UPB_CTYPE_PTR, 5, &strentries[92]), false, UPB_SYNTAX_PROTO2, &reftables[22], &reftables[23]),
- UPB_MSGDEF_INIT("google.protobuf.MessageOptions", 10, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[8], &arrays[107], 8, 4), UPB_STRTABLE_INIT(5, 7, UPB_CTYPE_PTR, 3, &strentries[124]), false, UPB_SYNTAX_PROTO2, &reftables[24], &reftables[25]),
- UPB_MSGDEF_INIT("google.protobuf.MethodDescriptorProto", 15, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[115], 7, 6), UPB_STRTABLE_INIT(6, 7, UPB_CTYPE_PTR, 3, &strentries[132]), false, UPB_SYNTAX_PROTO2, &reftables[26], &reftables[27]),
- UPB_MSGDEF_INIT("google.protobuf.MethodOptions", 7, 1, UPB_INTTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &intentries[10], &arrays[122], 1, 0), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[140]), false, UPB_SYNTAX_PROTO2, &reftables[28], &reftables[29]),
- UPB_MSGDEF_INIT("google.protobuf.OneofDescriptorProto", 5, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[123], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[144]), false, UPB_SYNTAX_PROTO2, &reftables[30], &reftables[31]),
- UPB_MSGDEF_INIT("google.protobuf.ServiceDescriptorProto", 11, 2, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[125], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[148]), false, UPB_SYNTAX_PROTO2, &reftables[32], &reftables[33]),
- UPB_MSGDEF_INIT("google.protobuf.ServiceOptions", 7, 1, UPB_INTTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &intentries[14], &arrays[129], 1, 0), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[152]), false, UPB_SYNTAX_PROTO2, &reftables[34], &reftables[35]),
- UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo", 6, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[130], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[156]), false, UPB_SYNTAX_PROTO2, &reftables[36], &reftables[37]),
- UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo.Location", 19, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[132], 7, 5), UPB_STRTABLE_INIT(5, 7, UPB_CTYPE_PTR, 3, &strentries[160]), false, UPB_SYNTAX_PROTO2, &reftables[38], &reftables[39]),
- UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption", 18, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[139], 9, 7), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[168]), false, UPB_SYNTAX_PROTO2, &reftables[40], &reftables[41]),
- UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption.NamePart", 6, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[148], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[184]), false, UPB_SYNTAX_PROTO2, &reftables[42], &reftables[43]),
+ UPB_MSGDEF_INIT("google.protobuf.DescriptorProto", 41, 8, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[0], 11, 10), UPB_STRTABLE_INIT(10, 15, UPB_CTYPE_PTR, 4, &strentries[0]), false, UPB_SYNTAX_PROTO2, &reftables[0], &reftables[1]),
+ UPB_MSGDEF_INIT("google.protobuf.DescriptorProto.ExtensionRange", 5, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[11], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[16]), false, UPB_SYNTAX_PROTO2, &reftables[2], &reftables[3]),
+ UPB_MSGDEF_INIT("google.protobuf.DescriptorProto.ReservedRange", 5, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[14], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[20]), false, UPB_SYNTAX_PROTO2, &reftables[4], &reftables[5]),
+ UPB_MSGDEF_INIT("google.protobuf.EnumDescriptorProto", 12, 2, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[17], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[24]), false, UPB_SYNTAX_PROTO2, &reftables[6], &reftables[7]),
+ UPB_MSGDEF_INIT("google.protobuf.EnumOptions", 9, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[0], &arrays[21], 4, 2), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[28]), false, UPB_SYNTAX_PROTO2, &reftables[8], &reftables[9]),
+ UPB_MSGDEF_INIT("google.protobuf.EnumValueDescriptorProto", 9, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[25], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[32]), false, UPB_SYNTAX_PROTO2, &reftables[10], &reftables[11]),
+ UPB_MSGDEF_INIT("google.protobuf.EnumValueOptions", 8, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[2], &arrays[29], 2, 1), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[36]), false, UPB_SYNTAX_PROTO2, &reftables[12], &reftables[13]),
+ UPB_MSGDEF_INIT("google.protobuf.FieldDescriptorProto", 24, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[31], 11, 10), UPB_STRTABLE_INIT(10, 15, UPB_CTYPE_PTR, 4, &strentries[40]), false, UPB_SYNTAX_PROTO2, &reftables[14], &reftables[15]),
+ UPB_MSGDEF_INIT("google.protobuf.FieldOptions", 13, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[4], &arrays[42], 11, 6), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[56]), false, UPB_SYNTAX_PROTO2, &reftables[16], &reftables[17]),
+ UPB_MSGDEF_INIT("google.protobuf.FileDescriptorProto", 43, 6, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[53], 13, 12), UPB_STRTABLE_INIT(12, 15, UPB_CTYPE_PTR, 4, &strentries[72]), false, UPB_SYNTAX_PROTO2, &reftables[18], &reftables[19]),
+ UPB_MSGDEF_INIT("google.protobuf.FileDescriptorSet", 7, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[66], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[88]), false, UPB_SYNTAX_PROTO2, &reftables[20], &reftables[21]),
+ UPB_MSGDEF_INIT("google.protobuf.FileOptions", 38, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[6], &arrays[68], 42, 17), UPB_STRTABLE_INIT(18, 31, UPB_CTYPE_PTR, 5, &strentries[92]), false, UPB_SYNTAX_PROTO2, &reftables[22], &reftables[23]),
+ UPB_MSGDEF_INIT("google.protobuf.MessageOptions", 11, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[8], &arrays[110], 8, 4), UPB_STRTABLE_INIT(5, 7, UPB_CTYPE_PTR, 3, &strentries[124]), false, UPB_SYNTAX_PROTO2, &reftables[24], &reftables[25]),
+ UPB_MSGDEF_INIT("google.protobuf.MethodDescriptorProto", 16, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[118], 7, 6), UPB_STRTABLE_INIT(6, 7, UPB_CTYPE_PTR, 3, &strentries[132]), false, UPB_SYNTAX_PROTO2, &reftables[26], &reftables[27]),
+ UPB_MSGDEF_INIT("google.protobuf.MethodOptions", 8, 1, UPB_INTTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &intentries[10], &arrays[125], 1, 0), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[140]), false, UPB_SYNTAX_PROTO2, &reftables[28], &reftables[29]),
+ UPB_MSGDEF_INIT("google.protobuf.OneofDescriptorProto", 6, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[126], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[144]), false, UPB_SYNTAX_PROTO2, &reftables[30], &reftables[31]),
+ UPB_MSGDEF_INIT("google.protobuf.ServiceDescriptorProto", 12, 2, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[128], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[148]), false, UPB_SYNTAX_PROTO2, &reftables[32], &reftables[33]),
+ UPB_MSGDEF_INIT("google.protobuf.ServiceOptions", 8, 1, UPB_INTTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &intentries[14], &arrays[132], 1, 0), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[152]), false, UPB_SYNTAX_PROTO2, &reftables[34], &reftables[35]),
+ UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo", 7, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[133], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[156]), false, UPB_SYNTAX_PROTO2, &reftables[36], &reftables[37]),
+ UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo.Location", 20, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[135], 7, 5), UPB_STRTABLE_INIT(5, 7, UPB_CTYPE_PTR, 3, &strentries[160]), false, UPB_SYNTAX_PROTO2, &reftables[38], &reftables[39]),
+ UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption", 19, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[142], 9, 7), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[168]), false, UPB_SYNTAX_PROTO2, &reftables[40], &reftables[41]),
+ UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption.NamePart", 7, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[151], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[184]), false, UPB_SYNTAX_PROTO2, &reftables[42], &reftables[43]),
};
-static const upb_fielddef fields[105] = {
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "aggregate_value", 8, &msgs[20], NULL, 15, 6, {0},&reftables[44], &reftables[45]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "allow_alias", 2, &msgs[4], NULL, 6, 1, {0},&reftables[46], &reftables[47]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "cc_enable_arenas", 31, &msgs[11], NULL, 23, 12, {0},&reftables[48], &reftables[49]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "cc_generic_services", 16, &msgs[11], NULL, 17, 6, {0},&reftables[50], &reftables[51]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "client_streaming", 5, &msgs[13], NULL, 13, 4, {0},&reftables[52], &reftables[53]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "csharp_namespace", 37, &msgs[11], NULL, 27, 14, {0},&reftables[54], &reftables[55]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "ctype", 1, &msgs[8], (const upb_def*)(&enums[2]), 6, 1, {0},&reftables[56], &reftables[57]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "default_value", 7, &msgs[7], NULL, 16, 7, {0},&reftables[58], &reftables[59]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "dependency", 3, &msgs[9], NULL, 30, 8, {0},&reftables[60], &reftables[61]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[12], NULL, 8, 3, {0},&reftables[62], &reftables[63]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[8], NULL, 8, 3, {0},&reftables[64], &reftables[65]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 33, &msgs[14], NULL, 6, 1, {0},&reftables[66], &reftables[67]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 23, &msgs[11], NULL, 21, 10, {0},&reftables[68], &reftables[69]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[4], NULL, 7, 2, {0},&reftables[70], &reftables[71]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 33, &msgs[17], NULL, 6, 1, {0},&reftables[72], &reftables[73]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 1, &msgs[6], NULL, 6, 1, {0},&reftables[74], &reftables[75]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_DOUBLE, 0, false, false, false, false, "double_value", 6, &msgs[20], NULL, 11, 4, {0},&reftables[76], &reftables[77]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "end", 2, &msgs[2], NULL, 3, 1, {0},&reftables[78], &reftables[79]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "end", 2, &msgs[1], NULL, 3, 1, {0},&reftables[80], &reftables[81]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "enum_type", 4, &msgs[0], (const upb_def*)(&msgs[3]), 18, 2, {0},&reftables[82], &reftables[83]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "enum_type", 5, &msgs[9], (const upb_def*)(&msgs[3]), 13, 1, {0},&reftables[84], &reftables[85]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "extendee", 2, &msgs[7], NULL, 7, 2, {0},&reftables[86], &reftables[87]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension", 6, &msgs[0], (const upb_def*)(&msgs[7]), 24, 4, {0},&reftables[88], &reftables[89]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension", 7, &msgs[9], (const upb_def*)(&msgs[7]), 19, 3, {0},&reftables[90], &reftables[91]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension_range", 5, &msgs[0], (const upb_def*)(&msgs[1]), 21, 3, {0},&reftables[92], &reftables[93]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "field", 2, &msgs[0], (const upb_def*)(&msgs[7]), 12, 0, {0},&reftables[94], &reftables[95]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "file", 1, &msgs[10], (const upb_def*)(&msgs[9]), 5, 0, {0},&reftables[96], &reftables[97]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "go_package", 11, &msgs[11], NULL, 14, 5, {0},&reftables[98], &reftables[99]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "identifier_value", 3, &msgs[20], NULL, 6, 1, {0},&reftables[100], &reftables[101]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "input_type", 2, &msgs[13], NULL, 7, 2, {0},&reftables[102], &reftables[103]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REQUIRED, UPB_TYPE_BOOL, 0, false, false, false, false, "is_extension", 2, &msgs[21], NULL, 5, 1, {0},&reftables[104], &reftables[105]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_generate_equals_and_hash", 20, &msgs[11], NULL, 20, 9, {0},&reftables[106], &reftables[107]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_generic_services", 17, &msgs[11], NULL, 18, 7, {0},&reftables[108], &reftables[109]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_multiple_files", 10, &msgs[11], NULL, 13, 4, {0},&reftables[110], &reftables[111]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "java_outer_classname", 8, &msgs[11], NULL, 9, 2, {0},&reftables[112], &reftables[113]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "java_package", 1, &msgs[11], NULL, 6, 1, {0},&reftables[114], &reftables[115]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_string_check_utf8", 27, &msgs[11], NULL, 22, 11, {0},&reftables[116], &reftables[117]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "javanano_use_deprecated_package", 38, &msgs[11], NULL, 30, 15, {0},&reftables[118], &reftables[119]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "json_name", 10, &msgs[7], NULL, 20, 9, {0},&reftables[120], &reftables[121]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "jstype", 6, &msgs[8], (const upb_def*)(&enums[3]), 10, 5, {0},&reftables[122], &reftables[123]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "label", 4, &msgs[7], (const upb_def*)(&enums[0]), 11, 4, {0},&reftables[124], &reftables[125]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "lazy", 5, &msgs[8], NULL, 9, 4, {0},&reftables[126], &reftables[127]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "leading_comments", 3, &msgs[19], NULL, 8, 2, {0},&reftables[128], &reftables[129]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "leading_detached_comments", 6, &msgs[19], NULL, 16, 4, {0},&reftables[130], &reftables[131]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "location", 1, &msgs[18], (const upb_def*)(&msgs[19]), 5, 0, {0},&reftables[132], &reftables[133]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "map_entry", 7, &msgs[12], NULL, 9, 4, {0},&reftables[134], &reftables[135]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "message_set_wire_format", 1, &msgs[12], NULL, 6, 1, {0},&reftables[136], &reftables[137]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "message_type", 4, &msgs[9], (const upb_def*)(&msgs[0]), 10, 0, {0},&reftables[138], &reftables[139]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "method", 2, &msgs[16], (const upb_def*)(&msgs[13]), 6, 0, {0},&reftables[140], &reftables[141]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[3], NULL, 8, 2, {0},&reftables[142], &reftables[143]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[15], NULL, 2, 0, {0},&reftables[144], &reftables[145]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "name", 2, &msgs[20], (const upb_def*)(&msgs[21]), 5, 0, {0},&reftables[146], &reftables[147]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[0], NULL, 32, 8, {0},&reftables[148], &reftables[149]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[5], NULL, 4, 1, {0},&reftables[150], &reftables[151]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[9], NULL, 22, 6, {0},&reftables[152], &reftables[153]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[7], NULL, 4, 1, {0},&reftables[154], &reftables[155]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[13], NULL, 4, 1, {0},&reftables[156], &reftables[157]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[16], NULL, 8, 2, {0},&reftables[158], &reftables[159]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REQUIRED, UPB_TYPE_STRING, 0, false, false, false, false, "name_part", 1, &msgs[21], NULL, 2, 0, {0},&reftables[160], &reftables[161]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT64, UPB_INTFMT_VARIABLE, false, false, false, false, "negative_int_value", 5, &msgs[20], NULL, 10, 3, {0},&reftables[162], &reftables[163]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "nested_type", 3, &msgs[0], (const upb_def*)(&msgs[0]), 15, 1, {0},&reftables[164], &reftables[165]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "no_standard_descriptor_accessor", 2, &msgs[12], NULL, 7, 2, {0},&reftables[166], &reftables[167]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "number", 2, &msgs[5], NULL, 7, 2, {0},&reftables[168], &reftables[169]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "number", 3, &msgs[7], NULL, 10, 3, {0},&reftables[170], &reftables[171]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "objc_class_prefix", 36, &msgs[11], NULL, 24, 13, {0},&reftables[172], &reftables[173]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "oneof_decl", 8, &msgs[0], (const upb_def*)(&msgs[15]), 28, 6, {0},&reftables[174], &reftables[175]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "oneof_index", 9, &msgs[7], NULL, 19, 8, {0},&reftables[176], &reftables[177]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "optimize_for", 9, &msgs[11], (const upb_def*)(&enums[4]), 12, 3, {0},&reftables[178], &reftables[179]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 7, &msgs[0], (const upb_def*)(&msgs[12]), 25, 5, {0},&reftables[180], &reftables[181]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 8, &msgs[9], (const upb_def*)(&msgs[11]), 20, 4, {0},&reftables[182], &reftables[183]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 4, &msgs[13], (const upb_def*)(&msgs[14]), 3, 0, {0},&reftables[184], &reftables[185]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 8, &msgs[7], (const upb_def*)(&msgs[8]), 3, 0, {0},&reftables[186], &reftables[187]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[16], (const upb_def*)(&msgs[17]), 7, 1, {0},&reftables[188], &reftables[189]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[5], (const upb_def*)(&msgs[6]), 3, 0, {0},&reftables[190], &reftables[191]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[3], (const upb_def*)(&msgs[4]), 7, 1, {0},&reftables[192], &reftables[193]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "output_type", 3, &msgs[13], NULL, 10, 3, {0},&reftables[194], &reftables[195]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "package", 2, &msgs[9], NULL, 25, 7, {0},&reftables[196], &reftables[197]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "packed", 2, &msgs[8], NULL, 7, 2, {0},&reftables[198], &reftables[199]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, true, "path", 1, &msgs[19], NULL, 4, 0, {0},&reftables[200], &reftables[201]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_UINT64, UPB_INTFMT_VARIABLE, false, false, false, false, "positive_int_value", 4, &msgs[20], NULL, 9, 2, {0},&reftables[202], &reftables[203]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "public_dependency", 10, &msgs[9], NULL, 35, 9, {0},&reftables[204], &reftables[205]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "py_generic_services", 18, &msgs[11], NULL, 19, 8, {0},&reftables[206], &reftables[207]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "reserved_name", 10, &msgs[0], NULL, 37, 9, {0},&reftables[208], &reftables[209]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "reserved_range", 9, &msgs[0], (const upb_def*)(&msgs[2]), 31, 7, {0},&reftables[210], &reftables[211]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "server_streaming", 6, &msgs[13], NULL, 14, 5, {0},&reftables[212], &reftables[213]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "service", 6, &msgs[9], (const upb_def*)(&msgs[16]), 16, 2, {0},&reftables[214], &reftables[215]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "source_code_info", 9, &msgs[9], (const upb_def*)(&msgs[18]), 21, 5, {0},&reftables[216], &reftables[217]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, true, "span", 2, &msgs[19], NULL, 7, 1, {0},&reftables[218], &reftables[219]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "start", 1, &msgs[2], NULL, 2, 0, {0},&reftables[220], &reftables[221]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "start", 1, &msgs[1], NULL, 2, 0, {0},&reftables[222], &reftables[223]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BYTES, 0, false, false, false, false, "string_value", 7, &msgs[20], NULL, 12, 5, {0},&reftables[224], &reftables[225]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "syntax", 12, &msgs[9], NULL, 39, 11, {0},&reftables[226], &reftables[227]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "trailing_comments", 4, &msgs[19], NULL, 11, 3, {0},&reftables[228], &reftables[229]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "type", 5, &msgs[7], (const upb_def*)(&enums[1]), 12, 5, {0},&reftables[230], &reftables[231]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "type_name", 6, &msgs[7], NULL, 13, 6, {0},&reftables[232], &reftables[233]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[11], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[234], &reftables[235]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[12], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[236], &reftables[237]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[6], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[238], &reftables[239]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[4], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[240], &reftables[241]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[8], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[242], &reftables[243]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[14], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[244], &reftables[245]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[17], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[246], &reftables[247]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "value", 2, &msgs[3], (const upb_def*)(&msgs[5]), 6, 0, {0},&reftables[248], &reftables[249]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "weak", 10, &msgs[8], NULL, 11, 6, {0},&reftables[250], &reftables[251]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "weak_dependency", 11, &msgs[9], NULL, 38, 10, {0},&reftables[252], &reftables[253]),
+static const upb_fielddef fields[107] = {
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "aggregate_value", 8, &msgs[20], NULL, 16, 6, {0},&reftables[44], &reftables[45]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "allow_alias", 2, &msgs[4], NULL, 7, 1, {0},&reftables[46], &reftables[47]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "cc_enable_arenas", 31, &msgs[11], NULL, 24, 12, {0},&reftables[48], &reftables[49]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "cc_generic_services", 16, &msgs[11], NULL, 18, 6, {0},&reftables[50], &reftables[51]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "client_streaming", 5, &msgs[13], NULL, 14, 4, {0},&reftables[52], &reftables[53]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "csharp_namespace", 37, &msgs[11], NULL, 28, 14, {0},&reftables[54], &reftables[55]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "ctype", 1, &msgs[8], (const upb_def*)(&enums[2]), 7, 1, {0},&reftables[56], &reftables[57]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "default_value", 7, &msgs[7], NULL, 17, 7, {0},&reftables[58], &reftables[59]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "dependency", 3, &msgs[9], NULL, 31, 8, {0},&reftables[60], &reftables[61]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[8], NULL, 9, 3, {0},&reftables[62], &reftables[63]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 33, &msgs[14], NULL, 7, 1, {0},&reftables[64], &reftables[65]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[12], NULL, 9, 3, {0},&reftables[66], &reftables[67]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 23, &msgs[11], NULL, 22, 10, {0},&reftables[68], &reftables[69]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 1, &msgs[6], NULL, 7, 1, {0},&reftables[70], &reftables[71]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[4], NULL, 8, 2, {0},&reftables[72], &reftables[73]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 33, &msgs[17], NULL, 7, 1, {0},&reftables[74], &reftables[75]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_DOUBLE, 0, false, false, false, false, "double_value", 6, &msgs[20], NULL, 12, 4, {0},&reftables[76], &reftables[77]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "end", 2, &msgs[2], NULL, 4, 1, {0},&reftables[78], &reftables[79]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "end", 2, &msgs[1], NULL, 4, 1, {0},&reftables[80], &reftables[81]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "enum_type", 5, &msgs[9], (const upb_def*)(&msgs[3]), 14, 1, {0},&reftables[82], &reftables[83]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "enum_type", 4, &msgs[0], (const upb_def*)(&msgs[3]), 19, 2, {0},&reftables[84], &reftables[85]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "extendee", 2, &msgs[7], NULL, 8, 2, {0},&reftables[86], &reftables[87]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension", 6, &msgs[0], (const upb_def*)(&msgs[7]), 25, 4, {0},&reftables[88], &reftables[89]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension", 7, &msgs[9], (const upb_def*)(&msgs[7]), 20, 3, {0},&reftables[90], &reftables[91]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension_range", 5, &msgs[0], (const upb_def*)(&msgs[1]), 22, 3, {0},&reftables[92], &reftables[93]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "field", 2, &msgs[0], (const upb_def*)(&msgs[7]), 13, 0, {0},&reftables[94], &reftables[95]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "file", 1, &msgs[10], (const upb_def*)(&msgs[9]), 6, 0, {0},&reftables[96], &reftables[97]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "go_package", 11, &msgs[11], NULL, 15, 5, {0},&reftables[98], &reftables[99]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "identifier_value", 3, &msgs[20], NULL, 7, 1, {0},&reftables[100], &reftables[101]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "input_type", 2, &msgs[13], NULL, 8, 2, {0},&reftables[102], &reftables[103]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REQUIRED, UPB_TYPE_BOOL, 0, false, false, false, false, "is_extension", 2, &msgs[21], NULL, 6, 1, {0},&reftables[104], &reftables[105]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_generate_equals_and_hash", 20, &msgs[11], NULL, 21, 9, {0},&reftables[106], &reftables[107]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_generic_services", 17, &msgs[11], NULL, 19, 7, {0},&reftables[108], &reftables[109]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_multiple_files", 10, &msgs[11], NULL, 14, 4, {0},&reftables[110], &reftables[111]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "java_outer_classname", 8, &msgs[11], NULL, 10, 2, {0},&reftables[112], &reftables[113]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "java_package", 1, &msgs[11], NULL, 7, 1, {0},&reftables[114], &reftables[115]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_string_check_utf8", 27, &msgs[11], NULL, 23, 11, {0},&reftables[116], &reftables[117]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "javanano_use_deprecated_package", 38, &msgs[11], NULL, 31, 15, {0},&reftables[118], &reftables[119]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "json_name", 10, &msgs[7], NULL, 21, 9, {0},&reftables[120], &reftables[121]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "jstype", 6, &msgs[8], (const upb_def*)(&enums[3]), 11, 5, {0},&reftables[122], &reftables[123]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "label", 4, &msgs[7], (const upb_def*)(&enums[0]), 12, 4, {0},&reftables[124], &reftables[125]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "lazy", 5, &msgs[8], NULL, 10, 4, {0},&reftables[126], &reftables[127]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "leading_comments", 3, &msgs[19], NULL, 9, 2, {0},&reftables[128], &reftables[129]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "leading_detached_comments", 6, &msgs[19], NULL, 17, 4, {0},&reftables[130], &reftables[131]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "location", 1, &msgs[18], (const upb_def*)(&msgs[19]), 6, 0, {0},&reftables[132], &reftables[133]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "map_entry", 7, &msgs[12], NULL, 10, 4, {0},&reftables[134], &reftables[135]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "message_set_wire_format", 1, &msgs[12], NULL, 7, 1, {0},&reftables[136], &reftables[137]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "message_type", 4, &msgs[9], (const upb_def*)(&msgs[0]), 11, 0, {0},&reftables[138], &reftables[139]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "method", 2, &msgs[16], (const upb_def*)(&msgs[13]), 7, 0, {0},&reftables[140], &reftables[141]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "name", 2, &msgs[20], (const upb_def*)(&msgs[21]), 6, 0, {0},&reftables[142], &reftables[143]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[5], NULL, 5, 1, {0},&reftables[144], &reftables[145]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[9], NULL, 23, 6, {0},&reftables[146], &reftables[147]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[3], NULL, 9, 2, {0},&reftables[148], &reftables[149]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[16], NULL, 9, 2, {0},&reftables[150], &reftables[151]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[15], NULL, 3, 0, {0},&reftables[152], &reftables[153]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[13], NULL, 5, 1, {0},&reftables[154], &reftables[155]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[7], NULL, 5, 1, {0},&reftables[156], &reftables[157]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[0], NULL, 33, 8, {0},&reftables[158], &reftables[159]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REQUIRED, UPB_TYPE_STRING, 0, false, false, false, false, "name_part", 1, &msgs[21], NULL, 3, 0, {0},&reftables[160], &reftables[161]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT64, UPB_INTFMT_VARIABLE, false, false, false, false, "negative_int_value", 5, &msgs[20], NULL, 11, 3, {0},&reftables[162], &reftables[163]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "nested_type", 3, &msgs[0], (const upb_def*)(&msgs[0]), 16, 1, {0},&reftables[164], &reftables[165]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "no_standard_descriptor_accessor", 2, &msgs[12], NULL, 8, 2, {0},&reftables[166], &reftables[167]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "number", 3, &msgs[7], NULL, 11, 3, {0},&reftables[168], &reftables[169]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "number", 2, &msgs[5], NULL, 8, 2, {0},&reftables[170], &reftables[171]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "objc_class_prefix", 36, &msgs[11], NULL, 25, 13, {0},&reftables[172], &reftables[173]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "oneof_decl", 8, &msgs[0], (const upb_def*)(&msgs[15]), 29, 6, {0},&reftables[174], &reftables[175]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "oneof_index", 9, &msgs[7], NULL, 20, 8, {0},&reftables[176], &reftables[177]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "optimize_for", 9, &msgs[11], (const upb_def*)(&enums[4]), 13, 3, {0},&reftables[178], &reftables[179]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 7, &msgs[0], (const upb_def*)(&msgs[12]), 26, 5, {0},&reftables[180], &reftables[181]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 8, &msgs[9], (const upb_def*)(&msgs[11]), 21, 4, {0},&reftables[182], &reftables[183]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 8, &msgs[7], (const upb_def*)(&msgs[8]), 4, 0, {0},&reftables[184], &reftables[185]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 4, &msgs[13], (const upb_def*)(&msgs[14]), 4, 0, {0},&reftables[186], &reftables[187]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[16], (const upb_def*)(&msgs[17]), 8, 1, {0},&reftables[188], &reftables[189]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[3], (const upb_def*)(&msgs[4]), 8, 1, {0},&reftables[190], &reftables[191]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[5], (const upb_def*)(&msgs[6]), 4, 0, {0},&reftables[192], &reftables[193]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "output_type", 3, &msgs[13], NULL, 11, 3, {0},&reftables[194], &reftables[195]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "package", 2, &msgs[9], NULL, 26, 7, {0},&reftables[196], &reftables[197]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "packed", 2, &msgs[8], NULL, 8, 2, {0},&reftables[198], &reftables[199]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, true, "path", 1, &msgs[19], NULL, 5, 0, {0},&reftables[200], &reftables[201]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "php_class_prefix", 40, &msgs[11], NULL, 32, 16, {0},&reftables[202], &reftables[203]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "php_namespace", 41, &msgs[11], NULL, 35, 17, {0},&reftables[204], &reftables[205]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_UINT64, UPB_INTFMT_VARIABLE, false, false, false, false, "positive_int_value", 4, &msgs[20], NULL, 10, 2, {0},&reftables[206], &reftables[207]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "public_dependency", 10, &msgs[9], NULL, 36, 9, {0},&reftables[208], &reftables[209]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "py_generic_services", 18, &msgs[11], NULL, 20, 8, {0},&reftables[210], &reftables[211]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "reserved_name", 10, &msgs[0], NULL, 38, 9, {0},&reftables[212], &reftables[213]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "reserved_range", 9, &msgs[0], (const upb_def*)(&msgs[2]), 32, 7, {0},&reftables[214], &reftables[215]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "server_streaming", 6, &msgs[13], NULL, 15, 5, {0},&reftables[216], &reftables[217]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "service", 6, &msgs[9], (const upb_def*)(&msgs[16]), 17, 2, {0},&reftables[218], &reftables[219]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "source_code_info", 9, &msgs[9], (const upb_def*)(&msgs[18]), 22, 5, {0},&reftables[220], &reftables[221]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, true, "span", 2, &msgs[19], NULL, 8, 1, {0},&reftables[222], &reftables[223]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "start", 1, &msgs[2], NULL, 3, 0, {0},&reftables[224], &reftables[225]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "start", 1, &msgs[1], NULL, 3, 0, {0},&reftables[226], &reftables[227]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BYTES, 0, false, false, false, false, "string_value", 7, &msgs[20], NULL, 13, 5, {0},&reftables[228], &reftables[229]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "syntax", 12, &msgs[9], NULL, 40, 11, {0},&reftables[230], &reftables[231]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "trailing_comments", 4, &msgs[19], NULL, 12, 3, {0},&reftables[232], &reftables[233]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "type", 5, &msgs[7], (const upb_def*)(&enums[1]), 13, 5, {0},&reftables[234], &reftables[235]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "type_name", 6, &msgs[7], NULL, 14, 6, {0},&reftables[236], &reftables[237]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[12], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[238], &reftables[239]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[17], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[240], &reftables[241]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[11], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[242], &reftables[243]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[14], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[244], &reftables[245]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[8], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[246], &reftables[247]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[6], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[248], &reftables[249]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[4], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[250], &reftables[251]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "value", 2, &msgs[3], (const upb_def*)(&msgs[5]), 7, 0, {0},&reftables[252], &reftables[253]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "weak", 10, &msgs[8], NULL, 12, 6, {0},&reftables[254], &reftables[255]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "weak_dependency", 11, &msgs[9], NULL, 39, 10, {0},&reftables[256], &reftables[257]),
};
static const upb_enumdef enums[5] = {
- UPB_ENUMDEF_INIT("google.protobuf.FieldDescriptorProto.Label", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[188]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[151], 4, 3), 0, &reftables[254], &reftables[255]),
- UPB_ENUMDEF_INIT("google.protobuf.FieldDescriptorProto.Type", UPB_STRTABLE_INIT(18, 31, UPB_CTYPE_INT32, 5, &strentries[192]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[155], 19, 18), 0, &reftables[256], &reftables[257]),
- UPB_ENUMDEF_INIT("google.protobuf.FieldOptions.CType", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[224]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[174], 3, 3), 0, &reftables[258], &reftables[259]),
- UPB_ENUMDEF_INIT("google.protobuf.FieldOptions.JSType", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[228]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[177], 3, 3), 0, &reftables[260], &reftables[261]),
- UPB_ENUMDEF_INIT("google.protobuf.FileOptions.OptimizeMode", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[232]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[180], 4, 3), 0, &reftables[262], &reftables[263]),
+ UPB_ENUMDEF_INIT("google.protobuf.FieldDescriptorProto.Label", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[188]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[154], 4, 3), 0, &reftables[258], &reftables[259]),
+ UPB_ENUMDEF_INIT("google.protobuf.FieldDescriptorProto.Type", UPB_STRTABLE_INIT(18, 31, UPB_CTYPE_INT32, 5, &strentries[192]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[158], 19, 18), 0, &reftables[260], &reftables[261]),
+ UPB_ENUMDEF_INIT("google.protobuf.FieldOptions.CType", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[224]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[177], 3, 3), 0, &reftables[262], &reftables[263]),
+ UPB_ENUMDEF_INIT("google.protobuf.FieldOptions.JSType", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[228]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[180], 3, 3), 0, &reftables[264], &reftables[265]),
+ UPB_ENUMDEF_INIT("google.protobuf.FileOptions.OptimizeMode", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[232]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[183], 4, 3), 0, &reftables[266], &reftables[267]),
};
static const upb_tabent strentries[236] = {
{UPB_TABKEY_STR("\011", "\000", "\000", "\000", "extension"), UPB_TABVALUE_PTR_INIT(&fields[22]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "reserved_name"), UPB_TABVALUE_PTR_INIT(&fields[82]), NULL},
- {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[52]), NULL},
+ {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "reserved_name"), UPB_TABVALUE_PTR_INIT(&fields[84]), NULL},
+ {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[57]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
@@ -5678,53 +7561,53 @@ static const upb_tabent strentries[236] = {
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_STR("\013", "\000", "\000", "\000", "nested_type"), UPB_TABVALUE_PTR_INIT(&fields[60]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "reserved_range"), UPB_TABVALUE_PTR_INIT(&fields[83]), NULL},
+ {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "reserved_range"), UPB_TABVALUE_PTR_INIT(&fields[85]), NULL},
{UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[68]), NULL},
{UPB_TABKEY_STR("\012", "\000", "\000", "\000", "oneof_decl"), UPB_TABVALUE_PTR_INIT(&fields[65]), NULL},
- {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "enum_type"), UPB_TABVALUE_PTR_INIT(&fields[19]), &strentries[13]},
- {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "start"), UPB_TABVALUE_PTR_INIT(&fields[89]), NULL},
+ {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "enum_type"), UPB_TABVALUE_PTR_INIT(&fields[20]), &strentries[13]},
+ {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "start"), UPB_TABVALUE_PTR_INIT(&fields[91]), NULL},
{UPB_TABKEY_STR("\003", "\000", "\000", "\000", "end"), UPB_TABVALUE_PTR_INIT(&fields[18]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "start"), UPB_TABVALUE_PTR_INIT(&fields[88]), NULL},
+ {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "start"), UPB_TABVALUE_PTR_INIT(&fields[90]), NULL},
{UPB_TABKEY_STR("\003", "\000", "\000", "\000", "end"), UPB_TABVALUE_PTR_INIT(&fields[17]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "value"), UPB_TABVALUE_PTR_INIT(&fields[102]), NULL},
- {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[74]), NULL},
- {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[49]), &strentries[26]},
- {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[98]), NULL},
- {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[13]), NULL},
+ {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "value"), UPB_TABVALUE_PTR_INIT(&fields[104]), NULL},
+ {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[73]), NULL},
+ {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[52]), &strentries[26]},
+ {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[103]), NULL},
+ {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[14]), NULL},
{UPB_TABKEY_STR("\013", "\000", "\000", "\000", "allow_alias"), UPB_TABVALUE_PTR_INIT(&fields[1]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "number"), UPB_TABVALUE_PTR_INIT(&fields[62]), NULL},
+ {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "number"), UPB_TABVALUE_PTR_INIT(&fields[63]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[73]), NULL},
- {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[53]), &strentries[34]},
- {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[97]), NULL},
- {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[15]), NULL},
+ {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[74]), NULL},
+ {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[50]), &strentries[34]},
+ {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[102]), NULL},
+ {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[13]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_STR("\013", "\000", "\000", "\000", "oneof_index"), UPB_TABVALUE_PTR_INIT(&fields[66]), NULL},
{UPB_TABKEY_STR("\005", "\000", "\000", "\000", "label"), UPB_TABVALUE_PTR_INIT(&fields[40]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[55]), NULL},
+ {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[56]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "number"), UPB_TABVALUE_PTR_INIT(&fields[63]), &strentries[53]},
+ {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "number"), UPB_TABVALUE_PTR_INIT(&fields[62]), &strentries[53]},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_STR("\010", "\000", "\000", "\000", "extendee"), UPB_TABVALUE_PTR_INIT(&fields[21]), NULL},
- {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "type_name"), UPB_TABVALUE_PTR_INIT(&fields[94]), NULL},
+ {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "type_name"), UPB_TABVALUE_PTR_INIT(&fields[96]), NULL},
{UPB_TABKEY_STR("\011", "\000", "\000", "\000", "json_name"), UPB_TABVALUE_PTR_INIT(&fields[38]), NULL},
- {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "type"), UPB_TABVALUE_PTR_INIT(&fields[93]), &strentries[50]},
+ {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "type"), UPB_TABVALUE_PTR_INIT(&fields[95]), &strentries[50]},
{UPB_TABKEY_STR("\015", "\000", "\000", "\000", "default_value"), UPB_TABVALUE_PTR_INIT(&fields[7]), NULL},
- {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[71]), NULL},
- {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[99]), NULL},
+ {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[70]), NULL},
+ {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[101]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "weak"), UPB_TABVALUE_PTR_INIT(&fields[103]), NULL},
+ {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "weak"), UPB_TABVALUE_PTR_INIT(&fields[105]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
@@ -5735,25 +7618,25 @@ static const upb_tabent strentries[236] = {
{UPB_TABKEY_STR("\005", "\000", "\000", "\000", "ctype"), UPB_TABVALUE_PTR_INIT(&fields[6]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_STR("\006", "\000", "\000", "\000", "jstype"), UPB_TABVALUE_PTR_INIT(&fields[39]), NULL},
- {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[10]), NULL},
+ {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[9]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_STR("\011", "\000", "\000", "\000", "extension"), UPB_TABVALUE_PTR_INIT(&fields[23]), NULL},
- {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "weak_dependency"), UPB_TABVALUE_PTR_INIT(&fields[104]), NULL},
+ {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "weak_dependency"), UPB_TABVALUE_PTR_INIT(&fields[106]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[54]), NULL},
- {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "service"), UPB_TABVALUE_PTR_INIT(&fields[85]), NULL},
+ {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[51]), NULL},
+ {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "service"), UPB_TABVALUE_PTR_INIT(&fields[87]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "source_code_info"), UPB_TABVALUE_PTR_INIT(&fields[86]), NULL},
+ {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "source_code_info"), UPB_TABVALUE_PTR_INIT(&fields[88]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "syntax"), UPB_TABVALUE_PTR_INIT(&fields[91]), NULL},
+ {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "syntax"), UPB_TABVALUE_PTR_INIT(&fields[93]), NULL},
{UPB_TABKEY_STR("\012", "\000", "\000", "\000", "dependency"), UPB_TABVALUE_PTR_INIT(&fields[8]), NULL},
{UPB_TABKEY_STR("\014", "\000", "\000", "\000", "message_type"), UPB_TABVALUE_PTR_INIT(&fields[47]), NULL},
{UPB_TABKEY_STR("\007", "\000", "\000", "\000", "package"), UPB_TABVALUE_PTR_INIT(&fields[76]), NULL},
{UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[69]), &strentries[86]},
- {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "enum_type"), UPB_TABVALUE_PTR_INIT(&fields[20]), NULL},
- {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "public_dependency"), UPB_TABVALUE_PTR_INIT(&fields[80]), &strentries[85]},
+ {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "enum_type"), UPB_TABVALUE_PTR_INIT(&fields[19]), NULL},
+ {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "public_dependency"), UPB_TABVALUE_PTR_INIT(&fields[82]), &strentries[85]},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_STR("\004", "\000", "\000", "\000", "file"), UPB_TABVALUE_PTR_INIT(&fields[26]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
@@ -5761,7 +7644,7 @@ static const upb_tabent strentries[236] = {
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_STR("\023", "\000", "\000", "\000", "cc_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[3]), NULL},
- {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "csharp_namespace"), UPB_TABVALUE_PTR_INIT(&fields[5]), NULL},
+ {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "csharp_namespace"), UPB_TABVALUE_PTR_INIT(&fields[5]), &strentries[116]},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
@@ -5774,17 +7657,17 @@ static const upb_tabent strentries[236] = {
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_STR("\024", "\000", "\000", "\000", "java_outer_classname"), UPB_TABVALUE_PTR_INIT(&fields[34]), NULL},
- {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[95]), NULL},
+ {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "php_namespace"), UPB_TABVALUE_PTR_INIT(&fields[80]), &strentries[113]},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_STR("\023", "\000", "\000", "\000", "java_multiple_files"), UPB_TABVALUE_PTR_INIT(&fields[33]), &strentries[117]},
- {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
+ {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[99]), NULL},
{UPB_TABKEY_STR("\025", "\000", "\000", "\000", "java_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[32]), &strentries[118]},
{UPB_TABKEY_STR("\035", "\000", "\000", "\000", "java_generate_equals_and_hash"), UPB_TABVALUE_PTR_INIT(&fields[31]), NULL},
- {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
+ {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "php_class_prefix"), UPB_TABVALUE_PTR_INIT(&fields[79]), NULL},
{UPB_TABKEY_STR("\037", "\000", "\000", "\000", "javanano_use_deprecated_package"), UPB_TABVALUE_PTR_INIT(&fields[37]), &strentries[123]},
- {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "py_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[81]), NULL},
+ {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "py_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[83]), NULL},
{UPB_TABKEY_STR("\014", "\000", "\000", "\000", "optimize_for"), UPB_TABVALUE_PTR_INIT(&fields[67]), NULL},
{UPB_TABKEY_STR("\026", "\000", "\000", "\000", "java_string_check_utf8"), UPB_TABVALUE_PTR_INIT(&fields[36]), NULL},
{UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[12]), &strentries[119]},
@@ -5794,32 +7677,32 @@ static const upb_tabent strentries[236] = {
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[96]), NULL},
- {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[9]), NULL},
+ {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[97]), NULL},
+ {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[11]), NULL},
{UPB_TABKEY_STR("\011", "\000", "\000", "\000", "map_entry"), UPB_TABVALUE_PTR_INIT(&fields[45]), NULL},
{UPB_TABKEY_STR("\037", "\000", "\000", "\000", "no_standard_descriptor_accessor"), UPB_TABVALUE_PTR_INIT(&fields[61]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_STR("\020", "\000", "\000", "\000", "client_streaming"), UPB_TABVALUE_PTR_INIT(&fields[4]), NULL},
- {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "server_streaming"), UPB_TABVALUE_PTR_INIT(&fields[84]), NULL},
- {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[56]), NULL},
+ {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "server_streaming"), UPB_TABVALUE_PTR_INIT(&fields[86]), NULL},
+ {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[55]), NULL},
{UPB_TABKEY_STR("\012", "\000", "\000", "\000", "input_type"), UPB_TABVALUE_PTR_INIT(&fields[29]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_STR("\013", "\000", "\000", "\000", "output_type"), UPB_TABVALUE_PTR_INIT(&fields[75]), NULL},
- {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[70]), NULL},
+ {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[71]), NULL},
{UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[100]), NULL},
- {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[11]), NULL},
+ {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[10]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[50]), NULL},
+ {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[54]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[72]), &strentries[150]},
{UPB_TABKEY_STR("\006", "\000", "\000", "\000", "method"), UPB_TABVALUE_PTR_INIT(&fields[48]), NULL},
- {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[57]), &strentries[149]},
- {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[101]), NULL},
- {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[14]), NULL},
+ {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[53]), &strentries[149]},
+ {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[98]), NULL},
+ {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[15]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
@@ -5829,15 +7712,15 @@ static const upb_tabent strentries[236] = {
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "span"), UPB_TABVALUE_PTR_INIT(&fields[87]), &strentries[167]},
+ {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "span"), UPB_TABVALUE_PTR_INIT(&fields[89]), &strentries[167]},
{UPB_TABKEY_STR("\031", "\000", "\000", "\000", "leading_detached_comments"), UPB_TABVALUE_PTR_INIT(&fields[43]), &strentries[165]},
- {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "trailing_comments"), UPB_TABVALUE_PTR_INIT(&fields[92]), NULL},
+ {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "trailing_comments"), UPB_TABVALUE_PTR_INIT(&fields[94]), NULL},
{UPB_TABKEY_STR("\020", "\000", "\000", "\000", "leading_comments"), UPB_TABVALUE_PTR_INIT(&fields[42]), &strentries[164]},
{UPB_TABKEY_STR("\004", "\000", "\000", "\000", "path"), UPB_TABVALUE_PTR_INIT(&fields[78]), NULL},
{UPB_TABKEY_STR("\014", "\000", "\000", "\000", "double_value"), UPB_TABVALUE_PTR_INIT(&fields[16]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[51]), NULL},
+ {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[49]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
@@ -5847,9 +7730,9 @@ static const upb_tabent strentries[236] = {
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\022", "\000", "\000", "\000", "positive_int_value"), UPB_TABVALUE_PTR_INIT(&fields[79]), NULL},
+ {UPB_TABKEY_STR("\022", "\000", "\000", "\000", "positive_int_value"), UPB_TABVALUE_PTR_INIT(&fields[81]), NULL},
{UPB_TABKEY_STR("\020", "\000", "\000", "\000", "identifier_value"), UPB_TABVALUE_PTR_INIT(&fields[28]), NULL},
- {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "string_value"), UPB_TABVALUE_PTR_INIT(&fields[90]), &strentries[182]},
+ {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "string_value"), UPB_TABVALUE_PTR_INIT(&fields[92]), &strentries[182]},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_STR("\014", "\000", "\000", "\000", "is_extension"), UPB_TABVALUE_PTR_INIT(&fields[30]), NULL},
@@ -5906,92 +7789,92 @@ static const upb_tabent strentries[236] = {
static const upb_tabent intentries[18] = {
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[98]), NULL},
+ {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[103]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[97]), NULL},
+ {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[102]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[99]), NULL},
+ {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[101]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[95]), NULL},
+ {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[99]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[96]), NULL},
+ {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[97]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_NUM(33), UPB_TABVALUE_PTR_INIT(&fields[11]), NULL},
+ {UPB_TABKEY_NUM(33), UPB_TABVALUE_PTR_INIT(&fields[10]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[100]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_NUM(33), UPB_TABVALUE_PTR_INIT(&fields[14]), NULL},
+ {UPB_TABKEY_NUM(33), UPB_TABVALUE_PTR_INIT(&fields[15]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[101]), NULL},
+ {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[98]), NULL},
};
-static const upb_tabval arrays[184] = {
+static const upb_tabval arrays[187] = {
UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[52]),
+ UPB_TABVALUE_PTR_INIT(&fields[57]),
UPB_TABVALUE_PTR_INIT(&fields[25]),
UPB_TABVALUE_PTR_INIT(&fields[60]),
- UPB_TABVALUE_PTR_INIT(&fields[19]),
+ UPB_TABVALUE_PTR_INIT(&fields[20]),
UPB_TABVALUE_PTR_INIT(&fields[24]),
UPB_TABVALUE_PTR_INIT(&fields[22]),
UPB_TABVALUE_PTR_INIT(&fields[68]),
UPB_TABVALUE_PTR_INIT(&fields[65]),
- UPB_TABVALUE_PTR_INIT(&fields[83]),
- UPB_TABVALUE_PTR_INIT(&fields[82]),
+ UPB_TABVALUE_PTR_INIT(&fields[85]),
+ UPB_TABVALUE_PTR_INIT(&fields[84]),
UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[89]),
+ UPB_TABVALUE_PTR_INIT(&fields[91]),
UPB_TABVALUE_PTR_INIT(&fields[18]),
UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[88]),
+ UPB_TABVALUE_PTR_INIT(&fields[90]),
UPB_TABVALUE_PTR_INIT(&fields[17]),
UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[49]),
- UPB_TABVALUE_PTR_INIT(&fields[102]),
- UPB_TABVALUE_PTR_INIT(&fields[74]),
+ UPB_TABVALUE_PTR_INIT(&fields[52]),
+ UPB_TABVALUE_PTR_INIT(&fields[104]),
+ UPB_TABVALUE_PTR_INIT(&fields[73]),
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_PTR_INIT(&fields[1]),
- UPB_TABVALUE_PTR_INIT(&fields[13]),
+ UPB_TABVALUE_PTR_INIT(&fields[14]),
UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[53]),
- UPB_TABVALUE_PTR_INIT(&fields[62]),
- UPB_TABVALUE_PTR_INIT(&fields[73]),
+ UPB_TABVALUE_PTR_INIT(&fields[50]),
+ UPB_TABVALUE_PTR_INIT(&fields[63]),
+ UPB_TABVALUE_PTR_INIT(&fields[74]),
UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[15]),
+ UPB_TABVALUE_PTR_INIT(&fields[13]),
UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[55]),
+ UPB_TABVALUE_PTR_INIT(&fields[56]),
UPB_TABVALUE_PTR_INIT(&fields[21]),
- UPB_TABVALUE_PTR_INIT(&fields[63]),
+ UPB_TABVALUE_PTR_INIT(&fields[62]),
UPB_TABVALUE_PTR_INIT(&fields[40]),
- UPB_TABVALUE_PTR_INIT(&fields[93]),
- UPB_TABVALUE_PTR_INIT(&fields[94]),
+ UPB_TABVALUE_PTR_INIT(&fields[95]),
+ UPB_TABVALUE_PTR_INIT(&fields[96]),
UPB_TABVALUE_PTR_INIT(&fields[7]),
- UPB_TABVALUE_PTR_INIT(&fields[71]),
+ UPB_TABVALUE_PTR_INIT(&fields[70]),
UPB_TABVALUE_PTR_INIT(&fields[66]),
UPB_TABVALUE_PTR_INIT(&fields[38]),
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_PTR_INIT(&fields[6]),
UPB_TABVALUE_PTR_INIT(&fields[77]),
- UPB_TABVALUE_PTR_INIT(&fields[10]),
+ UPB_TABVALUE_PTR_INIT(&fields[9]),
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_PTR_INIT(&fields[41]),
UPB_TABVALUE_PTR_INIT(&fields[39]),
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[103]),
+ UPB_TABVALUE_PTR_INIT(&fields[105]),
UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[54]),
+ UPB_TABVALUE_PTR_INIT(&fields[51]),
UPB_TABVALUE_PTR_INIT(&fields[76]),
UPB_TABVALUE_PTR_INIT(&fields[8]),
UPB_TABVALUE_PTR_INIT(&fields[47]),
- UPB_TABVALUE_PTR_INIT(&fields[20]),
- UPB_TABVALUE_PTR_INIT(&fields[85]),
+ UPB_TABVALUE_PTR_INIT(&fields[19]),
+ UPB_TABVALUE_PTR_INIT(&fields[87]),
UPB_TABVALUE_PTR_INIT(&fields[23]),
UPB_TABVALUE_PTR_INIT(&fields[69]),
- UPB_TABVALUE_PTR_INIT(&fields[86]),
- UPB_TABVALUE_PTR_INIT(&fields[80]),
- UPB_TABVALUE_PTR_INIT(&fields[104]),
- UPB_TABVALUE_PTR_INIT(&fields[91]),
+ UPB_TABVALUE_PTR_INIT(&fields[88]),
+ UPB_TABVALUE_PTR_INIT(&fields[82]),
+ UPB_TABVALUE_PTR_INIT(&fields[106]),
+ UPB_TABVALUE_PTR_INIT(&fields[93]),
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_PTR_INIT(&fields[26]),
UPB_TABVALUE_EMPTY_INIT,
@@ -6012,7 +7895,7 @@ static const upb_tabval arrays[184] = {
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_PTR_INIT(&fields[3]),
UPB_TABVALUE_PTR_INIT(&fields[32]),
- UPB_TABVALUE_PTR_INIT(&fields[81]),
+ UPB_TABVALUE_PTR_INIT(&fields[83]),
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_PTR_INIT(&fields[31]),
UPB_TABVALUE_EMPTY_INIT,
@@ -6034,25 +7917,28 @@ static const upb_tabval arrays[184] = {
UPB_TABVALUE_PTR_INIT(&fields[5]),
UPB_TABVALUE_PTR_INIT(&fields[37]),
UPB_TABVALUE_EMPTY_INIT,
+ UPB_TABVALUE_PTR_INIT(&fields[79]),
+ UPB_TABVALUE_PTR_INIT(&fields[80]),
+ UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_PTR_INIT(&fields[46]),
UPB_TABVALUE_PTR_INIT(&fields[61]),
- UPB_TABVALUE_PTR_INIT(&fields[9]),
+ UPB_TABVALUE_PTR_INIT(&fields[11]),
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_PTR_INIT(&fields[45]),
UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[56]),
+ UPB_TABVALUE_PTR_INIT(&fields[55]),
UPB_TABVALUE_PTR_INIT(&fields[29]),
UPB_TABVALUE_PTR_INIT(&fields[75]),
- UPB_TABVALUE_PTR_INIT(&fields[70]),
+ UPB_TABVALUE_PTR_INIT(&fields[71]),
UPB_TABVALUE_PTR_INIT(&fields[4]),
- UPB_TABVALUE_PTR_INIT(&fields[84]),
+ UPB_TABVALUE_PTR_INIT(&fields[86]),
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[50]),
+ UPB_TABVALUE_PTR_INIT(&fields[54]),
UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[57]),
+ UPB_TABVALUE_PTR_INIT(&fields[53]),
UPB_TABVALUE_PTR_INIT(&fields[48]),
UPB_TABVALUE_PTR_INIT(&fields[72]),
UPB_TABVALUE_EMPTY_INIT,
@@ -6060,19 +7946,19 @@ static const upb_tabval arrays[184] = {
UPB_TABVALUE_PTR_INIT(&fields[44]),
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_PTR_INIT(&fields[78]),
- UPB_TABVALUE_PTR_INIT(&fields[87]),
+ UPB_TABVALUE_PTR_INIT(&fields[89]),
UPB_TABVALUE_PTR_INIT(&fields[42]),
- UPB_TABVALUE_PTR_INIT(&fields[92]),
+ UPB_TABVALUE_PTR_INIT(&fields[94]),
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_PTR_INIT(&fields[43]),
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[51]),
+ UPB_TABVALUE_PTR_INIT(&fields[49]),
UPB_TABVALUE_PTR_INIT(&fields[28]),
- UPB_TABVALUE_PTR_INIT(&fields[79]),
+ UPB_TABVALUE_PTR_INIT(&fields[81]),
UPB_TABVALUE_PTR_INIT(&fields[59]),
UPB_TABVALUE_PTR_INIT(&fields[16]),
- UPB_TABVALUE_PTR_INIT(&fields[90]),
+ UPB_TABVALUE_PTR_INIT(&fields[92]),
UPB_TABVALUE_PTR_INIT(&fields[0]),
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_PTR_INIT(&fields[58]),
@@ -6113,7 +7999,11 @@ static const upb_tabval arrays[184] = {
};
#ifdef UPB_DEBUG_REFS
-static upb_inttable reftables[264] = {
+static upb_inttable reftables[268] = {
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
@@ -6466,6 +8356,7 @@ typedef struct {
struct upb_descreader {
upb_sink sink;
upb_inttable files;
+ upb_strtable files_by_name;
upb_filedef *file; /* The last file in files. */
upb_descreader_frame stack[UPB_MAX_MESSAGE_NESTING];
int stack_len;
@@ -6481,7 +8372,7 @@ struct upb_descreader {
upb_fielddef *f;
};
-static char *upb_strndup(const char *buf, size_t n) {
+static char *upb_gstrndup(const char *buf, size_t n) {
char *ret = upb_gmalloc(n + 1);
if (!ret) return NULL;
memcpy(ret, buf, n);
@@ -6631,7 +8522,8 @@ static size_t file_onname(void *closure, const void *hd, const char *buf,
UPB_UNUSED(hd);
UPB_UNUSED(handle);
- name = upb_strndup(buf, n);
+ name = upb_gstrndup(buf, n);
+ upb_strtable_insert(&r->files_by_name, name, upb_value_ptr(r->file));
/* XXX: see comment at the top of the file. */
ok = upb_filedef_setname(r->file, name, NULL);
upb_gfree(name);
@@ -6647,7 +8539,7 @@ static size_t file_onpackage(void *closure, const void *hd, const char *buf,
UPB_UNUSED(hd);
UPB_UNUSED(handle);
- package = upb_strndup(buf, n);
+ package = upb_gstrndup(buf, n);
/* XXX: see comment at the top of the file. */
upb_descreader_setscopename(r, package);
ok = upb_filedef_setpackage(r->file, package, NULL);
@@ -6655,6 +8547,49 @@ static size_t file_onpackage(void *closure, const void *hd, const char *buf,
return n;
}
+static void *file_startphpnamespace(void *closure, const void *hd,
+ size_t size_hint) {
+ upb_descreader *r = closure;
+ bool ok;
+ UPB_UNUSED(hd);
+ UPB_UNUSED(size_hint);
+
+ ok = upb_filedef_setphpnamespace(r->file, "", NULL);
+ UPB_ASSERT(ok);
+ return closure;
+}
+
+static size_t file_onphpnamespace(void *closure, const void *hd,
+ const char *buf, size_t n,
+ const upb_bufhandle *handle) {
+ upb_descreader *r = closure;
+ char *php_namespace;
+ bool ok;
+ UPB_UNUSED(hd);
+ UPB_UNUSED(handle);
+
+ php_namespace = upb_gstrndup(buf, n);
+ ok = upb_filedef_setphpnamespace(r->file, php_namespace, NULL);
+ upb_gfree(php_namespace);
+ UPB_ASSERT(ok);
+ return n;
+}
+
+static size_t file_onphpprefix(void *closure, const void *hd, const char *buf,
+ size_t n, const upb_bufhandle *handle) {
+ upb_descreader *r = closure;
+ char *prefix;
+ bool ok;
+ UPB_UNUSED(hd);
+ UPB_UNUSED(handle);
+
+ prefix = upb_gstrndup(buf, n);
+ ok = upb_filedef_setphpprefix(r->file, prefix, NULL);
+ upb_gfree(prefix);
+ UPB_ASSERT(ok);
+ return n;
+}
+
static size_t file_onsyntax(void *closure, const void *hd, const char *buf,
size_t n, const upb_bufhandle *handle) {
upb_descreader *r = closure;
@@ -6702,6 +8637,18 @@ static void *file_startext(void *closure, const void *hd) {
return r;
}
+static size_t file_ondep(void *closure, const void *hd, const char *buf,
+ size_t n, const upb_bufhandle *handle) {
+ upb_descreader *r = closure;
+ upb_value val;
+ if (upb_strtable_lookup2(&r->files_by_name, buf, n, &val)) {
+ upb_filedef_adddep(r->file, upb_value_getptr(val));
+ }
+ UPB_UNUSED(hd);
+ UPB_UNUSED(handle);
+ return n;
+}
+
/** Handlers for google.protobuf.EnumValueDescriptorProto. *********************/
static bool enumval_startmsg(void *closure, const void *hd) {
@@ -6719,7 +8666,7 @@ static size_t enumval_onname(void *closure, const void *hd, const char *buf,
UPB_UNUSED(handle);
/* XXX: see comment at the top of the file. */
upb_gfree(r->name);
- r->name = upb_strndup(buf, n);
+ r->name = upb_gstrndup(buf, n);
r->saw_name = true;
return n;
}
@@ -6770,7 +8717,7 @@ static bool enum_endmsg(void *closure, const void *hd, upb_status *status) {
static size_t enum_onname(void *closure, const void *hd, const char *buf,
size_t n, const upb_bufhandle *handle) {
upb_descreader *r = closure;
- char *fullname = upb_strndup(buf, n);
+ char *fullname = upb_gstrndup(buf, n);
UPB_UNUSED(hd);
UPB_UNUSED(handle);
/* XXX: see comment at the top of the file. */
@@ -6938,7 +8885,7 @@ static bool field_onnumber(void *closure, const void *hd, int32_t val) {
static size_t field_onname(void *closure, const void *hd, const char *buf,
size_t n, const upb_bufhandle *handle) {
upb_descreader *r = closure;
- char *name = upb_strndup(buf, n);
+ char *name = upb_gstrndup(buf, n);
UPB_UNUSED(hd);
UPB_UNUSED(handle);
@@ -6951,7 +8898,7 @@ static size_t field_onname(void *closure, const void *hd, const char *buf,
static size_t field_ontypename(void *closure, const void *hd, const char *buf,
size_t n, const upb_bufhandle *handle) {
upb_descreader *r = closure;
- char *name = upb_strndup(buf, n);
+ char *name = upb_gstrndup(buf, n);
UPB_UNUSED(hd);
UPB_UNUSED(handle);
@@ -6964,7 +8911,7 @@ static size_t field_ontypename(void *closure, const void *hd, const char *buf,
static size_t field_onextendee(void *closure, const void *hd, const char *buf,
size_t n, const upb_bufhandle *handle) {
upb_descreader *r = closure;
- char *name = upb_strndup(buf, n);
+ char *name = upb_gstrndup(buf, n);
UPB_UNUSED(hd);
UPB_UNUSED(handle);
@@ -6984,7 +8931,7 @@ static size_t field_ondefaultval(void *closure, const void *hd, const char *buf,
* type yet, so we save it as a string until the end of the field.
* XXX: see comment at the top of the file. */
upb_gfree(r->default_string);
- r->default_string = upb_strndup(buf, n);
+ r->default_string = upb_gstrndup(buf, n);
return n;
}
@@ -7005,7 +8952,7 @@ static size_t oneof_name(void *closure, const void *hd, const char *buf,
upb_descreader *r = closure;
upb_descreader_frame *f = &r->stack[r->stack_len-1];
upb_oneofdef *o = upb_descreader_getoneof(r, f->oneof_index++);
- char *name_null_terminated = upb_strndup(buf, n);
+ char *name_null_terminated = upb_gstrndup(buf, n);
bool ok = upb_oneofdef_setname(o, name_null_terminated, NULL);
UPB_UNUSED(hd);
UPB_UNUSED(handle);
@@ -7042,7 +8989,7 @@ static size_t msg_name(void *closure, const void *hd, const char *buf,
upb_descreader *r = closure;
upb_msgdef *m = upb_descreader_top(r);
/* XXX: see comment at the top of the file. */
- char *name = upb_strndup(buf, n);
+ char *name = upb_gstrndup(buf, n);
UPB_UNUSED(hd);
UPB_UNUSED(handle);
@@ -7146,6 +9093,8 @@ static void reghandlers(const void *closure, upb_handlers *h) {
&file_startenum, NULL);
upb_handlers_setstartsubmsg(h, F(FileDescriptorProto, extension),
&file_startext, NULL);
+ upb_handlers_setstring(h, F(FileDescriptorProto, dependency),
+ &file_ondep, NULL);
} else if (upbdefs_google_protobuf_EnumValueDescriptorProto_is(m)) {
upb_handlers_setstartmsg(h, &enumval_startmsg, NULL);
upb_handlers_setendmsg(h, &enumval_endmsg, NULL);
@@ -7181,6 +9130,13 @@ static void reghandlers(const void *closure, upb_handlers *h) {
upb_handlers_setbool(h, F(FieldOptions, packed), &field_onpacked, NULL);
} else if (upbdefs_google_protobuf_MessageOptions_is(m)) {
upb_handlers_setbool(h, F(MessageOptions, map_entry), &msg_onmapentry, NULL);
+ } else if (upbdefs_google_protobuf_FileOptions_is(m)) {
+ upb_handlers_setstring(h, F(FileOptions, php_class_prefix),
+ &file_onphpprefix, NULL);
+ upb_handlers_setstartstr(h, F(FileOptions, php_namespace),
+ &file_startphpnamespace, NULL);
+ upb_handlers_setstring(h, F(FileOptions, php_namespace),
+ &file_onphpnamespace, NULL);
}
UPB_ASSERT(upb_ok(upb_handlers_status(h)));
@@ -7198,6 +9154,7 @@ void descreader_cleanup(void *_r) {
upb_gfree(r->name);
upb_inttable_uninit(&r->files);
+ upb_strtable_uninit(&r->files_by_name);
upb_inttable_uninit(&r->oneofs);
upb_gfree(r->default_string);
while (r->stack_len > 0) {
@@ -7216,6 +9173,7 @@ upb_descreader *upb_descreader_create(upb_env *e, const upb_handlers *h) {
}
upb_inttable_init(&r->files, UPB_CTYPE_PTR);
+ upb_strtable_init(&r->files_by_name, UPB_CTYPE_PTR);
upb_inttable_init(&r->oneofs, UPB_CTYPE_PTR);
upb_sink_reset(upb_descreader_input(r), h, r);
r->stack_len = 0;
@@ -7515,7 +9473,7 @@ static void put32(compiler *c, uint32_t v) {
*c->pc++ = v;
}
-static void putop(compiler *c, opcode op, ...) {
+static void putop(compiler *c, int op, ...) {
va_list ap;
va_start(ap, op);
@@ -8798,7 +10756,6 @@ have_tag:
return upb_pbdecoder_suspend(d);
}
- /* TODO: deliver to unknown field callback. */
switch (wire_type) {
case UPB_WIRE_TYPE_32BIT:
CHECK_RETURN(skip(d, 4));
@@ -8836,6 +10793,8 @@ have_tag:
}
if (d->top->groupnum >= 0) {
+ /* TODO: More code needed for handling unknown groups. */
+ upb_sink_putunknown(&d->top->sink, d->checkpoint, d->ptr - d->checkpoint);
return DECODE_OK;
}
@@ -9691,6 +11650,12 @@ static void *encode_startdelimfield(void *c, const void *hd) {
return ok ? c : UPB_BREAK;
}
+static bool encode_unknown(void *c, const void *hd, const char *buf,
+ size_t len) {
+ UPB_UNUSED(hd);
+ return encode_bytes(c, buf, len) && commit(c);
+}
+
static bool encode_enddelimfield(void *c, const void *hd) {
UPB_UNUSED(hd);
return end_delim(c);
@@ -9728,7 +11693,7 @@ static size_t encode_strbuf(void *c, const void *hd, const char *buf,
T(double, double, dbl2uint64, encode_fixed64)
T(float, float, flt2uint32, encode_fixed32)
T(int64, int64_t, uint64_t, encode_varint)
-T(int32, int32_t, uint32_t, encode_varint)
+T(int32, int32_t, int64_t, encode_varint)
T(fixed64, uint64_t, uint64_t, encode_fixed64)
T(fixed32, uint32_t, uint32_t, encode_fixed32)
T(bool, bool, bool, encode_varint)
@@ -9753,6 +11718,7 @@ static void newhandlers_callback(const void *closure, upb_handlers *h) {
upb_handlers_setstartmsg(h, startmsg, NULL);
upb_handlers_setendmsg(h, endmsg, NULL);
+ upb_handlers_setunknown(h, encode_unknown, NULL);
m = upb_handlers_msgdef(h);
for(upb_msg_field_begin(&i, m);
@@ -10343,57 +12309,6 @@ done:
return r;
}
-/* Given an encoded varint v, returns an integer with a single bit set that
- * indicates the end of the varint. Subtracting one from this value will
- * yield a mask that leaves only bits that are part of the varint. Returns
- * 0 if the varint is unterminated. */
-static uint64_t upb_get_vstopbit(uint64_t v) {
- uint64_t cbits = v | 0x7f7f7f7f7f7f7f7fULL;
- return ~cbits & (cbits+1);
-}
-
-/* A branchless decoder. Credit to Pascal Massimino for the bit-twiddling. */
-upb_decoderet upb_vdecode_max8_massimino(upb_decoderet r) {
- uint64_t b;
- uint64_t stop_bit;
- upb_decoderet my_r;
- memcpy(&b, r.p, sizeof(b));
- stop_bit = upb_get_vstopbit(b);
- b = (b & 0x7f7f7f7f7f7f7f7fULL) & (stop_bit - 1);
- b += b & 0x007f007f007f007fULL;
- b += 3 * (b & 0x0000ffff0000ffffULL);
- b += 15 * (b & 0x00000000ffffffffULL);
- if (stop_bit == 0) {
- /* Error: unterminated varint. */
- upb_decoderet err_r = {(void*)0, 0};
- return err_r;
- }
- my_r = upb_decoderet_make(r.p + ((__builtin_ctzll(stop_bit) + 1) / 8),
- r.val | (b << 7));
- return my_r;
-}
-
-/* A branchless decoder. Credit to Daniel Wright for the bit-twiddling. */
-upb_decoderet upb_vdecode_max8_wright(upb_decoderet r) {
- uint64_t b;
- uint64_t stop_bit;
- upb_decoderet my_r;
- memcpy(&b, r.p, sizeof(b));
- stop_bit = upb_get_vstopbit(b);
- b &= (stop_bit - 1);
- b = ((b & 0x7f007f007f007f00ULL) >> 1) | (b & 0x007f007f007f007fULL);
- b = ((b & 0xffff0000ffff0000ULL) >> 2) | (b & 0x0000ffff0000ffffULL);
- b = ((b & 0xffffffff00000000ULL) >> 4) | (b & 0x00000000ffffffffULL);
- if (stop_bit == 0) {
- /* Error: unterminated varint. */
- upb_decoderet err_r = {(void*)0, 0};
- return err_r;
- }
- my_r = upb_decoderet_make(r.p + ((__builtin_ctzll(stop_bit) + 1) / 8),
- r.val | (b << 14));
- return my_r;
-}
-
#line 1 "upb/json/parser.rl"
/*
** upb::json::Parser (upb_json_parser)
@@ -10416,8 +12331,9 @@ upb_decoderet upb_vdecode_max8_wright(upb_decoderet r) {
** - handling of keys/escape-sequences/etc that span input buffers.
*/
-#include <assert.h>
#include <errno.h>
+#include <float.h>
+#include <math.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
@@ -11002,103 +12918,160 @@ static void start_number(upb_json_parser *p, const char *ptr) {
capture_begin(p, ptr);
}
-static bool parse_number(upb_json_parser *p);
+static bool parse_number(upb_json_parser *p, bool is_quoted);
static bool end_number(upb_json_parser *p, const char *ptr) {
if (!capture_end(p, ptr)) {
return false;
}
- return parse_number(p);
+ return parse_number(p, false);
}
-static bool parse_number(upb_json_parser *p) {
- size_t len;
- const char *buf;
- const char *myend;
+/* |buf| is NULL-terminated. |buf| itself will never include quotes;
+ * |is_quoted| tells us whether this text originally appeared inside quotes. */
+static bool parse_number_from_buffer(upb_json_parser *p, const char *buf,
+ bool is_quoted) {
+ size_t len = strlen(buf);
+ const char *bufend = buf + len;
char *end;
+ upb_fieldtype_t type = upb_fielddef_type(p->top->f);
+ double val;
+ double dummy;
+ double inf = 1.0 / 0.0; /* C89 does not have an INFINITY macro. */
- /* strtol() and friends unfortunately do not support specifying the length of
- * the input string, so we need to force a copy into a NULL-terminated buffer. */
- if (!multipart_text(p, "\0", 1, false)) {
+ errno = 0;
+
+ if (len == 0 || buf[0] == ' ') {
return false;
}
- buf = accumulate_getptr(p, &len);
- myend = buf + len - 1; /* One for NULL. */
-
- /* XXX: We are using strtol to parse integers, but this is wrong as even
- * integers can be represented as 1e6 (for example), which strtol can't
- * handle correctly.
- *
- * XXX: Also, we can't handle large integers properly because strto[u]ll
- * isn't in C89.
- *
- * XXX: Also, we don't properly check floats for overflow, since strtof
- * isn't in C89. */
- switch (upb_fielddef_type(p->top->f)) {
+ /* For integer types, first try parsing with integer-specific routines.
+ * If these succeed, they will be more accurate for int64/uint64 than
+ * strtod().
+ */
+ switch (type) {
case UPB_TYPE_ENUM:
case UPB_TYPE_INT32: {
- long val = strtol(p->accumulated, &end, 0);
- if (val > INT32_MAX || val < INT32_MIN || errno == ERANGE || end != myend)
- goto err;
- else
+ long val = strtol(buf, &end, 0);
+ if (errno == ERANGE || end != bufend) {
+ break;
+ } else if (val > INT32_MAX || val < INT32_MIN) {
+ return false;
+ } else {
upb_sink_putint32(&p->top->sink, parser_getsel(p), val);
- break;
- }
- case UPB_TYPE_INT64: {
- long long val = strtol(p->accumulated, &end, 0);
- if (val > INT64_MAX || val < INT64_MIN || errno == ERANGE || end != myend)
- goto err;
- else
- upb_sink_putint64(&p->top->sink, parser_getsel(p), val);
- break;
+ return true;
+ }
}
case UPB_TYPE_UINT32: {
- unsigned long val = strtoul(p->accumulated, &end, 0);
- if (val > UINT32_MAX || errno == ERANGE || end != myend)
- goto err;
- else
+ unsigned long val = strtoul(buf, &end, 0);
+ if (end != bufend) {
+ break;
+ } else if (val > UINT32_MAX || errno == ERANGE) {
+ return false;
+ } else {
upb_sink_putuint32(&p->top->sink, parser_getsel(p), val);
- break;
+ return true;
+ }
+ }
+ /* XXX: We can't handle [u]int64 properly on 32-bit machines because
+ * strto[u]ll isn't in C89. */
+ case UPB_TYPE_INT64: {
+ long val = strtol(buf, &end, 0);
+ if (errno == ERANGE || end != bufend) {
+ break;
+ } else {
+ upb_sink_putint64(&p->top->sink, parser_getsel(p), val);
+ return true;
+ }
}
case UPB_TYPE_UINT64: {
- unsigned long long val = strtoul(p->accumulated, &end, 0);
- if (val > UINT64_MAX || errno == ERANGE || end != myend)
- goto err;
- else
+ unsigned long val = strtoul(p->accumulated, &end, 0);
+ if (end != bufend) {
+ break;
+ } else if (errno == ERANGE) {
+ return false;
+ } else {
upb_sink_putuint64(&p->top->sink, parser_getsel(p), val);
- break;
+ return true;
+ }
}
- case UPB_TYPE_DOUBLE: {
- double val = strtod(p->accumulated, &end);
- if (errno == ERANGE || end != myend)
- goto err;
- else
- upb_sink_putdouble(&p->top->sink, parser_getsel(p), val);
+ default:
break;
+ }
+
+ if (type != UPB_TYPE_DOUBLE && type != UPB_TYPE_FLOAT && is_quoted) {
+ /* Quoted numbers for integer types are not allowed to be in double form. */
+ return false;
+ }
+
+ if (len == strlen("Infinity") && strcmp(buf, "Infinity") == 0) {
+ /* C89 does not have an INFINITY macro. */
+ val = inf;
+ } else if (len == strlen("-Infinity") && strcmp(buf, "-Infinity") == 0) {
+ val = -inf;
+ } else {
+ val = strtod(buf, &end);
+ if (errno == ERANGE || end != bufend) {
+ return false;
}
- case UPB_TYPE_FLOAT: {
- float val = strtod(p->accumulated, &end);
- if (errno == ERANGE || end != myend)
- goto err;
- else
- upb_sink_putfloat(&p->top->sink, parser_getsel(p), val);
- break;
+ }
+
+ switch (type) {
+#define CASE(capitaltype, smalltype, ctype, min, max) \
+ case UPB_TYPE_ ## capitaltype: { \
+ if (modf(val, &dummy) != 0 || val > max || val < min) { \
+ return false; \
+ } else { \
+ upb_sink_put ## smalltype(&p->top->sink, parser_getsel(p), \
+ (ctype)val); \
+ return true; \
+ } \
+ break; \
}
+ case UPB_TYPE_ENUM:
+ CASE(INT32, int32, int32_t, INT32_MIN, INT32_MAX);
+ CASE(INT64, int64, int64_t, INT64_MIN, INT64_MAX);
+ CASE(UINT32, uint32, uint32_t, 0, UINT32_MAX);
+ CASE(UINT64, uint64, uint64_t, 0, UINT64_MAX);
+#undef CASE
+
+ case UPB_TYPE_DOUBLE:
+ upb_sink_putdouble(&p->top->sink, parser_getsel(p), val);
+ return true;
+ case UPB_TYPE_FLOAT:
+ if ((val > FLT_MAX || val < -FLT_MAX) && val != inf && val != -inf) {
+ return false;
+ } else {
+ upb_sink_putfloat(&p->top->sink, parser_getsel(p), val);
+ return true;
+ }
default:
- UPB_ASSERT(false);
+ return false;
}
+}
- multipart_end(p);
+static bool parse_number(upb_json_parser *p, bool is_quoted) {
+ size_t len;
+ const char *buf;
- return true;
+ /* strtol() and friends unfortunately do not support specifying the length of
+ * the input string, so we need to force a copy into a NULL-terminated buffer. */
+ if (!multipart_text(p, "\0", 1, false)) {
+ return false;
+ }
-err:
- upb_status_seterrf(&p->status, "error parsing number: %s", buf);
- upb_env_reporterror(p->env, &p->status);
- multipart_end(p);
- return false;
+ buf = accumulate_getptr(p, &len);
+
+ if (parse_number_from_buffer(p, buf, is_quoted)) {
+ multipart_end(p);
+ return true;
+ } else {
+ upb_status_seterrf(&p->status, "error parsing number: %s", buf);
+ upb_env_reporterror(p->env, &p->status);
+ multipart_end(p);
+ return false;
+ }
}
static bool parser_putbool(upb_json_parser *p, bool val) {
@@ -11151,17 +13124,16 @@ static bool start_stringval(upb_json_parser *p) {
multipart_startaccum(p);
return true;
}
- } else if (upb_fielddef_type(p->top->f) == UPB_TYPE_ENUM) {
- /* No need to push a frame -- symbolic enum names in quotes remain in the
- * current parser frame.
- *
- * Enum string values must accumulate so we can look up the value in a table
- * once it is complete. */
+ } else if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL &&
+ upb_fielddef_type(p->top->f) != UPB_TYPE_MESSAGE) {
+ /* No need to push a frame -- numeric values in quotes remain in the
+ * current parser frame. These values must accmulate so we can convert
+ * them all at once at the end. */
multipart_startaccum(p);
return true;
} else {
upb_status_seterrf(&p->status,
- "String specified for non-string/non-enum field: %s",
+ "String specified for bool or submessage field: %s",
upb_fielddef_name(p->top->f));
upb_env_reporterror(p->env, &p->status);
return false;
@@ -11208,6 +13180,15 @@ static bool end_stringval(upb_json_parser *p) {
break;
}
+ case UPB_TYPE_INT32:
+ case UPB_TYPE_INT64:
+ case UPB_TYPE_UINT32:
+ case UPB_TYPE_UINT64:
+ case UPB_TYPE_DOUBLE:
+ case UPB_TYPE_FLOAT:
+ ok = parse_number(p, true);
+ break;
+
default:
UPB_ASSERT(false);
upb_status_seterrmsg(&p->status, "Internal error in JSON decoder");
@@ -11251,7 +13232,7 @@ static bool parse_mapentry_key(upb_json_parser *p) {
case UPB_TYPE_UINT32:
case UPB_TYPE_UINT64:
/* Invoke end_number. The accum buffer has the number's text already. */
- if (!parse_number(p)) {
+ if (!parse_number(p, true)) {
return false;
}
break;
@@ -11542,11 +13523,11 @@ static void end_object(upb_json_parser *p) {
* final state once, when the closing '"' is seen. */
-#line 1244 "upb/json/parser.rl"
+#line 1310 "upb/json/parser.rl"
-#line 1156 "upb/json/parser.c"
+#line 1222 "upb/json/parser.c"
static const char _json_actions[] = {
0, 1, 0, 1, 2, 1, 3, 1,
5, 1, 6, 1, 7, 1, 8, 1,
@@ -11695,7 +13676,7 @@ static const int json_en_value_machine = 27;
static const int json_en_main = 1;
-#line 1247 "upb/json/parser.rl"
+#line 1313 "upb/json/parser.rl"
size_t parse(void *closure, const void *hd, const char *buf, size_t size,
const upb_bufhandle *handle) {
@@ -11717,7 +13698,7 @@ size_t parse(void *closure, const void *hd, const char *buf, size_t size,
capture_resume(parser, buf);
-#line 1327 "upb/json/parser.c"
+#line 1393 "upb/json/parser.c"
{
int _klen;
unsigned int _trans;
@@ -11792,118 +13773,118 @@ _match:
switch ( *_acts++ )
{
case 0:
-#line 1159 "upb/json/parser.rl"
+#line 1225 "upb/json/parser.rl"
{ p--; {cs = stack[--top]; goto _again;} }
break;
case 1:
-#line 1160 "upb/json/parser.rl"
+#line 1226 "upb/json/parser.rl"
{ p--; {stack[top++] = cs; cs = 10; goto _again;} }
break;
case 2:
-#line 1164 "upb/json/parser.rl"
+#line 1230 "upb/json/parser.rl"
{ start_text(parser, p); }
break;
case 3:
-#line 1165 "upb/json/parser.rl"
+#line 1231 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_text(parser, p)); }
break;
case 4:
-#line 1171 "upb/json/parser.rl"
+#line 1237 "upb/json/parser.rl"
{ start_hex(parser); }
break;
case 5:
-#line 1172 "upb/json/parser.rl"
+#line 1238 "upb/json/parser.rl"
{ hexdigit(parser, p); }
break;
case 6:
-#line 1173 "upb/json/parser.rl"
+#line 1239 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_hex(parser)); }
break;
case 7:
-#line 1179 "upb/json/parser.rl"
+#line 1245 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(escape(parser, p)); }
break;
case 8:
-#line 1185 "upb/json/parser.rl"
+#line 1251 "upb/json/parser.rl"
{ p--; {cs = stack[--top]; goto _again;} }
break;
case 9:
-#line 1188 "upb/json/parser.rl"
+#line 1254 "upb/json/parser.rl"
{ {stack[top++] = cs; cs = 19; goto _again;} }
break;
case 10:
-#line 1190 "upb/json/parser.rl"
+#line 1256 "upb/json/parser.rl"
{ p--; {stack[top++] = cs; cs = 27; goto _again;} }
break;
case 11:
-#line 1195 "upb/json/parser.rl"
+#line 1261 "upb/json/parser.rl"
{ start_member(parser); }
break;
case 12:
-#line 1196 "upb/json/parser.rl"
+#line 1262 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_membername(parser)); }
break;
case 13:
-#line 1199 "upb/json/parser.rl"
+#line 1265 "upb/json/parser.rl"
{ end_member(parser); }
break;
case 14:
-#line 1205 "upb/json/parser.rl"
+#line 1271 "upb/json/parser.rl"
{ start_object(parser); }
break;
case 15:
-#line 1208 "upb/json/parser.rl"
+#line 1274 "upb/json/parser.rl"
{ end_object(parser); }
break;
case 16:
-#line 1214 "upb/json/parser.rl"
+#line 1280 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(start_array(parser)); }
break;
case 17:
-#line 1218 "upb/json/parser.rl"
+#line 1284 "upb/json/parser.rl"
{ end_array(parser); }
break;
case 18:
-#line 1223 "upb/json/parser.rl"
+#line 1289 "upb/json/parser.rl"
{ start_number(parser, p); }
break;
case 19:
-#line 1224 "upb/json/parser.rl"
+#line 1290 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_number(parser, p)); }
break;
case 20:
-#line 1226 "upb/json/parser.rl"
+#line 1292 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(start_stringval(parser)); }
break;
case 21:
-#line 1227 "upb/json/parser.rl"
+#line 1293 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_stringval(parser)); }
break;
case 22:
-#line 1229 "upb/json/parser.rl"
+#line 1295 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(parser_putbool(parser, true)); }
break;
case 23:
-#line 1231 "upb/json/parser.rl"
+#line 1297 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(parser_putbool(parser, false)); }
break;
case 24:
-#line 1233 "upb/json/parser.rl"
+#line 1299 "upb/json/parser.rl"
{ /* null value */ }
break;
case 25:
-#line 1235 "upb/json/parser.rl"
+#line 1301 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(start_subobject(parser)); }
break;
case 26:
-#line 1236 "upb/json/parser.rl"
+#line 1302 "upb/json/parser.rl"
{ end_subobject(parser); }
break;
case 27:
-#line 1241 "upb/json/parser.rl"
+#line 1307 "upb/json/parser.rl"
{ p--; {cs = stack[--top]; goto _again;} }
break;
-#line 1513 "upb/json/parser.c"
+#line 1579 "upb/json/parser.c"
}
}
@@ -11916,7 +13897,7 @@ _again:
_out: {}
}
-#line 1268 "upb/json/parser.rl"
+#line 1334 "upb/json/parser.rl"
if (p != pe) {
upb_status_seterrf(&parser->status, "Parse error at '%.*s'\n", pe - p, p);
@@ -11957,13 +13938,13 @@ static void json_parser_reset(upb_json_parser *p) {
/* Emit Ragel initialization of the parser. */
-#line 1567 "upb/json/parser.c"
+#line 1633 "upb/json/parser.c"
{
cs = json_start;
top = 0;
}
-#line 1308 "upb/json/parser.rl"
+#line 1374 "upb/json/parser.rl"
p->current_state = cs;
p->parser_top = top;
accumulate_clear(p);
@@ -12260,10 +14241,23 @@ static void putstring(upb_json_printer *p, const char *buf, unsigned int len) {
* Right now we use %.8g and %.17g for float/double, respectively, to match
* proto2::util::JsonFormat's defaults. May want to change this later. */
+const char neginf[] = "\"-Infinity\"";
+const char inf[] = "\"Infinity\"";
+
static size_t fmt_double(double val, char* buf, size_t length) {
- size_t n = _upb_snprintf(buf, length, "%.17g", val);
- CHKLENGTH(n > 0 && n < length);
- return n;
+ if (val == (1.0 / 0.0)) {
+ CHKLENGTH(length >= strlen(inf));
+ strcpy(buf, inf);
+ return strlen(inf);
+ } else if (val == (-1.0 / 0.0)) {
+ CHKLENGTH(length >= strlen(neginf));
+ strcpy(buf, neginf);
+ return strlen(neginf);
+ } else {
+ size_t n = _upb_snprintf(buf, length, "%.17g", val);
+ CHKLENGTH(n > 0 && n < length);
+ return n;
+ }
}
static size_t fmt_float(float val, char* buf, size_t length) {
diff --git a/php/ext/google/protobuf/upb.h b/php/ext/google/protobuf/upb.h
index c83b0e03..10371e8b 100644
--- a/php/ext/google/protobuf/upb.h
+++ b/php/ext/google/protobuf/upb.h
@@ -1,66 +1,13 @@
// Amalgamated source file
/*
-** Defs are upb's internal representation of the constructs that can appear
-** in a .proto file:
-**
-** - upb::MessageDef (upb_msgdef): describes a "message" construct.
-** - upb::FieldDef (upb_fielddef): describes a message field.
-** - upb::FileDef (upb_filedef): describes a .proto file and its defs.
-** - upb::EnumDef (upb_enumdef): describes an enum.
-** - upb::OneofDef (upb_oneofdef): describes a oneof.
-** - upb::Def (upb_def): base class of all the others.
-**
-** TODO: definitions of services.
-**
-** Like upb_refcounted objects, defs are mutable only until frozen, and are
-** only thread-safe once frozen.
-**
-** This is a mixed C/C++ interface that offers a full API to both languages.
-** See the top-level README for more information.
-*/
-
-#ifndef UPB_DEF_H_
-#define UPB_DEF_H_
-
-/*
-** upb::RefCounted (upb_refcounted)
-**
-** A refcounting scheme that supports circular refs. It accomplishes this by
-** partitioning the set of objects into groups such that no cycle spans groups;
-** we can then reference-count the group as a whole and ignore refs within the
-** group. When objects are mutable, these groups are computed very
-** conservatively; we group any objects that have ever had a link between them.
-** When objects are frozen, we compute strongly-connected components which
-** allows us to be precise and only group objects that are actually cyclic.
+** This file contains shared definitions that are widely used across upb.
**
** This is a mixed C/C++ interface that offers a full API to both languages.
** See the top-level README for more information.
*/
-#ifndef UPB_REFCOUNTED_H_
-#define UPB_REFCOUNTED_H_
-
-/*
-** upb_table
-**
-** This header is INTERNAL-ONLY! Its interfaces are not public or stable!
-** This file defines very fast int->upb_value (inttable) and string->upb_value
-** (strtable) hash tables.
-**
-** The table uses chained scatter with Brent's variation (inspired by the Lua
-** implementation of hash tables). The hash function for strings is Austin
-** Appleby's "MurmurHash."
-**
-** The inttable uses uintptr_t as its key, which guarantees it can be used to
-** store pointers or integers of at least 32 bits (upb isn't really useful on
-** systems where sizeof(void*) < 4).
-**
-** The table must be homogenous (all values of the same type). In debug
-** mode, we check this on insert and lookup.
-*/
-
-#ifndef UPB_TABLE_H_
-#define UPB_TABLE_H_
+#ifndef UPB_H_
+#define UPB_H_
// php.h intentionally defined NDEBUG. We have to define this macro in order to
// be used together with php.h
@@ -68,18 +15,6 @@
#define NDEBUG
#endif
-#include <stdint.h>
-#include <string.h>
-/*
-** This file contains shared definitions that are widely used across upb.
-**
-** This is a mixed C/C++ interface that offers a full API to both languages.
-** See the top-level README for more information.
-*/
-
-#ifndef UPB_H_
-#define UPB_H_
-
#include <assert.h>
#include <stdarg.h>
#include <stdbool.h>
@@ -106,6 +41,9 @@ template <int N> class InlinedEnvironment;
#define UPB_INLINE static
#endif
+/* Hints to the compiler about likely/unlikely branches. */
+#define UPB_LIKELY(x) __builtin_expect((x),1)
+
/* Define UPB_BIG_ENDIAN manually if you're on big endian and your compiler
* doesn't provide these preprocessor symbols. */
#if defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
@@ -123,20 +61,21 @@ template <int N> class InlinedEnvironment;
#define UPB_NORETURN
#endif
+#if __STDC_VERSION__ >= 199901L || __cplusplus >= 201103L
+/* C99/C++11 versions. */
+#include <stdio.h>
+#define _upb_snprintf snprintf
+#define _upb_vsnprintf vsnprintf
+#define _upb_va_copy(a, b) va_copy(a, b)
+#elif defined __GNUC__
/* A few hacky workarounds for functions not in C89.
* For internal use only!
* TODO(haberman): fix these by including our own implementations, or finding
* another workaround.
*/
-#ifdef __GNUC__
#define _upb_snprintf __builtin_snprintf
#define _upb_vsnprintf __builtin_vsnprintf
#define _upb_va_copy(a, b) __va_copy(a, b)
-#elif __STDC_VERSION__ >= 199901L
-/* C99 versions. */
-#define _upb_snprintf snprintf
-#define _upb_vsnprintf vsnprintf
-#define _upb_va_copy(a, b) va_copy(a, b)
#else
#error Need implementations of [v]snprintf and va_copy
#endif
@@ -280,6 +219,12 @@ template <int N> class InlinedEnvironment;
* exist in debug mode. This turns into regular assert. */
#define UPB_ASSERT_DEBUGVAR(expr) assert(expr)
+#ifdef __GNUC__
+#define UPB_UNREACHABLE() do { assert(0); __builtin_unreachable(); } while(0)
+#else
+#define UPB_UNREACHABLE() do { assert(0); } while(0)
+#endif
+
/* Generic function type. */
typedef void upb_func();
@@ -360,6 +305,16 @@ class PointerBase2 : public PointerBase<T, Base> {
#endif
+/* A list of types as they are encoded on-the-wire. */
+typedef enum {
+ UPB_WIRE_TYPE_VARINT = 0,
+ UPB_WIRE_TYPE_64BIT = 1,
+ UPB_WIRE_TYPE_DELIMITED = 2,
+ UPB_WIRE_TYPE_START_GROUP = 3,
+ UPB_WIRE_TYPE_END_GROUP = 4,
+ UPB_WIRE_TYPE_32BIT = 5
+} upb_wiretype_t;
+
/* upb::ErrorSpace ************************************************************/
@@ -513,17 +468,18 @@ struct upb_alloc {
};
UPB_INLINE void *upb_malloc(upb_alloc *alloc, size_t size) {
- UPB_ASSERT(size > 0);
+ UPB_ASSERT(alloc);
return alloc->func(alloc, NULL, 0, size);
}
UPB_INLINE void *upb_realloc(upb_alloc *alloc, void *ptr, size_t oldsize,
size_t size) {
- UPB_ASSERT(size > 0);
+ UPB_ASSERT(alloc);
return alloc->func(alloc, ptr, oldsize, size);
}
UPB_INLINE void upb_free(upb_alloc *alloc, void *ptr) {
+ assert(alloc);
alloc->func(alloc, ptr, 0, 0);
}
@@ -572,11 +528,11 @@ UPB_BEGIN_EXTERN_C
void upb_arena_init(upb_arena *a);
void upb_arena_init2(upb_arena *a, void *mem, size_t n, upb_alloc *alloc);
void upb_arena_uninit(upb_arena *a);
-upb_alloc *upb_arena_alloc(upb_arena *a);
bool upb_arena_addcleanup(upb_arena *a, upb_cleanup_func *func, void *ud);
size_t upb_arena_bytesallocated(const upb_arena *a);
void upb_arena_setnextblocksize(upb_arena *a, size_t size);
void upb_arena_setmaxblocksize(upb_arena *a, size_t size);
+UPB_INLINE upb_alloc *upb_arena_alloc(upb_arena *a) { return (upb_alloc*)a; }
UPB_END_EXTERN_C
@@ -687,7 +643,7 @@ void upb_env_uninit(upb_env *e);
void upb_env_initonly(upb_env *e);
-upb_arena *upb_env_arena(upb_env *e);
+UPB_INLINE upb_arena *upb_env_arena(upb_env *e) { return (upb_arena*)e; }
bool upb_env_ok(const upb_env *e);
void upb_env_seterrorfunc(upb_env *e, upb_error_func *func, void *ud);
@@ -787,6 +743,106 @@ template <int N> class upb::InlinedEnvironment : public upb::Environment {
#endif /* UPB_H_ */
+/*
+** upb_decode: parsing into a upb_msg using a upb_msglayout.
+*/
+
+#ifndef UPB_DECODE_H_
+#define UPB_DECODE_H_
+
+/*
+** upb::Message is a representation for protobuf messages.
+**
+** However it differs from other common representations like
+** google::protobuf::Message in one key way: it does not prescribe any
+** ownership between messages and submessages, and it relies on the
+** client to delete each message/submessage/array/map at the appropriate
+** time.
+**
+** A client can access a upb::Message without knowing anything about
+** ownership semantics, but to create or mutate a message a user needs
+** to implement the memory management themselves.
+**
+** Currently all messages, arrays, and maps store a upb_alloc* internally.
+** Mutating operations use this when they require dynamically-allocated
+** memory. We could potentially eliminate this size overhead later by
+** letting the user flip a bit on the factory that prevents this from
+** being stored. The user would then need to use separate functions where
+** the upb_alloc* is passed explicitly. However for handlers to populate
+** such structures, they would need a place to store this upb_alloc* during
+** parsing; upb_handlers don't currently have a good way to accommodate this.
+**
+** TODO: UTF-8 checking?
+**/
+
+#ifndef UPB_MSG_H_
+#define UPB_MSG_H_
+
+/*
+** Defs are upb's internal representation of the constructs that can appear
+** in a .proto file:
+**
+** - upb::MessageDef (upb_msgdef): describes a "message" construct.
+** - upb::FieldDef (upb_fielddef): describes a message field.
+** - upb::FileDef (upb_filedef): describes a .proto file and its defs.
+** - upb::EnumDef (upb_enumdef): describes an enum.
+** - upb::OneofDef (upb_oneofdef): describes a oneof.
+** - upb::Def (upb_def): base class of all the others.
+**
+** TODO: definitions of services.
+**
+** Like upb_refcounted objects, defs are mutable only until frozen, and are
+** only thread-safe once frozen.
+**
+** This is a mixed C/C++ interface that offers a full API to both languages.
+** See the top-level README for more information.
+*/
+
+#ifndef UPB_DEF_H_
+#define UPB_DEF_H_
+
+/*
+** upb::RefCounted (upb_refcounted)
+**
+** A refcounting scheme that supports circular refs. It accomplishes this by
+** partitioning the set of objects into groups such that no cycle spans groups;
+** we can then reference-count the group as a whole and ignore refs within the
+** group. When objects are mutable, these groups are computed very
+** conservatively; we group any objects that have ever had a link between them.
+** When objects are frozen, we compute strongly-connected components which
+** allows us to be precise and only group objects that are actually cyclic.
+**
+** This is a mixed C/C++ interface that offers a full API to both languages.
+** See the top-level README for more information.
+*/
+
+#ifndef UPB_REFCOUNTED_H_
+#define UPB_REFCOUNTED_H_
+
+/*
+** upb_table
+**
+** This header is INTERNAL-ONLY! Its interfaces are not public or stable!
+** This file defines very fast int->upb_value (inttable) and string->upb_value
+** (strtable) hash tables.
+**
+** The table uses chained scatter with Brent's variation (inspired by the Lua
+** implementation of hash tables). The hash function for strings is Austin
+** Appleby's "MurmurHash."
+**
+** The inttable uses uintptr_t as its key, which guarantees it can be used to
+** store pointers or integers of at least 32 bits (upb isn't really useful on
+** systems where sizeof(void*) < 4).
+**
+** The table must be homogenous (all values of the same type). In debug
+** mode, we check this on insert and lookup.
+*/
+
+#ifndef UPB_TABLE_H_
+#define UPB_TABLE_H_
+
+#include <stdint.h>
+#include <string.h>
#ifdef __cplusplus
extern "C" {
@@ -807,7 +863,9 @@ typedef enum {
UPB_CTYPE_CSTR = 6,
UPB_CTYPE_PTR = 7,
UPB_CTYPE_CONSTPTR = 8,
- UPB_CTYPE_FPTR = 9
+ UPB_CTYPE_FPTR = 9,
+ UPB_CTYPE_FLOAT = 10,
+ UPB_CTYPE_DOUBLE = 11
} upb_ctype_t;
typedef struct {
@@ -881,6 +939,29 @@ FUNCS(constptr, constptr, const void*, uintptr_t, UPB_CTYPE_CONSTPTR)
FUNCS(fptr, fptr, upb_func*, uintptr_t, UPB_CTYPE_FPTR)
#undef FUNCS
+
+UPB_INLINE void upb_value_setfloat(upb_value *val, float cval) {
+ memcpy(&val->val, &cval, sizeof(cval));
+ SET_TYPE(val->ctype, UPB_CTYPE_FLOAT);
+}
+
+UPB_INLINE void upb_value_setdouble(upb_value *val, double cval) {
+ memcpy(&val->val, &cval, sizeof(cval));
+ SET_TYPE(val->ctype, UPB_CTYPE_DOUBLE);
+}
+
+UPB_INLINE upb_value upb_value_float(float cval) {
+ upb_value ret;
+ upb_value_setfloat(&ret, cval);
+ return ret;
+}
+
+UPB_INLINE upb_value upb_value_double(double cval) {
+ upb_value ret;
+ upb_value_setdouble(&ret, cval);
+ return ret;
+}
+
#undef SET_TYPE
@@ -1123,6 +1204,13 @@ UPB_INLINE size_t upb_strtable_count(const upb_strtable *t) {
return t->t.count;
}
+void upb_inttable_packedsize(const upb_inttable *t, size_t *size);
+void upb_strtable_packedsize(const upb_strtable *t, size_t *size);
+upb_inttable *upb_inttable_pack(const upb_inttable *t, void *p, size_t *ofs,
+ size_t size);
+upb_strtable *upb_strtable_pack(const upb_strtable *t, void *p, size_t *ofs,
+ size_t size);
+
/* Inserts the given key into the hashtable with the given value. The key must
* not already exist in the hash table. For string tables, the key must be
* NULL-terminated, and the table will make an internal copy of the key.
@@ -1669,6 +1757,7 @@ class FieldDef;
class FileDef;
class MessageDef;
class OneofDef;
+class SymbolTable;
}
#endif
@@ -1677,6 +1766,8 @@ UPB_DECLARE_DERIVED_TYPE(upb::OneofDef, upb::RefCounted, upb_oneofdef,
upb_refcounted)
UPB_DECLARE_DERIVED_TYPE(upb::FileDef, upb::RefCounted, upb_filedef,
upb_refcounted)
+UPB_DECLARE_TYPE(upb::SymbolTable, upb_symtab)
+
/* The maximum message depth that the type graph can have. This is a resource
* limit for the C stack since we sometimes need to recursively traverse the
@@ -1710,8 +1801,6 @@ class upb::Def {
public:
typedef upb_deftype_t Type;
- Def* Dup(const void *owner) const;
-
/* upb::RefCounted methods like Ref()/Unref(). */
UPB_REFCOUNTED_CPPMETHODS
@@ -1757,9 +1846,6 @@ class upb::Def {
UPB_BEGIN_EXTERN_C
-/* Native C API. */
-upb_def *upb_def_dup(const upb_def *def, const void *owner);
-
/* Include upb_refcounted methods like upb_def_ref()/upb_def_unref(). */
UPB_REFCOUNTED_CMETHODS(upb_def, upb_def_upcast)
@@ -1856,15 +1942,19 @@ UPB_DECLARE_DEF_TYPE(upb::EnumDef, enumdef, ENUM)
* types defined in descriptor.proto, which gives INT32 and SINT32 separate
* types (we distinguish the two with the "integer encoding" enum below). */
typedef enum {
- UPB_TYPE_FLOAT = 1,
- UPB_TYPE_DOUBLE = 2,
- UPB_TYPE_BOOL = 3,
- UPB_TYPE_STRING = 4,
- UPB_TYPE_BYTES = 5,
- UPB_TYPE_MESSAGE = 6,
- UPB_TYPE_ENUM = 7, /* Enum values are int32. */
- UPB_TYPE_INT32 = 8,
- UPB_TYPE_UINT32 = 9,
+ /* Types stored in 1 byte. */
+ UPB_TYPE_BOOL = 1,
+ /* Types stored in 4 bytes. */
+ UPB_TYPE_FLOAT = 2,
+ UPB_TYPE_INT32 = 3,
+ UPB_TYPE_UINT32 = 4,
+ UPB_TYPE_ENUM = 5, /* Enum values are int32. */
+ /* Types stored as pointers (probably 4 or 8 bytes). */
+ UPB_TYPE_STRING = 6,
+ UPB_TYPE_BYTES = 7,
+ UPB_TYPE_MESSAGE = 8,
+ /* Types stored as 8 bytes. */
+ UPB_TYPE_DOUBLE = 9,
UPB_TYPE_INT64 = 10,
UPB_TYPE_UINT64 = 11
} upb_fieldtype_t;
@@ -1945,13 +2035,6 @@ class upb::FieldDef {
/* Returns NULL if memory allocation failed. */
static reffed_ptr<FieldDef> New();
- /* Duplicates the given field, returning NULL if memory allocation failed.
- * When a fielddef is duplicated, the subdef (if any) is made symbolic if it
- * wasn't already. If the subdef is set but has no name (which is possible
- * since msgdefs are not required to have a name) the new fielddef's subdef
- * will be unset. */
- FieldDef* Dup(const void* owner) const;
-
/* upb::RefCounted methods like Ref()/Unref(). */
UPB_REFCOUNTED_CPPMETHODS
@@ -2038,16 +2121,10 @@ class upb::FieldDef {
bool IsPrimitive() const;
bool IsMap() const;
- /* Whether this field must be able to explicitly represent presence:
- *
- * * This is always false for repeated fields (an empty repeated field is
- * equivalent to a repeated field with zero entries).
+ /* Returns whether this field explicitly represents presence.
*
- * * This is always true for submessages.
- *
- * * For other fields, it depends on the message (see
- * MessageDef::SetPrimitivesHavePresence())
- */
+ * For proto2 messages: Returns true for any scalar (non-repeated) field.
+ * For proto3 messages: Returns true for scalar submessage or oneof fields. */
bool HasPresence() const;
/* How integers are encoded. Only meaningful for integer types.
@@ -2206,7 +2283,6 @@ UPB_BEGIN_EXTERN_C
/* Native C API. */
upb_fielddef *upb_fielddef_new(const void *owner);
-upb_fielddef *upb_fielddef_dup(const upb_fielddef *f, const void *owner);
/* Include upb_refcounted methods like upb_fielddef_ref(). */
UPB_REFCOUNTED_CMETHODS(upb_fielddef, upb_fielddef_upcast2)
@@ -2416,16 +2492,6 @@ class upb::MessageDef {
return FindOneofByName(str.c_str(), str.size());
}
- /* Returns a new msgdef that is a copy of the given msgdef (and a copy of all
- * the fields) but with any references to submessages broken and replaced
- * with just the name of the submessage. Returns NULL if memory allocation
- * failed.
- *
- * TODO(haberman): which is more useful, keeping fields resolved or
- * unresolving them? If there's no obvious answer, Should this functionality
- * just be moved into symtab.c? */
- MessageDef* Dup(const void* owner) const;
-
/* Is this message a map entry? */
void setmapentry(bool map_entry);
bool mapentry() const;
@@ -2559,7 +2625,6 @@ UPB_REFCOUNTED_CMETHODS(upb_msgdef, upb_msgdef_upcast2)
bool upb_msgdef_freeze(upb_msgdef *m, upb_status *status);
-upb_msgdef *upb_msgdef_dup(const upb_msgdef *m, const void *owner);
const char *upb_msgdef_fullname(const upb_msgdef *m);
const char *upb_msgdef_name(const upb_msgdef *m);
int upb_msgdef_numoneofs(const upb_msgdef *m);
@@ -2709,10 +2774,6 @@ class upb::EnumDef {
* first one that was added. */
const char* FindValueByNumber(int32_t num) const;
- /* Returns a new EnumDef with all the same values. The new EnumDef will be
- * owned by the given owner. */
- EnumDef* Dup(const void* owner) const;
-
/* Iteration over name/value pairs. The order is undefined.
* Adding an enum val invalidates any iterators.
*
@@ -2740,7 +2801,6 @@ UPB_BEGIN_EXTERN_C
/* Native C API. */
upb_enumdef *upb_enumdef_new(const void *owner);
-upb_enumdef *upb_enumdef_dup(const upb_enumdef *e, const void *owner);
/* Include upb_refcounted methods like upb_enumdef_ref(). */
UPB_REFCOUNTED_CMETHODS(upb_enumdef, upb_enumdef_upcast2)
@@ -2785,6 +2845,7 @@ int32_t upb_enum_iter_number(upb_enum_iter *iter);
UPB_END_EXTERN_C
+
/* upb::OneofDef **************************************************************/
typedef upb_inttable_iter upb_oneof_iter;
@@ -2849,10 +2910,6 @@ class upb::OneofDef {
/* Looks up by tag number. */
const FieldDef* FindFieldByNumber(uint32_t num) const;
- /* Returns a new OneofDef with all the same fields. The OneofDef will be owned
- * by the given owner. */
- OneofDef* Dup(const void* owner) const;
-
/* Iteration over fields. The order is undefined. */
class iterator : public std::iterator<std::forward_iterator_tag, FieldDef*> {
public:
@@ -2898,16 +2955,16 @@ UPB_BEGIN_EXTERN_C
/* Native C API. */
upb_oneofdef *upb_oneofdef_new(const void *owner);
-upb_oneofdef *upb_oneofdef_dup(const upb_oneofdef *o, const void *owner);
/* Include upb_refcounted methods like upb_oneofdef_ref(). */
UPB_REFCOUNTED_CMETHODS(upb_oneofdef, upb_oneofdef_upcast)
const char *upb_oneofdef_name(const upb_oneofdef *o);
-bool upb_oneofdef_setname(upb_oneofdef *o, const char *name, upb_status *s);
-
const upb_msgdef *upb_oneofdef_containingtype(const upb_oneofdef *o);
int upb_oneofdef_numfields(const upb_oneofdef *o);
+uint32_t upb_oneofdef_index(const upb_oneofdef *o);
+
+bool upb_oneofdef_setname(upb_oneofdef *o, const char *name, upb_status *s);
bool upb_oneofdef_addfield(upb_oneofdef *o, upb_fielddef *f,
const void *ref_donor,
upb_status *s);
@@ -2963,6 +3020,17 @@ class upb::FileDef {
const char* package() const;
bool set_package(const char* package, Status* s);
+ /* Sets the php class prefix which is prepended to all php generated classes
+ * from this .proto. Default is empty. */
+ const char* phpprefix() const;
+ bool set_phpprefix(const char* phpprefix, Status* s);
+
+ /* Use this option to change the namespace of php generated classes. Default
+ * is empty. When this option is empty, the package name will be used for
+ * determining the namespace. */
+ const char* phpnamespace() const;
+ bool set_phpnamespace(const char* phpnamespace, Status* s);
+
/* Syntax for the file. Defaults to proto2. */
upb_syntax_t syntax() const;
void set_syntax(upb_syntax_t syntax);
@@ -3016,6 +3084,8 @@ UPB_REFCOUNTED_CMETHODS(upb_filedef, upb_filedef_upcast)
const char *upb_filedef_name(const upb_filedef *f);
const char *upb_filedef_package(const upb_filedef *f);
+const char *upb_filedef_phpprefix(const upb_filedef *f);
+const char *upb_filedef_phpnamespace(const upb_filedef *f);
upb_syntax_t upb_filedef_syntax(const upb_filedef *f);
size_t upb_filedef_defcount(const upb_filedef *f);
size_t upb_filedef_depcount(const upb_filedef *f);
@@ -3025,6 +3095,10 @@ const upb_filedef *upb_filedef_dep(const upb_filedef *f, size_t i);
bool upb_filedef_freeze(upb_filedef *f, upb_status *s);
bool upb_filedef_setname(upb_filedef *f, const char *name, upb_status *s);
bool upb_filedef_setpackage(upb_filedef *f, const char *package, upb_status *s);
+bool upb_filedef_setphpprefix(upb_filedef *f, const char *phpprefix,
+ upb_status *s);
+bool upb_filedef_setphpnamespace(upb_filedef *f, const char *phpnamespace,
+ upb_status *s);
bool upb_filedef_setsyntax(upb_filedef *f, upb_syntax_t syntax, upb_status *s);
bool upb_filedef_adddef(upb_filedef *f, upb_def *def, const void *ref_donor,
@@ -3051,6 +3125,153 @@ UPB_INLINE upb_def *upb_filedef_mutabledef(upb_filedef *f, int i) {
UPB_END_EXTERN_C
+typedef struct {
+ UPB_PRIVATE_FOR_CPP
+ upb_strtable_iter iter;
+ upb_deftype_t type;
+} upb_symtab_iter;
+
+#ifdef __cplusplus
+
+/* Non-const methods in upb::SymbolTable are NOT thread-safe. */
+class upb::SymbolTable {
+ public:
+ /* Returns a new symbol table with a single ref owned by "owner."
+ * Returns NULL if memory allocation failed. */
+ static SymbolTable* New();
+ static void Free(upb::SymbolTable* table);
+
+ /* For all lookup functions, the returned pointer is not owned by the
+ * caller; it may be invalidated by any non-const call or unref of the
+ * SymbolTable! To protect against this, take a ref if desired. */
+
+ /* Freezes the symbol table: prevents further modification of it.
+ * After the Freeze() operation is successful, the SymbolTable must only be
+ * accessed via a const pointer.
+ *
+ * Unlike with upb::MessageDef/upb::EnumDef/etc, freezing a SymbolTable is not
+ * a necessary step in using a SymbolTable. If you have no need for it to be
+ * immutable, there is no need to freeze it ever. However sometimes it is
+ * useful, and SymbolTables that are statically compiled into the binary are
+ * always frozen by nature. */
+ void Freeze();
+
+ /* Resolves the given symbol using the rules described in descriptor.proto,
+ * namely:
+ *
+ * If the name starts with a '.', it is fully-qualified. Otherwise,
+ * C++-like scoping rules are used to find the type (i.e. first the nested
+ * types within this message are searched, then within the parent, on up
+ * to the root namespace).
+ *
+ * If not found, returns NULL. */
+ const Def* Resolve(const char* base, const char* sym) const;
+
+ /* Finds an entry in the symbol table with this exact name. If not found,
+ * returns NULL. */
+ const Def* Lookup(const char *sym) const;
+ const MessageDef* LookupMessage(const char *sym) const;
+ const EnumDef* LookupEnum(const char *sym) const;
+
+ /* TODO: introduce a C++ iterator, but make it nice and templated so that if
+ * you ask for an iterator of MessageDef the iterated elements are strongly
+ * typed as MessageDef*. */
+
+ /* Adds the given mutable defs to the symtab, resolving all symbols (including
+ * enum default values) and finalizing the defs. Only one def per name may be
+ * in the list, and the defs may not duplicate any name already in the symtab.
+ * All defs must have a name -- anonymous defs are not allowed. Anonymous
+ * defs can still be frozen by calling upb_def_freeze() directly.
+ *
+ * The entire operation either succeeds or fails. If the operation fails,
+ * the symtab is unchanged, false is returned, and status indicates the
+ * error. The caller passes a ref on all defs to the symtab (even if the
+ * operation fails).
+ *
+ * TODO(haberman): currently failure will leave the symtab unchanged, but may
+ * leave the defs themselves partially resolved. Does this matter? If so we
+ * could do a prepass that ensures that all symbols are resolvable and bail
+ * if not, so we don't mutate anything until we know the operation will
+ * succeed. */
+ bool Add(Def*const* defs, size_t n, void* ref_donor, Status* status);
+
+ bool Add(const std::vector<Def*>& defs, void *owner, Status* status) {
+ return Add((Def*const*)&defs[0], defs.size(), owner, status);
+ }
+
+ /* Resolves all subdefs for messages in this file and attempts to freeze the
+ * file. If this succeeds, adds all the symbols to this SymbolTable
+ * (replacing any existing ones with the same names). */
+ bool AddFile(FileDef* file, Status* s);
+
+ private:
+ UPB_DISALLOW_POD_OPS(SymbolTable, upb::SymbolTable)
+};
+
+#endif /* __cplusplus */
+
+UPB_BEGIN_EXTERN_C
+
+/* Native C API. */
+
+upb_symtab *upb_symtab_new();
+void upb_symtab_free(upb_symtab* s);
+const upb_def *upb_symtab_resolve(const upb_symtab *s, const char *base,
+ const char *sym);
+const upb_def *upb_symtab_lookup(const upb_symtab *s, const char *sym);
+const upb_msgdef *upb_symtab_lookupmsg(const upb_symtab *s, const char *sym);
+const upb_enumdef *upb_symtab_lookupenum(const upb_symtab *s, const char *sym);
+bool upb_symtab_add(upb_symtab *s, upb_def *const*defs, size_t n,
+ void *ref_donor, upb_status *status);
+bool upb_symtab_addfile(upb_symtab *s, upb_filedef *file, upb_status* status);
+
+/* upb_symtab_iter i;
+ * for(upb_symtab_begin(&i, s, type); !upb_symtab_done(&i);
+ * upb_symtab_next(&i)) {
+ * const upb_def *def = upb_symtab_iter_def(&i);
+ * // ...
+ * }
+ *
+ * For C we don't have separate iterators for const and non-const.
+ * It is the caller's responsibility to cast the upb_fielddef* to
+ * const if the upb_msgdef* is const. */
+void upb_symtab_begin(upb_symtab_iter *iter, const upb_symtab *s,
+ upb_deftype_t type);
+void upb_symtab_next(upb_symtab_iter *iter);
+bool upb_symtab_done(const upb_symtab_iter *iter);
+const upb_def *upb_symtab_iter_def(const upb_symtab_iter *iter);
+
+UPB_END_EXTERN_C
+
+#ifdef __cplusplus
+/* C++ inline wrappers. */
+namespace upb {
+inline SymbolTable* SymbolTable::New() {
+ return upb_symtab_new();
+}
+inline void SymbolTable::Free(SymbolTable* s) {
+ upb_symtab_free(s);
+}
+inline const Def *SymbolTable::Resolve(const char *base,
+ const char *sym) const {
+ return upb_symtab_resolve(this, base, sym);
+}
+inline const Def* SymbolTable::Lookup(const char *sym) const {
+ return upb_symtab_lookup(this, sym);
+}
+inline const MessageDef *SymbolTable::LookupMessage(const char *sym) const {
+ return upb_symtab_lookupmsg(this, sym);
+}
+inline bool SymbolTable::Add(
+ Def*const* defs, size_t n, void* ref_donor, Status* status) {
+ return upb_symtab_add(this, (upb_def*const*)defs, n, ref_donor, status);
+}
+inline bool SymbolTable::AddFile(FileDef* file, Status* s) {
+ return upb_symtab_addfile(this, file, s);
+}
+} /* namespace upb */
+#endif
+
#ifdef __cplusplus
UPB_INLINE const char* upb_safecstr(const std::string& str) {
@@ -3061,9 +3282,6 @@ UPB_INLINE const char* upb_safecstr(const std::string& str) {
/* Inline C++ wrappers. */
namespace upb {
-inline Def* Def::Dup(const void* owner) const {
- return upb_def_dup(this, owner);
-}
inline Def::Type Def::def_type() const { return upb_def_type(this); }
inline const char* Def::full_name() const { return upb_def_fullname(this); }
inline const char* Def::name() const { return upb_def_name(this); }
@@ -3113,9 +3331,6 @@ inline reffed_ptr<FieldDef> FieldDef::New() {
upb_fielddef *f = upb_fielddef_new(&f);
return reffed_ptr<FieldDef>(f, &f);
}
-inline FieldDef* FieldDef::Dup(const void* owner) const {
- return upb_fielddef_dup(this, owner);
-}
inline const char* FieldDef::full_name() const {
return upb_fielddef_fullname(this);
}
@@ -3355,9 +3570,6 @@ inline const OneofDef* MessageDef::FindOneofByName(const char* name,
size_t len) const {
return upb_msgdef_ntoo(this, name, len);
}
-inline MessageDef* MessageDef::Dup(const void *owner) const {
- return upb_msgdef_dup(this, owner);
-}
inline void MessageDef::setmapentry(bool map_entry) {
upb_msgdef_setmapentry(this, map_entry);
}
@@ -3527,9 +3739,6 @@ inline bool EnumDef::FindValueByName(const char* name, int32_t *num) const {
inline const char* EnumDef::FindValueByNumber(int32_t num) const {
return upb_enumdef_iton(this, num);
}
-inline EnumDef* EnumDef::Dup(const void* owner) const {
- return upb_enumdef_dup(this, owner);
-}
inline EnumDef::Iterator::Iterator(const EnumDef* e) {
upb_enum_begin(&iter_, e);
@@ -3648,6 +3857,18 @@ inline const char* FileDef::package() const {
inline bool FileDef::set_package(const char* package, Status* s) {
return upb_filedef_setpackage(this, package, s);
}
+inline const char* FileDef::phpprefix() const {
+ return upb_filedef_phpprefix(this);
+}
+inline bool FileDef::set_phpprefix(const char* phpprefix, Status* s) {
+ return upb_filedef_setphpprefix(this, phpprefix, s);
+}
+inline const char* FileDef::phpnamespace() const {
+ return upb_filedef_phpnamespace(this);
+}
+inline bool FileDef::set_phpnamespace(const char* phpnamespace, Status* s) {
+ return upb_filedef_setphpnamespace(this, phpnamespace, s);
+}
inline int FileDef::def_count() const {
return upb_filedef_defcount(this);
}
@@ -3684,193 +3905,6 @@ inline bool FileDef::AddDependency(const FileDef* file) {
#endif /* UPB_DEF_H_ */
/*
-** This file contains definitions of structs that should be considered private
-** and NOT stable across versions of upb.
-**
-** The only reason they are declared here and not in .c files is to allow upb
-** and the application (if desired) to embed statically-initialized instances
-** of structures like defs.
-**
-** If you include this file, all guarantees of ABI compatibility go out the
-** window! Any code that includes this file needs to recompile against the
-** exact same version of upb that they are linking against.
-**
-** You also need to recompile if you change the value of the UPB_DEBUG_REFS
-** flag.
-*/
-
-
-#ifndef UPB_STATICINIT_H_
-#define UPB_STATICINIT_H_
-
-#ifdef __cplusplus
-/* Because of how we do our typedefs, this header can't be included from C++. */
-#error This file cannot be included from C++
-#endif
-
-/* upb_refcounted *************************************************************/
-
-
-/* upb_def ********************************************************************/
-
-struct upb_def {
- upb_refcounted base;
-
- const char *fullname;
- const upb_filedef* file;
- char type; /* A upb_deftype_t (char to save space) */
-
- /* Used as a flag during the def's mutable stage. Must be false unless
- * it is currently being used by a function on the stack. This allows
- * us to easily determine which defs were passed into the function's
- * current invocation. */
- bool came_from_user;
-};
-
-#define UPB_DEF_INIT(name, type, vtbl, refs, ref2s) \
- { UPB_REFCOUNT_INIT(vtbl, refs, ref2s), name, NULL, type, false }
-
-
-/* upb_fielddef ***************************************************************/
-
-struct upb_fielddef {
- upb_def base;
-
- union {
- int64_t sint;
- uint64_t uint;
- double dbl;
- float flt;
- void *bytes;
- } defaultval;
- union {
- const upb_msgdef *def; /* If !msg_is_symbolic. */
- char *name; /* If msg_is_symbolic. */
- } msg;
- union {
- const upb_def *def; /* If !subdef_is_symbolic. */
- char *name; /* If subdef_is_symbolic. */
- } sub; /* The msgdef or enumdef for this field, if upb_hassubdef(f). */
- bool subdef_is_symbolic;
- bool msg_is_symbolic;
- const upb_oneofdef *oneof;
- bool default_is_string;
- bool type_is_set_; /* False until type is explicitly set. */
- bool is_extension_;
- bool lazy_;
- bool packed_;
- upb_intfmt_t intfmt;
- bool tagdelim;
- upb_fieldtype_t type_;
- upb_label_t label_;
- uint32_t number_;
- uint32_t selector_base; /* Used to index into a upb::Handlers table. */
- uint32_t index_;
-};
-
-extern const struct upb_refcounted_vtbl upb_fielddef_vtbl;
-
-#define UPB_FIELDDEF_INIT(label, type, intfmt, tagdelim, is_extension, lazy, \
- packed, name, num, msgdef, subdef, selector_base, \
- index, defaultval, refs, ref2s) \
- { \
- UPB_DEF_INIT(name, UPB_DEF_FIELD, &upb_fielddef_vtbl, refs, ref2s), \
- defaultval, {msgdef}, {subdef}, NULL, false, false, \
- type == UPB_TYPE_STRING || type == UPB_TYPE_BYTES, true, is_extension, \
- lazy, packed, intfmt, tagdelim, type, label, num, selector_base, index \
- }
-
-
-/* upb_msgdef *****************************************************************/
-
-struct upb_msgdef {
- upb_def base;
-
- size_t selector_count;
- uint32_t submsg_field_count;
-
- /* Tables for looking up fields by number and name. */
- upb_inttable itof; /* int to field */
- upb_strtable ntof; /* name to field/oneof */
-
- /* Is this a map-entry message? */
- bool map_entry;
-
- /* Whether this message has proto2 or proto3 semantics. */
- upb_syntax_t syntax;
-
- /* TODO(haberman): proper extension ranges (there can be multiple). */
-};
-
-extern const struct upb_refcounted_vtbl upb_msgdef_vtbl;
-
-/* TODO: also support static initialization of the oneofs table. This will be
- * needed if we compile in descriptors that contain oneofs. */
-#define UPB_MSGDEF_INIT(name, selector_count, submsg_field_count, itof, ntof, \
- map_entry, syntax, refs, ref2s) \
- { \
- UPB_DEF_INIT(name, UPB_DEF_MSG, &upb_fielddef_vtbl, refs, ref2s), \
- selector_count, submsg_field_count, itof, ntof, map_entry, syntax \
- }
-
-
-/* upb_enumdef ****************************************************************/
-
-struct upb_enumdef {
- upb_def base;
-
- upb_strtable ntoi;
- upb_inttable iton;
- int32_t defaultval;
-};
-
-extern const struct upb_refcounted_vtbl upb_enumdef_vtbl;
-
-#define UPB_ENUMDEF_INIT(name, ntoi, iton, defaultval, refs, ref2s) \
- { UPB_DEF_INIT(name, UPB_DEF_ENUM, &upb_enumdef_vtbl, refs, ref2s), ntoi, \
- iton, defaultval }
-
-
-/* upb_oneofdef ***************************************************************/
-
-struct upb_oneofdef {
- upb_refcounted base;
-
- const char *name;
- upb_strtable ntof;
- upb_inttable itof;
- const upb_msgdef *parent;
-};
-
-extern const struct upb_refcounted_vtbl upb_oneofdef_vtbl;
-
-#define UPB_ONEOFDEF_INIT(name, ntof, itof, refs, ref2s) \
- { UPB_REFCOUNT_INIT(&upb_oneofdef_vtbl, refs, ref2s), name, ntof, itof }
-
-
-/* upb_symtab *****************************************************************/
-
-struct upb_symtab {
- upb_refcounted base;
-
- upb_strtable symtab;
-};
-
-struct upb_filedef {
- upb_refcounted base;
-
- const char *name;
- const char *package;
- upb_syntax_t syntax;
-
- upb_inttable defs;
- upb_inttable deps;
-};
-
-extern const struct upb_refcounted_vtbl upb_filedef_vtbl;
-
-#endif /* UPB_STATICINIT_H_ */
-/*
** upb::Handlers (upb_handlers)
**
** A upb_handlers is like a virtual table for a upb_msgdef. Each field of the
@@ -3974,7 +4008,8 @@ UPB_END_EXTERN_C
/* Static selectors for upb::Handlers. */
#define UPB_STARTMSG_SELECTOR 0
#define UPB_ENDMSG_SELECTOR 1
-#define UPB_STATIC_SELECTOR_COUNT 2
+#define UPB_UNKNOWN_SELECTOR 2
+#define UPB_STATIC_SELECTOR_COUNT 3
/* Static selectors for upb::BytesHandler. */
#define UPB_STARTSTR_SELECTOR 0
@@ -4503,6 +4538,8 @@ UPB_BEGIN_EXTERN_C
/* Native C API. */
/* Handler function typedefs. */
+typedef bool upb_unknown_handlerfunc(void *c, const void *hd, const char *buf,
+ size_t n);
typedef bool upb_startmsg_handlerfunc(void *c, const void*);
typedef bool upb_endmsg_handlerfunc(void *c, const void *, upb_status *status);
typedef void* upb_startfield_handlerfunc(void *c, const void *hd);
@@ -4556,6 +4593,8 @@ const upb_status *upb_handlers_status(upb_handlers *h);
void upb_handlers_clearerr(upb_handlers *h);
const upb_msgdef *upb_handlers_msgdef(const upb_handlers *h);
bool upb_handlers_addcleanup(upb_handlers *h, void *p, upb_handlerfree *hfree);
+bool upb_handlers_setunknown(upb_handlers *h, upb_unknown_handlerfunc *func,
+ upb_handlerattr *attr);
bool upb_handlers_setstartmsg(upb_handlers *h, upb_startmsg_handlerfunc *func,
upb_handlerattr *attr);
@@ -5832,12 +5871,14 @@ inline BytesHandler::~BytesHandler() {}
#ifdef __cplusplus
namespace upb {
+class BufferSink;
class BufferSource;
class BytesSink;
class Sink;
}
#endif
+UPB_DECLARE_TYPE(upb::BufferSink, upb_bufsink)
UPB_DECLARE_TYPE(upb::BufferSource, upb_bufsrc)
UPB_DECLARE_TYPE(upb::BytesSink, upb_bytessink)
UPB_DECLARE_TYPE(upb::Sink, upb_sink)
@@ -6024,6 +6065,13 @@ struct upb_bufsrc {
UPB_BEGIN_EXTERN_C
+/* A class for accumulating output string data in a flat buffer. */
+
+upb_bufsink *upb_bufsink_new(upb_env *env);
+void upb_bufsink_free(upb_bufsink *sink);
+upb_bytessink *upb_bufsink_sink(upb_bufsink *sink);
+const char *upb_bufsink_getdata(const upb_bufsink *sink, size_t *len);
+
/* Inline definitions. */
UPB_INLINE void upb_bytessink_reset(upb_bytessink *s, const upb_byteshandler *h,
@@ -6073,23 +6121,7 @@ UPB_INLINE bool upb_bytessink_end(upb_bytessink *s) {
&s->handler->table[UPB_ENDSTR_SELECTOR].attr));
}
-UPB_INLINE bool upb_bufsrc_putbuf(const char *buf, size_t len,
- upb_bytessink *sink) {
- void *subc;
- bool ret;
- upb_bufhandle handle;
- upb_bufhandle_init(&handle);
- upb_bufhandle_setbuf(&handle, buf, 0);
- ret = upb_bytessink_start(sink, len, &subc);
- if (ret && len != 0) {
- ret = (upb_bytessink_putbuf(sink, subc, buf, len, &handle) >= len);
- }
- if (ret) {
- ret = upb_bytessink_end(sink);
- }
- upb_bufhandle_uninit(&handle);
- return ret;
-}
+bool upb_bufsrc_putbuf(const char *buf, size_t len, upb_bytessink *sink);
#define PUTVAL(type, ctype) \
UPB_INLINE bool upb_sink_put##type(upb_sink *s, upb_selector_t sel, \
@@ -6132,6 +6164,18 @@ UPB_INLINE size_t upb_sink_putstring(upb_sink *s, upb_selector_t sel,
return handler(s->closure, hd, buf, n, handle);
}
+UPB_INLINE bool upb_sink_putunknown(upb_sink *s, const char *buf, size_t n) {
+ typedef upb_unknown_handlerfunc func;
+ func *handler;
+ const void *hd;
+ if (!s->handlers) return true;
+ handler = (func *)upb_handlers_gethandler(s->handlers, UPB_UNKNOWN_SELECTOR);
+
+ if (!handler) return n;
+ hd = upb_handlers_gethandlerdata(s->handlers, UPB_UNKNOWN_SELECTOR);
+ return handler(s->closure, hd, buf, n);
+}
+
UPB_INLINE bool upb_sink_startmsg(upb_sink *s) {
typedef upb_startmsg_handlerfunc func;
func *startmsg;
@@ -6336,268 +6380,642 @@ inline bool BufferSource::PutBuffer(const char *buf, size_t len,
#endif
#endif
-/*
-** For handlers that do very tiny, very simple operations, the function call
-** overhead of calling a handler can be significant. This file allows the
-** user to define handlers that do something very simple like store the value
-** to memory and/or set a hasbit. JIT compilers can then special-case these
-** handlers and emit specialized code for them instead of actually calling the
-** handler.
-**
-** The functionality is very simple/limited right now but may expand to be able
-** to call another function.
-*/
-#ifndef UPB_SHIM_H
-#define UPB_SHIM_H
+#ifdef __cplusplus
+
+namespace upb {
+class Array;
+class Map;
+class MapIterator;
+class MessageFactory;
+class MessageLayout;
+class Visitor;
+class VisitorPlan;
+}
+
+#endif
+
+UPB_DECLARE_TYPE(upb::MessageFactory, upb_msgfactory)
+UPB_DECLARE_TYPE(upb::MessageLayout, upb_msglayout)
+UPB_DECLARE_TYPE(upb::Array, upb_array)
+UPB_DECLARE_TYPE(upb::Map, upb_map)
+UPB_DECLARE_TYPE(upb::MapIterator, upb_mapiter)
+UPB_DECLARE_TYPE(upb::Visitor, upb_visitor)
+UPB_DECLARE_TYPE(upb::VisitorPlan, upb_visitorplan)
+
+/* TODO(haberman): C++ accessors */
+
+UPB_BEGIN_EXTERN_C
+
+typedef void upb_msg;
+
+
+/** upb_msglayout *************************************************************/
+
+/* upb_msglayout represents the memory layout of a given upb_msgdef. You get
+ * instances of this from a upb_msgfactory, and the factory always owns the
+ * msglayout. */
+
+
+/** upb_visitor ***************************************************************/
+
+/* upb_visitor will visit all the fields of a message and its submessages. It
+ * uses a upb_visitorplan which you can obtain from a upb_msgfactory. */
+
+upb_visitor *upb_visitor_create(upb_env *e, const upb_visitorplan *vp,
+ upb_sink *output);
+bool upb_visitor_visitmsg(upb_visitor *v, const upb_msg *msg);
+
+
+/** upb_msgfactory ************************************************************/
+
+/* A upb_msgfactory contains a cache of upb_msglayout, upb_handlers, and
+ * upb_visitorplan objects. These are the objects necessary to represent,
+ * populate, and and visit upb_msg objects.
+ *
+ * These caches are all populated by upb_msgdef, and lazily created on demand.
+ */
+
+/* Creates and destroys a msgfactory, respectively. The messages for this
+ * msgfactory must come from |symtab| (which should outlive the msgfactory). */
+upb_msgfactory *upb_msgfactory_new(const upb_symtab *symtab);
+void upb_msgfactory_free(upb_msgfactory *f);
+
+const upb_symtab *upb_msgfactory_symtab(const upb_msgfactory *f);
+
+/* The functions to get cached objects, lazily creating them on demand. These
+ * all require:
+ *
+ * - m is in upb_msgfactory_symtab(f)
+ * - upb_msgdef_mapentry(m) == false (since map messages can't have layouts).
+ *
+ * The returned objects will live for as long as the msgfactory does.
+ *
+ * TODO(haberman): consider making this thread-safe and take a const
+ * upb_msgfactory. */
+const upb_msglayout *upb_msgfactory_getlayout(upb_msgfactory *f,
+ const upb_msgdef *m);
+const upb_handlers *upb_msgfactory_getmergehandlers(upb_msgfactory *f,
+ const upb_msgdef *m);
+const upb_visitorplan *upb_msgfactory_getvisitorplan(upb_msgfactory *f,
+ const upb_handlers *h);
+
+/** upb_stringview ************************************************************/
typedef struct {
- size_t offset;
- int32_t hasbit;
-} upb_shim_data;
+ const char *data;
+ size_t size;
+} upb_stringview;
+
+UPB_INLINE upb_stringview upb_stringview_make(const char *data, size_t size) {
+ upb_stringview ret;
+ ret.data = data;
+ ret.size = size;
+ return ret;
+}
-#ifdef __cplusplus
+#define UPB_STRINGVIEW_INIT(ptr, len) {ptr, len}
-namespace upb {
-struct Shim {
- typedef upb_shim_data Data;
+/** upb_msgval ****************************************************************/
- /* Sets a handler for the given field that writes the value to the given
- * offset and, if hasbit >= 0, sets a bit at the given bit offset. Returns
- * true if the handler was set successfully. */
- static bool Set(Handlers *h, const FieldDef *f, size_t ofs, int32_t hasbit);
+/* A union representing all possible protobuf values. Used for generic get/set
+ * operations. */
- /* If this handler is a shim, returns the corresponding upb::Shim::Data and
- * stores the type in "type". Otherwise returns NULL. */
- static const Data* GetData(const Handlers* h, Handlers::Selector s,
- FieldDef::Type* type);
-};
+typedef union {
+ bool b;
+ float flt;
+ double dbl;
+ int32_t i32;
+ int64_t i64;
+ uint32_t u32;
+ uint64_t u64;
+ const upb_map* map;
+ const upb_msg* msg;
+ const upb_array* arr;
+ const void* ptr;
+ upb_stringview str;
+} upb_msgval;
+
+#define ACCESSORS(name, membername, ctype) \
+ UPB_INLINE ctype upb_msgval_get ## name(upb_msgval v) { \
+ return v.membername; \
+ } \
+ UPB_INLINE void upb_msgval_set ## name(upb_msgval *v, ctype cval) { \
+ v->membername = cval; \
+ } \
+ UPB_INLINE upb_msgval upb_msgval_ ## name(ctype v) { \
+ upb_msgval ret; \
+ ret.membername = v; \
+ return ret; \
+ }
-} /* namespace upb */
+ACCESSORS(bool, b, bool)
+ACCESSORS(float, flt, float)
+ACCESSORS(double, dbl, double)
+ACCESSORS(int32, i32, int32_t)
+ACCESSORS(int64, i64, int64_t)
+ACCESSORS(uint32, u32, uint32_t)
+ACCESSORS(uint64, u64, uint64_t)
+ACCESSORS(map, map, const upb_map*)
+ACCESSORS(msg, msg, const upb_msg*)
+ACCESSORS(ptr, ptr, const void*)
+ACCESSORS(arr, arr, const upb_array*)
+ACCESSORS(str, str, upb_stringview)
-#endif
+#undef ACCESSORS
+
+UPB_INLINE upb_msgval upb_msgval_makestr(const char *data, size_t size) {
+ return upb_msgval_str(upb_stringview_make(data, size));
+}
+
+
+/** upb_msg *******************************************************************/
+
+/* A upb_msg represents a protobuf message. It always corresponds to a specific
+ * upb_msglayout, which describes how it is laid out in memory.
+ *
+ * The message will have a fixed size, as returned by upb_msg_sizeof(), which
+ * will be used to store fixed-length fields. The upb_msg may also allocate
+ * dynamic memory internally to store data such as:
+ *
+ * - extensions
+ * - unknown fields
+ */
+
+/* Returns the size of a message given this layout. */
+size_t upb_msg_sizeof(const upb_msglayout *l);
+
+/* upb_msg_init() / upb_msg_uninit() allow the user to use a pre-allocated
+ * block of memory as a message. The block's size should be upb_msg_sizeof().
+ * upb_msg_uninit() must be called to release internally-allocated memory
+ * unless the allocator is an arena that does not require freeing.
+ *
+ * Please note that upb_msg_init() may return a value that is different than
+ * |msg|, so you must assign the return value and not cast your memory block
+ * to upb_msg* directly!
+ *
+ * Please note that upb_msg_uninit() does *not* free any submessages, maps,
+ * or arrays referred to by this message's fields. You must free them manually
+ * yourself.
+ *
+ * upb_msg_uninit returns the original memory block, which may be useful if
+ * you dynamically allocated it (though upb_msg_new() would normally be more
+ * appropriate in this case). */
+upb_msg *upb_msg_init(void *msg, const upb_msglayout *l, upb_alloc *a);
+void *upb_msg_uninit(upb_msg *msg, const upb_msglayout *l);
+
+/* Like upb_msg_init() / upb_msg_uninit(), except the message's memory is
+ * allocated / freed from the given upb_alloc. */
+upb_msg *upb_msg_new(const upb_msglayout *l, upb_alloc *a);
+void upb_msg_free(upb_msg *msg, const upb_msglayout *l);
+
+/* Returns the upb_alloc for the given message.
+ * TODO(haberman): get rid of this? Not sure we want to be storing this
+ * for every message. */
+upb_alloc *upb_msg_alloc(const upb_msg *msg);
+
+/* Packs the tree of messages rooted at "msg" into a single hunk of memory,
+ * allocated from the given allocator. */
+void *upb_msg_pack(const upb_msg *msg, const upb_msglayout *l,
+ void *p, size_t *ofs, size_t size);
+
+/* Read-only message API. Can be safely called by anyone. */
+
+/* Returns the value associated with this field:
+ * - for scalar fields (including strings), the value directly.
+ * - return upb_msg*, or upb_map* for msg/map.
+ * If the field is unset for these field types, returns NULL.
+ *
+ * TODO(haberman): should we let users store cached array/map/msg
+ * pointers here for fields that are unset? Could be useful for the
+ * strongly-owned submessage model (ie. generated C API that doesn't use
+ * arenas).
+ */
+upb_msgval upb_msg_get(const upb_msg *msg,
+ int field_index,
+ const upb_msglayout *l);
+
+/* May only be called for fields where upb_fielddef_haspresence(f) == true. */
+bool upb_msg_has(const upb_msg *msg,
+ int field_index,
+ const upb_msglayout *l);
+
+/* Mutable message API. May only be called by the owner of the message who
+ * knows its ownership scheme and how to keep it consistent. */
+
+/* Sets the given field to the given value. Does not perform any memory
+ * management: if you overwrite a pointer to a msg/array/map/string without
+ * cleaning it up (or using an arena) it will leak.
+ */
+void upb_msg_set(upb_msg *msg,
+ int field_index,
+ upb_msgval val,
+ const upb_msglayout *l);
+
+/* For a primitive field, set it back to its default. For repeated, string, and
+ * submessage fields set it back to NULL. This could involve releasing some
+ * internal memory (for example, from an extension dictionary), but it is not
+ * recursive in any way and will not recover any memory that may be used by
+ * arrays/maps/strings/msgs that this field may have pointed to.
+ */
+bool upb_msg_clearfield(upb_msg *msg,
+ int field_index,
+ const upb_msglayout *l);
+
+/* TODO(haberman): copyfrom()/mergefrom()? */
+
+
+/** upb_array *****************************************************************/
+
+/* A upb_array stores data for a repeated field. The memory management
+ * semantics are the same as upb_msg. A upb_array allocates dynamic
+ * memory internally for the array elements. */
+
+size_t upb_array_sizeof(upb_fieldtype_t type);
+void upb_array_init(upb_array *arr, upb_fieldtype_t type, upb_alloc *a);
+void upb_array_uninit(upb_array *arr);
+upb_array *upb_array_new(upb_fieldtype_t type, upb_alloc *a);
+void upb_array_free(upb_array *arr);
+
+/* Read-only interface. Safe for anyone to call. */
+
+size_t upb_array_size(const upb_array *arr);
+upb_fieldtype_t upb_array_type(const upb_array *arr);
+upb_msgval upb_array_get(const upb_array *arr, size_t i);
+
+/* Write interface. May only be called by the message's owner who can enforce
+ * its memory management invariants. */
+
+bool upb_array_set(upb_array *arr, size_t i, upb_msgval val);
+
+
+/** upb_map *******************************************************************/
+
+/* A upb_map stores data for a map field. The memory management semantics are
+ * the same as upb_msg, with one notable exception. upb_map will internally
+ * store a copy of all string keys, but *not* any string values or submessages.
+ * So you must ensure that any string or message values outlive the map, and you
+ * must delete them manually when they are no longer required. */
+
+size_t upb_map_sizeof(upb_fieldtype_t ktype, upb_fieldtype_t vtype);
+bool upb_map_init(upb_map *map, upb_fieldtype_t ktype, upb_fieldtype_t vtype,
+ upb_alloc *a);
+void upb_map_uninit(upb_map *map);
+upb_map *upb_map_new(upb_fieldtype_t ktype, upb_fieldtype_t vtype, upb_alloc *a);
+void upb_map_free(upb_map *map);
+
+/* Read-only interface. Safe for anyone to call. */
+
+size_t upb_map_size(const upb_map *map);
+upb_fieldtype_t upb_map_keytype(const upb_map *map);
+upb_fieldtype_t upb_map_valuetype(const upb_map *map);
+bool upb_map_get(const upb_map *map, upb_msgval key, upb_msgval *val);
+
+/* Write interface. May only be called by the message's owner who can enforce
+ * its memory management invariants. */
+
+/* Sets or overwrites an entry in the map. Return value indicates whether
+ * the operation succeeded or failed with OOM, and also whether an existing
+ * key was replaced or not. */
+bool upb_map_set(upb_map *map,
+ upb_msgval key, upb_msgval val,
+ upb_msgval *valremoved);
+
+/* Deletes an entry in the map. Returns true if the key was present. */
+bool upb_map_del(upb_map *map, upb_msgval key);
+
+
+/** upb_mapiter ***************************************************************/
+
+/* For iterating over a map. Map iterators are invalidated by mutations to the
+ * map, but an invalidated iterator will never return junk or crash the process.
+ * An invalidated iterator may return entries that were already returned though,
+ * and if you keep invalidating the iterator during iteration, the program may
+ * enter an infinite loop. */
+
+size_t upb_mapiter_sizeof();
+
+void upb_mapiter_begin(upb_mapiter *i, const upb_map *t);
+upb_mapiter *upb_mapiter_new(const upb_map *t, upb_alloc *a);
+void upb_mapiter_free(upb_mapiter *i, upb_alloc *a);
+void upb_mapiter_next(upb_mapiter *i);
+bool upb_mapiter_done(const upb_mapiter *i);
+
+upb_msgval upb_mapiter_key(const upb_mapiter *i);
+upb_msgval upb_mapiter_value(const upb_mapiter *i);
+void upb_mapiter_setdone(upb_mapiter *i);
+bool upb_mapiter_isequal(const upb_mapiter *i1, const upb_mapiter *i2);
+
+
+/** Handlers ******************************************************************/
+
+/* These are the handlers used internally by upb_msgfactory_getmergehandlers().
+ * They write scalar data to a known offset from the message pointer.
+ *
+ * These would be trivial for anyone to implement themselves, but it's better
+ * to use these because some JITs will recognize and specialize these instead
+ * of actually calling the function. */
+
+/* Sets a handler for the given primitive field that will write the data at the
+ * given offset. If hasbit > 0, also sets a hasbit at the given bit offset
+ * (addressing each byte low to high). */
+bool upb_msg_setscalarhandler(upb_handlers *h,
+ const upb_fielddef *f,
+ size_t offset,
+ int32_t hasbit);
+
+/* If the given handler is a msghandlers_primitive field, returns true and sets
+ * *type, *offset and *hasbit. Otherwise returns false. */
+bool upb_msg_getscalarhandlerdata(const upb_handlers *h,
+ upb_selector_t s,
+ upb_fieldtype_t *type,
+ size_t *offset,
+ int32_t *hasbit);
+
+
+/** Interfaces for generated code *********************************************/
+
+#define UPB_NOT_IN_ONEOF UINT16_MAX
+#define UPB_NO_HASBIT UINT16_MAX
+#define UPB_NO_SUBMSG UINT16_MAX
+
+typedef struct {
+ uint32_t number;
+ uint32_t offset; /* If in a oneof, offset of default in default_msg below. */
+ uint16_t hasbit; /* UPB_NO_HASBIT if no hasbit. */
+ uint16_t oneof_index; /* UPB_NOT_IN_ONEOF if not in a oneof. */
+ uint16_t submsg_index; /* UPB_NO_SUBMSG if no submsg. */
+ uint8_t type;
+ uint8_t label;
+} upb_msglayout_fieldinit_v1;
+
+typedef struct {
+ uint32_t data_offset;
+ uint32_t case_offset;
+} upb_msglayout_oneofinit_v1;
+
+typedef struct upb_msglayout_msginit_v1 {
+ const struct upb_msglayout_msginit_v1 *const* submsgs;
+ const upb_msglayout_fieldinit_v1 *fields;
+ const upb_msglayout_oneofinit_v1 *oneofs;
+ void *default_msg;
+ /* Must be aligned to sizeof(void*). Doesn't include internal members like
+ * unknown fields, extension dict, pointer to msglayout, etc. */
+ uint32_t size;
+ uint16_t field_count;
+ uint16_t oneof_count;
+ bool extendable;
+ bool is_proto2;
+} upb_msglayout_msginit_v1;
+
+#define UPB_ALIGN_UP_TO(val, align) ((val + (align - 1)) & -align)
+#define UPB_ALIGNED_SIZEOF(type) UPB_ALIGN_UP_TO(sizeof(type), sizeof(void*))
+
+/* Initialize/uninitialize a msglayout from a msginit. If upb uses v1
+ * internally, this will not allocate any memory. Should only be used by
+ * generated code. */
+upb_msglayout *upb_msglayout_frominit_v1(
+ const upb_msglayout_msginit_v1 *init, upb_alloc *a);
+void upb_msglayout_uninit_v1(upb_msglayout *layout, upb_alloc *a);
+
+UPB_END_EXTERN_C
+
+#endif /* UPB_MSG_H_ */
UPB_BEGIN_EXTERN_C
-/* C API. */
-bool upb_shim_set(upb_handlers *h, const upb_fielddef *f, size_t offset,
- int32_t hasbit);
-const upb_shim_data *upb_shim_getdata(const upb_handlers *h, upb_selector_t s,
- upb_fieldtype_t *type);
+bool upb_decode(upb_stringview buf, void *msg,
+ const upb_msglayout_msginit_v1 *l, upb_env *env);
UPB_END_EXTERN_C
-#ifdef __cplusplus
-/* C++ Wrappers. */
-namespace upb {
-inline bool Shim::Set(Handlers* h, const FieldDef* f, size_t ofs,
- int32_t hasbit) {
- return upb_shim_set(h, f, ofs, hasbit);
-}
-inline const Shim::Data* Shim::GetData(const Handlers* h, Handlers::Selector s,
- FieldDef::Type* type) {
- return upb_shim_getdata(h, s, type);
-}
-} /* namespace upb */
-#endif
+#endif /* UPB_DECODE_H_ */
+/*
+** structs.int.h: structures definitions that are internal to upb.
+*/
+
+#ifndef UPB_STRUCTS_H_
+#define UPB_STRUCTS_H_
+
+struct upb_array {
+ upb_fieldtype_t type;
+ uint8_t element_size;
+ void *data; /* Each element is element_size. */
+ size_t len; /* Measured in elements. */
+ size_t size; /* Measured in elements. */
+ upb_alloc *alloc;
+};
+
+#endif /* UPB_STRUCTS_H_ */
-#endif /* UPB_SHIM_H */
/*
-** upb::SymbolTable (upb_symtab)
+** This file contains definitions of structs that should be considered private
+** and NOT stable across versions of upb.
**
-** A symtab (symbol table) stores a name->def map of upb_defs. Clients could
-** always create such tables themselves, but upb_symtab has logic for resolving
-** symbolic references, and in particular, for keeping a whole set of consistent
-** defs when replacing some subset of those defs. This logic is nontrivial.
+** The only reason they are declared here and not in .c files is to allow upb
+** and the application (if desired) to embed statically-initialized instances
+** of structures like defs.
**
-** This is a mixed C/C++ interface that offers a full API to both languages.
-** See the top-level README for more information.
+** If you include this file, all guarantees of ABI compatibility go out the
+** window! Any code that includes this file needs to recompile against the
+** exact same version of upb that they are linking against.
+**
+** You also need to recompile if you change the value of the UPB_DEBUG_REFS
+** flag.
*/
-#ifndef UPB_SYMTAB_H_
-#define UPB_SYMTAB_H_
+#ifndef UPB_STATICINIT_H_
+#define UPB_STATICINIT_H_
#ifdef __cplusplus
-#include <vector>
-namespace upb { class SymbolTable; }
+/* Because of how we do our typedefs, this header can't be included from C++. */
+#error This file cannot be included from C++
#endif
-UPB_DECLARE_DERIVED_TYPE(upb::SymbolTable, upb::RefCounted,
- upb_symtab, upb_refcounted)
+/* upb_refcounted *************************************************************/
-typedef struct {
- UPB_PRIVATE_FOR_CPP
- upb_strtable_iter iter;
- upb_deftype_t type;
-} upb_symtab_iter;
-#ifdef __cplusplus
+/* upb_def ********************************************************************/
-/* Non-const methods in upb::SymbolTable are NOT thread-safe. */
-class upb::SymbolTable {
- public:
- /* Returns a new symbol table with a single ref owned by "owner."
- * Returns NULL if memory allocation failed. */
- static reffed_ptr<SymbolTable> New();
+struct upb_def {
+ upb_refcounted base;
- /* Include RefCounted base methods. */
- UPB_REFCOUNTED_CPPMETHODS
+ const char *fullname;
+ const upb_filedef* file;
+ char type; /* A upb_deftype_t (char to save space) */
- /* For all lookup functions, the returned pointer is not owned by the
- * caller; it may be invalidated by any non-const call or unref of the
- * SymbolTable! To protect against this, take a ref if desired. */
+ /* Used as a flag during the def's mutable stage. Must be false unless
+ * it is currently being used by a function on the stack. This allows
+ * us to easily determine which defs were passed into the function's
+ * current invocation. */
+ bool came_from_user;
+};
- /* Freezes the symbol table: prevents further modification of it.
- * After the Freeze() operation is successful, the SymbolTable must only be
- * accessed via a const pointer.
- *
- * Unlike with upb::MessageDef/upb::EnumDef/etc, freezing a SymbolTable is not
- * a necessary step in using a SymbolTable. If you have no need for it to be
- * immutable, there is no need to freeze it ever. However sometimes it is
- * useful, and SymbolTables that are statically compiled into the binary are
- * always frozen by nature. */
- void Freeze();
+#define UPB_DEF_INIT(name, type, vtbl, refs, ref2s) \
+ { UPB_REFCOUNT_INIT(vtbl, refs, ref2s), name, NULL, type, false }
- /* Resolves the given symbol using the rules described in descriptor.proto,
- * namely:
- *
- * If the name starts with a '.', it is fully-qualified. Otherwise,
- * C++-like scoping rules are used to find the type (i.e. first the nested
- * types within this message are searched, then within the parent, on up
- * to the root namespace).
- *
- * If not found, returns NULL. */
- const Def* Resolve(const char* base, const char* sym) const;
- /* Finds an entry in the symbol table with this exact name. If not found,
- * returns NULL. */
- const Def* Lookup(const char *sym) const;
- const MessageDef* LookupMessage(const char *sym) const;
- const EnumDef* LookupEnum(const char *sym) const;
+/* upb_fielddef ***************************************************************/
- /* TODO: introduce a C++ iterator, but make it nice and templated so that if
- * you ask for an iterator of MessageDef the iterated elements are strongly
- * typed as MessageDef*. */
+struct upb_fielddef {
+ upb_def base;
- /* Adds the given mutable defs to the symtab, resolving all symbols
- * (including enum default values) and finalizing the defs. Only one def per
- * name may be in the list, but defs can replace existing defs in the symtab.
- * All defs must have a name -- anonymous defs are not allowed. Anonymous
- * defs can still be frozen by calling upb_def_freeze() directly.
- *
- * Any existing defs that can reach defs that are being replaced will
- * themselves be replaced also, so that the resulting set of defs is fully
- * consistent.
- *
- * This logic implemented in this method is a convenience; ultimately it
- * calls some combination of upb_fielddef_setsubdef(), upb_def_dup(), and
- * upb_freeze(), any of which the client could call themself. However, since
- * the logic for doing so is nontrivial, we provide it here.
- *
- * The entire operation either succeeds or fails. If the operation fails,
- * the symtab is unchanged, false is returned, and status indicates the
- * error. The caller passes a ref on all defs to the symtab (even if the
- * operation fails).
- *
- * TODO(haberman): currently failure will leave the symtab unchanged, but may
- * leave the defs themselves partially resolved. Does this matter? If so we
- * could do a prepass that ensures that all symbols are resolvable and bail
- * if not, so we don't mutate anything until we know the operation will
- * succeed.
- *
- * TODO(haberman): since the defs must be mutable, refining a frozen def
- * requires making mutable copies of the entire tree. This is wasteful if
- * only a few messages are changing. We may want to add a way of adding a
- * tree of frozen defs to the symtab (perhaps an alternate constructor where
- * you pass the root of the tree?) */
- bool Add(Def*const* defs, size_t n, void* ref_donor, Status* status);
+ union {
+ int64_t sint;
+ uint64_t uint;
+ double dbl;
+ float flt;
+ void *bytes;
+ } defaultval;
+ union {
+ const upb_msgdef *def; /* If !msg_is_symbolic. */
+ char *name; /* If msg_is_symbolic. */
+ } msg;
+ union {
+ const upb_def *def; /* If !subdef_is_symbolic. */
+ char *name; /* If subdef_is_symbolic. */
+ } sub; /* The msgdef or enumdef for this field, if upb_hassubdef(f). */
+ bool subdef_is_symbolic;
+ bool msg_is_symbolic;
+ const upb_oneofdef *oneof;
+ bool default_is_string;
+ bool type_is_set_; /* False until type is explicitly set. */
+ bool is_extension_;
+ bool lazy_;
+ bool packed_;
+ upb_intfmt_t intfmt;
+ bool tagdelim;
+ upb_fieldtype_t type_;
+ upb_label_t label_;
+ uint32_t number_;
+ uint32_t selector_base; /* Used to index into a upb::Handlers table. */
+ uint32_t index_;
+};
- bool Add(const std::vector<Def*>& defs, void *owner, Status* status) {
- return Add((Def*const*)&defs[0], defs.size(), owner, status);
+extern const struct upb_refcounted_vtbl upb_fielddef_vtbl;
+
+#define UPB_FIELDDEF_INIT(label, type, intfmt, tagdelim, is_extension, lazy, \
+ packed, name, num, msgdef, subdef, selector_base, \
+ index, defaultval, refs, ref2s) \
+ { \
+ UPB_DEF_INIT(name, UPB_DEF_FIELD, &upb_fielddef_vtbl, refs, ref2s), \
+ defaultval, {msgdef}, {subdef}, NULL, false, false, \
+ type == UPB_TYPE_STRING || type == UPB_TYPE_BYTES, true, is_extension, \
+ lazy, packed, intfmt, tagdelim, type, label, num, selector_base, index \
}
- /* Resolves all subdefs for messages in this file and attempts to freeze the
- * file. If this succeeds, adds all the symbols to this SymbolTable
- * (replacing any existing ones with the same names). */
- bool AddFile(FileDef* file, Status* s);
- private:
- UPB_DISALLOW_POD_OPS(SymbolTable, upb::SymbolTable)
+/* upb_msgdef *****************************************************************/
+
+struct upb_msgdef {
+ upb_def base;
+
+ size_t selector_count;
+ uint32_t submsg_field_count;
+
+ /* Tables for looking up fields by number and name. */
+ upb_inttable itof; /* int to field */
+ upb_strtable ntof; /* name to field/oneof */
+
+ /* Is this a map-entry message? */
+ bool map_entry;
+
+ /* Whether this message has proto2 or proto3 semantics. */
+ upb_syntax_t syntax;
+
+ /* TODO(haberman): proper extension ranges (there can be multiple). */
};
-#endif /* __cplusplus */
+extern const struct upb_refcounted_vtbl upb_msgdef_vtbl;
-UPB_BEGIN_EXTERN_C
+/* TODO: also support static initialization of the oneofs table. This will be
+ * needed if we compile in descriptors that contain oneofs. */
+#define UPB_MSGDEF_INIT(name, selector_count, submsg_field_count, itof, ntof, \
+ map_entry, syntax, refs, ref2s) \
+ { \
+ UPB_DEF_INIT(name, UPB_DEF_MSG, &upb_fielddef_vtbl, refs, ref2s), \
+ selector_count, submsg_field_count, itof, ntof, map_entry, syntax \
+ }
-/* Native C API. */
-/* Include refcounted methods like upb_symtab_ref(). */
-UPB_REFCOUNTED_CMETHODS(upb_symtab, upb_symtab_upcast)
+/* upb_enumdef ****************************************************************/
-upb_symtab *upb_symtab_new(const void *owner);
-void upb_symtab_freeze(upb_symtab *s);
-const upb_def *upb_symtab_resolve(const upb_symtab *s, const char *base,
- const char *sym);
-const upb_def *upb_symtab_lookup(const upb_symtab *s, const char *sym);
-const upb_msgdef *upb_symtab_lookupmsg(const upb_symtab *s, const char *sym);
-const upb_enumdef *upb_symtab_lookupenum(const upb_symtab *s, const char *sym);
-bool upb_symtab_add(upb_symtab *s, upb_def *const*defs, size_t n,
- void *ref_donor, upb_status *status);
-bool upb_symtab_addfile(upb_symtab *s, upb_filedef *file, upb_status* status);
+struct upb_enumdef {
+ upb_def base;
-/* upb_symtab_iter i;
- * for(upb_symtab_begin(&i, s, type); !upb_symtab_done(&i);
- * upb_symtab_next(&i)) {
- * const upb_def *def = upb_symtab_iter_def(&i);
- * // ...
- * }
- *
- * For C we don't have separate iterators for const and non-const.
- * It is the caller's responsibility to cast the upb_fielddef* to
- * const if the upb_msgdef* is const. */
-void upb_symtab_begin(upb_symtab_iter *iter, const upb_symtab *s,
- upb_deftype_t type);
-void upb_symtab_next(upb_symtab_iter *iter);
-bool upb_symtab_done(const upb_symtab_iter *iter);
-const upb_def *upb_symtab_iter_def(const upb_symtab_iter *iter);
+ upb_strtable ntoi;
+ upb_inttable iton;
+ int32_t defaultval;
+};
-UPB_END_EXTERN_C
+extern const struct upb_refcounted_vtbl upb_enumdef_vtbl;
-#ifdef __cplusplus
-/* C++ inline wrappers. */
-namespace upb {
-inline reffed_ptr<SymbolTable> SymbolTable::New() {
- upb_symtab *s = upb_symtab_new(&s);
- return reffed_ptr<SymbolTable>(s, &s);
-}
+#define UPB_ENUMDEF_INIT(name, ntoi, iton, defaultval, refs, ref2s) \
+ { UPB_DEF_INIT(name, UPB_DEF_ENUM, &upb_enumdef_vtbl, refs, ref2s), ntoi, \
+ iton, defaultval }
-inline void SymbolTable::Freeze() {
- return upb_symtab_freeze(this);
-}
-inline const Def *SymbolTable::Resolve(const char *base,
- const char *sym) const {
- return upb_symtab_resolve(this, base, sym);
-}
-inline const Def* SymbolTable::Lookup(const char *sym) const {
- return upb_symtab_lookup(this, sym);
-}
-inline const MessageDef *SymbolTable::LookupMessage(const char *sym) const {
- return upb_symtab_lookupmsg(this, sym);
-}
-inline bool SymbolTable::Add(
- Def*const* defs, size_t n, void* ref_donor, Status* status) {
- return upb_symtab_add(this, (upb_def*const*)defs, n, ref_donor, status);
-}
-inline bool SymbolTable::AddFile(FileDef* file, Status* s) {
- return upb_symtab_addfile(this, file, s);
-}
-} /* namespace upb */
-#endif
-#endif /* UPB_SYMTAB_H_ */
+/* upb_oneofdef ***************************************************************/
+
+struct upb_oneofdef {
+ upb_refcounted base;
+
+ uint32_t index; /* Index within oneofs. */
+ const char *name;
+ upb_strtable ntof;
+ upb_inttable itof;
+ const upb_msgdef *parent;
+};
+
+extern const struct upb_refcounted_vtbl upb_oneofdef_vtbl;
+
+#define UPB_ONEOFDEF_INIT(name, ntof, itof, refs, ref2s) \
+ { UPB_REFCOUNT_INIT(&upb_oneofdef_vtbl, refs, ref2s), 0, name, ntof, itof }
+
+
+/* upb_symtab *****************************************************************/
+
+struct upb_symtab {
+ upb_refcounted base;
+
+ upb_strtable symtab;
+};
+
+struct upb_filedef {
+ upb_refcounted base;
+
+ const char *name;
+ const char *package;
+ const char *phpprefix;
+ const char *phpnamespace;
+ upb_syntax_t syntax;
+
+ upb_inttable defs;
+ upb_inttable deps;
+};
+
+extern const struct upb_refcounted_vtbl upb_filedef_vtbl;
+
+#endif /* UPB_STATICINIT_H_ */
+/*
+** upb_encode: parsing into a upb_msg using a upb_msglayout.
+*/
+
+#ifndef UPB_ENCODE_H_
+#define UPB_ENCODE_H_
+
+
+UPB_BEGIN_EXTERN_C
+
+char *upb_encode(const void *msg, const upb_msglayout_msginit_v1 *l,
+ upb_env *env, size_t *size);
+
+UPB_END_EXTERN_C
+
+#endif /* UPB_ENCODE_H_ */
/*
** upb::descriptor::Reader (upb_descreader)
**
@@ -6934,6 +7352,8 @@ UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_java_string
UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_javanano_use_deprecated_package(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 38); }
UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_objc_class_prefix(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 36); }
UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_optimize_for(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 9); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_php_class_prefix(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 40); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_php_namespace(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 41); }
UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_py_generic_services(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 18); }
UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_uninterpreted_option(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 999); }
UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MessageOptions_f_deprecated(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_MessageOptions_is(m)); return upb_msgdef_itof(m, 3); }
@@ -7985,21 +8405,9 @@ UPB_INLINE void upb_pbdecoder_unpackdispatch(uint64_t dispatch, uint64_t *ofs,
extern "C" {
#endif
-/* A list of types as they are encoded on-the-wire. */
-typedef enum {
- UPB_WIRE_TYPE_VARINT = 0,
- UPB_WIRE_TYPE_64BIT = 1,
- UPB_WIRE_TYPE_DELIMITED = 2,
- UPB_WIRE_TYPE_START_GROUP = 3,
- UPB_WIRE_TYPE_END_GROUP = 4,
- UPB_WIRE_TYPE_32BIT = 5
-} upb_wiretype_t;
-
#define UPB_MAX_WIRE_TYPE 5
-/* The maximum number of bytes that it takes to encode a 64-bit varint.
- * Note that with a better encoding this could be 9 (TODO: write up a
- * wiki document about this). */
+/* The maximum number of bytes that it takes to encode a 64-bit varint. */
#define UPB_PB_VARINT_MAX_LEN 10
/* Array of the "native" (ie. non-packed-repeated) wire type for the given a
@@ -8032,16 +8440,8 @@ UPB_INLINE upb_decoderet upb_decoderet_make(const char *p, uint64_t val) {
return ret;
}
-/* Four functions for decoding a varint of at most eight bytes. They are all
- * functionally identical, but are implemented in different ways and likely have
- * different performance profiles. We keep them around for performance testing.
- *
- * Note that these functions may not read byte-by-byte, so they must not be used
- * unless there are at least eight bytes left in the buffer! */
upb_decoderet upb_vdecode_max8_branch32(upb_decoderet r);
upb_decoderet upb_vdecode_max8_branch64(upb_decoderet r);
-upb_decoderet upb_vdecode_max8_wright(upb_decoderet r);
-upb_decoderet upb_vdecode_max8_massimino(upb_decoderet r);
/* Template for a function that checks the first two bytes with branching
* and dispatches 2-10 bytes with a separate function. Note that this may read
@@ -8066,8 +8466,6 @@ UPB_INLINE upb_decoderet upb_vdecode_check2_ ## name(const char *_p) { \
UPB_VARINT_DECODER_CHECK2(branch32, upb_vdecode_max8_branch32)
UPB_VARINT_DECODER_CHECK2(branch64, upb_vdecode_max8_branch64)
-UPB_VARINT_DECODER_CHECK2(wright, upb_vdecode_max8_wright)
-UPB_VARINT_DECODER_CHECK2(massimino, upb_vdecode_max8_massimino)
#undef UPB_VARINT_DECODER_CHECK2
/* Our canonical functions for decoding varints, based on the currently
@@ -8079,10 +8477,6 @@ UPB_INLINE upb_decoderet upb_vdecode_fast(const char *p) {
return upb_vdecode_check2_branch32(p);
}
-UPB_INLINE upb_decoderet upb_vdecode_max8_fast(upb_decoderet r) {
- return upb_vdecode_max8_massimino(r);
-}
-
/* Encoding *******************************************************************/
diff --git a/php/generate_descriptor_protos.sh b/php/generate_descriptor_protos.sh
new file mode 100755
index 00000000..372ad69c
--- /dev/null
+++ b/php/generate_descriptor_protos.sh
@@ -0,0 +1,16 @@
+#!/usr/bin/env bash
+
+# Run this script to regenerate desriptor protos after the protocol compiler
+# changes.
+
+if test ! -e src/google/protobuf/stubs/common.h; then
+ cat >&2 << __EOF__
+Could not find source code. Make sure you are running this script from the
+root of the distribution tree.
+__EOF__
+ exit 1
+fi
+
+pushd src
+./protoc --php_out=internal:../php/src google/protobuf/descriptor.proto
+popd
diff --git a/php/phpunit.xml b/php/phpunit.xml
index 0191a601..87440bbd 100644
--- a/php/phpunit.xml
+++ b/php/phpunit.xml
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
-<phpunit bootstrap="./vendor/autoload.php"
+<phpunit bootstrap="./tests/bootstrap_phpunit.php"
colors="true">
<testsuites>
<testsuite name="protobuf-tests">
@@ -7,8 +7,11 @@
<file>tests/array_test.php</file>
<file>tests/encode_decode_test.php</file>
<file>tests/generated_class_test.php</file>
+ <file>tests/generated_phpdoc_test.php</file>
<file>tests/map_field_test.php</file>
<file>tests/well_known_test.php</file>
+ <file>tests/descriptors_test.php</file>
+ <file>tests/generated_service_test.php</file>
</testsuite>
</testsuites>
</phpunit>
diff --git a/php/src/GPBMetadata/Google/Protobuf/Any.php b/php/src/GPBMetadata/Google/Protobuf/Any.php
new file mode 100644
index 00000000..22cc2500
--- /dev/null
+++ b/php/src/GPBMetadata/Google/Protobuf/Any.php
@@ -0,0 +1,30 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/any.proto
+
+namespace GPBMetadata\Google\Protobuf;
+
+class Any
+{
+ public static $is_initialized = false;
+
+ public static function initOnce() {
+ $pool = \Google\Protobuf\Internal\DescriptorPool::getGeneratedPool();
+
+ if (static::$is_initialized == true) {
+ return;
+ }
+ $pool->internalAddGeneratedFile(hex2bin(
+ "0acd010a19676f6f676c652f70726f746f6275662f616e792e70726f746f" .
+ "120f676f6f676c652e70726f746f62756622260a03416e7912100a087479" .
+ "70655f75726c180120012809120d0a0576616c756518022001280c426f0a" .
+ "13636f6d2e676f6f676c652e70726f746f6275664208416e7950726f746f" .
+ "50015a256769746875622e636f6d2f676f6c616e672f70726f746f627566" .
+ "2f7074797065732f616e79a20203475042aa021e476f6f676c652e50726f" .
+ "746f6275662e57656c6c4b6e6f776e5479706573620670726f746f33"
+ ));
+
+ static::$is_initialized = true;
+ }
+}
+
diff --git a/php/src/GPBMetadata/Google/Protobuf/Api.php b/php/src/GPBMetadata/Google/Protobuf/Api.php
new file mode 100644
index 00000000..b18e0d33
--- /dev/null
+++ b/php/src/GPBMetadata/Google/Protobuf/Api.php
@@ -0,0 +1,49 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/api.proto
+
+namespace GPBMetadata\Google\Protobuf;
+
+class Api
+{
+ public static $is_initialized = false;
+
+ public static function initOnce() {
+ $pool = \Google\Protobuf\Internal\DescriptorPool::getGeneratedPool();
+
+ if (static::$is_initialized == true) {
+ return;
+ }
+ \GPBMetadata\Google\Protobuf\SourceContext::initOnce();
+ \GPBMetadata\Google\Protobuf\Type::initOnce();
+ $pool->internalAddGeneratedFile(hex2bin(
+ "0ac8050a19676f6f676c652f70726f746f6275662f6170692e70726f746f" .
+ "120f676f6f676c652e70726f746f6275661a1a676f6f676c652f70726f74" .
+ "6f6275662f747970652e70726f746f2281020a03417069120c0a046e616d" .
+ "6518012001280912280a076d6574686f647318022003280b32172e676f6f" .
+ "676c652e70726f746f6275662e4d6574686f6412280a076f7074696f6e73" .
+ "18032003280b32172e676f6f676c652e70726f746f6275662e4f7074696f" .
+ "6e120f0a0776657273696f6e18042001280912360a0e736f757263655f63" .
+ "6f6e7465787418052001280b321e2e676f6f676c652e70726f746f627566" .
+ "2e536f75726365436f6e7465787412260a066d6978696e7318062003280b" .
+ "32162e676f6f676c652e70726f746f6275662e4d6978696e12270a067379" .
+ "6e74617818072001280e32172e676f6f676c652e70726f746f6275662e53" .
+ "796e74617822d5010a064d6574686f64120c0a046e616d65180120012809" .
+ "12180a10726571756573745f747970655f75726c18022001280912190a11" .
+ "726571756573745f73747265616d696e6718032001280812190a11726573" .
+ "706f6e73655f747970655f75726c180420012809121a0a12726573706f6e" .
+ "73655f73747265616d696e6718052001280812280a076f7074696f6e7318" .
+ "062003280b32172e676f6f676c652e70726f746f6275662e4f7074696f6e" .
+ "12270a0673796e74617818072001280e32172e676f6f676c652e70726f74" .
+ "6f6275662e53796e74617822230a054d6978696e120c0a046e616d651801" .
+ "20012809120c0a04726f6f7418022001280942750a13636f6d2e676f6f67" .
+ "6c652e70726f746f627566420841706950726f746f50015a2b676f6f676c" .
+ "652e676f6c616e672e6f72672f67656e70726f746f2f70726f746f627566" .
+ "2f6170693b617069a20203475042aa021e476f6f676c652e50726f746f62" .
+ "75662e57656c6c4b6e6f776e5479706573620670726f746f33"
+ ));
+
+ static::$is_initialized = true;
+ }
+}
+
diff --git a/php/src/GPBMetadata/Google/Protobuf/Duration.php b/php/src/GPBMetadata/Google/Protobuf/Duration.php
new file mode 100644
index 00000000..b1c85ad8
--- /dev/null
+++ b/php/src/GPBMetadata/Google/Protobuf/Duration.php
@@ -0,0 +1,31 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/duration.proto
+
+namespace GPBMetadata\Google\Protobuf;
+
+class Duration
+{
+ public static $is_initialized = false;
+
+ public static function initOnce() {
+ $pool = \Google\Protobuf\Internal\DescriptorPool::getGeneratedPool();
+
+ if (static::$is_initialized == true) {
+ return;
+ }
+ $pool->internalAddGeneratedFile(hex2bin(
+ "0ae3010a1e676f6f676c652f70726f746f6275662f6475726174696f6e2e" .
+ "70726f746f120f676f6f676c652e70726f746f627566222a0a0844757261" .
+ "74696f6e120f0a077365636f6e6473180120012803120d0a056e616e6f73" .
+ "180220012805427c0a13636f6d2e676f6f676c652e70726f746f62756642" .
+ "0d4475726174696f6e50726f746f50015a2a6769746875622e636f6d2f67" .
+ "6f6c616e672f70726f746f6275662f7074797065732f6475726174696f6e" .
+ "f80101a20203475042aa021e476f6f676c652e50726f746f6275662e5765" .
+ "6c6c4b6e6f776e5479706573620670726f746f33"
+ ));
+
+ static::$is_initialized = true;
+ }
+}
+
diff --git a/php/src/GPBMetadata/Google/Protobuf/FieldMask.php b/php/src/GPBMetadata/Google/Protobuf/FieldMask.php
new file mode 100644
index 00000000..5812be1e
--- /dev/null
+++ b/php/src/GPBMetadata/Google/Protobuf/FieldMask.php
@@ -0,0 +1,31 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/field_mask.proto
+
+namespace GPBMetadata\Google\Protobuf;
+
+class FieldMask
+{
+ public static $is_initialized = false;
+
+ public static function initOnce() {
+ $pool = \Google\Protobuf\Internal\DescriptorPool::getGeneratedPool();
+
+ if (static::$is_initialized == true) {
+ return;
+ }
+ $pool->internalAddGeneratedFile(hex2bin(
+ "0ae3010a20676f6f676c652f70726f746f6275662f6669656c645f6d6173" .
+ "6b2e70726f746f120f676f6f676c652e70726f746f627566221a0a094669" .
+ "656c644d61736b120d0a0570617468731801200328094289010a13636f6d" .
+ "2e676f6f676c652e70726f746f627566420e4669656c644d61736b50726f" .
+ "746f50015a39676f6f676c652e676f6c616e672e6f72672f67656e70726f" .
+ "746f2f70726f746f6275662f6669656c645f6d61736b3b6669656c645f6d" .
+ "61736ba20203475042aa021e476f6f676c652e50726f746f6275662e5765" .
+ "6c6c4b6e6f776e5479706573620670726f746f33"
+ ));
+
+ static::$is_initialized = true;
+ }
+}
+
diff --git a/php/src/GPBMetadata/Google/Protobuf/GPBEmpty.php b/php/src/GPBMetadata/Google/Protobuf/GPBEmpty.php
new file mode 100644
index 00000000..88f42a11
--- /dev/null
+++ b/php/src/GPBMetadata/Google/Protobuf/GPBEmpty.php
@@ -0,0 +1,30 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/empty.proto
+
+namespace GPBMetadata\Google\Protobuf;
+
+class GPBEmpty
+{
+ public static $is_initialized = false;
+
+ public static function initOnce() {
+ $pool = \Google\Protobuf\Internal\DescriptorPool::getGeneratedPool();
+
+ if (static::$is_initialized == true) {
+ return;
+ }
+ $pool->internalAddGeneratedFile(hex2bin(
+ "0ab7010a1b676f6f676c652f70726f746f6275662f656d7074792e70726f" .
+ "746f120f676f6f676c652e70726f746f62756622070a05456d7074794276" .
+ "0a13636f6d2e676f6f676c652e70726f746f627566420a456d7074795072" .
+ "6f746f50015a276769746875622e636f6d2f676f6c616e672f70726f746f" .
+ "6275662f7074797065732f656d707479f80101a20203475042aa021e476f" .
+ "6f676c652e50726f746f6275662e57656c6c4b6e6f776e54797065736206" .
+ "70726f746f33"
+ ));
+
+ static::$is_initialized = true;
+ }
+}
+
diff --git a/php/src/GPBMetadata/Google/Protobuf/Internal/Descriptor.php b/php/src/GPBMetadata/Google/Protobuf/Internal/Descriptor.php
index 7c5c8df4..b0ca8da0 100644
--- a/php/src/GPBMetadata/Google/Protobuf/Internal/Descriptor.php
+++ b/php/src/GPBMetadata/Google/Protobuf/Internal/Descriptor.php
@@ -49,6 +49,7 @@ class Descriptor
$pool->addMessage('google.protobuf.internal.DescriptorProto.ExtensionRange', \Google\Protobuf\Internal\DescriptorProto_ExtensionRange::class)
->optional('start', \Google\Protobuf\Internal\GPBType::INT32, 1)
->optional('end', \Google\Protobuf\Internal\GPBType::INT32, 2)
+ ->optional('options', \Google\Protobuf\Internal\GPBType::MESSAGE, 3, 'google.protobuf.internal.ExtensionRangeOptions')
->finalizeToPool();
$pool->addMessage('google.protobuf.internal.DescriptorProto.ReservedRange', \Google\Protobuf\Internal\DescriptorProto_ReservedRange::class)
@@ -56,6 +57,10 @@ class Descriptor
->optional('end', \Google\Protobuf\Internal\GPBType::INT32, 2)
->finalizeToPool();
+ $pool->addMessage('google.protobuf.internal.ExtensionRangeOptions', \Google\Protobuf\Internal\ExtensionRangeOptions::class)
+ ->repeated('uninterpreted_option', \Google\Protobuf\Internal\GPBType::MESSAGE, 999, 'google.protobuf.internal.UninterpretedOption')
+ ->finalizeToPool();
+
$pool->addMessage('google.protobuf.internal.FieldDescriptorProto', \Google\Protobuf\Internal\FieldDescriptorProto::class)
->optional('name', \Google\Protobuf\Internal\GPBType::STRING, 1)
->optional('number', \Google\Protobuf\Internal\GPBType::INT32, 3)
@@ -105,6 +110,13 @@ class Descriptor
->optional('name', \Google\Protobuf\Internal\GPBType::STRING, 1)
->repeated('value', \Google\Protobuf\Internal\GPBType::MESSAGE, 2, 'google.protobuf.internal.EnumValueDescriptorProto')
->optional('options', \Google\Protobuf\Internal\GPBType::MESSAGE, 3, 'google.protobuf.internal.EnumOptions')
+ ->repeated('reserved_range', \Google\Protobuf\Internal\GPBType::MESSAGE, 4, 'google.protobuf.internal.EnumDescriptorProto.EnumReservedRange')
+ ->repeated('reserved_name', \Google\Protobuf\Internal\GPBType::STRING, 5)
+ ->finalizeToPool();
+
+ $pool->addMessage('google.protobuf.internal.EnumDescriptorProto.EnumReservedRange', \Google\Protobuf\Internal\EnumDescriptorProto_EnumReservedRange::class)
+ ->optional('start', \Google\Protobuf\Internal\GPBType::INT32, 1)
+ ->optional('end', \Google\Protobuf\Internal\GPBType::INT32, 2)
->finalizeToPool();
$pool->addMessage('google.protobuf.internal.EnumValueDescriptorProto', \Google\Protobuf\Internal\EnumValueDescriptorProto::class)
@@ -139,11 +151,14 @@ class Descriptor
->optional('cc_generic_services', \Google\Protobuf\Internal\GPBType::BOOL, 16)
->optional('java_generic_services', \Google\Protobuf\Internal\GPBType::BOOL, 17)
->optional('py_generic_services', \Google\Protobuf\Internal\GPBType::BOOL, 18)
+ ->optional('php_generic_services', \Google\Protobuf\Internal\GPBType::BOOL, 42)
->optional('deprecated', \Google\Protobuf\Internal\GPBType::BOOL, 23)
->optional('cc_enable_arenas', \Google\Protobuf\Internal\GPBType::BOOL, 31)
->optional('objc_class_prefix', \Google\Protobuf\Internal\GPBType::STRING, 36)
->optional('csharp_namespace', \Google\Protobuf\Internal\GPBType::STRING, 37)
->optional('swift_prefix', \Google\Protobuf\Internal\GPBType::STRING, 39)
+ ->optional('php_class_prefix', \Google\Protobuf\Internal\GPBType::STRING, 40)
+ ->optional('php_namespace', \Google\Protobuf\Internal\GPBType::STRING, 41)
->repeated('uninterpreted_option', \Google\Protobuf\Internal\GPBType::MESSAGE, 999, 'google.protobuf.internal.UninterpretedOption')
->finalizeToPool();
diff --git a/php/src/GPBMetadata/Google/Protobuf/SourceContext.php b/php/src/GPBMetadata/Google/Protobuf/SourceContext.php
new file mode 100644
index 00000000..495c6de4
--- /dev/null
+++ b/php/src/GPBMetadata/Google/Protobuf/SourceContext.php
@@ -0,0 +1,32 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/source_context.proto
+
+namespace GPBMetadata\Google\Protobuf;
+
+class SourceContext
+{
+ public static $is_initialized = false;
+
+ public static function initOnce() {
+ $pool = \Google\Protobuf\Internal\DescriptorPool::getGeneratedPool();
+
+ if (static::$is_initialized == true) {
+ return;
+ }
+ $pool->internalAddGeneratedFile(hex2bin(
+ "0afb010a24676f6f676c652f70726f746f6275662f736f757263655f636f" .
+ "6e746578742e70726f746f120f676f6f676c652e70726f746f6275662222" .
+ "0a0d536f75726365436f6e7465787412110a0966696c655f6e616d651801" .
+ "200128094295010a13636f6d2e676f6f676c652e70726f746f6275664212" .
+ "536f75726365436f6e7465787450726f746f50015a41676f6f676c652e67" .
+ "6f6c616e672e6f72672f67656e70726f746f2f70726f746f6275662f736f" .
+ "757263655f636f6e746578743b736f757263655f636f6e74657874a20203" .
+ "475042aa021e476f6f676c652e50726f746f6275662e57656c6c4b6e6f77" .
+ "6e5479706573620670726f746f33"
+ ));
+
+ static::$is_initialized = true;
+ }
+}
+
diff --git a/php/src/GPBMetadata/Google/Protobuf/Struct.php b/php/src/GPBMetadata/Google/Protobuf/Struct.php
new file mode 100644
index 00000000..96b42af4
--- /dev/null
+++ b/php/src/GPBMetadata/Google/Protobuf/Struct.php
@@ -0,0 +1,45 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/struct.proto
+
+namespace GPBMetadata\Google\Protobuf;
+
+class Struct
+{
+ public static $is_initialized = false;
+
+ public static function initOnce() {
+ $pool = \Google\Protobuf\Internal\DescriptorPool::getGeneratedPool();
+
+ if (static::$is_initialized == true) {
+ return;
+ }
+ $pool->internalAddGeneratedFile(hex2bin(
+ "0a81050a1c676f6f676c652f70726f746f6275662f7374727563742e7072" .
+ "6f746f120f676f6f676c652e70726f746f6275662284010a065374727563" .
+ "7412330a066669656c647318012003280b32232e676f6f676c652e70726f" .
+ "746f6275662e5374727563742e4669656c6473456e7472791a450a0b4669" .
+ "656c6473456e747279120b0a036b657918012001280912250a0576616c75" .
+ "6518022001280b32162e676f6f676c652e70726f746f6275662e56616c75" .
+ "653a02380122ea010a0556616c756512300a0a6e756c6c5f76616c756518" .
+ "012001280e321a2e676f6f676c652e70726f746f6275662e4e756c6c5661" .
+ "6c7565480012160a0c6e756d6265725f76616c7565180220012801480012" .
+ "160a0c737472696e675f76616c7565180320012809480012140a0a626f6f" .
+ "6c5f76616c75651804200128084800122f0a0c7374727563745f76616c75" .
+ "6518052001280b32172e676f6f676c652e70726f746f6275662e53747275" .
+ "6374480012300a0a6c6973745f76616c756518062001280b321a2e676f6f" .
+ "676c652e70726f746f6275662e4c69737456616c7565480042060a046b69" .
+ "6e6422330a094c69737456616c756512260a0676616c7565731801200328" .
+ "0b32162e676f6f676c652e70726f746f6275662e56616c75652a1b0a094e" .
+ "756c6c56616c7565120e0a0a4e554c4c5f56414c554510004281010a1363" .
+ "6f6d2e676f6f676c652e70726f746f627566420b53747275637450726f74" .
+ "6f50015a316769746875622e636f6d2f676f6c616e672f70726f746f6275" .
+ "662f7074797065732f7374727563743b7374727563747062f80101a20203" .
+ "475042aa021e476f6f676c652e50726f746f6275662e57656c6c4b6e6f77" .
+ "6e5479706573620670726f746f33"
+ ));
+
+ static::$is_initialized = true;
+ }
+}
+
diff --git a/php/src/GPBMetadata/Google/Protobuf/Timestamp.php b/php/src/GPBMetadata/Google/Protobuf/Timestamp.php
new file mode 100644
index 00000000..373665c9
--- /dev/null
+++ b/php/src/GPBMetadata/Google/Protobuf/Timestamp.php
@@ -0,0 +1,31 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/timestamp.proto
+
+namespace GPBMetadata\Google\Protobuf;
+
+class Timestamp
+{
+ public static $is_initialized = false;
+
+ public static function initOnce() {
+ $pool = \Google\Protobuf\Internal\DescriptorPool::getGeneratedPool();
+
+ if (static::$is_initialized == true) {
+ return;
+ }
+ $pool->internalAddGeneratedFile(hex2bin(
+ "0ae7010a1f676f6f676c652f70726f746f6275662f74696d657374616d70" .
+ "2e70726f746f120f676f6f676c652e70726f746f627566222b0a0954696d" .
+ "657374616d70120f0a077365636f6e6473180120012803120d0a056e616e" .
+ "6f73180220012805427e0a13636f6d2e676f6f676c652e70726f746f6275" .
+ "66420e54696d657374616d7050726f746f50015a2b6769746875622e636f" .
+ "6d2f676f6c616e672f70726f746f6275662f7074797065732f74696d6573" .
+ "74616d70f80101a20203475042aa021e476f6f676c652e50726f746f6275" .
+ "662e57656c6c4b6e6f776e5479706573620670726f746f33"
+ ));
+
+ static::$is_initialized = true;
+ }
+}
+
diff --git a/php/src/GPBMetadata/Google/Protobuf/Type.php b/php/src/GPBMetadata/Google/Protobuf/Type.php
new file mode 100644
index 00000000..8fbe8cbf
--- /dev/null
+++ b/php/src/GPBMetadata/Google/Protobuf/Type.php
@@ -0,0 +1,78 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/type.proto
+
+namespace GPBMetadata\Google\Protobuf;
+
+class Type
+{
+ public static $is_initialized = false;
+
+ public static function initOnce() {
+ $pool = \Google\Protobuf\Internal\DescriptorPool::getGeneratedPool();
+
+ if (static::$is_initialized == true) {
+ return;
+ }
+ \GPBMetadata\Google\Protobuf\Any::initOnce();
+ \GPBMetadata\Google\Protobuf\SourceContext::initOnce();
+ $pool->internalAddGeneratedFile(hex2bin(
+ "0a9f0c0a1a676f6f676c652f70726f746f6275662f747970652e70726f74" .
+ "6f120f676f6f676c652e70726f746f6275661a24676f6f676c652f70726f" .
+ "746f6275662f736f757263655f636f6e746578742e70726f746f22d7010a" .
+ "0454797065120c0a046e616d6518012001280912260a066669656c647318" .
+ "022003280b32162e676f6f676c652e70726f746f6275662e4669656c6412" .
+ "0e0a066f6e656f667318032003280912280a076f7074696f6e7318042003" .
+ "280b32172e676f6f676c652e70726f746f6275662e4f7074696f6e12360a" .
+ "0e736f757263655f636f6e7465787418052001280b321e2e676f6f676c65" .
+ "2e70726f746f6275662e536f75726365436f6e7465787412270a0673796e" .
+ "74617818062001280e32172e676f6f676c652e70726f746f6275662e5379" .
+ "6e74617822d5050a054669656c6412290a046b696e6418012001280e321b" .
+ "2e676f6f676c652e70726f746f6275662e4669656c642e4b696e6412370a" .
+ "0b63617264696e616c69747918022001280e32222e676f6f676c652e7072" .
+ "6f746f6275662e4669656c642e43617264696e616c697479120e0a066e75" .
+ "6d626572180320012805120c0a046e616d6518042001280912100a087479" .
+ "70655f75726c18062001280912130a0b6f6e656f665f696e646578180720" .
+ "012805120e0a067061636b656418082001280812280a076f7074696f6e73" .
+ "18092003280b32172e676f6f676c652e70726f746f6275662e4f7074696f" .
+ "6e12110a096a736f6e5f6e616d65180a2001280912150a0d64656661756c" .
+ "745f76616c7565180b2001280922c8020a044b696e6412100a0c54595045" .
+ "5f554e4b4e4f574e1000120f0a0b545950455f444f55424c451001120e0a" .
+ "0a545950455f464c4f41541002120e0a0a545950455f494e543634100312" .
+ "0f0a0b545950455f55494e5436341004120e0a0a545950455f494e543332" .
+ "100512100a0c545950455f46495845443634100612100a0c545950455f46" .
+ "4958454433321007120d0a09545950455f424f4f4c1008120f0a0b545950" .
+ "455f535452494e471009120e0a0a545950455f47524f5550100a12100a0c" .
+ "545950455f4d455353414745100b120e0a0a545950455f4259544553100c" .
+ "120f0a0b545950455f55494e543332100d120d0a09545950455f454e554d" .
+ "100e12110a0d545950455f5346495845443332100f12110a0d545950455f" .
+ "53464958454436341010120f0a0b545950455f53494e5433321011120f0a" .
+ "0b545950455f53494e543634101222740a0b43617264696e616c69747912" .
+ "170a1343415244494e414c4954595f554e4b4e4f574e100012180a144341" .
+ "5244494e414c4954595f4f5054494f4e414c100112180a1443415244494e" .
+ "414c4954595f5245515549524544100212180a1443415244494e414c4954" .
+ "595f5245504541544544100322ce010a04456e756d120c0a046e616d6518" .
+ "0120012809122d0a09656e756d76616c756518022003280b321a2e676f6f" .
+ "676c652e70726f746f6275662e456e756d56616c756512280a076f707469" .
+ "6f6e7318032003280b32172e676f6f676c652e70726f746f6275662e4f70" .
+ "74696f6e12360a0e736f757263655f636f6e7465787418042001280b321e" .
+ "2e676f6f676c652e70726f746f6275662e536f75726365436f6e74657874" .
+ "12270a0673796e74617818052001280e32172e676f6f676c652e70726f74" .
+ "6f6275662e53796e74617822530a09456e756d56616c7565120c0a046e61" .
+ "6d65180120012809120e0a066e756d62657218022001280512280a076f70" .
+ "74696f6e7318032003280b32172e676f6f676c652e70726f746f6275662e" .
+ "4f7074696f6e223b0a064f7074696f6e120c0a046e616d65180120012809" .
+ "12230a0576616c756518022001280b32142e676f6f676c652e70726f746f" .
+ "6275662e416e792a2e0a0653796e74617812110a0d53594e5441585f5052" .
+ "4f544f32100012110a0d53594e5441585f50524f544f331001427d0a1363" .
+ "6f6d2e676f6f676c652e70726f746f62756642095479706550726f746f50" .
+ "015a2f676f6f676c652e676f6c616e672e6f72672f67656e70726f746f2f" .
+ "70726f746f6275662f70747970653b7074797065f80101a20203475042aa" .
+ "021e476f6f676c652e50726f746f6275662e57656c6c4b6e6f776e547970" .
+ "6573620670726f746f33"
+ ));
+
+ static::$is_initialized = true;
+ }
+}
+
diff --git a/php/src/GPBMetadata/Google/Protobuf/Wrappers.php b/php/src/GPBMetadata/Google/Protobuf/Wrappers.php
new file mode 100644
index 00000000..dd72ff48
--- /dev/null
+++ b/php/src/GPBMetadata/Google/Protobuf/Wrappers.php
@@ -0,0 +1,38 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/wrappers.proto
+
+namespace GPBMetadata\Google\Protobuf;
+
+class Wrappers
+{
+ public static $is_initialized = false;
+
+ public static function initOnce() {
+ $pool = \Google\Protobuf\Internal\DescriptorPool::getGeneratedPool();
+
+ if (static::$is_initialized == true) {
+ return;
+ }
+ $pool->internalAddGeneratedFile(hex2bin(
+ "0abf030a1e676f6f676c652f70726f746f6275662f77726170706572732e" .
+ "70726f746f120f676f6f676c652e70726f746f627566221c0a0b446f7562" .
+ "6c6556616c7565120d0a0576616c7565180120012801221b0a0a466c6f61" .
+ "7456616c7565120d0a0576616c7565180120012802221b0a0a496e743634" .
+ "56616c7565120d0a0576616c7565180120012803221c0a0b55496e743634" .
+ "56616c7565120d0a0576616c7565180120012804221b0a0a496e74333256" .
+ "616c7565120d0a0576616c7565180120012805221c0a0b55496e74333256" .
+ "616c7565120d0a0576616c756518012001280d221a0a09426f6f6c56616c" .
+ "7565120d0a0576616c7565180120012808221c0a0b537472696e6756616c" .
+ "7565120d0a0576616c7565180120012809221b0a0a427974657356616c75" .
+ "65120d0a0576616c756518012001280c427c0a13636f6d2e676f6f676c65" .
+ "2e70726f746f627566420d577261707065727350726f746f50015a2a6769" .
+ "746875622e636f6d2f676f6c616e672f70726f746f6275662f7074797065" .
+ "732f7772617070657273f80101a20203475042aa021e476f6f676c652e50" .
+ "726f746f6275662e57656c6c4b6e6f776e5479706573620670726f746f33"
+ ));
+
+ static::$is_initialized = true;
+ }
+}
+
diff --git a/php/src/Google/Protobuf/Any.php b/php/src/Google/Protobuf/Any.php
new file mode 100644
index 00000000..91ba4bd5
--- /dev/null
+++ b/php/src/Google/Protobuf/Any.php
@@ -0,0 +1,272 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/any.proto
+
+namespace Google\Protobuf;
+
+use Google\Protobuf\Internal\DescriptorPool;
+use Google\Protobuf\Internal\GPBType;
+use Google\Protobuf\Internal\GPBUtil;
+use Google\Protobuf\Internal\Message;
+use Google\Protobuf\Internal\RepeatedField;
+
+/**
+ * `Any` contains an arbitrary serialized protocol buffer message along with a
+ * URL that describes the type of the serialized message.
+ * Protobuf library provides support to pack/unpack Any values in the form
+ * of utility functions or additional generated methods of the Any type.
+ * Example 1: Pack and unpack a message in C++.
+ * Foo foo = ...;
+ * Any any;
+ * any.PackFrom(foo);
+ * ...
+ * if (any.UnpackTo(&foo)) {
+ * ...
+ * }
+ * Example 2: Pack and unpack a message in Java.
+ * Foo foo = ...;
+ * Any any = Any.pack(foo);
+ * ...
+ * if (any.is(Foo.class)) {
+ * foo = any.unpack(Foo.class);
+ * }
+ * Example 3: Pack and unpack a message in Python.
+ * foo = Foo(...)
+ * any = Any()
+ * any.Pack(foo)
+ * ...
+ * if any.Is(Foo.DESCRIPTOR):
+ * any.Unpack(foo)
+ * ...
+ * The pack methods provided by protobuf library will by default use
+ * 'type.googleapis.com/full.type.name' as the type URL and the unpack
+ * methods only use the fully qualified type name after the last '/'
+ * in the type URL, for example "foo.bar.com/x/y.z" will yield type
+ * name "y.z".
+ * JSON
+ * ====
+ * The JSON representation of an `Any` value uses the regular
+ * representation of the deserialized, embedded message, with an
+ * additional field `&#64;type` which contains the type URL. Example:
+ * package google.profile;
+ * message Person {
+ * string first_name = 1;
+ * string last_name = 2;
+ * }
+ * {
+ * "&#64;type": "type.googleapis.com/google.profile.Person",
+ * "firstName": <string>,
+ * "lastName": <string>
+ * }
+ * If the embedded message type is well-known and has a custom JSON
+ * representation, that representation will be embedded adding a field
+ * `value` which holds the custom JSON in addition to the `&#64;type`
+ * field. Example (for message [google.protobuf.Duration][]):
+ * {
+ * "&#64;type": "type.googleapis.com/google.protobuf.Duration",
+ * "value": "1.212s"
+ * }
+ *
+ * Generated from protobuf message <code>google.protobuf.Any</code>
+ */
+class Any extends \Google\Protobuf\Internal\Message
+{
+ /**
+ * A URL/resource name whose content describes the type of the
+ * serialized protocol buffer message.
+ * For URLs which use the scheme `http`, `https`, or no scheme, the
+ * following restrictions and interpretations apply:
+ * * If no scheme is provided, `https` is assumed.
+ * * The last segment of the URL's path must represent the fully
+ * qualified name of the type (as in `path/google.protobuf.Duration`).
+ * The name should be in a canonical form (e.g., leading "." is
+ * not accepted).
+ * * An HTTP GET on the URL must yield a [google.protobuf.Type][]
+ * value in binary format, or produce an error.
+ * * Applications are allowed to cache lookup results based on the
+ * URL, or have them precompiled into a binary to avoid any
+ * lookup. Therefore, binary compatibility needs to be preserved
+ * on changes to types. (Use versioned type names to manage
+ * breaking changes.)
+ * Schemes other than `http`, `https` (or the empty scheme) might be
+ * used with implementation specific semantics.
+ *
+ * Generated from protobuf field <code>string type_url = 1;</code>
+ */
+ private $type_url = '';
+ /**
+ * Must be a valid serialized protocol buffer of the above specified type.
+ *
+ * Generated from protobuf field <code>bytes value = 2;</code>
+ */
+ private $value = '';
+
+ const TYPE_URL_PREFIX = 'type.googleapis.com/';
+
+ public function __construct() {
+ \GPBMetadata\Google\Protobuf\Any::initOnce();
+ parent::__construct();
+ }
+
+ /**
+ * A URL/resource name whose content describes the type of the
+ * serialized protocol buffer message.
+ * For URLs which use the scheme `http`, `https`, or no scheme, the
+ * following restrictions and interpretations apply:
+ * * If no scheme is provided, `https` is assumed.
+ * * The last segment of the URL's path must represent the fully
+ * qualified name of the type (as in `path/google.protobuf.Duration`).
+ * The name should be in a canonical form (e.g., leading "." is
+ * not accepted).
+ * * An HTTP GET on the URL must yield a [google.protobuf.Type][]
+ * value in binary format, or produce an error.
+ * * Applications are allowed to cache lookup results based on the
+ * URL, or have them precompiled into a binary to avoid any
+ * lookup. Therefore, binary compatibility needs to be preserved
+ * on changes to types. (Use versioned type names to manage
+ * breaking changes.)
+ * Schemes other than `http`, `https` (or the empty scheme) might be
+ * used with implementation specific semantics.
+ *
+ * Generated from protobuf field <code>string type_url = 1;</code>
+ * @return string
+ */
+ public function getTypeUrl()
+ {
+ return $this->type_url;
+ }
+
+ /**
+ * A URL/resource name whose content describes the type of the
+ * serialized protocol buffer message.
+ * For URLs which use the scheme `http`, `https`, or no scheme, the
+ * following restrictions and interpretations apply:
+ * * If no scheme is provided, `https` is assumed.
+ * * The last segment of the URL's path must represent the fully
+ * qualified name of the type (as in `path/google.protobuf.Duration`).
+ * The name should be in a canonical form (e.g., leading "." is
+ * not accepted).
+ * * An HTTP GET on the URL must yield a [google.protobuf.Type][]
+ * value in binary format, or produce an error.
+ * * Applications are allowed to cache lookup results based on the
+ * URL, or have them precompiled into a binary to avoid any
+ * lookup. Therefore, binary compatibility needs to be preserved
+ * on changes to types. (Use versioned type names to manage
+ * breaking changes.)
+ * Schemes other than `http`, `https` (or the empty scheme) might be
+ * used with implementation specific semantics.
+ *
+ * Generated from protobuf field <code>string type_url = 1;</code>
+ * @param string $var
+ * @return $this
+ */
+ public function setTypeUrl($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->type_url = $var;
+
+ return $this;
+ }
+
+ /**
+ * Must be a valid serialized protocol buffer of the above specified type.
+ *
+ * Generated from protobuf field <code>bytes value = 2;</code>
+ * @return string
+ */
+ public function getValue()
+ {
+ return $this->value;
+ }
+
+ /**
+ * Must be a valid serialized protocol buffer of the above specified type.
+ *
+ * Generated from protobuf field <code>bytes value = 2;</code>
+ * @param string $var
+ * @return $this
+ */
+ public function setValue($var)
+ {
+ GPBUtil::checkString($var, False);
+ $this->value = $var;
+
+ return $this;
+ }
+
+ /**
+ * This method will try to resolve the type_url in Any message to get the
+ * targeted message type. If failed, an error will be thrown. Otherwise,
+ * the method will create a message of the targeted type and fill it with
+ * the decoded value in Any.
+ * @return unpacked message
+ * @throws Exception Type url needs to be type.googleapis.com/fully-qulified.
+ * @throws Exception Class hasn't been added to descriptor pool.
+ * @throws Exception cannot decode data in value field.
+ */
+ public function unpack()
+ {
+ // Get fully qualifed name from type url.
+ $url_prifix_len = strlen(GPBUtil::TYPE_URL_PREFIX);
+ if (substr($this->type_url, 0, $url_prifix_len) !=
+ GPBUtil::TYPE_URL_PREFIX) {
+ throw new \Exception(
+ "Type url needs to be type.googleapis.com/fully-qulified");
+ }
+ $fully_qualifed_name =
+ substr($this->type_url, $url_prifix_len);
+
+ // Create message according to fully qualified name.
+ $pool = DescriptorPool::getGeneratedPool();
+ $desc = $pool->getDescriptorByProtoName( ".".$fully_qualifed_name);
+ if (is_null($desc)) {
+ throw new \Exception("Class ".$fully_qualifed_name
+ ." hasn't been added to descriptor pool");
+ }
+ $klass = $desc->getClass();
+ $msg = new $klass();
+
+ // Merge data into message.
+ $msg->mergeFromString($this->value);
+ return $msg;
+ }
+
+ /**
+ * The type_url will be created according to the given message’s type and
+ * the value is encoded data from the given message..
+ * @param message: A proto message.
+ */
+ public function pack($msg)
+ {
+ if (!$msg instanceof Message) {
+ trigger_error("Given parameter is not a message instance.",
+ E_USER_ERROR);
+ return;
+ }
+
+ // Set value using serialzed message.
+ $this->value = $msg->serializeToString();
+
+ // Set type url.
+ $pool = DescriptorPool::getGeneratedPool();
+ $desc = $pool->getDescriptorByClassName(get_class($msg));
+ $fully_qualifed_name = $desc->getFullName();
+ $this->type_url = GPBUtil::TYPE_URL_PREFIX.substr(
+ $fully_qualifed_name, 1, strlen($fully_qualifed_name));
+ }
+
+ /**
+ * This method returns whether the type_url in any_message is corresponded
+ * to the given class.
+ * @param klass: The fully qualified PHP class name of a proto message type.
+ */
+ public function is($klass)
+ {
+ $pool = DescriptorPool::getGeneratedPool();
+ $desc = $pool->getDescriptorByClassName($klass);
+ $fully_qualifed_name = $desc->getFullName();
+ $type_url = GPBUtil::TYPE_URL_PREFIX.substr(
+ $fully_qualifed_name, 1, strlen($fully_qualifed_name));
+ return $this->type_url === $type_url;
+ }
+}
diff --git a/php/src/Google/Protobuf/Api.php b/php/src/Google/Protobuf/Api.php
new file mode 100644
index 00000000..d0dda3cd
--- /dev/null
+++ b/php/src/Google/Protobuf/Api.php
@@ -0,0 +1,310 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/api.proto
+
+namespace Google\Protobuf;
+
+use Google\Protobuf\Internal\GPBType;
+use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\GPBUtil;
+
+/**
+ * Api is a light-weight descriptor for an API Interface.
+ * Interfaces are also described as "protocol buffer services" in some contexts,
+ * such as by the "service" keyword in a .proto file, but they are different
+ * from API Services, which represent a concrete implementation of an interface
+ * as opposed to simply a description of methods and bindings. They are also
+ * sometimes simply referred to as "APIs" in other contexts, such as the name of
+ * this message itself. See https://cloud.google.com/apis/design/glossary for
+ * detailed terminology.
+ *
+ * Generated from protobuf message <code>google.protobuf.Api</code>
+ */
+class Api extends \Google\Protobuf\Internal\Message
+{
+ /**
+ * The fully qualified name of this interface, including package name
+ * followed by the interface's simple name.
+ *
+ * Generated from protobuf field <code>string name = 1;</code>
+ */
+ private $name = '';
+ /**
+ * The methods of this interface, in unspecified order.
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.Method methods = 2;</code>
+ */
+ private $methods;
+ /**
+ * Any metadata attached to the interface.
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.Option options = 3;</code>
+ */
+ private $options;
+ /**
+ * A version string for this interface. If specified, must have the form
+ * `major-version.minor-version`, as in `1.10`. If the minor version is
+ * omitted, it defaults to zero. If the entire version field is empty, the
+ * major version is derived from the package name, as outlined below. If the
+ * field is not empty, the version in the package name will be verified to be
+ * consistent with what is provided here.
+ * The versioning schema uses [semantic
+ * versioning](http://semver.org) where the major version number
+ * indicates a breaking change and the minor version an additive,
+ * non-breaking change. Both version numbers are signals to users
+ * what to expect from different versions, and should be carefully
+ * chosen based on the product plan.
+ * The major version is also reflected in the package name of the
+ * interface, which must end in `v<major-version>`, as in
+ * `google.feature.v1`. For major versions 0 and 1, the suffix can
+ * be omitted. Zero major versions must only be used for
+ * experimental, non-GA interfaces.
+ *
+ * Generated from protobuf field <code>string version = 4;</code>
+ */
+ private $version = '';
+ /**
+ * Source context for the protocol buffer service represented by this
+ * message.
+ *
+ * Generated from protobuf field <code>.google.protobuf.SourceContext source_context = 5;</code>
+ */
+ private $source_context = null;
+ /**
+ * Included interfaces. See [Mixin][].
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.Mixin mixins = 6;</code>
+ */
+ private $mixins;
+ /**
+ * The source syntax of the service.
+ *
+ * Generated from protobuf field <code>.google.protobuf.Syntax syntax = 7;</code>
+ */
+ private $syntax = 0;
+
+ public function __construct() {
+ \GPBMetadata\Google\Protobuf\Api::initOnce();
+ parent::__construct();
+ }
+
+ /**
+ * The fully qualified name of this interface, including package name
+ * followed by the interface's simple name.
+ *
+ * Generated from protobuf field <code>string name = 1;</code>
+ * @return string
+ */
+ public function getName()
+ {
+ return $this->name;
+ }
+
+ /**
+ * The fully qualified name of this interface, including package name
+ * followed by the interface's simple name.
+ *
+ * Generated from protobuf field <code>string name = 1;</code>
+ * @param string $var
+ * @return $this
+ */
+ public function setName($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->name = $var;
+
+ return $this;
+ }
+
+ /**
+ * The methods of this interface, in unspecified order.
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.Method methods = 2;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
+ */
+ public function getMethods()
+ {
+ return $this->methods;
+ }
+
+ /**
+ * The methods of this interface, in unspecified order.
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.Method methods = 2;</code>
+ * @param \Google\Protobuf\Method[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
+ */
+ public function setMethods($var)
+ {
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Method::class);
+ $this->methods = $arr;
+
+ return $this;
+ }
+
+ /**
+ * Any metadata attached to the interface.
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.Option options = 3;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
+ */
+ public function getOptions()
+ {
+ return $this->options;
+ }
+
+ /**
+ * Any metadata attached to the interface.
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.Option options = 3;</code>
+ * @param \Google\Protobuf\Option[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
+ */
+ public function setOptions($var)
+ {
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Option::class);
+ $this->options = $arr;
+
+ return $this;
+ }
+
+ /**
+ * A version string for this interface. If specified, must have the form
+ * `major-version.minor-version`, as in `1.10`. If the minor version is
+ * omitted, it defaults to zero. If the entire version field is empty, the
+ * major version is derived from the package name, as outlined below. If the
+ * field is not empty, the version in the package name will be verified to be
+ * consistent with what is provided here.
+ * The versioning schema uses [semantic
+ * versioning](http://semver.org) where the major version number
+ * indicates a breaking change and the minor version an additive,
+ * non-breaking change. Both version numbers are signals to users
+ * what to expect from different versions, and should be carefully
+ * chosen based on the product plan.
+ * The major version is also reflected in the package name of the
+ * interface, which must end in `v<major-version>`, as in
+ * `google.feature.v1`. For major versions 0 and 1, the suffix can
+ * be omitted. Zero major versions must only be used for
+ * experimental, non-GA interfaces.
+ *
+ * Generated from protobuf field <code>string version = 4;</code>
+ * @return string
+ */
+ public function getVersion()
+ {
+ return $this->version;
+ }
+
+ /**
+ * A version string for this interface. If specified, must have the form
+ * `major-version.minor-version`, as in `1.10`. If the minor version is
+ * omitted, it defaults to zero. If the entire version field is empty, the
+ * major version is derived from the package name, as outlined below. If the
+ * field is not empty, the version in the package name will be verified to be
+ * consistent with what is provided here.
+ * The versioning schema uses [semantic
+ * versioning](http://semver.org) where the major version number
+ * indicates a breaking change and the minor version an additive,
+ * non-breaking change. Both version numbers are signals to users
+ * what to expect from different versions, and should be carefully
+ * chosen based on the product plan.
+ * The major version is also reflected in the package name of the
+ * interface, which must end in `v<major-version>`, as in
+ * `google.feature.v1`. For major versions 0 and 1, the suffix can
+ * be omitted. Zero major versions must only be used for
+ * experimental, non-GA interfaces.
+ *
+ * Generated from protobuf field <code>string version = 4;</code>
+ * @param string $var
+ * @return $this
+ */
+ public function setVersion($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->version = $var;
+
+ return $this;
+ }
+
+ /**
+ * Source context for the protocol buffer service represented by this
+ * message.
+ *
+ * Generated from protobuf field <code>.google.protobuf.SourceContext source_context = 5;</code>
+ * @return \Google\Protobuf\SourceContext
+ */
+ public function getSourceContext()
+ {
+ return $this->source_context;
+ }
+
+ /**
+ * Source context for the protocol buffer service represented by this
+ * message.
+ *
+ * Generated from protobuf field <code>.google.protobuf.SourceContext source_context = 5;</code>
+ * @param \Google\Protobuf\SourceContext $var
+ * @return $this
+ */
+ public function setSourceContext($var)
+ {
+ GPBUtil::checkMessage($var, \Google\Protobuf\SourceContext::class);
+ $this->source_context = $var;
+
+ return $this;
+ }
+
+ /**
+ * Included interfaces. See [Mixin][].
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.Mixin mixins = 6;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
+ */
+ public function getMixins()
+ {
+ return $this->mixins;
+ }
+
+ /**
+ * Included interfaces. See [Mixin][].
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.Mixin mixins = 6;</code>
+ * @param \Google\Protobuf\Mixin[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
+ */
+ public function setMixins($var)
+ {
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Mixin::class);
+ $this->mixins = $arr;
+
+ return $this;
+ }
+
+ /**
+ * The source syntax of the service.
+ *
+ * Generated from protobuf field <code>.google.protobuf.Syntax syntax = 7;</code>
+ * @return int
+ */
+ public function getSyntax()
+ {
+ return $this->syntax;
+ }
+
+ /**
+ * The source syntax of the service.
+ *
+ * Generated from protobuf field <code>.google.protobuf.Syntax syntax = 7;</code>
+ * @param int $var
+ * @return $this
+ */
+ public function setSyntax($var)
+ {
+ GPBUtil::checkEnum($var, \Google\Protobuf\Syntax::class);
+ $this->syntax = $var;
+
+ return $this;
+ }
+
+}
+
diff --git a/php/src/Google/Protobuf/BoolValue.php b/php/src/Google/Protobuf/BoolValue.php
new file mode 100644
index 00000000..c28bf941
--- /dev/null
+++ b/php/src/Google/Protobuf/BoolValue.php
@@ -0,0 +1,58 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/wrappers.proto
+
+namespace Google\Protobuf;
+
+use Google\Protobuf\Internal\GPBType;
+use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\GPBUtil;
+
+/**
+ * Wrapper message for `bool`.
+ * The JSON representation for `BoolValue` is JSON `true` and `false`.
+ *
+ * Generated from protobuf message <code>google.protobuf.BoolValue</code>
+ */
+class BoolValue extends \Google\Protobuf\Internal\Message
+{
+ /**
+ * The bool value.
+ *
+ * Generated from protobuf field <code>bool value = 1;</code>
+ */
+ private $value = false;
+
+ public function __construct() {
+ \GPBMetadata\Google\Protobuf\Wrappers::initOnce();
+ parent::__construct();
+ }
+
+ /**
+ * The bool value.
+ *
+ * Generated from protobuf field <code>bool value = 1;</code>
+ * @return bool
+ */
+ public function getValue()
+ {
+ return $this->value;
+ }
+
+ /**
+ * The bool value.
+ *
+ * Generated from protobuf field <code>bool value = 1;</code>
+ * @param bool $var
+ * @return $this
+ */
+ public function setValue($var)
+ {
+ GPBUtil::checkBool($var);
+ $this->value = $var;
+
+ return $this;
+ }
+
+}
+
diff --git a/php/src/Google/Protobuf/BytesValue.php b/php/src/Google/Protobuf/BytesValue.php
new file mode 100644
index 00000000..d6a6b2e6
--- /dev/null
+++ b/php/src/Google/Protobuf/BytesValue.php
@@ -0,0 +1,58 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/wrappers.proto
+
+namespace Google\Protobuf;
+
+use Google\Protobuf\Internal\GPBType;
+use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\GPBUtil;
+
+/**
+ * Wrapper message for `bytes`.
+ * The JSON representation for `BytesValue` is JSON string.
+ *
+ * Generated from protobuf message <code>google.protobuf.BytesValue</code>
+ */
+class BytesValue extends \Google\Protobuf\Internal\Message
+{
+ /**
+ * The bytes value.
+ *
+ * Generated from protobuf field <code>bytes value = 1;</code>
+ */
+ private $value = '';
+
+ public function __construct() {
+ \GPBMetadata\Google\Protobuf\Wrappers::initOnce();
+ parent::__construct();
+ }
+
+ /**
+ * The bytes value.
+ *
+ * Generated from protobuf field <code>bytes value = 1;</code>
+ * @return string
+ */
+ public function getValue()
+ {
+ return $this->value;
+ }
+
+ /**
+ * The bytes value.
+ *
+ * Generated from protobuf field <code>bytes value = 1;</code>
+ * @param string $var
+ * @return $this
+ */
+ public function setValue($var)
+ {
+ GPBUtil::checkString($var, False);
+ $this->value = $var;
+
+ return $this;
+ }
+
+}
+
diff --git a/php/src/Google/Protobuf/Descriptor.php b/php/src/Google/Protobuf/Descriptor.php
new file mode 100644
index 00000000..986b81e1
--- /dev/null
+++ b/php/src/Google/Protobuf/Descriptor.php
@@ -0,0 +1,100 @@
+<?php
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2017 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.
+
+namespace Google\Protobuf;
+
+use Google\Protobuf\Internal\GetPublicDescriptorTrait;
+
+class Descriptor
+{
+ use GetPublicDescriptorTrait;
+
+ private $internal_desc;
+
+ /**
+ * @internal
+ */
+ public function __construct($internal_desc)
+ {
+ $this->internal_desc = $internal_desc;
+ }
+
+ /**
+ * @return string Full protobuf message name
+ */
+ public function getFullName()
+ {
+ return trim($this->internal_desc->getFullName(), ".");
+ }
+
+ /**
+ * @return string PHP class name
+ */
+ public function getClass()
+ {
+ return $this->internal_desc->getClass();
+ }
+
+ /**
+ * @param int $index Must be >= 0 and < getFieldCount()
+ * @return FieldDescriptor
+ */
+ public function getField($index)
+ {
+ return $this->getPublicDescriptor($this->internal_desc->getFieldByIndex($index));
+ }
+
+ /**
+ * @return int Number of fields in message
+ */
+ public function getFieldCount()
+ {
+ return count($this->internal_desc->getField());
+ }
+
+ /**
+ * @param int $index Must be >= 0 and < getOneofDeclCount()
+ * @return OneofDescriptor
+ */
+ public function getOneofDecl($index)
+ {
+ return $this->getPublicDescriptor($this->internal_desc->getOneofDecl()[$index]);
+ }
+
+ /**
+ * @return int Number of oneofs in message
+ */
+ public function getOneofDeclCount()
+ {
+ return count($this->internal_desc->getOneofDecl());
+ }
+}
diff --git a/php/src/Google/Protobuf/DescriptorPool.php b/php/src/Google/Protobuf/DescriptorPool.php
new file mode 100644
index 00000000..119f0e2e
--- /dev/null
+++ b/php/src/Google/Protobuf/DescriptorPool.php
@@ -0,0 +1,76 @@
+<?php
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2017 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.
+
+namespace Google\Protobuf;
+
+class DescriptorPool
+{
+ private static $pool;
+
+ private $internal_pool;
+
+ /**
+ * @return DescriptorPool
+ */
+ public static function getGeneratedPool()
+ {
+ if (!isset(self::$pool)) {
+ self::$pool = new DescriptorPool(\Google\Protobuf\Internal\DescriptorPool::getGeneratedPool());
+ }
+ return self::$pool;
+ }
+
+ private function __construct($internal_pool)
+ {
+ $this->internal_pool = $internal_pool;
+ }
+
+ /**
+ * @param string $className A fully qualified protobuf class name
+ * @return Descriptor
+ */
+ public function getDescriptorByClassName($className)
+ {
+ $desc = $this->internal_pool->getDescriptorByClassName($className);
+ return is_null($desc) ? null : $desc->getPublicDescriptor();
+ }
+
+ /**
+ * @param string $className A fully qualified protobuf class name
+ * @return EnumDescriptor
+ */
+ public function getEnumDescriptorByClassName($className)
+ {
+ $desc = $this->internal_pool->getEnumDescriptorByClassName($className);
+ return is_null($desc) ? null : $desc->getPublicDescriptor();
+ }
+}
diff --git a/php/src/Google/Protobuf/DoubleValue.php b/php/src/Google/Protobuf/DoubleValue.php
new file mode 100644
index 00000000..6718ce3c
--- /dev/null
+++ b/php/src/Google/Protobuf/DoubleValue.php
@@ -0,0 +1,58 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/wrappers.proto
+
+namespace Google\Protobuf;
+
+use Google\Protobuf\Internal\GPBType;
+use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\GPBUtil;
+
+/**
+ * Wrapper message for `double`.
+ * The JSON representation for `DoubleValue` is JSON number.
+ *
+ * Generated from protobuf message <code>google.protobuf.DoubleValue</code>
+ */
+class DoubleValue extends \Google\Protobuf\Internal\Message
+{
+ /**
+ * The double value.
+ *
+ * Generated from protobuf field <code>double value = 1;</code>
+ */
+ private $value = 0.0;
+
+ public function __construct() {
+ \GPBMetadata\Google\Protobuf\Wrappers::initOnce();
+ parent::__construct();
+ }
+
+ /**
+ * The double value.
+ *
+ * Generated from protobuf field <code>double value = 1;</code>
+ * @return float
+ */
+ public function getValue()
+ {
+ return $this->value;
+ }
+
+ /**
+ * The double value.
+ *
+ * Generated from protobuf field <code>double value = 1;</code>
+ * @param float $var
+ * @return $this
+ */
+ public function setValue($var)
+ {
+ GPBUtil::checkDouble($var);
+ $this->value = $var;
+
+ return $this;
+ }
+
+}
+
diff --git a/php/src/Google/Protobuf/Duration.php b/php/src/Google/Protobuf/Duration.php
new file mode 100644
index 00000000..ca1c4c07
--- /dev/null
+++ b/php/src/Google/Protobuf/Duration.php
@@ -0,0 +1,153 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/duration.proto
+
+namespace Google\Protobuf;
+
+use Google\Protobuf\Internal\GPBType;
+use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\GPBUtil;
+
+/**
+ * A Duration represents a signed, fixed-length span of time represented
+ * as a count of seconds and fractions of seconds at nanosecond
+ * resolution. It is independent of any calendar and concepts like "day"
+ * or "month". It is related to Timestamp in that the difference between
+ * two Timestamp values is a Duration and it can be added or subtracted
+ * from a Timestamp. Range is approximately +-10,000 years.
+ * # Examples
+ * Example 1: Compute Duration from two Timestamps in pseudo code.
+ * Timestamp start = ...;
+ * Timestamp end = ...;
+ * Duration duration = ...;
+ * duration.seconds = end.seconds - start.seconds;
+ * duration.nanos = end.nanos - start.nanos;
+ * if (duration.seconds < 0 && duration.nanos > 0) {
+ * duration.seconds += 1;
+ * duration.nanos -= 1000000000;
+ * } else if (durations.seconds > 0 && duration.nanos < 0) {
+ * duration.seconds -= 1;
+ * duration.nanos += 1000000000;
+ * }
+ * Example 2: Compute Timestamp from Timestamp + Duration in pseudo code.
+ * Timestamp start = ...;
+ * Duration duration = ...;
+ * Timestamp end = ...;
+ * end.seconds = start.seconds + duration.seconds;
+ * end.nanos = start.nanos + duration.nanos;
+ * if (end.nanos < 0) {
+ * end.seconds -= 1;
+ * end.nanos += 1000000000;
+ * } else if (end.nanos >= 1000000000) {
+ * end.seconds += 1;
+ * end.nanos -= 1000000000;
+ * }
+ * Example 3: Compute Duration from datetime.timedelta in Python.
+ * td = datetime.timedelta(days=3, minutes=10)
+ * duration = Duration()
+ * duration.FromTimedelta(td)
+ * # JSON Mapping
+ * In JSON format, the Duration type is encoded as a string rather than an
+ * object, where the string ends in the suffix "s" (indicating seconds) and
+ * is preceded by the number of seconds, with nanoseconds expressed as
+ * fractional seconds. For example, 3 seconds with 0 nanoseconds should be
+ * encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should
+ * be expressed in JSON format as "3.000000001s", and 3 seconds and 1
+ * microsecond should be expressed in JSON format as "3.000001s".
+ *
+ * Generated from protobuf message <code>google.protobuf.Duration</code>
+ */
+class Duration extends \Google\Protobuf\Internal\Message
+{
+ /**
+ * Signed seconds of the span of time. Must be from -315,576,000,000
+ * to +315,576,000,000 inclusive. Note: these bounds are computed from:
+ * 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years
+ *
+ * Generated from protobuf field <code>int64 seconds = 1;</code>
+ */
+ private $seconds = 0;
+ /**
+ * Signed fractions of a second at nanosecond resolution of the span
+ * of time. Durations less than one second are represented with a 0
+ * `seconds` field and a positive or negative `nanos` field. For durations
+ * of one second or more, a non-zero value for the `nanos` field must be
+ * of the same sign as the `seconds` field. Must be from -999,999,999
+ * to +999,999,999 inclusive.
+ *
+ * Generated from protobuf field <code>int32 nanos = 2;</code>
+ */
+ private $nanos = 0;
+
+ public function __construct() {
+ \GPBMetadata\Google\Protobuf\Duration::initOnce();
+ parent::__construct();
+ }
+
+ /**
+ * Signed seconds of the span of time. Must be from -315,576,000,000
+ * to +315,576,000,000 inclusive. Note: these bounds are computed from:
+ * 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years
+ *
+ * Generated from protobuf field <code>int64 seconds = 1;</code>
+ * @return int|string
+ */
+ public function getSeconds()
+ {
+ return $this->seconds;
+ }
+
+ /**
+ * Signed seconds of the span of time. Must be from -315,576,000,000
+ * to +315,576,000,000 inclusive. Note: these bounds are computed from:
+ * 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years
+ *
+ * Generated from protobuf field <code>int64 seconds = 1;</code>
+ * @param int|string $var
+ * @return $this
+ */
+ public function setSeconds($var)
+ {
+ GPBUtil::checkInt64($var);
+ $this->seconds = $var;
+
+ return $this;
+ }
+
+ /**
+ * Signed fractions of a second at nanosecond resolution of the span
+ * of time. Durations less than one second are represented with a 0
+ * `seconds` field and a positive or negative `nanos` field. For durations
+ * of one second or more, a non-zero value for the `nanos` field must be
+ * of the same sign as the `seconds` field. Must be from -999,999,999
+ * to +999,999,999 inclusive.
+ *
+ * Generated from protobuf field <code>int32 nanos = 2;</code>
+ * @return int
+ */
+ public function getNanos()
+ {
+ return $this->nanos;
+ }
+
+ /**
+ * Signed fractions of a second at nanosecond resolution of the span
+ * of time. Durations less than one second are represented with a 0
+ * `seconds` field and a positive or negative `nanos` field. For durations
+ * of one second or more, a non-zero value for the `nanos` field must be
+ * of the same sign as the `seconds` field. Must be from -999,999,999
+ * to +999,999,999 inclusive.
+ *
+ * Generated from protobuf field <code>int32 nanos = 2;</code>
+ * @param int $var
+ * @return $this
+ */
+ public function setNanos($var)
+ {
+ GPBUtil::checkInt32($var);
+ $this->nanos = $var;
+
+ return $this;
+ }
+}
+
diff --git a/php/src/Google/Protobuf/Enum.php b/php/src/Google/Protobuf/Enum.php
new file mode 100644
index 00000000..c63efc74
--- /dev/null
+++ b/php/src/Google/Protobuf/Enum.php
@@ -0,0 +1,185 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/type.proto
+
+namespace Google\Protobuf;
+
+use Google\Protobuf\Internal\GPBType;
+use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\GPBUtil;
+
+/**
+ * Enum type definition.
+ *
+ * Generated from protobuf message <code>google.protobuf.Enum</code>
+ */
+class Enum extends \Google\Protobuf\Internal\Message
+{
+ /**
+ * Enum type name.
+ *
+ * Generated from protobuf field <code>string name = 1;</code>
+ */
+ private $name = '';
+ /**
+ * Enum value definitions.
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.EnumValue enumvalue = 2;</code>
+ */
+ private $enumvalue;
+ /**
+ * Protocol buffer options.
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.Option options = 3;</code>
+ */
+ private $options;
+ /**
+ * The source context.
+ *
+ * Generated from protobuf field <code>.google.protobuf.SourceContext source_context = 4;</code>
+ */
+ private $source_context = null;
+ /**
+ * The source syntax.
+ *
+ * Generated from protobuf field <code>.google.protobuf.Syntax syntax = 5;</code>
+ */
+ private $syntax = 0;
+
+ public function __construct() {
+ \GPBMetadata\Google\Protobuf\Type::initOnce();
+ parent::__construct();
+ }
+
+ /**
+ * Enum type name.
+ *
+ * Generated from protobuf field <code>string name = 1;</code>
+ * @return string
+ */
+ public function getName()
+ {
+ return $this->name;
+ }
+
+ /**
+ * Enum type name.
+ *
+ * Generated from protobuf field <code>string name = 1;</code>
+ * @param string $var
+ * @return $this
+ */
+ public function setName($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->name = $var;
+
+ return $this;
+ }
+
+ /**
+ * Enum value definitions.
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.EnumValue enumvalue = 2;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
+ */
+ public function getEnumvalue()
+ {
+ return $this->enumvalue;
+ }
+
+ /**
+ * Enum value definitions.
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.EnumValue enumvalue = 2;</code>
+ * @param \Google\Protobuf\EnumValue[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
+ */
+ public function setEnumvalue($var)
+ {
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\EnumValue::class);
+ $this->enumvalue = $arr;
+
+ return $this;
+ }
+
+ /**
+ * Protocol buffer options.
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.Option options = 3;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
+ */
+ public function getOptions()
+ {
+ return $this->options;
+ }
+
+ /**
+ * Protocol buffer options.
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.Option options = 3;</code>
+ * @param \Google\Protobuf\Option[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
+ */
+ public function setOptions($var)
+ {
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Option::class);
+ $this->options = $arr;
+
+ return $this;
+ }
+
+ /**
+ * The source context.
+ *
+ * Generated from protobuf field <code>.google.protobuf.SourceContext source_context = 4;</code>
+ * @return \Google\Protobuf\SourceContext
+ */
+ public function getSourceContext()
+ {
+ return $this->source_context;
+ }
+
+ /**
+ * The source context.
+ *
+ * Generated from protobuf field <code>.google.protobuf.SourceContext source_context = 4;</code>
+ * @param \Google\Protobuf\SourceContext $var
+ * @return $this
+ */
+ public function setSourceContext($var)
+ {
+ GPBUtil::checkMessage($var, \Google\Protobuf\SourceContext::class);
+ $this->source_context = $var;
+
+ return $this;
+ }
+
+ /**
+ * The source syntax.
+ *
+ * Generated from protobuf field <code>.google.protobuf.Syntax syntax = 5;</code>
+ * @return int
+ */
+ public function getSyntax()
+ {
+ return $this->syntax;
+ }
+
+ /**
+ * The source syntax.
+ *
+ * Generated from protobuf field <code>.google.protobuf.Syntax syntax = 5;</code>
+ * @param int $var
+ * @return $this
+ */
+ public function setSyntax($var)
+ {
+ GPBUtil::checkEnum($var, \Google\Protobuf\Syntax::class);
+ $this->syntax = $var;
+
+ return $this;
+ }
+
+}
+
diff --git a/php/src/Google/Protobuf/EnumDescriptor.php b/php/src/Google/Protobuf/EnumDescriptor.php
new file mode 100644
index 00000000..a8b56c0d
--- /dev/null
+++ b/php/src/Google/Protobuf/EnumDescriptor.php
@@ -0,0 +1,79 @@
+<?php
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2017 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.
+
+namespace Google\Protobuf;
+
+class EnumDescriptor
+{
+ private $internal_desc;
+
+ /**
+ * @internal
+ */
+ public function __construct($internal_desc)
+ {
+ $this->internal_desc = $internal_desc;
+ }
+
+ /**
+ * @return string Full protobuf message name
+ */
+ public function getFullName()
+ {
+ return $this->internal_desc->getFullName();
+ }
+
+ /**
+ * @return string PHP class name
+ */
+ public function getClass()
+ {
+ return $this->internal_desc->getClass();
+ }
+
+ /**
+ * @param int $index Must be >= 0 and < getValueCount()
+ * @return EnumValueDescriptor
+ */
+ public function getValue($index)
+ {
+ return $this->internal_desc->getValueDescriptorByIndex($index);
+ }
+
+ /**
+ * @return int Number of values in enum
+ */
+ public function getValueCount()
+ {
+ return $this->internal_desc->getValueCount();
+ }
+}
diff --git a/php/src/Google/Protobuf/EnumValue.php b/php/src/Google/Protobuf/EnumValue.php
new file mode 100644
index 00000000..e102c29f
--- /dev/null
+++ b/php/src/Google/Protobuf/EnumValue.php
@@ -0,0 +1,121 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/type.proto
+
+namespace Google\Protobuf;
+
+use Google\Protobuf\Internal\GPBType;
+use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\GPBUtil;
+
+/**
+ * Enum value definition.
+ *
+ * Generated from protobuf message <code>google.protobuf.EnumValue</code>
+ */
+class EnumValue extends \Google\Protobuf\Internal\Message
+{
+ /**
+ * Enum value name.
+ *
+ * Generated from protobuf field <code>string name = 1;</code>
+ */
+ private $name = '';
+ /**
+ * Enum value number.
+ *
+ * Generated from protobuf field <code>int32 number = 2;</code>
+ */
+ private $number = 0;
+ /**
+ * Protocol buffer options.
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.Option options = 3;</code>
+ */
+ private $options;
+
+ public function __construct() {
+ \GPBMetadata\Google\Protobuf\Type::initOnce();
+ parent::__construct();
+ }
+
+ /**
+ * Enum value name.
+ *
+ * Generated from protobuf field <code>string name = 1;</code>
+ * @return string
+ */
+ public function getName()
+ {
+ return $this->name;
+ }
+
+ /**
+ * Enum value name.
+ *
+ * Generated from protobuf field <code>string name = 1;</code>
+ * @param string $var
+ * @return $this
+ */
+ public function setName($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->name = $var;
+
+ return $this;
+ }
+
+ /**
+ * Enum value number.
+ *
+ * Generated from protobuf field <code>int32 number = 2;</code>
+ * @return int
+ */
+ public function getNumber()
+ {
+ return $this->number;
+ }
+
+ /**
+ * Enum value number.
+ *
+ * Generated from protobuf field <code>int32 number = 2;</code>
+ * @param int $var
+ * @return $this
+ */
+ public function setNumber($var)
+ {
+ GPBUtil::checkInt32($var);
+ $this->number = $var;
+
+ return $this;
+ }
+
+ /**
+ * Protocol buffer options.
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.Option options = 3;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
+ */
+ public function getOptions()
+ {
+ return $this->options;
+ }
+
+ /**
+ * Protocol buffer options.
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.Option options = 3;</code>
+ * @param \Google\Protobuf\Option[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
+ */
+ public function setOptions($var)
+ {
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Option::class);
+ $this->options = $arr;
+
+ return $this;
+ }
+
+}
+
diff --git a/php/src/Google/Protobuf/EnumValueDescriptor.php b/php/src/Google/Protobuf/EnumValueDescriptor.php
new file mode 100644
index 00000000..e76e1997
--- /dev/null
+++ b/php/src/Google/Protobuf/EnumValueDescriptor.php
@@ -0,0 +1,64 @@
+<?php
+
+// 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.
+
+namespace Google\Protobuf;
+
+class EnumValueDescriptor
+{
+ private $name;
+ private $number;
+
+ /**
+ * @internal
+ */
+ public function __construct($name, $number)
+ {
+ $this->name = $name;
+ $this->number = $number;
+ }
+
+ /**
+ * @return string
+ */
+ public function getName()
+ {
+ return $this->name;
+ }
+
+ /**
+ * @return int
+ */
+ public function getNumber()
+ {
+ return $this->number;
+ }
+}
diff --git a/php/src/Google/Protobuf/Field.php b/php/src/Google/Protobuf/Field.php
new file mode 100644
index 00000000..0b560d89
--- /dev/null
+++ b/php/src/Google/Protobuf/Field.php
@@ -0,0 +1,351 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/type.proto
+
+namespace Google\Protobuf;
+
+use Google\Protobuf\Internal\GPBType;
+use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\GPBUtil;
+
+/**
+ * A single field of a message type.
+ *
+ * Generated from protobuf message <code>google.protobuf.Field</code>
+ */
+class Field extends \Google\Protobuf\Internal\Message
+{
+ /**
+ * The field type.
+ *
+ * Generated from protobuf field <code>.google.protobuf.Field.Kind kind = 1;</code>
+ */
+ private $kind = 0;
+ /**
+ * The field cardinality.
+ *
+ * Generated from protobuf field <code>.google.protobuf.Field.Cardinality cardinality = 2;</code>
+ */
+ private $cardinality = 0;
+ /**
+ * The field number.
+ *
+ * Generated from protobuf field <code>int32 number = 3;</code>
+ */
+ private $number = 0;
+ /**
+ * The field name.
+ *
+ * Generated from protobuf field <code>string name = 4;</code>
+ */
+ private $name = '';
+ /**
+ * The field type URL, without the scheme, for message or enumeration
+ * types. Example: `"type.googleapis.com/google.protobuf.Timestamp"`.
+ *
+ * Generated from protobuf field <code>string type_url = 6;</code>
+ */
+ private $type_url = '';
+ /**
+ * The index of the field type in `Type.oneofs`, for message or enumeration
+ * types. The first type has index 1; zero means the type is not in the list.
+ *
+ * Generated from protobuf field <code>int32 oneof_index = 7;</code>
+ */
+ private $oneof_index = 0;
+ /**
+ * Whether to use alternative packed wire representation.
+ *
+ * Generated from protobuf field <code>bool packed = 8;</code>
+ */
+ private $packed = false;
+ /**
+ * The protocol buffer options.
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.Option options = 9;</code>
+ */
+ private $options;
+ /**
+ * The field JSON name.
+ *
+ * Generated from protobuf field <code>string json_name = 10;</code>
+ */
+ private $json_name = '';
+ /**
+ * The string value of the default value of this field. Proto2 syntax only.
+ *
+ * Generated from protobuf field <code>string default_value = 11;</code>
+ */
+ private $default_value = '';
+
+ public function __construct() {
+ \GPBMetadata\Google\Protobuf\Type::initOnce();
+ parent::__construct();
+ }
+
+ /**
+ * The field type.
+ *
+ * Generated from protobuf field <code>.google.protobuf.Field.Kind kind = 1;</code>
+ * @return int
+ */
+ public function getKind()
+ {
+ return $this->kind;
+ }
+
+ /**
+ * The field type.
+ *
+ * Generated from protobuf field <code>.google.protobuf.Field.Kind kind = 1;</code>
+ * @param int $var
+ * @return $this
+ */
+ public function setKind($var)
+ {
+ GPBUtil::checkEnum($var, \Google\Protobuf\Field_Kind::class);
+ $this->kind = $var;
+
+ return $this;
+ }
+
+ /**
+ * The field cardinality.
+ *
+ * Generated from protobuf field <code>.google.protobuf.Field.Cardinality cardinality = 2;</code>
+ * @return int
+ */
+ public function getCardinality()
+ {
+ return $this->cardinality;
+ }
+
+ /**
+ * The field cardinality.
+ *
+ * Generated from protobuf field <code>.google.protobuf.Field.Cardinality cardinality = 2;</code>
+ * @param int $var
+ * @return $this
+ */
+ public function setCardinality($var)
+ {
+ GPBUtil::checkEnum($var, \Google\Protobuf\Field_Cardinality::class);
+ $this->cardinality = $var;
+
+ return $this;
+ }
+
+ /**
+ * The field number.
+ *
+ * Generated from protobuf field <code>int32 number = 3;</code>
+ * @return int
+ */
+ public function getNumber()
+ {
+ return $this->number;
+ }
+
+ /**
+ * The field number.
+ *
+ * Generated from protobuf field <code>int32 number = 3;</code>
+ * @param int $var
+ * @return $this
+ */
+ public function setNumber($var)
+ {
+ GPBUtil::checkInt32($var);
+ $this->number = $var;
+
+ return $this;
+ }
+
+ /**
+ * The field name.
+ *
+ * Generated from protobuf field <code>string name = 4;</code>
+ * @return string
+ */
+ public function getName()
+ {
+ return $this->name;
+ }
+
+ /**
+ * The field name.
+ *
+ * Generated from protobuf field <code>string name = 4;</code>
+ * @param string $var
+ * @return $this
+ */
+ public function setName($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->name = $var;
+
+ return $this;
+ }
+
+ /**
+ * The field type URL, without the scheme, for message or enumeration
+ * types. Example: `"type.googleapis.com/google.protobuf.Timestamp"`.
+ *
+ * Generated from protobuf field <code>string type_url = 6;</code>
+ * @return string
+ */
+ public function getTypeUrl()
+ {
+ return $this->type_url;
+ }
+
+ /**
+ * The field type URL, without the scheme, for message or enumeration
+ * types. Example: `"type.googleapis.com/google.protobuf.Timestamp"`.
+ *
+ * Generated from protobuf field <code>string type_url = 6;</code>
+ * @param string $var
+ * @return $this
+ */
+ public function setTypeUrl($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->type_url = $var;
+
+ return $this;
+ }
+
+ /**
+ * The index of the field type in `Type.oneofs`, for message or enumeration
+ * types. The first type has index 1; zero means the type is not in the list.
+ *
+ * Generated from protobuf field <code>int32 oneof_index = 7;</code>
+ * @return int
+ */
+ public function getOneofIndex()
+ {
+ return $this->oneof_index;
+ }
+
+ /**
+ * The index of the field type in `Type.oneofs`, for message or enumeration
+ * types. The first type has index 1; zero means the type is not in the list.
+ *
+ * Generated from protobuf field <code>int32 oneof_index = 7;</code>
+ * @param int $var
+ * @return $this
+ */
+ public function setOneofIndex($var)
+ {
+ GPBUtil::checkInt32($var);
+ $this->oneof_index = $var;
+
+ return $this;
+ }
+
+ /**
+ * Whether to use alternative packed wire representation.
+ *
+ * Generated from protobuf field <code>bool packed = 8;</code>
+ * @return bool
+ */
+ public function getPacked()
+ {
+ return $this->packed;
+ }
+
+ /**
+ * Whether to use alternative packed wire representation.
+ *
+ * Generated from protobuf field <code>bool packed = 8;</code>
+ * @param bool $var
+ * @return $this
+ */
+ public function setPacked($var)
+ {
+ GPBUtil::checkBool($var);
+ $this->packed = $var;
+
+ return $this;
+ }
+
+ /**
+ * The protocol buffer options.
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.Option options = 9;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
+ */
+ public function getOptions()
+ {
+ return $this->options;
+ }
+
+ /**
+ * The protocol buffer options.
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.Option options = 9;</code>
+ * @param \Google\Protobuf\Option[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
+ */
+ public function setOptions($var)
+ {
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Option::class);
+ $this->options = $arr;
+
+ return $this;
+ }
+
+ /**
+ * The field JSON name.
+ *
+ * Generated from protobuf field <code>string json_name = 10;</code>
+ * @return string
+ */
+ public function getJsonName()
+ {
+ return $this->json_name;
+ }
+
+ /**
+ * The field JSON name.
+ *
+ * Generated from protobuf field <code>string json_name = 10;</code>
+ * @param string $var
+ * @return $this
+ */
+ public function setJsonName($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->json_name = $var;
+
+ return $this;
+ }
+
+ /**
+ * The string value of the default value of this field. Proto2 syntax only.
+ *
+ * Generated from protobuf field <code>string default_value = 11;</code>
+ * @return string
+ */
+ public function getDefaultValue()
+ {
+ return $this->default_value;
+ }
+
+ /**
+ * The string value of the default value of this field. Proto2 syntax only.
+ *
+ * Generated from protobuf field <code>string default_value = 11;</code>
+ * @param string $var
+ * @return $this
+ */
+ public function setDefaultValue($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->default_value = $var;
+
+ return $this;
+ }
+
+}
+
diff --git a/php/src/Google/Protobuf/FieldDescriptor.php b/php/src/Google/Protobuf/FieldDescriptor.php
new file mode 100644
index 00000000..ac9271f9
--- /dev/null
+++ b/php/src/Google/Protobuf/FieldDescriptor.php
@@ -0,0 +1,117 @@
+<?php
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2017 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.
+
+namespace Google\Protobuf;
+
+use Google\Protobuf\Internal\GetPublicDescriptorTrait;
+use Google\Protobuf\Internal\GPBType;
+
+class FieldDescriptor
+{
+ use GetPublicDescriptorTrait;
+
+ private $internal_desc;
+
+ /**
+ * @internal
+ */
+ public function __construct($internal_desc)
+ {
+ $this->internal_desc = $internal_desc;
+ }
+
+ /**
+ * @return string Field name
+ */
+ public function getName()
+ {
+ return $this->internal_desc->getName();
+ }
+
+ /**
+ * @return int Protobuf field number
+ */
+ public function getNumber()
+ {
+ return $this->internal_desc->getNumber();
+ }
+
+ /**
+ * @return int
+ */
+ public function getLabel()
+ {
+ return $this->internal_desc->getLabel();
+ }
+
+ /**
+ * @return int
+ */
+ public function getType()
+ {
+ return $this->internal_desc->getType();
+ }
+
+ /**
+ * @return Descriptor Returns a descriptor for the field type if the field type is a message, otherwise throws \Exception
+ * @throws \Exception
+ */
+ public function getMessageType()
+ {
+ if ($this->getType() == GPBType::MESSAGE) {
+ return $this->getPublicDescriptor($this->internal_desc->getMessageType());
+ } else {
+ throw new \Exception("Cannot get message type for non-message field '" . $this->getName() . "'");
+ }
+ }
+
+ /**
+ * @return EnumDescriptor Returns an enum descriptor if the field type is an enum, otherwise throws \Exception
+ * @throws \Exception
+ */
+ public function getEnumType()
+ {
+ if ($this->getType() == GPBType::ENUM) {
+ return $this->getPublicDescriptor($this->internal_desc->getEnumType());
+ } else {
+ throw new \Exception("Cannot get enum type for non-enum field '" . $this->getName() . "'");
+ }
+ }
+
+ /**
+ * @return boolean
+ */
+ public function isMap()
+ {
+ return $this->internal_desc->isMap();
+ }
+}
diff --git a/php/src/Google/Protobuf/FieldMask.php b/php/src/Google/Protobuf/FieldMask.php
new file mode 100644
index 00000000..e18586af
--- /dev/null
+++ b/php/src/Google/Protobuf/FieldMask.php
@@ -0,0 +1,209 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/field_mask.proto
+
+namespace Google\Protobuf;
+
+use Google\Protobuf\Internal\GPBType;
+use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\GPBUtil;
+
+/**
+ * `FieldMask` represents a set of symbolic field paths, for example:
+ * paths: "f.a"
+ * paths: "f.b.d"
+ * Here `f` represents a field in some root message, `a` and `b`
+ * fields in the message found in `f`, and `d` a field found in the
+ * message in `f.b`.
+ * Field masks are used to specify a subset of fields that should be
+ * returned by a get operation or modified by an update operation.
+ * Field masks also have a custom JSON encoding (see below).
+ * # Field Masks in Projections
+ * When used in the context of a projection, a response message or
+ * sub-message is filtered by the API to only contain those fields as
+ * specified in the mask. For example, if the mask in the previous
+ * example is applied to a response message as follows:
+ * f {
+ * a : 22
+ * b {
+ * d : 1
+ * x : 2
+ * }
+ * y : 13
+ * }
+ * z: 8
+ * The result will not contain specific values for fields x,y and z
+ * (their value will be set to the default, and omitted in proto text
+ * output):
+ * f {
+ * a : 22
+ * b {
+ * d : 1
+ * }
+ * }
+ * A repeated field is not allowed except at the last position of a
+ * paths string.
+ * If a FieldMask object is not present in a get operation, the
+ * operation applies to all fields (as if a FieldMask of all fields
+ * had been specified).
+ * Note that a field mask does not necessarily apply to the
+ * top-level response message. In case of a REST get operation, the
+ * field mask applies directly to the response, but in case of a REST
+ * list operation, the mask instead applies to each individual message
+ * in the returned resource list. In case of a REST custom method,
+ * other definitions may be used. Where the mask applies will be
+ * clearly documented together with its declaration in the API. In
+ * any case, the effect on the returned resource/resources is required
+ * behavior for APIs.
+ * # Field Masks in Update Operations
+ * A field mask in update operations specifies which fields of the
+ * targeted resource are going to be updated. The API is required
+ * to only change the values of the fields as specified in the mask
+ * and leave the others untouched. If a resource is passed in to
+ * describe the updated values, the API ignores the values of all
+ * fields not covered by the mask.
+ * If a repeated field is specified for an update operation, the existing
+ * repeated values in the target resource will be overwritten by the new values.
+ * Note that a repeated field is only allowed in the last position of a `paths`
+ * string.
+ * If a sub-message is specified in the last position of the field mask for an
+ * update operation, then the existing sub-message in the target resource is
+ * overwritten. Given the target message:
+ * f {
+ * b {
+ * d : 1
+ * x : 2
+ * }
+ * c : 1
+ * }
+ * And an update message:
+ * f {
+ * b {
+ * d : 10
+ * }
+ * }
+ * then if the field mask is:
+ * paths: "f.b"
+ * then the result will be:
+ * f {
+ * b {
+ * d : 10
+ * }
+ * c : 1
+ * }
+ * However, if the update mask was:
+ * paths: "f.b.d"
+ * then the result would be:
+ * f {
+ * b {
+ * d : 10
+ * x : 2
+ * }
+ * c : 1
+ * }
+ * In order to reset a field's value to the default, the field must
+ * be in the mask and set to the default value in the provided resource.
+ * Hence, in order to reset all fields of a resource, provide a default
+ * instance of the resource and set all fields in the mask, or do
+ * not provide a mask as described below.
+ * If a field mask is not present on update, the operation applies to
+ * all fields (as if a field mask of all fields has been specified).
+ * Note that in the presence of schema evolution, this may mean that
+ * fields the client does not know and has therefore not filled into
+ * the request will be reset to their default. If this is unwanted
+ * behavior, a specific service may require a client to always specify
+ * a field mask, producing an error if not.
+ * As with get operations, the location of the resource which
+ * describes the updated values in the request message depends on the
+ * operation kind. In any case, the effect of the field mask is
+ * required to be honored by the API.
+ * ## Considerations for HTTP REST
+ * The HTTP kind of an update operation which uses a field mask must
+ * be set to PATCH instead of PUT in order to satisfy HTTP semantics
+ * (PUT must only be used for full updates).
+ * # JSON Encoding of Field Masks
+ * In JSON, a field mask is encoded as a single string where paths are
+ * separated by a comma. Fields name in each path are converted
+ * to/from lower-camel naming conventions.
+ * As an example, consider the following message declarations:
+ * message Profile {
+ * User user = 1;
+ * Photo photo = 2;
+ * }
+ * message User {
+ * string display_name = 1;
+ * string address = 2;
+ * }
+ * In proto a field mask for `Profile` may look as such:
+ * mask {
+ * paths: "user.display_name"
+ * paths: "photo"
+ * }
+ * In JSON, the same mask is represented as below:
+ * {
+ * mask: "user.displayName,photo"
+ * }
+ * # Field Masks and Oneof Fields
+ * Field masks treat fields in oneofs just as regular fields. Consider the
+ * following message:
+ * message SampleMessage {
+ * oneof test_oneof {
+ * string name = 4;
+ * SubMessage sub_message = 9;
+ * }
+ * }
+ * The field mask can be:
+ * mask {
+ * paths: "name"
+ * }
+ * Or:
+ * mask {
+ * paths: "sub_message"
+ * }
+ * Note that oneof type names ("test_oneof" in this case) cannot be used in
+ * paths.
+ *
+ * Generated from protobuf message <code>google.protobuf.FieldMask</code>
+ */
+class FieldMask extends \Google\Protobuf\Internal\Message
+{
+ /**
+ * The set of field mask paths.
+ *
+ * Generated from protobuf field <code>repeated string paths = 1;</code>
+ */
+ private $paths;
+
+ public function __construct() {
+ \GPBMetadata\Google\Protobuf\FieldMask::initOnce();
+ parent::__construct();
+ }
+
+ /**
+ * The set of field mask paths.
+ *
+ * Generated from protobuf field <code>repeated string paths = 1;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
+ */
+ public function getPaths()
+ {
+ return $this->paths;
+ }
+
+ /**
+ * The set of field mask paths.
+ *
+ * Generated from protobuf field <code>repeated string paths = 1;</code>
+ * @param string[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
+ */
+ public function setPaths($var)
+ {
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::STRING);
+ $this->paths = $arr;
+
+ return $this;
+ }
+
+}
+
diff --git a/php/src/Google/Protobuf/Field_Cardinality.php b/php/src/Google/Protobuf/Field_Cardinality.php
new file mode 100644
index 00000000..422587ca
--- /dev/null
+++ b/php/src/Google/Protobuf/Field_Cardinality.php
@@ -0,0 +1,39 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/type.proto
+
+namespace Google\Protobuf;
+
+/**
+ * Whether a field is optional, required, or repeated.
+ *
+ * Protobuf enum <code>Google\Protobuf\Field\Cardinality</code>
+ */
+class Field_Cardinality
+{
+ /**
+ * For fields with unknown cardinality.
+ *
+ * Generated from protobuf enum <code>CARDINALITY_UNKNOWN = 0;</code>
+ */
+ const CARDINALITY_UNKNOWN = 0;
+ /**
+ * For optional fields.
+ *
+ * Generated from protobuf enum <code>CARDINALITY_OPTIONAL = 1;</code>
+ */
+ const CARDINALITY_OPTIONAL = 1;
+ /**
+ * For required fields. Proto2 syntax only.
+ *
+ * Generated from protobuf enum <code>CARDINALITY_REQUIRED = 2;</code>
+ */
+ const CARDINALITY_REQUIRED = 2;
+ /**
+ * For repeated fields.
+ *
+ * Generated from protobuf enum <code>CARDINALITY_REPEATED = 3;</code>
+ */
+ const CARDINALITY_REPEATED = 3;
+}
+
diff --git a/php/src/Google/Protobuf/Field_Kind.php b/php/src/Google/Protobuf/Field_Kind.php
new file mode 100644
index 00000000..d0774970
--- /dev/null
+++ b/php/src/Google/Protobuf/Field_Kind.php
@@ -0,0 +1,129 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/type.proto
+
+namespace Google\Protobuf;
+
+/**
+ * Basic field types.
+ *
+ * Protobuf enum <code>Google\Protobuf\Field\Kind</code>
+ */
+class Field_Kind
+{
+ /**
+ * Field type unknown.
+ *
+ * Generated from protobuf enum <code>TYPE_UNKNOWN = 0;</code>
+ */
+ const TYPE_UNKNOWN = 0;
+ /**
+ * Field type double.
+ *
+ * Generated from protobuf enum <code>TYPE_DOUBLE = 1;</code>
+ */
+ const TYPE_DOUBLE = 1;
+ /**
+ * Field type float.
+ *
+ * Generated from protobuf enum <code>TYPE_FLOAT = 2;</code>
+ */
+ const TYPE_FLOAT = 2;
+ /**
+ * Field type int64.
+ *
+ * Generated from protobuf enum <code>TYPE_INT64 = 3;</code>
+ */
+ const TYPE_INT64 = 3;
+ /**
+ * Field type uint64.
+ *
+ * Generated from protobuf enum <code>TYPE_UINT64 = 4;</code>
+ */
+ const TYPE_UINT64 = 4;
+ /**
+ * Field type int32.
+ *
+ * Generated from protobuf enum <code>TYPE_INT32 = 5;</code>
+ */
+ const TYPE_INT32 = 5;
+ /**
+ * Field type fixed64.
+ *
+ * Generated from protobuf enum <code>TYPE_FIXED64 = 6;</code>
+ */
+ const TYPE_FIXED64 = 6;
+ /**
+ * Field type fixed32.
+ *
+ * Generated from protobuf enum <code>TYPE_FIXED32 = 7;</code>
+ */
+ const TYPE_FIXED32 = 7;
+ /**
+ * Field type bool.
+ *
+ * Generated from protobuf enum <code>TYPE_BOOL = 8;</code>
+ */
+ const TYPE_BOOL = 8;
+ /**
+ * Field type string.
+ *
+ * Generated from protobuf enum <code>TYPE_STRING = 9;</code>
+ */
+ const TYPE_STRING = 9;
+ /**
+ * Field type group. Proto2 syntax only, and deprecated.
+ *
+ * Generated from protobuf enum <code>TYPE_GROUP = 10;</code>
+ */
+ const TYPE_GROUP = 10;
+ /**
+ * Field type message.
+ *
+ * Generated from protobuf enum <code>TYPE_MESSAGE = 11;</code>
+ */
+ const TYPE_MESSAGE = 11;
+ /**
+ * Field type bytes.
+ *
+ * Generated from protobuf enum <code>TYPE_BYTES = 12;</code>
+ */
+ const TYPE_BYTES = 12;
+ /**
+ * Field type uint32.
+ *
+ * Generated from protobuf enum <code>TYPE_UINT32 = 13;</code>
+ */
+ const TYPE_UINT32 = 13;
+ /**
+ * Field type enum.
+ *
+ * Generated from protobuf enum <code>TYPE_ENUM = 14;</code>
+ */
+ const TYPE_ENUM = 14;
+ /**
+ * Field type sfixed32.
+ *
+ * Generated from protobuf enum <code>TYPE_SFIXED32 = 15;</code>
+ */
+ const TYPE_SFIXED32 = 15;
+ /**
+ * Field type sfixed64.
+ *
+ * Generated from protobuf enum <code>TYPE_SFIXED64 = 16;</code>
+ */
+ const TYPE_SFIXED64 = 16;
+ /**
+ * Field type sint32.
+ *
+ * Generated from protobuf enum <code>TYPE_SINT32 = 17;</code>
+ */
+ const TYPE_SINT32 = 17;
+ /**
+ * Field type sint64.
+ *
+ * Generated from protobuf enum <code>TYPE_SINT64 = 18;</code>
+ */
+ const TYPE_SINT64 = 18;
+}
+
diff --git a/php/src/Google/Protobuf/FloatValue.php b/php/src/Google/Protobuf/FloatValue.php
new file mode 100644
index 00000000..68787ef9
--- /dev/null
+++ b/php/src/Google/Protobuf/FloatValue.php
@@ -0,0 +1,58 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/wrappers.proto
+
+namespace Google\Protobuf;
+
+use Google\Protobuf\Internal\GPBType;
+use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\GPBUtil;
+
+/**
+ * Wrapper message for `float`.
+ * The JSON representation for `FloatValue` is JSON number.
+ *
+ * Generated from protobuf message <code>google.protobuf.FloatValue</code>
+ */
+class FloatValue extends \Google\Protobuf\Internal\Message
+{
+ /**
+ * The float value.
+ *
+ * Generated from protobuf field <code>float value = 1;</code>
+ */
+ private $value = 0.0;
+
+ public function __construct() {
+ \GPBMetadata\Google\Protobuf\Wrappers::initOnce();
+ parent::__construct();
+ }
+
+ /**
+ * The float value.
+ *
+ * Generated from protobuf field <code>float value = 1;</code>
+ * @return float
+ */
+ public function getValue()
+ {
+ return $this->value;
+ }
+
+ /**
+ * The float value.
+ *
+ * Generated from protobuf field <code>float value = 1;</code>
+ * @param float $var
+ * @return $this
+ */
+ public function setValue($var)
+ {
+ GPBUtil::checkFloat($var);
+ $this->value = $var;
+
+ return $this;
+ }
+
+}
+
diff --git a/php/src/Google/Protobuf/GPBEmpty.php b/php/src/Google/Protobuf/GPBEmpty.php
new file mode 100644
index 00000000..24a93f96
--- /dev/null
+++ b/php/src/Google/Protobuf/GPBEmpty.php
@@ -0,0 +1,31 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/empty.proto
+
+namespace Google\Protobuf;
+
+use Google\Protobuf\Internal\GPBType;
+use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\GPBUtil;
+
+/**
+ * A generic empty message that you can re-use to avoid defining duplicated
+ * empty messages in your APIs. A typical example is to use it as the request
+ * or the response type of an API method. For instance:
+ * service Foo {
+ * rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);
+ * }
+ * The JSON representation for `Empty` is empty JSON object `{}`.
+ *
+ * Generated from protobuf message <code>google.protobuf.Empty</code>
+ */
+class GPBEmpty extends \Google\Protobuf\Internal\Message
+{
+
+ public function __construct() {
+ \GPBMetadata\Google\Protobuf\GPBEmpty::initOnce();
+ parent::__construct();
+ }
+
+}
+
diff --git a/php/src/Google/Protobuf/Int32Value.php b/php/src/Google/Protobuf/Int32Value.php
new file mode 100644
index 00000000..d48aff1b
--- /dev/null
+++ b/php/src/Google/Protobuf/Int32Value.php
@@ -0,0 +1,58 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/wrappers.proto
+
+namespace Google\Protobuf;
+
+use Google\Protobuf\Internal\GPBType;
+use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\GPBUtil;
+
+/**
+ * Wrapper message for `int32`.
+ * The JSON representation for `Int32Value` is JSON number.
+ *
+ * Generated from protobuf message <code>google.protobuf.Int32Value</code>
+ */
+class Int32Value extends \Google\Protobuf\Internal\Message
+{
+ /**
+ * The int32 value.
+ *
+ * Generated from protobuf field <code>int32 value = 1;</code>
+ */
+ private $value = 0;
+
+ public function __construct() {
+ \GPBMetadata\Google\Protobuf\Wrappers::initOnce();
+ parent::__construct();
+ }
+
+ /**
+ * The int32 value.
+ *
+ * Generated from protobuf field <code>int32 value = 1;</code>
+ * @return int
+ */
+ public function getValue()
+ {
+ return $this->value;
+ }
+
+ /**
+ * The int32 value.
+ *
+ * Generated from protobuf field <code>int32 value = 1;</code>
+ * @param int $var
+ * @return $this
+ */
+ public function setValue($var)
+ {
+ GPBUtil::checkInt32($var);
+ $this->value = $var;
+
+ return $this;
+ }
+
+}
+
diff --git a/php/src/Google/Protobuf/Int64Value.php b/php/src/Google/Protobuf/Int64Value.php
new file mode 100644
index 00000000..a6fb9c5d
--- /dev/null
+++ b/php/src/Google/Protobuf/Int64Value.php
@@ -0,0 +1,58 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/wrappers.proto
+
+namespace Google\Protobuf;
+
+use Google\Protobuf\Internal\GPBType;
+use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\GPBUtil;
+
+/**
+ * Wrapper message for `int64`.
+ * The JSON representation for `Int64Value` is JSON string.
+ *
+ * Generated from protobuf message <code>google.protobuf.Int64Value</code>
+ */
+class Int64Value extends \Google\Protobuf\Internal\Message
+{
+ /**
+ * The int64 value.
+ *
+ * Generated from protobuf field <code>int64 value = 1;</code>
+ */
+ private $value = 0;
+
+ public function __construct() {
+ \GPBMetadata\Google\Protobuf\Wrappers::initOnce();
+ parent::__construct();
+ }
+
+ /**
+ * The int64 value.
+ *
+ * Generated from protobuf field <code>int64 value = 1;</code>
+ * @return int|string
+ */
+ public function getValue()
+ {
+ return $this->value;
+ }
+
+ /**
+ * The int64 value.
+ *
+ * Generated from protobuf field <code>int64 value = 1;</code>
+ * @param int|string $var
+ * @return $this
+ */
+ public function setValue($var)
+ {
+ GPBUtil::checkInt64($var);
+ $this->value = $var;
+
+ return $this;
+ }
+
+}
+
diff --git a/php/src/Google/Protobuf/Internal/InputStream.php b/php/src/Google/Protobuf/Internal/CodedInputStream.php
index 6d6c74e9..b612da5b 100644
--- a/php/src/Google/Protobuf/Internal/InputStream.php
+++ b/php/src/Google/Protobuf/Internal/CodedInputStream.php
@@ -34,25 +34,7 @@ namespace Google\Protobuf\Internal;
use Google\Protobuf\Internal\Uint64;
-function combineInt32ToInt64($high, $low)
-{
- $isNeg = $high < 0;
- if ($isNeg) {
- $high = ~$high;
- $low = ~$low;
- $low++;
- if (!$low) {
- $high++;
- }
- }
- $result = bcadd(bcmul($high, 4294967296), $low);
- if ($isNeg) {
- $result = bcsub(0, $result);
- }
- return $result;
-}
-
-class InputStream
+class CodedInputStream
{
private $buffer;
@@ -67,7 +49,6 @@ class InputStream
private $total_bytes_read;
const MAX_VARINT_BYTES = 10;
- const MAX_VARINT32_BYTES = 5;
const DEFAULT_RECURSION_LIMIT = 100;
const DEFAULT_TOTAL_BYTES_LIMIT = 33554432; // 32 << 20, 32MB
@@ -92,18 +73,23 @@ class InputStream
$this->current += $amount;
}
- private function bufferSize()
+ public function bufferSize()
{
return $this->buffer_end - $this->current;
}
- private function current()
+ public function current()
{
return $this->total_bytes_read -
($this->buffer_end - $this->current +
$this->buffer_size_after_limit);
}
+ public function substr($start, $end)
+ {
+ return substr($this->buffer, $start, $end - $start);
+ }
+
private function recomputeBufferLimits()
{
$this->buffer_end += $this->buffer_size_after_limit;
@@ -160,40 +146,62 @@ class InputStream
*/
public function readVarint64(&$var)
{
- $high = 0;
- $low = 0;
$count = 0;
- $b = 0;
-
- do {
- if ($this->current === $this->buffer_end) {
- return false;
- }
- if ($count === self::MAX_VARINT_BYTES) {
- return false;
- }
- $b = ord($this->buffer[$this->current]);
- $bits = 7 * $count;
- if ($bits >= 32) {
- $high |= (($b & 0x7F) << ($bits - 32));
- } else if ($bits > 25){
- $high_bits = $bits - 25;
- $low = ($low | (($b & 0x7F) << $bits)) & (int) 0xFFFFFFFF;
- $high = $b & ((0x1 << $high_bits) -1);
- } else {
- $low |= (($b & 0x7F) << $bits);
- }
-
- $this->advance(1);
- $count += 1;
- } while ($b & 0x80);
if (PHP_INT_SIZE == 4) {
- $var = combineInt32ToInt64($high, $low);
+ $high = 0;
+ $low = 0;
+ $b = 0;
+
+ do {
+ if ($this->current === $this->buffer_end) {
+ return false;
+ }
+ if ($count === self::MAX_VARINT_BYTES) {
+ return false;
+ }
+ $b = ord($this->buffer[$this->current]);
+ $bits = 7 * $count;
+ if ($bits >= 32) {
+ $high |= (($b & 0x7F) << ($bits - 32));
+ } else if ($bits > 25){
+ // $bits is 28 in this case.
+ $low |= (($b & 0x7F) << 28);
+ $high = ($b & 0x7F) >> 4;
+ } else {
+ $low |= (($b & 0x7F) << $bits);
+ }
+
+ $this->advance(1);
+ $count += 1;
+ } while ($b & 0x80);
+
+ $var = GPBUtil::combineInt32ToInt64($high, $low);
+ if (bccomp($var, 0) < 0) {
+ $var = bcadd($var, "18446744073709551616");
+ }
} else {
- $var = ($high & 0xFFFFFFFF) << 32 |
- ($low & 0xFFFFFFFF);
+ $result = 0;
+ $shift = 0;
+
+ do {
+ if ($this->current === $this->buffer_end) {
+ return false;
+ }
+ if ($count === self::MAX_VARINT_BYTES) {
+ return false;
+ }
+
+ $byte = ord($this->buffer[$this->current]);
+ $result |= ($byte & 0x7f) << $shift;
+ $shift += 7;
+ $this->advance(1);
+ $count += 1;
+ } while ($byte > 0x7f);
+
+ $var = $result;
}
+
return true;
}
@@ -244,7 +252,7 @@ class InputStream
}
$high = unpack('V', $data)[1];
if (PHP_INT_SIZE == 4) {
- $var = combineInt32ToInt64($high, $low);
+ $var = GPBUtil::combineInt32ToInt64($high, $low);
} else {
$var = ($high << 32) | $low;
}
@@ -309,6 +317,7 @@ class InputStream
* passed unchanged to the corresponding call to popLimit().
*
* @param integer $byte_limit
+ * @throws Exception Fail to push limit.
*/
public function pushLimit($byte_limit)
{
@@ -318,19 +327,15 @@ class InputStream
// security: byte_limit is possibly evil, so check for negative values
// and overflow.
- if ($byte_limit >= 0 && $byte_limit <= PHP_INT_MAX - $current_position) {
+ if ($byte_limit >= 0 &&
+ $byte_limit <= PHP_INT_MAX - $current_position &&
+ $byte_limit <= $this->current_limit - $current_position) {
$this->current_limit = $current_position + $byte_limit;
+ $this->recomputeBufferLimits();
} else {
- // Negative or overflow.
- $this->current_limit = PHP_INT_MAX;
+ throw new GPBDecodeException("Fail to push limit.");
}
- // We need to enforce all limits, not just the new one, so if the previous
- // limit was before the new requested limit, we continue to enforce the
- // previous limit.
- $this->current_limit = min($this->current_limit, $old_limit);
-
- $this->recomputeBufferLimits();
return $old_limit;
}
@@ -349,7 +354,7 @@ class InputStream
}
public function incrementRecursionDepthAndPushLimit(
- $byte_limit, &$old_limit, &$recursion_budget)
+ $byte_limit, &$old_limit, &$recursion_budget)
{
$old_limit = $this->pushLimit($byte_limit);
$recursion_limit = --$this->recursion_limit;
diff --git a/php/src/Google/Protobuf/Internal/OutputStream.php b/php/src/Google/Protobuf/Internal/CodedOutputStream.php
index 587ac352..f75e9c66 100644
--- a/php/src/Google/Protobuf/Internal/OutputStream.php
+++ b/php/src/Google/Protobuf/Internal/CodedOutputStream.php
@@ -32,14 +32,13 @@
namespace Google\Protobuf\Internal;
-class OutputStream
+class CodedOutputStream
{
private $buffer;
private $buffer_size;
private $current;
- const MAX_VARINT32_BYTES = 5;
const MAX_VARINT64_BYTES = 10;
public function __construct($size)
@@ -54,10 +53,10 @@ class OutputStream
return $this->buffer;
}
- public function writeVarint32($value)
+ public function writeVarint32($value, $trim)
{
- $bytes = str_repeat(chr(0), self::MAX_VARINT32_BYTES);
- $size = self::writeVarintToArray($value, $bytes, true);
+ $bytes = str_repeat(chr(0), self::MAX_VARINT64_BYTES);
+ $size = self::writeVarintToArray($value, $bytes, $trim);
return $this->writeRaw($bytes, $size);
}
@@ -84,7 +83,7 @@ class OutputStream
public function writeTag($tag)
{
- return $this->writeVarint32($tag);
+ return $this->writeVarint32($tag, true);
}
public function writeRaw($data, $size)
@@ -102,7 +101,7 @@ class OutputStream
return true;
}
- private static function writeVarintToArray($value, &$buffer, $trim = false)
+ public static function writeVarintToArray($value, &$buffer, $trim = false)
{
$current = 0;
@@ -111,14 +110,10 @@ class OutputStream
if (PHP_INT_SIZE == 4) {
GPBUtil::divideInt64ToInt32($value, $high, $low, $trim);
} else {
- if ($trim) {
- $low = $value & 0xFFFFFFFF;
- } else {
- $low = $value;
- }
+ $low = $value;
}
- while ($low >= 0x80 || $low < 0) {
+ while (($low >= 0x80 || $low < 0) || $high != 0) {
$buffer[$current] = chr($low | 0x80);
$value = ($value >> 7) & ~(0x7F << ((PHP_INT_SIZE << 3) - 7));
$carry = ($high & 0x7F) << ((PHP_INT_SIZE << 3) - 7);
diff --git a/php/src/Google/Protobuf/Internal/Descriptor.php b/php/src/Google/Protobuf/Internal/Descriptor.php
new file mode 100644
index 00000000..ee3a8bde
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/Descriptor.php
@@ -0,0 +1,208 @@
+<?php
+
+// 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.
+
+namespace Google\Protobuf\Internal;
+
+class Descriptor
+{
+ use HasPublicDescriptorTrait;
+
+ private $full_name;
+ private $field = [];
+ private $json_to_field = [];
+ private $name_to_field = [];
+ private $index_to_field = [];
+ private $nested_type = [];
+ private $enum_type = [];
+ private $klass;
+ private $options;
+ private $oneof_decl = [];
+
+ public function __construct()
+ {
+ $this->public_desc = new \Google\Protobuf\Descriptor($this);
+ }
+
+ public function addOneofDecl($oneof)
+ {
+ $this->oneof_decl[] = $oneof;
+ }
+
+ public function getOneofDecl()
+ {
+ return $this->oneof_decl;
+ }
+
+ public function setFullName($full_name)
+ {
+ $this->full_name = $full_name;
+ }
+
+ public function getFullName()
+ {
+ return $this->full_name;
+ }
+
+ public function addField($field)
+ {
+ $this->field[$field->getNumber()] = $field;
+ $this->json_to_field[$field->getJsonName()] = $field;
+ $this->name_to_field[$field->getName()] = $field;
+ $this->index_to_field[] = $field;
+ }
+
+ public function getField()
+ {
+ return $this->field;
+ }
+
+ public function addNestedType($desc)
+ {
+ $this->nested_type[] = $desc;
+ }
+
+ public function getNestedType()
+ {
+ return $this->nested_type;
+ }
+
+ public function addEnumType($desc)
+ {
+ $this->enum_type[] = $desc;
+ }
+
+ public function getEnumType()
+ {
+ return $this->enum_type;
+ }
+
+ public function getFieldByNumber($number)
+ {
+ if (!isset($this->field[$number])) {
+ return NULL;
+ } else {
+ return $this->field[$number];
+ }
+ }
+
+ public function getFieldByJsonName($json_name)
+ {
+ if (!isset($this->json_to_field[$json_name])) {
+ return NULL;
+ } else {
+ return $this->json_to_field[$json_name];
+ }
+ }
+
+ public function getFieldByName($name)
+ {
+ if (!isset($this->name_to_field[$name])) {
+ return NULL;
+ } else {
+ return $this->name_to_field[$name];
+ }
+ }
+
+ public function getFieldByIndex($index)
+ {
+ if (count($this->index_to_field) <= $index) {
+ return NULL;
+ } else {
+ return $this->index_to_field[$index];
+ }
+ }
+
+ public function setClass($klass)
+ {
+ $this->klass = $klass;
+ }
+
+ public function getClass()
+ {
+ return $this->klass;
+ }
+
+ public function setOptions($options)
+ {
+ $this->options = $options;
+ }
+
+ public function getOptions()
+ {
+ return $this->options;
+ }
+
+ public static function buildFromProto($proto, $file_proto, $containing)
+ {
+ $desc = new Descriptor();
+
+ $message_name_without_package = "";
+ $classname = "";
+ $fullname = "";
+ GPBUtil::getFullClassName(
+ $proto,
+ $containing,
+ $file_proto,
+ $message_name_without_package,
+ $classname,
+ $fullname);
+ $desc->setFullName($fullname);
+ $desc->setClass($classname);
+ $desc->setOptions($proto->getOptions());
+
+ foreach ($proto->getField() as $field_proto) {
+ $desc->addField(FieldDescriptor::buildFromProto($field_proto));
+ }
+
+ // Handle nested types.
+ foreach ($proto->getNestedType() as $nested_proto) {
+ $desc->addNestedType(Descriptor::buildFromProto(
+ $nested_proto, $file_proto, $message_name_without_package));
+ }
+
+ // Handle nested enum.
+ foreach ($proto->getEnumType() as $enum_proto) {
+ $desc->addEnumType(EnumDescriptor::buildFromProto(
+ $enum_proto, $file_proto, $message_name_without_package));
+ }
+
+ // Handle oneof fields.
+ $index = 0;
+ foreach ($proto->getOneofDecl() as $oneof_proto) {
+ $desc->addOneofDecl(
+ OneofDescriptor::buildFromProto($oneof_proto, $desc, $index));
+ $index++;
+ }
+
+ return $desc;
+ }
+}
diff --git a/php/src/Google/Protobuf/Internal/DescriptorPool.php b/php/src/Google/Protobuf/Internal/DescriptorPool.php
index 23b304ac..304c1615 100644
--- a/php/src/Google/Protobuf/Internal/DescriptorPool.php
+++ b/php/src/Google/Protobuf/Internal/DescriptorPool.php
@@ -58,20 +58,20 @@ class DescriptorPool
public function internalAddGeneratedFile($data)
{
$files = new FileDescriptorSet();
- $files->decode($data);
+ $files->mergeFromString($data);
$file = FileDescriptor::buildFromProto($files->getFile()[0]);
- foreach ($file->getMessageType() as &$desc) {
+ foreach ($file->getMessageType() as $desc) {
$this->addDescriptor($desc);
}
unset($desc);
- foreach ($file->getEnumType() as &$desc) {
+ foreach ($file->getEnumType() as $desc) {
$this->addEnumDescriptor($desc);
}
unset($desc);
- foreach ($file->getMessageType() as &$desc) {
+ foreach ($file->getMessageType() as $desc) {
$this->crossLink($desc);
}
unset($desc);
@@ -95,6 +95,9 @@ class DescriptorPool
foreach ($descriptor->getNestedType() as $nested_type) {
$this->addDescriptor($nested_type);
}
+ foreach ($descriptor->getEnumType() as $enum_type) {
+ $this->addEnumDescriptor($enum_type);
+ }
}
public function addEnumDescriptor($descriptor)
@@ -106,18 +109,30 @@ class DescriptorPool
public function getDescriptorByClassName($klass)
{
- return $this->class_to_desc[$klass];
+ if (isset($this->class_to_desc[$klass])) {
+ return $this->class_to_desc[$klass];
+ } else {
+ return null;
+ }
}
public function getEnumDescriptorByClassName($klass)
{
- return $this->class_to_enum_desc[$klass];
+ if (isset($this->class_to_enum_desc[$klass])) {
+ return $this->class_to_enum_desc[$klass];
+ } else {
+ return null;
+ }
}
public function getDescriptorByProtoName($proto)
{
- $klass = $this->proto_to_class[$proto];
- return $this->class_to_desc[$klass];
+ if (isset($this->proto_to_class[$proto])) {
+ $klass = $this->proto_to_class[$proto];
+ return $this->class_to_desc[$klass];
+ } else {
+ return null;
+ }
}
public function getEnumDescriptorByProtoName($proto)
@@ -126,9 +141,9 @@ class DescriptorPool
return $this->class_to_enum_desc[$klass];
}
- private function crossLink(&$desc)
+ private function crossLink(Descriptor $desc)
{
- foreach ($desc->getField() as &$field) {
+ foreach ($desc->getField() as $field) {
switch ($field->getType()) {
case GPBType::MESSAGE:
$proto = $field->getMessageType();
@@ -146,7 +161,7 @@ class DescriptorPool
}
unset($field);
- foreach ($desc->getNestedType() as &$nested_type) {
+ foreach ($desc->getNestedType() as $nested_type) {
$this->crossLink($nested_type);
}
unset($nested_type);
@@ -154,7 +169,7 @@ class DescriptorPool
public function finish()
{
- foreach ($this->class_to_desc as $klass => &$desc) {
+ foreach ($this->class_to_desc as $klass => $desc) {
$this->crossLink($desc);
}
unset($desc);
diff --git a/php/src/Google/Protobuf/Internal/DescriptorProto.php b/php/src/Google/Protobuf/Internal/DescriptorProto.php
index f076f6be..1d6959b7 100644
--- a/php/src/Google/Protobuf/Internal/DescriptorProto.php
+++ b/php/src/Google/Protobuf/Internal/DescriptorProto.php
@@ -8,70 +8,65 @@ use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\GPBWire;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\InputStream;
-
use Google\Protobuf\Internal\GPBUtil;
/**
- * <pre>
* Describes a message type.
- * </pre>
*
- * Protobuf type <code>google.protobuf.DescriptorProto</code>
+ * Generated from protobuf message <code>google.protobuf.DescriptorProto</code>
*/
class DescriptorProto extends \Google\Protobuf\Internal\Message
{
/**
- * <code>optional string name = 1;</code>
+ * Generated from protobuf field <code>optional string name = 1;</code>
*/
private $name = '';
private $has_name = false;
/**
- * <code>repeated .google.protobuf.FieldDescriptorProto field = 2;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.FieldDescriptorProto field = 2;</code>
*/
private $field;
private $has_field = false;
/**
- * <code>repeated .google.protobuf.FieldDescriptorProto extension = 6;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.FieldDescriptorProto extension = 6;</code>
*/
private $extension;
private $has_extension = false;
/**
- * <code>repeated .google.protobuf.DescriptorProto nested_type = 3;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.DescriptorProto nested_type = 3;</code>
*/
private $nested_type;
private $has_nested_type = false;
/**
- * <code>repeated .google.protobuf.EnumDescriptorProto enum_type = 4;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.EnumDescriptorProto enum_type = 4;</code>
*/
private $enum_type;
private $has_enum_type = false;
/**
- * <code>repeated .google.protobuf.DescriptorProto.ExtensionRange extension_range = 5;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.DescriptorProto.ExtensionRange extension_range = 5;</code>
*/
private $extension_range;
private $has_extension_range = false;
/**
- * <code>repeated .google.protobuf.OneofDescriptorProto oneof_decl = 8;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.OneofDescriptorProto oneof_decl = 8;</code>
*/
private $oneof_decl;
private $has_oneof_decl = false;
/**
- * <code>optional .google.protobuf.MessageOptions options = 7;</code>
+ * Generated from protobuf field <code>optional .google.protobuf.MessageOptions options = 7;</code>
*/
private $options = null;
private $has_options = false;
/**
- * <code>repeated .google.protobuf.DescriptorProto.ReservedRange reserved_range = 9;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.DescriptorProto.ReservedRange reserved_range = 9;</code>
*/
private $reserved_range;
private $has_reserved_range = false;
/**
- * <pre>
* Reserved field names, which may not be used by fields in the same message.
* A given name may only be reserved once.
- * </pre>
*
- * <code>repeated string reserved_name = 10;</code>
+ * Generated from protobuf field <code>repeated string reserved_name = 10;</code>
*/
private $reserved_name;
private $has_reserved_name = false;
@@ -82,7 +77,8 @@ class DescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional string name = 1;</code>
+ * Generated from protobuf field <code>optional string name = 1;</code>
+ * @return string
*/
public function getName()
{
@@ -90,13 +86,17 @@ class DescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional string name = 1;</code>
+ * Generated from protobuf field <code>optional string name = 1;</code>
+ * @param string $var
+ * @return $this
*/
public function setName($var)
{
GPBUtil::checkString($var, True);
$this->name = $var;
$this->has_name = true;
+
+ return $this;
}
public function hasName()
@@ -105,7 +105,8 @@ class DescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>repeated .google.protobuf.FieldDescriptorProto field = 2;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.FieldDescriptorProto field = 2;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
*/
public function getField()
{
@@ -113,13 +114,17 @@ class DescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>repeated .google.protobuf.FieldDescriptorProto field = 2;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.FieldDescriptorProto field = 2;</code>
+ * @param \Google\Protobuf\Internal\FieldDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
*/
- public function setField(&$var)
+ public function setField($var)
{
- GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\FieldDescriptorProto::class);
- $this->field = $var;
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\FieldDescriptorProto::class);
+ $this->field = $arr;
$this->has_field = true;
+
+ return $this;
}
public function hasField()
@@ -128,7 +133,8 @@ class DescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>repeated .google.protobuf.FieldDescriptorProto extension = 6;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.FieldDescriptorProto extension = 6;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
*/
public function getExtension()
{
@@ -136,13 +142,17 @@ class DescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>repeated .google.protobuf.FieldDescriptorProto extension = 6;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.FieldDescriptorProto extension = 6;</code>
+ * @param \Google\Protobuf\Internal\FieldDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
*/
- public function setExtension(&$var)
+ public function setExtension($var)
{
- GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\FieldDescriptorProto::class);
- $this->extension = $var;
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\FieldDescriptorProto::class);
+ $this->extension = $arr;
$this->has_extension = true;
+
+ return $this;
}
public function hasExtension()
@@ -151,7 +161,8 @@ class DescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>repeated .google.protobuf.DescriptorProto nested_type = 3;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.DescriptorProto nested_type = 3;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
*/
public function getNestedType()
{
@@ -159,13 +170,17 @@ class DescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>repeated .google.protobuf.DescriptorProto nested_type = 3;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.DescriptorProto nested_type = 3;</code>
+ * @param \Google\Protobuf\Internal\DescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
*/
- public function setNestedType(&$var)
+ public function setNestedType($var)
{
- GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\DescriptorProto::class);
- $this->nested_type = $var;
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\DescriptorProto::class);
+ $this->nested_type = $arr;
$this->has_nested_type = true;
+
+ return $this;
}
public function hasNestedType()
@@ -174,7 +189,8 @@ class DescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>repeated .google.protobuf.EnumDescriptorProto enum_type = 4;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.EnumDescriptorProto enum_type = 4;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
*/
public function getEnumType()
{
@@ -182,13 +198,17 @@ class DescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>repeated .google.protobuf.EnumDescriptorProto enum_type = 4;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.EnumDescriptorProto enum_type = 4;</code>
+ * @param \Google\Protobuf\Internal\EnumDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
*/
- public function setEnumType(&$var)
+ public function setEnumType($var)
{
- GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\EnumDescriptorProto::class);
- $this->enum_type = $var;
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\EnumDescriptorProto::class);
+ $this->enum_type = $arr;
$this->has_enum_type = true;
+
+ return $this;
}
public function hasEnumType()
@@ -197,7 +217,8 @@ class DescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>repeated .google.protobuf.DescriptorProto.ExtensionRange extension_range = 5;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.DescriptorProto.ExtensionRange extension_range = 5;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
*/
public function getExtensionRange()
{
@@ -205,13 +226,17 @@ class DescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>repeated .google.protobuf.DescriptorProto.ExtensionRange extension_range = 5;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.DescriptorProto.ExtensionRange extension_range = 5;</code>
+ * @param \Google\Protobuf\Internal\DescriptorProto_ExtensionRange[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
*/
- public function setExtensionRange(&$var)
+ public function setExtensionRange($var)
{
- GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\DescriptorProto_ExtensionRange::class);
- $this->extension_range = $var;
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\DescriptorProto_ExtensionRange::class);
+ $this->extension_range = $arr;
$this->has_extension_range = true;
+
+ return $this;
}
public function hasExtensionRange()
@@ -220,7 +245,8 @@ class DescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>repeated .google.protobuf.OneofDescriptorProto oneof_decl = 8;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.OneofDescriptorProto oneof_decl = 8;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
*/
public function getOneofDecl()
{
@@ -228,13 +254,17 @@ class DescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>repeated .google.protobuf.OneofDescriptorProto oneof_decl = 8;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.OneofDescriptorProto oneof_decl = 8;</code>
+ * @param \Google\Protobuf\Internal\OneofDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
*/
- public function setOneofDecl(&$var)
+ public function setOneofDecl($var)
{
- GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\OneofDescriptorProto::class);
- $this->oneof_decl = $var;
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\OneofDescriptorProto::class);
+ $this->oneof_decl = $arr;
$this->has_oneof_decl = true;
+
+ return $this;
}
public function hasOneofDecl()
@@ -243,7 +273,8 @@ class DescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional .google.protobuf.MessageOptions options = 7;</code>
+ * Generated from protobuf field <code>optional .google.protobuf.MessageOptions options = 7;</code>
+ * @return \Google\Protobuf\Internal\MessageOptions
*/
public function getOptions()
{
@@ -251,13 +282,17 @@ class DescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional .google.protobuf.MessageOptions options = 7;</code>
+ * Generated from protobuf field <code>optional .google.protobuf.MessageOptions options = 7;</code>
+ * @param \Google\Protobuf\Internal\MessageOptions $var
+ * @return $this
*/
- public function setOptions(&$var)
+ public function setOptions($var)
{
GPBUtil::checkMessage($var, \Google\Protobuf\Internal\MessageOptions::class);
$this->options = $var;
$this->has_options = true;
+
+ return $this;
}
public function hasOptions()
@@ -266,7 +301,8 @@ class DescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>repeated .google.protobuf.DescriptorProto.ReservedRange reserved_range = 9;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.DescriptorProto.ReservedRange reserved_range = 9;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
*/
public function getReservedRange()
{
@@ -274,13 +310,17 @@ class DescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>repeated .google.protobuf.DescriptorProto.ReservedRange reserved_range = 9;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.DescriptorProto.ReservedRange reserved_range = 9;</code>
+ * @param \Google\Protobuf\Internal\DescriptorProto_ReservedRange[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
*/
- public function setReservedRange(&$var)
+ public function setReservedRange($var)
{
- GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\DescriptorProto_ReservedRange::class);
- $this->reserved_range = $var;
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\DescriptorProto_ReservedRange::class);
+ $this->reserved_range = $arr;
$this->has_reserved_range = true;
+
+ return $this;
}
public function hasReservedRange()
@@ -289,12 +329,11 @@ class DescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Reserved field names, which may not be used by fields in the same message.
* A given name may only be reserved once.
- * </pre>
*
- * <code>repeated string reserved_name = 10;</code>
+ * Generated from protobuf field <code>repeated string reserved_name = 10;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
*/
public function getReservedName()
{
@@ -302,18 +341,20 @@ class DescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Reserved field names, which may not be used by fields in the same message.
* A given name may only be reserved once.
- * </pre>
*
- * <code>repeated string reserved_name = 10;</code>
+ * Generated from protobuf field <code>repeated string reserved_name = 10;</code>
+ * @param string[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
*/
- public function setReservedName(&$var)
+ public function setReservedName($var)
{
- GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::STRING);
- $this->reserved_name = $var;
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::STRING);
+ $this->reserved_name = $arr;
$this->has_reserved_name = true;
+
+ return $this;
}
public function hasReservedName()
diff --git a/php/src/Google/Protobuf/Internal/DescriptorProto_ExtensionRange.php b/php/src/Google/Protobuf/Internal/DescriptorProto_ExtensionRange.php
index 738a1738..1d455995 100644
--- a/php/src/Google/Protobuf/Internal/DescriptorProto_ExtensionRange.php
+++ b/php/src/Google/Protobuf/Internal/DescriptorProto_ExtensionRange.php
@@ -8,24 +8,28 @@ use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\GPBWire;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\InputStream;
-
use Google\Protobuf\Internal\GPBUtil;
/**
- * Protobuf type <code>google.protobuf.DescriptorProto.ExtensionRange</code>
+ * Generated from protobuf message <code>google.protobuf.DescriptorProto.ExtensionRange</code>
*/
class DescriptorProto_ExtensionRange extends \Google\Protobuf\Internal\Message
{
/**
- * <code>optional int32 start = 1;</code>
+ * Generated from protobuf field <code>optional int32 start = 1;</code>
*/
private $start = 0;
private $has_start = false;
/**
- * <code>optional int32 end = 2;</code>
+ * Generated from protobuf field <code>optional int32 end = 2;</code>
*/
private $end = 0;
private $has_end = false;
+ /**
+ * Generated from protobuf field <code>optional .google.protobuf.ExtensionRangeOptions options = 3;</code>
+ */
+ private $options = null;
+ private $has_options = false;
public function __construct() {
\GPBMetadata\Google\Protobuf\Internal\Descriptor::initOnce();
@@ -33,7 +37,8 @@ class DescriptorProto_ExtensionRange extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional int32 start = 1;</code>
+ * Generated from protobuf field <code>optional int32 start = 1;</code>
+ * @return int
*/
public function getStart()
{
@@ -41,13 +46,17 @@ class DescriptorProto_ExtensionRange extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional int32 start = 1;</code>
+ * Generated from protobuf field <code>optional int32 start = 1;</code>
+ * @param int $var
+ * @return $this
*/
public function setStart($var)
{
GPBUtil::checkInt32($var);
$this->start = $var;
$this->has_start = true;
+
+ return $this;
}
public function hasStart()
@@ -56,7 +65,8 @@ class DescriptorProto_ExtensionRange extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional int32 end = 2;</code>
+ * Generated from protobuf field <code>optional int32 end = 2;</code>
+ * @return int
*/
public function getEnd()
{
@@ -64,13 +74,17 @@ class DescriptorProto_ExtensionRange extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional int32 end = 2;</code>
+ * Generated from protobuf field <code>optional int32 end = 2;</code>
+ * @param int $var
+ * @return $this
*/
public function setEnd($var)
{
GPBUtil::checkInt32($var);
$this->end = $var;
$this->has_end = true;
+
+ return $this;
}
public function hasEnd()
@@ -78,5 +92,33 @@ class DescriptorProto_ExtensionRange extends \Google\Protobuf\Internal\Message
return $this->has_end;
}
+ /**
+ * Generated from protobuf field <code>optional .google.protobuf.ExtensionRangeOptions options = 3;</code>
+ * @return \Google\Protobuf\Internal\ExtensionRangeOptions
+ */
+ public function getOptions()
+ {
+ return $this->options;
+ }
+
+ /**
+ * Generated from protobuf field <code>optional .google.protobuf.ExtensionRangeOptions options = 3;</code>
+ * @param \Google\Protobuf\Internal\ExtensionRangeOptions $var
+ * @return $this
+ */
+ public function setOptions($var)
+ {
+ GPBUtil::checkMessage($var, \Google\Protobuf\Internal\ExtensionRangeOptions::class);
+ $this->options = $var;
+ $this->has_options = true;
+
+ return $this;
+ }
+
+ public function hasOptions()
+ {
+ return $this->has_options;
+ }
+
}
diff --git a/php/src/Google/Protobuf/Internal/DescriptorProto_ReservedRange.php b/php/src/Google/Protobuf/Internal/DescriptorProto_ReservedRange.php
index be36b8aa..b1022d61 100644
--- a/php/src/Google/Protobuf/Internal/DescriptorProto_ReservedRange.php
+++ b/php/src/Google/Protobuf/Internal/DescriptorProto_ReservedRange.php
@@ -8,35 +8,28 @@ use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\GPBWire;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\InputStream;
-
use Google\Protobuf\Internal\GPBUtil;
/**
- * <pre>
* Range of reserved tag numbers. Reserved tag numbers may not be used by
* fields or extension ranges in the same message. Reserved ranges may
* not overlap.
- * </pre>
*
- * Protobuf type <code>google.protobuf.DescriptorProto.ReservedRange</code>
+ * Generated from protobuf message <code>google.protobuf.DescriptorProto.ReservedRange</code>
*/
class DescriptorProto_ReservedRange extends \Google\Protobuf\Internal\Message
{
/**
- * <pre>
* Inclusive.
- * </pre>
*
- * <code>optional int32 start = 1;</code>
+ * Generated from protobuf field <code>optional int32 start = 1;</code>
*/
private $start = 0;
private $has_start = false;
/**
- * <pre>
* Exclusive.
- * </pre>
*
- * <code>optional int32 end = 2;</code>
+ * Generated from protobuf field <code>optional int32 end = 2;</code>
*/
private $end = 0;
private $has_end = false;
@@ -47,11 +40,10 @@ class DescriptorProto_ReservedRange extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Inclusive.
- * </pre>
*
- * <code>optional int32 start = 1;</code>
+ * Generated from protobuf field <code>optional int32 start = 1;</code>
+ * @return int
*/
public function getStart()
{
@@ -59,17 +51,19 @@ class DescriptorProto_ReservedRange extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Inclusive.
- * </pre>
*
- * <code>optional int32 start = 1;</code>
+ * Generated from protobuf field <code>optional int32 start = 1;</code>
+ * @param int $var
+ * @return $this
*/
public function setStart($var)
{
GPBUtil::checkInt32($var);
$this->start = $var;
$this->has_start = true;
+
+ return $this;
}
public function hasStart()
@@ -78,11 +72,10 @@ class DescriptorProto_ReservedRange extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Exclusive.
- * </pre>
*
- * <code>optional int32 end = 2;</code>
+ * Generated from protobuf field <code>optional int32 end = 2;</code>
+ * @return int
*/
public function getEnd()
{
@@ -90,17 +83,19 @@ class DescriptorProto_ReservedRange extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Exclusive.
- * </pre>
*
- * <code>optional int32 end = 2;</code>
+ * Generated from protobuf field <code>optional int32 end = 2;</code>
+ * @param int $var
+ * @return $this
*/
public function setEnd($var)
{
GPBUtil::checkInt32($var);
$this->end = $var;
$this->has_end = true;
+
+ return $this;
}
public function hasEnd()
diff --git a/php/src/Google/Protobuf/Internal/EnumBuilderContext.php b/php/src/Google/Protobuf/Internal/EnumBuilderContext.php
index c1dac24d..08397284 100644
--- a/php/src/Google/Protobuf/Internal/EnumBuilderContext.php
+++ b/php/src/Google/Protobuf/Internal/EnumBuilderContext.php
@@ -33,7 +33,7 @@
namespace Google\Protobuf\Internal;
use Google\Protobuf\Internal\EnumDescriptor;
-use Google\Protobuf\Internal\EnumValueDescriptor;
+use Google\Protobuf\EnumValueDescriptor;
class EnumBuilderContext
{
@@ -51,7 +51,7 @@ class EnumBuilderContext
public function value($name, $number)
{
- $value = new EnumValueDescriptor();
+ $value = new EnumValueDescriptor($name, $number);
$this->descriptor->addValue($number, $value);
return $this;
}
diff --git a/php/src/Google/Protobuf/Internal/EnumDescriptor.php b/php/src/Google/Protobuf/Internal/EnumDescriptor.php
new file mode 100644
index 00000000..01649fec
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/EnumDescriptor.php
@@ -0,0 +1,92 @@
+<?php
+
+namespace Google\Protobuf\Internal;
+
+use Google\Protobuf\EnumValueDescriptor;
+
+class EnumDescriptor
+{
+ use HasPublicDescriptorTrait;
+
+ private $klass;
+ private $full_name;
+ private $value;
+ private $name_to_value;
+ private $value_descriptor = [];
+
+ public function __construct()
+ {
+ $this->public_desc = new \Google\Protobuf\EnumDescriptor($this);
+ }
+
+ public function setFullName($full_name)
+ {
+ $this->full_name = $full_name;
+ }
+
+ public function getFullName()
+ {
+ return $this->full_name;
+ }
+
+ public function addValue($number, $value)
+ {
+ $this->value[$number] = $value;
+ $this->name_to_value[$value->getName()] = $value;
+ $this->value_descriptor[] = new EnumValueDescriptor($value->getName(), $number);
+ }
+
+ public function getValueByNumber($number)
+ {
+ return $this->value[$number];
+ }
+
+ public function getValueByName($name)
+ {
+ return $this->name_to_value[$name];
+ }
+
+ public function getValueDescriptorByIndex($index)
+ {
+ return $this->value_descriptor[$index];
+ }
+
+ public function getValueCount()
+ {
+ return count($this->value);
+ }
+
+ public function setClass($klass)
+ {
+ $this->klass = $klass;
+ }
+
+ public function getClass()
+ {
+ return $this->klass;
+ }
+
+ public static function buildFromProto($proto, $file_proto, $containing)
+ {
+ $desc = new EnumDescriptor();
+
+ $enum_name_without_package = "";
+ $classname = "";
+ $fullname = "";
+ GPBUtil::getFullClassName(
+ $proto,
+ $containing,
+ $file_proto,
+ $enum_name_without_package,
+ $classname,
+ $fullname);
+ $desc->setFullName($fullname);
+ $desc->setClass($classname);
+ $values = $proto->getValue();
+ foreach ($values as $value) {
+ $desc->addValue($value->getNumber(), $value);
+ }
+
+ return $desc;
+ }
+}
diff --git a/php/src/Google/Protobuf/Internal/EnumDescriptorProto.php b/php/src/Google/Protobuf/Internal/EnumDescriptorProto.php
index 9c5f245b..930f26ef 100644
--- a/php/src/Google/Protobuf/Internal/EnumDescriptorProto.php
+++ b/php/src/Google/Protobuf/Internal/EnumDescriptorProto.php
@@ -8,33 +8,47 @@ use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\GPBWire;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\InputStream;
-
use Google\Protobuf\Internal\GPBUtil;
/**
- * <pre>
* Describes an enum type.
- * </pre>
*
- * Protobuf type <code>google.protobuf.EnumDescriptorProto</code>
+ * Generated from protobuf message <code>google.protobuf.EnumDescriptorProto</code>
*/
class EnumDescriptorProto extends \Google\Protobuf\Internal\Message
{
/**
- * <code>optional string name = 1;</code>
+ * Generated from protobuf field <code>optional string name = 1;</code>
*/
private $name = '';
private $has_name = false;
/**
- * <code>repeated .google.protobuf.EnumValueDescriptorProto value = 2;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.EnumValueDescriptorProto value = 2;</code>
*/
private $value;
private $has_value = false;
/**
- * <code>optional .google.protobuf.EnumOptions options = 3;</code>
+ * Generated from protobuf field <code>optional .google.protobuf.EnumOptions options = 3;</code>
*/
private $options = null;
private $has_options = false;
+ /**
+ * Range of reserved numeric values. Reserved numeric values may not be used
+ * by enum values in the same enum declaration. Reserved ranges may not
+ * overlap.
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.EnumDescriptorProto.EnumReservedRange reserved_range = 4;</code>
+ */
+ private $reserved_range;
+ private $has_reserved_range = false;
+ /**
+ * Reserved enum value names, which may not be reused. A given name may only
+ * be reserved once.
+ *
+ * Generated from protobuf field <code>repeated string reserved_name = 5;</code>
+ */
+ private $reserved_name;
+ private $has_reserved_name = false;
public function __construct() {
\GPBMetadata\Google\Protobuf\Internal\Descriptor::initOnce();
@@ -42,7 +56,8 @@ class EnumDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional string name = 1;</code>
+ * Generated from protobuf field <code>optional string name = 1;</code>
+ * @return string
*/
public function getName()
{
@@ -50,13 +65,17 @@ class EnumDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional string name = 1;</code>
+ * Generated from protobuf field <code>optional string name = 1;</code>
+ * @param string $var
+ * @return $this
*/
public function setName($var)
{
GPBUtil::checkString($var, True);
$this->name = $var;
$this->has_name = true;
+
+ return $this;
}
public function hasName()
@@ -65,7 +84,8 @@ class EnumDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>repeated .google.protobuf.EnumValueDescriptorProto value = 2;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.EnumValueDescriptorProto value = 2;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
*/
public function getValue()
{
@@ -73,13 +93,17 @@ class EnumDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>repeated .google.protobuf.EnumValueDescriptorProto value = 2;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.EnumValueDescriptorProto value = 2;</code>
+ * @param \Google\Protobuf\Internal\EnumValueDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
*/
- public function setValue(&$var)
+ public function setValue($var)
{
- GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\EnumValueDescriptorProto::class);
- $this->value = $var;
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\EnumValueDescriptorProto::class);
+ $this->value = $arr;
$this->has_value = true;
+
+ return $this;
}
public function hasValue()
@@ -88,7 +112,8 @@ class EnumDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional .google.protobuf.EnumOptions options = 3;</code>
+ * Generated from protobuf field <code>optional .google.protobuf.EnumOptions options = 3;</code>
+ * @return \Google\Protobuf\Internal\EnumOptions
*/
public function getOptions()
{
@@ -96,13 +121,17 @@ class EnumDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional .google.protobuf.EnumOptions options = 3;</code>
+ * Generated from protobuf field <code>optional .google.protobuf.EnumOptions options = 3;</code>
+ * @param \Google\Protobuf\Internal\EnumOptions $var
+ * @return $this
*/
- public function setOptions(&$var)
+ public function setOptions($var)
{
GPBUtil::checkMessage($var, \Google\Protobuf\Internal\EnumOptions::class);
$this->options = $var;
$this->has_options = true;
+
+ return $this;
}
public function hasOptions()
@@ -110,5 +139,75 @@ class EnumDescriptorProto extends \Google\Protobuf\Internal\Message
return $this->has_options;
}
+ /**
+ * Range of reserved numeric values. Reserved numeric values may not be used
+ * by enum values in the same enum declaration. Reserved ranges may not
+ * overlap.
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.EnumDescriptorProto.EnumReservedRange reserved_range = 4;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
+ */
+ public function getReservedRange()
+ {
+ return $this->reserved_range;
+ }
+
+ /**
+ * Range of reserved numeric values. Reserved numeric values may not be used
+ * by enum values in the same enum declaration. Reserved ranges may not
+ * overlap.
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.EnumDescriptorProto.EnumReservedRange reserved_range = 4;</code>
+ * @param \Google\Protobuf\Internal\EnumDescriptorProto_EnumReservedRange[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
+ */
+ public function setReservedRange($var)
+ {
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\EnumDescriptorProto_EnumReservedRange::class);
+ $this->reserved_range = $arr;
+ $this->has_reserved_range = true;
+
+ return $this;
+ }
+
+ public function hasReservedRange()
+ {
+ return $this->has_reserved_range;
+ }
+
+ /**
+ * Reserved enum value names, which may not be reused. A given name may only
+ * be reserved once.
+ *
+ * Generated from protobuf field <code>repeated string reserved_name = 5;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
+ */
+ public function getReservedName()
+ {
+ return $this->reserved_name;
+ }
+
+ /**
+ * Reserved enum value names, which may not be reused. A given name may only
+ * be reserved once.
+ *
+ * Generated from protobuf field <code>repeated string reserved_name = 5;</code>
+ * @param string[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
+ */
+ public function setReservedName($var)
+ {
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::STRING);
+ $this->reserved_name = $arr;
+ $this->has_reserved_name = true;
+
+ return $this;
+ }
+
+ public function hasReservedName()
+ {
+ return $this->has_reserved_name;
+ }
+
}
diff --git a/php/src/Google/Protobuf/Internal/EnumDescriptorProto_EnumReservedRange.php b/php/src/Google/Protobuf/Internal/EnumDescriptorProto_EnumReservedRange.php
new file mode 100644
index 00000000..6b2449fa
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/EnumDescriptorProto_EnumReservedRange.php
@@ -0,0 +1,109 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/descriptor.proto
+
+namespace Google\Protobuf\Internal;
+
+use Google\Protobuf\Internal\GPBType;
+use Google\Protobuf\Internal\GPBWire;
+use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\InputStream;
+use Google\Protobuf\Internal\GPBUtil;
+
+/**
+ * Range of reserved numeric values. Reserved values may not be used by
+ * entries in the same enum. Reserved ranges may not overlap.
+ * Note that this is distinct from DescriptorProto.ReservedRange in that it
+ * is inclusive such that it can appropriately represent the entire int32
+ * domain.
+ *
+ * Generated from protobuf message <code>google.protobuf.EnumDescriptorProto.EnumReservedRange</code>
+ */
+class EnumDescriptorProto_EnumReservedRange extends \Google\Protobuf\Internal\Message
+{
+ /**
+ * Inclusive.
+ *
+ * Generated from protobuf field <code>optional int32 start = 1;</code>
+ */
+ private $start = 0;
+ private $has_start = false;
+ /**
+ * Inclusive.
+ *
+ * Generated from protobuf field <code>optional int32 end = 2;</code>
+ */
+ private $end = 0;
+ private $has_end = false;
+
+ public function __construct() {
+ \GPBMetadata\Google\Protobuf\Internal\Descriptor::initOnce();
+ parent::__construct();
+ }
+
+ /**
+ * Inclusive.
+ *
+ * Generated from protobuf field <code>optional int32 start = 1;</code>
+ * @return int
+ */
+ public function getStart()
+ {
+ return $this->start;
+ }
+
+ /**
+ * Inclusive.
+ *
+ * Generated from protobuf field <code>optional int32 start = 1;</code>
+ * @param int $var
+ * @return $this
+ */
+ public function setStart($var)
+ {
+ GPBUtil::checkInt32($var);
+ $this->start = $var;
+ $this->has_start = true;
+
+ return $this;
+ }
+
+ public function hasStart()
+ {
+ return $this->has_start;
+ }
+
+ /**
+ * Inclusive.
+ *
+ * Generated from protobuf field <code>optional int32 end = 2;</code>
+ * @return int
+ */
+ public function getEnd()
+ {
+ return $this->end;
+ }
+
+ /**
+ * Inclusive.
+ *
+ * Generated from protobuf field <code>optional int32 end = 2;</code>
+ * @param int $var
+ * @return $this
+ */
+ public function setEnd($var)
+ {
+ GPBUtil::checkInt32($var);
+ $this->end = $var;
+ $this->has_end = true;
+
+ return $this;
+ }
+
+ public function hasEnd()
+ {
+ return $this->has_end;
+ }
+
+}
+
diff --git a/php/src/Google/Protobuf/Internal/EnumOptions.php b/php/src/Google/Protobuf/Internal/EnumOptions.php
index a9c4e0d7..3f598a41 100644
--- a/php/src/Google/Protobuf/Internal/EnumOptions.php
+++ b/php/src/Google/Protobuf/Internal/EnumOptions.php
@@ -8,42 +8,35 @@ use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\GPBWire;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\InputStream;
-
use Google\Protobuf\Internal\GPBUtil;
/**
- * Protobuf type <code>google.protobuf.EnumOptions</code>
+ * Generated from protobuf message <code>google.protobuf.EnumOptions</code>
*/
class EnumOptions extends \Google\Protobuf\Internal\Message
{
/**
- * <pre>
* Set this option to true to allow mapping different tag names to the same
* value.
- * </pre>
*
- * <code>optional bool allow_alias = 2;</code>
+ * Generated from protobuf field <code>optional bool allow_alias = 2;</code>
*/
private $allow_alias = false;
private $has_allow_alias = false;
/**
- * <pre>
* Is this enum deprecated?
* Depending on the target platform, this can emit Deprecated annotations
* for the enum, or it will be completely ignored; in the very least, this
* is a formalization for deprecating enums.
- * </pre>
*
- * <code>optional bool deprecated = 3 [default = false];</code>
+ * Generated from protobuf field <code>optional bool deprecated = 3 [default = false];</code>
*/
private $deprecated = false;
private $has_deprecated = false;
/**
- * <pre>
* The parser stores options it doesn't recognize here. See above.
- * </pre>
*
- * <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
*/
private $uninterpreted_option;
private $has_uninterpreted_option = false;
@@ -54,12 +47,11 @@ class EnumOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Set this option to true to allow mapping different tag names to the same
* value.
- * </pre>
*
- * <code>optional bool allow_alias = 2;</code>
+ * Generated from protobuf field <code>optional bool allow_alias = 2;</code>
+ * @return bool
*/
public function getAllowAlias()
{
@@ -67,18 +59,20 @@ class EnumOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Set this option to true to allow mapping different tag names to the same
* value.
- * </pre>
*
- * <code>optional bool allow_alias = 2;</code>
+ * Generated from protobuf field <code>optional bool allow_alias = 2;</code>
+ * @param bool $var
+ * @return $this
*/
public function setAllowAlias($var)
{
GPBUtil::checkBool($var);
$this->allow_alias = $var;
$this->has_allow_alias = true;
+
+ return $this;
}
public function hasAllowAlias()
@@ -87,14 +81,13 @@ class EnumOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Is this enum deprecated?
* Depending on the target platform, this can emit Deprecated annotations
* for the enum, or it will be completely ignored; in the very least, this
* is a formalization for deprecating enums.
- * </pre>
*
- * <code>optional bool deprecated = 3 [default = false];</code>
+ * Generated from protobuf field <code>optional bool deprecated = 3 [default = false];</code>
+ * @return bool
*/
public function getDeprecated()
{
@@ -102,20 +95,22 @@ class EnumOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Is this enum deprecated?
* Depending on the target platform, this can emit Deprecated annotations
* for the enum, or it will be completely ignored; in the very least, this
* is a formalization for deprecating enums.
- * </pre>
*
- * <code>optional bool deprecated = 3 [default = false];</code>
+ * Generated from protobuf field <code>optional bool deprecated = 3 [default = false];</code>
+ * @param bool $var
+ * @return $this
*/
public function setDeprecated($var)
{
GPBUtil::checkBool($var);
$this->deprecated = $var;
$this->has_deprecated = true;
+
+ return $this;
}
public function hasDeprecated()
@@ -124,11 +119,10 @@ class EnumOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* The parser stores options it doesn't recognize here. See above.
- * </pre>
*
- * <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
*/
public function getUninterpretedOption()
{
@@ -136,17 +130,19 @@ class EnumOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* The parser stores options it doesn't recognize here. See above.
- * </pre>
*
- * <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * @param \Google\Protobuf\Internal\UninterpretedOption[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
*/
- public function setUninterpretedOption(&$var)
+ public function setUninterpretedOption($var)
{
- GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\UninterpretedOption::class);
- $this->uninterpreted_option = $var;
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\UninterpretedOption::class);
+ $this->uninterpreted_option = $arr;
$this->has_uninterpreted_option = true;
+
+ return $this;
}
public function hasUninterpretedOption()
diff --git a/php/src/Google/Protobuf/Internal/EnumValueDescriptorProto.php b/php/src/Google/Protobuf/Internal/EnumValueDescriptorProto.php
index 94dc36ec..e363220f 100644
--- a/php/src/Google/Protobuf/Internal/EnumValueDescriptorProto.php
+++ b/php/src/Google/Protobuf/Internal/EnumValueDescriptorProto.php
@@ -8,30 +8,27 @@ use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\GPBWire;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\InputStream;
-
use Google\Protobuf\Internal\GPBUtil;
/**
- * <pre>
* Describes a value within an enum.
- * </pre>
*
- * Protobuf type <code>google.protobuf.EnumValueDescriptorProto</code>
+ * Generated from protobuf message <code>google.protobuf.EnumValueDescriptorProto</code>
*/
class EnumValueDescriptorProto extends \Google\Protobuf\Internal\Message
{
/**
- * <code>optional string name = 1;</code>
+ * Generated from protobuf field <code>optional string name = 1;</code>
*/
private $name = '';
private $has_name = false;
/**
- * <code>optional int32 number = 2;</code>
+ * Generated from protobuf field <code>optional int32 number = 2;</code>
*/
private $number = 0;
private $has_number = false;
/**
- * <code>optional .google.protobuf.EnumValueOptions options = 3;</code>
+ * Generated from protobuf field <code>optional .google.protobuf.EnumValueOptions options = 3;</code>
*/
private $options = null;
private $has_options = false;
@@ -42,7 +39,8 @@ class EnumValueDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional string name = 1;</code>
+ * Generated from protobuf field <code>optional string name = 1;</code>
+ * @return string
*/
public function getName()
{
@@ -50,13 +48,17 @@ class EnumValueDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional string name = 1;</code>
+ * Generated from protobuf field <code>optional string name = 1;</code>
+ * @param string $var
+ * @return $this
*/
public function setName($var)
{
GPBUtil::checkString($var, True);
$this->name = $var;
$this->has_name = true;
+
+ return $this;
}
public function hasName()
@@ -65,7 +67,8 @@ class EnumValueDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional int32 number = 2;</code>
+ * Generated from protobuf field <code>optional int32 number = 2;</code>
+ * @return int
*/
public function getNumber()
{
@@ -73,13 +76,17 @@ class EnumValueDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional int32 number = 2;</code>
+ * Generated from protobuf field <code>optional int32 number = 2;</code>
+ * @param int $var
+ * @return $this
*/
public function setNumber($var)
{
GPBUtil::checkInt32($var);
$this->number = $var;
$this->has_number = true;
+
+ return $this;
}
public function hasNumber()
@@ -88,7 +95,8 @@ class EnumValueDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional .google.protobuf.EnumValueOptions options = 3;</code>
+ * Generated from protobuf field <code>optional .google.protobuf.EnumValueOptions options = 3;</code>
+ * @return \Google\Protobuf\Internal\EnumValueOptions
*/
public function getOptions()
{
@@ -96,13 +104,17 @@ class EnumValueDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional .google.protobuf.EnumValueOptions options = 3;</code>
+ * Generated from protobuf field <code>optional .google.protobuf.EnumValueOptions options = 3;</code>
+ * @param \Google\Protobuf\Internal\EnumValueOptions $var
+ * @return $this
*/
- public function setOptions(&$var)
+ public function setOptions($var)
{
GPBUtil::checkMessage($var, \Google\Protobuf\Internal\EnumValueOptions::class);
$this->options = $var;
$this->has_options = true;
+
+ return $this;
}
public function hasOptions()
diff --git a/php/src/Google/Protobuf/Internal/EnumValueOptions.php b/php/src/Google/Protobuf/Internal/EnumValueOptions.php
index 6446ecd4..db8de174 100644
--- a/php/src/Google/Protobuf/Internal/EnumValueOptions.php
+++ b/php/src/Google/Protobuf/Internal/EnumValueOptions.php
@@ -8,32 +8,27 @@ use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\GPBWire;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\InputStream;
-
use Google\Protobuf\Internal\GPBUtil;
/**
- * Protobuf type <code>google.protobuf.EnumValueOptions</code>
+ * Generated from protobuf message <code>google.protobuf.EnumValueOptions</code>
*/
class EnumValueOptions extends \Google\Protobuf\Internal\Message
{
/**
- * <pre>
* Is this enum value deprecated?
* Depending on the target platform, this can emit Deprecated annotations
* for the enum value, or it will be completely ignored; in the very least,
* this is a formalization for deprecating enum values.
- * </pre>
*
- * <code>optional bool deprecated = 1 [default = false];</code>
+ * Generated from protobuf field <code>optional bool deprecated = 1 [default = false];</code>
*/
private $deprecated = false;
private $has_deprecated = false;
/**
- * <pre>
* The parser stores options it doesn't recognize here. See above.
- * </pre>
*
- * <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
*/
private $uninterpreted_option;
private $has_uninterpreted_option = false;
@@ -44,14 +39,13 @@ class EnumValueOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Is this enum value deprecated?
* Depending on the target platform, this can emit Deprecated annotations
* for the enum value, or it will be completely ignored; in the very least,
* this is a formalization for deprecating enum values.
- * </pre>
*
- * <code>optional bool deprecated = 1 [default = false];</code>
+ * Generated from protobuf field <code>optional bool deprecated = 1 [default = false];</code>
+ * @return bool
*/
public function getDeprecated()
{
@@ -59,20 +53,22 @@ class EnumValueOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Is this enum value deprecated?
* Depending on the target platform, this can emit Deprecated annotations
* for the enum value, or it will be completely ignored; in the very least,
* this is a formalization for deprecating enum values.
- * </pre>
*
- * <code>optional bool deprecated = 1 [default = false];</code>
+ * Generated from protobuf field <code>optional bool deprecated = 1 [default = false];</code>
+ * @param bool $var
+ * @return $this
*/
public function setDeprecated($var)
{
GPBUtil::checkBool($var);
$this->deprecated = $var;
$this->has_deprecated = true;
+
+ return $this;
}
public function hasDeprecated()
@@ -81,11 +77,10 @@ class EnumValueOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* The parser stores options it doesn't recognize here. See above.
- * </pre>
*
- * <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
*/
public function getUninterpretedOption()
{
@@ -93,17 +88,19 @@ class EnumValueOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* The parser stores options it doesn't recognize here. See above.
- * </pre>
*
- * <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * @param \Google\Protobuf\Internal\UninterpretedOption[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
*/
- public function setUninterpretedOption(&$var)
+ public function setUninterpretedOption($var)
{
- GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\UninterpretedOption::class);
- $this->uninterpreted_option = $var;
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\UninterpretedOption::class);
+ $this->uninterpreted_option = $arr;
$this->has_uninterpreted_option = true;
+
+ return $this;
}
public function hasUninterpretedOption()
diff --git a/php/src/Google/Protobuf/Internal/ExtensionRangeOptions.php b/php/src/Google/Protobuf/Internal/ExtensionRangeOptions.php
new file mode 100644
index 00000000..ee9e38bb
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/ExtensionRangeOptions.php
@@ -0,0 +1,64 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/descriptor.proto
+
+namespace Google\Protobuf\Internal;
+
+use Google\Protobuf\Internal\GPBType;
+use Google\Protobuf\Internal\GPBWire;
+use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\InputStream;
+use Google\Protobuf\Internal\GPBUtil;
+
+/**
+ * Generated from protobuf message <code>google.protobuf.ExtensionRangeOptions</code>
+ */
+class ExtensionRangeOptions extends \Google\Protobuf\Internal\Message
+{
+ /**
+ * The parser stores options it doesn't recognize here. See above.
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ */
+ private $uninterpreted_option;
+ private $has_uninterpreted_option = false;
+
+ public function __construct() {
+ \GPBMetadata\Google\Protobuf\Internal\Descriptor::initOnce();
+ parent::__construct();
+ }
+
+ /**
+ * The parser stores options it doesn't recognize here. See above.
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
+ */
+ public function getUninterpretedOption()
+ {
+ return $this->uninterpreted_option;
+ }
+
+ /**
+ * The parser stores options it doesn't recognize here. See above.
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * @param \Google\Protobuf\Internal\UninterpretedOption[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
+ */
+ public function setUninterpretedOption($var)
+ {
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\UninterpretedOption::class);
+ $this->uninterpreted_option = $arr;
+ $this->has_uninterpreted_option = true;
+
+ return $this;
+ }
+
+ public function hasUninterpretedOption()
+ {
+ return $this->has_uninterpreted_option;
+ }
+
+}
+
diff --git a/php/src/Google/Protobuf/Internal/FieldDescriptor.php b/php/src/Google/Protobuf/Internal/FieldDescriptor.php
new file mode 100644
index 00000000..6644a2e0
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/FieldDescriptor.php
@@ -0,0 +1,265 @@
+<?php
+
+// 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.
+
+namespace Google\Protobuf\Internal;
+
+class FieldDescriptor
+{
+ use HasPublicDescriptorTrait;
+
+ private $name;
+ private $json_name;
+ private $setter;
+ private $getter;
+ private $number;
+ private $label;
+ private $type;
+ private $message_type;
+ private $enum_type;
+ private $packed;
+ private $is_map;
+ private $oneof_index = -1;
+
+ public function __construct()
+ {
+ $this->public_desc = new \Google\Protobuf\FieldDescriptor($this);
+ }
+
+ public function setOneofIndex($index)
+ {
+ $this->oneof_index = $index;
+ }
+
+ public function getOneofIndex()
+ {
+ return $this->oneof_index;
+ }
+
+ public function setName($name)
+ {
+ $this->name = $name;
+ }
+
+ public function getName()
+ {
+ return $this->name;
+ }
+
+ public function setJsonName($json_name)
+ {
+ $this->json_name = $json_name;
+ }
+
+ public function getJsonName()
+ {
+ return $this->json_name;
+ }
+
+ public function setSetter($setter)
+ {
+ $this->setter = $setter;
+ }
+
+ public function getSetter()
+ {
+ return $this->setter;
+ }
+
+ public function setGetter($getter)
+ {
+ $this->getter = $getter;
+ }
+
+ public function getGetter()
+ {
+ return $this->getter;
+ }
+
+ public function setNumber($number)
+ {
+ $this->number = $number;
+ }
+
+ public function getNumber()
+ {
+ return $this->number;
+ }
+
+ public function setLabel($label)
+ {
+ $this->label = $label;
+ }
+
+ public function getLabel()
+ {
+ return $this->label;
+ }
+
+ public function isRepeated()
+ {
+ return $this->label === GPBLabel::REPEATED;
+ }
+
+ public function setType($type)
+ {
+ $this->type = $type;
+ }
+
+ public function getType()
+ {
+ return $this->type;
+ }
+
+ public function setMessageType($message_type)
+ {
+ $this->message_type = $message_type;
+ }
+
+ public function getMessageType()
+ {
+ return $this->message_type;
+ }
+
+ public function setEnumType($enum_type)
+ {
+ $this->enum_type = $enum_type;
+ }
+
+ public function getEnumType()
+ {
+ return $this->enum_type;
+ }
+
+ public function setPacked($packed)
+ {
+ $this->packed = $packed;
+ }
+
+ public function getPacked()
+ {
+ return $this->packed;
+ }
+
+ public function isPackable()
+ {
+ return $this->isRepeated() && self::isTypePackable($this->type);
+ }
+
+ public function isMap()
+ {
+ return $this->getType() == GPBType::MESSAGE &&
+ !is_null($this->getMessageType()->getOptions()) &&
+ $this->getMessageType()->getOptions()->getMapEntry();
+ }
+
+ public function isTimestamp()
+ {
+ return $this->getType() == GPBType::MESSAGE &&
+ $this->getMessageType()->getClass() === "Google\Protobuf\Timestamp";
+ }
+
+ private static function isTypePackable($field_type)
+ {
+ return ($field_type !== GPBType::STRING &&
+ $field_type !== GPBType::GROUP &&
+ $field_type !== GPBType::MESSAGE &&
+ $field_type !== GPBType::BYTES);
+ }
+
+ public static function getFieldDescriptor($proto)
+ {
+ $type_name = null;
+ $type = $proto->getType();
+ switch ($type) {
+ case GPBType::MESSAGE:
+ case GPBType::GROUP:
+ case GPBType::ENUM:
+ $type_name = $proto->getTypeName();
+ break;
+ default:
+ break;
+ }
+
+ $oneof_index = $proto->hasOneofIndex() ? $proto->getOneofIndex() : -1;
+ $packed = false;
+ $options = $proto->getOptions();
+ if ($options !== null) {
+ $packed = $options->getPacked();
+ }
+
+ $field = new FieldDescriptor();
+ $field->setName($proto->getName());
+
+ $json_name = $proto->hasJsonName() ? $proto->getJsonName() :
+ lcfirst(implode('', array_map('ucwords', explode('_', $proto->getName()))));
+ if ($proto->hasJsonName()) {
+ $json_name = $proto->getJsonName();
+ } else {
+ $proto_name = $proto->getName();
+ $json_name = implode('', array_map('ucwords', explode('_', $proto_name)));
+ if ($proto_name[0] !== "_" && !ctype_upper($proto_name[0])) {
+ $json_name = lcfirst($json_name);
+ }
+ }
+ $field->setJsonName($json_name);
+
+ $camel_name = implode('', array_map('ucwords', explode('_', $proto->getName())));
+ $field->setGetter('get' . $camel_name);
+ $field->setSetter('set' . $camel_name);
+ $field->setType($proto->getType());
+ $field->setNumber($proto->getNumber());
+ $field->setLabel($proto->getLabel());
+ $field->setPacked($packed);
+ $field->setOneofIndex($oneof_index);
+
+ // At this time, the message/enum type may have not been added to pool.
+ // So we use the type name as place holder and will replace it with the
+ // actual descriptor in cross building.
+ switch ($type) {
+ case GPBType::MESSAGE:
+ $field->setMessageType($type_name);
+ break;
+ case GPBType::ENUM:
+ $field->setEnumType($type_name);
+ break;
+ default:
+ break;
+ }
+
+ return $field;
+ }
+
+ public static function buildFromProto($proto)
+ {
+ return FieldDescriptor::getFieldDescriptor($proto);
+ }
+}
diff --git a/php/src/Google/Protobuf/Internal/FieldDescriptorProto.php b/php/src/Google/Protobuf/Internal/FieldDescriptorProto.php
index 6ae2cd41..10c27593 100644
--- a/php/src/Google/Protobuf/Internal/FieldDescriptorProto.php
+++ b/php/src/Google/Protobuf/Internal/FieldDescriptorProto.php
@@ -8,103 +8,88 @@ use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\GPBWire;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\InputStream;
-
use Google\Protobuf\Internal\GPBUtil;
/**
- * <pre>
* Describes a field within a message.
- * </pre>
*
- * Protobuf type <code>google.protobuf.FieldDescriptorProto</code>
+ * Generated from protobuf message <code>google.protobuf.FieldDescriptorProto</code>
*/
class FieldDescriptorProto extends \Google\Protobuf\Internal\Message
{
/**
- * <code>optional string name = 1;</code>
+ * Generated from protobuf field <code>optional string name = 1;</code>
*/
private $name = '';
private $has_name = false;
/**
- * <code>optional int32 number = 3;</code>
+ * Generated from protobuf field <code>optional int32 number = 3;</code>
*/
private $number = 0;
private $has_number = false;
/**
- * <code>optional .google.protobuf.FieldDescriptorProto.Label label = 4;</code>
+ * Generated from protobuf field <code>optional .google.protobuf.FieldDescriptorProto.Label label = 4;</code>
*/
private $label = 0;
private $has_label = false;
/**
- * <pre>
* If type_name is set, this need not be set. If both this and type_name
* are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP.
- * </pre>
*
- * <code>optional .google.protobuf.FieldDescriptorProto.Type type = 5;</code>
+ * Generated from protobuf field <code>optional .google.protobuf.FieldDescriptorProto.Type type = 5;</code>
*/
private $type = 0;
private $has_type = false;
/**
- * <pre>
* For message and enum types, this is the name of the type. If the name
* starts with a '.', it is fully-qualified. Otherwise, C++-like scoping
* rules are used to find the type (i.e. first the nested types within this
* message are searched, then within the parent, on up to the root
* namespace).
- * </pre>
*
- * <code>optional string type_name = 6;</code>
+ * Generated from protobuf field <code>optional string type_name = 6;</code>
*/
private $type_name = '';
private $has_type_name = false;
/**
- * <pre>
* For extensions, this is the name of the type being extended. It is
* resolved in the same manner as type_name.
- * </pre>
*
- * <code>optional string extendee = 2;</code>
+ * Generated from protobuf field <code>optional string extendee = 2;</code>
*/
private $extendee = '';
private $has_extendee = false;
/**
- * <pre>
* For numeric types, contains the original text representation of the value.
* For booleans, "true" or "false".
* For strings, contains the default text contents (not escaped in any way).
- * For bytes, contains the C escaped value. All bytes &gt;= 128 are escaped.
+ * For bytes, contains the C escaped value. All bytes >= 128 are escaped.
* TODO(kenton): Base-64 encode?
- * </pre>
*
- * <code>optional string default_value = 7;</code>
+ * Generated from protobuf field <code>optional string default_value = 7;</code>
*/
private $default_value = '';
private $has_default_value = false;
/**
- * <pre>
* If set, gives the index of a oneof in the containing type's oneof_decl
* list. This field is a member of that oneof.
- * </pre>
*
- * <code>optional int32 oneof_index = 9;</code>
+ * Generated from protobuf field <code>optional int32 oneof_index = 9;</code>
*/
private $oneof_index = 0;
private $has_oneof_index = false;
/**
- * <pre>
* JSON name of this field. The value is set by protocol compiler. If the
* user has set a "json_name" option on this field, that option's value
* will be used. Otherwise, it's deduced from the field's name by converting
* it to camelCase.
- * </pre>
*
- * <code>optional string json_name = 10;</code>
+ * Generated from protobuf field <code>optional string json_name = 10;</code>
*/
private $json_name = '';
private $has_json_name = false;
/**
- * <code>optional .google.protobuf.FieldOptions options = 8;</code>
+ * Generated from protobuf field <code>optional .google.protobuf.FieldOptions options = 8;</code>
*/
private $options = null;
private $has_options = false;
@@ -115,7 +100,8 @@ class FieldDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional string name = 1;</code>
+ * Generated from protobuf field <code>optional string name = 1;</code>
+ * @return string
*/
public function getName()
{
@@ -123,13 +109,17 @@ class FieldDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional string name = 1;</code>
+ * Generated from protobuf field <code>optional string name = 1;</code>
+ * @param string $var
+ * @return $this
*/
public function setName($var)
{
GPBUtil::checkString($var, True);
$this->name = $var;
$this->has_name = true;
+
+ return $this;
}
public function hasName()
@@ -138,7 +128,8 @@ class FieldDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional int32 number = 3;</code>
+ * Generated from protobuf field <code>optional int32 number = 3;</code>
+ * @return int
*/
public function getNumber()
{
@@ -146,13 +137,17 @@ class FieldDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional int32 number = 3;</code>
+ * Generated from protobuf field <code>optional int32 number = 3;</code>
+ * @param int $var
+ * @return $this
*/
public function setNumber($var)
{
GPBUtil::checkInt32($var);
$this->number = $var;
$this->has_number = true;
+
+ return $this;
}
public function hasNumber()
@@ -161,7 +156,8 @@ class FieldDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional .google.protobuf.FieldDescriptorProto.Label label = 4;</code>
+ * Generated from protobuf field <code>optional .google.protobuf.FieldDescriptorProto.Label label = 4;</code>
+ * @return int
*/
public function getLabel()
{
@@ -169,13 +165,17 @@ class FieldDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional .google.protobuf.FieldDescriptorProto.Label label = 4;</code>
+ * Generated from protobuf field <code>optional .google.protobuf.FieldDescriptorProto.Label label = 4;</code>
+ * @param int $var
+ * @return $this
*/
public function setLabel($var)
{
GPBUtil::checkEnum($var, \Google\Protobuf\Internal\FieldDescriptorProto_Label::class);
$this->label = $var;
$this->has_label = true;
+
+ return $this;
}
public function hasLabel()
@@ -184,12 +184,11 @@ class FieldDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* If type_name is set, this need not be set. If both this and type_name
* are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP.
- * </pre>
*
- * <code>optional .google.protobuf.FieldDescriptorProto.Type type = 5;</code>
+ * Generated from protobuf field <code>optional .google.protobuf.FieldDescriptorProto.Type type = 5;</code>
+ * @return int
*/
public function getType()
{
@@ -197,18 +196,20 @@ class FieldDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* If type_name is set, this need not be set. If both this and type_name
* are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP.
- * </pre>
*
- * <code>optional .google.protobuf.FieldDescriptorProto.Type type = 5;</code>
+ * Generated from protobuf field <code>optional .google.protobuf.FieldDescriptorProto.Type type = 5;</code>
+ * @param int $var
+ * @return $this
*/
public function setType($var)
{
GPBUtil::checkEnum($var, \Google\Protobuf\Internal\FieldDescriptorProto_Type::class);
$this->type = $var;
$this->has_type = true;
+
+ return $this;
}
public function hasType()
@@ -217,15 +218,14 @@ class FieldDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* For message and enum types, this is the name of the type. If the name
* starts with a '.', it is fully-qualified. Otherwise, C++-like scoping
* rules are used to find the type (i.e. first the nested types within this
* message are searched, then within the parent, on up to the root
* namespace).
- * </pre>
*
- * <code>optional string type_name = 6;</code>
+ * Generated from protobuf field <code>optional string type_name = 6;</code>
+ * @return string
*/
public function getTypeName()
{
@@ -233,21 +233,23 @@ class FieldDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* For message and enum types, this is the name of the type. If the name
* starts with a '.', it is fully-qualified. Otherwise, C++-like scoping
* rules are used to find the type (i.e. first the nested types within this
* message are searched, then within the parent, on up to the root
* namespace).
- * </pre>
*
- * <code>optional string type_name = 6;</code>
+ * Generated from protobuf field <code>optional string type_name = 6;</code>
+ * @param string $var
+ * @return $this
*/
public function setTypeName($var)
{
GPBUtil::checkString($var, True);
$this->type_name = $var;
$this->has_type_name = true;
+
+ return $this;
}
public function hasTypeName()
@@ -256,12 +258,11 @@ class FieldDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* For extensions, this is the name of the type being extended. It is
* resolved in the same manner as type_name.
- * </pre>
*
- * <code>optional string extendee = 2;</code>
+ * Generated from protobuf field <code>optional string extendee = 2;</code>
+ * @return string
*/
public function getExtendee()
{
@@ -269,18 +270,20 @@ class FieldDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* For extensions, this is the name of the type being extended. It is
* resolved in the same manner as type_name.
- * </pre>
*
- * <code>optional string extendee = 2;</code>
+ * Generated from protobuf field <code>optional string extendee = 2;</code>
+ * @param string $var
+ * @return $this
*/
public function setExtendee($var)
{
GPBUtil::checkString($var, True);
$this->extendee = $var;
$this->has_extendee = true;
+
+ return $this;
}
public function hasExtendee()
@@ -289,15 +292,14 @@ class FieldDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* For numeric types, contains the original text representation of the value.
* For booleans, "true" or "false".
* For strings, contains the default text contents (not escaped in any way).
- * For bytes, contains the C escaped value. All bytes &gt;= 128 are escaped.
+ * For bytes, contains the C escaped value. All bytes >= 128 are escaped.
* TODO(kenton): Base-64 encode?
- * </pre>
*
- * <code>optional string default_value = 7;</code>
+ * Generated from protobuf field <code>optional string default_value = 7;</code>
+ * @return string
*/
public function getDefaultValue()
{
@@ -305,21 +307,23 @@ class FieldDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* For numeric types, contains the original text representation of the value.
* For booleans, "true" or "false".
* For strings, contains the default text contents (not escaped in any way).
- * For bytes, contains the C escaped value. All bytes &gt;= 128 are escaped.
+ * For bytes, contains the C escaped value. All bytes >= 128 are escaped.
* TODO(kenton): Base-64 encode?
- * </pre>
*
- * <code>optional string default_value = 7;</code>
+ * Generated from protobuf field <code>optional string default_value = 7;</code>
+ * @param string $var
+ * @return $this
*/
public function setDefaultValue($var)
{
GPBUtil::checkString($var, True);
$this->default_value = $var;
$this->has_default_value = true;
+
+ return $this;
}
public function hasDefaultValue()
@@ -328,12 +332,11 @@ class FieldDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* If set, gives the index of a oneof in the containing type's oneof_decl
* list. This field is a member of that oneof.
- * </pre>
*
- * <code>optional int32 oneof_index = 9;</code>
+ * Generated from protobuf field <code>optional int32 oneof_index = 9;</code>
+ * @return int
*/
public function getOneofIndex()
{
@@ -341,18 +344,20 @@ class FieldDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* If set, gives the index of a oneof in the containing type's oneof_decl
* list. This field is a member of that oneof.
- * </pre>
*
- * <code>optional int32 oneof_index = 9;</code>
+ * Generated from protobuf field <code>optional int32 oneof_index = 9;</code>
+ * @param int $var
+ * @return $this
*/
public function setOneofIndex($var)
{
GPBUtil::checkInt32($var);
$this->oneof_index = $var;
$this->has_oneof_index = true;
+
+ return $this;
}
public function hasOneofIndex()
@@ -361,14 +366,13 @@ class FieldDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* JSON name of this field. The value is set by protocol compiler. If the
* user has set a "json_name" option on this field, that option's value
* will be used. Otherwise, it's deduced from the field's name by converting
* it to camelCase.
- * </pre>
*
- * <code>optional string json_name = 10;</code>
+ * Generated from protobuf field <code>optional string json_name = 10;</code>
+ * @return string
*/
public function getJsonName()
{
@@ -376,20 +380,22 @@ class FieldDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* JSON name of this field. The value is set by protocol compiler. If the
* user has set a "json_name" option on this field, that option's value
* will be used. Otherwise, it's deduced from the field's name by converting
* it to camelCase.
- * </pre>
*
- * <code>optional string json_name = 10;</code>
+ * Generated from protobuf field <code>optional string json_name = 10;</code>
+ * @param string $var
+ * @return $this
*/
public function setJsonName($var)
{
GPBUtil::checkString($var, True);
$this->json_name = $var;
$this->has_json_name = true;
+
+ return $this;
}
public function hasJsonName()
@@ -398,7 +404,8 @@ class FieldDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional .google.protobuf.FieldOptions options = 8;</code>
+ * Generated from protobuf field <code>optional .google.protobuf.FieldOptions options = 8;</code>
+ * @return \Google\Protobuf\Internal\FieldOptions
*/
public function getOptions()
{
@@ -406,13 +413,17 @@ class FieldDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional .google.protobuf.FieldOptions options = 8;</code>
+ * Generated from protobuf field <code>optional .google.protobuf.FieldOptions options = 8;</code>
+ * @param \Google\Protobuf\Internal\FieldOptions $var
+ * @return $this
*/
- public function setOptions(&$var)
+ public function setOptions($var)
{
GPBUtil::checkMessage($var, \Google\Protobuf\Internal\FieldOptions::class);
$this->options = $var;
$this->has_options = true;
+
+ return $this;
}
public function hasOptions()
diff --git a/php/src/Google/Protobuf/Internal/FieldDescriptorProto_Label.php b/php/src/Google/Protobuf/Internal/FieldDescriptorProto_Label.php
index 06f26015..f2a32fdf 100644
--- a/php/src/Google/Protobuf/Internal/FieldDescriptorProto_Label.php
+++ b/php/src/Google/Protobuf/Internal/FieldDescriptorProto_Label.php
@@ -2,27 +2,25 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/descriptor.proto
-/**
- * Protobuf enum <code>google.protobuf.FieldDescriptorProto.Label</code>
- */
namespace Google\Protobuf\Internal;
+/**
+ * Protobuf enum <code>Google\Protobuf\Internal</code>
+ */
class FieldDescriptorProto_Label
{
/**
- * <pre>
* 0 is reserved for errors
- * </pre>
*
- * <code>LABEL_OPTIONAL = 1;</code>
+ * Generated from protobuf enum <code>LABEL_OPTIONAL = 1;</code>
*/
const LABEL_OPTIONAL = 1;
/**
- * <code>LABEL_REQUIRED = 2;</code>
+ * Generated from protobuf enum <code>LABEL_REQUIRED = 2;</code>
*/
const LABEL_REQUIRED = 2;
/**
- * <code>LABEL_REPEATED = 3;</code>
+ * Generated from protobuf enum <code>LABEL_REPEATED = 3;</code>
*/
const LABEL_REPEATED = 3;
}
diff --git a/php/src/Google/Protobuf/Internal/FieldDescriptorProto_Type.php b/php/src/Google/Protobuf/Internal/FieldDescriptorProto_Type.php
index 9bda76c2..1b022deb 100644
--- a/php/src/Google/Protobuf/Internal/FieldDescriptorProto_Type.php
+++ b/php/src/Google/Protobuf/Internal/FieldDescriptorProto_Type.php
@@ -2,118 +2,105 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/descriptor.proto
-/**
- * Protobuf enum <code>google.protobuf.FieldDescriptorProto.Type</code>
- */
namespace Google\Protobuf\Internal;
+/**
+ * Protobuf enum <code>Google\Protobuf\Internal</code>
+ */
class FieldDescriptorProto_Type
{
/**
- * <pre>
* 0 is reserved for errors.
* Order is weird for historical reasons.
- * </pre>
*
- * <code>TYPE_DOUBLE = 1;</code>
+ * Generated from protobuf enum <code>TYPE_DOUBLE = 1;</code>
*/
const TYPE_DOUBLE = 1;
/**
- * <code>TYPE_FLOAT = 2;</code>
+ * Generated from protobuf enum <code>TYPE_FLOAT = 2;</code>
*/
const TYPE_FLOAT = 2;
/**
- * <pre>
* Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if
* negative values are likely.
- * </pre>
*
- * <code>TYPE_INT64 = 3;</code>
+ * Generated from protobuf enum <code>TYPE_INT64 = 3;</code>
*/
const TYPE_INT64 = 3;
/**
- * <code>TYPE_UINT64 = 4;</code>
+ * Generated from protobuf enum <code>TYPE_UINT64 = 4;</code>
*/
const TYPE_UINT64 = 4;
/**
- * <pre>
* Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if
* negative values are likely.
- * </pre>
*
- * <code>TYPE_INT32 = 5;</code>
+ * Generated from protobuf enum <code>TYPE_INT32 = 5;</code>
*/
const TYPE_INT32 = 5;
/**
- * <code>TYPE_FIXED64 = 6;</code>
+ * Generated from protobuf enum <code>TYPE_FIXED64 = 6;</code>
*/
const TYPE_FIXED64 = 6;
/**
- * <code>TYPE_FIXED32 = 7;</code>
+ * Generated from protobuf enum <code>TYPE_FIXED32 = 7;</code>
*/
const TYPE_FIXED32 = 7;
/**
- * <code>TYPE_BOOL = 8;</code>
+ * Generated from protobuf enum <code>TYPE_BOOL = 8;</code>
*/
const TYPE_BOOL = 8;
/**
- * <code>TYPE_STRING = 9;</code>
+ * Generated from protobuf enum <code>TYPE_STRING = 9;</code>
*/
const TYPE_STRING = 9;
/**
- * <pre>
* Tag-delimited aggregate.
- * </pre>
+ * Group type is deprecated and not supported in proto3. However, Proto3
+ * implementations should still be able to parse the group wire format and
+ * treat group fields as unknown fields.
*
- * <code>TYPE_GROUP = 10;</code>
+ * Generated from protobuf enum <code>TYPE_GROUP = 10;</code>
*/
const TYPE_GROUP = 10;
/**
- * <pre>
* Length-delimited aggregate.
- * </pre>
*
- * <code>TYPE_MESSAGE = 11;</code>
+ * Generated from protobuf enum <code>TYPE_MESSAGE = 11;</code>
*/
const TYPE_MESSAGE = 11;
/**
- * <pre>
* New in version 2.
- * </pre>
*
- * <code>TYPE_BYTES = 12;</code>
+ * Generated from protobuf enum <code>TYPE_BYTES = 12;</code>
*/
const TYPE_BYTES = 12;
/**
- * <code>TYPE_UINT32 = 13;</code>
+ * Generated from protobuf enum <code>TYPE_UINT32 = 13;</code>
*/
const TYPE_UINT32 = 13;
/**
- * <code>TYPE_ENUM = 14;</code>
+ * Generated from protobuf enum <code>TYPE_ENUM = 14;</code>
*/
const TYPE_ENUM = 14;
/**
- * <code>TYPE_SFIXED32 = 15;</code>
+ * Generated from protobuf enum <code>TYPE_SFIXED32 = 15;</code>
*/
const TYPE_SFIXED32 = 15;
/**
- * <code>TYPE_SFIXED64 = 16;</code>
+ * Generated from protobuf enum <code>TYPE_SFIXED64 = 16;</code>
*/
const TYPE_SFIXED64 = 16;
/**
- * <pre>
* Uses ZigZag encoding.
- * </pre>
*
- * <code>TYPE_SINT32 = 17;</code>
+ * Generated from protobuf enum <code>TYPE_SINT32 = 17;</code>
*/
const TYPE_SINT32 = 17;
/**
- * <pre>
* Uses ZigZag encoding.
- * </pre>
*
- * <code>TYPE_SINT64 = 18;</code>
+ * Generated from protobuf enum <code>TYPE_SINT64 = 18;</code>
*/
const TYPE_SINT64 = 18;
}
diff --git a/php/src/Google/Protobuf/Internal/FieldOptions.php b/php/src/Google/Protobuf/Internal/FieldOptions.php
index af1393a5..169f860b 100644
--- a/php/src/Google/Protobuf/Internal/FieldOptions.php
+++ b/php/src/Google/Protobuf/Internal/FieldOptions.php
@@ -8,58 +8,51 @@ use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\GPBWire;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\InputStream;
-
use Google\Protobuf\Internal\GPBUtil;
/**
- * Protobuf type <code>google.protobuf.FieldOptions</code>
+ * Generated from protobuf message <code>google.protobuf.FieldOptions</code>
*/
class FieldOptions extends \Google\Protobuf\Internal\Message
{
/**
- * <pre>
* The ctype option instructs the C++ code generator to use a different
* representation of the field than it normally would. See the specific
* options below. This option is not yet implemented in the open source
* release -- sorry, we'll try to include it in a future version!
- * </pre>
*
- * <code>optional .google.protobuf.FieldOptions.CType ctype = 1 [default = STRING];</code>
+ * Generated from protobuf field <code>optional .google.protobuf.FieldOptions.CType ctype = 1 [default = STRING];</code>
*/
private $ctype = 0;
private $has_ctype = false;
/**
- * <pre>
* The packed option can be enabled for repeated primitive fields to enable
* a more efficient representation on the wire. Rather than repeatedly
* writing the tag and type for each element, the entire array is encoded as
* a single length-delimited blob. In proto3, only explicit setting it to
* false will avoid using packed encoding.
- * </pre>
*
- * <code>optional bool packed = 2;</code>
+ * Generated from protobuf field <code>optional bool packed = 2;</code>
*/
private $packed = false;
private $has_packed = false;
/**
- * <pre>
* The jstype option determines the JavaScript type used for values of the
* field. The option is permitted only for 64 bit integral and fixed types
- * (int64, uint64, sint64, fixed64, sfixed64). By default these types are
- * represented as JavaScript strings. This avoids loss of precision that can
- * happen when a large value is converted to a floating point JavaScript
- * numbers. Specifying JS_NUMBER for the jstype causes the generated
- * JavaScript code to use the JavaScript "number" type instead of strings.
- * This option is an enum to permit additional types to be added,
- * e.g. goog.math.Integer.
- * </pre>
+ * (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING
+ * is represented as JavaScript string, which avoids loss of precision that
+ * can happen when a large value is converted to a floating point JavaScript.
+ * Specifying JS_NUMBER for the jstype causes the generated JavaScript code to
+ * use the JavaScript "number" type. The behavior of the default option
+ * JS_NORMAL is implementation dependent.
+ * This option is an enum to permit additional types to be added, e.g.
+ * goog.math.Integer.
*
- * <code>optional .google.protobuf.FieldOptions.JSType jstype = 6 [default = JS_NORMAL];</code>
+ * Generated from protobuf field <code>optional .google.protobuf.FieldOptions.JSType jstype = 6 [default = JS_NORMAL];</code>
*/
private $jstype = 0;
private $has_jstype = false;
/**
- * <pre>
* Should this field be parsed lazily? Lazy applies only to message-type
* fields. It means that when the outer message is initially parsed, the
* inner message's contents will not be parsed but instead stored in encoded
@@ -84,39 +77,32 @@ class FieldOptions extends \Google\Protobuf\Internal\Message
* implementation must either *always* check its required fields, or *never*
* check its required fields, regardless of whether or not the message has
* been parsed.
- * </pre>
*
- * <code>optional bool lazy = 5 [default = false];</code>
+ * Generated from protobuf field <code>optional bool lazy = 5 [default = false];</code>
*/
private $lazy = false;
private $has_lazy = false;
/**
- * <pre>
* Is this field deprecated?
* Depending on the target platform, this can emit Deprecated annotations
* for accessors, or it will be completely ignored; in the very least, this
* is a formalization for deprecating fields.
- * </pre>
*
- * <code>optional bool deprecated = 3 [default = false];</code>
+ * Generated from protobuf field <code>optional bool deprecated = 3 [default = false];</code>
*/
private $deprecated = false;
private $has_deprecated = false;
/**
- * <pre>
* For Google-internal migration only. Do not use.
- * </pre>
*
- * <code>optional bool weak = 10 [default = false];</code>
+ * Generated from protobuf field <code>optional bool weak = 10 [default = false];</code>
*/
private $weak = false;
private $has_weak = false;
/**
- * <pre>
* The parser stores options it doesn't recognize here. See above.
- * </pre>
*
- * <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
*/
private $uninterpreted_option;
private $has_uninterpreted_option = false;
@@ -127,14 +113,13 @@ class FieldOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* The ctype option instructs the C++ code generator to use a different
* representation of the field than it normally would. See the specific
* options below. This option is not yet implemented in the open source
* release -- sorry, we'll try to include it in a future version!
- * </pre>
*
- * <code>optional .google.protobuf.FieldOptions.CType ctype = 1 [default = STRING];</code>
+ * Generated from protobuf field <code>optional .google.protobuf.FieldOptions.CType ctype = 1 [default = STRING];</code>
+ * @return int
*/
public function getCtype()
{
@@ -142,20 +127,22 @@ class FieldOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* The ctype option instructs the C++ code generator to use a different
* representation of the field than it normally would. See the specific
* options below. This option is not yet implemented in the open source
* release -- sorry, we'll try to include it in a future version!
- * </pre>
*
- * <code>optional .google.protobuf.FieldOptions.CType ctype = 1 [default = STRING];</code>
+ * Generated from protobuf field <code>optional .google.protobuf.FieldOptions.CType ctype = 1 [default = STRING];</code>
+ * @param int $var
+ * @return $this
*/
public function setCtype($var)
{
GPBUtil::checkEnum($var, \Google\Protobuf\Internal\FieldOptions_CType::class);
$this->ctype = $var;
$this->has_ctype = true;
+
+ return $this;
}
public function hasCtype()
@@ -164,15 +151,14 @@ class FieldOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* The packed option can be enabled for repeated primitive fields to enable
* a more efficient representation on the wire. Rather than repeatedly
* writing the tag and type for each element, the entire array is encoded as
* a single length-delimited blob. In proto3, only explicit setting it to
* false will avoid using packed encoding.
- * </pre>
*
- * <code>optional bool packed = 2;</code>
+ * Generated from protobuf field <code>optional bool packed = 2;</code>
+ * @return bool
*/
public function getPacked()
{
@@ -180,21 +166,23 @@ class FieldOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* The packed option can be enabled for repeated primitive fields to enable
* a more efficient representation on the wire. Rather than repeatedly
* writing the tag and type for each element, the entire array is encoded as
* a single length-delimited blob. In proto3, only explicit setting it to
* false will avoid using packed encoding.
- * </pre>
*
- * <code>optional bool packed = 2;</code>
+ * Generated from protobuf field <code>optional bool packed = 2;</code>
+ * @param bool $var
+ * @return $this
*/
public function setPacked($var)
{
GPBUtil::checkBool($var);
$this->packed = $var;
$this->has_packed = true;
+
+ return $this;
}
public function hasPacked()
@@ -203,19 +191,19 @@ class FieldOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* The jstype option determines the JavaScript type used for values of the
* field. The option is permitted only for 64 bit integral and fixed types
- * (int64, uint64, sint64, fixed64, sfixed64). By default these types are
- * represented as JavaScript strings. This avoids loss of precision that can
- * happen when a large value is converted to a floating point JavaScript
- * numbers. Specifying JS_NUMBER for the jstype causes the generated
- * JavaScript code to use the JavaScript "number" type instead of strings.
- * This option is an enum to permit additional types to be added,
- * e.g. goog.math.Integer.
- * </pre>
+ * (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING
+ * is represented as JavaScript string, which avoids loss of precision that
+ * can happen when a large value is converted to a floating point JavaScript.
+ * Specifying JS_NUMBER for the jstype causes the generated JavaScript code to
+ * use the JavaScript "number" type. The behavior of the default option
+ * JS_NORMAL is implementation dependent.
+ * This option is an enum to permit additional types to be added, e.g.
+ * goog.math.Integer.
*
- * <code>optional .google.protobuf.FieldOptions.JSType jstype = 6 [default = JS_NORMAL];</code>
+ * Generated from protobuf field <code>optional .google.protobuf.FieldOptions.JSType jstype = 6 [default = JS_NORMAL];</code>
+ * @return int
*/
public function getJstype()
{
@@ -223,25 +211,28 @@ class FieldOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* The jstype option determines the JavaScript type used for values of the
* field. The option is permitted only for 64 bit integral and fixed types
- * (int64, uint64, sint64, fixed64, sfixed64). By default these types are
- * represented as JavaScript strings. This avoids loss of precision that can
- * happen when a large value is converted to a floating point JavaScript
- * numbers. Specifying JS_NUMBER for the jstype causes the generated
- * JavaScript code to use the JavaScript "number" type instead of strings.
- * This option is an enum to permit additional types to be added,
- * e.g. goog.math.Integer.
- * </pre>
+ * (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING
+ * is represented as JavaScript string, which avoids loss of precision that
+ * can happen when a large value is converted to a floating point JavaScript.
+ * Specifying JS_NUMBER for the jstype causes the generated JavaScript code to
+ * use the JavaScript "number" type. The behavior of the default option
+ * JS_NORMAL is implementation dependent.
+ * This option is an enum to permit additional types to be added, e.g.
+ * goog.math.Integer.
*
- * <code>optional .google.protobuf.FieldOptions.JSType jstype = 6 [default = JS_NORMAL];</code>
+ * Generated from protobuf field <code>optional .google.protobuf.FieldOptions.JSType jstype = 6 [default = JS_NORMAL];</code>
+ * @param int $var
+ * @return $this
*/
public function setJstype($var)
{
GPBUtil::checkEnum($var, \Google\Protobuf\Internal\FieldOptions_JSType::class);
$this->jstype = $var;
$this->has_jstype = true;
+
+ return $this;
}
public function hasJstype()
@@ -250,7 +241,6 @@ class FieldOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Should this field be parsed lazily? Lazy applies only to message-type
* fields. It means that when the outer message is initially parsed, the
* inner message's contents will not be parsed but instead stored in encoded
@@ -275,9 +265,9 @@ class FieldOptions extends \Google\Protobuf\Internal\Message
* implementation must either *always* check its required fields, or *never*
* check its required fields, regardless of whether or not the message has
* been parsed.
- * </pre>
*
- * <code>optional bool lazy = 5 [default = false];</code>
+ * Generated from protobuf field <code>optional bool lazy = 5 [default = false];</code>
+ * @return bool
*/
public function getLazy()
{
@@ -285,7 +275,6 @@ class FieldOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Should this field be parsed lazily? Lazy applies only to message-type
* fields. It means that when the outer message is initially parsed, the
* inner message's contents will not be parsed but instead stored in encoded
@@ -310,15 +299,18 @@ class FieldOptions extends \Google\Protobuf\Internal\Message
* implementation must either *always* check its required fields, or *never*
* check its required fields, regardless of whether or not the message has
* been parsed.
- * </pre>
*
- * <code>optional bool lazy = 5 [default = false];</code>
+ * Generated from protobuf field <code>optional bool lazy = 5 [default = false];</code>
+ * @param bool $var
+ * @return $this
*/
public function setLazy($var)
{
GPBUtil::checkBool($var);
$this->lazy = $var;
$this->has_lazy = true;
+
+ return $this;
}
public function hasLazy()
@@ -327,14 +319,13 @@ class FieldOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Is this field deprecated?
* Depending on the target platform, this can emit Deprecated annotations
* for accessors, or it will be completely ignored; in the very least, this
* is a formalization for deprecating fields.
- * </pre>
*
- * <code>optional bool deprecated = 3 [default = false];</code>
+ * Generated from protobuf field <code>optional bool deprecated = 3 [default = false];</code>
+ * @return bool
*/
public function getDeprecated()
{
@@ -342,20 +333,22 @@ class FieldOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Is this field deprecated?
* Depending on the target platform, this can emit Deprecated annotations
* for accessors, or it will be completely ignored; in the very least, this
* is a formalization for deprecating fields.
- * </pre>
*
- * <code>optional bool deprecated = 3 [default = false];</code>
+ * Generated from protobuf field <code>optional bool deprecated = 3 [default = false];</code>
+ * @param bool $var
+ * @return $this
*/
public function setDeprecated($var)
{
GPBUtil::checkBool($var);
$this->deprecated = $var;
$this->has_deprecated = true;
+
+ return $this;
}
public function hasDeprecated()
@@ -364,11 +357,10 @@ class FieldOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* For Google-internal migration only. Do not use.
- * </pre>
*
- * <code>optional bool weak = 10 [default = false];</code>
+ * Generated from protobuf field <code>optional bool weak = 10 [default = false];</code>
+ * @return bool
*/
public function getWeak()
{
@@ -376,17 +368,19 @@ class FieldOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* For Google-internal migration only. Do not use.
- * </pre>
*
- * <code>optional bool weak = 10 [default = false];</code>
+ * Generated from protobuf field <code>optional bool weak = 10 [default = false];</code>
+ * @param bool $var
+ * @return $this
*/
public function setWeak($var)
{
GPBUtil::checkBool($var);
$this->weak = $var;
$this->has_weak = true;
+
+ return $this;
}
public function hasWeak()
@@ -395,11 +389,10 @@ class FieldOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* The parser stores options it doesn't recognize here. See above.
- * </pre>
*
- * <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
*/
public function getUninterpretedOption()
{
@@ -407,17 +400,19 @@ class FieldOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* The parser stores options it doesn't recognize here. See above.
- * </pre>
*
- * <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * @param \Google\Protobuf\Internal\UninterpretedOption[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
*/
- public function setUninterpretedOption(&$var)
+ public function setUninterpretedOption($var)
{
- GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\UninterpretedOption::class);
- $this->uninterpreted_option = $var;
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\UninterpretedOption::class);
+ $this->uninterpreted_option = $arr;
$this->has_uninterpreted_option = true;
+
+ return $this;
}
public function hasUninterpretedOption()
diff --git a/php/src/Google/Protobuf/Internal/FieldOptions_CType.php b/php/src/Google/Protobuf/Internal/FieldOptions_CType.php
index 2ff2a478..0f33072d 100644
--- a/php/src/Google/Protobuf/Internal/FieldOptions_CType.php
+++ b/php/src/Google/Protobuf/Internal/FieldOptions_CType.php
@@ -2,27 +2,25 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/descriptor.proto
-/**
- * Protobuf enum <code>google.protobuf.FieldOptions.CType</code>
- */
namespace Google\Protobuf\Internal;
+/**
+ * Protobuf enum <code>Google\Protobuf\Internal</code>
+ */
class FieldOptions_CType
{
/**
- * <pre>
* Default mode.
- * </pre>
*
- * <code>STRING = 0;</code>
+ * Generated from protobuf enum <code>STRING = 0;</code>
*/
const STRING = 0;
/**
- * <code>CORD = 1;</code>
+ * Generated from protobuf enum <code>CORD = 1;</code>
*/
const CORD = 1;
/**
- * <code>STRING_PIECE = 2;</code>
+ * Generated from protobuf enum <code>STRING_PIECE = 2;</code>
*/
const STRING_PIECE = 2;
}
diff --git a/php/src/Google/Protobuf/Internal/FieldOptions_JSType.php b/php/src/Google/Protobuf/Internal/FieldOptions_JSType.php
index 541c8ae5..73bdf3f2 100644
--- a/php/src/Google/Protobuf/Internal/FieldOptions_JSType.php
+++ b/php/src/Google/Protobuf/Internal/FieldOptions_JSType.php
@@ -2,35 +2,29 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/descriptor.proto
-/**
- * Protobuf enum <code>google.protobuf.FieldOptions.JSType</code>
- */
namespace Google\Protobuf\Internal;
+/**
+ * Protobuf enum <code>Google\Protobuf\Internal</code>
+ */
class FieldOptions_JSType
{
/**
- * <pre>
* Use the default type.
- * </pre>
*
- * <code>JS_NORMAL = 0;</code>
+ * Generated from protobuf enum <code>JS_NORMAL = 0;</code>
*/
const JS_NORMAL = 0;
/**
- * <pre>
* Use JavaScript strings.
- * </pre>
*
- * <code>JS_STRING = 1;</code>
+ * Generated from protobuf enum <code>JS_STRING = 1;</code>
*/
const JS_STRING = 1;
/**
- * <pre>
* Use JavaScript numbers.
- * </pre>
*
- * <code>JS_NUMBER = 2;</code>
+ * Generated from protobuf enum <code>JS_NUMBER = 2;</code>
*/
const JS_NUMBER = 2;
}
diff --git a/php/src/Google/Protobuf/Internal/FileDescriptor.php b/php/src/Google/Protobuf/Internal/FileDescriptor.php
new file mode 100644
index 00000000..038da38c
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/FileDescriptor.php
@@ -0,0 +1,89 @@
+<?php
+
+// 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.
+
+namespace Google\Protobuf\Internal;
+
+class FileDescriptor
+{
+
+ private $package;
+ private $message_type = [];
+ private $enum_type = [];
+
+ public function setPackage($package)
+ {
+ $this->package = $package;
+ }
+
+ public function getPackage()
+ {
+ return $this->package;
+ }
+
+ public function getMessageType()
+ {
+ return $this->message_type;
+ }
+
+ public function addMessageType($desc)
+ {
+ $this->message_type[] = $desc;
+ }
+
+ public function getEnumType()
+ {
+ return $this->enum_type;
+ }
+
+ public function addEnumType($desc)
+ {
+ $this->enum_type[]= $desc;
+ }
+
+ public static function buildFromProto($proto)
+ {
+ $file = new FileDescriptor();
+ $file->setPackage($proto->getPackage());
+ foreach ($proto->getMessageType() as $message_proto) {
+ $file->addMessageType(Descriptor::buildFromProto(
+ $message_proto, $proto, ""));
+ }
+ foreach ($proto->getEnumType() as $enum_proto) {
+ $file->addEnumType(
+ EnumDescriptor::buildFromProto(
+ $enum_proto,
+ $proto,
+ ""));
+ }
+ return $file;
+ }
+}
diff --git a/php/src/Google/Protobuf/Internal/FileDescriptorProto.php b/php/src/Google/Protobuf/Internal/FileDescriptorProto.php
index 39f67768..9ee222d1 100644
--- a/php/src/Google/Protobuf/Internal/FileDescriptorProto.php
+++ b/php/src/Google/Protobuf/Internal/FileDescriptorProto.php
@@ -8,112 +8,93 @@ use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\GPBWire;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\InputStream;
-
use Google\Protobuf\Internal\GPBUtil;
/**
- * <pre>
* Describes a complete .proto file.
- * </pre>
*
- * Protobuf type <code>google.protobuf.FileDescriptorProto</code>
+ * Generated from protobuf message <code>google.protobuf.FileDescriptorProto</code>
*/
class FileDescriptorProto extends \Google\Protobuf\Internal\Message
{
/**
- * <pre>
* file name, relative to root of source tree
- * </pre>
*
- * <code>optional string name = 1;</code>
+ * Generated from protobuf field <code>optional string name = 1;</code>
*/
private $name = '';
private $has_name = false;
/**
- * <pre>
* e.g. "foo", "foo.bar", etc.
- * </pre>
*
- * <code>optional string package = 2;</code>
+ * Generated from protobuf field <code>optional string package = 2;</code>
*/
private $package = '';
private $has_package = false;
/**
- * <pre>
* Names of files imported by this file.
- * </pre>
*
- * <code>repeated string dependency = 3;</code>
+ * Generated from protobuf field <code>repeated string dependency = 3;</code>
*/
private $dependency;
private $has_dependency = false;
/**
- * <pre>
* Indexes of the public imported files in the dependency list above.
- * </pre>
*
- * <code>repeated int32 public_dependency = 10;</code>
+ * Generated from protobuf field <code>repeated int32 public_dependency = 10;</code>
*/
private $public_dependency;
private $has_public_dependency = false;
/**
- * <pre>
* Indexes of the weak imported files in the dependency list.
* For Google-internal migration only. Do not use.
- * </pre>
*
- * <code>repeated int32 weak_dependency = 11;</code>
+ * Generated from protobuf field <code>repeated int32 weak_dependency = 11;</code>
*/
private $weak_dependency;
private $has_weak_dependency = false;
/**
- * <pre>
* All top-level definitions in this file.
- * </pre>
*
- * <code>repeated .google.protobuf.DescriptorProto message_type = 4;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.DescriptorProto message_type = 4;</code>
*/
private $message_type;
private $has_message_type = false;
/**
- * <code>repeated .google.protobuf.EnumDescriptorProto enum_type = 5;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.EnumDescriptorProto enum_type = 5;</code>
*/
private $enum_type;
private $has_enum_type = false;
/**
- * <code>repeated .google.protobuf.ServiceDescriptorProto service = 6;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.ServiceDescriptorProto service = 6;</code>
*/
private $service;
private $has_service = false;
/**
- * <code>repeated .google.protobuf.FieldDescriptorProto extension = 7;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.FieldDescriptorProto extension = 7;</code>
*/
private $extension;
private $has_extension = false;
/**
- * <code>optional .google.protobuf.FileOptions options = 8;</code>
+ * Generated from protobuf field <code>optional .google.protobuf.FileOptions options = 8;</code>
*/
private $options = null;
private $has_options = false;
/**
- * <pre>
* This field contains optional information about the original source code.
* You may safely remove this entire field without harming runtime
* functionality of the descriptors -- the information is needed only by
* development tools.
- * </pre>
*
- * <code>optional .google.protobuf.SourceCodeInfo source_code_info = 9;</code>
+ * Generated from protobuf field <code>optional .google.protobuf.SourceCodeInfo source_code_info = 9;</code>
*/
private $source_code_info = null;
private $has_source_code_info = false;
/**
- * <pre>
* The syntax of the proto file.
* The supported values are "proto2" and "proto3".
- * </pre>
*
- * <code>optional string syntax = 12;</code>
+ * Generated from protobuf field <code>optional string syntax = 12;</code>
*/
private $syntax = '';
private $has_syntax = false;
@@ -124,11 +105,10 @@ class FileDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* file name, relative to root of source tree
- * </pre>
*
- * <code>optional string name = 1;</code>
+ * Generated from protobuf field <code>optional string name = 1;</code>
+ * @return string
*/
public function getName()
{
@@ -136,17 +116,19 @@ class FileDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* file name, relative to root of source tree
- * </pre>
*
- * <code>optional string name = 1;</code>
+ * Generated from protobuf field <code>optional string name = 1;</code>
+ * @param string $var
+ * @return $this
*/
public function setName($var)
{
GPBUtil::checkString($var, True);
$this->name = $var;
$this->has_name = true;
+
+ return $this;
}
public function hasName()
@@ -155,11 +137,10 @@ class FileDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* e.g. "foo", "foo.bar", etc.
- * </pre>
*
- * <code>optional string package = 2;</code>
+ * Generated from protobuf field <code>optional string package = 2;</code>
+ * @return string
*/
public function getPackage()
{
@@ -167,17 +148,19 @@ class FileDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* e.g. "foo", "foo.bar", etc.
- * </pre>
*
- * <code>optional string package = 2;</code>
+ * Generated from protobuf field <code>optional string package = 2;</code>
+ * @param string $var
+ * @return $this
*/
public function setPackage($var)
{
GPBUtil::checkString($var, True);
$this->package = $var;
$this->has_package = true;
+
+ return $this;
}
public function hasPackage()
@@ -186,11 +169,10 @@ class FileDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Names of files imported by this file.
- * </pre>
*
- * <code>repeated string dependency = 3;</code>
+ * Generated from protobuf field <code>repeated string dependency = 3;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
*/
public function getDependency()
{
@@ -198,17 +180,19 @@ class FileDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Names of files imported by this file.
- * </pre>
*
- * <code>repeated string dependency = 3;</code>
+ * Generated from protobuf field <code>repeated string dependency = 3;</code>
+ * @param string[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
*/
- public function setDependency(&$var)
+ public function setDependency($var)
{
- GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::STRING);
- $this->dependency = $var;
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::STRING);
+ $this->dependency = $arr;
$this->has_dependency = true;
+
+ return $this;
}
public function hasDependency()
@@ -217,11 +201,10 @@ class FileDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Indexes of the public imported files in the dependency list above.
- * </pre>
*
- * <code>repeated int32 public_dependency = 10;</code>
+ * Generated from protobuf field <code>repeated int32 public_dependency = 10;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
*/
public function getPublicDependency()
{
@@ -229,17 +212,19 @@ class FileDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Indexes of the public imported files in the dependency list above.
- * </pre>
*
- * <code>repeated int32 public_dependency = 10;</code>
+ * Generated from protobuf field <code>repeated int32 public_dependency = 10;</code>
+ * @param int[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
*/
- public function setPublicDependency(&$var)
+ public function setPublicDependency($var)
{
- GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::INT32);
- $this->public_dependency = $var;
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::INT32);
+ $this->public_dependency = $arr;
$this->has_public_dependency = true;
+
+ return $this;
}
public function hasPublicDependency()
@@ -248,12 +233,11 @@ class FileDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Indexes of the weak imported files in the dependency list.
* For Google-internal migration only. Do not use.
- * </pre>
*
- * <code>repeated int32 weak_dependency = 11;</code>
+ * Generated from protobuf field <code>repeated int32 weak_dependency = 11;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
*/
public function getWeakDependency()
{
@@ -261,18 +245,20 @@ class FileDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Indexes of the weak imported files in the dependency list.
* For Google-internal migration only. Do not use.
- * </pre>
*
- * <code>repeated int32 weak_dependency = 11;</code>
+ * Generated from protobuf field <code>repeated int32 weak_dependency = 11;</code>
+ * @param int[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
*/
- public function setWeakDependency(&$var)
+ public function setWeakDependency($var)
{
- GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::INT32);
- $this->weak_dependency = $var;
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::INT32);
+ $this->weak_dependency = $arr;
$this->has_weak_dependency = true;
+
+ return $this;
}
public function hasWeakDependency()
@@ -281,11 +267,10 @@ class FileDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* All top-level definitions in this file.
- * </pre>
*
- * <code>repeated .google.protobuf.DescriptorProto message_type = 4;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.DescriptorProto message_type = 4;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
*/
public function getMessageType()
{
@@ -293,17 +278,19 @@ class FileDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* All top-level definitions in this file.
- * </pre>
*
- * <code>repeated .google.protobuf.DescriptorProto message_type = 4;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.DescriptorProto message_type = 4;</code>
+ * @param \Google\Protobuf\Internal\DescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
*/
- public function setMessageType(&$var)
+ public function setMessageType($var)
{
- GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\DescriptorProto::class);
- $this->message_type = $var;
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\DescriptorProto::class);
+ $this->message_type = $arr;
$this->has_message_type = true;
+
+ return $this;
}
public function hasMessageType()
@@ -312,7 +299,8 @@ class FileDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>repeated .google.protobuf.EnumDescriptorProto enum_type = 5;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.EnumDescriptorProto enum_type = 5;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
*/
public function getEnumType()
{
@@ -320,13 +308,17 @@ class FileDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>repeated .google.protobuf.EnumDescriptorProto enum_type = 5;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.EnumDescriptorProto enum_type = 5;</code>
+ * @param \Google\Protobuf\Internal\EnumDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
*/
- public function setEnumType(&$var)
+ public function setEnumType($var)
{
- GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\EnumDescriptorProto::class);
- $this->enum_type = $var;
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\EnumDescriptorProto::class);
+ $this->enum_type = $arr;
$this->has_enum_type = true;
+
+ return $this;
}
public function hasEnumType()
@@ -335,7 +327,8 @@ class FileDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>repeated .google.protobuf.ServiceDescriptorProto service = 6;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.ServiceDescriptorProto service = 6;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
*/
public function getService()
{
@@ -343,13 +336,17 @@ class FileDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>repeated .google.protobuf.ServiceDescriptorProto service = 6;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.ServiceDescriptorProto service = 6;</code>
+ * @param \Google\Protobuf\Internal\ServiceDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
*/
- public function setService(&$var)
+ public function setService($var)
{
- GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\ServiceDescriptorProto::class);
- $this->service = $var;
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\ServiceDescriptorProto::class);
+ $this->service = $arr;
$this->has_service = true;
+
+ return $this;
}
public function hasService()
@@ -358,7 +355,8 @@ class FileDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>repeated .google.protobuf.FieldDescriptorProto extension = 7;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.FieldDescriptorProto extension = 7;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
*/
public function getExtension()
{
@@ -366,13 +364,17 @@ class FileDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>repeated .google.protobuf.FieldDescriptorProto extension = 7;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.FieldDescriptorProto extension = 7;</code>
+ * @param \Google\Protobuf\Internal\FieldDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
*/
- public function setExtension(&$var)
+ public function setExtension($var)
{
- GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\FieldDescriptorProto::class);
- $this->extension = $var;
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\FieldDescriptorProto::class);
+ $this->extension = $arr;
$this->has_extension = true;
+
+ return $this;
}
public function hasExtension()
@@ -381,7 +383,8 @@ class FileDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional .google.protobuf.FileOptions options = 8;</code>
+ * Generated from protobuf field <code>optional .google.protobuf.FileOptions options = 8;</code>
+ * @return \Google\Protobuf\Internal\FileOptions
*/
public function getOptions()
{
@@ -389,13 +392,17 @@ class FileDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional .google.protobuf.FileOptions options = 8;</code>
+ * Generated from protobuf field <code>optional .google.protobuf.FileOptions options = 8;</code>
+ * @param \Google\Protobuf\Internal\FileOptions $var
+ * @return $this
*/
- public function setOptions(&$var)
+ public function setOptions($var)
{
GPBUtil::checkMessage($var, \Google\Protobuf\Internal\FileOptions::class);
$this->options = $var;
$this->has_options = true;
+
+ return $this;
}
public function hasOptions()
@@ -404,14 +411,13 @@ class FileDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* This field contains optional information about the original source code.
* You may safely remove this entire field without harming runtime
* functionality of the descriptors -- the information is needed only by
* development tools.
- * </pre>
*
- * <code>optional .google.protobuf.SourceCodeInfo source_code_info = 9;</code>
+ * Generated from protobuf field <code>optional .google.protobuf.SourceCodeInfo source_code_info = 9;</code>
+ * @return \Google\Protobuf\Internal\SourceCodeInfo
*/
public function getSourceCodeInfo()
{
@@ -419,20 +425,22 @@ class FileDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* This field contains optional information about the original source code.
* You may safely remove this entire field without harming runtime
* functionality of the descriptors -- the information is needed only by
* development tools.
- * </pre>
*
- * <code>optional .google.protobuf.SourceCodeInfo source_code_info = 9;</code>
+ * Generated from protobuf field <code>optional .google.protobuf.SourceCodeInfo source_code_info = 9;</code>
+ * @param \Google\Protobuf\Internal\SourceCodeInfo $var
+ * @return $this
*/
- public function setSourceCodeInfo(&$var)
+ public function setSourceCodeInfo($var)
{
GPBUtil::checkMessage($var, \Google\Protobuf\Internal\SourceCodeInfo::class);
$this->source_code_info = $var;
$this->has_source_code_info = true;
+
+ return $this;
}
public function hasSourceCodeInfo()
@@ -441,12 +449,11 @@ class FileDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* The syntax of the proto file.
* The supported values are "proto2" and "proto3".
- * </pre>
*
- * <code>optional string syntax = 12;</code>
+ * Generated from protobuf field <code>optional string syntax = 12;</code>
+ * @return string
*/
public function getSyntax()
{
@@ -454,18 +461,20 @@ class FileDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* The syntax of the proto file.
* The supported values are "proto2" and "proto3".
- * </pre>
*
- * <code>optional string syntax = 12;</code>
+ * Generated from protobuf field <code>optional string syntax = 12;</code>
+ * @param string $var
+ * @return $this
*/
public function setSyntax($var)
{
GPBUtil::checkString($var, True);
$this->syntax = $var;
$this->has_syntax = true;
+
+ return $this;
}
public function hasSyntax()
diff --git a/php/src/Google/Protobuf/Internal/FileDescriptorSet.php b/php/src/Google/Protobuf/Internal/FileDescriptorSet.php
index 20a165c4..0b2cf957 100644
--- a/php/src/Google/Protobuf/Internal/FileDescriptorSet.php
+++ b/php/src/Google/Protobuf/Internal/FileDescriptorSet.php
@@ -8,21 +8,18 @@ use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\GPBWire;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\InputStream;
-
use Google\Protobuf\Internal\GPBUtil;
/**
- * <pre>
* The protocol compiler can output a FileDescriptorSet containing the .proto
* files it parses.
- * </pre>
*
- * Protobuf type <code>google.protobuf.FileDescriptorSet</code>
+ * Generated from protobuf message <code>google.protobuf.FileDescriptorSet</code>
*/
class FileDescriptorSet extends \Google\Protobuf\Internal\Message
{
/**
- * <code>repeated .google.protobuf.FileDescriptorProto file = 1;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.FileDescriptorProto file = 1;</code>
*/
private $file;
private $has_file = false;
@@ -33,7 +30,8 @@ class FileDescriptorSet extends \Google\Protobuf\Internal\Message
}
/**
- * <code>repeated .google.protobuf.FileDescriptorProto file = 1;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.FileDescriptorProto file = 1;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
*/
public function getFile()
{
@@ -41,13 +39,17 @@ class FileDescriptorSet extends \Google\Protobuf\Internal\Message
}
/**
- * <code>repeated .google.protobuf.FileDescriptorProto file = 1;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.FileDescriptorProto file = 1;</code>
+ * @param \Google\Protobuf\Internal\FileDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
*/
- public function setFile(&$var)
+ public function setFile($var)
{
- GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\FileDescriptorProto::class);
- $this->file = $var;
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\FileDescriptorProto::class);
+ $this->file = $arr;
$this->has_file = true;
+
+ return $this;
}
public function hasFile()
diff --git a/php/src/Google/Protobuf/Internal/FileOptions.php b/php/src/Google/Protobuf/Internal/FileOptions.php
index 2422f3ee..f3bacad6 100644
--- a/php/src/Google/Protobuf/Internal/FileOptions.php
+++ b/php/src/Google/Protobuf/Internal/FileOptions.php
@@ -8,96 +8,82 @@ use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\GPBWire;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\InputStream;
-
use Google\Protobuf\Internal\GPBUtil;
/**
- * Protobuf type <code>google.protobuf.FileOptions</code>
+ * Generated from protobuf message <code>google.protobuf.FileOptions</code>
*/
class FileOptions extends \Google\Protobuf\Internal\Message
{
/**
- * <pre>
* Sets the Java package where classes generated from this .proto will be
* placed. By default, the proto package is used, but this is often
* inappropriate because proto packages do not normally start with backwards
* domain names.
- * </pre>
*
- * <code>optional string java_package = 1;</code>
+ * Generated from protobuf field <code>optional string java_package = 1;</code>
*/
private $java_package = '';
private $has_java_package = false;
/**
- * <pre>
* If set, all the classes from the .proto file are wrapped in a single
* outer class with the given name. This applies to both Proto1
* (equivalent to the old "--one_java_file" option) and Proto2 (where
* a .proto always translates to a single class, but you may want to
* explicitly choose the class name).
- * </pre>
*
- * <code>optional string java_outer_classname = 8;</code>
+ * Generated from protobuf field <code>optional string java_outer_classname = 8;</code>
*/
private $java_outer_classname = '';
private $has_java_outer_classname = false;
/**
- * <pre>
* If set true, then the Java code generator will generate a separate .java
* file for each top-level message, enum, and service defined in the .proto
* file. Thus, these types will *not* be nested inside the outer class
* named by java_outer_classname. However, the outer class will still be
* generated to contain the file's getDescriptor() method as well as any
* top-level extensions defined in the file.
- * </pre>
*
- * <code>optional bool java_multiple_files = 10 [default = false];</code>
+ * Generated from protobuf field <code>optional bool java_multiple_files = 10 [default = false];</code>
*/
private $java_multiple_files = false;
private $has_java_multiple_files = false;
/**
- * <pre>
* This option does nothing.
- * </pre>
*
- * <code>optional bool java_generate_equals_and_hash = 20 [deprecated = true];</code>
+ * Generated from protobuf field <code>optional bool java_generate_equals_and_hash = 20 [deprecated = true];</code>
*/
private $java_generate_equals_and_hash = false;
private $has_java_generate_equals_and_hash = false;
/**
- * <pre>
* If set true, then the Java2 code generator will generate code that
* throws an exception whenever an attempt is made to assign a non-UTF-8
* byte sequence to a string field.
* Message reflection will do the same.
* However, an extension field still accepts non-UTF-8 byte sequences.
* This option has no effect on when used with the lite runtime.
- * </pre>
*
- * <code>optional bool java_string_check_utf8 = 27 [default = false];</code>
+ * Generated from protobuf field <code>optional bool java_string_check_utf8 = 27 [default = false];</code>
*/
private $java_string_check_utf8 = false;
private $has_java_string_check_utf8 = false;
/**
- * <code>optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED];</code>
+ * Generated from protobuf field <code>optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED];</code>
*/
private $optimize_for = 0;
private $has_optimize_for = false;
/**
- * <pre>
* Sets the Go package where structs generated from this .proto will be
* placed. If omitted, the Go package will be derived from the following:
* - The basename of the package import path, if provided.
* - Otherwise, the package statement in the .proto file, if present.
* - Otherwise, the basename of the .proto file, without extension.
- * </pre>
*
- * <code>optional string go_package = 11;</code>
+ * Generated from protobuf field <code>optional string go_package = 11;</code>
*/
private $go_package = '';
private $has_go_package = false;
/**
- * <pre>
* Should generic services be generated in each language? "Generic" services
* are not specific to any particular RPC system. They are generated by the
* main code generators in each language (without additional plugins).
@@ -107,81 +93,91 @@ class FileOptions extends \Google\Protobuf\Internal\Message
* that generate code specific to your particular RPC system. Therefore,
* these default to false. Old code which depends on generic services should
* explicitly set them to true.
- * </pre>
*
- * <code>optional bool cc_generic_services = 16 [default = false];</code>
+ * Generated from protobuf field <code>optional bool cc_generic_services = 16 [default = false];</code>
*/
private $cc_generic_services = false;
private $has_cc_generic_services = false;
/**
- * <code>optional bool java_generic_services = 17 [default = false];</code>
+ * Generated from protobuf field <code>optional bool java_generic_services = 17 [default = false];</code>
*/
private $java_generic_services = false;
private $has_java_generic_services = false;
/**
- * <code>optional bool py_generic_services = 18 [default = false];</code>
+ * Generated from protobuf field <code>optional bool py_generic_services = 18 [default = false];</code>
*/
private $py_generic_services = false;
private $has_py_generic_services = false;
/**
- * <pre>
+ * Generated from protobuf field <code>optional bool php_generic_services = 42 [default = false];</code>
+ */
+ private $php_generic_services = false;
+ private $has_php_generic_services = false;
+ /**
* Is this file deprecated?
* Depending on the target platform, this can emit Deprecated annotations
* for everything in the file, or it will be completely ignored; in the very
* least, this is a formalization for deprecating files.
- * </pre>
*
- * <code>optional bool deprecated = 23 [default = false];</code>
+ * Generated from protobuf field <code>optional bool deprecated = 23 [default = false];</code>
*/
private $deprecated = false;
private $has_deprecated = false;
/**
- * <pre>
* Enables the use of arenas for the proto messages in this file. This applies
* only to generated classes for C++.
- * </pre>
*
- * <code>optional bool cc_enable_arenas = 31 [default = false];</code>
+ * Generated from protobuf field <code>optional bool cc_enable_arenas = 31 [default = false];</code>
*/
private $cc_enable_arenas = false;
private $has_cc_enable_arenas = false;
/**
- * <pre>
* Sets the objective c class prefix which is prepended to all objective c
* generated classes from this .proto. There is no default.
- * </pre>
*
- * <code>optional string objc_class_prefix = 36;</code>
+ * Generated from protobuf field <code>optional string objc_class_prefix = 36;</code>
*/
private $objc_class_prefix = '';
private $has_objc_class_prefix = false;
/**
- * <pre>
* Namespace for generated classes; defaults to the package.
- * </pre>
*
- * <code>optional string csharp_namespace = 37;</code>
+ * Generated from protobuf field <code>optional string csharp_namespace = 37;</code>
*/
private $csharp_namespace = '';
private $has_csharp_namespace = false;
/**
- * <pre>
* By default Swift generators will take the proto package and CamelCase it
* replacing '.' with underscore and use that to prefix the types/symbols
* defined. When this options is provided, they will use this value instead
* to prefix the types/symbols defined.
- * </pre>
*
- * <code>optional string swift_prefix = 39;</code>
+ * Generated from protobuf field <code>optional string swift_prefix = 39;</code>
*/
private $swift_prefix = '';
private $has_swift_prefix = false;
/**
- * <pre>
- * The parser stores options it doesn't recognize here. See above.
- * </pre>
+ * Sets the php class prefix which is prepended to all php generated classes
+ * from this .proto. Default is empty.
+ *
+ * Generated from protobuf field <code>optional string php_class_prefix = 40;</code>
+ */
+ private $php_class_prefix = '';
+ private $has_php_class_prefix = false;
+ /**
+ * Use this option to change the namespace of php generated classes. Default
+ * is empty. When this option is empty, the package name will be used for
+ * determining the namespace.
*
- * <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * Generated from protobuf field <code>optional string php_namespace = 41;</code>
+ */
+ private $php_namespace = '';
+ private $has_php_namespace = false;
+ /**
+ * The parser stores options it doesn't recognize here.
+ * See the documentation for the "Options" section above.
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
*/
private $uninterpreted_option;
private $has_uninterpreted_option = false;
@@ -192,14 +188,13 @@ class FileOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Sets the Java package where classes generated from this .proto will be
* placed. By default, the proto package is used, but this is often
* inappropriate because proto packages do not normally start with backwards
* domain names.
- * </pre>
*
- * <code>optional string java_package = 1;</code>
+ * Generated from protobuf field <code>optional string java_package = 1;</code>
+ * @return string
*/
public function getJavaPackage()
{
@@ -207,20 +202,22 @@ class FileOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Sets the Java package where classes generated from this .proto will be
* placed. By default, the proto package is used, but this is often
* inappropriate because proto packages do not normally start with backwards
* domain names.
- * </pre>
*
- * <code>optional string java_package = 1;</code>
+ * Generated from protobuf field <code>optional string java_package = 1;</code>
+ * @param string $var
+ * @return $this
*/
public function setJavaPackage($var)
{
GPBUtil::checkString($var, True);
$this->java_package = $var;
$this->has_java_package = true;
+
+ return $this;
}
public function hasJavaPackage()
@@ -229,15 +226,14 @@ class FileOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* If set, all the classes from the .proto file are wrapped in a single
* outer class with the given name. This applies to both Proto1
* (equivalent to the old "--one_java_file" option) and Proto2 (where
* a .proto always translates to a single class, but you may want to
* explicitly choose the class name).
- * </pre>
*
- * <code>optional string java_outer_classname = 8;</code>
+ * Generated from protobuf field <code>optional string java_outer_classname = 8;</code>
+ * @return string
*/
public function getJavaOuterClassname()
{
@@ -245,21 +241,23 @@ class FileOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* If set, all the classes from the .proto file are wrapped in a single
* outer class with the given name. This applies to both Proto1
* (equivalent to the old "--one_java_file" option) and Proto2 (where
* a .proto always translates to a single class, but you may want to
* explicitly choose the class name).
- * </pre>
*
- * <code>optional string java_outer_classname = 8;</code>
+ * Generated from protobuf field <code>optional string java_outer_classname = 8;</code>
+ * @param string $var
+ * @return $this
*/
public function setJavaOuterClassname($var)
{
GPBUtil::checkString($var, True);
$this->java_outer_classname = $var;
$this->has_java_outer_classname = true;
+
+ return $this;
}
public function hasJavaOuterClassname()
@@ -268,16 +266,15 @@ class FileOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* If set true, then the Java code generator will generate a separate .java
* file for each top-level message, enum, and service defined in the .proto
* file. Thus, these types will *not* be nested inside the outer class
* named by java_outer_classname. However, the outer class will still be
* generated to contain the file's getDescriptor() method as well as any
* top-level extensions defined in the file.
- * </pre>
*
- * <code>optional bool java_multiple_files = 10 [default = false];</code>
+ * Generated from protobuf field <code>optional bool java_multiple_files = 10 [default = false];</code>
+ * @return bool
*/
public function getJavaMultipleFiles()
{
@@ -285,22 +282,24 @@ class FileOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* If set true, then the Java code generator will generate a separate .java
* file for each top-level message, enum, and service defined in the .proto
* file. Thus, these types will *not* be nested inside the outer class
* named by java_outer_classname. However, the outer class will still be
* generated to contain the file's getDescriptor() method as well as any
* top-level extensions defined in the file.
- * </pre>
*
- * <code>optional bool java_multiple_files = 10 [default = false];</code>
+ * Generated from protobuf field <code>optional bool java_multiple_files = 10 [default = false];</code>
+ * @param bool $var
+ * @return $this
*/
public function setJavaMultipleFiles($var)
{
GPBUtil::checkBool($var);
$this->java_multiple_files = $var;
$this->has_java_multiple_files = true;
+
+ return $this;
}
public function hasJavaMultipleFiles()
@@ -309,11 +308,10 @@ class FileOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* This option does nothing.
- * </pre>
*
- * <code>optional bool java_generate_equals_and_hash = 20 [deprecated = true];</code>
+ * Generated from protobuf field <code>optional bool java_generate_equals_and_hash = 20 [deprecated = true];</code>
+ * @return bool
*/
public function getJavaGenerateEqualsAndHash()
{
@@ -321,17 +319,19 @@ class FileOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* This option does nothing.
- * </pre>
*
- * <code>optional bool java_generate_equals_and_hash = 20 [deprecated = true];</code>
+ * Generated from protobuf field <code>optional bool java_generate_equals_and_hash = 20 [deprecated = true];</code>
+ * @param bool $var
+ * @return $this
*/
public function setJavaGenerateEqualsAndHash($var)
{
GPBUtil::checkBool($var);
$this->java_generate_equals_and_hash = $var;
$this->has_java_generate_equals_and_hash = true;
+
+ return $this;
}
public function hasJavaGenerateEqualsAndHash()
@@ -340,16 +340,15 @@ class FileOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* If set true, then the Java2 code generator will generate code that
* throws an exception whenever an attempt is made to assign a non-UTF-8
* byte sequence to a string field.
* Message reflection will do the same.
* However, an extension field still accepts non-UTF-8 byte sequences.
* This option has no effect on when used with the lite runtime.
- * </pre>
*
- * <code>optional bool java_string_check_utf8 = 27 [default = false];</code>
+ * Generated from protobuf field <code>optional bool java_string_check_utf8 = 27 [default = false];</code>
+ * @return bool
*/
public function getJavaStringCheckUtf8()
{
@@ -357,22 +356,24 @@ class FileOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* If set true, then the Java2 code generator will generate code that
* throws an exception whenever an attempt is made to assign a non-UTF-8
* byte sequence to a string field.
* Message reflection will do the same.
* However, an extension field still accepts non-UTF-8 byte sequences.
* This option has no effect on when used with the lite runtime.
- * </pre>
*
- * <code>optional bool java_string_check_utf8 = 27 [default = false];</code>
+ * Generated from protobuf field <code>optional bool java_string_check_utf8 = 27 [default = false];</code>
+ * @param bool $var
+ * @return $this
*/
public function setJavaStringCheckUtf8($var)
{
GPBUtil::checkBool($var);
$this->java_string_check_utf8 = $var;
$this->has_java_string_check_utf8 = true;
+
+ return $this;
}
public function hasJavaStringCheckUtf8()
@@ -381,7 +382,8 @@ class FileOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED];</code>
+ * Generated from protobuf field <code>optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED];</code>
+ * @return int
*/
public function getOptimizeFor()
{
@@ -389,13 +391,17 @@ class FileOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED];</code>
+ * Generated from protobuf field <code>optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED];</code>
+ * @param int $var
+ * @return $this
*/
public function setOptimizeFor($var)
{
GPBUtil::checkEnum($var, \Google\Protobuf\Internal\FileOptions_OptimizeMode::class);
$this->optimize_for = $var;
$this->has_optimize_for = true;
+
+ return $this;
}
public function hasOptimizeFor()
@@ -404,15 +410,14 @@ class FileOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Sets the Go package where structs generated from this .proto will be
* placed. If omitted, the Go package will be derived from the following:
* - The basename of the package import path, if provided.
* - Otherwise, the package statement in the .proto file, if present.
* - Otherwise, the basename of the .proto file, without extension.
- * </pre>
*
- * <code>optional string go_package = 11;</code>
+ * Generated from protobuf field <code>optional string go_package = 11;</code>
+ * @return string
*/
public function getGoPackage()
{
@@ -420,21 +425,23 @@ class FileOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Sets the Go package where structs generated from this .proto will be
* placed. If omitted, the Go package will be derived from the following:
* - The basename of the package import path, if provided.
* - Otherwise, the package statement in the .proto file, if present.
* - Otherwise, the basename of the .proto file, without extension.
- * </pre>
*
- * <code>optional string go_package = 11;</code>
+ * Generated from protobuf field <code>optional string go_package = 11;</code>
+ * @param string $var
+ * @return $this
*/
public function setGoPackage($var)
{
GPBUtil::checkString($var, True);
$this->go_package = $var;
$this->has_go_package = true;
+
+ return $this;
}
public function hasGoPackage()
@@ -443,7 +450,6 @@ class FileOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Should generic services be generated in each language? "Generic" services
* are not specific to any particular RPC system. They are generated by the
* main code generators in each language (without additional plugins).
@@ -453,9 +459,9 @@ class FileOptions extends \Google\Protobuf\Internal\Message
* that generate code specific to your particular RPC system. Therefore,
* these default to false. Old code which depends on generic services should
* explicitly set them to true.
- * </pre>
*
- * <code>optional bool cc_generic_services = 16 [default = false];</code>
+ * Generated from protobuf field <code>optional bool cc_generic_services = 16 [default = false];</code>
+ * @return bool
*/
public function getCcGenericServices()
{
@@ -463,7 +469,6 @@ class FileOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Should generic services be generated in each language? "Generic" services
* are not specific to any particular RPC system. They are generated by the
* main code generators in each language (without additional plugins).
@@ -473,15 +478,18 @@ class FileOptions extends \Google\Protobuf\Internal\Message
* that generate code specific to your particular RPC system. Therefore,
* these default to false. Old code which depends on generic services should
* explicitly set them to true.
- * </pre>
*
- * <code>optional bool cc_generic_services = 16 [default = false];</code>
+ * Generated from protobuf field <code>optional bool cc_generic_services = 16 [default = false];</code>
+ * @param bool $var
+ * @return $this
*/
public function setCcGenericServices($var)
{
GPBUtil::checkBool($var);
$this->cc_generic_services = $var;
$this->has_cc_generic_services = true;
+
+ return $this;
}
public function hasCcGenericServices()
@@ -490,7 +498,8 @@ class FileOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional bool java_generic_services = 17 [default = false];</code>
+ * Generated from protobuf field <code>optional bool java_generic_services = 17 [default = false];</code>
+ * @return bool
*/
public function getJavaGenericServices()
{
@@ -498,13 +507,17 @@ class FileOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional bool java_generic_services = 17 [default = false];</code>
+ * Generated from protobuf field <code>optional bool java_generic_services = 17 [default = false];</code>
+ * @param bool $var
+ * @return $this
*/
public function setJavaGenericServices($var)
{
GPBUtil::checkBool($var);
$this->java_generic_services = $var;
$this->has_java_generic_services = true;
+
+ return $this;
}
public function hasJavaGenericServices()
@@ -513,7 +526,8 @@ class FileOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional bool py_generic_services = 18 [default = false];</code>
+ * Generated from protobuf field <code>optional bool py_generic_services = 18 [default = false];</code>
+ * @return bool
*/
public function getPyGenericServices()
{
@@ -521,13 +535,17 @@ class FileOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional bool py_generic_services = 18 [default = false];</code>
+ * Generated from protobuf field <code>optional bool py_generic_services = 18 [default = false];</code>
+ * @param bool $var
+ * @return $this
*/
public function setPyGenericServices($var)
{
GPBUtil::checkBool($var);
$this->py_generic_services = $var;
$this->has_py_generic_services = true;
+
+ return $this;
}
public function hasPyGenericServices()
@@ -536,14 +554,41 @@ class FileOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
+ * Generated from protobuf field <code>optional bool php_generic_services = 42 [default = false];</code>
+ * @return bool
+ */
+ public function getPhpGenericServices()
+ {
+ return $this->php_generic_services;
+ }
+
+ /**
+ * Generated from protobuf field <code>optional bool php_generic_services = 42 [default = false];</code>
+ * @param bool $var
+ * @return $this
+ */
+ public function setPhpGenericServices($var)
+ {
+ GPBUtil::checkBool($var);
+ $this->php_generic_services = $var;
+ $this->has_php_generic_services = true;
+
+ return $this;
+ }
+
+ public function hasPhpGenericServices()
+ {
+ return $this->has_php_generic_services;
+ }
+
+ /**
* Is this file deprecated?
* Depending on the target platform, this can emit Deprecated annotations
* for everything in the file, or it will be completely ignored; in the very
* least, this is a formalization for deprecating files.
- * </pre>
*
- * <code>optional bool deprecated = 23 [default = false];</code>
+ * Generated from protobuf field <code>optional bool deprecated = 23 [default = false];</code>
+ * @return bool
*/
public function getDeprecated()
{
@@ -551,20 +596,22 @@ class FileOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Is this file deprecated?
* Depending on the target platform, this can emit Deprecated annotations
* for everything in the file, or it will be completely ignored; in the very
* least, this is a formalization for deprecating files.
- * </pre>
*
- * <code>optional bool deprecated = 23 [default = false];</code>
+ * Generated from protobuf field <code>optional bool deprecated = 23 [default = false];</code>
+ * @param bool $var
+ * @return $this
*/
public function setDeprecated($var)
{
GPBUtil::checkBool($var);
$this->deprecated = $var;
$this->has_deprecated = true;
+
+ return $this;
}
public function hasDeprecated()
@@ -573,12 +620,11 @@ class FileOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Enables the use of arenas for the proto messages in this file. This applies
* only to generated classes for C++.
- * </pre>
*
- * <code>optional bool cc_enable_arenas = 31 [default = false];</code>
+ * Generated from protobuf field <code>optional bool cc_enable_arenas = 31 [default = false];</code>
+ * @return bool
*/
public function getCcEnableArenas()
{
@@ -586,18 +632,20 @@ class FileOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Enables the use of arenas for the proto messages in this file. This applies
* only to generated classes for C++.
- * </pre>
*
- * <code>optional bool cc_enable_arenas = 31 [default = false];</code>
+ * Generated from protobuf field <code>optional bool cc_enable_arenas = 31 [default = false];</code>
+ * @param bool $var
+ * @return $this
*/
public function setCcEnableArenas($var)
{
GPBUtil::checkBool($var);
$this->cc_enable_arenas = $var;
$this->has_cc_enable_arenas = true;
+
+ return $this;
}
public function hasCcEnableArenas()
@@ -606,12 +654,11 @@ class FileOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Sets the objective c class prefix which is prepended to all objective c
* generated classes from this .proto. There is no default.
- * </pre>
*
- * <code>optional string objc_class_prefix = 36;</code>
+ * Generated from protobuf field <code>optional string objc_class_prefix = 36;</code>
+ * @return string
*/
public function getObjcClassPrefix()
{
@@ -619,18 +666,20 @@ class FileOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Sets the objective c class prefix which is prepended to all objective c
* generated classes from this .proto. There is no default.
- * </pre>
*
- * <code>optional string objc_class_prefix = 36;</code>
+ * Generated from protobuf field <code>optional string objc_class_prefix = 36;</code>
+ * @param string $var
+ * @return $this
*/
public function setObjcClassPrefix($var)
{
GPBUtil::checkString($var, True);
$this->objc_class_prefix = $var;
$this->has_objc_class_prefix = true;
+
+ return $this;
}
public function hasObjcClassPrefix()
@@ -639,11 +688,10 @@ class FileOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Namespace for generated classes; defaults to the package.
- * </pre>
*
- * <code>optional string csharp_namespace = 37;</code>
+ * Generated from protobuf field <code>optional string csharp_namespace = 37;</code>
+ * @return string
*/
public function getCsharpNamespace()
{
@@ -651,17 +699,19 @@ class FileOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Namespace for generated classes; defaults to the package.
- * </pre>
*
- * <code>optional string csharp_namespace = 37;</code>
+ * Generated from protobuf field <code>optional string csharp_namespace = 37;</code>
+ * @param string $var
+ * @return $this
*/
public function setCsharpNamespace($var)
{
GPBUtil::checkString($var, True);
$this->csharp_namespace = $var;
$this->has_csharp_namespace = true;
+
+ return $this;
}
public function hasCsharpNamespace()
@@ -670,14 +720,13 @@ class FileOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* By default Swift generators will take the proto package and CamelCase it
* replacing '.' with underscore and use that to prefix the types/symbols
* defined. When this options is provided, they will use this value instead
* to prefix the types/symbols defined.
- * </pre>
*
- * <code>optional string swift_prefix = 39;</code>
+ * Generated from protobuf field <code>optional string swift_prefix = 39;</code>
+ * @return string
*/
public function getSwiftPrefix()
{
@@ -685,20 +734,22 @@ class FileOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* By default Swift generators will take the proto package and CamelCase it
* replacing '.' with underscore and use that to prefix the types/symbols
* defined. When this options is provided, they will use this value instead
* to prefix the types/symbols defined.
- * </pre>
*
- * <code>optional string swift_prefix = 39;</code>
+ * Generated from protobuf field <code>optional string swift_prefix = 39;</code>
+ * @param string $var
+ * @return $this
*/
public function setSwiftPrefix($var)
{
GPBUtil::checkString($var, True);
$this->swift_prefix = $var;
$this->has_swift_prefix = true;
+
+ return $this;
}
public function hasSwiftPrefix()
@@ -707,11 +758,81 @@ class FileOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
- * The parser stores options it doesn't recognize here. See above.
- * </pre>
+ * Sets the php class prefix which is prepended to all php generated classes
+ * from this .proto. Default is empty.
+ *
+ * Generated from protobuf field <code>optional string php_class_prefix = 40;</code>
+ * @return string
+ */
+ public function getPhpClassPrefix()
+ {
+ return $this->php_class_prefix;
+ }
+
+ /**
+ * Sets the php class prefix which is prepended to all php generated classes
+ * from this .proto. Default is empty.
+ *
+ * Generated from protobuf field <code>optional string php_class_prefix = 40;</code>
+ * @param string $var
+ * @return $this
+ */
+ public function setPhpClassPrefix($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->php_class_prefix = $var;
+ $this->has_php_class_prefix = true;
+
+ return $this;
+ }
+
+ public function hasPhpClassPrefix()
+ {
+ return $this->has_php_class_prefix;
+ }
+
+ /**
+ * Use this option to change the namespace of php generated classes. Default
+ * is empty. When this option is empty, the package name will be used for
+ * determining the namespace.
*
- * <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * Generated from protobuf field <code>optional string php_namespace = 41;</code>
+ * @return string
+ */
+ public function getPhpNamespace()
+ {
+ return $this->php_namespace;
+ }
+
+ /**
+ * Use this option to change the namespace of php generated classes. Default
+ * is empty. When this option is empty, the package name will be used for
+ * determining the namespace.
+ *
+ * Generated from protobuf field <code>optional string php_namespace = 41;</code>
+ * @param string $var
+ * @return $this
+ */
+ public function setPhpNamespace($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->php_namespace = $var;
+ $this->has_php_namespace = true;
+
+ return $this;
+ }
+
+ public function hasPhpNamespace()
+ {
+ return $this->has_php_namespace;
+ }
+
+ /**
+ * The parser stores options it doesn't recognize here.
+ * See the documentation for the "Options" section above.
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
*/
public function getUninterpretedOption()
{
@@ -719,17 +840,20 @@ class FileOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
- * The parser stores options it doesn't recognize here. See above.
- * </pre>
+ * The parser stores options it doesn't recognize here.
+ * See the documentation for the "Options" section above.
*
- * <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * @param \Google\Protobuf\Internal\UninterpretedOption[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
*/
- public function setUninterpretedOption(&$var)
+ public function setUninterpretedOption($var)
{
- GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\UninterpretedOption::class);
- $this->uninterpreted_option = $var;
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\UninterpretedOption::class);
+ $this->uninterpreted_option = $arr;
$this->has_uninterpreted_option = true;
+
+ return $this;
}
public function hasUninterpretedOption()
diff --git a/php/src/Google/Protobuf/Internal/FileOptions_OptimizeMode.php b/php/src/Google/Protobuf/Internal/FileOptions_OptimizeMode.php
index 7fd488eb..4dd56ef8 100644
--- a/php/src/Google/Protobuf/Internal/FileOptions_OptimizeMode.php
+++ b/php/src/Google/Protobuf/Internal/FileOptions_OptimizeMode.php
@@ -2,39 +2,31 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/descriptor.proto
+namespace Google\Protobuf\Internal;
+
/**
- * <pre>
* Generated classes can be optimized for speed or code size.
- * </pre>
*
- * Protobuf enum <code>google.protobuf.FileOptions.OptimizeMode</code>
+ * Protobuf enum <code>Google\Protobuf\Internal</code>
*/
-namespace Google\Protobuf\Internal;
-
class FileOptions_OptimizeMode
{
/**
- * <pre>
* Generate complete code for parsing, serialization,
- * </pre>
*
- * <code>SPEED = 1;</code>
+ * Generated from protobuf enum <code>SPEED = 1;</code>
*/
const SPEED = 1;
/**
- * <pre>
* etc.
- * </pre>
*
- * <code>CODE_SIZE = 2;</code>
+ * Generated from protobuf enum <code>CODE_SIZE = 2;</code>
*/
const CODE_SIZE = 2;
/**
- * <pre>
* Generate code using MessageLite and the lite runtime.
- * </pre>
*
- * <code>LITE_RUNTIME = 3;</code>
+ * Generated from protobuf enum <code>LITE_RUNTIME = 3;</code>
*/
const LITE_RUNTIME = 3;
}
diff --git a/php/src/Google/Protobuf/Internal/GPBDecodeException.php b/php/src/Google/Protobuf/Internal/GPBDecodeException.php
new file mode 100644
index 00000000..402d542f
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/GPBDecodeException.php
@@ -0,0 +1,47 @@
+<?php
+
+// 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.
+
+namespace Google\Protobuf\Internal;
+
+class GPBDecodeException extends \Exception
+{
+ public function __construct(
+ $message,
+ $code = 0,
+ \Exception $previous = null)
+ {
+ parent::__construct(
+ "Error occurred during parsing: " . $message,
+ $code,
+ $previous);
+ }
+}
diff --git a/php/src/Google/Protobuf/Internal/GPBJsonWire.php b/php/src/Google/Protobuf/Internal/GPBJsonWire.php
new file mode 100644
index 00000000..9ae57ab3
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/GPBJsonWire.php
@@ -0,0 +1,304 @@
+<?php
+
+// 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.
+
+namespace Google\Protobuf\Internal;
+
+class GPBJsonWire
+{
+
+ public static function serializeFieldToStream(
+ $value,
+ $field,
+ &$output, $has_field_name = true)
+ {
+ if ($has_field_name) {
+ $output->writeRaw("\"", 1);
+ $field_name = GPBJsonWire::formatFieldName($field);
+ $output->writeRaw($field_name, strlen($field_name));
+ $output->writeRaw("\":", 2);
+ }
+ return static::serializeFieldValueToStream(
+ $value,
+ $field,
+ $output,
+ !$has_field_name);
+ }
+
+ public static function serializeFieldValueToStream(
+ $values,
+ $field,
+ &$output,
+ $is_well_known = false)
+ {
+ if ($field->isMap()) {
+ $output->writeRaw("{", 1);
+ $first = true;
+ $map_entry = $field->getMessageType();
+ $key_field = $map_entry->getFieldByNumber(1);
+ $value_field = $map_entry->getFieldByNumber(2);
+
+ switch ($key_field->getType()) {
+ case GPBType::STRING:
+ case GPBType::SFIXED64:
+ case GPBType::INT64:
+ case GPBType::SINT64:
+ case GPBType::FIXED64:
+ case GPBType::UINT64:
+ $additional_quote = false;
+ break;
+ default:
+ $additional_quote = true;
+ }
+
+ foreach ($values as $key => $value) {
+ if ($first) {
+ $first = false;
+ } else {
+ $output->writeRaw(",", 1);
+ }
+ if ($additional_quote) {
+ $output->writeRaw("\"", 1);
+ }
+ if (!static::serializeSingularFieldValueToStream(
+ $key,
+ $key_field,
+ $output,
+ $is_well_known)) {
+ return false;
+ }
+ if ($additional_quote) {
+ $output->writeRaw("\"", 1);
+ }
+ $output->writeRaw(":", 1);
+ if (!static::serializeSingularFieldValueToStream(
+ $value,
+ $value_field,
+ $output,
+ $is_well_known)) {
+ return false;
+ }
+ }
+ $output->writeRaw("}", 1);
+ return true;
+ } elseif ($field->isRepeated()) {
+ $output->writeRaw("[", 1);
+ $first = true;
+ foreach ($values as $value) {
+ if ($first) {
+ $first = false;
+ } else {
+ $output->writeRaw(",", 1);
+ }
+ if (!static::serializeSingularFieldValueToStream(
+ $value,
+ $field,
+ $output,
+ $is_well_known)) {
+ return false;
+ }
+ }
+ $output->writeRaw("]", 1);
+ return true;
+ } else {
+ return static::serializeSingularFieldValueToStream(
+ $values,
+ $field,
+ $output,
+ $is_well_known);
+ }
+ }
+
+ private static function serializeSingularFieldValueToStream(
+ $value,
+ $field,
+ &$output, $is_well_known = false)
+ {
+ switch ($field->getType()) {
+ case GPBType::SFIXED32:
+ case GPBType::SINT32:
+ case GPBType::INT32:
+ $str_value = strval($value);
+ $output->writeRaw($str_value, strlen($str_value));
+ break;
+ case GPBType::FIXED32:
+ case GPBType::UINT32:
+ if ($value < 0) {
+ $value = bcadd($value, "4294967296");
+ }
+ $str_value = strval($value);
+ $output->writeRaw($str_value, strlen($str_value));
+ break;
+ case GPBType::FIXED64:
+ case GPBType::UINT64:
+ if ($value < 0) {
+ $value = bcadd($value, "18446744073709551616");
+ }
+ // Intentional fall through.
+ case GPBType::SFIXED64:
+ case GPBType::INT64:
+ case GPBType::SINT64:
+ $output->writeRaw("\"", 1);
+ $str_value = strval($value);
+ $output->writeRaw($str_value, strlen($str_value));
+ $output->writeRaw("\"", 1);
+ break;
+ case GPBType::FLOAT:
+ if (is_nan($value)) {
+ $str_value = "\"NaN\"";
+ } elseif ($value === INF) {
+ $str_value = "\"Infinity\"";
+ } elseif ($value === -INF) {
+ $str_value = "\"-Infinity\"";
+ } else {
+ $str_value = sprintf("%.8g", $value);
+ }
+ $output->writeRaw($str_value, strlen($str_value));
+ break;
+ case GPBType::DOUBLE:
+ if (is_nan($value)) {
+ $str_value = "\"NaN\"";
+ } elseif ($value === INF) {
+ $str_value = "\"Infinity\"";
+ } elseif ($value === -INF) {
+ $str_value = "\"-Infinity\"";
+ } else {
+ $str_value = sprintf("%.17g", $value);
+ }
+ $output->writeRaw($str_value, strlen($str_value));
+ break;
+ case GPBType::ENUM:
+ $enum_desc = $field->getEnumType();
+ if ($enum_desc->getClass() === "Google\Protobuf\NullValue") {
+ $output->writeRaw("null", 4);
+ break;
+ }
+ $enum_value_desc = $enum_desc->getValueByNumber($value);
+ if (!is_null($enum_value_desc)) {
+ $str_value = $enum_value_desc->getName();
+ $output->writeRaw("\"", 1);
+ $output->writeRaw($str_value, strlen($str_value));
+ $output->writeRaw("\"", 1);
+ } else {
+ $str_value = strval($value);
+ $output->writeRaw($str_value, strlen($str_value));
+ }
+ break;
+ case GPBType::BOOL:
+ if ($value) {
+ $output->writeRaw("true", 4);
+ } else {
+ $output->writeRaw("false", 5);
+ }
+ break;
+ case GPBType::BYTES:
+ $bytes_value = base64_encode($value);
+ $output->writeRaw("\"", 1);
+ $output->writeRaw($bytes_value, strlen($bytes_value));
+ $output->writeRaw("\"", 1);
+ break;
+ case GPBType::STRING:
+ $value = json_encode($value);
+ $output->writeRaw($value, strlen($value));
+ break;
+ // case GPBType::GROUP:
+ // echo "GROUP\xA";
+ // trigger_error("Not implemented.", E_ERROR);
+ // break;
+ case GPBType::MESSAGE:
+ $value->serializeToJsonStream($output);
+ break;
+ default:
+ user_error("Unsupported type.");
+ return false;
+ }
+ return true;
+ }
+
+ private static function formatFieldName($field)
+ {
+ return $field->getJsonName();
+ }
+
+ // Used for escaping control chars in strings.
+ private static $k_control_char_limit = 0x20;
+
+ private static function jsonNiceEscape($c)
+ {
+ switch ($c) {
+ case '"': return "\\\"";
+ case '\\': return "\\\\";
+ case '/': return "\\/";
+ case '\b': return "\\b";
+ case '\f': return "\\f";
+ case '\n': return "\\n";
+ case '\r': return "\\r";
+ case '\t': return "\\t";
+ default: return NULL;
+ }
+ }
+
+ private static function isJsonEscaped($c)
+ {
+ // See RFC 4627.
+ return $c < chr($k_control_char_limit) || $c === "\"" || $c === "\\";
+ }
+
+ public static function escapedJson($value)
+ {
+ $escaped_value = "";
+ $unescaped_run = "";
+ for ($i = 0; $i < strlen($value); $i++) {
+ $c = $value[$i];
+ // Handle escaping.
+ if (static::isJsonEscaped($c)) {
+ // Use a "nice" escape, like \n, if one exists for this
+ // character.
+ $escape = static::jsonNiceEscape($c);
+ if (is_null($escape)) {
+ $escape = "\\u00" . bin2hex($c);
+ }
+ if ($unescaped_run !== "") {
+ $escaped_value .= $unescaped_run;
+ $unescaped_run = "";
+ }
+ $escaped_value .= $escape;
+ } else {
+ if ($unescaped_run === "") {
+ $unescaped_run .= $c;
+ }
+ }
+ }
+ $escaped_value .= $unescaped_run;
+ return $escaped_value;
+ }
+
+}
diff --git a/php/src/Google/Protobuf/Internal/GPBUtil.php b/php/src/Google/Protobuf/Internal/GPBUtil.php
index 30d7350f..76f84cbd 100644
--- a/php/src/Google/Protobuf/Internal/GPBUtil.php
+++ b/php/src/Google/Protobuf/Internal/GPBUtil.php
@@ -32,25 +32,56 @@
namespace Google\Protobuf\Internal;
+use Google\Protobuf\Duration;
+use Google\Protobuf\FieldMask;
use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\MapField;
+
+function camel2underscore($input) {
+ preg_match_all(
+ '!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!',
+ $input,
+ $matches);
+ $ret = $matches[0];
+ foreach ($ret as &$match) {
+ $match = $match == strtoupper($match) ? strtolower($match) : lcfirst($match);
+ }
+ return implode('_', $ret);
+}
class GPBUtil
{
- public function divideInt64ToInt32($value, &$high, &$low, $trim = false)
+ const NANOS_PER_MILLISECOND = 1000000;
+ const NANOS_PER_MICROSECOND = 1000;
+ const TYPE_URL_PREFIX = 'type.googleapis.com/';
+
+ public static function divideInt64ToInt32($value, &$high, &$low, $trim = false)
{
$isNeg = (bccomp($value, 0) < 0);
if ($isNeg) {
$value = bcsub(0, $value);
}
- $high = (int) bcdiv(bcadd($value, 1), 4294967296);
- $low = (int) bcmod($value, 4294967296);
+
+ $high = bcdiv($value, 4294967296);
+ $low = bcmod($value, 4294967296);
+ if (bccomp($high, 2147483647) > 0) {
+ $high = (int) bcsub($high, 4294967296);
+ } else {
+ $high = (int) $high;
+ }
+ if (bccomp($low, 2147483647) > 0) {
+ $low = (int) bcsub($low, 4294967296);
+ } else {
+ $low = (int) $low;
+ }
+
if ($isNeg) {
$high = ~$high;
$low = ~$low;
$low++;
if (!$low) {
- $high++;
+ $high = (int)($high + 1);
}
}
@@ -59,19 +90,16 @@ class GPBUtil
}
}
-
public static function checkString(&$var, $check_utf8)
{
if (is_array($var) || is_object($var)) {
- trigger_error("Expect string.", E_USER_ERROR);
- return;
+ throw new \InvalidArgumentException("Expect string.");
}
if (!is_string($var)) {
$var = strval($var);
}
if ($check_utf8 && !preg_match('//u', $var)) {
- trigger_error("Expect utf-8 encoding.", E_USER_ERROR);
- return;
+ throw new \Exception("Expect utf-8 encoding.");
}
}
@@ -85,7 +113,7 @@ class GPBUtil
if (is_numeric($var)) {
$var = intval($var);
} else {
- trigger_error("Expect integer.", E_USER_ERROR);
+ throw new \Exception("Expect integer.");
}
}
@@ -102,7 +130,7 @@ class GPBUtil
$var = (int) $var;
}
} else {
- trigger_error("Expect integer.", E_USER_ERROR);
+ throw new \Exception("Expect integer.");
}
}
@@ -112,10 +140,15 @@ class GPBUtil
if (PHP_INT_SIZE == 8) {
$var = intval($var);
} else {
- $var = bcdiv($var, 1, 0);
+ if (is_float($var) ||
+ is_integer($var) ||
+ (is_string($var) &&
+ bccomp($var, "9223372036854774784") < 0)) {
+ $var = number_format($var, 0, ".", "");
+ }
}
} else {
- trigger_error("Expect integer.", E_USER_ERROR);
+ throw new \Exception("Expect integer.");
}
}
@@ -125,10 +158,10 @@ class GPBUtil
if (PHP_INT_SIZE == 8) {
$var = intval($var);
} else {
- $var = bcdiv($var, 1, 0);
+ $var = number_format($var, 0, ".", "");
}
} else {
- trigger_error("Expect integer.", E_USER_ERROR);
+ throw new \Exception("Expect integer.");
}
}
@@ -137,7 +170,7 @@ class GPBUtil
if (is_float($var) || is_numeric($var)) {
$var = floatval($var);
} else {
- trigger_error("Expect float.", E_USER_ERROR);
+ throw new \Exception("Expect float.");
}
}
@@ -146,15 +179,14 @@ class GPBUtil
if (is_float($var) || is_numeric($var)) {
$var = floatval($var);
} else {
- trigger_error("Expect float.", E_USER_ERROR);
+ throw new \Exception("Expect float.");
}
}
public static function checkBool(&$var)
{
if (is_array($var) || is_object($var)) {
- trigger_error("Expect boolean.", E_USER_ERROR);
- return;
+ throw new \Exception("Expect boolean.");
}
$var = boolval($var);
}
@@ -162,25 +194,59 @@ class GPBUtil
public static function checkMessage(&$var, $klass)
{
if (!$var instanceof $klass && !is_null($var)) {
- trigger_error("Expect message.", E_USER_ERROR);
+ throw new \Exception("Expect message.");
}
}
public static function checkRepeatedField(&$var, $type, $klass = null)
{
- if (!$var instanceof RepeatedField) {
- trigger_error("Expect repeated field.", E_USER_ERROR);
+ if (!$var instanceof RepeatedField && !is_array($var)) {
+ throw new \Exception("Expect array.");
+ }
+ if (is_array($var)) {
+ $tmp = new RepeatedField($type, $klass);
+ foreach ($var as $value) {
+ $tmp[] = $value;
+ }
+ return $tmp;
+ } else {
+ if ($var->getType() != $type) {
+ throw new \Exception(
+ "Expect repeated field of different type.");
+ }
+ if ($var->getType() === GPBType::MESSAGE &&
+ $var->getClass() !== $klass) {
+ throw new \Exception(
+ "Expect repeated field of different message.");
+ }
+ return $var;
}
- if ($var->getType() != $type) {
- trigger_error(
- "Expect repeated field of different type.",
- E_USER_ERROR);
+ }
+
+ public static function checkMapField(&$var, $key_type, $value_type, $klass = null)
+ {
+ if (!$var instanceof MapField && !is_array($var)) {
+ throw new \Exception("Expect dict.");
}
- if ($var->getType() === GPBType::MESSAGE &&
- $var->getClass() !== $klass) {
- trigger_error(
- "Expect repeated field of different message.",
- E_USER_ERROR);
+ if (is_array($var)) {
+ $tmp = new MapField($key_type, $value_type, $klass);
+ foreach ($var as $key => $value) {
+ $tmp[$key] = $value;
+ }
+ return $tmp;
+ } else {
+ if ($var->getKeyType() != $key_type) {
+ throw new \Exception("Expect map field of key type.");
+ }
+ if ($var->getValueType() != $value_type) {
+ throw new \Exception("Expect map field of value type.");
+ }
+ if ($var->getValueType() === GPBType::MESSAGE &&
+ $var->getValueClass() !== $klass) {
+ throw new \Exception(
+ "Expect map field of different value message.");
+ }
+ return $var;
}
}
@@ -193,4 +259,313 @@ class GPBUtil
{
return new Uint64($value);
}
+
+ public static function getClassNamePrefix(
+ $classname,
+ $file_proto)
+ {
+ $option = $file_proto->getOptions();
+ $prefix = is_null($option) ? "" : $option->getPhpClassPrefix();
+ if ($prefix !== "") {
+ return $prefix;
+ }
+
+ $reserved_words = array(
+ "abstract"=>0, "and"=>0, "array"=>0, "as"=>0, "break"=>0,
+ "callable"=>0, "case"=>0, "catch"=>0, "class"=>0, "clone"=>0,
+ "const"=>0, "continue"=>0, "declare"=>0, "default"=>0, "die"=>0,
+ "do"=>0, "echo"=>0, "else"=>0, "elseif"=>0, "empty"=>0,
+ "enddeclare"=>0, "endfor"=>0, "endforeach"=>0, "endif"=>0,
+ "endswitch"=>0, "endwhile"=>0, "eval"=>0, "exit"=>0, "extends"=>0,
+ "final"=>0, "for"=>0, "foreach"=>0, "function"=>0, "global"=>0,
+ "goto"=>0, "if"=>0, "implements"=>0, "include"=>0,
+ "include_once"=>0, "instanceof"=>0, "insteadof"=>0, "interface"=>0,
+ "isset"=>0, "list"=>0, "namespace"=>0, "new"=>0, "or"=>0,
+ "print"=>0, "private"=>0, "protected"=>0, "public"=>0, "require"=>0,
+ "require_once"=>0, "return"=>0, "static"=>0, "switch"=>0,
+ "throw"=>0, "trait"=>0, "try"=>0, "unset"=>0, "use"=>0, "var"=>0,
+ "while"=>0, "xor"=>0, "int"=>0, "float"=>0, "bool"=>0, "string"=>0,
+ "true"=>0, "false"=>0, "null"=>0, "void"=>0, "iterable"=>0
+ );
+
+ if (array_key_exists(strtolower($classname), $reserved_words)) {
+ if ($file_proto->getPackage() === "google.protobuf") {
+ return "GPB";
+ } else {
+ return "PB";
+ }
+ }
+
+ return "";
+ }
+
+ public static function getClassNameWithoutPackage(
+ $name,
+ $file_proto)
+ {
+ $classname = implode('_', explode('.', $name));
+ return static::getClassNamePrefix($classname, $file_proto) . $classname;
+ }
+
+ public static function getFullClassName(
+ $proto,
+ $containing,
+ $file_proto,
+ &$message_name_without_package,
+ &$classname,
+ &$fullname)
+ {
+ // Full name needs to start with '.'.
+ $message_name_without_package = $proto->getName();
+ if ($containing !== "") {
+ $message_name_without_package =
+ $containing . "." . $message_name_without_package;
+ }
+
+ $package = $file_proto->getPackage();
+ if ($package === "") {
+ $fullname = "." . $message_name_without_package;
+ } else {
+ $fullname = "." . $package . "." . $message_name_without_package;
+ }
+
+ $class_name_without_package =
+ static::getClassNameWithoutPackage($message_name_without_package, $file_proto);
+
+ $option = $file_proto->getOptions();
+ if (!is_null($option) && $option->hasPhpNamespace()) {
+ $namespace = $option->getPhpNamespace();
+ if ($namespace !== "") {
+ $classname = $namespace . "\\" . $class_name_without_package;
+ return;
+ } else {
+ $classname = $class_name_without_package;
+ return;
+ }
+ }
+
+ if ($package === "") {
+ $classname = $class_name_without_package;
+ } else {
+ $classname =
+ implode('\\', array_map('ucwords', explode('.', $package))).
+ "\\".$class_name_without_package;
+ }
+ }
+
+ public static function combineInt32ToInt64($high, $low)
+ {
+ $isNeg = $high < 0;
+ if ($isNeg) {
+ $high = ~$high;
+ $low = ~$low;
+ $low++;
+ if (!$low) {
+ $high = (int) ($high + 1);
+ }
+ }
+ $result = bcadd(bcmul($high, 4294967296), $low);
+ if ($low < 0) {
+ $result = bcadd($result, 4294967296);
+ }
+ if ($isNeg) {
+ $result = bcsub(0, $result);
+ }
+ return $result;
+ }
+
+ public static function parseTimestamp($timestamp)
+ {
+ // prevent parsing timestamps containing with the non-existant year "0000"
+ // DateTime::createFromFormat parses without failing but as a nonsensical date
+ if (substr($timestamp, 0, 4) === "0000") {
+ throw new \Exception("Year cannot be zero.");
+ }
+ // prevent parsing timestamps ending with a lowercase z
+ if (substr($timestamp, -1, 1) === "z") {
+ throw new \Exception("Timezone cannot be a lowercase z.");
+ }
+
+ $nanoseconds = 0;
+ $periodIndex = strpos($timestamp, ".");
+ if ($periodIndex !== false) {
+ $nanosecondsLength = 0;
+ // find the next non-numeric character in the timestamp to calculate
+ // the length of the nanoseconds text
+ for ($i = $periodIndex + 1, $length = strlen($timestamp); $i < $length; $i++) {
+ if (!is_numeric($timestamp[$i])) {
+ $nanosecondsLength = $i - ($periodIndex + 1);
+ break;
+ }
+ }
+ if ($nanosecondsLength % 3 !== 0) {
+ throw new \Exception("Nanoseconds must be disible by 3.");
+ }
+ if ($nanosecondsLength > 9) {
+ throw new \Exception("Nanoseconds must be in the range of 0 to 999,999,999 nanoseconds.");
+ }
+ if ($nanosecondsLength > 0) {
+ $nanoseconds = substr($timestamp, $periodIndex + 1, $nanosecondsLength);
+ $nanoseconds = intval($nanoseconds);
+
+ // remove the nanoseconds and preceding period from the timestamp
+ $date = substr($timestamp, 0, $periodIndex - 1);
+ $timezone = substr($timestamp, $periodIndex + $nanosecondsLength);
+ $timestamp = $date.$timezone;
+ }
+ }
+
+ $date = \DateTime::createFromFormat(\DateTime::RFC3339, $timestamp, new \DateTimeZone("UTC"));
+ if ($date === false) {
+ throw new \Exception("Invalid RFC 3339 timestamp.");
+ }
+
+ $value = new \Google\Protobuf\Timestamp();
+ $seconds = $date->format("U");
+ $value->setSeconds($seconds);
+ $value->setNanos($nanoseconds);
+ return $value;
+ }
+
+ public static function formatTimestamp($value)
+ {
+ if (bccomp($value->getSeconds(), "253402300800") != -1) {
+ throw new GPBDecodeException("Duration number too large.");
+ }
+ if (bccomp($value->getSeconds(), "-62135596801") != 1) {
+ throw new GPBDecodeException("Duration number too small.");
+ }
+ $nanoseconds = static::getNanosecondsForTimestamp($value->getNanos());
+ if (!empty($nanoseconds)) {
+ $nanoseconds = ".".$nanoseconds;
+ }
+ $date = new \DateTime('@'.$value->getSeconds(), new \DateTimeZone("UTC"));
+ return $date->format("Y-m-d\TH:i:s".$nanoseconds."\Z");
+ }
+
+ public static function parseDuration($value)
+ {
+ if (strlen($value) < 2 || substr($value, -1) !== "s") {
+ throw new GPBDecodeException("Missing s after duration string");
+ }
+ $number = substr($value, 0, -1);
+ if (bccomp($number, "315576000001") != -1) {
+ throw new GPBDecodeException("Duration number too large.");
+ }
+ if (bccomp($number, "-315576000001") != 1) {
+ throw new GPBDecodeException("Duration number too small.");
+ }
+ $pos = strrpos($number, ".");
+ if ($pos !== false) {
+ $seconds = substr($number, 0, $pos);
+ if (bccomp($seconds, 0) < 0) {
+ $nanos = bcmul("0" . substr($number, $pos), -1000000000);
+ } else {
+ $nanos = bcmul("0" . substr($number, $pos), 1000000000);
+ }
+ } else {
+ $seconds = $number;
+ $nanos = 0;
+ }
+ $duration = new Duration();
+ $duration->setSeconds($seconds);
+ $duration->setNanos($nanos);
+ return $duration;
+ }
+
+ public static function formatDuration($value)
+ {
+ if (bccomp($value->getSeconds(), "315576000001") != -1) {
+ throw new GPBDecodeException("Duration number too large.");
+ }
+ if (bccomp($value->getSeconds(), "-315576000001") != 1) {
+ throw new GPBDecodeException("Duration number too small.");
+ }
+ return strval(bcadd($value->getSeconds(),
+ $value->getNanos() / 1000000000.0, 9));
+ }
+
+
+
+ public static function parseFieldMask($paths_string)
+ {
+ $path_strings = explode(",", $paths_string);
+ $field_mask = new FieldMask();
+ $paths = $field_mask->getPaths();
+ foreach($path_strings as &$path_string) {
+ $field_strings = explode(".", $path_string);
+ foreach($field_strings as &$field_string) {
+ $field_string = camel2underscore($field_string);
+ }
+ $path_string = implode(".", $field_strings);
+ $paths[] = $path_string;
+ }
+ return $field_mask;
+ }
+
+ public static function formatFieldMask($field_mask)
+ {
+ $converted_paths = [];
+ foreach($field_mask->getPaths() as $path) {
+ $fields = explode('.', $path);
+ $converted_path = [];
+ foreach ($fields as $field) {
+ $segments = explode('_', $field);
+ $start = true;
+ $converted_segments = "";
+ foreach($segments as $segment) {
+ if (!$start) {
+ $converted = ucfirst($segment);
+ } else {
+ $converted = $segment;
+ $start = false;
+ }
+ $converted_segments .= $converted;
+ }
+ $converted_path []= $converted_segments;
+ }
+ $converted_path = implode(".", $converted_path);
+ $converted_paths []= $converted_path;
+ }
+ return implode(",", $converted_paths);
+ }
+
+ public static function getNanosecondsForTimestamp($nanoseconds)
+ {
+ if ($nanoseconds == 0) {
+ return '';
+ }
+ if ($nanoseconds % static::NANOS_PER_MILLISECOND == 0) {
+ return sprintf('%03d', $nanoseconds / static::NANOS_PER_MILLISECOND);
+ }
+ if ($nanoseconds % static::NANOS_PER_MICROSECOND == 0) {
+ return sprintf('%06d', $nanoseconds / static::NANOS_PER_MICROSECOND);
+ }
+ return sprintf('%09d', $nanoseconds);
+ }
+
+ public static function hasSpecialJsonMapping($msg)
+ {
+ return is_a($msg, 'Google\Protobuf\Any') ||
+ is_a($msg, "Google\Protobuf\ListValue") ||
+ is_a($msg, "Google\Protobuf\Struct") ||
+ is_a($msg, "Google\Protobuf\Value") ||
+ is_a($msg, "Google\Protobuf\Duration") ||
+ is_a($msg, "Google\Protobuf\Timestamp") ||
+ is_a($msg, "Google\Protobuf\FieldMask") ||
+ static::hasJsonValue($msg);
+ }
+
+ public static function hasJsonValue($msg)
+ {
+ return is_a($msg, "Google\Protobuf\DoubleValue") ||
+ is_a($msg, "Google\Protobuf\FloatValue") ||
+ is_a($msg, "Google\Protobuf\Int64Value") ||
+ is_a($msg, "Google\Protobuf\UInt64Value") ||
+ is_a($msg, "Google\Protobuf\Int32Value") ||
+ is_a($msg, "Google\Protobuf\UInt32Value") ||
+ is_a($msg, "Google\Protobuf\BoolValue") ||
+ is_a($msg, "Google\Protobuf\StringValue") ||
+ is_a($msg, "Google\Protobuf\BytesValue");
+ }
}
diff --git a/php/src/Google/Protobuf/Internal/GPBWire.php b/php/src/Google/Protobuf/Internal/GPBWire.php
index 7e2c124f..e7eec552 100644
--- a/php/src/Google/Protobuf/Internal/GPBWire.php
+++ b/php/src/Google/Protobuf/Internal/GPBWire.php
@@ -117,19 +117,12 @@ class GPBWire
// << decode <<
public static function zigZagEncode32($int32)
{
- // Fill high 32 bits.
- if (PHP_INT_SIZE === 8) {
- $int32 |= ((($int32 << 32) >> 31) & (0xFFFFFFFF << 32));
+ if (PHP_INT_SIZE == 8) {
+ $trim_int32 = $int32 & 0xFFFFFFFF;
+ return (($trim_int32 << 1) ^ ($int32 << 32 >> 63)) & 0xFFFFFFFF;
+ } else {
+ return ($int32 << 1) ^ ($int32 >> 31);
}
-
- $uint32 = ($int32 << 1) ^ ($int32 >> 31);
-
- // Fill high 32 bits.
- if (PHP_INT_SIZE === 8) {
- $uint32 |= ((($uint32 << 32) >> 31) & (0xFFFFFFFF << 32));
- }
-
- return $uint32;
}
public static function zigZagDecode32($uint32)
@@ -177,7 +170,11 @@ class GPBWire
public static function readInt64(&$input, &$value)
{
- return $input->readVarint64($value);
+ $success = $input->readVarint64($value);
+ if (PHP_INT_SIZE == 4 && bccomp($value, "9223372036854775807") > 0) {
+ $value = bcsub($value, "18446744073709551616");
+ }
+ return $success;
}
public static function readUint32(&$input, &$value)
@@ -231,7 +228,11 @@ class GPBWire
public static function readSfixed64(&$input, &$value)
{
- return $input->readLittleEndian64($value);
+ $success = $input->readLittleEndian64($value);
+ if (PHP_INT_SIZE == 4 && bccomp($value, "9223372036854775807") > 0) {
+ $value = bcsub($value, "18446744073709551616");
+ }
+ return $success;
}
public static function readFloat(&$input, &$value)
@@ -298,7 +299,7 @@ class GPBWire
public static function writeInt32(&$output, $value)
{
- return $output->writeVarint32($value);
+ return $output->writeVarint32($value, false);
}
public static function writeInt64(&$output, $value)
@@ -308,7 +309,7 @@ class GPBWire
public static function writeUint32(&$output, $value)
{
- return $output->writeVarint32($value);
+ return $output->writeVarint32($value, true);
}
public static function writeUint64(&$output, $value)
@@ -319,7 +320,7 @@ class GPBWire
public static function writeSint32(&$output, $value)
{
$value = GPBWire::zigZagEncode32($value);
- return $output->writeVarint64($value);
+ return $output->writeVarint32($value, true);
}
public static function writeSint64(&$output, $value)
@@ -351,9 +352,9 @@ class GPBWire
public static function writeBool(&$output, $value)
{
if ($value) {
- return $output->writeVarint32(1);
+ return $output->writeVarint32(1, true);
} else {
- return $output->writeVarint32(0);
+ return $output->writeVarint32(0, true);
}
}
@@ -377,7 +378,7 @@ class GPBWire
public static function writeBytes(&$output, $value)
{
$size = strlen($value);
- if (!$output->writeVarint32($size)) {
+ if (!$output->writeVarint32($size, true)) {
return false;
}
return $output->writeRaw($value, $size);
@@ -386,7 +387,7 @@ class GPBWire
public static function writeMessage(&$output, $value)
{
$size = $value->byteSize();
- if (!$output->writeVarint32($size)) {
+ if (!$output->writeVarint32($size, true)) {
return false;
}
return $value->serializeToStream($output);
@@ -403,10 +404,14 @@ class GPBWire
return self::varint32Size($tag);
}
- public static function varint32Size($value)
+ public static function varint32Size($value, $sign_extended = false)
{
if ($value < 0) {
- return 5;
+ if ($sign_extended) {
+ return 10;
+ } else {
+ return 5;
+ }
}
if ($value < (1 << 7)) {
return 1;
@@ -437,34 +442,66 @@ class GPBWire
public static function varint64Size($value)
{
- if ($value < 0) {
- return 10;
- }
- if ($value < (1 << 7)) {
- return 1;
- }
- if ($value < (1 << 14)) {
- return 2;
- }
- if ($value < (1 << 21)) {
- return 3;
- }
- if ($value < (1 << 28)) {
- return 4;
- }
- if ($value < (1 << 35)) {
- return 5;
- }
- if ($value < (1 << 42)) {
- return 6;
- }
- if ($value < (1 << 49)) {
- return 7;
- }
- if ($value < (1 << 56)) {
- return 8;
+ if (PHP_INT_SIZE == 4) {
+ if (bccomp($value, 0) < 0 ||
+ bccomp($value, "9223372036854775807") > 0) {
+ return 10;
+ }
+ if (bccomp($value, 1 << 7) < 0) {
+ return 1;
+ }
+ if (bccomp($value, 1 << 14) < 0) {
+ return 2;
+ }
+ if (bccomp($value, 1 << 21) < 0) {
+ return 3;
+ }
+ if (bccomp($value, 1 << 28) < 0) {
+ return 4;
+ }
+ if (bccomp($value, '34359738368') < 0) {
+ return 5;
+ }
+ if (bccomp($value, '4398046511104') < 0) {
+ return 6;
+ }
+ if (bccomp($value, '562949953421312') < 0) {
+ return 7;
+ }
+ if (bccomp($value, '72057594037927936') < 0) {
+ return 8;
+ }
+ return 9;
+ } else {
+ if ($value < 0) {
+ return 10;
+ }
+ if ($value < (1 << 7)) {
+ return 1;
+ }
+ if ($value < (1 << 14)) {
+ return 2;
+ }
+ if ($value < (1 << 21)) {
+ return 3;
+ }
+ if ($value < (1 << 28)) {
+ return 4;
+ }
+ if ($value < (1 << 35)) {
+ return 5;
+ }
+ if ($value < (1 << 42)) {
+ return 6;
+ }
+ if ($value < (1 << 49)) {
+ return 7;
+ }
+ if ($value < (1 << 56)) {
+ return 8;
+ }
+ return 9;
}
- return 9;
}
public static function serializeFieldToStream(
@@ -543,6 +580,9 @@ class GPBWire
}
break;
case GPBType::UINT32:
+ if (PHP_INT_SIZE === 8 && $value < 0) {
+ $value += 4294967296;
+ }
if (!GPBWire::writeUint32($output, $value)) {
return false;
}
diff --git a/php/src/Google/Protobuf/Internal/GPBWireType.php b/php/src/Google/Protobuf/Internal/GPBWireType.php
new file mode 100644
index 00000000..c1ad370e
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/GPBWireType.php
@@ -0,0 +1,43 @@
+<?php
+
+// 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.
+
+namespace Google\Protobuf\Internal;
+
+class GPBWireType
+{
+ const VARINT = 0;
+ const FIXED64 = 1;
+ const LENGTH_DELIMITED = 2;
+ const START_GROUP = 3;
+ const END_GROUP = 4;
+ const FIXED32 = 5;
+}
diff --git a/php/src/Google/Protobuf/Internal/GeneratedCodeInfo.php b/php/src/Google/Protobuf/Internal/GeneratedCodeInfo.php
index 8e493c2f..ae2ad745 100644
--- a/php/src/Google/Protobuf/Internal/GeneratedCodeInfo.php
+++ b/php/src/Google/Protobuf/Internal/GeneratedCodeInfo.php
@@ -8,27 +8,22 @@ use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\GPBWire;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\InputStream;
-
use Google\Protobuf\Internal\GPBUtil;
/**
- * <pre>
* Describes the relationship between generated code and its original source
* file. A GeneratedCodeInfo message is associated with only one generated
* source file, but may contain references to different source .proto files.
- * </pre>
*
- * Protobuf type <code>google.protobuf.GeneratedCodeInfo</code>
+ * Generated from protobuf message <code>google.protobuf.GeneratedCodeInfo</code>
*/
class GeneratedCodeInfo extends \Google\Protobuf\Internal\Message
{
/**
- * <pre>
* An Annotation connects some span of text in generated code to an element
* of its generating .proto file.
- * </pre>
*
- * <code>repeated .google.protobuf.GeneratedCodeInfo.Annotation annotation = 1;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.GeneratedCodeInfo.Annotation annotation = 1;</code>
*/
private $annotation;
private $has_annotation = false;
@@ -39,12 +34,11 @@ class GeneratedCodeInfo extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* An Annotation connects some span of text in generated code to an element
* of its generating .proto file.
- * </pre>
*
- * <code>repeated .google.protobuf.GeneratedCodeInfo.Annotation annotation = 1;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.GeneratedCodeInfo.Annotation annotation = 1;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
*/
public function getAnnotation()
{
@@ -52,18 +46,20 @@ class GeneratedCodeInfo extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* An Annotation connects some span of text in generated code to an element
* of its generating .proto file.
- * </pre>
*
- * <code>repeated .google.protobuf.GeneratedCodeInfo.Annotation annotation = 1;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.GeneratedCodeInfo.Annotation annotation = 1;</code>
+ * @param \Google\Protobuf\Internal\GeneratedCodeInfo_Annotation[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
*/
- public function setAnnotation(&$var)
+ public function setAnnotation($var)
{
- GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\GeneratedCodeInfo_Annotation::class);
- $this->annotation = $var;
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\GeneratedCodeInfo_Annotation::class);
+ $this->annotation = $arr;
$this->has_annotation = true;
+
+ return $this;
}
public function hasAnnotation()
diff --git a/php/src/Google/Protobuf/Internal/GeneratedCodeInfo_Annotation.php b/php/src/Google/Protobuf/Internal/GeneratedCodeInfo_Annotation.php
index dcc7edfe..22ac2337 100644
--- a/php/src/Google/Protobuf/Internal/GeneratedCodeInfo_Annotation.php
+++ b/php/src/Google/Protobuf/Internal/GeneratedCodeInfo_Annotation.php
@@ -8,51 +8,42 @@ use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\GPBWire;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\InputStream;
-
use Google\Protobuf\Internal\GPBUtil;
/**
- * Protobuf type <code>google.protobuf.GeneratedCodeInfo.Annotation</code>
+ * Generated from protobuf message <code>google.protobuf.GeneratedCodeInfo.Annotation</code>
*/
class GeneratedCodeInfo_Annotation extends \Google\Protobuf\Internal\Message
{
/**
- * <pre>
* Identifies the element in the original source .proto file. This field
* is formatted the same as SourceCodeInfo.Location.path.
- * </pre>
*
- * <code>repeated int32 path = 1 [packed = true];</code>
+ * Generated from protobuf field <code>repeated int32 path = 1 [packed = true];</code>
*/
private $path;
private $has_path = false;
/**
- * <pre>
* Identifies the filesystem path to the original source .proto.
- * </pre>
*
- * <code>optional string source_file = 2;</code>
+ * Generated from protobuf field <code>optional string source_file = 2;</code>
*/
private $source_file = '';
private $has_source_file = false;
/**
- * <pre>
* Identifies the starting offset in bytes in the generated code
* that relates to the identified object.
- * </pre>
*
- * <code>optional int32 begin = 3;</code>
+ * Generated from protobuf field <code>optional int32 begin = 3;</code>
*/
private $begin = 0;
private $has_begin = false;
/**
- * <pre>
* Identifies the ending offset in bytes in the generated code that
* relates to the identified offset. The end offset should be one past
* the last relevant byte (so the length of the text = end - begin).
- * </pre>
*
- * <code>optional int32 end = 4;</code>
+ * Generated from protobuf field <code>optional int32 end = 4;</code>
*/
private $end = 0;
private $has_end = false;
@@ -63,12 +54,11 @@ class GeneratedCodeInfo_Annotation extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Identifies the element in the original source .proto file. This field
* is formatted the same as SourceCodeInfo.Location.path.
- * </pre>
*
- * <code>repeated int32 path = 1 [packed = true];</code>
+ * Generated from protobuf field <code>repeated int32 path = 1 [packed = true];</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
*/
public function getPath()
{
@@ -76,18 +66,20 @@ class GeneratedCodeInfo_Annotation extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Identifies the element in the original source .proto file. This field
* is formatted the same as SourceCodeInfo.Location.path.
- * </pre>
*
- * <code>repeated int32 path = 1 [packed = true];</code>
+ * Generated from protobuf field <code>repeated int32 path = 1 [packed = true];</code>
+ * @param int[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
*/
- public function setPath(&$var)
+ public function setPath($var)
{
- GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::INT32);
- $this->path = $var;
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::INT32);
+ $this->path = $arr;
$this->has_path = true;
+
+ return $this;
}
public function hasPath()
@@ -96,11 +88,10 @@ class GeneratedCodeInfo_Annotation extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Identifies the filesystem path to the original source .proto.
- * </pre>
*
- * <code>optional string source_file = 2;</code>
+ * Generated from protobuf field <code>optional string source_file = 2;</code>
+ * @return string
*/
public function getSourceFile()
{
@@ -108,17 +99,19 @@ class GeneratedCodeInfo_Annotation extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Identifies the filesystem path to the original source .proto.
- * </pre>
*
- * <code>optional string source_file = 2;</code>
+ * Generated from protobuf field <code>optional string source_file = 2;</code>
+ * @param string $var
+ * @return $this
*/
public function setSourceFile($var)
{
GPBUtil::checkString($var, True);
$this->source_file = $var;
$this->has_source_file = true;
+
+ return $this;
}
public function hasSourceFile()
@@ -127,12 +120,11 @@ class GeneratedCodeInfo_Annotation extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Identifies the starting offset in bytes in the generated code
* that relates to the identified object.
- * </pre>
*
- * <code>optional int32 begin = 3;</code>
+ * Generated from protobuf field <code>optional int32 begin = 3;</code>
+ * @return int
*/
public function getBegin()
{
@@ -140,18 +132,20 @@ class GeneratedCodeInfo_Annotation extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Identifies the starting offset in bytes in the generated code
* that relates to the identified object.
- * </pre>
*
- * <code>optional int32 begin = 3;</code>
+ * Generated from protobuf field <code>optional int32 begin = 3;</code>
+ * @param int $var
+ * @return $this
*/
public function setBegin($var)
{
GPBUtil::checkInt32($var);
$this->begin = $var;
$this->has_begin = true;
+
+ return $this;
}
public function hasBegin()
@@ -160,13 +154,12 @@ class GeneratedCodeInfo_Annotation extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Identifies the ending offset in bytes in the generated code that
* relates to the identified offset. The end offset should be one past
* the last relevant byte (so the length of the text = end - begin).
- * </pre>
*
- * <code>optional int32 end = 4;</code>
+ * Generated from protobuf field <code>optional int32 end = 4;</code>
+ * @return int
*/
public function getEnd()
{
@@ -174,19 +167,21 @@ class GeneratedCodeInfo_Annotation extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Identifies the ending offset in bytes in the generated code that
* relates to the identified offset. The end offset should be one past
* the last relevant byte (so the length of the text = end - begin).
- * </pre>
*
- * <code>optional int32 end = 4;</code>
+ * Generated from protobuf field <code>optional int32 end = 4;</code>
+ * @param int $var
+ * @return $this
*/
public function setEnd($var)
{
GPBUtil::checkInt32($var);
$this->end = $var;
$this->has_end = true;
+
+ return $this;
}
public function hasEnd()
diff --git a/php/src/Google/Protobuf/Internal/GetPublicDescriptorTrait.php b/php/src/Google/Protobuf/Internal/GetPublicDescriptorTrait.php
new file mode 100644
index 00000000..d22bc305
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/GetPublicDescriptorTrait.php
@@ -0,0 +1,41 @@
+<?php
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2017 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.
+
+namespace Google\Protobuf\Internal;
+
+trait GetPublicDescriptorTrait
+{
+ private function getPublicDescriptor($desc)
+ {
+ return is_null($desc) ? null : $desc->getPublicDescriptor();
+ }
+}
diff --git a/php/src/Google/Protobuf/Internal/HasPublicDescriptorTrait.php b/php/src/Google/Protobuf/Internal/HasPublicDescriptorTrait.php
new file mode 100644
index 00000000..ed5d1660
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/HasPublicDescriptorTrait.php
@@ -0,0 +1,43 @@
+<?php
+
+// 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.
+
+namespace Google\Protobuf\Internal;
+
+trait HasPublicDescriptorTrait
+{
+ private $public_desc;
+
+ public function getPublicDescriptor()
+ {
+ return $this->public_desc;
+ }
+}
diff --git a/php/src/Google/Protobuf/Internal/MapEntry.php b/php/src/Google/Protobuf/Internal/MapEntry.php
index 926645e1..9c32f1ea 100644
--- a/php/src/Google/Protobuf/Internal/MapEntry.php
+++ b/php/src/Google/Protobuf/Internal/MapEntry.php
@@ -39,7 +39,7 @@ class MapEntry extends Message
public $key;
public $value;
- public function setKey(&$key) {
+ public function setKey($key) {
$this->key = $key;
}
@@ -47,7 +47,7 @@ class MapEntry extends Message
return $this->key;
}
- public function setValue(&$value) {
+ public function setValue($value) {
$this->value = $value;
}
diff --git a/php/src/Google/Protobuf/Internal/MapField.php b/php/src/Google/Protobuf/Internal/MapField.php
index 14ee7ebe..38736dad 100644
--- a/php/src/Google/Protobuf/Internal/MapField.php
+++ b/php/src/Google/Protobuf/Internal/MapField.php
@@ -38,132 +38,6 @@
namespace Google\Protobuf\Internal;
/**
- * MapFieldIter is used to iterate MapField. It is also need for the foreach
- * syntax.
- */
-class MapFieldIter implements \Iterator
-{
-
- /**
- * @ignore
- */
- private $container;
-
- /**
- * Create iterator instance for MapField.
- *
- * @param MapField The MapField instance for which this iterator is
- * created.
- * @ignore
- */
- public function __construct($container)
- {
- $this->container = $container;
- }
-
- /**
- * Reset the status of the iterator
- *
- * @return void
- */
- public function rewind()
- {
- return reset($this->container);
- }
-
- /**
- * Return the element at the current position.
- *
- * @return object The element at the current position.
- */
- public function current()
- {
- return current($this->container);
- }
-
- /**
- * Return the current key.
- *
- * @return object The current key.
- */
- public function key()
- {
- return key($this->container);
- }
-
- /**
- * Move to the next position.
- *
- * @return void
- */
- public function next()
- {
- return next($this->container);
- }
-
- /**
- * Check whether there are more elements to iterate.
- *
- * @return bool True if there are more elements to iterate.
- */
- public function valid()
- {
- return key($this->container) !== null;
- }
-}
-
-/**
- * @ignore
- */
-function checkKey($key_type, &$key)
-{
- switch ($key_type) {
- case GPBType::INT32:
- GPBUtil::checkInt32($key);
- break;
- case GPBType::UINT32:
- GPBUtil::checkUint32($key);
- break;
- case GPBType::INT64:
- GPBUtil::checkInt64($key);
- break;
- case GPBType::UINT64:
- GPBUtil::checkUint64($key);
- break;
- case GPBType::FIXED64:
- GPBUtil::checkUint64($key);
- break;
- case GPBType::FIXED32:
- GPBUtil::checkUint32($key);
- break;
- case GPBType::SFIXED64:
- GPBUtil::checkInt64($key);
- break;
- case GPBType::SFIXED32:
- GPBUtil::checkInt32($key);
- break;
- case GPBType::SINT64:
- GPBUtil::checkInt64($key);
- break;
- case GPBType::SINT32:
- GPBUtil::checkInt32($key);
- break;
- case GPBType::BOOL:
- GPBUtil::checkBool($key);
- break;
- case GPBType::STRING:
- GPBUtil::checkString($key, true);
- break;
- default:
- var_dump($key_type);
- trigger_error(
- "Given type cannot be map key.",
- E_USER_ERROR);
- break;
- }
-}
-
-/**
* MapField is used by generated protocol message classes to manipulate map
* fields. It can be used like native PHP array.
*/
@@ -204,6 +78,30 @@ class MapField implements \ArrayAccess, \IteratorAggregate, \Countable
}
/**
+ * @ignore
+ */
+ public function getKeyType()
+ {
+ return $this->key_type;
+ }
+
+ /**
+ * @ignore
+ */
+ public function getValueType()
+ {
+ return $this->value_type;
+ }
+
+ /**
+ * @ignore
+ */
+ public function getValueClass()
+ {
+ return $this->klass;
+ }
+
+ /**
* Return the element at the given key.
*
* This will also be called for: $ele = $arr[$key]
@@ -232,7 +130,7 @@ class MapField implements \ArrayAccess, \IteratorAggregate, \Countable
*/
public function offsetSet($key, $value)
{
- checkKey($this->key_type, $key);
+ $this->checkKey($this->key_type, $key);
switch ($this->value_type) {
case GPBType::INT32:
@@ -260,6 +158,9 @@ class MapField implements \ArrayAccess, \IteratorAggregate, \Countable
GPBUtil::checkString($value, true);
break;
case GPBType::MESSAGE:
+ if (is_null($value)) {
+ trigger_error("Map element cannot be null.", E_USER_ERROR);
+ }
GPBUtil::checkMessage($value, $this->klass);
break;
default:
@@ -280,7 +181,7 @@ class MapField implements \ArrayAccess, \IteratorAggregate, \Countable
*/
public function offsetUnset($key)
{
- checkKey($this->key_type, $key);
+ $this->checkKey($this->key_type, $key);
unset($this->container[$key]);
}
@@ -295,7 +196,7 @@ class MapField implements \ArrayAccess, \IteratorAggregate, \Countable
*/
public function offsetExists($key)
{
- checkKey($this->key_type, $key);
+ $this->checkKey($this->key_type, $key);
return isset($this->container[$key]);
}
@@ -304,7 +205,7 @@ class MapField implements \ArrayAccess, \IteratorAggregate, \Countable
*/
public function getIterator()
{
- return new MapFieldIter($this->container);
+ return new MapFieldIter($this->container, $this->key_type);
}
/**
@@ -318,4 +219,54 @@ class MapField implements \ArrayAccess, \IteratorAggregate, \Countable
{
return count($this->container);
}
+
+ /**
+ * @ignore
+ */
+ private function checkKey($key_type, &$key)
+ {
+ switch ($key_type) {
+ case GPBType::INT32:
+ GPBUtil::checkInt32($key);
+ break;
+ case GPBType::UINT32:
+ GPBUtil::checkUint32($key);
+ break;
+ case GPBType::INT64:
+ GPBUtil::checkInt64($key);
+ break;
+ case GPBType::UINT64:
+ GPBUtil::checkUint64($key);
+ break;
+ case GPBType::FIXED64:
+ GPBUtil::checkUint64($key);
+ break;
+ case GPBType::FIXED32:
+ GPBUtil::checkUint32($key);
+ break;
+ case GPBType::SFIXED64:
+ GPBUtil::checkInt64($key);
+ break;
+ case GPBType::SFIXED32:
+ GPBUtil::checkInt32($key);
+ break;
+ case GPBType::SINT64:
+ GPBUtil::checkInt64($key);
+ break;
+ case GPBType::SINT32:
+ GPBUtil::checkInt32($key);
+ break;
+ case GPBType::BOOL:
+ GPBUtil::checkBool($key);
+ break;
+ case GPBType::STRING:
+ GPBUtil::checkString($key, true);
+ break;
+ default:
+ trigger_error(
+ "Given type cannot be map key.",
+ E_USER_ERROR);
+ break;
+ }
+ }
}
diff --git a/php/src/Google/Protobuf/Internal/MapFieldIter.php b/php/src/Google/Protobuf/Internal/MapFieldIter.php
new file mode 100644
index 00000000..88e6c8b2
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/MapFieldIter.php
@@ -0,0 +1,124 @@
+<?php
+
+// 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.
+
+/**
+ * MapField and MapFieldIter are used by generated protocol message classes to
+ * manipulate map fields.
+ */
+
+namespace Google\Protobuf\Internal;
+
+/**
+ * MapFieldIter is used to iterate MapField. It is also need for the foreach
+ * syntax.
+ */
+class MapFieldIter implements \Iterator
+{
+
+ /**
+ * @ignore
+ */
+ private $container;
+
+ /**
+ * Create iterator instance for MapField.
+ *
+ * @param MapField The MapField instance for which this iterator is
+ * created.
+ * @param GPBType Map key type.
+ * @ignore
+ */
+ public function __construct($container, $key_type)
+ {
+ $this->container = $container;
+ $this->key_type = $key_type;
+ }
+
+ /**
+ * Reset the status of the iterator
+ *
+ * @return void
+ */
+ public function rewind()
+ {
+ return reset($this->container);
+ }
+
+ /**
+ * Return the element at the current position.
+ *
+ * @return object The element at the current position.
+ */
+ public function current()
+ {
+ return current($this->container);
+ }
+
+ /**
+ * Return the current key.
+ *
+ * @return object The current key.
+ */
+ public function key()
+ {
+ $key = key($this->container);
+ if ($this->key_type === GPBType::BOOL) {
+ // PHP associative array stores bool as integer for key.
+ return boolval($key);
+ } elseif ($this->key_type === GPBType::STRING) {
+ // PHP associative array stores int string as int for key.
+ return strval($key);
+ } else {
+ return $key;
+ }
+ }
+
+ /**
+ * Move to the next position.
+ *
+ * @return void
+ */
+ public function next()
+ {
+ return next($this->container);
+ }
+
+ /**
+ * Check whether there are more elements to iterate.
+ *
+ * @return bool True if there are more elements to iterate.
+ */
+ public function valid()
+ {
+ return key($this->container) !== null;
+ }
+}
diff --git a/php/src/Google/Protobuf/Internal/Message.php b/php/src/Google/Protobuf/Internal/Message.php
index 3d1f1598..9785be30 100644
--- a/php/src/Google/Protobuf/Internal/Message.php
+++ b/php/src/Google/Protobuf/Internal/Message.php
@@ -36,14 +36,18 @@
namespace Google\Protobuf\Internal;
-use Google\Protobuf\Internal\InputStream;
-use Google\Protobuf\Internal\OutputStream;
+use Google\Protobuf\Internal\CodedInputStream;
+use Google\Protobuf\Internal\CodedOutputStream;
use Google\Protobuf\Internal\DescriptorPool;
use Google\Protobuf\Internal\GPBLabel;
use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\GPBWire;
use Google\Protobuf\Internal\MapEntry;
use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\ListValue;
+use Google\Protobuf\Value;
+use Google\Protobuf\Struct;
+use Google\Protobuf\NullValue;
/**
* Parent class of all proto messages. Users should not instantiate this class
@@ -57,6 +61,7 @@ class Message
* @ignore
*/
private $desc;
+ private $unknown = "";
/**
* @ignore
@@ -68,10 +73,17 @@ class Message
// specific descriptor from the descriptor pool.
if (get_class($this) === 'Google\Protobuf\Internal\MapEntry') {
$this->desc = $desc;
+ foreach ($desc->getField() as $field) {
+ $setter = $field->getSetter();
+ $this->$setter($this->defaultValue($field));
+ }
return;
}
$pool = DescriptorPool::getGeneratedPool();
$this->desc = $pool->getDescriptorByClassName(get_class($this));
+ if (is_null($this->desc)) {
+ user_error(get_class($this) . "is not found in descriptor pool.");
+ }
foreach ($this->desc->getField() as $field) {
$setter = $field->getSetter();
if ($field->isMap()) {
@@ -125,7 +137,7 @@ class Message
$oneof = $this->desc->getOneofDecl()[$field->getOneofIndex()];
$oneof_name = $oneof->getName();
$this->$oneof_name = new OneofField($oneof);
- } else if ($field->getLabel() === GPBLabel::OPTIONAL &&
+ } else if ($field->getLabel() === GPBLabel::OPTIONAL &&
PHP_INT_SIZE == 4) {
switch ($field->getType()) {
case GPBType::INT64:
@@ -163,6 +175,17 @@ class Message
$oneof_field->setNumber($number);
}
+ protected function whichOneof($oneof_name)
+ {
+ $oneof_field = $this->$oneof_name;
+ $number = $oneof_field->getNumber();
+ if ($number == 0) {
+ return "";
+ }
+ $field = $this->desc->getFieldByNumber($number);
+ return $field->getName();
+ }
+
/**
* @ignore
*/
@@ -175,17 +198,22 @@ class Message
case GPBType::FLOAT:
return 0.0;
case GPBType::UINT32:
- case GPBType::UINT64:
case GPBType::INT32:
- case GPBType::INT64:
case GPBType::FIXED32:
- case GPBType::FIXED64:
case GPBType::SFIXED32:
- case GPBType::SFIXED64:
case GPBType::SINT32:
- case GPBType::SINT64:
case GPBType::ENUM:
return 0;
+ case GPBType::INT64:
+ case GPBType::UINT64:
+ case GPBType::FIXED64:
+ case GPBType::SFIXED64:
+ case GPBType::SINT64:
+ if (PHP_INT_SIZE === 4) {
+ return '0';
+ } else {
+ return 0;
+ }
case GPBType::BOOL:
return false;
case GPBType::STRING:
@@ -203,57 +231,123 @@ class Message
/**
* @ignore
*/
+ private function skipField($input, $tag)
+ {
+ $number = GPBWire::getTagFieldNumber($tag);
+ if ($number === 0) {
+ throw new GPBDecodeException("Illegal field number zero.");
+ }
+
+ $start = $input->current();
+ switch (GPBWire::getTagWireType($tag)) {
+ case GPBWireType::VARINT:
+ $uint64 = 0;
+ if (!$input->readVarint64($uint64)) {
+ throw new GPBDecodeException(
+ "Unexpected EOF inside varint.");
+ }
+ break;
+ case GPBWireType::FIXED64:
+ $uint64 = 0;
+ if (!$input->readLittleEndian64($uint64)) {
+ throw new GPBDecodeException(
+ "Unexpected EOF inside fixed64.");
+ }
+ break;
+ case GPBWireType::FIXED32:
+ $uint32 = 0;
+ if (!$input->readLittleEndian32($uint32)) {
+ throw new GPBDecodeException(
+ "Unexpected EOF inside fixed32.");
+ }
+ break;
+ case GPBWireType::LENGTH_DELIMITED:
+ $length = 0;
+ if (!$input->readVarint32($length)) {
+ throw new GPBDecodeException(
+ "Unexpected EOF inside length.");
+ }
+ $data = NULL;
+ if (!$input->readRaw($length, $data)) {
+ throw new GPBDecodeException(
+ "Unexpected EOF inside length delimited data.");
+ }
+ break;
+ case GPBWireType::START_GROUP:
+ case GPBWireType::END_GROUP:
+ throw new GPBDecodeException("Unexpected wire type.");
+ default:
+ throw new GPBDecodeException("Unexpected wire type.");
+ }
+ $end = $input->current();
+
+ $bytes = str_repeat(chr(0), CodedOutputStream::MAX_VARINT64_BYTES);
+ $size = CodedOutputStream::writeVarintToArray($tag, $bytes, true);
+ $this->unknown .= substr($bytes, 0, $size) . $input->substr($start, $end);
+ }
+
+ /**
+ * @ignore
+ */
private static function parseFieldFromStreamNoTag($input, $field, &$value)
{
switch ($field->getType()) {
case GPBType::DOUBLE:
if (!GPBWire::readDouble($input, $value)) {
- return false;
+ throw new GPBDecodeException(
+ "Unexpected EOF inside double field.");
}
break;
case GPBType::FLOAT:
if (!GPBWire::readFloat($input, $value)) {
- return false;
+ throw new GPBDecodeException(
+ "Unexpected EOF inside float field.");
}
break;
case GPBType::INT64:
if (!GPBWire::readInt64($input, $value)) {
- return false;
+ throw new GPBDecodeException(
+ "Unexpected EOF inside int64 field.");
}
break;
case GPBType::UINT64:
if (!GPBWire::readUint64($input, $value)) {
- return false;
+ throw new GPBDecodeException(
+ "Unexpected EOF inside uint64 field.");
}
break;
case GPBType::INT32:
if (!GPBWire::readInt32($input, $value)) {
- return false;
+ throw new GPBDecodeException(
+ "Unexpected EOF inside int32 field.");
}
break;
case GPBType::FIXED64:
if (!GPBWire::readFixed64($input, $value)) {
- return false;
+ throw new GPBDecodeException(
+ "Unexpected EOF inside fixed64 field.");
}
break;
case GPBType::FIXED32:
if (!GPBWire::readFixed32($input, $value)) {
- return false;
+ throw new GPBDecodeException(
+ "Unexpected EOF inside fixed32 field.");
}
break;
case GPBType::BOOL:
if (!GPBWire::readBool($input, $value)) {
- return false;
+ throw new GPBDecodeException(
+ "Unexpected EOF inside bool field.");
}
break;
case GPBType::STRING:
// TODO(teboring): Add utf-8 check.
if (!GPBWire::readString($input, $value)) {
- return false;
+ throw new GPBDecodeException(
+ "Unexpected EOF inside string field.");
}
break;
case GPBType::GROUP:
- echo "GROUP\xA";
trigger_error("Not implemented.", E_ERROR);
break;
case GPBType::MESSAGE:
@@ -264,43 +358,51 @@ class Message
$value = new $klass;
}
if (!GPBWire::readMessage($input, $value)) {
- return false;
+ throw new GPBDecodeException(
+ "Unexpected EOF inside message.");
}
break;
case GPBType::BYTES:
if (!GPBWire::readString($input, $value)) {
- return false;
+ throw new GPBDecodeException(
+ "Unexpected EOF inside bytes field.");
}
break;
case GPBType::UINT32:
if (!GPBWire::readUint32($input, $value)) {
- return false;
+ throw new GPBDecodeException(
+ "Unexpected EOF inside uint32 field.");
}
break;
case GPBType::ENUM:
// TODO(teboring): Check unknown enum value.
if (!GPBWire::readInt32($input, $value)) {
- return false;
+ throw new GPBDecodeException(
+ "Unexpected EOF inside enum field.");
}
break;
case GPBType::SFIXED32:
if (!GPBWire::readSfixed32($input, $value)) {
- return false;
+ throw new GPBDecodeException(
+ "Unexpected EOF inside sfixed32 field.");
}
break;
case GPBType::SFIXED64:
if (!GPBWire::readSfixed64($input, $value)) {
- return false;
+ throw new GPBDecodeException(
+ "Unexpected EOF inside sfixed64 field.");
}
break;
case GPBType::SINT32:
if (!GPBWire::readSint32($input, $value)) {
- return false;
+ throw new GPBDecodeException(
+ "Unexpected EOF inside sint32 field.");
}
break;
case GPBType::SINT64:
if (!GPBWire::readSint64($input, $value)) {
- return false;
+ throw new GPBDecodeException(
+ "Unexpected EOF inside sint64 field.");
}
break;
default:
@@ -316,71 +418,270 @@ class Message
private function parseFieldFromStream($tag, $input, $field)
{
$value = null;
- $field_type = $field->getType();
- $value_format = GPBWire::UNKNOWN;
- if (GPBWire::getTagWireType($tag) ===
- GPBWire::getWireType($field_type)) {
+ if (is_null($field)) {
+ $value_format = GPBWire::UNKNOWN;
+ } elseif (GPBWire::getTagWireType($tag) ===
+ GPBWire::getWireType($field->getType())) {
$value_format = GPBWire::NORMAL_FORMAT;
} elseif ($field->isPackable() &&
GPBWire::getTagWireType($tag) ===
GPBWire::WIRETYPE_LENGTH_DELIMITED) {
$value_format = GPBWire::PACKED_FORMAT;
+ } else {
+ // the wire type doesn't match. Put it in our unknown field set.
+ $value_format = GPBWire::UNKNOWN;
}
- if ($value_format === GPBWire::NORMAL_FORMAT) {
- if (!self::parseFieldFromStreamNoTag($input, $field, $value)) {
- return false;
- }
+ if ($value_format === GPBWire::UNKNOWN) {
+ $this->skipField($input, $tag);
+ return;
+ } elseif ($value_format === GPBWire::NORMAL_FORMAT) {
+ self::parseFieldFromStreamNoTag($input, $field, $value);
} elseif ($value_format === GPBWire::PACKED_FORMAT) {
$length = 0;
if (!GPBWire::readInt32($input, $length)) {
- return false;
+ throw new GPBDecodeException(
+ "Unexpected EOF inside packed length.");
}
$limit = $input->pushLimit($length);
$getter = $field->getGetter();
while ($input->bytesUntilLimit() > 0) {
- if (!self::parseFieldFromStreamNoTag($input, $field, $value)) {
- return false;
- }
- $this->$getter()[] = $value;
+ self::parseFieldFromStreamNoTag($input, $field, $value);
+ $this->appendHelper($field, $value);
}
$input->popLimit($limit);
- return true;
+ return;
} else {
- return false;
+ return;
}
if ($field->isMap()) {
- $getter = $field->getGetter();
- $this->$getter()[$value->getKey()] = $value->getValue();
+ $this->kvUpdateHelper($field, $value->getKey(), $value->getValue());
} else if ($field->isRepeated()) {
- $getter = $field->getGetter();
- $this->$getter()[] = $value;
+ $this->appendHelper($field, $value);
} else {
$setter = $field->getSetter();
$this->$setter($value);
}
+ }
- return true;
+ /**
+ * Clear all containing fields.
+ * @return null.
+ */
+ public function clear()
+ {
+ $this->unknown = "";
+ foreach ($this->desc->getField() as $field) {
+ $setter = $field->getSetter();
+ if ($field->isMap()) {
+ $message_type = $field->getMessageType();
+ $key_field = $message_type->getFieldByNumber(1);
+ $value_field = $message_type->getFieldByNumber(2);
+ switch ($value_field->getType()) {
+ case GPBType::MESSAGE:
+ case GPBType::GROUP:
+ $map_field = new MapField(
+ $key_field->getType(),
+ $value_field->getType(),
+ $value_field->getMessageType()->getClass());
+ $this->$setter($map_field);
+ break;
+ case GPBType::ENUM:
+ $map_field = new MapField(
+ $key_field->getType(),
+ $value_field->getType(),
+ $value_field->getEnumType()->getClass());
+ $this->$setter($map_field);
+ break;
+ default:
+ $map_field = new MapField(
+ $key_field->getType(),
+ $value_field->getType());
+ $this->$setter($map_field);
+ break;
+ }
+ } else if ($field->getLabel() === GPBLabel::REPEATED) {
+ switch ($field->getType()) {
+ case GPBType::MESSAGE:
+ case GPBType::GROUP:
+ $repeated_field = new RepeatedField(
+ $field->getType(),
+ $field->getMessageType()->getClass());
+ $this->$setter($repeated_field);
+ break;
+ case GPBType::ENUM:
+ $repeated_field = new RepeatedField(
+ $field->getType(),
+ $field->getEnumType()->getClass());
+ $this->$setter($repeated_field);
+ break;
+ default:
+ $repeated_field = new RepeatedField($field->getType());
+ $this->$setter($repeated_field);
+ break;
+ }
+ } else if ($field->getOneofIndex() !== -1) {
+ $oneof = $this->desc->getOneofDecl()[$field->getOneofIndex()];
+ $oneof_name = $oneof->getName();
+ $this->$oneof_name = new OneofField($oneof);
+ } else if ($field->getLabel() === GPBLabel::OPTIONAL) {
+ switch ($field->getType()) {
+ case GPBType::DOUBLE :
+ case GPBType::FLOAT :
+ $this->$setter(0.0);
+ break;
+ case GPBType::INT32 :
+ case GPBType::FIXED32 :
+ case GPBType::UINT32 :
+ case GPBType::SFIXED32 :
+ case GPBType::SINT32 :
+ case GPBType::ENUM :
+ $this->$setter(0);
+ break;
+ case GPBType::BOOL :
+ $this->$setter(false);
+ break;
+ case GPBType::STRING :
+ case GPBType::BYTES :
+ $this->$setter("");
+ break;
+ case GPBType::GROUP :
+ case GPBType::MESSAGE :
+ $null = null;
+ $this->$setter($null);
+ break;
+ }
+ if (PHP_INT_SIZE == 4) {
+ switch ($field->getType()) {
+ case GPBType::INT64:
+ case GPBType::UINT64:
+ case GPBType::FIXED64:
+ case GPBType::SFIXED64:
+ case GPBType::SINT64:
+ $this->$setter("0");
+ }
+ } else {
+ switch ($field->getType()) {
+ case GPBType::INT64:
+ case GPBType::UINT64:
+ case GPBType::FIXED64:
+ case GPBType::SFIXED64:
+ case GPBType::SINT64:
+ $this->$setter(0);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Merges the contents of the specified message into current message.
+ *
+ * This method merges the contents of the specified message into the
+ * current message. Singular fields that are set in the specified message
+ * overwrite the corresponding fields in the current message. Repeated
+ * fields are appended. Map fields key-value pairs are overritten.
+ * Singular/Oneof sub-messages are recursively merged. All overritten
+ * sub-messages are deep-copied.
+ *
+ * @param object $msg Protobuf message to be merged from.
+ * @return null.
+ */
+ public function mergeFrom($msg)
+ {
+ if (get_class($this) !== get_class($msg)) {
+ user_error("Cannot merge messages with different class.");
+ return;
+ }
+
+ foreach ($this->desc->getField() as $field) {
+ $setter = $field->getSetter();
+ $getter = $field->getGetter();
+ if ($field->isMap()) {
+ if (count($msg->$getter()) != 0) {
+ $value_field = $field->getMessageType()->getFieldByNumber(2);
+ foreach ($msg->$getter() as $key => $value) {
+ if ($value_field->getType() == GPBType::MESSAGE) {
+ $klass = $value_field->getMessageType()->getClass();
+ $copy = new $klass;
+ $copy->mergeFrom($value);
+
+ $this->kvUpdateHelper($field, $key, $copy);
+ } else {
+ $this->kvUpdateHelper($field, $key, $value);
+ }
+ }
+ }
+ } else if ($field->getLabel() === GPBLabel::REPEATED) {
+ if (count($msg->$getter()) != 0) {
+ foreach ($msg->$getter() as $tmp) {
+ if ($field->getType() == GPBType::MESSAGE) {
+ $klass = $field->getMessageType()->getClass();
+ $copy = new $klass;
+ $copy->mergeFrom($tmp);
+ $this->appendHelper($field, $copy);
+ } else {
+ $this->appendHelper($field, $tmp);
+ }
+ }
+ }
+ } else if ($field->getLabel() === GPBLabel::OPTIONAL) {
+ if($msg->$getter() !== $this->defaultValue($field)) {
+ $tmp = $msg->$getter();
+ if ($field->getType() == GPBType::MESSAGE) {
+ if (is_null($this->$getter())) {
+ $klass = $field->getMessageType()->getClass();
+ $new_msg = new $klass;
+ $this->$setter($new_msg);
+ }
+ $this->$getter()->mergeFrom($tmp);
+ } else {
+ $this->$setter($tmp);
+ }
+ }
+ }
+ }
}
/**
* Parses a protocol buffer contained in a string.
*
* This function takes a string in the (non-human-readable) binary wire
- * format, matching the encoding output by encode().
+ * format, matching the encoding output by serializeToString().
+ * See mergeFrom() for merging behavior, if the field is already set in the
+ * specified message.
*
* @param string $data Binary protobuf data.
- * @return bool Return true on success.
+ * @return null.
+ * @throws Exception Invalid data.
*/
- public function decode($data)
+ public function mergeFromString($data)
{
- $input = new InputStream($data);
+ $input = new CodedInputStream($data);
$this->parseFromStream($input);
}
/**
+ * Parses a json string to protobuf message.
+ *
+ * This function takes a string in the json wire format, matching the
+ * encoding output by serializeToJsonString().
+ * See mergeFrom() for merging behavior, if the field is already set in the
+ * specified message.
+ *
+ * @param string $data Json protobuf data.
+ * @return null.
+ * @throws Exception Invalid data.
+ */
+ public function mergeFromJsonString($data)
+ {
+ $input = new RawInputStream($data);
+ $this->parseFromJsonStream($input);
+ }
+
+ /**
* @ignore
*/
public function parseFromStream($input)
@@ -395,9 +696,385 @@ class Message
$number = GPBWire::getTagFieldNumber($tag);
$field = $this->desc->getFieldByNumber($number);
- if (!$this->parseFieldFromStream($tag, $input, $field)) {
- return false;
+ $this->parseFieldFromStream($tag, $input, $field);
+ }
+ }
+
+ private function convertJsonValueToProtoValue(
+ $value,
+ $field,
+ $is_map_key = false)
+ {
+ switch ($field->getType()) {
+ case GPBType::MESSAGE:
+ $klass = $field->getMessageType()->getClass();
+ $submsg = new $klass;
+
+ if (is_a($submsg, "Google\Protobuf\Duration")) {
+ if (is_null($value)) {
+ return $this->defaultValue($field);
+ } else if (!is_string($value)) {
+ throw new GPBDecodeException("Expect string.");
+ }
+ return GPBUtil::parseDuration($value);
+ } else if ($field->isTimestamp()) {
+ if (is_null($value)) {
+ return $this->defaultValue($field);
+ } else if (!is_string($value)) {
+ throw new GPBDecodeException("Expect string.");
+ }
+ try {
+ $timestamp = GPBUtil::parseTimestamp($value);
+ } catch (\Exception $e) {
+ throw new GPBDecodeException("Invalid RFC 3339 timestamp: ".$e->getMessage());
+ }
+
+ $submsg->setSeconds($timestamp->getSeconds());
+ $submsg->setNanos($timestamp->getNanos());
+ } else if (is_a($submsg, "Google\Protobuf\FieldMask")) {
+ if (is_null($value)) {
+ return $this->defaultValue($field);
+ }
+ try {
+ return GPBUtil::parseFieldMask($value);
+ } catch (\Exception $e) {
+ throw new GPBDecodeException("Invalid FieldMask: ".$e->getMessage());
+ }
+ } else {
+ if (is_null($value) &&
+ !is_a($submsg, "Google\Protobuf\Value")) {
+ return $this->defaultValue($field);
+ }
+ if (GPBUtil::hasSpecialJsonMapping($submsg)) {
+ } elseif (!is_object($value) && !is_array($value)) {
+ throw new GPBDecodeException("Expect message.");
+ }
+ $submsg->mergeFromJsonArray($value);
+ }
+ return $submsg;
+ case GPBType::ENUM:
+ if (is_null($value)) {
+ return $this->defaultValue($field);
+ } else if (is_integer($value)) {
+ return $value;
+ } else {
+ $enum_value =
+ $field->getEnumType()->getValueByName($value);
+ }
+ if (!is_null($enum_value)) {
+ return $enum_value->getNumber();
+ }
+ case GPBType::STRING:
+ if (is_null($value)) {
+ return $this->defaultValue($field);
+ }
+ if (!is_string($value)) {
+ throw new GPBDecodeException("Expect string");
+ }
+ return $value;
+ case GPBType::BYTES:
+ if (is_null($value)) {
+ return $this->defaultValue($field);
+ }
+ if (!is_string($value)) {
+ throw new GPBDecodeException("Expect string");
+ }
+ $proto_value = base64_decode($value, true);
+ if ($proto_value === false) {
+ throw new GPBDecodeException(
+ "Invalid base64 characters");
+ }
+ return $proto_value;
+ case GPBType::BOOL:
+ if (is_null($value)) {
+ return $this->defaultValue($field);
+ }
+ if ($is_map_key) {
+ if ($value === "true") {
+ return true;
+ }
+ if ($value === "false") {
+ return false;
+ }
+ throw new GPBDecodeException(
+ "Bool field only accept bool value");
+ }
+ if (!is_bool($value)) {
+ throw new GPBDecodeException(
+ "Bool field only accept bool value");
+ }
+ return $value;
+ case GPBType::FLOAT:
+ if (is_null($value)) {
+ return $this->defaultValue($field);
+ }
+ if ($value === "Infinity") {
+ return INF;
+ }
+ if ($value === "-Infinity") {
+ return -INF;
+ }
+ if ($value === "NaN") {
+ return NAN;
+ }
+ return $value;
+ case GPBType::DOUBLE:
+ if (is_null($value)) {
+ return $this->defaultValue($field);
+ }
+ if ($value === "Infinity") {
+ return INF;
+ }
+ if ($value === "-Infinity") {
+ return -INF;
+ }
+ if ($value === "NaN") {
+ return NAN;
+ }
+ return $value;
+ case GPBType::INT32:
+ if (is_null($value)) {
+ return $this->defaultValue($field);
+ }
+ if (!is_numeric($value)) {
+ throw new GPBDecodeException(
+ "Invalid data type for int32 field");
+ }
+ if (bccomp($value, "2147483647") > 0) {
+ throw new GPBDecodeException(
+ "Int32 too large");
+ }
+ if (bccomp($value, "-2147483648") < 0) {
+ throw new GPBDecodeException(
+ "Int32 too small");
+ }
+ return $value;
+ case GPBType::UINT32:
+ if (is_null($value)) {
+ return $this->defaultValue($field);
+ }
+ if (!is_numeric($value)) {
+ throw new GPBDecodeException(
+ "Invalid data type for uint32 field");
+ }
+ if (bccomp($value, 4294967295) > 0) {
+ throw new GPBDecodeException(
+ "Uint32 too large");
+ }
+ return $value;
+ case GPBType::INT64:
+ if (is_null($value)) {
+ return $this->defaultValue($field);
+ }
+ if (!is_numeric($value)) {
+ throw new GPBDecodeException(
+ "Invalid data type for int64 field");
+ }
+ if (bccomp($value, "9223372036854775807") > 0) {
+ throw new GPBDecodeException(
+ "Int64 too large");
+ }
+ if (bccomp($value, "-9223372036854775808") < 0) {
+ throw new GPBDecodeException(
+ "Int64 too small");
+ }
+ return $value;
+ case GPBType::UINT64:
+ if (is_null($value)) {
+ return $this->defaultValue($field);
+ }
+ if (!is_numeric($value)) {
+ throw new GPBDecodeException(
+ "Invalid data type for int64 field");
+ }
+ if (bccomp($value, "18446744073709551615") > 0) {
+ throw new GPBDecodeException(
+ "Uint64 too large");
+ }
+ if (bccomp($value, "9223372036854775807") > 0) {
+ $value = bcsub($value, "18446744073709551616");
+ }
+ return $value;
+ case GPBType::FIXED64:
+ if (is_null($value)) {
+ return $this->defaultValue($field);
+ }
+ return $value;
+ default:
+ return $value;
+ }
+ }
+
+ protected function mergeFromJsonArray($array)
+ {
+ if (is_a($this, "Google\Protobuf\Any")) {
+ $this->clear();
+ $this->setTypeUrl($array["@type"]);
+ $msg = $this->unpack();
+ if (GPBUtil::hasSpecialJsonMapping($msg)) {
+ $msg->mergeFromJsonArray($array["value"]);
+ } else {
+ unset($array["@type"]);
+ $msg->mergeFromJsonArray($array);
}
+ $this->setValue($msg->serializeToString());
+ return;
+ }
+ if (is_a($this, "Google\Protobuf\DoubleValue") ||
+ is_a($this, "Google\Protobuf\FloatValue") ||
+ is_a($this, "Google\Protobuf\Int64Value") ||
+ is_a($this, "Google\Protobuf\UInt64Value") ||
+ is_a($this, "Google\Protobuf\Int32Value") ||
+ is_a($this, "Google\Protobuf\UInt32Value") ||
+ is_a($this, "Google\Protobuf\BoolValue") ||
+ is_a($this, "Google\Protobuf\StringValue")) {
+ $this->setValue($array);
+ return;
+ }
+ if (is_a($this, "Google\Protobuf\BytesValue")) {
+ $this->setValue(base64_decode($array));
+ return;
+ }
+ if (is_a($this, "Google\Protobuf\Duration")) {
+ $this->mergeFrom(GPBUtil::parseDuration($array));
+ return;
+ }
+ if (is_a($this, "Google\Protobuf\FieldMask")) {
+ $this->mergeFrom(GPBUtil::parseFieldMask($array));
+ return;
+ }
+ if (is_a($this, "Google\Protobuf\Timestamp")) {
+ $this->mergeFrom(GPBUtil::parseTimestamp($array));
+ return;
+ }
+ if (is_a($this, "Google\Protobuf\Struct")) {
+ $fields = $this->getFields();
+ foreach($array as $key => $value) {
+ $v = new Value();
+ $v->mergeFromJsonArray($value);
+ $fields[$key] = $v;
+ }
+ }
+ if (is_a($this, "Google\Protobuf\Value")) {
+ if (is_bool($array)) {
+ $this->setBoolValue($array);
+ } elseif (is_string($array)) {
+ $this->setStringValue($array);
+ } elseif (is_null($array)) {
+ $this->setNullValue(0);
+ } elseif (is_double($array) || is_integer($array)) {
+ $this->setNumberValue($array);
+ } elseif (is_array($array)) {
+ if (array_values($array) !== $array) {
+ // Associative array
+ $struct_value = $this->getStructValue();
+ if (is_null($struct_value)) {
+ $struct_value = new Struct();
+ $this->setStructValue($struct_value);
+ }
+ foreach ($array as $key => $v) {
+ $value = new Value();
+ $value->mergeFromJsonArray($v);
+ $values = $struct_value->getFields();
+ $values[$key]= $value;
+ }
+ } else {
+ // Array
+ $list_value = $this->getListValue();
+ if (is_null($list_value)) {
+ $list_value = new ListValue();
+ $this->setListValue($list_value);
+ }
+ foreach ($array as $v) {
+ $value = new Value();
+ $value->mergeFromJsonArray($v);
+ $values = $list_value->getValues();
+ $values[]= $value;
+ }
+ }
+ } else {
+ throw new GPBDecodeException("Invalid type for Value.");
+ }
+ return;
+ }
+ foreach ($array as $key => $value) {
+ $field = $this->desc->getFieldByJsonName($key);
+ if (is_null($field)) {
+ $field = $this->desc->getFieldByName($key);
+ if (is_null($field)) {
+ continue;
+ }
+ }
+ $setter = $field->getSetter();
+ if ($field->isMap()) {
+ if (is_null($value)) {
+ continue;
+ }
+ $key_field = $field->getMessageType()->getFieldByNumber(1);
+ $value_field = $field->getMessageType()->getFieldByNumber(2);
+ foreach ($value as $tmp_key => $tmp_value) {
+ if (is_null($tmp_value)) {
+ throw new \Exception(
+ "Map value field element cannot be null.");
+ }
+ $proto_key =
+ $this->convertJsonValueToProtoValue(
+ $tmp_key,
+ $key_field,
+ true);
+ $proto_value =
+ $this->convertJsonValueToProtoValue(
+ $tmp_value,
+ $value_field);
+ self::kvUpdateHelper($field, $proto_key, $proto_value);
+ }
+ } else if ($field->isRepeated()) {
+ if (is_null($value)) {
+ continue;
+ }
+ foreach ($value as $tmp) {
+ if (is_null($tmp)) {
+ throw new \Exception(
+ "Repeated field elements cannot be null.");
+ }
+ $proto_value =
+ $this->convertJsonValueToProtoValue($tmp, $field);
+ self::appendHelper($field, $proto_value);
+ }
+ } else {
+ $setter = $field->getSetter();
+ $proto_value =
+ $this->convertJsonValueToProtoValue($value, $field);
+ if ($field->getType() === GPBType::MESSAGE) {
+ if (is_null($proto_value)) {
+ continue;
+ }
+ $getter = $field->getGetter();
+ $submsg = $this->$getter();
+ if (!is_null($submsg)) {
+ $submsg->mergeFrom($proto_value);
+ continue;
+ }
+ }
+ $this->$setter($proto_value);
+ }
+ }
+ }
+
+ /**
+ * @ignore
+ */
+ public function parseFromJsonStream($input)
+ {
+ $array = json_decode($input->getData(), JSON_BIGINT_AS_STRING);
+ if (is_null($array)) {
+ throw new GPBDecodeException(
+ "Cannot decode json string.");
+ }
+ try {
+ $this->mergeFromJsonArray($array);
+ } catch (Exception $e) {
+ throw new GPBDecodeException($e->getMessage());
}
}
@@ -440,7 +1117,7 @@ class Message
foreach ($values as $value) {
$size += $this->fieldDataOnlyByteSize($field, $value);
}
- if (!$output->writeVarint32($size)) {
+ if (!$output->writeVarint32($size, true)) {
return false;
}
}
@@ -501,6 +1178,17 @@ class Message
/**
* @ignore
*/
+ private function serializeFieldToJsonStream(&$output, $field)
+ {
+ $getter = $field->getGetter();
+ $values = $this->$getter();
+ return GPBJsonWire::serializeFieldToStream(
+ $values, $field, $output, !GPBUtil::hasSpecialJsonMapping($this));
+ }
+
+ /**
+ * @ignore
+ */
public function serializeToStream(&$output)
{
$fields = $this->desc->getField();
@@ -509,6 +1197,80 @@ class Message
return false;
}
}
+ $output->writeRaw($this->unknown, strlen($this->unknown));
+ return true;
+ }
+
+ /**
+ * @ignore
+ */
+ public function serializeToJsonStream(&$output)
+ {
+ if (is_a($this, 'Google\Protobuf\Any')) {
+ $output->writeRaw("{", 1);
+ $type_field = $this->desc->getFieldByNumber(1);
+ $value_msg = $this->unpack();
+
+ // Serialize type url.
+ $output->writeRaw("\"@type\":", 8);
+ $output->writeRaw("\"", 1);
+ $output->writeRaw($this->getTypeUrl(), strlen($this->getTypeUrl()));
+ $output->writeRaw("\"", 1);
+
+ // Serialize value
+ if (GPBUtil::hasSpecialJsonMapping($value_msg)) {
+ $output->writeRaw(",\"value\":", 9);
+ $value_msg->serializeToJsonStream($output);
+ } else {
+ $value_fields = $value_msg->desc->getField();
+ foreach ($value_fields as $field) {
+ if ($value_msg->existField($field)) {
+ $output->writeRaw(",", 1);
+ if (!$value_msg->serializeFieldToJsonStream($output, $field)) {
+ return false;
+ }
+ }
+ }
+ }
+
+ $output->writeRaw("}", 1);
+ } elseif (is_a($this, 'Google\Protobuf\FieldMask')) {
+ $field_mask = GPBUtil::formatFieldMask($this);
+ $output->writeRaw("\"", 1);
+ $output->writeRaw($field_mask, strlen($field_mask));
+ $output->writeRaw("\"", 1);
+ } elseif (is_a($this, 'Google\Protobuf\Duration')) {
+ $duration = GPBUtil::formatDuration($this) . "s";
+ $output->writeRaw("\"", 1);
+ $output->writeRaw($duration, strlen($duration));
+ $output->writeRaw("\"", 1);
+ } elseif (get_class($this) === 'Google\Protobuf\Timestamp') {
+ $timestamp = GPBUtil::formatTimestamp($this);
+ $timestamp = json_encode($timestamp);
+ $output->writeRaw($timestamp, strlen($timestamp));
+ } else {
+ if (!GPBUtil::hasSpecialJsonMapping($this)) {
+ $output->writeRaw("{", 1);
+ }
+ $fields = $this->desc->getField();
+ $first = true;
+ foreach ($fields as $field) {
+ if ($this->existField($field) ||
+ GPBUtil::hasJsonValue($this)) {
+ if ($first) {
+ $first = false;
+ } else {
+ $output->writeRaw(",", 1);
+ }
+ if (!$this->serializeFieldToJsonStream($output, $field)) {
+ return false;
+ }
+ }
+ }
+ if (!GPBUtil::hasSpecialJsonMapping($this)) {
+ $output->writeRaw("}", 1);
+ }
+ }
return true;
}
@@ -516,21 +1278,45 @@ class Message
* Serialize the message to string.
* @return string Serialized binary protobuf data.
*/
- public function encode()
+ public function serializeToString()
{
- $output = new OutputStream($this->byteSize());
+ $output = new CodedOutputStream($this->byteSize());
$this->serializeToStream($output);
return $output->getData();
}
/**
+ * Serialize the message to json string.
+ * @return string Serialized json protobuf data.
+ */
+ public function serializeToJsonString()
+ {
+ $output = new CodedOutputStream($this->jsonByteSize());
+ $this->serializeToJsonStream($output);
+ return $output->getData();
+ }
+
+ /**
* @ignore
*/
private function existField($field)
{
+ $oneof_index = $field->getOneofIndex();
+ if ($oneof_index !== -1) {
+ $oneof = $this->desc->getOneofDecl()[$oneof_index];
+ $oneof_name = $oneof->getName();
+ return $this->$oneof_name->getNumber() === $field->getNumber();
+ }
+
$getter = $field->getGetter();
- $value = $this->$getter();
- return $value !== $this->defaultValue($field);
+ $values = $this->$getter();
+ if ($field->isMap()) {
+ return count($values) !== 0;
+ } elseif ($field->isRepeated()) {
+ return count($values) !== 0;
+ } else {
+ return $values !== $this->defaultValue($field);
+ }
}
/**
@@ -572,9 +1358,11 @@ class Message
case GPBType::SFIXED64:
$size += 8;
break;
- case GPBType::UINT32:
case GPBType::INT32:
case GPBType::ENUM:
+ $size += GPBWire::varint32Size($value, true);
+ break;
+ case GPBType::UINT32:
$size += GPBWire::varint32Size($value);
break;
case GPBType::UINT64:
@@ -611,6 +1399,111 @@ class Message
/**
* @ignore
*/
+ private function fieldDataOnlyJsonByteSize($field, $value)
+ {
+ $size = 0;
+
+ switch ($field->getType()) {
+ case GPBType::SFIXED32:
+ case GPBType::SINT32:
+ case GPBType::INT32:
+ $size += strlen(strval($value));
+ break;
+ case GPBType::FIXED32:
+ case GPBType::UINT32:
+ if ($value < 0) {
+ $value = bcadd($value, "4294967296");
+ }
+ $size += strlen(strval($value));
+ break;
+ case GPBType::FIXED64:
+ case GPBType::UINT64:
+ if ($value < 0) {
+ $value = bcadd($value, "18446744073709551616");
+ }
+ // Intentional fall through.
+ case GPBType::SFIXED64:
+ case GPBType::INT64:
+ case GPBType::SINT64:
+ $size += 2; // size for ""
+ $size += strlen(strval($value));
+ break;
+ case GPBType::FLOAT:
+ if (is_nan($value)) {
+ $size += strlen("NaN") + 2;
+ } elseif ($value === INF) {
+ $size += strlen("Infinity") + 2;
+ } elseif ($value === -INF) {
+ $size += strlen("-Infinity") + 2;
+ } else {
+ $size += strlen(sprintf("%.8g", $value));
+ }
+ break;
+ case GPBType::DOUBLE:
+ if (is_nan($value)) {
+ $size += strlen("NaN") + 2;
+ } elseif ($value === INF) {
+ $size += strlen("Infinity") + 2;
+ } elseif ($value === -INF) {
+ $size += strlen("-Infinity") + 2;
+ } else {
+ $size += strlen(sprintf("%.17g", $value));
+ }
+ break;
+ case GPBType::ENUM:
+ $enum_desc = $field->getEnumType();
+ if ($enum_desc->getClass() === "Google\Protobuf\NullValue") {
+ $size += 4;
+ break;
+ }
+ $enum_value_desc = $enum_desc->getValueByNumber($value);
+ if (!is_null($enum_value_desc)) {
+ $size += 2; // size for ""
+ $size += strlen($enum_value_desc->getName());
+ } else {
+ $str_value = strval($value);
+ $size += strlen($str_value);
+ }
+ break;
+ case GPBType::BOOL:
+ if ($value) {
+ $size += 4;
+ } else {
+ $size += 5;
+ }
+ break;
+ case GPBType::STRING:
+ $value = json_encode($value);
+ $size += strlen($value);
+ break;
+ case GPBType::BYTES:
+ # if (is_a($this, "Google\Protobuf\BytesValue")) {
+ # $size += strlen(json_encode($value));
+ # } else {
+ # $size += strlen(base64_encode($value));
+ # $size += 2; // size for \"\"
+ # }
+ $size += strlen(base64_encode($value));
+ $size += 2; // size for \"\"
+ break;
+ case GPBType::MESSAGE:
+ $size += $value->jsonByteSize();
+ break;
+# case GPBType::GROUP:
+# // TODO(teboring): Add support.
+# user_error("Unsupported type.");
+# break;
+ default:
+ user_error("Unsupported type " . $field->getType());
+ return 0;
+ }
+
+ return $size;
+ }
+
+ /**
+ * @ignore
+ */
private function fieldByteSize($field)
{
$size = 0;
@@ -625,12 +1518,18 @@ class Message
$value_field = $message_type->getFieldByNumber(2);
foreach ($values as $key => $value) {
$data_size = 0;
- $data_size += $this->fieldDataOnlyByteSize($key_field, $key);
- $data_size += $this->fieldDataOnlyByteSize(
- $value_field,
- $value);
- $data_size += GPBWire::tagSize($key_field);
- $data_size += GPBWire::tagSize($value_field);
+ if ($key != $this->defaultValue($key_field)) {
+ $data_size += $this->fieldDataOnlyByteSize(
+ $key_field,
+ $key);
+ $data_size += GPBWire::tagSize($key_field);
+ }
+ if ($value != $this->defaultValue($value_field)) {
+ $data_size += $this->fieldDataOnlyByteSize(
+ $value_field,
+ $value);
+ $data_size += GPBWire::tagSize($value_field);
+ }
$size += GPBWire::varint32Size($data_size) + $data_size;
}
}
@@ -666,6 +1565,77 @@ class Message
/**
* @ignore
*/
+ private function fieldJsonByteSize($field)
+ {
+ $size = 0;
+
+ if ($field->isMap()) {
+ $getter = $field->getGetter();
+ $values = $this->$getter();
+ $count = count($values);
+ if ($count !== 0) {
+ if (!GPBUtil::hasSpecialJsonMapping($this)) {
+ $size += 3; // size for "\"\":".
+ $size += strlen($field->getJsonName()); // size for field name
+ }
+ $size += 2; // size for "{}".
+ $size += $count - 1; // size for commas
+ $getter = $field->getGetter();
+ $map_entry = $field->getMessageType();
+ $key_field = $map_entry->getFieldByNumber(1);
+ $value_field = $map_entry->getFieldByNumber(2);
+ switch ($key_field->getType()) {
+ case GPBType::STRING:
+ case GPBType::SFIXED64:
+ case GPBType::INT64:
+ case GPBType::SINT64:
+ case GPBType::FIXED64:
+ case GPBType::UINT64:
+ $additional_quote = false;
+ break;
+ default:
+ $additional_quote = true;
+ }
+ foreach ($values as $key => $value) {
+ if ($additional_quote) {
+ $size += 2; // size for ""
+ }
+ $size += $this->fieldDataOnlyJsonByteSize($key_field, $key);
+ $size += $this->fieldDataOnlyJsonByteSize($value_field, $value);
+ $size += 1; // size for :
+ }
+ }
+ } elseif ($field->isRepeated()) {
+ $getter = $field->getGetter();
+ $values = $this->$getter();
+ $count = count($values);
+ if ($count !== 0) {
+ if (!GPBUtil::hasSpecialJsonMapping($this)) {
+ $size += 3; // size for "\"\":".
+ $size += strlen($field->getJsonName()); // size for field name
+ }
+ $size += 2; // size for "[]".
+ $size += $count - 1; // size for commas
+ $getter = $field->getGetter();
+ foreach ($values as $value) {
+ $size += $this->fieldDataOnlyJsonByteSize($field, $value);
+ }
+ }
+ } elseif ($this->existField($field) || GPBUtil::hasJsonValue($this)) {
+ if (!GPBUtil::hasSpecialJsonMapping($this)) {
+ $size += 3; // size for "\"\":".
+ $size += strlen($field->getJsonName()); // size for field name
+ }
+ $getter = $field->getGetter();
+ $value = $this->$getter();
+ $size += $this->fieldDataOnlyJsonByteSize($field, $value);
+ }
+ return $size;
+ }
+
+ /**
+ * @ignore
+ */
public function byteSize()
{
$size = 0;
@@ -674,6 +1644,89 @@ class Message
foreach ($fields as $field) {
$size += $this->fieldByteSize($field);
}
+ $size += strlen($this->unknown);
+ return $size;
+ }
+
+ private function appendHelper($field, $append_value)
+ {
+ $getter = $field->getGetter();
+ $setter = $field->getSetter();
+
+ $field_arr_value = $this->$getter();
+ $field_arr_value[] = $append_value;
+
+ if (!is_object($field_arr_value)) {
+ $this->$setter($field_arr_value);
+ }
+ }
+
+ private function kvUpdateHelper($field, $update_key, $update_value)
+ {
+ $getter = $field->getGetter();
+ $setter = $field->getSetter();
+
+ $field_arr_value = $this->$getter();
+ $field_arr_value[$update_key] = $update_value;
+
+ if (!is_object($field_arr_value)) {
+ $this->$setter($field_arr_value);
+ }
+ }
+
+ /**
+ * @ignore
+ */
+ public function jsonByteSize()
+ {
+ $size = 0;
+ if (is_a($this, 'Google\Protobuf\Any')) {
+ // Size for "{}".
+ $size += 2;
+
+ // Size for "\"@type\":".
+ $size += 8;
+
+ // Size for url. +2 for "" /.
+ $size += strlen($this->getTypeUrl()) + 2;
+
+ $value_msg = $this->unpack();
+ if (GPBUtil::hasSpecialJsonMapping($value_msg)) {
+ // Size for "\",value\":".
+ $size += 9;
+ $size += $value_msg->jsonByteSize();
+ } else {
+ // Size for value. +1 for comma, -2 for "{}".
+ $size += $value_msg->jsonByteSize() -1;
+ }
+ } elseif (get_class($this) === 'Google\Protobuf\FieldMask') {
+ $field_mask = GPBUtil::formatFieldMask($this);
+ $size += strlen($field_mask) + 2; // 2 for ""
+ } elseif (get_class($this) === 'Google\Protobuf\Duration') {
+ $duration = GPBUtil::formatDuration($this) . "s";
+ $size += strlen($duration) + 2; // 2 for ""
+ } elseif (get_class($this) === 'Google\Protobuf\Timestamp') {
+ $timestamp = GPBUtil::formatTimestamp($this);
+ $timestamp = json_encode($timestamp);
+ $size += strlen($timestamp);
+ } else {
+ if (!GPBUtil::hasSpecialJsonMapping($this)) {
+ // Size for "{}".
+ $size += 2;
+ }
+
+ $fields = $this->desc->getField();
+ $count = 0;
+ foreach ($fields as $field) {
+ $field_size = $this->fieldJsonByteSize($field);
+ $size += $field_size;
+ if ($field_size != 0) {
+ $count++;
+ }
+ }
+ // size for comma
+ $size += $count > 0 ? ($count - 1) : 0;
+ }
return $size;
}
}
diff --git a/php/src/Google/Protobuf/Internal/MessageOptions.php b/php/src/Google/Protobuf/Internal/MessageOptions.php
index e4a214cb..99ff3d0e 100644
--- a/php/src/Google/Protobuf/Internal/MessageOptions.php
+++ b/php/src/Google/Protobuf/Internal/MessageOptions.php
@@ -8,16 +8,14 @@ use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\GPBWire;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\InputStream;
-
use Google\Protobuf\Internal\GPBUtil;
/**
- * Protobuf type <code>google.protobuf.MessageOptions</code>
+ * Generated from protobuf message <code>google.protobuf.MessageOptions</code>
*/
class MessageOptions extends \Google\Protobuf\Internal\Message
{
/**
- * <pre>
* Set true to use the old proto1 MessageSet wire format for extensions.
* This is provided for backwards-compatibility with the MessageSet wire
* format. You should not use this for any other reason: It's less
@@ -33,41 +31,35 @@ class MessageOptions extends \Google\Protobuf\Internal\Message
* be int32s, enums, or repeated messages.
* Because this is an option, the above two restrictions are not enforced by
* the protocol compiler.
- * </pre>
*
- * <code>optional bool message_set_wire_format = 1 [default = false];</code>
+ * Generated from protobuf field <code>optional bool message_set_wire_format = 1 [default = false];</code>
*/
private $message_set_wire_format = false;
private $has_message_set_wire_format = false;
/**
- * <pre>
* Disables the generation of the standard "descriptor()" accessor, which can
* conflict with a field of the same name. This is meant to make migration
* from proto1 easier; new code should avoid fields named "descriptor".
- * </pre>
*
- * <code>optional bool no_standard_descriptor_accessor = 2 [default = false];</code>
+ * Generated from protobuf field <code>optional bool no_standard_descriptor_accessor = 2 [default = false];</code>
*/
private $no_standard_descriptor_accessor = false;
private $has_no_standard_descriptor_accessor = false;
/**
- * <pre>
* Is this message deprecated?
* Depending on the target platform, this can emit Deprecated annotations
* for the message, or it will be completely ignored; in the very least,
* this is a formalization for deprecating messages.
- * </pre>
*
- * <code>optional bool deprecated = 3 [default = false];</code>
+ * Generated from protobuf field <code>optional bool deprecated = 3 [default = false];</code>
*/
private $deprecated = false;
private $has_deprecated = false;
/**
- * <pre>
* Whether the message is an automatically generated map entry type for the
* maps field.
* For maps fields:
- * map&lt;KeyType, ValueType&gt; map_field = 1;
+ * map<KeyType, ValueType> map_field = 1;
* The parsed descriptor looks like:
* message MapFieldEntry {
* option map_entry = true;
@@ -82,18 +74,15 @@ class MessageOptions extends \Google\Protobuf\Internal\Message
* NOTE: Do not set the option in .proto files. Always use the maps syntax
* instead. The option should only be implicitly set by the proto compiler
* parser.
- * </pre>
*
- * <code>optional bool map_entry = 7;</code>
+ * Generated from protobuf field <code>optional bool map_entry = 7;</code>
*/
private $map_entry = false;
private $has_map_entry = false;
/**
- * <pre>
* The parser stores options it doesn't recognize here. See above.
- * </pre>
*
- * <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
*/
private $uninterpreted_option;
private $has_uninterpreted_option = false;
@@ -104,7 +93,6 @@ class MessageOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Set true to use the old proto1 MessageSet wire format for extensions.
* This is provided for backwards-compatibility with the MessageSet wire
* format. You should not use this for any other reason: It's less
@@ -120,9 +108,9 @@ class MessageOptions extends \Google\Protobuf\Internal\Message
* be int32s, enums, or repeated messages.
* Because this is an option, the above two restrictions are not enforced by
* the protocol compiler.
- * </pre>
*
- * <code>optional bool message_set_wire_format = 1 [default = false];</code>
+ * Generated from protobuf field <code>optional bool message_set_wire_format = 1 [default = false];</code>
+ * @return bool
*/
public function getMessageSetWireFormat()
{
@@ -130,7 +118,6 @@ class MessageOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Set true to use the old proto1 MessageSet wire format for extensions.
* This is provided for backwards-compatibility with the MessageSet wire
* format. You should not use this for any other reason: It's less
@@ -146,15 +133,18 @@ class MessageOptions extends \Google\Protobuf\Internal\Message
* be int32s, enums, or repeated messages.
* Because this is an option, the above two restrictions are not enforced by
* the protocol compiler.
- * </pre>
*
- * <code>optional bool message_set_wire_format = 1 [default = false];</code>
+ * Generated from protobuf field <code>optional bool message_set_wire_format = 1 [default = false];</code>
+ * @param bool $var
+ * @return $this
*/
public function setMessageSetWireFormat($var)
{
GPBUtil::checkBool($var);
$this->message_set_wire_format = $var;
$this->has_message_set_wire_format = true;
+
+ return $this;
}
public function hasMessageSetWireFormat()
@@ -163,13 +153,12 @@ class MessageOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Disables the generation of the standard "descriptor()" accessor, which can
* conflict with a field of the same name. This is meant to make migration
* from proto1 easier; new code should avoid fields named "descriptor".
- * </pre>
*
- * <code>optional bool no_standard_descriptor_accessor = 2 [default = false];</code>
+ * Generated from protobuf field <code>optional bool no_standard_descriptor_accessor = 2 [default = false];</code>
+ * @return bool
*/
public function getNoStandardDescriptorAccessor()
{
@@ -177,19 +166,21 @@ class MessageOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Disables the generation of the standard "descriptor()" accessor, which can
* conflict with a field of the same name. This is meant to make migration
* from proto1 easier; new code should avoid fields named "descriptor".
- * </pre>
*
- * <code>optional bool no_standard_descriptor_accessor = 2 [default = false];</code>
+ * Generated from protobuf field <code>optional bool no_standard_descriptor_accessor = 2 [default = false];</code>
+ * @param bool $var
+ * @return $this
*/
public function setNoStandardDescriptorAccessor($var)
{
GPBUtil::checkBool($var);
$this->no_standard_descriptor_accessor = $var;
$this->has_no_standard_descriptor_accessor = true;
+
+ return $this;
}
public function hasNoStandardDescriptorAccessor()
@@ -198,14 +189,13 @@ class MessageOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Is this message deprecated?
* Depending on the target platform, this can emit Deprecated annotations
* for the message, or it will be completely ignored; in the very least,
* this is a formalization for deprecating messages.
- * </pre>
*
- * <code>optional bool deprecated = 3 [default = false];</code>
+ * Generated from protobuf field <code>optional bool deprecated = 3 [default = false];</code>
+ * @return bool
*/
public function getDeprecated()
{
@@ -213,20 +203,22 @@ class MessageOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Is this message deprecated?
* Depending on the target platform, this can emit Deprecated annotations
* for the message, or it will be completely ignored; in the very least,
* this is a formalization for deprecating messages.
- * </pre>
*
- * <code>optional bool deprecated = 3 [default = false];</code>
+ * Generated from protobuf field <code>optional bool deprecated = 3 [default = false];</code>
+ * @param bool $var
+ * @return $this
*/
public function setDeprecated($var)
{
GPBUtil::checkBool($var);
$this->deprecated = $var;
$this->has_deprecated = true;
+
+ return $this;
}
public function hasDeprecated()
@@ -235,11 +227,10 @@ class MessageOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Whether the message is an automatically generated map entry type for the
* maps field.
* For maps fields:
- * map&lt;KeyType, ValueType&gt; map_field = 1;
+ * map<KeyType, ValueType> map_field = 1;
* The parsed descriptor looks like:
* message MapFieldEntry {
* option map_entry = true;
@@ -254,9 +245,9 @@ class MessageOptions extends \Google\Protobuf\Internal\Message
* NOTE: Do not set the option in .proto files. Always use the maps syntax
* instead. The option should only be implicitly set by the proto compiler
* parser.
- * </pre>
*
- * <code>optional bool map_entry = 7;</code>
+ * Generated from protobuf field <code>optional bool map_entry = 7;</code>
+ * @return bool
*/
public function getMapEntry()
{
@@ -264,11 +255,10 @@ class MessageOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Whether the message is an automatically generated map entry type for the
* maps field.
* For maps fields:
- * map&lt;KeyType, ValueType&gt; map_field = 1;
+ * map<KeyType, ValueType> map_field = 1;
* The parsed descriptor looks like:
* message MapFieldEntry {
* option map_entry = true;
@@ -283,15 +273,18 @@ class MessageOptions extends \Google\Protobuf\Internal\Message
* NOTE: Do not set the option in .proto files. Always use the maps syntax
* instead. The option should only be implicitly set by the proto compiler
* parser.
- * </pre>
*
- * <code>optional bool map_entry = 7;</code>
+ * Generated from protobuf field <code>optional bool map_entry = 7;</code>
+ * @param bool $var
+ * @return $this
*/
public function setMapEntry($var)
{
GPBUtil::checkBool($var);
$this->map_entry = $var;
$this->has_map_entry = true;
+
+ return $this;
}
public function hasMapEntry()
@@ -300,11 +293,10 @@ class MessageOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* The parser stores options it doesn't recognize here. See above.
- * </pre>
*
- * <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
*/
public function getUninterpretedOption()
{
@@ -312,17 +304,19 @@ class MessageOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* The parser stores options it doesn't recognize here. See above.
- * </pre>
*
- * <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * @param \Google\Protobuf\Internal\UninterpretedOption[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
*/
- public function setUninterpretedOption(&$var)
+ public function setUninterpretedOption($var)
{
- GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\UninterpretedOption::class);
- $this->uninterpreted_option = $var;
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\UninterpretedOption::class);
+ $this->uninterpreted_option = $arr;
$this->has_uninterpreted_option = true;
+
+ return $this;
}
public function hasUninterpretedOption()
diff --git a/php/src/Google/Protobuf/Internal/MethodDescriptorProto.php b/php/src/Google/Protobuf/Internal/MethodDescriptorProto.php
index 3d8df7af..ccfce2db 100644
--- a/php/src/Google/Protobuf/Internal/MethodDescriptorProto.php
+++ b/php/src/Google/Protobuf/Internal/MethodDescriptorProto.php
@@ -8,58 +8,49 @@ use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\GPBWire;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\InputStream;
-
use Google\Protobuf\Internal\GPBUtil;
/**
- * <pre>
* Describes a method of a service.
- * </pre>
*
- * Protobuf type <code>google.protobuf.MethodDescriptorProto</code>
+ * Generated from protobuf message <code>google.protobuf.MethodDescriptorProto</code>
*/
class MethodDescriptorProto extends \Google\Protobuf\Internal\Message
{
/**
- * <code>optional string name = 1;</code>
+ * Generated from protobuf field <code>optional string name = 1;</code>
*/
private $name = '';
private $has_name = false;
/**
- * <pre>
* Input and output type names. These are resolved in the same way as
* FieldDescriptorProto.type_name, but must refer to a message type.
- * </pre>
*
- * <code>optional string input_type = 2;</code>
+ * Generated from protobuf field <code>optional string input_type = 2;</code>
*/
private $input_type = '';
private $has_input_type = false;
/**
- * <code>optional string output_type = 3;</code>
+ * Generated from protobuf field <code>optional string output_type = 3;</code>
*/
private $output_type = '';
private $has_output_type = false;
/**
- * <code>optional .google.protobuf.MethodOptions options = 4;</code>
+ * Generated from protobuf field <code>optional .google.protobuf.MethodOptions options = 4;</code>
*/
private $options = null;
private $has_options = false;
/**
- * <pre>
* Identifies if client streams multiple client messages
- * </pre>
*
- * <code>optional bool client_streaming = 5 [default = false];</code>
+ * Generated from protobuf field <code>optional bool client_streaming = 5 [default = false];</code>
*/
private $client_streaming = false;
private $has_client_streaming = false;
/**
- * <pre>
* Identifies if server streams multiple server messages
- * </pre>
*
- * <code>optional bool server_streaming = 6 [default = false];</code>
+ * Generated from protobuf field <code>optional bool server_streaming = 6 [default = false];</code>
*/
private $server_streaming = false;
private $has_server_streaming = false;
@@ -70,7 +61,8 @@ class MethodDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional string name = 1;</code>
+ * Generated from protobuf field <code>optional string name = 1;</code>
+ * @return string
*/
public function getName()
{
@@ -78,13 +70,17 @@ class MethodDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional string name = 1;</code>
+ * Generated from protobuf field <code>optional string name = 1;</code>
+ * @param string $var
+ * @return $this
*/
public function setName($var)
{
GPBUtil::checkString($var, True);
$this->name = $var;
$this->has_name = true;
+
+ return $this;
}
public function hasName()
@@ -93,12 +89,11 @@ class MethodDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Input and output type names. These are resolved in the same way as
* FieldDescriptorProto.type_name, but must refer to a message type.
- * </pre>
*
- * <code>optional string input_type = 2;</code>
+ * Generated from protobuf field <code>optional string input_type = 2;</code>
+ * @return string
*/
public function getInputType()
{
@@ -106,18 +101,20 @@ class MethodDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Input and output type names. These are resolved in the same way as
* FieldDescriptorProto.type_name, but must refer to a message type.
- * </pre>
*
- * <code>optional string input_type = 2;</code>
+ * Generated from protobuf field <code>optional string input_type = 2;</code>
+ * @param string $var
+ * @return $this
*/
public function setInputType($var)
{
GPBUtil::checkString($var, True);
$this->input_type = $var;
$this->has_input_type = true;
+
+ return $this;
}
public function hasInputType()
@@ -126,7 +123,8 @@ class MethodDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional string output_type = 3;</code>
+ * Generated from protobuf field <code>optional string output_type = 3;</code>
+ * @return string
*/
public function getOutputType()
{
@@ -134,13 +132,17 @@ class MethodDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional string output_type = 3;</code>
+ * Generated from protobuf field <code>optional string output_type = 3;</code>
+ * @param string $var
+ * @return $this
*/
public function setOutputType($var)
{
GPBUtil::checkString($var, True);
$this->output_type = $var;
$this->has_output_type = true;
+
+ return $this;
}
public function hasOutputType()
@@ -149,7 +151,8 @@ class MethodDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional .google.protobuf.MethodOptions options = 4;</code>
+ * Generated from protobuf field <code>optional .google.protobuf.MethodOptions options = 4;</code>
+ * @return \Google\Protobuf\Internal\MethodOptions
*/
public function getOptions()
{
@@ -157,13 +160,17 @@ class MethodDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional .google.protobuf.MethodOptions options = 4;</code>
+ * Generated from protobuf field <code>optional .google.protobuf.MethodOptions options = 4;</code>
+ * @param \Google\Protobuf\Internal\MethodOptions $var
+ * @return $this
*/
- public function setOptions(&$var)
+ public function setOptions($var)
{
GPBUtil::checkMessage($var, \Google\Protobuf\Internal\MethodOptions::class);
$this->options = $var;
$this->has_options = true;
+
+ return $this;
}
public function hasOptions()
@@ -172,11 +179,10 @@ class MethodDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Identifies if client streams multiple client messages
- * </pre>
*
- * <code>optional bool client_streaming = 5 [default = false];</code>
+ * Generated from protobuf field <code>optional bool client_streaming = 5 [default = false];</code>
+ * @return bool
*/
public function getClientStreaming()
{
@@ -184,17 +190,19 @@ class MethodDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Identifies if client streams multiple client messages
- * </pre>
*
- * <code>optional bool client_streaming = 5 [default = false];</code>
+ * Generated from protobuf field <code>optional bool client_streaming = 5 [default = false];</code>
+ * @param bool $var
+ * @return $this
*/
public function setClientStreaming($var)
{
GPBUtil::checkBool($var);
$this->client_streaming = $var;
$this->has_client_streaming = true;
+
+ return $this;
}
public function hasClientStreaming()
@@ -203,11 +211,10 @@ class MethodDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Identifies if server streams multiple server messages
- * </pre>
*
- * <code>optional bool server_streaming = 6 [default = false];</code>
+ * Generated from protobuf field <code>optional bool server_streaming = 6 [default = false];</code>
+ * @return bool
*/
public function getServerStreaming()
{
@@ -215,17 +222,19 @@ class MethodDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Identifies if server streams multiple server messages
- * </pre>
*
- * <code>optional bool server_streaming = 6 [default = false];</code>
+ * Generated from protobuf field <code>optional bool server_streaming = 6 [default = false];</code>
+ * @param bool $var
+ * @return $this
*/
public function setServerStreaming($var)
{
GPBUtil::checkBool($var);
$this->server_streaming = $var;
$this->has_server_streaming = true;
+
+ return $this;
}
public function hasServerStreaming()
diff --git a/php/src/Google/Protobuf/Internal/MethodOptions.php b/php/src/Google/Protobuf/Internal/MethodOptions.php
index 3325e52b..baa806b7 100644
--- a/php/src/Google/Protobuf/Internal/MethodOptions.php
+++ b/php/src/Google/Protobuf/Internal/MethodOptions.php
@@ -8,37 +8,32 @@ use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\GPBWire;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\InputStream;
-
use Google\Protobuf\Internal\GPBUtil;
/**
- * Protobuf type <code>google.protobuf.MethodOptions</code>
+ * Generated from protobuf message <code>google.protobuf.MethodOptions</code>
*/
class MethodOptions extends \Google\Protobuf\Internal\Message
{
/**
- * <pre>
* Is this method deprecated?
* Depending on the target platform, this can emit Deprecated annotations
* for the method, or it will be completely ignored; in the very least,
* this is a formalization for deprecating methods.
- * </pre>
*
- * <code>optional bool deprecated = 33 [default = false];</code>
+ * Generated from protobuf field <code>optional bool deprecated = 33 [default = false];</code>
*/
private $deprecated = false;
private $has_deprecated = false;
/**
- * <code>optional .google.protobuf.MethodOptions.IdempotencyLevel idempotency_level = 34 [default = IDEMPOTENCY_UNKNOWN];</code>
+ * Generated from protobuf field <code>optional .google.protobuf.MethodOptions.IdempotencyLevel idempotency_level = 34 [default = IDEMPOTENCY_UNKNOWN];</code>
*/
private $idempotency_level = 0;
private $has_idempotency_level = false;
/**
- * <pre>
* The parser stores options it doesn't recognize here. See above.
- * </pre>
*
- * <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
*/
private $uninterpreted_option;
private $has_uninterpreted_option = false;
@@ -49,14 +44,13 @@ class MethodOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Is this method deprecated?
* Depending on the target platform, this can emit Deprecated annotations
* for the method, or it will be completely ignored; in the very least,
* this is a formalization for deprecating methods.
- * </pre>
*
- * <code>optional bool deprecated = 33 [default = false];</code>
+ * Generated from protobuf field <code>optional bool deprecated = 33 [default = false];</code>
+ * @return bool
*/
public function getDeprecated()
{
@@ -64,20 +58,22 @@ class MethodOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Is this method deprecated?
* Depending on the target platform, this can emit Deprecated annotations
* for the method, or it will be completely ignored; in the very least,
* this is a formalization for deprecating methods.
- * </pre>
*
- * <code>optional bool deprecated = 33 [default = false];</code>
+ * Generated from protobuf field <code>optional bool deprecated = 33 [default = false];</code>
+ * @param bool $var
+ * @return $this
*/
public function setDeprecated($var)
{
GPBUtil::checkBool($var);
$this->deprecated = $var;
$this->has_deprecated = true;
+
+ return $this;
}
public function hasDeprecated()
@@ -86,7 +82,8 @@ class MethodOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional .google.protobuf.MethodOptions.IdempotencyLevel idempotency_level = 34 [default = IDEMPOTENCY_UNKNOWN];</code>
+ * Generated from protobuf field <code>optional .google.protobuf.MethodOptions.IdempotencyLevel idempotency_level = 34 [default = IDEMPOTENCY_UNKNOWN];</code>
+ * @return int
*/
public function getIdempotencyLevel()
{
@@ -94,13 +91,17 @@ class MethodOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional .google.protobuf.MethodOptions.IdempotencyLevel idempotency_level = 34 [default = IDEMPOTENCY_UNKNOWN];</code>
+ * Generated from protobuf field <code>optional .google.protobuf.MethodOptions.IdempotencyLevel idempotency_level = 34 [default = IDEMPOTENCY_UNKNOWN];</code>
+ * @param int $var
+ * @return $this
*/
public function setIdempotencyLevel($var)
{
GPBUtil::checkEnum($var, \Google\Protobuf\Internal\MethodOptions_IdempotencyLevel::class);
$this->idempotency_level = $var;
$this->has_idempotency_level = true;
+
+ return $this;
}
public function hasIdempotencyLevel()
@@ -109,11 +110,10 @@ class MethodOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* The parser stores options it doesn't recognize here. See above.
- * </pre>
*
- * <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
*/
public function getUninterpretedOption()
{
@@ -121,17 +121,19 @@ class MethodOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* The parser stores options it doesn't recognize here. See above.
- * </pre>
*
- * <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * @param \Google\Protobuf\Internal\UninterpretedOption[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
*/
- public function setUninterpretedOption(&$var)
+ public function setUninterpretedOption($var)
{
- GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\UninterpretedOption::class);
- $this->uninterpreted_option = $var;
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\UninterpretedOption::class);
+ $this->uninterpreted_option = $arr;
$this->has_uninterpreted_option = true;
+
+ return $this;
}
public function hasUninterpretedOption()
diff --git a/php/src/Google/Protobuf/Internal/MethodOptions_IdempotencyLevel.php b/php/src/Google/Protobuf/Internal/MethodOptions_IdempotencyLevel.php
index 62768b5c..9e06d8ee 100644
--- a/php/src/Google/Protobuf/Internal/MethodOptions_IdempotencyLevel.php
+++ b/php/src/Google/Protobuf/Internal/MethodOptions_IdempotencyLevel.php
@@ -2,37 +2,31 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/descriptor.proto
+namespace Google\Protobuf\Internal;
+
/**
- * <pre>
* Is this method side-effect-free (or safe in HTTP parlance), or idempotent,
* or neither? HTTP based RPC implementation may choose GET verb for safe
* methods, and PUT verb for idempotent methods instead of the default POST.
- * </pre>
*
- * Protobuf enum <code>google.protobuf.MethodOptions.IdempotencyLevel</code>
+ * Protobuf enum <code>Google\Protobuf\Internal</code>
*/
-namespace Google\Protobuf\Internal;
-
class MethodOptions_IdempotencyLevel
{
/**
- * <code>IDEMPOTENCY_UNKNOWN = 0;</code>
+ * Generated from protobuf enum <code>IDEMPOTENCY_UNKNOWN = 0;</code>
*/
const IDEMPOTENCY_UNKNOWN = 0;
/**
- * <pre>
* implies idempotent
- * </pre>
*
- * <code>NO_SIDE_EFFECTS = 1;</code>
+ * Generated from protobuf enum <code>NO_SIDE_EFFECTS = 1;</code>
*/
const NO_SIDE_EFFECTS = 1;
/**
- * <pre>
* idempotent, but may have side effects
- * </pre>
*
- * <code>IDEMPOTENT = 2;</code>
+ * Generated from protobuf enum <code>IDEMPOTENT = 2;</code>
*/
const IDEMPOTENT = 2;
}
diff --git a/php/src/Google/Protobuf/Internal/OneofDescriptor.php b/php/src/Google/Protobuf/Internal/OneofDescriptor.php
new file mode 100644
index 00000000..67b107f6
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/OneofDescriptor.php
@@ -0,0 +1,78 @@
+<?php
+
+// 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.
+
+namespace Google\Protobuf\Internal;
+
+class OneofDescriptor
+{
+ use HasPublicDescriptorTrait;
+
+ private $name;
+ private $fields;
+
+ public function __construct()
+ {
+ $this->public_desc = new \Google\Protobuf\OneofDescriptor($this);
+ }
+
+ public function setName($name)
+ {
+ $this->name = $name;
+ }
+
+ public function getName()
+ {
+ return $this->name;
+ }
+
+ public function addField(FieldDescriptor $field)
+ {
+ $this->fields[] = $field;
+ }
+
+ public function getFields()
+ {
+ return $this->fields;
+ }
+
+ public static function buildFromProto($oneof_proto, $desc, $index)
+ {
+ $oneof = new OneofDescriptor();
+ $oneof->setName($oneof_proto->getName());
+ foreach ($desc->getField() as $field) {
+ if ($field->getOneofIndex() == $index) {
+ $oneof->addField($field);
+ }
+ }
+ return $oneof;
+ }
+}
diff --git a/php/src/Google/Protobuf/Internal/OneofDescriptorProto.php b/php/src/Google/Protobuf/Internal/OneofDescriptorProto.php
index e5fbe370..15ff0610 100644
--- a/php/src/Google/Protobuf/Internal/OneofDescriptorProto.php
+++ b/php/src/Google/Protobuf/Internal/OneofDescriptorProto.php
@@ -8,25 +8,22 @@ use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\GPBWire;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\InputStream;
-
use Google\Protobuf\Internal\GPBUtil;
/**
- * <pre>
* Describes a oneof.
- * </pre>
*
- * Protobuf type <code>google.protobuf.OneofDescriptorProto</code>
+ * Generated from protobuf message <code>google.protobuf.OneofDescriptorProto</code>
*/
class OneofDescriptorProto extends \Google\Protobuf\Internal\Message
{
/**
- * <code>optional string name = 1;</code>
+ * Generated from protobuf field <code>optional string name = 1;</code>
*/
private $name = '';
private $has_name = false;
/**
- * <code>optional .google.protobuf.OneofOptions options = 2;</code>
+ * Generated from protobuf field <code>optional .google.protobuf.OneofOptions options = 2;</code>
*/
private $options = null;
private $has_options = false;
@@ -37,7 +34,8 @@ class OneofDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional string name = 1;</code>
+ * Generated from protobuf field <code>optional string name = 1;</code>
+ * @return string
*/
public function getName()
{
@@ -45,13 +43,17 @@ class OneofDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional string name = 1;</code>
+ * Generated from protobuf field <code>optional string name = 1;</code>
+ * @param string $var
+ * @return $this
*/
public function setName($var)
{
GPBUtil::checkString($var, True);
$this->name = $var;
$this->has_name = true;
+
+ return $this;
}
public function hasName()
@@ -60,7 +62,8 @@ class OneofDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional .google.protobuf.OneofOptions options = 2;</code>
+ * Generated from protobuf field <code>optional .google.protobuf.OneofOptions options = 2;</code>
+ * @return \Google\Protobuf\Internal\OneofOptions
*/
public function getOptions()
{
@@ -68,13 +71,17 @@ class OneofDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional .google.protobuf.OneofOptions options = 2;</code>
+ * Generated from protobuf field <code>optional .google.protobuf.OneofOptions options = 2;</code>
+ * @param \Google\Protobuf\Internal\OneofOptions $var
+ * @return $this
*/
- public function setOptions(&$var)
+ public function setOptions($var)
{
GPBUtil::checkMessage($var, \Google\Protobuf\Internal\OneofOptions::class);
$this->options = $var;
$this->has_options = true;
+
+ return $this;
}
public function hasOptions()
diff --git a/php/src/Google/Protobuf/Internal/OneofOptions.php b/php/src/Google/Protobuf/Internal/OneofOptions.php
index 083d9929..e5b4633d 100644
--- a/php/src/Google/Protobuf/Internal/OneofOptions.php
+++ b/php/src/Google/Protobuf/Internal/OneofOptions.php
@@ -8,20 +8,17 @@ use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\GPBWire;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\InputStream;
-
use Google\Protobuf\Internal\GPBUtil;
/**
- * Protobuf type <code>google.protobuf.OneofOptions</code>
+ * Generated from protobuf message <code>google.protobuf.OneofOptions</code>
*/
class OneofOptions extends \Google\Protobuf\Internal\Message
{
/**
- * <pre>
* The parser stores options it doesn't recognize here. See above.
- * </pre>
*
- * <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
*/
private $uninterpreted_option;
private $has_uninterpreted_option = false;
@@ -32,11 +29,10 @@ class OneofOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* The parser stores options it doesn't recognize here. See above.
- * </pre>
*
- * <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
*/
public function getUninterpretedOption()
{
@@ -44,17 +40,19 @@ class OneofOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* The parser stores options it doesn't recognize here. See above.
- * </pre>
*
- * <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * @param \Google\Protobuf\Internal\UninterpretedOption[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
*/
- public function setUninterpretedOption(&$var)
+ public function setUninterpretedOption($var)
{
- GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\UninterpretedOption::class);
- $this->uninterpreted_option = $var;
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\UninterpretedOption::class);
+ $this->uninterpreted_option = $arr;
$this->has_uninterpreted_option = true;
+
+ return $this;
}
public function hasUninterpretedOption()
diff --git a/php/src/Google/Protobuf/Internal/RawInputStream.php b/php/src/Google/Protobuf/Internal/RawInputStream.php
new file mode 100644
index 00000000..4e7ed5cb
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/RawInputStream.php
@@ -0,0 +1,50 @@
+<?php
+
+// 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.
+
+namespace Google\Protobuf\Internal;
+
+class RawInputStream
+{
+
+ private $buffer;
+
+ public function __construct($buffer)
+ {
+ $this->buffer = $buffer;
+ }
+
+ public function getData()
+ {
+ return $this->buffer;
+ }
+
+}
diff --git a/php/src/Google/Protobuf/Internal/RepeatedField.php b/php/src/Google/Protobuf/Internal/RepeatedField.php
index 0dc5d9d2..797b3b3a 100644
--- a/php/src/Google/Protobuf/Internal/RepeatedField.php
+++ b/php/src/Google/Protobuf/Internal/RepeatedField.php
@@ -41,86 +41,6 @@ use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\GPBUtil;
/**
- * RepeatedFieldIter is used to iterate RepeatedField. It is also need for the
- * foreach syntax.
- */
-class RepeatedFieldIter implements \Iterator
-{
-
- /**
- * @ignore
- */
- private $position;
- /**
- * @ignore
- */
- private $container;
-
- /**
- * Create iterator instance for RepeatedField.
- *
- * @param RepeatedField The RepeatedField instance for which this iterator
- * is created.
- * @ignore
- */
- public function __construct($container)
- {
- $this->position = 0;
- $this->container = $container;
- }
-
- /**
- * Reset the status of the iterator
- *
- * @return void
- */
- public function rewind()
- {
- $this->position = 0;
- }
-
- /**
- * Return the element at the current position.
- *
- * @return object The element at the current position.
- */
- public function current()
- {
- return $this->container[$this->position];
- }
-
- /**
- * Return the current position.
- *
- * @return integer The current position.
- */
- public function key()
- {
- return $this->position;
- }
-
- /**
- * Move to the next position.
- *
- * @return void
- */
- public function next()
- {
- ++$this->position;
- }
-
- /**
- * Check whether there are more elements to iterate.
- *
- * @return bool True if there are more elements to iterate.
- */
- public function valid()
- {
- return isset($this->container[$this->position]);
- }
-}
-
-/**
* RepeatedField is used by generated protocol message classes to manipulate
* repeated fields. It can be used like native PHP array.
*/
@@ -225,6 +145,10 @@ class RepeatedField implements \ArrayAccess, \IteratorAggregate, \Countable
GPBUtil::checkString($value, true);
break;
case GPBType::MESSAGE:
+ if (is_null($value)) {
+ trigger_error("RepeatedField element cannot be null.",
+ E_USER_ERROR);
+ }
GPBUtil::checkMessage($value, $this->klass);
break;
default:
diff --git a/php/src/Google/Protobuf/Internal/RepeatedFieldIter.php b/php/src/Google/Protobuf/Internal/RepeatedFieldIter.php
new file mode 100644
index 00000000..2b6f8230
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/RepeatedFieldIter.php
@@ -0,0 +1,118 @@
+<?php
+
+// 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.
+
+/**
+ * RepeatedField and RepeatedFieldIter are used by generated protocol message
+ * classes to manipulate repeated fields.
+ */
+
+namespace Google\Protobuf\Internal;
+
+/**
+ * RepeatedFieldIter is used to iterate RepeatedField. It is also need for the
+ * foreach syntax.
+ */
+class RepeatedFieldIter implements \Iterator
+{
+
+ /**
+ * @ignore
+ */
+ private $position;
+ /**
+ * @ignore
+ */
+ private $container;
+
+ /**
+ * Create iterator instance for RepeatedField.
+ *
+ * @param RepeatedField The RepeatedField instance for which this iterator
+ * is created.
+ * @ignore
+ */
+ public function __construct($container)
+ {
+ $this->position = 0;
+ $this->container = $container;
+ }
+
+ /**
+ * Reset the status of the iterator
+ *
+ * @return void
+ */
+ public function rewind()
+ {
+ $this->position = 0;
+ }
+
+ /**
+ * Return the element at the current position.
+ *
+ * @return object The element at the current position.
+ */
+ public function current()
+ {
+ return $this->container[$this->position];
+ }
+
+ /**
+ * Return the current position.
+ *
+ * @return integer The current position.
+ */
+ public function key()
+ {
+ return $this->position;
+ }
+
+ /**
+ * Move to the next position.
+ *
+ * @return void
+ */
+ public function next()
+ {
+ ++$this->position;
+ }
+
+ /**
+ * Check whether there are more elements to iterate.
+ *
+ * @return bool True if there are more elements to iterate.
+ */
+ public function valid()
+ {
+ return isset($this->container[$this->position]);
+ }
+}
diff --git a/php/src/Google/Protobuf/Internal/ServiceDescriptorProto.php b/php/src/Google/Protobuf/Internal/ServiceDescriptorProto.php
index 624bde84..da88e9c4 100644
--- a/php/src/Google/Protobuf/Internal/ServiceDescriptorProto.php
+++ b/php/src/Google/Protobuf/Internal/ServiceDescriptorProto.php
@@ -8,30 +8,27 @@ use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\GPBWire;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\InputStream;
-
use Google\Protobuf\Internal\GPBUtil;
/**
- * <pre>
* Describes a service.
- * </pre>
*
- * Protobuf type <code>google.protobuf.ServiceDescriptorProto</code>
+ * Generated from protobuf message <code>google.protobuf.ServiceDescriptorProto</code>
*/
class ServiceDescriptorProto extends \Google\Protobuf\Internal\Message
{
/**
- * <code>optional string name = 1;</code>
+ * Generated from protobuf field <code>optional string name = 1;</code>
*/
private $name = '';
private $has_name = false;
/**
- * <code>repeated .google.protobuf.MethodDescriptorProto method = 2;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.MethodDescriptorProto method = 2;</code>
*/
private $method;
private $has_method = false;
/**
- * <code>optional .google.protobuf.ServiceOptions options = 3;</code>
+ * Generated from protobuf field <code>optional .google.protobuf.ServiceOptions options = 3;</code>
*/
private $options = null;
private $has_options = false;
@@ -42,7 +39,8 @@ class ServiceDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional string name = 1;</code>
+ * Generated from protobuf field <code>optional string name = 1;</code>
+ * @return string
*/
public function getName()
{
@@ -50,13 +48,17 @@ class ServiceDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional string name = 1;</code>
+ * Generated from protobuf field <code>optional string name = 1;</code>
+ * @param string $var
+ * @return $this
*/
public function setName($var)
{
GPBUtil::checkString($var, True);
$this->name = $var;
$this->has_name = true;
+
+ return $this;
}
public function hasName()
@@ -65,7 +67,8 @@ class ServiceDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>repeated .google.protobuf.MethodDescriptorProto method = 2;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.MethodDescriptorProto method = 2;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
*/
public function getMethod()
{
@@ -73,13 +76,17 @@ class ServiceDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>repeated .google.protobuf.MethodDescriptorProto method = 2;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.MethodDescriptorProto method = 2;</code>
+ * @param \Google\Protobuf\Internal\MethodDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
*/
- public function setMethod(&$var)
+ public function setMethod($var)
{
- GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\MethodDescriptorProto::class);
- $this->method = $var;
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\MethodDescriptorProto::class);
+ $this->method = $arr;
$this->has_method = true;
+
+ return $this;
}
public function hasMethod()
@@ -88,7 +95,8 @@ class ServiceDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional .google.protobuf.ServiceOptions options = 3;</code>
+ * Generated from protobuf field <code>optional .google.protobuf.ServiceOptions options = 3;</code>
+ * @return \Google\Protobuf\Internal\ServiceOptions
*/
public function getOptions()
{
@@ -96,13 +104,17 @@ class ServiceDescriptorProto extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional .google.protobuf.ServiceOptions options = 3;</code>
+ * Generated from protobuf field <code>optional .google.protobuf.ServiceOptions options = 3;</code>
+ * @param \Google\Protobuf\Internal\ServiceOptions $var
+ * @return $this
*/
- public function setOptions(&$var)
+ public function setOptions($var)
{
GPBUtil::checkMessage($var, \Google\Protobuf\Internal\ServiceOptions::class);
$this->options = $var;
$this->has_options = true;
+
+ return $this;
}
public function hasOptions()
diff --git a/php/src/Google/Protobuf/Internal/ServiceOptions.php b/php/src/Google/Protobuf/Internal/ServiceOptions.php
index 5f3564e4..3e7214a1 100644
--- a/php/src/Google/Protobuf/Internal/ServiceOptions.php
+++ b/php/src/Google/Protobuf/Internal/ServiceOptions.php
@@ -8,32 +8,27 @@ use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\GPBWire;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\InputStream;
-
use Google\Protobuf\Internal\GPBUtil;
/**
- * Protobuf type <code>google.protobuf.ServiceOptions</code>
+ * Generated from protobuf message <code>google.protobuf.ServiceOptions</code>
*/
class ServiceOptions extends \Google\Protobuf\Internal\Message
{
/**
- * <pre>
* Is this service deprecated?
* Depending on the target platform, this can emit Deprecated annotations
* for the service, or it will be completely ignored; in the very least,
* this is a formalization for deprecating services.
- * </pre>
*
- * <code>optional bool deprecated = 33 [default = false];</code>
+ * Generated from protobuf field <code>optional bool deprecated = 33 [default = false];</code>
*/
private $deprecated = false;
private $has_deprecated = false;
/**
- * <pre>
* The parser stores options it doesn't recognize here. See above.
- * </pre>
*
- * <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
*/
private $uninterpreted_option;
private $has_uninterpreted_option = false;
@@ -44,14 +39,13 @@ class ServiceOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Is this service deprecated?
* Depending on the target platform, this can emit Deprecated annotations
* for the service, or it will be completely ignored; in the very least,
* this is a formalization for deprecating services.
- * </pre>
*
- * <code>optional bool deprecated = 33 [default = false];</code>
+ * Generated from protobuf field <code>optional bool deprecated = 33 [default = false];</code>
+ * @return bool
*/
public function getDeprecated()
{
@@ -59,20 +53,22 @@ class ServiceOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Is this service deprecated?
* Depending on the target platform, this can emit Deprecated annotations
* for the service, or it will be completely ignored; in the very least,
* this is a formalization for deprecating services.
- * </pre>
*
- * <code>optional bool deprecated = 33 [default = false];</code>
+ * Generated from protobuf field <code>optional bool deprecated = 33 [default = false];</code>
+ * @param bool $var
+ * @return $this
*/
public function setDeprecated($var)
{
GPBUtil::checkBool($var);
$this->deprecated = $var;
$this->has_deprecated = true;
+
+ return $this;
}
public function hasDeprecated()
@@ -81,11 +77,10 @@ class ServiceOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* The parser stores options it doesn't recognize here. See above.
- * </pre>
*
- * <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
*/
public function getUninterpretedOption()
{
@@ -93,17 +88,19 @@ class ServiceOptions extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* The parser stores options it doesn't recognize here. See above.
- * </pre>
*
- * <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code>
+ * @param \Google\Protobuf\Internal\UninterpretedOption[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
*/
- public function setUninterpretedOption(&$var)
+ public function setUninterpretedOption($var)
{
- GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\UninterpretedOption::class);
- $this->uninterpreted_option = $var;
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\UninterpretedOption::class);
+ $this->uninterpreted_option = $arr;
$this->has_uninterpreted_option = true;
+
+ return $this;
}
public function hasUninterpretedOption()
diff --git a/php/src/Google/Protobuf/Internal/SourceCodeInfo.php b/php/src/Google/Protobuf/Internal/SourceCodeInfo.php
index d2352ddd..6ce05ed4 100644
--- a/php/src/Google/Protobuf/Internal/SourceCodeInfo.php
+++ b/php/src/Google/Protobuf/Internal/SourceCodeInfo.php
@@ -8,21 +8,17 @@ use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\GPBWire;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\InputStream;
-
use Google\Protobuf\Internal\GPBUtil;
/**
- * <pre>
* Encapsulates information about the original source file from which a
* FileDescriptorProto was generated.
- * </pre>
*
- * Protobuf type <code>google.protobuf.SourceCodeInfo</code>
+ * Generated from protobuf message <code>google.protobuf.SourceCodeInfo</code>
*/
class SourceCodeInfo extends \Google\Protobuf\Internal\Message
{
/**
- * <pre>
* A Location identifies a piece of source code in a .proto file which
* corresponds to a particular definition. This information is intended
* to be useful to IDEs, code indexers, documentation generators, and similar
@@ -64,9 +60,8 @@ class SourceCodeInfo extends \Google\Protobuf\Internal\Message
* - Code which tries to interpret locations should probably be designed to
* ignore those that it doesn't understand, as more types of locations could
* be recorded in the future.
- * </pre>
*
- * <code>repeated .google.protobuf.SourceCodeInfo.Location location = 1;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.SourceCodeInfo.Location location = 1;</code>
*/
private $location;
private $has_location = false;
@@ -77,7 +72,6 @@ class SourceCodeInfo extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* A Location identifies a piece of source code in a .proto file which
* corresponds to a particular definition. This information is intended
* to be useful to IDEs, code indexers, documentation generators, and similar
@@ -119,9 +113,9 @@ class SourceCodeInfo extends \Google\Protobuf\Internal\Message
* - Code which tries to interpret locations should probably be designed to
* ignore those that it doesn't understand, as more types of locations could
* be recorded in the future.
- * </pre>
*
- * <code>repeated .google.protobuf.SourceCodeInfo.Location location = 1;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.SourceCodeInfo.Location location = 1;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
*/
public function getLocation()
{
@@ -129,7 +123,6 @@ class SourceCodeInfo extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* A Location identifies a piece of source code in a .proto file which
* corresponds to a particular definition. This information is intended
* to be useful to IDEs, code indexers, documentation generators, and similar
@@ -171,15 +164,18 @@ class SourceCodeInfo extends \Google\Protobuf\Internal\Message
* - Code which tries to interpret locations should probably be designed to
* ignore those that it doesn't understand, as more types of locations could
* be recorded in the future.
- * </pre>
*
- * <code>repeated .google.protobuf.SourceCodeInfo.Location location = 1;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.SourceCodeInfo.Location location = 1;</code>
+ * @param \Google\Protobuf\Internal\SourceCodeInfo_Location[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
*/
- public function setLocation(&$var)
+ public function setLocation($var)
{
- GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\SourceCodeInfo_Location::class);
- $this->location = $var;
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\SourceCodeInfo_Location::class);
+ $this->location = $arr;
$this->has_location = true;
+
+ return $this;
}
public function hasLocation()
diff --git a/php/src/Google/Protobuf/Internal/SourceCodeInfo_Location.php b/php/src/Google/Protobuf/Internal/SourceCodeInfo_Location.php
index d1bdb166..19ed2bc2 100644
--- a/php/src/Google/Protobuf/Internal/SourceCodeInfo_Location.php
+++ b/php/src/Google/Protobuf/Internal/SourceCodeInfo_Location.php
@@ -8,16 +8,14 @@ use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\GPBWire;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\InputStream;
-
use Google\Protobuf\Internal\GPBUtil;
/**
- * Protobuf type <code>google.protobuf.SourceCodeInfo.Location</code>
+ * Generated from protobuf message <code>google.protobuf.SourceCodeInfo.Location</code>
*/
class SourceCodeInfo_Location extends \Google\Protobuf\Internal\Message
{
/**
- * <pre>
* Identifies which part of the FileDescriptorProto was defined at this
* location.
* Each element is a field number or an index. They form a path from
@@ -39,27 +37,23 @@ class SourceCodeInfo_Location extends \Google\Protobuf\Internal\Message
* [ 4, 3, 2, 7 ]
* this path refers to the whole field declaration (from the beginning
* of the label to the terminating semicolon).
- * </pre>
*
- * <code>repeated int32 path = 1 [packed = true];</code>
+ * Generated from protobuf field <code>repeated int32 path = 1 [packed = true];</code>
*/
private $path;
private $has_path = false;
/**
- * <pre>
* Always has exactly three or four elements: start line, start column,
* end line (optional, otherwise assumed same as start line), end column.
* These are packed into a single field for efficiency. Note that line
* and column numbers are zero-based -- typically you will want to add
* 1 to each before displaying to a user.
- * </pre>
*
- * <code>repeated int32 span = 2 [packed = true];</code>
+ * Generated from protobuf field <code>repeated int32 span = 2 [packed = true];</code>
*/
private $span;
private $has_span = false;
/**
- * <pre>
* If this SourceCodeInfo represents a complete declaration, these are any
* comments appearing before and after the declaration which appear to be
* attached to the declaration.
@@ -96,19 +90,18 @@ class SourceCodeInfo_Location extends \Google\Protobuf\Internal\Message
* * grault. *&#47;
* optional int32 grault = 6;
* // ignored detached comments.
- * </pre>
*
- * <code>optional string leading_comments = 3;</code>
+ * Generated from protobuf field <code>optional string leading_comments = 3;</code>
*/
private $leading_comments = '';
private $has_leading_comments = false;
/**
- * <code>optional string trailing_comments = 4;</code>
+ * Generated from protobuf field <code>optional string trailing_comments = 4;</code>
*/
private $trailing_comments = '';
private $has_trailing_comments = false;
/**
- * <code>repeated string leading_detached_comments = 6;</code>
+ * Generated from protobuf field <code>repeated string leading_detached_comments = 6;</code>
*/
private $leading_detached_comments;
private $has_leading_detached_comments = false;
@@ -119,7 +112,6 @@ class SourceCodeInfo_Location extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Identifies which part of the FileDescriptorProto was defined at this
* location.
* Each element is a field number or an index. They form a path from
@@ -141,9 +133,9 @@ class SourceCodeInfo_Location extends \Google\Protobuf\Internal\Message
* [ 4, 3, 2, 7 ]
* this path refers to the whole field declaration (from the beginning
* of the label to the terminating semicolon).
- * </pre>
*
- * <code>repeated int32 path = 1 [packed = true];</code>
+ * Generated from protobuf field <code>repeated int32 path = 1 [packed = true];</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
*/
public function getPath()
{
@@ -151,7 +143,6 @@ class SourceCodeInfo_Location extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Identifies which part of the FileDescriptorProto was defined at this
* location.
* Each element is a field number or an index. They form a path from
@@ -173,15 +164,18 @@ class SourceCodeInfo_Location extends \Google\Protobuf\Internal\Message
* [ 4, 3, 2, 7 ]
* this path refers to the whole field declaration (from the beginning
* of the label to the terminating semicolon).
- * </pre>
*
- * <code>repeated int32 path = 1 [packed = true];</code>
+ * Generated from protobuf field <code>repeated int32 path = 1 [packed = true];</code>
+ * @param int[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
*/
- public function setPath(&$var)
+ public function setPath($var)
{
- GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::INT32);
- $this->path = $var;
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::INT32);
+ $this->path = $arr;
$this->has_path = true;
+
+ return $this;
}
public function hasPath()
@@ -190,15 +184,14 @@ class SourceCodeInfo_Location extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Always has exactly three or four elements: start line, start column,
* end line (optional, otherwise assumed same as start line), end column.
* These are packed into a single field for efficiency. Note that line
* and column numbers are zero-based -- typically you will want to add
* 1 to each before displaying to a user.
- * </pre>
*
- * <code>repeated int32 span = 2 [packed = true];</code>
+ * Generated from protobuf field <code>repeated int32 span = 2 [packed = true];</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
*/
public function getSpan()
{
@@ -206,21 +199,23 @@ class SourceCodeInfo_Location extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* Always has exactly three or four elements: start line, start column,
* end line (optional, otherwise assumed same as start line), end column.
* These are packed into a single field for efficiency. Note that line
* and column numbers are zero-based -- typically you will want to add
* 1 to each before displaying to a user.
- * </pre>
*
- * <code>repeated int32 span = 2 [packed = true];</code>
+ * Generated from protobuf field <code>repeated int32 span = 2 [packed = true];</code>
+ * @param int[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
*/
- public function setSpan(&$var)
+ public function setSpan($var)
{
- GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::INT32);
- $this->span = $var;
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::INT32);
+ $this->span = $arr;
$this->has_span = true;
+
+ return $this;
}
public function hasSpan()
@@ -229,7 +224,6 @@ class SourceCodeInfo_Location extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* If this SourceCodeInfo represents a complete declaration, these are any
* comments appearing before and after the declaration which appear to be
* attached to the declaration.
@@ -266,9 +260,9 @@ class SourceCodeInfo_Location extends \Google\Protobuf\Internal\Message
* * grault. *&#47;
* optional int32 grault = 6;
* // ignored detached comments.
- * </pre>
*
- * <code>optional string leading_comments = 3;</code>
+ * Generated from protobuf field <code>optional string leading_comments = 3;</code>
+ * @return string
*/
public function getLeadingComments()
{
@@ -276,7 +270,6 @@ class SourceCodeInfo_Location extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* If this SourceCodeInfo represents a complete declaration, these are any
* comments appearing before and after the declaration which appear to be
* attached to the declaration.
@@ -313,15 +306,18 @@ class SourceCodeInfo_Location extends \Google\Protobuf\Internal\Message
* * grault. *&#47;
* optional int32 grault = 6;
* // ignored detached comments.
- * </pre>
*
- * <code>optional string leading_comments = 3;</code>
+ * Generated from protobuf field <code>optional string leading_comments = 3;</code>
+ * @param string $var
+ * @return $this
*/
public function setLeadingComments($var)
{
GPBUtil::checkString($var, True);
$this->leading_comments = $var;
$this->has_leading_comments = true;
+
+ return $this;
}
public function hasLeadingComments()
@@ -330,7 +326,8 @@ class SourceCodeInfo_Location extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional string trailing_comments = 4;</code>
+ * Generated from protobuf field <code>optional string trailing_comments = 4;</code>
+ * @return string
*/
public function getTrailingComments()
{
@@ -338,13 +335,17 @@ class SourceCodeInfo_Location extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional string trailing_comments = 4;</code>
+ * Generated from protobuf field <code>optional string trailing_comments = 4;</code>
+ * @param string $var
+ * @return $this
*/
public function setTrailingComments($var)
{
GPBUtil::checkString($var, True);
$this->trailing_comments = $var;
$this->has_trailing_comments = true;
+
+ return $this;
}
public function hasTrailingComments()
@@ -353,7 +354,8 @@ class SourceCodeInfo_Location extends \Google\Protobuf\Internal\Message
}
/**
- * <code>repeated string leading_detached_comments = 6;</code>
+ * Generated from protobuf field <code>repeated string leading_detached_comments = 6;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
*/
public function getLeadingDetachedComments()
{
@@ -361,13 +363,17 @@ class SourceCodeInfo_Location extends \Google\Protobuf\Internal\Message
}
/**
- * <code>repeated string leading_detached_comments = 6;</code>
+ * Generated from protobuf field <code>repeated string leading_detached_comments = 6;</code>
+ * @param string[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
*/
- public function setLeadingDetachedComments(&$var)
+ public function setLeadingDetachedComments($var)
{
- GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::STRING);
- $this->leading_detached_comments = $var;
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::STRING);
+ $this->leading_detached_comments = $arr;
$this->has_leading_detached_comments = true;
+
+ return $this;
}
public function hasLeadingDetachedComments()
diff --git a/php/src/Google/Protobuf/Internal/UninterpretedOption.php b/php/src/Google/Protobuf/Internal/UninterpretedOption.php
index c0f48310..4d342eb3 100644
--- a/php/src/Google/Protobuf/Internal/UninterpretedOption.php
+++ b/php/src/Google/Protobuf/Internal/UninterpretedOption.php
@@ -8,60 +8,55 @@ use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\GPBWire;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\InputStream;
-
use Google\Protobuf\Internal\GPBUtil;
/**
- * <pre>
* A message representing a option the parser does not recognize. This only
* appears in options protos created by the compiler::Parser class.
* DescriptorPool resolves these when building Descriptor objects. Therefore,
* options protos in descriptor objects (e.g. returned by Descriptor::options(),
* or produced by Descriptor::CopyTo()) will never have UninterpretedOptions
* in them.
- * </pre>
*
- * Protobuf type <code>google.protobuf.UninterpretedOption</code>
+ * Generated from protobuf message <code>google.protobuf.UninterpretedOption</code>
*/
class UninterpretedOption extends \Google\Protobuf\Internal\Message
{
/**
- * <code>repeated .google.protobuf.UninterpretedOption.NamePart name = 2;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption.NamePart name = 2;</code>
*/
private $name;
private $has_name = false;
/**
- * <pre>
* The value of the uninterpreted option, in whatever type the tokenizer
* identified it as during parsing. Exactly one of these should be set.
- * </pre>
*
- * <code>optional string identifier_value = 3;</code>
+ * Generated from protobuf field <code>optional string identifier_value = 3;</code>
*/
private $identifier_value = '';
private $has_identifier_value = false;
/**
- * <code>optional uint64 positive_int_value = 4;</code>
+ * Generated from protobuf field <code>optional uint64 positive_int_value = 4;</code>
*/
private $positive_int_value = 0;
private $has_positive_int_value = false;
/**
- * <code>optional int64 negative_int_value = 5;</code>
+ * Generated from protobuf field <code>optional int64 negative_int_value = 5;</code>
*/
private $negative_int_value = 0;
private $has_negative_int_value = false;
/**
- * <code>optional double double_value = 6;</code>
+ * Generated from protobuf field <code>optional double double_value = 6;</code>
*/
private $double_value = 0.0;
private $has_double_value = false;
/**
- * <code>optional bytes string_value = 7;</code>
+ * Generated from protobuf field <code>optional bytes string_value = 7;</code>
*/
private $string_value = '';
private $has_string_value = false;
/**
- * <code>optional string aggregate_value = 8;</code>
+ * Generated from protobuf field <code>optional string aggregate_value = 8;</code>
*/
private $aggregate_value = '';
private $has_aggregate_value = false;
@@ -72,7 +67,8 @@ class UninterpretedOption extends \Google\Protobuf\Internal\Message
}
/**
- * <code>repeated .google.protobuf.UninterpretedOption.NamePart name = 2;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption.NamePart name = 2;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
*/
public function getName()
{
@@ -80,13 +76,17 @@ class UninterpretedOption extends \Google\Protobuf\Internal\Message
}
/**
- * <code>repeated .google.protobuf.UninterpretedOption.NamePart name = 2;</code>
+ * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption.NamePart name = 2;</code>
+ * @param \Google\Protobuf\Internal\UninterpretedOption_NamePart[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
*/
- public function setName(&$var)
+ public function setName($var)
{
- GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\UninterpretedOption_NamePart::class);
- $this->name = $var;
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Internal\UninterpretedOption_NamePart::class);
+ $this->name = $arr;
$this->has_name = true;
+
+ return $this;
}
public function hasName()
@@ -95,12 +95,11 @@ class UninterpretedOption extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* The value of the uninterpreted option, in whatever type the tokenizer
* identified it as during parsing. Exactly one of these should be set.
- * </pre>
*
- * <code>optional string identifier_value = 3;</code>
+ * Generated from protobuf field <code>optional string identifier_value = 3;</code>
+ * @return string
*/
public function getIdentifierValue()
{
@@ -108,18 +107,20 @@ class UninterpretedOption extends \Google\Protobuf\Internal\Message
}
/**
- * <pre>
* The value of the uninterpreted option, in whatever type the tokenizer
* identified it as during parsing. Exactly one of these should be set.
- * </pre>
*
- * <code>optional string identifier_value = 3;</code>
+ * Generated from protobuf field <code>optional string identifier_value = 3;</code>
+ * @param string $var
+ * @return $this
*/
public function setIdentifierValue($var)
{
GPBUtil::checkString($var, True);
$this->identifier_value = $var;
$this->has_identifier_value = true;
+
+ return $this;
}
public function hasIdentifierValue()
@@ -128,7 +129,8 @@ class UninterpretedOption extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional uint64 positive_int_value = 4;</code>
+ * Generated from protobuf field <code>optional uint64 positive_int_value = 4;</code>
+ * @return int|string
*/
public function getPositiveIntValue()
{
@@ -136,13 +138,17 @@ class UninterpretedOption extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional uint64 positive_int_value = 4;</code>
+ * Generated from protobuf field <code>optional uint64 positive_int_value = 4;</code>
+ * @param int|string $var
+ * @return $this
*/
public function setPositiveIntValue($var)
{
GPBUtil::checkUint64($var);
$this->positive_int_value = $var;
$this->has_positive_int_value = true;
+
+ return $this;
}
public function hasPositiveIntValue()
@@ -151,7 +157,8 @@ class UninterpretedOption extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional int64 negative_int_value = 5;</code>
+ * Generated from protobuf field <code>optional int64 negative_int_value = 5;</code>
+ * @return int|string
*/
public function getNegativeIntValue()
{
@@ -159,13 +166,17 @@ class UninterpretedOption extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional int64 negative_int_value = 5;</code>
+ * Generated from protobuf field <code>optional int64 negative_int_value = 5;</code>
+ * @param int|string $var
+ * @return $this
*/
public function setNegativeIntValue($var)
{
GPBUtil::checkInt64($var);
$this->negative_int_value = $var;
$this->has_negative_int_value = true;
+
+ return $this;
}
public function hasNegativeIntValue()
@@ -174,7 +185,8 @@ class UninterpretedOption extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional double double_value = 6;</code>
+ * Generated from protobuf field <code>optional double double_value = 6;</code>
+ * @return float
*/
public function getDoubleValue()
{
@@ -182,13 +194,17 @@ class UninterpretedOption extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional double double_value = 6;</code>
+ * Generated from protobuf field <code>optional double double_value = 6;</code>
+ * @param float $var
+ * @return $this
*/
public function setDoubleValue($var)
{
GPBUtil::checkDouble($var);
$this->double_value = $var;
$this->has_double_value = true;
+
+ return $this;
}
public function hasDoubleValue()
@@ -197,7 +213,8 @@ class UninterpretedOption extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional bytes string_value = 7;</code>
+ * Generated from protobuf field <code>optional bytes string_value = 7;</code>
+ * @return string
*/
public function getStringValue()
{
@@ -205,13 +222,17 @@ class UninterpretedOption extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional bytes string_value = 7;</code>
+ * Generated from protobuf field <code>optional bytes string_value = 7;</code>
+ * @param string $var
+ * @return $this
*/
public function setStringValue($var)
{
GPBUtil::checkString($var, False);
$this->string_value = $var;
$this->has_string_value = true;
+
+ return $this;
}
public function hasStringValue()
@@ -220,7 +241,8 @@ class UninterpretedOption extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional string aggregate_value = 8;</code>
+ * Generated from protobuf field <code>optional string aggregate_value = 8;</code>
+ * @return string
*/
public function getAggregateValue()
{
@@ -228,13 +250,17 @@ class UninterpretedOption extends \Google\Protobuf\Internal\Message
}
/**
- * <code>optional string aggregate_value = 8;</code>
+ * Generated from protobuf field <code>optional string aggregate_value = 8;</code>
+ * @param string $var
+ * @return $this
*/
public function setAggregateValue($var)
{
GPBUtil::checkString($var, True);
$this->aggregate_value = $var;
$this->has_aggregate_value = true;
+
+ return $this;
}
public function hasAggregateValue()
diff --git a/php/src/Google/Protobuf/Internal/UninterpretedOption_NamePart.php b/php/src/Google/Protobuf/Internal/UninterpretedOption_NamePart.php
index 86484d23..c9a6fc3c 100644
--- a/php/src/Google/Protobuf/Internal/UninterpretedOption_NamePart.php
+++ b/php/src/Google/Protobuf/Internal/UninterpretedOption_NamePart.php
@@ -8,29 +8,26 @@ use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\GPBWire;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\InputStream;
-
use Google\Protobuf\Internal\GPBUtil;
/**
- * <pre>
* The name of the uninterpreted option. Each string represents a segment in
* a dot-separated name. is_extension is true iff a segment represents an
* extension (denoted with parentheses in options specs in .proto files).
* E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents
* "foo.(bar.baz).qux".
- * </pre>
*
- * Protobuf type <code>google.protobuf.UninterpretedOption.NamePart</code>
+ * Generated from protobuf message <code>google.protobuf.UninterpretedOption.NamePart</code>
*/
class UninterpretedOption_NamePart extends \Google\Protobuf\Internal\Message
{
/**
- * <code>required string name_part = 1;</code>
+ * Generated from protobuf field <code>required string name_part = 1;</code>
*/
private $name_part = '';
private $has_name_part = false;
/**
- * <code>required bool is_extension = 2;</code>
+ * Generated from protobuf field <code>required bool is_extension = 2;</code>
*/
private $is_extension = false;
private $has_is_extension = false;
@@ -41,7 +38,8 @@ class UninterpretedOption_NamePart extends \Google\Protobuf\Internal\Message
}
/**
- * <code>required string name_part = 1;</code>
+ * Generated from protobuf field <code>required string name_part = 1;</code>
+ * @return string
*/
public function getNamePart()
{
@@ -49,13 +47,17 @@ class UninterpretedOption_NamePart extends \Google\Protobuf\Internal\Message
}
/**
- * <code>required string name_part = 1;</code>
+ * Generated from protobuf field <code>required string name_part = 1;</code>
+ * @param string $var
+ * @return $this
*/
public function setNamePart($var)
{
GPBUtil::checkString($var, True);
$this->name_part = $var;
$this->has_name_part = true;
+
+ return $this;
}
public function hasNamePart()
@@ -64,7 +66,8 @@ class UninterpretedOption_NamePart extends \Google\Protobuf\Internal\Message
}
/**
- * <code>required bool is_extension = 2;</code>
+ * Generated from protobuf field <code>required bool is_extension = 2;</code>
+ * @return bool
*/
public function getIsExtension()
{
@@ -72,13 +75,17 @@ class UninterpretedOption_NamePart extends \Google\Protobuf\Internal\Message
}
/**
- * <code>required bool is_extension = 2;</code>
+ * Generated from protobuf field <code>required bool is_extension = 2;</code>
+ * @param bool $var
+ * @return $this
*/
public function setIsExtension($var)
{
GPBUtil::checkBool($var);
$this->is_extension = $var;
$this->has_is_extension = true;
+
+ return $this;
}
public function hasIsExtension()
diff --git a/php/src/Google/Protobuf/ListValue.php b/php/src/Google/Protobuf/ListValue.php
new file mode 100644
index 00000000..12552ef4
--- /dev/null
+++ b/php/src/Google/Protobuf/ListValue.php
@@ -0,0 +1,58 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/struct.proto
+
+namespace Google\Protobuf;
+
+use Google\Protobuf\Internal\GPBType;
+use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\GPBUtil;
+
+/**
+ * `ListValue` is a wrapper around a repeated field of values.
+ * The JSON representation for `ListValue` is JSON array.
+ *
+ * Generated from protobuf message <code>google.protobuf.ListValue</code>
+ */
+class ListValue extends \Google\Protobuf\Internal\Message
+{
+ /**
+ * Repeated field of dynamically typed values.
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.Value values = 1;</code>
+ */
+ private $values;
+
+ public function __construct() {
+ \GPBMetadata\Google\Protobuf\Struct::initOnce();
+ parent::__construct();
+ }
+
+ /**
+ * Repeated field of dynamically typed values.
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.Value values = 1;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
+ */
+ public function getValues()
+ {
+ return $this->values;
+ }
+
+ /**
+ * Repeated field of dynamically typed values.
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.Value values = 1;</code>
+ * @param \Google\Protobuf\Value[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
+ */
+ public function setValues($var)
+ {
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Value::class);
+ $this->values = $arr;
+
+ return $this;
+ }
+
+}
+
diff --git a/php/src/Google/Protobuf/Method.php b/php/src/Google/Protobuf/Method.php
new file mode 100644
index 00000000..f55cb764
--- /dev/null
+++ b/php/src/Google/Protobuf/Method.php
@@ -0,0 +1,249 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/api.proto
+
+namespace Google\Protobuf;
+
+use Google\Protobuf\Internal\GPBType;
+use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\GPBUtil;
+
+/**
+ * Method represents a method of an API interface.
+ *
+ * Generated from protobuf message <code>google.protobuf.Method</code>
+ */
+class Method extends \Google\Protobuf\Internal\Message
+{
+ /**
+ * The simple name of this method.
+ *
+ * Generated from protobuf field <code>string name = 1;</code>
+ */
+ private $name = '';
+ /**
+ * A URL of the input message type.
+ *
+ * Generated from protobuf field <code>string request_type_url = 2;</code>
+ */
+ private $request_type_url = '';
+ /**
+ * If true, the request is streamed.
+ *
+ * Generated from protobuf field <code>bool request_streaming = 3;</code>
+ */
+ private $request_streaming = false;
+ /**
+ * The URL of the output message type.
+ *
+ * Generated from protobuf field <code>string response_type_url = 4;</code>
+ */
+ private $response_type_url = '';
+ /**
+ * If true, the response is streamed.
+ *
+ * Generated from protobuf field <code>bool response_streaming = 5;</code>
+ */
+ private $response_streaming = false;
+ /**
+ * Any metadata attached to the method.
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.Option options = 6;</code>
+ */
+ private $options;
+ /**
+ * The source syntax of this method.
+ *
+ * Generated from protobuf field <code>.google.protobuf.Syntax syntax = 7;</code>
+ */
+ private $syntax = 0;
+
+ public function __construct() {
+ \GPBMetadata\Google\Protobuf\Api::initOnce();
+ parent::__construct();
+ }
+
+ /**
+ * The simple name of this method.
+ *
+ * Generated from protobuf field <code>string name = 1;</code>
+ * @return string
+ */
+ public function getName()
+ {
+ return $this->name;
+ }
+
+ /**
+ * The simple name of this method.
+ *
+ * Generated from protobuf field <code>string name = 1;</code>
+ * @param string $var
+ * @return $this
+ */
+ public function setName($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->name = $var;
+
+ return $this;
+ }
+
+ /**
+ * A URL of the input message type.
+ *
+ * Generated from protobuf field <code>string request_type_url = 2;</code>
+ * @return string
+ */
+ public function getRequestTypeUrl()
+ {
+ return $this->request_type_url;
+ }
+
+ /**
+ * A URL of the input message type.
+ *
+ * Generated from protobuf field <code>string request_type_url = 2;</code>
+ * @param string $var
+ * @return $this
+ */
+ public function setRequestTypeUrl($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->request_type_url = $var;
+
+ return $this;
+ }
+
+ /**
+ * If true, the request is streamed.
+ *
+ * Generated from protobuf field <code>bool request_streaming = 3;</code>
+ * @return bool
+ */
+ public function getRequestStreaming()
+ {
+ return $this->request_streaming;
+ }
+
+ /**
+ * If true, the request is streamed.
+ *
+ * Generated from protobuf field <code>bool request_streaming = 3;</code>
+ * @param bool $var
+ * @return $this
+ */
+ public function setRequestStreaming($var)
+ {
+ GPBUtil::checkBool($var);
+ $this->request_streaming = $var;
+
+ return $this;
+ }
+
+ /**
+ * The URL of the output message type.
+ *
+ * Generated from protobuf field <code>string response_type_url = 4;</code>
+ * @return string
+ */
+ public function getResponseTypeUrl()
+ {
+ return $this->response_type_url;
+ }
+
+ /**
+ * The URL of the output message type.
+ *
+ * Generated from protobuf field <code>string response_type_url = 4;</code>
+ * @param string $var
+ * @return $this
+ */
+ public function setResponseTypeUrl($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->response_type_url = $var;
+
+ return $this;
+ }
+
+ /**
+ * If true, the response is streamed.
+ *
+ * Generated from protobuf field <code>bool response_streaming = 5;</code>
+ * @return bool
+ */
+ public function getResponseStreaming()
+ {
+ return $this->response_streaming;
+ }
+
+ /**
+ * If true, the response is streamed.
+ *
+ * Generated from protobuf field <code>bool response_streaming = 5;</code>
+ * @param bool $var
+ * @return $this
+ */
+ public function setResponseStreaming($var)
+ {
+ GPBUtil::checkBool($var);
+ $this->response_streaming = $var;
+
+ return $this;
+ }
+
+ /**
+ * Any metadata attached to the method.
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.Option options = 6;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
+ */
+ public function getOptions()
+ {
+ return $this->options;
+ }
+
+ /**
+ * Any metadata attached to the method.
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.Option options = 6;</code>
+ * @param \Google\Protobuf\Option[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
+ */
+ public function setOptions($var)
+ {
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Option::class);
+ $this->options = $arr;
+
+ return $this;
+ }
+
+ /**
+ * The source syntax of this method.
+ *
+ * Generated from protobuf field <code>.google.protobuf.Syntax syntax = 7;</code>
+ * @return int
+ */
+ public function getSyntax()
+ {
+ return $this->syntax;
+ }
+
+ /**
+ * The source syntax of this method.
+ *
+ * Generated from protobuf field <code>.google.protobuf.Syntax syntax = 7;</code>
+ * @param int $var
+ * @return $this
+ */
+ public function setSyntax($var)
+ {
+ GPBUtil::checkEnum($var, \Google\Protobuf\Syntax::class);
+ $this->syntax = $var;
+
+ return $this;
+ }
+
+}
+
diff --git a/php/src/Google/Protobuf/Mixin.php b/php/src/Google/Protobuf/Mixin.php
new file mode 100644
index 00000000..eb5117e0
--- /dev/null
+++ b/php/src/Google/Protobuf/Mixin.php
@@ -0,0 +1,153 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/api.proto
+
+namespace Google\Protobuf;
+
+use Google\Protobuf\Internal\GPBType;
+use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\GPBUtil;
+
+/**
+ * Declares an API Interface to be included in this interface. The including
+ * interface must redeclare all the methods from the included interface, but
+ * documentation and options are inherited as follows:
+ * - If after comment and whitespace stripping, the documentation
+ * string of the redeclared method is empty, it will be inherited
+ * from the original method.
+ * - Each annotation belonging to the service config (http,
+ * visibility) which is not set in the redeclared method will be
+ * inherited.
+ * - If an http annotation is inherited, the path pattern will be
+ * modified as follows. Any version prefix will be replaced by the
+ * version of the including interface plus the [root][] path if
+ * specified.
+ * Example of a simple mixin:
+ * package google.acl.v1;
+ * service AccessControl {
+ * // Get the underlying ACL object.
+ * rpc GetAcl(GetAclRequest) returns (Acl) {
+ * option (google.api.http).get = "/v1/{resource=**}:getAcl";
+ * }
+ * }
+ * package google.storage.v2;
+ * service Storage {
+ * rpc GetAcl(GetAclRequest) returns (Acl);
+ * // Get a data record.
+ * rpc GetData(GetDataRequest) returns (Data) {
+ * option (google.api.http).get = "/v2/{resource=**}";
+ * }
+ * }
+ * Example of a mixin configuration:
+ * apis:
+ * - name: google.storage.v2.Storage
+ * mixins:
+ * - name: google.acl.v1.AccessControl
+ * The mixin construct implies that all methods in `AccessControl` are
+ * also declared with same name and request/response types in
+ * `Storage`. A documentation generator or annotation processor will
+ * see the effective `Storage.GetAcl` method after inherting
+ * documentation and annotations as follows:
+ * service Storage {
+ * // Get the underlying ACL object.
+ * rpc GetAcl(GetAclRequest) returns (Acl) {
+ * option (google.api.http).get = "/v2/{resource=**}:getAcl";
+ * }
+ * ...
+ * }
+ * Note how the version in the path pattern changed from `v1` to `v2`.
+ * If the `root` field in the mixin is specified, it should be a
+ * relative path under which inherited HTTP paths are placed. Example:
+ * apis:
+ * - name: google.storage.v2.Storage
+ * mixins:
+ * - name: google.acl.v1.AccessControl
+ * root: acls
+ * This implies the following inherited HTTP annotation:
+ * service Storage {
+ * // Get the underlying ACL object.
+ * rpc GetAcl(GetAclRequest) returns (Acl) {
+ * option (google.api.http).get = "/v2/acls/{resource=**}:getAcl";
+ * }
+ * ...
+ * }
+ *
+ * Generated from protobuf message <code>google.protobuf.Mixin</code>
+ */
+class Mixin extends \Google\Protobuf\Internal\Message
+{
+ /**
+ * The fully qualified name of the interface which is included.
+ *
+ * Generated from protobuf field <code>string name = 1;</code>
+ */
+ private $name = '';
+ /**
+ * If non-empty specifies a path under which inherited HTTP paths
+ * are rooted.
+ *
+ * Generated from protobuf field <code>string root = 2;</code>
+ */
+ private $root = '';
+
+ public function __construct() {
+ \GPBMetadata\Google\Protobuf\Api::initOnce();
+ parent::__construct();
+ }
+
+ /**
+ * The fully qualified name of the interface which is included.
+ *
+ * Generated from protobuf field <code>string name = 1;</code>
+ * @return string
+ */
+ public function getName()
+ {
+ return $this->name;
+ }
+
+ /**
+ * The fully qualified name of the interface which is included.
+ *
+ * Generated from protobuf field <code>string name = 1;</code>
+ * @param string $var
+ * @return $this
+ */
+ public function setName($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->name = $var;
+
+ return $this;
+ }
+
+ /**
+ * If non-empty specifies a path under which inherited HTTP paths
+ * are rooted.
+ *
+ * Generated from protobuf field <code>string root = 2;</code>
+ * @return string
+ */
+ public function getRoot()
+ {
+ return $this->root;
+ }
+
+ /**
+ * If non-empty specifies a path under which inherited HTTP paths
+ * are rooted.
+ *
+ * Generated from protobuf field <code>string root = 2;</code>
+ * @param string $var
+ * @return $this
+ */
+ public function setRoot($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->root = $var;
+
+ return $this;
+ }
+
+}
+
diff --git a/php/src/Google/Protobuf/NullValue.php b/php/src/Google/Protobuf/NullValue.php
new file mode 100644
index 00000000..d4022ccc
--- /dev/null
+++ b/php/src/Google/Protobuf/NullValue.php
@@ -0,0 +1,23 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/struct.proto
+
+namespace Google\Protobuf;
+
+/**
+ * `NullValue` is a singleton enumeration to represent the null value for the
+ * `Value` type union.
+ * The JSON representation for `NullValue` is JSON `null`.
+ *
+ * Protobuf enum <code>Google\Protobuf\NullValue</code>
+ */
+class NullValue
+{
+ /**
+ * Null value.
+ *
+ * Generated from protobuf enum <code>NULL_VALUE = 0;</code>
+ */
+ const NULL_VALUE = 0;
+}
+
diff --git a/php/src/Google/Protobuf/OneofDescriptor.php b/php/src/Google/Protobuf/OneofDescriptor.php
new file mode 100644
index 00000000..d9736634
--- /dev/null
+++ b/php/src/Google/Protobuf/OneofDescriptor.php
@@ -0,0 +1,75 @@
+<?php
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2017 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.
+
+namespace Google\Protobuf;
+
+use Google\Protobuf\Internal\GetPublicDescriptorTrait;
+
+class OneofDescriptor
+{
+ use GetPublicDescriptorTrait;
+
+ private $internal_desc;
+
+ /**
+ * @internal
+ */
+ public function __construct($internal_desc)
+ {
+ $this->internal_desc = $internal_desc;
+ }
+
+ /**
+ * @return string The name of the oneof
+ */
+ public function getName()
+ {
+ return $this->internal_desc->getName();
+ }
+
+ /**
+ * @param int $index Must be >= 0 and < getFieldCount()
+ * @return FieldDescriptor
+ */
+ public function getField($index)
+ {
+ return $this->getPublicDescriptor($this->internal_desc->getFields()[$index]);
+ }
+
+ /**
+ * @return int Number of fields in the oneof
+ */
+ public function getFieldCount()
+ {
+ return count($this->internal_desc->getFields());
+ }
+}
diff --git a/php/src/Google/Protobuf/Option.php b/php/src/Google/Protobuf/Option.php
new file mode 100644
index 00000000..f8038681
--- /dev/null
+++ b/php/src/Google/Protobuf/Option.php
@@ -0,0 +1,108 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/type.proto
+
+namespace Google\Protobuf;
+
+use Google\Protobuf\Internal\GPBType;
+use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\GPBUtil;
+
+/**
+ * A protocol buffer option, which can be attached to a message, field,
+ * enumeration, etc.
+ *
+ * Generated from protobuf message <code>google.protobuf.Option</code>
+ */
+class Option extends \Google\Protobuf\Internal\Message
+{
+ /**
+ * The option's name. For protobuf built-in options (options defined in
+ * descriptor.proto), this is the short name. For example, `"map_entry"`.
+ * For custom options, it should be the fully-qualified name. For example,
+ * `"google.api.http"`.
+ *
+ * Generated from protobuf field <code>string name = 1;</code>
+ */
+ private $name = '';
+ /**
+ * The option's value packed in an Any message. If the value is a primitive,
+ * the corresponding wrapper type defined in google/protobuf/wrappers.proto
+ * should be used. If the value is an enum, it should be stored as an int32
+ * value using the google.protobuf.Int32Value type.
+ *
+ * Generated from protobuf field <code>.google.protobuf.Any value = 2;</code>
+ */
+ private $value = null;
+
+ public function __construct() {
+ \GPBMetadata\Google\Protobuf\Type::initOnce();
+ parent::__construct();
+ }
+
+ /**
+ * The option's name. For protobuf built-in options (options defined in
+ * descriptor.proto), this is the short name. For example, `"map_entry"`.
+ * For custom options, it should be the fully-qualified name. For example,
+ * `"google.api.http"`.
+ *
+ * Generated from protobuf field <code>string name = 1;</code>
+ * @return string
+ */
+ public function getName()
+ {
+ return $this->name;
+ }
+
+ /**
+ * The option's name. For protobuf built-in options (options defined in
+ * descriptor.proto), this is the short name. For example, `"map_entry"`.
+ * For custom options, it should be the fully-qualified name. For example,
+ * `"google.api.http"`.
+ *
+ * Generated from protobuf field <code>string name = 1;</code>
+ * @param string $var
+ * @return $this
+ */
+ public function setName($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->name = $var;
+
+ return $this;
+ }
+
+ /**
+ * The option's value packed in an Any message. If the value is a primitive,
+ * the corresponding wrapper type defined in google/protobuf/wrappers.proto
+ * should be used. If the value is an enum, it should be stored as an int32
+ * value using the google.protobuf.Int32Value type.
+ *
+ * Generated from protobuf field <code>.google.protobuf.Any value = 2;</code>
+ * @return \Google\Protobuf\Any
+ */
+ public function getValue()
+ {
+ return $this->value;
+ }
+
+ /**
+ * The option's value packed in an Any message. If the value is a primitive,
+ * the corresponding wrapper type defined in google/protobuf/wrappers.proto
+ * should be used. If the value is an enum, it should be stored as an int32
+ * value using the google.protobuf.Int32Value type.
+ *
+ * Generated from protobuf field <code>.google.protobuf.Any value = 2;</code>
+ * @param \Google\Protobuf\Any $var
+ * @return $this
+ */
+ public function setValue($var)
+ {
+ GPBUtil::checkMessage($var, \Google\Protobuf\Any::class);
+ $this->value = $var;
+
+ return $this;
+ }
+
+}
+
diff --git a/php/src/Google/Protobuf/SourceContext.php b/php/src/Google/Protobuf/SourceContext.php
new file mode 100644
index 00000000..07d90c68
--- /dev/null
+++ b/php/src/Google/Protobuf/SourceContext.php
@@ -0,0 +1,61 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/source_context.proto
+
+namespace Google\Protobuf;
+
+use Google\Protobuf\Internal\GPBType;
+use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\GPBUtil;
+
+/**
+ * `SourceContext` represents information about the source of a
+ * protobuf element, like the file in which it is defined.
+ *
+ * Generated from protobuf message <code>google.protobuf.SourceContext</code>
+ */
+class SourceContext extends \Google\Protobuf\Internal\Message
+{
+ /**
+ * The path-qualified name of the .proto file that contained the associated
+ * protobuf element. For example: `"google/protobuf/source_context.proto"`.
+ *
+ * Generated from protobuf field <code>string file_name = 1;</code>
+ */
+ private $file_name = '';
+
+ public function __construct() {
+ \GPBMetadata\Google\Protobuf\SourceContext::initOnce();
+ parent::__construct();
+ }
+
+ /**
+ * The path-qualified name of the .proto file that contained the associated
+ * protobuf element. For example: `"google/protobuf/source_context.proto"`.
+ *
+ * Generated from protobuf field <code>string file_name = 1;</code>
+ * @return string
+ */
+ public function getFileName()
+ {
+ return $this->file_name;
+ }
+
+ /**
+ * The path-qualified name of the .proto file that contained the associated
+ * protobuf element. For example: `"google/protobuf/source_context.proto"`.
+ *
+ * Generated from protobuf field <code>string file_name = 1;</code>
+ * @param string $var
+ * @return $this
+ */
+ public function setFileName($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->file_name = $var;
+
+ return $this;
+ }
+
+}
+
diff --git a/php/src/Google/Protobuf/StringValue.php b/php/src/Google/Protobuf/StringValue.php
new file mode 100644
index 00000000..f6bcc48a
--- /dev/null
+++ b/php/src/Google/Protobuf/StringValue.php
@@ -0,0 +1,58 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/wrappers.proto
+
+namespace Google\Protobuf;
+
+use Google\Protobuf\Internal\GPBType;
+use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\GPBUtil;
+
+/**
+ * Wrapper message for `string`.
+ * The JSON representation for `StringValue` is JSON string.
+ *
+ * Generated from protobuf message <code>google.protobuf.StringValue</code>
+ */
+class StringValue extends \Google\Protobuf\Internal\Message
+{
+ /**
+ * The string value.
+ *
+ * Generated from protobuf field <code>string value = 1;</code>
+ */
+ private $value = '';
+
+ public function __construct() {
+ \GPBMetadata\Google\Protobuf\Wrappers::initOnce();
+ parent::__construct();
+ }
+
+ /**
+ * The string value.
+ *
+ * Generated from protobuf field <code>string value = 1;</code>
+ * @return string
+ */
+ public function getValue()
+ {
+ return $this->value;
+ }
+
+ /**
+ * The string value.
+ *
+ * Generated from protobuf field <code>string value = 1;</code>
+ * @param string $var
+ * @return $this
+ */
+ public function setValue($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->value = $var;
+
+ return $this;
+ }
+
+}
+
diff --git a/php/src/Google/Protobuf/Struct.php b/php/src/Google/Protobuf/Struct.php
new file mode 100644
index 00000000..721e991c
--- /dev/null
+++ b/php/src/Google/Protobuf/Struct.php
@@ -0,0 +1,63 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/struct.proto
+
+namespace Google\Protobuf;
+
+use Google\Protobuf\Internal\GPBType;
+use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\GPBUtil;
+
+/**
+ * `Struct` represents a structured data value, consisting of fields
+ * which map to dynamically typed values. In some languages, `Struct`
+ * might be supported by a native representation. For example, in
+ * scripting languages like JS a struct is represented as an
+ * object. The details of that representation are described together
+ * with the proto support for the language.
+ * The JSON representation for `Struct` is JSON object.
+ *
+ * Generated from protobuf message <code>google.protobuf.Struct</code>
+ */
+class Struct extends \Google\Protobuf\Internal\Message
+{
+ /**
+ * Unordered map of dynamically typed values.
+ *
+ * Generated from protobuf field <code>map<string, .google.protobuf.Value> fields = 1;</code>
+ */
+ private $fields;
+
+ public function __construct() {
+ \GPBMetadata\Google\Protobuf\Struct::initOnce();
+ parent::__construct();
+ }
+
+ /**
+ * Unordered map of dynamically typed values.
+ *
+ * Generated from protobuf field <code>map<string, .google.protobuf.Value> fields = 1;</code>
+ * @return \Google\Protobuf\Internal\MapField
+ */
+ public function getFields()
+ {
+ return $this->fields;
+ }
+
+ /**
+ * Unordered map of dynamically typed values.
+ *
+ * Generated from protobuf field <code>map<string, .google.protobuf.Value> fields = 1;</code>
+ * @param array|\Google\Protobuf\Internal\MapField $var
+ * @return $this
+ */
+ public function setFields($var)
+ {
+ $arr = GPBUtil::checkMapField($var, \Google\Protobuf\Internal\GPBType::STRING, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Value::class);
+ $this->fields = $arr;
+
+ return $this;
+ }
+
+}
+
diff --git a/php/src/Google/Protobuf/Syntax.php b/php/src/Google/Protobuf/Syntax.php
new file mode 100644
index 00000000..bb7b7896
--- /dev/null
+++ b/php/src/Google/Protobuf/Syntax.php
@@ -0,0 +1,27 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/type.proto
+
+namespace Google\Protobuf;
+
+/**
+ * The syntax in which a protocol buffer element is defined.
+ *
+ * Protobuf enum <code>Google\Protobuf\Syntax</code>
+ */
+class Syntax
+{
+ /**
+ * Syntax `proto2`.
+ *
+ * Generated from protobuf enum <code>SYNTAX_PROTO2 = 0;</code>
+ */
+ const SYNTAX_PROTO2 = 0;
+ /**
+ * Syntax `proto3`.
+ *
+ * Generated from protobuf enum <code>SYNTAX_PROTO3 = 1;</code>
+ */
+ const SYNTAX_PROTO3 = 1;
+}
+
diff --git a/php/src/Google/Protobuf/Timestamp.php b/php/src/Google/Protobuf/Timestamp.php
new file mode 100644
index 00000000..7da8e956
--- /dev/null
+++ b/php/src/Google/Protobuf/Timestamp.php
@@ -0,0 +1,184 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/timestamp.proto
+
+namespace Google\Protobuf;
+
+use Google\Protobuf\Internal\GPBType;
+use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\GPBUtil;
+
+/**
+ * A Timestamp represents a point in time independent of any time zone
+ * or calendar, represented as seconds and fractions of seconds at
+ * nanosecond resolution in UTC Epoch time. It is encoded using the
+ * Proleptic Gregorian Calendar which extends the Gregorian calendar
+ * backwards to year one. It is encoded assuming all minutes are 60
+ * seconds long, i.e. leap seconds are "smeared" so that no leap second
+ * table is needed for interpretation. Range is from
+ * 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z.
+ * By restricting to that range, we ensure that we can convert to
+ * and from RFC 3339 date strings.
+ * See [https://www.ietf.org/rfc/rfc3339.txt](https://www.ietf.org/rfc/rfc3339.txt).
+ * # Examples
+ * Example 1: Compute Timestamp from POSIX `time()`.
+ * Timestamp timestamp;
+ * timestamp.set_seconds(time(NULL));
+ * timestamp.set_nanos(0);
+ * Example 2: Compute Timestamp from POSIX `gettimeofday()`.
+ * struct timeval tv;
+ * gettimeofday(&tv, NULL);
+ * Timestamp timestamp;
+ * timestamp.set_seconds(tv.tv_sec);
+ * timestamp.set_nanos(tv.tv_usec * 1000);
+ * Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`.
+ * FILETIME ft;
+ * GetSystemTimeAsFileTime(&ft);
+ * UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
+ * // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
+ * // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
+ * Timestamp timestamp;
+ * timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
+ * timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
+ * Example 4: Compute Timestamp from Java `System.currentTimeMillis()`.
+ * long millis = System.currentTimeMillis();
+ * Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
+ * .setNanos((int) ((millis % 1000) * 1000000)).build();
+ * Example 5: Compute Timestamp from current time in Python.
+ * timestamp = Timestamp()
+ * timestamp.GetCurrentTime()
+ * # JSON Mapping
+ * In JSON format, the Timestamp type is encoded as a string in the
+ * [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the
+ * format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z"
+ * where {year} is always expressed using four digits while {month}, {day},
+ * {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional
+ * seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution),
+ * are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone
+ * is required, though only UTC (as indicated by "Z") is presently supported.
+ * For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past
+ * 01:30 UTC on January 15, 2017.
+ * In JavaScript, one can convert a Date object to this format using the
+ * standard [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString]
+ * method. In Python, a standard `datetime.datetime` object can be converted
+ * to this format using [`strftime`](https://docs.python.org/2/library/time.html#time.strftime)
+ * with the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one
+ * can use the Joda Time's [`ISODateTimeFormat.dateTime()`](
+ * http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime--)
+ * to obtain a formatter capable of generating timestamps in this format.
+ *
+ * Generated from protobuf message <code>google.protobuf.Timestamp</code>
+ */
+class Timestamp extends \Google\Protobuf\Internal\Message
+{
+ /**
+ * Represents seconds of UTC time since Unix epoch
+ * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
+ * 9999-12-31T23:59:59Z inclusive.
+ *
+ * Generated from protobuf field <code>int64 seconds = 1;</code>
+ */
+ private $seconds = 0;
+ /**
+ * Non-negative fractions of a second at nanosecond resolution. Negative
+ * second values with fractions must still have non-negative nanos values
+ * that count forward in time. Must be from 0 to 999,999,999
+ * inclusive.
+ *
+ * Generated from protobuf field <code>int32 nanos = 2;</code>
+ */
+ private $nanos = 0;
+
+ public function __construct() {
+ \GPBMetadata\Google\Protobuf\Timestamp::initOnce();
+ parent::__construct();
+ }
+
+ /**
+ * Represents seconds of UTC time since Unix epoch
+ * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
+ * 9999-12-31T23:59:59Z inclusive.
+ *
+ * Generated from protobuf field <code>int64 seconds = 1;</code>
+ * @return int|string
+ */
+ public function getSeconds()
+ {
+ return $this->seconds;
+ }
+
+ /**
+ * Represents seconds of UTC time since Unix epoch
+ * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
+ * 9999-12-31T23:59:59Z inclusive.
+ *
+ * Generated from protobuf field <code>int64 seconds = 1;</code>
+ * @param int|string $var
+ * @return $this
+ */
+ public function setSeconds($var)
+ {
+ GPBUtil::checkInt64($var);
+ $this->seconds = $var;
+
+ return $this;
+ }
+
+ /**
+ * Non-negative fractions of a second at nanosecond resolution. Negative
+ * second values with fractions must still have non-negative nanos values
+ * that count forward in time. Must be from 0 to 999,999,999
+ * inclusive.
+ *
+ * Generated from protobuf field <code>int32 nanos = 2;</code>
+ * @return int
+ */
+ public function getNanos()
+ {
+ return $this->nanos;
+ }
+
+ /**
+ * Non-negative fractions of a second at nanosecond resolution. Negative
+ * second values with fractions must still have non-negative nanos values
+ * that count forward in time. Must be from 0 to 999,999,999
+ * inclusive.
+ *
+ * Generated from protobuf field <code>int32 nanos = 2;</code>
+ * @param int $var
+ * @return $this
+ */
+ public function setNanos($var)
+ {
+ GPBUtil::checkInt32($var);
+ $this->nanos = $var;
+
+ return $this;
+ }
+
+ /**
+ * Converts PHP DateTime to Timestamp.
+ *
+ * @param DateTime $datetime
+ */
+ public function fromDateTime($datetime)
+ {
+ if (get_class($datetime) !== \DateTime::class) {
+ trigger_error("Given parameter is not a DateTime.",
+ E_USER_ERROR);
+ }
+ $this->seconds = $datetime->format('U');
+ $this->nanos = 0;
+ }
+
+ /**
+ * Converts Timestamp to PHP DateTime. Nano second is ignored.
+ *
+ * @return DateTime $datetime
+ */
+ public function toDateTime()
+ {
+ return \DateTime::createFromFormat('U', $this->seconds);
+ }
+}
+
diff --git a/php/src/Google/Protobuf/Type.php b/php/src/Google/Protobuf/Type.php
new file mode 100644
index 00000000..7dbe2cab
--- /dev/null
+++ b/php/src/Google/Protobuf/Type.php
@@ -0,0 +1,217 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/type.proto
+
+namespace Google\Protobuf;
+
+use Google\Protobuf\Internal\GPBType;
+use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\GPBUtil;
+
+/**
+ * A protocol buffer message type.
+ *
+ * Generated from protobuf message <code>google.protobuf.Type</code>
+ */
+class Type extends \Google\Protobuf\Internal\Message
+{
+ /**
+ * The fully qualified message name.
+ *
+ * Generated from protobuf field <code>string name = 1;</code>
+ */
+ private $name = '';
+ /**
+ * The list of fields.
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.Field fields = 2;</code>
+ */
+ private $fields;
+ /**
+ * The list of types appearing in `oneof` definitions in this type.
+ *
+ * Generated from protobuf field <code>repeated string oneofs = 3;</code>
+ */
+ private $oneofs;
+ /**
+ * The protocol buffer options.
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.Option options = 4;</code>
+ */
+ private $options;
+ /**
+ * The source context.
+ *
+ * Generated from protobuf field <code>.google.protobuf.SourceContext source_context = 5;</code>
+ */
+ private $source_context = null;
+ /**
+ * The source syntax.
+ *
+ * Generated from protobuf field <code>.google.protobuf.Syntax syntax = 6;</code>
+ */
+ private $syntax = 0;
+
+ public function __construct() {
+ \GPBMetadata\Google\Protobuf\Type::initOnce();
+ parent::__construct();
+ }
+
+ /**
+ * The fully qualified message name.
+ *
+ * Generated from protobuf field <code>string name = 1;</code>
+ * @return string
+ */
+ public function getName()
+ {
+ return $this->name;
+ }
+
+ /**
+ * The fully qualified message name.
+ *
+ * Generated from protobuf field <code>string name = 1;</code>
+ * @param string $var
+ * @return $this
+ */
+ public function setName($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->name = $var;
+
+ return $this;
+ }
+
+ /**
+ * The list of fields.
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.Field fields = 2;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
+ */
+ public function getFields()
+ {
+ return $this->fields;
+ }
+
+ /**
+ * The list of fields.
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.Field fields = 2;</code>
+ * @param \Google\Protobuf\Field[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
+ */
+ public function setFields($var)
+ {
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Field::class);
+ $this->fields = $arr;
+
+ return $this;
+ }
+
+ /**
+ * The list of types appearing in `oneof` definitions in this type.
+ *
+ * Generated from protobuf field <code>repeated string oneofs = 3;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
+ */
+ public function getOneofs()
+ {
+ return $this->oneofs;
+ }
+
+ /**
+ * The list of types appearing in `oneof` definitions in this type.
+ *
+ * Generated from protobuf field <code>repeated string oneofs = 3;</code>
+ * @param string[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
+ */
+ public function setOneofs($var)
+ {
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::STRING);
+ $this->oneofs = $arr;
+
+ return $this;
+ }
+
+ /**
+ * The protocol buffer options.
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.Option options = 4;</code>
+ * @return \Google\Protobuf\Internal\RepeatedField
+ */
+ public function getOptions()
+ {
+ return $this->options;
+ }
+
+ /**
+ * The protocol buffer options.
+ *
+ * Generated from protobuf field <code>repeated .google.protobuf.Option options = 4;</code>
+ * @param \Google\Protobuf\Option[]|\Google\Protobuf\Internal\RepeatedField $var
+ * @return $this
+ */
+ public function setOptions($var)
+ {
+ $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Option::class);
+ $this->options = $arr;
+
+ return $this;
+ }
+
+ /**
+ * The source context.
+ *
+ * Generated from protobuf field <code>.google.protobuf.SourceContext source_context = 5;</code>
+ * @return \Google\Protobuf\SourceContext
+ */
+ public function getSourceContext()
+ {
+ return $this->source_context;
+ }
+
+ /**
+ * The source context.
+ *
+ * Generated from protobuf field <code>.google.protobuf.SourceContext source_context = 5;</code>
+ * @param \Google\Protobuf\SourceContext $var
+ * @return $this
+ */
+ public function setSourceContext($var)
+ {
+ GPBUtil::checkMessage($var, \Google\Protobuf\SourceContext::class);
+ $this->source_context = $var;
+
+ return $this;
+ }
+
+ /**
+ * The source syntax.
+ *
+ * Generated from protobuf field <code>.google.protobuf.Syntax syntax = 6;</code>
+ * @return int
+ */
+ public function getSyntax()
+ {
+ return $this->syntax;
+ }
+
+ /**
+ * The source syntax.
+ *
+ * Generated from protobuf field <code>.google.protobuf.Syntax syntax = 6;</code>
+ * @param int $var
+ * @return $this
+ */
+ public function setSyntax($var)
+ {
+ GPBUtil::checkEnum($var, \Google\Protobuf\Syntax::class);
+ $this->syntax = $var;
+
+ return $this;
+ }
+
+}
+
diff --git a/php/src/Google/Protobuf/UInt32Value.php b/php/src/Google/Protobuf/UInt32Value.php
new file mode 100644
index 00000000..61a3ddf1
--- /dev/null
+++ b/php/src/Google/Protobuf/UInt32Value.php
@@ -0,0 +1,58 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/wrappers.proto
+
+namespace Google\Protobuf;
+
+use Google\Protobuf\Internal\GPBType;
+use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\GPBUtil;
+
+/**
+ * Wrapper message for `uint32`.
+ * The JSON representation for `UInt32Value` is JSON number.
+ *
+ * Generated from protobuf message <code>google.protobuf.UInt32Value</code>
+ */
+class UInt32Value extends \Google\Protobuf\Internal\Message
+{
+ /**
+ * The uint32 value.
+ *
+ * Generated from protobuf field <code>uint32 value = 1;</code>
+ */
+ private $value = 0;
+
+ public function __construct() {
+ \GPBMetadata\Google\Protobuf\Wrappers::initOnce();
+ parent::__construct();
+ }
+
+ /**
+ * The uint32 value.
+ *
+ * Generated from protobuf field <code>uint32 value = 1;</code>
+ * @return int
+ */
+ public function getValue()
+ {
+ return $this->value;
+ }
+
+ /**
+ * The uint32 value.
+ *
+ * Generated from protobuf field <code>uint32 value = 1;</code>
+ * @param int $var
+ * @return $this
+ */
+ public function setValue($var)
+ {
+ GPBUtil::checkUint32($var);
+ $this->value = $var;
+
+ return $this;
+ }
+
+}
+
diff --git a/php/src/Google/Protobuf/UInt64Value.php b/php/src/Google/Protobuf/UInt64Value.php
new file mode 100644
index 00000000..69f7eb8e
--- /dev/null
+++ b/php/src/Google/Protobuf/UInt64Value.php
@@ -0,0 +1,58 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/wrappers.proto
+
+namespace Google\Protobuf;
+
+use Google\Protobuf\Internal\GPBType;
+use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\GPBUtil;
+
+/**
+ * Wrapper message for `uint64`.
+ * The JSON representation for `UInt64Value` is JSON string.
+ *
+ * Generated from protobuf message <code>google.protobuf.UInt64Value</code>
+ */
+class UInt64Value extends \Google\Protobuf\Internal\Message
+{
+ /**
+ * The uint64 value.
+ *
+ * Generated from protobuf field <code>uint64 value = 1;</code>
+ */
+ private $value = 0;
+
+ public function __construct() {
+ \GPBMetadata\Google\Protobuf\Wrappers::initOnce();
+ parent::__construct();
+ }
+
+ /**
+ * The uint64 value.
+ *
+ * Generated from protobuf field <code>uint64 value = 1;</code>
+ * @return int|string
+ */
+ public function getValue()
+ {
+ return $this->value;
+ }
+
+ /**
+ * The uint64 value.
+ *
+ * Generated from protobuf field <code>uint64 value = 1;</code>
+ * @param int|string $var
+ * @return $this
+ */
+ public function setValue($var)
+ {
+ GPBUtil::checkUint64($var);
+ $this->value = $var;
+
+ return $this;
+ }
+
+}
+
diff --git a/php/src/Google/Protobuf/Value.php b/php/src/Google/Protobuf/Value.php
new file mode 100644
index 00000000..052a3779
--- /dev/null
+++ b/php/src/Google/Protobuf/Value.php
@@ -0,0 +1,194 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/struct.proto
+
+namespace Google\Protobuf;
+
+use Google\Protobuf\Internal\GPBType;
+use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\GPBUtil;
+
+/**
+ * `Value` represents a dynamically typed value which can be either
+ * null, a number, a string, a boolean, a recursive struct value, or a
+ * list of values. A producer of value is expected to set one of that
+ * variants, absence of any variant indicates an error.
+ * The JSON representation for `Value` is JSON value.
+ *
+ * Generated from protobuf message <code>google.protobuf.Value</code>
+ */
+class Value extends \Google\Protobuf\Internal\Message
+{
+ protected $kind;
+
+ public function __construct() {
+ \GPBMetadata\Google\Protobuf\Struct::initOnce();
+ parent::__construct();
+ }
+
+ /**
+ * Represents a null value.
+ *
+ * Generated from protobuf field <code>.google.protobuf.NullValue null_value = 1;</code>
+ * @return int
+ */
+ public function getNullValue()
+ {
+ return $this->readOneof(1);
+ }
+
+ /**
+ * Represents a null value.
+ *
+ * Generated from protobuf field <code>.google.protobuf.NullValue null_value = 1;</code>
+ * @param int $var
+ * @return $this
+ */
+ public function setNullValue($var)
+ {
+ GPBUtil::checkEnum($var, \Google\Protobuf\NullValue::class);
+ $this->writeOneof(1, $var);
+
+ return $this;
+ }
+
+ /**
+ * Represents a double value.
+ *
+ * Generated from protobuf field <code>double number_value = 2;</code>
+ * @return float
+ */
+ public function getNumberValue()
+ {
+ return $this->readOneof(2);
+ }
+
+ /**
+ * Represents a double value.
+ *
+ * Generated from protobuf field <code>double number_value = 2;</code>
+ * @param float $var
+ * @return $this
+ */
+ public function setNumberValue($var)
+ {
+ GPBUtil::checkDouble($var);
+ $this->writeOneof(2, $var);
+
+ return $this;
+ }
+
+ /**
+ * Represents a string value.
+ *
+ * Generated from protobuf field <code>string string_value = 3;</code>
+ * @return string
+ */
+ public function getStringValue()
+ {
+ return $this->readOneof(3);
+ }
+
+ /**
+ * Represents a string value.
+ *
+ * Generated from protobuf field <code>string string_value = 3;</code>
+ * @param string $var
+ * @return $this
+ */
+ public function setStringValue($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->writeOneof(3, $var);
+
+ return $this;
+ }
+
+ /**
+ * Represents a boolean value.
+ *
+ * Generated from protobuf field <code>bool bool_value = 4;</code>
+ * @return bool
+ */
+ public function getBoolValue()
+ {
+ return $this->readOneof(4);
+ }
+
+ /**
+ * Represents a boolean value.
+ *
+ * Generated from protobuf field <code>bool bool_value = 4;</code>
+ * @param bool $var
+ * @return $this
+ */
+ public function setBoolValue($var)
+ {
+ GPBUtil::checkBool($var);
+ $this->writeOneof(4, $var);
+
+ return $this;
+ }
+
+ /**
+ * Represents a structured value.
+ *
+ * Generated from protobuf field <code>.google.protobuf.Struct struct_value = 5;</code>
+ * @return \Google\Protobuf\Struct
+ */
+ public function getStructValue()
+ {
+ return $this->readOneof(5);
+ }
+
+ /**
+ * Represents a structured value.
+ *
+ * Generated from protobuf field <code>.google.protobuf.Struct struct_value = 5;</code>
+ * @param \Google\Protobuf\Struct $var
+ * @return $this
+ */
+ public function setStructValue($var)
+ {
+ GPBUtil::checkMessage($var, \Google\Protobuf\Struct::class);
+ $this->writeOneof(5, $var);
+
+ return $this;
+ }
+
+ /**
+ * Represents a repeated `Value`.
+ *
+ * Generated from protobuf field <code>.google.protobuf.ListValue list_value = 6;</code>
+ * @return \Google\Protobuf\ListValue
+ */
+ public function getListValue()
+ {
+ return $this->readOneof(6);
+ }
+
+ /**
+ * Represents a repeated `Value`.
+ *
+ * Generated from protobuf field <code>.google.protobuf.ListValue list_value = 6;</code>
+ * @param \Google\Protobuf\ListValue $var
+ * @return $this
+ */
+ public function setListValue($var)
+ {
+ GPBUtil::checkMessage($var, \Google\Protobuf\ListValue::class);
+ $this->writeOneof(6, $var);
+
+ return $this;
+ }
+
+ /**
+ * @return string
+ */
+ public function getKind()
+ {
+ return $this->whichOneof("kind");
+ }
+
+}
+
diff --git a/php/src/Google/Protobuf/descriptor.php b/php/src/Google/Protobuf/descriptor.php
deleted file mode 100644
index ef6b9dcf..00000000
--- a/php/src/Google/Protobuf/descriptor.php
+++ /dev/null
@@ -1,558 +0,0 @@
-<?php
-
-// 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.
-
-namespace Google\Protobuf\Internal;
-
-use Google\Protobuf\Internal\GPBType;
-use Google\Protobuf\Internal\MessageOptions;
-
-class FileDescriptor
-{
-
- private $package;
- private $message_type = [];
- private $enum_type = [];
-
- public function setPackage($package)
- {
- $this->package = $package;
- }
-
- public function getPackage()
- {
- return $this->package;
- }
-
- public function getMessageType()
- {
- return $this->message_type;
- }
-
- public function addMessageType($desc)
- {
- $this->message_type[] = $desc;
- }
-
- public function getEnumType()
- {
- return $this->enum_type;
- }
-
- public function addEnumType($desc)
- {
- $this->enum_type[]= $desc;
- }
-
- public static function buildFromProto($proto)
- {
- $file = new FileDescriptor();
- $file->setPackage($proto->getPackage());
- foreach ($proto->getMessageType() as $message_proto) {
- $file->addMessageType(Descriptor::buildFromProto(
- $message_proto, $file->getPackage(), ""));
- }
- foreach ($proto->getEnumType() as $enum_proto) {
- $file->getEnumType()[] =
- $file->addEnumType(
- EnumDescriptor::buildFromProto(
- $enum_proto,
- $file->getPackage(),
- ""));
- }
- return $file;
- }
-}
-
-class Descriptor
-{
-
- private $full_name;
- private $field = [];
- private $nested_type = [];
- private $enum_type = [];
- private $klass;
- private $options;
- private $oneof_decl = [];
-
- public function addOneofDecl($oneof)
- {
- $this->oneof_decl[] = $oneof;
- }
-
- public function getOneofDecl()
- {
- return $this->oneof_decl;
- }
-
- public function setFullName($full_name)
- {
- $this->full_name = $full_name;
- }
-
- public function getFullName()
- {
- return $this->full_name;
- }
-
- public function addField($field)
- {
- $this->field[$field->getNumber()] = $field;
- }
-
- public function getField()
- {
- return $this->field;
- }
-
- public function addNestedType($desc)
- {
- $this->nested_type[] = $desc;
- }
-
- public function getNestedType()
- {
- return $this->nested_type;
- }
-
- public function addEnumType($desc)
- {
- $this->enum_type[] = $desc;
- }
-
- public function getEnumType()
- {
- return $this->enum_type;
- }
-
- public function getFieldByNumber($number)
- {
- return $this->field[$number];
- }
-
- public function setClass($klass)
- {
- $this->klass = $klass;
- }
-
- public function getClass()
- {
- return $this->klass;
- }
-
- public function setOptions($options)
- {
- $this->options = $options;
- }
-
- public function getOptions()
- {
- return $this->options;
- }
-
- public static function buildFromProto($proto, $package, $containing)
- {
- $desc = new Descriptor();
-
- $message_name_without_package = "";
- $classname = "";
- $fullname = "";
- getFullClassName(
- $proto,
- $containing,
- $package,
- $message_name_without_package,
- $classname,
- $fullname);
- $desc->setFullName($fullname);
- $desc->setClass($classname);
- $desc->setOptions($proto->getOptions());
-
- foreach ($proto->getField() as $field_proto) {
- $desc->addField(FieldDescriptor::buildFromProto($field_proto));
- }
-
- // Handle nested types.
- foreach ($proto->getNestedType() as $nested_proto) {
- $desc->addNestedType(Descriptor::buildFromProto(
- $nested_proto, $package, $message_name_without_package));
- }
-
- // Handle oneof fields.
- foreach ($proto->getOneofDecl() as $oneof_proto) {
- $desc->addOneofDecl(
- OneofDescriptor::buildFromProto($oneof_proto, $desc));
- }
-
- return $desc;
- }
-}
-
-function addPrefixIfSpecial(
- $name,
- $package)
-{
- if ($name === "Empty" && $package === "google.protobuf") {
- return "GPBEmpty";
- } else {
- return $name;
- }
-}
-
-function getFullClassName(
- $proto,
- $containing,
- $package,
- &$message_name_without_package,
- &$classname,
- &$fullname)
-{
- // Full name needs to start with '.'.
- $message_name_without_package =
- addPrefixIfSpecial($proto->getName(), $package);
- if ($containing !== "") {
- $message_name_without_package =
- $containing . "." . $message_name_without_package;
- }
- if ($package === "") {
- $fullname = "." . $message_name_without_package;
- } else {
- $fullname = "." . $package . "." . $message_name_without_package;
- }
-
- // Nested message class names are seperated by '_', and package names are
- // seperated by '\'.
- $class_name_without_package =
- implode('_', array_map('ucwords',
- explode('.', $message_name_without_package)));
- if ($package === "") {
- $classname = $class_name_without_package;
- } else {
- $classname =
- implode('\\', array_map('ucwords', explode('.', $package))).
- "\\".$class_name_without_package;
- }
-}
-
-class OneofDescriptor
-{
-
- private $name;
- private $fields;
-
- public function setName($name)
- {
- $this->name = $name;
- }
-
- public function getName()
- {
- return $this->name;
- }
-
- public function addField(&$field)
- {
- $this->fields[] = $field;
- }
-
- public function getFields()
- {
- return $this->fields;
- }
-
- public static function buildFromProto($oneof_proto)
- {
- $oneof = new OneofDescriptor();
- $oneof->setName($oneof_proto->getName());
- return $oneof;
- }
-}
-
-
-class EnumDescriptor
-{
-
- private $klass;
- private $full_name;
- private $value;
-
- public function setFullName($full_name)
- {
- $this->full_name = $full_name;
- }
-
- public function getFullName()
- {
- return $this->full_name;
- }
-
- public function addValue($number, $value)
- {
- $this->value[$number] = $value;
- }
-
- public function setClass($klass)
- {
- $this->klass = $klass;
- }
-
- public function getClass()
- {
- return $this->klass;
- }
-
- public static function buildFromProto($proto, $package, $containing)
- {
- $desc = new EnumDescriptor();
-
- $enum_name_without_package = "";
- $classname = "";
- $fullname = "";
- getFullClassName(
- $proto,
- $containing,
- $package,
- $enum_name_without_package,
- $classname,
- $fullname);
- $desc->setFullName($fullname);
- $desc->setClass($classname);
-
- return $desc;
- }
-}
-
-class EnumValueDescriptor
-{
-}
-
-class FieldDescriptor
-{
-
- private $name;
- private $setter;
- private $getter;
- private $number;
- private $label;
- private $type;
- private $message_type;
- private $enum_type;
- private $packed;
- private $is_map;
- private $oneof_index = -1;
-
- public function setOneofIndex($index)
- {
- $this->oneof_index = $index;
- }
-
- public function getOneofIndex()
- {
- return $this->oneof_index;
- }
-
- public function setName($name)
- {
- $this->name = $name;
- }
-
- public function getName()
- {
- return $this->name;
- }
-
- public function setSetter($setter)
- {
- $this->setter = $setter;
- }
-
- public function getSetter()
- {
- return $this->setter;
- }
-
- public function setGetter($getter)
- {
- $this->getter = $getter;
- }
-
- public function getGetter()
- {
- return $this->getter;
- }
-
- public function setNumber($number)
- {
- $this->number = $number;
- }
-
- public function getNumber()
- {
- return $this->number;
- }
-
- public function setLabel($label)
- {
- $this->label = $label;
- }
-
- public function getLabel()
- {
- return $this->label;
- }
-
- public function isRepeated()
- {
- return $this->label === GPBLabel::REPEATED;
- }
-
- public function setType($type)
- {
- $this->type = $type;
- }
-
- public function getType()
- {
- return $this->type;
- }
-
- public function setMessageType($message_type)
- {
- $this->message_type = $message_type;
- }
-
- public function getMessageType()
- {
- return $this->message_type;
- }
-
- public function setEnumType($enum_type)
- {
- $this->enum_type = $enum_type;
- }
-
- public function getEnumType()
- {
- return $this->enum_type;
- }
-
- public function setPacked($packed)
- {
- $this->packed = $packed;
- }
-
- public function getPacked()
- {
- return $this->packed;
- }
-
- public function isPackable()
- {
- return $this->isRepeated() && self::isTypePackable($this->type);
- }
-
- public function isMap()
- {
- return $this->getType() == GPBType::MESSAGE &&
- !is_null($this->getMessageType()->getOptions()) &&
- $this->getMessageType()->getOptions()->getMapEntry();
- }
-
- private static function isTypePackable($field_type)
- {
- return ($field_type !== GPBType::STRING &&
- $field_type !== GPBType::GROUP &&
- $field_type !== GPBType::MESSAGE &&
- $field_type !== GPBType::BYTES);
- }
-
- public static function getFieldDescriptor(
- $name,
- $label,
- $type,
- $number,
- $oneof_index,
- $packed,
- $type_name = null)
- {
- $field = new FieldDescriptor();
- $field->setName($name);
- $camel_name = implode('', array_map('ucwords', explode('_', $name)));
- $field->setGetter('get' . $camel_name);
- $field->setSetter('set' . $camel_name);
- $field->setType($type);
- $field->setNumber($number);
- $field->setLabel($label);
- $field->setPacked($packed);
- $field->setOneofIndex($oneof_index);
-
- // At this time, the message/enum type may have not been added to pool.
- // So we use the type name as place holder and will replace it with the
- // actual descriptor in cross building.
- switch ($type) {
- case GPBType::MESSAGE:
- $field->setMessageType($type_name);
- break;
- case GPBType::ENUM:
- $field->setEnumType($type_name);
- break;
- default:
- break;
- }
-
- return $field;
- }
-
- public static function buildFromProto($proto)
- {
- $type_name = null;
- switch ($proto->getType()) {
- case GPBType::MESSAGE:
- case GPBType::GROUP:
- case GPBType::ENUM:
- $type_name = $proto->getTypeName();
- break;
- default:
- break;
- }
-
- $oneof_index = $proto->hasOneofIndex() ? $proto->getOneofIndex() : -1;
- $packed = false;
- $options = $proto->getOptions();
- if ($options !== null) {
- $packed = $options->getPacked();
- }
-
- return FieldDescriptor::getFieldDescriptor(
- $proto->getName(), $proto->getLabel(), $proto->getType(),
- $proto->getNumber(), $oneof_index, $packed, $type_name);
- }
-}
diff --git a/php/tests/array_test.php b/php/tests/array_test.php
index a4cad719..1a26d72a 100644
--- a/php/tests/array_test.php
+++ b/php/tests/array_test.php
@@ -19,23 +19,23 @@ class RepeatedFieldTest extends PHPUnit_Framework_TestCase
$arr = new RepeatedField(GPBType::INT32);
// Test append.
- $arr []= MAX_INT32;
+ $arr[] = MAX_INT32;
$this->assertSame(MAX_INT32, $arr[0]);
- $arr []= MIN_INT32;
+ $arr[] = MIN_INT32;
$this->assertSame(MIN_INT32, $arr[1]);
- $arr []= 1.1;
+ $arr[] = 1.1;
$this->assertSame(1, $arr[2]);
- $arr []= MAX_INT32_FLOAT;
+ $arr[] = MAX_INT32_FLOAT;
$this->assertSame(MAX_INT32, $arr[3]);
- $arr []= MAX_INT32_FLOAT;
+ $arr[] = MAX_INT32_FLOAT;
$this->assertSame(MAX_INT32, $arr[4]);
- $arr []= '2';
+ $arr[] = '2';
$this->assertSame(2, $arr[5]);
- $arr []= '3.1';
+ $arr[] = '3.1';
$this->assertSame(3, $arr[6]);
- $arr []= MAX_INT32_STRING;
+ $arr[] = MAX_INT32_STRING;
$this->assertSame(MAX_INT32, $arr[7]);
$this->assertEquals(8, count($arr));
@@ -46,29 +46,29 @@ class RepeatedFieldTest extends PHPUnit_Framework_TestCase
}
// Test set.
- $arr [0]= MAX_INT32;
+ $arr[0] = MAX_INT32;
$this->assertSame(MAX_INT32, $arr[0]);
- $arr [1]= MIN_INT32;
+ $arr[1] = MIN_INT32;
$this->assertSame(MIN_INT32, $arr[1]);
- $arr [2]= 1.1;
+ $arr[2] = 1.1;
$this->assertSame(1, $arr[2]);
- $arr [3]= MAX_INT32_FLOAT;
+ $arr[3] = MAX_INT32_FLOAT;
$this->assertSame(MAX_INT32, $arr[3]);
- $arr [4]= MAX_INT32_FLOAT;
+ $arr[4] = MAX_INT32_FLOAT;
$this->assertSame(MAX_INT32, $arr[4]);
- $arr [5]= '2';
+ $arr[5] = '2';
$this->assertSame(2, $arr[5]);
- $arr [6]= '3.1';
+ $arr[6] = '3.1';
$this->assertSame(3, $arr[6]);
- $arr [7]= MAX_INT32_STRING;
+ $arr[7] = MAX_INT32_STRING;
$this->assertSame(MAX_INT32, $arr[7]);
// Test foreach.
$arr = new RepeatedField(GPBType::INT32);
for ($i = 0; $i < 3; $i++) {
- $arr []= $i;
+ $arr[] = $i;
}
$i = 0;
foreach ($arr as $val) {
@@ -77,44 +77,6 @@ class RepeatedFieldTest extends PHPUnit_Framework_TestCase
$this->assertSame(3, $i);
}
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testInt32AppendStringFail()
- {
- $arr = new RepeatedField(GPBType::INT32);
- $arr []= 'abc';
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testInt32SetStringFail()
- {
- $arr = new RepeatedField(GPBType::INT32);
- $arr []= 0;
- $arr [0]= 'abc';
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testInt32AppendMessageFail()
- {
- $arr = new RepeatedField(GPBType::INT32);
- $arr []= new TestMessage_Sub();
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testInt32SetMessageFail()
- {
- $arr = new RepeatedField(GPBType::INT32);
- $arr []= 0;
- $arr [0]= new TestMessage_Sub();
- }
-
#########################################################
# Test uint32 field.
#########################################################
@@ -124,31 +86,31 @@ class RepeatedFieldTest extends PHPUnit_Framework_TestCase
$arr = new RepeatedField(GPBType::UINT32);
// Test append.
- $arr []= MAX_UINT32;
+ $arr[] = MAX_UINT32;
$this->assertSame(-1, $arr[0]);
- $arr []= -1;
+ $arr[] = -1;
$this->assertSame(-1, $arr[1]);
- $arr []= MIN_UINT32;
+ $arr[] = MIN_UINT32;
$this->assertSame(MIN_UINT32, $arr[2]);
- $arr []= 1.1;
+ $arr[] = 1.1;
$this->assertSame(1, $arr[3]);
- $arr []= MAX_UINT32_FLOAT;
+ $arr[] = MAX_UINT32_FLOAT;
$this->assertSame(-1, $arr[4]);
- $arr []= -1.0;
+ $arr[] = -1.0;
$this->assertSame(-1, $arr[5]);
- $arr []= MIN_UINT32_FLOAT;
+ $arr[] = MIN_UINT32_FLOAT;
$this->assertSame(MIN_UINT32, $arr[6]);
- $arr []= '2';
+ $arr[] = '2';
$this->assertSame(2, $arr[7]);
- $arr []= '3.1';
+ $arr[] = '3.1';
$this->assertSame(3, $arr[8]);
- $arr []= MAX_UINT32_STRING;
+ $arr[] = MAX_UINT32_STRING;
$this->assertSame(-1, $arr[9]);
- $arr []= '-1.0';
+ $arr[] = '-1.0';
$this->assertSame(-1, $arr[10]);
- $arr []= MIN_UINT32_STRING;
+ $arr[] = MIN_UINT32_STRING;
$this->assertSame(MIN_UINT32, $arr[11]);
$this->assertEquals(12, count($arr));
@@ -159,72 +121,34 @@ class RepeatedFieldTest extends PHPUnit_Framework_TestCase
}
// Test set.
- $arr [0]= MAX_UINT32;
+ $arr[0] = MAX_UINT32;
$this->assertSame(-1, $arr[0]);
- $arr [1]= -1;
+ $arr[1] = -1;
$this->assertSame(-1, $arr[1]);
- $arr [2]= MIN_UINT32;
+ $arr[2] = MIN_UINT32;
$this->assertSame(MIN_UINT32, $arr[2]);
- $arr [3]= 1.1;
+ $arr[3] = 1.1;
$this->assertSame(1, $arr[3]);
- $arr [4]= MAX_UINT32_FLOAT;
+ $arr[4] = MAX_UINT32_FLOAT;
$this->assertSame(-1, $arr[4]);
- $arr [5]= -1.0;
+ $arr[5] = -1.0;
$this->assertSame(-1, $arr[5]);
- $arr [6]= MIN_UINT32_FLOAT;
+ $arr[6] = MIN_UINT32_FLOAT;
$this->assertSame(MIN_UINT32, $arr[6]);
- $arr [7]= '2';
+ $arr[7] = '2';
$this->assertSame(2, $arr[7]);
- $arr [8]= '3.1';
+ $arr[8] = '3.1';
$this->assertSame(3, $arr[8]);
- $arr [9]= MAX_UINT32_STRING;
+ $arr[9] = MAX_UINT32_STRING;
$this->assertSame(-1, $arr[9]);
- $arr [10]= '-1.0';
+ $arr[10] = '-1.0';
$this->assertSame(-1, $arr[10]);
- $arr [11]= MIN_UINT32_STRING;
+ $arr[11] = MIN_UINT32_STRING;
$this->assertSame(MIN_UINT32, $arr[11]);
}
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testUint32AppendStringFail()
- {
- $arr = new RepeatedField(GPBType::UINT32);
- $arr []= 'abc';
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testUint32SetStringFail()
- {
- $arr = new RepeatedField(GPBType::UINT32);
- $arr []= 0;
- $arr [0]= 'abc';
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testUint32AppendMessageFail()
- {
- $arr = new RepeatedField(GPBType::UINT32);
- $arr []= new TestMessage_Sub();
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testUint32SetMessageFail()
- {
- $arr = new RepeatedField(GPBType::UINT32);
- $arr []= 0;
- $arr [0]= new TestMessage_Sub();
- }
-
#########################################################
# Test int64 field.
#########################################################
@@ -234,13 +158,13 @@ class RepeatedFieldTest extends PHPUnit_Framework_TestCase
$arr = new RepeatedField(GPBType::INT64);
// Test append.
- $arr []= MAX_INT64;
- $arr []= MIN_INT64;
- $arr []= 1.1;
- $arr []= '2';
- $arr []= '3.1';
- $arr []= MAX_INT64_STRING;
- $arr []= MIN_INT64_STRING;
+ $arr[] = MAX_INT64;
+ $arr[] = MIN_INT64;
+ $arr[] = 1.1;
+ $arr[] = '2';
+ $arr[] = '3.1';
+ $arr[] = MAX_INT64_STRING;
+ $arr[] = MIN_INT64_STRING;
if (PHP_INT_SIZE == 4) {
$this->assertSame(MAX_INT64, $arr[0]);
$this->assertSame(MIN_INT64, $arr[1]);
@@ -272,13 +196,13 @@ class RepeatedFieldTest extends PHPUnit_Framework_TestCase
}
// Test set.
- $arr [0]= MAX_INT64;
- $arr [1]= MIN_INT64;
- $arr [2]= 1.1;
- $arr [3]= '2';
- $arr [4]= '3.1';
- $arr [5]= MAX_INT64_STRING;
- $arr [6]= MIN_INT64_STRING;
+ $arr[0] = MAX_INT64;
+ $arr[1] = MIN_INT64;
+ $arr[2] = 1.1;
+ $arr[3] = '2';
+ $arr[4] = '3.1';
+ $arr[5] = MAX_INT64_STRING;
+ $arr[6] = MIN_INT64_STRING;
if (PHP_INT_SIZE == 4) {
$this->assertSame(MAX_INT64_STRING, $arr[0]);
@@ -299,44 +223,6 @@ class RepeatedFieldTest extends PHPUnit_Framework_TestCase
}
}
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testInt64AppendStringFail()
- {
- $arr = new RepeatedField(GPBType::INT64);
- $arr []= 'abc';
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testInt64SetStringFail()
- {
- $arr = new RepeatedField(GPBType::INT64);
- $arr []= 0;
- $arr [0]= 'abc';
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testInt64AppendMessageFail()
- {
- $arr = new RepeatedField(GPBType::INT64);
- $arr []= new TestMessage_Sub();
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testInt64SetMessageFail()
- {
- $arr = new RepeatedField(GPBType::INT64);
- $arr []= 0;
- $arr [0]= new TestMessage_Sub();
- }
-
#########################################################
# Test uint64 field.
#########################################################
@@ -346,11 +232,11 @@ class RepeatedFieldTest extends PHPUnit_Framework_TestCase
$arr = new RepeatedField(GPBType::UINT64);
// Test append.
- $arr []= MAX_UINT64;
- $arr []= 1.1;
- $arr []= '2';
- $arr []= '3.1';
- $arr []= MAX_UINT64_STRING;
+ $arr[] = MAX_UINT64;
+ $arr[] = 1.1;
+ $arr[] = '2';
+ $arr[] = '3.1';
+ $arr[] = MAX_UINT64_STRING;
if (PHP_INT_SIZE == 4) {
$this->assertSame(MAX_UINT64_STRING, $arr[0]);
@@ -379,11 +265,11 @@ class RepeatedFieldTest extends PHPUnit_Framework_TestCase
}
// Test set.
- $arr [0]= MAX_UINT64;
- $arr [1]= 1.1;
- $arr [2]= '2';
- $arr [3]= '3.1';
- $arr [4]= MAX_UINT64_STRING;
+ $arr[0] = MAX_UINT64;
+ $arr[1] = 1.1;
+ $arr[2] = '2';
+ $arr[3] = '3.1';
+ $arr[4] = MAX_UINT64_STRING;
if (PHP_INT_SIZE == 4) {
$this->assertSame(MAX_UINT64_STRING, $arr[0]);
@@ -400,44 +286,6 @@ class RepeatedFieldTest extends PHPUnit_Framework_TestCase
}
}
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testUint64AppendStringFail()
- {
- $arr = new RepeatedField(GPBType::UINT64);
- $arr []= 'abc';
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testUint64SetStringFail()
- {
- $arr = new RepeatedField(GPBType::UINT64);
- $arr []= 0;
- $arr [0]= 'abc';
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testUint64AppendMessageFail()
- {
- $arr = new RepeatedField(GPBType::UINT64);
- $arr []= new TestMessage_Sub();
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testUint64SetMessageFail()
- {
- $arr = new RepeatedField(GPBType::UINT64);
- $arr []= 0;
- $arr [0]= new TestMessage_Sub();
- }
-
#########################################################
# Test float field.
#########################################################
@@ -447,15 +295,15 @@ class RepeatedFieldTest extends PHPUnit_Framework_TestCase
$arr = new RepeatedField(GPBType::FLOAT);
// Test append.
- $arr []= 1;
+ $arr[] = 1;
$this->assertEquals(1.0, $arr[0], '', MAX_FLOAT_DIFF);
- $arr []= 1.1;
+ $arr[] = 1.1;
$this->assertEquals(1.1, $arr[1], '', MAX_FLOAT_DIFF);
- $arr []= '2';
+ $arr[] = '2';
$this->assertEquals(2.0, $arr[2], '', MAX_FLOAT_DIFF);
- $arr []= '3.1';
+ $arr[] = '3.1';
$this->assertEquals(3.1, $arr[3], '', MAX_FLOAT_DIFF);
$this->assertEquals(4, count($arr));
@@ -466,56 +314,18 @@ class RepeatedFieldTest extends PHPUnit_Framework_TestCase
}
// Test set.
- $arr [0]= 1;
+ $arr[0] = 1;
$this->assertEquals(1.0, $arr[0], '', MAX_FLOAT_DIFF);
- $arr [1]= 1.1;
+ $arr[1] = 1.1;
$this->assertEquals(1.1, $arr[1], '', MAX_FLOAT_DIFF);
- $arr [2]= '2';
+ $arr[2] = '2';
$this->assertEquals(2.0, $arr[2], '', MAX_FLOAT_DIFF);
- $arr [3]= '3.1';
+ $arr[3] = '3.1';
$this->assertEquals(3.1, $arr[3], '', MAX_FLOAT_DIFF);
}
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testFloatAppendStringFail()
- {
- $arr = new RepeatedField(GPBType::FLOAT);
- $arr []= 'abc';
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testFloatSetStringFail()
- {
- $arr = new RepeatedField(GPBType::FLOAT);
- $arr []= 0.0;
- $arr [0]= 'abc';
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testFloatAppendMessageFail()
- {
- $arr = new RepeatedField(GPBType::FLOAT);
- $arr []= new TestMessage_Sub();
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testFloatSetMessageFail()
- {
- $arr = new RepeatedField(GPBType::FLOAT);
- $arr []= 0.0;
- $arr [0]= new TestMessage_Sub();
- }
-
#########################################################
# Test double field.
#########################################################
@@ -525,15 +335,15 @@ class RepeatedFieldTest extends PHPUnit_Framework_TestCase
$arr = new RepeatedField(GPBType::DOUBLE);
// Test append.
- $arr []= 1;
+ $arr[] = 1;
$this->assertEquals(1.0, $arr[0], '', MAX_FLOAT_DIFF);
- $arr []= 1.1;
+ $arr[] = 1.1;
$this->assertEquals(1.1, $arr[1], '', MAX_FLOAT_DIFF);
- $arr []= '2';
+ $arr[] = '2';
$this->assertEquals(2.0, $arr[2], '', MAX_FLOAT_DIFF);
- $arr []= '3.1';
+ $arr[] = '3.1';
$this->assertEquals(3.1, $arr[3], '', MAX_FLOAT_DIFF);
$this->assertEquals(4, count($arr));
@@ -544,56 +354,18 @@ class RepeatedFieldTest extends PHPUnit_Framework_TestCase
}
// Test set.
- $arr [0]= 1;
+ $arr[0] = 1;
$this->assertEquals(1.0, $arr[0], '', MAX_FLOAT_DIFF);
- $arr [1]= 1.1;
+ $arr[1] = 1.1;
$this->assertEquals(1.1, $arr[1], '', MAX_FLOAT_DIFF);
- $arr [2]= '2';
+ $arr[2] = '2';
$this->assertEquals(2.0, $arr[2], '', MAX_FLOAT_DIFF);
- $arr [3]= '3.1';
+ $arr[3] = '3.1';
$this->assertEquals(3.1, $arr[3], '', MAX_FLOAT_DIFF);
}
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testDoubleAppendStringFail()
- {
- $arr = new RepeatedField(GPBType::DOUBLE);
- $arr []= 'abc';
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testDoubleSetStringFail()
- {
- $arr = new RepeatedField(GPBType::DOUBLE);
- $arr []= 0.0;
- $arr [0]= 'abc';
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testDoubleAppendMessageFail()
- {
- $arr = new RepeatedField(GPBType::DOUBLE);
- $arr []= new TestMessage_Sub();
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testDoubleSetMessageFail()
- {
- $arr = new RepeatedField(GPBType::DOUBLE);
- $arr []= 0.0;
- $arr [0]= new TestMessage_Sub();
- }
-
#########################################################
# Test bool field.
#########################################################
@@ -603,16 +375,16 @@ class RepeatedFieldTest extends PHPUnit_Framework_TestCase
$arr = new RepeatedField(GPBType::BOOL);
// Test append.
- $arr []= true;
+ $arr[] = true;
$this->assertSame(true, $arr[0]);
- $arr []= -1;
+ $arr[] = -1;
$this->assertSame(true, $arr[1]);
- $arr []= 1.1;
+ $arr[] = 1.1;
$this->assertSame(true, $arr[2]);
- $arr []= '';
+ $arr[] = '';
$this->assertSame(false, $arr[3]);
$this->assertEquals(4, count($arr));
@@ -623,38 +395,19 @@ class RepeatedFieldTest extends PHPUnit_Framework_TestCase
}
// Test set.
- $arr [0]= true;
+ $arr[0] = true;
$this->assertSame(true, $arr[0]);
- $arr [1]= -1;
+ $arr[1] = -1;
$this->assertSame(true, $arr[1]);
- $arr [2]= 1.1;
+ $arr[2] = 1.1;
$this->assertSame(true, $arr[2]);
- $arr [3]= '';
+ $arr[3] = '';
$this->assertSame(false, $arr[3]);
}
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testBoolAppendMessageFail()
- {
- $arr = new RepeatedField(GPBType::BOOL);
- $arr []= new TestMessage_Sub();
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testBoolSetMessageFail()
- {
- $arr = new RepeatedField(GPBType::BOOL);
- $arr []= true;
- $arr [0]= new TestMessage_Sub();
- }
-
#########################################################
# Test string field.
#########################################################
@@ -664,16 +417,16 @@ class RepeatedFieldTest extends PHPUnit_Framework_TestCase
$arr = new RepeatedField(GPBType::STRING);
// Test append.
- $arr []= 'abc';
+ $arr[] = 'abc';
$this->assertSame('abc', $arr[0]);
- $arr []= 1;
+ $arr[] = 1;
$this->assertSame('1', $arr[1]);
- $arr []= 1.1;
+ $arr[] = 1.1;
$this->assertSame('1.1', $arr[2]);
- $arr []= true;
+ $arr[] = true;
$this->assertSame('1', $arr[3]);
$this->assertEquals(4, count($arr));
@@ -684,59 +437,19 @@ class RepeatedFieldTest extends PHPUnit_Framework_TestCase
}
// Test set.
- $arr [0]= 'abc';
+ $arr[0] = 'abc';
$this->assertSame('abc', $arr[0]);
- $arr [1]= 1;
+ $arr[1] = 1;
$this->assertSame('1', $arr[1]);
- $arr [2]= 1.1;
+ $arr[2] = 1.1;
$this->assertSame('1.1', $arr[2]);
- $arr [3]= true;
+ $arr[3] = true;
$this->assertSame('1', $arr[3]);
}
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testStringAppendMessageFail()
- {
- $arr = new RepeatedField(GPBType::STRING);
- $arr []= new TestMessage_Sub();
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testStringSetMessageFail()
- {
- $arr = new RepeatedField(GPBType::STRING);
- $arr []= 'abc';
- $arr [0]= new TestMessage_Sub();
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testStringAppendInvalidUTF8Fail()
- {
- $arr = new RepeatedField(GPBType::STRING);
- $hex = hex2bin("ff");
- $arr []= $hex;
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testStringSetInvalidUTF8Fail()
- {
- $arr = new RepeatedField(GPBType::STRING);
- $arr []= 'abc';
- $hex = hex2bin("ff");
- $arr [0]= $hex;
- }
-
#########################################################
# Test message field.
#########################################################
@@ -748,73 +461,28 @@ class RepeatedFieldTest extends PHPUnit_Framework_TestCase
// Test append.
$sub_m = new TestMessage_Sub();
$sub_m->setA(1);
- $arr []= $sub_m;
+ $arr[] = $sub_m;
$this->assertSame(1, $arr[0]->getA());
- $null = null;
- $arr []= $null;
- $this->assertNull($arr[1]);
-
- $this->assertEquals(2, count($arr));
-
- for ($i = 0; $i < count($arr); $i++) {
- $arr[$i] = $null;
- $this->assertNull($arr[$i]);
- }
+ $this->assertEquals(1, count($arr));
// Test set.
- $arr [0]= $sub_m;
- $this->assertSame(1, $arr[0]->getA());
-
- $arr [1]= $null;
- $this->assertNull($arr[1]);
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testMessageAppendIntFail()
- {
- $arr = new RepeatedField(GPBType::MESSAGE, TestMessage_Sub::class);
- $arr []= 1;
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testMessageSetIntFail()
- {
- $arr = new RepeatedField(GPBType::MESSAGE, TestMessage_Sub::class);
- $arr []= new TestMessage_Sub;
- $arr [0]= 'abc';
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testMessageAppendStringFail()
- {
- $arr = new RepeatedField(GPBType::MESSAGE, TestMessage_Sub::class);
- $arr []= 'abc';
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testMessageSetStringFail()
- {
- $arr = new RepeatedField(GPBType::MESSAGE, TestMessage_Sub::class);
- $arr []= new TestMessage_Sub;
- $arr [0]= 'abc';
- }
+ $sub_m = new TestMessage_Sub();
+ $sub_m->setA(2);
+ $arr[0] = $sub_m;
+ $this->assertSame(2, $arr[0]->getA());
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testMessageAppendOtherMessageFail()
- {
+ // Test foreach.
$arr = new RepeatedField(GPBType::MESSAGE, TestMessage_Sub::class);
- $arr []= new TestMessage;
+ for ($i = 0; $i < 3; $i++) {
+ $arr[] = new TestMessage_Sub();
+ $arr[$i]->setA($i);
+ }
+ $i = 0;
+ foreach ($arr as $val) {
+ $this->assertSame($i++, $val->getA());
+ }
+ $this->assertSame(3, $i);
}
#########################################################
@@ -824,18 +492,18 @@ class RepeatedFieldTest extends PHPUnit_Framework_TestCase
public function testOffset()
{
$arr = new RepeatedField(GPBType::INT32);
- $arr []= 0;
+ $arr[] = 0;
- $arr [0]= 1;
+ $arr[0] = 1;
$this->assertSame(1, $arr[0]);
$this->assertSame(1, count($arr));
- $arr ['0']= 2;
+ $arr['0'] = 2;
$this->assertSame(2, $arr['0']);
$this->assertSame(2, $arr[0]);
$this->assertSame(1, count($arr));
- $arr [0.0]= 3;
+ $arr[0.0] = 3;
$this->assertSame(3, $arr[0.0]);
$this->assertSame(1, count($arr));
}
@@ -844,9 +512,9 @@ class RepeatedFieldTest extends PHPUnit_Framework_TestCase
{
$arr = new RepeatedField(GPBType::INT32);
- $arr []= 0;
- $arr []= 1;
- $arr []= 2;
+ $arr[] = 0;
+ $arr[] = 1;
+ $arr[] = 2;
$this->assertSame(3, count($arr));
unset($arr[2]);
@@ -854,75 +522,22 @@ class RepeatedFieldTest extends PHPUnit_Framework_TestCase
$this->assertSame(0, $arr[0]);
$this->assertSame(1, $arr[1]);
- $arr [] = 3;
+ $arr[] = 3;
$this->assertSame(3, count($arr));
$this->assertSame(0, $arr[0]);
$this->assertSame(1, $arr[1]);
$this->assertSame(3, $arr[2]);
}
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testRemoveMiddleFail()
- {
- $arr = new RepeatedField(GPBType::INT32);
-
- $arr []= 0;
- $arr []= 1;
- $arr []= 2;
- $this->assertSame(3, count($arr));
-
- unset($arr[1]);
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testRemoveEmptyFail()
- {
- $arr = new RepeatedField(GPBType::INT32);
-
- unset($arr[0]);
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testMessageOffsetFail()
- {
- $arr = new RepeatedField(GPBType::INT32);
- $arr []= 0;
- $arr [new TestMessage_Sub()]= 0;
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testStringOffsetFail()
- {
- $arr = new RepeatedField(GPBType::INT32);
- $arr []= 0;
- $arr ['abc']= 0;
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testSetNonExistedOffsetFail()
- {
- $arr = new RepeatedField(GPBType::INT32);
- $arr [0]= 0;
- }
-
#########################################################
# Test memory leak
#########################################################
public function testCycleLeak()
{
+ gc_collect_cycles();
$arr = new RepeatedField(GPBType::MESSAGE, TestMessage::class);
- $arr []= new TestMessage;
+ $arr[] = new TestMessage;
$arr[0]->SetRepeatedRecursive($arr);
// Clean up memory before test.
diff --git a/php/tests/autoload.php b/php/tests/autoload.php
index 0a917fc5..b98b13ab 100755
--- a/php/tests/autoload.php
+++ b/php/tests/autoload.php
@@ -1,5 +1,7 @@
<?php
+error_reporting(E_ALL);
+
function getGeneratedFiles($dir, &$results = array())
{
$files = scandir($dir);
diff --git a/php/tests/bootstrap_phpunit.php b/php/tests/bootstrap_phpunit.php
new file mode 100644
index 00000000..8452f158
--- /dev/null
+++ b/php/tests/bootstrap_phpunit.php
@@ -0,0 +1,5 @@
+<?php
+
+require_once("vendor/autoload.php");
+
+error_reporting(E_ALL);
diff --git a/php/tests/compatibility_test.sh b/php/tests/compatibility_test.sh
new file mode 100755
index 00000000..7caa46e7
--- /dev/null
+++ b/php/tests/compatibility_test.sh
@@ -0,0 +1,140 @@
+#!/bin/bash
+
+function use_php() {
+ VERSION=$1
+ PHP=`which php`
+ PHP_CONFIG=`which php-config`
+ PHPIZE=`which phpize`
+ ln -sfn "/usr/local/php-${VERSION}/bin/php" $PHP
+ ln -sfn "/usr/local/php-${VERSION}/bin/php-config" $PHP_CONFIG
+ ln -sfn "/usr/local/php-${VERSION}/bin/phpize" $PHPIZE
+}
+
+function generate_proto() {
+ PROTOC1=$1
+ PROTOC2=$2
+
+ rm -rf generated
+ mkdir generated
+
+ $PROTOC1 --php_out=generated proto/test_include.proto
+ $PROTOC2 --php_out=generated proto/test.proto proto/test_no_namespace.proto proto/test_prefix.proto
+ pushd ../../src
+ $PROTOC2 --php_out=../php/tests/generated -I../php/tests -I. ../php/tests/proto/test_import_descriptor_proto.proto
+ popd
+}
+
+# Remove tests to expect error. These were added to API tests by mistake.
+function remove_error_test() {
+ local TEMPFILE=`tempfile`
+ cat $1 | \
+ awk -v file=`basename $1` -v dir=`basename $(dirname $1)` '
+ BEGIN {
+ show = 1
+ }
+ /@expectedException PHPUnit_Framework_Error/ { show = 0; next; }
+ / *\*\// { print; next; }
+ / *}/ {
+ if (!show) {
+ show = 1;
+ next;
+ }
+ }
+ show { print }
+ ' > $TEMPFILE
+ cp $TEMPFILE $1
+}
+
+set -ex
+
+# Change to the script's directory.
+cd $(dirname $0)
+
+# The old version of protobuf that we are testing compatibility against.
+case "$1" in
+ ""|3.3.0)
+ OLD_VERSION=3.3.0
+ OLD_VERSION_PROTOC=http://repo1.maven.org/maven2/com/google/protobuf/protoc/3.3.0/protoc-3.3.0-linux-x86_64.exe
+ ;;
+ *)
+ echo "[ERROR]: Unknown version number: $1"
+ exit 1
+ ;;
+esac
+
+# Extract the latest protobuf version number.
+VERSION_NUMBER=`grep "PHP_PROTOBUF_VERSION" ../ext/google/protobuf/protobuf.h | sed "s|#define PHP_PROTOBUF_VERSION \"\(.*\)\"|\1|"`
+
+echo "Running compatibility tests between $VERSION_NUMBER and $OLD_VERSION"
+
+# Check protoc
+[ -f ../../src/protoc ] || {
+ echo "[ERROR]: Please build protoc first."
+ exit 1
+}
+
+# Download old test.
+rm -rf protobuf
+git clone https://github.com/google/protobuf.git
+pushd protobuf
+git checkout v$OLD_VERSION
+popd
+
+# Build and copy the new runtime
+use_php 5.5
+pushd ../ext/google/protobuf
+make clean || true
+phpize && ./configure && make
+popd
+
+rm -rf protobuf/php/ext
+rm -rf protobuf/php/src
+cp -r ../ext protobuf/php/ext/
+cp -r ../src protobuf/php/src/
+
+# Download old version protoc compiler (for linux)
+wget $OLD_VERSION_PROTOC -O old_protoc
+chmod +x old_protoc
+
+NEW_PROTOC=`pwd`/../../src/protoc
+OLD_PROTOC=`pwd`/old_protoc
+cd protobuf/php
+cp -r /usr/local/vendor-5.5 vendor
+wget https://phar.phpunit.de/phpunit-4.8.0.phar -O /usr/bin/phpunit
+
+# Remove implementation detail tests.
+tests=( array_test.php encode_decode_test.php generated_class_test.php map_field_test.php well_known_test.php )
+sed -i.bak '/php_implementation_test.php/d' phpunit.xml
+for t in "${tests[@]}"
+do
+ remove_error_test tests/$t
+done
+
+cd tests
+
+# Test A.1:
+# proto set 1: use old version
+# proto set 2 which may import protos in set 1: use old version
+generate_proto $OLD_PROTOC $OLD_PROTOC
+./test.sh
+pushd ..
+phpunit
+popd
+
+# Test A.2:
+# proto set 1: use new version
+# proto set 2 which may import protos in set 1: use old version
+generate_proto $NEW_PROTOC $OLD_PROTOC
+./test.sh
+pushd ..
+phpunit
+popd
+
+# Test A.3:
+# proto set 1: use old version
+# proto set 2 which may import protos in set 1: use new version
+generate_proto $OLD_PROTOC $NEW_PROTOC
+./test.sh
+pushd ..
+phpunit
+popd
diff --git a/php/tests/descriptors_test.php b/php/tests/descriptors_test.php
new file mode 100644
index 00000000..17e8a4f2
--- /dev/null
+++ b/php/tests/descriptors_test.php
@@ -0,0 +1,246 @@
+<?php
+
+require_once('generated/Descriptors/TestDescriptorsEnum.php');
+require_once('generated/Descriptors/TestDescriptorsMessage.php');
+require_once('test_base.php');
+require_once('test_util.php');
+
+use Google\Protobuf\DescriptorPool;
+use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\MapField;
+use Descriptors\TestDescriptorsEnum;
+use Descriptors\TestDescriptorsMessage;
+use Descriptors\TestDescriptorsMessage_Sub;
+
+class DescriptorsTest extends TestBase
+{
+
+ // Redefine these here for compatibility with c extension
+ const GPBLABEL_OPTIONAL = 1;
+ const GPBLABEL_REQUIRED = 2;
+ const GPBLABEL_REPEATED = 3;
+
+ const GPBTYPE_DOUBLE = 1;
+ const GPBTYPE_FLOAT = 2;
+ const GPBTYPE_INT64 = 3;
+ const GPBTYPE_UINT64 = 4;
+ const GPBTYPE_INT32 = 5;
+ const GPBTYPE_FIXED64 = 6;
+ const GPBTYPE_FIXED32 = 7;
+ const GPBTYPE_BOOL = 8;
+ const GPBTYPE_STRING = 9;
+ const GPBTYPE_GROUP = 10;
+ const GPBTYPE_MESSAGE = 11;
+ const GPBTYPE_BYTES = 12;
+ const GPBTYPE_UINT32 = 13;
+ const GPBTYPE_ENUM = 14;
+ const GPBTYPE_SFIXED32 = 15;
+ const GPBTYPE_SFIXED64 = 16;
+ const GPBTYPE_SINT32 = 17;
+ const GPBTYPE_SINT64 = 18;
+
+ #########################################################
+ # Test descriptor pool.
+ #########################################################
+
+ public function testDescriptorPool()
+ {
+ $pool = DescriptorPool::getGeneratedPool();
+
+ $desc = $pool->getDescriptorByClassName(get_class(new TestDescriptorsMessage()));
+ $this->assertInstanceOf('\Google\Protobuf\Descriptor', $desc);
+
+ $enumDesc = $pool->getEnumDescriptorByClassName(get_class(new TestDescriptorsEnum()));
+ $this->assertInstanceOf('\Google\Protobuf\EnumDescriptor', $enumDesc);
+ }
+
+ public function testDescriptorPoolIncorrectArgs()
+ {
+ $pool = DescriptorPool::getGeneratedPool();
+
+ $desc = $pool->getDescriptorByClassName('NotAClass');
+ $this->assertNull($desc);
+
+ $desc = $pool->getDescriptorByClassName(get_class(new TestDescriptorsEnum()));
+ $this->assertNull($desc);
+
+ $enumDesc = $pool->getEnumDescriptorByClassName(get_class(new TestDescriptorsMessage()));
+ $this->assertNull($enumDesc);
+ }
+
+ #########################################################
+ # Test descriptor.
+ #########################################################
+
+ public function testDescriptor()
+ {
+ $pool = DescriptorPool::getGeneratedPool();
+ $class = get_class(new TestDescriptorsMessage());
+ $this->assertSame('Descriptors\TestDescriptorsMessage', $class);
+ $desc = $pool->getDescriptorByClassName($class);
+
+ $this->assertSame('descriptors.TestDescriptorsMessage', $desc->getFullName());
+ $this->assertSame($class, $desc->getClass());
+
+ $this->assertInstanceOf('\Google\Protobuf\FieldDescriptor', $desc->getField(0));
+ $this->assertSame(7, $desc->getFieldCount());
+
+ $this->assertInstanceOf('\Google\Protobuf\OneofDescriptor', $desc->getOneofDecl(0));
+ $this->assertSame(1, $desc->getOneofDeclCount());
+ }
+
+ #########################################################
+ # Test enum descriptor.
+ #########################################################
+
+ public function testEnumDescriptor()
+ {
+ // WARNINIG - we need to do this so that TestDescriptorsEnum is registered!!?
+ new TestDescriptorsMessage();
+
+ $pool = DescriptorPool::getGeneratedPool();
+
+ $enumDesc = $pool->getEnumDescriptorByClassName(get_class(new TestDescriptorsEnum()));
+
+ // Build map of enum values
+ $enumDescMap = [];
+ for ($i = 0; $i < $enumDesc->getValueCount(); $i++) {
+ $enumValueDesc = $enumDesc->getValue($i);
+ $this->assertInstanceOf('\Google\Protobuf\EnumValueDescriptor', $enumValueDesc);
+ $enumDescMap[$enumValueDesc->getNumber()] = $enumValueDesc->getName();
+ }
+
+ $this->assertSame('ZERO', $enumDescMap[0]);
+ $this->assertSame('ONE', $enumDescMap[1]);
+
+ $this->assertSame(2, $enumDesc->getValueCount());
+ }
+
+ #########################################################
+ # Test field descriptor.
+ #########################################################
+
+ public function testFieldDescriptor()
+ {
+ $pool = DescriptorPool::getGeneratedPool();
+ $desc = $pool->getDescriptorByClassName(get_class(new TestDescriptorsMessage()));
+
+ $fieldDescMap = $this->buildFieldMap($desc);
+
+ // Optional int field
+ $fieldDesc = $fieldDescMap[1];
+ $this->assertSame('optional_int32', $fieldDesc->getName());
+ $this->assertSame(1, $fieldDesc->getNumber());
+ $this->assertSame(self::GPBLABEL_OPTIONAL, $fieldDesc->getLabel());
+ $this->assertSame(self::GPBTYPE_INT32, $fieldDesc->getType());
+ $this->assertFalse($fieldDesc->isMap());
+
+ // Optional enum field
+ $fieldDesc = $fieldDescMap[16];
+ $this->assertSame('optional_enum', $fieldDesc->getName());
+ $this->assertSame(16, $fieldDesc->getNumber());
+ $this->assertSame(self::GPBLABEL_OPTIONAL, $fieldDesc->getLabel());
+ $this->assertSame(self::GPBTYPE_ENUM, $fieldDesc->getType());
+ $this->assertInstanceOf('\Google\Protobuf\EnumDescriptor', $fieldDesc->getEnumType());
+ $this->assertFalse($fieldDesc->isMap());
+
+ // Optional message field
+ $fieldDesc = $fieldDescMap[17];
+ $this->assertSame('optional_message', $fieldDesc->getName());
+ $this->assertSame(17, $fieldDesc->getNumber());
+ $this->assertSame(self::GPBLABEL_OPTIONAL, $fieldDesc->getLabel());
+ $this->assertSame(self::GPBTYPE_MESSAGE, $fieldDesc->getType());
+ $this->assertInstanceOf('\Google\Protobuf\Descriptor', $fieldDesc->getMessageType());
+ $this->assertFalse($fieldDesc->isMap());
+
+ // Repeated int field
+ $fieldDesc = $fieldDescMap[31];
+ $this->assertSame('repeated_int32', $fieldDesc->getName());
+ $this->assertSame(31, $fieldDesc->getNumber());
+ $this->assertSame(self::GPBLABEL_REPEATED, $fieldDesc->getLabel());
+ $this->assertSame(self::GPBTYPE_INT32, $fieldDesc->getType());
+ $this->assertFalse($fieldDesc->isMap());
+
+ // Repeated message field
+ $fieldDesc = $fieldDescMap[47];
+ $this->assertSame('repeated_message', $fieldDesc->getName());
+ $this->assertSame(47, $fieldDesc->getNumber());
+ $this->assertSame(self::GPBLABEL_REPEATED, $fieldDesc->getLabel());
+ $this->assertSame(self::GPBTYPE_MESSAGE, $fieldDesc->getType());
+ $this->assertInstanceOf('\Google\Protobuf\Descriptor', $fieldDesc->getMessageType());
+ $this->assertFalse($fieldDesc->isMap());
+
+ // Oneof int field
+ // Tested further in testOneofDescriptor()
+ $fieldDesc = $fieldDescMap[51];
+ $this->assertSame('oneof_int32', $fieldDesc->getName());
+ $this->assertSame(51, $fieldDesc->getNumber());
+ $this->assertSame(self::GPBLABEL_OPTIONAL, $fieldDesc->getLabel());
+ $this->assertSame(self::GPBTYPE_INT32, $fieldDesc->getType());
+ $this->assertFalse($fieldDesc->isMap());
+
+ // Map int-enum field
+ $fieldDesc = $fieldDescMap[71];
+ $this->assertSame('map_int32_enum', $fieldDesc->getName());
+ $this->assertSame(71, $fieldDesc->getNumber());
+ $this->assertSame(self::GPBLABEL_REPEATED, $fieldDesc->getLabel());
+ $this->assertSame(self::GPBTYPE_MESSAGE, $fieldDesc->getType());
+ $this->assertTrue($fieldDesc->isMap());
+ $mapDesc = $fieldDesc->getMessageType();
+ $this->assertSame('descriptors.TestDescriptorsMessage.MapInt32EnumEntry', $mapDesc->getFullName());
+ $this->assertSame(self::GPBTYPE_INT32, $mapDesc->getField(0)->getType());
+ $this->assertSame(self::GPBTYPE_ENUM, $mapDesc->getField(1)->getType());
+ }
+
+ /**
+ * @expectedException \Exception
+ */
+ public function testFieldDescriptorEnumException()
+ {
+ $pool = DescriptorPool::getGeneratedPool();
+ $desc = $pool->getDescriptorByClassName(get_class(new TestDescriptorsMessage()));
+ $fieldDesc = $desc->getField(0);
+ $fieldDesc->getEnumType();
+ }
+
+ /**
+ * @expectedException \Exception
+ */
+ public function testFieldDescriptorMessageException()
+ {
+ $pool = DescriptorPool::getGeneratedPool();
+ $desc = $pool->getDescriptorByClassName(get_class(new TestDescriptorsMessage()));
+ $fieldDesc = $desc->getField(0);
+ $fieldDesc->getMessageType();
+ }
+
+ #########################################################
+ # Test oneof descriptor.
+ #########################################################
+
+ public function testOneofDescriptor()
+ {
+ $pool = DescriptorPool::getGeneratedPool();
+ $desc = $pool->getDescriptorByClassName(get_class(new TestDescriptorsMessage()));
+
+ $fieldDescMap = $this->buildFieldMap($desc);
+ $fieldDesc = $fieldDescMap[51];
+
+ $oneofDesc = $desc->getOneofDecl(0);
+
+ $this->assertSame('my_oneof', $oneofDesc->getName());
+ $fieldDescFromOneof = $oneofDesc->getField(0);
+ $this->assertSame($fieldDesc, $fieldDescFromOneof);
+ $this->assertSame(1, $oneofDesc->getFieldCount());
+ }
+
+ private function buildFieldMap($desc)
+ {
+ $fieldDescMap = [];
+ for ($i = 0; $i < $desc->getFieldCount(); $i++) {
+ $fieldDesc = $desc->getField($i);
+ $fieldDescMap[$fieldDesc->getNumber()] = $fieldDesc;
+ }
+ return $fieldDescMap;
+ }
+}
diff --git a/php/tests/encode_decode_test.php b/php/tests/encode_decode_test.php
index af9c0415..4dca922b 100644
--- a/php/tests/encode_decode_test.php
+++ b/php/tests/encode_decode_test.php
@@ -9,6 +9,7 @@ use Foo\TestEnum;
use Foo\TestMessage;
use Foo\TestMessage_Sub;
use Foo\TestPackedMessage;
+use Foo\TestRandomFieldOrder;
use Foo\TestUnpackedMessage;
class EncodeDecodeTest extends TestBase
@@ -21,14 +22,15 @@ class EncodeDecodeTest extends TestBase
$this->setFields($from);
$this->expectFields($from);
- $data = $from->encode();
- $this->assertSame(TestUtil::getGoldenTestMessage(), $data);
+ $data = $from->serializeToString();
+ $this->assertSame(bin2hex(TestUtil::getGoldenTestMessage()),
+ bin2hex($data));
}
public function testDecode()
{
$to = new TestMessage();
- $to->decode(TestUtil::getGoldenTestMessage());
+ $to->mergeFromString(TestUtil::getGoldenTestMessage());
$this->expectFields($to);
}
@@ -39,10 +41,10 @@ class EncodeDecodeTest extends TestBase
$this->setFields($from);
$this->expectFields($from);
- $data = $from->encode();
+ $data = $from->serializeToString();
$to = new TestMessage();
- $to->decode($data);
+ $to->mergeFromString($data);
$this->expectFields($to);
}
@@ -51,10 +53,10 @@ class EncodeDecodeTest extends TestBase
$from = new TestMessage();
$this->expectEmptyFields($from);
- $data = $from->encode();
+ $data = $from->serializeToString();
$to = new TestMessage();
- $to->decode($data);
+ $to->mergeFromString($data);
$this->expectEmptyFields($to);
}
@@ -63,30 +65,54 @@ class EncodeDecodeTest extends TestBase
$m = new TestMessage();
$m->setOneofInt32(1);
- $data = $m->encode();
+ $data = $m->serializeToString();
$n = new TestMessage();
- $n->decode($data);
+ $n->mergeFromString($data);
$this->assertSame(1, $n->getOneofInt32());
$m->setOneofFloat(2.0);
- $data = $m->encode();
+ $data = $m->serializeToString();
$n = new TestMessage();
- $n->decode($data);
+ $n->mergeFromString($data);
$this->assertSame(2.0, $n->getOneofFloat());
$m->setOneofString('abc');
- $data = $m->encode();
+ $data = $m->serializeToString();
$n = new TestMessage();
- $n->decode($data);
+ $n->mergeFromString($data);
$this->assertSame('abc', $n->getOneofString());
$sub_m = new TestMessage_Sub();
$sub_m->setA(1);
$m->setOneofMessage($sub_m);
- $data = $m->encode();
+ $data = $m->serializeToString();
$n = new TestMessage();
- $n->decode($data);
+ $n->mergeFromString($data);
$this->assertSame(1, $n->getOneofMessage()->getA());
+
+ // Encode default value
+ $m->setOneofEnum(TestEnum::ZERO);
+ $data = $m->serializeToString();
+ $n = new TestMessage();
+ $n->mergeFromString($data);
+ $this->assertSame("oneof_enum", $n->getMyOneof());
+ $this->assertSame(TestEnum::ZERO, $n->getOneofEnum());
+
+ $m->setOneofString("");
+ $data = $m->serializeToString();
+ $n = new TestMessage();
+ $n->mergeFromString($data);
+ $this->assertSame("oneof_string", $n->getMyOneof());
+ $this->assertSame("", $n->getOneofString());
+
+ $sub_m = new TestMessage_Sub();
+ $m->setOneofMessage($sub_m);
+ $data = $m->serializeToString();
+ $n = new TestMessage();
+ $n->mergeFromString($data);
+ $this->assertSame("oneof_message", $n->getMyOneof());
+ $this->assertFalse(is_null($n->getOneofMessage()));
+
}
public function testPackedEncode()
@@ -94,20 +120,20 @@ class EncodeDecodeTest extends TestBase
$from = new TestPackedMessage();
TestUtil::setTestPackedMessage($from);
$this->assertSame(TestUtil::getGoldenTestPackedMessage(),
- $from->encode());
+ $from->serializeToString());
}
public function testPackedDecodePacked()
{
$to = new TestPackedMessage();
- $to->decode(TestUtil::getGoldenTestPackedMessage());
+ $to->mergeFromString(TestUtil::getGoldenTestPackedMessage());
TestUtil::assertTestPackedMessage($to);
}
public function testPackedDecodeUnpacked()
{
$to = new TestPackedMessage();
- $to->decode(TestUtil::getGoldenTestUnpackedMessage());
+ $to->mergeFromString(TestUtil::getGoldenTestUnpackedMessage());
TestUtil::assertTestPackedMessage($to);
}
@@ -116,20 +142,339 @@ class EncodeDecodeTest extends TestBase
$from = new TestUnpackedMessage();
TestUtil::setTestPackedMessage($from);
$this->assertSame(TestUtil::getGoldenTestUnpackedMessage(),
- $from->encode());
+ $from->serializeToString());
}
public function testUnpackedDecodePacked()
{
$to = new TestUnpackedMessage();
- $to->decode(TestUtil::getGoldenTestPackedMessage());
+ $to->mergeFromString(TestUtil::getGoldenTestPackedMessage());
TestUtil::assertTestPackedMessage($to);
}
public function testUnpackedDecodeUnpacked()
{
$to = new TestUnpackedMessage();
- $to->decode(TestUtil::getGoldenTestUnpackedMessage());
+ $to->mergeFromString(TestUtil::getGoldenTestUnpackedMessage());
TestUtil::assertTestPackedMessage($to);
}
+
+ public function testDecodeInt64()
+ {
+ // Read 64 testing
+ $testVals = array(
+ '10' => '100a',
+ '100' => '1064',
+ '800' => '10a006',
+ '6400' => '108032',
+ '70400' => '1080a604',
+ '774400' => '1080a22f',
+ '9292800' => '108098b704',
+ '74342400' => '1080c0b923',
+ '743424000' => '108080bfe202',
+ '8177664000' => '108080b5bb1e',
+ '65421312000' => '108080a8dbf301',
+ '785055744000' => '108080e0c7ec16',
+ '9420668928000' => '10808080dd969202',
+ '103627358208000' => '10808080fff9c717',
+ '1139900940288000' => '10808080f5bd978302',
+ '13678811283456000' => '10808080fce699a618',
+ '109430490267648000' => '10808080e0b7ceb1c201',
+ '984874412408832000' => '10808080e0f5c1bed50d',
+ );
+
+ $msg = new TestMessage();
+ foreach ($testVals as $original => $encoded) {
+ $msg->setOptionalInt64($original);
+ $data = $msg->serializeToString();
+ $this->assertSame($encoded, bin2hex($data));
+ $msg->setOptionalInt64(0);
+ $msg->mergeFromString($data);
+ $this->assertEquals($original, $msg->getOptionalInt64());
+ }
+ }
+
+ public function testDecodeToExistingMessage()
+ {
+ $m1 = new TestMessage();
+ $this->setFields($m1);
+ $this->expectFields($m1);
+
+ $m2 = new TestMessage();
+ $this->setFields2($m2);
+ $data = $m2->serializeToString();
+
+ $m1->mergeFromString($data);
+ $this->expectFieldsMerged($m1);
+ }
+
+ public function testDecodeFieldNonExist()
+ {
+ $data = hex2bin('c80501');
+ $m = new TestMessage();
+ $m->mergeFromString($data);
+ }
+
+ public function testEncodeNegativeInt32()
+ {
+ $m = new TestMessage();
+ $m->setOptionalInt32(-1);
+ $data = $m->serializeToString();
+ $this->assertSame("08ffffffffffffffffff01", bin2hex($data));
+ }
+
+ public function testDecodeNegativeInt32()
+ {
+ $m = new TestMessage();
+ $this->assertEquals(0, $m->getOptionalInt32());
+ $m->mergeFromString(hex2bin("08ffffffffffffffffff01"));
+ $this->assertEquals(-1, $m->getOptionalInt32());
+
+ $m = new TestMessage();
+ $this->assertEquals(0, $m->getOptionalInt32());
+ $m->mergeFromString(hex2bin("08ffffffff0f"));
+ $this->assertEquals(-1, $m->getOptionalInt32());
+ }
+
+ public function testRandomFieldOrder()
+ {
+ $m = new TestRandomFieldOrder();
+ $data = $m->serializeToString();
+ $this->assertSame("", $data);
+ }
+
+ /**
+ * @expectedException Exception
+ */
+ public function testDecodeInvalidInt32()
+ {
+ $m = new TestMessage();
+ $m->mergeFromString(hex2bin('08'));
+ }
+
+ /**
+ * @expectedException Exception
+ */
+ public function testDecodeInvalidSubMessage()
+ {
+ $m = new TestMessage();
+ $m->mergeFromString(hex2bin('9A010108'));
+ }
+
+ /**
+ * @expectedException Exception
+ */
+ public function testDecodeInvalidInt64()
+ {
+ $m = new TestMessage();
+ $m->mergeFromString(hex2bin('10'));
+ }
+
+ /**
+ * @expectedException Exception
+ */
+ public function testDecodeInvalidUInt32()
+ {
+ $m = new TestMessage();
+ $m->mergeFromString(hex2bin('18'));
+ }
+
+ /**
+ * @expectedException Exception
+ */
+ public function testDecodeInvalidUInt64()
+ {
+ $m = new TestMessage();
+ $m->mergeFromString(hex2bin('20'));
+ }
+
+ /**
+ * @expectedException Exception
+ */
+ public function testDecodeInvalidSInt32()
+ {
+ $m = new TestMessage();
+ $m->mergeFromString(hex2bin('28'));
+ }
+
+ /**
+ * @expectedException Exception
+ */
+ public function testDecodeInvalidSInt64()
+ {
+ $m = new TestMessage();
+ $m->mergeFromString(hex2bin('30'));
+ }
+
+ /**
+ * @expectedException Exception
+ */
+ public function testDecodeInvalidFixed32()
+ {
+ $m = new TestMessage();
+ $m->mergeFromString(hex2bin('3D'));
+ }
+
+ /**
+ * @expectedException Exception
+ */
+ public function testDecodeInvalidFixed64()
+ {
+ $m = new TestMessage();
+ $m->mergeFromString(hex2bin('41'));
+ }
+
+ /**
+ * @expectedException Exception
+ */
+ public function testDecodeInvalidSFixed32()
+ {
+ $m = new TestMessage();
+ $m->mergeFromString(hex2bin('4D'));
+ }
+
+ /**
+ * @expectedException Exception
+ */
+ public function testDecodeInvalidSFixed64()
+ {
+ $m = new TestMessage();
+ $m->mergeFromString(hex2bin('51'));
+ }
+
+ /**
+ * @expectedException Exception
+ */
+ public function testDecodeInvalidFloat()
+ {
+ $m = new TestMessage();
+ $m->mergeFromString(hex2bin('5D'));
+ }
+
+ /**
+ * @expectedException Exception
+ */
+ public function testDecodeInvalidDouble()
+ {
+ $m = new TestMessage();
+ $m->mergeFromString(hex2bin('61'));
+ }
+
+ /**
+ * @expectedException Exception
+ */
+ public function testDecodeInvalidBool()
+ {
+ $m = new TestMessage();
+ $m->mergeFromString(hex2bin('68'));
+ }
+
+ /**
+ * @expectedException Exception
+ */
+ public function testDecodeInvalidStringLengthMiss()
+ {
+ $m = new TestMessage();
+ $m->mergeFromString(hex2bin('72'));
+ }
+
+ /**
+ * @expectedException Exception
+ */
+ public function testDecodeInvalidStringDataMiss()
+ {
+ $m = new TestMessage();
+ $m->mergeFromString(hex2bin('7201'));
+ }
+
+ /**
+ * @expectedException Exception
+ */
+ public function testDecodeInvalidBytesLengthMiss()
+ {
+ $m = new TestMessage();
+ $m->mergeFromString(hex2bin('7A'));
+ }
+
+ /**
+ * @expectedException Exception
+ */
+ public function testDecodeInvalidBytesDataMiss()
+ {
+ $m = new TestMessage();
+ $m->mergeFromString(hex2bin('7A01'));
+ }
+
+ /**
+ * @expectedException Exception
+ */
+ public function testDecodeInvalidEnum()
+ {
+ $m = new TestMessage();
+ $m->mergeFromString(hex2bin('8001'));
+ }
+
+ /**
+ * @expectedException Exception
+ */
+ public function testDecodeInvalidMessageLengthMiss()
+ {
+ $m = new TestMessage();
+ $m->mergeFromString(hex2bin('8A01'));
+ }
+
+ /**
+ * @expectedException Exception
+ */
+ public function testDecodeInvalidMessageDataMiss()
+ {
+ $m = new TestMessage();
+ $m->mergeFromString(hex2bin('8A0101'));
+ }
+
+ /**
+ * @expectedException Exception
+ */
+ public function testDecodeInvalidPackedMessageLength()
+ {
+ $m = new TestPackedMessage();
+ $m->mergeFromString(hex2bin('D205'));
+ }
+
+ public function testUnknown()
+ {
+ $m = new TestMessage();
+ $from = hex2bin('F80601');
+ $m->mergeFromString($from);
+ $to = $m->serializeToString();
+ $this->assertSame(bin2hex($from), bin2hex($to));
+
+ $m = new TestMessage();
+ $from = hex2bin('F9060000000000000000');
+ $m->mergeFromString($from);
+ $to = $m->serializeToString();
+ $this->assertSame(bin2hex($from), bin2hex($to));
+
+ $m = new TestMessage();
+ $from = hex2bin('FA0600');
+ $m->mergeFromString($from);
+ $to = $m->serializeToString();
+ $this->assertSame(bin2hex($from), bin2hex($to));
+
+ $m = new TestMessage();
+ $from = hex2bin('FD0600000000');
+ $m->mergeFromString($from);
+ $to = $m->serializeToString();
+ $this->assertSame(bin2hex($from), bin2hex($to));
+ }
+
+ public function testJsonEncode()
+ {
+ $from = new TestMessage();
+ $this->setFields($from);
+ $data = $from->serializeToJsonString();
+ $to = new TestMessage();
+ $to->mergeFromJsonString($data);
+ $this->expectFields($to);
+ }
}
diff --git a/php/tests/gdb_test.sh b/php/tests/gdb_test.sh
index 3c0d97a2..484e2edf 100755
--- a/php/tests/gdb_test.sh
+++ b/php/tests/gdb_test.sh
@@ -5,8 +5,6 @@
#
gdb --args php -dextension=../ext/google/protobuf/modules/protobuf.so `which phpunit` --bootstrap autoload.php encode_decode_test.php
#
-# # gdb --args php -dextension=../ext/google/protobuf/modules/protobuf.so
-# memory_leak_test.php
+# gdb --args php -dextension=../ext/google/protobuf/modules/protobuf.so memory_leak_test.php
#
-# # USE_ZEND_ALLOC=0 valgrind --leak-check=yes php
-# -dextension=../ext/google/protobuf/modules/protobuf.so memory_leak_test.php
+# USE_ZEND_ALLOC=0 valgrind --leak-check=yes php -dextension=../ext/google/protobuf/modules/protobuf.so memory_leak_test.php
diff --git a/php/tests/generated_class_test.php b/php/tests/generated_class_test.php
index 27912ecd..53d18ee7 100644
--- a/php/tests/generated_class_test.php
+++ b/php/tests/generated_class_test.php
@@ -1,15 +1,24 @@
<?php
-require_once('generated/NoNameSpace.php');
+require_once('generated/NoNamespaceEnum.php');
+require_once('generated/NoNamespaceMessage.php');
+require_once('test_base.php');
require_once('test_util.php');
use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\MapField;
use Google\Protobuf\Internal\GPBType;
use Foo\TestEnum;
+use Foo\TestIncludeNamespaceMessage;
+use Foo\TestIncludePrefixMessage;
use Foo\TestMessage;
use Foo\TestMessage_Sub;
+use Foo\TestReverseFieldOrder;
+use Foo\testLowerCaseMessage;
+use Foo\testLowerCaseEnum;
+use Php\Test\TestNamespace;
-class GeneratedClassTest extends PHPUnit_Framework_TestCase
+class GeneratedClassTest extends TestBase
{
#########################################################
@@ -56,24 +65,6 @@ class GeneratedClassTest extends PHPUnit_Framework_TestCase
$this->assertSame(MIN_INT32, $m->getOptionalInt32());
}
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testInt32FieldInvalidTypeFail()
- {
- $m = new TestMessage();
- $m->setOptionalInt32(new TestMessage());
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testInt32FieldInvalidStringFail()
- {
- $m = new TestMessage();
- $m->setOptionalInt32('abc');
- }
-
#########################################################
# Test uint32 field.
#########################################################
@@ -113,24 +104,6 @@ class GeneratedClassTest extends PHPUnit_Framework_TestCase
$this->assertSame(MIN_INT32, $m->getOptionalUint32());
}
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testUint32FieldInvalidTypeFail()
- {
- $m = new TestMessage();
- $m->setOptionalUint32(new TestMessage());
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testUint32FieldInvalidStringFail()
- {
- $m = new TestMessage();
- $m->setOptionalUint32('abc');
- }
-
#########################################################
# Test int64 field.
#########################################################
@@ -183,24 +156,6 @@ class GeneratedClassTest extends PHPUnit_Framework_TestCase
}
}
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testInt64FieldInvalidTypeFail()
- {
- $m = new TestMessage();
- $m->setOptionalInt64(new TestMessage());
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testInt64FieldInvalidStringFail()
- {
- $m = new TestMessage();
- $m->setOptionalInt64('abc');
- }
-
#########################################################
# Test uint64 field.
#########################################################
@@ -248,24 +203,6 @@ class GeneratedClassTest extends PHPUnit_Framework_TestCase
}
}
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testUint64FieldInvalidTypeFail()
- {
- $m = new TestMessage();
- $m->setOptionalUint64(new TestMessage());
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testUint64FieldInvalidStringFail()
- {
- $m = new TestMessage();
- $m->setOptionalUint64('abc');
- }
-
#########################################################
# Test enum field.
#########################################################
@@ -291,6 +228,12 @@ class GeneratedClassTest extends PHPUnit_Framework_TestCase
$this->assertEquals(TestEnum::ONE, $m->getOptionalEnum());
}
+ public function testNestedEnum()
+ {
+ $m = new TestMessage();
+ $m->setOptionalNestedEnum(\Foo\TestMessage_NestedEnum::ZERO);
+ }
+
#########################################################
# Test float field.
#########################################################
@@ -314,24 +257,6 @@ class GeneratedClassTest extends PHPUnit_Framework_TestCase
$this->assertEquals(3.1, $m->getOptionalFloat(), '', MAX_FLOAT_DIFF);
}
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testFloatFieldInvalidTypeFail()
- {
- $m = new TestMessage();
- $m->setOptionalFloat(new TestMessage());
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testFloatFieldInvalidStringFail()
- {
- $m = new TestMessage();
- $m->setOptionalFloat('abc');
- }
-
#########################################################
# Test double field.
#########################################################
@@ -355,24 +280,6 @@ class GeneratedClassTest extends PHPUnit_Framework_TestCase
$this->assertEquals(3.1, $m->getOptionalDouble(), '', MAX_FLOAT_DIFF);
}
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testDoubleFieldInvalidTypeFail()
- {
- $m = new TestMessage();
- $m->setOptionalDouble(new TestMessage());
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testDoubleFieldInvalidStringFail()
- {
- $m = new TestMessage();
- $m->setOptionalDouble('abc');
- }
-
#########################################################
# Test bool field.
#########################################################
@@ -398,15 +305,6 @@ class GeneratedClassTest extends PHPUnit_Framework_TestCase
$this->assertSame(false, $m->getOptionalBool());
}
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testBoolFieldInvalidStringFail()
- {
- $m = new TestMessage();
- $m->setOptionalBool(new TestMessage());
- }
-
#########################################################
# Test string field.
#########################################################
@@ -432,16 +330,6 @@ class GeneratedClassTest extends PHPUnit_Framework_TestCase
$this->assertSame('1', $m->getOptionalString());
}
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testStringFieldInvalidUTF8Fail()
- {
- $m = new TestMessage();
- $hex = hex2bin("ff");
- $m->setOptionalString($hex);
- }
-
#########################################################
# Test bytes field.
#########################################################
@@ -492,25 +380,6 @@ class GeneratedClassTest extends PHPUnit_Framework_TestCase
$this->assertNull($m->getOptionalMessage());
}
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testMessageFieldWrongTypeFail()
- {
- $m = new TestMessage();
- $a = 1;
- $m->setOptionalMessage($a);
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testMessageFieldWrongClassFail()
- {
- $m = new TestMessage();
- $m->setOptionalMessage(new TestMessage());
- }
-
#########################################################
# Test repeated field.
#########################################################
@@ -524,46 +393,55 @@ class GeneratedClassTest extends PHPUnit_Framework_TestCase
$this->assertSame($repeated_int32, $m->getRepeatedInt32());
}
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testRepeatedFieldWrongTypeFail()
+ public function testRepeatedFieldViaArray()
{
$m = new TestMessage();
- $a = 1;
- $m->setRepeatedInt32($a);
- }
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testRepeatedFieldWrongObjectFail()
- {
- $m = new TestMessage();
- $m->setRepeatedInt32($m);
+ $arr = array();
+ $m->setRepeatedInt32($arr);
+ $this->assertSame(0, count($m->getRepeatedInt32()));
+
+ $arr = array(1, 2.1, "3");
+ $m->setRepeatedInt32($arr);
+ $this->assertTrue($m->getRepeatedInt32() instanceof RepeatedField);
+ $this->assertSame("Google\Protobuf\Internal\RepeatedField",
+ get_class($m->getRepeatedInt32()));
+ $this->assertSame(3, count($m->getRepeatedInt32()));
+ $this->assertSame(1, $m->getRepeatedInt32()[0]);
+ $this->assertSame(2, $m->getRepeatedInt32()[1]);
+ $this->assertSame(3, $m->getRepeatedInt32()[2]);
+ $this->assertFalse($arr instanceof RepeatedField);
}
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testRepeatedFieldWrongRepeatedTypeFail()
+ #########################################################
+ # Test map field.
+ #########################################################
+
+ public function testMapField()
{
$m = new TestMessage();
- $repeated_int32 = new RepeatedField(GPBType::UINT32);
- $m->setRepeatedInt32($repeated_int32);
+ $map_int32_int32 = new MapField(GPBType::INT32, GPBType::INT32);
+ $m->setMapInt32Int32($map_int32_int32);
+ $this->assertSame($map_int32_int32, $m->getMapInt32Int32());
}
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testRepeatedFieldWrongRepeatedMessageClassFail()
+ public function testMapFieldViaArray()
{
$m = new TestMessage();
- $repeated_message = new RepeatedField(GPBType::MESSAGE,
- TestMessage::class);
- $m->setRepeatedMessage($repeated_message);
+ $dict = array();
+ $m->setMapInt32Int32($dict);
+ $this->assertSame(0, count($m->getMapInt32Int32()));
+
+ $dict = array(5 => 5, 6.1 => 6.1, "7" => "7");
+ $m->setMapInt32Int32($dict);
+ $this->assertTrue($m->getMapInt32Int32() instanceof MapField);
+ $this->assertSame(3, count($m->getMapInt32Int32()));
+ $this->assertSame(5, $m->getMapInt32Int32()[5]);
+ $this->assertSame(6, $m->getMapInt32Int32()[6]);
+ $this->assertSame(7, $m->getMapInt32Int32()[7]);
+ $this->assertFalse($dict instanceof MapField);
}
#########################################################
@@ -573,23 +451,28 @@ class GeneratedClassTest extends PHPUnit_Framework_TestCase
public function testOneofField() {
$m = new TestMessage();
+ $this->assertSame("", $m->getMyOneof());
+
$m->setOneofInt32(1);
$this->assertSame(1, $m->getOneofInt32());
$this->assertSame(0.0, $m->getOneofFloat());
$this->assertSame('', $m->getOneofString());
$this->assertSame(NULL, $m->getOneofMessage());
+ $this->assertSame("oneof_int32", $m->getMyOneof());
$m->setOneofFloat(2.0);
$this->assertSame(0, $m->getOneofInt32());
$this->assertSame(2.0, $m->getOneofFloat());
$this->assertSame('', $m->getOneofString());
$this->assertSame(NULL, $m->getOneofMessage());
+ $this->assertSame("oneof_float", $m->getMyOneof());
$m->setOneofString('abc');
$this->assertSame(0, $m->getOneofInt32());
$this->assertSame(0.0, $m->getOneofFloat());
$this->assertSame('abc', $m->getOneofString());
$this->assertSame(NULL, $m->getOneofMessage());
+ $this->assertSame("oneof_string", $m->getMyOneof());
$sub_m = new TestMessage_Sub();
$sub_m->setA(1);
@@ -598,13 +481,694 @@ class GeneratedClassTest extends PHPUnit_Framework_TestCase
$this->assertSame(0.0, $m->getOneofFloat());
$this->assertSame('', $m->getOneofString());
$this->assertSame(1, $m->getOneofMessage()->getA());
+ $this->assertSame("oneof_message", $m->getMyOneof());
}
#########################################################
- # Test oneof field.
+ # Test clear method.
+ #########################################################
+
+ public function testMessageClear()
+ {
+ $m = new TestMessage();
+ $this->setFields($m);
+ $this->expectFields($m);
+ $m->clear();
+ $this->expectEmptyFields($m);
+ }
+
+ #########################################################
+ # Test mergeFrom method.
+ #########################################################
+
+ public function testMessageMergeFrom()
+ {
+ $m = new TestMessage();
+ $this->setFields($m);
+ $this->expectFields($m);
+ $arr = $m->getOptionalMessage()->getB();
+ $arr[] = 1;
+
+ $n = new TestMessage();
+
+ // Singular
+ $n->setOptionalInt32(100);
+ $sub1 = new TestMessage_Sub();
+ $sub1->setA(101);
+
+ $b = $sub1->getB();
+ $b[] = 102;
+ $sub1->setB($b);
+
+ $n->setOptionalMessage($sub1);
+
+ // Repeated
+ $repeatedInt32 = $n->getRepeatedInt32();
+ $repeatedInt32[] = 200;
+ $n->setRepeatedInt32($repeatedInt32);
+
+ $repeatedString = $n->getRepeatedString();
+ $repeatedString[] = 'abc';
+ $n->setRepeatedString($repeatedString);
+
+ $sub2 = new TestMessage_Sub();
+ $sub2->setA(201);
+ $repeatedMessage = $n->getRepeatedMessage();
+ $repeatedMessage[] = $sub2;
+ $n->setRepeatedMessage($repeatedMessage);
+
+ // Map
+ $mapInt32Int32 = $n->getMapInt32Int32();
+ $mapInt32Int32[1] = 300;
+ $mapInt32Int32[-62] = 301;
+ $n->setMapInt32Int32($mapInt32Int32);
+
+ $mapStringString = $n->getMapStringString();
+ $mapStringString['def'] = 'def';
+ $n->setMapStringString($mapStringString);
+
+ $mapInt32Message = $n->getMapInt32Message();
+ $mapInt32Message[1] = new TestMessage_Sub();
+ $mapInt32Message[1]->setA(302);
+ $mapInt32Message[2] = new TestMessage_Sub();
+ $mapInt32Message[2]->setA(303);
+ $n->setMapInt32Message($mapInt32Message);
+
+ $m->mergeFrom($n);
+
+ $this->assertSame(100, $m->getOptionalInt32());
+ $this->assertSame(42, $m->getOptionalUint32());
+ $this->assertSame(101, $m->getOptionalMessage()->getA());
+ $this->assertSame(2, count($m->getOptionalMessage()->getB()));
+ $this->assertSame(1, $m->getOptionalMessage()->getB()[0]);
+ $this->assertSame(102, $m->getOptionalMessage()->getB()[1]);
+
+ $this->assertSame(3, count($m->getRepeatedInt32()));
+ $this->assertSame(200, $m->getRepeatedInt32()[2]);
+ $this->assertSame(2, count($m->getRepeatedUint32()));
+ $this->assertSame(3, count($m->getRepeatedString()));
+ $this->assertSame('abc', $m->getRepeatedString()[2]);
+ $this->assertSame(3, count($m->getRepeatedMessage()));
+ $this->assertSame(201, $m->getRepeatedMessage()[2]->getA());
+
+ $this->assertSame(2, count($m->getMapInt32Int32()));
+ $this->assertSame(300, $m->getMapInt32Int32()[1]);
+ $this->assertSame(301, $m->getMapInt32Int32()[-62]);
+ $this->assertSame(1, count($m->getMapUint32Uint32()));
+ $this->assertSame(2, count($m->getMapStringString()));
+ $this->assertSame('def', $m->getMapStringString()['def']);
+
+ $this->assertSame(2, count($m->getMapInt32Message()));
+ $this->assertSame(302, $m->getMapInt32Message()[1]->getA());
+ $this->assertSame(303, $m->getMapInt32Message()[2]->getA());
+
+ $this->assertSame("", $m->getMyOneof());
+
+ // Check sub-messages are copied by value.
+ $n->getOptionalMessage()->setA(-101);
+ $this->assertSame(101, $m->getOptionalMessage()->getA());
+
+ $repeatedMessage = $n->getRepeatedMessage();
+ $repeatedMessage[0]->setA(-201);
+ $n->setRepeatedMessage($repeatedMessage);
+ $this->assertSame(201, $m->getRepeatedMessage()[2]->getA());
+
+ $mapInt32Message = $n->getMapInt32Message();
+ $mapInt32Message[1]->setA(-302);
+ $n->setMapInt32Message($mapInt32Message);
+
+ $this->assertSame(302, $m->getMapInt32Message()[1]->getA());
+
+ // Test merge oneof.
+ $m = new TestMessage();
+
+ $n = new TestMessage();
+ $n->setOneofInt32(1);
+ $m->mergeFrom($n);
+ $this->assertSame(1, $m->getOneofInt32());
+
+ $sub = new TestMessage_Sub();
+ $n->setOneofMessage($sub);
+ $n->getOneofMessage()->setA(400);
+ $m->mergeFrom($n);
+ $this->assertSame(400, $m->getOneofMessage()->getA());
+ $n->getOneofMessage()->setA(-400);
+ $this->assertSame(400, $m->getOneofMessage()->getA());
+
+ // Test all fields
+ $m = new TestMessage();
+ $n = new TestMessage();
+ $this->setFields($m);
+ $n->mergeFrom($m);
+ $this->expectFields($n);
+ }
+
#########################################################
+ # Test message/enum without namespace.
+ #########################################################
+
+ public function testMessageWithoutNamespace()
+ {
+ $m = new TestMessage();
+ $sub = new NoNameSpaceMessage();
+ $m->setOptionalNoNamespaceMessage($sub);
+ $repeatedNoNamespaceMessage = $m->getRepeatedNoNamespaceMessage();
+ $repeatedNoNamespaceMessage[] = new NoNameSpaceMessage();
+ $m->setRepeatedNoNamespaceMessage($repeatedNoNamespaceMessage);
+
+ $n = new NoNamespaceMessage();
+ $n->setB(NoNamespaceMessage_NestedEnum::ZERO);
+ }
- public function testMessageWithoutNamespace() {
- $m = new NoNameSpace();
+ public function testEnumWithoutNamespace()
+ {
+ $m = new TestMessage();
+ $m->setOptionalNoNamespaceEnum(NoNameSpaceEnum::VALUE_A);
+ $repeatedNoNamespaceEnum = $m->getRepeatedNoNamespaceEnum();
+ $repeatedNoNamespaceEnum[] = NoNameSpaceEnum::VALUE_A;
+ $m->setRepeatedNoNamespaceEnum($repeatedNoNamespaceEnum);
+ }
+
+ #########################################################
+ # Test message with given prefix.
+ #########################################################
+
+ public function testPrefixMessage()
+ {
+ $m = new TestIncludePrefixMessage();
+ $n = new PrefixTestPrefix();
+ $n->setA(1);
+ $m->setPrefixMessage($n);
+ $this->assertSame(1, $m->getPrefixMessage()->getA());
+ }
+
+ #########################################################
+ # Test message with given namespace.
+ #########################################################
+
+ public function testNamespaceMessage()
+ {
+ $m = new TestIncludeNamespaceMessage();
+
+ $n = new TestNamespace();
+ $n->setA(1);
+ $m->setNamespaceMessage($n);
+ $this->assertSame(1, $m->getNamespaceMessage()->getA());
+
+ $n = new TestEmptyNamespace();
+ $n->setA(1);
+ $m->setEmptyNamespaceMessage($n);
+ $this->assertSame(1, $m->getEmptyNamespaceMessage()->getA());
+ }
+
+ #########################################################
+ # Test prefix for reserved words.
+ #########################################################
+
+ public function testPrefixForReservedWords()
+ {
+ $m = new \Foo\TestMessage_Empty();
+ $m = new \Foo\PBEmpty();
+ $m = new \PrefixEmpty();
+ $m = new \Foo\PBARRAY();
+
+ $m = new \Lower\PBabstract();
+ $m = new \Lower\PBand();
+ $m = new \Lower\PBarray();
+ $m = new \Lower\PBas();
+ $m = new \Lower\PBbreak();
+ $m = new \Lower\PBcallable();
+ $m = new \Lower\PBcase();
+ $m = new \Lower\PBcatch();
+ $m = new \Lower\PBclass();
+ $m = new \Lower\PBclone();
+ $m = new \Lower\PBconst();
+ $m = new \Lower\PBcontinue();
+ $m = new \Lower\PBdeclare();
+ $m = new \Lower\PBdefault();
+ $m = new \Lower\PBdie();
+ $m = new \Lower\PBdo();
+ $m = new \Lower\PBecho();
+ $m = new \Lower\PBelse();
+ $m = new \Lower\PBelseif();
+ $m = new \Lower\PBempty();
+ $m = new \Lower\PBenddeclare();
+ $m = new \Lower\PBendfor();
+ $m = new \Lower\PBendforeach();
+ $m = new \Lower\PBendif();
+ $m = new \Lower\PBendswitch();
+ $m = new \Lower\PBendwhile();
+ $m = new \Lower\PBeval();
+ $m = new \Lower\PBexit();
+ $m = new \Lower\PBextends();
+ $m = new \Lower\PBfinal();
+ $m = new \Lower\PBfor();
+ $m = new \Lower\PBforeach();
+ $m = new \Lower\PBfunction();
+ $m = new \Lower\PBglobal();
+ $m = new \Lower\PBgoto();
+ $m = new \Lower\PBif();
+ $m = new \Lower\PBimplements();
+ $m = new \Lower\PBinclude();
+ $m = new \Lower\PBinclude_once();
+ $m = new \Lower\PBinstanceof();
+ $m = new \Lower\PBinsteadof();
+ $m = new \Lower\PBinterface();
+ $m = new \Lower\PBisset();
+ $m = new \Lower\PBlist();
+ $m = new \Lower\PBnamespace();
+ $m = new \Lower\PBnew();
+ $m = new \Lower\PBor();
+ $m = new \Lower\PBprint();
+ $m = new \Lower\PBprivate();
+ $m = new \Lower\PBprotected();
+ $m = new \Lower\PBpublic();
+ $m = new \Lower\PBrequire();
+ $m = new \Lower\PBrequire_once();
+ $m = new \Lower\PBreturn();
+ $m = new \Lower\PBstatic();
+ $m = new \Lower\PBswitch();
+ $m = new \Lower\PBthrow();
+ $m = new \Lower\PBtrait();
+ $m = new \Lower\PBtry();
+ $m = new \Lower\PBunset();
+ $m = new \Lower\PBuse();
+ $m = new \Lower\PBvar();
+ $m = new \Lower\PBwhile();
+ $m = new \Lower\PBxor();
+ $m = new \Lower\PBint();
+ $m = new \Lower\PBfloat();
+ $m = new \Lower\PBbool();
+ $m = new \Lower\PBstring();
+ $m = new \Lower\PBtrue();
+ $m = new \Lower\PBfalse();
+ $m = new \Lower\PBnull();
+ $m = new \Lower\PBvoid();
+ $m = new \Lower\PBiterable();
+
+ $m = new \Upper\PBABSTRACT();
+ $m = new \Upper\PBAND();
+ $m = new \Upper\PBARRAY();
+ $m = new \Upper\PBAS();
+ $m = new \Upper\PBBREAK();
+ $m = new \Upper\PBCALLABLE();
+ $m = new \Upper\PBCASE();
+ $m = new \Upper\PBCATCH();
+ $m = new \Upper\PBCLASS();
+ $m = new \Upper\PBCLONE();
+ $m = new \Upper\PBCONST();
+ $m = new \Upper\PBCONTINUE();
+ $m = new \Upper\PBDECLARE();
+ $m = new \Upper\PBDEFAULT();
+ $m = new \Upper\PBDIE();
+ $m = new \Upper\PBDO();
+ $m = new \Upper\PBECHO();
+ $m = new \Upper\PBELSE();
+ $m = new \Upper\PBELSEIF();
+ $m = new \Upper\PBEMPTY();
+ $m = new \Upper\PBENDDECLARE();
+ $m = new \Upper\PBENDFOR();
+ $m = new \Upper\PBENDFOREACH();
+ $m = new \Upper\PBENDIF();
+ $m = new \Upper\PBENDSWITCH();
+ $m = new \Upper\PBENDWHILE();
+ $m = new \Upper\PBEVAL();
+ $m = new \Upper\PBEXIT();
+ $m = new \Upper\PBEXTENDS();
+ $m = new \Upper\PBFINAL();
+ $m = new \Upper\PBFOR();
+ $m = new \Upper\PBFOREACH();
+ $m = new \Upper\PBFUNCTION();
+ $m = new \Upper\PBGLOBAL();
+ $m = new \Upper\PBGOTO();
+ $m = new \Upper\PBIF();
+ $m = new \Upper\PBIMPLEMENTS();
+ $m = new \Upper\PBINCLUDE();
+ $m = new \Upper\PBINCLUDE_ONCE();
+ $m = new \Upper\PBINSTANCEOF();
+ $m = new \Upper\PBINSTEADOF();
+ $m = new \Upper\PBINTERFACE();
+ $m = new \Upper\PBISSET();
+ $m = new \Upper\PBLIST();
+ $m = new \Upper\PBNAMESPACE();
+ $m = new \Upper\PBNEW();
+ $m = new \Upper\PBOR();
+ $m = new \Upper\PBPRINT();
+ $m = new \Upper\PBPRIVATE();
+ $m = new \Upper\PBPROTECTED();
+ $m = new \Upper\PBPUBLIC();
+ $m = new \Upper\PBREQUIRE();
+ $m = new \Upper\PBREQUIRE_ONCE();
+ $m = new \Upper\PBRETURN();
+ $m = new \Upper\PBSTATIC();
+ $m = new \Upper\PBSWITCH();
+ $m = new \Upper\PBTHROW();
+ $m = new \Upper\PBTRAIT();
+ $m = new \Upper\PBTRY();
+ $m = new \Upper\PBUNSET();
+ $m = new \Upper\PBUSE();
+ $m = new \Upper\PBVAR();
+ $m = new \Upper\PBWHILE();
+ $m = new \Upper\PBXOR();
+ $m = new \Upper\PBINT();
+ $m = new \Upper\PBFLOAT();
+ $m = new \Upper\PBBOOL();
+ $m = new \Upper\PBSTRING();
+ $m = new \Upper\PBTRUE();
+ $m = new \Upper\PBFALSE();
+ $m = new \Upper\PBNULL();
+ $m = new \Upper\PBVOID();
+ $m = new \Upper\PBITERABLE();
+
+ $m = new \Lower_enum\PBabstract();
+ $m = new \Lower_enum\PBand();
+ $m = new \Lower_enum\PBarray();
+ $m = new \Lower_enum\PBas();
+ $m = new \Lower_enum\PBbreak();
+ $m = new \Lower_enum\PBcallable();
+ $m = new \Lower_enum\PBcase();
+ $m = new \Lower_enum\PBcatch();
+ $m = new \Lower_enum\PBclass();
+ $m = new \Lower_enum\PBclone();
+ $m = new \Lower_enum\PBconst();
+ $m = new \Lower_enum\PBcontinue();
+ $m = new \Lower_enum\PBdeclare();
+ $m = new \Lower_enum\PBdefault();
+ $m = new \Lower_enum\PBdie();
+ $m = new \Lower_enum\PBdo();
+ $m = new \Lower_enum\PBecho();
+ $m = new \Lower_enum\PBelse();
+ $m = new \Lower_enum\PBelseif();
+ $m = new \Lower_enum\PBempty();
+ $m = new \Lower_enum\PBenddeclare();
+ $m = new \Lower_enum\PBendfor();
+ $m = new \Lower_enum\PBendforeach();
+ $m = new \Lower_enum\PBendif();
+ $m = new \Lower_enum\PBendswitch();
+ $m = new \Lower_enum\PBendwhile();
+ $m = new \Lower_enum\PBeval();
+ $m = new \Lower_enum\PBexit();
+ $m = new \Lower_enum\PBextends();
+ $m = new \Lower_enum\PBfinal();
+ $m = new \Lower_enum\PBfor();
+ $m = new \Lower_enum\PBforeach();
+ $m = new \Lower_enum\PBfunction();
+ $m = new \Lower_enum\PBglobal();
+ $m = new \Lower_enum\PBgoto();
+ $m = new \Lower_enum\PBif();
+ $m = new \Lower_enum\PBimplements();
+ $m = new \Lower_enum\PBinclude();
+ $m = new \Lower_enum\PBinclude_once();
+ $m = new \Lower_enum\PBinstanceof();
+ $m = new \Lower_enum\PBinsteadof();
+ $m = new \Lower_enum\PBinterface();
+ $m = new \Lower_enum\PBisset();
+ $m = new \Lower_enum\PBlist();
+ $m = new \Lower_enum\PBnamespace();
+ $m = new \Lower_enum\PBnew();
+ $m = new \Lower_enum\PBor();
+ $m = new \Lower_enum\PBprint();
+ $m = new \Lower_enum\PBprivate();
+ $m = new \Lower_enum\PBprotected();
+ $m = new \Lower_enum\PBpublic();
+ $m = new \Lower_enum\PBrequire();
+ $m = new \Lower_enum\PBrequire_once();
+ $m = new \Lower_enum\PBreturn();
+ $m = new \Lower_enum\PBstatic();
+ $m = new \Lower_enum\PBswitch();
+ $m = new \Lower_enum\PBthrow();
+ $m = new \Lower_enum\PBtrait();
+ $m = new \Lower_enum\PBtry();
+ $m = new \Lower_enum\PBunset();
+ $m = new \Lower_enum\PBuse();
+ $m = new \Lower_enum\PBvar();
+ $m = new \Lower_enum\PBwhile();
+ $m = new \Lower_enum\PBxor();
+ $m = new \Lower_enum\PBint();
+ $m = new \Lower_enum\PBfloat();
+ $m = new \Lower_enum\PBbool();
+ $m = new \Lower_enum\PBstring();
+ $m = new \Lower_enum\PBtrue();
+ $m = new \Lower_enum\PBfalse();
+ $m = new \Lower_enum\PBnull();
+ $m = new \Lower_enum\PBvoid();
+ $m = new \Lower_enum\PBiterable();
+
+ $m = new \Upper_enum\PBABSTRACT();
+ $m = new \Upper_enum\PBAND();
+ $m = new \Upper_enum\PBARRAY();
+ $m = new \Upper_enum\PBAS();
+ $m = new \Upper_enum\PBBREAK();
+ $m = new \Upper_enum\PBCALLABLE();
+ $m = new \Upper_enum\PBCASE();
+ $m = new \Upper_enum\PBCATCH();
+ $m = new \Upper_enum\PBCLASS();
+ $m = new \Upper_enum\PBCLONE();
+ $m = new \Upper_enum\PBCONST();
+ $m = new \Upper_enum\PBCONTINUE();
+ $m = new \Upper_enum\PBDECLARE();
+ $m = new \Upper_enum\PBDEFAULT();
+ $m = new \Upper_enum\PBDIE();
+ $m = new \Upper_enum\PBDO();
+ $m = new \Upper_enum\PBECHO();
+ $m = new \Upper_enum\PBELSE();
+ $m = new \Upper_enum\PBELSEIF();
+ $m = new \Upper_enum\PBEMPTY();
+ $m = new \Upper_enum\PBENDDECLARE();
+ $m = new \Upper_enum\PBENDFOR();
+ $m = new \Upper_enum\PBENDFOREACH();
+ $m = new \Upper_enum\PBENDIF();
+ $m = new \Upper_enum\PBENDSWITCH();
+ $m = new \Upper_enum\PBENDWHILE();
+ $m = new \Upper_enum\PBEVAL();
+ $m = new \Upper_enum\PBEXIT();
+ $m = new \Upper_enum\PBEXTENDS();
+ $m = new \Upper_enum\PBFINAL();
+ $m = new \Upper_enum\PBFOR();
+ $m = new \Upper_enum\PBFOREACH();
+ $m = new \Upper_enum\PBFUNCTION();
+ $m = new \Upper_enum\PBGLOBAL();
+ $m = new \Upper_enum\PBGOTO();
+ $m = new \Upper_enum\PBIF();
+ $m = new \Upper_enum\PBIMPLEMENTS();
+ $m = new \Upper_enum\PBINCLUDE();
+ $m = new \Upper_enum\PBINCLUDE_ONCE();
+ $m = new \Upper_enum\PBINSTANCEOF();
+ $m = new \Upper_enum\PBINSTEADOF();
+ $m = new \Upper_enum\PBINTERFACE();
+ $m = new \Upper_enum\PBISSET();
+ $m = new \Upper_enum\PBLIST();
+ $m = new \Upper_enum\PBNAMESPACE();
+ $m = new \Upper_enum\PBNEW();
+ $m = new \Upper_enum\PBOR();
+ $m = new \Upper_enum\PBPRINT();
+ $m = new \Upper_enum\PBPRIVATE();
+ $m = new \Upper_enum\PBPROTECTED();
+ $m = new \Upper_enum\PBPUBLIC();
+ $m = new \Upper_enum\PBREQUIRE();
+ $m = new \Upper_enum\PBREQUIRE_ONCE();
+ $m = new \Upper_enum\PBRETURN();
+ $m = new \Upper_enum\PBSTATIC();
+ $m = new \Upper_enum\PBSWITCH();
+ $m = new \Upper_enum\PBTHROW();
+ $m = new \Upper_enum\PBTRAIT();
+ $m = new \Upper_enum\PBTRY();
+ $m = new \Upper_enum\PBUNSET();
+ $m = new \Upper_enum\PBUSE();
+ $m = new \Upper_enum\PBVAR();
+ $m = new \Upper_enum\PBWHILE();
+ $m = new \Upper_enum\PBXOR();
+ $m = new \Upper_enum\PBINT();
+ $m = new \Upper_enum\PBFLOAT();
+ $m = new \Upper_enum\PBBOOL();
+ $m = new \Upper_enum\PBSTRING();
+ $m = new \Upper_enum\PBTRUE();
+ $m = new \Upper_enum\PBFALSE();
+ $m = new \Upper_enum\PBNULL();
+ $m = new \Upper_enum\PBVOID();
+ $m = new \Upper_enum\PBITERABLE();
+
+ $m = \Lower_enum_value\NotAllowed::PBabstract;
+ $m = \Lower_enum_value\NotAllowed::PBand;
+ $m = \Lower_enum_value\NotAllowed::PBarray;
+ $m = \Lower_enum_value\NotAllowed::PBas;
+ $m = \Lower_enum_value\NotAllowed::PBbreak;
+ $m = \Lower_enum_value\NotAllowed::PBcallable;
+ $m = \Lower_enum_value\NotAllowed::PBcase;
+ $m = \Lower_enum_value\NotAllowed::PBcatch;
+ $m = \Lower_enum_value\NotAllowed::PBclass;
+ $m = \Lower_enum_value\NotAllowed::PBclone;
+ $m = \Lower_enum_value\NotAllowed::PBconst;
+ $m = \Lower_enum_value\NotAllowed::PBcontinue;
+ $m = \Lower_enum_value\NotAllowed::PBdeclare;
+ $m = \Lower_enum_value\NotAllowed::PBdefault;
+ $m = \Lower_enum_value\NotAllowed::PBdie;
+ $m = \Lower_enum_value\NotAllowed::PBdo;
+ $m = \Lower_enum_value\NotAllowed::PBecho;
+ $m = \Lower_enum_value\NotAllowed::PBelse;
+ $m = \Lower_enum_value\NotAllowed::PBelseif;
+ $m = \Lower_enum_value\NotAllowed::PBempty;
+ $m = \Lower_enum_value\NotAllowed::PBenddeclare;
+ $m = \Lower_enum_value\NotAllowed::PBendfor;
+ $m = \Lower_enum_value\NotAllowed::PBendforeach;
+ $m = \Lower_enum_value\NotAllowed::PBendif;
+ $m = \Lower_enum_value\NotAllowed::PBendswitch;
+ $m = \Lower_enum_value\NotAllowed::PBendwhile;
+ $m = \Lower_enum_value\NotAllowed::PBeval;
+ $m = \Lower_enum_value\NotAllowed::PBexit;
+ $m = \Lower_enum_value\NotAllowed::PBextends;
+ $m = \Lower_enum_value\NotAllowed::PBfinal;
+ $m = \Lower_enum_value\NotAllowed::PBfor;
+ $m = \Lower_enum_value\NotAllowed::PBforeach;
+ $m = \Lower_enum_value\NotAllowed::PBfunction;
+ $m = \Lower_enum_value\NotAllowed::PBglobal;
+ $m = \Lower_enum_value\NotAllowed::PBgoto;
+ $m = \Lower_enum_value\NotAllowed::PBif;
+ $m = \Lower_enum_value\NotAllowed::PBimplements;
+ $m = \Lower_enum_value\NotAllowed::PBinclude;
+ $m = \Lower_enum_value\NotAllowed::PBinclude_once;
+ $m = \Lower_enum_value\NotAllowed::PBinstanceof;
+ $m = \Lower_enum_value\NotAllowed::PBinsteadof;
+ $m = \Lower_enum_value\NotAllowed::PBinterface;
+ $m = \Lower_enum_value\NotAllowed::PBisset;
+ $m = \Lower_enum_value\NotAllowed::PBlist;
+ $m = \Lower_enum_value\NotAllowed::PBnamespace;
+ $m = \Lower_enum_value\NotAllowed::PBnew;
+ $m = \Lower_enum_value\NotAllowed::PBor;
+ $m = \Lower_enum_value\NotAllowed::PBprint;
+ $m = \Lower_enum_value\NotAllowed::PBprivate;
+ $m = \Lower_enum_value\NotAllowed::PBprotected;
+ $m = \Lower_enum_value\NotAllowed::PBpublic;
+ $m = \Lower_enum_value\NotAllowed::PBrequire;
+ $m = \Lower_enum_value\NotAllowed::PBrequire_once;
+ $m = \Lower_enum_value\NotAllowed::PBreturn;
+ $m = \Lower_enum_value\NotAllowed::PBstatic;
+ $m = \Lower_enum_value\NotAllowed::PBswitch;
+ $m = \Lower_enum_value\NotAllowed::PBthrow;
+ $m = \Lower_enum_value\NotAllowed::PBtrait;
+ $m = \Lower_enum_value\NotAllowed::PBtry;
+ $m = \Lower_enum_value\NotAllowed::PBunset;
+ $m = \Lower_enum_value\NotAllowed::PBuse;
+ $m = \Lower_enum_value\NotAllowed::PBvar;
+ $m = \Lower_enum_value\NotAllowed::PBwhile;
+ $m = \Lower_enum_value\NotAllowed::PBxor;
+ $m = \Lower_enum_value\NotAllowed::int;
+ $m = \Lower_enum_value\NotAllowed::float;
+ $m = \Lower_enum_value\NotAllowed::bool;
+ $m = \Lower_enum_value\NotAllowed::string;
+ $m = \Lower_enum_value\NotAllowed::true;
+ $m = \Lower_enum_value\NotAllowed::false;
+ $m = \Lower_enum_value\NotAllowed::null;
+ $m = \Lower_enum_value\NotAllowed::void;
+ $m = \Lower_enum_value\NotAllowed::iterable;
+
+ $m = \Upper_enum_value\NotAllowed::PBABSTRACT;
+ $m = \Upper_enum_value\NotAllowed::PBAND;
+ $m = \Upper_enum_value\NotAllowed::PBARRAY;
+ $m = \Upper_enum_value\NotAllowed::PBAS;
+ $m = \Upper_enum_value\NotAllowed::PBBREAK;
+ $m = \Upper_enum_value\NotAllowed::PBCALLABLE;
+ $m = \Upper_enum_value\NotAllowed::PBCASE;
+ $m = \Upper_enum_value\NotAllowed::PBCATCH;
+ $m = \Upper_enum_value\NotAllowed::PBCLASS;
+ $m = \Upper_enum_value\NotAllowed::PBCLONE;
+ $m = \Upper_enum_value\NotAllowed::PBCONST;
+ $m = \Upper_enum_value\NotAllowed::PBCONTINUE;
+ $m = \Upper_enum_value\NotAllowed::PBDECLARE;
+ $m = \Upper_enum_value\NotAllowed::PBDEFAULT;
+ $m = \Upper_enum_value\NotAllowed::PBDIE;
+ $m = \Upper_enum_value\NotAllowed::PBDO;
+ $m = \Upper_enum_value\NotAllowed::PBECHO;
+ $m = \Upper_enum_value\NotAllowed::PBELSE;
+ $m = \Upper_enum_value\NotAllowed::PBELSEIF;
+ $m = \Upper_enum_value\NotAllowed::PBEMPTY;
+ $m = \Upper_enum_value\NotAllowed::PBENDDECLARE;
+ $m = \Upper_enum_value\NotAllowed::PBENDFOR;
+ $m = \Upper_enum_value\NotAllowed::PBENDFOREACH;
+ $m = \Upper_enum_value\NotAllowed::PBENDIF;
+ $m = \Upper_enum_value\NotAllowed::PBENDSWITCH;
+ $m = \Upper_enum_value\NotAllowed::PBENDWHILE;
+ $m = \Upper_enum_value\NotAllowed::PBEVAL;
+ $m = \Upper_enum_value\NotAllowed::PBEXIT;
+ $m = \Upper_enum_value\NotAllowed::PBEXTENDS;
+ $m = \Upper_enum_value\NotAllowed::PBFINAL;
+ $m = \Upper_enum_value\NotAllowed::PBFOR;
+ $m = \Upper_enum_value\NotAllowed::PBFOREACH;
+ $m = \Upper_enum_value\NotAllowed::PBFUNCTION;
+ $m = \Upper_enum_value\NotAllowed::PBGLOBAL;
+ $m = \Upper_enum_value\NotAllowed::PBGOTO;
+ $m = \Upper_enum_value\NotAllowed::PBIF;
+ $m = \Upper_enum_value\NotAllowed::PBIMPLEMENTS;
+ $m = \Upper_enum_value\NotAllowed::PBINCLUDE;
+ $m = \Upper_enum_value\NotAllowed::PBINCLUDE_ONCE;
+ $m = \Upper_enum_value\NotAllowed::PBINSTANCEOF;
+ $m = \Upper_enum_value\NotAllowed::PBINSTEADOF;
+ $m = \Upper_enum_value\NotAllowed::PBINTERFACE;
+ $m = \Upper_enum_value\NotAllowed::PBISSET;
+ $m = \Upper_enum_value\NotAllowed::PBLIST;
+ $m = \Upper_enum_value\NotAllowed::PBNAMESPACE;
+ $m = \Upper_enum_value\NotAllowed::PBNEW;
+ $m = \Upper_enum_value\NotAllowed::PBOR;
+ $m = \Upper_enum_value\NotAllowed::PBPRINT;
+ $m = \Upper_enum_value\NotAllowed::PBPRIVATE;
+ $m = \Upper_enum_value\NotAllowed::PBPROTECTED;
+ $m = \Upper_enum_value\NotAllowed::PBPUBLIC;
+ $m = \Upper_enum_value\NotAllowed::PBREQUIRE;
+ $m = \Upper_enum_value\NotAllowed::PBREQUIRE_ONCE;
+ $m = \Upper_enum_value\NotAllowed::PBRETURN;
+ $m = \Upper_enum_value\NotAllowed::PBSTATIC;
+ $m = \Upper_enum_value\NotAllowed::PBSWITCH;
+ $m = \Upper_enum_value\NotAllowed::PBTHROW;
+ $m = \Upper_enum_value\NotAllowed::PBTRAIT;
+ $m = \Upper_enum_value\NotAllowed::PBTRY;
+ $m = \Upper_enum_value\NotAllowed::PBUNSET;
+ $m = \Upper_enum_value\NotAllowed::PBUSE;
+ $m = \Upper_enum_value\NotAllowed::PBVAR;
+ $m = \Upper_enum_value\NotAllowed::PBWHILE;
+ $m = \Upper_enum_value\NotAllowed::PBXOR;
+ $m = \Upper_enum_value\NotAllowed::INT;
+ $m = \Upper_enum_value\NotAllowed::FLOAT;
+ $m = \Upper_enum_value\NotAllowed::BOOL;
+ $m = \Upper_enum_value\NotAllowed::STRING;
+ $m = \Upper_enum_value\NotAllowed::TRUE;
+ $m = \Upper_enum_value\NotAllowed::FALSE;
+ $m = \Upper_enum_value\NotAllowed::NULL;
+ $m = \Upper_enum_value\NotAllowed::VOID;
+ $m = \Upper_enum_value\NotAllowed::ITERABLE;
+ }
+
+ #########################################################
+ # Test fluent setters.
+ #########################################################
+
+ public function testFluentSetters()
+ {
+ $m = (new TestMessage())
+ ->setOptionalInt32(1)
+ ->setOptionalUInt32(2);
+ $this->assertSame(1, $m->getOptionalInt32());
+ $this->assertSame(2, $m->getOptionalUInt32());
+ }
+
+ #########################################################
+ # Test Reverse Field Order.
+ #########################################################
+
+ public function testReverseFieldOrder()
+ {
+ $m = new TestReverseFieldOrder();
+ $m->setB("abc");
+ $this->assertSame("abc", $m->getB());
+ $this->assertNotSame("abc", $m->getA());
+ }
+
+ #########################################################
+ # Test Reverse Field Order.
+ #########################################################
+
+ public function testLowerCase()
+ {
+ $m = new testLowerCaseMessage();
+ $n = testLowerCaseEnum::VALUE;
}
}
diff --git a/php/tests/generated_phpdoc_test.php b/php/tests/generated_phpdoc_test.php
new file mode 100644
index 00000000..6c1a26f7
--- /dev/null
+++ b/php/tests/generated_phpdoc_test.php
@@ -0,0 +1,337 @@
+<?php
+
+require_once('generated/NoNamespaceEnum.php');
+require_once('generated/NoNamespaceMessage.php');
+require_once('test_base.php');
+require_once('test_util.php');
+
+use Foo\TestMessage;
+
+class GeneratedPhpdocTest extends TestBase
+{
+ public function testPhpDocForClass()
+ {
+ $class = new ReflectionClass('Foo\TestMessage');
+ $doc = $class->getDocComment();
+ $this->assertContains('foo.TestMessage', $doc);
+ }
+
+ /**
+ * @dataProvider providePhpDocForGettersAndSetters
+ */
+ public function testPhpDocForIntGetters($methods, $expectedDoc)
+ {
+ $class = new ReflectionClass('Foo\TestMessage');
+ foreach ($methods as $method) {
+ $doc = $class->getMethod($method)->getDocComment();
+ $this->assertContains($expectedDoc, $doc);
+ }
+ }
+
+ public function providePhpDocForGettersAndSetters()
+ {
+ return [
+ [
+ [
+ 'setOptionalInt32',
+ 'setOptionalUint32',
+ 'setOptionalSint32',
+ 'setOptionalFixed32',
+ 'setOptionalSfixed32',
+ 'setOneofInt32',
+ 'setOneofUint32',
+ 'setOneofSint32',
+ 'setOneofFixed32',
+ 'setOneofSfixed32',
+ 'setOptionalEnum',
+ 'setOptionalNoNamespaceEnum',
+ 'setOptionalNestedEnum',
+ 'setOneofEnum'
+ ],
+ '@param int $var'
+ ],
+ [
+ [
+ 'setOptionalInt64',
+ 'setOptionalUint64',
+ 'setOptionalSint64',
+ 'setOptionalFixed64',
+ 'setOptionalSfixed64',
+ 'setOneofInt64',
+ 'setOneofUint64',
+ 'setOneofSint64',
+ 'setOneofFixed64',
+ 'setOneofSfixed64',
+ ],
+ '@param int|string $var'
+ ],
+ [
+ [
+ 'getOptionalInt32',
+ 'getOptionalUint32',
+ 'getOptionalSint32',
+ 'getOptionalFixed32',
+ 'getOptionalSfixed32',
+ 'getOneofInt32',
+ 'getOneofUint32',
+ 'getOneofSint32',
+ 'getOneofFixed32',
+ 'getOneofSfixed32',
+ 'getOptionalEnum',
+ 'getOptionalNoNamespaceEnum',
+ 'getOptionalNestedEnum',
+ 'getOneofEnum',
+ ],
+ '@return int'
+ ],
+ [
+ [
+ 'setOptionalInt64',
+ 'setOptionalUint64',
+ 'setOptionalSint64',
+ 'setOptionalFixed64',
+ 'setOptionalSfixed64',
+ 'setOneofInt64',
+ 'setOneofUint64',
+ 'setOneofSint64',
+ 'setOneofFixed64',
+ 'setOneofSfixed64',
+ ],
+ '@param int|string $var'
+ ],
+ [
+ [
+ 'getRepeatedInt32',
+ 'getRepeatedInt64',
+ 'getRepeatedUint32',
+ 'getRepeatedUint64',
+ 'getRepeatedSint32',
+ 'getRepeatedSint64',
+ 'getRepeatedFixed32',
+ 'getRepeatedFixed64',
+ 'getRepeatedSfixed32',
+ 'getRepeatedSfixed64',
+ 'getRepeatedFloat',
+ 'getRepeatedDouble',
+ 'getRepeatedBool',
+ 'getRepeatedString',
+ 'getRepeatedBytes',
+ 'getRepeatedEnum',
+ 'getRepeatedMessage',
+ 'getRepeatedRecursive',
+ 'getRepeatedNoNamespaceMessage',
+ 'getRepeatedNoNamespaceEnum',
+ ],
+ '@return \Google\Protobuf\Internal\RepeatedField'
+ ],
+ [
+ [
+ 'getMapInt32Int32',
+ 'getMapInt64Int64',
+ 'getMapUint32Uint32',
+ 'getMapUint64Uint64',
+ 'getMapSint32Sint32',
+ 'getMapSint64Sint64',
+ 'getMapFixed32Fixed32',
+ 'getMapFixed64Fixed64',
+ 'getMapSfixed32Sfixed32',
+ 'getMapSfixed64Sfixed64',
+ 'getMapInt32Float',
+ 'getMapInt32Double',
+ 'getMapBoolBool',
+ 'getMapStringString',
+ 'getMapInt32Bytes',
+ 'getMapInt32Enum',
+ 'getMapInt32Message',
+ 'getMapRecursive',
+ ],
+ '@return \Google\Protobuf\Internal\MapField'
+ ],
+ [
+ [
+ 'setRepeatedInt32',
+ 'setRepeatedUint32',
+ 'setRepeatedSint32',
+ 'setRepeatedFixed32',
+ 'setRepeatedSfixed32',
+ 'setRepeatedEnum',
+ 'setRepeatedNoNamespaceEnum',
+ ],
+ '@param int[]|\Google\Protobuf\Internal\RepeatedField $var'
+ ],
+ [
+ [
+ 'setRepeatedInt64',
+ 'setRepeatedUint64',
+ 'setRepeatedSint64',
+ 'setRepeatedFixed64',
+ 'setRepeatedSfixed64',
+ ],
+ '@param int[]|string[]|\Google\Protobuf\Internal\RepeatedField $var'
+ ],
+ [
+ [
+ 'setRepeatedFloat',
+ 'setRepeatedDouble',
+ ],
+ '@param float[]|\Google\Protobuf\Internal\RepeatedField $var'
+ ],
+ [
+ [
+ 'setRepeatedBool',
+ ],
+ '@param bool[]|\Google\Protobuf\Internal\RepeatedField $var'
+ ],
+ [
+ [
+ 'setRepeatedString',
+ 'setRepeatedBytes',
+ ],
+ '@param string[]|\Google\Protobuf\Internal\RepeatedField $var'
+ ],
+ [
+ [
+ 'setRepeatedMessage',
+ ],
+ '@param \Foo\TestMessage_Sub[]|\Google\Protobuf\Internal\RepeatedField $var'
+ ],
+ [
+ [
+ 'setRepeatedRecursive',
+ ],
+ '@param \Foo\TestMessage[]|\Google\Protobuf\Internal\RepeatedField $var'
+ ],
+ [
+ [
+ 'setRepeatedNoNamespaceMessage',
+ ],
+ '@param \NoNamespaceMessage[]|\Google\Protobuf\Internal\RepeatedField $var'
+ ],
+ [
+ [
+ 'setMapInt32Int32',
+ 'setMapInt64Int64',
+ 'setMapUint32Uint32',
+ 'setMapUint64Uint64',
+ 'setMapSint32Sint32',
+ 'setMapSint64Sint64',
+ 'setMapFixed32Fixed32',
+ 'setMapFixed64Fixed64',
+ 'setMapSfixed32Sfixed32',
+ 'setMapSfixed64Sfixed64',
+ 'setMapInt32Float',
+ 'setMapInt32Double',
+ 'setMapBoolBool',
+ 'setMapStringString',
+ 'setMapInt32Bytes',
+ 'setMapInt32Enum',
+ 'setMapInt32Message',
+ 'setMapRecursive',
+ ],
+ '@param array|\Google\Protobuf\Internal\MapField $var'
+ ],
+ [
+ [
+ 'getOptionalFloat',
+ 'getOptionalDouble',
+ 'getOneofDouble',
+ 'getOneofFloat',
+ ],
+ '@return float'
+ ],
+ [
+ [
+ 'setOptionalFloat',
+ 'setOptionalDouble',
+ 'setOneofDouble',
+ 'setOneofFloat',
+ ],
+ '@param float $var'
+ ],
+ [
+ [
+ 'getOptionalBool',
+ 'getOneofBool',
+ ],
+ '@return bool'],
+ [
+ [
+ 'setOptionalBool',
+ 'setOneofBool',
+ ],
+ '@param bool $var'
+ ],
+ [
+ [
+ 'getOptionalString',
+ 'getOptionalBytes',
+ 'getOneofString',
+ 'getOneofBytes',
+ 'getMyOneof',
+ ],
+ '@return string'
+ ],
+ [
+ [
+ 'setOptionalString',
+ 'setOptionalBytes',
+ 'setOneofString',
+ 'setOneofBytes',
+ ],
+ '@param string $var'
+ ],
+
+ [
+ [
+ 'getOptionalMessage',
+ 'getOneofMessage'
+ ],
+ '@return \Foo\TestMessage_Sub'
+ ],
+ [
+ [
+ 'setOptionalMessage',
+ 'setOneofMessage'
+ ],
+ '@param \Foo\TestMessage_Sub $var'
+ ],
+ [
+ [
+ 'getOptionalIncludedMessage'
+ ],
+ '@return \Bar\TestInclude'
+ ],
+ [
+ [
+ 'setOptionalIncludedMessage'
+ ],
+ '@param \Bar\TestInclude $var'
+ ],
+ [
+ [
+ 'getRecursive'
+ ],
+ '@return \Foo\TestMessage'
+ ],
+ [
+ [
+ 'setRecursive'
+ ],
+ '@param \Foo\TestMessage $var'
+ ],
+
+ [
+ [
+ 'getOptionalNoNamespaceMessage'
+ ],
+ '@return \NoNamespaceMessage'
+ ],
+ [
+ [
+ 'setOptionalNoNamespaceMessage'
+ ],
+ '@param \NoNamespaceMessage $var'
+ ],
+ ];
+ }
+}
diff --git a/php/tests/generated_service_test.php b/php/tests/generated_service_test.php
new file mode 100644
index 00000000..5407db9a
--- /dev/null
+++ b/php/tests/generated_service_test.php
@@ -0,0 +1,110 @@
+<?php
+
+require_once('test_base.php');
+require_once('test_util.php');
+
+use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\MapField;
+use Google\Protobuf\Internal\GPBType;
+use Foo\Greeter;
+use Foo\HelloRequest;
+use Foo\HelloReply;
+
+class GeneratedServiceTest extends TestBase
+{
+ /**
+ * @var \ReflectionClass
+ */
+ private $serviceClass;
+
+ /**
+ * @var \ReflectionClass
+ */
+ private $namespacedServiceClass;
+
+ /**
+ * @var array
+ */
+ private $methodNames = [
+ 'sayHello',
+ 'sayHelloAgain'
+ ];
+
+ public function setUp()
+ {
+ parent::setUp();
+
+ $this->serviceClass = new ReflectionClass('Foo\GreeterInterface');
+
+ $this->namespacedServiceClass = new ReflectionClass('Bar\OtherGreeterInterface');
+ }
+
+ public function testIsInterface()
+ {
+ $this->assertTrue($this->serviceClass->isInterface());
+ }
+
+ public function testPhpDocForClass()
+ {
+ $this->assertContains('foo.Greeter', $this->serviceClass->getDocComment());
+ }
+
+ public function testPhpDocForNamespacedClass()
+ {
+ $this->assertContains('foo.OtherGreeter', $this->namespacedServiceClass->getDocComment());
+ }
+
+ public function testServiceMethodsAreGenerated()
+ {
+ $this->assertCount(count($this->methodNames), $this->serviceClass->getMethods());
+ foreach ($this->methodNames as $methodName) {
+ $this->assertTrue($this->serviceClass->hasMethod($methodName));
+ }
+ }
+
+ public function testPhpDocForServiceMethod()
+ {
+ foreach ($this->methodNames as $methodName) {
+ $docComment = $this->serviceClass->getMethod($methodName)->getDocComment();
+ $this->assertContains($methodName, $docComment);
+ $this->assertContains('@param \Foo\HelloRequest $request', $docComment);
+ $this->assertContains('@return \Foo\HelloReply', $docComment);
+ }
+ }
+
+ public function testPhpDocForServiceMethodInNamespacedClass()
+ {
+ foreach ($this->methodNames as $methodName) {
+ $docComment = $this->namespacedServiceClass->getMethod($methodName)->getDocComment();
+ $this->assertContains($methodName, $docComment);
+ $this->assertContains('@param \Foo\HelloRequest $request', $docComment);
+ $this->assertContains('@return \Foo\HelloReply', $docComment);
+ }
+ }
+
+ public function testParamForServiceMethod()
+ {
+ foreach ($this->methodNames as $methodName) {
+ $method = $this->serviceClass->getMethod($methodName);
+ $this->assertCount(1, $method->getParameters());
+ $param = $method->getParameters()[0];
+ $this->assertFalse($param->isOptional());
+ $this->assertSame('request', $param->getName());
+ // ReflectionParameter::getType only exists in PHP 7+, so get the type from __toString
+ $this->assertContains('Foo\HelloRequest $request', (string) $param);
+ }
+ }
+
+ public function testParamForServiceMethodInNamespacedClass()
+ {
+ foreach ($this->methodNames as $methodName) {
+ $method = $this->serviceClass->getMethod($methodName);
+ $this->assertCount(1, $method->getParameters());
+ $param = $method->getParameters()[0];
+ $this->assertFalse($param->isOptional());
+ $this->assertSame('request', $param->getName());
+ // ReflectionParameter::getType only exists in PHP 7+, so get the type from __toString
+ $this->assertContains('Foo\HelloRequest $request', (string) $param);
+ }
+ }
+}
diff --git a/php/tests/map_field_test.php b/php/tests/map_field_test.php
index d4ec44fc..cffa2526 100644
--- a/php/tests/map_field_test.php
+++ b/php/tests/map_field_test.php
@@ -56,42 +56,23 @@ class MapFieldTest extends PHPUnit_Framework_TestCase {
unset($arr['3.1']);
unset($arr[MAX_INT32_STRING]);
$this->assertEquals(0, count($arr));
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testInt32SetStringKeyFail()
- {
- $arr = new MapField(GPBType::INT32, GPBType::INT32);
- $arr ['abc']= 0;
- }
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testInt32SetStringValueFail()
- {
+ // Test foreach.
$arr = new MapField(GPBType::INT32, GPBType::INT32);
- $arr [0]= 'abc';
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testInt32SetMessageKeyFail()
- {
- $arr = new MapField(GPBType::INT32, GPBType::INT32);
- $arr [new TestMessage_Sub()]= 0;
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testInt32SetMessageValueFail()
- {
- $arr = new MapField(GPBType::INT32, GPBType::INT32);
- $arr [0]= new TestMessage_Sub();
+ for ($i = 0; $i < 3; $i++) {
+ $arr[$i] = $i;
+ }
+ $i = 0;
+ $arr_test = [];
+ foreach ($arr as $key => $val) {
+ $this->assertSame($key, $val);
+ $arr_test[] = $key;
+ $i++;
+ }
+ $this->assertTrue(isset($arr_test[0]));
+ $this->assertTrue(isset($arr_test[1]));
+ $this->assertTrue(isset($arr_test[2]));
+ $this->assertSame(3, $i);
}
#########################################################
@@ -159,42 +140,6 @@ class MapFieldTest extends PHPUnit_Framework_TestCase {
$this->assertEquals(0, count($arr));
}
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testUint32SetStringKeyFail()
- {
- $arr = new MapField(GPBType::UINT32, GPBType::UINT32);
- $arr ['abc']= 0;
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testUint32SetStringValueFail()
- {
- $arr = new MapField(GPBType::UINT32, GPBType::UINT32);
- $arr [0]= 'abc';
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testUint32SetMessageKeyFail()
- {
- $arr = new MapField(GPBType::UINT32, GPBType::UINT32);
- $arr [new TestMessage_Sub()]= 0;
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testUint32SetMessageValueFail()
- {
- $arr = new MapField(GPBType::UINT32, GPBType::UINT32);
- $arr [0]= new TestMessage_Sub();
- }
-
#########################################################
# Test int64 field.
#########################################################
@@ -252,42 +197,6 @@ class MapFieldTest extends PHPUnit_Framework_TestCase {
$this->assertEquals(0, count($arr));
}
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testInt64SetStringKeyFail()
- {
- $arr = new MapField(GPBType::INT64, GPBType::INT64);
- $arr ['abc']= 0;
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testInt64SetStringValueFail()
- {
- $arr = new MapField(GPBType::INT64, GPBType::INT64);
- $arr [0]= 'abc';
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testInt64SetMessageKeyFail()
- {
- $arr = new MapField(GPBType::INT64, GPBType::INT64);
- $arr [new TestMessage_Sub()]= 0;
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testInt64SetMessageValueFail()
- {
- $arr = new MapField(GPBType::INT64, GPBType::INT64);
- $arr [0]= new TestMessage_Sub();
- }
-
#########################################################
# Test uint64 field.
#########################################################
@@ -339,42 +248,6 @@ class MapFieldTest extends PHPUnit_Framework_TestCase {
$this->assertEquals(0, count($arr));
}
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testUint64SetStringKeyFail()
- {
- $arr = new MapField(GPBType::UINT64, GPBType::UINT64);
- $arr ['abc']= 0;
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testUint64SetStringValueFail()
- {
- $arr = new MapField(GPBType::UINT64, GPBType::UINT64);
- $arr [0]= 'abc';
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testUint64SetMessageKeyFail()
- {
- $arr = new MapField(GPBType::UINT64, GPBType::UINT64);
- $arr [new TestMessage_Sub()]= 0;
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testUint64SetMessageValueFail()
- {
- $arr = new MapField(GPBType::UINT64, GPBType::UINT64);
- $arr [0]= new TestMessage_Sub();
- }
-
#########################################################
# Test float field.
#########################################################
@@ -397,24 +270,6 @@ class MapFieldTest extends PHPUnit_Framework_TestCase {
$this->assertEquals(4, count($arr));
}
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testFloatSetStringValueFail()
- {
- $arr = new MapField(GPBType::INT64, GPBType::FLOAT);
- $arr [0]= 'abc';
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testFloatSetMessageValueFail()
- {
- $arr = new MapField(GPBType::INT64, GPBType::FLOAT);
- $arr [0]= new TestMessage_Sub();
- }
-
#########################################################
# Test double field.
#########################################################
@@ -437,24 +292,6 @@ class MapFieldTest extends PHPUnit_Framework_TestCase {
$this->assertEquals(4, count($arr));
}
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testDoubleSetStringValueFail()
- {
- $arr = new MapField(GPBType::INT64, GPBType::DOUBLE);
- $arr [0]= 'abc';
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testDoubleSetMessageValueFail()
- {
- $arr = new MapField(GPBType::INT64, GPBType::DOUBLE);
- $arr [0]= new TestMessage_Sub();
- }
-
#########################################################
# Test bool field.
#########################################################
@@ -515,24 +352,6 @@ class MapFieldTest extends PHPUnit_Framework_TestCase {
$this->assertEquals(0, count($arr));
}
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testBoolSetMessageKeyFail()
- {
- $arr = new MapField(GPBType::BOOL, GPBType::BOOL);
- $arr [new TestMessage_Sub()]= true;
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testBoolSetMessageValueFail()
- {
- $arr = new MapField(GPBType::BOOL, GPBType::BOOL);
- $arr [true]= new TestMessage_Sub();
- }
-
#########################################################
# Test string field.
#########################################################
@@ -564,42 +383,23 @@ class MapFieldTest extends PHPUnit_Framework_TestCase {
$this->assertEquals(1, count($arr));
unset($arr[True]);
$this->assertEquals(0, count($arr));
- }
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testStringSetInvalidUTF8KeyFail()
- {
+ // Test foreach.
$arr = new MapField(GPBType::STRING, GPBType::STRING);
- $arr[hex2bin("ff")]= 'abc';
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testStringSetInvalidUTF8ValueFail()
- {
- $arr = new MapField(GPBType::STRING, GPBType::STRING);
- $arr ['abc']= hex2bin("ff");
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testStringSetMessageKeyFail()
- {
- $arr = new MapField(GPBType::STRING, GPBType::STRING);
- $arr [new TestMessage_Sub()]= 'abc';
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testStringSetMessageValueFail()
- {
- $arr = new MapField(GPBType::STRING, GPBType::STRING);
- $arr ['abc']= new TestMessage_Sub();
+ for ($i = 0; $i < 3; $i++) {
+ $arr[$i] = $i;
+ }
+ $i = 0;
+ $arr_test = [];
+ foreach ($arr as $key => $val) {
+ $this->assertSame($key, $val);
+ $arr_test[] = $key;
+ $i++;
+ }
+ $this->assertTrue(isset($arr_test['0']));
+ $this->assertTrue(isset($arr_test['1']));
+ $this->assertTrue(isset($arr_test['2']));
+ $this->assertSame(3, $i);
}
#########################################################
@@ -616,41 +416,30 @@ class MapFieldTest extends PHPUnit_Framework_TestCase {
$arr[0] = $sub_m;
$this->assertSame(1, $arr[0]->getA());
- $null = NULL;
- $arr[1] = $null;
- $this->assertNull($arr[1]);
-
- $this->assertEquals(2, count($arr));
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testMessageSetIntValueFail()
- {
- $arr =
- new MapField(GPBType::INT32, GPBType::MESSAGE, TestMessage::class);
- $arr[0] = 0;
- }
-
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testMessageSetStringValueFail()
- {
- $arr =
- new MapField(GPBType::INT32, GPBType::MESSAGE, TestMessage::class);
- $arr[0] = 'abc';
- }
+ $this->assertEquals(1, count($arr));
- /**
- * @expectedException PHPUnit_Framework_Error
- */
- public function testMessageSetOtherMessageValueFail()
- {
- $arr =
- new MapField(GPBType::INT32, GPBType::MESSAGE, TestMessage::class);
- $arr[0] = new TestMessage_Sub();
+ // Test foreach.
+ $arr = new MapField(GPBType::INT32,
+ GPBType::MESSAGE, TestMessage_Sub::class);
+ for ($i = 0; $i < 3; $i++) {
+ $arr[$i] = new TestMessage_Sub();;
+ $arr[$i]->setA($i);
+ }
+ $i = 0;
+ $key_test = [];
+ $value_test = [];
+ foreach ($arr as $key => $val) {
+ $key_test[] = $key;
+ $value_test[] = $val->getA();
+ $i++;
+ }
+ $this->assertTrue(isset($key_test['0']));
+ $this->assertTrue(isset($key_test['1']));
+ $this->assertTrue(isset($key_test['2']));
+ $this->assertTrue(isset($value_test['0']));
+ $this->assertTrue(isset($value_test['1']));
+ $this->assertTrue(isset($value_test['2']));
+ $this->assertSame(3, $i);
}
#########################################################
@@ -662,7 +451,7 @@ class MapFieldTest extends PHPUnit_Framework_TestCase {
// {
// $arr = new MapField(GPBType::INT32,
// GPBType::MESSAGE, TestMessage::class);
- // $arr [0]= new TestMessage;
+ // $arr[0] = new TestMessage;
// $arr[0]->SetMapRecursive($arr);
// // Clean up memory before test.
diff --git a/php/tests/memory_leak_test.php b/php/tests/memory_leak_test.php
index af327273..b76c8bff 100644
--- a/php/tests/memory_leak_test.php
+++ b/php/tests/memory_leak_test.php
@@ -2,15 +2,36 @@
# phpunit has memory leak by itself. Thus, it cannot be used to test memory leak.
+require_once('generated/NoNamespaceEnum.php');
+require_once('generated/NoNamespaceMessage.php');
+require_once('generated/NoNamespaceMessage_NestedEnum.php');
+require_once('generated/PrefixEmpty.php');
+require_once('generated/PrefixTestPrefix.php');
+require_once('generated/TestEmptyNamespace.php');
require_once('generated/Bar/TestInclude.php');
+require_once('generated/Foo/PBARRAY.php');
+require_once('generated/Foo/PBEmpty.php');
require_once('generated/Foo/TestEnum.php');
+require_once('generated/Foo/TestIncludeNamespaceMessage.php');
+require_once('generated/Foo/TestIncludePrefixMessage.php');
require_once('generated/Foo/TestMessage.php');
+require_once('generated/Foo/TestMessage_Empty.php');
+require_once('generated/Foo/TestMessage_NestedEnum.php');
require_once('generated/Foo/TestMessage_Sub.php');
require_once('generated/Foo/TestPackedMessage.php');
require_once('generated/Foo/TestPhpDoc.php');
+require_once('generated/Foo/TestRandomFieldOrder.php');
+require_once('generated/Foo/TestReverseFieldOrder.php');
require_once('generated/Foo/TestUnpackedMessage.php');
+require_once('generated/Foo/testLowerCaseMessage.php');
+require_once('generated/Foo/testLowerCaseEnum.php');
require_once('generated/GPBMetadata/Proto/Test.php');
+require_once('generated/GPBMetadata/Proto/TestEmptyPhpNamespace.php');
require_once('generated/GPBMetadata/Proto/TestInclude.php');
+require_once('generated/GPBMetadata/Proto/TestNoNamespace.php');
+require_once('generated/GPBMetadata/Proto/TestPhpNamespace.php');
+require_once('generated/GPBMetadata/Proto/TestPrefix.php');
+require_once('generated/Php/Test/TestNamespace.php');
require_once('test_util.php');
use Google\Protobuf\Internal\RepeatedField;
@@ -22,17 +43,17 @@ $from = new TestMessage();
TestUtil::setTestMessage($from);
TestUtil::assertTestMessage($from);
-$data = $from->encode();
+$data = $from->serializeToString();
$to = new TestMessage();
-$to->decode($data);
+$to->mergeFromString($data);
TestUtil::assertTestMessage($to);
$from->setRecursive($from);
$arr = new RepeatedField(GPBType::MESSAGE, TestMessage::class);
-$arr []= new TestMessage;
+$arr[] = new TestMessage;
$arr[0]->SetRepeatedRecursive($arr);
// Test oneof fields.
@@ -43,9 +64,9 @@ assert(1 === $m->getOneofInt32());
assert(0.0 === $m->getOneofFloat());
assert('' === $m->getOneofString());
assert(NULL === $m->getOneofMessage());
-$data = $m->encode();
+$data = $m->serializeToString();
$n = new TestMessage();
-$n->decode($data);
+$n->mergeFromString($data);
assert(1 === $n->getOneofInt32());
$m->setOneofFloat(2.0);
@@ -53,9 +74,9 @@ assert(0 === $m->getOneofInt32());
assert(2.0 === $m->getOneofFloat());
assert('' === $m->getOneofString());
assert(NULL === $m->getOneofMessage());
-$data = $m->encode();
+$data = $m->serializeToString();
$n = new TestMessage();
-$n->decode($data);
+$n->mergeFromString($data);
assert(2.0 === $n->getOneofFloat());
$m->setOneofString('abc');
@@ -63,9 +84,9 @@ assert(0 === $m->getOneofInt32());
assert(0.0 === $m->getOneofFloat());
assert('abc' === $m->getOneofString());
assert(NULL === $m->getOneofMessage());
-$data = $m->encode();
+$data = $m->serializeToString();
$n = new TestMessage();
-$n->decode($data);
+$n->mergeFromString($data);
assert('abc' === $n->getOneofString());
$sub_m = new TestMessage_Sub();
@@ -75,7 +96,17 @@ assert(0 === $m->getOneofInt32());
assert(0.0 === $m->getOneofFloat());
assert('' === $m->getOneofString());
assert(1 === $m->getOneofMessage()->getA());
-$data = $m->encode();
+$data = $m->serializeToString();
$n = new TestMessage();
-$n->decode($data);
+$n->mergeFromString($data);
assert(1 === $n->getOneofMessage()->getA());
+
+$m = new TestMessage();
+$m->mergeFromString(hex2bin('F80601'));
+assert('F80601', bin2hex($m->serializeToString()));
+
+# $from = new TestMessage();
+# $to = new TestMessage();
+# TestUtil::setTestMessage($from);
+# $to->mergeFrom($from);
+# TestUtil::assertTestMessage($to);
diff --git a/php/tests/php_implementation_test.php b/php/tests/php_implementation_test.php
index 4f626f1c..5dbc9233 100644
--- a/php/tests/php_implementation_test.php
+++ b/php/tests/php_implementation_test.php
@@ -6,12 +6,12 @@ require_once('test_util.php');
use Foo\TestMessage;
use Foo\TestMessage_Sub;
use Foo\TestPackedMessage;
-use Google\Protobuf\Internal\InputStream;
+use Google\Protobuf\Internal\CodedInputStream;
use Google\Protobuf\Internal\FileDescriptorSet;
use Google\Protobuf\Internal\GPBLabel;
use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\GPBWire;
-use Google\Protobuf\Internal\OutputStream;
+use Google\Protobuf\Internal\CodedOutputStream;
class ImplementationTest extends TestBase
{
@@ -21,17 +21,17 @@ class ImplementationTest extends TestBase
$value = null;
// Positive number.
- $input = new InputStream(hex2bin("01"));
+ $input = new CodedInputStream(hex2bin("01"));
GPBWire::readInt32($input, $value);
$this->assertSame(1, $value);
// Negative number.
- $input = new InputStream(hex2bin("ffffffff0f"));
+ $input = new CodedInputStream(hex2bin("ffffffff0f"));
GPBWire::readInt32($input, $value);
$this->assertSame(-1, $value);
// Discard overflow bits.
- $input = new InputStream(hex2bin("ffffffff7f"));
+ $input = new CodedInputStream(hex2bin("ffffffff7f"));
GPBWire::readInt32($input, $value);
$this->assertSame(-1, $value);
}
@@ -41,17 +41,17 @@ class ImplementationTest extends TestBase
$value = null;
// Positive number.
- $input = new InputStream(hex2bin("01"));
+ $input = new CodedInputStream(hex2bin("01"));
GPBWire::readUint32($input, $value);
$this->assertSame(1, $value);
// Max uint32.
- $input = new InputStream(hex2bin("ffffffff0f"));
+ $input = new CodedInputStream(hex2bin("ffffffff0f"));
GPBWire::readUint32($input, $value);
$this->assertSame(-1, $value);
// Discard overflow bits.
- $input = new InputStream(hex2bin("ffffffff7f"));
+ $input = new CodedInputStream(hex2bin("ffffffff7f"));
GPBWire::readUint32($input, $value);
$this->assertSame(-1, $value);
}
@@ -61,17 +61,17 @@ class ImplementationTest extends TestBase
$value = null;
// Positive number.
- $input = new InputStream(hex2bin("01"));
+ $input = new CodedInputStream(hex2bin("01"));
GPBWire::readInt64($input, $value);
$this->assertEquals(1, $value);
// Negative number.
- $input = new InputStream(hex2bin("ffffffffffffffffff01"));
+ $input = new CodedInputStream(hex2bin("ffffffffffffffffff01"));
GPBWire::readInt64($input, $value);
$this->assertEquals(-1, $value);
// Discard overflow bits.
- $input = new InputStream(hex2bin("ffffffffffffffffff0f"));
+ $input = new CodedInputStream(hex2bin("ffffffffffffffffff0f"));
GPBWire::readInt64($input, $value);
$this->assertEquals(-1, $value);
}
@@ -81,17 +81,17 @@ class ImplementationTest extends TestBase
$value = null;
// Positive number.
- $input = new InputStream(hex2bin("01"));
+ $input = new CodedInputStream(hex2bin("01"));
GPBWire::readUint64($input, $value);
$this->assertEquals(1, $value);
// Negative number.
- $input = new InputStream(hex2bin("FFFFFFFFFFFFFFFFFF01"));
+ $input = new CodedInputStream(hex2bin("FFFFFFFFFFFFFFFFFF01"));
GPBWire::readUint64($input, $value);
$this->assertEquals(-1, $value);
// Discard overflow bits.
- $input = new InputStream(hex2bin("FFFFFFFFFFFFFFFFFF0F"));
+ $input = new CodedInputStream(hex2bin("FFFFFFFFFFFFFFFFFF0F"));
GPBWire::readUint64($input, $value);
$this->assertEquals(-1, $value);
}
@@ -100,15 +100,15 @@ class ImplementationTest extends TestBase
{
$value = null;
- $input = new InputStream(hex2bin("00"));
+ $input = new CodedInputStream(hex2bin("00"));
GPBWire::readSint32($input, $value);
$this->assertSame(0, $value);
- $input = new InputStream(hex2bin("01"));
+ $input = new CodedInputStream(hex2bin("01"));
GPBWire::readSint32($input, $value);
$this->assertSame(-1, $value);
- $input = new InputStream(hex2bin("02"));
+ $input = new CodedInputStream(hex2bin("02"));
GPBWire::readSint32($input, $value);
$this->assertSame(1, $value);
}
@@ -117,15 +117,15 @@ class ImplementationTest extends TestBase
{
$value = null;
- $input = new InputStream(hex2bin("00"));
+ $input = new CodedInputStream(hex2bin("00"));
GPBWire::readSint64($input, $value);
$this->assertEquals(0, $value);
- $input = new InputStream(hex2bin("01"));
+ $input = new CodedInputStream(hex2bin("01"));
GPBWire::readSint64($input, $value);
$this->assertEquals(-1, $value);
- $input = new InputStream(hex2bin("02"));
+ $input = new CodedInputStream(hex2bin("02"));
GPBWire::readSint64($input, $value);
$this->assertEquals(1, $value);
}
@@ -133,7 +133,7 @@ class ImplementationTest extends TestBase
public function testReadFixed32()
{
$value = null;
- $input = new InputStream(hex2bin("12345678"));
+ $input = new CodedInputStream(hex2bin("12345678"));
GPBWire::readFixed32($input, $value);
$this->assertSame(0x78563412, $value);
}
@@ -141,7 +141,7 @@ class ImplementationTest extends TestBase
public function testReadFixed64()
{
$value = null;
- $input = new InputStream(hex2bin("1234567812345678"));
+ $input = new CodedInputStream(hex2bin("1234567812345678"));
GPBWire::readFixed64($input, $value);
if (PHP_INT_SIZE == 4) {
$this->assertSame("8671175386481439762", $value);
@@ -153,7 +153,7 @@ class ImplementationTest extends TestBase
public function testReadSfixed32()
{
$value = null;
- $input = new InputStream(hex2bin("12345678"));
+ $input = new CodedInputStream(hex2bin("12345678"));
GPBWire::readSfixed32($input, $value);
$this->assertSame(0x78563412, $value);
}
@@ -161,7 +161,7 @@ class ImplementationTest extends TestBase
public function testReadFloat()
{
$value = null;
- $input = new InputStream(hex2bin("0000803F"));
+ $input = new CodedInputStream(hex2bin("0000803F"));
GPBWire::readFloat($input, $value);
$this->assertSame(1.0, $value);
}
@@ -170,11 +170,11 @@ class ImplementationTest extends TestBase
{
$value = null;
- $input = new InputStream(hex2bin("00"));
+ $input = new CodedInputStream(hex2bin("00"));
GPBWire::readBool($input, $value);
$this->assertSame(false, $value);
- $input = new InputStream(hex2bin("01"));
+ $input = new CodedInputStream(hex2bin("01"));
GPBWire::readBool($input, $value);
$this->assertSame(true, $value);
}
@@ -182,7 +182,7 @@ class ImplementationTest extends TestBase
public function testReadDouble()
{
$value = null;
- $input = new InputStream(hex2bin("000000000000F03F"));
+ $input = new CodedInputStream(hex2bin("000000000000F03F"));
GPBWire::readDouble($input, $value);
$this->assertSame(1.0, $value);
}
@@ -190,7 +190,7 @@ class ImplementationTest extends TestBase
public function testReadSfixed64()
{
$value = null;
- $input = new InputStream(hex2bin("1234567812345678"));
+ $input = new CodedInputStream(hex2bin("1234567812345678"));
GPBWire::readSfixed64($input, $value);
if (PHP_INT_SIZE == 4) {
$this->assertSame("8671175386481439762", $value);
@@ -207,8 +207,7 @@ class ImplementationTest extends TestBase
$this->assertSame(3, GPBWire::zigZagEncode32(-2));
$this->assertSame(0x7FFFFFFE, GPBWire::zigZagEncode32(0x3FFFFFFF));
$this->assertSame(0x7FFFFFFF, GPBWire::zigZagEncode32(0xC0000000));
- $this->assertSame(-2, GPBWire::zigZagEncode32(0x7FFFFFFF));
- $this->assertSame(-1, GPBWire::zigZagEncode32(0x80000000));
+ $this->assertSame(0x7FFFFFFF, GPBWire::zigZagEncode32(-1073741824));
$this->assertSame(0, GPBWire::zigZagDecode32(0));
$this->assertSame(-1, GPBWire::zigZagDecode32(1));
@@ -220,6 +219,8 @@ class ImplementationTest extends TestBase
$this->assertSame((int)-2147483648,GPBWire::zigZagDecode32(0xFFFFFFFF));
if (PHP_INT_SIZE == 4) {
+ $this->assertSame(-2, GPBWire::zigZagEncode32(0x7FFFFFFF));
+ $this->assertSame(-1, GPBWire::zigZagEncode32(0x80000000));
$this->assertSame('0', GPBWire::zigZagEncode64(0));
$this->assertSame('1', GPBWire::zigZagEncode64(-1));
$this->assertSame('2', GPBWire::zigZagEncode64(1));
@@ -250,6 +251,8 @@ class ImplementationTest extends TestBase
$this->assertSame('1', GPBWire::zigZagDecode64(2));
$this->assertSame('-2', GPBWire::zigZagDecode64(3));
} else {
+ $this->assertSame(4294967294, GPBWire::zigZagEncode32(0x7FFFFFFF));
+ $this->assertSame(4294967295, GPBWire::zigZagEncode32(0x80000000));
$this->assertSame(0, GPBWire::zigZagEncode64(0));
$this->assertSame(1, GPBWire::zigZagEncode64(-1));
$this->assertSame(2, GPBWire::zigZagEncode64(1));
@@ -290,14 +293,14 @@ class ImplementationTest extends TestBase
public function testDecode()
{
$m = new TestMessage();
- $m->decode(TestUtil::getGoldenTestMessage());
+ $m->mergeFromString(TestUtil::getGoldenTestMessage());
TestUtil::assertTestMessage($m);
}
public function testDescriptorDecode()
{
$file_desc_set = new FileDescriptorSet();
- $file_desc_set->decode(hex2bin(
+ $file_desc_set->mergeFromString(hex2bin(
"0a3b0a12746573745f696e636c7564652e70726f746f120362617222180a" .
"0b54657374496e636c75646512090a0161180120012805620670726f746f33"));
@@ -330,19 +333,19 @@ class ImplementationTest extends TestBase
$var = 0;
// Empty buffer.
- $input = new InputStream(hex2bin(''));
+ $input = new CodedInputStream(hex2bin(''));
$this->assertFalse($input->readVarint64($var));
// The largest varint is 10 bytes long.
- $input = new InputStream(hex2bin('8080808080808080808001'));
+ $input = new CodedInputStream(hex2bin('8080808080808080808001'));
$this->assertFalse($input->readVarint64($var));
// Corrupted varint.
- $input = new InputStream(hex2bin('808080'));
+ $input = new CodedInputStream(hex2bin('808080'));
$this->assertFalse($input->readVarint64($var));
// Normal case.
- $input = new InputStream(hex2bin('808001'));
+ $input = new CodedInputStream(hex2bin('808001'));
$this->assertTrue($input->readVarint64($var));
if (PHP_INT_SIZE == 4) {
$this->assertSame('16384', $var);
@@ -352,7 +355,7 @@ class ImplementationTest extends TestBase
$this->assertFalse($input->readVarint64($var));
// Read two varint.
- $input = new InputStream(hex2bin('808001808002'));
+ $input = new CodedInputStream(hex2bin('808001808002'));
$this->assertTrue($input->readVarint64($var));
if (PHP_INT_SIZE == 4) {
$this->assertSame('16384', $var);
@@ -366,6 +369,34 @@ class ImplementationTest extends TestBase
$this->assertSame(32768, $var);
}
$this->assertFalse($input->readVarint64($var));
+
+ // Read 64 testing
+ $testVals = array(
+ '10' => '0a000000000000000000',
+ '100' => '64000000000000000000',
+ '800' => 'a0060000000000000000',
+ '6400' => '80320000000000000000',
+ '70400' => '80a60400000000000000',
+ '774400' => '80a22f00000000000000',
+ '9292800' => '8098b704000000000000',
+ '74342400' => '80c0b923000000000000',
+ '743424000' => '8080bfe2020000000000',
+ '8177664000' => '8080b5bb1e0000000000',
+ '65421312000' => '8080a8dbf30100000000',
+ '785055744000' => '8080e0c7ec1600000000',
+ '9420668928000' => '808080dd969202000000',
+ '103627358208000' => '808080fff9c717000000',
+ '1139900940288000' => '808080f5bd9783020000',
+ '13678811283456000' => '808080fce699a6180000',
+ '109430490267648000' => '808080e0b7ceb1c20100',
+ '984874412408832000' => '808080e0f5c1bed50d00',
+ );
+
+ foreach ($testVals as $original => $encoded) {
+ $input = new CodedInputStream(hex2bin($encoded));
+ $this->assertTrue($input->readVarint64($var));
+ $this->assertEquals($original, $var);
+ }
}
public function testReadVarint32()
@@ -373,25 +404,25 @@ class ImplementationTest extends TestBase
$var = 0;
// Empty buffer.
- $input = new InputStream(hex2bin(''));
+ $input = new CodedInputStream(hex2bin(''));
$this->assertFalse($input->readVarint32($var));
// The largest varint is 10 bytes long.
- $input = new InputStream(hex2bin('8080808080808080808001'));
+ $input = new CodedInputStream(hex2bin('8080808080808080808001'));
$this->assertFalse($input->readVarint32($var));
// Corrupted varint.
- $input = new InputStream(hex2bin('808080'));
+ $input = new CodedInputStream(hex2bin('808080'));
$this->assertFalse($input->readVarint32($var));
// Normal case.
- $input = new InputStream(hex2bin('808001'));
+ $input = new CodedInputStream(hex2bin('808001'));
$this->assertTrue($input->readVarint32($var));
$this->assertSame(16384, $var);
$this->assertFalse($input->readVarint32($var));
// Read two varint.
- $input = new InputStream(hex2bin('808001808002'));
+ $input = new CodedInputStream(hex2bin('808001808002'));
$this->assertTrue($input->readVarint32($var));
$this->assertSame(16384, $var);
$this->assertTrue($input->readVarint32($var));
@@ -399,7 +430,7 @@ class ImplementationTest extends TestBase
$this->assertFalse($input->readVarint32($var));
// Read a 64-bit integer. High-order bits should be discarded.
- $input = new InputStream(hex2bin('808081808001'));
+ $input = new CodedInputStream(hex2bin('808081808001'));
$this->assertTrue($input->readVarint32($var));
$this->assertSame(16384, $var);
$this->assertFalse($input->readVarint32($var));
@@ -407,7 +438,7 @@ class ImplementationTest extends TestBase
public function testReadTag()
{
- $input = new InputStream(hex2bin('808001'));
+ $input = new CodedInputStream(hex2bin('808001'));
$tag = $input->readTag();
$this->assertSame(16384, $tag);
$tag = $input->readTag();
@@ -416,7 +447,7 @@ class ImplementationTest extends TestBase
public function testPushPopLimit()
{
- $input = new InputStream(hex2bin('808001'));
+ $input = new CodedInputStream(hex2bin('808001'));
$old_limit = $input->pushLimit(0);
$tag = $input->readTag();
$this->assertSame(0, $tag);
@@ -427,7 +458,7 @@ class ImplementationTest extends TestBase
public function testReadRaw()
{
- $input = new InputStream(hex2bin('808001'));
+ $input = new CodedInputStream(hex2bin('808001'));
$buffer = null;
$this->assertTrue($input->readRaw(3, $buffer));
@@ -438,28 +469,33 @@ class ImplementationTest extends TestBase
public function testWriteVarint32()
{
- $output = new OutputStream(3);
- $output->writeVarint32(16384);
+ $output = new CodedOutputStream(3);
+ $output->writeVarint32(16384, true);
$this->assertSame(hex2bin('808001'), $output->getData());
+
+ // Negative numbers are padded to be compatible with int64.
+ $output = new CodedOutputStream(10);
+ $output->writeVarint32(-43, false);
+ $this->assertSame(hex2bin('D5FFFFFFFFFFFFFFFF01'), $output->getData());
}
public function testWriteVarint64()
{
- $output = new OutputStream(10);
+ $output = new CodedOutputStream(10);
$output->writeVarint64(-43);
$this->assertSame(hex2bin('D5FFFFFFFFFFFFFFFF01'), $output->getData());
}
public function testWriteLittleEndian32()
{
- $output = new OutputStream(4);
+ $output = new CodedOutputStream(4);
$output->writeLittleEndian32(46);
$this->assertSame(hex2bin('2E000000'), $output->getData());
}
public function testWriteLittleEndian64()
{
- $output = new OutputStream(8);
+ $output = new CodedOutputStream(8);
$output->writeLittleEndian64(47);
$this->assertSame(hex2bin('2F00000000000000'), $output->getData());
}
@@ -468,13 +504,13 @@ class ImplementationTest extends TestBase
{
$m = new TestMessage();
TestUtil::setTestMessage($m);
- $this->assertSame(447, $m->byteSize());
+ $this->assertSame(506, $m->byteSize());
}
public function testPackedByteSize()
{
$m = new TestPackedMessage();
TestUtil::setTestPackedMessage($m);
- $this->assertSame(156, $m->byteSize());
+ $this->assertSame(166, $m->byteSize());
}
}
diff --git a/php/tests/proto/test.proto b/php/tests/proto/test.proto
index fc283a05..d0109d83 100644
--- a/php/tests/proto/test.proto
+++ b/php/tests/proto/test.proto
@@ -1,6 +1,10 @@
syntax = "proto3";
import 'proto/test_include.proto';
+import 'proto/test_no_namespace.proto';
+import 'proto/test_php_namespace.proto';
+import 'proto/test_empty_php_namespace.proto';
+import 'proto/test_prefix.proto';
package foo;
@@ -90,14 +94,45 @@ message TestMessage {
message Sub {
int32 a = 1;
+ repeated int32 b = 2;
}
- // NestedMessage nested_message = 90;
+ // Reserved for non-existing field test.
+ // int32 non_exist = 89;
+
+ NoNamespaceMessage optional_no_namespace_message = 91;
+ NoNamespaceEnum optional_no_namespace_enum = 92;
+ repeated NoNamespaceMessage repeated_no_namespace_message = 93;
+ repeated NoNamespaceEnum repeated_no_namespace_enum = 94;
+
+ enum NestedEnum {
+ ZERO = 0;
+ }
+
+ NestedEnum optional_nested_enum = 101;
+
+ // Test prefix for reserved words.
+ message Empty {
+ int32 a = 1;
+ }
+
+ reserved 111;
}
enum TestEnum {
ZERO = 0;
ONE = 1;
+ TWO = 2;
+ ECHO = 3; // Test reserved name.
+}
+
+// Test prefix for reserved words.
+message Empty {
+ int32 a = 1;
+}
+
+message ARRAY {
+ int32 a = 1;
}
message TestPackedMessage {
@@ -139,3 +174,30 @@ message TestUnpackedMessage {
message TestPhpDoc {
int32 a = 1;
}
+
+message TestIncludePrefixMessage {
+ TestPrefix prefix_message = 1;
+}
+
+message TestIncludeNamespaceMessage {
+ TestNamespace namespace_message = 1;
+ TestEmptyNamespace empty_namespace_message = 2;
+}
+
+// This will cause upb fields not ordered by the order in the generated code.
+message TestRandomFieldOrder {
+ int64 tag13 = 150;
+ string tag14 = 160;
+}
+
+message TestReverseFieldOrder {
+ repeated int32 a = 2;
+ string b = 1;
+}
+
+message testLowerCaseMessage {
+}
+
+enum testLowerCaseEnum {
+ VALUE = 0;
+}
diff --git a/php/tests/proto/test_descriptors.proto b/php/tests/proto/test_descriptors.proto
new file mode 100644
index 00000000..d42aec7c
--- /dev/null
+++ b/php/tests/proto/test_descriptors.proto
@@ -0,0 +1,35 @@
+syntax = "proto3";
+
+package descriptors;
+
+message TestDescriptorsMessage {
+ int32 optional_int32 = 1;
+ TestDescriptorsEnum optional_enum = 16;
+ Sub optional_message = 17;
+
+ // Repeated
+ repeated int32 repeated_int32 = 31;
+ repeated Sub repeated_message = 47;
+
+ oneof my_oneof {
+ int32 oneof_int32 = 51;
+ }
+
+ map<int32, EnumSub> map_int32_enum = 71;
+
+ message Sub {
+ int32 a = 1;
+ repeated int32 b = 2;
+ }
+
+ enum EnumSub {
+ ZERO = 0;
+ ONE = 1;
+ }
+}
+
+enum TestDescriptorsEnum {
+ ZERO = 0;
+ ONE = 1;
+}
+
diff --git a/php/tests/proto/test_empty_php_namespace.proto b/php/tests/proto/test_empty_php_namespace.proto
new file mode 100644
index 00000000..7b4bc74d
--- /dev/null
+++ b/php/tests/proto/test_empty_php_namespace.proto
@@ -0,0 +1,8 @@
+syntax = "proto3";
+
+package foo;
+option php_namespace = "";
+
+message TestEmptyNamespace {
+ int32 a = 1;
+}
diff --git a/php/tests/proto/test_import_descriptor_proto.proto b/php/tests/proto/test_import_descriptor_proto.proto
new file mode 100644
index 00000000..2a19940d
--- /dev/null
+++ b/php/tests/proto/test_import_descriptor_proto.proto
@@ -0,0 +1,14 @@
+syntax = "proto3";
+
+import "google/protobuf/descriptor.proto";
+
+message TestImportDescriptorProto {
+ extend google.protobuf.MethodOptions {
+ int32 a = 72295727;
+ }
+}
+
+extend google.protobuf.MethodOptions {
+ int32 a = 72295728;
+}
+
diff --git a/php/tests/proto/test_no_namespace.proto b/php/tests/proto/test_no_namespace.proto
index 4331aeab..58f13d47 100644
--- a/php/tests/proto/test_no_namespace.proto
+++ b/php/tests/proto/test_no_namespace.proto
@@ -1,5 +1,16 @@
syntax = "proto3";
-message NoNameSpace {
+message NoNamespaceMessage {
int32 a = 1;
+
+ enum NestedEnum {
+ ZERO = 0;
+ }
+ NestedEnum b = 2;
+ repeated NestedEnum c = 3;
+}
+
+enum NoNamespaceEnum {
+ VALUE_A = 0;
+ VALUE_B = 1;
}
diff --git a/php/tests/proto/test_php_namespace.proto b/php/tests/proto/test_php_namespace.proto
new file mode 100644
index 00000000..713187b9
--- /dev/null
+++ b/php/tests/proto/test_php_namespace.proto
@@ -0,0 +1,8 @@
+syntax = "proto3";
+
+package foo;
+option php_namespace = "Php\\Test";
+
+message TestNamespace {
+ int32 a = 1;
+}
diff --git a/php/tests/proto/test_prefix.proto b/php/tests/proto/test_prefix.proto
new file mode 100644
index 00000000..9bfbad7f
--- /dev/null
+++ b/php/tests/proto/test_prefix.proto
@@ -0,0 +1,12 @@
+syntax = "proto3";
+
+option php_class_prefix = "Prefix";
+
+message TestPrefix {
+ int32 a = 1;
+}
+
+// Test prefix for reserved words.
+message Empty {
+ int32 a = 1;
+}
diff --git a/php/tests/proto/test_reserved_enum_lower.proto b/php/tests/proto/test_reserved_enum_lower.proto
new file mode 100644
index 00000000..d2daeaff
--- /dev/null
+++ b/php/tests/proto/test_reserved_enum_lower.proto
@@ -0,0 +1,77 @@
+syntax = "proto3";
+
+package lower_enum;
+
+enum abstract { ZERO1 = 0; }
+enum and { ZERO2 = 0; }
+enum array { ZERO3 = 0; }
+enum as { ZERO4 = 0; }
+enum break { ZERO5 = 0; }
+enum callable { ZERO6 = 0; }
+enum case { ZERO7 = 0; }
+enum catch { ZERO8 = 0; }
+enum class { ZERO9 = 0; }
+enum clone { ZERO10 = 0; }
+enum const { ZERO11 = 0; }
+enum continue { ZERO12 = 0; }
+enum declare { ZERO13 = 0; }
+enum default { ZERO14 = 0; }
+enum die { ZERO15 = 0; }
+enum do { ZERO16 = 0; }
+enum echo { ZERO17 = 0; }
+enum else { ZERO18 = 0; }
+enum elseif { ZERO19 = 0; }
+enum empty { ZERO20 = 0; }
+enum enddeclare { ZERO21 = 0; }
+enum endfor { ZERO22 = 0; }
+enum endforeach { ZERO23 = 0; }
+enum endif { ZERO24 = 0; }
+enum endswitch { ZERO25 = 0; }
+enum endwhile { ZERO26 = 0; }
+enum eval { ZERO27 = 0; }
+enum exit { ZERO28 = 0; }
+enum extends { ZERO29 = 0; }
+enum final { ZERO30 = 0; }
+enum for { ZERO31 = 0; }
+enum foreach { ZERO32 = 0; }
+enum function { ZERO33 = 0; }
+enum global { ZERO34 = 0; }
+enum goto { ZERO35 = 0; }
+enum if { ZERO36 = 0; }
+enum implements { ZERO37 = 0; }
+enum include { ZERO38 = 0; }
+enum include_once { ZERO39 = 0; }
+enum instanceof { ZERO40 = 0; }
+enum insteadof { ZERO41 = 0; }
+enum interface { ZERO42 = 0; }
+enum isset { ZERO43 = 0; }
+enum list { ZERO44 = 0; }
+enum namespace { ZERO45 = 0; }
+enum new { ZERO46 = 0; }
+enum or { ZERO47 = 0; }
+enum print { ZERO48 = 0; }
+enum private { ZERO49 = 0; }
+enum protected { ZERO50 = 0; }
+enum public { ZERO51 = 0; }
+enum require { ZERO52 = 0; }
+enum require_once { ZERO53 = 0; }
+enum return { ZERO54 = 0; }
+enum static { ZERO55 = 0; }
+enum switch { ZERO56 = 0; }
+enum throw { ZERO57 = 0; }
+enum trait { ZERO58 = 0; }
+enum try { ZERO59 = 0; }
+enum unset { ZERO60 = 0; }
+enum use { ZERO61 = 0; }
+enum var { ZERO62 = 0; }
+enum while { ZERO63 = 0; }
+enum xor { ZERO64 = 0; }
+enum int { ZERO65 = 0; }
+enum float { ZERO66 = 0; }
+enum bool { ZERO67 = 0; }
+enum string { ZERO68 = 0; }
+enum true { ZERO69 = 0; }
+enum false { ZERO70 = 0; }
+enum null { ZERO71 = 0; }
+enum void { ZERO72 = 0; }
+enum iterable { ZERO73 = 0; }
diff --git a/php/tests/proto/test_reserved_enum_upper.proto b/php/tests/proto/test_reserved_enum_upper.proto
new file mode 100644
index 00000000..a396fea3
--- /dev/null
+++ b/php/tests/proto/test_reserved_enum_upper.proto
@@ -0,0 +1,77 @@
+syntax = "proto3";
+
+package upper_enum;
+
+enum ABSTRACT { ZERO1 = 0; }
+enum AND { ZERO2 = 0; }
+enum ARRAY { ZERO3 = 0; }
+enum AS { ZERO4 = 0; }
+enum BREAK { ZERO5 = 0; }
+enum CALLABLE { ZERO6 = 0; }
+enum CASE { ZERO7 = 0; }
+enum CATCH { ZERO8 = 0; }
+enum CLASS { ZERO9 = 0; }
+enum CLONE { ZERO10 = 0; }
+enum CONST { ZERO11 = 0; }
+enum CONTINUE { ZERO12 = 0; }
+enum DECLARE { ZERO13 = 0; }
+enum DEFAULT { ZERO14 = 0; }
+enum DIE { ZERO15 = 0; }
+enum DO { ZERO16 = 0; }
+enum ECHO { ZERO17 = 0; }
+enum ELSE { ZERO18 = 0; }
+enum ELSEIF { ZERO19 = 0; }
+enum EMPTY { ZERO20 = 0; }
+enum ENDDECLARE { ZERO21 = 0; }
+enum ENDFOR { ZERO22 = 0; }
+enum ENDFOREACH { ZERO23 = 0; }
+enum ENDIF { ZERO24 = 0; }
+enum ENDSWITCH { ZERO25 = 0; }
+enum ENDWHILE { ZERO26 = 0; }
+enum EVAL { ZERO27 = 0; }
+enum EXIT { ZERO28 = 0; }
+enum EXTENDS { ZERO29 = 0; }
+enum FINAL { ZERO30 = 0; }
+enum FOR { ZERO31 = 0; }
+enum FOREACH { ZERO32 = 0; }
+enum FUNCTION { ZERO33 = 0; }
+enum GLOBAL { ZERO34 = 0; }
+enum GOTO { ZERO35 = 0; }
+enum IF { ZERO36 = 0; }
+enum IMPLEMENTS { ZERO37 = 0; }
+enum INCLUDE { ZERO38 = 0; }
+enum INCLUDE_ONCE { ZERO39 = 0; }
+enum INSTANCEOF { ZERO40 = 0; }
+enum INSTEADOF { ZERO41 = 0; }
+enum INTERFACE { ZERO42 = 0; }
+enum ISSET { ZERO43 = 0; }
+enum LIST { ZERO44 = 0; }
+enum NAMESPACE { ZERO45 = 0; }
+enum NEW { ZERO46 = 0; }
+enum OR { ZERO47 = 0; }
+enum PRINT { ZERO48 = 0; }
+enum PRIVATE { ZERO49 = 0; }
+enum PROTECTED { ZERO50 = 0; }
+enum PUBLIC { ZERO51 = 0; }
+enum REQUIRE { ZERO52 = 0; }
+enum REQUIRE_ONCE { ZERO53 = 0; }
+enum RETURN { ZERO54 = 0; }
+enum STATIC { ZERO55 = 0; }
+enum SWITCH { ZERO56 = 0; }
+enum THROW { ZERO57 = 0; }
+enum TRAIT { ZERO58 = 0; }
+enum TRY { ZERO59 = 0; }
+enum UNSET { ZERO60 = 0; }
+enum USE { ZERO61 = 0; }
+enum VAR { ZERO62 = 0; }
+enum WHILE { ZERO63 = 0; }
+enum XOR { ZERO64 = 0; }
+enum INT { ZERO65 = 0; }
+enum FLOAT { ZERO66 = 0; }
+enum BOOL { ZERO67 = 0; }
+enum STRING { ZERO68 = 0; }
+enum TRUE { ZERO69 = 0; }
+enum FALSE { ZERO70 = 0; }
+enum NULL { ZERO71 = 0; }
+enum VOID { ZERO72 = 0; }
+enum ITERABLE { ZERO73 = 0; }
diff --git a/php/tests/proto/test_reserved_enum_value_lower.proto b/php/tests/proto/test_reserved_enum_value_lower.proto
new file mode 100644
index 00000000..96da319e
--- /dev/null
+++ b/php/tests/proto/test_reserved_enum_value_lower.proto
@@ -0,0 +1,79 @@
+syntax = "proto3";
+
+package lower_enum_value;
+
+enum NotAllowed {
+ abstract = 0;
+ and = 1;
+ array = 2;
+ as = 3;
+ break = 4;
+ callable = 5;
+ case = 6;
+ catch = 7;
+ class = 8;
+ clone = 9;
+ const = 10;
+ continue = 11;
+ declare = 12;
+ default = 13;
+ die = 14;
+ do = 15;
+ echo = 16;
+ else = 17;
+ elseif = 18;
+ empty = 19;
+ enddeclare = 20;
+ endfor = 21;
+ endforeach = 22;
+ endif = 23;
+ endswitch = 24;
+ endwhile = 25;
+ eval = 26;
+ exit = 27;
+ extends = 28;
+ final = 29;
+ for = 30;
+ foreach = 31;
+ function = 32;
+ global = 33;
+ goto = 34;
+ if = 35;
+ implements = 36;
+ include = 37;
+ include_once = 38;
+ instanceof = 39;
+ insteadof = 40;
+ interface = 41;
+ isset = 42;
+ list = 43;
+ namespace = 44;
+ new = 45;
+ or = 46;
+ print = 47;
+ private = 48;
+ protected = 49;
+ public = 50;
+ require = 51;
+ require_once = 52;
+ return = 53;
+ static = 54;
+ switch = 55;
+ throw = 56;
+ trait = 57;
+ try = 58;
+ unset = 59;
+ use = 60;
+ var = 61;
+ while = 62;
+ xor = 63;
+ int = 64;
+ float = 65;
+ bool = 66;
+ string = 67;
+ true = 68;
+ false = 69;
+ null = 70;
+ void = 71;
+ iterable = 72;
+}
diff --git a/php/tests/proto/test_reserved_enum_value_upper.proto b/php/tests/proto/test_reserved_enum_value_upper.proto
new file mode 100644
index 00000000..b026a858
--- /dev/null
+++ b/php/tests/proto/test_reserved_enum_value_upper.proto
@@ -0,0 +1,79 @@
+syntax = "proto3";
+
+package upper_enum_value;
+
+enum NotAllowed {
+ ABSTRACT = 0;
+ AND = 1;
+ ARRAY = 2;
+ AS = 3;
+ BREAK = 4;
+ CALLABLE = 5;
+ CASE = 6;
+ CATCH = 7;
+ CLASS = 8;
+ CLONE = 9;
+ CONST = 10;
+ CONTINUE = 11;
+ DECLARE = 12;
+ DEFAULT = 13;
+ DIE = 14;
+ DO = 15;
+ ECHO = 16;
+ ELSE = 17;
+ ELSEIF = 18;
+ EMPTY = 19;
+ ENDDECLARE = 20;
+ ENDFOR = 21;
+ ENDFOREACH = 22;
+ ENDIF = 23;
+ ENDSWITCH = 24;
+ ENDWHILE = 25;
+ EVAL = 26;
+ EXIT = 27;
+ EXTENDS = 28;
+ FINAL = 29;
+ FOR = 30;
+ FOREACH = 31;
+ FUNCTION = 32;
+ GLOBAL = 33;
+ GOTO = 34;
+ IF = 35;
+ IMPLEMENTS = 36;
+ INCLUDE = 37;
+ INCLUDE_ONCE = 38;
+ INSTANCEOF = 39;
+ INSTEADOF = 40;
+ INTERFACE = 41;
+ ISSET = 42;
+ LIST = 43;
+ NAMESPACE = 44;
+ NEW = 45;
+ OR = 46;
+ PRINT = 47;
+ PRIVATE = 48;
+ PROTECTED = 49;
+ PUBLIC = 50;
+ REQUIRE = 51;
+ REQUIRE_ONCE = 52;
+ RETURN = 53;
+ STATIC = 54;
+ SWITCH = 55;
+ THROW = 56;
+ TRAIT = 57;
+ TRY = 58;
+ UNSET = 59;
+ USE = 60;
+ VAR = 61;
+ WHILE = 62;
+ XOR = 63;
+ INT = 64;
+ FLOAT = 65;
+ BOOL = 66;
+ STRING = 67;
+ TRUE = 68;
+ FALSE = 69;
+ NULL = 70;
+ VOID = 71;
+ ITERABLE = 72;
+}
diff --git a/php/tests/proto/test_reserved_message_lower.proto b/php/tests/proto/test_reserved_message_lower.proto
new file mode 100644
index 00000000..ed120808
--- /dev/null
+++ b/php/tests/proto/test_reserved_message_lower.proto
@@ -0,0 +1,77 @@
+syntax = "proto3";
+
+package lower;
+
+message abstract {}
+message and {}
+message array {}
+message as {}
+message break {}
+message callable {}
+message case {}
+message catch {}
+message class {}
+message clone {}
+message const {}
+message continue {}
+message declare {}
+message default {}
+message die {}
+message do {}
+message echo {}
+message else {}
+message elseif {}
+message empty {}
+message enddeclare {}
+message endfor {}
+message endforeach {}
+message endif {}
+message endswitch {}
+message endwhile {}
+message eval {}
+message exit {}
+message extends {}
+message final {}
+message for {}
+message foreach {}
+message function {}
+message global {}
+message goto {}
+message if {}
+message implements {}
+message include {}
+message include_once {}
+message instanceof {}
+message insteadof {}
+message interface {}
+message isset {}
+message list {}
+message namespace {}
+message new {}
+message or {}
+message print {}
+message private {}
+message protected {}
+message public {}
+message require {}
+message require_once {}
+message return {}
+message static {}
+message switch {}
+message throw {}
+message trait {}
+message try {}
+message unset {}
+message use {}
+message var {}
+message while {}
+message xor {}
+message int {}
+message float {}
+message bool {}
+message string {}
+message true {}
+message false {}
+message null {}
+message void {}
+message iterable {}
diff --git a/php/tests/proto/test_reserved_message_upper.proto b/php/tests/proto/test_reserved_message_upper.proto
new file mode 100644
index 00000000..2917fd11
--- /dev/null
+++ b/php/tests/proto/test_reserved_message_upper.proto
@@ -0,0 +1,77 @@
+syntax = "proto3";
+
+package upper;
+
+message ABSTRACT {}
+message AND {}
+message ARRAY {}
+message AS {}
+message BREAK {}
+message CALLABLE {}
+message CASE {}
+message CATCH {}
+message CLASS {}
+message CLONE {}
+message CONST {}
+message CONTINUE {}
+message DECLARE {}
+message DEFAULT {}
+message DIE {}
+message DO {}
+message ECHO {}
+message ELSE {}
+message ELSEIF {}
+message EMPTY {}
+message ENDDECLARE {}
+message ENDFOR {}
+message ENDFOREACH {}
+message ENDIF {}
+message ENDSWITCH {}
+message ENDWHILE {}
+message EVAL {}
+message EXIT {}
+message EXTENDS {}
+message FINAL {}
+message FOR {}
+message FOREACH {}
+message FUNCTION {}
+message GLOBAL {}
+message GOTO {}
+message IF {}
+message IMPLEMENTS {}
+message INCLUDE {}
+message INCLUDE_ONCE {}
+message INSTANCEOF {}
+message INSTEADOF {}
+message INTERFACE {}
+message ISSET {}
+message LIST {}
+message NAMESPACE {}
+message NEW {}
+message OR {}
+message PRINT {}
+message PRIVATE {}
+message PROTECTED {}
+message PUBLIC {}
+message REQUIRE {}
+message REQUIRE_ONCE {}
+message RETURN {}
+message STATIC {}
+message SWITCH {}
+message THROW {}
+message TRAIT {}
+message TRY {}
+message UNSET {}
+message USE {}
+message VAR {}
+message WHILE {}
+message XOR {}
+message INT {}
+message FLOAT {}
+message BOOL {}
+message STRING {}
+message TRUE {}
+message FALSE {}
+message NULL {}
+message VOID {}
+message ITERABLE {}
diff --git a/php/tests/proto/test_service.proto b/php/tests/proto/test_service.proto
new file mode 100644
index 00000000..a03dbc46
--- /dev/null
+++ b/php/tests/proto/test_service.proto
@@ -0,0 +1,18 @@
+syntax = "proto3";
+
+package foo;
+
+option php_generic_services = true;
+
+service Greeter {
+ rpc SayHello (HelloRequest) returns (HelloReply) {}
+ rpc SayHelloAgain (HelloRequest) returns (HelloReply) {}
+}
+
+message HelloRequest {
+ string name = 1;
+}
+
+message HelloReply {
+ string message = 1;
+}
diff --git a/php/tests/proto/test_service_namespace.proto b/php/tests/proto/test_service_namespace.proto
new file mode 100644
index 00000000..719aa484
--- /dev/null
+++ b/php/tests/proto/test_service_namespace.proto
@@ -0,0 +1,13 @@
+syntax = "proto3";
+
+import "proto/test_service.proto";
+
+package foo;
+
+option php_generic_services = true;
+option php_namespace = "Bar";
+
+service OtherGreeter {
+ rpc SayHello (HelloRequest) returns (HelloReply) {}
+ rpc SayHelloAgain (HelloRequest) returns (HelloReply) {}
+}
diff --git a/php/tests/test.sh b/php/tests/test.sh
index 3635d86c..c35372d3 100755
--- a/php/tests/test.sh
+++ b/php/tests/test.sh
@@ -2,13 +2,13 @@
# Compile c extension
pushd ../ext/google/protobuf/
-make clean
+make clean || true
set -e
# Add following in configure for debug: --enable-debug CFLAGS='-g -O0'
-phpize && ./configure --enable-debug CFLAGS='-g -O0' && make
+phpize && ./configure CFLAGS='-g -O0' && make
popd
-tests=( array_test.php encode_decode_test.php generated_class_test.php map_field_test.php well_known_test.php )
+tests=( array_test.php encode_decode_test.php generated_class_test.php generated_phpdoc_test.php map_field_test.php well_known_test.php generated_service_test.php descriptors_test.php )
for t in "${tests[@]}"
do
@@ -19,7 +19,9 @@ do
echo ""
done
-# Make sure to run the memory test in debug mode.
-php -dextension=../ext/google/protobuf/modules/protobuf.so memory_leak_test.php
+# # Make sure to run the memory test in debug mode.
+# php -dextension=../ext/google/protobuf/modules/protobuf.so memory_leak_test.php
-USE_ZEND_ALLOC=0 valgrind --leak-check=yes php -dextension=../ext/google/protobuf/modules/protobuf.so memory_leak_test.php
+export ZEND_DONT_UNLOAD_MODULES=1
+export USE_ZEND_ALLOC=0
+valgrind --leak-check=yes php -dextension=../ext/google/protobuf/modules/protobuf.so memory_leak_test.php
diff --git a/php/tests/test_base.php b/php/tests/test_base.php
index d461f0f7..dc5e73f5 100644
--- a/php/tests/test_base.php
+++ b/php/tests/test_base.php
@@ -1,6 +1,7 @@
<?php
use Foo\TestMessage;
+use Foo\TestEnum;
use Foo\TestMessage_Sub;
class TestBase extends PHPUnit_Framework_TestCase
@@ -11,8 +12,15 @@ class TestBase extends PHPUnit_Framework_TestCase
TestUtil::setTestMessage($m);
}
+ public function setFields2(TestMessage $m)
+ {
+ TestUtil::setTestMessage2($m);
+ }
+
public function expectFields(TestMessage $m)
{
+ $this->assertSame(-42, $m->getOptionalInt32());
+ $this->assertSame(42, $m->getOptionalUint32());
$this->assertSame(-44, $m->getOptionalSint32());
$this->assertSame(46, $m->getOptionalFixed32());
$this->assertSame(-46, $m->getOptionalSfixed32());
@@ -21,6 +29,7 @@ class TestBase extends PHPUnit_Framework_TestCase
$this->assertSame(true, $m->getOptionalBool());
$this->assertSame('a', $m->getOptionalString());
$this->assertSame('b', $m->getOptionalBytes());
+ $this->assertSame(TestEnum::ONE, $m->getOptionalEnum());
$this->assertSame(33, $m->getOptionalMessage()->getA());
if (PHP_INT_SIZE == 4) {
$this->assertSame('-43', $m->getOptionalInt64());
@@ -69,6 +78,165 @@ class TestBase extends PHPUnit_Framework_TestCase
$this->assertEquals('c', $m->getRepeatedString()[1]);
$this->assertEquals('d', $m->getRepeatedBytes()[1]);
$this->assertEquals(35, $m->getRepeatedMessage()[1]->GetA());
+
+ if (PHP_INT_SIZE == 4) {
+ $this->assertEquals('-63', $m->getMapInt64Int64()['-63']);
+ $this->assertEquals('63', $m->getMapUint64Uint64()['63']);
+ $this->assertEquals('-65', $m->getMapSint64Sint64()['-65']);
+ $this->assertEquals('67', $m->getMapFixed64Fixed64()['67']);
+ $this->assertEquals('-69', $m->getMapSfixed64Sfixed64()['-69']);
+ } else {
+ $this->assertEquals(-63, $m->getMapInt64Int64()[-63]);
+ $this->assertEquals(63, $m->getMapUint64Uint64()[63]);
+ $this->assertEquals(-65, $m->getMapSint64Sint64()[-65]);
+ $this->assertEquals(67, $m->getMapFixed64Fixed64()[67]);
+ $this->assertEquals(-69, $m->getMapSfixed64Sfixed64()[-69]);
+ }
+ $this->assertEquals(-62, $m->getMapInt32Int32()[-62]);
+ $this->assertEquals(62, $m->getMapUint32Uint32()[62]);
+ $this->assertEquals(-64, $m->getMapSint32Sint32()[-64]);
+ $this->assertEquals(66, $m->getMapFixed32Fixed32()[66]);
+ $this->assertEquals(-68, $m->getMapSfixed32Sfixed32()[-68]);
+ $this->assertEquals(3.5, $m->getMapInt32Float()[1]);
+ $this->assertEquals(3.6, $m->getMapInt32Double()[1]);
+ $this->assertEquals(true , $m->getMapBoolBool()[true]);
+ $this->assertEquals('e', $m->getMapStringString()['e']);
+ $this->assertEquals('f', $m->getMapInt32Bytes()[1]);
+ $this->assertEquals(TestEnum::ONE, $m->getMapInt32Enum()[1]);
+ $this->assertEquals(36, $m->getMapInt32Message()[1]->GetA());
+ }
+
+ // Test message merged from setFields and setFields2.
+ public function expectFieldsMerged(TestMessage $m)
+ {
+ $this->assertSame(-144, $m->getOptionalSint32());
+ $this->assertSame(146, $m->getOptionalFixed32());
+ $this->assertSame(-146, $m->getOptionalSfixed32());
+ $this->assertSame(11.5, $m->getOptionalFloat());
+ $this->assertSame(11.6, $m->getOptionalDouble());
+ $this->assertSame(true, $m->getOptionalBool());
+ $this->assertSame('aa', $m->getOptionalString());
+ $this->assertSame('bb', $m->getOptionalBytes());
+ $this->assertSame(133, $m->getOptionalMessage()->getA());
+ if (PHP_INT_SIZE == 4) {
+ $this->assertSame('-143', $m->getOptionalInt64());
+ $this->assertSame('143', $m->getOptionalUint64());
+ $this->assertSame('-145', $m->getOptionalSint64());
+ $this->assertSame('147', $m->getOptionalFixed64());
+ $this->assertSame('-147', $m->getOptionalSfixed64());
+ } else {
+ $this->assertSame(-143, $m->getOptionalInt64());
+ $this->assertSame(143, $m->getOptionalUint64());
+ $this->assertSame(-145, $m->getOptionalSint64());
+ $this->assertSame(147, $m->getOptionalFixed64());
+ $this->assertSame(-147, $m->getOptionalSfixed64());
+ }
+
+ $this->assertEquals(-42, $m->getRepeatedInt32()[0]);
+ $this->assertEquals(42, $m->getRepeatedUint32()[0]);
+ $this->assertEquals(-43, $m->getRepeatedInt64()[0]);
+ $this->assertEquals(43, $m->getRepeatedUint64()[0]);
+ $this->assertEquals(-44, $m->getRepeatedSint32()[0]);
+ $this->assertEquals(-45, $m->getRepeatedSint64()[0]);
+ $this->assertEquals(46, $m->getRepeatedFixed32()[0]);
+ $this->assertEquals(47, $m->getRepeatedFixed64()[0]);
+ $this->assertEquals(-46, $m->getRepeatedSfixed32()[0]);
+ $this->assertEquals(-47, $m->getRepeatedSfixed64()[0]);
+ $this->assertEquals(1.5, $m->getRepeatedFloat()[0]);
+ $this->assertEquals(1.6, $m->getRepeatedDouble()[0]);
+ $this->assertEquals(true, $m->getRepeatedBool()[0]);
+ $this->assertEquals('a', $m->getRepeatedString()[0]);
+ $this->assertEquals('b', $m->getRepeatedBytes()[0]);
+ $this->assertEquals(TestEnum::ZERO, $m->getRepeatedEnum()[0]);
+ $this->assertEquals(34, $m->getRepeatedMessage()[0]->GetA());
+
+ $this->assertEquals(-52, $m->getRepeatedInt32()[1]);
+ $this->assertEquals(52, $m->getRepeatedUint32()[1]);
+ $this->assertEquals(-53, $m->getRepeatedInt64()[1]);
+ $this->assertEquals(53, $m->getRepeatedUint64()[1]);
+ $this->assertEquals(-54, $m->getRepeatedSint32()[1]);
+ $this->assertEquals(-55, $m->getRepeatedSint64()[1]);
+ $this->assertEquals(56, $m->getRepeatedFixed32()[1]);
+ $this->assertEquals(57, $m->getRepeatedFixed64()[1]);
+ $this->assertEquals(-56, $m->getRepeatedSfixed32()[1]);
+ $this->assertEquals(-57, $m->getRepeatedSfixed64()[1]);
+ $this->assertEquals(2.5, $m->getRepeatedFloat()[1]);
+ $this->assertEquals(2.6, $m->getRepeatedDouble()[1]);
+ $this->assertEquals(false, $m->getRepeatedBool()[1]);
+ $this->assertEquals('c', $m->getRepeatedString()[1]);
+ $this->assertEquals('d', $m->getRepeatedBytes()[1]);
+ $this->assertEquals(TestEnum::ONE, $m->getRepeatedEnum()[1]);
+ $this->assertEquals(35, $m->getRepeatedMessage()[1]->GetA());
+
+ $this->assertEquals(-142, $m->getRepeatedInt32()[2]);
+ $this->assertEquals(142, $m->getRepeatedUint32()[2]);
+ $this->assertEquals(-143, $m->getRepeatedInt64()[2]);
+ $this->assertEquals(143, $m->getRepeatedUint64()[2]);
+ $this->assertEquals(-144, $m->getRepeatedSint32()[2]);
+ $this->assertEquals(-145, $m->getRepeatedSint64()[2]);
+ $this->assertEquals(146, $m->getRepeatedFixed32()[2]);
+ $this->assertEquals(147, $m->getRepeatedFixed64()[2]);
+ $this->assertEquals(-146, $m->getRepeatedSfixed32()[2]);
+ $this->assertEquals(-147, $m->getRepeatedSfixed64()[2]);
+ $this->assertEquals(11.5, $m->getRepeatedFloat()[2]);
+ $this->assertEquals(11.6, $m->getRepeatedDouble()[2]);
+ $this->assertEquals(false, $m->getRepeatedBool()[2]);
+ $this->assertEquals('aa', $m->getRepeatedString()[2]);
+ $this->assertEquals('bb', $m->getRepeatedBytes()[2]);
+ $this->assertEquals(TestEnum::TWO, $m->getRepeatedEnum()[2]);
+ $this->assertEquals(134, $m->getRepeatedMessage()[2]->GetA());
+
+ if (PHP_INT_SIZE == 4) {
+ $this->assertEquals('-163', $m->getMapInt64Int64()['-63']);
+ $this->assertEquals('163', $m->getMapUint64Uint64()['63']);
+ $this->assertEquals('-165', $m->getMapSint64Sint64()['-65']);
+ $this->assertEquals('167', $m->getMapFixed64Fixed64()['67']);
+ $this->assertEquals('-169', $m->getMapSfixed64Sfixed64()['-69']);
+ } else {
+ $this->assertEquals(-163, $m->getMapInt64Int64()[-63]);
+ $this->assertEquals(163, $m->getMapUint64Uint64()[63]);
+ $this->assertEquals(-165, $m->getMapSint64Sint64()[-65]);
+ $this->assertEquals(167, $m->getMapFixed64Fixed64()[67]);
+ $this->assertEquals(-169, $m->getMapSfixed64Sfixed64()[-69]);
+ }
+ $this->assertEquals(-162, $m->getMapInt32Int32()[-62]);
+ $this->assertEquals(162, $m->getMapUint32Uint32()[62]);
+ $this->assertEquals(-164, $m->getMapSint32Sint32()[-64]);
+ $this->assertEquals(166, $m->getMapFixed32Fixed32()[66]);
+ $this->assertEquals(-168, $m->getMapSfixed32Sfixed32()[-68]);
+ $this->assertEquals(13.5, $m->getMapInt32Float()[1]);
+ $this->assertEquals(13.6, $m->getMapInt32Double()[1]);
+ $this->assertEquals(false , $m->getMapBoolBool()[true]);
+ $this->assertEquals('ee', $m->getMapStringString()['e']);
+ $this->assertEquals('ff', $m->getMapInt32Bytes()[1]);
+ $this->assertEquals(TestEnum::TWO, $m->getMapInt32Enum()[1]);
+ $this->assertEquals(136, $m->getMapInt32Message()[1]->GetA());
+
+ if (PHP_INT_SIZE == 4) {
+ $this->assertEquals('-163', $m->getMapInt64Int64()['-163']);
+ $this->assertEquals('163', $m->getMapUint64Uint64()['163']);
+ $this->assertEquals('-165', $m->getMapSint64Sint64()['-165']);
+ $this->assertEquals('167', $m->getMapFixed64Fixed64()['167']);
+ $this->assertEquals('-169', $m->getMapSfixed64Sfixed64()['-169']);
+ } else {
+ $this->assertEquals(-163, $m->getMapInt64Int64()[-163]);
+ $this->assertEquals(163, $m->getMapUint64Uint64()[163]);
+ $this->assertEquals(-165, $m->getMapSint64Sint64()[-165]);
+ $this->assertEquals(167, $m->getMapFixed64Fixed64()[167]);
+ $this->assertEquals(-169, $m->getMapSfixed64Sfixed64()[-169]);
+ }
+ $this->assertEquals(-162, $m->getMapInt32Int32()[-162]);
+ $this->assertEquals(162, $m->getMapUint32Uint32()[162]);
+ $this->assertEquals(-164, $m->getMapSint32Sint32()[-164]);
+ $this->assertEquals(166, $m->getMapFixed32Fixed32()[166]);
+ $this->assertEquals(-168, $m->getMapSfixed32Sfixed32()[-168]);
+ $this->assertEquals(13.5, $m->getMapInt32Float()[2]);
+ $this->assertEquals(13.6, $m->getMapInt32Double()[2]);
+ $this->assertEquals(false , $m->getMapBoolBool()[false]);
+ $this->assertEquals('ee', $m->getMapStringString()['ee']);
+ $this->assertEquals('ff', $m->getMapInt32Bytes()[2]);
+ $this->assertEquals(TestEnum::TWO, $m->getMapInt32Enum()[2]);
+ $this->assertEquals(136, $m->getMapInt32Message()[2]->GetA());
}
public function expectEmptyFields(TestMessage $m)
@@ -83,7 +251,10 @@ class TestBase extends PHPUnit_Framework_TestCase
$this->assertSame(false, $m->getOptionalBool());
$this->assertSame('', $m->getOptionalString());
$this->assertSame('', $m->getOptionalBytes());
+ $this->assertSame(0, $m->getOptionalEnum());
$this->assertNull($m->getOptionalMessage());
+ $this->assertNull($m->getOptionalIncludedMessage());
+ $this->assertNull($m->getRecursive());
if (PHP_INT_SIZE == 4) {
$this->assertSame("0", $m->getOptionalInt64());
$this->assertSame("0", $m->getOptionalUint64());
@@ -97,6 +268,71 @@ class TestBase extends PHPUnit_Framework_TestCase
$this->assertSame(0, $m->getOptionalFixed64());
$this->assertSame(0, $m->getOptionalSfixed64());
}
+
+ $this->assertEquals(0, count($m->getRepeatedInt32()));
+ $this->assertEquals(0, count($m->getRepeatedUint32()));
+ $this->assertEquals(0, count($m->getRepeatedInt64()));
+ $this->assertEquals(0, count($m->getRepeatedUint64()));
+ $this->assertEquals(0, count($m->getRepeatedSint32()));
+ $this->assertEquals(0, count($m->getRepeatedSint64()));
+ $this->assertEquals(0, count($m->getRepeatedFixed32()));
+ $this->assertEquals(0, count($m->getRepeatedFixed64()));
+ $this->assertEquals(0, count($m->getRepeatedSfixed32()));
+ $this->assertEquals(0, count($m->getRepeatedSfixed64()));
+ $this->assertEquals(0, count($m->getRepeatedFloat()));
+ $this->assertEquals(0, count($m->getRepeatedDouble()));
+ $this->assertEquals(0, count($m->getRepeatedBool()));
+ $this->assertEquals(0, count($m->getRepeatedString()));
+ $this->assertEquals(0, count($m->getRepeatedBytes()));
+ $this->assertEquals(0, count($m->getRepeatedEnum()));
+ $this->assertEquals(0, count($m->getRepeatedMessage()));
+ $this->assertEquals(0, count($m->getRepeatedRecursive()));
+
+ $this->assertSame("", $m->getMyOneof());
+ $this->assertSame(0, $m->getOneofInt32());
+ $this->assertSame(0, $m->getOneofUint32());
+ $this->assertSame(0, $m->getOneofSint32());
+ $this->assertSame(0, $m->getOneofFixed32());
+ $this->assertSame(0, $m->getOneofSfixed32());
+ $this->assertSame(0.0, $m->getOneofFloat());
+ $this->assertSame(0.0, $m->getOneofDouble());
+ $this->assertSame(false, $m->getOneofBool());
+ $this->assertSame('', $m->getOneofString());
+ $this->assertSame('', $m->getOneofBytes());
+ $this->assertSame(0, $m->getOneofEnum());
+ $this->assertNull($m->getOptionalMessage());
+ if (PHP_INT_SIZE == 4) {
+ $this->assertSame("0", $m->getOneofInt64());
+ $this->assertSame("0", $m->getOneofUint64());
+ $this->assertSame("0", $m->getOneofSint64());
+ $this->assertSame("0", $m->getOneofFixed64());
+ $this->assertSame("0", $m->getOneofSfixed64());
+ } else {
+ $this->assertSame(0, $m->getOneofInt64());
+ $this->assertSame(0, $m->getOneofUint64());
+ $this->assertSame(0, $m->getOneofSint64());
+ $this->assertSame(0, $m->getOneofFixed64());
+ $this->assertSame(0, $m->getOneofSfixed64());
+ }
+
+ $this->assertEquals(0, count($m->getMapInt64Int64()));
+ $this->assertEquals(0, count($m->getMapUint64Uint64()));
+ $this->assertEquals(0, count($m->getMapSint64Sint64()));
+ $this->assertEquals(0, count($m->getMapFixed64Fixed64()));
+ $this->assertEquals(0, count($m->getMapInt32Int32()));
+ $this->assertEquals(0, count($m->getMapUint32Uint32()));
+ $this->assertEquals(0, count($m->getMapSint32Sint32()));
+ $this->assertEquals(0, count($m->getMapFixed32Fixed32()));
+ $this->assertEquals(0, count($m->getMapSfixed32Sfixed32()));
+ $this->assertEquals(0, count($m->getMapSfixed64Sfixed64()));
+ $this->assertEquals(0, count($m->getMapInt32Float()));
+ $this->assertEquals(0, count($m->getMapInt32Double()));
+ $this->assertEquals(0, count($m->getMapBoolBool()));
+ $this->assertEquals(0, count($m->getMapStringString()));
+ $this->assertEquals(0, count($m->getMapInt32Bytes()));
+ $this->assertEquals(0, count($m->getMapInt32Enum()));
+ $this->assertEquals(0, count($m->getMapInt32Message()));
+ $this->assertEquals(0, count($m->getMapRecursive()));
}
// This test is to avoid the warning of no test by php unit.
diff --git a/php/tests/test_util.php b/php/tests/test_util.php
index 7f2aae15..c8afdd3e 100644
--- a/php/tests/test_util.php
+++ b/php/tests/test_util.php
@@ -51,8 +51,6 @@ class TestUtil
public static function setTestMessage(TestMessage $m)
{
- $sub = new TestMessage_Sub();
-
$m->setOptionalInt32(-42);
$m->setOptionalInt64(-43);
$m->setOptionalUint32(42);
@@ -69,65 +67,149 @@ class TestUtil
$m->setOptionalString('a');
$m->setOptionalBytes('b');
$m->setOptionalEnum(TestEnum::ONE);
+ $sub = new TestMessage_Sub();
$m->setOptionalMessage($sub);
$m->getOptionalMessage()->SetA(33);
- $m->getRepeatedInt32() []= -42;
- $m->getRepeatedInt64() []= -43;
- $m->getRepeatedUint32() []= 42;
- $m->getRepeatedUint64() []= 43;
- $m->getRepeatedSint32() []= -44;
- $m->getRepeatedSint64() []= -45;
- $m->getRepeatedFixed32() []= 46;
- $m->getRepeatedFixed64() []= 47;
- $m->getRepeatedSfixed32() []= -46;
- $m->getRepeatedSfixed64() []= -47;
- $m->getRepeatedFloat() []= 1.5;
- $m->getRepeatedDouble() []= 1.6;
- $m->getRepeatedBool() []= true;
- $m->getRepeatedString() []= 'a';
- $m->getRepeatedBytes() []= 'b';
- $m->getRepeatedEnum() []= TestEnum::ZERO;
- $m->getRepeatedMessage() []= new TestMessage_Sub();
+ self::appendHelper($m, 'RepeatedInt32', -42);
+ self::appendHelper($m, 'RepeatedInt64', -43);
+ self::appendHelper($m, 'RepeatedUint32', 42);
+ self::appendHelper($m, 'RepeatedUint64', 43);
+ self::appendHelper($m, 'RepeatedSint32', -44);
+ self::appendHelper($m, 'RepeatedSint64', -45);
+ self::appendHelper($m, 'RepeatedFixed32', 46);
+ self::appendHelper($m, 'RepeatedFixed64', 47);
+ self::appendHelper($m, 'RepeatedSfixed32', -46);
+ self::appendHelper($m, 'RepeatedSfixed64', -47);
+ self::appendHelper($m, 'RepeatedFloat', 1.5);
+ self::appendHelper($m, 'RepeatedDouble', 1.6);
+ self::appendHelper($m, 'RepeatedBool', true);
+ self::appendHelper($m, 'RepeatedString', 'a');
+ self::appendHelper($m, 'RepeatedBytes', 'b');
+ self::appendHelper($m, 'RepeatedEnum', TestEnum::ZERO);
+ self::appendHelper($m, 'RepeatedMessage', new TestMessage_Sub());
$m->getRepeatedMessage()[0]->setA(34);
- $m->getRepeatedInt32() []= -52;
- $m->getRepeatedInt64() []= -53;
- $m->getRepeatedUint32() []= 52;
- $m->getRepeatedUint64() []= 53;
- $m->getRepeatedSint32() []= -54;
- $m->getRepeatedSint64() []= -55;
- $m->getRepeatedFixed32() []= 56;
- $m->getRepeatedFixed64() []= 57;
- $m->getRepeatedSfixed32() []= -56;
- $m->getRepeatedSfixed64() []= -57;
- $m->getRepeatedFloat() []= 2.5;
- $m->getRepeatedDouble() []= 2.6;
- $m->getRepeatedBool() []= false;
- $m->getRepeatedString() []= 'c';
- $m->getRepeatedBytes() []= 'd';
- $m->getRepeatedEnum() []= TestEnum::ONE;
- $m->getRepeatedMessage() []= new TestMessage_Sub();
+ self::appendHelper($m, 'RepeatedInt32', -52);
+ self::appendHelper($m, 'RepeatedInt64', -53);
+ self::appendHelper($m, 'RepeatedUint32', 52);
+ self::appendHelper($m, 'RepeatedUint64', 53);
+ self::appendHelper($m, 'RepeatedSint32', -54);
+ self::appendHelper($m, 'RepeatedSint64', -55);
+ self::appendHelper($m, 'RepeatedFixed32', 56);
+ self::appendHelper($m, 'RepeatedFixed64', 57);
+ self::appendHelper($m, 'RepeatedSfixed32', -56);
+ self::appendHelper($m, 'RepeatedSfixed64', -57);
+ self::appendHelper($m, 'RepeatedFloat', 2.5);
+ self::appendHelper($m, 'RepeatedDouble', 2.6);
+ self::appendHelper($m, 'RepeatedBool', false);
+ self::appendHelper($m, 'RepeatedString', 'c');
+ self::appendHelper($m, 'RepeatedBytes', 'd');
+ self::appendHelper($m, 'RepeatedEnum', TestEnum::ONE);
+ self::appendHelper($m, 'RepeatedMessage', new TestMessage_Sub());
$m->getRepeatedMessage()[1]->SetA(35);
- $m->getMapInt32Int32()[-62] = -62;
- $m->getMapInt64Int64()[-63] = -63;
- $m->getMapUint32Uint32()[62] = 62;
- $m->getMapUint64Uint64()[63] = 63;
- $m->getMapSint32Sint32()[-64] = -64;
- $m->getMapSint64Sint64()[-65] = -65;
- $m->getMapFixed32Fixed32()[66] = 66;
- $m->getMapFixed64Fixed64()[67] = 67;
- $m->getMapInt32Float()[1] = 3.5;
- $m->getMapInt32Double()[1] = 3.6;
- $m->getMapBoolBool()[true] = true;
- $m->getMapStringString()['e'] = 'e';
- $m->getMapInt32Bytes()[1] = 'f';
- $m->getMapInt32Enum()[1] = TestEnum::ONE;
- $m->getMapInt32Message()[1] = new TestMessage_Sub();
+ self::kvUpdateHelper($m, 'MapInt32Int32', -62, -62);
+ self::kvUpdateHelper($m, 'MapInt64Int64', -63, -63);
+ self::kvUpdateHelper($m, 'MapUint32Uint32', 62, 62);
+ self::kvUpdateHelper($m, 'MapUint64Uint64', 63, 63);
+ self::kvUpdateHelper($m, 'MapSint32Sint32', -64, -64);
+ self::kvUpdateHelper($m, 'MapSint64Sint64', -65, -65);
+ self::kvUpdateHelper($m, 'MapFixed32Fixed32', 66, 66);
+ self::kvUpdateHelper($m, 'MapFixed64Fixed64', 67, 67);
+ self::kvUpdateHelper($m, 'MapSfixed32Sfixed32', -68, -68);
+ self::kvUpdateHelper($m, 'MapSfixed64Sfixed64', -69, -69);
+ self::kvUpdateHelper($m, 'MapInt32Float', 1, 3.5);
+ self::kvUpdateHelper($m, 'MapInt32Double', 1, 3.6);
+ self::kvUpdateHelper($m, 'MapBoolBool', true, true);
+ self::kvUpdateHelper($m, 'MapStringString', 'e', 'e');
+ self::kvUpdateHelper($m, 'MapInt32Bytes', 1, 'f');
+ self::kvUpdateHelper($m, 'MapInt32Enum', 1, TestEnum::ONE);
+ self::kvUpdateHelper($m, 'MapInt32Message', 1, new TestMessage_Sub());
$m->getMapInt32Message()[1]->SetA(36);
}
+ public static function setTestMessage2(TestMessage $m)
+ {
+ $sub = new TestMessage_Sub();
+
+ $m->setOptionalInt32(-142);
+ $m->setOptionalInt64(-143);
+ $m->setOptionalUint32(142);
+ $m->setOptionalUint64(143);
+ $m->setOptionalSint32(-144);
+ $m->setOptionalSint64(-145);
+ $m->setOptionalFixed32(146);
+ $m->setOptionalFixed64(147);
+ $m->setOptionalSfixed32(-146);
+ $m->setOptionalSfixed64(-147);
+ $m->setOptionalFloat(11.5);
+ $m->setOptionalDouble(11.6);
+ $m->setOptionalBool(true);
+ $m->setOptionalString('aa');
+ $m->setOptionalBytes('bb');
+ $m->setOptionalEnum(TestEnum::TWO);
+ $m->setOptionalMessage($sub);
+ $m->getOptionalMessage()->SetA(133);
+
+ self::appendHelper($m, 'RepeatedInt32', -142);
+ self::appendHelper($m, 'RepeatedInt64', -143);
+ self::appendHelper($m, 'RepeatedUint32', 142);
+ self::appendHelper($m, 'RepeatedUint64', 143);
+ self::appendHelper($m, 'RepeatedSint32', -144);
+ self::appendHelper($m, 'RepeatedSint64', -145);
+ self::appendHelper($m, 'RepeatedFixed32', 146);
+ self::appendHelper($m, 'RepeatedFixed64', 147);
+ self::appendHelper($m, 'RepeatedSfixed32', -146);
+ self::appendHelper($m, 'RepeatedSfixed64', -147);
+ self::appendHelper($m, 'RepeatedFloat', 11.5);
+ self::appendHelper($m, 'RepeatedDouble', 11.6);
+ self::appendHelper($m, 'RepeatedBool', false);
+ self::appendHelper($m, 'RepeatedString', 'aa');
+ self::appendHelper($m, 'RepeatedBytes', 'bb');
+ self::appendHelper($m, 'RepeatedEnum', TestEnum::TWO);
+ self::appendHelper($m, 'RepeatedMessage', new TestMessage_Sub());
+ $m->getRepeatedMessage()[0]->setA(134);
+
+ self::kvUpdateHelper($m, 'MapInt32Int32', -62, -162);
+ self::kvUpdateHelper($m, 'MapInt64Int64', -63, -163);
+ self::kvUpdateHelper($m, 'MapUint32Uint32', 62, 162);
+ self::kvUpdateHelper($m, 'MapUint64Uint64', 63, 163);
+ self::kvUpdateHelper($m, 'MapSint32Sint32', -64, -164);
+ self::kvUpdateHelper($m, 'MapSint64Sint64', -65, -165);
+ self::kvUpdateHelper($m, 'MapFixed32Fixed32', 66, 166);
+ self::kvUpdateHelper($m, 'MapFixed64Fixed64', 67, 167);
+ self::kvUpdateHelper($m, 'MapSfixed32Sfixed32', -68, -168);
+ self::kvUpdateHelper($m, 'MapSfixed64Sfixed64', -69, -169);
+ self::kvUpdateHelper($m, 'MapInt32Float', 1, 13.5);
+ self::kvUpdateHelper($m, 'MapInt32Double', 1, 13.6);
+ self::kvUpdateHelper($m, 'MapBoolBool', true, false);
+ self::kvUpdateHelper($m, 'MapStringString', 'e', 'ee');
+ self::kvUpdateHelper($m, 'MapInt32Bytes', 1, 'ff');
+ self::kvUpdateHelper($m, 'MapInt32Enum', 1, TestEnum::TWO);
+ self::kvUpdateHelper($m, 'MapInt32Message', 1, new TestMessage_Sub());
+ $m->getMapInt32Message()[1]->SetA(136);
+
+ self::kvUpdateHelper($m, 'MapInt32Int32', -162, -162);
+ self::kvUpdateHelper($m, 'MapInt64Int64', -163, -163);
+ self::kvUpdateHelper($m, 'MapUint32Uint32', 162, 162);
+ self::kvUpdateHelper($m, 'MapUint64Uint64', 163, 163);
+ self::kvUpdateHelper($m, 'MapSint32Sint32', -164, -164);
+ self::kvUpdateHelper($m, 'MapSint64Sint64', -165, -165);
+ self::kvUpdateHelper($m, 'MapFixed32Fixed32', 166, 166);
+ self::kvUpdateHelper($m, 'MapFixed64Fixed64', 167, 167);
+ self::kvUpdateHelper($m, 'MapSfixed32Sfixed32', -168, -168);
+ self::kvUpdateHelper($m, 'MapSfixed64Sfixed64', -169, -169);
+ self::kvUpdateHelper($m, 'MapInt32Float', 2, 13.5);
+ self::kvUpdateHelper($m, 'MapInt32Double', 2, 13.6);
+ self::kvUpdateHelper($m, 'MapBoolBool', false, false);
+ self::kvUpdateHelper($m, 'MapStringString', 'ee', 'ee');
+ self::kvUpdateHelper($m, 'MapInt32Bytes', 2, 'ff');
+ self::kvUpdateHelper($m, 'MapInt32Enum', 2, TestEnum::TWO);
+ self::kvUpdateHelper($m, 'MapInt32Message', 2, new TestMessage_Sub());
+ $m->getMapInt32Message()[2]->SetA(136);
+ }
+
public static function assertTestMessage(TestMessage $m)
{
if (PHP_INT_SIZE == 4) {
@@ -213,16 +295,19 @@ class TestUtil
assert('63' === $m->getMapUint64Uint64()['63']);
assert('-65' === $m->getMapSint64Sint64()['-65']);
assert('67' === $m->getMapFixed64Fixed64()['67']);
+ assert('-69' === $m->getMapSfixed64Sfixed64()['-69']);
} else {
assert(-63 === $m->getMapInt64Int64()[-63]);
assert(63 === $m->getMapUint64Uint64()[63]);
assert(-65 === $m->getMapSint64Sint64()[-65]);
assert(67 === $m->getMapFixed64Fixed64()[67]);
+ assert(-69 === $m->getMapSfixed64Sfixed64()[-69]);
}
assert(-62 === $m->getMapInt32Int32()[-62]);
assert(62 === $m->getMapUint32Uint32()[62]);
assert(-64 === $m->getMapSint32Sint32()[-64]);
assert(66 === $m->getMapFixed32Fixed32()[66]);
+ assert(-68 === $m->getMapSfixed32Sfixed32()[-68]);
assert(3.5 === $m->getMapInt32Float()[1]);
assert(3.6 === $m->getMapInt32Double()[1]);
assert(true === $m->getMapBoolBool()[true]);
@@ -235,7 +320,7 @@ class TestUtil
public static function getGoldenTestMessage()
{
return hex2bin(
- "08D6FFFFFF0F" .
+ "08D6FFFFFFFFFFFFFFFF01" .
"10D5FFFFFFFFFFFFFFFF01" .
"182A" .
"202B" .
@@ -253,8 +338,8 @@ class TestUtil
"800101" .
"8A01020821" .
- "F801D6FFFFFF0F" .
- "F801CCFFFFFF0F" .
+ "F801D6FFFFFFFFFFFFFFFF01" .
+ "F801CCFFFFFFFFFFFFFFFF01" .
"8002D5FFFFFFFFFFFFFFFF01" .
"8002CBFFFFFFFFFFFFFFFF01" .
"88022A" .
@@ -288,7 +373,7 @@ class TestUtil
"FA02020822" .
"FA02020823" .
- "BA040C08C2FFFFFF0F10C2FFFFFF0F" .
+ "BA041608C2FFFFFFFFFFFFFFFF0110C2FFFFFFFFFFFFFFFF01" .
"C2041608C1FFFFFFFFFFFFFFFF0110C1FFFFFFFFFFFFFFFF01" .
"CA0404083E103E" .
"D20404083F103F" .
@@ -296,6 +381,8 @@ class TestUtil
"E20406088101108101" .
"EA040A0D420000001542000000" .
"F20412094300000000000000114300000000000000" .
+ "FA040A0DBCFFFFFF15BCFFFFFF" .
+ "82051209BBFFFFFFFFFFFFFF11BBFFFFFFFFFFFFFF" .
"8A050708011500006040" .
"92050B080111CDCCCCCCCCCC0C40" .
"9A050408011001" .
@@ -308,34 +395,34 @@ class TestUtil
public static function setTestPackedMessage($m)
{
- $m->getRepeatedInt32()[] = -42;
- $m->getRepeatedInt32()[] = -52;
- $m->getRepeatedInt64()[] = -43;
- $m->getRepeatedInt64()[] = -53;
- $m->getRepeatedUint32()[] = 42;
- $m->getRepeatedUint32()[] = 52;
- $m->getRepeatedUint64()[] = 43;
- $m->getRepeatedUint64()[] = 53;
- $m->getRepeatedSint32()[] = -44;
- $m->getRepeatedSint32()[] = -54;
- $m->getRepeatedSint64()[] = -45;
- $m->getRepeatedSint64()[] = -55;
- $m->getRepeatedFixed32()[] = 46;
- $m->getRepeatedFixed32()[] = 56;
- $m->getRepeatedFixed64()[] = 47;
- $m->getRepeatedFixed64()[] = 57;
- $m->getRepeatedSfixed32()[] = -46;
- $m->getRepeatedSfixed32()[] = -56;
- $m->getRepeatedSfixed64()[] = -47;
- $m->getRepeatedSfixed64()[] = -57;
- $m->getRepeatedFloat()[] = 1.5;
- $m->getRepeatedFloat()[] = 2.5;
- $m->getRepeatedDouble()[] = 1.6;
- $m->getRepeatedDouble()[] = 2.6;
- $m->getRepeatedBool()[] = true;
- $m->getRepeatedBool()[] = false;
- $m->getRepeatedEnum()[] = TestEnum::ONE;
- $m->getRepeatedEnum()[] = TestEnum::ZERO;
+ self::appendHelper($m, 'RepeatedInt32', -42);
+ self::appendHelper($m, 'RepeatedInt32', -52);
+ self::appendHelper($m, 'RepeatedInt64', -43);
+ self::appendHelper($m, 'RepeatedInt64', -53);
+ self::appendHelper($m, 'RepeatedUint32', 42);
+ self::appendHelper($m, 'RepeatedUint32', 52);
+ self::appendHelper($m, 'RepeatedUint64', 43);
+ self::appendHelper($m, 'RepeatedUint64', 53);
+ self::appendHelper($m, 'RepeatedSint32', -44);
+ self::appendHelper($m, 'RepeatedSint32', -54);
+ self::appendHelper($m, 'RepeatedSint64', -45);
+ self::appendHelper($m, 'RepeatedSint64', -55);
+ self::appendHelper($m, 'RepeatedFixed32', 46);
+ self::appendHelper($m, 'RepeatedFixed32', 56);
+ self::appendHelper($m, 'RepeatedFixed64', 47);
+ self::appendHelper($m, 'RepeatedFixed64', 57);
+ self::appendHelper($m, 'RepeatedSfixed32', -46);
+ self::appendHelper($m, 'RepeatedSfixed32', -56);
+ self::appendHelper($m, 'RepeatedSfixed64', -47);
+ self::appendHelper($m, 'RepeatedSfixed64', -57);
+ self::appendHelper($m, 'RepeatedFloat', 1.5);
+ self::appendHelper($m, 'RepeatedFloat', 2.5);
+ self::appendHelper($m, 'RepeatedDouble', 1.6);
+ self::appendHelper($m, 'RepeatedDouble', 2.6);
+ self::appendHelper($m, 'RepeatedBool', true);
+ self::appendHelper($m, 'RepeatedBool', false);
+ self::appendHelper($m, 'RepeatedEnum', TestEnum::ONE);
+ self::appendHelper($m, 'RepeatedEnum', TestEnum::ZERO);
}
public static function assertTestPackedMessage($m)
@@ -401,7 +488,7 @@ class TestUtil
public static function getGoldenTestPackedMessage()
{
return hex2bin(
- "D2050AD6FFFFFF0FCCFFFFFF0F" .
+ "D20514D6FFFFFFFFFFFFFFFF01CCFFFFFFFFFFFFFFFF01" .
"DA0514D5FFFFFFFFFFFFFFFF01CBFFFFFFFFFFFFFFFF01" .
"E205022A34" .
"EA05022B35" .
@@ -421,7 +508,7 @@ class TestUtil
public static function getGoldenTestUnpackedMessage()
{
return hex2bin(
- "D005D6FFFFFF0FD005CCFFFFFF0F" .
+ "D005D6FFFFFFFFFFFFFFFF01D005CCFFFFFFFFFFFFFFFF01" .
"D805D5FFFFFFFFFFFFFFFF01D805CBFFFFFFFFFFFFFFFF01" .
"E0052AE00534" .
"E8052BE80535" .
@@ -437,4 +524,24 @@ class TestUtil
"B80601B80600"
);
}
+
+ private static function appendHelper($obj, $func_suffix, $value)
+ {
+ $getter_function = 'get'.$func_suffix;
+ $setter_function = 'set'.$func_suffix;
+
+ $arr = $obj->$getter_function();
+ $arr[] = $value;
+ $obj->$setter_function($arr);
+ }
+
+ private static function kvUpdateHelper($obj, $func_suffix, $key, $value)
+ {
+ $getter_function = 'get'.$func_suffix;
+ $setter_function = 'set'.$func_suffix;
+
+ $arr = $obj->$getter_function();
+ $arr[$key] = $value;
+ $obj->$setter_function($arr);
+ }
}
diff --git a/php/tests/undefined_test.php b/php/tests/undefined_test.php
new file mode 100644
index 00000000..dc6b7086
--- /dev/null
+++ b/php/tests/undefined_test.php
@@ -0,0 +1,920 @@
+<?php
+
+require_once('test_util.php');
+
+use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\GPBType;
+use Foo\TestMessage;
+use Foo\TestMessage_Sub;
+
+class UndefinedTest extends PHPUnit_Framework_TestCase
+{
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt32AppendStringFail()
+ {
+ $arr = new RepeatedField(GPBType::INT32);
+ $arr[] = 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt32SetStringFail()
+ {
+ $arr = new RepeatedField(GPBType::INT32);
+ $arr[] = 0;
+ $arr[0] = 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt32AppendMessageFail()
+ {
+ $arr = new RepeatedField(GPBType::INT32);
+ $arr[] = new TestMessage_Sub();
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt32SetMessageFail()
+ {
+ $arr = new RepeatedField(GPBType::INT32);
+ $arr[] = 0;
+ $arr[0] = new TestMessage_Sub();
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint32AppendStringFail()
+ {
+ $arr = new RepeatedField(GPBType::UINT32);
+ $arr[] = 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint32SetStringFail()
+ {
+ $arr = new RepeatedField(GPBType::UINT32);
+ $arr[] = 0;
+ $arr[0] = 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint32AppendMessageFail()
+ {
+ $arr = new RepeatedField(GPBType::UINT32);
+ $arr[] = new TestMessage_Sub();
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint32SetMessageFail()
+ {
+ $arr = new RepeatedField(GPBType::UINT32);
+ $arr[] = 0;
+ $arr[0] = new TestMessage_Sub();
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt64AppendStringFail()
+ {
+ $arr = new RepeatedField(GPBType::INT64);
+ $arr[] = 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt64SetStringFail()
+ {
+ $arr = new RepeatedField(GPBType::INT64);
+ $arr[] = 0;
+ $arr[0] = 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt64AppendMessageFail()
+ {
+ $arr = new RepeatedField(GPBType::INT64);
+ $arr[] = new TestMessage_Sub();
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt64SetMessageFail()
+ {
+ $arr = new RepeatedField(GPBType::INT64);
+ $arr[] = 0;
+ $arr[0] = new TestMessage_Sub();
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint64AppendStringFail()
+ {
+ $arr = new RepeatedField(GPBType::UINT64);
+ $arr[] = 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint64SetStringFail()
+ {
+ $arr = new RepeatedField(GPBType::UINT64);
+ $arr[] = 0;
+ $arr[0] = 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint64AppendMessageFail()
+ {
+ $arr = new RepeatedField(GPBType::UINT64);
+ $arr[] = new TestMessage_Sub();
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint64SetMessageFail()
+ {
+ $arr = new RepeatedField(GPBType::UINT64);
+ $arr[] = 0;
+ $arr[0] = new TestMessage_Sub();
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testFloatAppendStringFail()
+ {
+ $arr = new RepeatedField(GPBType::FLOAT);
+ $arr[] = 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testFloatSetStringFail()
+ {
+ $arr = new RepeatedField(GPBType::FLOAT);
+ $arr[] = 0.0;
+ $arr[0] = 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testFloatAppendMessageFail()
+ {
+ $arr = new RepeatedField(GPBType::FLOAT);
+ $arr[] = new TestMessage_Sub();
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testFloatSetMessageFail()
+ {
+ $arr = new RepeatedField(GPBType::FLOAT);
+ $arr[] = 0.0;
+ $arr[0] = new TestMessage_Sub();
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testDoubleAppendStringFail()
+ {
+ $arr = new RepeatedField(GPBType::DOUBLE);
+ $arr[] = 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testDoubleSetStringFail()
+ {
+ $arr = new RepeatedField(GPBType::DOUBLE);
+ $arr[] = 0.0;
+ $arr[0] = 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testDoubleAppendMessageFail()
+ {
+ $arr = new RepeatedField(GPBType::DOUBLE);
+ $arr[] = new TestMessage_Sub();
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testDoubleSetMessageFail()
+ {
+ $arr = new RepeatedField(GPBType::DOUBLE);
+ $arr[] = 0.0;
+ $arr[0] = new TestMessage_Sub();
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testBoolAppendMessageFail()
+ {
+ $arr = new RepeatedField(GPBType::BOOL);
+ $arr[] = new TestMessage_Sub();
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testBoolSetMessageFail()
+ {
+ $arr = new RepeatedField(GPBType::BOOL);
+ $arr[] = true;
+ $arr[0] = new TestMessage_Sub();
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testStringAppendMessageFail()
+ {
+ $arr = new RepeatedField(GPBType::STRING);
+ $arr[] = new TestMessage_Sub();
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testStringSetMessageFail()
+ {
+ $arr = new RepeatedField(GPBType::STRING);
+ $arr[] = 'abc';
+ $arr[0] = new TestMessage_Sub();
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testStringAppendInvalidUTF8Fail()
+ {
+ $arr = new RepeatedField(GPBType::STRING);
+ $hex = hex2bin("ff");
+ $arr[] = $hex;
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testStringSetInvalidUTF8Fail()
+ {
+ $arr = new RepeatedField(GPBType::STRING);
+ $arr[] = 'abc';
+ $hex = hex2bin("ff");
+ $arr[0] = $hex;
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testMessageAppendIntFail()
+ {
+ $arr = new RepeatedField(GPBType::MESSAGE, TestMessage_Sub::class);
+ $arr[] = 1;
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testMessageSetIntFail()
+ {
+ $arr = new RepeatedField(GPBType::MESSAGE, TestMessage_Sub::class);
+ $arr[] = new TestMessage_Sub;
+ $arr[0] = 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testMessageAppendStringFail()
+ {
+ $arr = new RepeatedField(GPBType::MESSAGE, TestMessage_Sub::class);
+ $arr[] = 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testMessageSetStringFail()
+ {
+ $arr = new RepeatedField(GPBType::MESSAGE, TestMessage_Sub::class);
+ $arr[] = new TestMessage_Sub;
+ $arr[0] = 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testMessageAppendOtherMessageFail()
+ {
+ $arr = new RepeatedField(GPBType::MESSAGE, TestMessage_Sub::class);
+ $arr[] = new TestMessage;
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testMessageAppendNullFail()
+ {
+ $arr = new RepeatedField(GPBType::MESSAGE, TestMessage_Sub::class);
+ $null = null;
+ $arr[] = $null;
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testMessageSetNullFail()
+ {
+ $arr = new RepeatedField(GPBType::MESSAGE, TestMessage_Sub::class);
+ $arr[] = new TestMessage_Sub();
+ $null = null;
+ $arr[0] = $null;
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testRemoveMiddleFail()
+ {
+ $arr = new RepeatedField(GPBType::INT32);
+
+ $arr[] = 0;
+ $arr[] = 1;
+ $arr[] = 2;
+ $this->assertSame(3, count($arr));
+
+ unset($arr[1]);
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testRemoveEmptyFail()
+ {
+ $arr = new RepeatedField(GPBType::INT32);
+
+ unset($arr[0]);
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testMessageOffsetFail()
+ {
+ $arr = new RepeatedField(GPBType::INT32);
+ $arr[] = 0;
+ $arr[new TestMessage_Sub()] = 0;
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testStringOffsetFail()
+ {
+ $arr = new RepeatedField(GPBType::INT32);
+ $arr[] = 0;
+ $arr['abc'] = 0;
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testSetNonExistedOffsetFail()
+ {
+ $arr = new RepeatedField(GPBType::INT32);
+ $arr[0] = 0;
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt32FieldInvalidTypeFail()
+ {
+ $m = new TestMessage();
+ $m->setOptionalInt32(new TestMessage());
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt32FieldInvalidStringFail()
+ {
+ $m = new TestMessage();
+ $m->setOptionalInt32('abc');
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint32FieldInvalidTypeFail()
+ {
+ $m = new TestMessage();
+ $m->setOptionalUint32(new TestMessage());
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint32FieldInvalidStringFail()
+ {
+ $m = new TestMessage();
+ $m->setOptionalUint32('abc');
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt64FieldInvalidTypeFail()
+ {
+ $m = new TestMessage();
+ $m->setOptionalInt64(new TestMessage());
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt64FieldInvalidStringFail()
+ {
+ $m = new TestMessage();
+ $m->setOptionalInt64('abc');
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint64FieldInvalidTypeFail()
+ {
+ $m = new TestMessage();
+ $m->setOptionalUint64(new TestMessage());
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint64FieldInvalidStringFail()
+ {
+ $m = new TestMessage();
+ $m->setOptionalUint64('abc');
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testFloatFieldInvalidTypeFail()
+ {
+ $m = new TestMessage();
+ $m->setOptionalFloat(new TestMessage());
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testFloatFieldInvalidStringFail()
+ {
+ $m = new TestMessage();
+ $m->setOptionalFloat('abc');
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testDoubleFieldInvalidTypeFail()
+ {
+ $m = new TestMessage();
+ $m->setOptionalDouble(new TestMessage());
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testDoubleFieldInvalidStringFail()
+ {
+ $m = new TestMessage();
+ $m->setOptionalDouble('abc');
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testBoolFieldInvalidStringFail()
+ {
+ $m = new TestMessage();
+ $m->setOptionalBool(new TestMessage());
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testStringFieldInvalidUTF8Fail()
+ {
+ $m = new TestMessage();
+ $hex = hex2bin("ff");
+ $m->setOptionalString($hex);
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testMessageFieldWrongTypeFail()
+ {
+ $m = new TestMessage();
+ $a = 1;
+ $m->setOptionalMessage($a);
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testMessageFieldWrongClassFail()
+ {
+ $m = new TestMessage();
+ $m->setOptionalMessage(new TestMessage());
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testRepeatedFieldWrongTypeFail()
+ {
+ $m = new TestMessage();
+ $a = 1;
+ $m->setRepeatedInt32($a);
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testRepeatedFieldWrongObjectFail()
+ {
+ $m = new TestMessage();
+ $m->setRepeatedInt32($m);
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testRepeatedFieldWrongRepeatedTypeFail()
+ {
+ $m = new TestMessage();
+
+ $repeated_int32 = new RepeatedField(GPBType::UINT32);
+ $m->setRepeatedInt32($repeated_int32);
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testRepeatedFieldWrongRepeatedMessageClassFail()
+ {
+ $m = new TestMessage();
+
+ $repeated_message = new RepeatedField(GPBType::MESSAGE,
+ TestMessage::class);
+ $m->setRepeatedMessage($repeated_message);
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testMapFieldWrongTypeFail()
+ {
+ $m = new TestMessage();
+ $a = 1;
+ $m->setMapInt32Int32($a);
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testMapFieldWrongObjectFail()
+ {
+ $m = new TestMessage();
+ $m->setMapInt32Int32($m);
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testMapFieldWrongRepeatedTypeFail()
+ {
+ $m = new TestMessage();
+
+ $map_uint32_uint32 = new MapField(GPBType::UINT32, GPBType::UINT32);
+ $m->setMapInt32Int32($map_uint32_uint32);
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testMapFieldWrongRepeatedMessageClassFail()
+ {
+ $m = new TestMessage();
+
+ $map_int32_message = new MapField(GPBType::INT32,
+ GPBType::MESSAGE,
+ TestMessage::class);
+ $m->setMapInt32Message($map_int32_message);
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testMessageMergeFromInvalidTypeFail()
+ {
+ $m = new TestMessage();
+ $n = new TestMessage_Sub();
+ $m->mergeFrom($n);
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt32SetStringKeyFail()
+ {
+ $arr = new MapField(GPBType::INT32, GPBType::INT32);
+ $arr['abc'] = 0;
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt32SetStringValueFail()
+ {
+ $arr = new MapField(GPBType::INT32, GPBType::INT32);
+ $arr[0] = 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt32SetMessageKeyFail()
+ {
+ $arr = new MapField(GPBType::INT32, GPBType::INT32);
+ $arr[new TestMessage_Sub()] = 0;
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt32SetMessageValueFail()
+ {
+ $arr = new MapField(GPBType::INT32, GPBType::INT32);
+ $arr[0] = new TestMessage_Sub();
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint32SetStringKeyFail()
+ {
+ $arr = new MapField(GPBType::UINT32, GPBType::UINT32);
+ $arr['abc'] = 0;
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint32SetStringValueFail()
+ {
+ $arr = new MapField(GPBType::UINT32, GPBType::UINT32);
+ $arr[0] = 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint32SetMessageKeyFail()
+ {
+ $arr = new MapField(GPBType::UINT32, GPBType::UINT32);
+ $arr[new TestMessage_Sub()] = 0;
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint32SetMessageValueFail()
+ {
+ $arr = new MapField(GPBType::UINT32, GPBType::UINT32);
+ $arr[0] = new TestMessage_Sub();
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt64SetStringKeyFail()
+ {
+ $arr = new MapField(GPBType::INT64, GPBType::INT64);
+ $arr['abc'] = 0;
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt64SetStringValueFail()
+ {
+ $arr = new MapField(GPBType::INT64, GPBType::INT64);
+ $arr[0] = 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt64SetMessageKeyFail()
+ {
+ $arr = new MapField(GPBType::INT64, GPBType::INT64);
+ $arr[new TestMessage_Sub()] = 0;
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt64SetMessageValueFail()
+ {
+ $arr = new MapField(GPBType::INT64, GPBType::INT64);
+ $arr[0] = new TestMessage_Sub();
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint64SetStringKeyFail()
+ {
+ $arr = new MapField(GPBType::UINT64, GPBType::UINT64);
+ $arr['abc'] = 0;
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint64SetStringValueFail()
+ {
+ $arr = new MapField(GPBType::UINT64, GPBType::UINT64);
+ $arr[0] = 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint64SetMessageKeyFail()
+ {
+ $arr = new MapField(GPBType::UINT64, GPBType::UINT64);
+ $arr[new TestMessage_Sub()] = 0;
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint64SetMessageValueFail()
+ {
+ $arr = new MapField(GPBType::UINT64, GPBType::UINT64);
+ $arr[0] = new TestMessage_Sub();
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testDoubleSetStringValueFail()
+ {
+ $arr = new MapField(GPBType::INT64, GPBType::DOUBLE);
+ $arr[0] = 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testDoubleSetMessageValueFail()
+ {
+ $arr = new MapField(GPBType::INT64, GPBType::DOUBLE);
+ $arr[0] = new TestMessage_Sub();
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testBoolSetMessageKeyFail()
+ {
+ $arr = new MapField(GPBType::BOOL, GPBType::BOOL);
+ $arr[new TestMessage_Sub()] = true;
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testBoolSetMessageValueFail()
+ {
+ $arr = new MapField(GPBType::BOOL, GPBType::BOOL);
+ $arr[true] = new TestMessage_Sub();
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testStringSetInvalidUTF8KeyFail()
+ {
+ $arr = new MapField(GPBType::STRING, GPBType::STRING);
+ $arr[hex2bin("ff")] = 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testStringSetInvalidUTF8ValueFail()
+ {
+ $arr = new MapField(GPBType::STRING, GPBType::STRING);
+ $arr['abc'] = hex2bin("ff");
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testStringSetMessageKeyFail()
+ {
+ $arr = new MapField(GPBType::STRING, GPBType::STRING);
+ $arr[new TestMessage_Sub()] = 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testStringSetMessageValueFail()
+ {
+ $arr = new MapField(GPBType::STRING, GPBType::STRING);
+ $arr['abc'] = new TestMessage_Sub();
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testMessageSetIntValueFail()
+ {
+ $arr =
+ new MapField(GPBType::INT32, GPBType::MESSAGE, TestMessage::class);
+ $arr[0] = 0;
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testMessageSetStringValueFail()
+ {
+ $arr =
+ new MapField(GPBType::INT32, GPBType::MESSAGE, TestMessage::class);
+ $arr[0] = 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testMessageSetOtherMessageValueFail()
+ {
+ $arr =
+ new MapField(GPBType::INT32, GPBType::MESSAGE, TestMessage::class);
+ $arr[0] = new TestMessage_Sub();
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testMessageSetNullFail()
+ {
+ $arr =
+ new MapField(GPBType::INT32, GPBType::MESSAGE, TestMessage::class);
+ $null = NULL;
+ $arr[0] = $null;
+ }
+
+}
diff --git a/php/tests/well_known_test.php b/php/tests/well_known_test.php
index 40ff1c8f..a7760685 100644
--- a/php/tests/well_known_test.php
+++ b/php/tests/well_known_test.php
@@ -1,11 +1,393 @@
<?php
+require_once('test_base.php');
+require_once('test_util.php');
+
+use Foo\TestMessage;
+use Google\Protobuf\Any;
+use Google\Protobuf\Api;
+use Google\Protobuf\BoolValue;
+use Google\Protobuf\BytesValue;
+use Google\Protobuf\DoubleValue;
+use Google\Protobuf\Duration;
+use Google\Protobuf\Enum;
+use Google\Protobuf\EnumValue;
+use Google\Protobuf\Field;
+use Google\Protobuf\FieldMask;
+use Google\Protobuf\Field_Cardinality;
+use Google\Protobuf\Field_Kind;
+use Google\Protobuf\FloatValue;
use Google\Protobuf\GPBEmpty;
+use Google\Protobuf\Int32Value;
+use Google\Protobuf\Int64Value;
+use Google\Protobuf\ListValue;
+use Google\Protobuf\Method;
+use Google\Protobuf\Mixin;
+use Google\Protobuf\NullValue;
+use Google\Protobuf\Option;
+use Google\Protobuf\SourceContext;
+use Google\Protobuf\StringValue;
+use Google\Protobuf\Struct;
+use Google\Protobuf\Syntax;
+use Google\Protobuf\Timestamp;
+use Google\Protobuf\Type;
+use Google\Protobuf\UInt32Value;
+use Google\Protobuf\UInt64Value;
+use Google\Protobuf\Value;
+
+class NotMessage {}
+
+class WellKnownTest extends TestBase {
+
+ public function testEmpty()
+ {
+ $msg = new GPBEmpty();
+ }
+
+ public function testImportDescriptorProto()
+ {
+ $msg = new TestImportDescriptorProto();
+ }
+
+ public function testAny()
+ {
+ // Create embed message
+ $embed = new TestMessage();
+ $this->setFields($embed);
+ $data = $embed->serializeToString();
+
+ // Set any via normal setter.
+ $any = new Any();
+
+ $this->assertSame(
+ $any, $any->setTypeUrl("type.googleapis.com/foo.TestMessage"));
+ $this->assertSame("type.googleapis.com/foo.TestMessage",
+ $any->getTypeUrl());
+
+ $this->assertSame($any, $any->setValue($data));
+ $this->assertSame($data, $any->getValue());
+
+ // Test unpack.
+ $msg = $any->unpack();
+ $this->assertTrue($msg instanceof TestMessage);
+ $this->expectFields($msg);
+
+ // Test pack.
+ $any = new Any();
+ $any->pack($embed);
+ $this->assertSame($data, $any->getValue());
+ $this->assertSame("type.googleapis.com/foo.TestMessage", $any->getTypeUrl());
+
+ // Test is.
+ $this->assertTrue($any->is(TestMessage::class));
+ $this->assertFalse($any->is(Any::class));
+ }
+
+ /**
+ * @expectedException Exception
+ */
+ public function testAnyUnpackInvalidTypeUrl()
+ {
+ $any = new Any();
+ $any->setTypeUrl("invalid");
+ $any->unpack();
+ }
+
+ /**
+ * @expectedException Exception
+ */
+ public function testAnyUnpackMessageNotAdded()
+ {
+ $any = new Any();
+ $any->setTypeUrl("type.googleapis.com/MessageNotAdded");
+ $any->unpack();
+ }
+
+ /**
+ * @expectedException Exception
+ */
+ public function testAnyUnpackDecodeError()
+ {
+ $any = new Any();
+ $any->setTypeUrl("type.googleapis.com/foo.TestMessage");
+ $any->setValue("abc");
+ $any->unpack();
+ }
+
+ public function testApi()
+ {
+ $m = new Api();
+
+ $m->setName("a");
+ $this->assertSame("a", $m->getName());
+
+ $m->setMethods([new Method()]);
+ $this->assertSame(1, count($m->getMethods()));
+
+ $m->setOptions([new Option()]);
+ $this->assertSame(1, count($m->getOptions()));
+
+ $m->setVersion("a");
+ $this->assertSame("a", $m->getVersion());
+
+ $m->setSourceContext(new SourceContext());
+ $this->assertFalse(is_null($m->getSourceContext()));
+
+ $m->setMixins([new Mixin()]);
+ $this->assertSame(1, count($m->getMixins()));
+
+ $m->setSyntax(Syntax::SYNTAX_PROTO2);
+ $this->assertSame(Syntax::SYNTAX_PROTO2, $m->getSyntax());
+
+ $m = new Method();
+
+ $m->setName("a");
+ $this->assertSame("a", $m->getName());
+
+ $m->setRequestTypeUrl("a");
+ $this->assertSame("a", $m->getRequestTypeUrl());
+
+ $m->setRequestStreaming(true);
+ $this->assertSame(true, $m->getRequestStreaming());
+
+ $m->setResponseTypeUrl("a");
+ $this->assertSame("a", $m->getResponseTypeUrl());
+
+ $m->setResponseStreaming(true);
+ $this->assertSame(true, $m->getResponseStreaming());
+
+ $m->setOptions([new Option()]);
+ $this->assertSame(1, count($m->getOptions()));
+
+ $m = new Mixin();
+
+ $m->setName("a");
+ $this->assertSame("a", $m->getName());
+
+ $m->setRoot("a");
+ $this->assertSame("a", $m->getRoot());
+ }
+
+ public function testEnum()
+ {
+ $m = new Enum();
+
+ $m->setName("a");
+ $this->assertSame("a", $m->getName());
+
+ $m->setEnumvalue([new EnumValue()]);
+ $this->assertSame(1, count($m->getEnumvalue()));
+
+ $m->setOptions([new Option()]);
+ $this->assertSame(1, count($m->getOptions()));
+
+ $m->setSourceContext(new SourceContext());
+ $this->assertFalse(is_null($m->getSourceContext()));
+
+ $m->setSyntax(Syntax::SYNTAX_PROTO2);
+ $this->assertSame(Syntax::SYNTAX_PROTO2, $m->getSyntax());
+ }
+
+ public function testEnumValue()
+ {
+ $m = new EnumValue();
+
+ $m->setName("a");
+ $this->assertSame("a", $m->getName());
+
+ $m->setNumber(1);
+ $this->assertSame(1, $m->getNumber());
+
+ $m->setOptions([new Option()]);
+ $this->assertSame(1, count($m->getOptions()));
+ }
-class WellKnownTest extends PHPUnit_Framework_TestCase {
+ public function testField()
+ {
+ $m = new Field();
- public function testNone() {
- $msg = new GPBEmpty();
+ $m->setKind(Field_Kind::TYPE_DOUBLE);
+ $this->assertSame(Field_Kind::TYPE_DOUBLE, $m->getKind());
+
+ $m->setCardinality(Field_Cardinality::CARDINALITY_OPTIONAL);
+ $this->assertSame(Field_Cardinality::CARDINALITY_OPTIONAL, $m->getCardinality());
+
+ $m->setNumber(1);
+ $this->assertSame(1, $m->getNumber());
+
+ $m->setName("a");
+ $this->assertSame("a", $m->getName());
+
+ $m->setTypeUrl("a");
+ $this->assertSame("a", $m->getTypeUrl());
+
+ $m->setOneofIndex(1);
+ $this->assertSame(1, $m->getOneofIndex());
+
+ $m->setPacked(true);
+ $this->assertSame(true, $m->getPacked());
+
+ $m->setOptions([new Option()]);
+ $this->assertSame(1, count($m->getOptions()));
+
+ $m->setJsonName("a");
+ $this->assertSame("a", $m->getJsonName());
+
+ $m->setDefaultValue("a");
+ $this->assertSame("a", $m->getDefaultValue());
+ }
+
+ public function testFieldMask()
+ {
+ $m = new FieldMask();
+ $m->setPaths(["a"]);
+ $this->assertSame(1, count($m->getPaths()));
+ }
+
+ public function testOption()
+ {
+ $m = new Option();
+
+ $m->setName("a");
+ $this->assertSame("a", $m->getName());
+
+ $m->setValue(new Any());
+ $this->assertFalse(is_null($m->getValue()));
+ }
+
+ public function testSourceContext()
+ {
+ $m = new SourceContext();
+ $m->setFileName("a");
+ $this->assertSame("a", $m->getFileName());
+ }
+
+ public function testStruct()
+ {
+ $m = new ListValue();
+ $m->setValues([new Value()]);
+ $this->assertSame(1, count($m->getValues()));
+
+ $m = new Value();
+
+ $m->setNullValue(NullValue::NULL_VALUE);
+ $this->assertSame(NullValue::NULL_VALUE, $m->getNullValue());
+ $this->assertSame("null_value", $m->getKind());
+
+ $m->setNumberValue(1.0);
+ $this->assertSame(1.0, $m->getNumberValue());
+ $this->assertSame("number_value", $m->getKind());
+
+ $m->setStringValue("a");
+ $this->assertSame("a", $m->getStringValue());
+ $this->assertSame("string_value", $m->getKind());
+
+ $m->setBoolValue(true);
+ $this->assertSame(true, $m->getBoolValue());
+ $this->assertSame("bool_value", $m->getKind());
+
+ $m->setStructValue(new Struct());
+ $this->assertFalse(is_null($m->getStructValue()));
+ $this->assertSame("struct_value", $m->getKind());
+
+ $m->setListValue(new ListValue());
+ $this->assertFalse(is_null($m->getListValue()));
+ $this->assertSame("list_value", $m->getKind());
+
+ $m = new Struct();
+ $m->setFields(array("a"=>new Value()));
+ $this->assertSame(1, count($m->getFields()));
+ }
+
+ public function testTimestamp()
+ {
+ $timestamp = new Timestamp();
+
+ $timestamp->setSeconds(1);
+ $timestamp->setNanos(2);
+ $this->assertEquals(1, $timestamp->getSeconds());
+ $this->assertSame(2, $timestamp->getNanos());
+
+ date_default_timezone_set('UTC');
+ $from = new DateTime('2011-01-01T15:03:01.012345UTC');
+ $timestamp->fromDateTime($from);
+ $this->assertEquals($from->format('U'), $timestamp->getSeconds());
+ $this->assertSame(0, $timestamp->getNanos());
+
+ $to = $timestamp->toDateTime();
+ $this->assertSame(\DateTime::class, get_class($to));
+ $this->assertSame($from->format('U'), $to->format('U'));
+ }
+
+ public function testType()
+ {
+ $m = new Type();
+
+ $m->setName("a");
+ $this->assertSame("a", $m->getName());
+
+ $m->setFields([new Field()]);
+ $this->assertSame(1, count($m->getFields()));
+
+ $m->setOneofs(["a"]);
+ $this->assertSame(1, count($m->getOneofs()));
+
+ $m->setOptions([new Option()]);
+ $this->assertSame(1, count($m->getOptions()));
+
+ $m->setSourceContext(new SourceContext());
+ $this->assertFalse(is_null($m->getSourceContext()));
+
+ $m->setSyntax(Syntax::SYNTAX_PROTO2);
+ $this->assertSame(Syntax::SYNTAX_PROTO2, $m->getSyntax());
+ }
+
+ public function testDuration()
+ {
+ $duration = new Duration();
+
+ $duration->setSeconds(1);
+ $duration->setNanos(2);
+ $this->assertEquals(1, $duration->getSeconds());
+ $this->assertSame(2, $duration->getNanos());
}
+ public function testWrappers()
+ {
+ $m = new DoubleValue();
+ $m->setValue(1.0);
+ $this->assertSame(1.0, $m->getValue());
+
+ $m = new FloatValue();
+ $m->setValue(1.0);
+ $this->assertSame(1.0, $m->getValue());
+
+ $m = new Int64Value();
+ $m->setValue(1);
+ $this->assertEquals(1, $m->getValue());
+
+ $m = new UInt64Value();
+ $m->setValue(1);
+ $this->assertEquals(1, $m->getValue());
+
+ $m = new Int32Value();
+ $m->setValue(1);
+ $this->assertSame(1, $m->getValue());
+
+ $m = new UInt32Value();
+ $m->setValue(1);
+ $this->assertSame(1, $m->getValue());
+
+ $m = new BoolValue();
+ $m->setValue(true);
+ $this->assertSame(true, $m->getValue());
+
+ $m = new StringValue();
+ $m->setValue("a");
+ $this->assertSame("a", $m->getValue());
+
+ $m = new BytesValue();
+ $m->setValue("a");
+ $this->assertSame("a", $m->getValue());
+ }
}
diff --git a/protobuf.bzl b/protobuf.bzl
index 3998e77b..23380bab 100644
--- a/protobuf.bzl
+++ b/protobuf.bzl
@@ -4,7 +4,24 @@ def _GetPath(ctx, path):
else:
return path
+def _IsNewExternal(ctx):
+ # Bazel 0.4.4 and older have genfiles paths that look like:
+ # bazel-out/local-fastbuild/genfiles/external/repo/foo
+ # After the exec root rearrangement, they look like:
+ # ../repo/bazel-out/local-fastbuild/genfiles/foo
+ return ctx.label.workspace_root.startswith("../")
+
def _GenDir(ctx):
+ if _IsNewExternal(ctx):
+ # We are using the fact that Bazel 0.4.4+ provides repository-relative paths
+ # for ctx.genfiles_dir.
+ return ctx.genfiles_dir.path + (
+ "/" + ctx.attr.includes[0] if ctx.attr.includes and ctx.attr.includes[0] else "")
+ # This means that we're either in the old version OR the new version in the local repo.
+ # Either way, appending the source path to the genfiles dir works.
+ return ctx.var["GENDIR"] + "/" + _SourceDir(ctx)
+
+def _SourceDir(ctx):
if not ctx.attr.includes:
return ctx.label.workspace_root
if not ctx.attr.includes[0]:
@@ -51,9 +68,10 @@ def _proto_gen_impl(ctx):
srcs = ctx.files.srcs
deps = []
deps += ctx.files.srcs
+ source_dir = _SourceDir(ctx)
gen_dir = _GenDir(ctx)
- if gen_dir:
- import_flags = ["-I" + gen_dir, "-I" + ctx.var["GENDIR"] + "/" + gen_dir]
+ if source_dir:
+ import_flags = ["-I" + source_dir, "-I" + gen_dir]
else:
import_flags = ["-I."]
@@ -63,9 +81,9 @@ def _proto_gen_impl(ctx):
args = []
if ctx.attr.gen_cc:
- args += ["--cpp_out=" + ctx.var["GENDIR"] + "/" + gen_dir]
+ args += ["--cpp_out=" + gen_dir]
if ctx.attr.gen_py:
- args += ["--python_out=" + ctx.var["GENDIR"] + "/" + gen_dir]
+ args += ["--python_out=" + gen_dir]
inputs = srcs + deps
if ctx.executable.plugin:
@@ -76,7 +94,7 @@ def _proto_gen_impl(ctx):
if not lang:
fail("cannot infer the target language of plugin", "plugin_language")
- outdir = ctx.var["GENDIR"] + "/" + gen_dir
+ outdir = gen_dir
if ctx.attr.plugin_options:
outdir = ",".join(ctx.attr.plugin_options) + ":" + outdir
args += ["--plugin=protoc-gen-%s=%s" % (lang, plugin.path)]
@@ -90,6 +108,7 @@ def _proto_gen_impl(ctx):
arguments=args + import_flags + [s.path for s in srcs],
executable=ctx.executable.protoc,
mnemonic="ProtoCompile",
+ use_default_shell_env=True,
)
return struct(
@@ -141,7 +160,7 @@ Args:
compiler.
plugin_language: the language of the generated sources
plugin_options: a list of options to be passed to the plugin
- gen_cc: generates C++ sources in addition to the ones from the plugin.
+ gen_cc: generates C++ sources in addition to the ones from the plugin.
gen_py: generates Python sources in addition to the ones from the plugin.
outs: a list of labels of the expected outputs from the protocol compiler.
"""
@@ -226,9 +245,9 @@ def cc_proto_library(
)
if default_runtime and not default_runtime in cc_libs:
- cc_libs += [default_runtime]
+ cc_libs = cc_libs + [default_runtime]
if use_grpc_plugin:
- cc_libs += ["//external:grpc_lib"]
+ cc_libs = cc_libs + ["//external:grpc_lib"]
native.cc_library(
name=name,
@@ -245,10 +264,11 @@ def internal_gen_well_known_protos_java(srcs):
srcs: the well known protos
"""
root = Label("%s//protobuf_java" % (REPOSITORY_NAME)).workspace_root
+ pkg = PACKAGE_NAME + "/" if PACKAGE_NAME else ""
if root == "":
- include = " -Isrc "
+ include = " -I%ssrc " % pkg
else:
- include = " -I%s/src " % root
+ include = " -I%s/%ssrc " % (root, pkg)
native.genrule(
name = "gen_well_known_protos_java",
srcs = srcs,
@@ -351,7 +371,7 @@ def py_proto_library(
)
if default_runtime and not default_runtime in py_libs + deps:
- py_libs += [default_runtime]
+ py_libs = py_libs + [default_runtime]
native.py_library(
name=name,
diff --git a/protoc-artifacts/Dockerfile b/protoc-artifacts/Dockerfile
index 5143b028..43e6863c 100644
--- a/protoc-artifacts/Dockerfile
+++ b/protoc-artifacts/Dockerfile
@@ -15,9 +15,10 @@ RUN yum install -y git \
# Install Java 8
RUN wget -q --no-cookies --no-check-certificate \
- --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/8u45-b14/jdk-8u45-linux-x64.tar.gz" \
+ --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" \
+ "http://download.oracle.com/otn-pub/java/jdk/8u131-b11/d54c1d3a095b4ff2b6607d096fa80163/jdk-8u131-linux-x64.tar.gz" \
-O - | tar xz -C /var/local
-ENV JAVA_HOME /var/local/jdk1.8.0_45
+ENV JAVA_HOME /var/local/jdk1.8.0_131
ENV PATH $JAVA_HOME/bin:$PATH
# Install Maven
@@ -30,7 +31,7 @@ RUN wget http://people.centos.org/tru/devtools-1.1/devtools-1.1.repo -P /etc/yum
RUN bash -c 'echo "enabled=1" >> /etc/yum.repos.d/devtools-1.1.repo'
RUN bash -c "sed -e 's/\$basearch/i386/g' /etc/yum.repos.d/devtools-1.1.repo > /etc/yum.repos.d/devtools-i386-1.1.repo"
RUN sed -e 's/testing-/testing-i386-/g' -i /etc/yum.repos.d/devtools-i386-1.1.repo
-RUN yum install -y devtoolset-1.1 \
+RUN rpm --rebuilddb && yum install -y devtoolset-1.1 \
devtoolset-1.1-libstdc++-devel \
devtoolset-1.1-libstdc++-devel.i686
diff --git a/protoc-artifacts/README.md b/protoc-artifacts/README.md
index 50629209..b306c7c3 100644
--- a/protoc-artifacts/README.md
+++ b/protoc-artifacts/README.md
@@ -68,10 +68,11 @@ configure GPG and Sonatype account.
You need to perform the deployment for every platform that you want to
support. DO NOT close the staging repository until you have done the
deployment for all platforms. Currently the following platforms are supported:
-- Linux (x86_32 and x86_64)
+- Linux (x86_32, x86_64 and cross compiled aarch_64)
- Windows (x86_32 and x86_64) with
- - Cygwin64 with MinGW compilers (x86_64)
- - MSYS with MinGW32 (x86_32)
+ * Cygwin64 with MinGW compilers (x86_64)
+ * MSYS with MinGW32 (x86_32)
+ * Cross compile in Linux with MinGW-w64 (x86_32, x86_64)
- MacOSX (x86_32 and x86_64)
As for MSYS2/MinGW64 for Windows: protoc will build, but it insists on
@@ -98,6 +99,12 @@ $ mvn clean deploy -P release -Dstaging.repository=comgoogle-123
A 32-bit artifact can be deployed from a 64-bit host with
``-Dos.detected.arch=x86_32``
+An arm64 artifact can be deployed from x86 host with
+``-Dos.detected.arch=aarch_64``
+
+A windows artifact can be deployed from a linux machine with
+``-Dos.detected.name=windows``
+
When you have done deployment for all platforms, go to
https://oss.sonatype.org/#stagingRepositories, verify that the staging
repository has all the binaries, close and release this repository.
@@ -173,5 +180,7 @@ We have successfully built artifacts on the following environments:
- Centos 6.6 (within Docker 1.6.1)
- Ubuntu 14.04.2 64-bit
- Windows x86_32: MSYS with ``mingw32-gcc-g++ 4.8.1-4`` on Windows 7 64-bit
+- Windows x86_32: Cross compile with ``i686-w64-mingw32-g++ 4.8.2`` on Ubuntu 14.04.2 64-bit
- Windows x86_64: Cygwin64 with ``mingw64-x86_64-gcc-g++ 4.8.3-1`` on Windows 7 64-bit
+- Windows x86_64: Cross compile with ``x86_64-w64-mingw32-g++ 4.8.2`` on Ubuntu 14.04.2 64-bit
- Mac OS X x86_32 and x86_64: Mac OS X 10.9.5
diff --git a/protoc-artifacts/build-protoc.sh b/protoc-artifacts/build-protoc.sh
index e31948e9..57523a41 100755
--- a/protoc-artifacts/build-protoc.sh
+++ b/protoc-artifacts/build-protoc.sh
@@ -185,8 +185,6 @@ elif [[ "$(uname)" == Linux* ]]; then
fi
elif [[ "$OS" == windows ]]; then
# Cross-compilation for Windows
- # TODO(zhangkun83) MinGW 64 always adds dependency on libwinpthread-1.dll,
- # which is undesirable for repository deployment.
CONFIGURE_ARGS="$CONFIGURE_ARGS"
if [[ "$ARCH" == x86_64 ]]; then
CONFIGURE_ARGS="$CONFIGURE_ARGS --host=x86_64-w64-mingw32"
@@ -215,8 +213,11 @@ fi
# Statically link libgcc and libstdc++.
# -s to produce stripped binary.
-# And they don't work under Mac.
-if [[ "$OS" != osx ]]; then
+if [[ "$OS" == windows ]]; then
+ # Also static link libpthread required by mingw64
+ LDFLAGS="$LDFLAGS -static-libgcc -static-libstdc++ -Wl,-Bstatic -lstdc++ -lpthread -s"
+elif [[ "$OS" != osx ]]; then
+ # And they don't work under Mac.
LDFLAGS="$LDFLAGS -static-libgcc -static-libstdc++ -s"
fi
diff --git a/protoc-artifacts/build-zip.sh b/protoc-artifacts/build-zip.sh
index 3c5e887b..a124ed7c 100755
--- a/protoc-artifacts/build-zip.sh
+++ b/protoc-artifacts/build-zip.sh
@@ -73,6 +73,10 @@ compiler (protoc). This binary is intended for users who want to use Protocol
Buffers in languages other than C++ but do not want to compile protoc
themselves. To install, simply place this binary somewhere in your PATH.
+If you intend to use the included well known types then don't forget to
+copy the contents of the 'include' directory somewhere as well, for example
+into '/usr/local/include/'.
+
Please refer to our official github site for more installation instructions:
https://github.com/google/protobuf
EOF
diff --git a/protoc-artifacts/pom.xml b/protoc-artifacts/pom.xml
index 680154b1..c6f5a77f 100644
--- a/protoc-artifacts/pom.xml
+++ b/protoc-artifacts/pom.xml
@@ -10,7 +10,7 @@
</parent>
<groupId>com.google.protobuf</groupId>
<artifactId>protoc</artifactId>
- <version>3.1.0</version>
+ <version>3.4.1</version>
<packaging>pom</packaging>
<name>Protobuf Compiler</name>
<description>
@@ -21,8 +21,8 @@
<url>https://developers.google.com/protocol-buffers/</url>
<licenses>
<license>
- <name>New BSD license</name>
- <url>http://www.opensource.org/licenses/bsd-license.php</url>
+ <name>3-Clause BSD License</name>
+ <url>https://opensource.org/licenses/BSD-3-Clause</url>
<distribution>repo</distribution>
</license>
</licenses>
diff --git a/python/MANIFEST.in b/python/MANIFEST.in
index 26088826..5fb01922 100644
--- a/python/MANIFEST.in
+++ b/python/MANIFEST.in
@@ -4,6 +4,9 @@ exclude google/protobuf/internal/*_test.py
exclude google/protobuf/internal/*.proto
exclude google/protobuf/internal/test_util.py
+recursive-include google *.cc
+recursive-include google *.h
+
recursive-exclude google *_test.py
recursive-exclude google *_test.proto
recursive-exclude google unittest*_pb2.py
diff --git a/python/README.md b/python/README.md
index 8f3db785..4c194297 100644
--- a/python/README.md
+++ b/python/README.md
@@ -32,77 +32,84 @@ Installation
1) Make sure you have Python 2.6 or newer. If in doubt, run:
- $ python -V
+ $ python -V
2) If you do not have setuptools installed, note that it will be
- downloaded and installed automatically as soon as you run setup.py.
+ downloaded and installed automatically as soon as you run `setup.py`.
If you would rather install it manually, you may do so by following
- the instructions on this page:
+ the instructions on [this page](https://packaging.python.org/en/latest/installing.html#setup-for-installing-packages).
- https://packaging.python.org/en/latest/installing.html#setup-for-installing-packages
-
-3) Build the C++ code, or install a binary distribution of protoc. If
+3) Build the C++ code, or install a binary distribution of `protoc`. If
you install a binary distribution, make sure that it is the same
version as this package. If in doubt, run:
- $ protoc --version
+ $ protoc --version
4) Build and run the tests:
- $ python setup.py build
- $ python setup.py test
+ $ python setup.py build
+ $ python setup.py test
+
+ To build, test, and use the C++ implementation, you must first compile
+ `libprotobuf.so`:
+
+ $ (cd .. && make)
+
+ On OS X:
+
+ If you are running a Homebrew-provided Python, you must make sure another
+ version of protobuf is not already installed, as Homebrew's Python will
+ search `/usr/local/lib` for `libprotobuf.so` before it searches
+ `../src/.libs`.
- To build, test, and use the C++ implementation, you must first compile
- libprotobuf.so:
+ You can either unlink Homebrew's protobuf or install the `libprotobuf` you
+ built earlier:
- $ (cd .. && make)
+ $ brew unlink protobuf
- On OS X:
+ or
- If you are running a homebrew-provided python, you must make sure another
- version of protobuf is not already installed, as homebrew's python will
- search /usr/local/lib for libprotobuf.so before it searches ../src/.libs
- You can either unlink homebrew's protobuf or install the libprotobuf you
- built earlier:
+ $ (cd .. && make install)
- $ brew unlink protobuf
- or
- $ (cd .. && make install)
+ On other *nix:
- On other *nix:
+ You must make `libprotobuf.so` dynamically available. You can either
+ install libprotobuf you built earlier, or set `LD_LIBRARY_PATH`:
- You must make libprotobuf.so dynamically available. You can either
- install libprotobuf you built earlier, or set LD_LIBRARY_PATH:
+ $ export LD_LIBRARY_PATH=../src/.libs
- $ export LD_LIBRARY_PATH=../src/.libs
- or
- $ (cd .. && make install)
+ or
- To build the C++ implementation run:
- $ python setup.py build --cpp_implementation
+ $ (cd .. && make install)
- Then run the tests like so:
- $ python setup.py test --cpp_implementation
+ To build the C++ implementation run:
+
+ $ python setup.py build --cpp_implementation
+
+ Then run the tests like so:
+
+ $ python setup.py test --cpp_implementation
If some tests fail, this library may not work correctly on your
system. Continue at your own risk.
Please note that there is a known problem with some versions of
Python on Cygwin which causes the tests to fail after printing the
- error: "sem_init: Resource temporarily unavailable". This appears
- to be a bug either in Cygwin or in Python:
- http://www.cygwin.com/ml/cygwin/2005-07/msg01378.html
+ error: `sem_init: Resource temporarily unavailable`. This appears
+ to be a [bug either in Cygwin or in
+ Python](http://www.cygwin.com/ml/cygwin/2005-07/msg01378.html).
+
We do not know if or when it might be fixed. We also do not know
how likely it is that this bug will affect users in practice.
5) Install:
- $ python setup.py install
+ $ python setup.py install
- or:
+ or:
- $ (cd .. && make install)
- $ python setup.py install --cpp_implementation
+ $ (cd .. && make install)
+ $ python setup.py install --cpp_implementation
This step may require superuser privileges.
NOTE: To use C++ implementation, you need to export an environment
diff --git a/python/compatibility_tests/v2.5.0/protos/python/google/protobuf/internal/factory_test1.proto b/python/compatibility_tests/v2.5.0/protos/python/google/protobuf/internal/factory_test1.proto
new file mode 100644
index 00000000..9f55e037
--- /dev/null
+++ b/python/compatibility_tests/v2.5.0/protos/python/google/protobuf/internal/factory_test1.proto
@@ -0,0 +1,55 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// http://code.google.com/p/protobuf/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+// Author: matthewtoia@google.com (Matt Toia)
+
+
+package google.protobuf.python.internal;
+
+
+enum Factory1Enum {
+ FACTORY_1_VALUE_0 = 0;
+ FACTORY_1_VALUE_1 = 1;
+}
+
+message Factory1Message {
+ optional Factory1Enum factory_1_enum = 1;
+ enum NestedFactory1Enum {
+ NESTED_FACTORY_1_VALUE_0 = 0;
+ NESTED_FACTORY_1_VALUE_1 = 1;
+ }
+ optional NestedFactory1Enum nested_factory_1_enum = 2;
+ message NestedFactory1Message {
+ optional string value = 1;
+ }
+ optional NestedFactory1Message nested_factory_1_message = 3;
+ optional int32 scalar_value = 4;
+ repeated string list_value = 5;
+}
diff --git a/python/compatibility_tests/v2.5.0/protos/python/google/protobuf/internal/factory_test2.proto b/python/compatibility_tests/v2.5.0/protos/python/google/protobuf/internal/factory_test2.proto
new file mode 100644
index 00000000..d3ce4d7f
--- /dev/null
+++ b/python/compatibility_tests/v2.5.0/protos/python/google/protobuf/internal/factory_test2.proto
@@ -0,0 +1,77 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// http://code.google.com/p/protobuf/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+// Author: matthewtoia@google.com (Matt Toia)
+
+
+package google.protobuf.python.internal;
+
+import "google/protobuf/internal/factory_test1.proto";
+
+
+enum Factory2Enum {
+ FACTORY_2_VALUE_0 = 0;
+ FACTORY_2_VALUE_1 = 1;
+}
+
+message Factory2Message {
+ required int32 mandatory = 1;
+ optional Factory2Enum factory_2_enum = 2;
+ enum NestedFactory2Enum {
+ NESTED_FACTORY_2_VALUE_0 = 0;
+ NESTED_FACTORY_2_VALUE_1 = 1;
+ }
+ optional NestedFactory2Enum nested_factory_2_enum = 3;
+ message NestedFactory2Message {
+ optional string value = 1;
+ }
+ optional NestedFactory2Message nested_factory_2_message = 4;
+ optional Factory1Message factory_1_message = 5;
+ optional Factory1Enum factory_1_enum = 6;
+ optional Factory1Message.NestedFactory1Enum nested_factory_1_enum = 7;
+ optional Factory1Message.NestedFactory1Message nested_factory_1_message = 8;
+ optional Factory2Message circular_message = 9;
+ optional string scalar_value = 10;
+ repeated string list_value = 11;
+ repeated group Grouped = 12 {
+ optional string part_1 = 13;
+ optional string part_2 = 14;
+ }
+ optional LoopMessage loop = 15;
+ optional int32 int_with_default = 16 [default = 1776];
+ optional double double_with_default = 17 [default = 9.99];
+ optional string string_with_default = 18 [default = "hello world"];
+ optional bool bool_with_default = 19 [default = false];
+ optional Factory2Enum enum_with_default = 20 [default = FACTORY_2_VALUE_1];
+}
+
+message LoopMessage {
+ optional Factory2Message loop = 1;
+}
diff --git a/python/compatibility_tests/v2.5.0/protos/python/google/protobuf/internal/more_extensions.proto b/python/compatibility_tests/v2.5.0/protos/python/google/protobuf/internal/more_extensions.proto
new file mode 100644
index 00000000..e2d97010
--- /dev/null
+++ b/python/compatibility_tests/v2.5.0/protos/python/google/protobuf/internal/more_extensions.proto
@@ -0,0 +1,58 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// http://code.google.com/p/protobuf/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+// Author: robinson@google.com (Will Robinson)
+
+
+package google.protobuf.internal;
+
+
+message TopLevelMessage {
+ optional ExtendedMessage submessage = 1;
+}
+
+
+message ExtendedMessage {
+ extensions 1 to max;
+}
+
+
+message ForeignMessage {
+ optional int32 foreign_message_int = 1;
+}
+
+
+extend ExtendedMessage {
+ optional int32 optional_int_extension = 1;
+ optional ForeignMessage optional_message_extension = 2;
+
+ repeated int32 repeated_int_extension = 3;
+ repeated ForeignMessage repeated_message_extension = 4;
+}
diff --git a/python/compatibility_tests/v2.5.0/protos/python/google/protobuf/internal/more_extensions_dynamic.proto b/python/compatibility_tests/v2.5.0/protos/python/google/protobuf/internal/more_extensions_dynamic.proto
new file mode 100644
index 00000000..df98ac4b
--- /dev/null
+++ b/python/compatibility_tests/v2.5.0/protos/python/google/protobuf/internal/more_extensions_dynamic.proto
@@ -0,0 +1,49 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// http://code.google.com/p/protobuf/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+// Author: jasonh@google.com (Jason Hsueh)
+//
+// This file is used to test a corner case in the CPP implementation where the
+// generated C++ type is available for the extendee, but the extension is
+// defined in a file whose C++ type is not in the binary.
+
+
+import "google/protobuf/internal/more_extensions.proto";
+
+package google.protobuf.internal;
+
+message DynamicMessageType {
+ optional int32 a = 1;
+}
+
+extend ExtendedMessage {
+ optional int32 dynamic_int32_extension = 100;
+ optional DynamicMessageType dynamic_message_extension = 101;
+}
diff --git a/python/compatibility_tests/v2.5.0/protos/python/google/protobuf/internal/more_messages.proto b/python/compatibility_tests/v2.5.0/protos/python/google/protobuf/internal/more_messages.proto
new file mode 100644
index 00000000..c701b446
--- /dev/null
+++ b/python/compatibility_tests/v2.5.0/protos/python/google/protobuf/internal/more_messages.proto
@@ -0,0 +1,51 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// http://code.google.com/p/protobuf/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+// Author: robinson@google.com (Will Robinson)
+
+
+package google.protobuf.internal;
+
+// A message where tag numbers are listed out of order, to allow us to test our
+// canonicalization of serialized output, which should always be in tag order.
+// We also mix in some extensions for extra fun.
+message OutOfOrderFields {
+ optional sint32 optional_sint32 = 5;
+ extensions 4 to 4;
+ optional uint32 optional_uint32 = 3;
+ extensions 2 to 2;
+ optional int32 optional_int32 = 1;
+};
+
+
+extend OutOfOrderFields {
+ optional uint64 optional_uint64 = 4;
+ optional int64 optional_int64 = 2;
+}
diff --git a/python/compatibility_tests/v2.5.0/protos/python/google/protobuf/internal/test_bad_identifiers.proto b/python/compatibility_tests/v2.5.0/protos/python/google/protobuf/internal/test_bad_identifiers.proto
new file mode 100644
index 00000000..6a82299a
--- /dev/null
+++ b/python/compatibility_tests/v2.5.0/protos/python/google/protobuf/internal/test_bad_identifiers.proto
@@ -0,0 +1,52 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// http://code.google.com/p/protobuf/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+// Author: kenton@google.com (Kenton Varda)
+
+
+package protobuf_unittest;
+
+option py_generic_services = true;
+
+message TestBadIdentifiers {
+ extensions 100 to max;
+}
+
+// Make sure these reasonable extension names don't conflict with internal
+// variables.
+extend TestBadIdentifiers {
+ optional string message = 100 [default="foo"];
+ optional string descriptor = 101 [default="bar"];
+ optional string reflection = 102 [default="baz"];
+ optional string service = 103 [default="qux"];
+}
+
+message AnotherMessage {}
+service AnotherService {}
diff --git a/python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/descriptor.proto b/python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/descriptor.proto
new file mode 100644
index 00000000..a785f79f
--- /dev/null
+++ b/python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/descriptor.proto
@@ -0,0 +1,620 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// http://code.google.com/p/protobuf/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+// Author: kenton@google.com (Kenton Varda)
+// Based on original Protocol Buffers design by
+// Sanjay Ghemawat, Jeff Dean, and others.
+//
+// The messages in this file describe the definitions found in .proto files.
+// A valid .proto file can be translated directly to a FileDescriptorProto
+// without any other information (e.g. without reading its imports).
+
+
+
+package google.protobuf;
+option java_package = "com.google.protobuf";
+option java_outer_classname = "DescriptorProtos";
+
+// descriptor.proto must be optimized for speed because reflection-based
+// algorithms don't work during bootstrapping.
+option optimize_for = SPEED;
+
+// The protocol compiler can output a FileDescriptorSet containing the .proto
+// files it parses.
+message FileDescriptorSet {
+ repeated FileDescriptorProto file = 1;
+}
+
+// Describes a complete .proto file.
+message FileDescriptorProto {
+ optional string name = 1; // file name, relative to root of source tree
+ optional string package = 2; // e.g. "foo", "foo.bar", etc.
+
+ // Names of files imported by this file.
+ repeated string dependency = 3;
+ // Indexes of the public imported files in the dependency list above.
+ repeated int32 public_dependency = 10;
+ // Indexes of the weak imported files in the dependency list.
+ // For Google-internal migration only. Do not use.
+ repeated int32 weak_dependency = 11;
+
+ // All top-level definitions in this file.
+ repeated DescriptorProto message_type = 4;
+ repeated EnumDescriptorProto enum_type = 5;
+ repeated ServiceDescriptorProto service = 6;
+ repeated FieldDescriptorProto extension = 7;
+
+ optional FileOptions options = 8;
+
+ // This field contains optional information about the original source code.
+ // You may safely remove this entire field whithout harming runtime
+ // functionality of the descriptors -- the information is needed only by
+ // development tools.
+ optional SourceCodeInfo source_code_info = 9;
+}
+
+// Describes a message type.
+message DescriptorProto {
+ optional string name = 1;
+
+ repeated FieldDescriptorProto field = 2;
+ repeated FieldDescriptorProto extension = 6;
+
+ repeated DescriptorProto nested_type = 3;
+ repeated EnumDescriptorProto enum_type = 4;
+
+ message ExtensionRange {
+ optional int32 start = 1;
+ optional int32 end = 2;
+ }
+ repeated ExtensionRange extension_range = 5;
+
+ optional MessageOptions options = 7;
+}
+
+// Describes a field within a message.
+message FieldDescriptorProto {
+ enum Type {
+ // 0 is reserved for errors.
+ // Order is weird for historical reasons.
+ TYPE_DOUBLE = 1;
+ TYPE_FLOAT = 2;
+ // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if
+ // negative values are likely.
+ TYPE_INT64 = 3;
+ TYPE_UINT64 = 4;
+ // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if
+ // negative values are likely.
+ TYPE_INT32 = 5;
+ TYPE_FIXED64 = 6;
+ TYPE_FIXED32 = 7;
+ TYPE_BOOL = 8;
+ TYPE_STRING = 9;
+ TYPE_GROUP = 10; // Tag-delimited aggregate.
+ TYPE_MESSAGE = 11; // Length-delimited aggregate.
+
+ // New in version 2.
+ TYPE_BYTES = 12;
+ TYPE_UINT32 = 13;
+ TYPE_ENUM = 14;
+ TYPE_SFIXED32 = 15;
+ TYPE_SFIXED64 = 16;
+ TYPE_SINT32 = 17; // Uses ZigZag encoding.
+ TYPE_SINT64 = 18; // Uses ZigZag encoding.
+ };
+
+ enum Label {
+ // 0 is reserved for errors
+ LABEL_OPTIONAL = 1;
+ LABEL_REQUIRED = 2;
+ LABEL_REPEATED = 3;
+ // TODO(sanjay): Should we add LABEL_MAP?
+ };
+
+ optional string name = 1;
+ optional int32 number = 3;
+ optional Label label = 4;
+
+ // If type_name is set, this need not be set. If both this and type_name
+ // are set, this must be either TYPE_ENUM or TYPE_MESSAGE.
+ optional Type type = 5;
+
+ // For message and enum types, this is the name of the type. If the name
+ // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping
+ // rules are used to find the type (i.e. first the nested types within this
+ // message are searched, then within the parent, on up to the root
+ // namespace).
+ optional string type_name = 6;
+
+ // For extensions, this is the name of the type being extended. It is
+ // resolved in the same manner as type_name.
+ optional string extendee = 2;
+
+ // For numeric types, contains the original text representation of the value.
+ // For booleans, "true" or "false".
+ // For strings, contains the default text contents (not escaped in any way).
+ // For bytes, contains the C escaped value. All bytes >= 128 are escaped.
+ // TODO(kenton): Base-64 encode?
+ optional string default_value = 7;
+
+ optional FieldOptions options = 8;
+}
+
+// Describes an enum type.
+message EnumDescriptorProto {
+ optional string name = 1;
+
+ repeated EnumValueDescriptorProto value = 2;
+
+ optional EnumOptions options = 3;
+}
+
+// Describes a value within an enum.
+message EnumValueDescriptorProto {
+ optional string name = 1;
+ optional int32 number = 2;
+
+ optional EnumValueOptions options = 3;
+}
+
+// Describes a service.
+message ServiceDescriptorProto {
+ optional string name = 1;
+ repeated MethodDescriptorProto method = 2;
+
+ optional ServiceOptions options = 3;
+}
+
+// Describes a method of a service.
+message MethodDescriptorProto {
+ optional string name = 1;
+
+ // Input and output type names. These are resolved in the same way as
+ // FieldDescriptorProto.type_name, but must refer to a message type.
+ optional string input_type = 2;
+ optional string output_type = 3;
+
+ optional MethodOptions options = 4;
+}
+
+
+// ===================================================================
+// Options
+
+// Each of the definitions above may have "options" attached. These are
+// just annotations which may cause code to be generated slightly differently
+// or may contain hints for code that manipulates protocol messages.
+//
+// Clients may define custom options as extensions of the *Options messages.
+// These extensions may not yet be known at parsing time, so the parser cannot
+// store the values in them. Instead it stores them in a field in the *Options
+// message called uninterpreted_option. This field must have the same name
+// across all *Options messages. We then use this field to populate the
+// extensions when we build a descriptor, at which point all protos have been
+// parsed and so all extensions are known.
+//
+// Extension numbers for custom options may be chosen as follows:
+// * For options which will only be used within a single application or
+// organization, or for experimental options, use field numbers 50000
+// through 99999. It is up to you to ensure that you do not use the
+// same number for multiple options.
+// * For options which will be published and used publicly by multiple
+// independent entities, e-mail protobuf-global-extension-registry@google.com
+// to reserve extension numbers. Simply provide your project name (e.g.
+// Object-C plugin) and your porject website (if available) -- there's no need
+// to explain how you intend to use them. Usually you only need one extension
+// number. You can declare multiple options with only one extension number by
+// putting them in a sub-message. See the Custom Options section of the docs
+// for examples:
+// http://code.google.com/apis/protocolbuffers/docs/proto.html#options
+// If this turns out to be popular, a web service will be set up
+// to automatically assign option numbers.
+
+
+message FileOptions {
+
+ // Sets the Java package where classes generated from this .proto will be
+ // placed. By default, the proto package is used, but this is often
+ // inappropriate because proto packages do not normally start with backwards
+ // domain names.
+ optional string java_package = 1;
+
+
+ // If set, all the classes from the .proto file are wrapped in a single
+ // outer class with the given name. This applies to both Proto1
+ // (equivalent to the old "--one_java_file" option) and Proto2 (where
+ // a .proto always translates to a single class, but you may want to
+ // explicitly choose the class name).
+ optional string java_outer_classname = 8;
+
+ // If set true, then the Java code generator will generate a separate .java
+ // file for each top-level message, enum, and service defined in the .proto
+ // file. Thus, these types will *not* be nested inside the outer class
+ // named by java_outer_classname. However, the outer class will still be
+ // generated to contain the file's getDescriptor() method as well as any
+ // top-level extensions defined in the file.
+ optional bool java_multiple_files = 10 [default=false];
+
+ // If set true, then the Java code generator will generate equals() and
+ // hashCode() methods for all messages defined in the .proto file. This is
+ // purely a speed optimization, as the AbstractMessage base class includes
+ // reflection-based implementations of these methods.
+ optional bool java_generate_equals_and_hash = 20 [default=false];
+
+ // Generated classes can be optimized for speed or code size.
+ enum OptimizeMode {
+ SPEED = 1; // Generate complete code for parsing, serialization,
+ // etc.
+ CODE_SIZE = 2; // Use ReflectionOps to implement these methods.
+ LITE_RUNTIME = 3; // Generate code using MessageLite and the lite runtime.
+ }
+ optional OptimizeMode optimize_for = 9 [default=SPEED];
+
+ // Sets the Go package where structs generated from this .proto will be
+ // placed. There is no default.
+ optional string go_package = 11;
+
+
+
+ // Should generic services be generated in each language? "Generic" services
+ // are not specific to any particular RPC system. They are generated by the
+ // main code generators in each language (without additional plugins).
+ // Generic services were the only kind of service generation supported by
+ // early versions of proto2.
+ //
+ // Generic services are now considered deprecated in favor of using plugins
+ // that generate code specific to your particular RPC system. Therefore,
+ // these default to false. Old code which depends on generic services should
+ // explicitly set them to true.
+ optional bool cc_generic_services = 16 [default=false];
+ optional bool java_generic_services = 17 [default=false];
+ optional bool py_generic_services = 18 [default=false];
+
+ // The parser stores options it doesn't recognize here. See above.
+ repeated UninterpretedOption uninterpreted_option = 999;
+
+ // Clients can define custom options in extensions of this message. See above.
+ extensions 1000 to max;
+}
+
+message MessageOptions {
+ // Set true to use the old proto1 MessageSet wire format for extensions.
+ // This is provided for backwards-compatibility with the MessageSet wire
+ // format. You should not use this for any other reason: It's less
+ // efficient, has fewer features, and is more complicated.
+ //
+ // The message must be defined exactly as follows:
+ // message Foo {
+ // option message_set_wire_format = true;
+ // extensions 4 to max;
+ // }
+ // Note that the message cannot have any defined fields; MessageSets only
+ // have extensions.
+ //
+ // All extensions of your type must be singular messages; e.g. they cannot
+ // be int32s, enums, or repeated messages.
+ //
+ // Because this is an option, the above two restrictions are not enforced by
+ // the protocol compiler.
+ optional bool message_set_wire_format = 1 [default=false];
+
+ // Disables the generation of the standard "descriptor()" accessor, which can
+ // conflict with a field of the same name. This is meant to make migration
+ // from proto1 easier; new code should avoid fields named "descriptor".
+ optional bool no_standard_descriptor_accessor = 2 [default=false];
+
+ // The parser stores options it doesn't recognize here. See above.
+ repeated UninterpretedOption uninterpreted_option = 999;
+
+ // Clients can define custom options in extensions of this message. See above.
+ extensions 1000 to max;
+}
+
+message FieldOptions {
+ // The ctype option instructs the C++ code generator to use a different
+ // representation of the field than it normally would. See the specific
+ // options below. This option is not yet implemented in the open source
+ // release -- sorry, we'll try to include it in a future version!
+ optional CType ctype = 1 [default = STRING];
+ enum CType {
+ // Default mode.
+ STRING = 0;
+
+ CORD = 1;
+
+ STRING_PIECE = 2;
+ }
+ // The packed option can be enabled for repeated primitive fields to enable
+ // a more efficient representation on the wire. Rather than repeatedly
+ // writing the tag and type for each element, the entire array is encoded as
+ // a single length-delimited blob.
+ optional bool packed = 2;
+
+
+
+ // Should this field be parsed lazily? Lazy applies only to message-type
+ // fields. It means that when the outer message is initially parsed, the
+ // inner message's contents will not be parsed but instead stored in encoded
+ // form. The inner message will actually be parsed when it is first accessed.
+ //
+ // This is only a hint. Implementations are free to choose whether to use
+ // eager or lazy parsing regardless of the value of this option. However,
+ // setting this option true suggests that the protocol author believes that
+ // using lazy parsing on this field is worth the additional bookkeeping
+ // overhead typically needed to implement it.
+ //
+ // This option does not affect the public interface of any generated code;
+ // all method signatures remain the same. Furthermore, thread-safety of the
+ // interface is not affected by this option; const methods remain safe to
+ // call from multiple threads concurrently, while non-const methods continue
+ // to require exclusive access.
+ //
+ //
+ // Note that implementations may choose not to check required fields within
+ // a lazy sub-message. That is, calling IsInitialized() on the outher message
+ // may return true even if the inner message has missing required fields.
+ // This is necessary because otherwise the inner message would have to be
+ // parsed in order to perform the check, defeating the purpose of lazy
+ // parsing. An implementation which chooses not to check required fields
+ // must be consistent about it. That is, for any particular sub-message, the
+ // implementation must either *always* check its required fields, or *never*
+ // check its required fields, regardless of whether or not the message has
+ // been parsed.
+ optional bool lazy = 5 [default=false];
+
+ // Is this field deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for accessors, or it will be completely ignored; in the very least, this
+ // is a formalization for deprecating fields.
+ optional bool deprecated = 3 [default=false];
+
+ // EXPERIMENTAL. DO NOT USE.
+ // For "map" fields, the name of the field in the enclosed type that
+ // is the key for this map. For example, suppose we have:
+ // message Item {
+ // required string name = 1;
+ // required string value = 2;
+ // }
+ // message Config {
+ // repeated Item items = 1 [experimental_map_key="name"];
+ // }
+ // In this situation, the map key for Item will be set to "name".
+ // TODO: Fully-implement this, then remove the "experimental_" prefix.
+ optional string experimental_map_key = 9;
+
+ // For Google-internal migration only. Do not use.
+ optional bool weak = 10 [default=false];
+
+ // The parser stores options it doesn't recognize here. See above.
+ repeated UninterpretedOption uninterpreted_option = 999;
+
+ // Clients can define custom options in extensions of this message. See above.
+ extensions 1000 to max;
+}
+
+message EnumOptions {
+
+ // Set this option to false to disallow mapping different tag names to a same
+ // value.
+ optional bool allow_alias = 2 [default=true];
+
+ // The parser stores options it doesn't recognize here. See above.
+ repeated UninterpretedOption uninterpreted_option = 999;
+
+ // Clients can define custom options in extensions of this message. See above.
+ extensions 1000 to max;
+}
+
+message EnumValueOptions {
+ // The parser stores options it doesn't recognize here. See above.
+ repeated UninterpretedOption uninterpreted_option = 999;
+
+ // Clients can define custom options in extensions of this message. See above.
+ extensions 1000 to max;
+}
+
+message ServiceOptions {
+
+ // Note: Field numbers 1 through 32 are reserved for Google's internal RPC
+ // framework. We apologize for hoarding these numbers to ourselves, but
+ // we were already using them long before we decided to release Protocol
+ // Buffers.
+
+ // The parser stores options it doesn't recognize here. See above.
+ repeated UninterpretedOption uninterpreted_option = 999;
+
+ // Clients can define custom options in extensions of this message. See above.
+ extensions 1000 to max;
+}
+
+message MethodOptions {
+
+ // Note: Field numbers 1 through 32 are reserved for Google's internal RPC
+ // framework. We apologize for hoarding these numbers to ourselves, but
+ // we were already using them long before we decided to release Protocol
+ // Buffers.
+
+ // The parser stores options it doesn't recognize here. See above.
+ repeated UninterpretedOption uninterpreted_option = 999;
+
+ // Clients can define custom options in extensions of this message. See above.
+ extensions 1000 to max;
+}
+
+
+// A message representing a option the parser does not recognize. This only
+// appears in options protos created by the compiler::Parser class.
+// DescriptorPool resolves these when building Descriptor objects. Therefore,
+// options protos in descriptor objects (e.g. returned by Descriptor::options(),
+// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions
+// in them.
+message UninterpretedOption {
+ // The name of the uninterpreted option. Each string represents a segment in
+ // a dot-separated name. is_extension is true iff a segment represents an
+ // extension (denoted with parentheses in options specs in .proto files).
+ // E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents
+ // "foo.(bar.baz).qux".
+ message NamePart {
+ required string name_part = 1;
+ required bool is_extension = 2;
+ }
+ repeated NamePart name = 2;
+
+ // The value of the uninterpreted option, in whatever type the tokenizer
+ // identified it as during parsing. Exactly one of these should be set.
+ optional string identifier_value = 3;
+ optional uint64 positive_int_value = 4;
+ optional int64 negative_int_value = 5;
+ optional double double_value = 6;
+ optional bytes string_value = 7;
+ optional string aggregate_value = 8;
+}
+
+// ===================================================================
+// Optional source code info
+
+// Encapsulates information about the original source file from which a
+// FileDescriptorProto was generated.
+message SourceCodeInfo {
+ // A Location identifies a piece of source code in a .proto file which
+ // corresponds to a particular definition. This information is intended
+ // to be useful to IDEs, code indexers, documentation generators, and similar
+ // tools.
+ //
+ // For example, say we have a file like:
+ // message Foo {
+ // optional string foo = 1;
+ // }
+ // Let's look at just the field definition:
+ // optional string foo = 1;
+ // ^ ^^ ^^ ^ ^^^
+ // a bc de f ghi
+ // We have the following locations:
+ // span path represents
+ // [a,i) [ 4, 0, 2, 0 ] The whole field definition.
+ // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional).
+ // [c,d) [ 4, 0, 2, 0, 5 ] The type (string).
+ // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo).
+ // [g,h) [ 4, 0, 2, 0, 3 ] The number (1).
+ //
+ // Notes:
+ // - A location may refer to a repeated field itself (i.e. not to any
+ // particular index within it). This is used whenever a set of elements are
+ // logically enclosed in a single code segment. For example, an entire
+ // extend block (possibly containing multiple extension definitions) will
+ // have an outer location whose path refers to the "extensions" repeated
+ // field without an index.
+ // - Multiple locations may have the same path. This happens when a single
+ // logical declaration is spread out across multiple places. The most
+ // obvious example is the "extend" block again -- there may be multiple
+ // extend blocks in the same scope, each of which will have the same path.
+ // - A location's span is not always a subset of its parent's span. For
+ // example, the "extendee" of an extension declaration appears at the
+ // beginning of the "extend" block and is shared by all extensions within
+ // the block.
+ // - Just because a location's span is a subset of some other location's span
+ // does not mean that it is a descendent. For example, a "group" defines
+ // both a type and a field in a single declaration. Thus, the locations
+ // corresponding to the type and field and their components will overlap.
+ // - Code which tries to interpret locations should probably be designed to
+ // ignore those that it doesn't understand, as more types of locations could
+ // be recorded in the future.
+ repeated Location location = 1;
+ message Location {
+ // Identifies which part of the FileDescriptorProto was defined at this
+ // location.
+ //
+ // Each element is a field number or an index. They form a path from
+ // the root FileDescriptorProto to the place where the definition. For
+ // example, this path:
+ // [ 4, 3, 2, 7, 1 ]
+ // refers to:
+ // file.message_type(3) // 4, 3
+ // .field(7) // 2, 7
+ // .name() // 1
+ // This is because FileDescriptorProto.message_type has field number 4:
+ // repeated DescriptorProto message_type = 4;
+ // and DescriptorProto.field has field number 2:
+ // repeated FieldDescriptorProto field = 2;
+ // and FieldDescriptorProto.name has field number 1:
+ // optional string name = 1;
+ //
+ // Thus, the above path gives the location of a field name. If we removed
+ // the last element:
+ // [ 4, 3, 2, 7 ]
+ // this path refers to the whole field declaration (from the beginning
+ // of the label to the terminating semicolon).
+ repeated int32 path = 1 [packed=true];
+
+ // Always has exactly three or four elements: start line, start column,
+ // end line (optional, otherwise assumed same as start line), end column.
+ // These are packed into a single field for efficiency. Note that line
+ // and column numbers are zero-based -- typically you will want to add
+ // 1 to each before displaying to a user.
+ repeated int32 span = 2 [packed=true];
+
+ // If this SourceCodeInfo represents a complete declaration, these are any
+ // comments appearing before and after the declaration which appear to be
+ // attached to the declaration.
+ //
+ // A series of line comments appearing on consecutive lines, with no other
+ // tokens appearing on those lines, will be treated as a single comment.
+ //
+ // Only the comment content is provided; comment markers (e.g. //) are
+ // stripped out. For block comments, leading whitespace and an asterisk
+ // will be stripped from the beginning of each line other than the first.
+ // Newlines are included in the output.
+ //
+ // Examples:
+ //
+ // optional int32 foo = 1; // Comment attached to foo.
+ // // Comment attached to bar.
+ // optional int32 bar = 2;
+ //
+ // optional string baz = 3;
+ // // Comment attached to baz.
+ // // Another line attached to baz.
+ //
+ // // Comment attached to qux.
+ // //
+ // // Another line attached to qux.
+ // optional double qux = 4;
+ //
+ // optional string corge = 5;
+ // /* Block comment attached
+ // * to corge. Leading asterisks
+ // * will be removed. */
+ // /* Block comment attached to
+ // * grault. */
+ // optional int32 grault = 6;
+ optional string leading_comments = 3;
+ optional string trailing_comments = 4;
+ }
+}
diff --git a/python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest.proto b/python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest.proto
new file mode 100644
index 00000000..6eb2d86f
--- /dev/null
+++ b/python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest.proto
@@ -0,0 +1,719 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// http://code.google.com/p/protobuf/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+// Author: kenton@google.com (Kenton Varda)
+// Based on original Protocol Buffers design by
+// Sanjay Ghemawat, Jeff Dean, and others.
+//
+// A proto file we will use for unit testing.
+
+
+// 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
+
+import "google/protobuf/unittest_import.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.
+ optional int32 bb = 1;
+ }
+
+ enum NestedEnum {
+ FOO = 1;
+ BAR = 2;
+ BAZ = 3;
+ }
+
+ // Singular
+ optional int32 optional_int32 = 1;
+ optional int64 optional_int64 = 2;
+ optional uint32 optional_uint32 = 3;
+ optional uint64 optional_uint64 = 4;
+ optional sint32 optional_sint32 = 5;
+ optional sint64 optional_sint64 = 6;
+ optional fixed32 optional_fixed32 = 7;
+ optional fixed64 optional_fixed64 = 8;
+ optional sfixed32 optional_sfixed32 = 9;
+ optional sfixed64 optional_sfixed64 = 10;
+ optional float optional_float = 11;
+ optional double optional_double = 12;
+ optional bool optional_bool = 13;
+ optional string optional_string = 14;
+ optional bytes optional_bytes = 15;
+
+ optional group OptionalGroup = 16 {
+ optional int32 a = 17;
+ }
+
+ optional NestedMessage optional_nested_message = 18;
+ optional ForeignMessage optional_foreign_message = 19;
+ optional protobuf_unittest_import.ImportMessage optional_import_message = 20;
+
+ optional NestedEnum optional_nested_enum = 21;
+ optional ForeignEnum optional_foreign_enum = 22;
+ optional protobuf_unittest_import.ImportEnum optional_import_enum = 23;
+
+ optional string optional_string_piece = 24 [ctype=STRING_PIECE];
+ optional string optional_cord = 25 [ctype=CORD];
+
+ // Defined in unittest_import_public.proto
+ optional protobuf_unittest_import.PublicImportMessage
+ optional_public_import_message = 26;
+
+ optional NestedMessage optional_lazy_message = 27 [lazy=true];
+
+ // Repeated
+ repeated int32 repeated_int32 = 31;
+ repeated int64 repeated_int64 = 32;
+ repeated uint32 repeated_uint32 = 33;
+ repeated uint64 repeated_uint64 = 34;
+ repeated sint32 repeated_sint32 = 35;
+ repeated sint64 repeated_sint64 = 36;
+ repeated fixed32 repeated_fixed32 = 37;
+ repeated fixed64 repeated_fixed64 = 38;
+ repeated sfixed32 repeated_sfixed32 = 39;
+ repeated sfixed64 repeated_sfixed64 = 40;
+ repeated float repeated_float = 41;
+ repeated double repeated_double = 42;
+ repeated bool repeated_bool = 43;
+ repeated string repeated_string = 44;
+ repeated bytes repeated_bytes = 45;
+
+ repeated group RepeatedGroup = 46 {
+ optional int32 a = 47;
+ }
+
+ repeated NestedMessage repeated_nested_message = 48;
+ repeated 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;
+
+ repeated string repeated_string_piece = 54 [ctype=STRING_PIECE];
+ repeated string repeated_cord = 55 [ctype=CORD];
+
+ repeated NestedMessage repeated_lazy_message = 57 [lazy=true];
+
+ // Singular with defaults
+ optional int32 default_int32 = 61 [default = 41 ];
+ optional int64 default_int64 = 62 [default = 42 ];
+ optional uint32 default_uint32 = 63 [default = 43 ];
+ optional uint64 default_uint64 = 64 [default = 44 ];
+ optional sint32 default_sint32 = 65 [default = -45 ];
+ optional sint64 default_sint64 = 66 [default = 46 ];
+ optional fixed32 default_fixed32 = 67 [default = 47 ];
+ optional fixed64 default_fixed64 = 68 [default = 48 ];
+ optional sfixed32 default_sfixed32 = 69 [default = 49 ];
+ optional sfixed64 default_sfixed64 = 70 [default = -50 ];
+ optional float default_float = 71 [default = 51.5 ];
+ optional double default_double = 72 [default = 52e3 ];
+ optional bool default_bool = 73 [default = true ];
+ optional string default_string = 74 [default = "hello"];
+ optional bytes default_bytes = 75 [default = "world"];
+
+ optional NestedEnum default_nested_enum = 81 [default = BAR ];
+ optional ForeignEnum default_foreign_enum = 82 [default = FOREIGN_BAR];
+ optional protobuf_unittest_import.ImportEnum
+ default_import_enum = 83 [default = IMPORT_BAR];
+
+ optional string default_string_piece = 84 [ctype=STRING_PIECE,default="abc"];
+ optional string default_cord = 85 [ctype=CORD,default="123"];
+}
+
+message TestDeprecatedFields {
+ optional int32 deprecated_int32 = 1 [deprecated=true];
+}
+
+// Define these after TestAllTypes to make sure the compiler can handle
+// that.
+message ForeignMessage {
+ optional int32 c = 1;
+}
+
+enum ForeignEnum {
+ FOREIGN_FOO = 4;
+ FOREIGN_BAR = 5;
+ FOREIGN_BAZ = 6;
+}
+
+message TestAllExtensions {
+ extensions 1 to max;
+}
+
+extend TestAllExtensions {
+ // Singular
+ optional int32 optional_int32_extension = 1;
+ optional int64 optional_int64_extension = 2;
+ optional uint32 optional_uint32_extension = 3;
+ optional uint64 optional_uint64_extension = 4;
+ optional sint32 optional_sint32_extension = 5;
+ optional sint64 optional_sint64_extension = 6;
+ optional fixed32 optional_fixed32_extension = 7;
+ optional fixed64 optional_fixed64_extension = 8;
+ optional sfixed32 optional_sfixed32_extension = 9;
+ optional sfixed64 optional_sfixed64_extension = 10;
+ optional float optional_float_extension = 11;
+ optional double optional_double_extension = 12;
+ optional bool optional_bool_extension = 13;
+ optional string optional_string_extension = 14;
+ optional bytes optional_bytes_extension = 15;
+
+ optional group OptionalGroup_extension = 16 {
+ optional int32 a = 17;
+ }
+
+ optional TestAllTypes.NestedMessage optional_nested_message_extension = 18;
+ optional ForeignMessage optional_foreign_message_extension = 19;
+ optional protobuf_unittest_import.ImportMessage
+ optional_import_message_extension = 20;
+
+ optional TestAllTypes.NestedEnum optional_nested_enum_extension = 21;
+ optional ForeignEnum optional_foreign_enum_extension = 22;
+ optional protobuf_unittest_import.ImportEnum
+ optional_import_enum_extension = 23;
+
+ optional string optional_string_piece_extension = 24 [ctype=STRING_PIECE];
+ optional string optional_cord_extension = 25 [ctype=CORD];
+
+ optional protobuf_unittest_import.PublicImportMessage
+ optional_public_import_message_extension = 26;
+
+ optional TestAllTypes.NestedMessage
+ optional_lazy_message_extension = 27 [lazy=true];
+
+ // Repeated
+ repeated int32 repeated_int32_extension = 31;
+ repeated int64 repeated_int64_extension = 32;
+ repeated uint32 repeated_uint32_extension = 33;
+ repeated uint64 repeated_uint64_extension = 34;
+ repeated sint32 repeated_sint32_extension = 35;
+ repeated sint64 repeated_sint64_extension = 36;
+ repeated fixed32 repeated_fixed32_extension = 37;
+ repeated fixed64 repeated_fixed64_extension = 38;
+ repeated sfixed32 repeated_sfixed32_extension = 39;
+ repeated sfixed64 repeated_sfixed64_extension = 40;
+ repeated float repeated_float_extension = 41;
+ repeated double repeated_double_extension = 42;
+ repeated bool repeated_bool_extension = 43;
+ repeated string repeated_string_extension = 44;
+ repeated bytes repeated_bytes_extension = 45;
+
+ repeated group RepeatedGroup_extension = 46 {
+ optional int32 a = 47;
+ }
+
+ repeated TestAllTypes.NestedMessage repeated_nested_message_extension = 48;
+ repeated ForeignMessage repeated_foreign_message_extension = 49;
+ repeated protobuf_unittest_import.ImportMessage
+ repeated_import_message_extension = 50;
+
+ repeated TestAllTypes.NestedEnum repeated_nested_enum_extension = 51;
+ repeated ForeignEnum repeated_foreign_enum_extension = 52;
+ repeated protobuf_unittest_import.ImportEnum
+ repeated_import_enum_extension = 53;
+
+ repeated string repeated_string_piece_extension = 54 [ctype=STRING_PIECE];
+ repeated string repeated_cord_extension = 55 [ctype=CORD];
+
+ repeated TestAllTypes.NestedMessage
+ repeated_lazy_message_extension = 57 [lazy=true];
+
+ // Singular with defaults
+ optional int32 default_int32_extension = 61 [default = 41 ];
+ optional int64 default_int64_extension = 62 [default = 42 ];
+ optional uint32 default_uint32_extension = 63 [default = 43 ];
+ optional uint64 default_uint64_extension = 64 [default = 44 ];
+ optional sint32 default_sint32_extension = 65 [default = -45 ];
+ optional sint64 default_sint64_extension = 66 [default = 46 ];
+ optional fixed32 default_fixed32_extension = 67 [default = 47 ];
+ optional fixed64 default_fixed64_extension = 68 [default = 48 ];
+ optional sfixed32 default_sfixed32_extension = 69 [default = 49 ];
+ optional sfixed64 default_sfixed64_extension = 70 [default = -50 ];
+ optional float default_float_extension = 71 [default = 51.5 ];
+ optional double default_double_extension = 72 [default = 52e3 ];
+ optional bool default_bool_extension = 73 [default = true ];
+ optional string default_string_extension = 74 [default = "hello"];
+ optional bytes default_bytes_extension = 75 [default = "world"];
+
+ optional TestAllTypes.NestedEnum
+ default_nested_enum_extension = 81 [default = BAR];
+ optional ForeignEnum
+ default_foreign_enum_extension = 82 [default = FOREIGN_BAR];
+ optional protobuf_unittest_import.ImportEnum
+ default_import_enum_extension = 83 [default = IMPORT_BAR];
+
+ optional string default_string_piece_extension = 84 [ctype=STRING_PIECE,
+ default="abc"];
+ optional string default_cord_extension = 85 [ctype=CORD, default="123"];
+}
+
+message TestNestedExtension {
+ extend TestAllExtensions {
+ // Check for bug where string extensions declared in tested scope did not
+ // compile.
+ optional string test = 1002 [default="test"];
+ }
+}
+
+// We have separate messages for testing required fields because it's
+// annoying to have to fill in required fields in TestProto in order to
+// do anything with it. Note that we don't need to test every type of
+// required filed because the code output is basically identical to
+// optional fields for all types.
+message TestRequired {
+ required int32 a = 1;
+ optional int32 dummy2 = 2;
+ required int32 b = 3;
+
+ extend TestAllExtensions {
+ optional TestRequired single = 1000;
+ repeated TestRequired multi = 1001;
+ }
+
+ // Pad the field count to 32 so that we can test that IsInitialized()
+ // properly checks multiple elements of has_bits_.
+ optional int32 dummy4 = 4;
+ optional int32 dummy5 = 5;
+ optional int32 dummy6 = 6;
+ optional int32 dummy7 = 7;
+ optional int32 dummy8 = 8;
+ optional int32 dummy9 = 9;
+ optional int32 dummy10 = 10;
+ optional int32 dummy11 = 11;
+ optional int32 dummy12 = 12;
+ optional int32 dummy13 = 13;
+ optional int32 dummy14 = 14;
+ optional int32 dummy15 = 15;
+ optional int32 dummy16 = 16;
+ optional int32 dummy17 = 17;
+ optional int32 dummy18 = 18;
+ optional int32 dummy19 = 19;
+ optional int32 dummy20 = 20;
+ optional int32 dummy21 = 21;
+ optional int32 dummy22 = 22;
+ optional int32 dummy23 = 23;
+ optional int32 dummy24 = 24;
+ optional int32 dummy25 = 25;
+ optional int32 dummy26 = 26;
+ optional int32 dummy27 = 27;
+ optional int32 dummy28 = 28;
+ optional int32 dummy29 = 29;
+ optional int32 dummy30 = 30;
+ optional int32 dummy31 = 31;
+ optional int32 dummy32 = 32;
+
+ required int32 c = 33;
+}
+
+message TestRequiredForeign {
+ optional TestRequired optional_message = 1;
+ repeated TestRequired repeated_message = 2;
+ optional int32 dummy = 3;
+}
+
+// Test that we can use NestedMessage from outside TestAllTypes.
+message TestForeignNested {
+ optional TestAllTypes.NestedMessage foreign_nested = 1;
+}
+
+// TestEmptyMessage is used to test unknown field support.
+message TestEmptyMessage {
+}
+
+// Like above, but declare all field numbers as potential extensions. No
+// actual extensions should ever be defined for this type.
+message TestEmptyMessageWithExtensions {
+ extensions 1 to max;
+}
+
+message TestMultipleExtensionRanges {
+ extensions 42;
+ extensions 4143 to 4243;
+ extensions 65536 to max;
+}
+
+// Test that really large tag numbers don't break anything.
+message TestReallyLargeTagNumber {
+ // The largest possible tag number is 2^28 - 1, since the wire format uses
+ // three bits to communicate wire type.
+ optional int32 a = 1;
+ optional int32 bb = 268435455;
+}
+
+message TestRecursiveMessage {
+ optional TestRecursiveMessage a = 1;
+ optional int32 i = 2;
+}
+
+// Test that mutual recursion works.
+message TestMutualRecursionA {
+ optional TestMutualRecursionB bb = 1;
+}
+
+message TestMutualRecursionB {
+ optional TestMutualRecursionA a = 1;
+ optional int32 optional_int32 = 2;
+}
+
+// Test that groups have disjoint field numbers from their siblings and
+// parents. This is NOT possible in proto1; only proto2. When attempting
+// to compile with proto1, this will emit an error; so we only include it
+// in protobuf_unittest_proto.
+message TestDupFieldNumber { // NO_PROTO1
+ optional int32 a = 1; // NO_PROTO1
+ optional group Foo = 2 { optional int32 a = 1; } // NO_PROTO1
+ optional group Bar = 3 { optional int32 a = 1; } // NO_PROTO1
+} // NO_PROTO1
+
+// Additional messages for testing lazy fields.
+message TestEagerMessage {
+ optional TestAllTypes sub_message = 1 [lazy=false];
+}
+message TestLazyMessage {
+ optional TestAllTypes sub_message = 1 [lazy=true];
+}
+
+// Needed for a Python test.
+message TestNestedMessageHasBits {
+ message NestedMessage {
+ repeated int32 nestedmessage_repeated_int32 = 1;
+ repeated ForeignMessage nestedmessage_repeated_foreignmessage = 2;
+ }
+ optional NestedMessage optional_nested_message = 1;
+}
+
+
+// Test an enum that has multiple values with the same number.
+enum TestEnumWithDupValue {
+ option allow_alias = true;
+ FOO1 = 1;
+ BAR1 = 2;
+ BAZ = 3;
+ FOO2 = 1;
+ BAR2 = 2;
+}
+
+// Test an enum with large, unordered values.
+enum TestSparseEnum {
+ SPARSE_A = 123;
+ SPARSE_B = 62374;
+ SPARSE_C = 12589234;
+ SPARSE_D = -15;
+ SPARSE_E = -53452;
+ SPARSE_F = 0;
+ SPARSE_G = 2;
+}
+
+// Test message with CamelCase field names. This violates Protocol Buffer
+// standard style.
+message TestCamelCaseFieldNames {
+ optional int32 PrimitiveField = 1;
+ optional string StringField = 2;
+ optional ForeignEnum EnumField = 3;
+ optional ForeignMessage MessageField = 4;
+ optional string StringPieceField = 5 [ctype=STRING_PIECE];
+ optional string CordField = 6 [ctype=CORD];
+
+ repeated int32 RepeatedPrimitiveField = 7;
+ repeated string RepeatedStringField = 8;
+ repeated ForeignEnum RepeatedEnumField = 9;
+ repeated ForeignMessage RepeatedMessageField = 10;
+ repeated string RepeatedStringPieceField = 11 [ctype=STRING_PIECE];
+ repeated string RepeatedCordField = 12 [ctype=CORD];
+}
+
+
+// We list fields out of order, to ensure that we're using field number and not
+// field index to determine serialization order.
+message TestFieldOrderings {
+ optional string my_string = 11;
+ extensions 2 to 10;
+ optional int64 my_int = 1;
+ extensions 12 to 100;
+ optional float my_float = 101;
+}
+
+
+extend TestFieldOrderings {
+ optional string my_extension_string = 50;
+ optional int32 my_extension_int = 5;
+}
+
+
+message TestExtremeDefaultValues {
+ optional bytes escaped_bytes = 1 [default = "\0\001\a\b\f\n\r\t\v\\\'\"\xfe"];
+ optional uint32 large_uint32 = 2 [default = 0xFFFFFFFF];
+ optional uint64 large_uint64 = 3 [default = 0xFFFFFFFFFFFFFFFF];
+ optional int32 small_int32 = 4 [default = -0x7FFFFFFF];
+ optional int64 small_int64 = 5 [default = -0x7FFFFFFFFFFFFFFF];
+ optional int32 really_small_int32 = 21 [default = -0x80000000];
+ optional int64 really_small_int64 = 22 [default = -0x8000000000000000];
+
+ // The default value here is UTF-8 for "\u1234". (We could also just type
+ // the UTF-8 text directly into this text file rather than escape it, but
+ // lots of people use editors that would be confused by this.)
+ optional string utf8_string = 6 [default = "\341\210\264"];
+
+ // Tests for single-precision floating-point values.
+ optional float zero_float = 7 [default = 0];
+ optional float one_float = 8 [default = 1];
+ optional float small_float = 9 [default = 1.5];
+ optional float negative_one_float = 10 [default = -1];
+ optional float negative_float = 11 [default = -1.5];
+ // Using exponents
+ optional float large_float = 12 [default = 2E8];
+ optional float small_negative_float = 13 [default = -8e-28];
+
+ // Text for nonfinite floating-point values.
+ optional double inf_double = 14 [default = inf];
+ optional double neg_inf_double = 15 [default = -inf];
+ optional double nan_double = 16 [default = nan];
+ optional float inf_float = 17 [default = inf];
+ optional float neg_inf_float = 18 [default = -inf];
+ optional float nan_float = 19 [default = nan];
+
+ // Tests for C++ trigraphs.
+ // Trigraphs should be escaped in C++ generated files, but they should not be
+ // escaped for other languages.
+ // Note that in .proto file, "\?" is a valid way to escape ? in string
+ // literals.
+ optional string cpp_trigraph = 20 [default = "? \? ?? \?? \??? ??/ ?\?-"];
+
+ // String defaults containing the character '\000'
+ optional string string_with_zero = 23 [default = "hel\000lo"];
+ optional bytes bytes_with_zero = 24 [default = "wor\000ld"];
+ optional string string_piece_with_zero = 25 [ctype=STRING_PIECE,
+ default="ab\000c"];
+ optional string cord_with_zero = 26 [ctype=CORD,
+ default="12\0003"];
+}
+
+message SparseEnumMessage {
+ optional TestSparseEnum sparse_enum = 1;
+}
+
+// Test String and Bytes: string is for valid UTF-8 strings
+message OneString {
+ optional string data = 1;
+}
+
+message MoreString {
+ repeated string data = 1;
+}
+
+message OneBytes {
+ optional bytes data = 1;
+}
+
+message MoreBytes {
+ repeated bytes data = 1;
+}
+
+
+// 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 TestPackedExtensions {
+ extensions 1 to max;
+}
+
+extend TestPackedExtensions {
+ repeated int32 packed_int32_extension = 90 [packed = true];
+ repeated int64 packed_int64_extension = 91 [packed = true];
+ repeated uint32 packed_uint32_extension = 92 [packed = true];
+ repeated uint64 packed_uint64_extension = 93 [packed = true];
+ repeated sint32 packed_sint32_extension = 94 [packed = true];
+ repeated sint64 packed_sint64_extension = 95 [packed = true];
+ repeated fixed32 packed_fixed32_extension = 96 [packed = true];
+ repeated fixed64 packed_fixed64_extension = 97 [packed = true];
+ repeated sfixed32 packed_sfixed32_extension = 98 [packed = true];
+ repeated sfixed64 packed_sfixed64_extension = 99 [packed = true];
+ repeated float packed_float_extension = 100 [packed = true];
+ repeated double packed_double_extension = 101 [packed = true];
+ repeated bool packed_bool_extension = 102 [packed = true];
+ repeated ForeignEnum packed_enum_extension = 103 [packed = true];
+}
+
+// Used by ExtensionSetTest/DynamicExtensions. The test actually builds
+// a set of extensions to TestAllExtensions dynamically, based on the fields
+// of this message type.
+message TestDynamicExtensions {
+ enum DynamicEnumType {
+ DYNAMIC_FOO = 2200;
+ DYNAMIC_BAR = 2201;
+ DYNAMIC_BAZ = 2202;
+ }
+ message DynamicMessageType {
+ optional int32 dynamic_field = 2100;
+ }
+
+ optional fixed32 scalar_extension = 2000;
+ optional ForeignEnum enum_extension = 2001;
+ optional DynamicEnumType dynamic_enum_extension = 2002;
+
+ optional ForeignMessage message_extension = 2003;
+ optional DynamicMessageType dynamic_message_extension = 2004;
+
+ repeated string repeated_extension = 2005;
+ repeated sint32 packed_extension = 2006 [packed = true];
+}
+
+message TestRepeatedScalarDifferentTagSizes {
+ // Parsing repeated fixed size values used to fail. This message needs to be
+ // used in order to get a tag of the right size; all of the repeated fields
+ // in TestAllTypes didn't trigger the check.
+ repeated fixed32 repeated_fixed32 = 12;
+ // Check for a varint type, just for good measure.
+ repeated int32 repeated_int32 = 13;
+
+ // These have two-byte tags.
+ repeated fixed64 repeated_fixed64 = 2046;
+ repeated int64 repeated_int64 = 2047;
+
+ // Three byte tags.
+ repeated float repeated_float = 262142;
+ repeated uint64 repeated_uint64 = 262143;
+}
+
+// Test that if an optional or required message/group field appears multiple
+// times in the input, they need to be merged.
+message TestParsingMerge {
+ // RepeatedFieldsGenerator defines matching field types as TestParsingMerge,
+ // except that all fields are repeated. In the tests, we will serialize the
+ // RepeatedFieldsGenerator to bytes, and parse the bytes to TestParsingMerge.
+ // Repeated fields in RepeatedFieldsGenerator are expected to be merged into
+ // the corresponding required/optional fields in TestParsingMerge.
+ message RepeatedFieldsGenerator {
+ repeated TestAllTypes field1 = 1;
+ repeated TestAllTypes field2 = 2;
+ repeated TestAllTypes field3 = 3;
+ repeated group Group1 = 10 {
+ optional TestAllTypes field1 = 11;
+ }
+ repeated group Group2 = 20 {
+ optional TestAllTypes field1 = 21;
+ }
+ repeated TestAllTypes ext1 = 1000;
+ repeated TestAllTypes ext2 = 1001;
+ }
+ required TestAllTypes required_all_types = 1;
+ optional TestAllTypes optional_all_types = 2;
+ repeated TestAllTypes repeated_all_types = 3;
+ optional group OptionalGroup = 10 {
+ optional TestAllTypes optional_group_all_types = 11;
+ }
+ repeated group RepeatedGroup = 20 {
+ optional TestAllTypes repeated_group_all_types = 21;
+ }
+ extensions 1000 to max;
+ extend TestParsingMerge {
+ optional TestAllTypes optional_ext = 1000;
+ repeated TestAllTypes repeated_ext = 1001;
+ }
+}
+
+message TestCommentInjectionMessage {
+ // */ <- This should not close the generated doc comment
+ optional string a = 1 [default="*/ <- Neither should this."];
+}
+
+
+// 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 {}
diff --git a/python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_custom_options.proto b/python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_custom_options.proto
new file mode 100644
index 00000000..e591d294
--- /dev/null
+++ b/python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_custom_options.proto
@@ -0,0 +1,387 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// http://code.google.com/p/protobuf/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+// Author: benjy@google.com (Benjy Weinberger)
+// Based on original Protocol Buffers design by
+// Sanjay Ghemawat, Jeff Dean, and others.
+//
+// A proto file used to test the "custom options" feature of proto2.
+
+
+// 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;
+
+// A custom file option (defined below).
+option (file_opt1) = 9876543210;
+
+import "google/protobuf/descriptor.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.
+package protobuf_unittest;
+
+
+// Some simple test custom options of various types.
+
+extend google.protobuf.FileOptions {
+ optional uint64 file_opt1 = 7736974;
+}
+
+extend google.protobuf.MessageOptions {
+ optional int32 message_opt1 = 7739036;
+}
+
+extend google.protobuf.FieldOptions {
+ optional fixed64 field_opt1 = 7740936;
+ // This is useful for testing that we correctly register default values for
+ // extension options.
+ optional int32 field_opt2 = 7753913 [default=42];
+}
+
+extend google.protobuf.EnumOptions {
+ optional sfixed32 enum_opt1 = 7753576;
+}
+
+extend google.protobuf.EnumValueOptions {
+ optional int32 enum_value_opt1 = 1560678;
+}
+
+extend google.protobuf.ServiceOptions {
+ optional sint64 service_opt1 = 7887650;
+}
+
+enum MethodOpt1 {
+ METHODOPT1_VAL1 = 1;
+ METHODOPT1_VAL2 = 2;
+}
+
+extend google.protobuf.MethodOptions {
+ optional MethodOpt1 method_opt1 = 7890860;
+}
+
+// A test message with custom options at all possible locations (and also some
+// regular options, to make sure they interact nicely).
+message TestMessageWithCustomOptions {
+ option message_set_wire_format = false;
+
+ option (message_opt1) = -56;
+
+ optional string field1 = 1 [ctype=CORD,
+ (field_opt1)=8765432109];
+
+ enum AnEnum {
+ option (enum_opt1) = -789;
+
+ ANENUM_VAL1 = 1;
+ ANENUM_VAL2 = 2 [(enum_value_opt1) = 123];
+ }
+}
+
+
+// A test RPC service with custom options at all possible locations (and also
+// some regular options, to make sure they interact nicely).
+message CustomOptionFooRequest {
+}
+
+message CustomOptionFooResponse {
+}
+
+message CustomOptionFooClientMessage {
+}
+
+message CustomOptionFooServerMessage {
+}
+
+service TestServiceWithCustomOptions {
+ option (service_opt1) = -9876543210;
+
+ rpc Foo(CustomOptionFooRequest) returns (CustomOptionFooResponse) {
+ option (method_opt1) = METHODOPT1_VAL2;
+ }
+}
+
+
+
+// Options of every possible field type, so we can test them all exhaustively.
+
+message DummyMessageContainingEnum {
+ enum TestEnumType {
+ TEST_OPTION_ENUM_TYPE1 = 22;
+ TEST_OPTION_ENUM_TYPE2 = -23;
+ }
+}
+
+message DummyMessageInvalidAsOptionType {
+}
+
+extend google.protobuf.MessageOptions {
+ optional bool bool_opt = 7706090;
+ optional int32 int32_opt = 7705709;
+ optional int64 int64_opt = 7705542;
+ optional uint32 uint32_opt = 7704880;
+ optional uint64 uint64_opt = 7702367;
+ optional sint32 sint32_opt = 7701568;
+ optional sint64 sint64_opt = 7700863;
+ optional fixed32 fixed32_opt = 7700307;
+ optional fixed64 fixed64_opt = 7700194;
+ optional sfixed32 sfixed32_opt = 7698645;
+ optional sfixed64 sfixed64_opt = 7685475;
+ optional float float_opt = 7675390;
+ optional double double_opt = 7673293;
+ optional string string_opt = 7673285;
+ optional bytes bytes_opt = 7673238;
+ optional DummyMessageContainingEnum.TestEnumType enum_opt = 7673233;
+ optional DummyMessageInvalidAsOptionType message_type_opt = 7665967;
+}
+
+message CustomOptionMinIntegerValues {
+ option (bool_opt) = false;
+ option (int32_opt) = -0x80000000;
+ option (int64_opt) = -0x8000000000000000;
+ option (uint32_opt) = 0;
+ option (uint64_opt) = 0;
+ option (sint32_opt) = -0x80000000;
+ option (sint64_opt) = -0x8000000000000000;
+ option (fixed32_opt) = 0;
+ option (fixed64_opt) = 0;
+ option (sfixed32_opt) = -0x80000000;
+ option (sfixed64_opt) = -0x8000000000000000;
+}
+
+message CustomOptionMaxIntegerValues {
+ option (bool_opt) = true;
+ option (int32_opt) = 0x7FFFFFFF;
+ option (int64_opt) = 0x7FFFFFFFFFFFFFFF;
+ option (uint32_opt) = 0xFFFFFFFF;
+ option (uint64_opt) = 0xFFFFFFFFFFFFFFFF;
+ option (sint32_opt) = 0x7FFFFFFF;
+ option (sint64_opt) = 0x7FFFFFFFFFFFFFFF;
+ option (fixed32_opt) = 0xFFFFFFFF;
+ option (fixed64_opt) = 0xFFFFFFFFFFFFFFFF;
+ option (sfixed32_opt) = 0x7FFFFFFF;
+ option (sfixed64_opt) = 0x7FFFFFFFFFFFFFFF;
+}
+
+message CustomOptionOtherValues {
+ option (int32_opt) = -100; // To test sign-extension.
+ option (float_opt) = 12.3456789;
+ option (double_opt) = 1.234567890123456789;
+ option (string_opt) = "Hello, \"World\"";
+ option (bytes_opt) = "Hello\0World";
+ option (enum_opt) = TEST_OPTION_ENUM_TYPE2;
+}
+
+message SettingRealsFromPositiveInts {
+ option (float_opt) = 12;
+ option (double_opt) = 154;
+}
+
+message SettingRealsFromNegativeInts {
+ option (float_opt) = -12;
+ option (double_opt) = -154;
+}
+
+// Options of complex message types, themselves combined and extended in
+// various ways.
+
+message ComplexOptionType1 {
+ optional int32 foo = 1;
+ optional int32 foo2 = 2;
+ optional int32 foo3 = 3;
+
+ extensions 100 to max;
+}
+
+message ComplexOptionType2 {
+ optional ComplexOptionType1 bar = 1;
+ optional int32 baz = 2;
+
+ message ComplexOptionType4 {
+ optional int32 waldo = 1;
+
+ extend google.protobuf.MessageOptions {
+ optional ComplexOptionType4 complex_opt4 = 7633546;
+ }
+ }
+
+ optional ComplexOptionType4 fred = 3;
+
+ extensions 100 to max;
+}
+
+message ComplexOptionType3 {
+ optional int32 qux = 1;
+
+ optional group ComplexOptionType5 = 2 {
+ optional int32 plugh = 3;
+ }
+}
+
+extend ComplexOptionType1 {
+ optional int32 quux = 7663707;
+ optional ComplexOptionType3 corge = 7663442;
+}
+
+extend ComplexOptionType2 {
+ optional int32 grault = 7650927;
+ optional ComplexOptionType1 garply = 7649992;
+}
+
+extend google.protobuf.MessageOptions {
+ optional protobuf_unittest.ComplexOptionType1 complex_opt1 = 7646756;
+ optional ComplexOptionType2 complex_opt2 = 7636949;
+ optional ComplexOptionType3 complex_opt3 = 7636463;
+ optional group ComplexOpt6 = 7595468 {
+ optional int32 xyzzy = 7593951;
+ }
+}
+
+// Note that we try various different ways of naming the same extension.
+message VariousComplexOptions {
+ option (.protobuf_unittest.complex_opt1).foo = 42;
+ option (protobuf_unittest.complex_opt1).(.protobuf_unittest.quux) = 324;
+ option (.protobuf_unittest.complex_opt1).(protobuf_unittest.corge).qux = 876;
+ option (complex_opt2).baz = 987;
+ option (complex_opt2).(grault) = 654;
+ option (complex_opt2).bar.foo = 743;
+ option (complex_opt2).bar.(quux) = 1999;
+ option (complex_opt2).bar.(protobuf_unittest.corge).qux = 2008;
+ option (complex_opt2).(garply).foo = 741;
+ option (complex_opt2).(garply).(.protobuf_unittest.quux) = 1998;
+ option (complex_opt2).(protobuf_unittest.garply).(corge).qux = 2121;
+ option (ComplexOptionType2.ComplexOptionType4.complex_opt4).waldo = 1971;
+ option (complex_opt2).fred.waldo = 321;
+ option (protobuf_unittest.complex_opt3).qux = 9;
+ option (complex_opt3).complexoptiontype5.plugh = 22;
+ option (complexopt6).xyzzy = 24;
+}
+
+// ------------------------------------------------------
+// Definitions for testing aggregate option parsing.
+// See descriptor_unittest.cc.
+
+message AggregateMessageSet {
+ option message_set_wire_format = true;
+ extensions 4 to max;
+}
+
+message AggregateMessageSetElement {
+ extend AggregateMessageSet {
+ optional AggregateMessageSetElement message_set_extension = 15447542;
+ }
+ optional string s = 1;
+}
+
+// A helper type used to test aggregate option parsing
+message Aggregate {
+ optional int32 i = 1;
+ optional string s = 2;
+
+ // A nested object
+ optional Aggregate sub = 3;
+
+ // To test the parsing of extensions inside aggregate values
+ optional google.protobuf.FileOptions file = 4;
+ extend google.protobuf.FileOptions {
+ optional Aggregate nested = 15476903;
+ }
+
+ // An embedded message set
+ optional AggregateMessageSet mset = 5;
+}
+
+// Allow Aggregate to be used as an option at all possible locations
+// in the .proto grammer.
+extend google.protobuf.FileOptions { optional Aggregate fileopt = 15478479; }
+extend google.protobuf.MessageOptions { optional Aggregate msgopt = 15480088; }
+extend google.protobuf.FieldOptions { optional Aggregate fieldopt = 15481374; }
+extend google.protobuf.EnumOptions { optional Aggregate enumopt = 15483218; }
+extend google.protobuf.EnumValueOptions { optional Aggregate enumvalopt = 15486921; }
+extend google.protobuf.ServiceOptions { optional Aggregate serviceopt = 15497145; }
+extend google.protobuf.MethodOptions { optional Aggregate methodopt = 15512713; }
+
+// Try using AggregateOption at different points in the proto grammar
+option (fileopt) = {
+ s: 'FileAnnotation'
+ // Also test the handling of comments
+ /* of both types */ i: 100
+
+ sub { s: 'NestedFileAnnotation' }
+
+ // Include a google.protobuf.FileOptions and recursively extend it with
+ // another fileopt.
+ file {
+ [protobuf_unittest.fileopt] {
+ s:'FileExtensionAnnotation'
+ }
+ }
+
+ // A message set inside an option value
+ mset {
+ [protobuf_unittest.AggregateMessageSetElement.message_set_extension] {
+ s: 'EmbeddedMessageSetElement'
+ }
+ }
+};
+
+message AggregateMessage {
+ option (msgopt) = { i:101 s:'MessageAnnotation' };
+ optional int32 fieldname = 1 [(fieldopt) = { s:'FieldAnnotation' }];
+}
+
+service AggregateService {
+ option (serviceopt) = { s:'ServiceAnnotation' };
+ rpc Method (AggregateMessage) returns (AggregateMessage) {
+ option (methodopt) = { s:'MethodAnnotation' };
+ }
+}
+
+enum AggregateEnum {
+ option (enumopt) = { s:'EnumAnnotation' };
+ VALUE = 1 [(enumvalopt) = { s:'EnumValueAnnotation' }];
+}
+
+// Test custom options for nested type.
+message NestedOptionType {
+ message NestedMessage {
+ option (message_opt1) = 1001;
+ optional int32 nested_field = 1 [(field_opt1) = 1002];
+ }
+ enum NestedEnum {
+ option (enum_opt1) = 1003;
+ NESTED_ENUM_VALUE = 1 [(enum_value_opt1) = 1004];
+ }
+ extend google.protobuf.FileOptions {
+ optional int32 nested_extension = 7912573 [(field_opt2) = 1005];
+ }
+}
diff --git a/python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_import.proto b/python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_import.proto
new file mode 100644
index 00000000..c115b111
--- /dev/null
+++ b/python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_import.proto
@@ -0,0 +1,64 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// http://code.google.com/p/protobuf/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+// Author: kenton@google.com (Kenton Varda)
+// Based on original Protocol Buffers design by
+// Sanjay Ghemawat, Jeff Dean, and others.
+//
+// A proto file which is imported by unittest.proto to test importing.
+
+
+// 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;
+
+// Excercise the java_package option.
+option java_package = "com.google.protobuf.test";
+
+// 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.proto";
+
+message ImportMessage {
+ optional int32 d = 1;
+}
+
+enum ImportEnum {
+ IMPORT_FOO = 7;
+ IMPORT_BAR = 8;
+ IMPORT_BAZ = 9;
+}
+
diff --git a/python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_import_public.proto b/python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_import_public.proto
new file mode 100644
index 00000000..ea5d1b13
--- /dev/null
+++ b/python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_import_public.proto
@@ -0,0 +1,40 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// http://code.google.com/p/protobuf/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+// Author: liujisi@google.com (Pherl Liu)
+
+
+package protobuf_unittest_import;
+
+option java_package = "com.google.protobuf.test";
+
+message PublicImportMessage {
+ optional int32 e = 1;
+}
diff --git a/python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_mset.proto b/python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_mset.proto
new file mode 100644
index 00000000..3497f09f
--- /dev/null
+++ b/python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_mset.proto
@@ -0,0 +1,72 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// http://code.google.com/p/protobuf/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+// Author: kenton@google.com (Kenton Varda)
+// Based on original Protocol Buffers design by
+// Sanjay Ghemawat, Jeff Dean, and others.
+//
+// This file contains messages for testing message_set_wire_format.
+
+package protobuf_unittest;
+
+option optimize_for = SPEED;
+
+// A message with message_set_wire_format.
+message TestMessageSet {
+ option message_set_wire_format = true;
+ extensions 4 to max;
+}
+
+message TestMessageSetContainer {
+ optional TestMessageSet message_set = 1;
+}
+
+message TestMessageSetExtension1 {
+ extend TestMessageSet {
+ optional TestMessageSetExtension1 message_set_extension = 1545008;
+ }
+ optional int32 i = 15;
+}
+
+message TestMessageSetExtension2 {
+ extend TestMessageSet {
+ optional TestMessageSetExtension2 message_set_extension = 1547769;
+ }
+ optional string str = 25;
+}
+
+// MessageSet wire format is equivalent to this.
+message RawMessageSet {
+ repeated group Item = 1 {
+ required int32 type_id = 2;
+ required bytes message = 3;
+ }
+}
+
diff --git a/python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_no_generic_services.proto b/python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_no_generic_services.proto
new file mode 100644
index 00000000..cffb4122
--- /dev/null
+++ b/python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_no_generic_services.proto
@@ -0,0 +1,52 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// http://code.google.com/p/protobuf/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+// Author: kenton@google.com (Kenton Varda)
+
+package google.protobuf.no_generic_services_test;
+
+// *_generic_services are false by default.
+
+message TestMessage {
+ optional int32 a = 1;
+ extensions 1000 to max;
+}
+
+enum TestEnum {
+ FOO = 1;
+}
+
+extend TestMessage {
+ optional int32 test_extension = 1000;
+}
+
+service TestService {
+ rpc Foo(TestMessage) returns(TestMessage);
+}
diff --git a/python/compatibility_tests/v2.5.0/setup.py b/python/compatibility_tests/v2.5.0/setup.py
new file mode 100755
index 00000000..b41d54d4
--- /dev/null
+++ b/python/compatibility_tests/v2.5.0/setup.py
@@ -0,0 +1,87 @@
+#! /usr/bin/env python
+#
+import glob
+import os
+import subprocess
+import sys
+
+from setuptools import setup, Extension, find_packages
+
+if sys.version_info[0] == 3:
+ # Python 3
+ from distutils.command.build_py import build_py_2to3 as _build_py
+else:
+ # Python 2
+ from distutils.command.build_py import build_py as _build_py
+from distutils.spawn import find_executable
+
+def generate_proto(source, code_gen):
+ """Invokes the Protocol Compiler to generate a _pb2.py from the given
+ .proto file."""
+ output = source.replace(".proto", "_pb2.py").replace("protos/src/proto/", "").replace("protos/python/", "")
+
+ if not os.path.exists(source):
+ sys.stderr.write("Can't find required file: %s\n" % source)
+ sys.exit(-1)
+
+ protoc_command = [ code_gen, "-Iprotos/src/proto", "-Iprotos/python", "--python_out=.", source ]
+ if subprocess.call(protoc_command) != 0:
+ sys.exit(-1)
+
+class build_py(_build_py):
+ def run(self):
+ # generate .proto file
+ protoc_1 = "./protoc_1"
+ protoc_2 = "./protoc_2"
+ generate_proto("protos/src/proto/google/protobuf/unittest.proto", protoc_2)
+ generate_proto("protos/src/proto/google/protobuf/unittest_custom_options.proto", protoc_1)
+ generate_proto("protos/src/proto/google/protobuf/unittest_import.proto", protoc_1)
+ generate_proto("protos/src/proto/google/protobuf/unittest_import_public.proto", protoc_1)
+ generate_proto("protos/src/proto/google/protobuf/unittest_mset.proto", protoc_1)
+ generate_proto("protos/src/proto/google/protobuf/unittest_no_generic_services.proto", protoc_1)
+ generate_proto("protos/python/google/protobuf/internal/factory_test1.proto", protoc_1)
+ generate_proto("protos/python/google/protobuf/internal/factory_test2.proto", protoc_1)
+ generate_proto("protos/python/google/protobuf/internal/more_extensions.proto", protoc_1)
+ generate_proto("protos/python/google/protobuf/internal/more_extensions_dynamic.proto", protoc_1)
+ generate_proto("protos/python/google/protobuf/internal/more_messages.proto", protoc_1)
+ generate_proto("protos/python/google/protobuf/internal/test_bad_identifiers.proto", protoc_1)
+
+ # _build_py is an old-style class, so super() doesn't work.
+ _build_py.run(self)
+
+if __name__ == '__main__':
+ # Keep this list of dependencies in sync with tox.ini.
+ install_requires = ['six>=1.9', 'setuptools']
+ if sys.version_info <= (2,7):
+ install_requires.append('ordereddict')
+ install_requires.append('unittest2')
+
+ setup(
+ name='protobuf',
+ description='Protocol Buffers',
+ download_url='https://github.com/google/protobuf/releases',
+ long_description="Protocol Buffers are Google's data interchange format",
+ url='https://developers.google.com/protocol-buffers/',
+ maintainer='protobuf@googlegroups.com',
+ maintainer_email='protobuf@googlegroups.com',
+ license='3-Clause BSD License',
+ classifiers=[
+ "Programming Language :: Python",
+ "Programming Language :: Python :: 2",
+ "Programming Language :: Python :: 2.6",
+ "Programming Language :: Python :: 2.7",
+ "Programming Language :: Python :: 3",
+ "Programming Language :: Python :: 3.3",
+ "Programming Language :: Python :: 3.4",
+ ],
+ packages=find_packages(
+ exclude=[
+ 'import_test_package',
+ ],
+ ),
+ test_suite='tests.google.protobuf.internal',
+ cmdclass={
+ 'build_py': build_py,
+ },
+ install_requires=install_requires,
+ )
diff --git a/python/compatibility_tests/v2.5.0/test.sh b/python/compatibility_tests/v2.5.0/test.sh
new file mode 100755
index 00000000..78c16ad1
--- /dev/null
+++ b/python/compatibility_tests/v2.5.0/test.sh
@@ -0,0 +1,104 @@
+#!/bin/bash
+
+set -ex
+
+# Change to the script's directory.
+cd $(dirname $0)
+
+# Version of the tests (i.e., the version of protobuf from where we extracted
+# these tests).
+TEST_VERSION=2.5.0
+
+# The old version of protobuf that we are testing compatibility against. This
+# is usually the same as TEST_VERSION (i.e., we use the tests extracted from
+# that version to test compatibility of the newest runtime against it), but it
+# is also possible to use this same test set to test the compatibiilty of the
+# latest version against other versions.
+case "$1" in
+ ""|2.5.0)
+ OLD_VERSION=2.5.0
+ OLD_VERSION_PROTOC=https://github.com/xfxyjwf/protobuf-compiler-release/raw/master/v2.5.0/linux/protoc
+ ;;
+ 2.6.1)
+ OLD_VERSION=2.6.1
+ OLD_VERSION_PROTOC=http://repo1.maven.org/maven2/com/google/protobuf/protoc/2.6.1-build2/protoc-2.6.1-build2-linux-x86_64.exe
+ ;;
+ 3.0.0-beta-1)
+ OLD_VERSION=3.0.0-beta-1
+ OLD_VERSION_PROTOC=http://repo1.maven.org/maven2/com/google/protobuf/protoc/3.0.0-beta-1/protoc-3.0.0-beta-1-linux-x86_64.exe
+ ;;
+ 3.0.0-beta-2)
+ OLD_VERSION=3.0.0-beta-2
+ OLD_VERSION_PROTOC=http://repo1.maven.org/maven2/com/google/protobuf/protoc/3.0.0-beta-2/protoc-3.0.0-beta-2-linux-x86_64.exe
+ ;;
+ 3.0.0-beta-3)
+ OLD_VERSION=3.0.0-beta-3
+ OLD_VERSION_PROTOC=http://repo1.maven.org/maven2/com/google/protobuf/protoc/3.0.0-beta-3/protoc-3.0.0-beta-3-linux-x86_64.exe
+ ;;
+ 3.0.0-beta-4)
+ OLD_VERSION=3.0.0-beta-4
+ OLD_VERSION_PROTOC=http://repo1.maven.org/maven2/com/google/protobuf/protoc/3.0.0-beta-4/protoc-3.0.0-beta-4-linux-x86_64.exe
+ ;;
+ *)
+ echo "[ERROR]: Unknown version number: $1"
+ exit 1
+ ;;
+esac
+
+# Extract the latest protobuf version number.
+VERSION_NUMBER=`grep "^__version__ = '.*'" ../../google/protobuf/__init__.py | sed "s|__version__ = '\(.*\)'|\1|"`
+
+echo "Running compatibility tests between $VERSION_NUMBER and $OLD_VERSION"
+
+# Check protoc
+[ -f ../../../src/protoc ] || {
+ echo "[ERROR]: Please build protoc first."
+ exit 1
+}
+
+# Test source compatibility. In these tests we recompile everything against
+# the new runtime (including old version generated code).
+rm google -f -r
+mkdir -p google/protobuf/internal
+# Build and copy the new runtime
+cd ../../
+python setup.py build
+cp google/protobuf/*.py compatibility_tests/v2.5.0/google/protobuf/
+cp google/protobuf/internal/*.py compatibility_tests/v2.5.0/google/protobuf/internal/
+cd compatibility_tests/v2.5.0
+cp tests/google/protobuf/internal/test_util.py google/protobuf/internal/
+cp google/protobuf/__init__.py google/
+
+# Download old version protoc compiler (for linux)
+wget $OLD_VERSION_PROTOC -O old_protoc
+chmod +x old_protoc
+
+# Test A.1:
+# proto set 1: use old version
+# proto set 2 which may import protos in set 1: use old version
+cp old_protoc protoc_1
+cp old_protoc protoc_2
+python setup.py build
+python setup.py test
+
+# Test A.2:
+# proto set 1: use new version
+# proto set 2 which may import protos in set 1: use old version
+cp ../../../src/protoc protoc_1
+cp old_protoc protoc_2
+python setup.py build
+python setup.py test
+
+# Test A.3:
+# proto set 1: use old version
+# proto set 2 which may import protos in set 1: use new version
+cp old_protoc protoc_1
+cp ../../../src/protoc protoc_2
+python setup.py build
+python setup.py test
+
+rm google -r -f
+rm build -r -f
+rm protoc_1
+rm protoc_2
+rm old_protoc
diff --git a/python/compatibility_tests/v2.5.0/tests/__init__.py b/python/compatibility_tests/v2.5.0/tests/__init__.py
new file mode 100644
index 00000000..55856141
--- /dev/null
+++ b/python/compatibility_tests/v2.5.0/tests/__init__.py
@@ -0,0 +1,4 @@
+try:
+ __import__('pkg_resources').declare_namespace(__name__)
+except ImportError:
+ __path__ = __import__('pkgutil').extend_path(__path__, __name__)
diff --git a/python/compatibility_tests/v2.5.0/tests/google/__init__.py b/python/compatibility_tests/v2.5.0/tests/google/__init__.py
new file mode 100644
index 00000000..55856141
--- /dev/null
+++ b/python/compatibility_tests/v2.5.0/tests/google/__init__.py
@@ -0,0 +1,4 @@
+try:
+ __import__('pkg_resources').declare_namespace(__name__)
+except ImportError:
+ __path__ = __import__('pkgutil').extend_path(__path__, __name__)
diff --git a/python/compatibility_tests/v2.5.0/tests/google/protobuf/__init__.py b/python/compatibility_tests/v2.5.0/tests/google/protobuf/__init__.py
new file mode 100644
index 00000000..55856141
--- /dev/null
+++ b/python/compatibility_tests/v2.5.0/tests/google/protobuf/__init__.py
@@ -0,0 +1,4 @@
+try:
+ __import__('pkg_resources').declare_namespace(__name__)
+except ImportError:
+ __path__ = __import__('pkgutil').extend_path(__path__, __name__)
diff --git a/src/google/protobuf/arena_nc_test.py b/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/__init__.py
index 56a7dd05..64c6956f 100644
--- a/src/google/protobuf/arena_nc_test.py
+++ b/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/__init__.py
@@ -1,5 +1,3 @@
-#! /usr/bin/env python
-#
# Protocol Buffers - Google's data interchange format
# Copyright 2008 Google Inc. All rights reserved.
# https://developers.google.com/protocol-buffers/
@@ -30,32 +28,10 @@
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-"""Negative compilation unit tests for arena API."""
-
-import unittest
-
-from google3.testing.pybase import fake_target_util
-from google3.testing.pybase import unittest
-
-
-class ArenaNcTest(unittest.TestCase):
-
- def testCompilerErrors(self):
- """Runs a list of tests to verify compiler error messages."""
-
- # Defines a list of test specs, where each element is a tuple
- # (test name, list of regexes for matching the compiler errors).
- test_specs = [
- ('ARENA_PRIVATE_CONSTRUCTOR',
- [r'calling a protected constructor']),
- ('SANITY', None)]
-
- fake_target_util.AssertCcCompilerErrors(
- self, # The current test case.
- 'google3/google/protobuf/arena_nc', # The fake target file.
- 'arena_nc.o', # The sub-target to build.
- test_specs # List of test specifications.
- )
+# Copyright 2007 Google Inc. All Rights Reserved.
-if __name__ == '__main__':
- unittest.main()
+if __name__ != '__main__':
+ try:
+ __import__('pkg_resources').declare_namespace(__name__)
+ except ImportError:
+ __path__ = __import__('pkgutil').extend_path(__path__, __name__)
diff --git a/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/descriptor_test.py b/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/descriptor_test.py
new file mode 100755
index 00000000..c74f882e
--- /dev/null
+++ b/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/descriptor_test.py
@@ -0,0 +1,613 @@
+#! /usr/bin/python
+#
+# Protocol Buffers - Google's data interchange format
+# Copyright 2008 Google Inc. All rights reserved.
+# http://code.google.com/p/protobuf/
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following disclaimer
+# in the documentation and/or other materials provided with the
+# distribution.
+# * Neither the name of Google Inc. nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+"""Unittest for google.protobuf.internal.descriptor."""
+
+__author__ = 'robinson@google.com (Will Robinson)'
+
+import unittest
+from google.protobuf import unittest_custom_options_pb2
+from google.protobuf import unittest_import_pb2
+from google.protobuf import unittest_pb2
+from google.protobuf import descriptor_pb2
+from google.protobuf import descriptor
+from google.protobuf import text_format
+
+
+TEST_EMPTY_MESSAGE_DESCRIPTOR_ASCII = """
+name: 'TestEmptyMessage'
+"""
+
+
+class DescriptorTest(unittest.TestCase):
+
+ def setUp(self):
+ self.my_file = descriptor.FileDescriptor(
+ name='some/filename/some.proto',
+ package='protobuf_unittest'
+ )
+ self.my_enum = descriptor.EnumDescriptor(
+ name='ForeignEnum',
+ full_name='protobuf_unittest.ForeignEnum',
+ filename=None,
+ file=self.my_file,
+ values=[
+ descriptor.EnumValueDescriptor(name='FOREIGN_FOO', index=0, number=4),
+ descriptor.EnumValueDescriptor(name='FOREIGN_BAR', index=1, number=5),
+ descriptor.EnumValueDescriptor(name='FOREIGN_BAZ', index=2, number=6),
+ ])
+ self.my_message = descriptor.Descriptor(
+ name='NestedMessage',
+ full_name='protobuf_unittest.TestAllTypes.NestedMessage',
+ filename=None,
+ file=self.my_file,
+ containing_type=None,
+ fields=[
+ descriptor.FieldDescriptor(
+ name='bb',
+ full_name='protobuf_unittest.TestAllTypes.NestedMessage.bb',
+ index=0, number=1,
+ type=5, cpp_type=1, label=1,
+ has_default_value=False, default_value=0,
+ message_type=None, enum_type=None, containing_type=None,
+ is_extension=False, extension_scope=None),
+ ],
+ nested_types=[],
+ enum_types=[
+ self.my_enum,
+ ],
+ extensions=[])
+ self.my_method = descriptor.MethodDescriptor(
+ name='Bar',
+ full_name='protobuf_unittest.TestService.Bar',
+ index=0,
+ containing_service=None,
+ input_type=None,
+ output_type=None)
+ self.my_service = descriptor.ServiceDescriptor(
+ name='TestServiceWithOptions',
+ full_name='protobuf_unittest.TestServiceWithOptions',
+ file=self.my_file,
+ index=0,
+ methods=[
+ self.my_method
+ ])
+
+ def testEnumValueName(self):
+ self.assertEqual(self.my_message.EnumValueName('ForeignEnum', 4),
+ 'FOREIGN_FOO')
+
+ self.assertEqual(
+ self.my_message.enum_types_by_name[
+ 'ForeignEnum'].values_by_number[4].name,
+ self.my_message.EnumValueName('ForeignEnum', 4))
+
+ def testEnumFixups(self):
+ self.assertEqual(self.my_enum, self.my_enum.values[0].type)
+
+ def testContainingTypeFixups(self):
+ self.assertEqual(self.my_message, self.my_message.fields[0].containing_type)
+ self.assertEqual(self.my_message, self.my_enum.containing_type)
+
+ def testContainingServiceFixups(self):
+ self.assertEqual(self.my_service, self.my_method.containing_service)
+
+ def testGetOptions(self):
+ self.assertEqual(self.my_enum.GetOptions(),
+ descriptor_pb2.EnumOptions())
+ self.assertEqual(self.my_enum.values[0].GetOptions(),
+ descriptor_pb2.EnumValueOptions())
+ self.assertEqual(self.my_message.GetOptions(),
+ descriptor_pb2.MessageOptions())
+ self.assertEqual(self.my_message.fields[0].GetOptions(),
+ descriptor_pb2.FieldOptions())
+ self.assertEqual(self.my_method.GetOptions(),
+ descriptor_pb2.MethodOptions())
+ self.assertEqual(self.my_service.GetOptions(),
+ descriptor_pb2.ServiceOptions())
+
+ def testSimpleCustomOptions(self):
+ file_descriptor = unittest_custom_options_pb2.DESCRIPTOR
+ message_descriptor =\
+ unittest_custom_options_pb2.TestMessageWithCustomOptions.DESCRIPTOR
+ field_descriptor = message_descriptor.fields_by_name["field1"]
+ enum_descriptor = message_descriptor.enum_types_by_name["AnEnum"]
+ enum_value_descriptor =\
+ message_descriptor.enum_values_by_name["ANENUM_VAL2"]
+ service_descriptor =\
+ unittest_custom_options_pb2.TestServiceWithCustomOptions.DESCRIPTOR
+ method_descriptor = service_descriptor.FindMethodByName("Foo")
+
+ file_options = file_descriptor.GetOptions()
+ file_opt1 = unittest_custom_options_pb2.file_opt1
+ self.assertEqual(9876543210, file_options.Extensions[file_opt1])
+ message_options = message_descriptor.GetOptions()
+ message_opt1 = unittest_custom_options_pb2.message_opt1
+ self.assertEqual(-56, message_options.Extensions[message_opt1])
+ field_options = field_descriptor.GetOptions()
+ field_opt1 = unittest_custom_options_pb2.field_opt1
+ self.assertEqual(8765432109, field_options.Extensions[field_opt1])
+ field_opt2 = unittest_custom_options_pb2.field_opt2
+ self.assertEqual(42, field_options.Extensions[field_opt2])
+ enum_options = enum_descriptor.GetOptions()
+ enum_opt1 = unittest_custom_options_pb2.enum_opt1
+ self.assertEqual(-789, enum_options.Extensions[enum_opt1])
+ enum_value_options = enum_value_descriptor.GetOptions()
+ enum_value_opt1 = unittest_custom_options_pb2.enum_value_opt1
+ self.assertEqual(123, enum_value_options.Extensions[enum_value_opt1])
+
+ service_options = service_descriptor.GetOptions()
+ service_opt1 = unittest_custom_options_pb2.service_opt1
+ self.assertEqual(-9876543210, service_options.Extensions[service_opt1])
+ method_options = method_descriptor.GetOptions()
+ method_opt1 = unittest_custom_options_pb2.method_opt1
+ self.assertEqual(unittest_custom_options_pb2.METHODOPT1_VAL2,
+ method_options.Extensions[method_opt1])
+
+ def testDifferentCustomOptionTypes(self):
+ kint32min = -2**31
+ kint64min = -2**63
+ kint32max = 2**31 - 1
+ kint64max = 2**63 - 1
+ kuint32max = 2**32 - 1
+ kuint64max = 2**64 - 1
+
+ message_descriptor =\
+ unittest_custom_options_pb2.CustomOptionMinIntegerValues.DESCRIPTOR
+ message_options = message_descriptor.GetOptions()
+ self.assertEqual(False, message_options.Extensions[
+ unittest_custom_options_pb2.bool_opt])
+ self.assertEqual(kint32min, message_options.Extensions[
+ unittest_custom_options_pb2.int32_opt])
+ self.assertEqual(kint64min, message_options.Extensions[
+ unittest_custom_options_pb2.int64_opt])
+ self.assertEqual(0, message_options.Extensions[
+ unittest_custom_options_pb2.uint32_opt])
+ self.assertEqual(0, message_options.Extensions[
+ unittest_custom_options_pb2.uint64_opt])
+ self.assertEqual(kint32min, message_options.Extensions[
+ unittest_custom_options_pb2.sint32_opt])
+ self.assertEqual(kint64min, message_options.Extensions[
+ unittest_custom_options_pb2.sint64_opt])
+ self.assertEqual(0, message_options.Extensions[
+ unittest_custom_options_pb2.fixed32_opt])
+ self.assertEqual(0, message_options.Extensions[
+ unittest_custom_options_pb2.fixed64_opt])
+ self.assertEqual(kint32min, message_options.Extensions[
+ unittest_custom_options_pb2.sfixed32_opt])
+ self.assertEqual(kint64min, message_options.Extensions[
+ unittest_custom_options_pb2.sfixed64_opt])
+
+ message_descriptor =\
+ unittest_custom_options_pb2.CustomOptionMaxIntegerValues.DESCRIPTOR
+ message_options = message_descriptor.GetOptions()
+ self.assertEqual(True, message_options.Extensions[
+ unittest_custom_options_pb2.bool_opt])
+ self.assertEqual(kint32max, message_options.Extensions[
+ unittest_custom_options_pb2.int32_opt])
+ self.assertEqual(kint64max, message_options.Extensions[
+ unittest_custom_options_pb2.int64_opt])
+ self.assertEqual(kuint32max, message_options.Extensions[
+ unittest_custom_options_pb2.uint32_opt])
+ self.assertEqual(kuint64max, message_options.Extensions[
+ unittest_custom_options_pb2.uint64_opt])
+ self.assertEqual(kint32max, message_options.Extensions[
+ unittest_custom_options_pb2.sint32_opt])
+ self.assertEqual(kint64max, message_options.Extensions[
+ unittest_custom_options_pb2.sint64_opt])
+ self.assertEqual(kuint32max, message_options.Extensions[
+ unittest_custom_options_pb2.fixed32_opt])
+ self.assertEqual(kuint64max, message_options.Extensions[
+ unittest_custom_options_pb2.fixed64_opt])
+ self.assertEqual(kint32max, message_options.Extensions[
+ unittest_custom_options_pb2.sfixed32_opt])
+ self.assertEqual(kint64max, message_options.Extensions[
+ unittest_custom_options_pb2.sfixed64_opt])
+
+ message_descriptor =\
+ unittest_custom_options_pb2.CustomOptionOtherValues.DESCRIPTOR
+ message_options = message_descriptor.GetOptions()
+ self.assertEqual(-100, message_options.Extensions[
+ unittest_custom_options_pb2.int32_opt])
+ self.assertAlmostEqual(12.3456789, message_options.Extensions[
+ unittest_custom_options_pb2.float_opt], 6)
+ self.assertAlmostEqual(1.234567890123456789, message_options.Extensions[
+ unittest_custom_options_pb2.double_opt])
+ self.assertEqual("Hello, \"World\"", message_options.Extensions[
+ unittest_custom_options_pb2.string_opt])
+ self.assertEqual("Hello\0World", message_options.Extensions[
+ unittest_custom_options_pb2.bytes_opt])
+ dummy_enum = unittest_custom_options_pb2.DummyMessageContainingEnum
+ self.assertEqual(
+ dummy_enum.TEST_OPTION_ENUM_TYPE2,
+ message_options.Extensions[unittest_custom_options_pb2.enum_opt])
+
+ message_descriptor =\
+ unittest_custom_options_pb2.SettingRealsFromPositiveInts.DESCRIPTOR
+ message_options = message_descriptor.GetOptions()
+ self.assertAlmostEqual(12, message_options.Extensions[
+ unittest_custom_options_pb2.float_opt], 6)
+ self.assertAlmostEqual(154, message_options.Extensions[
+ unittest_custom_options_pb2.double_opt])
+
+ message_descriptor =\
+ unittest_custom_options_pb2.SettingRealsFromNegativeInts.DESCRIPTOR
+ message_options = message_descriptor.GetOptions()
+ self.assertAlmostEqual(-12, message_options.Extensions[
+ unittest_custom_options_pb2.float_opt], 6)
+ self.assertAlmostEqual(-154, message_options.Extensions[
+ unittest_custom_options_pb2.double_opt])
+
+ def testComplexExtensionOptions(self):
+ descriptor =\
+ unittest_custom_options_pb2.VariousComplexOptions.DESCRIPTOR
+ options = descriptor.GetOptions()
+ self.assertEqual(42, options.Extensions[
+ unittest_custom_options_pb2.complex_opt1].foo)
+ self.assertEqual(324, options.Extensions[
+ unittest_custom_options_pb2.complex_opt1].Extensions[
+ unittest_custom_options_pb2.quux])
+ self.assertEqual(876, options.Extensions[
+ unittest_custom_options_pb2.complex_opt1].Extensions[
+ unittest_custom_options_pb2.corge].qux)
+ self.assertEqual(987, options.Extensions[
+ unittest_custom_options_pb2.complex_opt2].baz)
+ self.assertEqual(654, options.Extensions[
+ unittest_custom_options_pb2.complex_opt2].Extensions[
+ unittest_custom_options_pb2.grault])
+ self.assertEqual(743, options.Extensions[
+ unittest_custom_options_pb2.complex_opt2].bar.foo)
+ self.assertEqual(1999, options.Extensions[
+ unittest_custom_options_pb2.complex_opt2].bar.Extensions[
+ unittest_custom_options_pb2.quux])
+ self.assertEqual(2008, options.Extensions[
+ unittest_custom_options_pb2.complex_opt2].bar.Extensions[
+ unittest_custom_options_pb2.corge].qux)
+ self.assertEqual(741, options.Extensions[
+ unittest_custom_options_pb2.complex_opt2].Extensions[
+ unittest_custom_options_pb2.garply].foo)
+ self.assertEqual(1998, options.Extensions[
+ unittest_custom_options_pb2.complex_opt2].Extensions[
+ unittest_custom_options_pb2.garply].Extensions[
+ unittest_custom_options_pb2.quux])
+ self.assertEqual(2121, options.Extensions[
+ unittest_custom_options_pb2.complex_opt2].Extensions[
+ unittest_custom_options_pb2.garply].Extensions[
+ unittest_custom_options_pb2.corge].qux)
+ self.assertEqual(1971, options.Extensions[
+ unittest_custom_options_pb2.ComplexOptionType2
+ .ComplexOptionType4.complex_opt4].waldo)
+ self.assertEqual(321, options.Extensions[
+ unittest_custom_options_pb2.complex_opt2].fred.waldo)
+ self.assertEqual(9, options.Extensions[
+ unittest_custom_options_pb2.complex_opt3].qux)
+ self.assertEqual(22, options.Extensions[
+ unittest_custom_options_pb2.complex_opt3].complexoptiontype5.plugh)
+ self.assertEqual(24, options.Extensions[
+ unittest_custom_options_pb2.complexopt6].xyzzy)
+
+ # Check that aggregate options were parsed and saved correctly in
+ # the appropriate descriptors.
+ def testAggregateOptions(self):
+ file_descriptor = unittest_custom_options_pb2.DESCRIPTOR
+ message_descriptor =\
+ unittest_custom_options_pb2.AggregateMessage.DESCRIPTOR
+ field_descriptor = message_descriptor.fields_by_name["fieldname"]
+ enum_descriptor = unittest_custom_options_pb2.AggregateEnum.DESCRIPTOR
+ enum_value_descriptor = enum_descriptor.values_by_name["VALUE"]
+ service_descriptor =\
+ unittest_custom_options_pb2.AggregateService.DESCRIPTOR
+ method_descriptor = service_descriptor.FindMethodByName("Method")
+
+ # Tests for the different types of data embedded in fileopt
+ file_options = file_descriptor.GetOptions().Extensions[
+ unittest_custom_options_pb2.fileopt]
+ self.assertEqual(100, file_options.i)
+ self.assertEqual("FileAnnotation", file_options.s)
+ self.assertEqual("NestedFileAnnotation", file_options.sub.s)
+ self.assertEqual("FileExtensionAnnotation", file_options.file.Extensions[
+ unittest_custom_options_pb2.fileopt].s)
+ self.assertEqual("EmbeddedMessageSetElement", file_options.mset.Extensions[
+ unittest_custom_options_pb2.AggregateMessageSetElement
+ .message_set_extension].s)
+
+ # Simple tests for all the other types of annotations
+ self.assertEqual(
+ "MessageAnnotation",
+ message_descriptor.GetOptions().Extensions[
+ unittest_custom_options_pb2.msgopt].s)
+ self.assertEqual(
+ "FieldAnnotation",
+ field_descriptor.GetOptions().Extensions[
+ unittest_custom_options_pb2.fieldopt].s)
+ self.assertEqual(
+ "EnumAnnotation",
+ enum_descriptor.GetOptions().Extensions[
+ unittest_custom_options_pb2.enumopt].s)
+ self.assertEqual(
+ "EnumValueAnnotation",
+ enum_value_descriptor.GetOptions().Extensions[
+ unittest_custom_options_pb2.enumvalopt].s)
+ self.assertEqual(
+ "ServiceAnnotation",
+ service_descriptor.GetOptions().Extensions[
+ unittest_custom_options_pb2.serviceopt].s)
+ self.assertEqual(
+ "MethodAnnotation",
+ method_descriptor.GetOptions().Extensions[
+ unittest_custom_options_pb2.methodopt].s)
+
+ def testNestedOptions(self):
+ nested_message =\
+ unittest_custom_options_pb2.NestedOptionType.NestedMessage.DESCRIPTOR
+ self.assertEqual(1001, nested_message.GetOptions().Extensions[
+ unittest_custom_options_pb2.message_opt1])
+ nested_field = nested_message.fields_by_name["nested_field"]
+ self.assertEqual(1002, nested_field.GetOptions().Extensions[
+ unittest_custom_options_pb2.field_opt1])
+ outer_message =\
+ unittest_custom_options_pb2.NestedOptionType.DESCRIPTOR
+ nested_enum = outer_message.enum_types_by_name["NestedEnum"]
+ self.assertEqual(1003, nested_enum.GetOptions().Extensions[
+ unittest_custom_options_pb2.enum_opt1])
+ nested_enum_value = outer_message.enum_values_by_name["NESTED_ENUM_VALUE"]
+ self.assertEqual(1004, nested_enum_value.GetOptions().Extensions[
+ unittest_custom_options_pb2.enum_value_opt1])
+ nested_extension = outer_message.extensions_by_name["nested_extension"]
+ self.assertEqual(1005, nested_extension.GetOptions().Extensions[
+ unittest_custom_options_pb2.field_opt2])
+
+ def testFileDescriptorReferences(self):
+ self.assertEqual(self.my_enum.file, self.my_file)
+ self.assertEqual(self.my_message.file, self.my_file)
+
+ def testFileDescriptor(self):
+ self.assertEqual(self.my_file.name, 'some/filename/some.proto')
+ self.assertEqual(self.my_file.package, 'protobuf_unittest')
+
+
+class DescriptorCopyToProtoTest(unittest.TestCase):
+ """Tests for CopyTo functions of Descriptor."""
+
+ def _AssertProtoEqual(self, actual_proto, expected_class, expected_ascii):
+ expected_proto = expected_class()
+ text_format.Merge(expected_ascii, expected_proto)
+
+ self.assertEqual(
+ actual_proto, expected_proto,
+ 'Not equal,\nActual:\n%s\nExpected:\n%s\n'
+ % (str(actual_proto), str(expected_proto)))
+
+ def _InternalTestCopyToProto(self, desc, expected_proto_class,
+ expected_proto_ascii):
+ actual = expected_proto_class()
+ desc.CopyToProto(actual)
+ self._AssertProtoEqual(
+ actual, expected_proto_class, expected_proto_ascii)
+
+ def testCopyToProto_EmptyMessage(self):
+ self._InternalTestCopyToProto(
+ unittest_pb2.TestEmptyMessage.DESCRIPTOR,
+ descriptor_pb2.DescriptorProto,
+ TEST_EMPTY_MESSAGE_DESCRIPTOR_ASCII)
+
+ def testCopyToProto_NestedMessage(self):
+ TEST_NESTED_MESSAGE_ASCII = """
+ name: 'NestedMessage'
+ field: <
+ name: 'bb'
+ number: 1
+ label: 1 # Optional
+ type: 5 # TYPE_INT32
+ >
+ """
+
+ self._InternalTestCopyToProto(
+ unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR,
+ descriptor_pb2.DescriptorProto,
+ TEST_NESTED_MESSAGE_ASCII)
+
+ def testCopyToProto_ForeignNestedMessage(self):
+ TEST_FOREIGN_NESTED_ASCII = """
+ name: 'TestForeignNested'
+ field: <
+ name: 'foreign_nested'
+ number: 1
+ label: 1 # Optional
+ type: 11 # TYPE_MESSAGE
+ type_name: '.protobuf_unittest.TestAllTypes.NestedMessage'
+ >
+ """
+
+ self._InternalTestCopyToProto(
+ unittest_pb2.TestForeignNested.DESCRIPTOR,
+ descriptor_pb2.DescriptorProto,
+ TEST_FOREIGN_NESTED_ASCII)
+
+ def testCopyToProto_ForeignEnum(self):
+ TEST_FOREIGN_ENUM_ASCII = """
+ name: 'ForeignEnum'
+ value: <
+ name: 'FOREIGN_FOO'
+ number: 4
+ >
+ value: <
+ name: 'FOREIGN_BAR'
+ number: 5
+ >
+ value: <
+ name: 'FOREIGN_BAZ'
+ number: 6
+ >
+ """
+
+ self._InternalTestCopyToProto(
+ unittest_pb2._FOREIGNENUM,
+ descriptor_pb2.EnumDescriptorProto,
+ TEST_FOREIGN_ENUM_ASCII)
+
+ def testCopyToProto_Options(self):
+ TEST_DEPRECATED_FIELDS_ASCII = """
+ name: 'TestDeprecatedFields'
+ field: <
+ name: 'deprecated_int32'
+ number: 1
+ label: 1 # Optional
+ type: 5 # TYPE_INT32
+ options: <
+ deprecated: true
+ >
+ >
+ """
+
+ self._InternalTestCopyToProto(
+ unittest_pb2.TestDeprecatedFields.DESCRIPTOR,
+ descriptor_pb2.DescriptorProto,
+ TEST_DEPRECATED_FIELDS_ASCII)
+
+ def testCopyToProto_AllExtensions(self):
+ TEST_EMPTY_MESSAGE_WITH_EXTENSIONS_ASCII = """
+ name: 'TestEmptyMessageWithExtensions'
+ extension_range: <
+ start: 1
+ end: 536870912
+ >
+ """
+
+ self._InternalTestCopyToProto(
+ unittest_pb2.TestEmptyMessageWithExtensions.DESCRIPTOR,
+ descriptor_pb2.DescriptorProto,
+ TEST_EMPTY_MESSAGE_WITH_EXTENSIONS_ASCII)
+
+ def testCopyToProto_SeveralExtensions(self):
+ TEST_MESSAGE_WITH_SEVERAL_EXTENSIONS_ASCII = """
+ name: 'TestMultipleExtensionRanges'
+ extension_range: <
+ start: 42
+ end: 43
+ >
+ extension_range: <
+ start: 4143
+ end: 4244
+ >
+ extension_range: <
+ start: 65536
+ end: 536870912
+ >
+ """
+
+ self._InternalTestCopyToProto(
+ unittest_pb2.TestMultipleExtensionRanges.DESCRIPTOR,
+ descriptor_pb2.DescriptorProto,
+ TEST_MESSAGE_WITH_SEVERAL_EXTENSIONS_ASCII)
+
+ def testCopyToProto_FileDescriptor(self):
+ UNITTEST_IMPORT_FILE_DESCRIPTOR_ASCII = ("""
+ name: 'google/protobuf/unittest_import.proto'
+ package: 'protobuf_unittest_import'
+ dependency: 'google/protobuf/unittest_import_public.proto'
+ message_type: <
+ name: 'ImportMessage'
+ field: <
+ name: 'd'
+ number: 1
+ label: 1 # Optional
+ type: 5 # TYPE_INT32
+ >
+ >
+ """ +
+ """enum_type: <
+ name: 'ImportEnum'
+ value: <
+ name: 'IMPORT_FOO'
+ number: 7
+ >
+ value: <
+ name: 'IMPORT_BAR'
+ number: 8
+ >
+ value: <
+ name: 'IMPORT_BAZ'
+ number: 9
+ >
+ >
+ options: <
+ java_package: 'com.google.protobuf.test'
+ optimize_for: 1 # SPEED
+ >
+ public_dependency: 0
+ """)
+
+ self._InternalTestCopyToProto(
+ unittest_import_pb2.DESCRIPTOR,
+ descriptor_pb2.FileDescriptorProto,
+ UNITTEST_IMPORT_FILE_DESCRIPTOR_ASCII)
+
+ def testCopyToProto_ServiceDescriptor(self):
+ TEST_SERVICE_ASCII = """
+ name: 'TestService'
+ method: <
+ name: 'Foo'
+ input_type: '.protobuf_unittest.FooRequest'
+ output_type: '.protobuf_unittest.FooResponse'
+ >
+ method: <
+ name: 'Bar'
+ input_type: '.protobuf_unittest.BarRequest'
+ output_type: '.protobuf_unittest.BarResponse'
+ >
+ """
+
+ self._InternalTestCopyToProto(
+ unittest_pb2.TestService.DESCRIPTOR,
+ descriptor_pb2.ServiceDescriptorProto,
+ TEST_SERVICE_ASCII)
+
+
+class MakeDescriptorTest(unittest.TestCase):
+ def testMakeDescriptorWithUnsignedIntField(self):
+ file_descriptor_proto = descriptor_pb2.FileDescriptorProto()
+ file_descriptor_proto.name = 'Foo'
+ message_type = file_descriptor_proto.message_type.add()
+ message_type.name = file_descriptor_proto.name
+ field = message_type.field.add()
+ field.number = 1
+ field.name = 'uint64_field'
+ field.label = descriptor.FieldDescriptor.LABEL_REQUIRED
+ field.type = descriptor.FieldDescriptor.TYPE_UINT64
+ result = descriptor.MakeDescriptor(message_type)
+ self.assertEqual(result.fields[0].cpp_type,
+ descriptor.FieldDescriptor.CPPTYPE_UINT64)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/generator_test.py b/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/generator_test.py
new file mode 100755
index 00000000..8343aba1
--- /dev/null
+++ b/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/generator_test.py
@@ -0,0 +1,269 @@
+#! /usr/bin/python
+#
+# Protocol Buffers - Google's data interchange format
+# Copyright 2008 Google Inc. All rights reserved.
+# http://code.google.com/p/protobuf/
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following disclaimer
+# in the documentation and/or other materials provided with the
+# distribution.
+# * Neither the name of Google Inc. nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+# TODO(robinson): Flesh this out considerably. We focused on reflection_test.py
+# first, since it's testing the subtler code, and since it provides decent
+# indirect testing of the protocol compiler output.
+
+"""Unittest that directly tests the output of the pure-Python protocol
+compiler. See //google/protobuf/reflection_test.py for a test which
+further ensures that we can use Python protocol message objects as we expect.
+"""
+
+__author__ = 'robinson@google.com (Will Robinson)'
+
+import unittest
+from google.protobuf.internal import test_bad_identifiers_pb2
+from google.protobuf import unittest_custom_options_pb2
+from google.protobuf import unittest_import_pb2
+from google.protobuf import unittest_import_public_pb2
+from google.protobuf import unittest_mset_pb2
+from google.protobuf import unittest_pb2
+from google.protobuf import unittest_no_generic_services_pb2
+from google.protobuf import service
+
+MAX_EXTENSION = 536870912
+
+
+class GeneratorTest(unittest.TestCase):
+
+ def testNestedMessageDescriptor(self):
+ field_name = 'optional_nested_message'
+ proto_type = unittest_pb2.TestAllTypes
+ self.assertEqual(
+ proto_type.NestedMessage.DESCRIPTOR,
+ proto_type.DESCRIPTOR.fields_by_name[field_name].message_type)
+
+ def testEnums(self):
+ # We test only module-level enums here.
+ # TODO(robinson): Examine descriptors directly to check
+ # enum descriptor output.
+ self.assertEqual(4, unittest_pb2.FOREIGN_FOO)
+ self.assertEqual(5, unittest_pb2.FOREIGN_BAR)
+ self.assertEqual(6, unittest_pb2.FOREIGN_BAZ)
+
+ proto = unittest_pb2.TestAllTypes()
+ self.assertEqual(1, proto.FOO)
+ self.assertEqual(1, unittest_pb2.TestAllTypes.FOO)
+ self.assertEqual(2, proto.BAR)
+ self.assertEqual(2, unittest_pb2.TestAllTypes.BAR)
+ self.assertEqual(3, proto.BAZ)
+ self.assertEqual(3, unittest_pb2.TestAllTypes.BAZ)
+
+ def testExtremeDefaultValues(self):
+ message = unittest_pb2.TestExtremeDefaultValues()
+
+ # Python pre-2.6 does not have isinf() or isnan() functions, so we have
+ # to provide our own.
+ def isnan(val):
+ # NaN is never equal to itself.
+ return val != val
+ def isinf(val):
+ # Infinity times zero equals NaN.
+ return not isnan(val) and isnan(val * 0)
+
+ self.assertTrue(isinf(message.inf_double))
+ self.assertTrue(message.inf_double > 0)
+ self.assertTrue(isinf(message.neg_inf_double))
+ self.assertTrue(message.neg_inf_double < 0)
+ self.assertTrue(isnan(message.nan_double))
+
+ self.assertTrue(isinf(message.inf_float))
+ self.assertTrue(message.inf_float > 0)
+ self.assertTrue(isinf(message.neg_inf_float))
+ self.assertTrue(message.neg_inf_float < 0)
+ self.assertTrue(isnan(message.nan_float))
+ self.assertEqual("? ? ?? ?? ??? ??/ ??-", message.cpp_trigraph)
+
+ def testHasDefaultValues(self):
+ desc = unittest_pb2.TestAllTypes.DESCRIPTOR
+
+ expected_has_default_by_name = {
+ 'optional_int32': False,
+ 'repeated_int32': False,
+ 'optional_nested_message': False,
+ 'default_int32': True,
+ }
+
+ has_default_by_name = dict(
+ [(f.name, f.has_default_value)
+ for f in desc.fields
+ if f.name in expected_has_default_by_name])
+ self.assertEqual(expected_has_default_by_name, has_default_by_name)
+
+ def testContainingTypeBehaviorForExtensions(self):
+ self.assertEqual(unittest_pb2.optional_int32_extension.containing_type,
+ unittest_pb2.TestAllExtensions.DESCRIPTOR)
+ self.assertEqual(unittest_pb2.TestRequired.single.containing_type,
+ unittest_pb2.TestAllExtensions.DESCRIPTOR)
+
+ def testExtensionScope(self):
+ self.assertEqual(unittest_pb2.optional_int32_extension.extension_scope,
+ None)
+ self.assertEqual(unittest_pb2.TestRequired.single.extension_scope,
+ unittest_pb2.TestRequired.DESCRIPTOR)
+
+ def testIsExtension(self):
+ self.assertTrue(unittest_pb2.optional_int32_extension.is_extension)
+ self.assertTrue(unittest_pb2.TestRequired.single.is_extension)
+
+ message_descriptor = unittest_pb2.TestRequired.DESCRIPTOR
+ non_extension_descriptor = message_descriptor.fields_by_name['a']
+ self.assertTrue(not non_extension_descriptor.is_extension)
+
+ def testOptions(self):
+ proto = unittest_mset_pb2.TestMessageSet()
+ self.assertTrue(proto.DESCRIPTOR.GetOptions().message_set_wire_format)
+
+ def testMessageWithCustomOptions(self):
+ proto = unittest_custom_options_pb2.TestMessageWithCustomOptions()
+ enum_options = proto.DESCRIPTOR.enum_types_by_name['AnEnum'].GetOptions()
+ self.assertTrue(enum_options is not None)
+ # TODO(gps): We really should test for the presense of the enum_opt1
+ # extension and for its value to be set to -789.
+
+ def testNestedTypes(self):
+ self.assertEquals(
+ set(unittest_pb2.TestAllTypes.DESCRIPTOR.nested_types),
+ set([
+ unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR,
+ unittest_pb2.TestAllTypes.OptionalGroup.DESCRIPTOR,
+ unittest_pb2.TestAllTypes.RepeatedGroup.DESCRIPTOR,
+ ]))
+ self.assertEqual(unittest_pb2.TestEmptyMessage.DESCRIPTOR.nested_types, [])
+ self.assertEqual(
+ unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR.nested_types, [])
+
+ def testContainingType(self):
+ self.assertTrue(
+ unittest_pb2.TestEmptyMessage.DESCRIPTOR.containing_type is None)
+ self.assertTrue(
+ unittest_pb2.TestAllTypes.DESCRIPTOR.containing_type is None)
+ self.assertEqual(
+ unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR.containing_type,
+ unittest_pb2.TestAllTypes.DESCRIPTOR)
+ self.assertEqual(
+ unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR.containing_type,
+ unittest_pb2.TestAllTypes.DESCRIPTOR)
+ self.assertEqual(
+ unittest_pb2.TestAllTypes.RepeatedGroup.DESCRIPTOR.containing_type,
+ unittest_pb2.TestAllTypes.DESCRIPTOR)
+
+ def testContainingTypeInEnumDescriptor(self):
+ self.assertTrue(unittest_pb2._FOREIGNENUM.containing_type is None)
+ self.assertEqual(unittest_pb2._TESTALLTYPES_NESTEDENUM.containing_type,
+ unittest_pb2.TestAllTypes.DESCRIPTOR)
+
+ def testPackage(self):
+ self.assertEqual(
+ unittest_pb2.TestAllTypes.DESCRIPTOR.file.package,
+ 'protobuf_unittest')
+ desc = unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR
+ self.assertEqual(desc.file.package, 'protobuf_unittest')
+ self.assertEqual(
+ unittest_import_pb2.ImportMessage.DESCRIPTOR.file.package,
+ 'protobuf_unittest_import')
+
+ self.assertEqual(
+ unittest_pb2._FOREIGNENUM.file.package, 'protobuf_unittest')
+ self.assertEqual(
+ unittest_pb2._TESTALLTYPES_NESTEDENUM.file.package,
+ 'protobuf_unittest')
+ self.assertEqual(
+ unittest_import_pb2._IMPORTENUM.file.package,
+ 'protobuf_unittest_import')
+
+ def testExtensionRange(self):
+ self.assertEqual(
+ unittest_pb2.TestAllTypes.DESCRIPTOR.extension_ranges, [])
+ self.assertEqual(
+ unittest_pb2.TestAllExtensions.DESCRIPTOR.extension_ranges,
+ [(1, MAX_EXTENSION)])
+ self.assertEqual(
+ unittest_pb2.TestMultipleExtensionRanges.DESCRIPTOR.extension_ranges,
+ [(42, 43), (4143, 4244), (65536, MAX_EXTENSION)])
+
+ def testFileDescriptor(self):
+ self.assertEqual(unittest_pb2.DESCRIPTOR.name,
+ 'google/protobuf/unittest.proto')
+ self.assertEqual(unittest_pb2.DESCRIPTOR.package, 'protobuf_unittest')
+ self.assertFalse(unittest_pb2.DESCRIPTOR.serialized_pb is None)
+
+ def testNoGenericServices(self):
+ self.assertTrue(hasattr(unittest_no_generic_services_pb2, "TestMessage"))
+ self.assertTrue(hasattr(unittest_no_generic_services_pb2, "FOO"))
+ self.assertTrue(hasattr(unittest_no_generic_services_pb2, "test_extension"))
+
+ # Make sure unittest_no_generic_services_pb2 has no services subclassing
+ # Proto2 Service class.
+ if hasattr(unittest_no_generic_services_pb2, "TestService"):
+ self.assertFalse(issubclass(unittest_no_generic_services_pb2.TestService,
+ service.Service))
+
+ def testMessageTypesByName(self):
+ file_type = unittest_pb2.DESCRIPTOR
+ self.assertEqual(
+ unittest_pb2._TESTALLTYPES,
+ file_type.message_types_by_name[unittest_pb2._TESTALLTYPES.name])
+
+ # Nested messages shouldn't be included in the message_types_by_name
+ # dictionary (like in the C++ API).
+ self.assertFalse(
+ unittest_pb2._TESTALLTYPES_NESTEDMESSAGE.name in
+ file_type.message_types_by_name)
+
+ def testPublicImports(self):
+ # Test public imports as embedded message.
+ all_type_proto = unittest_pb2.TestAllTypes()
+ self.assertEqual(0, all_type_proto.optional_public_import_message.e)
+
+ # PublicImportMessage is actually defined in unittest_import_public_pb2
+ # module, and is public imported by unittest_import_pb2 module.
+ public_import_proto = unittest_import_pb2.PublicImportMessage()
+ self.assertEqual(0, public_import_proto.e)
+ self.assertTrue(unittest_import_public_pb2.PublicImportMessage is
+ unittest_import_pb2.PublicImportMessage)
+
+ def testBadIdentifiers(self):
+ # We're just testing that the code was imported without problems.
+ message = test_bad_identifiers_pb2.TestBadIdentifiers()
+ self.assertEqual(message.Extensions[test_bad_identifiers_pb2.message],
+ "foo")
+ self.assertEqual(message.Extensions[test_bad_identifiers_pb2.descriptor],
+ "bar")
+ self.assertEqual(message.Extensions[test_bad_identifiers_pb2.reflection],
+ "baz")
+ self.assertEqual(message.Extensions[test_bad_identifiers_pb2.service],
+ "qux")
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/golden_message b/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/golden_message
new file mode 100644
index 00000000..4dd62cd3
--- /dev/null
+++ b/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/golden_message
Binary files differ
diff --git a/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/golden_packed_fields_message b/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/golden_packed_fields_message
new file mode 100644
index 00000000..ee28d388
--- /dev/null
+++ b/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/golden_packed_fields_message
Binary files differ
diff --git a/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/message_test.py b/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/message_test.py
new file mode 100755
index 00000000..e71b295b
--- /dev/null
+++ b/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/message_test.py
@@ -0,0 +1,499 @@
+#! /usr/bin/python
+#
+# Protocol Buffers - Google's data interchange format
+# Copyright 2008 Google Inc. All rights reserved.
+# http://code.google.com/p/protobuf/
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following disclaimer
+# in the documentation and/or other materials provided with the
+# distribution.
+# * Neither the name of Google Inc. nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+"""Tests python protocol buffers against the golden message.
+
+Note that the golden messages exercise every known field type, thus this
+test ends up exercising and verifying nearly all of the parsing and
+serialization code in the whole library.
+
+TODO(kenton): Merge with wire_format_test? It doesn't make a whole lot of
+sense to call this a test of the "message" module, which only declares an
+abstract interface.
+"""
+
+__author__ = 'gps@google.com (Gregory P. Smith)'
+
+import copy
+import math
+import operator
+import pickle
+
+import unittest
+from google.protobuf import unittest_import_pb2
+from google.protobuf import unittest_pb2
+from google.protobuf.internal import api_implementation
+from google.protobuf.internal import test_util
+from google.protobuf import message
+
+try:
+ cmp # Python 2
+except NameError:
+ cmp = lambda x, y: (x > y) - (x < y) # Python 3
+
+# Python pre-2.6 does not have isinf() or isnan() functions, so we have
+# to provide our own.
+def isnan(val):
+ # NaN is never equal to itself.
+ return val != val
+def isinf(val):
+ # Infinity times zero equals NaN.
+ return not isnan(val) and isnan(val * 0)
+def IsPosInf(val):
+ return isinf(val) and (val > 0)
+def IsNegInf(val):
+ return isinf(val) and (val < 0)
+
+class MessageTest(unittest.TestCase):
+
+ def testGoldenMessage(self):
+ golden_data = test_util.GoldenFile('golden_message').read()
+ golden_message = unittest_pb2.TestAllTypes()
+ golden_message.ParseFromString(golden_data)
+ test_util.ExpectAllFieldsSet(self, golden_message)
+ self.assertEqual(golden_data, golden_message.SerializeToString())
+ golden_copy = copy.deepcopy(golden_message)
+ self.assertEqual(golden_data, golden_copy.SerializeToString())
+
+ def testGoldenExtensions(self):
+ golden_data = test_util.GoldenFile('golden_message').read()
+ golden_message = unittest_pb2.TestAllExtensions()
+ golden_message.ParseFromString(golden_data)
+ all_set = unittest_pb2.TestAllExtensions()
+ test_util.SetAllExtensions(all_set)
+ self.assertEquals(all_set, golden_message)
+ self.assertEqual(golden_data, golden_message.SerializeToString())
+ golden_copy = copy.deepcopy(golden_message)
+ self.assertEqual(golden_data, golden_copy.SerializeToString())
+
+ def testGoldenPackedMessage(self):
+ golden_data = test_util.GoldenFile('golden_packed_fields_message').read()
+ golden_message = unittest_pb2.TestPackedTypes()
+ golden_message.ParseFromString(golden_data)
+ all_set = unittest_pb2.TestPackedTypes()
+ test_util.SetAllPackedFields(all_set)
+ self.assertEquals(all_set, golden_message)
+ self.assertEqual(golden_data, all_set.SerializeToString())
+ golden_copy = copy.deepcopy(golden_message)
+ self.assertEqual(golden_data, golden_copy.SerializeToString())
+
+ def testGoldenPackedExtensions(self):
+ golden_data = test_util.GoldenFile('golden_packed_fields_message').read()
+ golden_message = unittest_pb2.TestPackedExtensions()
+ golden_message.ParseFromString(golden_data)
+ all_set = unittest_pb2.TestPackedExtensions()
+ test_util.SetAllPackedExtensions(all_set)
+ self.assertEquals(all_set, golden_message)
+ self.assertEqual(golden_data, all_set.SerializeToString())
+ golden_copy = copy.deepcopy(golden_message)
+ self.assertEqual(golden_data, golden_copy.SerializeToString())
+
+ def testPickleSupport(self):
+ golden_data = test_util.GoldenFile('golden_message').read()
+ golden_message = unittest_pb2.TestAllTypes()
+ golden_message.ParseFromString(golden_data)
+ pickled_message = pickle.dumps(golden_message)
+
+ unpickled_message = pickle.loads(pickled_message)
+ self.assertEquals(unpickled_message, golden_message)
+
+ def testPickleIncompleteProto(self):
+ golden_message = unittest_pb2.TestRequired(a=1)
+ pickled_message = pickle.dumps(golden_message)
+
+ unpickled_message = pickle.loads(pickled_message)
+ self.assertEquals(unpickled_message, golden_message)
+ self.assertEquals(unpickled_message.a, 1)
+ # This is still an incomplete proto - so serializing should fail
+ self.assertRaises(message.EncodeError, unpickled_message.SerializeToString)
+
+ def testPositiveInfinity(self):
+ golden_data = ('\x5D\x00\x00\x80\x7F'
+ '\x61\x00\x00\x00\x00\x00\x00\xF0\x7F'
+ '\xCD\x02\x00\x00\x80\x7F'
+ '\xD1\x02\x00\x00\x00\x00\x00\x00\xF0\x7F')
+ golden_message = unittest_pb2.TestAllTypes()
+ golden_message.ParseFromString(golden_data)
+ self.assertTrue(IsPosInf(golden_message.optional_float))
+ self.assertTrue(IsPosInf(golden_message.optional_double))
+ self.assertTrue(IsPosInf(golden_message.repeated_float[0]))
+ self.assertTrue(IsPosInf(golden_message.repeated_double[0]))
+ self.assertEqual(golden_data, golden_message.SerializeToString())
+
+ def testNegativeInfinity(self):
+ golden_data = ('\x5D\x00\x00\x80\xFF'
+ '\x61\x00\x00\x00\x00\x00\x00\xF0\xFF'
+ '\xCD\x02\x00\x00\x80\xFF'
+ '\xD1\x02\x00\x00\x00\x00\x00\x00\xF0\xFF')
+ golden_message = unittest_pb2.TestAllTypes()
+ golden_message.ParseFromString(golden_data)
+ self.assertTrue(IsNegInf(golden_message.optional_float))
+ self.assertTrue(IsNegInf(golden_message.optional_double))
+ self.assertTrue(IsNegInf(golden_message.repeated_float[0]))
+ self.assertTrue(IsNegInf(golden_message.repeated_double[0]))
+ self.assertEqual(golden_data, golden_message.SerializeToString())
+
+ def testNotANumber(self):
+ golden_data = ('\x5D\x00\x00\xC0\x7F'
+ '\x61\x00\x00\x00\x00\x00\x00\xF8\x7F'
+ '\xCD\x02\x00\x00\xC0\x7F'
+ '\xD1\x02\x00\x00\x00\x00\x00\x00\xF8\x7F')
+ golden_message = unittest_pb2.TestAllTypes()
+ golden_message.ParseFromString(golden_data)
+ self.assertTrue(isnan(golden_message.optional_float))
+ self.assertTrue(isnan(golden_message.optional_double))
+ self.assertTrue(isnan(golden_message.repeated_float[0]))
+ self.assertTrue(isnan(golden_message.repeated_double[0]))
+
+ # The protocol buffer may serialize to any one of multiple different
+ # representations of a NaN. Rather than verify a specific representation,
+ # verify the serialized string can be converted into a correctly
+ # behaving protocol buffer.
+ serialized = golden_message.SerializeToString()
+ message = unittest_pb2.TestAllTypes()
+ message.ParseFromString(serialized)
+ self.assertTrue(isnan(message.optional_float))
+ self.assertTrue(isnan(message.optional_double))
+ self.assertTrue(isnan(message.repeated_float[0]))
+ self.assertTrue(isnan(message.repeated_double[0]))
+
+ def testPositiveInfinityPacked(self):
+ golden_data = ('\xA2\x06\x04\x00\x00\x80\x7F'
+ '\xAA\x06\x08\x00\x00\x00\x00\x00\x00\xF0\x7F')
+ golden_message = unittest_pb2.TestPackedTypes()
+ golden_message.ParseFromString(golden_data)
+ self.assertTrue(IsPosInf(golden_message.packed_float[0]))
+ self.assertTrue(IsPosInf(golden_message.packed_double[0]))
+ self.assertEqual(golden_data, golden_message.SerializeToString())
+
+ def testNegativeInfinityPacked(self):
+ golden_data = ('\xA2\x06\x04\x00\x00\x80\xFF'
+ '\xAA\x06\x08\x00\x00\x00\x00\x00\x00\xF0\xFF')
+ golden_message = unittest_pb2.TestPackedTypes()
+ golden_message.ParseFromString(golden_data)
+ self.assertTrue(IsNegInf(golden_message.packed_float[0]))
+ self.assertTrue(IsNegInf(golden_message.packed_double[0]))
+ self.assertEqual(golden_data, golden_message.SerializeToString())
+
+ def testNotANumberPacked(self):
+ golden_data = ('\xA2\x06\x04\x00\x00\xC0\x7F'
+ '\xAA\x06\x08\x00\x00\x00\x00\x00\x00\xF8\x7F')
+ golden_message = unittest_pb2.TestPackedTypes()
+ golden_message.ParseFromString(golden_data)
+ self.assertTrue(isnan(golden_message.packed_float[0]))
+ self.assertTrue(isnan(golden_message.packed_double[0]))
+
+ serialized = golden_message.SerializeToString()
+ message = unittest_pb2.TestPackedTypes()
+ message.ParseFromString(serialized)
+ self.assertTrue(isnan(message.packed_float[0]))
+ self.assertTrue(isnan(message.packed_double[0]))
+
+ def testExtremeFloatValues(self):
+ message = unittest_pb2.TestAllTypes()
+
+ # Most positive exponent, no significand bits set.
+ kMostPosExponentNoSigBits = math.pow(2, 127)
+ message.optional_float = kMostPosExponentNoSigBits
+ message.ParseFromString(message.SerializeToString())
+ self.assertTrue(message.optional_float == kMostPosExponentNoSigBits)
+
+ # Most positive exponent, one significand bit set.
+ kMostPosExponentOneSigBit = 1.5 * math.pow(2, 127)
+ message.optional_float = kMostPosExponentOneSigBit
+ message.ParseFromString(message.SerializeToString())
+ self.assertTrue(message.optional_float == kMostPosExponentOneSigBit)
+
+ # Repeat last two cases with values of same magnitude, but negative.
+ message.optional_float = -kMostPosExponentNoSigBits
+ message.ParseFromString(message.SerializeToString())
+ self.assertTrue(message.optional_float == -kMostPosExponentNoSigBits)
+
+ message.optional_float = -kMostPosExponentOneSigBit
+ message.ParseFromString(message.SerializeToString())
+ self.assertTrue(message.optional_float == -kMostPosExponentOneSigBit)
+
+ # Most negative exponent, no significand bits set.
+ kMostNegExponentNoSigBits = math.pow(2, -127)
+ message.optional_float = kMostNegExponentNoSigBits
+ message.ParseFromString(message.SerializeToString())
+ self.assertTrue(message.optional_float == kMostNegExponentNoSigBits)
+
+ # Most negative exponent, one significand bit set.
+ kMostNegExponentOneSigBit = 1.5 * math.pow(2, -127)
+ message.optional_float = kMostNegExponentOneSigBit
+ message.ParseFromString(message.SerializeToString())
+ self.assertTrue(message.optional_float == kMostNegExponentOneSigBit)
+
+ # Repeat last two cases with values of the same magnitude, but negative.
+ message.optional_float = -kMostNegExponentNoSigBits
+ message.ParseFromString(message.SerializeToString())
+ self.assertTrue(message.optional_float == -kMostNegExponentNoSigBits)
+
+ message.optional_float = -kMostNegExponentOneSigBit
+ message.ParseFromString(message.SerializeToString())
+ self.assertTrue(message.optional_float == -kMostNegExponentOneSigBit)
+
+ def testExtremeDoubleValues(self):
+ message = unittest_pb2.TestAllTypes()
+
+ # Most positive exponent, no significand bits set.
+ kMostPosExponentNoSigBits = math.pow(2, 1023)
+ message.optional_double = kMostPosExponentNoSigBits
+ message.ParseFromString(message.SerializeToString())
+ self.assertTrue(message.optional_double == kMostPosExponentNoSigBits)
+
+ # Most positive exponent, one significand bit set.
+ kMostPosExponentOneSigBit = 1.5 * math.pow(2, 1023)
+ message.optional_double = kMostPosExponentOneSigBit
+ message.ParseFromString(message.SerializeToString())
+ self.assertTrue(message.optional_double == kMostPosExponentOneSigBit)
+
+ # Repeat last two cases with values of same magnitude, but negative.
+ message.optional_double = -kMostPosExponentNoSigBits
+ message.ParseFromString(message.SerializeToString())
+ self.assertTrue(message.optional_double == -kMostPosExponentNoSigBits)
+
+ message.optional_double = -kMostPosExponentOneSigBit
+ message.ParseFromString(message.SerializeToString())
+ self.assertTrue(message.optional_double == -kMostPosExponentOneSigBit)
+
+ # Most negative exponent, no significand bits set.
+ kMostNegExponentNoSigBits = math.pow(2, -1023)
+ message.optional_double = kMostNegExponentNoSigBits
+ message.ParseFromString(message.SerializeToString())
+ self.assertTrue(message.optional_double == kMostNegExponentNoSigBits)
+
+ # Most negative exponent, one significand bit set.
+ kMostNegExponentOneSigBit = 1.5 * math.pow(2, -1023)
+ message.optional_double = kMostNegExponentOneSigBit
+ message.ParseFromString(message.SerializeToString())
+ self.assertTrue(message.optional_double == kMostNegExponentOneSigBit)
+
+ # Repeat last two cases with values of the same magnitude, but negative.
+ message.optional_double = -kMostNegExponentNoSigBits
+ message.ParseFromString(message.SerializeToString())
+ self.assertTrue(message.optional_double == -kMostNegExponentNoSigBits)
+
+ message.optional_double = -kMostNegExponentOneSigBit
+ message.ParseFromString(message.SerializeToString())
+ self.assertTrue(message.optional_double == -kMostNegExponentOneSigBit)
+
+ def testSortingRepeatedScalarFieldsDefaultComparator(self):
+ """Check some different types with the default comparator."""
+ message = unittest_pb2.TestAllTypes()
+
+ # TODO(mattp): would testing more scalar types strengthen test?
+ message.repeated_int32.append(1)
+ message.repeated_int32.append(3)
+ message.repeated_int32.append(2)
+ message.repeated_int32.sort()
+ self.assertEqual(message.repeated_int32[0], 1)
+ self.assertEqual(message.repeated_int32[1], 2)
+ self.assertEqual(message.repeated_int32[2], 3)
+
+ message.repeated_float.append(1.1)
+ message.repeated_float.append(1.3)
+ message.repeated_float.append(1.2)
+ message.repeated_float.sort()
+ self.assertAlmostEqual(message.repeated_float[0], 1.1)
+ self.assertAlmostEqual(message.repeated_float[1], 1.2)
+ self.assertAlmostEqual(message.repeated_float[2], 1.3)
+
+ message.repeated_string.append('a')
+ message.repeated_string.append('c')
+ message.repeated_string.append('b')
+ message.repeated_string.sort()
+ self.assertEqual(message.repeated_string[0], 'a')
+ self.assertEqual(message.repeated_string[1], 'b')
+ self.assertEqual(message.repeated_string[2], 'c')
+
+ message.repeated_bytes.append('a')
+ message.repeated_bytes.append('c')
+ message.repeated_bytes.append('b')
+ message.repeated_bytes.sort()
+ self.assertEqual(message.repeated_bytes[0], 'a')
+ self.assertEqual(message.repeated_bytes[1], 'b')
+ self.assertEqual(message.repeated_bytes[2], 'c')
+
+ def testSortingRepeatedScalarFieldsCustomComparator(self):
+ """Check some different types with custom comparator."""
+ message = unittest_pb2.TestAllTypes()
+
+ message.repeated_int32.append(-3)
+ message.repeated_int32.append(-2)
+ message.repeated_int32.append(-1)
+ message.repeated_int32.sort(lambda x,y: cmp(abs(x), abs(y)))
+ self.assertEqual(message.repeated_int32[0], -1)
+ self.assertEqual(message.repeated_int32[1], -2)
+ self.assertEqual(message.repeated_int32[2], -3)
+
+ message.repeated_string.append('aaa')
+ message.repeated_string.append('bb')
+ message.repeated_string.append('c')
+ message.repeated_string.sort(lambda x,y: cmp(len(x), len(y)))
+ self.assertEqual(message.repeated_string[0], 'c')
+ self.assertEqual(message.repeated_string[1], 'bb')
+ self.assertEqual(message.repeated_string[2], 'aaa')
+
+ def testSortingRepeatedCompositeFieldsCustomComparator(self):
+ """Check passing a custom comparator to sort a repeated composite field."""
+ message = unittest_pb2.TestAllTypes()
+
+ message.repeated_nested_message.add().bb = 1
+ message.repeated_nested_message.add().bb = 3
+ message.repeated_nested_message.add().bb = 2
+ message.repeated_nested_message.add().bb = 6
+ message.repeated_nested_message.add().bb = 5
+ message.repeated_nested_message.add().bb = 4
+ message.repeated_nested_message.sort(lambda x,y: cmp(x.bb, y.bb))
+ self.assertEqual(message.repeated_nested_message[0].bb, 1)
+ self.assertEqual(message.repeated_nested_message[1].bb, 2)
+ self.assertEqual(message.repeated_nested_message[2].bb, 3)
+ self.assertEqual(message.repeated_nested_message[3].bb, 4)
+ self.assertEqual(message.repeated_nested_message[4].bb, 5)
+ self.assertEqual(message.repeated_nested_message[5].bb, 6)
+
+ def testRepeatedCompositeFieldSortArguments(self):
+ """Check sorting a repeated composite field using list.sort() arguments."""
+ message = unittest_pb2.TestAllTypes()
+
+ get_bb = operator.attrgetter('bb')
+ cmp_bb = lambda a, b: cmp(a.bb, b.bb)
+ message.repeated_nested_message.add().bb = 1
+ message.repeated_nested_message.add().bb = 3
+ message.repeated_nested_message.add().bb = 2
+ message.repeated_nested_message.add().bb = 6
+ message.repeated_nested_message.add().bb = 5
+ message.repeated_nested_message.add().bb = 4
+ message.repeated_nested_message.sort(key=get_bb)
+ self.assertEqual([k.bb for k in message.repeated_nested_message],
+ [1, 2, 3, 4, 5, 6])
+ message.repeated_nested_message.sort(key=get_bb, reverse=True)
+ self.assertEqual([k.bb for k in message.repeated_nested_message],
+ [6, 5, 4, 3, 2, 1])
+ message.repeated_nested_message.sort(sort_function=cmp_bb)
+ self.assertEqual([k.bb for k in message.repeated_nested_message],
+ [1, 2, 3, 4, 5, 6])
+ message.repeated_nested_message.sort(cmp=cmp_bb, reverse=True)
+ self.assertEqual([k.bb for k in message.repeated_nested_message],
+ [6, 5, 4, 3, 2, 1])
+
+ def testRepeatedScalarFieldSortArguments(self):
+ """Check sorting a scalar field using list.sort() arguments."""
+ message = unittest_pb2.TestAllTypes()
+
+ abs_cmp = lambda a, b: cmp(abs(a), abs(b))
+ message.repeated_int32.append(-3)
+ message.repeated_int32.append(-2)
+ message.repeated_int32.append(-1)
+ message.repeated_int32.sort(key=abs)
+ self.assertEqual(list(message.repeated_int32), [-1, -2, -3])
+ message.repeated_int32.sort(key=abs, reverse=True)
+ self.assertEqual(list(message.repeated_int32), [-3, -2, -1])
+ message.repeated_int32.sort(sort_function=abs_cmp)
+ self.assertEqual(list(message.repeated_int32), [-1, -2, -3])
+ message.repeated_int32.sort(cmp=abs_cmp, reverse=True)
+ self.assertEqual(list(message.repeated_int32), [-3, -2, -1])
+
+ len_cmp = lambda a, b: cmp(len(a), len(b))
+ message.repeated_string.append('aaa')
+ message.repeated_string.append('bb')
+ message.repeated_string.append('c')
+ message.repeated_string.sort(key=len)
+ self.assertEqual(list(message.repeated_string), ['c', 'bb', 'aaa'])
+ message.repeated_string.sort(key=len, reverse=True)
+ self.assertEqual(list(message.repeated_string), ['aaa', 'bb', 'c'])
+ message.repeated_string.sort(sort_function=len_cmp)
+ self.assertEqual(list(message.repeated_string), ['c', 'bb', 'aaa'])
+ message.repeated_string.sort(cmp=len_cmp, reverse=True)
+ self.assertEqual(list(message.repeated_string), ['aaa', 'bb', 'c'])
+
+ def testParsingMerge(self):
+ """Check the merge behavior when a required or optional field appears
+ multiple times in the input."""
+ messages = [
+ unittest_pb2.TestAllTypes(),
+ unittest_pb2.TestAllTypes(),
+ unittest_pb2.TestAllTypes() ]
+ messages[0].optional_int32 = 1
+ messages[1].optional_int64 = 2
+ messages[2].optional_int32 = 3
+ messages[2].optional_string = 'hello'
+
+ merged_message = unittest_pb2.TestAllTypes()
+ merged_message.optional_int32 = 3
+ merged_message.optional_int64 = 2
+ merged_message.optional_string = 'hello'
+
+ generator = unittest_pb2.TestParsingMerge.RepeatedFieldsGenerator()
+ generator.field1.extend(messages)
+ generator.field2.extend(messages)
+ generator.field3.extend(messages)
+ generator.ext1.extend(messages)
+ generator.ext2.extend(messages)
+ generator.group1.add().field1.MergeFrom(messages[0])
+ generator.group1.add().field1.MergeFrom(messages[1])
+ generator.group1.add().field1.MergeFrom(messages[2])
+ generator.group2.add().field1.MergeFrom(messages[0])
+ generator.group2.add().field1.MergeFrom(messages[1])
+ generator.group2.add().field1.MergeFrom(messages[2])
+
+ data = generator.SerializeToString()
+ parsing_merge = unittest_pb2.TestParsingMerge()
+ parsing_merge.ParseFromString(data)
+
+ # Required and optional fields should be merged.
+ self.assertEqual(parsing_merge.required_all_types, merged_message)
+ self.assertEqual(parsing_merge.optional_all_types, merged_message)
+ self.assertEqual(parsing_merge.optionalgroup.optional_group_all_types,
+ merged_message)
+ self.assertEqual(parsing_merge.Extensions[
+ unittest_pb2.TestParsingMerge.optional_ext],
+ merged_message)
+
+ # Repeated fields should not be merged.
+ self.assertEqual(len(parsing_merge.repeated_all_types), 3)
+ self.assertEqual(len(parsing_merge.repeatedgroup), 3)
+ self.assertEqual(len(parsing_merge.Extensions[
+ unittest_pb2.TestParsingMerge.repeated_ext]), 3)
+
+
+ def testSortEmptyRepeatedCompositeContainer(self):
+ """Exercise a scenario that has led to segfaults in the past.
+ """
+ m = unittest_pb2.TestAllTypes()
+ m.repeated_nested_message.sort()
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/service_reflection_test.py b/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/service_reflection_test.py
new file mode 100755
index 00000000..e04f8252
--- /dev/null
+++ b/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/service_reflection_test.py
@@ -0,0 +1,136 @@
+#! /usr/bin/python
+#
+# Protocol Buffers - Google's data interchange format
+# Copyright 2008 Google Inc. All rights reserved.
+# http://code.google.com/p/protobuf/
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following disclaimer
+# in the documentation and/or other materials provided with the
+# distribution.
+# * Neither the name of Google Inc. nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+"""Tests for google.protobuf.internal.service_reflection."""
+
+__author__ = 'petar@google.com (Petar Petrov)'
+
+import unittest
+from google.protobuf import unittest_pb2
+from google.protobuf import service_reflection
+from google.protobuf import service
+
+
+class FooUnitTest(unittest.TestCase):
+
+ def testService(self):
+ class MockRpcChannel(service.RpcChannel):
+ def CallMethod(self, method, controller, request, response, callback):
+ self.method = method
+ self.controller = controller
+ self.request = request
+ callback(response)
+
+ class MockRpcController(service.RpcController):
+ def SetFailed(self, msg):
+ self.failure_message = msg
+
+ self.callback_response = None
+
+ class MyService(unittest_pb2.TestService):
+ pass
+
+ self.callback_response = None
+
+ def MyCallback(response):
+ self.callback_response = response
+
+ rpc_controller = MockRpcController()
+ channel = MockRpcChannel()
+ srvc = MyService()
+ srvc.Foo(rpc_controller, unittest_pb2.FooRequest(), MyCallback)
+ self.assertEqual('Method Foo not implemented.',
+ rpc_controller.failure_message)
+ self.assertEqual(None, self.callback_response)
+
+ rpc_controller.failure_message = None
+
+ service_descriptor = unittest_pb2.TestService.GetDescriptor()
+ srvc.CallMethod(service_descriptor.methods[1], rpc_controller,
+ unittest_pb2.BarRequest(), MyCallback)
+ self.assertEqual('Method Bar not implemented.',
+ rpc_controller.failure_message)
+ self.assertEqual(None, self.callback_response)
+
+ class MyServiceImpl(unittest_pb2.TestService):
+ def Foo(self, rpc_controller, request, done):
+ self.foo_called = True
+ def Bar(self, rpc_controller, request, done):
+ self.bar_called = True
+
+ srvc = MyServiceImpl()
+ rpc_controller.failure_message = None
+ srvc.Foo(rpc_controller, unittest_pb2.FooRequest(), MyCallback)
+ self.assertEqual(None, rpc_controller.failure_message)
+ self.assertEqual(True, srvc.foo_called)
+
+ rpc_controller.failure_message = None
+ srvc.CallMethod(service_descriptor.methods[1], rpc_controller,
+ unittest_pb2.BarRequest(), MyCallback)
+ self.assertEqual(None, rpc_controller.failure_message)
+ self.assertEqual(True, srvc.bar_called)
+
+ def testServiceStub(self):
+ class MockRpcChannel(service.RpcChannel):
+ def CallMethod(self, method, controller, request,
+ response_class, callback):
+ self.method = method
+ self.controller = controller
+ self.request = request
+ callback(response_class())
+
+ self.callback_response = None
+
+ def MyCallback(response):
+ self.callback_response = response
+
+ channel = MockRpcChannel()
+ stub = unittest_pb2.TestService_Stub(channel)
+ rpc_controller = 'controller'
+ request = 'request'
+
+ # GetDescriptor now static, still works as instance method for compatability
+ self.assertEqual(unittest_pb2.TestService_Stub.GetDescriptor(),
+ stub.GetDescriptor())
+
+ # Invoke method.
+ stub.Foo(rpc_controller, request, MyCallback)
+
+ self.assertTrue(isinstance(self.callback_response,
+ unittest_pb2.FooResponse))
+ self.assertEqual(request, channel.request)
+ self.assertEqual(rpc_controller, channel.controller)
+ self.assertEqual(stub.GetDescriptor().methods[0], channel.method)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/test_util.py b/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/test_util.py
new file mode 100755
index 00000000..e2c9db03
--- /dev/null
+++ b/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/test_util.py
@@ -0,0 +1,651 @@
+# Protocol Buffers - Google's data interchange format
+# Copyright 2008 Google Inc. All rights reserved.
+# http://code.google.com/p/protobuf/
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following disclaimer
+# in the documentation and/or other materials provided with the
+# distribution.
+# * Neither the name of Google Inc. nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+"""Utilities for Python proto2 tests.
+
+This is intentionally modeled on C++ code in
+//google/protobuf/test_util.*.
+"""
+
+__author__ = 'robinson@google.com (Will Robinson)'
+
+import os.path
+
+from google.protobuf import unittest_import_pb2
+from google.protobuf import unittest_pb2
+
+
+def SetAllNonLazyFields(message):
+ """Sets every non-lazy field in the message to a unique value.
+
+ Args:
+ message: A unittest_pb2.TestAllTypes instance.
+ """
+
+ #
+ # Optional fields.
+ #
+
+ message.optional_int32 = 101
+ message.optional_int64 = 102
+ message.optional_uint32 = 103
+ message.optional_uint64 = 104
+ message.optional_sint32 = 105
+ message.optional_sint64 = 106
+ message.optional_fixed32 = 107
+ message.optional_fixed64 = 108
+ message.optional_sfixed32 = 109
+ message.optional_sfixed64 = 110
+ message.optional_float = 111
+ message.optional_double = 112
+ message.optional_bool = True
+ # TODO(robinson): Firmly spec out and test how
+ # protos interact with unicode. One specific example:
+ # what happens if we change the literal below to
+ # u'115'? What *should* happen? Still some discussion
+ # to finish with Kenton about bytes vs. strings
+ # and forcing everything to be utf8. :-/
+ message.optional_string = '115'
+ message.optional_bytes = '116'
+
+ message.optionalgroup.a = 117
+ message.optional_nested_message.bb = 118
+ message.optional_foreign_message.c = 119
+ message.optional_import_message.d = 120
+ message.optional_public_import_message.e = 126
+
+ message.optional_nested_enum = unittest_pb2.TestAllTypes.BAZ
+ message.optional_foreign_enum = unittest_pb2.FOREIGN_BAZ
+ message.optional_import_enum = unittest_import_pb2.IMPORT_BAZ
+
+ message.optional_string_piece = '124'
+ message.optional_cord = '125'
+
+ #
+ # Repeated fields.
+ #
+
+ message.repeated_int32.append(201)
+ message.repeated_int64.append(202)
+ message.repeated_uint32.append(203)
+ message.repeated_uint64.append(204)
+ message.repeated_sint32.append(205)
+ message.repeated_sint64.append(206)
+ message.repeated_fixed32.append(207)
+ message.repeated_fixed64.append(208)
+ message.repeated_sfixed32.append(209)
+ message.repeated_sfixed64.append(210)
+ message.repeated_float.append(211)
+ message.repeated_double.append(212)
+ message.repeated_bool.append(True)
+ message.repeated_string.append('215')
+ message.repeated_bytes.append('216')
+
+ message.repeatedgroup.add().a = 217
+ message.repeated_nested_message.add().bb = 218
+ message.repeated_foreign_message.add().c = 219
+ message.repeated_import_message.add().d = 220
+ message.repeated_lazy_message.add().bb = 227
+
+ message.repeated_nested_enum.append(unittest_pb2.TestAllTypes.BAR)
+ message.repeated_foreign_enum.append(unittest_pb2.FOREIGN_BAR)
+ message.repeated_import_enum.append(unittest_import_pb2.IMPORT_BAR)
+
+ message.repeated_string_piece.append('224')
+ message.repeated_cord.append('225')
+
+ # Add a second one of each field.
+ message.repeated_int32.append(301)
+ message.repeated_int64.append(302)
+ message.repeated_uint32.append(303)
+ message.repeated_uint64.append(304)
+ message.repeated_sint32.append(305)
+ message.repeated_sint64.append(306)
+ message.repeated_fixed32.append(307)
+ message.repeated_fixed64.append(308)
+ message.repeated_sfixed32.append(309)
+ message.repeated_sfixed64.append(310)
+ message.repeated_float.append(311)
+ message.repeated_double.append(312)
+ message.repeated_bool.append(False)
+ message.repeated_string.append('315')
+ message.repeated_bytes.append('316')
+
+ message.repeatedgroup.add().a = 317
+ message.repeated_nested_message.add().bb = 318
+ message.repeated_foreign_message.add().c = 319
+ message.repeated_import_message.add().d = 320
+ message.repeated_lazy_message.add().bb = 327
+
+ message.repeated_nested_enum.append(unittest_pb2.TestAllTypes.BAZ)
+ message.repeated_foreign_enum.append(unittest_pb2.FOREIGN_BAZ)
+ message.repeated_import_enum.append(unittest_import_pb2.IMPORT_BAZ)
+
+ message.repeated_string_piece.append('324')
+ message.repeated_cord.append('325')
+
+ #
+ # Fields that have defaults.
+ #
+
+ message.default_int32 = 401
+ message.default_int64 = 402
+ message.default_uint32 = 403
+ message.default_uint64 = 404
+ message.default_sint32 = 405
+ message.default_sint64 = 406
+ message.default_fixed32 = 407
+ message.default_fixed64 = 408
+ message.default_sfixed32 = 409
+ message.default_sfixed64 = 410
+ message.default_float = 411
+ message.default_double = 412
+ message.default_bool = False
+ message.default_string = '415'
+ message.default_bytes = '416'
+
+ message.default_nested_enum = unittest_pb2.TestAllTypes.FOO
+ message.default_foreign_enum = unittest_pb2.FOREIGN_FOO
+ message.default_import_enum = unittest_import_pb2.IMPORT_FOO
+
+ message.default_string_piece = '424'
+ message.default_cord = '425'
+
+
+def SetAllFields(message):
+ SetAllNonLazyFields(message)
+ message.optional_lazy_message.bb = 127
+
+
+def SetAllExtensions(message):
+ """Sets every extension in the message to a unique value.
+
+ Args:
+ message: A unittest_pb2.TestAllExtensions instance.
+ """
+
+ extensions = message.Extensions
+ pb2 = unittest_pb2
+ import_pb2 = unittest_import_pb2
+
+ #
+ # Optional fields.
+ #
+
+ extensions[pb2.optional_int32_extension] = 101
+ extensions[pb2.optional_int64_extension] = 102
+ extensions[pb2.optional_uint32_extension] = 103
+ extensions[pb2.optional_uint64_extension] = 104
+ extensions[pb2.optional_sint32_extension] = 105
+ extensions[pb2.optional_sint64_extension] = 106
+ extensions[pb2.optional_fixed32_extension] = 107
+ extensions[pb2.optional_fixed64_extension] = 108
+ extensions[pb2.optional_sfixed32_extension] = 109
+ extensions[pb2.optional_sfixed64_extension] = 110
+ extensions[pb2.optional_float_extension] = 111
+ extensions[pb2.optional_double_extension] = 112
+ extensions[pb2.optional_bool_extension] = True
+ extensions[pb2.optional_string_extension] = '115'
+ extensions[pb2.optional_bytes_extension] = '116'
+
+ extensions[pb2.optionalgroup_extension].a = 117
+ extensions[pb2.optional_nested_message_extension].bb = 118
+ extensions[pb2.optional_foreign_message_extension].c = 119
+ extensions[pb2.optional_import_message_extension].d = 120
+ extensions[pb2.optional_public_import_message_extension].e = 126
+ extensions[pb2.optional_lazy_message_extension].bb = 127
+
+ extensions[pb2.optional_nested_enum_extension] = pb2.TestAllTypes.BAZ
+ extensions[pb2.optional_nested_enum_extension] = pb2.TestAllTypes.BAZ
+ extensions[pb2.optional_foreign_enum_extension] = pb2.FOREIGN_BAZ
+ extensions[pb2.optional_import_enum_extension] = import_pb2.IMPORT_BAZ
+
+ extensions[pb2.optional_string_piece_extension] = '124'
+ extensions[pb2.optional_cord_extension] = '125'
+
+ #
+ # Repeated fields.
+ #
+
+ extensions[pb2.repeated_int32_extension].append(201)
+ extensions[pb2.repeated_int64_extension].append(202)
+ extensions[pb2.repeated_uint32_extension].append(203)
+ extensions[pb2.repeated_uint64_extension].append(204)
+ extensions[pb2.repeated_sint32_extension].append(205)
+ extensions[pb2.repeated_sint64_extension].append(206)
+ extensions[pb2.repeated_fixed32_extension].append(207)
+ extensions[pb2.repeated_fixed64_extension].append(208)
+ extensions[pb2.repeated_sfixed32_extension].append(209)
+ extensions[pb2.repeated_sfixed64_extension].append(210)
+ extensions[pb2.repeated_float_extension].append(211)
+ extensions[pb2.repeated_double_extension].append(212)
+ extensions[pb2.repeated_bool_extension].append(True)
+ extensions[pb2.repeated_string_extension].append('215')
+ extensions[pb2.repeated_bytes_extension].append('216')
+
+ extensions[pb2.repeatedgroup_extension].add().a = 217
+ extensions[pb2.repeated_nested_message_extension].add().bb = 218
+ extensions[pb2.repeated_foreign_message_extension].add().c = 219
+ extensions[pb2.repeated_import_message_extension].add().d = 220
+ extensions[pb2.repeated_lazy_message_extension].add().bb = 227
+
+ extensions[pb2.repeated_nested_enum_extension].append(pb2.TestAllTypes.BAR)
+ extensions[pb2.repeated_foreign_enum_extension].append(pb2.FOREIGN_BAR)
+ extensions[pb2.repeated_import_enum_extension].append(import_pb2.IMPORT_BAR)
+
+ extensions[pb2.repeated_string_piece_extension].append('224')
+ extensions[pb2.repeated_cord_extension].append('225')
+
+ # Append a second one of each field.
+ extensions[pb2.repeated_int32_extension].append(301)
+ extensions[pb2.repeated_int64_extension].append(302)
+ extensions[pb2.repeated_uint32_extension].append(303)
+ extensions[pb2.repeated_uint64_extension].append(304)
+ extensions[pb2.repeated_sint32_extension].append(305)
+ extensions[pb2.repeated_sint64_extension].append(306)
+ extensions[pb2.repeated_fixed32_extension].append(307)
+ extensions[pb2.repeated_fixed64_extension].append(308)
+ extensions[pb2.repeated_sfixed32_extension].append(309)
+ extensions[pb2.repeated_sfixed64_extension].append(310)
+ extensions[pb2.repeated_float_extension].append(311)
+ extensions[pb2.repeated_double_extension].append(312)
+ extensions[pb2.repeated_bool_extension].append(False)
+ extensions[pb2.repeated_string_extension].append('315')
+ extensions[pb2.repeated_bytes_extension].append('316')
+
+ extensions[pb2.repeatedgroup_extension].add().a = 317
+ extensions[pb2.repeated_nested_message_extension].add().bb = 318
+ extensions[pb2.repeated_foreign_message_extension].add().c = 319
+ extensions[pb2.repeated_import_message_extension].add().d = 320
+ extensions[pb2.repeated_lazy_message_extension].add().bb = 327
+
+ extensions[pb2.repeated_nested_enum_extension].append(pb2.TestAllTypes.BAZ)
+ extensions[pb2.repeated_foreign_enum_extension].append(pb2.FOREIGN_BAZ)
+ extensions[pb2.repeated_import_enum_extension].append(import_pb2.IMPORT_BAZ)
+
+ extensions[pb2.repeated_string_piece_extension].append('324')
+ extensions[pb2.repeated_cord_extension].append('325')
+
+ #
+ # Fields with defaults.
+ #
+
+ extensions[pb2.default_int32_extension] = 401
+ extensions[pb2.default_int64_extension] = 402
+ extensions[pb2.default_uint32_extension] = 403
+ extensions[pb2.default_uint64_extension] = 404
+ extensions[pb2.default_sint32_extension] = 405
+ extensions[pb2.default_sint64_extension] = 406
+ extensions[pb2.default_fixed32_extension] = 407
+ extensions[pb2.default_fixed64_extension] = 408
+ extensions[pb2.default_sfixed32_extension] = 409
+ extensions[pb2.default_sfixed64_extension] = 410
+ extensions[pb2.default_float_extension] = 411
+ extensions[pb2.default_double_extension] = 412
+ extensions[pb2.default_bool_extension] = False
+ extensions[pb2.default_string_extension] = '415'
+ extensions[pb2.default_bytes_extension] = '416'
+
+ extensions[pb2.default_nested_enum_extension] = pb2.TestAllTypes.FOO
+ extensions[pb2.default_foreign_enum_extension] = pb2.FOREIGN_FOO
+ extensions[pb2.default_import_enum_extension] = import_pb2.IMPORT_FOO
+
+ extensions[pb2.default_string_piece_extension] = '424'
+ extensions[pb2.default_cord_extension] = '425'
+
+
+def SetAllFieldsAndExtensions(message):
+ """Sets every field and extension in the message to a unique value.
+
+ Args:
+ message: A unittest_pb2.TestAllExtensions message.
+ """
+ message.my_int = 1
+ message.my_string = 'foo'
+ message.my_float = 1.0
+ message.Extensions[unittest_pb2.my_extension_int] = 23
+ message.Extensions[unittest_pb2.my_extension_string] = 'bar'
+
+
+def ExpectAllFieldsAndExtensionsInOrder(serialized):
+ """Ensures that serialized is the serialization we expect for a message
+ filled with SetAllFieldsAndExtensions(). (Specifically, ensures that the
+ serialization is in canonical, tag-number order).
+ """
+ my_extension_int = unittest_pb2.my_extension_int
+ my_extension_string = unittest_pb2.my_extension_string
+ expected_strings = []
+ message = unittest_pb2.TestFieldOrderings()
+ message.my_int = 1 # Field 1.
+ expected_strings.append(message.SerializeToString())
+ message.Clear()
+ message.Extensions[my_extension_int] = 23 # Field 5.
+ expected_strings.append(message.SerializeToString())
+ message.Clear()
+ message.my_string = 'foo' # Field 11.
+ expected_strings.append(message.SerializeToString())
+ message.Clear()
+ message.Extensions[my_extension_string] = 'bar' # Field 50.
+ expected_strings.append(message.SerializeToString())
+ message.Clear()
+ message.my_float = 1.0
+ expected_strings.append(message.SerializeToString())
+ message.Clear()
+ expected = ''.join(expected_strings)
+
+ if expected != serialized:
+ raise ValueError('Expected %r, found %r' % (expected, serialized))
+
+
+def ExpectAllFieldsSet(test_case, message):
+ """Check all fields for correct values have after Set*Fields() is called."""
+ test_case.assertTrue(message.HasField('optional_int32'))
+ test_case.assertTrue(message.HasField('optional_int64'))
+ test_case.assertTrue(message.HasField('optional_uint32'))
+ test_case.assertTrue(message.HasField('optional_uint64'))
+ test_case.assertTrue(message.HasField('optional_sint32'))
+ test_case.assertTrue(message.HasField('optional_sint64'))
+ test_case.assertTrue(message.HasField('optional_fixed32'))
+ test_case.assertTrue(message.HasField('optional_fixed64'))
+ test_case.assertTrue(message.HasField('optional_sfixed32'))
+ test_case.assertTrue(message.HasField('optional_sfixed64'))
+ test_case.assertTrue(message.HasField('optional_float'))
+ test_case.assertTrue(message.HasField('optional_double'))
+ test_case.assertTrue(message.HasField('optional_bool'))
+ test_case.assertTrue(message.HasField('optional_string'))
+ test_case.assertTrue(message.HasField('optional_bytes'))
+
+ test_case.assertTrue(message.HasField('optionalgroup'))
+ test_case.assertTrue(message.HasField('optional_nested_message'))
+ test_case.assertTrue(message.HasField('optional_foreign_message'))
+ test_case.assertTrue(message.HasField('optional_import_message'))
+
+ test_case.assertTrue(message.optionalgroup.HasField('a'))
+ test_case.assertTrue(message.optional_nested_message.HasField('bb'))
+ test_case.assertTrue(message.optional_foreign_message.HasField('c'))
+ test_case.assertTrue(message.optional_import_message.HasField('d'))
+
+ test_case.assertTrue(message.HasField('optional_nested_enum'))
+ test_case.assertTrue(message.HasField('optional_foreign_enum'))
+ test_case.assertTrue(message.HasField('optional_import_enum'))
+
+ test_case.assertTrue(message.HasField('optional_string_piece'))
+ test_case.assertTrue(message.HasField('optional_cord'))
+
+ test_case.assertEqual(101, message.optional_int32)
+ test_case.assertEqual(102, message.optional_int64)
+ test_case.assertEqual(103, message.optional_uint32)
+ test_case.assertEqual(104, message.optional_uint64)
+ test_case.assertEqual(105, message.optional_sint32)
+ test_case.assertEqual(106, message.optional_sint64)
+ test_case.assertEqual(107, message.optional_fixed32)
+ test_case.assertEqual(108, message.optional_fixed64)
+ test_case.assertEqual(109, message.optional_sfixed32)
+ test_case.assertEqual(110, message.optional_sfixed64)
+ test_case.assertEqual(111, message.optional_float)
+ test_case.assertEqual(112, message.optional_double)
+ test_case.assertEqual(True, message.optional_bool)
+ test_case.assertEqual('115', message.optional_string)
+ test_case.assertEqual('116', message.optional_bytes)
+
+ test_case.assertEqual(117, message.optionalgroup.a)
+ test_case.assertEqual(118, message.optional_nested_message.bb)
+ test_case.assertEqual(119, message.optional_foreign_message.c)
+ test_case.assertEqual(120, message.optional_import_message.d)
+ test_case.assertEqual(126, message.optional_public_import_message.e)
+ test_case.assertEqual(127, message.optional_lazy_message.bb)
+
+ test_case.assertEqual(unittest_pb2.TestAllTypes.BAZ,
+ message.optional_nested_enum)
+ test_case.assertEqual(unittest_pb2.FOREIGN_BAZ,
+ message.optional_foreign_enum)
+ test_case.assertEqual(unittest_import_pb2.IMPORT_BAZ,
+ message.optional_import_enum)
+
+ # -----------------------------------------------------------------
+
+ test_case.assertEqual(2, len(message.repeated_int32))
+ test_case.assertEqual(2, len(message.repeated_int64))
+ test_case.assertEqual(2, len(message.repeated_uint32))
+ test_case.assertEqual(2, len(message.repeated_uint64))
+ test_case.assertEqual(2, len(message.repeated_sint32))
+ test_case.assertEqual(2, len(message.repeated_sint64))
+ test_case.assertEqual(2, len(message.repeated_fixed32))
+ test_case.assertEqual(2, len(message.repeated_fixed64))
+ test_case.assertEqual(2, len(message.repeated_sfixed32))
+ test_case.assertEqual(2, len(message.repeated_sfixed64))
+ test_case.assertEqual(2, len(message.repeated_float))
+ test_case.assertEqual(2, len(message.repeated_double))
+ test_case.assertEqual(2, len(message.repeated_bool))
+ test_case.assertEqual(2, len(message.repeated_string))
+ test_case.assertEqual(2, len(message.repeated_bytes))
+
+ test_case.assertEqual(2, len(message.repeatedgroup))
+ test_case.assertEqual(2, len(message.repeated_nested_message))
+ test_case.assertEqual(2, len(message.repeated_foreign_message))
+ test_case.assertEqual(2, len(message.repeated_import_message))
+ test_case.assertEqual(2, len(message.repeated_nested_enum))
+ test_case.assertEqual(2, len(message.repeated_foreign_enum))
+ test_case.assertEqual(2, len(message.repeated_import_enum))
+
+ test_case.assertEqual(2, len(message.repeated_string_piece))
+ test_case.assertEqual(2, len(message.repeated_cord))
+
+ test_case.assertEqual(201, message.repeated_int32[0])
+ test_case.assertEqual(202, message.repeated_int64[0])
+ test_case.assertEqual(203, message.repeated_uint32[0])
+ test_case.assertEqual(204, message.repeated_uint64[0])
+ test_case.assertEqual(205, message.repeated_sint32[0])
+ test_case.assertEqual(206, message.repeated_sint64[0])
+ test_case.assertEqual(207, message.repeated_fixed32[0])
+ test_case.assertEqual(208, message.repeated_fixed64[0])
+ test_case.assertEqual(209, message.repeated_sfixed32[0])
+ test_case.assertEqual(210, message.repeated_sfixed64[0])
+ test_case.assertEqual(211, message.repeated_float[0])
+ test_case.assertEqual(212, message.repeated_double[0])
+ test_case.assertEqual(True, message.repeated_bool[0])
+ test_case.assertEqual('215', message.repeated_string[0])
+ test_case.assertEqual('216', message.repeated_bytes[0])
+
+ test_case.assertEqual(217, message.repeatedgroup[0].a)
+ test_case.assertEqual(218, message.repeated_nested_message[0].bb)
+ test_case.assertEqual(219, message.repeated_foreign_message[0].c)
+ test_case.assertEqual(220, message.repeated_import_message[0].d)
+ test_case.assertEqual(227, message.repeated_lazy_message[0].bb)
+
+ test_case.assertEqual(unittest_pb2.TestAllTypes.BAR,
+ message.repeated_nested_enum[0])
+ test_case.assertEqual(unittest_pb2.FOREIGN_BAR,
+ message.repeated_foreign_enum[0])
+ test_case.assertEqual(unittest_import_pb2.IMPORT_BAR,
+ message.repeated_import_enum[0])
+
+ test_case.assertEqual(301, message.repeated_int32[1])
+ test_case.assertEqual(302, message.repeated_int64[1])
+ test_case.assertEqual(303, message.repeated_uint32[1])
+ test_case.assertEqual(304, message.repeated_uint64[1])
+ test_case.assertEqual(305, message.repeated_sint32[1])
+ test_case.assertEqual(306, message.repeated_sint64[1])
+ test_case.assertEqual(307, message.repeated_fixed32[1])
+ test_case.assertEqual(308, message.repeated_fixed64[1])
+ test_case.assertEqual(309, message.repeated_sfixed32[1])
+ test_case.assertEqual(310, message.repeated_sfixed64[1])
+ test_case.assertEqual(311, message.repeated_float[1])
+ test_case.assertEqual(312, message.repeated_double[1])
+ test_case.assertEqual(False, message.repeated_bool[1])
+ test_case.assertEqual('315', message.repeated_string[1])
+ test_case.assertEqual('316', message.repeated_bytes[1])
+
+ test_case.assertEqual(317, message.repeatedgroup[1].a)
+ test_case.assertEqual(318, message.repeated_nested_message[1].bb)
+ test_case.assertEqual(319, message.repeated_foreign_message[1].c)
+ test_case.assertEqual(320, message.repeated_import_message[1].d)
+ test_case.assertEqual(327, message.repeated_lazy_message[1].bb)
+
+ test_case.assertEqual(unittest_pb2.TestAllTypes.BAZ,
+ message.repeated_nested_enum[1])
+ test_case.assertEqual(unittest_pb2.FOREIGN_BAZ,
+ message.repeated_foreign_enum[1])
+ test_case.assertEqual(unittest_import_pb2.IMPORT_BAZ,
+ message.repeated_import_enum[1])
+
+ # -----------------------------------------------------------------
+
+ test_case.assertTrue(message.HasField('default_int32'))
+ test_case.assertTrue(message.HasField('default_int64'))
+ test_case.assertTrue(message.HasField('default_uint32'))
+ test_case.assertTrue(message.HasField('default_uint64'))
+ test_case.assertTrue(message.HasField('default_sint32'))
+ test_case.assertTrue(message.HasField('default_sint64'))
+ test_case.assertTrue(message.HasField('default_fixed32'))
+ test_case.assertTrue(message.HasField('default_fixed64'))
+ test_case.assertTrue(message.HasField('default_sfixed32'))
+ test_case.assertTrue(message.HasField('default_sfixed64'))
+ test_case.assertTrue(message.HasField('default_float'))
+ test_case.assertTrue(message.HasField('default_double'))
+ test_case.assertTrue(message.HasField('default_bool'))
+ test_case.assertTrue(message.HasField('default_string'))
+ test_case.assertTrue(message.HasField('default_bytes'))
+
+ test_case.assertTrue(message.HasField('default_nested_enum'))
+ test_case.assertTrue(message.HasField('default_foreign_enum'))
+ test_case.assertTrue(message.HasField('default_import_enum'))
+
+ test_case.assertEqual(401, message.default_int32)
+ test_case.assertEqual(402, message.default_int64)
+ test_case.assertEqual(403, message.default_uint32)
+ test_case.assertEqual(404, message.default_uint64)
+ test_case.assertEqual(405, message.default_sint32)
+ test_case.assertEqual(406, message.default_sint64)
+ test_case.assertEqual(407, message.default_fixed32)
+ test_case.assertEqual(408, message.default_fixed64)
+ test_case.assertEqual(409, message.default_sfixed32)
+ test_case.assertEqual(410, message.default_sfixed64)
+ test_case.assertEqual(411, message.default_float)
+ test_case.assertEqual(412, message.default_double)
+ test_case.assertEqual(False, message.default_bool)
+ test_case.assertEqual('415', message.default_string)
+ test_case.assertEqual('416', message.default_bytes)
+
+ test_case.assertEqual(unittest_pb2.TestAllTypes.FOO,
+ message.default_nested_enum)
+ test_case.assertEqual(unittest_pb2.FOREIGN_FOO,
+ message.default_foreign_enum)
+ test_case.assertEqual(unittest_import_pb2.IMPORT_FOO,
+ message.default_import_enum)
+
+def GoldenFile(filename):
+ """Finds the given golden file and returns a file object representing it."""
+
+ # Search up the directory tree looking for the C++ protobuf source code.
+ path = '.'
+ while os.path.exists(path):
+ if os.path.exists(os.path.join(path, 'tests/google/protobuf/internal')):
+ # Found it. Load the golden file from the testdata directory.
+ full_path = os.path.join(path, 'tests/google/protobuf/internal', filename)
+ return open(full_path, 'rb')
+ path = os.path.join(path, '..')
+
+ raise RuntimeError(
+ 'Could not find golden files. This test must be run from within the '
+ 'protobuf source package so that it can read test data files from the '
+ 'C++ source tree.')
+
+
+def SetAllPackedFields(message):
+ """Sets every field in the message to a unique value.
+
+ Args:
+ message: A unittest_pb2.TestPackedTypes instance.
+ """
+ message.packed_int32.extend([601, 701])
+ message.packed_int64.extend([602, 702])
+ message.packed_uint32.extend([603, 703])
+ message.packed_uint64.extend([604, 704])
+ message.packed_sint32.extend([605, 705])
+ message.packed_sint64.extend([606, 706])
+ message.packed_fixed32.extend([607, 707])
+ message.packed_fixed64.extend([608, 708])
+ message.packed_sfixed32.extend([609, 709])
+ message.packed_sfixed64.extend([610, 710])
+ message.packed_float.extend([611.0, 711.0])
+ message.packed_double.extend([612.0, 712.0])
+ message.packed_bool.extend([True, False])
+ message.packed_enum.extend([unittest_pb2.FOREIGN_BAR,
+ unittest_pb2.FOREIGN_BAZ])
+
+
+def SetAllPackedExtensions(message):
+ """Sets every extension in the message to a unique value.
+
+ Args:
+ message: A unittest_pb2.TestPackedExtensions instance.
+ """
+ extensions = message.Extensions
+ pb2 = unittest_pb2
+
+ extensions[pb2.packed_int32_extension].extend([601, 701])
+ extensions[pb2.packed_int64_extension].extend([602, 702])
+ extensions[pb2.packed_uint32_extension].extend([603, 703])
+ extensions[pb2.packed_uint64_extension].extend([604, 704])
+ extensions[pb2.packed_sint32_extension].extend([605, 705])
+ extensions[pb2.packed_sint64_extension].extend([606, 706])
+ extensions[pb2.packed_fixed32_extension].extend([607, 707])
+ extensions[pb2.packed_fixed64_extension].extend([608, 708])
+ extensions[pb2.packed_sfixed32_extension].extend([609, 709])
+ extensions[pb2.packed_sfixed64_extension].extend([610, 710])
+ extensions[pb2.packed_float_extension].extend([611.0, 711.0])
+ extensions[pb2.packed_double_extension].extend([612.0, 712.0])
+ extensions[pb2.packed_bool_extension].extend([True, False])
+ extensions[pb2.packed_enum_extension].extend([unittest_pb2.FOREIGN_BAR,
+ unittest_pb2.FOREIGN_BAZ])
+
+
+def SetAllUnpackedFields(message):
+ """Sets every field in the message to a unique value.
+
+ Args:
+ message: A unittest_pb2.TestUnpackedTypes instance.
+ """
+ message.unpacked_int32.extend([601, 701])
+ message.unpacked_int64.extend([602, 702])
+ message.unpacked_uint32.extend([603, 703])
+ message.unpacked_uint64.extend([604, 704])
+ message.unpacked_sint32.extend([605, 705])
+ message.unpacked_sint64.extend([606, 706])
+ message.unpacked_fixed32.extend([607, 707])
+ message.unpacked_fixed64.extend([608, 708])
+ message.unpacked_sfixed32.extend([609, 709])
+ message.unpacked_sfixed64.extend([610, 710])
+ message.unpacked_float.extend([611.0, 711.0])
+ message.unpacked_double.extend([612.0, 712.0])
+ message.unpacked_bool.extend([True, False])
+ message.unpacked_enum.extend([unittest_pb2.FOREIGN_BAR,
+ unittest_pb2.FOREIGN_BAZ])
diff --git a/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/text_format_test.py b/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/text_format_test.py
new file mode 100755
index 00000000..8267cd2c
--- /dev/null
+++ b/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/text_format_test.py
@@ -0,0 +1,619 @@
+#! /usr/bin/python
+#
+# Protocol Buffers - Google's data interchange format
+# Copyright 2008 Google Inc. All rights reserved.
+# http://code.google.com/p/protobuf/
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following disclaimer
+# in the documentation and/or other materials provided with the
+# distribution.
+# * Neither the name of Google Inc. nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+"""Test for google.protobuf.text_format."""
+
+__author__ = 'kenton@google.com (Kenton Varda)'
+
+import difflib
+import re
+
+import unittest
+from google.protobuf import text_format
+from google.protobuf.internal import test_util
+from google.protobuf import unittest_pb2
+from google.protobuf import unittest_mset_pb2
+
+
+class TextFormatTest(unittest.TestCase):
+ def ReadGolden(self, golden_filename):
+ f = test_util.GoldenFile(golden_filename)
+ golden_lines = f.readlines()
+ f.close()
+ return golden_lines
+
+ def CompareToGoldenFile(self, text, golden_filename):
+ golden_lines = self.ReadGolden(golden_filename)
+ self.CompareToGoldenLines(text, golden_lines)
+
+ def CompareToGoldenText(self, text, golden_text):
+ self.CompareToGoldenLines(text, golden_text.splitlines(1))
+
+ def CompareToGoldenLines(self, text, golden_lines):
+ actual_lines = text.splitlines(1)
+ self.assertEqual(golden_lines, actual_lines,
+ "Text doesn't match golden. Diff:\n" +
+ ''.join(difflib.ndiff(golden_lines, actual_lines)))
+
+ def testPrintAllFields(self):
+ message = unittest_pb2.TestAllTypes()
+ test_util.SetAllFields(message)
+ self.CompareToGoldenFile(
+ self.RemoveRedundantZeros(text_format.MessageToString(message)),
+ 'text_format_unittest_data.txt')
+
+ def testPrintAllExtensions(self):
+ message = unittest_pb2.TestAllExtensions()
+ test_util.SetAllExtensions(message)
+ self.CompareToGoldenFile(
+ self.RemoveRedundantZeros(text_format.MessageToString(message)),
+ 'text_format_unittest_extensions_data.txt')
+
+ def testPrintMessageSet(self):
+ message = unittest_mset_pb2.TestMessageSetContainer()
+ ext1 = unittest_mset_pb2.TestMessageSetExtension1.message_set_extension
+ ext2 = unittest_mset_pb2.TestMessageSetExtension2.message_set_extension
+ message.message_set.Extensions[ext1].i = 23
+ message.message_set.Extensions[ext2].str = 'foo'
+ self.CompareToGoldenText(text_format.MessageToString(message),
+ 'message_set {\n'
+ ' [protobuf_unittest.TestMessageSetExtension1] {\n'
+ ' i: 23\n'
+ ' }\n'
+ ' [protobuf_unittest.TestMessageSetExtension2] {\n'
+ ' str: \"foo\"\n'
+ ' }\n'
+ '}\n')
+
+ """
+ def testPrintBadEnumValue(self):
+ message = unittest_pb2.TestAllTypes()
+ message.optional_nested_enum = 100
+ message.optional_foreign_enum = 101
+ message.optional_import_enum = 102
+ self.CompareToGoldenText(
+ text_format.MessageToString(message),
+ 'optional_nested_enum: 100\n'
+ 'optional_foreign_enum: 101\n'
+ 'optional_import_enum: 102\n')
+
+ def testPrintBadEnumValueExtensions(self):
+ message = unittest_pb2.TestAllExtensions()
+ message.Extensions[unittest_pb2.optional_nested_enum_extension] = 100
+ message.Extensions[unittest_pb2.optional_foreign_enum_extension] = 101
+ message.Extensions[unittest_pb2.optional_import_enum_extension] = 102
+ self.CompareToGoldenText(
+ text_format.MessageToString(message),
+ '[protobuf_unittest.optional_nested_enum_extension]: 100\n'
+ '[protobuf_unittest.optional_foreign_enum_extension]: 101\n'
+ '[protobuf_unittest.optional_import_enum_extension]: 102\n')
+ """
+
+ def testPrintExotic(self):
+ message = unittest_pb2.TestAllTypes()
+ message.repeated_int64.append(-9223372036854775808)
+ message.repeated_uint64.append(18446744073709551615)
+ message.repeated_double.append(123.456)
+ message.repeated_double.append(1.23e22)
+ message.repeated_double.append(1.23e-18)
+ message.repeated_string.append('\000\001\a\b\f\n\r\t\v\\\'"')
+ message.repeated_string.append(u'\u00fc\ua71f')
+ self.CompareToGoldenText(
+ self.RemoveRedundantZeros(text_format.MessageToString(message)),
+ 'repeated_int64: -9223372036854775808\n'
+ 'repeated_uint64: 18446744073709551615\n'
+ 'repeated_double: 123.456\n'
+ 'repeated_double: 1.23e+22\n'
+ 'repeated_double: 1.23e-18\n'
+ 'repeated_string: '
+ '"\\000\\001\\007\\010\\014\\n\\r\\t\\013\\\\\\\'\\""\n'
+ 'repeated_string: "\\303\\274\\352\\234\\237"\n')
+
+ def testPrintNestedMessageAsOneLine(self):
+ message = unittest_pb2.TestAllTypes()
+ msg = message.repeated_nested_message.add()
+ msg.bb = 42;
+ self.CompareToGoldenText(
+ text_format.MessageToString(message, as_one_line=True),
+ 'repeated_nested_message { bb: 42 }')
+
+ def testPrintRepeatedFieldsAsOneLine(self):
+ message = unittest_pb2.TestAllTypes()
+ message.repeated_int32.append(1)
+ message.repeated_int32.append(1)
+ message.repeated_int32.append(3)
+ message.repeated_string.append("Google")
+ message.repeated_string.append("Zurich")
+ self.CompareToGoldenText(
+ text_format.MessageToString(message, as_one_line=True),
+ 'repeated_int32: 1 repeated_int32: 1 repeated_int32: 3 '
+ 'repeated_string: "Google" repeated_string: "Zurich"')
+
+ def testPrintNestedNewLineInStringAsOneLine(self):
+ message = unittest_pb2.TestAllTypes()
+ message.optional_string = "a\nnew\nline"
+ self.CompareToGoldenText(
+ text_format.MessageToString(message, as_one_line=True),
+ 'optional_string: "a\\nnew\\nline"')
+
+ def testPrintMessageSetAsOneLine(self):
+ message = unittest_mset_pb2.TestMessageSetContainer()
+ ext1 = unittest_mset_pb2.TestMessageSetExtension1.message_set_extension
+ ext2 = unittest_mset_pb2.TestMessageSetExtension2.message_set_extension
+ message.message_set.Extensions[ext1].i = 23
+ message.message_set.Extensions[ext2].str = 'foo'
+ self.CompareToGoldenText(
+ text_format.MessageToString(message, as_one_line=True),
+ 'message_set {'
+ ' [protobuf_unittest.TestMessageSetExtension1] {'
+ ' i: 23'
+ ' }'
+ ' [protobuf_unittest.TestMessageSetExtension2] {'
+ ' str: \"foo\"'
+ ' }'
+ ' }')
+
+ def testPrintExoticAsOneLine(self):
+ message = unittest_pb2.TestAllTypes()
+ message.repeated_int64.append(-9223372036854775808)
+ message.repeated_uint64.append(18446744073709551615)
+ message.repeated_double.append(123.456)
+ message.repeated_double.append(1.23e22)
+ message.repeated_double.append(1.23e-18)
+ message.repeated_string.append('\000\001\a\b\f\n\r\t\v\\\'"')
+ message.repeated_string.append(u'\u00fc\ua71f')
+ self.CompareToGoldenText(
+ self.RemoveRedundantZeros(
+ text_format.MessageToString(message, as_one_line=True)),
+ 'repeated_int64: -9223372036854775808'
+ ' repeated_uint64: 18446744073709551615'
+ ' repeated_double: 123.456'
+ ' repeated_double: 1.23e+22'
+ ' repeated_double: 1.23e-18'
+ ' repeated_string: '
+ '"\\000\\001\\007\\010\\014\\n\\r\\t\\013\\\\\\\'\\""'
+ ' repeated_string: "\\303\\274\\352\\234\\237"')
+
+ def testRoundTripExoticAsOneLine(self):
+ message = unittest_pb2.TestAllTypes()
+ message.repeated_int64.append(-9223372036854775808)
+ message.repeated_uint64.append(18446744073709551615)
+ message.repeated_double.append(123.456)
+ message.repeated_double.append(1.23e22)
+ message.repeated_double.append(1.23e-18)
+ message.repeated_string.append('\000\001\a\b\f\n\r\t\v\\\'"')
+ message.repeated_string.append(u'\u00fc\ua71f')
+
+ # Test as_utf8 = False.
+ wire_text = text_format.MessageToString(
+ message, as_one_line=True, as_utf8=False)
+ parsed_message = unittest_pb2.TestAllTypes()
+ text_format.Merge(wire_text, parsed_message)
+ self.assertEquals(message, parsed_message)
+
+ # Test as_utf8 = True.
+ wire_text = text_format.MessageToString(
+ message, as_one_line=True, as_utf8=True)
+ parsed_message = unittest_pb2.TestAllTypes()
+ text_format.Merge(wire_text, parsed_message)
+ self.assertEquals(message, parsed_message)
+
+ def testPrintRawUtf8String(self):
+ message = unittest_pb2.TestAllTypes()
+ message.repeated_string.append(u'\u00fc\ua71f')
+ text = text_format.MessageToString(message, as_utf8 = True)
+ self.CompareToGoldenText(text, 'repeated_string: "\303\274\352\234\237"\n')
+ parsed_message = unittest_pb2.TestAllTypes()
+ text_format.Merge(text, parsed_message)
+ self.assertEquals(message, parsed_message)
+
+ def testMessageToString(self):
+ message = unittest_pb2.ForeignMessage()
+ message.c = 123
+ self.assertEqual('c: 123\n', str(message))
+
+ def RemoveRedundantZeros(self, text):
+ # Some platforms print 1e+5 as 1e+005. This is fine, but we need to remove
+ # these zeros in order to match the golden file.
+ text = text.replace('e+0','e+').replace('e+0','e+') \
+ .replace('e-0','e-').replace('e-0','e-')
+ # Floating point fields are printed with .0 suffix even if they are
+ # actualy integer numbers.
+ text = re.compile('\.0$', re.MULTILINE).sub('', text)
+ return text
+
+ def testMergeGolden(self):
+ golden_text = '\n'.join(self.ReadGolden('text_format_unittest_data.txt'))
+ parsed_message = unittest_pb2.TestAllTypes()
+ text_format.Merge(golden_text, parsed_message)
+
+ message = unittest_pb2.TestAllTypes()
+ test_util.SetAllFields(message)
+ self.assertEquals(message, parsed_message)
+
+ def testMergeGoldenExtensions(self):
+ golden_text = '\n'.join(self.ReadGolden(
+ 'text_format_unittest_extensions_data.txt'))
+ parsed_message = unittest_pb2.TestAllExtensions()
+ text_format.Merge(golden_text, parsed_message)
+
+ message = unittest_pb2.TestAllExtensions()
+ test_util.SetAllExtensions(message)
+ self.assertEquals(message, parsed_message)
+
+ def testMergeAllFields(self):
+ message = unittest_pb2.TestAllTypes()
+ test_util.SetAllFields(message)
+ ascii_text = text_format.MessageToString(message)
+
+ parsed_message = unittest_pb2.TestAllTypes()
+ text_format.Merge(ascii_text, parsed_message)
+ self.assertEqual(message, parsed_message)
+ test_util.ExpectAllFieldsSet(self, message)
+
+ def testMergeAllExtensions(self):
+ message = unittest_pb2.TestAllExtensions()
+ test_util.SetAllExtensions(message)
+ ascii_text = text_format.MessageToString(message)
+
+ parsed_message = unittest_pb2.TestAllExtensions()
+ text_format.Merge(ascii_text, parsed_message)
+ self.assertEqual(message, parsed_message)
+
+ def testMergeMessageSet(self):
+ message = unittest_pb2.TestAllTypes()
+ text = ('repeated_uint64: 1\n'
+ 'repeated_uint64: 2\n')
+ text_format.Merge(text, message)
+ self.assertEqual(1, message.repeated_uint64[0])
+ self.assertEqual(2, message.repeated_uint64[1])
+
+ message = unittest_mset_pb2.TestMessageSetContainer()
+ text = ('message_set {\n'
+ ' [protobuf_unittest.TestMessageSetExtension1] {\n'
+ ' i: 23\n'
+ ' }\n'
+ ' [protobuf_unittest.TestMessageSetExtension2] {\n'
+ ' str: \"foo\"\n'
+ ' }\n'
+ '}\n')
+ text_format.Merge(text, message)
+ ext1 = unittest_mset_pb2.TestMessageSetExtension1.message_set_extension
+ ext2 = unittest_mset_pb2.TestMessageSetExtension2.message_set_extension
+ self.assertEquals(23, message.message_set.Extensions[ext1].i)
+ self.assertEquals('foo', message.message_set.Extensions[ext2].str)
+
+ def testMergeExotic(self):
+ message = unittest_pb2.TestAllTypes()
+ text = ('repeated_int64: -9223372036854775808\n'
+ 'repeated_uint64: 18446744073709551615\n'
+ 'repeated_double: 123.456\n'
+ 'repeated_double: 1.23e+22\n'
+ 'repeated_double: 1.23e-18\n'
+ 'repeated_string: \n'
+ '"\\000\\001\\007\\010\\014\\n\\r\\t\\013\\\\\\\'\\""\n'
+ 'repeated_string: "foo" \'corge\' "grault"\n'
+ 'repeated_string: "\\303\\274\\352\\234\\237"\n'
+ 'repeated_string: "\\xc3\\xbc"\n'
+ 'repeated_string: "\xc3\xbc"\n')
+ text_format.Merge(text, message)
+
+ self.assertEqual(-9223372036854775808, message.repeated_int64[0])
+ self.assertEqual(18446744073709551615, message.repeated_uint64[0])
+ self.assertEqual(123.456, message.repeated_double[0])
+ self.assertEqual(1.23e22, message.repeated_double[1])
+ self.assertEqual(1.23e-18, message.repeated_double[2])
+ self.assertEqual(
+ '\000\001\a\b\f\n\r\t\v\\\'"', message.repeated_string[0])
+ self.assertEqual('foocorgegrault', message.repeated_string[1])
+ self.assertEqual(u'\u00fc\ua71f', message.repeated_string[2])
+ self.assertEqual(u'\u00fc', message.repeated_string[3])
+
+ def testMergeEmptyText(self):
+ message = unittest_pb2.TestAllTypes()
+ text = ''
+ text_format.Merge(text, message)
+ self.assertEquals(unittest_pb2.TestAllTypes(), message)
+
+ def testMergeInvalidUtf8(self):
+ message = unittest_pb2.TestAllTypes()
+ text = 'repeated_string: "\\xc3\\xc3"'
+ self.assertRaises(text_format.ParseError, text_format.Merge, text, message)
+
+ def testMergeSingleWord(self):
+ message = unittest_pb2.TestAllTypes()
+ text = 'foo'
+ self.assertRaisesWithMessage(
+ text_format.ParseError,
+ ('1:1 : Message type "protobuf_unittest.TestAllTypes" has no field named '
+ '"foo".'),
+ text_format.Merge, text, message)
+
+ def testMergeUnknownField(self):
+ message = unittest_pb2.TestAllTypes()
+ text = 'unknown_field: 8\n'
+ self.assertRaisesWithMessage(
+ text_format.ParseError,
+ ('1:1 : Message type "protobuf_unittest.TestAllTypes" has no field named '
+ '"unknown_field".'),
+ text_format.Merge, text, message)
+
+ def testMergeBadExtension(self):
+ message = unittest_pb2.TestAllExtensions()
+ text = '[unknown_extension]: 8\n'
+ self.assertRaises(
+ text_format.ParseError,
+ text_format.Merge, text, message)
+ message = unittest_pb2.TestAllTypes()
+ self.assertRaisesWithMessage(
+ text_format.ParseError,
+ ('1:2 : Message type "protobuf_unittest.TestAllTypes" does not have '
+ 'extensions.'),
+ text_format.Merge, text, message)
+
+ def testMergeGroupNotClosed(self):
+ message = unittest_pb2.TestAllTypes()
+ text = 'RepeatedGroup: <'
+ self.assertRaisesWithMessage(
+ text_format.ParseError, '1:16 : Expected ">".',
+ text_format.Merge, text, message)
+
+ text = 'RepeatedGroup: {'
+ self.assertRaisesWithMessage(
+ text_format.ParseError, '1:16 : Expected "}".',
+ text_format.Merge, text, message)
+
+ def testMergeEmptyGroup(self):
+ message = unittest_pb2.TestAllTypes()
+ text = 'OptionalGroup: {}'
+ text_format.Merge(text, message)
+ self.assertTrue(message.HasField('optionalgroup'))
+
+ message.Clear()
+
+ message = unittest_pb2.TestAllTypes()
+ text = 'OptionalGroup: <>'
+ text_format.Merge(text, message)
+ self.assertTrue(message.HasField('optionalgroup'))
+
+ def testMergeBadEnumValue(self):
+ message = unittest_pb2.TestAllTypes()
+ text = 'optional_nested_enum: BARR'
+ self.assertRaisesWithMessage(
+ text_format.ParseError,
+ ('1:23 : Enum type "protobuf_unittest.TestAllTypes.NestedEnum" '
+ 'has no value named BARR.'),
+ text_format.Merge, text, message)
+
+ message = unittest_pb2.TestAllTypes()
+ text = 'optional_nested_enum: 100'
+ self.assertRaisesWithMessage(
+ text_format.ParseError,
+ ('1:23 : Enum type "protobuf_unittest.TestAllTypes.NestedEnum" '
+ 'has no value with number 100.'),
+ text_format.Merge, text, message)
+
+ def testMergeBadIntValue(self):
+ message = unittest_pb2.TestAllTypes()
+ text = 'optional_int32: bork'
+ self.assertRaisesWithMessage(
+ text_format.ParseError,
+ ('1:17 : Couldn\'t parse integer: bork'),
+ text_format.Merge, text, message)
+
+ def testMergeStringFieldUnescape(self):
+ message = unittest_pb2.TestAllTypes()
+ text = r'''repeated_string: "\xf\x62"
+ repeated_string: "\\xf\\x62"
+ repeated_string: "\\\xf\\\x62"
+ repeated_string: "\\\\xf\\\\x62"
+ repeated_string: "\\\\\xf\\\\\x62"
+ repeated_string: "\x5cx20"'''
+ text_format.Merge(text, message)
+
+ SLASH = '\\'
+ self.assertEqual('\x0fb', message.repeated_string[0])
+ self.assertEqual(SLASH + 'xf' + SLASH + 'x62', message.repeated_string[1])
+ self.assertEqual(SLASH + '\x0f' + SLASH + 'b', message.repeated_string[2])
+ self.assertEqual(SLASH + SLASH + 'xf' + SLASH + SLASH + 'x62',
+ message.repeated_string[3])
+ self.assertEqual(SLASH + SLASH + '\x0f' + SLASH + SLASH + 'b',
+ message.repeated_string[4])
+ self.assertEqual(SLASH + 'x20', message.repeated_string[5])
+
+ def assertRaisesWithMessage(self, e_class, e, func, *args, **kwargs):
+ """Same as assertRaises, but also compares the exception message."""
+ if hasattr(e_class, '__name__'):
+ exc_name = e_class.__name__
+ else:
+ exc_name = str(e_class)
+
+ try:
+ func(*args, **kwargs)
+ except e_class as expr:
+ if str(expr) != e:
+ msg = '%s raised, but with wrong message: "%s" instead of "%s"'
+ raise self.failureException(msg % (exc_name,
+ str(expr).encode('string_escape'),
+ e.encode('string_escape')))
+ return
+ else:
+ raise self.failureException('%s not raised' % exc_name)
+
+
+class TokenizerTest(unittest.TestCase):
+ """
+ def testSimpleTokenCases(self):
+ text = ('identifier1:"string1"\n \n\n'
+ 'identifier2 : \n \n123 \n identifier3 :\'string\'\n'
+ 'identifiER_4 : 1.1e+2 ID5:-0.23 ID6:\'aaaa\\\'bbbb\'\n'
+ 'ID7 : "aa\\"bb"\n\n\n\n ID8: {A:inf B:-inf C:true D:false}\n'
+ 'ID9: 22 ID10: -111111111111111111 ID11: -22\n'
+ 'ID12: 2222222222222222222 ID13: 1.23456f ID14: 1.2e+2f '
+ 'false_bool: 0 true_BOOL:t \n true_bool1: 1 false_BOOL1:f ' )
+ tokenizer = text_format._Tokenizer(text)
+ methods = [(tokenizer.ConsumeIdentifier, 'identifier1'),
+ ':',
+ (tokenizer.ConsumeString, 'string1'),
+ (tokenizer.ConsumeIdentifier, 'identifier2'),
+ ':',
+ (tokenizer.ConsumeInt32, 123),
+ (tokenizer.ConsumeIdentifier, 'identifier3'),
+ ':',
+ (tokenizer.ConsumeString, 'string'),
+ (tokenizer.ConsumeIdentifier, 'identifiER_4'),
+ ':',
+ (tokenizer.ConsumeFloat, 1.1e+2),
+ (tokenizer.ConsumeIdentifier, 'ID5'),
+ ':',
+ (tokenizer.ConsumeFloat, -0.23),
+ (tokenizer.ConsumeIdentifier, 'ID6'),
+ ':',
+ (tokenizer.ConsumeString, 'aaaa\'bbbb'),
+ (tokenizer.ConsumeIdentifier, 'ID7'),
+ ':',
+ (tokenizer.ConsumeString, 'aa\"bb'),
+ (tokenizer.ConsumeIdentifier, 'ID8'),
+ ':',
+ '{',
+ (tokenizer.ConsumeIdentifier, 'A'),
+ ':',
+ (tokenizer.ConsumeFloat, float('inf')),
+ (tokenizer.ConsumeIdentifier, 'B'),
+ ':',
+ (tokenizer.ConsumeFloat, -float('inf')),
+ (tokenizer.ConsumeIdentifier, 'C'),
+ ':',
+ (tokenizer.ConsumeBool, True),
+ (tokenizer.ConsumeIdentifier, 'D'),
+ ':',
+ (tokenizer.ConsumeBool, False),
+ '}',
+ (tokenizer.ConsumeIdentifier, 'ID9'),
+ ':',
+ (tokenizer.ConsumeUint32, 22),
+ (tokenizer.ConsumeIdentifier, 'ID10'),
+ ':',
+ (tokenizer.ConsumeInt64, -111111111111111111),
+ (tokenizer.ConsumeIdentifier, 'ID11'),
+ ':',
+ (tokenizer.ConsumeInt32, -22),
+ (tokenizer.ConsumeIdentifier, 'ID12'),
+ ':',
+ (tokenizer.ConsumeUint64, 2222222222222222222),
+ (tokenizer.ConsumeIdentifier, 'ID13'),
+ ':',
+ (tokenizer.ConsumeFloat, 1.23456),
+ (tokenizer.ConsumeIdentifier, 'ID14'),
+ ':',
+ (tokenizer.ConsumeFloat, 1.2e+2),
+ (tokenizer.ConsumeIdentifier, 'false_bool'),
+ ':',
+ (tokenizer.ConsumeBool, False),
+ (tokenizer.ConsumeIdentifier, 'true_BOOL'),
+ ':',
+ (tokenizer.ConsumeBool, True),
+ (tokenizer.ConsumeIdentifier, 'true_bool1'),
+ ':',
+ (tokenizer.ConsumeBool, True),
+ (tokenizer.ConsumeIdentifier, 'false_BOOL1'),
+ ':',
+ (tokenizer.ConsumeBool, False)]
+
+ i = 0
+ while not tokenizer.AtEnd():
+ m = methods[i]
+ if type(m) == str:
+ token = tokenizer.token
+ self.assertEqual(token, m)
+ tokenizer.NextToken()
+ else:
+ self.assertEqual(m[1], m[0]())
+ i += 1
+
+ def testConsumeIntegers(self):
+ # This test only tests the failures in the integer parsing methods as well
+ # as the '0' special cases.
+ int64_max = (1 << 63) - 1
+ uint32_max = (1 << 32) - 1
+ text = '-1 %d %d' % (uint32_max + 1, int64_max + 1)
+ tokenizer = text_format._Tokenizer(text)
+ self.assertRaises(text_format.ParseError, tokenizer.ConsumeUint32)
+ self.assertRaises(text_format.ParseError, tokenizer.ConsumeUint64)
+ self.assertEqual(-1, tokenizer.ConsumeInt32())
+
+ self.assertRaises(text_format.ParseError, tokenizer.ConsumeUint32)
+ self.assertRaises(text_format.ParseError, tokenizer.ConsumeInt32)
+ self.assertEqual(uint32_max + 1, tokenizer.ConsumeInt64())
+
+ self.assertRaises(text_format.ParseError, tokenizer.ConsumeInt64)
+ self.assertEqual(int64_max + 1, tokenizer.ConsumeUint64())
+ self.assertTrue(tokenizer.AtEnd())
+
+ text = '-0 -0 0 0'
+ tokenizer = text_format._Tokenizer(text)
+ self.assertEqual(0, tokenizer.ConsumeUint32())
+ self.assertEqual(0, tokenizer.ConsumeUint64())
+ self.assertEqual(0, tokenizer.ConsumeUint32())
+ self.assertEqual(0, tokenizer.ConsumeUint64())
+ self.assertTrue(tokenizer.AtEnd())
+ """
+
+ def testConsumeByteString(self):
+ text = '"string1\''
+ tokenizer = text_format._Tokenizer(text)
+ self.assertRaises(text_format.ParseError, tokenizer.ConsumeByteString)
+
+ text = 'string1"'
+ tokenizer = text_format._Tokenizer(text)
+ self.assertRaises(text_format.ParseError, tokenizer.ConsumeByteString)
+
+ text = '\n"\\xt"'
+ tokenizer = text_format._Tokenizer(text)
+ self.assertRaises(text_format.ParseError, tokenizer.ConsumeByteString)
+
+ text = '\n"\\"'
+ tokenizer = text_format._Tokenizer(text)
+ self.assertRaises(text_format.ParseError, tokenizer.ConsumeByteString)
+
+ text = '\n"\\x"'
+ tokenizer = text_format._Tokenizer(text)
+ self.assertRaises(text_format.ParseError, tokenizer.ConsumeByteString)
+
+ def testConsumeBool(self):
+ text = 'not-a-bool'
+ tokenizer = text_format._Tokenizer(text)
+ self.assertRaises(text_format.ParseError, tokenizer.ConsumeBool)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/text_format_unittest_data.txt b/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/text_format_unittest_data.txt
new file mode 100644
index 00000000..bbe58826
--- /dev/null
+++ b/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/text_format_unittest_data.txt
@@ -0,0 +1,128 @@
+optional_int32: 101
+optional_int64: 102
+optional_uint32: 103
+optional_uint64: 104
+optional_sint32: 105
+optional_sint64: 106
+optional_fixed32: 107
+optional_fixed64: 108
+optional_sfixed32: 109
+optional_sfixed64: 110
+optional_float: 111
+optional_double: 112
+optional_bool: true
+optional_string: "115"
+optional_bytes: "116"
+OptionalGroup {
+ a: 117
+}
+optional_nested_message {
+ bb: 118
+}
+optional_foreign_message {
+ c: 119
+}
+optional_import_message {
+ d: 120
+}
+optional_nested_enum: BAZ
+optional_foreign_enum: FOREIGN_BAZ
+optional_import_enum: IMPORT_BAZ
+optional_string_piece: "124"
+optional_cord: "125"
+optional_public_import_message {
+ e: 126
+}
+optional_lazy_message {
+ bb: 127
+}
+repeated_int32: 201
+repeated_int32: 301
+repeated_int64: 202
+repeated_int64: 302
+repeated_uint32: 203
+repeated_uint32: 303
+repeated_uint64: 204
+repeated_uint64: 304
+repeated_sint32: 205
+repeated_sint32: 305
+repeated_sint64: 206
+repeated_sint64: 306
+repeated_fixed32: 207
+repeated_fixed32: 307
+repeated_fixed64: 208
+repeated_fixed64: 308
+repeated_sfixed32: 209
+repeated_sfixed32: 309
+repeated_sfixed64: 210
+repeated_sfixed64: 310
+repeated_float: 211
+repeated_float: 311
+repeated_double: 212
+repeated_double: 312
+repeated_bool: true
+repeated_bool: false
+repeated_string: "215"
+repeated_string: "315"
+repeated_bytes: "216"
+repeated_bytes: "316"
+RepeatedGroup {
+ a: 217
+}
+RepeatedGroup {
+ a: 317
+}
+repeated_nested_message {
+ bb: 218
+}
+repeated_nested_message {
+ bb: 318
+}
+repeated_foreign_message {
+ c: 219
+}
+repeated_foreign_message {
+ c: 319
+}
+repeated_import_message {
+ d: 220
+}
+repeated_import_message {
+ d: 320
+}
+repeated_nested_enum: BAR
+repeated_nested_enum: BAZ
+repeated_foreign_enum: FOREIGN_BAR
+repeated_foreign_enum: FOREIGN_BAZ
+repeated_import_enum: IMPORT_BAR
+repeated_import_enum: IMPORT_BAZ
+repeated_string_piece: "224"
+repeated_string_piece: "324"
+repeated_cord: "225"
+repeated_cord: "325"
+repeated_lazy_message {
+ bb: 227
+}
+repeated_lazy_message {
+ bb: 327
+}
+default_int32: 401
+default_int64: 402
+default_uint32: 403
+default_uint64: 404
+default_sint32: 405
+default_sint64: 406
+default_fixed32: 407
+default_fixed64: 408
+default_sfixed32: 409
+default_sfixed64: 410
+default_float: 411
+default_double: 412
+default_bool: false
+default_string: "415"
+default_bytes: "416"
+default_nested_enum: FOO
+default_foreign_enum: FOREIGN_FOO
+default_import_enum: IMPORT_FOO
+default_string_piece: "424"
+default_cord: "425"
diff --git a/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/text_format_unittest_extensions_data.txt b/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/text_format_unittest_extensions_data.txt
new file mode 100644
index 00000000..0a217f02
--- /dev/null
+++ b/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/text_format_unittest_extensions_data.txt
@@ -0,0 +1,128 @@
+[protobuf_unittest.optional_int32_extension]: 101
+[protobuf_unittest.optional_int64_extension]: 102
+[protobuf_unittest.optional_uint32_extension]: 103
+[protobuf_unittest.optional_uint64_extension]: 104
+[protobuf_unittest.optional_sint32_extension]: 105
+[protobuf_unittest.optional_sint64_extension]: 106
+[protobuf_unittest.optional_fixed32_extension]: 107
+[protobuf_unittest.optional_fixed64_extension]: 108
+[protobuf_unittest.optional_sfixed32_extension]: 109
+[protobuf_unittest.optional_sfixed64_extension]: 110
+[protobuf_unittest.optional_float_extension]: 111
+[protobuf_unittest.optional_double_extension]: 112
+[protobuf_unittest.optional_bool_extension]: true
+[protobuf_unittest.optional_string_extension]: "115"
+[protobuf_unittest.optional_bytes_extension]: "116"
+[protobuf_unittest.optionalgroup_extension] {
+ a: 117
+}
+[protobuf_unittest.optional_nested_message_extension] {
+ bb: 118
+}
+[protobuf_unittest.optional_foreign_message_extension] {
+ c: 119
+}
+[protobuf_unittest.optional_import_message_extension] {
+ d: 120
+}
+[protobuf_unittest.optional_nested_enum_extension]: BAZ
+[protobuf_unittest.optional_foreign_enum_extension]: FOREIGN_BAZ
+[protobuf_unittest.optional_import_enum_extension]: IMPORT_BAZ
+[protobuf_unittest.optional_string_piece_extension]: "124"
+[protobuf_unittest.optional_cord_extension]: "125"
+[protobuf_unittest.optional_public_import_message_extension] {
+ e: 126
+}
+[protobuf_unittest.optional_lazy_message_extension] {
+ bb: 127
+}
+[protobuf_unittest.repeated_int32_extension]: 201
+[protobuf_unittest.repeated_int32_extension]: 301
+[protobuf_unittest.repeated_int64_extension]: 202
+[protobuf_unittest.repeated_int64_extension]: 302
+[protobuf_unittest.repeated_uint32_extension]: 203
+[protobuf_unittest.repeated_uint32_extension]: 303
+[protobuf_unittest.repeated_uint64_extension]: 204
+[protobuf_unittest.repeated_uint64_extension]: 304
+[protobuf_unittest.repeated_sint32_extension]: 205
+[protobuf_unittest.repeated_sint32_extension]: 305
+[protobuf_unittest.repeated_sint64_extension]: 206
+[protobuf_unittest.repeated_sint64_extension]: 306
+[protobuf_unittest.repeated_fixed32_extension]: 207
+[protobuf_unittest.repeated_fixed32_extension]: 307
+[protobuf_unittest.repeated_fixed64_extension]: 208
+[protobuf_unittest.repeated_fixed64_extension]: 308
+[protobuf_unittest.repeated_sfixed32_extension]: 209
+[protobuf_unittest.repeated_sfixed32_extension]: 309
+[protobuf_unittest.repeated_sfixed64_extension]: 210
+[protobuf_unittest.repeated_sfixed64_extension]: 310
+[protobuf_unittest.repeated_float_extension]: 211
+[protobuf_unittest.repeated_float_extension]: 311
+[protobuf_unittest.repeated_double_extension]: 212
+[protobuf_unittest.repeated_double_extension]: 312
+[protobuf_unittest.repeated_bool_extension]: true
+[protobuf_unittest.repeated_bool_extension]: false
+[protobuf_unittest.repeated_string_extension]: "215"
+[protobuf_unittest.repeated_string_extension]: "315"
+[protobuf_unittest.repeated_bytes_extension]: "216"
+[protobuf_unittest.repeated_bytes_extension]: "316"
+[protobuf_unittest.repeatedgroup_extension] {
+ a: 217
+}
+[protobuf_unittest.repeatedgroup_extension] {
+ a: 317
+}
+[protobuf_unittest.repeated_nested_message_extension] {
+ bb: 218
+}
+[protobuf_unittest.repeated_nested_message_extension] {
+ bb: 318
+}
+[protobuf_unittest.repeated_foreign_message_extension] {
+ c: 219
+}
+[protobuf_unittest.repeated_foreign_message_extension] {
+ c: 319
+}
+[protobuf_unittest.repeated_import_message_extension] {
+ d: 220
+}
+[protobuf_unittest.repeated_import_message_extension] {
+ d: 320
+}
+[protobuf_unittest.repeated_nested_enum_extension]: BAR
+[protobuf_unittest.repeated_nested_enum_extension]: BAZ
+[protobuf_unittest.repeated_foreign_enum_extension]: FOREIGN_BAR
+[protobuf_unittest.repeated_foreign_enum_extension]: FOREIGN_BAZ
+[protobuf_unittest.repeated_import_enum_extension]: IMPORT_BAR
+[protobuf_unittest.repeated_import_enum_extension]: IMPORT_BAZ
+[protobuf_unittest.repeated_string_piece_extension]: "224"
+[protobuf_unittest.repeated_string_piece_extension]: "324"
+[protobuf_unittest.repeated_cord_extension]: "225"
+[protobuf_unittest.repeated_cord_extension]: "325"
+[protobuf_unittest.repeated_lazy_message_extension] {
+ bb: 227
+}
+[protobuf_unittest.repeated_lazy_message_extension] {
+ bb: 327
+}
+[protobuf_unittest.default_int32_extension]: 401
+[protobuf_unittest.default_int64_extension]: 402
+[protobuf_unittest.default_uint32_extension]: 403
+[protobuf_unittest.default_uint64_extension]: 404
+[protobuf_unittest.default_sint32_extension]: 405
+[protobuf_unittest.default_sint64_extension]: 406
+[protobuf_unittest.default_fixed32_extension]: 407
+[protobuf_unittest.default_fixed64_extension]: 408
+[protobuf_unittest.default_sfixed32_extension]: 409
+[protobuf_unittest.default_sfixed64_extension]: 410
+[protobuf_unittest.default_float_extension]: 411
+[protobuf_unittest.default_double_extension]: 412
+[protobuf_unittest.default_bool_extension]: false
+[protobuf_unittest.default_string_extension]: "415"
+[protobuf_unittest.default_bytes_extension]: "416"
+[protobuf_unittest.default_nested_enum_extension]: FOO
+[protobuf_unittest.default_foreign_enum_extension]: FOREIGN_FOO
+[protobuf_unittest.default_import_enum_extension]: IMPORT_FOO
+[protobuf_unittest.default_string_piece_extension]: "424"
+[protobuf_unittest.default_cord_extension]: "425"
diff --git a/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/wire_format_test.py b/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/wire_format_test.py
new file mode 100755
index 00000000..76007786
--- /dev/null
+++ b/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/wire_format_test.py
@@ -0,0 +1,253 @@
+#! /usr/bin/python
+#
+# Protocol Buffers - Google's data interchange format
+# Copyright 2008 Google Inc. All rights reserved.
+# http://code.google.com/p/protobuf/
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following disclaimer
+# in the documentation and/or other materials provided with the
+# distribution.
+# * Neither the name of Google Inc. nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+"""Test for google.protobuf.internal.wire_format."""
+
+__author__ = 'robinson@google.com (Will Robinson)'
+
+import unittest
+from google.protobuf import message
+from google.protobuf.internal import wire_format
+
+
+class WireFormatTest(unittest.TestCase):
+
+ def testPackTag(self):
+ field_number = 0xabc
+ tag_type = 2
+ self.assertEqual((field_number << 3) | tag_type,
+ wire_format.PackTag(field_number, tag_type))
+ PackTag = wire_format.PackTag
+ # Number too high.
+ self.assertRaises(message.EncodeError, PackTag, field_number, 6)
+ # Number too low.
+ self.assertRaises(message.EncodeError, PackTag, field_number, -1)
+
+ def testUnpackTag(self):
+ # Test field numbers that will require various varint sizes.
+ for expected_field_number in (1, 15, 16, 2047, 2048):
+ for expected_wire_type in range(6): # Highest-numbered wiretype is 5.
+ field_number, wire_type = wire_format.UnpackTag(
+ wire_format.PackTag(expected_field_number, expected_wire_type))
+ self.assertEqual(expected_field_number, field_number)
+ self.assertEqual(expected_wire_type, wire_type)
+
+ self.assertRaises(TypeError, wire_format.UnpackTag, None)
+ self.assertRaises(TypeError, wire_format.UnpackTag, 'abc')
+ self.assertRaises(TypeError, wire_format.UnpackTag, 0.0)
+ self.assertRaises(TypeError, wire_format.UnpackTag, object())
+
+ def testZigZagEncode(self):
+ Z = wire_format.ZigZagEncode
+ self.assertEqual(0, Z(0))
+ self.assertEqual(1, Z(-1))
+ self.assertEqual(2, Z(1))
+ self.assertEqual(3, Z(-2))
+ self.assertEqual(4, Z(2))
+ self.assertEqual(0xfffffffe, Z(0x7fffffff))
+ self.assertEqual(0xffffffff, Z(-0x80000000))
+ self.assertEqual(0xfffffffffffffffe, Z(0x7fffffffffffffff))
+ self.assertEqual(0xffffffffffffffff, Z(-0x8000000000000000))
+
+ self.assertRaises(TypeError, Z, None)
+ self.assertRaises(TypeError, Z, 'abcd')
+ self.assertRaises(TypeError, Z, 0.0)
+ self.assertRaises(TypeError, Z, object())
+
+ def testZigZagDecode(self):
+ Z = wire_format.ZigZagDecode
+ self.assertEqual(0, Z(0))
+ self.assertEqual(-1, Z(1))
+ self.assertEqual(1, Z(2))
+ self.assertEqual(-2, Z(3))
+ self.assertEqual(2, Z(4))
+ self.assertEqual(0x7fffffff, Z(0xfffffffe))
+ self.assertEqual(-0x80000000, Z(0xffffffff))
+ self.assertEqual(0x7fffffffffffffff, Z(0xfffffffffffffffe))
+ self.assertEqual(-0x8000000000000000, Z(0xffffffffffffffff))
+
+ self.assertRaises(TypeError, Z, None)
+ self.assertRaises(TypeError, Z, 'abcd')
+ self.assertRaises(TypeError, Z, 0.0)
+ self.assertRaises(TypeError, Z, object())
+
+ def NumericByteSizeTestHelper(self, byte_size_fn, value, expected_value_size):
+ # Use field numbers that cause various byte sizes for the tag information.
+ for field_number, tag_bytes in ((15, 1), (16, 2), (2047, 2), (2048, 3)):
+ expected_size = expected_value_size + tag_bytes
+ actual_size = byte_size_fn(field_number, value)
+ self.assertEqual(expected_size, actual_size,
+ 'byte_size_fn: %s, field_number: %d, value: %r\n'
+ 'Expected: %d, Actual: %d'% (
+ byte_size_fn, field_number, value, expected_size, actual_size))
+
+ def testByteSizeFunctions(self):
+ # Test all numeric *ByteSize() functions.
+ NUMERIC_ARGS = [
+ # Int32ByteSize().
+ [wire_format.Int32ByteSize, 0, 1],
+ [wire_format.Int32ByteSize, 127, 1],
+ [wire_format.Int32ByteSize, 128, 2],
+ [wire_format.Int32ByteSize, -1, 10],
+ # Int64ByteSize().
+ [wire_format.Int64ByteSize, 0, 1],
+ [wire_format.Int64ByteSize, 127, 1],
+ [wire_format.Int64ByteSize, 128, 2],
+ [wire_format.Int64ByteSize, -1, 10],
+ # UInt32ByteSize().
+ [wire_format.UInt32ByteSize, 0, 1],
+ [wire_format.UInt32ByteSize, 127, 1],
+ [wire_format.UInt32ByteSize, 128, 2],
+ [wire_format.UInt32ByteSize, wire_format.UINT32_MAX, 5],
+ # UInt64ByteSize().
+ [wire_format.UInt64ByteSize, 0, 1],
+ [wire_format.UInt64ByteSize, 127, 1],
+ [wire_format.UInt64ByteSize, 128, 2],
+ [wire_format.UInt64ByteSize, wire_format.UINT64_MAX, 10],
+ # SInt32ByteSize().
+ [wire_format.SInt32ByteSize, 0, 1],
+ [wire_format.SInt32ByteSize, -1, 1],
+ [wire_format.SInt32ByteSize, 1, 1],
+ [wire_format.SInt32ByteSize, -63, 1],
+ [wire_format.SInt32ByteSize, 63, 1],
+ [wire_format.SInt32ByteSize, -64, 1],
+ [wire_format.SInt32ByteSize, 64, 2],
+ # SInt64ByteSize().
+ [wire_format.SInt64ByteSize, 0, 1],
+ [wire_format.SInt64ByteSize, -1, 1],
+ [wire_format.SInt64ByteSize, 1, 1],
+ [wire_format.SInt64ByteSize, -63, 1],
+ [wire_format.SInt64ByteSize, 63, 1],
+ [wire_format.SInt64ByteSize, -64, 1],
+ [wire_format.SInt64ByteSize, 64, 2],
+ # Fixed32ByteSize().
+ [wire_format.Fixed32ByteSize, 0, 4],
+ [wire_format.Fixed32ByteSize, wire_format.UINT32_MAX, 4],
+ # Fixed64ByteSize().
+ [wire_format.Fixed64ByteSize, 0, 8],
+ [wire_format.Fixed64ByteSize, wire_format.UINT64_MAX, 8],
+ # SFixed32ByteSize().
+ [wire_format.SFixed32ByteSize, 0, 4],
+ [wire_format.SFixed32ByteSize, wire_format.INT32_MIN, 4],
+ [wire_format.SFixed32ByteSize, wire_format.INT32_MAX, 4],
+ # SFixed64ByteSize().
+ [wire_format.SFixed64ByteSize, 0, 8],
+ [wire_format.SFixed64ByteSize, wire_format.INT64_MIN, 8],
+ [wire_format.SFixed64ByteSize, wire_format.INT64_MAX, 8],
+ # FloatByteSize().
+ [wire_format.FloatByteSize, 0.0, 4],
+ [wire_format.FloatByteSize, 1000000000.0, 4],
+ [wire_format.FloatByteSize, -1000000000.0, 4],
+ # DoubleByteSize().
+ [wire_format.DoubleByteSize, 0.0, 8],
+ [wire_format.DoubleByteSize, 1000000000.0, 8],
+ [wire_format.DoubleByteSize, -1000000000.0, 8],
+ # BoolByteSize().
+ [wire_format.BoolByteSize, False, 1],
+ [wire_format.BoolByteSize, True, 1],
+ # EnumByteSize().
+ [wire_format.EnumByteSize, 0, 1],
+ [wire_format.EnumByteSize, 127, 1],
+ [wire_format.EnumByteSize, 128, 2],
+ [wire_format.EnumByteSize, wire_format.UINT32_MAX, 5],
+ ]
+ for args in NUMERIC_ARGS:
+ self.NumericByteSizeTestHelper(*args)
+
+ # Test strings and bytes.
+ for byte_size_fn in (wire_format.StringByteSize, wire_format.BytesByteSize):
+ # 1 byte for tag, 1 byte for length, 3 bytes for contents.
+ self.assertEqual(5, byte_size_fn(10, 'abc'))
+ # 2 bytes for tag, 1 byte for length, 3 bytes for contents.
+ self.assertEqual(6, byte_size_fn(16, 'abc'))
+ # 2 bytes for tag, 2 bytes for length, 128 bytes for contents.
+ self.assertEqual(132, byte_size_fn(16, 'a' * 128))
+
+ # Test UTF-8 string byte size calculation.
+ # 1 byte for tag, 1 byte for length, 8 bytes for content.
+ self.assertEqual(10, wire_format.StringByteSize(
+ 5, unicode('\xd0\xa2\xd0\xb5\xd1\x81\xd1\x82', 'utf-8')))
+
+ class MockMessage(object):
+ def __init__(self, byte_size):
+ self.byte_size = byte_size
+ def ByteSize(self):
+ return self.byte_size
+
+ message_byte_size = 10
+ mock_message = MockMessage(byte_size=message_byte_size)
+ # Test groups.
+ # (2 * 1) bytes for begin and end tags, plus message_byte_size.
+ self.assertEqual(2 + message_byte_size,
+ wire_format.GroupByteSize(1, mock_message))
+ # (2 * 2) bytes for begin and end tags, plus message_byte_size.
+ self.assertEqual(4 + message_byte_size,
+ wire_format.GroupByteSize(16, mock_message))
+
+ # Test messages.
+ # 1 byte for tag, plus 1 byte for length, plus contents.
+ self.assertEqual(2 + mock_message.byte_size,
+ wire_format.MessageByteSize(1, mock_message))
+ # 2 bytes for tag, plus 1 byte for length, plus contents.
+ self.assertEqual(3 + mock_message.byte_size,
+ wire_format.MessageByteSize(16, mock_message))
+ # 2 bytes for tag, plus 2 bytes for length, plus contents.
+ mock_message.byte_size = 128
+ self.assertEqual(4 + mock_message.byte_size,
+ wire_format.MessageByteSize(16, mock_message))
+
+
+ # Test message set item byte size.
+ # 4 bytes for tags, plus 1 byte for length, plus 1 byte for type_id,
+ # plus contents.
+ mock_message.byte_size = 10
+ self.assertEqual(mock_message.byte_size + 6,
+ wire_format.MessageSetItemByteSize(1, mock_message))
+
+ # 4 bytes for tags, plus 2 bytes for length, plus 1 byte for type_id,
+ # plus contents.
+ mock_message.byte_size = 128
+ self.assertEqual(mock_message.byte_size + 7,
+ wire_format.MessageSetItemByteSize(1, mock_message))
+
+ # 4 bytes for tags, plus 2 bytes for length, plus 2 byte for type_id,
+ # plus contents.
+ self.assertEqual(mock_message.byte_size + 8,
+ wire_format.MessageSetItemByteSize(128, mock_message))
+
+ # Too-long varint.
+ self.assertRaises(message.EncodeError,
+ wire_format.UInt64ByteSize, 1, 1 << 128)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/python/google/protobuf/__init__.py b/python/google/protobuf/__init__.py
index 0e2a89ff..9f1a4f19 100755
--- a/python/google/protobuf/__init__.py
+++ b/python/google/protobuf/__init__.py
@@ -30,7 +30,7 @@
# Copyright 2007 Google Inc. All Rights Reserved.
-__version__ = '3.1.0'
+__version__ = '3.4.1'
if __name__ != '__main__':
try:
diff --git a/python/google/protobuf/descriptor.py b/python/google/protobuf/descriptor.py
index e1f2e3b7..b1f3ca38 100755
--- a/python/google/protobuf/descriptor.py
+++ b/python/google/protobuf/descriptor.py
@@ -406,6 +406,8 @@ class FieldDescriptor(DescriptorBase):
containing_oneof: (OneofDescriptor) If the field is a member of a oneof
union, contains its descriptor. Otherwise, None.
+
+ file: (FileDescriptor) Reference to file descriptor.
"""
# Must be consistent with C++ FieldDescriptor::Type enum in
@@ -490,7 +492,8 @@ class FieldDescriptor(DescriptorBase):
def __new__(cls, name, full_name, index, number, type, cpp_type, label,
default_value, message_type, enum_type, containing_type,
is_extension, extension_scope, options=None,
- has_default_value=True, containing_oneof=None, json_name=None):
+ has_default_value=True, containing_oneof=None, json_name=None,
+ file=None):
_message.Message._CheckCalledFromGeneratedFile()
if is_extension:
return _message.default_pool.FindExtensionByName(full_name)
@@ -500,7 +503,8 @@ class FieldDescriptor(DescriptorBase):
def __init__(self, name, full_name, index, number, type, cpp_type, label,
default_value, message_type, enum_type, containing_type,
is_extension, extension_scope, options=None,
- has_default_value=True, containing_oneof=None, json_name=None):
+ has_default_value=True, containing_oneof=None, json_name=None,
+ file=None):
"""The arguments are as described in the description of FieldDescriptor
attributes above.
@@ -511,6 +515,7 @@ class FieldDescriptor(DescriptorBase):
super(FieldDescriptor, self).__init__(options, 'FieldOptions')
self.name = name
self.full_name = full_name
+ self.file = file
self._camelcase_name = None
if json_name is None:
self.json_name = _ToJsonName(name)
diff --git a/python/google/protobuf/descriptor_database.py b/python/google/protobuf/descriptor_database.py
index 1333f996..b8f5140b 100644
--- a/python/google/protobuf/descriptor_database.py
+++ b/python/google/protobuf/descriptor_database.py
@@ -54,9 +54,9 @@ class DescriptorDatabase(object):
Args:
file_desc_proto: The FileDescriptorProto to add.
Raises:
- DescriptorDatabaseException: if an attempt is made to add a proto
- with the same name but different definition than an exisiting
- proto in the database.
+ DescriptorDatabaseConflictingDefinitionError: if an attempt is made to
+ add a proto with the same name but different definition than an
+ exisiting proto in the database.
"""
proto_name = file_desc_proto.name
if proto_name not in self._file_desc_protos_by_file:
@@ -65,7 +65,7 @@ class DescriptorDatabase(object):
raise DescriptorDatabaseConflictingDefinitionError(
'%s already added, but with different descriptor.' % proto_name)
- # Add the top-level Message, Enum and Extension descriptors to the index.
+ # Add all the top-level descriptors to the index.
package = file_desc_proto.package
for message in file_desc_proto.message_type:
self._file_desc_protos_by_symbol.update(
@@ -76,6 +76,9 @@ class DescriptorDatabase(object):
for extension in file_desc_proto.extension:
self._file_desc_protos_by_symbol[
'.'.join((package, extension.name))] = file_desc_proto
+ for service in file_desc_proto.service:
+ self._file_desc_protos_by_symbol[
+ '.'.join((package, service.name))] = file_desc_proto
def FindFileByName(self, name):
"""Finds the file descriptor proto by file name.
@@ -104,6 +107,7 @@ class DescriptorDatabase(object):
'some.package.name.Message'
'some.package.name.Message.NestedEnum'
+ 'some.package.name.Message.some_field'
The file descriptor proto containing the specified symbol must be added to
this database using the Add method or else an error will be raised.
@@ -117,8 +121,16 @@ class DescriptorDatabase(object):
Raises:
KeyError if no file contains the specified symbol.
"""
-
- return self._file_desc_protos_by_symbol[symbol]
+ try:
+ return self._file_desc_protos_by_symbol[symbol]
+ except KeyError:
+ # Fields, enum values, and nested extensions are not in
+ # _file_desc_protos_by_symbol. Try to find the top level
+ # descriptor. Non-existent nested symbol under a valid top level
+ # descriptor can also be found. The behavior is the same with
+ # protobuf C++.
+ top_level, _, _ = symbol.rpartition('.')
+ return self._file_desc_protos_by_symbol[top_level]
def _ExtractSymbols(desc_proto, package):
@@ -131,8 +143,7 @@ def _ExtractSymbols(desc_proto, package):
Yields:
The fully qualified name found in the descriptor.
"""
-
- message_name = '.'.join((package, desc_proto.name))
+ message_name = package + '.' + desc_proto.name if package else desc_proto.name
yield message_name
for nested_type in desc_proto.nested_type:
for symbol in _ExtractSymbols(nested_type, message_name):
diff --git a/python/google/protobuf/descriptor_pool.py b/python/google/protobuf/descriptor_pool.py
index fc3a7f44..cb7146b6 100644
--- a/python/google/protobuf/descriptor_pool.py
+++ b/python/google/protobuf/descriptor_pool.py
@@ -124,6 +124,7 @@ class DescriptorPool(object):
self._descriptor_db = descriptor_db
self._descriptors = {}
self._enum_descriptors = {}
+ self._service_descriptors = {}
self._file_descriptors = {}
self._toplevel_extensions = {}
# We store extensions in two two-level mappings: The first key is the
@@ -169,12 +170,12 @@ class DescriptorPool(object):
raise TypeError('Expected instance of descriptor.Descriptor.')
self._descriptors[desc.full_name] = desc
- self.AddFileDescriptor(desc.file)
+ self._AddFileDescriptor(desc.file)
def AddEnumDescriptor(self, enum_desc):
"""Adds an EnumDescriptor to the pool.
- This method also registers the FileDescriptor associated with the message.
+ This method also registers the FileDescriptor associated with the enum.
Args:
enum_desc: An EnumDescriptor.
@@ -184,7 +185,19 @@ class DescriptorPool(object):
raise TypeError('Expected instance of descriptor.EnumDescriptor.')
self._enum_descriptors[enum_desc.full_name] = enum_desc
- self.AddFileDescriptor(enum_desc.file)
+ self._AddFileDescriptor(enum_desc.file)
+
+ def AddServiceDescriptor(self, service_desc):
+ """Adds a ServiceDescriptor to the pool.
+
+ Args:
+ service_desc: A ServiceDescriptor.
+ """
+
+ if not isinstance(service_desc, descriptor.ServiceDescriptor):
+ raise TypeError('Expected instance of descriptor.ServiceDescriptor.')
+
+ self._service_descriptors[service_desc.full_name] = service_desc
def AddExtensionDescriptor(self, extension):
"""Adds a FieldDescriptor describing an extension to the pool.
@@ -238,6 +251,18 @@ class DescriptorPool(object):
file_desc: A FileDescriptor.
"""
+ self._AddFileDescriptor(file_desc)
+
+ def _AddFileDescriptor(self, file_desc):
+ """Adds a FileDescriptor to the pool, non-recursively.
+
+ If the FileDescriptor contains messages or enums, the caller must explicitly
+ register them.
+
+ Args:
+ file_desc: A FileDescriptor.
+ """
+
if not isinstance(file_desc, descriptor.FileDescriptor):
raise TypeError('Expected instance of descriptor.FileDescriptor.')
self._file_descriptors[file_desc.name] = file_desc
@@ -252,7 +277,7 @@ class DescriptorPool(object):
A FileDescriptor for the named file.
Raises:
- KeyError: if the file can not be found in the pool.
+ KeyError: if the file cannot be found in the pool.
"""
try:
@@ -281,7 +306,7 @@ class DescriptorPool(object):
A FileDescriptor that contains the specified symbol.
Raises:
- KeyError: if the file can not be found in the pool.
+ KeyError: if the file cannot be found in the pool.
"""
symbol = _NormalizeFullyQualifiedName(symbol)
@@ -296,15 +321,28 @@ class DescriptorPool(object):
pass
try:
- file_proto = self._internal_db.FindFileContainingSymbol(symbol)
- except KeyError as error:
- if self._descriptor_db:
- file_proto = self._descriptor_db.FindFileContainingSymbol(symbol)
- else:
- raise error
- if not file_proto:
+ return self._service_descriptors[symbol].file
+ except KeyError:
+ pass
+
+ try:
+ return self._FindFileContainingSymbolInDb(symbol)
+ except KeyError:
+ pass
+
+ try:
+ return self._toplevel_extensions[symbol].file
+ except KeyError:
+ pass
+
+ # Try nested extensions inside a message.
+ message_name, _, extension_name = symbol.rpartition('.')
+ try:
+ message = self.FindMessageTypeByName(message_name)
+ assert message.extensions_by_name[extension_name]
+ return message.file
+ except KeyError:
raise KeyError('Cannot find a file containing %s' % symbol)
- return self._ConvertFileProtoToFileDescriptor(file_proto)
def FindMessageTypeByName(self, full_name):
"""Loads the named descriptor from the pool.
@@ -314,11 +352,14 @@ class DescriptorPool(object):
Returns:
The descriptor for the named type.
+
+ Raises:
+ KeyError: if the message cannot be found in the pool.
"""
full_name = _NormalizeFullyQualifiedName(full_name)
if full_name not in self._descriptors:
- self.FindFileContainingSymbol(full_name)
+ self._FindFileContainingSymbolInDb(full_name)
return self._descriptors[full_name]
def FindEnumTypeByName(self, full_name):
@@ -329,11 +370,14 @@ class DescriptorPool(object):
Returns:
The enum descriptor for the named type.
+
+ Raises:
+ KeyError: if the enum cannot be found in the pool.
"""
full_name = _NormalizeFullyQualifiedName(full_name)
if full_name not in self._enum_descriptors:
- self.FindFileContainingSymbol(full_name)
+ self._FindFileContainingSymbolInDb(full_name)
return self._enum_descriptors[full_name]
def FindFieldByName(self, full_name):
@@ -344,12 +388,32 @@ class DescriptorPool(object):
Returns:
The field descriptor for the named field.
+
+ Raises:
+ KeyError: if the field cannot be found in the pool.
"""
full_name = _NormalizeFullyQualifiedName(full_name)
message_name, _, field_name = full_name.rpartition('.')
message_descriptor = self.FindMessageTypeByName(message_name)
return message_descriptor.fields_by_name[field_name]
+ def FindOneofByName(self, full_name):
+ """Loads the named oneof descriptor from the pool.
+
+ Args:
+ full_name: The full name of the oneof descriptor to load.
+
+ Returns:
+ The oneof descriptor for the named oneof.
+
+ Raises:
+ KeyError: if the oneof cannot be found in the pool.
+ """
+ full_name = _NormalizeFullyQualifiedName(full_name)
+ message_name, _, oneof_name = full_name.rpartition('.')
+ message_descriptor = self.FindMessageTypeByName(message_name)
+ return message_descriptor.oneofs_by_name[oneof_name]
+
def FindExtensionByName(self, full_name):
"""Loads the named extension descriptor from the pool.
@@ -358,6 +422,9 @@ class DescriptorPool(object):
Returns:
A FieldDescriptor, describing the named extension.
+
+ Raises:
+ KeyError: if the extension cannot be found in the pool.
"""
full_name = _NormalizeFullyQualifiedName(full_name)
try:
@@ -374,7 +441,7 @@ class DescriptorPool(object):
scope = self.FindMessageTypeByName(message_name)
except KeyError:
# Some extensions are defined at file scope.
- scope = self.FindFileContainingSymbol(full_name)
+ scope = self._FindFileContainingSymbolInDb(full_name)
return scope.extensions_by_name[extension_name]
def FindExtensionByNumber(self, message_descriptor, number):
@@ -390,7 +457,7 @@ class DescriptorPool(object):
Returns:
A FieldDescriptor describing the extension.
- Raise:
+ Raises:
KeyError: when no extension with the given number is known for the
specified message.
"""
@@ -410,6 +477,46 @@ class DescriptorPool(object):
"""
return list(self._extensions_by_number[message_descriptor].values())
+ def FindServiceByName(self, full_name):
+ """Loads the named service descriptor from the pool.
+
+ Args:
+ full_name: The full name of the service descriptor to load.
+
+ Returns:
+ The service descriptor for the named service.
+
+ Raises:
+ KeyError: if the service cannot be found in the pool.
+ """
+ full_name = _NormalizeFullyQualifiedName(full_name)
+ if full_name not in self._service_descriptors:
+ self._FindFileContainingSymbolInDb(full_name)
+ return self._service_descriptors[full_name]
+
+ def _FindFileContainingSymbolInDb(self, symbol):
+ """Finds the file in descriptor DB containing the specified symbol.
+
+ Args:
+ symbol: The name of the symbol to search for.
+
+ Returns:
+ A FileDescriptor that contains the specified symbol.
+
+ Raises:
+ KeyError: if the file cannot be found in the descriptor database.
+ """
+ try:
+ file_proto = self._internal_db.FindFileContainingSymbol(symbol)
+ except KeyError as error:
+ if self._descriptor_db:
+ file_proto = self._descriptor_db.FindFileContainingSymbol(symbol)
+ else:
+ raise error
+ if not file_proto:
+ raise KeyError('Cannot find a file containing %s' % symbol)
+ return self._ConvertFileProtoToFileDescriptor(file_proto)
+
def _ConvertFileProtoToFileDescriptor(self, file_proto):
"""Creates a FileDescriptor from a proto or returns a cached copy.
@@ -463,7 +570,8 @@ class DescriptorPool(object):
for index, extension_proto in enumerate(file_proto.extension):
extension_desc = self._MakeFieldDescriptor(
- extension_proto, file_proto.package, index, is_extension=True)
+ extension_proto, file_proto.package, index, file_descriptor,
+ is_extension=True)
extension_desc.containing_type = self._GetTypeFromScope(
file_descriptor.package, extension_proto.extendee, scope)
self._SetFieldType(extension_proto, extension_desc,
@@ -529,10 +637,10 @@ class DescriptorPool(object):
enums = [
self._ConvertEnumDescriptor(enum, desc_name, file_desc, None, scope)
for enum in desc_proto.enum_type]
- fields = [self._MakeFieldDescriptor(field, desc_name, index)
+ fields = [self._MakeFieldDescriptor(field, desc_name, index, file_desc)
for index, field in enumerate(desc_proto.field)]
extensions = [
- self._MakeFieldDescriptor(extension, desc_name, index,
+ self._MakeFieldDescriptor(extension, desc_name, index, file_desc,
is_extension=True)
for index, extension in enumerate(desc_proto.extension)]
oneofs = [
@@ -614,7 +722,7 @@ class DescriptorPool(object):
return desc
def _MakeFieldDescriptor(self, field_proto, message_name, index,
- is_extension=False):
+ file_desc, is_extension=False):
"""Creates a field descriptor from a FieldDescriptorProto.
For message and enum type fields, this method will do a look up
@@ -627,6 +735,7 @@ class DescriptorPool(object):
field_proto: The proto describing the field.
message_name: The name of the containing message.
index: Index of the field
+ file_desc: The file containing the field descriptor.
is_extension: Indication that this field is for an extension.
Returns:
@@ -653,7 +762,8 @@ class DescriptorPool(object):
default_value=None,
is_extension=is_extension,
extension_scope=None,
- options=_OptionsOrNone(field_proto))
+ options=_OptionsOrNone(field_proto),
+ file=file_desc)
def _SetAllFieldTypes(self, package, desc_proto, scope):
"""Sets all the descriptor's fields's types.
@@ -804,6 +914,7 @@ class DescriptorPool(object):
methods=methods,
options=_OptionsOrNone(service_proto),
file=file_desc)
+ self._service_descriptors[service_name] = desc
return desc
def _MakeMethodDescriptor(self, method_proto, service_name, package, scope,
diff --git a/python/google/protobuf/internal/any_test.proto b/python/google/protobuf/internal/any_test.proto
index 76a7ebd6..1a563fd9 100644
--- a/python/google/protobuf/internal/any_test.proto
+++ b/python/google/protobuf/internal/any_test.proto
@@ -39,6 +39,7 @@ import "google/protobuf/any.proto";
message TestAny {
optional google.protobuf.Any value = 1;
optional int32 int_value = 2;
+ map<string,int32> map_value = 3;
extensions 10 to max;
}
diff --git a/python/google/protobuf/internal/api_implementation.py b/python/google/protobuf/internal/api_implementation.py
index 460a4a6c..553fcdb6 100755
--- a/python/google/protobuf/internal/api_implementation.py
+++ b/python/google/protobuf/internal/api_implementation.py
@@ -61,10 +61,15 @@ if _api_version < 0: # Still unspecified?
del _use_fast_cpp_protos
_api_version = 2
except ImportError:
- if _proto_extension_modules_exist_in_build:
- if sys.version_info[0] >= 3: # Python 3 defaults to C++ impl v2.
- _api_version = 2
- # TODO(b/17427486): Make Python 2 default to C++ impl v2.
+ try:
+ # pylint: disable=g-import-not-at-top
+ from google.protobuf.internal import use_pure_python
+ del use_pure_python # Avoids a pylint error and namespace pollution.
+ except ImportError:
+ if _proto_extension_modules_exist_in_build:
+ if sys.version_info[0] >= 3: # Python 3 defaults to C++ impl v2.
+ _api_version = 2
+ # TODO(b/17427486): Make Python 2 default to C++ impl v2.
_default_implementation_type = (
'python' if _api_version <= 0 else 'cpp')
@@ -100,6 +105,27 @@ if _implementation_version_str != '2':
_implementation_version = int(_implementation_version_str)
+# Detect if serialization should be deterministic by default
+try:
+ # The presence of this module in a build allows the proto implementation to
+ # be upgraded merely via build deps.
+ #
+ # NOTE: Merely importing this automatically enables deterministic proto
+ # serialization for C++ code, but we still need to export it as a boolean so
+ # that we can do the same for `_implementation_type == 'python'`.
+ #
+ # NOTE2: It is possible for C++ code to enable deterministic serialization by
+ # default _without_ affecting Python code, if the C++ implementation is not in
+ # use by this module. That is intended behavior, so we don't actually expose
+ # this boolean outside of this module.
+ #
+ # pylint: disable=g-import-not-at-top,unused-import
+ from google.protobuf import enable_deterministic_proto_serialization
+ _python_deterministic_proto_serialization = True
+except ImportError:
+ _python_deterministic_proto_serialization = False
+
+
# Usage of this function is discouraged. Clients shouldn't care which
# implementation of the API is in use. Note that there is no guarantee
# that differences between APIs will be maintained.
@@ -111,3 +137,34 @@ def Type():
# See comment on 'Type' above.
def Version():
return _implementation_version
+
+
+# For internal use only
+def IsPythonDefaultSerializationDeterministic():
+ return _python_deterministic_proto_serialization
+
+# DO NOT USE: For migration and testing only. Will be removed when Proto3
+# defaults to preserve unknowns.
+if _implementation_type == 'cpp':
+ try:
+ # pylint: disable=g-import-not-at-top
+ from google.protobuf.pyext import _message
+
+ def GetPythonProto3PreserveUnknownsDefault():
+ return _message.GetPythonProto3PreserveUnknownsDefault()
+
+ def SetPythonProto3PreserveUnknownsDefault(preserve):
+ _message.SetPythonProto3PreserveUnknownsDefault(preserve)
+ except ImportError:
+ # Unrecognized cpp implementation. Skipping the unknown fields APIs.
+ pass
+else:
+ _python_proto3_preserve_unknowns_default = True
+
+ def GetPythonProto3PreserveUnknownsDefault():
+ return _python_proto3_preserve_unknowns_default
+
+ def SetPythonProto3PreserveUnknownsDefault(preserve):
+ global _python_proto3_preserve_unknowns_default
+ _python_proto3_preserve_unknowns_default = preserve
+
diff --git a/python/google/protobuf/internal/containers.py b/python/google/protobuf/internal/containers.py
index de13018e..68be9e54 100755
--- a/python/google/protobuf/internal/containers.py
+++ b/python/google/protobuf/internal/containers.py
@@ -275,7 +275,7 @@ class RepeatedScalarFieldContainer(BaseContainer):
new_values = [self._type_checker.CheckValue(elem) for elem in elem_seq_iter]
if new_values:
self._values.extend(new_values)
- self._message_listener.Modified()
+ self._message_listener.Modified()
def MergeFrom(self, other):
"""Appends the contents of another repeated field of the same type to this
diff --git a/python/google/protobuf/internal/decoder.py b/python/google/protobuf/internal/decoder.py
index c5f73dc1..52b64915 100755
--- a/python/google/protobuf/internal/decoder.py
+++ b/python/google/protobuf/internal/decoder.py
@@ -131,9 +131,12 @@ def _VarintDecoder(mask, result_type):
return DecodeVarint
-def _SignedVarintDecoder(mask, result_type):
+def _SignedVarintDecoder(bits, result_type):
"""Like _VarintDecoder() but decodes signed values."""
+ signbit = 1 << (bits - 1)
+ mask = (1 << bits) - 1
+
def DecodeVarint(buffer, pos):
result = 0
shift = 0
@@ -142,11 +145,8 @@ def _SignedVarintDecoder(mask, result_type):
result |= ((b & 0x7f) << shift)
pos += 1
if not (b & 0x80):
- if result > 0x7fffffffffffffff:
- result -= (1 << 64)
- result |= ~mask
- else:
- result &= mask
+ result &= mask
+ result = (result ^ signbit) - signbit
result = result_type(result)
return (result, pos)
shift += 7
@@ -159,11 +159,11 @@ def _SignedVarintDecoder(mask, result_type):
# (e.g. the C++ implementation) simpler.
_DecodeVarint = _VarintDecoder((1 << 64) - 1, long)
-_DecodeSignedVarint = _SignedVarintDecoder((1 << 64) - 1, long)
+_DecodeSignedVarint = _SignedVarintDecoder(64, long)
# Use these versions for values which must be limited to 32 bits.
_DecodeVarint32 = _VarintDecoder((1 << 32) - 1, int)
-_DecodeSignedVarint32 = _SignedVarintDecoder((1 << 32) - 1, int)
+_DecodeSignedVarint32 = _SignedVarintDecoder(32, int)
def ReadTag(buffer, pos):
@@ -181,7 +181,7 @@ def ReadTag(buffer, pos):
while six.indexbytes(buffer, pos) & 0x80:
pos += 1
pos += 1
- return (buffer[start:pos], pos)
+ return (six.binary_type(buffer[start:pos]), pos)
# --------------------------------------------------------------------
diff --git a/python/google/protobuf/internal/descriptor_database_test.py b/python/google/protobuf/internal/descriptor_database_test.py
index 5225a458..1f1a3db9 100644
--- a/python/google/protobuf/internal/descriptor_database_test.py
+++ b/python/google/protobuf/internal/descriptor_database_test.py
@@ -39,6 +39,7 @@ try:
except ImportError:
import unittest
+from google.protobuf import unittest_pb2
from google.protobuf import descriptor_pb2
from google.protobuf.internal import factory_test2_pb2
from google.protobuf import descriptor_database
@@ -54,16 +55,49 @@ class DescriptorDatabaseTest(unittest.TestCase):
self.assertEqual(file_desc_proto, db.FindFileByName(
'google/protobuf/internal/factory_test2.proto'))
+ # Can find message type.
self.assertEqual(file_desc_proto, db.FindFileContainingSymbol(
'google.protobuf.python.internal.Factory2Message'))
+ # Can find nested message type.
self.assertEqual(file_desc_proto, db.FindFileContainingSymbol(
'google.protobuf.python.internal.Factory2Message.NestedFactory2Message'))
+ # Can find enum type.
self.assertEqual(file_desc_proto, db.FindFileContainingSymbol(
'google.protobuf.python.internal.Factory2Enum'))
+ # Can find nested enum type.
self.assertEqual(file_desc_proto, db.FindFileContainingSymbol(
'google.protobuf.python.internal.Factory2Message.NestedFactory2Enum'))
self.assertEqual(file_desc_proto, db.FindFileContainingSymbol(
'google.protobuf.python.internal.MessageWithNestedEnumOnly.NestedEnum'))
+ # Can find field.
+ self.assertEqual(file_desc_proto, db.FindFileContainingSymbol(
+ 'google.protobuf.python.internal.Factory2Message.list_field'))
+ # Can find enum value.
+ self.assertEqual(file_desc_proto, db.FindFileContainingSymbol(
+ 'google.protobuf.python.internal.Factory2Enum.FACTORY_2_VALUE_0'))
+ # Can find top level extension.
+ self.assertEqual(file_desc_proto, db.FindFileContainingSymbol(
+ 'google.protobuf.python.internal.another_field'))
+ # Can find nested extension inside a message.
+ self.assertEqual(file_desc_proto, db.FindFileContainingSymbol(
+ 'google.protobuf.python.internal.Factory2Message.one_more_field'))
+
+ # Can find service.
+ file_desc_proto2 = descriptor_pb2.FileDescriptorProto.FromString(
+ unittest_pb2.DESCRIPTOR.serialized_pb)
+ db.Add(file_desc_proto2)
+ self.assertEqual(file_desc_proto2, db.FindFileContainingSymbol(
+ 'protobuf_unittest.TestService'))
+
+ # Non-existent field under a valid top level symbol can also be
+ # found. The behavior is the same with protobuf C++.
+ self.assertEqual(file_desc_proto2, db.FindFileContainingSymbol(
+ 'protobuf_unittest.TestAllTypes.none_field'))
+
+ self.assertRaises(KeyError,
+ db.FindFileContainingSymbol,
+ 'protobuf_unittest.NoneMessage')
+
if __name__ == '__main__':
unittest.main()
diff --git a/python/google/protobuf/internal/descriptor_pool_test.py b/python/google/protobuf/internal/descriptor_pool_test.py
index 1e710dcf..15c857bb 100644
--- a/python/google/protobuf/internal/descriptor_pool_test.py
+++ b/python/google/protobuf/internal/descriptor_pool_test.py
@@ -60,16 +60,8 @@ from google.protobuf import message_factory
from google.protobuf import symbol_database
-class DescriptorPoolTest(unittest.TestCase):
- def setUp(self):
- self.pool = descriptor_pool.DescriptorPool()
- self.factory_test1_fd = descriptor_pb2.FileDescriptorProto.FromString(
- factory_test1_pb2.DESCRIPTOR.serialized_pb)
- self.factory_test2_fd = descriptor_pb2.FileDescriptorProto.FromString(
- factory_test2_pb2.DESCRIPTOR.serialized_pb)
- self.pool.Add(self.factory_test1_fd)
- self.pool.Add(self.factory_test2_fd)
+class DescriptorPoolTestBase(object):
def testFindFileByName(self):
name1 = 'google/protobuf/internal/factory_test1.proto'
@@ -107,6 +99,26 @@ class DescriptorPoolTest(unittest.TestCase):
self.assertEqual('google.protobuf.python.internal', file_desc2.package)
self.assertIn('Factory2Message', file_desc2.message_types_by_name)
+ # Tests top level extension.
+ file_desc3 = self.pool.FindFileContainingSymbol(
+ 'google.protobuf.python.internal.another_field')
+ self.assertIsInstance(file_desc3, descriptor.FileDescriptor)
+ self.assertEqual('google/protobuf/internal/factory_test2.proto',
+ file_desc3.name)
+
+ # Tests nested extension inside a message.
+ file_desc4 = self.pool.FindFileContainingSymbol(
+ 'google.protobuf.python.internal.Factory2Message.one_more_field')
+ self.assertIsInstance(file_desc4, descriptor.FileDescriptor)
+ self.assertEqual('google/protobuf/internal/factory_test2.proto',
+ file_desc4.name)
+
+ file_desc5 = self.pool.FindFileContainingSymbol(
+ 'protobuf_unittest.TestService')
+ self.assertIsInstance(file_desc5, descriptor.FileDescriptor)
+ self.assertEqual('google/protobuf/unittest.proto',
+ file_desc5.name)
+
def testFindFileContainingSymbolFailure(self):
with self.assertRaises(KeyError):
self.pool.FindFileContainingSymbol('Does not exist')
@@ -193,6 +205,27 @@ class DescriptorPoolTest(unittest.TestCase):
msg2.fields_by_name[name].containing_oneof)
self.assertIn(msg2.fields_by_name[name], msg2.oneofs[0].fields)
+ def testFindTypeErrors(self):
+ self.assertRaises(TypeError, self.pool.FindExtensionByNumber, '')
+
+ # TODO(jieluo): Fix python to raise correct errors.
+ if api_implementation.Type() == 'cpp':
+ self.assertRaises(TypeError, self.pool.FindMethodByName, 0)
+ self.assertRaises(KeyError, self.pool.FindMethodByName, '')
+ error_type = TypeError
+ else:
+ error_type = AttributeError
+ self.assertRaises(error_type, self.pool.FindMessageTypeByName, 0)
+ self.assertRaises(error_type, self.pool.FindFieldByName, 0)
+ self.assertRaises(error_type, self.pool.FindExtensionByName, 0)
+ self.assertRaises(error_type, self.pool.FindEnumTypeByName, 0)
+ self.assertRaises(error_type, self.pool.FindOneofByName, 0)
+ self.assertRaises(error_type, self.pool.FindServiceByName, 0)
+ self.assertRaises(error_type, self.pool.FindFileContainingSymbol, 0)
+ if api_implementation.Type() == 'python':
+ error_type = KeyError
+ self.assertRaises(error_type, self.pool.FindFileByName, 0)
+
def testFindMessageTypeByNameFailure(self):
with self.assertRaises(KeyError):
self.pool.FindMessageTypeByName('Does not exist')
@@ -232,6 +265,11 @@ class DescriptorPoolTest(unittest.TestCase):
self.pool.FindEnumTypeByName('Does not exist')
def testFindFieldByName(self):
+ if isinstance(self, SecondaryDescriptorFromDescriptorDB):
+ if api_implementation.Type() == 'cpp':
+ # TODO(jieluo): Fix cpp extension to find field correctly
+ # when descriptor pool is using an underlying database.
+ return
field = self.pool.FindFieldByName(
'google.protobuf.python.internal.Factory1Message.list_value')
self.assertEqual(field.name, 'list_value')
@@ -241,7 +279,24 @@ class DescriptorPoolTest(unittest.TestCase):
with self.assertRaises(KeyError):
self.pool.FindFieldByName('Does not exist')
+ def testFindOneofByName(self):
+ if isinstance(self, SecondaryDescriptorFromDescriptorDB):
+ if api_implementation.Type() == 'cpp':
+ # TODO(jieluo): Fix cpp extension to find oneof correctly
+ # when descriptor pool is using an underlying database.
+ return
+ oneof = self.pool.FindOneofByName(
+ 'google.protobuf.python.internal.Factory2Message.oneof_field')
+ self.assertEqual(oneof.name, 'oneof_field')
+ with self.assertRaises(KeyError):
+ self.pool.FindOneofByName('Does not exist')
+
def testFindExtensionByName(self):
+ if isinstance(self, SecondaryDescriptorFromDescriptorDB):
+ if api_implementation.Type() == 'cpp':
+ # TODO(jieluo): Fix cpp extension to find extension correctly
+ # when descriptor pool is using an underlying database.
+ return
# An extension defined in a message.
extension = self.pool.FindExtensionByName(
'google.protobuf.python.internal.Factory2Message.one_more_field')
@@ -311,6 +366,12 @@ class DescriptorPoolTest(unittest.TestCase):
self.pool.FindExtensionByName(
'google.protobuf.python.internal.Factory1Message.list_value')
+ def testFindService(self):
+ service = self.pool.FindServiceByName('protobuf_unittest.TestService')
+ self.assertEqual(service.full_name, 'protobuf_unittest.TestService')
+ with self.assertRaises(KeyError):
+ self.pool.FindServiceByName('Does not exist')
+
def testUserDefinedDB(self):
db = descriptor_database.DescriptorDatabase()
self.pool = descriptor_pool.DescriptorPool(db)
@@ -319,24 +380,17 @@ class DescriptorPoolTest(unittest.TestCase):
self.testFindMessageTypeByName()
def testAddSerializedFile(self):
+ if isinstance(self, SecondaryDescriptorFromDescriptorDB):
+ if api_implementation.Type() == 'cpp':
+ # Cpp extension cannot call Add on a DescriptorPool
+ # that uses a DescriptorDatabase.
+ # TODO(jieluo): Fix python and cpp extension diff.
+ return
self.pool = descriptor_pool.DescriptorPool()
self.pool.AddSerializedFile(self.factory_test1_fd.SerializeToString())
self.pool.AddSerializedFile(self.factory_test2_fd.SerializeToString())
self.testFindMessageTypeByName()
- def testComplexNesting(self):
- more_messages_desc = descriptor_pb2.FileDescriptorProto.FromString(
- more_messages_pb2.DESCRIPTOR.serialized_pb)
- test1_desc = descriptor_pb2.FileDescriptorProto.FromString(
- descriptor_pool_test1_pb2.DESCRIPTOR.serialized_pb)
- test2_desc = descriptor_pb2.FileDescriptorProto.FromString(
- descriptor_pool_test2_pb2.DESCRIPTOR.serialized_pb)
- self.pool.Add(more_messages_desc)
- self.pool.Add(test1_desc)
- self.pool.Add(test2_desc)
- TEST1_FILE.CheckFile(self, self.pool)
- TEST2_FILE.CheckFile(self, self.pool)
-
def testEnumDefaultValue(self):
"""Test the default value of enums which don't start at zero."""
@@ -355,6 +409,12 @@ class DescriptorPoolTest(unittest.TestCase):
self.assertIs(file_descriptor, descriptor_pool_test1_pb2.DESCRIPTOR)
_CheckDefaultValue(file_descriptor)
+ if isinstance(self, SecondaryDescriptorFromDescriptorDB):
+ if api_implementation.Type() == 'cpp':
+ # Cpp extension cannot call Add on a DescriptorPool
+ # that uses a DescriptorDatabase.
+ # TODO(jieluo): Fix python and cpp extension diff.
+ return
# Then check the dynamic pool and its internal DescriptorDatabase.
descriptor_proto = descriptor_pb2.FileDescriptorProto.FromString(
descriptor_pool_test1_pb2.DESCRIPTOR.serialized_pb)
@@ -402,6 +462,110 @@ class DescriptorPoolTest(unittest.TestCase):
unittest_pb2.TestAllTypes.DESCRIPTOR.full_name))
_CheckDefaultValues(message_class())
+ def testAddFileDescriptor(self):
+ if isinstance(self, SecondaryDescriptorFromDescriptorDB):
+ if api_implementation.Type() == 'cpp':
+ # Cpp extension cannot call Add on a DescriptorPool
+ # that uses a DescriptorDatabase.
+ # TODO(jieluo): Fix python and cpp extension diff.
+ return
+ file_desc = descriptor_pb2.FileDescriptorProto(name='some/file.proto')
+ self.pool.Add(file_desc)
+ self.pool.AddSerializedFile(file_desc.SerializeToString())
+
+ def testComplexNesting(self):
+ if isinstance(self, SecondaryDescriptorFromDescriptorDB):
+ if api_implementation.Type() == 'cpp':
+ # Cpp extension cannot call Add on a DescriptorPool
+ # that uses a DescriptorDatabase.
+ # TODO(jieluo): Fix python and cpp extension diff.
+ return
+ more_messages_desc = descriptor_pb2.FileDescriptorProto.FromString(
+ more_messages_pb2.DESCRIPTOR.serialized_pb)
+ test1_desc = descriptor_pb2.FileDescriptorProto.FromString(
+ descriptor_pool_test1_pb2.DESCRIPTOR.serialized_pb)
+ test2_desc = descriptor_pb2.FileDescriptorProto.FromString(
+ descriptor_pool_test2_pb2.DESCRIPTOR.serialized_pb)
+ self.pool.Add(more_messages_desc)
+ self.pool.Add(test1_desc)
+ self.pool.Add(test2_desc)
+ TEST1_FILE.CheckFile(self, self.pool)
+ TEST2_FILE.CheckFile(self, self.pool)
+
+
+class DefaultDescriptorPoolTest(DescriptorPoolTestBase, unittest.TestCase):
+
+ def setUp(self):
+ self.pool = descriptor_pool.Default()
+ self.factory_test1_fd = descriptor_pb2.FileDescriptorProto.FromString(
+ factory_test1_pb2.DESCRIPTOR.serialized_pb)
+ self.factory_test2_fd = descriptor_pb2.FileDescriptorProto.FromString(
+ factory_test2_pb2.DESCRIPTOR.serialized_pb)
+
+ def testFindMethods(self):
+ self.assertIs(
+ self.pool.FindFileByName('google/protobuf/unittest.proto'),
+ unittest_pb2.DESCRIPTOR)
+ self.assertIs(
+ self.pool.FindMessageTypeByName('protobuf_unittest.TestAllTypes'),
+ unittest_pb2.TestAllTypes.DESCRIPTOR)
+ self.assertIs(
+ self.pool.FindFieldByName(
+ 'protobuf_unittest.TestAllTypes.optional_int32'),
+ unittest_pb2.TestAllTypes.DESCRIPTOR.fields_by_name['optional_int32'])
+ self.assertIs(
+ self.pool.FindEnumTypeByName('protobuf_unittest.ForeignEnum'),
+ unittest_pb2.ForeignEnum.DESCRIPTOR)
+ self.assertIs(
+ self.pool.FindExtensionByName(
+ 'protobuf_unittest.optional_int32_extension'),
+ unittest_pb2.DESCRIPTOR.extensions_by_name['optional_int32_extension'])
+ self.assertIs(
+ self.pool.FindOneofByName('protobuf_unittest.TestAllTypes.oneof_field'),
+ unittest_pb2.TestAllTypes.DESCRIPTOR.oneofs_by_name['oneof_field'])
+ self.assertIs(
+ self.pool.FindServiceByName('protobuf_unittest.TestService'),
+ unittest_pb2.DESCRIPTOR.services_by_name['TestService'])
+
+
+class CreateDescriptorPoolTest(DescriptorPoolTestBase, unittest.TestCase):
+
+ def setUp(self):
+ self.pool = descriptor_pool.DescriptorPool()
+ self.factory_test1_fd = descriptor_pb2.FileDescriptorProto.FromString(
+ factory_test1_pb2.DESCRIPTOR.serialized_pb)
+ self.factory_test2_fd = descriptor_pb2.FileDescriptorProto.FromString(
+ factory_test2_pb2.DESCRIPTOR.serialized_pb)
+ self.pool.Add(self.factory_test1_fd)
+ self.pool.Add(self.factory_test2_fd)
+
+ self.pool.Add(descriptor_pb2.FileDescriptorProto.FromString(
+ unittest_import_public_pb2.DESCRIPTOR.serialized_pb))
+ self.pool.Add(descriptor_pb2.FileDescriptorProto.FromString(
+ unittest_import_pb2.DESCRIPTOR.serialized_pb))
+ self.pool.Add(descriptor_pb2.FileDescriptorProto.FromString(
+ unittest_pb2.DESCRIPTOR.serialized_pb))
+
+
+class SecondaryDescriptorFromDescriptorDB(DescriptorPoolTestBase,
+ unittest.TestCase):
+
+ def setUp(self):
+ self.factory_test1_fd = descriptor_pb2.FileDescriptorProto.FromString(
+ factory_test1_pb2.DESCRIPTOR.serialized_pb)
+ self.factory_test2_fd = descriptor_pb2.FileDescriptorProto.FromString(
+ factory_test2_pb2.DESCRIPTOR.serialized_pb)
+ db = descriptor_database.DescriptorDatabase()
+ db.Add(self.factory_test1_fd)
+ db.Add(self.factory_test2_fd)
+ db.Add(descriptor_pb2.FileDescriptorProto.FromString(
+ unittest_import_public_pb2.DESCRIPTOR.serialized_pb))
+ db.Add(descriptor_pb2.FileDescriptorProto.FromString(
+ unittest_import_pb2.DESCRIPTOR.serialized_pb))
+ db.Add(descriptor_pb2.FileDescriptorProto.FromString(
+ unittest_pb2.DESCRIPTOR.serialized_pb))
+ self.pool = descriptor_pool.DescriptorPool(descriptor_db=db)
+
class ProtoFile(object):
@@ -472,10 +636,10 @@ class MessageType(object):
subtype.CheckType(test, desc, name, file_desc)
for index, (name, field) in enumerate(self.field_list):
- field.CheckField(test, desc, name, index)
+ field.CheckField(test, desc, name, index, file_desc)
for index, (name, field) in enumerate(self.extensions):
- field.CheckField(test, desc, name, index)
+ field.CheckField(test, desc, name, index, file_desc)
class EnumField(object):
@@ -485,7 +649,7 @@ class EnumField(object):
self.type_name = type_name
self.default_value = default_value
- def CheckField(self, test, msg_desc, name, index):
+ def CheckField(self, test, msg_desc, name, index, file_desc):
field_desc = msg_desc.fields_by_name[name]
enum_desc = msg_desc.enum_types_by_name[self.type_name]
test.assertEqual(name, field_desc.name)
@@ -502,6 +666,7 @@ class EnumField(object):
test.assertFalse(enum_desc.values_by_name[self.default_value].has_options)
test.assertEqual(msg_desc, field_desc.containing_type)
test.assertEqual(enum_desc, field_desc.enum_type)
+ test.assertEqual(file_desc, enum_desc.file)
class MessageField(object):
@@ -510,7 +675,7 @@ class MessageField(object):
self.number = number
self.type_name = type_name
- def CheckField(self, test, msg_desc, name, index):
+ def CheckField(self, test, msg_desc, name, index, file_desc):
field_desc = msg_desc.fields_by_name[name]
field_type_desc = msg_desc.nested_types_by_name[self.type_name]
test.assertEqual(name, field_desc.name)
@@ -524,6 +689,12 @@ class MessageField(object):
test.assertFalse(field_desc.has_default_value)
test.assertEqual(msg_desc, field_desc.containing_type)
test.assertEqual(field_type_desc, field_desc.message_type)
+ test.assertEqual(file_desc, field_desc.file)
+ # TODO(jieluo): Fix python and cpp extension diff for message field
+ # default value.
+ if api_implementation.Type() == 'cpp':
+ test.assertRaises(
+ NotImplementedError, getattr, field_desc, 'default_value')
class StringField(object):
@@ -532,7 +703,7 @@ class StringField(object):
self.number = number
self.default_value = default_value
- def CheckField(self, test, msg_desc, name, index):
+ def CheckField(self, test, msg_desc, name, index, file_desc):
field_desc = msg_desc.fields_by_name[name]
test.assertEqual(name, field_desc.name)
expected_field_full_name = '.'.join([msg_desc.full_name, name])
@@ -544,6 +715,7 @@ class StringField(object):
field_desc.cpp_type)
test.assertTrue(field_desc.has_default_value)
test.assertEqual(self.default_value, field_desc.default_value)
+ test.assertEqual(file_desc, field_desc.file)
class ExtensionField(object):
@@ -552,7 +724,7 @@ class ExtensionField(object):
self.number = number
self.extended_type = extended_type
- def CheckField(self, test, msg_desc, name, index):
+ def CheckField(self, test, msg_desc, name, index, file_desc):
field_desc = msg_desc.extensions_by_name[name]
test.assertEqual(name, field_desc.name)
expected_field_full_name = '.'.join([msg_desc.full_name, name])
@@ -567,6 +739,7 @@ class ExtensionField(object):
test.assertEqual(msg_desc, field_desc.extension_scope)
test.assertEqual(msg_desc, field_desc.message_type)
test.assertEqual(self.extended_type, field_desc.containing_type.name)
+ test.assertEqual(file_desc, field_desc.file)
class AddDescriptorTest(unittest.TestCase):
@@ -645,6 +818,17 @@ class AddDescriptorTest(unittest.TestCase):
@unittest.skipIf(api_implementation.Type() == 'cpp',
'With the cpp implementation, Add() must be called first')
+ def testService(self):
+ pool = descriptor_pool.DescriptorPool()
+ with self.assertRaises(KeyError):
+ pool.FindServiceByName('protobuf_unittest.TestService')
+ pool.AddServiceDescriptor(unittest_pb2._TESTSERVICE)
+ self.assertEqual(
+ 'protobuf_unittest.TestService',
+ pool.FindServiceByName('protobuf_unittest.TestService').full_name)
+
+ @unittest.skipIf(api_implementation.Type() == 'cpp',
+ 'With the cpp implementation, Add() must be called first')
def testFile(self):
pool = descriptor_pool.DescriptorPool()
pool.AddFileDescriptor(unittest_pb2.DESCRIPTOR)
@@ -682,6 +866,25 @@ class AddDescriptorTest(unittest.TestCase):
'some/file.proto')
self.assertEqual(pool.FindMessageTypeByName('package.Message').name,
'Message')
+ # Test no package
+ file_proto = descriptor_pb2.FileDescriptorProto(
+ name='some/filename/container.proto')
+ message_proto = file_proto.message_type.add(
+ name='TopMessage')
+ message_proto.field.add(
+ name='bb',
+ number=1,
+ type=descriptor_pb2.FieldDescriptorProto.TYPE_INT32,
+ label=descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL)
+ enum_proto = file_proto.enum_type.add(name='TopEnum')
+ enum_proto.value.add(name='FOREIGN_FOO', number=4)
+ file_proto.service.add(name='TopService')
+ pool = descriptor_pool.DescriptorPool()
+ pool.Add(file_proto)
+ self.assertEqual('TopMessage',
+ pool.FindMessageTypeByName('TopMessage').name)
+ self.assertEqual('TopEnum', pool.FindEnumTypeByName('TopEnum').name)
+ self.assertEqual('TopService', pool.FindServiceByName('TopService').name)
def testFileDescriptorOptionsWithCustomDescriptorPool(self):
# Create a descriptor pool, and add a new FileDescriptorProto to it.
@@ -700,42 +903,18 @@ class AddDescriptorTest(unittest.TestCase):
# The object returned by GetOptions() is cached.
self.assertIs(options, file_descriptor.GetOptions())
-
-@unittest.skipIf(
- api_implementation.Type() != 'cpp',
- 'default_pool is only supported by the C++ implementation')
-class DefaultPoolTest(unittest.TestCase):
-
- def testFindMethods(self):
- # pylint: disable=g-import-not-at-top
- from google.protobuf.pyext import _message
- pool = _message.default_pool
- self.assertIs(
- pool.FindFileByName('google/protobuf/unittest.proto'),
- unittest_pb2.DESCRIPTOR)
- self.assertIs(
- pool.FindMessageTypeByName('protobuf_unittest.TestAllTypes'),
- unittest_pb2.TestAllTypes.DESCRIPTOR)
- self.assertIs(
- pool.FindFieldByName('protobuf_unittest.TestAllTypes.optional_int32'),
- unittest_pb2.TestAllTypes.DESCRIPTOR.fields_by_name['optional_int32'])
- self.assertIs(
- pool.FindExtensionByName('protobuf_unittest.optional_int32_extension'),
- unittest_pb2.DESCRIPTOR.extensions_by_name['optional_int32_extension'])
- self.assertIs(
- pool.FindEnumTypeByName('protobuf_unittest.ForeignEnum'),
- unittest_pb2.ForeignEnum.DESCRIPTOR)
- self.assertIs(
- pool.FindOneofByName('protobuf_unittest.TestAllTypes.oneof_field'),
- unittest_pb2.TestAllTypes.DESCRIPTOR.oneofs_by_name['oneof_field'])
-
- def testAddFileDescriptor(self):
- # pylint: disable=g-import-not-at-top
- from google.protobuf.pyext import _message
- pool = _message.default_pool
- file_desc = descriptor_pb2.FileDescriptorProto(name='some/file.proto')
- pool.Add(file_desc)
- pool.AddSerializedFile(file_desc.SerializeToString())
+ def testAddTypeError(self):
+ pool = descriptor_pool.DescriptorPool()
+ with self.assertRaises(TypeError):
+ pool.AddDescriptor(0)
+ with self.assertRaises(TypeError):
+ pool.AddEnumDescriptor(0)
+ with self.assertRaises(TypeError):
+ pool.AddServiceDescriptor(0)
+ with self.assertRaises(TypeError):
+ pool.AddExtensionDescriptor(0)
+ with self.assertRaises(TypeError):
+ pool.AddFileDescriptor(0)
TEST1_FILE = ProtoFile(
diff --git a/python/google/protobuf/internal/descriptor_test.py b/python/google/protobuf/internal/descriptor_test.py
index 1f148ab9..f1d5934e 100755
--- a/python/google/protobuf/internal/descriptor_test.py
+++ b/python/google/protobuf/internal/descriptor_test.py
@@ -107,6 +107,12 @@ class DescriptorTest(unittest.TestCase):
self.my_message.enum_types_by_name[
'ForeignEnum'].values_by_number[4].name,
self.my_message.EnumValueName('ForeignEnum', 4))
+ with self.assertRaises(KeyError):
+ self.my_message.EnumValueName('ForeignEnum', 999)
+ with self.assertRaises(KeyError):
+ self.my_message.EnumValueName('NoneEnum', 999)
+ with self.assertRaises(TypeError):
+ self.my_message.EnumValueName()
def testEnumFixups(self):
self.assertEqual(self.my_enum, self.my_enum.values[0].type)
@@ -134,15 +140,17 @@ class DescriptorTest(unittest.TestCase):
def testSimpleCustomOptions(self):
file_descriptor = unittest_custom_options_pb2.DESCRIPTOR
- message_descriptor =\
- unittest_custom_options_pb2.TestMessageWithCustomOptions.DESCRIPTOR
+ message_descriptor = (unittest_custom_options_pb2.
+ TestMessageWithCustomOptions.DESCRIPTOR)
field_descriptor = message_descriptor.fields_by_name['field1']
oneof_descriptor = message_descriptor.oneofs_by_name['AnOneof']
enum_descriptor = message_descriptor.enum_types_by_name['AnEnum']
- enum_value_descriptor =\
- message_descriptor.enum_values_by_name['ANENUM_VAL2']
- service_descriptor =\
- unittest_custom_options_pb2.TestServiceWithCustomOptions.DESCRIPTOR
+ enum_value_descriptor = (message_descriptor.
+ enum_values_by_name['ANENUM_VAL2'])
+ other_enum_value_descriptor = (message_descriptor.
+ enum_values_by_name['ANENUM_VAL1'])
+ service_descriptor = (unittest_custom_options_pb2.
+ TestServiceWithCustomOptions.DESCRIPTOR)
method_descriptor = service_descriptor.FindMethodByName('Foo')
file_options = file_descriptor.GetOptions()
@@ -178,6 +186,11 @@ class DescriptorTest(unittest.TestCase):
unittest_custom_options_pb2.DummyMessageContainingEnum.DESCRIPTOR)
self.assertTrue(file_descriptor.has_options)
self.assertFalse(message_descriptor.has_options)
+ self.assertTrue(field_descriptor.has_options)
+ self.assertTrue(oneof_descriptor.has_options)
+ self.assertTrue(enum_descriptor.has_options)
+ self.assertTrue(enum_value_descriptor.has_options)
+ self.assertFalse(other_enum_value_descriptor.has_options)
def testDifferentCustomOptionTypes(self):
kint32min = -2**31
@@ -400,6 +413,12 @@ class DescriptorTest(unittest.TestCase):
self.assertEqual(self.my_file.name, 'some/filename/some.proto')
self.assertEqual(self.my_file.package, 'protobuf_unittest')
self.assertEqual(self.my_file.pool, self.pool)
+ self.assertFalse(self.my_file.has_options)
+ self.assertEqual('proto2', self.my_file.syntax)
+ file_proto = descriptor_pb2.FileDescriptorProto()
+ self.my_file.CopyToProto(file_proto)
+ self.assertEqual(self.my_file.serialized_pb,
+ file_proto.SerializeToString())
# Generated modules also belong to the default pool.
self.assertEqual(unittest_pb2.DESCRIPTOR.pool, descriptor_pool.Default())
@@ -407,13 +426,31 @@ class DescriptorTest(unittest.TestCase):
api_implementation.Type() != 'cpp' or api_implementation.Version() != 2,
'Immutability of descriptors is only enforced in v2 implementation')
def testImmutableCppDescriptor(self):
+ file_descriptor = unittest_pb2.DESCRIPTOR
message_descriptor = unittest_pb2.TestAllTypes.DESCRIPTOR
+ field_descriptor = message_descriptor.fields_by_name['optional_int32']
+ enum_descriptor = message_descriptor.enum_types_by_name['NestedEnum']
+ oneof_descriptor = message_descriptor.oneofs_by_name['oneof_field']
with self.assertRaises(AttributeError):
message_descriptor.fields_by_name = None
with self.assertRaises(TypeError):
message_descriptor.fields_by_name['Another'] = None
with self.assertRaises(TypeError):
message_descriptor.fields.append(None)
+ with self.assertRaises(AttributeError):
+ field_descriptor.containing_type = message_descriptor
+ with self.assertRaises(AttributeError):
+ file_descriptor.has_options = False
+ with self.assertRaises(AttributeError):
+ field_descriptor.has_options = False
+ with self.assertRaises(AttributeError):
+ oneof_descriptor.has_options = False
+ with self.assertRaises(AttributeError):
+ enum_descriptor.has_options = False
+ with self.assertRaises(AttributeError) as e:
+ message_descriptor.has_options = True
+ self.assertEqual('attribute is not writable: has_options',
+ str(e.exception))
class NewDescriptorTest(DescriptorTest):
@@ -442,6 +479,12 @@ class GeneratedDescriptorTest(unittest.TestCase):
self.CheckDescriptorMapping(message_descriptor.fields_by_name)
self.CheckDescriptorMapping(message_descriptor.fields_by_number)
self.CheckDescriptorMapping(message_descriptor.fields_by_camelcase_name)
+ self.CheckDescriptorMapping(message_descriptor.enum_types_by_name)
+ self.CheckDescriptorMapping(message_descriptor.enum_values_by_name)
+ self.CheckDescriptorMapping(message_descriptor.oneofs_by_name)
+ self.CheckDescriptorMapping(message_descriptor.enum_types[0].values_by_name)
+ # Test extension range
+ self.assertEqual(message_descriptor.extension_ranges, [])
def CheckFieldDescriptor(self, field_descriptor):
# Basic properties
@@ -450,6 +493,7 @@ class GeneratedDescriptorTest(unittest.TestCase):
self.assertEqual(field_descriptor.full_name,
'protobuf_unittest.TestAllTypes.optional_int32')
self.assertEqual(field_descriptor.containing_type.name, 'TestAllTypes')
+ self.assertEqual(field_descriptor.file, unittest_pb2.DESCRIPTOR)
# Test equality and hashability
self.assertEqual(field_descriptor, field_descriptor)
self.assertEqual(
@@ -461,32 +505,73 @@ class GeneratedDescriptorTest(unittest.TestCase):
field_descriptor)
self.assertIn(field_descriptor, [field_descriptor])
self.assertIn(field_descriptor, {field_descriptor: None})
+ self.assertEqual(None, field_descriptor.extension_scope)
+ self.assertEqual(None, field_descriptor.enum_type)
+ if api_implementation.Type() == 'cpp':
+ # For test coverage only
+ self.assertEqual(field_descriptor.id, field_descriptor.id)
def CheckDescriptorSequence(self, sequence):
# Verifies that a property like 'messageDescriptor.fields' has all the
# properties of an immutable abc.Sequence.
+ self.assertNotEqual(sequence,
+ unittest_pb2.TestAllExtensions.DESCRIPTOR.fields)
+ self.assertNotEqual(sequence, [])
+ self.assertNotEqual(sequence, 1)
+ self.assertFalse(sequence == 1) # Only for cpp test coverage
+ self.assertEqual(sequence, sequence)
+ expected_list = list(sequence)
+ self.assertEqual(expected_list, sequence)
self.assertGreater(len(sequence), 0) # Sized
- self.assertEqual(len(sequence), len(list(sequence))) # Iterable
+ self.assertEqual(len(sequence), len(expected_list)) # Iterable
+ self.assertEqual(sequence[len(sequence) -1], sequence[-1])
item = sequence[0]
self.assertEqual(item, sequence[0])
self.assertIn(item, sequence) # Container
self.assertEqual(sequence.index(item), 0)
self.assertEqual(sequence.count(item), 1)
+ other_item = unittest_pb2.NestedTestAllTypes.DESCRIPTOR.fields[0]
+ self.assertNotIn(other_item, sequence)
+ self.assertEqual(sequence.count(other_item), 0)
+ self.assertRaises(ValueError, sequence.index, other_item)
+ self.assertRaises(ValueError, sequence.index, [])
reversed_iterator = reversed(sequence)
self.assertEqual(list(reversed_iterator), list(sequence)[::-1])
self.assertRaises(StopIteration, next, reversed_iterator)
+ expected_list[0] = 'change value'
+ self.assertNotEqual(expected_list, sequence)
+ # TODO(jieluo): Change __repr__ support for DescriptorSequence.
+ if api_implementation.Type() == 'python':
+ self.assertEqual(str(list(sequence)), str(sequence))
+ else:
+ self.assertEqual(str(sequence)[0], '<')
def CheckDescriptorMapping(self, mapping):
# Verifies that a property like 'messageDescriptor.fields' has all the
# properties of an immutable abc.Mapping.
+ self.assertNotEqual(
+ mapping, unittest_pb2.TestAllExtensions.DESCRIPTOR.fields_by_name)
+ self.assertNotEqual(mapping, {})
+ self.assertNotEqual(mapping, 1)
+ self.assertFalse(mapping == 1) # Only for cpp test coverage
+ excepted_dict = dict(mapping.items())
+ self.assertEqual(mapping, excepted_dict)
+ self.assertEqual(mapping, mapping)
self.assertGreater(len(mapping), 0) # Sized
- self.assertEqual(len(mapping), len(list(mapping))) # Iterable
+ self.assertEqual(len(mapping), len(excepted_dict)) # Iterable
if sys.version_info >= (3,):
key, item = next(iter(mapping.items()))
else:
key, item = mapping.items()[0]
self.assertIn(key, mapping) # Container
self.assertEqual(mapping.get(key), item)
+ with self.assertRaises(TypeError):
+ mapping.get()
+ # TODO(jieluo): Fix python and cpp extension diff.
+ if api_implementation.Type() == 'python':
+ self.assertRaises(TypeError, mapping.get, [])
+ else:
+ self.assertEqual(None, mapping.get([]))
# keys(), iterkeys() &co
item = (next(iter(mapping.keys())), next(iter(mapping.values())))
self.assertEqual(item, next(iter(mapping.items())))
@@ -497,6 +582,18 @@ class GeneratedDescriptorTest(unittest.TestCase):
CheckItems(mapping.keys(), mapping.iterkeys())
CheckItems(mapping.values(), mapping.itervalues())
CheckItems(mapping.items(), mapping.iteritems())
+ excepted_dict[key] = 'change value'
+ self.assertNotEqual(mapping, excepted_dict)
+ del excepted_dict[key]
+ excepted_dict['new_key'] = 'new'
+ self.assertNotEqual(mapping, excepted_dict)
+ self.assertRaises(KeyError, mapping.__getitem__, 'key_error')
+ self.assertRaises(KeyError, mapping.__getitem__, len(mapping) + 1)
+ # TODO(jieluo): Add __repr__ support for DescriptorMapping.
+ if api_implementation.Type() == 'python':
+ self.assertEqual(len(str(dict(mapping.items()))), len(str(mapping)))
+ else:
+ self.assertEqual(str(mapping)[0], '<')
def testDescriptor(self):
message_descriptor = unittest_pb2.TestAllTypes.DESCRIPTOR
@@ -506,13 +603,26 @@ class GeneratedDescriptorTest(unittest.TestCase):
field_descriptor = message_descriptor.fields_by_camelcase_name[
'optionalInt32']
self.CheckFieldDescriptor(field_descriptor)
+ enum_descriptor = unittest_pb2.DESCRIPTOR.enum_types_by_name[
+ 'ForeignEnum']
+ self.assertEqual(None, enum_descriptor.containing_type)
+ # Test extension range
+ self.assertEqual(
+ unittest_pb2.TestAllExtensions.DESCRIPTOR.extension_ranges,
+ [(1, 536870912)])
+ self.assertEqual(
+ unittest_pb2.TestMultipleExtensionRanges.DESCRIPTOR.extension_ranges,
+ [(42, 43), (4143, 4244), (65536, 536870912)])
def testCppDescriptorContainer(self):
- # Check that the collection is still valid even if the parent disappeared.
- enum = unittest_pb2.TestAllTypes.DESCRIPTOR.enum_types_by_name['NestedEnum']
- values = enum.values
- del enum
- self.assertEqual('FOO', values[0].name)
+ containing_file = unittest_pb2.DESCRIPTOR
+ self.CheckDescriptorSequence(containing_file.dependencies)
+ self.CheckDescriptorMapping(containing_file.message_types_by_name)
+ self.CheckDescriptorMapping(containing_file.enum_types_by_name)
+ self.CheckDescriptorMapping(containing_file.services_by_name)
+ self.CheckDescriptorMapping(containing_file.extensions_by_name)
+ self.CheckDescriptorMapping(
+ unittest_pb2.TestNestedExtension.DESCRIPTOR.extensions_by_name)
def testCppDescriptorContainer_Iterator(self):
# Same test with the iterator
@@ -521,6 +631,24 @@ class GeneratedDescriptorTest(unittest.TestCase):
del enum
self.assertEqual('FOO', next(values_iter).name)
+ def testServiceDescriptor(self):
+ service_descriptor = unittest_pb2.DESCRIPTOR.services_by_name['TestService']
+ self.assertEqual(service_descriptor.name, 'TestService')
+ self.assertEqual(service_descriptor.methods[0].name, 'Foo')
+ self.assertIs(service_descriptor.file, unittest_pb2.DESCRIPTOR)
+ self.assertEqual(service_descriptor.index, 0)
+ self.CheckDescriptorMapping(service_descriptor.methods_by_name)
+
+ def testOneofDescriptor(self):
+ message_descriptor = unittest_pb2.TestAllTypes.DESCRIPTOR
+ oneof_descriptor = message_descriptor.oneofs_by_name['oneof_field']
+ self.assertFalse(oneof_descriptor.has_options)
+ self.assertEqual(message_descriptor, oneof_descriptor.containing_type)
+ self.assertEqual('oneof_field', oneof_descriptor.name)
+ self.assertEqual('protobuf_unittest.TestAllTypes.oneof_field',
+ oneof_descriptor.full_name)
+ self.assertEqual(0, oneof_descriptor.index)
+
class DescriptorCopyToProtoTest(unittest.TestCase):
"""Tests for CopyTo functions of Descriptor."""
@@ -657,49 +785,64 @@ class DescriptorCopyToProtoTest(unittest.TestCase):
descriptor_pb2.DescriptorProto,
TEST_MESSAGE_WITH_SEVERAL_EXTENSIONS_ASCII)
- # Disable this test so we can make changes to the proto file.
- # TODO(xiaofeng): Enable this test after cl/55530659 is submitted.
- #
- # def testCopyToProto_FileDescriptor(self):
- # UNITTEST_IMPORT_FILE_DESCRIPTOR_ASCII = ("""
- # name: 'google/protobuf/unittest_import.proto'
- # package: 'protobuf_unittest_import'
- # dependency: 'google/protobuf/unittest_import_public.proto'
- # message_type: <
- # name: 'ImportMessage'
- # field: <
- # name: 'd'
- # number: 1
- # label: 1 # Optional
- # type: 5 # TYPE_INT32
- # >
- # >
- # """ +
- # """enum_type: <
- # name: 'ImportEnum'
- # value: <
- # name: 'IMPORT_FOO'
- # number: 7
- # >
- # value: <
- # name: 'IMPORT_BAR'
- # number: 8
- # >
- # value: <
- # name: 'IMPORT_BAZ'
- # number: 9
- # >
- # >
- # options: <
- # java_package: 'com.google.protobuf.test'
- # optimize_for: 1 # SPEED
- # >
- # public_dependency: 0
- # """)
- # self._InternalTestCopyToProto(
- # unittest_import_pb2.DESCRIPTOR,
- # descriptor_pb2.FileDescriptorProto,
- # UNITTEST_IMPORT_FILE_DESCRIPTOR_ASCII)
+ def testCopyToProto_FileDescriptor(self):
+ UNITTEST_IMPORT_FILE_DESCRIPTOR_ASCII = ("""
+ name: 'google/protobuf/unittest_import.proto'
+ package: 'protobuf_unittest_import'
+ dependency: 'google/protobuf/unittest_import_public.proto'
+ message_type: <
+ name: 'ImportMessage'
+ field: <
+ name: 'd'
+ number: 1
+ label: 1 # Optional
+ type: 5 # TYPE_INT32
+ >
+ >
+ """ +
+ """enum_type: <
+ name: 'ImportEnum'
+ value: <
+ name: 'IMPORT_FOO'
+ number: 7
+ >
+ value: <
+ name: 'IMPORT_BAR'
+ number: 8
+ >
+ value: <
+ name: 'IMPORT_BAZ'
+ number: 9
+ >
+ >
+ enum_type: <
+ name: 'ImportEnumForMap'
+ value: <
+ name: 'UNKNOWN'
+ number: 0
+ >
+ value: <
+ name: 'FOO'
+ number: 1
+ >
+ value: <
+ name: 'BAR'
+ number: 2
+ >
+ >
+ options: <
+ java_package: 'com.google.protobuf.test'
+ optimize_for: 1 # SPEED
+ """ +
+ """
+ cc_enable_arenas: true
+ >
+ public_dependency: 0
+ """)
+ self._InternalTestCopyToProto(
+ unittest_import_pb2.DESCRIPTOR,
+ descriptor_pb2.FileDescriptorProto,
+ UNITTEST_IMPORT_FILE_DESCRIPTOR_ASCII)
def testCopyToProto_ServiceDescriptor(self):
TEST_SERVICE_ASCII = """
@@ -715,12 +858,47 @@ class DescriptorCopyToProtoTest(unittest.TestCase):
output_type: '.protobuf_unittest.BarResponse'
>
"""
- # TODO(rocking): enable this test after the proto descriptor change is
- # checked in.
- #self._InternalTestCopyToProto(
- # unittest_pb2.TestService.DESCRIPTOR,
- # descriptor_pb2.ServiceDescriptorProto,
- # TEST_SERVICE_ASCII)
+ self._InternalTestCopyToProto(
+ unittest_pb2.TestService.DESCRIPTOR,
+ descriptor_pb2.ServiceDescriptorProto,
+ TEST_SERVICE_ASCII)
+
+ @unittest.skipIf(
+ api_implementation.Type() == 'python',
+ 'It is not implemented in python.')
+ # TODO(jieluo): Add support for pure python or remove in c extension.
+ def testCopyToProto_MethodDescriptor(self):
+ expected_ascii = """
+ name: 'Foo'
+ input_type: '.protobuf_unittest.FooRequest'
+ output_type: '.protobuf_unittest.FooResponse'
+ """
+ method_descriptor = unittest_pb2.TestService.DESCRIPTOR.FindMethodByName(
+ 'Foo')
+ self._InternalTestCopyToProto(
+ method_descriptor,
+ descriptor_pb2.MethodDescriptorProto,
+ expected_ascii)
+
+ @unittest.skipIf(
+ api_implementation.Type() == 'python',
+ 'Pure python does not raise error.')
+ # TODO(jieluo): Fix pure python to check with the proto type.
+ def testCopyToProto_TypeError(self):
+ file_proto = descriptor_pb2.FileDescriptorProto()
+ self.assertRaises(TypeError,
+ unittest_pb2.TestEmptyMessage.DESCRIPTOR.CopyToProto,
+ file_proto)
+ self.assertRaises(TypeError,
+ unittest_pb2.ForeignEnum.DESCRIPTOR.CopyToProto,
+ file_proto)
+ self.assertRaises(TypeError,
+ unittest_pb2.TestService.DESCRIPTOR.CopyToProto,
+ file_proto)
+ proto = descriptor_pb2.DescriptorProto()
+ self.assertRaises(TypeError,
+ unittest_import_pb2.DESCRIPTOR.CopyToProto,
+ proto)
class MakeDescriptorTest(unittest.TestCase):
@@ -768,6 +946,9 @@ class MakeDescriptorTest(unittest.TestCase):
result.nested_types[0].enum_types[0])
self.assertFalse(result.has_options)
self.assertFalse(result.fields[0].has_options)
+ if api_implementation.Type() == 'cpp':
+ with self.assertRaises(AttributeError):
+ result.fields[0].has_options = False
def testMakeDescriptorWithUnsignedIntField(self):
file_descriptor_proto = descriptor_pb2.FileDescriptorProto()
diff --git a/python/google/protobuf/internal/encoder.py b/python/google/protobuf/internal/encoder.py
index 48ef2df3..40c62d67 100755
--- a/python/google/protobuf/internal/encoder.py
+++ b/python/google/protobuf/internal/encoder.py
@@ -340,7 +340,7 @@ def MessageSetItemSizer(field_number):
# Map is special: it needs custom logic to compute its size properly.
-def MapSizer(field_descriptor):
+def MapSizer(field_descriptor, is_message_map):
"""Returns a sizer for a map field."""
# Can't look at field_descriptor.message_type._concrete_class because it may
@@ -355,9 +355,12 @@ def MapSizer(field_descriptor):
# It's wasteful to create the messages and throw them away one second
# later since we'll do the same for the actual encode. But there's not an
# obvious way to avoid this within the current design without tons of code
- # duplication.
+ # duplication. For message map, value.ByteSize() should be called to
+ # update the status.
entry_msg = message_type._concrete_class(key=key, value=value)
total += message_sizer(entry_msg)
+ if is_message_map:
+ value.ByteSize()
return total
return FieldSize
@@ -369,7 +372,7 @@ def MapSizer(field_descriptor):
def _VarintEncoder():
"""Return an encoder for a basic varint value (does not include tag)."""
- def EncodeVarint(write, value):
+ def EncodeVarint(write, value, unused_deterministic):
bits = value & 0x7f
value >>= 7
while value:
@@ -385,7 +388,7 @@ def _SignedVarintEncoder():
"""Return an encoder for a basic signed varint value (does not include
tag)."""
- def EncodeSignedVarint(write, value):
+ def EncodeSignedVarint(write, value, unused_deterministic):
if value < 0:
value += (1 << 64)
bits = value & 0x7f
@@ -408,14 +411,14 @@ def _VarintBytes(value):
called at startup time so it doesn't need to be fast."""
pieces = []
- _EncodeVarint(pieces.append, value)
+ _EncodeVarint(pieces.append, value, True)
return b"".join(pieces)
def TagBytes(field_number, wire_type):
"""Encode the given tag and return the bytes. Only called at startup."""
- return _VarintBytes(wire_format.PackTag(field_number, wire_type))
+ return six.binary_type( _VarintBytes(wire_format.PackTag(field_number, wire_type)) )
# --------------------------------------------------------------------
# As with sizers (see above), we have a number of common encoder
@@ -437,27 +440,27 @@ def _SimpleEncoder(wire_type, encode_value, compute_value_size):
if is_packed:
tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
local_EncodeVarint = _EncodeVarint
- def EncodePackedField(write, value):
+ def EncodePackedField(write, value, deterministic):
write(tag_bytes)
size = 0
for element in value:
size += compute_value_size(element)
- local_EncodeVarint(write, size)
+ local_EncodeVarint(write, size, deterministic)
for element in value:
- encode_value(write, element)
+ encode_value(write, element, deterministic)
return EncodePackedField
elif is_repeated:
tag_bytes = TagBytes(field_number, wire_type)
- def EncodeRepeatedField(write, value):
+ def EncodeRepeatedField(write, value, deterministic):
for element in value:
write(tag_bytes)
- encode_value(write, element)
+ encode_value(write, element, deterministic)
return EncodeRepeatedField
else:
tag_bytes = TagBytes(field_number, wire_type)
- def EncodeField(write, value):
+ def EncodeField(write, value, deterministic):
write(tag_bytes)
- return encode_value(write, value)
+ return encode_value(write, value, deterministic)
return EncodeField
return SpecificEncoder
@@ -471,27 +474,27 @@ def _ModifiedEncoder(wire_type, encode_value, compute_value_size, modify_value):
if is_packed:
tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
local_EncodeVarint = _EncodeVarint
- def EncodePackedField(write, value):
+ def EncodePackedField(write, value, deterministic):
write(tag_bytes)
size = 0
for element in value:
size += compute_value_size(modify_value(element))
- local_EncodeVarint(write, size)
+ local_EncodeVarint(write, size, deterministic)
for element in value:
- encode_value(write, modify_value(element))
+ encode_value(write, modify_value(element), deterministic)
return EncodePackedField
elif is_repeated:
tag_bytes = TagBytes(field_number, wire_type)
- def EncodeRepeatedField(write, value):
+ def EncodeRepeatedField(write, value, deterministic):
for element in value:
write(tag_bytes)
- encode_value(write, modify_value(element))
+ encode_value(write, modify_value(element), deterministic)
return EncodeRepeatedField
else:
tag_bytes = TagBytes(field_number, wire_type)
- def EncodeField(write, value):
+ def EncodeField(write, value, deterministic):
write(tag_bytes)
- return encode_value(write, modify_value(value))
+ return encode_value(write, modify_value(value), deterministic)
return EncodeField
return SpecificEncoder
@@ -512,22 +515,22 @@ def _StructPackEncoder(wire_type, format):
if is_packed:
tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
local_EncodeVarint = _EncodeVarint
- def EncodePackedField(write, value):
+ def EncodePackedField(write, value, deterministic):
write(tag_bytes)
- local_EncodeVarint(write, len(value) * value_size)
+ local_EncodeVarint(write, len(value) * value_size, deterministic)
for element in value:
write(local_struct_pack(format, element))
return EncodePackedField
elif is_repeated:
tag_bytes = TagBytes(field_number, wire_type)
- def EncodeRepeatedField(write, value):
+ def EncodeRepeatedField(write, value, unused_deterministic):
for element in value:
write(tag_bytes)
write(local_struct_pack(format, element))
return EncodeRepeatedField
else:
tag_bytes = TagBytes(field_number, wire_type)
- def EncodeField(write, value):
+ def EncodeField(write, value, unused_deterministic):
write(tag_bytes)
return write(local_struct_pack(format, value))
return EncodeField
@@ -578,9 +581,9 @@ def _FloatingPointEncoder(wire_type, format):
if is_packed:
tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
local_EncodeVarint = _EncodeVarint
- def EncodePackedField(write, value):
+ def EncodePackedField(write, value, deterministic):
write(tag_bytes)
- local_EncodeVarint(write, len(value) * value_size)
+ local_EncodeVarint(write, len(value) * value_size, deterministic)
for element in value:
# This try/except block is going to be faster than any code that
# we could write to check whether element is finite.
@@ -591,7 +594,7 @@ def _FloatingPointEncoder(wire_type, format):
return EncodePackedField
elif is_repeated:
tag_bytes = TagBytes(field_number, wire_type)
- def EncodeRepeatedField(write, value):
+ def EncodeRepeatedField(write, value, unused_deterministic):
for element in value:
write(tag_bytes)
try:
@@ -601,7 +604,7 @@ def _FloatingPointEncoder(wire_type, format):
return EncodeRepeatedField
else:
tag_bytes = TagBytes(field_number, wire_type)
- def EncodeField(write, value):
+ def EncodeField(write, value, unused_deterministic):
write(tag_bytes)
try:
write(local_struct_pack(format, value))
@@ -647,9 +650,9 @@ def BoolEncoder(field_number, is_repeated, is_packed):
if is_packed:
tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
local_EncodeVarint = _EncodeVarint
- def EncodePackedField(write, value):
+ def EncodePackedField(write, value, deterministic):
write(tag_bytes)
- local_EncodeVarint(write, len(value))
+ local_EncodeVarint(write, len(value), deterministic)
for element in value:
if element:
write(true_byte)
@@ -658,7 +661,7 @@ def BoolEncoder(field_number, is_repeated, is_packed):
return EncodePackedField
elif is_repeated:
tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_VARINT)
- def EncodeRepeatedField(write, value):
+ def EncodeRepeatedField(write, value, unused_deterministic):
for element in value:
write(tag_bytes)
if element:
@@ -668,7 +671,7 @@ def BoolEncoder(field_number, is_repeated, is_packed):
return EncodeRepeatedField
else:
tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_VARINT)
- def EncodeField(write, value):
+ def EncodeField(write, value, unused_deterministic):
write(tag_bytes)
if value:
return write(true_byte)
@@ -684,18 +687,18 @@ def StringEncoder(field_number, is_repeated, is_packed):
local_len = len
assert not is_packed
if is_repeated:
- def EncodeRepeatedField(write, value):
+ def EncodeRepeatedField(write, value, deterministic):
for element in value:
encoded = element.encode('utf-8')
write(tag)
- local_EncodeVarint(write, local_len(encoded))
+ local_EncodeVarint(write, local_len(encoded), deterministic)
write(encoded)
return EncodeRepeatedField
else:
- def EncodeField(write, value):
+ def EncodeField(write, value, deterministic):
encoded = value.encode('utf-8')
write(tag)
- local_EncodeVarint(write, local_len(encoded))
+ local_EncodeVarint(write, local_len(encoded), deterministic)
return write(encoded)
return EncodeField
@@ -708,16 +711,16 @@ def BytesEncoder(field_number, is_repeated, is_packed):
local_len = len
assert not is_packed
if is_repeated:
- def EncodeRepeatedField(write, value):
+ def EncodeRepeatedField(write, value, deterministic):
for element in value:
write(tag)
- local_EncodeVarint(write, local_len(element))
+ local_EncodeVarint(write, local_len(element), deterministic)
write(element)
return EncodeRepeatedField
else:
- def EncodeField(write, value):
+ def EncodeField(write, value, deterministic):
write(tag)
- local_EncodeVarint(write, local_len(value))
+ local_EncodeVarint(write, local_len(value), deterministic)
return write(value)
return EncodeField
@@ -729,16 +732,16 @@ def GroupEncoder(field_number, is_repeated, is_packed):
end_tag = TagBytes(field_number, wire_format.WIRETYPE_END_GROUP)
assert not is_packed
if is_repeated:
- def EncodeRepeatedField(write, value):
+ def EncodeRepeatedField(write, value, deterministic):
for element in value:
write(start_tag)
- element._InternalSerialize(write)
+ element._InternalSerialize(write, deterministic)
write(end_tag)
return EncodeRepeatedField
else:
- def EncodeField(write, value):
+ def EncodeField(write, value, deterministic):
write(start_tag)
- value._InternalSerialize(write)
+ value._InternalSerialize(write, deterministic)
return write(end_tag)
return EncodeField
@@ -750,17 +753,17 @@ def MessageEncoder(field_number, is_repeated, is_packed):
local_EncodeVarint = _EncodeVarint
assert not is_packed
if is_repeated:
- def EncodeRepeatedField(write, value):
+ def EncodeRepeatedField(write, value, deterministic):
for element in value:
write(tag)
- local_EncodeVarint(write, element.ByteSize())
- element._InternalSerialize(write)
+ local_EncodeVarint(write, element.ByteSize(), deterministic)
+ element._InternalSerialize(write, deterministic)
return EncodeRepeatedField
else:
- def EncodeField(write, value):
+ def EncodeField(write, value, deterministic):
write(tag)
- local_EncodeVarint(write, value.ByteSize())
- return value._InternalSerialize(write)
+ local_EncodeVarint(write, value.ByteSize(), deterministic)
+ return value._InternalSerialize(write, deterministic)
return EncodeField
@@ -787,10 +790,10 @@ def MessageSetItemEncoder(field_number):
end_bytes = TagBytes(1, wire_format.WIRETYPE_END_GROUP)
local_EncodeVarint = _EncodeVarint
- def EncodeField(write, value):
+ def EncodeField(write, value, deterministic):
write(start_bytes)
- local_EncodeVarint(write, value.ByteSize())
- value._InternalSerialize(write)
+ local_EncodeVarint(write, value.ByteSize(), deterministic)
+ value._InternalSerialize(write, deterministic)
return write(end_bytes)
return EncodeField
@@ -815,9 +818,10 @@ def MapEncoder(field_descriptor):
message_type = field_descriptor.message_type
encode_message = MessageEncoder(field_descriptor.number, False, False)
- def EncodeField(write, value):
- for key in value:
+ def EncodeField(write, value, deterministic):
+ value_keys = sorted(value.keys()) if deterministic else value
+ for key in value_keys:
entry_msg = message_type._concrete_class(key=key, value=value[key])
- encode_message(write, entry_msg)
+ encode_message(write, entry_msg, deterministic)
return EncodeField
diff --git a/python/google/protobuf/internal/factory_test2.proto b/python/google/protobuf/internal/factory_test2.proto
index bb1b54ad..5fcbc5ac 100644
--- a/python/google/protobuf/internal/factory_test2.proto
+++ b/python/google/protobuf/internal/factory_test2.proto
@@ -97,3 +97,8 @@ message MessageWithNestedEnumOnly {
extend Factory1Message {
optional string another_field = 1002;
}
+
+message MessageWithOption {
+ option no_standard_descriptor_accessor = true;
+ optional int32 field1 = 1;
+}
diff --git a/python/google/protobuf/internal/json_format_test.py b/python/google/protobuf/internal/json_format_test.py
index 5ed65622..19182b7f 100644
--- a/python/google/protobuf/internal/json_format_test.py
+++ b/python/google/protobuf/internal/json_format_test.py
@@ -49,6 +49,8 @@ from google.protobuf import field_mask_pb2
from google.protobuf import struct_pb2
from google.protobuf import timestamp_pb2
from google.protobuf import wrappers_pb2
+from google.protobuf import unittest_mset_pb2
+from google.protobuf import unittest_pb2
from google.protobuf.internal import well_known_types
from google.protobuf import json_format
from google.protobuf.util import json_format_proto3_pb2
@@ -158,6 +160,98 @@ class JsonFormatTest(JsonFormatBase):
json_format.Parse(text, parsed_message)
self.assertEqual(message, parsed_message)
+ def testUnknownEnumToJsonAndBack(self):
+ text = '{\n "enumValue": 999\n}'
+ message = json_format_proto3_pb2.TestMessage()
+ message.enum_value = 999
+ self.assertEqual(json_format.MessageToJson(message),
+ text)
+ parsed_message = json_format_proto3_pb2.TestMessage()
+ json_format.Parse(text, parsed_message)
+ self.assertEqual(message, parsed_message)
+
+ def testExtensionToJsonAndBack(self):
+ message = unittest_mset_pb2.TestMessageSetContainer()
+ ext1 = unittest_mset_pb2.TestMessageSetExtension1.message_set_extension
+ ext2 = unittest_mset_pb2.TestMessageSetExtension2.message_set_extension
+ message.message_set.Extensions[ext1].i = 23
+ message.message_set.Extensions[ext2].str = 'foo'
+ message_text = json_format.MessageToJson(
+ message
+ )
+ parsed_message = unittest_mset_pb2.TestMessageSetContainer()
+ json_format.Parse(message_text, parsed_message)
+ self.assertEqual(message, parsed_message)
+
+ def testExtensionErrors(self):
+ self.CheckError('{"[extensionField]": {}}',
+ 'Message type proto3.TestMessage does not have extensions')
+
+ def testExtensionToDictAndBack(self):
+ message = unittest_mset_pb2.TestMessageSetContainer()
+ ext1 = unittest_mset_pb2.TestMessageSetExtension1.message_set_extension
+ ext2 = unittest_mset_pb2.TestMessageSetExtension2.message_set_extension
+ message.message_set.Extensions[ext1].i = 23
+ message.message_set.Extensions[ext2].str = 'foo'
+ message_dict = json_format.MessageToDict(
+ message
+ )
+ parsed_message = unittest_mset_pb2.TestMessageSetContainer()
+ json_format.ParseDict(message_dict, parsed_message)
+ self.assertEqual(message, parsed_message)
+
+ def testExtensionSerializationDictMatchesProto3Spec(self):
+ """See go/proto3-json-spec for spec.
+ """
+ message = unittest_mset_pb2.TestMessageSetContainer()
+ ext1 = unittest_mset_pb2.TestMessageSetExtension1.message_set_extension
+ ext2 = unittest_mset_pb2.TestMessageSetExtension2.message_set_extension
+ message.message_set.Extensions[ext1].i = 23
+ message.message_set.Extensions[ext2].str = 'foo'
+ message_dict = json_format.MessageToDict(
+ message
+ )
+ golden_dict = {
+ 'messageSet': {
+ '[protobuf_unittest.'
+ 'TestMessageSetExtension1.messageSetExtension]': {
+ 'i': 23,
+ },
+ '[protobuf_unittest.'
+ 'TestMessageSetExtension2.messageSetExtension]': {
+ 'str': u'foo',
+ },
+ },
+ }
+ self.assertEqual(golden_dict, message_dict)
+
+
+ def testExtensionSerializationJsonMatchesProto3Spec(self):
+ """See go/proto3-json-spec for spec.
+ """
+ message = unittest_mset_pb2.TestMessageSetContainer()
+ ext1 = unittest_mset_pb2.TestMessageSetExtension1.message_set_extension
+ ext2 = unittest_mset_pb2.TestMessageSetExtension2.message_set_extension
+ message.message_set.Extensions[ext1].i = 23
+ message.message_set.Extensions[ext2].str = 'foo'
+ message_text = json_format.MessageToJson(
+ message
+ )
+ ext1_text = ('protobuf_unittest.TestMessageSetExtension1.'
+ 'messageSetExtension')
+ ext2_text = ('protobuf_unittest.TestMessageSetExtension2.'
+ 'messageSetExtension')
+ golden_text = ('{"messageSet": {'
+ ' "[%s]": {'
+ ' "i": 23'
+ ' },'
+ ' "[%s]": {'
+ ' "str": "foo"'
+ ' }'
+ '}}') % (ext1_text, ext2_text)
+ self.assertEqual(json.loads(golden_text), json.loads(message_text))
+
+
def testJsonEscapeString(self):
message = json_format_proto3_pb2.TestMessage()
if sys.version_info[0] < 3:
@@ -215,7 +309,18 @@ class JsonFormatTest(JsonFormatBase):
self.assertEqual(message.int32_value, 1)
def testMapFields(self):
- message = json_format_proto3_pb2.TestMap()
+ message = json_format_proto3_pb2.TestNestedMap()
+ self.assertEqual(
+ json.loads(json_format.MessageToJson(message, True)),
+ json.loads('{'
+ '"boolMap": {},'
+ '"int32Map": {},'
+ '"int64Map": {},'
+ '"uint32Map": {},'
+ '"uint64Map": {},'
+ '"stringMap": {},'
+ '"mapMap": {}'
+ '}'))
message.bool_map[True] = 1
message.bool_map[False] = 2
message.int32_map[1] = 2
@@ -228,17 +333,19 @@ class JsonFormatTest(JsonFormatBase):
message.uint64_map[2] = 3
message.string_map['1'] = 2
message.string_map['null'] = 3
+ message.map_map['1'].bool_map[True] = 3
self.assertEqual(
- json.loads(json_format.MessageToJson(message, True)),
+ json.loads(json_format.MessageToJson(message, False)),
json.loads('{'
'"boolMap": {"false": 2, "true": 1},'
'"int32Map": {"1": 2, "2": 3},'
'"int64Map": {"1": 2, "2": 3},'
'"uint32Map": {"1": 2, "2": 3},'
'"uint64Map": {"1": 2, "2": 3},'
- '"stringMap": {"1": 2, "null": 3}'
+ '"stringMap": {"1": 2, "null": 3},'
+ '"mapMap": {"1": {"boolMap": {"true": 3}}}'
'}'))
- parsed_message = json_format_proto3_pb2.TestMap()
+ parsed_message = json_format_proto3_pb2.TestNestedMap()
self.CheckParseBack(message, parsed_message)
def testOneofFields(self):
@@ -624,6 +731,9 @@ class JsonFormatTest(JsonFormatBase):
json_format.Parse,
'{"repeatedInt32Value":[1, null]}',
parsed_message)
+ self.CheckError('{"repeatedMessageValue":[null]}',
+ 'Failed to parse repeatedMessageValue field: null is not'
+ ' allowed to be used as an element in a repeated field.')
def testNanFloat(self):
message = json_format_proto3_pb2.TestMessage()
@@ -648,6 +758,16 @@ class JsonFormatTest(JsonFormatBase):
'{"enumValue": "baz"}',
'Failed to parse enumValue field: Invalid enum value baz '
'for enum type proto3.EnumType.')
+ # Proto3 accepts numeric unknown enums.
+ text = '{"enumValue": 12345}'
+ json_format.Parse(text, message)
+ # Proto2 does not accept unknown enums.
+ message = unittest_pb2.TestAllTypes()
+ self.assertRaisesRegexp(
+ json_format.ParseError,
+ 'Failed to parse optionalNestedEnum field: Invalid enum value 12345 '
+ 'for enum type protobuf_unittest.TestAllTypes.NestedEnum.',
+ json_format.Parse, '{"optionalNestedEnum": 12345}', message)
def testParseBadIdentifer(self):
self.CheckError('{int32Value: 1}',
@@ -720,6 +840,11 @@ class JsonFormatTest(JsonFormatBase):
self.CheckError('{"bytesValue": "AQI*"}',
'Failed to parse bytesValue field: Incorrect padding.')
+ def testInvalidRepeated(self):
+ self.CheckError('{"repeatedInt32Value": 12345}',
+ (r'Failed to parse repeatedInt32Value field: repeated field'
+ r' repeatedInt32Value must be in \[\] which is 12345.'))
+
def testInvalidMap(self):
message = json_format_proto3_pb2.TestMap()
text = '{"int32Map": {"null": 2, "2": 3}}'
@@ -745,6 +870,12 @@ class JsonFormatTest(JsonFormatBase):
json_format.ParseError,
'Failed to load JSON: duplicate key a',
json_format.Parse, text, message)
+ text = r'{"stringMap": 0}'
+ self.assertRaisesRegexp(
+ json_format.ParseError,
+ 'Failed to parse stringMap field: Map field string_map must be '
+ 'in a dict which is 0.',
+ json_format.Parse, text, message)
def testInvalidTimestamp(self):
message = json_format_proto3_pb2.TestTimestamp()
@@ -768,7 +899,7 @@ class JsonFormatTest(JsonFormatBase):
text = '{"value": "0000-01-01T00:00:00Z"}'
self.assertRaisesRegexp(
json_format.ParseError,
- 'Failed to parse value field: year is out of range.',
+ 'Failed to parse value field: year (0 )?is out of range.',
json_format.Parse, text, message)
# Time bigger than maxinum time.
message.value.seconds = 253402300800
@@ -832,6 +963,12 @@ class JsonFormatTest(JsonFormatBase):
json_format.MessageToJson(message))
self.assertEqual('{\n "int32_value": 12345\n}',
json_format.MessageToJson(message, False, True))
+ # When including_default_value_fields is True.
+ message = json_format_proto3_pb2.TestTimestamp()
+ self.assertEqual('{\n "repeatedValue": []\n}',
+ json_format.MessageToJson(message, True, False))
+ self.assertEqual('{\n "repeated_value": []\n}',
+ json_format.MessageToJson(message, True, True))
# Parsers accept both original proto field names and lowerCamelCase names.
message = json_format_proto3_pb2.TestMessage()
@@ -840,6 +977,12 @@ class JsonFormatTest(JsonFormatBase):
json_format.Parse('{"int32_value": 12345}', message)
self.assertEqual(12345, message.int32_value)
+ def testIndent(self):
+ message = json_format_proto3_pb2.TestMessage()
+ message.int32_value = 12345
+ self.assertEqual('{\n"int32Value": 12345\n}',
+ json_format.MessageToJson(message, indent=0))
+
def testParseDict(self):
expected = 12345
js_dict = {'int32Value': expected}
@@ -862,6 +1005,22 @@ class JsonFormatTest(JsonFormatBase):
parsed_message = json_format_proto3_pb2.TestCustomJsonName()
self.CheckParseBack(message, parsed_message)
+ def testSortKeys(self):
+ # Testing sort_keys is not perfectly working, as by random luck we could
+ # get the output sorted. We just use a selection of names.
+ message = json_format_proto3_pb2.TestMessage(bool_value=True,
+ int32_value=1,
+ int64_value=3,
+ uint32_value=4,
+ string_value='bla')
+ self.assertEqual(
+ json_format.MessageToJson(message, sort_keys=True),
+ # We use json.dumps() instead of a hardcoded string due to differences
+ # between Python 2 and Python 3.
+ json.dumps({'boolValue': True, 'int32Value': 1, 'int64Value': '3',
+ 'uint32Value': 4, 'stringValue': 'bla'},
+ indent=2, sort_keys=True))
+
if __name__ == '__main__':
unittest.main()
diff --git a/python/google/protobuf/internal/message_factory_test.py b/python/google/protobuf/internal/message_factory_test.py
index 4caa2443..6df52ed2 100644
--- a/python/google/protobuf/internal/message_factory_test.py
+++ b/python/google/protobuf/internal/message_factory_test.py
@@ -40,6 +40,7 @@ except ImportError:
import unittest
from google.protobuf import descriptor_pb2
+from google.protobuf.internal import api_implementation
from google.protobuf.internal import factory_test1_pb2
from google.protobuf.internal import factory_test2_pb2
from google.protobuf import descriptor_database
@@ -106,8 +107,17 @@ class MessageFactoryTest(unittest.TestCase):
def testGetMessages(self):
# performed twice because multiple calls with the same input must be allowed
for _ in range(2):
- messages = message_factory.GetMessages([self.factory_test1_fd,
- self.factory_test2_fd])
+ # GetMessage should work regardless of the order the FileDescriptorProto
+ # are provided. In particular, the function should succeed when the files
+ # are not in the topological order of dependencies.
+
+ # Assuming factory_test2_fd depends on factory_test1_fd.
+ self.assertIn(self.factory_test1_fd.name,
+ self.factory_test2_fd.dependency)
+ # Get messages should work when a file comes before its dependencies:
+ # factory_test2_fd comes before factory_test1_fd.
+ messages = message_factory.GetMessages([self.factory_test2_fd,
+ self.factory_test1_fd])
self.assertTrue(
set(['google.protobuf.python.internal.Factory2Message',
'google.protobuf.python.internal.Factory1Message'],
@@ -130,6 +140,21 @@ class MessageFactoryTest(unittest.TestCase):
msg1.Extensions[ext2] = 'test2'
self.assertEqual('test1', msg1.Extensions[ext1])
self.assertEqual('test2', msg1.Extensions[ext2])
+ self.assertEqual(None,
+ msg1.Extensions._FindExtensionByNumber(12321))
+ if api_implementation.Type() == 'cpp':
+ # TODO(jieluo): Fix len to return the correct value.
+ # self.assertEqual(2, len(msg1.Extensions))
+ self.assertEqual(len(msg1.Extensions), len(msg1.Extensions))
+ self.assertRaises(TypeError,
+ msg1.Extensions._FindExtensionByName, 0)
+ self.assertRaises(TypeError,
+ msg1.Extensions._FindExtensionByNumber, '')
+ else:
+ self.assertEqual(None,
+ msg1.Extensions._FindExtensionByName(0))
+ self.assertEqual(None,
+ msg1.Extensions._FindExtensionByNumber(''))
def testDuplicateExtensionNumber(self):
pool = descriptor_pool.DescriptorPool()
@@ -183,7 +208,14 @@ class MessageFactoryTest(unittest.TestCase):
with self.assertRaises(Exception) as cm:
factory.GetMessages([f.name])
- self.assertIsInstance(cm.exception, (AssertionError, ValueError))
+ self.assertIn(str(cm.exception),
+ ['Extensions '
+ '"google.protobuf.python.internal.Duplicate.extension_field" and'
+ ' "google.protobuf.python.internal.Extension.extension_field"'
+ ' both try to extend message type'
+ ' "google.protobuf.python.internal.Container"'
+ ' with field number 2.',
+ 'Double registration of Extensions'])
if __name__ == '__main__':
diff --git a/python/google/protobuf/internal/message_test.py b/python/google/protobuf/internal/message_test.py
index 9986c0d9..a303b1aa 100755
--- a/python/google/protobuf/internal/message_test.py
+++ b/python/google/protobuf/internal/message_test.py
@@ -51,12 +51,18 @@ import operator
import pickle
import six
import sys
+import warnings
try:
- import unittest2 as unittest #PY26
+ import unittest2 as unittest # PY26
except ImportError:
import unittest
+try:
+ cmp # Python 2
+except NameError:
+ cmp = lambda x, y: (x > y) - (x < y) # Python 3
+from google.protobuf import map_proto2_unittest_pb2
from google.protobuf import map_unittest_pb2
from google.protobuf import unittest_pb2
from google.protobuf import unittest_proto3_arena_pb2
@@ -65,6 +71,7 @@ from google.protobuf import descriptor_pool
from google.protobuf import message_factory
from google.protobuf import text_format
from google.protobuf.internal import api_implementation
+from google.protobuf.internal import encoder
from google.protobuf.internal import packed_field_test_pb2
from google.protobuf.internal import test_util
from google.protobuf.internal import testing_refleaks
@@ -136,6 +143,63 @@ class MessageTest(BaseTestCase):
golden_copy = copy.deepcopy(golden_message)
self.assertEqual(golden_data, golden_copy.SerializeToString())
+ def testParseErrors(self, message_module):
+ msg = message_module.TestAllTypes()
+ self.assertRaises(TypeError, msg.FromString, 0)
+ self.assertRaises(Exception, msg.FromString, '0')
+ # TODO(jieluo): Fix cpp extension to raise error instead of warning.
+ # b/27494216
+ end_tag = encoder.TagBytes(1, 4)
+ if api_implementation.Type() == 'python':
+ with self.assertRaises(message.DecodeError) as context:
+ msg.FromString(end_tag)
+ self.assertEqual('Unexpected end-group tag.', str(context.exception))
+ else:
+ with warnings.catch_warnings(record=True) as w:
+ # Cause all warnings to always be triggered.
+ warnings.simplefilter('always')
+ msg.FromString(end_tag)
+ assert len(w) == 1
+ assert issubclass(w[-1].category, RuntimeWarning)
+ self.assertEqual('Unexpected end-group tag: Not all data was converted',
+ str(w[-1].message))
+
+ def testDeterminismParameters(self, message_module):
+ # This message is always deterministically serialized, even if determinism
+ # is disabled, so we can use it to verify that all the determinism
+ # parameters work correctly.
+ golden_data = (b'\xe2\x02\nOne string'
+ b'\xe2\x02\nTwo string'
+ b'\xe2\x02\nRed string'
+ b'\xe2\x02\x0bBlue string')
+ golden_message = message_module.TestAllTypes()
+ golden_message.repeated_string.extend([
+ 'One string',
+ 'Two string',
+ 'Red string',
+ 'Blue string',
+ ])
+ self.assertEqual(golden_data,
+ golden_message.SerializeToString(deterministic=None))
+ self.assertEqual(golden_data,
+ golden_message.SerializeToString(deterministic=False))
+ self.assertEqual(golden_data,
+ golden_message.SerializeToString(deterministic=True))
+
+ class BadArgError(Exception):
+ pass
+
+ class BadArg(object):
+
+ def __nonzero__(self):
+ raise BadArgError()
+
+ def __bool__(self):
+ raise BadArgError()
+
+ with self.assertRaises(BadArgError):
+ golden_message.SerializeToString(deterministic=BadArg())
+
def testPickleSupport(self, message_module):
golden_data = test_util.GoldenFileData('golden_message')
golden_message = message_module.TestAllTypes()
@@ -377,6 +441,7 @@ class MessageTest(BaseTestCase):
self.assertEqual(message.repeated_int32[0], 1)
self.assertEqual(message.repeated_int32[1], 2)
self.assertEqual(message.repeated_int32[2], 3)
+ self.assertEqual(str(message.repeated_int32), str([1, 2, 3]))
message.repeated_float.append(1.1)
message.repeated_float.append(1.3)
@@ -393,6 +458,7 @@ class MessageTest(BaseTestCase):
self.assertEqual(message.repeated_string[0], 'a')
self.assertEqual(message.repeated_string[1], 'b')
self.assertEqual(message.repeated_string[2], 'c')
+ self.assertEqual(str(message.repeated_string), str([u'a', u'b', u'c']))
message.repeated_bytes.append(b'a')
message.repeated_bytes.append(b'c')
@@ -401,6 +467,7 @@ class MessageTest(BaseTestCase):
self.assertEqual(message.repeated_bytes[0], b'a')
self.assertEqual(message.repeated_bytes[1], b'b')
self.assertEqual(message.repeated_bytes[2], b'c')
+ self.assertEqual(str(message.repeated_bytes), str([b'a', b'b', b'c']))
def testSortingRepeatedScalarFieldsCustomComparator(self, message_module):
"""Check some different types with custom comparator."""
@@ -439,6 +506,8 @@ class MessageTest(BaseTestCase):
self.assertEqual(message.repeated_nested_message[3].bb, 4)
self.assertEqual(message.repeated_nested_message[4].bb, 5)
self.assertEqual(message.repeated_nested_message[5].bb, 6)
+ self.assertEqual(str(message.repeated_nested_message),
+ '[bb: 1\n, bb: 2\n, bb: 3\n, bb: 4\n, bb: 5\n, bb: 6\n]')
def testSortingRepeatedCompositeFieldsStable(self, message_module):
"""Check passing a custom comparator to sort a repeated composite field."""
@@ -564,6 +633,18 @@ class MessageTest(BaseTestCase):
self.assertIsInstance(m.repeated_nested_message,
collections.MutableSequence)
+ def testRepeatedFieldsNotHashable(self, message_module):
+ m = message_module.TestAllTypes()
+ with self.assertRaises(TypeError):
+ hash(m.repeated_int32)
+ with self.assertRaises(TypeError):
+ hash(m.repeated_nested_message)
+
+ def testRepeatedFieldInsideNestedMessage(self, message_module):
+ m = message_module.NestedTestAllTypes()
+ m.payload.repeated_int32.extend([])
+ self.assertTrue(m.HasField('payload'))
+
def ensureNestedMessageExists(self, msg, attribute):
"""Make sure that a nested message object exists.
@@ -576,6 +657,7 @@ class MessageTest(BaseTestCase):
def testOneofGetCaseNonexistingField(self, message_module):
m = message_module.TestAllTypes()
self.assertRaises(ValueError, m.WhichOneof, 'no_such_oneof_field')
+ self.assertRaises(Exception, m.WhichOneof, 0)
def testOneofDefaultValues(self, message_module):
m = message_module.TestAllTypes()
@@ -951,6 +1033,8 @@ class MessageTest(BaseTestCase):
m = message_module.TestAllTypes()
with self.assertRaises(IndexError) as _:
m.repeated_nested_message.pop()
+ with self.assertRaises(TypeError) as _:
+ m.repeated_nested_message.pop('0')
for i in range(5):
n = m.repeated_nested_message.add()
n.bb = i
@@ -959,6 +1043,39 @@ class MessageTest(BaseTestCase):
self.assertEqual(2, m.repeated_nested_message.pop(1).bb)
self.assertEqual([1, 3], [n.bb for n in m.repeated_nested_message])
+ def testRepeatedCompareWithSelf(self, message_module):
+ m = message_module.TestAllTypes()
+ for i in range(5):
+ m.repeated_int32.insert(i, i)
+ n = m.repeated_nested_message.add()
+ n.bb = i
+ self.assertSequenceEqual(m.repeated_int32, m.repeated_int32)
+ self.assertEqual(m.repeated_nested_message, m.repeated_nested_message)
+
+ def testReleasedNestedMessages(self, message_module):
+ """A case that lead to a segfault when a message detached from its parent
+ container has itself a child container.
+ """
+ m = message_module.NestedTestAllTypes()
+ m = m.repeated_child.add()
+ m = m.child
+ m = m.repeated_child.add()
+ self.assertEqual(m.payload.optional_int32, 0)
+
+ def testSetRepeatedComposite(self, message_module):
+ m = message_module.TestAllTypes()
+ with self.assertRaises(AttributeError):
+ m.repeated_int32 = []
+ m.repeated_int32.append(1)
+ if api_implementation.Type() == 'cpp':
+ # For test coverage: cpp has a different path if composite
+ # field is in cache
+ with self.assertRaises(TypeError):
+ m.repeated_int32 = []
+ else:
+ with self.assertRaises(AttributeError):
+ m.repeated_int32 = []
+
# Class to test proto2-only features (required, extensions, etc.)
class Proto2Test(BaseTestCase):
@@ -1011,18 +1128,46 @@ class Proto2Test(BaseTestCase):
self.assertEqual(False, message.optional_bool)
self.assertEqual(0, message.optional_nested_message.bb)
- # TODO(tibell): The C++ implementations actually allows assignment
- # of unknown enum values to *scalar* fields (but not repeated
- # fields). Once checked enum fields becomes the default in the
- # Python implementation, the C++ implementation should follow suit.
def testAssignInvalidEnum(self):
- """It should not be possible to assign an invalid enum number to an
- enum field."""
+ """Assigning an invalid enum number is not allowed in proto2."""
m = unittest_pb2.TestAllTypes()
+ # Proto2 can not assign unknown enum.
with self.assertRaises(ValueError) as _:
m.optional_nested_enum = 1234567
self.assertRaises(ValueError, m.repeated_nested_enum.append, 1234567)
+ # Assignment is a different code path than append for the C++ impl.
+ m.repeated_nested_enum.append(2)
+ m.repeated_nested_enum[0] = 2
+ with self.assertRaises(ValueError):
+ m.repeated_nested_enum[0] = 123456
+
+ # Unknown enum value can be parsed but is ignored.
+ m2 = unittest_proto3_arena_pb2.TestAllTypes()
+ m2.optional_nested_enum = 1234567
+ m2.repeated_nested_enum.append(7654321)
+ serialized = m2.SerializeToString()
+
+ m3 = unittest_pb2.TestAllTypes()
+ m3.ParseFromString(serialized)
+ self.assertFalse(m3.HasField('optional_nested_enum'))
+ # 1 is the default value for optional_nested_enum.
+ self.assertEqual(1, m3.optional_nested_enum)
+ self.assertEqual(0, len(m3.repeated_nested_enum))
+ m2.Clear()
+ m2.ParseFromString(m3.SerializeToString())
+ self.assertEqual(1234567, m2.optional_nested_enum)
+ self.assertEqual(7654321, m2.repeated_nested_enum[0])
+
+ def testUnknownEnumMap(self):
+ m = map_proto2_unittest_pb2.TestEnumMap()
+ m.known_map_field[123] = 0
+ with self.assertRaises(ValueError):
+ m.unknown_map_field[1] = 123
+
+ def testExtensionsErrors(self):
+ msg = unittest_pb2.TestAllTypes()
+ self.assertRaises(AttributeError, getattr, msg, 'Extensions')
def testGoldenExtensions(self):
golden_data = test_util.GoldenFileData('golden_message')
@@ -1247,6 +1392,7 @@ class Proto3Test(BaseTestCase):
"""Assigning an unknown enum value is allowed and preserves the value."""
m = unittest_proto3_arena_pb2.TestAllTypes()
+ # Proto3 can assign unknown enums.
m.optional_nested_enum = 1234567
self.assertEqual(1234567, m.optional_nested_enum)
m.repeated_nested_enum.append(22334455)
@@ -1264,7 +1410,7 @@ class Proto3Test(BaseTestCase):
# Map isn't really a proto3-only feature. But there is no proto2 equivalent
# of google/protobuf/map_unittest.proto right now, so it's not easy to
# test both with the same test like we do for the other proto2/proto3 tests.
- # (google/protobuf/map_protobuf_unittest.proto is very different in the set
+ # (google/protobuf/map_proto2_unittest.proto is very different in the set
# of messages and fields it contains).
def testScalarMapDefaults(self):
msg = map_unittest_pb2.TestMap()
@@ -1325,12 +1471,21 @@ class Proto3Test(BaseTestCase):
msg.map_int32_int32[5] = 15
self.assertEqual(15, msg.map_int32_int32.get(5))
+ self.assertEqual(15, msg.map_int32_int32.get(5))
+ with self.assertRaises(TypeError):
+ msg.map_int32_int32.get('')
self.assertIsNone(msg.map_int32_foreign_message.get(5))
self.assertEqual(10, msg.map_int32_foreign_message.get(5, 10))
submsg = msg.map_int32_foreign_message[5]
self.assertIs(submsg, msg.map_int32_foreign_message.get(5))
+ # TODO(jieluo): Fix python and cpp extension diff.
+ if api_implementation.Type() == 'cpp':
+ with self.assertRaises(TypeError):
+ msg.map_int32_foreign_message.get('')
+ else:
+ self.assertEqual(None, msg.map_int32_foreign_message.get(''))
def testScalarMap(self):
msg = map_unittest_pb2.TestMap()
@@ -1342,8 +1497,13 @@ class Proto3Test(BaseTestCase):
msg.map_int64_int64[-2**33] = -2**34
msg.map_uint32_uint32[123] = 456
msg.map_uint64_uint64[2**33] = 2**34
+ msg.map_int32_float[2] = 1.2
+ msg.map_int32_double[1] = 3.3
msg.map_string_string['abc'] = '123'
+ msg.map_bool_bool[True] = True
msg.map_int32_enum[888] = 2
+ # Unknown numeric enum is supported in proto3.
+ msg.map_int32_enum[123] = 456
self.assertEqual([], msg.FindInitializationErrors())
@@ -1377,8 +1537,24 @@ class Proto3Test(BaseTestCase):
self.assertEqual(-2**34, msg2.map_int64_int64[-2**33])
self.assertEqual(456, msg2.map_uint32_uint32[123])
self.assertEqual(2**34, msg2.map_uint64_uint64[2**33])
+ self.assertAlmostEqual(1.2, msg.map_int32_float[2])
+ self.assertEqual(3.3, msg.map_int32_double[1])
self.assertEqual('123', msg2.map_string_string['abc'])
+ self.assertEqual(True, msg2.map_bool_bool[True])
self.assertEqual(2, msg2.map_int32_enum[888])
+ self.assertEqual(456, msg2.map_int32_enum[123])
+ # TODO(jieluo): Add cpp extension support.
+ if api_implementation.Type() == 'python':
+ self.assertEqual('{-123: -456}',
+ str(msg2.map_int32_int32))
+
+ def testMapEntryAlwaysSerialized(self):
+ msg = map_unittest_pb2.TestMap()
+ msg.map_int32_int32[0] = 0
+ msg.map_string_string[''] = ''
+ self.assertEqual(msg.ByteSize(), 12)
+ self.assertEqual(b'\n\x04\x08\x00\x10\x00r\x04\n\x00\x12\x00',
+ msg.SerializeToString())
def testStringUnicodeConversionInMap(self):
msg = map_unittest_pb2.TestMap()
@@ -1431,6 +1607,40 @@ class Proto3Test(BaseTestCase):
self.assertIn(123, msg2.map_int32_foreign_message)
self.assertIn(-456, msg2.map_int32_foreign_message)
self.assertEqual(2, len(msg2.map_int32_foreign_message))
+ # TODO(jieluo): Fix text format for message map.
+ # TODO(jieluo): Add cpp extension support.
+ if api_implementation.Type() == 'python':
+ self.assertEqual(15,
+ len(str(msg2.map_int32_foreign_message)))
+
+ def testNestedMessageMapItemDelete(self):
+ msg = map_unittest_pb2.TestMap()
+ msg.map_int32_all_types[1].optional_nested_message.bb = 1
+ del msg.map_int32_all_types[1]
+ msg.map_int32_all_types[2].optional_nested_message.bb = 2
+ self.assertEqual(1, len(msg.map_int32_all_types))
+ msg.map_int32_all_types[1].optional_nested_message.bb = 1
+ self.assertEqual(2, len(msg.map_int32_all_types))
+
+ serialized = msg.SerializeToString()
+ msg2 = map_unittest_pb2.TestMap()
+ msg2.ParseFromString(serialized)
+ keys = [1, 2]
+ # The loop triggers PyErr_Occurred() in c extension.
+ for key in keys:
+ del msg2.map_int32_all_types[key]
+
+ def testMapByteSize(self):
+ msg = map_unittest_pb2.TestMap()
+ msg.map_int32_int32[1] = 1
+ size = msg.ByteSize()
+ msg.map_int32_int32[1] = 128
+ self.assertEqual(msg.ByteSize(), size + 1)
+
+ msg.map_int32_foreign_message[19].c = 1
+ size = msg.ByteSize()
+ msg.map_int32_foreign_message[19].c = 128
+ self.assertEqual(msg.ByteSize(), size + 1)
def testMergeFrom(self):
msg = map_unittest_pb2.TestMap()
@@ -1456,7 +1666,15 @@ class Proto3Test(BaseTestCase):
self.assertEqual(5, msg2.map_int32_foreign_message[111].c)
self.assertEqual(10, msg2.map_int32_foreign_message[222].c)
self.assertFalse(msg2.map_int32_foreign_message[222].HasField('d'))
- self.assertEqual(15, old_map_value.c)
+ if api_implementation.Type() != 'cpp':
+ # During the call to MergeFrom(), the C++ implementation will have
+ # deallocated the underlying message, but this is very difficult to detect
+ # properly. The line below is likely to cause a segmentation fault.
+ # With the Python implementation, old_map_value is just 'detached' from
+ # the main message. Using it will not crash of course, but since it still
+ # have a reference to the parent message I'm sure we can find interesting
+ # ways to cause inconsistencies.
+ self.assertEqual(15, old_map_value.c)
# Verify that there is only one entry per key, even though the MergeFrom
# may have internally created multiple entries for a single key in the
@@ -1477,6 +1695,12 @@ class Proto3Test(BaseTestCase):
del msg2.map_int32_foreign_message[222]
self.assertFalse(222 in msg2.map_int32_foreign_message)
+ if api_implementation.Type() == 'cpp':
+ with self.assertRaises(TypeError):
+ del msg2.map_int32_foreign_message['']
+ else:
+ with self.assertRaises(KeyError):
+ del msg2.map_int32_foreign_message['']
def testMergeFromBadType(self):
msg = map_unittest_pb2.TestMap()
@@ -1611,6 +1835,54 @@ class Proto3Test(BaseTestCase):
matching_dict = {2: 4, 3: 6, 4: 8}
self.assertMapIterEquals(msg.map_int32_int32.items(), matching_dict)
+ def testPython2Map(self):
+ if sys.version_info < (3,):
+ msg = map_unittest_pb2.TestMap()
+ msg.map_int32_int32[2] = 4
+ msg.map_int32_int32[3] = 6
+ msg.map_int32_int32[4] = 8
+ msg.map_int32_int32[5] = 10
+ map_int32 = msg.map_int32_int32
+ self.assertEqual(4, len(map_int32))
+ msg2 = map_unittest_pb2.TestMap()
+ msg2.ParseFromString(msg.SerializeToString())
+
+ def CheckItems(seq, iterator):
+ self.assertEqual(next(iterator), seq[0])
+ self.assertEqual(list(iterator), seq[1:])
+
+ CheckItems(map_int32.items(), map_int32.iteritems())
+ CheckItems(map_int32.keys(), map_int32.iterkeys())
+ CheckItems(map_int32.values(), map_int32.itervalues())
+
+ self.assertEqual(6, map_int32.get(3))
+ self.assertEqual(None, map_int32.get(999))
+ self.assertEqual(6, map_int32.pop(3))
+ self.assertEqual(0, map_int32.pop(3))
+ self.assertEqual(3, len(map_int32))
+ key, value = map_int32.popitem()
+ self.assertEqual(2 * key, value)
+ self.assertEqual(2, len(map_int32))
+ map_int32.clear()
+ self.assertEqual(0, len(map_int32))
+
+ with self.assertRaises(KeyError):
+ map_int32.popitem()
+
+ self.assertEqual(0, map_int32.setdefault(2))
+ self.assertEqual(1, len(map_int32))
+
+ map_int32.update(msg2.map_int32_int32)
+ self.assertEqual(4, len(map_int32))
+
+ with self.assertRaises(TypeError):
+ map_int32.update(msg2.map_int32_int32,
+ msg2.map_int32_int32)
+ with self.assertRaises(TypeError):
+ map_int32.update(0)
+ with self.assertRaises(TypeError):
+ map_int32.update(value=12)
+
def testMapItems(self):
# Map items used to have strange behaviors when use c extension. Because
# [] may reorder the map and invalidate any exsting iterators.
@@ -1626,6 +1898,35 @@ class Proto3Test(BaseTestCase):
items2 = msg.map_string_string.items()
self.assertEqual(items1, items2)
+ def testMapDeterministicSerialization(self):
+ golden_data = (b'r\x0c\n\x07init_op\x12\x01d'
+ b'r\n\n\x05item1\x12\x01e'
+ b'r\n\n\x05item2\x12\x01f'
+ b'r\n\n\x05item3\x12\x01g'
+ b'r\x0b\n\x05item4\x12\x02QQ'
+ b'r\x12\n\rlocal_init_op\x12\x01a'
+ b'r\x0e\n\tsummaries\x12\x01e'
+ b'r\x18\n\x13trainable_variables\x12\x01b'
+ b'r\x0e\n\tvariables\x12\x01c')
+ msg = map_unittest_pb2.TestMap()
+ msg.map_string_string['local_init_op'] = 'a'
+ msg.map_string_string['trainable_variables'] = 'b'
+ msg.map_string_string['variables'] = 'c'
+ msg.map_string_string['init_op'] = 'd'
+ msg.map_string_string['summaries'] = 'e'
+ msg.map_string_string['item1'] = 'e'
+ msg.map_string_string['item2'] = 'f'
+ msg.map_string_string['item3'] = 'g'
+ msg.map_string_string['item4'] = 'QQ'
+
+ # If deterministic serialization is not working correctly, this will be
+ # "flaky" depending on the exact python dict hash seed.
+ #
+ # Fortunately, there are enough items in this map that it is extremely
+ # unlikely to ever hit the "right" in-order combination, so the test
+ # itself should fail reliably.
+ self.assertEqual(golden_data, msg.SerializeToString(deterministic=True))
+
def testMapIterationClearMessage(self):
# Iterator needs to work even if message and map are deleted.
msg = map_unittest_pb2.TestMap()
@@ -1712,6 +2013,9 @@ class Proto3Test(BaseTestCase):
del msg.map_int32_int32[4]
self.assertEqual(0, len(msg.map_int32_int32))
+ with self.assertRaises(KeyError):
+ del msg.map_int32_all_types[32]
+
def testMapsAreMapping(self):
msg = map_unittest_pb2.TestMap()
self.assertIsInstance(msg.map_int32_int32, collections.Mapping)
@@ -1720,6 +2024,14 @@ class Proto3Test(BaseTestCase):
self.assertIsInstance(msg.map_int32_foreign_message,
collections.MutableMapping)
+ def testMapsCompare(self):
+ msg = map_unittest_pb2.TestMap()
+ msg.map_int32_int32[-123] = -456
+ self.assertEqual(msg.map_int32_int32, msg.map_int32_int32)
+ self.assertEqual(msg.map_int32_foreign_message,
+ msg.map_int32_foreign_message)
+ self.assertNotEqual(msg.map_int32_int32, 0)
+
def testMapFindInitializationErrorsSmokeTest(self):
msg = map_unittest_pb2.TestMap()
msg.map_string_string['abc'] = '123'
@@ -1807,8 +2119,9 @@ class PackedFieldTest(BaseTestCase):
self.assertEqual(golden_data, message.SerializeToString())
-@unittest.skipIf(api_implementation.Type() != 'cpp',
- 'explicit tests of the C++ implementation')
+@unittest.skipIf(api_implementation.Type() != 'cpp' or
+ sys.version_info < (2, 7),
+ 'explicit tests of the C++ implementation for PY27 and above')
class OversizeProtosTest(BaseTestCase):
@classmethod
diff --git a/python/google/protobuf/internal/more_extensions_dynamic.proto b/python/google/protobuf/internal/more_extensions_dynamic.proto
index 11f85ef6..98fcbcb6 100644
--- a/python/google/protobuf/internal/more_extensions_dynamic.proto
+++ b/python/google/protobuf/internal/more_extensions_dynamic.proto
@@ -47,4 +47,5 @@ message DynamicMessageType {
extend ExtendedMessage {
optional int32 dynamic_int32_extension = 100;
optional DynamicMessageType dynamic_message_extension = 101;
+ repeated DynamicMessageType repeated_dynamic_message_extension = 102;
}
diff --git a/python/google/protobuf/internal/python_message.py b/python/google/protobuf/internal/python_message.py
index c1bd1f9c..975e3b4d 100755
--- a/python/google/protobuf/internal/python_message.py
+++ b/python/google/protobuf/internal/python_message.py
@@ -56,19 +56,9 @@ import sys
import weakref
import six
-try:
- import six.moves.copyreg as copyreg
-except ImportError:
- # On some platforms, for example gMac, we run native Python because there is
- # nothing like hermetic Python. This means lesser control on the system and
- # the six.moves package may be missing (is missing on 20150321 on gMac). Be
- # extra conservative and try to load the old replacement if it fails.
- try:
- import copy_reg as copyreg #PY26
- except ImportError:
- import copyreg
# We use "as" to avoid name collisions with variables.
+from google.protobuf.internal import api_implementation
from google.protobuf.internal import containers
from google.protobuf.internal import decoder
from google.protobuf.internal import encoder
@@ -179,7 +169,6 @@ class GeneratedProtocolMessageType(type):
_AddStaticMethods(cls)
_AddMessageMethods(descriptor, cls)
_AddPrivateHelperMethods(descriptor, cls)
- copyreg.pickle(cls, lambda obj: (cls, (), obj.__getstate__()))
superclass = super(GeneratedProtocolMessageType, cls)
superclass.__init__(name, bases, dictionary)
@@ -300,7 +289,8 @@ def _AttachFieldHelpers(cls, field_descriptor):
if is_map_entry:
field_encoder = encoder.MapEncoder(field_descriptor)
- sizer = encoder.MapSizer(field_descriptor)
+ sizer = encoder.MapSizer(field_descriptor,
+ _IsMessageMapField(field_descriptor))
elif _IsMessageSetExtension(field_descriptor):
field_encoder = encoder.MessageSetItemEncoder(field_descriptor.number)
sizer = encoder.MessageSetItemSizer(field_descriptor.number)
@@ -903,7 +893,7 @@ def _AddHasExtensionMethod(cls):
def _InternalUnpackAny(msg):
"""Unpacks Any message and returns the unpacked message.
- This internal method is differnt from public Any Unpack method which takes
+ This internal method is different from public Any Unpack method which takes
the target message as argument. _InternalUnpackAny method does not have
target message type and need to find the message type in descriptor pool.
@@ -1020,11 +1010,16 @@ def _AddByteSizeMethod(message_descriptor, cls):
return self._cached_byte_size
size = 0
- for field_descriptor, field_value in self.ListFields():
- size += field_descriptor._sizer(field_value)
-
- for tag_bytes, value_bytes in self._unknown_fields:
- size += len(tag_bytes) + len(value_bytes)
+ descriptor = self.DESCRIPTOR
+ if descriptor.GetOptions().map_entry:
+ # Fields of map entry should always be serialized.
+ size = descriptor.fields_by_name['key']._sizer(self.key)
+ size += descriptor.fields_by_name['value']._sizer(self.value)
+ else:
+ for field_descriptor, field_value in self.ListFields():
+ size += field_descriptor._sizer(field_value)
+ for tag_bytes, value_bytes in self._unknown_fields:
+ size += len(tag_bytes) + len(value_bytes)
self._cached_byte_size = size
self._cached_byte_size_dirty = False
@@ -1037,32 +1032,46 @@ def _AddByteSizeMethod(message_descriptor, cls):
def _AddSerializeToStringMethod(message_descriptor, cls):
"""Helper for _AddMessageMethods()."""
- def SerializeToString(self):
+ def SerializeToString(self, **kwargs):
# Check if the message has all of its required fields set.
errors = []
if not self.IsInitialized():
raise message_mod.EncodeError(
'Message %s is missing required fields: %s' % (
self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
- return self.SerializePartialToString()
+ return self.SerializePartialToString(**kwargs)
cls.SerializeToString = SerializeToString
def _AddSerializePartialToStringMethod(message_descriptor, cls):
"""Helper for _AddMessageMethods()."""
- def SerializePartialToString(self):
+ def SerializePartialToString(self, **kwargs):
out = BytesIO()
- self._InternalSerialize(out.write)
+ self._InternalSerialize(out.write, **kwargs)
return out.getvalue()
cls.SerializePartialToString = SerializePartialToString
- def InternalSerialize(self, write_bytes):
- for field_descriptor, field_value in self.ListFields():
- field_descriptor._encoder(write_bytes, field_value)
- for tag_bytes, value_bytes in self._unknown_fields:
- write_bytes(tag_bytes)
- write_bytes(value_bytes)
+ def InternalSerialize(self, write_bytes, deterministic=None):
+ if deterministic is None:
+ deterministic = (
+ api_implementation.IsPythonDefaultSerializationDeterministic())
+ else:
+ deterministic = bool(deterministic)
+
+ descriptor = self.DESCRIPTOR
+ if descriptor.GetOptions().map_entry:
+ # Fields of map entry should always be serialized.
+ descriptor.fields_by_name['key']._encoder(
+ write_bytes, self.key, deterministic)
+ descriptor.fields_by_name['value']._encoder(
+ write_bytes, self.value, deterministic)
+ else:
+ for field_descriptor, field_value in self.ListFields():
+ field_descriptor._encoder(write_bytes, field_value, deterministic)
+ for tag_bytes, value_bytes in self._unknown_fields:
+ write_bytes(tag_bytes)
+ write_bytes(value_bytes)
cls._InternalSerialize = InternalSerialize
@@ -1100,7 +1109,8 @@ def _AddMergeFromStringMethod(message_descriptor, cls):
new_pos = local_SkipField(buffer, new_pos, end, tag_bytes)
if new_pos == -1:
return pos
- if not is_proto3:
+ if (not is_proto3 or
+ api_implementation.GetPythonProto3PreserveUnknownsDefault()):
if not unknown_field_list:
unknown_field_list = self._unknown_fields = []
unknown_field_list.append(
@@ -1271,6 +1281,12 @@ def _AddWhichOneofMethod(message_descriptor, cls):
cls.WhichOneof = WhichOneof
+def _AddReduceMethod(cls):
+ def __reduce__(self): # pylint: disable=invalid-name
+ return (type(self), (), self.__getstate__())
+ cls.__reduce__ = __reduce__
+
+
def _Clear(self):
# Clear fields.
self._fields = {}
@@ -1316,6 +1332,7 @@ def _AddMessageMethods(message_descriptor, cls):
_AddIsInitializedMethod(message_descriptor, cls)
_AddMergeFromMethod(cls)
_AddWhichOneofMethod(message_descriptor, cls)
+ _AddReduceMethod(cls)
# Adds methods which do not depend on cls.
cls.Clear = _Clear
cls.DiscardUnknownFields = _DiscardUnknownFields
diff --git a/python/google/protobuf/internal/python_protobuf.cc b/python/google/protobuf/internal/python_protobuf.cc
new file mode 100644
index 00000000..f90cc438
--- /dev/null
+++ b/python/google/protobuf/internal/python_protobuf.cc
@@ -0,0 +1,63 @@
+// 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: qrczak@google.com (Marcin Kowalczyk)
+
+#include <google/protobuf/python/python_protobuf.h>
+
+namespace google {
+namespace protobuf {
+namespace python {
+
+static const Message* GetCProtoInsidePyProtoStub(PyObject* msg) {
+ return NULL;
+}
+static Message* MutableCProtoInsidePyProtoStub(PyObject* msg) {
+ return NULL;
+}
+
+// This is initialized with a default, stub implementation.
+// If python-google.protobuf.cc is loaded, the function pointer is overridden
+// with a full implementation.
+const Message* (*GetCProtoInsidePyProtoPtr)(PyObject* msg) =
+ GetCProtoInsidePyProtoStub;
+Message* (*MutableCProtoInsidePyProtoPtr)(PyObject* msg) =
+ MutableCProtoInsidePyProtoStub;
+
+const Message* GetCProtoInsidePyProto(PyObject* msg) {
+ return GetCProtoInsidePyProtoPtr(msg);
+}
+Message* MutableCProtoInsidePyProto(PyObject* msg) {
+ return MutableCProtoInsidePyProtoPtr(msg);
+}
+
+} // namespace python
+} // namespace protobuf
+} // namespace google
diff --git a/python/google/protobuf/internal/reflection_test.py b/python/google/protobuf/internal/reflection_test.py
index 0e881015..0306ff46 100755
--- a/python/google/protobuf/internal/reflection_test.py
+++ b/python/google/protobuf/internal/reflection_test.py
@@ -620,6 +620,14 @@ class ReflectionTest(BaseTestCase):
self.assertRaises(TypeError, setattr, proto, 'optional_int32', 'foo')
self.assertRaises(TypeError, setattr, proto, 'optional_string', 10)
self.assertRaises(TypeError, setattr, proto, 'optional_bytes', 10)
+ self.assertRaises(TypeError, setattr, proto, 'optional_bool', 'foo')
+ self.assertRaises(TypeError, setattr, proto, 'optional_float', 'foo')
+ self.assertRaises(TypeError, setattr, proto, 'optional_double', 'foo')
+ # TODO(jieluo): Fix type checking difference for python and c extension
+ if api_implementation.Type() == 'python':
+ self.assertRaises(TypeError, setattr, proto, 'optional_bool', 1.1)
+ else:
+ proto.optional_bool = 1.1
def assertIntegerTypes(self, integer_fn):
"""Verifies setting of scalar integers.
@@ -686,8 +694,10 @@ class ReflectionTest(BaseTestCase):
self.assertEqual(expected_min, getattr(pb, field_name))
setattr(pb, field_name, expected_max)
self.assertEqual(expected_max, getattr(pb, field_name))
- self.assertRaises(ValueError, setattr, pb, field_name, expected_min - 1)
- self.assertRaises(ValueError, setattr, pb, field_name, expected_max + 1)
+ self.assertRaises((ValueError, TypeError), setattr, pb, field_name,
+ expected_min - 1)
+ self.assertRaises((ValueError, TypeError), setattr, pb, field_name,
+ expected_max + 1)
TestMinAndMaxIntegers('optional_int32', -(1 << 31), (1 << 31) - 1)
TestMinAndMaxIntegers('optional_uint32', 0, 0xffffffff)
@@ -696,7 +706,7 @@ class ReflectionTest(BaseTestCase):
# A bit of white-box testing since -1 is an int and not a long in C++ and
# so goes down a different path.
pb = unittest_pb2.TestAllTypes()
- with self.assertRaises(ValueError):
+ with self.assertRaises((ValueError, TypeError)):
pb.optional_uint64 = integer_fn(-(1 << 63))
pb = unittest_pb2.TestAllTypes()
@@ -720,6 +730,12 @@ class ReflectionTest(BaseTestCase):
proto.repeated_int32[0] = 23
self.assertRaises(IndexError, proto.repeated_int32.__setitem__, 500, 23)
self.assertRaises(TypeError, proto.repeated_int32.__setitem__, 0, 'abc')
+ self.assertRaises(TypeError, proto.repeated_int32.__setitem__, 0, [])
+ self.assertRaises(TypeError, proto.repeated_int32.__setitem__,
+ 'index', 23)
+
+ proto.repeated_string.append('2')
+ self.assertRaises(TypeError, proto.repeated_string.__setitem__, 0, 10)
# Repeated enums tests.
#proto.repeated_nested_enum.append(0)
@@ -1007,6 +1023,14 @@ class ReflectionTest(BaseTestCase):
self.assertEqual(4, len(proto.repeated_nested_message))
self.assertEqual(n1, proto.repeated_nested_message[2])
self.assertEqual(n2, proto.repeated_nested_message[3])
+ self.assertRaises(TypeError,
+ proto.repeated_nested_message.extend, n1)
+ self.assertRaises(TypeError,
+ proto.repeated_nested_message.extend, [0])
+ wrong_message_type = unittest_pb2.TestAllTypes()
+ self.assertRaises(TypeError,
+ proto.repeated_nested_message.extend,
+ [wrong_message_type])
# Test clearing.
proto.ClearField('repeated_nested_message')
@@ -1018,6 +1042,8 @@ class ReflectionTest(BaseTestCase):
self.assertEqual(1, len(proto.repeated_nested_message))
self.assertEqual(23, proto.repeated_nested_message[0].bb)
self.assertRaises(TypeError, proto.repeated_nested_message.add, 23)
+ with self.assertRaises(Exception):
+ proto.repeated_nested_message[0] = 23
def testRepeatedCompositeRemove(self):
proto = unittest_pb2.TestAllTypes()
@@ -1551,7 +1577,14 @@ class ReflectionTest(BaseTestCase):
container = copy.deepcopy(proto1.repeated_int32)
self.assertEqual([2, 3], container)
- # TODO(anuraag): Implement deepcopy for repeated composite / extension dict
+ message1 = proto1.repeated_nested_message.add()
+ message1.bb = 1
+ messages = copy.deepcopy(proto1.repeated_nested_message)
+ self.assertEqual(proto1.repeated_nested_message, messages)
+ message1.bb = 2
+ self.assertNotEqual(proto1.repeated_nested_message, messages)
+
+ # TODO(anuraag): Implement deepcopy for extension dict
def testClear(self):
proto = unittest_pb2.TestAllTypes()
@@ -1635,8 +1668,11 @@ class ReflectionTest(BaseTestCase):
proto.SerializeToString()
proto.SerializePartialToString()
- def assertNotInitialized(self, proto):
+ def assertNotInitialized(self, proto, error_size=None):
+ errors = []
self.assertFalse(proto.IsInitialized())
+ self.assertFalse(proto.IsInitialized(errors))
+ self.assertEqual(error_size, len(errors))
self.assertRaises(message.EncodeError, proto.SerializeToString)
# "Partial" serialization doesn't care if message is uninitialized.
proto.SerializePartialToString()
@@ -1650,7 +1686,7 @@ class ReflectionTest(BaseTestCase):
# The case of uninitialized required fields.
proto = unittest_pb2.TestRequired()
- self.assertNotInitialized(proto)
+ self.assertNotInitialized(proto, 3)
proto.a = proto.b = proto.c = 2
self.assertInitialized(proto)
@@ -1658,14 +1694,14 @@ class ReflectionTest(BaseTestCase):
proto = unittest_pb2.TestRequiredForeign()
self.assertInitialized(proto)
proto.optional_message.a = 1
- self.assertNotInitialized(proto)
+ self.assertNotInitialized(proto, 2)
proto.optional_message.b = 0
proto.optional_message.c = 0
self.assertInitialized(proto)
# Uninitialized repeated submessage.
message1 = proto.repeated_message.add()
- self.assertNotInitialized(proto)
+ self.assertNotInitialized(proto, 3)
message1.a = message1.b = message1.c = 0
self.assertInitialized(proto)
@@ -1674,11 +1710,11 @@ class ReflectionTest(BaseTestCase):
extension = unittest_pb2.TestRequired.multi
message1 = proto.Extensions[extension].add()
message2 = proto.Extensions[extension].add()
- self.assertNotInitialized(proto)
+ self.assertNotInitialized(proto, 6)
message1.a = 1
message1.b = 1
message1.c = 1
- self.assertNotInitialized(proto)
+ self.assertNotInitialized(proto, 3)
message2.a = 2
message2.b = 2
message2.c = 2
@@ -1688,7 +1724,7 @@ class ReflectionTest(BaseTestCase):
proto = unittest_pb2.TestAllExtensions()
extension = unittest_pb2.TestRequired.single
proto.Extensions[extension].a = 1
- self.assertNotInitialized(proto)
+ self.assertNotInitialized(proto, 2)
proto.Extensions[extension].b = 2
proto.Extensions[extension].c = 3
self.assertInitialized(proto)
@@ -2147,6 +2183,8 @@ class ByteSizeTest(BaseTestCase):
foreign_message_1 = self.proto.repeated_nested_message.add()
foreign_message_1.bb = 9
self.assertEqual(2 + 1 + 2 + 1 + 1 + 1, self.Size())
+ repeated_nested_message = copy.deepcopy(
+ self.proto.repeated_nested_message)
# 2 bytes tag plus 1 byte length plus 1 byte bb tag 1 byte int.
del self.proto.repeated_nested_message[0]
@@ -2167,6 +2205,16 @@ class ByteSizeTest(BaseTestCase):
del self.proto.repeated_nested_message[0]
self.assertEqual(0, self.Size())
+ self.assertEqual(2, len(repeated_nested_message))
+ del repeated_nested_message[0:1]
+ # TODO(jieluo): Fix cpp extension bug when delete repeated message.
+ if api_implementation.Type() == 'python':
+ self.assertEqual(1, len(repeated_nested_message))
+ del repeated_nested_message[-1]
+ # TODO(jieluo): Fix cpp extension bug when delete repeated message.
+ if api_implementation.Type() == 'python':
+ self.assertEqual(0, len(repeated_nested_message))
+
def testRepeatedGroups(self):
# 2-byte START_GROUP plus 2-byte END_GROUP.
group_0 = self.proto.repeatedgroup.add()
@@ -2183,6 +2231,10 @@ class ByteSizeTest(BaseTestCase):
proto.Extensions[extension] = 23
# 1 byte for tag, 1 byte for value.
self.assertEqual(2, proto.ByteSize())
+ field = unittest_pb2.TestAllTypes.DESCRIPTOR.fields_by_name[
+ 'optional_int32']
+ with self.assertRaises(KeyError):
+ proto.Extensions[field] = 23
def testCacheInvalidationForNonrepeatedScalar(self):
# Test non-extension.
diff --git a/python/google/protobuf/internal/service_reflection_test.py b/python/google/protobuf/internal/service_reflection_test.py
index 62900b1d..77239f44 100755
--- a/python/google/protobuf/internal/service_reflection_test.py
+++ b/python/google/protobuf/internal/service_reflection_test.py
@@ -82,6 +82,10 @@ class FooUnitTest(unittest.TestCase):
service_descriptor = unittest_pb2.TestService.GetDescriptor()
srvc.CallMethod(service_descriptor.methods[1], rpc_controller,
unittest_pb2.BarRequest(), MyCallback)
+ self.assertTrue(srvc.GetRequestClass(service_descriptor.methods[1]) is
+ unittest_pb2.BarRequest)
+ self.assertTrue(srvc.GetResponseClass(service_descriptor.methods[1]) is
+ unittest_pb2.BarResponse)
self.assertEqual('Method Bar not implemented.',
rpc_controller.failure_message)
self.assertEqual(None, self.callback_response)
diff --git a/python/google/protobuf/internal/symbol_database_test.py b/python/google/protobuf/internal/symbol_database_test.py
index 4f5173b2..af42681a 100644
--- a/python/google/protobuf/internal/symbol_database_test.py
+++ b/python/google/protobuf/internal/symbol_database_test.py
@@ -60,6 +60,7 @@ class SymbolDatabaseTest(unittest.TestCase):
db.RegisterMessage(unittest_pb2.TestAllTypes.RepeatedGroup)
db.RegisterEnumDescriptor(unittest_pb2.ForeignEnum.DESCRIPTOR)
db.RegisterEnumDescriptor(unittest_pb2.TestAllTypes.NestedEnum.DESCRIPTOR)
+ db.RegisterServiceDescriptor(unittest_pb2._TESTSERVICE)
return db
def testGetPrototype(self):
@@ -109,7 +110,13 @@ class SymbolDatabaseTest(unittest.TestCase):
self._Database().pool.FindMessageTypeByName(
'protobuf_unittest.TestAllTypes.NestedMessage').full_name)
- def testFindFindContainingSymbol(self):
+ def testFindServiceByName(self):
+ self.assertEqual(
+ 'protobuf_unittest.TestService',
+ self._Database().pool.FindServiceByName(
+ 'protobuf_unittest.TestService').full_name)
+
+ def testFindFileContainingSymbol(self):
# Lookup based on either enum or message.
self.assertEqual(
'google/protobuf/unittest.proto',
diff --git a/python/google/protobuf/internal/test_util.py b/python/google/protobuf/internal/test_util.py
index 269d0e2d..a6e34ef5 100755
--- a/python/google/protobuf/internal/test_util.py
+++ b/python/google/protobuf/internal/test_util.py
@@ -39,11 +39,15 @@ __author__ = 'robinson@google.com (Will Robinson)'
import numbers
import operator
import os.path
-import sys
from google.protobuf import unittest_import_pb2
from google.protobuf import unittest_pb2
-from google.protobuf import descriptor_pb2
+
+try:
+ long # Python 2
+except NameError:
+ long = int # Python 3
+
# Tests whether the given TestAllTypes message is proto2 or not.
# This is used to gate several fields/features that only exist
@@ -51,6 +55,7 @@ from google.protobuf import descriptor_pb2
def IsProto2(message):
return message.DESCRIPTOR.syntax == "proto2"
+
def SetAllNonLazyFields(message):
"""Sets every non-lazy field in the message to a unique value.
@@ -128,22 +133,37 @@ def SetAllNonLazyFields(message):
message.repeated_string_piece.append(u'224')
message.repeated_cord.append(u'225')
- # Add a second one of each field.
- message.repeated_int32.append(301)
- message.repeated_int64.append(302)
- message.repeated_uint32.append(303)
- message.repeated_uint64.append(304)
- message.repeated_sint32.append(305)
- message.repeated_sint64.append(306)
- message.repeated_fixed32.append(307)
- message.repeated_fixed64.append(308)
- message.repeated_sfixed32.append(309)
- message.repeated_sfixed64.append(310)
- message.repeated_float.append(311)
- message.repeated_double.append(312)
- message.repeated_bool.append(False)
- message.repeated_string.append(u'315')
- message.repeated_bytes.append(b'316')
+ # Add a second one of each field and set value by index.
+ message.repeated_int32.append(0)
+ message.repeated_int64.append(0)
+ message.repeated_uint32.append(0)
+ message.repeated_uint64.append(0)
+ message.repeated_sint32.append(0)
+ message.repeated_sint64.append(0)
+ message.repeated_fixed32.append(0)
+ message.repeated_fixed64.append(0)
+ message.repeated_sfixed32.append(0)
+ message.repeated_sfixed64.append(0)
+ message.repeated_float.append(0)
+ message.repeated_double.append(0)
+ message.repeated_bool.append(True)
+ message.repeated_string.append(u'0')
+ message.repeated_bytes.append(b'0')
+ message.repeated_int32[1] = 301
+ message.repeated_int64[1] = 302
+ message.repeated_uint32[1] = 303
+ message.repeated_uint64[1] = 304
+ message.repeated_sint32[1] = 305
+ message.repeated_sint64[1] = 306
+ message.repeated_fixed32[1] = 307
+ message.repeated_fixed64[1] = 308
+ message.repeated_sfixed32[1] = 309
+ message.repeated_sfixed64[1] = 310
+ message.repeated_float[1] = 311
+ message.repeated_double[1] = 312
+ message.repeated_bool[1] = False
+ message.repeated_string[1] = u'315'
+ message.repeated_bytes[1] = b'316'
if IsProto2(message):
message.repeatedgroup.add().a = 317
@@ -152,7 +172,8 @@ def SetAllNonLazyFields(message):
message.repeated_import_message.add().d = 320
message.repeated_lazy_message.add().bb = 327
- message.repeated_nested_enum.append(unittest_pb2.TestAllTypes.BAZ)
+ message.repeated_nested_enum.append(unittest_pb2.TestAllTypes.BAR)
+ message.repeated_nested_enum[1] = unittest_pb2.TestAllTypes.BAZ
message.repeated_foreign_enum.append(unittest_pb2.FOREIGN_BAZ)
if IsProto2(message):
message.repeated_import_enum.append(unittest_import_pb2.IMPORT_BAZ)
@@ -707,8 +728,8 @@ class NonStandardInteger(numbers.Integral):
NonStandardInteger is the minimal legal specification for a custom Integral.
As such, it does not support 0 < x < 5 and it is not hashable.
- Note: This is added here instead of relying on numpy or a similar library with
- custom integers to limit dependencies.
+ Note: This is added here instead of relying on numpy or a similar library
+ with custom integers to limit dependencies.
"""
def __init__(self, val, error_string_on_conversion=None):
@@ -845,4 +866,3 @@ class NonStandardInteger(numbers.Integral):
def __repr__(self):
return 'NonStandardInteger(%s)' % self.val
-
diff --git a/python/google/protobuf/internal/text_format_test.py b/python/google/protobuf/internal/text_format_test.py
index 176cbd15..a52f133f 100755
--- a/python/google/protobuf/internal/text_format_test.py
+++ b/python/google/protobuf/internal/text_format_test.py
@@ -1,4 +1,5 @@
#! /usr/bin/env python
+# -*- coding: utf-8 -*-
#
# Protocol Buffers - Google's data interchange format
# Copyright 2008 Google Inc. All rights reserved.
@@ -35,6 +36,7 @@
__author__ = 'kenton@google.com (Kenton Varda)'
+import math
import re
import six
import string
@@ -53,8 +55,8 @@ from google.protobuf import unittest_pb2
from google.protobuf import unittest_proto3_arena_pb2
from google.protobuf.internal import api_implementation
from google.protobuf.internal import any_test_pb2 as test_extend_any
-from google.protobuf.internal import test_util
from google.protobuf.internal import message_set_extensions_pb2
+from google.protobuf.internal import test_util
from google.protobuf import descriptor_pool
from google.protobuf import text_format
@@ -297,6 +299,33 @@ class TextFormatTest(TextFormatBase):
if message_module is unittest_pb2:
test_util.ExpectAllFieldsSet(self, message)
+ def testParseAndMergeUtf8(self, message_module):
+ message = message_module.TestAllTypes()
+ test_util.SetAllFields(message)
+ ascii_text = text_format.MessageToString(message)
+ ascii_text = ascii_text.encode('utf-8')
+
+ parsed_message = message_module.TestAllTypes()
+ text_format.Parse(ascii_text, parsed_message)
+ self.assertEqual(message, parsed_message)
+ if message_module is unittest_pb2:
+ test_util.ExpectAllFieldsSet(self, message)
+
+ parsed_message.Clear()
+ text_format.Merge(ascii_text, parsed_message)
+ self.assertEqual(message, parsed_message)
+ if message_module is unittest_pb2:
+ test_util.ExpectAllFieldsSet(self, message)
+
+ if six.PY2:
+ msg2 = message_module.TestAllTypes()
+ text = (u'optional_string: "café"')
+ text_format.Merge(text, msg2)
+ self.assertEqual(msg2.optional_string, u'café')
+ msg2.Clear()
+ text_format.Parse(text, msg2)
+ self.assertEqual(msg2.optional_string, u'café')
+
def testParseExotic(self, message_module):
message = message_module.TestAllTypes()
text = ('repeated_int64: -9223372036854775808\n'
@@ -371,7 +400,10 @@ class TextFormatTest(TextFormatBase):
def testParseInvalidUtf8(self, message_module):
message = message_module.TestAllTypes()
text = 'repeated_string: "\\xc3\\xc3"'
- self.assertRaises(text_format.ParseError, text_format.Parse, text, message)
+ with self.assertRaises(text_format.ParseError) as e:
+ text_format.Parse(text, message)
+ self.assertEqual(e.exception.GetLine(), 1)
+ self.assertEqual(e.exception.GetColumn(), 28)
def testParseSingleWord(self, message_module):
message = message_module.TestAllTypes()
@@ -395,13 +427,6 @@ class TextFormatTest(TextFormatBase):
r'has no value named BARR.'), text_format.Parse,
text, message)
- message = message_module.TestAllTypes()
- text = 'optional_nested_enum: 100'
- six.assertRaisesRegex(self, text_format.ParseError,
- (r'1:23 : Enum type "\w+.TestAllTypes.NestedEnum" '
- r'has no value with number 100.'), text_format.Parse,
- text, message)
-
def testParseBadIntValue(self, message_module):
message = message_module.TestAllTypes()
text = 'optional_int32: bork'
@@ -452,16 +477,18 @@ class TextFormatTest(TextFormatBase):
text_format.Parse(text_format.MessageToString(m), m2)
self.assertEqual('oneof_uint32', m2.WhichOneof('oneof_field'))
+ def testMergeMultipleOneof(self, message_module):
+ m_string = '\n'.join(['oneof_uint32: 11', 'oneof_string: "foo"'])
+ m2 = message_module.TestAllTypes()
+ text_format.Merge(m_string, m2)
+ self.assertEqual('oneof_string', m2.WhichOneof('oneof_field'))
+
def testParseMultipleOneof(self, message_module):
m_string = '\n'.join(['oneof_uint32: 11', 'oneof_string: "foo"'])
m2 = message_module.TestAllTypes()
- if message_module is unittest_pb2:
- with self.assertRaisesRegexp(text_format.ParseError,
- ' is specified along with field '):
- text_format.Parse(m_string, m2)
- else:
+ with self.assertRaisesRegexp(text_format.ParseError,
+ ' is specified along with field '):
text_format.Parse(m_string, m2)
- self.assertEqual('oneof_string', m2.WhichOneof('oneof_field'))
# These are tests that aren't fundamentally specific to proto2, but are at
@@ -782,13 +809,14 @@ class Proto2Tests(TextFormatBase):
' bin: "\xe0"'
' [nested_unknown_ext]: {\n'
' i: 23\n'
+ ' x: x\n'
' test: "test_string"\n'
' floaty_float: -0.315\n'
' num: -inf\n'
' multiline_str: "abc"\n'
' "def"\n'
' "xyz."\n'
- ' [nested_unknown_ext]: <\n'
+ ' [nested_unknown_ext.ext]: <\n'
' i: 23\n'
' i: 24\n'
' pointfloat: .3\n'
@@ -894,6 +922,14 @@ class Proto2Tests(TextFormatBase):
self.assertEqual(23, message.message_set.Extensions[ext1].i)
self.assertEqual('foo', message.message_set.Extensions[ext2].str)
+ def testParseBadIdentifier(self):
+ message = unittest_pb2.TestAllTypes()
+ text = ('optional_nested_message { "bb": 1 }')
+ with self.assertRaises(text_format.ParseError) as e:
+ text_format.Parse(text, message)
+ self.assertEqual(str(e.exception),
+ '1:27 : Expected identifier or number, got "bb".')
+
def testParseBadExtension(self):
message = unittest_pb2.TestAllExtensions()
text = '[unknown_extension]: 8\n'
@@ -905,6 +941,14 @@ class Proto2Tests(TextFormatBase):
'1:2 : Message type "protobuf_unittest.TestAllTypes" does not have '
'extensions.'), text_format.Parse, text, message)
+ def testParseNumericUnknownEnum(self):
+ message = unittest_pb2.TestAllTypes()
+ text = 'optional_nested_enum: 100'
+ six.assertRaisesRegex(self, text_format.ParseError,
+ (r'1:23 : Enum type "\w+.TestAllTypes.NestedEnum" '
+ r'has no value with number 100.'), text_format.Parse,
+ text, message)
+
def testMergeDuplicateExtensionScalars(self):
message = unittest_pb2.TestAllExtensions()
text = ('[protobuf_unittest.optional_int32_extension]: 42 '
@@ -1026,8 +1070,7 @@ class Proto3Tests(unittest.TestCase):
packed_message.data = 'string1'
message.repeated_any_value.add().Pack(packed_message)
self.assertEqual(
- text_format.MessageToString(message,
- descriptor_pool=descriptor_pool.Default()),
+ text_format.MessageToString(message),
'repeated_any_value {\n'
' [type.googleapis.com/protobuf_unittest.OneString] {\n'
' data: "string0"\n'
@@ -1039,18 +1082,6 @@ class Proto3Tests(unittest.TestCase):
' }\n'
'}\n')
- def testPrintMessageExpandAnyNoDescriptorPool(self):
- packed_message = unittest_pb2.OneString()
- packed_message.data = 'string'
- message = any_test_pb2.TestAny()
- message.any_value.Pack(packed_message)
- self.assertEqual(
- text_format.MessageToString(message, descriptor_pool=None),
- 'any_value {\n'
- ' type_url: "type.googleapis.com/protobuf_unittest.OneString"\n'
- ' value: "\\n\\006string"\n'
- '}\n')
-
def testPrintMessageExpandAnyDescriptorPoolMissingType(self):
packed_message = unittest_pb2.OneString()
packed_message.data = 'string'
@@ -1071,8 +1102,7 @@ class Proto3Tests(unittest.TestCase):
message.any_value.Pack(packed_message)
self.assertEqual(
text_format.MessageToString(message,
- pointy_brackets=True,
- descriptor_pool=descriptor_pool.Default()),
+ pointy_brackets=True),
'any_value <\n'
' [type.googleapis.com/protobuf_unittest.OneString] <\n'
' data: "string"\n'
@@ -1086,8 +1116,7 @@ class Proto3Tests(unittest.TestCase):
message.any_value.Pack(packed_message)
self.assertEqual(
text_format.MessageToString(message,
- as_one_line=True,
- descriptor_pool=descriptor_pool.Default()),
+ as_one_line=True),
'any_value {'
' [type.googleapis.com/protobuf_unittest.OneString]'
' { data: "string" } '
@@ -1108,6 +1137,14 @@ class Proto3Tests(unittest.TestCase):
' < data: "string" > '
'>')
+ def testUnknownEnums(self):
+ message = unittest_proto3_arena_pb2.TestAllTypes()
+ message2 = unittest_proto3_arena_pb2.TestAllTypes()
+ message.optional_nested_enum = 999
+ text_string = text_format.MessageToString(message)
+ text_format.Parse(text_string, message2)
+ self.assertEqual(999, message2.optional_nested_enum)
+
def testMergeExpandedAny(self):
message = any_test_pb2.TestAny()
text = ('any_value {\n'
@@ -1115,7 +1152,12 @@ class Proto3Tests(unittest.TestCase):
' data: "string"\n'
' }\n'
'}\n')
- text_format.Merge(text, message, descriptor_pool=descriptor_pool.Default())
+ text_format.Merge(text, message)
+ packed_message = unittest_pb2.OneString()
+ message.any_value.Unpack(packed_message)
+ self.assertEqual('string', packed_message.data)
+ message.Clear()
+ text_format.Parse(text, message)
packed_message = unittest_pb2.OneString()
message.any_value.Unpack(packed_message)
self.assertEqual('string', packed_message.data)
@@ -1132,7 +1174,7 @@ class Proto3Tests(unittest.TestCase):
' data: "string1"\n'
' }\n'
'}\n')
- text_format.Merge(text, message, descriptor_pool=descriptor_pool.Default())
+ text_format.Merge(text, message)
packed_message = unittest_pb2.OneString()
message.repeated_any_value[0].Unpack(packed_message)
self.assertEqual('string0', packed_message.data)
@@ -1146,22 +1188,22 @@ class Proto3Tests(unittest.TestCase):
' data: "string"\n'
' >\n'
'}\n')
- text_format.Merge(text, message, descriptor_pool=descriptor_pool.Default())
+ text_format.Merge(text, message)
packed_message = unittest_pb2.OneString()
message.any_value.Unpack(packed_message)
self.assertEqual('string', packed_message.data)
- def testMergeExpandedAnyNoDescriptorPool(self):
+ def testMergeAlternativeUrl(self):
message = any_test_pb2.TestAny()
text = ('any_value {\n'
- ' [type.googleapis.com/protobuf_unittest.OneString] {\n'
+ ' [type.otherapi.com/protobuf_unittest.OneString] {\n'
' data: "string"\n'
' }\n'
'}\n')
- with self.assertRaises(text_format.ParseError) as e:
- text_format.Merge(text, message, descriptor_pool=None)
- self.assertEqual(str(e.exception),
- 'Descriptor pool required to parse expanded Any field')
+ text_format.Merge(text, message)
+ packed_message = unittest_pb2.OneString()
+ self.assertEqual('type.otherapi.com/protobuf_unittest.OneString',
+ message.any_value.type_url)
def testMergeExpandedAnyDescriptorPoolMissingType(self):
message = any_test_pb2.TestAny()
@@ -1188,6 +1230,15 @@ class Proto3Tests(unittest.TestCase):
message.any_value.Unpack(packed_message)
self.assertEqual('string', packed_message.data)
+ def testMergeMissingAnyEndToken(self):
+ message = any_test_pb2.TestAny()
+ text = ('any_value {\n'
+ ' [type.googleapis.com/protobuf_unittest.OneString] {\n'
+ ' data: "string"\n')
+ with self.assertRaises(text_format.ParseError) as e:
+ text_format.Merge(text, message)
+ self.assertEqual(str(e.exception), '3:11 : Expected "}".')
+
class TokenizerTest(unittest.TestCase):
@@ -1199,7 +1250,7 @@ class TokenizerTest(unittest.TestCase):
'ID9: 22 ID10: -111111111111111111 ID11: -22\n'
'ID12: 2222222222222222222 ID13: 1.23456f ID14: 1.2e+2f '
'false_bool: 0 true_BOOL:t \n true_bool1: 1 false_BOOL1:f '
- 'False_bool: False True_bool: True')
+ 'False_bool: False True_bool: True X:iNf Y:-inF Z:nAN')
tokenizer = text_format.Tokenizer(text.splitlines())
methods = [(tokenizer.ConsumeIdentifier, 'identifier1'), ':',
(tokenizer.ConsumeString, 'string1'),
@@ -1247,7 +1298,13 @@ class TokenizerTest(unittest.TestCase):
(tokenizer.ConsumeIdentifier, 'False_bool'), ':',
(tokenizer.ConsumeBool, False),
(tokenizer.ConsumeIdentifier, 'True_bool'), ':',
- (tokenizer.ConsumeBool, True)]
+ (tokenizer.ConsumeBool, True),
+ (tokenizer.ConsumeIdentifier, 'X'), ':',
+ (tokenizer.ConsumeFloat, float('inf')),
+ (tokenizer.ConsumeIdentifier, 'Y'), ':',
+ (tokenizer.ConsumeFloat, float('-inf')),
+ (tokenizer.ConsumeIdentifier, 'Z'), ':',
+ (tokenizer.ConsumeFloat, float('nan'))]
i = 0
while not tokenizer.AtEnd():
@@ -1256,6 +1313,8 @@ class TokenizerTest(unittest.TestCase):
token = tokenizer.token
self.assertEqual(token, m)
tokenizer.NextToken()
+ elif isinstance(m[1], float) and math.isnan(m[1]):
+ self.assertTrue(math.isnan(m[0]()))
else:
self.assertEqual(m[1], m[0]())
i += 1
@@ -1274,10 +1333,15 @@ class TokenizerTest(unittest.TestCase):
self.assertEqual(int64_max + 1, tokenizer.ConsumeInteger())
self.assertTrue(tokenizer.AtEnd())
- text = '-0 0'
+ text = '-0 0 0 1.2'
tokenizer = text_format.Tokenizer(text.splitlines())
self.assertEqual(0, tokenizer.ConsumeInteger())
self.assertEqual(0, tokenizer.ConsumeInteger())
+ self.assertEqual(True, tokenizer.TryConsumeInteger())
+ self.assertEqual(False, tokenizer.TryConsumeInteger())
+ with self.assertRaises(text_format.ParseError):
+ tokenizer.ConsumeInteger()
+ self.assertEqual(1.2, tokenizer.ConsumeFloat())
self.assertTrue(tokenizer.AtEnd())
def testConsumeIntegers(self):
@@ -1373,6 +1437,148 @@ class TokenizerTest(unittest.TestCase):
self.assertEqual('# some comment', tokenizer.ConsumeComment())
self.assertTrue(tokenizer.AtEnd())
+ def testConsumeLineComment(self):
+ tokenizer = text_format.Tokenizer('# some comment'.splitlines(),
+ skip_comments=False)
+ self.assertFalse(tokenizer.AtEnd())
+ self.assertEqual((False, '# some comment'),
+ tokenizer.ConsumeCommentOrTrailingComment())
+ self.assertTrue(tokenizer.AtEnd())
+
+ def testConsumeTwoLineComments(self):
+ text = '# some comment\n# another comment'
+ tokenizer = text_format.Tokenizer(text.splitlines(), skip_comments=False)
+ self.assertEqual((False, '# some comment'),
+ tokenizer.ConsumeCommentOrTrailingComment())
+ self.assertFalse(tokenizer.AtEnd())
+ self.assertEqual((False, '# another comment'),
+ tokenizer.ConsumeCommentOrTrailingComment())
+ self.assertTrue(tokenizer.AtEnd())
+
+ def testConsumeAndCheckTrailingComment(self):
+ text = 'some_number: 4 # some comment' # trailing comment on the same line
+ tokenizer = text_format.Tokenizer(text.splitlines(), skip_comments=False)
+ self.assertRaises(text_format.ParseError,
+ tokenizer.ConsumeCommentOrTrailingComment)
+
+ self.assertEqual('some_number', tokenizer.ConsumeIdentifier())
+ self.assertEqual(tokenizer.token, ':')
+ tokenizer.NextToken()
+ self.assertRaises(text_format.ParseError,
+ tokenizer.ConsumeCommentOrTrailingComment)
+ self.assertEqual(4, tokenizer.ConsumeInteger())
+ self.assertFalse(tokenizer.AtEnd())
+
+ self.assertEqual((True, '# some comment'),
+ tokenizer.ConsumeCommentOrTrailingComment())
+ self.assertTrue(tokenizer.AtEnd())
+
+ def testHashinComment(self):
+ text = 'some_number: 4 # some comment # not a new comment'
+ tokenizer = text_format.Tokenizer(text.splitlines(), skip_comments=False)
+ self.assertEqual('some_number', tokenizer.ConsumeIdentifier())
+ self.assertEqual(tokenizer.token, ':')
+ tokenizer.NextToken()
+ self.assertEqual(4, tokenizer.ConsumeInteger())
+ self.assertEqual((True, '# some comment # not a new comment'),
+ tokenizer.ConsumeCommentOrTrailingComment())
+ self.assertTrue(tokenizer.AtEnd())
+
+
+# Tests for pretty printer functionality.
+@_parameterized.Parameters((unittest_pb2), (unittest_proto3_arena_pb2))
+class PrettyPrinterTest(TextFormatBase):
+
+ def testPrettyPrintNoMatch(self, message_module):
+
+ def printer(message, indent, as_one_line):
+ del message, indent, as_one_line
+ return None
+
+ message = message_module.TestAllTypes()
+ msg = message.repeated_nested_message.add()
+ msg.bb = 42
+ self.CompareToGoldenText(
+ text_format.MessageToString(
+ message, as_one_line=True, message_formatter=printer),
+ 'repeated_nested_message { bb: 42 }')
+
+ def testPrettyPrintOneLine(self, message_module):
+
+ def printer(m, indent, as_one_line):
+ del indent, as_one_line
+ if m.DESCRIPTOR == message_module.TestAllTypes.NestedMessage.DESCRIPTOR:
+ return 'My lucky number is %s' % m.bb
+
+ message = message_module.TestAllTypes()
+ msg = message.repeated_nested_message.add()
+ msg.bb = 42
+ self.CompareToGoldenText(
+ text_format.MessageToString(
+ message, as_one_line=True, message_formatter=printer),
+ 'repeated_nested_message { My lucky number is 42 }')
+
+ def testPrettyPrintMultiLine(self, message_module):
+
+ def printer(m, indent, as_one_line):
+ if m.DESCRIPTOR == message_module.TestAllTypes.NestedMessage.DESCRIPTOR:
+ line_deliminator = (' ' if as_one_line else '\n') + ' ' * indent
+ return 'My lucky number is:%s%s' % (line_deliminator, m.bb)
+ return None
+
+ message = message_module.TestAllTypes()
+ msg = message.repeated_nested_message.add()
+ msg.bb = 42
+ self.CompareToGoldenText(
+ text_format.MessageToString(
+ message, as_one_line=True, message_formatter=printer),
+ 'repeated_nested_message { My lucky number is: 42 }')
+ self.CompareToGoldenText(
+ text_format.MessageToString(
+ message, as_one_line=False, message_formatter=printer),
+ 'repeated_nested_message {\n My lucky number is:\n 42\n}\n')
+
+ def testPrettyPrintEntireMessage(self, message_module):
+
+ def printer(m, indent, as_one_line):
+ del indent, as_one_line
+ if m.DESCRIPTOR == message_module.TestAllTypes.DESCRIPTOR:
+ return 'The is the message!'
+ return None
+
+ message = message_module.TestAllTypes()
+ self.CompareToGoldenText(
+ text_format.MessageToString(
+ message, as_one_line=False, message_formatter=printer),
+ 'The is the message!\n')
+ self.CompareToGoldenText(
+ text_format.MessageToString(
+ message, as_one_line=True, message_formatter=printer),
+ 'The is the message!')
+
+ def testPrettyPrintMultipleParts(self, message_module):
+
+ def printer(m, indent, as_one_line):
+ del indent, as_one_line
+ if m.DESCRIPTOR == message_module.TestAllTypes.NestedMessage.DESCRIPTOR:
+ return 'My lucky number is %s' % m.bb
+ return None
+
+ message = message_module.TestAllTypes()
+ message.optional_int32 = 61
+ msg = message.repeated_nested_message.add()
+ msg.bb = 42
+ msg = message.repeated_nested_message.add()
+ msg.bb = 99
+ msg = message.optional_nested_message
+ msg.bb = 1
+ self.CompareToGoldenText(
+ text_format.MessageToString(
+ message, as_one_line=True, message_formatter=printer),
+ ('optional_int32: 61 '
+ 'optional_nested_message { My lucky number is 1 } '
+ 'repeated_nested_message { My lucky number is 42 } '
+ 'repeated_nested_message { My lucky number is 99 }'))
if __name__ == '__main__':
unittest.main()
diff --git a/python/google/protobuf/internal/unknown_fields_test.py b/python/google/protobuf/internal/unknown_fields_test.py
index d614eaa8..8b7de2e7 100755
--- a/python/google/protobuf/internal/unknown_fields_test.py
+++ b/python/google/protobuf/internal/unknown_fields_test.py
@@ -54,10 +54,13 @@ from google.protobuf.internal import type_checkers
BaseTestCase = testing_refleaks.BaseTestCase
-def SkipIfCppImplementation(func):
+# CheckUnknownField() cannot be used by the C++ implementation because
+# some protect members are called. It is not a behavior difference
+# for python and C++ implementation.
+def SkipCheckUnknownFieldIfCppImplementation(func):
return unittest.skipIf(
api_implementation.Type() == 'cpp' and api_implementation.Version() == 2,
- 'C++ implementation does not expose unknown fields to Python')(func)
+ 'Addtional test for pure python involved protect members')(func)
class UnknownFieldsTest(BaseTestCase):
@@ -77,11 +80,23 @@ class UnknownFieldsTest(BaseTestCase):
# stdout.
self.assertTrue(data == self.all_fields_data)
- def testSerializeProto3(self):
- # Verify that proto3 doesn't preserve unknown fields.
+ def expectSerializeProto3(self, preserve):
message = unittest_proto3_arena_pb2.TestEmptyMessage()
message.ParseFromString(self.all_fields_data)
- self.assertEqual(0, len(message.SerializeToString()))
+ if preserve:
+ self.assertEqual(self.all_fields_data, message.SerializeToString())
+ else:
+ self.assertEqual(0, len(message.SerializeToString()))
+
+ def testSerializeProto3(self):
+ # Verify that proto3 unknown fields behavior.
+ default_preserve = (api_implementation
+ .GetPythonProto3PreserveUnknownsDefault())
+ self.expectSerializeProto3(default_preserve)
+ api_implementation.SetPythonProto3PreserveUnknownsDefault(
+ not default_preserve)
+ self.expectSerializeProto3(not default_preserve)
+ api_implementation.SetPythonProto3PreserveUnknownsDefault(default_preserve)
def testByteSize(self):
self.assertEqual(self.all_fields.ByteSize(), self.empty_message.ByteSize())
@@ -154,12 +169,13 @@ class UnknownFieldsAccessorsTest(BaseTestCase):
self.empty_message = unittest_pb2.TestEmptyMessage()
self.empty_message.ParseFromString(self.all_fields_data)
- # GetUnknownField() checks a detail of the Python implementation, which stores
- # unknown fields as serialized strings. It cannot be used by the C++
- # implementation: it's enough to check that the message is correctly
- # serialized.
+ # CheckUnknownField() is an additional Pure Python check which checks
+ # a detail of unknown fields. It cannot be used by the C++
+ # implementation because some protect members are called.
+ # The test is added for historical reasons. It is not necessary as
+ # serialized string is checked.
- def GetUnknownField(self, name):
+ def CheckUnknownField(self, name, expected_value):
field_descriptor = self.descriptor.fields_by_name[name]
wire_type = type_checkers.FIELD_TYPE_TO_WIRE_TYPE[field_descriptor.type]
field_tag = encoder.TagBytes(field_descriptor.number, wire_type)
@@ -168,42 +184,35 @@ class UnknownFieldsAccessorsTest(BaseTestCase):
if tag_bytes == field_tag:
decoder = unittest_pb2.TestAllTypes._decoders_by_tag[tag_bytes][0]
decoder(value, 0, len(value), self.all_fields, result_dict)
- return result_dict[field_descriptor]
-
- @SkipIfCppImplementation
- def testEnum(self):
- value = self.GetUnknownField('optional_nested_enum')
- self.assertEqual(self.all_fields.optional_nested_enum, value)
-
- @SkipIfCppImplementation
- def testRepeatedEnum(self):
- value = self.GetUnknownField('repeated_nested_enum')
- self.assertEqual(self.all_fields.repeated_nested_enum, value)
-
- @SkipIfCppImplementation
- def testVarint(self):
- value = self.GetUnknownField('optional_int32')
- self.assertEqual(self.all_fields.optional_int32, value)
-
- @SkipIfCppImplementation
- def testFixed32(self):
- value = self.GetUnknownField('optional_fixed32')
- self.assertEqual(self.all_fields.optional_fixed32, value)
-
- @SkipIfCppImplementation
- def testFixed64(self):
- value = self.GetUnknownField('optional_fixed64')
- self.assertEqual(self.all_fields.optional_fixed64, value)
-
- @SkipIfCppImplementation
- def testLengthDelimited(self):
- value = self.GetUnknownField('optional_string')
- self.assertEqual(self.all_fields.optional_string, value)
-
- @SkipIfCppImplementation
- def testGroup(self):
- value = self.GetUnknownField('optionalgroup')
- self.assertEqual(self.all_fields.optionalgroup, value)
+ self.assertEqual(expected_value, result_dict[field_descriptor])
+
+ @SkipCheckUnknownFieldIfCppImplementation
+ def testCheckUnknownFieldValue(self):
+ # Test enum.
+ self.CheckUnknownField('optional_nested_enum',
+ self.all_fields.optional_nested_enum)
+ # Test repeated enum.
+ self.CheckUnknownField('repeated_nested_enum',
+ self.all_fields.repeated_nested_enum)
+
+ # Test varint.
+ self.CheckUnknownField('optional_int32',
+ self.all_fields.optional_int32)
+ # Test fixed32.
+ self.CheckUnknownField('optional_fixed32',
+ self.all_fields.optional_fixed32)
+
+ # Test fixed64.
+ self.CheckUnknownField('optional_fixed64',
+ self.all_fields.optional_fixed64)
+
+ # Test lengthd elimited.
+ self.CheckUnknownField('optional_string',
+ self.all_fields.optional_string)
+
+ # Test group.
+ self.CheckUnknownField('optionalgroup',
+ self.all_fields.optionalgroup)
def testCopyFrom(self):
message = unittest_pb2.TestEmptyMessage()
@@ -263,12 +272,13 @@ class UnknownEnumValuesTest(BaseTestCase):
self.missing_message = missing_enum_values_pb2.TestMissingEnumValues()
self.missing_message.ParseFromString(self.message_data)
- # GetUnknownField() checks a detail of the Python implementation, which stores
- # unknown fields as serialized strings. It cannot be used by the C++
- # implementation: it's enough to check that the message is correctly
- # serialized.
+ # CheckUnknownField() is an additional Pure Python check which checks
+ # a detail of unknown fields. It cannot be used by the C++
+ # implementation because some protect members are called.
+ # The test is added for historical reasons. It is not necessary as
+ # serialized string is checked.
- def GetUnknownField(self, name):
+ def CheckUnknownField(self, name, expected_value):
field_descriptor = self.descriptor.fields_by_name[name]
wire_type = type_checkers.FIELD_TYPE_TO_WIRE_TYPE[field_descriptor.type]
field_tag = encoder.TagBytes(field_descriptor.number, wire_type)
@@ -278,7 +288,7 @@ class UnknownEnumValuesTest(BaseTestCase):
decoder = missing_enum_values_pb2.TestEnumValues._decoders_by_tag[
tag_bytes][0]
decoder(value, 0, len(value), self.message, result_dict)
- return result_dict[field_descriptor]
+ self.assertEqual(expected_value, result_dict[field_descriptor])
def testUnknownParseMismatchEnumValue(self):
just_string = missing_enum_values_pb2.JustString()
@@ -294,38 +304,27 @@ class UnknownEnumValuesTest(BaseTestCase):
self.assertEqual(missing.optional_nested_enum, 0)
def testUnknownEnumValue(self):
- if api_implementation.Type() == 'cpp':
- # The CPP implementation of protos (wrongly) allows unknown enum values
- # for proto2.
- self.assertTrue(self.missing_message.HasField('optional_nested_enum'))
- self.assertEqual(self.message.optional_nested_enum,
- self.missing_message.optional_nested_enum)
- else:
- # On the other hand, the Python implementation considers unknown values
- # as unknown fields. This is the correct behavior.
- self.assertFalse(self.missing_message.HasField('optional_nested_enum'))
- value = self.GetUnknownField('optional_nested_enum')
- self.assertEqual(self.message.optional_nested_enum, value)
- self.missing_message.ClearField('optional_nested_enum')
self.assertFalse(self.missing_message.HasField('optional_nested_enum'))
+ self.assertEqual(self.missing_message.optional_nested_enum, 2)
+ # Clear does not do anything.
+ serialized = self.missing_message.SerializeToString()
+ self.missing_message.ClearField('optional_nested_enum')
+ self.assertEqual(self.missing_message.SerializeToString(), serialized)
def testUnknownRepeatedEnumValue(self):
- if api_implementation.Type() == 'cpp':
- # For repeated enums, both implementations agree.
- self.assertEqual([], self.missing_message.repeated_nested_enum)
- else:
- self.assertEqual([], self.missing_message.repeated_nested_enum)
- value = self.GetUnknownField('repeated_nested_enum')
- self.assertEqual(self.message.repeated_nested_enum, value)
+ self.assertEqual([], self.missing_message.repeated_nested_enum)
def testUnknownPackedEnumValue(self):
- if api_implementation.Type() == 'cpp':
- # For repeated enums, both implementations agree.
- self.assertEqual([], self.missing_message.packed_nested_enum)
- else:
- self.assertEqual([], self.missing_message.packed_nested_enum)
- value = self.GetUnknownField('packed_nested_enum')
- self.assertEqual(self.message.packed_nested_enum, value)
+ self.assertEqual([], self.missing_message.packed_nested_enum)
+
+ @SkipCheckUnknownFieldIfCppImplementation
+ def testCheckUnknownFieldValueForEnum(self):
+ self.CheckUnknownField('optional_nested_enum',
+ self.message.optional_nested_enum)
+ self.CheckUnknownField('repeated_nested_enum',
+ self.message.repeated_nested_enum)
+ self.CheckUnknownField('packed_nested_enum',
+ self.message.packed_nested_enum)
def testRoundTrip(self):
new_message = missing_enum_values_pb2.TestEnumValues()
diff --git a/python/google/protobuf/internal/well_known_types.py b/python/google/protobuf/internal/well_known_types.py
index d631abee..3573770b 100644
--- a/python/google/protobuf/internal/well_known_types.py
+++ b/python/google/protobuf/internal/well_known_types.py
@@ -40,6 +40,7 @@ This files defines well known classes which need extra maintenance including:
__author__ = 'jieluo@google.com (Jie Luo)'
+import collections
from datetime import datetime
from datetime import timedelta
import six
@@ -67,13 +68,14 @@ class ParseError(Error):
class Any(object):
"""Class for Any Message type."""
- def Pack(self, msg, type_url_prefix='type.googleapis.com/'):
+ def Pack(self, msg, type_url_prefix='type.googleapis.com/',
+ deterministic=None):
"""Packs the specified message into current Any message."""
if len(type_url_prefix) < 1 or type_url_prefix[-1] != '/':
self.type_url = '%s/%s' % (type_url_prefix, msg.DESCRIPTOR.full_name)
else:
self.type_url = '%s%s' % (type_url_prefix, msg.DESCRIPTOR.full_name)
- self.value = msg.SerializeToString()
+ self.value = msg.SerializeToString(deterministic=deterministic)
def Unpack(self, msg):
"""Unpacks the current Any message into specified message."""
@@ -350,12 +352,12 @@ class Duration(object):
self.nanos, _NANOS_PER_MICROSECOND))
def FromTimedelta(self, td):
- """Convertd timedelta to Duration."""
+ """Converts timedelta to Duration."""
self._NormalizeDuration(td.seconds + td.days * _SECONDS_PER_DAY,
td.microseconds * _NANOS_PER_MICROSECOND)
def _NormalizeDuration(self, seconds, nanos):
- """Set Duration by seconds and nonas."""
+ """Set Duration by seconds and nanos."""
# Force nanos to be negative if the duration is negative.
if seconds < 0 and nanos > 0:
seconds += 1
@@ -473,7 +475,7 @@ def _IsValidPath(message_descriptor, path):
parts = path.split('.')
last = parts.pop()
for name in parts:
- field = message_descriptor.fields_by_name[name]
+ field = message_descriptor.fields_by_name.get(name)
if (field is None or
field.label == FieldDescriptor.LABEL_REPEATED or
field.type != FieldDescriptor.TYPE_MESSAGE):
@@ -698,6 +700,12 @@ def _SetStructValue(struct_value, value):
struct_value.string_value = value
elif isinstance(value, _INT_OR_FLOAT):
struct_value.number_value = value
+ elif isinstance(value, dict):
+ struct_value.struct_value.Clear()
+ struct_value.struct_value.update(value)
+ elif isinstance(value, list):
+ struct_value.list_value.Clear()
+ struct_value.list_value.extend(value)
else:
raise ValueError('Unexpected type')
@@ -728,18 +736,49 @@ class Struct(object):
def __getitem__(self, key):
return _GetStructValue(self.fields[key])
+ def __contains__(self, item):
+ return item in self.fields
+
def __setitem__(self, key, value):
_SetStructValue(self.fields[key], value)
+ def __delitem__(self, key):
+ del self.fields[key]
+
+ def __len__(self):
+ return len(self.fields)
+
+ def __iter__(self):
+ return iter(self.fields)
+
+ def keys(self): # pylint: disable=invalid-name
+ return self.fields.keys()
+
+ def values(self): # pylint: disable=invalid-name
+ return [self[key] for key in self]
+
+ def items(self): # pylint: disable=invalid-name
+ return [(key, self[key]) for key in self]
+
def get_or_create_list(self, key):
"""Returns a list for this key, creating if it didn't exist already."""
+ if not self.fields[key].HasField('list_value'):
+ # Clear will mark list_value modified which will indeed create a list.
+ self.fields[key].list_value.Clear()
return self.fields[key].list_value
def get_or_create_struct(self, key):
"""Returns a struct for this key, creating if it didn't exist already."""
+ if not self.fields[key].HasField('struct_value'):
+ # Clear will mark struct_value modified which will indeed create a struct.
+ self.fields[key].struct_value.Clear()
return self.fields[key].struct_value
- # TODO(haberman): allow constructing/merging from dict.
+ def update(self, dictionary): # pylint: disable=invalid-name
+ for key, value in dictionary.items():
+ _SetStructValue(self.fields[key], value)
+
+collections.MutableMapping.register(Struct)
class ListValue(object):
@@ -762,17 +801,28 @@ class ListValue(object):
def __setitem__(self, index, value):
_SetStructValue(self.values.__getitem__(index), value)
+ def __delitem__(self, key):
+ del self.values[key]
+
def items(self):
for i in range(len(self)):
yield self[i]
def add_struct(self):
"""Appends and returns a struct value as the next value in the list."""
- return self.values.add().struct_value
+ struct_value = self.values.add().struct_value
+ # Clear will mark struct_value modified which will indeed create a struct.
+ struct_value.Clear()
+ return struct_value
def add_list(self):
"""Appends and returns a list value as the next value in the list."""
- return self.values.add().list_value
+ list_value = self.values.add().list_value
+ # Clear will mark list_value modified which will indeed create a list.
+ list_value.Clear()
+ return list_value
+
+collections.MutableSequence.register(ListValue)
WKTBASES = {
diff --git a/python/google/protobuf/internal/well_known_types_test.py b/python/google/protobuf/internal/well_known_types_test.py
index 077f630f..573bc37d 100644
--- a/python/google/protobuf/internal/well_known_types_test.py
+++ b/python/google/protobuf/internal/well_known_types_test.py
@@ -34,6 +34,7 @@
__author__ = 'jieluo@google.com (Jie Luo)'
+import collections
from datetime import datetime
try:
@@ -100,11 +101,15 @@ class TimeUtilTest(TimeUtilTestBase):
message.FromJsonString('1970-01-01T00:00:00.1Z')
self.assertEqual(0, message.seconds)
self.assertEqual(100000000, message.nanos)
- # Parsing accpets offsets.
+ # Parsing accepts offsets.
message.FromJsonString('1970-01-01T00:00:00-08:00')
self.assertEqual(8 * 3600, message.seconds)
self.assertEqual(0, message.nanos)
+ # It is not easy to check with current time. For test coverage only.
+ message.GetCurrentTime()
+ self.assertNotEqual(8 * 3600, message.seconds)
+
def testDurationSerializeAndParse(self):
message = duration_pb2.Duration()
# Generated output should contain 3, 6, or 9 fractional digits.
@@ -268,6 +273,17 @@ class TimeUtilTest(TimeUtilTestBase):
def testInvalidTimestamp(self):
message = timestamp_pb2.Timestamp()
self.assertRaisesRegexp(
+ well_known_types.ParseError,
+ 'Failed to parse timestamp: missing valid timezone offset.',
+ message.FromJsonString,
+ '')
+ self.assertRaisesRegexp(
+ well_known_types.ParseError,
+ 'Failed to parse timestamp: invalid trailing data '
+ '1970-01-01T00:00:01Ztrail.',
+ message.FromJsonString,
+ '1970-01-01T00:00:01Ztrail')
+ self.assertRaisesRegexp(
ValueError,
'time data \'10000-01-01T00:00:00\' does not match'
' format \'%Y-%m-%dT%H:%M:%S\'',
@@ -284,7 +300,7 @@ class TimeUtilTest(TimeUtilTestBase):
'1972-01-01T01:00:00.01+08',)
self.assertRaisesRegexp(
ValueError,
- 'year is out of range',
+ 'year (0 )?is out of range',
message.FromJsonString,
'0000-01-01T00:00:00Z')
message.seconds = 253402300800
@@ -322,6 +338,13 @@ class TimeUtilTest(TimeUtilTestBase):
r'Duration is not valid\: Seconds -315576000001 must be in range'
r' \[-315576000000\, 315576000000\].',
message.ToJsonString)
+ message.seconds = 0
+ message.nanos = 999999999 + 1
+ self.assertRaisesRegexp(
+ well_known_types.Error,
+ r'Duration is not valid\: Nanos 1000000000 must be in range'
+ r' \[-999999999\, 999999999\].',
+ message.ToJsonString)
class FieldMaskTest(unittest.TestCase):
@@ -363,10 +386,37 @@ class FieldMaskTest(unittest.TestCase):
self.assertTrue(mask.IsValidForDescriptor(msg_descriptor))
for field in msg_descriptor.fields:
self.assertTrue(field.name in mask.paths)
+
+ def testIsValidForDescriptor(self):
+ msg_descriptor = unittest_pb2.TestAllTypes.DESCRIPTOR
+ # Empty mask
+ mask = field_mask_pb2.FieldMask()
+ self.assertTrue(mask.IsValidForDescriptor(msg_descriptor))
+ # All fields from descriptor
+ mask.AllFieldsFromDescriptor(msg_descriptor)
+ self.assertTrue(mask.IsValidForDescriptor(msg_descriptor))
+ # Child under optional message
mask.paths.append('optional_nested_message.bb')
self.assertTrue(mask.IsValidForDescriptor(msg_descriptor))
+ # Repeated field is only allowed in the last position of path
mask.paths.append('repeated_nested_message.bb')
self.assertFalse(mask.IsValidForDescriptor(msg_descriptor))
+ # Invalid top level field
+ mask = field_mask_pb2.FieldMask()
+ mask.paths.append('xxx')
+ self.assertFalse(mask.IsValidForDescriptor(msg_descriptor))
+ # Invalid field in root
+ mask = field_mask_pb2.FieldMask()
+ mask.paths.append('xxx.zzz')
+ self.assertFalse(mask.IsValidForDescriptor(msg_descriptor))
+ # Invalid field in internal node
+ mask = field_mask_pb2.FieldMask()
+ mask.paths.append('optional_nested_message.xxx.zzz')
+ self.assertFalse(mask.IsValidForDescriptor(msg_descriptor))
+ # Invalid field in leaf
+ mask = field_mask_pb2.FieldMask()
+ mask.paths.append('optional_nested_message.xxx')
+ self.assertFalse(mask.IsValidForDescriptor(msg_descriptor))
def testCanonicalFrom(self):
mask = field_mask_pb2.FieldMask()
@@ -422,6 +472,9 @@ class FieldMaskTest(unittest.TestCase):
mask2.FromJsonString('foo.bar,bar')
out_mask.Union(mask1, mask2)
self.assertEqual('bar,foo.bar,quz', out_mask.ToJsonString())
+ src = unittest_pb2.TestAllTypes()
+ with self.assertRaises(ValueError):
+ out_mask.Union(src, mask2)
def testIntersect(self):
mask1 = field_mask_pb2.FieldMask()
@@ -546,6 +599,19 @@ class FieldMaskTest(unittest.TestCase):
self.assertEqual(1, len(nested_dst.payload.repeated_int32))
self.assertEqual(1234, nested_dst.payload.repeated_int32[0])
+ def testMergeErrors(self):
+ src = unittest_pb2.TestAllTypes()
+ dst = unittest_pb2.TestAllTypes()
+ mask = field_mask_pb2.FieldMask()
+ test_util.SetAllFields(src)
+ mask.FromJsonString('optionalInt32.field')
+ with self.assertRaises(ValueError) as e:
+ mask.MergeMessage(src, dst)
+ self.assertEqual('Error: Field optional_int32 in message '
+ 'protobuf_unittest.TestAllTypes is not a singular '
+ 'message field and cannot have sub-fields.',
+ str(e.exception))
+
def testSnakeCaseToCamelCase(self):
self.assertEqual('fooBar',
well_known_types._SnakeCaseToCamelCase('foo_bar'))
@@ -602,6 +668,8 @@ class StructTest(unittest.TestCase):
def testStruct(self):
struct = struct_pb2.Struct()
+ self.assertIsInstance(struct, collections.Mapping)
+ self.assertEqual(0, len(struct))
struct_class = struct.__class__
struct['key1'] = 5
@@ -609,9 +677,13 @@ class StructTest(unittest.TestCase):
struct['key3'] = True
struct.get_or_create_struct('key4')['subkey'] = 11.0
struct_list = struct.get_or_create_list('key5')
+ self.assertIsInstance(struct_list, collections.Sequence)
struct_list.extend([6, 'seven', True, False, None])
struct_list.add_struct()['subkey2'] = 9
+ struct['key6'] = {'subkey': {}}
+ struct['key7'] = [2, False]
+ self.assertEqual(7, len(struct))
self.assertTrue(isinstance(struct, well_known_types.Struct))
self.assertEqual(5, struct['key1'])
self.assertEqual('abc', struct['key2'])
@@ -621,13 +693,28 @@ class StructTest(unittest.TestCase):
inner_struct['subkey2'] = 9
self.assertEqual([6, 'seven', True, False, None, inner_struct],
list(struct['key5'].items()))
+ self.assertEqual({}, dict(struct['key6']['subkey'].fields))
+ self.assertEqual([2, False], list(struct['key7'].items()))
serialized = struct.SerializeToString()
-
struct2 = struct_pb2.Struct()
struct2.ParseFromString(serialized)
self.assertEqual(struct, struct2)
+ for key, value in struct.items():
+ self.assertIn(key, struct)
+ self.assertIn(key, struct2)
+ self.assertEqual(value, struct2[key])
+
+ self.assertEqual(7, len(struct.keys()))
+ self.assertEqual(7, len(struct.values()))
+ for key in struct.keys():
+ self.assertIn(key, struct)
+ self.assertIn(key, struct2)
+ self.assertEqual(struct[key], struct2[key])
+
+ item = (next(iter(struct.keys())), next(iter(struct.values())))
+ self.assertEqual(item, next(iter(struct.items())))
self.assertTrue(isinstance(struct2, well_known_types.Struct))
self.assertEqual(5, struct2['key1'])
@@ -651,6 +738,17 @@ class StructTest(unittest.TestCase):
struct_list.add_list().extend([1, 'two', True, False, None])
self.assertEqual([1, 'two', True, False, None],
list(struct_list[6].items()))
+ struct_list.extend([{'nested_struct': 30}, ['nested_list', 99], {}, []])
+ self.assertEqual(11, len(struct_list.values))
+ self.assertEqual(30, struct_list[7]['nested_struct'])
+ self.assertEqual('nested_list', struct_list[8][0])
+ self.assertEqual(99, struct_list[8][1])
+ self.assertEqual({}, dict(struct_list[9].fields))
+ self.assertEqual([], list(struct_list[10].items()))
+ struct_list[0] = {'replace': 'set'}
+ struct_list[1] = ['replace', 'set']
+ self.assertEqual('set', struct_list[0]['replace'])
+ self.assertEqual(['replace', 'set'], list(struct_list[1].items()))
text_serialized = str(struct)
struct3 = struct_pb2.Struct()
@@ -660,6 +758,77 @@ class StructTest(unittest.TestCase):
struct.get_or_create_struct('key3')['replace'] = 12
self.assertEqual(12, struct['key3']['replace'])
+ # Tests empty list.
+ struct.get_or_create_list('empty_list')
+ empty_list = struct['empty_list']
+ self.assertEqual([], list(empty_list.items()))
+ list2 = struct_pb2.ListValue()
+ list2.add_list()
+ empty_list = list2[0]
+ self.assertEqual([], list(empty_list.items()))
+
+ # Tests empty struct.
+ struct.get_or_create_struct('empty_struct')
+ empty_struct = struct['empty_struct']
+ self.assertEqual({}, dict(empty_struct.fields))
+ list2.add_struct()
+ empty_struct = list2[1]
+ self.assertEqual({}, dict(empty_struct.fields))
+
+ self.assertEqual(9, len(struct))
+ del struct['key3']
+ del struct['key4']
+ self.assertEqual(7, len(struct))
+ self.assertEqual(6, len(struct['key5']))
+ del struct['key5'][1]
+ self.assertEqual(5, len(struct['key5']))
+ self.assertEqual([6, True, False, None, inner_struct],
+ list(struct['key5'].items()))
+
+ def testMergeFrom(self):
+ struct = struct_pb2.Struct()
+ struct_class = struct.__class__
+
+ dictionary = {
+ 'key1': 5,
+ 'key2': 'abc',
+ 'key3': True,
+ 'key4': {'subkey': 11.0},
+ 'key5': [6, 'seven', True, False, None, {'subkey2': 9}],
+ 'key6': [['nested_list', True]],
+ 'empty_struct': {},
+ 'empty_list': []
+ }
+ struct.update(dictionary)
+ self.assertEqual(5, struct['key1'])
+ self.assertEqual('abc', struct['key2'])
+ self.assertIs(True, struct['key3'])
+ self.assertEqual(11, struct['key4']['subkey'])
+ inner_struct = struct_class()
+ inner_struct['subkey2'] = 9
+ self.assertEqual([6, 'seven', True, False, None, inner_struct],
+ list(struct['key5'].items()))
+ self.assertEqual(2, len(struct['key6'][0].values))
+ self.assertEqual('nested_list', struct['key6'][0][0])
+ self.assertEqual(True, struct['key6'][0][1])
+ empty_list = struct['empty_list']
+ self.assertEqual([], list(empty_list.items()))
+ empty_struct = struct['empty_struct']
+ self.assertEqual({}, dict(empty_struct.fields))
+
+ # According to documentation: "When parsing from the wire or when merging,
+ # if there are duplicate map keys the last key seen is used".
+ duplicate = {
+ 'key4': {'replace': 20},
+ 'key5': [[False, 5]]
+ }
+ struct.update(duplicate)
+ self.assertEqual(1, len(struct['key4'].fields))
+ self.assertEqual(20, struct['key4']['replace'])
+ self.assertEqual(1, len(struct['key5'].values))
+ self.assertEqual(False, struct['key5'][0][0])
+ self.assertEqual(5, struct['key5'][0][1])
+
class AnyTest(unittest.TestCase):
@@ -723,6 +892,20 @@ class AnyTest(unittest.TestCase):
self.assertTrue(msg.Unpack(unpacked_message))
self.assertEqual(submessage, unpacked_message)
+ def testPackDeterministic(self):
+ submessage = any_test_pb2.TestAny()
+ for i in range(10):
+ submessage.map_value[str(i)] = i * 2
+ msg = any_pb2.Any()
+ msg.Pack(submessage, deterministic=True)
+ serialized = msg.SerializeToString(deterministic=True)
+ golden = (b'\n4type.googleapis.com/google.protobuf.internal.TestAny\x12F'
+ b'\x1a\x05\n\x010\x10\x00\x1a\x05\n\x011\x10\x02\x1a\x05\n\x01'
+ b'2\x10\x04\x1a\x05\n\x013\x10\x06\x1a\x05\n\x014\x10\x08\x1a'
+ b'\x05\n\x015\x10\n\x1a\x05\n\x016\x10\x0c\x1a\x05\n\x017\x10'
+ b'\x0e\x1a\x05\n\x018\x10\x10\x1a\x05\n\x019\x10\x12')
+ self.assertEqual(golden, serialized)
+
if __name__ == '__main__':
unittest.main()
diff --git a/python/google/protobuf/json_format.py b/python/google/protobuf/json_format.py
index d02cb091..878291db 100644
--- a/python/google/protobuf/json_format.py
+++ b/python/google/protobuf/json_format.py
@@ -74,6 +74,9 @@ _UNPAIRED_SURROGATE_PATTERN = re.compile(six.u(
r'[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]'
))
+_VALID_EXTENSION_NAME = re.compile(r'\[[a-zA-Z0-9\._]*\]$')
+
+
class Error(Exception):
"""Top-level module error for json_format."""
@@ -88,7 +91,9 @@ class ParseError(Error):
def MessageToJson(message,
including_default_value_fields=False,
- preserving_proto_field_name=False):
+ preserving_proto_field_name=False,
+ indent=2,
+ sort_keys=False):
"""Converts protobuf message to JSON format.
Args:
@@ -100,19 +105,24 @@ def MessageToJson(message,
preserving_proto_field_name: If True, use the original proto field
names as defined in the .proto file. If False, convert the field
names to lowerCamelCase.
+ indent: The JSON object will be pretty-printed with this indent level.
+ An indent level of 0 or negative will only insert newlines.
+ sort_keys: If True, then the output will be sorted by field names.
Returns:
A string containing the JSON formatted protocol buffer message.
"""
printer = _Printer(including_default_value_fields,
preserving_proto_field_name)
- return printer.ToJsonString(message)
+ return printer.ToJsonString(message, indent, sort_keys)
def MessageToDict(message,
including_default_value_fields=False,
preserving_proto_field_name=False):
- """Converts protobuf message to a JSON dictionary.
+ """Converts protobuf message to a dictionary.
+
+ When the dictionary is encoded to JSON, it conforms to proto3 JSON spec.
Args:
message: The protocol buffers message instance to serialize.
@@ -125,7 +135,7 @@ def MessageToDict(message,
names to lowerCamelCase.
Returns:
- A dict representation of the JSON formatted protocol buffer message.
+ A dict representation of the protocol buffer message.
"""
printer = _Printer(including_default_value_fields,
preserving_proto_field_name)
@@ -148,9 +158,9 @@ class _Printer(object):
self.including_default_value_fields = including_default_value_fields
self.preserving_proto_field_name = preserving_proto_field_name
- def ToJsonString(self, message):
+ def ToJsonString(self, message, indent, sort_keys):
js = self._MessageToJsonObject(message)
- return json.dumps(js, indent=2)
+ return json.dumps(js, indent=indent, sort_keys=sort_keys)
def _MessageToJsonObject(self, message):
"""Converts message to an object according to Proto3 JSON Specification."""
@@ -192,6 +202,14 @@ class _Printer(object):
# Convert a repeated field.
js[name] = [self._FieldToJsonObject(field, k)
for k in value]
+ elif field.is_extension:
+ f = field
+ if (f.containing_type.GetOptions().message_set_wire_format and
+ f.type == descriptor.FieldDescriptor.TYPE_MESSAGE and
+ f.label == descriptor.FieldDescriptor.LABEL_OPTIONAL):
+ f = f.message_type
+ name = '[%s.%s]' % (f.full_name, name)
+ js[name] = self._FieldToJsonObject(field, value)
else:
js[name] = self._FieldToJsonObject(field, value)
@@ -233,6 +251,8 @@ class _Printer(object):
if enum_value is not None:
return enum_value.name
else:
+ if field.file.syntax == 'proto3':
+ return value
raise SerializeToJsonError('Enum field contains an integer value '
'which can not mapped to an enum value.')
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING:
@@ -433,12 +453,23 @@ class _Parser(object):
field = fields_by_json_name.get(name, None)
if not field:
field = message_descriptor.fields_by_name.get(name, None)
+ if not field and _VALID_EXTENSION_NAME.match(name):
+ if not message_descriptor.is_extendable:
+ raise ParseError('Message type {0} does not have extensions'.format(
+ message_descriptor.full_name))
+ identifier = name[1:-1] # strip [] brackets
+ identifier = '.'.join(identifier.split('.')[:-1])
+ # pylint: disable=protected-access
+ field = message.Extensions._FindExtensionByName(identifier)
+ # pylint: enable=protected-access
if not field:
if self.ignore_unknown_fields:
continue
raise ParseError(
- 'Message type "{0}" has no field named "{1}".'.format(
- message_descriptor.full_name, name))
+ ('Message type "{0}" has no field named "{1}".\n'
+ ' Available Fields(except extensions): {2}').format(
+ message_descriptor.full_name, name,
+ message_descriptor.fields))
if name in names:
raise ParseError('Message type "{0}" should not have multiple '
'"{1}" fields.'.format(
@@ -491,7 +522,10 @@ class _Parser(object):
getattr(message, field.name).append(
_ConvertScalarFieldValue(item, field))
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
- sub_message = getattr(message, field.name)
+ if field.is_extension:
+ sub_message = message.Extensions[field]
+ else:
+ sub_message = getattr(message, field.name)
sub_message.SetInParent()
self.ConvertMessage(value, sub_message)
else:
@@ -532,8 +566,8 @@ class _Parser(object):
def _ConvertGenericMessage(self, value, message):
"""Convert a JSON representation into message with FromJsonString."""
- # Durantion, Timestamp, FieldMask have FromJsonString method to do the
- # convert. Users can also call the method directly.
+ # Duration, Timestamp, FieldMask have a FromJsonString method to do the
+ # conversion. Users can also call the method directly.
message.FromJsonString(value)
def _ConvertValueMessage(self, value, message):
@@ -643,6 +677,9 @@ def _ConvertScalarFieldValue(value, field, require_str=False):
raise ParseError('Invalid enum value {0} for enum type {1}.'.format(
value, field.enum_type.full_name))
if enum_value is None:
+ if field.file.syntax == 'proto3':
+ # Proto3 accepts unknown enums.
+ return number
raise ParseError('Invalid enum value {0} for enum type {1}.'.format(
value, field.enum_type.full_name))
return enum_value.number
diff --git a/python/google/protobuf/message.py b/python/google/protobuf/message.py
index aab250e4..eeb0d576 100755
--- a/python/google/protobuf/message.py
+++ b/python/google/protobuf/message.py
@@ -184,9 +184,15 @@ class Message(object):
self.Clear()
self.MergeFromString(serialized)
- def SerializeToString(self):
+ def SerializeToString(self, **kwargs):
"""Serializes the protocol message to a binary string.
+ Arguments:
+ **kwargs: Keyword arguments to the serialize method, accepts
+ the following keyword args:
+ deterministic: If true, requests deterministic serialization of the
+ protobuf, with predictable ordering of map keys.
+
Returns:
A binary string representation of the message if all of the required
fields in the message are set (i.e. the message is initialized).
@@ -196,12 +202,18 @@ class Message(object):
"""
raise NotImplementedError
- def SerializePartialToString(self):
+ def SerializePartialToString(self, **kwargs):
"""Serializes the protocol message to a binary string.
This method is similar to SerializeToString but doesn't check if the
message is initialized.
+ Arguments:
+ **kwargs: Keyword arguments to the serialize method, accepts
+ the following keyword args:
+ deterministic: If true, requests deterministic serialization of the
+ protobuf, with predictable ordering of map keys.
+
Returns:
A string representation of the partial message.
"""
diff --git a/python/google/protobuf/message_factory.py b/python/google/protobuf/message_factory.py
index 8ab1c513..e4fb065e 100644
--- a/python/google/protobuf/message_factory.py
+++ b/python/google/protobuf/message_factory.py
@@ -66,7 +66,7 @@ class MessageFactory(object):
Returns:
A class describing the passed in descriptor.
"""
- if descriptor.full_name not in self._classes:
+ if descriptor not in self._classes:
descriptor_name = descriptor.name
if str is bytes: # PY2
descriptor_name = descriptor.name.encode('ascii', 'ignore')
@@ -75,16 +75,16 @@ class MessageFactory(object):
(message.Message,),
{'DESCRIPTOR': descriptor, '__module__': None})
# If module not set, it wrongly points to the reflection.py module.
- self._classes[descriptor.full_name] = result_class
+ self._classes[descriptor] = result_class
for field in descriptor.fields:
if field.message_type:
self.GetPrototype(field.message_type)
for extension in result_class.DESCRIPTOR.extensions:
- if extension.containing_type.full_name not in self._classes:
+ if extension.containing_type not in self._classes:
self.GetPrototype(extension.containing_type)
- extended_class = self._classes[extension.containing_type.full_name]
+ extended_class = self._classes[extension.containing_type]
extended_class.RegisterExtension(extension)
- return self._classes[descriptor.full_name]
+ return self._classes[descriptor]
def GetMessages(self, files):
"""Gets all the messages from a specified file.
@@ -116,9 +116,9 @@ class MessageFactory(object):
# an error if they were different.
for extension in file_desc.extensions_by_name.values():
- if extension.containing_type.full_name not in self._classes:
+ if extension.containing_type not in self._classes:
self.GetPrototype(extension.containing_type)
- extended_class = self._classes[extension.containing_type.full_name]
+ extended_class = self._classes[extension.containing_type]
extended_class.RegisterExtension(extension)
return result
@@ -130,13 +130,22 @@ def GetMessages(file_protos):
"""Builds a dictionary of all the messages available in a set of files.
Args:
- file_protos: A sequence of file protos to build messages out of.
+ file_protos: Iterable of FileDescriptorProto to build messages out of.
Returns:
A dictionary mapping proto names to the message classes. This will include
any dependent messages as well as any messages defined in the same file as
a specified message.
"""
- for file_proto in file_protos:
+ # The cpp implementation of the protocol buffer library requires to add the
+ # message in topological order of the dependency graph.
+ file_by_name = {file_proto.name: file_proto for file_proto in file_protos}
+ def _AddFile(file_proto):
+ for dependency in file_proto.dependency:
+ if dependency in file_by_name:
+ # Remove from elements to be visited, in order to cut cycles.
+ _AddFile(file_by_name.pop(dependency))
_FACTORY.pool.Add(file_proto)
+ while file_by_name:
+ _AddFile(file_by_name.popitem()[1])
return _FACTORY.GetMessages([file_proto.name for file_proto in file_protos])
diff --git a/python/google/protobuf/pyext/descriptor.cc b/python/google/protobuf/pyext/descriptor.cc
index 924ae0b9..9634ea05 100644
--- a/python/google/protobuf/pyext/descriptor.cc
+++ b/python/google/protobuf/pyext/descriptor.cc
@@ -32,6 +32,7 @@
#include <Python.h>
#include <frameobject.h>
+#include <google/protobuf/stubs/hash.h>
#include <string>
#include <google/protobuf/io/coded_stream.h>
@@ -708,6 +709,10 @@ static PyObject* GetJsonName(PyBaseDescriptor* self, void *closure) {
return PyString_FromCppString(_GetDescriptor(self)->json_name());
}
+static PyObject* GetFile(PyBaseDescriptor *self, void *closure) {
+ return PyFileDescriptor_FromDescriptor(_GetDescriptor(self)->file());
+}
+
static PyObject* GetType(PyBaseDescriptor *self, void *closure) {
return PyInt_FromLong(_GetDescriptor(self)->type());
}
@@ -898,6 +903,7 @@ static PyGetSetDef Getters[] = {
{ "name", (getter)GetName, NULL, "Unqualified name"},
{ "camelcase_name", (getter)GetCamelcaseName, NULL, "Camelcase name"},
{ "json_name", (getter)GetJsonName, NULL, "Json name"},
+ { "file", (getter)GetFile, NULL, "File Descriptor"},
{ "type", (getter)GetType, NULL, "C++ Type"},
{ "cpp_type", (getter)GetCppType, NULL, "C++ Type"},
{ "label", (getter)GetLabel, NULL, "Label"},
@@ -1569,6 +1575,10 @@ static PyObject* GetFullName(PyBaseDescriptor* self, void *closure) {
return PyString_FromCppString(_GetDescriptor(self)->full_name());
}
+static PyObject* GetFile(PyBaseDescriptor *self, void *closure) {
+ return PyFileDescriptor_FromDescriptor(_GetDescriptor(self)->file());
+}
+
static PyObject* GetIndex(PyBaseDescriptor *self, void *closure) {
return PyInt_FromLong(_GetDescriptor(self)->index());
}
@@ -1610,6 +1620,7 @@ static PyObject* CopyToProto(PyBaseDescriptor *self, PyObject *target) {
static PyGetSetDef Getters[] = {
{ "name", (getter)GetName, NULL, "Name", NULL},
{ "full_name", (getter)GetFullName, NULL, "Full name", NULL},
+ { "file", (getter)GetFile, NULL, "File descriptor"},
{ "index", (getter)GetIndex, NULL, "Index", NULL},
{ "methods", (getter)GetMethods, NULL, "Methods", NULL},
@@ -1666,6 +1677,15 @@ PyObject* PyServiceDescriptor_FromDescriptor(
&PyServiceDescriptor_Type, service_descriptor, NULL);
}
+const ServiceDescriptor* PyServiceDescriptor_AsDescriptor(PyObject* obj) {
+ if (!PyObject_TypeCheck(obj, &PyServiceDescriptor_Type)) {
+ PyErr_SetString(PyExc_TypeError, "Not a ServiceDescriptor");
+ return NULL;
+ }
+ return reinterpret_cast<const ServiceDescriptor*>(
+ reinterpret_cast<PyBaseDescriptor*>(obj)->descriptor);
+}
+
namespace method_descriptor {
// Unchecked accessor to the C++ pointer.
@@ -1769,6 +1789,15 @@ PyObject* PyMethodDescriptor_FromDescriptor(
&PyMethodDescriptor_Type, method_descriptor, NULL);
}
+const MethodDescriptor* PyMethodDescriptor_AsDescriptor(PyObject* obj) {
+ if (!PyObject_TypeCheck(obj, &PyMethodDescriptor_Type)) {
+ PyErr_SetString(PyExc_TypeError, "Not a MethodDescriptor");
+ return NULL;
+ }
+ return reinterpret_cast<const MethodDescriptor*>(
+ reinterpret_cast<PyBaseDescriptor*>(obj)->descriptor);
+}
+
// Add a enum values to a type dictionary.
static bool AddEnumValues(PyTypeObject *type,
const EnumDescriptor* enum_descriptor) {
diff --git a/python/google/protobuf/pyext/descriptor.h b/python/google/protobuf/pyext/descriptor.h
index 1ae0e672..f081df84 100644
--- a/python/google/protobuf/pyext/descriptor.h
+++ b/python/google/protobuf/pyext/descriptor.h
@@ -80,6 +80,8 @@ const Descriptor* PyMessageDescriptor_AsDescriptor(PyObject* obj);
const FieldDescriptor* PyFieldDescriptor_AsDescriptor(PyObject* obj);
const EnumDescriptor* PyEnumDescriptor_AsDescriptor(PyObject* obj);
const FileDescriptor* PyFileDescriptor_AsDescriptor(PyObject* obj);
+const ServiceDescriptor* PyServiceDescriptor_AsDescriptor(PyObject* obj);
+const MethodDescriptor* PyMethodDescriptor_AsDescriptor(PyObject* obj);
// Returns the raw C++ pointer.
const void* PyDescriptor_AsVoidPtr(PyObject* obj);
diff --git a/python/google/protobuf/pyext/descriptor_pool.cc b/python/google/protobuf/pyext/descriptor_pool.cc
index fa66bf9a..16f4d49d 100644
--- a/python/google/protobuf/pyext/descriptor_pool.cc
+++ b/python/google/protobuf/pyext/descriptor_pool.cc
@@ -39,6 +39,7 @@
#include <google/protobuf/pyext/message.h>
#include <google/protobuf/pyext/message_factory.h>
#include <google/protobuf/pyext/scoped_pyobject_ptr.h>
+#include <google/protobuf/stubs/hash.h>
#if PY_MAJOR_VERSION >= 3
#define PyString_FromStringAndSize PyUnicode_FromStringAndSize
@@ -437,8 +438,23 @@ PyObject* AddExtensionDescriptor(PyDescriptorPool* self, PyObject* descriptor) {
Py_RETURN_NONE;
}
-// The code below loads new Descriptors from a serialized FileDescriptorProto.
+PyObject* AddServiceDescriptor(PyDescriptorPool* self, PyObject* descriptor) {
+ const ServiceDescriptor* service_descriptor =
+ PyServiceDescriptor_AsDescriptor(descriptor);
+ if (!service_descriptor) {
+ return NULL;
+ }
+ if (service_descriptor !=
+ self->pool->FindServiceByName(service_descriptor->full_name())) {
+ PyErr_Format(PyExc_ValueError,
+ "The service descriptor %s does not belong to this pool",
+ service_descriptor->full_name().c_str());
+ return NULL;
+ }
+ Py_RETURN_NONE;
+}
+// The code below loads new Descriptors from a serialized FileDescriptorProto.
// Collects errors that occur during proto file building to allow them to be
// propagated in the python exception instead of only living in ERROR logs.
@@ -538,6 +554,8 @@ static PyMethodDef Methods[] = {
"No-op. Add() must have been called before." },
{ "AddExtensionDescriptor", (PyCFunction)AddExtensionDescriptor, METH_O,
"No-op. Add() must have been called before." },
+ { "AddServiceDescriptor", (PyCFunction)AddServiceDescriptor, METH_O,
+ "No-op. Add() must have been called before." },
{ "FindFileByName", (PyCFunction)FindFileByName, METH_O,
"Searches for a file descriptor by its .proto name." },
diff --git a/python/google/protobuf/pyext/descriptor_pool.h b/python/google/protobuf/pyext/descriptor_pool.h
index c4d7d403..53ee53dc 100644
--- a/python/google/protobuf/pyext/descriptor_pool.h
+++ b/python/google/protobuf/pyext/descriptor_pool.h
@@ -85,6 +85,7 @@ extern PyTypeObject PyDescriptorPool_Type;
namespace cdescriptor_pool {
+
// Looks up a message by name.
// Returns a message Descriptor, or NULL if not found.
const Descriptor* FindMessageTypeByName(PyDescriptorPool* self,
diff --git a/python/google/protobuf/pyext/extension_dict.cc b/python/google/protobuf/pyext/extension_dict.cc
index 9423c1d8..6830b10d 100644
--- a/python/google/protobuf/pyext/extension_dict.cc
+++ b/python/google/protobuf/pyext/extension_dict.cc
@@ -32,6 +32,10 @@
// Author: tibell@google.com (Johan Tibell)
#include <google/protobuf/pyext/extension_dict.h>
+#include <memory>
+#ifndef _SHARED_PTR_H
+#include <google/protobuf/stubs/shared_ptr.h>
+#endif
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
@@ -45,7 +49,6 @@
#include <google/protobuf/pyext/repeated_composite_container.h>
#include <google/protobuf/pyext/repeated_scalar_container.h>
#include <google/protobuf/pyext/scoped_pyobject_ptr.h>
-#include <google/protobuf/stubs/shared_ptr.h>
#if PY_MAJOR_VERSION >= 3
#if PY_VERSION_HEX < 0x03030000
@@ -126,6 +129,8 @@ PyObject* subscript(ExtensionDict* self, PyObject* key) {
CMessageClass* message_class = message_factory::GetOrCreateMessageClass(
cmessage::GetFactoryForMessage(self->parent),
descriptor->message_type());
+ ScopedPyObjectPtr message_class_handler(
+ reinterpret_cast<PyObject*>(message_class));
if (message_class == NULL) {
return NULL;
}
diff --git a/python/google/protobuf/pyext/map_container.cc b/python/google/protobuf/pyext/map_container.cc
index 088ddf93..abd15b77 100644
--- a/python/google/protobuf/pyext/map_container.cc
+++ b/python/google/protobuf/pyext/map_container.cc
@@ -712,8 +712,33 @@ int MapReflectionFriend::MessageMapSetItem(PyObject* _self, PyObject* key,
}
// Delete key from map.
- if (reflection->DeleteMapValue(message, self->parent_field_descriptor,
+ if (reflection->ContainsMapKey(*message, self->parent_field_descriptor,
map_key)) {
+ // Delete key from CMessage dict.
+ MapValueRef value;
+ reflection->InsertOrLookupMapValue(message, self->parent_field_descriptor,
+ map_key, &value);
+ ScopedPyObjectPtr key(PyLong_FromVoidPtr(value.MutableMessageValue()));
+
+ PyObject* cmsg_value = PyDict_GetItem(self->message_dict, key.get());
+ if (cmsg_value) {
+ // Need to keep CMessage stay alive if it is still referenced after
+ // deletion. Makes a new message and swaps values into CMessage
+ // instead of just removing.
+ CMessage* cmsg = reinterpret_cast<CMessage*>(cmsg_value);
+ Message* msg = cmsg->message;
+ cmsg->owner.reset(msg->New());
+ cmsg->message = cmsg->owner.get();
+ cmsg->parent = NULL;
+ msg->GetReflection()->Swap(msg, cmsg->message);
+ if (PyDict_DelItem(self->message_dict, key.get()) < 0) {
+ return -1;
+ }
+ }
+
+ // Delete key from map.
+ reflection->DeleteMapValue(message, self->parent_field_descriptor,
+ map_key);
return 0;
} else {
PyErr_Format(PyExc_KeyError, "Key not present in map");
diff --git a/python/google/protobuf/pyext/message.cc b/python/google/protobuf/pyext/message.cc
index 4f3abc84..ef75acab 100644
--- a/python/google/protobuf/pyext/message.cc
+++ b/python/google/protobuf/pyext/message.cc
@@ -52,6 +52,7 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/io/coded_stream.h>
+#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
#include <google/protobuf/util/message_differencer.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/message.h>
@@ -66,7 +67,6 @@
#include <google/protobuf/pyext/message_factory.h>
#include <google/protobuf/pyext/safe_numerics.h>
#include <google/protobuf/pyext/scoped_pyobject_ptr.h>
-#include <google/protobuf/stubs/strutil.h>
#if PY_MAJOR_VERSION >= 3
#define PyInt_AsLong PyLong_AsLong
@@ -101,6 +101,17 @@ namespace message_meta {
static int InsertEmptyWeakref(PyTypeObject* base);
+namespace {
+// Copied oveer from internal 'google/protobuf/stubs/strutil.h'.
+inline void UpperString(string * s) {
+ string::iterator end = s->end();
+ for (string::iterator i = s->begin(); i != end; ++i) {
+ // toupper() changes based on locale. We don't want this!
+ if ('a' <= *i && *i <= 'z') *i += 'A' - 'a';
+ }
+}
+}
+
// Add the number of a field descriptor to the containing message class.
// Equivalent to:
// _cls.<field>_FIELD_NUMBER = <number>
@@ -594,19 +605,21 @@ void OutOfRangeError(PyObject* arg) {
template<class RangeType, class ValueType>
bool VerifyIntegerCastAndRange(PyObject* arg, ValueType value) {
- if GOOGLE_PREDICT_FALSE(value == -1 && PyErr_Occurred()) {
- if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
- // Replace it with the same ValueError as pure python protos instead of
- // the default one.
- PyErr_Clear();
+ if
+ GOOGLE_PREDICT_FALSE(value == -1 && PyErr_Occurred()) {
+ if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
+ // Replace it with the same ValueError as pure python protos instead of
+ // the default one.
+ PyErr_Clear();
+ OutOfRangeError(arg);
+ } // Otherwise propagate existing error.
+ return false;
+ }
+ if
+ GOOGLE_PREDICT_FALSE(!IsValidNumericCast<RangeType>(value)) {
OutOfRangeError(arg);
- } // Otherwise propagate existing error.
- return false;
- }
- if GOOGLE_PREDICT_FALSE(!IsValidNumericCast<RangeType>(value)) {
- OutOfRangeError(arg);
- return false;
- }
+ return false;
+ }
return true;
}
@@ -615,25 +628,29 @@ bool CheckAndGetInteger(PyObject* arg, T* value) {
// The fast path.
#if PY_MAJOR_VERSION < 3
// For the typical case, offer a fast path.
- if GOOGLE_PREDICT_TRUE(PyInt_Check(arg)) {
- long int_result = PyInt_AsLong(arg);
- if GOOGLE_PREDICT_TRUE(IsValidNumericCast<T>(int_result)) {
- *value = static_cast<T>(int_result);
- return true;
- } else {
- OutOfRangeError(arg);
- return false;
+ if
+ GOOGLE_PREDICT_TRUE(PyInt_Check(arg)) {
+ long int_result = PyInt_AsLong(arg);
+ if
+ GOOGLE_PREDICT_TRUE(IsValidNumericCast<T>(int_result)) {
+ *value = static_cast<T>(int_result);
+ return true;
+ }
+ else {
+ OutOfRangeError(arg);
+ return false;
+ }
}
- }
#endif
// This effectively defines an integer as "an object that can be cast as
// an integer and can be used as an ordinal number".
// This definition includes everything that implements numbers.Integral
// and shouldn't cast the net too wide.
- if GOOGLE_PREDICT_FALSE(!PyIndex_Check(arg)) {
- FormatTypeError(arg, "int, long");
- return false;
- }
+ if
+ GOOGLE_PREDICT_FALSE(!PyIndex_Check(arg)) {
+ FormatTypeError(arg, "int, long");
+ return false;
+ }
// Now we have an integral number so we can safely use PyLong_ functions.
// We need to treat the signed and unsigned cases differently in case arg is
@@ -647,10 +664,11 @@ bool CheckAndGetInteger(PyObject* arg, T* value) {
// Unlike PyLong_AsLongLong, PyLong_AsUnsignedLongLong is very
// picky about the exact type.
PyObject* casted = PyNumber_Long(arg);
- if GOOGLE_PREDICT_FALSE(casted == NULL) {
- // Propagate existing error.
- return false;
- }
+ if
+ GOOGLE_PREDICT_FALSE(casted == NULL) {
+ // Propagate existing error.
+ return false;
+ }
ulong_result = PyLong_AsUnsignedLongLong(casted);
Py_DECREF(casted);
}
@@ -672,10 +690,11 @@ bool CheckAndGetInteger(PyObject* arg, T* value) {
// Valid subclasses of numbers.Integral should have a __long__() method
// so fall back to that.
PyObject* casted = PyNumber_Long(arg);
- if GOOGLE_PREDICT_FALSE(casted == NULL) {
- // Propagate existing error.
- return false;
- }
+ if
+ GOOGLE_PREDICT_FALSE(casted == NULL) {
+ // Propagate existing error.
+ return false;
+ }
long_result = PyLong_AsLongLong(casted);
Py_DECREF(casted);
}
@@ -698,10 +717,11 @@ template bool CheckAndGetInteger<uint64>(PyObject*, uint64*);
bool CheckAndGetDouble(PyObject* arg, double* value) {
*value = PyFloat_AsDouble(arg);
- if GOOGLE_PREDICT_FALSE(*value == -1 && PyErr_Occurred()) {
- FormatTypeError(arg, "int, long, float");
- return false;
- }
+ if
+ GOOGLE_PREDICT_FALSE(*value == -1 && PyErr_Occurred()) {
+ FormatTypeError(arg, "int, long, float");
+ return false;
+ }
return true;
}
@@ -779,7 +799,7 @@ PyObject* CheckString(PyObject* arg, const FieldDescriptor* descriptor) {
encoded_string = arg; // Already encoded.
Py_INCREF(encoded_string);
} else {
- encoded_string = PyUnicode_AsEncodedObject(arg, "utf-8", NULL);
+ encoded_string = PyUnicode_AsEncodedString(arg, "utf-8", NULL);
}
} else {
// In this case field type is "bytes".
@@ -1055,13 +1075,15 @@ int InternalDeleteRepeatedField(
if (PySlice_Check(slice)) {
from = to = step = slice_length = 0;
- PySlice_GetIndicesEx(
#if PY_MAJOR_VERSION < 3
+ PySlice_GetIndicesEx(
reinterpret_cast<PySliceObject*>(slice),
+ length, &from, &to, &step, &slice_length);
#else
+ PySlice_GetIndicesEx(
slice,
-#endif
length, &from, &to, &step, &slice_length);
+#endif
if (from < to) {
min = from;
max = to - 1;
@@ -1540,20 +1562,7 @@ PyObject* HasField(CMessage* self, PyObject* arg) {
if (message->GetReflection()->HasField(*message, field_descriptor)) {
Py_RETURN_TRUE;
}
- if (!message->GetReflection()->SupportsUnknownEnumValues() &&
- field_descriptor->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) {
- // Special case: Python HasField() differs in semantics from C++
- // slightly: we return HasField('enum_field') == true if there is
- // an unknown enum value present. To implement this we have to
- // look in the UnknownFieldSet.
- const UnknownFieldSet& unknown_field_set =
- message->GetReflection()->GetUnknownFields(*message);
- for (int i = 0; i < unknown_field_set.field_count(); ++i) {
- if (unknown_field_set.field(i).number() == field_descriptor->number()) {
- Py_RETURN_TRUE;
- }
- }
- }
+
Py_RETURN_FALSE;
}
@@ -1732,12 +1741,6 @@ PyObject* ClearFieldByDescriptor(
AssureWritable(self);
Message* message = self->message;
message->GetReflection()->ClearField(message, field_descriptor);
- if (field_descriptor->cpp_type() == FieldDescriptor::CPPTYPE_ENUM &&
- !message->GetReflection()->SupportsUnknownEnumValues()) {
- UnknownFieldSet* unknown_field_set =
- message->GetReflection()->MutableUnknownFields(message);
- unknown_field_set->DeleteByNumber(field_descriptor->number());
- }
Py_RETURN_NONE;
}
@@ -1808,8 +1811,25 @@ static string GetMessageName(CMessage* self) {
}
}
-static PyObject* SerializeToString(CMessage* self, PyObject* args) {
- if (!self->message->IsInitialized()) {
+static PyObject* InternalSerializeToString(
+ CMessage* self, PyObject* args, PyObject* kwargs,
+ bool require_initialized) {
+ // Parse the "deterministic" kwarg; defaults to False.
+ static char* kwlist[] = { "deterministic", 0 };
+ PyObject* deterministic_obj = Py_None;
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", kwlist,
+ &deterministic_obj)) {
+ return NULL;
+ }
+ // Preemptively convert to a bool first, so we don't need to back out of
+ // allocating memory if this raises an exception.
+ // NOTE: This is unused later if deterministic == Py_None, but that's fine.
+ int deterministic = PyObject_IsTrue(deterministic_obj);
+ if (deterministic < 0) {
+ return NULL;
+ }
+
+ if (require_initialized && !self->message->IsInitialized()) {
ScopedPyObjectPtr errors(FindInitializationErrors(self));
if (errors == NULL) {
return NULL;
@@ -1847,24 +1867,36 @@ static PyObject* SerializeToString(CMessage* self, PyObject* args) {
GetMessageName(self).c_str(), PyString_AsString(joined.get()));
return NULL;
}
- int size = self->message->ByteSize();
- if (size <= 0) {
+
+ // Ok, arguments parsed and errors checked, now encode to a string
+ const size_t size = self->message->ByteSizeLong();
+ if (size == 0) {
return PyBytes_FromString("");
}
PyObject* result = PyBytes_FromStringAndSize(NULL, size);
if (result == NULL) {
return NULL;
}
- char* buffer = PyBytes_AS_STRING(result);
- self->message->SerializeWithCachedSizesToArray(
- reinterpret_cast<uint8*>(buffer));
+ io::ArrayOutputStream out(PyBytes_AS_STRING(result), size);
+ io::CodedOutputStream coded_out(&out);
+ if (deterministic_obj != Py_None) {
+ coded_out.SetSerializationDeterministic(deterministic);
+ }
+ self->message->SerializeWithCachedSizes(&coded_out);
+ GOOGLE_CHECK(!coded_out.HadError());
return result;
}
-static PyObject* SerializePartialToString(CMessage* self) {
- string contents;
- self->message->SerializePartialToString(&contents);
- return PyBytes_FromStringAndSize(contents.c_str(), contents.size());
+static PyObject* SerializeToString(
+ CMessage* self, PyObject* args, PyObject* kwargs) {
+ return InternalSerializeToString(self, args, kwargs,
+ /*require_initialized=*/true);
+}
+
+static PyObject* SerializePartialToString(
+ CMessage* self, PyObject* args, PyObject* kwargs) {
+ return InternalSerializeToString(self, args, kwargs,
+ /*require_initialized=*/false);
}
// Formats proto fields for ascii dumps using python formatting functions where
@@ -2033,6 +2065,11 @@ static PyObject* MergeFromString(CMessage* self, PyObject* arg) {
input.SetExtensionRegistry(factory->pool->pool, factory->message_factory);
bool success = self->message->MergePartialFromCodedStream(&input);
if (success) {
+ if (!input.ConsumedEntireMessage()) {
+ // TODO(jieluo): Raise error and return NULL instead.
+ // b/27494216
+ PyErr_Warn(NULL, "Unexpected end-group tag: Not all data was converted");
+ }
return PyInt_FromLong(input.CurrentPosition());
} else {
PyErr_Format(DecodeError_class, "Error parsing message");
@@ -2303,27 +2340,9 @@ PyObject* InternalGetScalar(const Message* message,
break;
}
case FieldDescriptor::CPPTYPE_ENUM: {
- if (!message->GetReflection()->SupportsUnknownEnumValues() &&
- !message->GetReflection()->HasField(*message, field_descriptor)) {
- // Look for the value in the unknown fields.
- const UnknownFieldSet& unknown_field_set =
- message->GetReflection()->GetUnknownFields(*message);
- for (int i = 0; i < unknown_field_set.field_count(); ++i) {
- if (unknown_field_set.field(i).number() ==
- field_descriptor->number() &&
- unknown_field_set.field(i).type() ==
- google::protobuf::UnknownField::TYPE_VARINT) {
- result = PyInt_FromLong(unknown_field_set.field(i).varint());
- break;
- }
- }
- }
-
- if (result == NULL) {
- const EnumValueDescriptor* enum_value =
- message->GetReflection()->GetEnum(*message, field_descriptor);
- result = PyInt_FromLong(enum_value->number());
- }
+ const EnumValueDescriptor* enum_value =
+ message->GetReflection()->GetEnum(*message, field_descriptor);
+ result = PyInt_FromLong(enum_value->number());
break;
}
default:
@@ -2342,8 +2361,10 @@ PyObject* InternalGetSubMessage(
const Message& sub_message = reflection->GetMessage(
*self->message, field_descriptor, factory->message_factory);
- CMessageClass* message_class = message_factory::GetMessageClass(
+ CMessageClass* message_class = message_factory::GetOrCreateMessageClass(
factory, field_descriptor->message_type());
+ ScopedPyObjectPtr message_class_handler(
+ reinterpret_cast<PyObject*>(message_class));
if (message_class == NULL) {
return NULL;
}
@@ -2533,7 +2554,10 @@ PyObject* Reduce(CMessage* self) {
if (state == NULL) {
return NULL;
}
- ScopedPyObjectPtr serialized(SerializePartialToString(self));
+ string contents;
+ self->message->SerializePartialToString(&contents);
+ ScopedPyObjectPtr serialized(
+ PyBytes_FromStringAndSize(contents.c_str(), contents.size()));
if (serialized == NULL) {
return NULL;
}
@@ -2654,9 +2678,10 @@ static PyMethodDef Methods[] = {
{ "RegisterExtension", (PyCFunction)RegisterExtension, METH_O | METH_CLASS,
"Registers an extension with the current message." },
{ "SerializePartialToString", (PyCFunction)SerializePartialToString,
- METH_NOARGS,
+ METH_VARARGS | METH_KEYWORDS,
"Serializes the message to a string, even if it isn't initialized." },
- { "SerializeToString", (PyCFunction)SerializeToString, METH_NOARGS,
+ { "SerializeToString", (PyCFunction)SerializeToString,
+ METH_VARARGS | METH_KEYWORDS,
"Serializes the message to a string, only for initialized messages." },
{ "SetInParent", (PyCFunction)SetInParent, METH_NOARGS,
"Sets the has bit of the given field in its parent message." },
@@ -3039,5 +3064,4 @@ bool InitProto2MessageModule(PyObject *m) {
} // namespace python
} // namespace protobuf
-
} // namespace google
diff --git a/python/google/protobuf/pyext/message_factory.cc b/python/google/protobuf/pyext/message_factory.cc
index e0b45bf2..571bae2b 100644
--- a/python/google/protobuf/pyext/message_factory.cc
+++ b/python/google/protobuf/pyext/message_factory.cc
@@ -133,11 +133,7 @@ int RegisterMessageClass(PyMessageFactory* self,
CMessageClass* GetOrCreateMessageClass(PyMessageFactory* self,
const Descriptor* descriptor) {
// This is the same implementation as MessageFactory.GetPrototype().
- ScopedPyObjectPtr py_descriptor(
- PyMessageDescriptor_FromDescriptor(descriptor));
- if (py_descriptor == NULL) {
- return NULL;
- }
+
// Do not create a MessageClass that already exists.
hash_map<const Descriptor*, CMessageClass*>::iterator it =
self->classes_by_descriptor->find(descriptor);
@@ -145,6 +141,11 @@ CMessageClass* GetOrCreateMessageClass(PyMessageFactory* self,
Py_INCREF(it->second);
return it->second;
}
+ ScopedPyObjectPtr py_descriptor(
+ PyMessageDescriptor_FromDescriptor(descriptor));
+ if (py_descriptor == NULL) {
+ return NULL;
+ }
// Create a new message class.
ScopedPyObjectPtr args(Py_BuildValue(
"s(){sOsOsO}", descriptor->name().c_str(),
diff --git a/python/google/protobuf/pyext/message_module.cc b/python/google/protobuf/pyext/message_module.cc
index d90d9de3..7c4df47f 100644
--- a/python/google/protobuf/pyext/message_module.cc
+++ b/python/google/protobuf/pyext/message_module.cc
@@ -28,8 +28,33 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#include <Python.h>
+
#include <google/protobuf/pyext/message.h>
+#include <google/protobuf/message_lite.h>
+
+static PyObject* GetPythonProto3PreserveUnknownsDefault(
+ PyObject* /*m*/, PyObject* /*args*/) {
+ if (google::protobuf::internal::GetProto3PreserveUnknownsDefault()) {
+ Py_RETURN_TRUE;
+ } else {
+ Py_RETURN_FALSE;
+ }
+}
+
+static PyObject* SetPythonProto3PreserveUnknownsDefault(
+ PyObject* /*m*/, PyObject* arg) {
+ if (!arg || !PyBool_Check(arg)) {
+ PyErr_SetString(
+ PyExc_TypeError,
+ "Argument to SetPythonProto3PreserveUnknownsDefault must be boolean");
+ return NULL;
+ }
+ google::protobuf::internal::SetProto3PreserveUnknownsDefault(PyObject_IsTrue(arg));
+ Py_RETURN_NONE;
+}
+
static const char module_docstring[] =
"python-proto2 is a module that can be used to enhance proto2 Python API\n"
"performance.\n"
@@ -41,6 +66,14 @@ static PyMethodDef ModuleMethods[] = {
{"SetAllowOversizeProtos",
(PyCFunction)google::protobuf::python::cmessage::SetAllowOversizeProtos,
METH_O, "Enable/disable oversize proto parsing."},
+ // DO NOT USE: For migration and testing only.
+ {"GetPythonProto3PreserveUnknownsDefault",
+ (PyCFunction)GetPythonProto3PreserveUnknownsDefault,
+ METH_NOARGS, "Get Proto3 preserve unknowns default."},
+ // DO NOT USE: For migration and testing only.
+ {"SetPythonProto3PreserveUnknownsDefault",
+ (PyCFunction)SetPythonProto3PreserveUnknownsDefault,
+ METH_O, "Enable/disable proto3 unknowns preservation."},
{ NULL, NULL}
};
diff --git a/python/google/protobuf/pyext/python.proto b/python/google/protobuf/pyext/python.proto
index cce645d7..2e50df74 100644
--- a/python/google/protobuf/pyext/python.proto
+++ b/python/google/protobuf/pyext/python.proto
@@ -58,11 +58,11 @@ message ForeignMessage {
repeated int32 d = 2;
}
-message TestAllExtensions {
+message TestAllExtensions { // extension begin
extensions 1 to max;
-}
+} // extension end
-extend TestAllExtensions {
+extend TestAllExtensions { // extension begin
optional TestAllTypes.NestedMessage optional_nested_message_extension = 1;
repeated TestAllTypes.NestedMessage repeated_nested_message_extension = 2;
-}
+} // extension end
diff --git a/python/google/protobuf/pyext/repeated_composite_container.cc b/python/google/protobuf/pyext/repeated_composite_container.cc
index 43a2bc12..5ad71db5 100644
--- a/python/google/protobuf/pyext/repeated_composite_container.cc
+++ b/python/google/protobuf/pyext/repeated_composite_container.cc
@@ -46,7 +46,9 @@
#include <google/protobuf/pyext/descriptor.h>
#include <google/protobuf/pyext/descriptor_pool.h>
#include <google/protobuf/pyext/message.h>
+#include <google/protobuf/pyext/message_factory.h>
#include <google/protobuf/pyext/scoped_pyobject_ptr.h>
+#include <google/protobuf/reflection.h>
#if PY_MAJOR_VERSION >= 3
#define PyInt_Check PyLong_Check
@@ -136,9 +138,12 @@ static PyObject* AddToAttached(RepeatedCompositeContainer* self,
if (cmessage::AssureWritable(self->parent) == -1)
return NULL;
Message* message = self->message;
+
Message* sub_message =
- message->GetReflection()->AddMessage(message,
- self->parent_field_descriptor);
+ message->GetReflection()->AddMessage(
+ message,
+ self->parent_field_descriptor,
+ self->child_message_class->py_message_factory->message_factory);
CMessage* cmsg = cmessage::NewEmptyMessage(self->child_message_class);
if (cmsg == NULL)
return NULL;
@@ -265,10 +270,11 @@ int AssignSubscript(RepeatedCompositeContainer* self,
if (PySlice_Check(slice)) {
#if PY_MAJOR_VERSION >= 3
if (PySlice_GetIndicesEx(slice,
+ length, &from, &to, &step, &slicelength) == -1) {
#else
if (PySlice_GetIndicesEx(reinterpret_cast<PySliceObject*>(slice),
-#endif
length, &from, &to, &step, &slicelength) == -1) {
+#endif
return -1;
}
return PySequence_DelSlice(self->child_messages, from, to);
@@ -334,6 +340,18 @@ static PyObject* RichCompare(RepeatedCompositeContainer* self,
}
}
+static PyObject* ToStr(RepeatedCompositeContainer* self) {
+ ScopedPyObjectPtr full_slice(PySlice_New(NULL, NULL, NULL));
+ if (full_slice == NULL) {
+ return NULL;
+ }
+ ScopedPyObjectPtr list(Subscript(self, full_slice.get()));
+ if (list == NULL) {
+ return NULL;
+ }
+ return PyObject_Repr(list.get());
+}
+
// ---------------------------------------------------------------------
// sort()
@@ -485,6 +503,32 @@ int Release(RepeatedCompositeContainer* self) {
return 0;
}
+PyObject* DeepCopy(RepeatedCompositeContainer* self, PyObject* arg) {
+ ScopedPyObjectPtr cloneObj(
+ PyType_GenericAlloc(&RepeatedCompositeContainer_Type, 0));
+ if (cloneObj == NULL) {
+ return NULL;
+ }
+ RepeatedCompositeContainer* clone =
+ reinterpret_cast<RepeatedCompositeContainer*>(cloneObj.get());
+
+ Message* new_message = self->message->New();
+ clone->parent = NULL;
+ clone->parent_field_descriptor = self->parent_field_descriptor;
+ clone->message = new_message;
+ clone->owner.reset(new_message);
+ Py_INCREF(self->child_message_class);
+ clone->child_message_class = self->child_message_class;
+ clone->child_messages = PyList_New(0);
+
+ new_message->GetReflection()
+ ->GetMutableRepeatedFieldRef<Message>(new_message,
+ self->parent_field_descriptor)
+ .MergeFrom(self->message->GetReflection()->GetRepeatedFieldRef<Message>(
+ *self->message, self->parent_field_descriptor));
+ return cloneObj.release();
+}
+
int SetOwner(RepeatedCompositeContainer* self,
const shared_ptr<Message>& new_owner) {
GOOGLE_CHECK_ATTACHED(self);
@@ -551,6 +595,8 @@ static PyMappingMethods MpMethods = {
};
static PyMethodDef Methods[] = {
+ { "__deepcopy__", (PyCFunction)DeepCopy, METH_VARARGS,
+ "Makes a deep copy of the class." },
{ "add", (PyCFunction) Add, METH_VARARGS | METH_KEYWORDS,
"Adds an object to the repeated container." },
{ "extend", (PyCFunction) Extend, METH_O,
@@ -578,7 +624,7 @@ PyTypeObject RepeatedCompositeContainer_Type = {
0, // tp_getattr
0, // tp_setattr
0, // tp_compare
- 0, // tp_repr
+ (reprfunc)repeated_composite_container::ToStr, // tp_repr
0, // tp_as_number
&repeated_composite_container::SqMethods, // tp_as_sequence
&repeated_composite_container::MpMethods, // tp_as_mapping
diff --git a/python/google/protobuf/pyext/repeated_scalar_container.cc b/python/google/protobuf/pyext/repeated_scalar_container.cc
index 95da85f8..5a7832cd 100644
--- a/python/google/protobuf/pyext/repeated_scalar_container.cc
+++ b/python/google/protobuf/pyext/repeated_scalar_container.cc
@@ -261,22 +261,6 @@ static PyObject* Item(RepeatedScalarContainer* self, Py_ssize_t index) {
result = ToStringObject(field_descriptor, value);
break;
}
- case FieldDescriptor::CPPTYPE_MESSAGE: {
- PyObject* py_cmsg = PyObject_CallObject(reinterpret_cast<PyObject*>(
- &CMessage_Type), NULL);
- if (py_cmsg == NULL) {
- return NULL;
- }
- CMessage* cmsg = reinterpret_cast<CMessage*>(py_cmsg);
- const Message& msg = reflection->GetRepeatedMessage(
- *message, field_descriptor, index);
- cmsg->owner = self->owner;
- cmsg->parent = self->parent;
- cmsg->message = const_cast<Message*>(&msg);
- cmsg->read_only = false;
- result = reinterpret_cast<PyObject*>(py_cmsg);
- break;
- }
default:
PyErr_Format(
PyExc_SystemError,
@@ -305,10 +289,12 @@ static PyObject* Subscript(RepeatedScalarContainer* self, PyObject* slice) {
length = Len(self);
#if PY_MAJOR_VERSION >= 3
if (PySlice_GetIndicesEx(slice,
+ length, &from, &to, &step, &slicelength) == -1) {
#else
if (PySlice_GetIndicesEx(reinterpret_cast<PySliceObject*>(slice),
-#endif
length, &from, &to, &step, &slicelength) == -1) {
+
+#endif
return NULL;
}
return_list = true;
@@ -458,10 +444,11 @@ static int AssSubscript(RepeatedScalarContainer* self,
length = reflection->FieldSize(*message, field_descriptor);
#if PY_MAJOR_VERSION >= 3
if (PySlice_GetIndicesEx(slice,
+ length, &from, &to, &step, &slicelength) == -1) {
#else
if (PySlice_GetIndicesEx(reinterpret_cast<PySliceObject*>(slice),
-#endif
length, &from, &to, &step, &slicelength) == -1) {
+#endif
return -1;
}
create_list = true;
@@ -656,6 +643,18 @@ static PyObject* Pop(RepeatedScalarContainer* self,
return item;
}
+static PyObject* ToStr(RepeatedScalarContainer* self) {
+ ScopedPyObjectPtr full_slice(PySlice_New(NULL, NULL, NULL));
+ if (full_slice == NULL) {
+ return NULL;
+ }
+ ScopedPyObjectPtr list(Subscript(self, full_slice.get()));
+ if (list == NULL) {
+ return NULL;
+ }
+ return PyObject_Repr(list.get());
+}
+
// The private constructor of RepeatedScalarContainer objects.
PyObject *NewContainer(
CMessage* parent, const FieldDescriptor* parent_field_descriptor) {
@@ -778,7 +777,7 @@ PyTypeObject RepeatedScalarContainer_Type = {
0, // tp_getattr
0, // tp_setattr
0, // tp_compare
- 0, // tp_repr
+ (reprfunc)repeated_scalar_container::ToStr, // tp_repr
0, // tp_as_number
&repeated_scalar_container::SqMethods, // tp_as_sequence
&repeated_scalar_container::MpMethods, // tp_as_mapping
diff --git a/python/google/protobuf/pyext/scoped_pyobject_ptr.h b/python/google/protobuf/pyext/scoped_pyobject_ptr.h
index a128cd4c..a2afa7f1 100644
--- a/python/google/protobuf/pyext/scoped_pyobject_ptr.h
+++ b/python/google/protobuf/pyext/scoped_pyobject_ptr.h
@@ -36,61 +36,70 @@
#include <google/protobuf/stubs/common.h>
#include <Python.h>
-
namespace google {
-class ScopedPyObjectPtr {
+namespace protobuf {
+namespace python {
+
+// Owns a python object and decrements the reference count on destruction.
+// This class is not threadsafe.
+template <typename PyObjectStruct>
+class ScopedPythonPtr {
public:
- // Constructor. Defaults to initializing with NULL.
- // There is no way to create an uninitialized ScopedPyObjectPtr.
- explicit ScopedPyObjectPtr(PyObject* p = NULL) : ptr_(p) { }
+ // Takes the ownership of the specified object to ScopedPythonPtr.
+ // The reference count of the specified py_object is not incremented.
+ explicit ScopedPythonPtr(PyObjectStruct* py_object = NULL)
+ : ptr_(py_object) {}
- // Destructor. If there is a PyObject object, delete it.
- ~ScopedPyObjectPtr() {
- Py_XDECREF(ptr_);
- }
+ // If a PyObject is owned, decrement its reference count.
+ ~ScopedPythonPtr() { Py_XDECREF(ptr_); }
- // Reset. Deletes the current owned object, if any.
- // Then takes ownership of a new object, if given.
+ // Deletes the current owned object, if any.
+ // Then takes ownership of a new object without incrementing the reference
+ // count.
// This function must be called with a reference that you own.
// this->reset(this->get()) is wrong!
// this->reset(this->release()) is OK.
- PyObject* reset(PyObject* p = NULL) {
+ PyObjectStruct* reset(PyObjectStruct* p = NULL) {
Py_XDECREF(ptr_);
ptr_ = p;
return ptr_;
}
- // Releases ownership of the object.
+ // Releases ownership of the object without decrementing the reference count.
// The caller now owns the returned reference.
- PyObject* release() {
+ PyObjectStruct* release() {
PyObject* p = ptr_;
ptr_ = NULL;
return p;
}
- PyObject* operator->() const {
+ PyObjectStruct* operator->() const {
assert(ptr_ != NULL);
return ptr_;
}
- PyObject* get() const { return ptr_; }
+ PyObjectStruct* get() const { return ptr_; }
- Py_ssize_t refcnt() const { return Py_REFCNT(ptr_); }
+ PyObject* as_pyobject() const { return reinterpret_cast<PyObject*>(ptr_); }
+ // Increments the reference count fo the current object.
+ // Should not be called when no object is held.
void inc() const { Py_INCREF(ptr_); }
- // Comparison operators.
- // These return whether a ScopedPyObjectPtr and a raw pointer
- // refer to the same object, not just to two different but equal
- // objects.
- bool operator==(const PyObject* p) const { return ptr_ == p; }
- bool operator!=(const PyObject* p) const { return ptr_ != p; }
+ // True when a ScopedPyObjectPtr and a raw pointer refer to the same object.
+ // Comparison operators are non reflexive.
+ bool operator==(const PyObjectStruct* p) const { return ptr_ == p; }
+ bool operator!=(const PyObjectStruct* p) const { return ptr_ != p; }
private:
- PyObject* ptr_;
+ PyObjectStruct* ptr_;
- GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ScopedPyObjectPtr);
+ GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ScopedPythonPtr);
};
+typedef ScopedPythonPtr<PyObject> ScopedPyObjectPtr;
+
+} // namespace python
+} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_PYTHON_CPP_SCOPED_PYOBJECT_PTR_H__
diff --git a/python/google/protobuf/pyext/python_protobuf.h b/python/google/protobuf/python_protobuf.h
index beb6e460..beb6e460 100644
--- a/python/google/protobuf/pyext/python_protobuf.h
+++ b/python/google/protobuf/python_protobuf.h
diff --git a/python/google/protobuf/reflection.py b/python/google/protobuf/reflection.py
index 51c83321..f4ce8caf 100755
--- a/python/google/protobuf/reflection.py
+++ b/python/google/protobuf/reflection.py
@@ -61,6 +61,8 @@ else:
# Part of the public interface, but normally only used by message factories.
GeneratedProtocolMessageType = message_impl.GeneratedProtocolMessageType
+MESSAGE_CLASS_CACHE = {}
+
def ParseMessage(descriptor, byte_str):
"""Generate a new Message instance from this Descriptor and a byte string.
@@ -104,11 +106,16 @@ def MakeClass(descriptor):
Returns:
The Message class object described by the descriptor.
"""
+ if descriptor in MESSAGE_CLASS_CACHE:
+ return MESSAGE_CLASS_CACHE[descriptor]
+
attributes = {}
for name, nested_type in descriptor.nested_types_by_name.items():
attributes[name] = MakeClass(nested_type)
attributes[GeneratedProtocolMessageType._DESCRIPTOR_KEY] = descriptor
- return GeneratedProtocolMessageType(str(descriptor.name), (message.Message,),
- attributes)
+ result = GeneratedProtocolMessageType(
+ str(descriptor.name), (message.Message,), attributes)
+ MESSAGE_CLASS_CACHE[descriptor] = result
+ return result
diff --git a/python/google/protobuf/symbol_database.py b/python/google/protobuf/symbol_database.py
index ecbef211..5ad869f4 100644
--- a/python/google/protobuf/symbol_database.py
+++ b/python/google/protobuf/symbol_database.py
@@ -78,10 +78,18 @@ class SymbolDatabase(message_factory.MessageFactory):
"""
desc = message.DESCRIPTOR
- self._classes[desc.full_name] = message
- self.pool.AddDescriptor(desc)
+ self._classes[desc] = message
+ self.RegisterMessageDescriptor(desc)
return message
+ def RegisterMessageDescriptor(self, message_descriptor):
+ """Registers the given message descriptor in the local database.
+
+ Args:
+ message_descriptor: a descriptor.MessageDescriptor.
+ """
+ self.pool.AddDescriptor(message_descriptor)
+
def RegisterEnumDescriptor(self, enum_descriptor):
"""Registers the given enum descriptor in the local database.
@@ -94,6 +102,17 @@ class SymbolDatabase(message_factory.MessageFactory):
self.pool.AddEnumDescriptor(enum_descriptor)
return enum_descriptor
+ def RegisterServiceDescriptor(self, service_descriptor):
+ """Registers the given service descriptor in the local database.
+
+ Args:
+ service_descriptor: a descriptor.ServiceDescriptor.
+
+ Returns:
+ The provided descriptor.
+ """
+ self.pool.AddServiceDescriptor(service_descriptor)
+
def RegisterFileDescriptor(self, file_descriptor):
"""Registers the given file descriptor in the local database.
@@ -121,7 +140,7 @@ class SymbolDatabase(message_factory.MessageFactory):
KeyError: if the symbol could not be found.
"""
- return self._classes[symbol]
+ return self._classes[self.pool.FindMessageTypeByName(symbol)]
def GetMessages(self, files):
# TODO(amauryfa): Fix the differences with MessageFactory.
@@ -142,20 +161,20 @@ class SymbolDatabase(message_factory.MessageFactory):
KeyError: if a file could not be found.
"""
- def _GetAllMessageNames(desc):
+ def _GetAllMessages(desc):
"""Walk a message Descriptor and recursively yields all message names."""
- yield desc.full_name
+ yield desc
for msg_desc in desc.nested_types:
- for full_name in _GetAllMessageNames(msg_desc):
- yield full_name
+ for nested_desc in _GetAllMessages(msg_desc):
+ yield nested_desc
result = {}
for file_name in files:
file_desc = self.pool.FindFileByName(file_name)
for msg_desc in file_desc.message_types_by_name.values():
- for full_name in _GetAllMessageNames(msg_desc):
+ for desc in _GetAllMessages(msg_desc):
try:
- result[full_name] = self._classes[full_name]
+ result[desc.full_name] = self._classes[desc]
except KeyError:
# This descriptor has no registered class, skip it.
pass
diff --git a/python/google/protobuf/text_format.py b/python/google/protobuf/text_format.py
index 90f6ce42..6b12632e 100755
--- a/python/google/protobuf/text_format.py
+++ b/python/google/protobuf/text_format.py
@@ -126,7 +126,8 @@ def MessageToString(message,
float_format=None,
use_field_number=False,
descriptor_pool=None,
- indent=0):
+ indent=0,
+ message_formatter=None):
"""Convert protobuf message to text format.
Floating point values can be formatted compactly with 15 digits of
@@ -148,6 +149,9 @@ def MessageToString(message,
use_field_number: If True, print field numbers instead of names.
descriptor_pool: A DescriptorPool used to resolve Any types.
indent: The indent level, in terms of spaces, for pretty print.
+ message_formatter: A function(message, indent, as_one_line): unicode|None
+ to custom format selected sub-messages (usually based on message type).
+ Use to pretty print parts of the protobuf for easier diffing.
Returns:
A string of the text formatted protocol buffer message.
@@ -155,7 +159,7 @@ def MessageToString(message,
out = TextWriter(as_utf8)
printer = _Printer(out, indent, as_utf8, as_one_line, pointy_brackets,
use_index_order, float_format, use_field_number,
- descriptor_pool)
+ descriptor_pool, message_formatter)
printer.PrintMessage(message)
result = out.getvalue()
out.close()
@@ -179,10 +183,11 @@ def PrintMessage(message,
use_index_order=False,
float_format=None,
use_field_number=False,
- descriptor_pool=None):
+ descriptor_pool=None,
+ message_formatter=None):
printer = _Printer(out, indent, as_utf8, as_one_line, pointy_brackets,
use_index_order, float_format, use_field_number,
- descriptor_pool)
+ descriptor_pool, message_formatter)
printer.PrintMessage(message)
@@ -194,10 +199,11 @@ def PrintField(field,
as_one_line=False,
pointy_brackets=False,
use_index_order=False,
- float_format=None):
+ float_format=None,
+ message_formatter=None):
"""Print a single field name/value pair."""
printer = _Printer(out, indent, as_utf8, as_one_line, pointy_brackets,
- use_index_order, float_format)
+ use_index_order, float_format, message_formatter)
printer.PrintField(field, value)
@@ -209,10 +215,11 @@ def PrintFieldValue(field,
as_one_line=False,
pointy_brackets=False,
use_index_order=False,
- float_format=None):
+ float_format=None,
+ message_formatter=None):
"""Print a single field value (not including name)."""
printer = _Printer(out, indent, as_utf8, as_one_line, pointy_brackets,
- use_index_order, float_format)
+ use_index_order, float_format, message_formatter)
printer.PrintFieldValue(field, value)
@@ -228,6 +235,9 @@ def _BuildMessageFromTypeName(type_name, descriptor_pool):
wasn't found matching type_name.
"""
# pylint: disable=g-import-not-at-top
+ if descriptor_pool is None:
+ from google.protobuf import descriptor_pool as pool_mod
+ descriptor_pool = pool_mod.Default()
from google.protobuf import symbol_database
database = symbol_database.Default()
try:
@@ -250,7 +260,8 @@ class _Printer(object):
use_index_order=False,
float_format=None,
use_field_number=False,
- descriptor_pool=None):
+ descriptor_pool=None,
+ message_formatter=None):
"""Initialize the Printer.
Floating point values can be formatted compactly with 15 digits of
@@ -273,6 +284,9 @@ class _Printer(object):
used.
use_field_number: If True, print field numbers instead of names.
descriptor_pool: A DescriptorPool used to resolve Any types.
+ message_formatter: A function(message, indent, as_one_line): unicode|None
+ to custom format selected sub-messages (usually based on message type).
+ Use to pretty print parts of the protobuf for easier diffing.
"""
self.out = out
self.indent = indent
@@ -283,6 +297,7 @@ class _Printer(object):
self.float_format = float_format
self.use_field_number = use_field_number
self.descriptor_pool = descriptor_pool
+ self.message_formatter = message_formatter
def _TryPrintAsAnyMessage(self, message):
"""Serializes if message is a google.protobuf.Any field."""
@@ -297,14 +312,27 @@ class _Printer(object):
else:
return False
+ def _TryCustomFormatMessage(self, message):
+ formatted = self.message_formatter(message, self.indent, self.as_one_line)
+ if formatted is None:
+ return False
+
+ out = self.out
+ out.write(' ' * self.indent)
+ out.write(formatted)
+ out.write(' ' if self.as_one_line else '\n')
+ return True
+
def PrintMessage(self, message):
"""Convert protobuf message to text format.
Args:
message: The protocol buffers message.
"""
+ if self.message_formatter and self._TryCustomFormatMessage(message):
+ return
if (message.DESCRIPTOR.full_name == _ANY_FULL_TYPE_NAME and
- self.descriptor_pool and self._TryPrintAsAnyMessage(message)):
+ self._TryPrintAsAnyMessage(message)):
return
fields = message.ListFields()
if self.use_index_order:
@@ -422,15 +450,33 @@ class _Printer(object):
def Parse(text,
message,
allow_unknown_extension=False,
- allow_field_number=False):
+ allow_field_number=False,
+ descriptor_pool=None):
"""Parses a text representation of a protocol message into a message.
+ NOTE: for historical reasons this function does not clear the input
+ message. This is different from what the binary msg.ParseFrom(...) does.
+
+ Example
+ a = MyProto()
+ a.repeated_field.append('test')
+ b = MyProto()
+
+ text_format.Parse(repr(a), b)
+ text_format.Parse(repr(a), b) # repeated_field contains ["test", "test"]
+
+ # Binary version:
+ b.ParseFromString(a.SerializeToString()) # repeated_field is now "test"
+
+ Caller is responsible for clearing the message as needed.
+
Args:
text: Message text representation.
message: A protocol buffer message to merge into.
allow_unknown_extension: if True, skip over missing extensions and keep
parsing
allow_field_number: if True, both field number and field name are allowed.
+ descriptor_pool: A DescriptorPool used to resolve Any types.
Returns:
The same message passed as argument.
@@ -439,9 +485,15 @@ def Parse(text,
ParseError: On text parsing problems.
"""
if not isinstance(text, str):
- text = text.decode('utf-8')
- return ParseLines(
- text.split('\n'), message, allow_unknown_extension, allow_field_number)
+ if six.PY3:
+ text = text.decode('utf-8')
+ else:
+ text = text.encode('utf-8')
+ return ParseLines(text.split('\n'),
+ message,
+ allow_unknown_extension,
+ allow_field_number,
+ descriptor_pool=descriptor_pool)
def Merge(text,
@@ -468,6 +520,11 @@ def Merge(text,
Raises:
ParseError: On text parsing problems.
"""
+ if not isinstance(text, str):
+ if six.PY3:
+ text = text.decode('utf-8')
+ else:
+ text = text.encode('utf-8')
return MergeLines(
text.split('\n'),
message,
@@ -479,7 +536,8 @@ def Merge(text,
def ParseLines(lines,
message,
allow_unknown_extension=False,
- allow_field_number=False):
+ allow_field_number=False,
+ descriptor_pool=None):
"""Parses a text representation of a protocol message into a message.
Args:
@@ -496,7 +554,9 @@ def ParseLines(lines,
Raises:
ParseError: On text parsing problems.
"""
- parser = _Parser(allow_unknown_extension, allow_field_number)
+ parser = _Parser(allow_unknown_extension,
+ allow_field_number,
+ descriptor_pool=descriptor_pool)
return parser.ParseLines(lines, message)
@@ -513,6 +573,7 @@ def MergeLines(lines,
allow_unknown_extension: if True, skip over missing extensions and keep
parsing
allow_field_number: if True, both field number and field name are allowed.
+ descriptor_pool: A DescriptorPool used to resolve Any types.
Returns:
The same message passed as argument.
@@ -584,11 +645,6 @@ class _Parser(object):
ParseError: In case of text parsing problems.
"""
message_descriptor = message.DESCRIPTOR
- if (hasattr(message_descriptor, 'syntax') and
- message_descriptor.syntax == 'proto3'):
- # Proto3 doesn't represent presence so we can't test if multiple
- # scalars have occurred. We have to allow them.
- self._allow_multiple_scalars = True
if tokenizer.TryConsume('['):
name = [tokenizer.ConsumeIdentifier()]
while tokenizer.TryConsume('.'):
@@ -607,7 +663,11 @@ class _Parser(object):
field = None
else:
raise tokenizer.ParseErrorPreviousToken(
- 'Extension "%s" not registered.' % name)
+ 'Extension "%s" not registered. '
+ 'Did you import the _pb2 module which defines it? '
+ 'If you are trying to place the extension in the MessageSet '
+ 'field of another message that is in an Any or MessageSet field, '
+ 'that message\'s _pb2 module must be imported as well' % name)
elif message_descriptor != field.containing_type:
raise tokenizer.ParseErrorPreviousToken(
'Extension "%s" does not extend message type "%s".' %
@@ -686,17 +746,17 @@ class _Parser(object):
def _ConsumeAnyTypeUrl(self, tokenizer):
"""Consumes a google.protobuf.Any type URL and returns the type name."""
# Consume "type.googleapis.com/".
- tokenizer.ConsumeIdentifier()
+ prefix = [tokenizer.ConsumeIdentifier()]
tokenizer.Consume('.')
- tokenizer.ConsumeIdentifier()
+ prefix.append(tokenizer.ConsumeIdentifier())
tokenizer.Consume('.')
- tokenizer.ConsumeIdentifier()
+ prefix.append(tokenizer.ConsumeIdentifier())
tokenizer.Consume('/')
# Consume the fully-qualified type name.
name = [tokenizer.ConsumeIdentifier()]
while tokenizer.TryConsume('.'):
name.append(tokenizer.ConsumeIdentifier())
- return '.'.join(name)
+ return '.'.join(prefix), '.'.join(name)
def _MergeMessageField(self, tokenizer, message, field):
"""Merges a single scalar field into a message.
@@ -719,7 +779,7 @@ class _Parser(object):
if (field.message_type.full_name == _ANY_FULL_TYPE_NAME and
tokenizer.TryConsume('[')):
- packed_type_name = self._ConsumeAnyTypeUrl(tokenizer)
+ type_url_prefix, packed_type_name = self._ConsumeAnyTypeUrl(tokenizer)
tokenizer.Consume(']')
tokenizer.TryConsume(':')
if tokenizer.TryConsume('<'):
@@ -727,8 +787,6 @@ class _Parser(object):
else:
tokenizer.Consume('{')
expanded_any_end_token = '}'
- if not self.descriptor_pool:
- raise ParseError('Descriptor pool required to parse expanded Any field')
expanded_any_sub_message = _BuildMessageFromTypeName(packed_type_name,
self.descriptor_pool)
if not expanded_any_sub_message:
@@ -743,7 +801,8 @@ class _Parser(object):
any_message = getattr(message, field.name).add()
else:
any_message = getattr(message, field.name)
- any_message.Pack(expanded_any_sub_message)
+ any_message.Pack(expanded_any_sub_message,
+ type_url_prefix=type_url_prefix)
elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
if field.is_extension:
sub_message = message.Extensions[field].add()
@@ -771,6 +830,12 @@ class _Parser(object):
else:
getattr(message, field.name)[sub_message.key] = sub_message.value
+ @staticmethod
+ def _IsProto3Syntax(message):
+ message_descriptor = message.DESCRIPTOR
+ return (hasattr(message_descriptor, 'syntax') and
+ message_descriptor.syntax == 'proto3')
+
def _MergeScalarField(self, tokenizer, message, field):
"""Merges a single scalar field into a message.
@@ -820,15 +885,20 @@ class _Parser(object):
else:
getattr(message, field.name).append(value)
else:
+ # Proto3 doesn't represent presence so we can't test if multiple scalars
+ # have occurred. We have to allow them.
+ can_check_presence = not self._IsProto3Syntax(message)
if field.is_extension:
- if not self._allow_multiple_scalars and message.HasExtension(field):
+ if (not self._allow_multiple_scalars and can_check_presence and
+ message.HasExtension(field)):
raise tokenizer.ParseErrorPreviousToken(
'Message type "%s" should not have multiple "%s" extensions.' %
(message.DESCRIPTOR.full_name, field.full_name))
else:
message.Extensions[field] = value
else:
- if not self._allow_multiple_scalars and message.HasField(field.name):
+ if (not self._allow_multiple_scalars and can_check_presence and
+ message.HasField(field.name)):
raise tokenizer.ParseErrorPreviousToken(
'Message type "%s" should not have multiple "%s" fields.' %
(message.DESCRIPTOR.full_name, field.name))
@@ -1023,6 +1093,22 @@ class Tokenizer(object):
self.NextToken()
return result
+ def ConsumeCommentOrTrailingComment(self):
+ """Consumes a comment, returns a 2-tuple (trailing bool, comment str)."""
+
+ # Tokenizer initializes _previous_line and _previous_column to 0. As the
+ # tokenizer starts, it looks like there is a previous token on the line.
+ just_started = self._line == 0 and self._column == 0
+
+ before_parsing = self._previous_line
+ comment = self.ConsumeComment()
+
+ # A trailing comment is a comment on the same line than the previous token.
+ trailing = (self._previous_line == before_parsing
+ and not just_started)
+
+ return trailing, comment
+
def TryConsumeIdentifier(self):
try:
self.ConsumeIdentifier()
@@ -1063,7 +1149,7 @@ class Tokenizer(object):
"""
result = self.token
if not self._IDENTIFIER_OR_NUMBER.match(result):
- raise self.ParseError('Expected identifier or number.')
+ raise self.ParseError('Expected identifier or number, got %s.' % result)
self.NextToken()
return result
@@ -1481,6 +1567,11 @@ def ParseEnum(field, value):
(enum_descriptor.full_name, value))
else:
# Numeric value.
+ if hasattr(field.file, 'syntax'):
+ # Attribute is checked for compatibility.
+ if field.file.syntax == 'proto3':
+ # Proto3 accept numeric unknown enums.
+ return number
enum_value = enum_descriptor.values_by_number.get(number, None)
if enum_value is None:
raise ValueError('Enum type "%s" has no value with number %d.' %
diff --git a/python/mox.py b/python/mox.py
index 257468e5..43db0219 100755
--- a/python/mox.py
+++ b/python/mox.py
@@ -778,7 +778,7 @@ class Comparator:
rhs: any python object
"""
- raise NotImplementedError, 'method must be implemented by a subclass.'
+ raise NotImplementedError('method must be implemented by a subclass.')
def __eq__(self, rhs):
return self.equals(rhs)
diff --git a/python/release.sh b/python/release.sh
new file mode 100755
index 00000000..b0bf3b3f
--- /dev/null
+++ b/python/release.sh
@@ -0,0 +1,114 @@
+#!/bin/bash
+
+set -ex
+
+function get_source_version() {
+ grep "__version__ = '.*'" python/google/protobuf/__init__.py | sed -r "s/__version__ = '(.*)'/\1/"
+}
+
+function run_install_test() {
+ local VERSION=$1
+ local PYTHON=$2
+ local PYPI=$3
+
+ virtualenv --no-site-packages -p `which $PYTHON` test-venv
+
+ # Intentionally put a broken protoc in the path to make sure installation
+ # doesn't require protoc installed.
+ touch test-venv/bin/protoc
+ chmod +x test-venv/bin/protoc
+
+ source test-venv/bin/activate
+ pip install -i ${PYPI} protobuf==${VERSION}
+ deactivate
+ rm -fr test-venv
+}
+
+
+[ $# -lt 1 ] && {
+ echo "Usage: $0 VERSION ["
+ echo ""
+ echo "Examples:"
+ echo " Test 3.3.0 release using version number 3.3.0.dev1:"
+ echo " $0 3.0.0 dev1"
+ echo " Actually release 3.3.0 to PyPI:"
+ echo " $0 3.3.0"
+ exit 1
+}
+VERSION=$1
+DEV=$2
+
+# Make sure we are in a protobuf source tree.
+[ -f "python/google/protobuf/__init__.py" ] || {
+ echo "This script must be ran under root of protobuf source tree."
+ exit 1
+}
+
+# Make sure all files are world-readable.
+find python -type d -exec chmod a+r,a+x {} +
+find python -type f -exec chmod a+r {} +
+
+# Check that the supplied version number matches what's inside the source code.
+SOURCE_VERSION=`get_source_version`
+
+[ "${VERSION}" == "${SOURCE_VERSION}" -o "${VERSION}.${DEV}" == "${SOURCE_VERSION}" ] || {
+ echo "Version number specified on the command line ${VERSION} doesn't match"
+ echo "the actual version number in the source code: ${SOURCE_VERSION}"
+ exit 1
+}
+
+TESTING_ONLY=1
+TESTING_VERSION=${VERSION}.${DEV}
+if [ -z "${DEV}" ]; then
+ read -p "You are releasing ${VERSION} to PyPI. Are you sure? [y/n]" -r
+ echo
+ if [[ ! $REPLY =~ ^[Yy]$ ]]; then
+ exit 1
+ fi
+ TESTING_ONLY=0
+ TESTING_VERSION=${VERSION}
+else
+ # Use dev version number for testing.
+ sed -i -r "s/__version__ = '.*'/__version__ = '${VERSION}.${DEV}'/" python/google/protobuf/__init__.py
+fi
+
+cd python
+
+# Run tests locally.
+python setup.py build
+python setup.py test
+
+# Deploy source package to testing PyPI
+python setup.py sdist upload -r https://test.pypi.org/legacy/
+
+# Test locally with different python versions.
+run_install_test ${TESTING_VERSION} python2.7 https://test.pypi.org/simple
+run_install_test ${TESTING_VERSION} python3.4 https://test.pypi.org/simple
+
+# Deploy egg/wheel packages to testing PyPI and test again.
+python setup.py bdist_egg bdist_wheel upload -r https://test.pypi.org/legacy/
+run_install_test ${TESTING_VERSION} python2.7 https://test.pypi.org/simple
+run_install_test ${TESTING_VERSION} python3.4 https://test.pypi.org/simple
+
+echo "All install tests have passed using testing PyPI."
+
+if [ $TESTING_ONLY -eq 0 ]; then
+ read -p "Publish to PyPI? [y/n]" -r
+ echo
+ if [[ ! $REPLY =~ ^[Yy]$ ]]; then
+ exit 1
+ fi
+ echo "Publishing to PyPI..."
+ # Be sure to run build before sdist, because otherwise sdist will not include
+ # well-known types.
+ python setup.py clean build sdist upload
+ # Be sure to run clean before bdist_xxx, because otherwise bdist_xxx will
+ # include files you may not want in the package. E.g., if you have built
+ # and tested with --cpp_implemenation, bdist_xxx will include the _message.so
+ # file even when you no longer pass the --cpp_implemenation flag. See:
+ # https://github.com/google/protobuf/issues/3042
+ python setup.py clean build bdist_egg bdist_wheel upload
+else
+ # Set the version number back (i.e., remove dev suffix).
+ sed -i -r "s/__version__ = '.*'/__version__ = '${VERSION}'/" google/protobuf/__init__.py
+fi
diff --git a/python/release/wheel/Dockerfile b/python/release/wheel/Dockerfile
new file mode 100644
index 00000000..f38ec2f5
--- /dev/null
+++ b/python/release/wheel/Dockerfile
@@ -0,0 +1,6 @@
+FROM quay.io/pypa/manylinux1_x86_64
+
+RUN yum install -y libtool
+RUN /opt/python/cp27-cp27mu/bin/pip install twine
+
+COPY protobuf_optimized_pip.sh /
diff --git a/python/release/wheel/README.md b/python/release/wheel/README.md
new file mode 100644
index 00000000..edda2cd7
--- /dev/null
+++ b/python/release/wheel/README.md
@@ -0,0 +1,17 @@
+Description
+------------------------------
+This directory is used to build released wheels according to PEP513 and upload
+them to pypi.
+
+Usage
+------------------------------
+For example, to release 3.3.0:
+ ./protobuf_optimized_pip.sh 3.3.0 PYPI_USERNAME PYPI_PASSWORD
+
+Structure
+------------------------------
+| Source | Source |
+|--------------------------------------|---------------------------------------------------|
+| protobuf_optimized_pip.sh | Entry point. Calling Dockerfile and build_wheel_manylinux.sh |
+| Dockerfile | Build docker image according to PEP513. |
+| build_wheel_manylinux.sh | Build wheel packages in the docker container. |
diff --git a/python/release/wheel/build_wheel_manylinux.sh b/python/release/wheel/build_wheel_manylinux.sh
new file mode 100755
index 00000000..39fd8c12
--- /dev/null
+++ b/python/release/wheel/build_wheel_manylinux.sh
@@ -0,0 +1,27 @@
+#!/bin/bash
+
+# Print usage and fail.
+function usage() {
+ echo "Usage: protobuf_optimized_pip.sh PROTOBUF_VERSION PYPI_USERNAME PYPI_PASSWORD" >&2
+ exit 1 # Causes caller to exit because we use -e.
+}
+
+# Validate arguments.
+if [ $0 != ./build_wheel_manylinux.sh ]; then
+ echo "Please run this script from the directory in which it is located." >&2
+ exit 1
+fi
+
+if [ $# -lt 3 ]; then
+ usage
+ exit 1
+fi
+
+PROTOBUF_VERSION=$1
+PYPI_USERNAME=$2
+PYPI_PASSWORD=$3
+
+docker rmi protobuf-python-wheel
+docker build . -t protobuf-python-wheel
+docker run --rm protobuf-python-wheel ./protobuf_optimized_pip.sh $PROTOBUF_VERSION $PYPI_USERNAME $PYPI_PASSWORD
+docker rmi protobuf-python-wheel
diff --git a/python/release/wheel/protobuf_optimized_pip.sh b/python/release/wheel/protobuf_optimized_pip.sh
new file mode 100755
index 00000000..064d1d2a
--- /dev/null
+++ b/python/release/wheel/protobuf_optimized_pip.sh
@@ -0,0 +1,69 @@
+#!/usr/bin/env bash
+
+# DO NOT use this script manually! Called by docker.
+
+set -ex
+
+# Print usage and fail.
+function usage() {
+ echo "Usage: protobuf_optimized_pip.sh PROTOBUF_VERSION PYPI_USERNAME PYPI_PASSWORD" >&2
+ exit 1 # Causes caller to exit because we use -e.
+}
+
+# Build wheel
+function build_wheel() {
+ PYTHON_VERSION=$1
+ PYTHON_BIN=/opt/python/${PYTHON_VERSION}/bin/python
+
+ $PYTHON_BIN setup.py bdist_wheel --cpp_implementation --compile_static_extension
+ auditwheel repair dist/protobuf-${PROTOBUF_VERSION}-${PYTHON_VERSION}-linux_x86_64.whl
+}
+
+# Validate arguments.
+if [ $0 != ./protobuf_optimized_pip.sh ]; then
+ echo "Please run this script from the directory in which it is located." >&2
+ exit 1
+fi
+
+if [ $# -lt 3 ]; then
+ usage
+ exit 1
+fi
+
+PROTOBUF_VERSION=$1
+PYPI_USERNAME=$2
+PYPI_PASSWORD=$3
+
+DIR=${PWD}/'protobuf-python-build'
+PYTHON_VERSIONS=('cp27-cp27mu' 'cp33-cp33m' 'cp34-cp34m' 'cp35-cp35m' 'cp36-cp36m')
+
+mkdir -p ${DIR}
+cd ${DIR}
+curl -SsL -O https://github.com/google/protobuf/archive/v${PROTOBUF_VERSION}.tar.gz
+tar xzf v${PROTOBUF_VERSION}.tar.gz
+cd $DIR/protobuf-${PROTOBUF_VERSION}
+
+# Autoconf on centos 5.11 cannot recognize AC_PROG_OBJC.
+sed -i '/AC_PROG_OBJC/d' configure.ac
+sed -i 's/conformance\/Makefile//g' configure.ac
+
+# Use the /usr/bin/autoconf and related tools to pick the correct aclocal macros
+export PATH="/usr/bin:$PATH"
+
+# Build protoc
+./autogen.sh
+CXXFLAGS="-fPIC -g -O2" ./configure
+make -j8
+export PROTOC=$DIR/src/protoc
+
+cd python
+
+for PYTHON_VERSION in "${PYTHON_VERSIONS[@]}"
+do
+ build_wheel $PYTHON_VERSION
+done
+
+/opt/python/cp27-cp27mu/bin/twine upload wheelhouse/* <<!
+$PYPI_USERNAME
+$PYPI_PASSWORD
+!
diff --git a/python/setup.py b/python/setup.py
index ef1a31b4..efb74fe7 100755
--- a/python/setup.py
+++ b/python/setup.py
@@ -5,6 +5,7 @@ import glob
import os
import subprocess
import sys
+import platform
# We must use setuptools, not distutils, because we need to use the
# namespace_packages option for the "google" package.
@@ -77,8 +78,10 @@ def generate_proto(source, require = True):
def GenerateUnittestProtos():
generate_proto("../src/google/protobuf/any_test.proto", False)
+ generate_proto("../src/google/protobuf/map_proto2_unittest.proto", False)
generate_proto("../src/google/protobuf/map_unittest.proto", False)
generate_proto("../src/google/protobuf/test_messages_proto3.proto", False)
+ generate_proto("../src/google/protobuf/test_messages_proto2.proto", False)
generate_proto("../src/google/protobuf/unittest_arena.proto", False)
generate_proto("../src/google/protobuf/unittest_no_arena.proto", False)
generate_proto("../src/google/protobuf/unittest_no_arena_import.proto", False)
@@ -189,6 +192,12 @@ if __name__ == '__main__':
if "clang" in os.popen('$CC --version 2> /dev/null').read():
extra_compile_args.append('-Wno-shorten-64-to-32')
+ v, _, _ = platform.mac_ver()
+ if v:
+ v = float('.'.join(v.split('.')[:2]))
+ if v >= 10.12:
+ extra_compile_args.append('-std=c++11')
+
if warnings_as_errors in sys.argv:
extra_compile_args.append('-Werror')
sys.argv.remove(warnings_as_errors)
@@ -227,7 +236,7 @@ if __name__ == '__main__':
url='https://developers.google.com/protocol-buffers/',
maintainer='protobuf@googlegroups.com',
maintainer_email='protobuf@googlegroups.com',
- license='New BSD License',
+ license='3-Clause BSD License',
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 2",
diff --git a/python/tox.ini b/python/tox.ini
index 1600db21..38a81b4f 100644
--- a/python/tox.ini
+++ b/python/tox.ini
@@ -1,6 +1,6 @@
[tox]
envlist =
- py{26,27,33,34}-{cpp,python}
+ py{27,33,34,35,36}-{cpp,python}
[testenv]
usedevelop=true
@@ -9,6 +9,7 @@ setenv =
cpp: LD_LIBRARY_PATH={toxinidir}/../src/.libs
cpp: DYLD_LIBRARY_PATH={toxinidir}/../src/.libs
cpp: PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=cpp
+ python: PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python
commands =
python setup.py -q build_py
python: python setup.py -q build
diff --git a/ruby/Rakefile b/ruby/Rakefile
index 40d0a314..e30a75a3 100644
--- a/ruby/Rakefile
+++ b/ruby/Rakefile
@@ -64,13 +64,13 @@ else
task 'gem:windows' do
require 'rake_compiler_dock'
- RakeCompilerDock.sh "bundle && IN_DOCKER=true rake cross native gem RUBY_CC_VERSION=2.3.0:2.2.2:2.1.5:2.0.0"
+ RakeCompilerDock.sh "bundle && IN_DOCKER=true rake cross native gem RUBY_CC_VERSION=2.4.0:2.3.0:2.2.2:2.1.5:2.0.0"
end
if RUBY_PLATFORM =~ /darwin/
task 'gem:native' do
system "rake genproto"
- system "rake cross native gem RUBY_CC_VERSION=2.3.0:2.2.2:2.1.5:2.0.0"
+ system "rake cross native gem RUBY_CC_VERSION=2.4.0:2.3.0:2.2.2:2.1.5:2.0.0"
end
else
task 'gem:native' => [:genproto, 'gem:windows']
@@ -99,7 +99,13 @@ Gem::PackageTask.new(spec) do |pkg|
end
Rake::TestTask.new(:test => :build) do |t|
- t.test_files = FileList["tests/*.rb"]
+ t.test_files = FileList["tests/*.rb"].exclude("tests/gc_test.rb")
+end
+
+# gc_test needs to be split out to ensure the generated file hasn't been
+# imported by other tests.
+Rake::TestTask.new(:gc_test => :build) do |t|
+ t.test_files = FileList["tests/gc_test.rb"]
end
task :build => [:clean, :compile, :genproto]
diff --git a/ruby/compatibility_tests/v3.0.0/README.md b/ruby/compatibility_tests/v3.0.0/README.md
new file mode 100644
index 00000000..eb341228
--- /dev/null
+++ b/ruby/compatibility_tests/v3.0.0/README.md
@@ -0,0 +1,5 @@
+# Protobuf Ruby Compatibility Tests
+
+This drectory contains a snapshot of protobuf ruby 3.0.0 unittest code and
+test scripts used to verifies whether the latest version of protobuf is
+still compatible with 3.0.0 generated code.
diff --git a/ruby/compatibility_tests/v3.0.0/Rakefile b/ruby/compatibility_tests/v3.0.0/Rakefile
new file mode 100644
index 00000000..19a4ba12
--- /dev/null
+++ b/ruby/compatibility_tests/v3.0.0/Rakefile
@@ -0,0 +1,25 @@
+require "rake/testtask"
+
+# Proto for tests.
+genproto_output = []
+genproto_output << "tests/generated_code.rb"
+genproto_output << "tests/test_import.rb"
+file "tests/generated_code.rb" => "tests/generated_code.proto" do |file_task|
+ sh "./protoc --ruby_out=. tests/generated_code.proto"
+end
+
+file "tests/test_import.rb" => "tests/test_import.proto" do |file_task|
+ sh "./protoc --ruby_out=. tests/test_import.proto"
+end
+
+task :genproto => genproto_output
+
+task :clean do
+ sh "rm -f #{genproto_output.join(' ')}"
+end
+
+Rake::TestTask.new(:test => :genproto) do |t|
+ t.test_files = FileList["tests/*.rb"]
+end
+
+task :default => [:test]
diff --git a/ruby/compatibility_tests/v3.0.0/test.sh b/ruby/compatibility_tests/v3.0.0/test.sh
new file mode 100755
index 00000000..996dc020
--- /dev/null
+++ b/ruby/compatibility_tests/v3.0.0/test.sh
@@ -0,0 +1,17 @@
+#!/bin/bash
+
+set -ex
+
+# Change to the script's directory
+cd $(dirname $0)
+
+# Download 3.0.0 version of protoc
+PROTOC_BINARY_NAME="protoc-3.0.0-linux-x86_64.exe"
+if [ `uname` = "Darwin" ]; then
+ PROTOC_BINARY_NAME="protoc-3.0.0-osx-x86_64.exe"
+fi
+wget http://repo1.maven.org/maven2/com/google/protobuf/protoc/3.0.0/${PROTOC_BINARY_NAME} -O protoc
+chmod +x protoc
+
+# Run tests
+rake test
diff --git a/ruby/compatibility_tests/v3.0.0/tests/basic.rb b/ruby/compatibility_tests/v3.0.0/tests/basic.rb
new file mode 100644
index 00000000..05fe0278
--- /dev/null
+++ b/ruby/compatibility_tests/v3.0.0/tests/basic.rb
@@ -0,0 +1,1182 @@
+#!/usr/bin/ruby
+
+require 'google/protobuf'
+require 'test/unit'
+
+# ------------- generated code --------------
+
+module BasicTest
+ pool = Google::Protobuf::DescriptorPool.new
+ pool.build do
+ add_message "Foo" do
+ optional :bar, :message, 1, "Bar"
+ repeated :baz, :message, 2, "Baz"
+ end
+
+ add_message "Bar" do
+ optional :msg, :string, 1
+ end
+
+ add_message "Baz" do
+ optional :msg, :string, 1
+ end
+
+ add_message "TestMessage" do
+ optional :optional_int32, :int32, 1
+ optional :optional_int64, :int64, 2
+ optional :optional_uint32, :uint32, 3
+ optional :optional_uint64, :uint64, 4
+ optional :optional_bool, :bool, 5
+ optional :optional_float, :float, 6
+ optional :optional_double, :double, 7
+ optional :optional_string, :string, 8
+ optional :optional_bytes, :bytes, 9
+ optional :optional_msg, :message, 10, "TestMessage2"
+ optional :optional_enum, :enum, 11, "TestEnum"
+
+ repeated :repeated_int32, :int32, 12
+ repeated :repeated_int64, :int64, 13
+ repeated :repeated_uint32, :uint32, 14
+ repeated :repeated_uint64, :uint64, 15
+ repeated :repeated_bool, :bool, 16
+ repeated :repeated_float, :float, 17
+ repeated :repeated_double, :double, 18
+ repeated :repeated_string, :string, 19
+ repeated :repeated_bytes, :bytes, 20
+ repeated :repeated_msg, :message, 21, "TestMessage2"
+ repeated :repeated_enum, :enum, 22, "TestEnum"
+ end
+ add_message "TestMessage2" do
+ optional :foo, :int32, 1
+ end
+
+ add_message "Recursive1" do
+ optional :foo, :message, 1, "Recursive2"
+ end
+ add_message "Recursive2" do
+ optional :foo, :message, 1, "Recursive1"
+ end
+
+ add_enum "TestEnum" do
+ value :Default, 0
+ value :A, 1
+ value :B, 2
+ value :C, 3
+ end
+
+ add_message "BadFieldNames" do
+ optional :dup, :int32, 1
+ optional :class, :int32, 2
+ optional :"a.b", :int32, 3
+ end
+
+ add_message "MapMessage" do
+ map :map_string_int32, :string, :int32, 1
+ map :map_string_msg, :string, :message, 2, "TestMessage2"
+ end
+ add_message "MapMessageWireEquiv" do
+ repeated :map_string_int32, :message, 1, "MapMessageWireEquiv_entry1"
+ repeated :map_string_msg, :message, 2, "MapMessageWireEquiv_entry2"
+ end
+ add_message "MapMessageWireEquiv_entry1" do
+ optional :key, :string, 1
+ optional :value, :int32, 2
+ end
+ add_message "MapMessageWireEquiv_entry2" do
+ optional :key, :string, 1
+ optional :value, :message, 2, "TestMessage2"
+ end
+
+ add_message "OneofMessage" do
+ oneof :my_oneof do
+ optional :a, :string, 1
+ optional :b, :int32, 2
+ optional :c, :message, 3, "TestMessage2"
+ optional :d, :enum, 4, "TestEnum"
+ end
+ end
+ end
+
+ Foo = pool.lookup("Foo").msgclass
+ Bar = pool.lookup("Bar").msgclass
+ Baz = pool.lookup("Baz").msgclass
+ TestMessage = pool.lookup("TestMessage").msgclass
+ TestMessage2 = pool.lookup("TestMessage2").msgclass
+ Recursive1 = pool.lookup("Recursive1").msgclass
+ Recursive2 = pool.lookup("Recursive2").msgclass
+ TestEnum = pool.lookup("TestEnum").enummodule
+ BadFieldNames = pool.lookup("BadFieldNames").msgclass
+ MapMessage = pool.lookup("MapMessage").msgclass
+ MapMessageWireEquiv = pool.lookup("MapMessageWireEquiv").msgclass
+ MapMessageWireEquiv_entry1 =
+ pool.lookup("MapMessageWireEquiv_entry1").msgclass
+ MapMessageWireEquiv_entry2 =
+ pool.lookup("MapMessageWireEquiv_entry2").msgclass
+ OneofMessage = pool.lookup("OneofMessage").msgclass
+
+# ------------ test cases ---------------
+
+ class MessageContainerTest < Test::Unit::TestCase
+
+ def test_defaults
+ m = TestMessage.new
+ assert m.optional_int32 == 0
+ assert m.optional_int64 == 0
+ assert m.optional_uint32 == 0
+ assert m.optional_uint64 == 0
+ assert m.optional_bool == false
+ assert m.optional_float == 0.0
+ assert m.optional_double == 0.0
+ assert m.optional_string == ""
+ assert m.optional_bytes == ""
+ assert m.optional_msg == nil
+ assert m.optional_enum == :Default
+ end
+
+ def test_setters
+ m = TestMessage.new
+ m.optional_int32 = -42
+ assert m.optional_int32 == -42
+ m.optional_int64 = -0x1_0000_0000
+ assert m.optional_int64 == -0x1_0000_0000
+ m.optional_uint32 = 0x9000_0000
+ assert m.optional_uint32 == 0x9000_0000
+ m.optional_uint64 = 0x9000_0000_0000_0000
+ assert m.optional_uint64 == 0x9000_0000_0000_0000
+ m.optional_bool = true
+ assert m.optional_bool == true
+ m.optional_float = 0.5
+ assert m.optional_float == 0.5
+ m.optional_double = 0.5
+ m.optional_string = "hello"
+ assert m.optional_string == "hello"
+ m.optional_bytes = "world".encode!('ASCII-8BIT')
+ assert m.optional_bytes == "world"
+ m.optional_msg = TestMessage2.new(:foo => 42)
+ assert m.optional_msg == TestMessage2.new(:foo => 42)
+ m.optional_msg = nil
+ assert m.optional_msg == nil
+ end
+
+ def test_ctor_args
+ m = TestMessage.new(:optional_int32 => -42,
+ :optional_msg => TestMessage2.new,
+ :optional_enum => :C,
+ :repeated_string => ["hello", "there", "world"])
+ assert m.optional_int32 == -42
+ assert m.optional_msg.class == TestMessage2
+ assert m.repeated_string.length == 3
+ assert m.optional_enum == :C
+ assert m.repeated_string[0] == "hello"
+ assert m.repeated_string[1] == "there"
+ assert m.repeated_string[2] == "world"
+ end
+
+ def test_inspect
+ m = TestMessage.new(:optional_int32 => -42,
+ :optional_enum => :A,
+ :optional_msg => TestMessage2.new,
+ :repeated_string => ["hello", "there", "world"])
+ expected = '<BasicTest::TestMessage: optional_int32: -42, optional_int64: 0, optional_uint32: 0, optional_uint64: 0, optional_bool: false, optional_float: 0.0, optional_double: 0.0, optional_string: "", optional_bytes: "", optional_msg: <BasicTest::TestMessage2: foo: 0>, optional_enum: :A, repeated_int32: [], repeated_int64: [], repeated_uint32: [], repeated_uint64: [], repeated_bool: [], repeated_float: [], repeated_double: [], repeated_string: ["hello", "there", "world"], repeated_bytes: [], repeated_msg: [], repeated_enum: []>'
+ assert_equal expected, m.inspect
+ end
+
+ def test_hash
+ m1 = TestMessage.new(:optional_int32 => 42)
+ m2 = TestMessage.new(:optional_int32 => 102)
+ assert m1.hash != 0
+ assert m2.hash != 0
+ # relying on the randomness here -- if hash function changes and we are
+ # unlucky enough to get a collision, then change the values above.
+ assert m1.hash != m2.hash
+ end
+
+ def test_unknown_field_errors
+ e = assert_raise NoMethodError do
+ TestMessage.new.hello
+ end
+ assert_match(/hello/, e.message)
+
+ e = assert_raise NoMethodError do
+ TestMessage.new.hello = "world"
+ end
+ assert_match(/hello/, e.message)
+ end
+
+ def test_initialization_map_errors
+ e = assert_raise ArgumentError do
+ TestMessage.new(:hello => "world")
+ end
+ assert_match(/hello/, e.message)
+
+ e = assert_raise ArgumentError do
+ MapMessage.new(:map_string_int32 => "hello")
+ end
+ assert_equal e.message, "Expected Hash object as initializer value for map field 'map_string_int32'."
+
+ e = assert_raise ArgumentError do
+ TestMessage.new(:repeated_uint32 => "hello")
+ end
+ assert_equal e.message, "Expected array as initializer value for repeated field 'repeated_uint32'."
+ end
+
+ def test_type_errors
+ m = TestMessage.new
+ assert_raise TypeError do
+ m.optional_int32 = "hello"
+ end
+ assert_raise TypeError do
+ m.optional_string = 42
+ end
+ assert_raise TypeError do
+ m.optional_string = nil
+ end
+ assert_raise TypeError do
+ m.optional_bool = 42
+ end
+ assert_raise TypeError do
+ m.optional_msg = TestMessage.new # expects TestMessage2
+ end
+
+ assert_raise TypeError do
+ m.repeated_int32 = [] # needs RepeatedField
+ end
+
+ assert_raise TypeError do
+ m.repeated_int32.push "hello"
+ end
+
+ assert_raise TypeError do
+ m.repeated_msg.push TestMessage.new
+ end
+ end
+
+ def test_string_encoding
+ m = TestMessage.new
+
+ # Assigning a normal (ASCII or UTF8) string to a bytes field, or
+ # ASCII-8BIT to a string field will convert to the proper encoding.
+ m.optional_bytes = "Test string ASCII".encode!('ASCII')
+ assert m.optional_bytes.frozen?
+ assert_equal Encoding::ASCII_8BIT, m.optional_bytes.encoding
+ assert_equal "Test string ASCII", m.optional_bytes
+
+ assert_raise Encoding::UndefinedConversionError do
+ m.optional_bytes = "Test string UTF-8 \u0100".encode!('UTF-8')
+ end
+
+ assert_raise Encoding::UndefinedConversionError do
+ m.optional_string = ["FFFF"].pack('H*')
+ end
+
+ # "Ordinary" use case.
+ m.optional_bytes = ["FFFF"].pack('H*')
+ m.optional_string = "\u0100"
+
+ # strings are immutable so we can't do this, but serialize should catch it.
+ m.optional_string = "asdf".encode!('UTF-8')
+ assert_raise RuntimeError do
+ m.optional_string.encode!('ASCII-8BIT')
+ end
+ end
+
+ def test_rptfield_int32
+ l = Google::Protobuf::RepeatedField.new(:int32)
+ assert l.count == 0
+ l = Google::Protobuf::RepeatedField.new(:int32, [1, 2, 3])
+ assert l.count == 3
+ assert_equal [1, 2, 3], l
+ assert_equal l, [1, 2, 3]
+ l.push 4
+ assert l == [1, 2, 3, 4]
+ dst_list = []
+ l.each { |val| dst_list.push val }
+ assert dst_list == [1, 2, 3, 4]
+ assert l.to_a == [1, 2, 3, 4]
+ assert l[0] == 1
+ assert l[3] == 4
+ l[0] = 5
+ assert l == [5, 2, 3, 4]
+
+ l2 = l.dup
+ assert l == l2
+ assert l.object_id != l2.object_id
+ l2.push 6
+ assert l.count == 4
+ assert l2.count == 5
+
+ assert l.inspect == '[5, 2, 3, 4]'
+
+ l.concat([7, 8, 9])
+ assert l == [5, 2, 3, 4, 7, 8, 9]
+ assert l.pop == 9
+ assert l == [5, 2, 3, 4, 7, 8]
+
+ assert_raise TypeError do
+ m = TestMessage.new
+ l.push m
+ end
+
+ m = TestMessage.new
+ m.repeated_int32 = l
+ assert m.repeated_int32 == [5, 2, 3, 4, 7, 8]
+ assert m.repeated_int32.object_id == l.object_id
+ l.push 42
+ assert m.repeated_int32.pop == 42
+
+ l3 = l + l.dup
+ assert l3.count == l.count * 2
+ l.count.times do |i|
+ assert l3[i] == l[i]
+ assert l3[l.count + i] == l[i]
+ end
+
+ l.clear
+ assert l.count == 0
+ l += [1, 2, 3, 4]
+ l.replace([5, 6, 7, 8])
+ assert l == [5, 6, 7, 8]
+
+ l4 = Google::Protobuf::RepeatedField.new(:int32)
+ l4[5] = 42
+ assert l4 == [0, 0, 0, 0, 0, 42]
+
+ l4 << 100
+ assert l4 == [0, 0, 0, 0, 0, 42, 100]
+ l4 << 101 << 102
+ assert l4 == [0, 0, 0, 0, 0, 42, 100, 101, 102]
+ end
+
+ def test_parent_rptfield
+ #make sure we set the RepeatedField and can add to it
+ m = TestMessage.new
+ assert m.repeated_string == []
+ m.repeated_string << 'ok'
+ m.repeated_string.push('ok2')
+ assert m.repeated_string == ['ok', 'ok2']
+ m.repeated_string += ['ok3']
+ assert m.repeated_string == ['ok', 'ok2', 'ok3']
+ end
+
+ def test_rptfield_msg
+ l = Google::Protobuf::RepeatedField.new(:message, TestMessage)
+ l.push TestMessage.new
+ assert l.count == 1
+ assert_raise TypeError do
+ l.push TestMessage2.new
+ end
+ assert_raise TypeError do
+ l.push 42
+ end
+
+ l2 = l.dup
+ assert l2[0] == l[0]
+ assert l2[0].object_id == l[0].object_id
+
+ l2 = Google::Protobuf.deep_copy(l)
+ assert l2[0] == l[0]
+ assert l2[0].object_id != l[0].object_id
+
+ l3 = l + l2
+ assert l3.count == 2
+ assert l3[0] == l[0]
+ assert l3[1] == l2[0]
+ l3[0].optional_int32 = 1000
+ assert l[0].optional_int32 == 1000
+
+ new_msg = TestMessage.new(:optional_int32 => 200)
+ l4 = l + [new_msg]
+ assert l4.count == 2
+ new_msg.optional_int32 = 1000
+ assert l4[1].optional_int32 == 1000
+ end
+
+ def test_rptfield_enum
+ l = Google::Protobuf::RepeatedField.new(:enum, TestEnum)
+ l.push :A
+ l.push :B
+ l.push :C
+ assert l.count == 3
+ assert_raise RangeError do
+ l.push :D
+ end
+ assert l[0] == :A
+
+ l.push 4
+ assert l[3] == 4
+ end
+
+ def test_rptfield_initialize
+ assert_raise ArgumentError do
+ l = Google::Protobuf::RepeatedField.new
+ end
+ assert_raise ArgumentError do
+ l = Google::Protobuf::RepeatedField.new(:message)
+ end
+ assert_raise ArgumentError do
+ l = Google::Protobuf::RepeatedField.new([1, 2, 3])
+ end
+ assert_raise ArgumentError do
+ l = Google::Protobuf::RepeatedField.new(:message, [TestMessage2.new])
+ end
+ end
+
+ def test_rptfield_array_ducktyping
+ l = Google::Protobuf::RepeatedField.new(:int32)
+ length_methods = %w(count length size)
+ length_methods.each do |lm|
+ assert l.send(lm) == 0
+ end
+ # out of bounds returns a nil
+ assert l[0] == nil
+ assert l[1] == nil
+ assert l[-1] == nil
+ l.push 4
+ length_methods.each do |lm|
+ assert l.send(lm) == 1
+ end
+ assert l[0] == 4
+ assert l[1] == nil
+ assert l[-1] == 4
+ assert l[-2] == nil
+
+ l.push 2
+ length_methods.each do |lm|
+ assert l.send(lm) == 2
+ end
+ assert l[0] == 4
+ assert l[1] == 2
+ assert l[2] == nil
+ assert l[-1] == 2
+ assert l[-2] == 4
+ assert l[-3] == nil
+
+ #adding out of scope will backfill with empty objects
+ end
+
+ def test_map_basic
+ # allowed key types:
+ # :int32, :int64, :uint32, :uint64, :bool, :string, :bytes.
+
+ m = Google::Protobuf::Map.new(:string, :int32)
+ m["asdf"] = 1
+ assert m["asdf"] == 1
+ m["jkl;"] = 42
+ assert m == { "jkl;" => 42, "asdf" => 1 }
+ assert m.has_key?("asdf")
+ assert !m.has_key?("qwerty")
+ assert m.length == 2
+
+ m2 = m.dup
+ assert m == m2
+ assert m.hash != 0
+ assert m.hash == m2.hash
+
+ collected = {}
+ m.each { |k,v| collected[v] = k }
+ assert collected == { 42 => "jkl;", 1 => "asdf" }
+
+ assert m.delete("asdf") == 1
+ assert !m.has_key?("asdf")
+ assert m["asdf"] == nil
+ assert !m.has_key?("asdf")
+
+ # We only assert on inspect value when there is one map entry because the
+ # order in which elements appear is unspecified (depends on the internal
+ # hash function). We don't want a brittle test.
+ assert m.inspect == "{\"jkl;\"=>42}"
+
+ assert m.keys == ["jkl;"]
+ assert m.values == [42]
+
+ m.clear
+ assert m.length == 0
+ assert m == {}
+
+ assert_raise TypeError do
+ m[1] = 1
+ end
+ assert_raise RangeError do
+ m["asdf"] = 0x1_0000_0000
+ end
+ end
+
+ def test_map_ctor
+ m = Google::Protobuf::Map.new(:string, :int32,
+ {"a" => 1, "b" => 2, "c" => 3})
+ assert m == {"a" => 1, "c" => 3, "b" => 2}
+ end
+
+ def test_map_keytypes
+ m = Google::Protobuf::Map.new(:int32, :int32)
+ m[1] = 42
+ m[-1] = 42
+ assert_raise RangeError do
+ m[0x8000_0000] = 1
+ end
+ assert_raise TypeError do
+ m["asdf"] = 1
+ end
+
+ m = Google::Protobuf::Map.new(:int64, :int32)
+ m[0x1000_0000_0000_0000] = 1
+ assert_raise RangeError do
+ m[0x1_0000_0000_0000_0000] = 1
+ end
+ assert_raise TypeError do
+ m["asdf"] = 1
+ end
+
+ m = Google::Protobuf::Map.new(:uint32, :int32)
+ m[0x8000_0000] = 1
+ assert_raise RangeError do
+ m[0x1_0000_0000] = 1
+ end
+ assert_raise RangeError do
+ m[-1] = 1
+ end
+
+ m = Google::Protobuf::Map.new(:uint64, :int32)
+ m[0x8000_0000_0000_0000] = 1
+ assert_raise RangeError do
+ m[0x1_0000_0000_0000_0000] = 1
+ end
+ assert_raise RangeError do
+ m[-1] = 1
+ end
+
+ m = Google::Protobuf::Map.new(:bool, :int32)
+ m[true] = 1
+ m[false] = 2
+ assert_raise TypeError do
+ m[1] = 1
+ end
+ assert_raise TypeError do
+ m["asdf"] = 1
+ end
+
+ m = Google::Protobuf::Map.new(:string, :int32)
+ m["asdf"] = 1
+ assert_raise TypeError do
+ m[1] = 1
+ end
+ assert_raise Encoding::UndefinedConversionError do
+ bytestring = ["FFFF"].pack("H*")
+ m[bytestring] = 1
+ end
+
+ m = Google::Protobuf::Map.new(:bytes, :int32)
+ bytestring = ["FFFF"].pack("H*")
+ m[bytestring] = 1
+ # Allowed -- we will automatically convert to ASCII-8BIT.
+ m["asdf"] = 1
+ assert_raise TypeError do
+ m[1] = 1
+ end
+ end
+
+ def test_map_msg_enum_valuetypes
+ m = Google::Protobuf::Map.new(:string, :message, TestMessage)
+ m["asdf"] = TestMessage.new
+ assert_raise TypeError do
+ m["jkl;"] = TestMessage2.new
+ end
+
+ m = Google::Protobuf::Map.new(
+ :string, :message, TestMessage,
+ { "a" => TestMessage.new(:optional_int32 => 42),
+ "b" => TestMessage.new(:optional_int32 => 84) })
+ assert m.length == 2
+ assert m.values.map{|msg| msg.optional_int32}.sort == [42, 84]
+
+ m = Google::Protobuf::Map.new(:string, :enum, TestEnum,
+ { "x" => :A, "y" => :B, "z" => :C })
+ assert m.length == 3
+ assert m["z"] == :C
+ m["z"] = 2
+ assert m["z"] == :B
+ m["z"] = 4
+ assert m["z"] == 4
+ assert_raise RangeError do
+ m["z"] = :Z
+ end
+ assert_raise RangeError do
+ m["z"] = "z"
+ end
+ end
+
+ def test_map_dup_deep_copy
+ m = Google::Protobuf::Map.new(
+ :string, :message, TestMessage,
+ { "a" => TestMessage.new(:optional_int32 => 42),
+ "b" => TestMessage.new(:optional_int32 => 84) })
+
+ m2 = m.dup
+ assert m == m2
+ assert m.object_id != m2.object_id
+ assert m["a"].object_id == m2["a"].object_id
+ assert m["b"].object_id == m2["b"].object_id
+
+ m2 = Google::Protobuf.deep_copy(m)
+ assert m == m2
+ assert m.object_id != m2.object_id
+ assert m["a"].object_id != m2["a"].object_id
+ assert m["b"].object_id != m2["b"].object_id
+ end
+
+ def test_map_field
+ m = MapMessage.new
+ assert m.map_string_int32 == {}
+ assert m.map_string_msg == {}
+
+ m = MapMessage.new(
+ :map_string_int32 => {"a" => 1, "b" => 2},
+ :map_string_msg => {"a" => TestMessage2.new(:foo => 1),
+ "b" => TestMessage2.new(:foo => 2)})
+ assert m.map_string_int32.keys.sort == ["a", "b"]
+ assert m.map_string_int32["a"] == 1
+ assert m.map_string_msg["b"].foo == 2
+
+ m.map_string_int32["c"] = 3
+ assert m.map_string_int32["c"] == 3
+ m.map_string_msg["c"] = TestMessage2.new(:foo => 3)
+ assert m.map_string_msg["c"] == TestMessage2.new(:foo => 3)
+ m.map_string_msg.delete("b")
+ m.map_string_msg.delete("c")
+ assert m.map_string_msg == { "a" => TestMessage2.new(:foo => 1) }
+
+ assert_raise TypeError do
+ m.map_string_msg["e"] = TestMessage.new # wrong value type
+ end
+ # ensure nothing was added by the above
+ assert m.map_string_msg == { "a" => TestMessage2.new(:foo => 1) }
+
+ m.map_string_int32 = Google::Protobuf::Map.new(:string, :int32)
+ assert_raise TypeError do
+ m.map_string_int32 = Google::Protobuf::Map.new(:string, :int64)
+ end
+ assert_raise TypeError do
+ m.map_string_int32 = {}
+ end
+
+ assert_raise TypeError do
+ m = MapMessage.new(:map_string_int32 => { 1 => "I am not a number" })
+ end
+ end
+
+ def test_map_encode_decode
+ m = MapMessage.new(
+ :map_string_int32 => {"a" => 1, "b" => 2},
+ :map_string_msg => {"a" => TestMessage2.new(:foo => 1),
+ "b" => TestMessage2.new(:foo => 2)})
+ m2 = MapMessage.decode(MapMessage.encode(m))
+ assert m == m2
+
+ m3 = MapMessageWireEquiv.decode(MapMessage.encode(m))
+ assert m3.map_string_int32.length == 2
+
+ kv = {}
+ m3.map_string_int32.map { |msg| kv[msg.key] = msg.value }
+ assert kv == {"a" => 1, "b" => 2}
+
+ kv = {}
+ m3.map_string_msg.map { |msg| kv[msg.key] = msg.value }
+ assert kv == {"a" => TestMessage2.new(:foo => 1),
+ "b" => TestMessage2.new(:foo => 2)}
+ end
+
+ def test_oneof_descriptors
+ d = OneofMessage.descriptor
+ o = d.lookup_oneof("my_oneof")
+ assert o != nil
+ assert o.class == Google::Protobuf::OneofDescriptor
+ assert o.name == "my_oneof"
+ oneof_count = 0
+ d.each_oneof{ |oneof|
+ oneof_count += 1
+ assert oneof == o
+ }
+ assert oneof_count == 1
+ assert o.count == 4
+ field_names = o.map{|f| f.name}.sort
+ assert field_names == ["a", "b", "c", "d"]
+ end
+
+ def test_oneof
+ d = OneofMessage.new
+ assert d.a == ""
+ assert d.b == 0
+ assert d.c == nil
+ assert d.d == :Default
+ assert d.my_oneof == nil
+
+ d.a = "hi"
+ assert d.a == "hi"
+ assert d.b == 0
+ assert d.c == nil
+ assert d.d == :Default
+ assert d.my_oneof == :a
+
+ d.b = 42
+ assert d.a == ""
+ assert d.b == 42
+ assert d.c == nil
+ assert d.d == :Default
+ assert d.my_oneof == :b
+
+ d.c = TestMessage2.new(:foo => 100)
+ assert d.a == ""
+ assert d.b == 0
+ assert d.c.foo == 100
+ assert d.d == :Default
+ assert d.my_oneof == :c
+
+ d.d = :C
+ assert d.a == ""
+ assert d.b == 0
+ assert d.c == nil
+ assert d.d == :C
+ assert d.my_oneof == :d
+
+ d2 = OneofMessage.decode(OneofMessage.encode(d))
+ assert d2 == d
+
+ encoded_field_a = OneofMessage.encode(OneofMessage.new(:a => "string"))
+ encoded_field_b = OneofMessage.encode(OneofMessage.new(:b => 1000))
+ encoded_field_c = OneofMessage.encode(
+ OneofMessage.new(:c => TestMessage2.new(:foo => 1)))
+ encoded_field_d = OneofMessage.encode(OneofMessage.new(:d => :B))
+
+ d3 = OneofMessage.decode(
+ encoded_field_c + encoded_field_a + encoded_field_d)
+ assert d3.a == ""
+ assert d3.b == 0
+ assert d3.c == nil
+ assert d3.d == :B
+
+ d4 = OneofMessage.decode(
+ encoded_field_c + encoded_field_a + encoded_field_d +
+ encoded_field_c)
+ assert d4.a == ""
+ assert d4.b == 0
+ assert d4.c.foo == 1
+ assert d4.d == :Default
+
+ d5 = OneofMessage.new(:a => "hello")
+ assert d5.a == "hello"
+ d5.a = nil
+ assert d5.a == ""
+ assert OneofMessage.encode(d5) == ''
+ assert d5.my_oneof == nil
+ end
+
+ def test_enum_field
+ m = TestMessage.new
+ assert m.optional_enum == :Default
+ m.optional_enum = :A
+ assert m.optional_enum == :A
+ assert_raise RangeError do
+ m.optional_enum = :ASDF
+ end
+ m.optional_enum = 1
+ assert m.optional_enum == :A
+ m.optional_enum = 100
+ assert m.optional_enum == 100
+ end
+
+ def test_dup
+ m = TestMessage.new
+ m.optional_string = "hello"
+ m.optional_int32 = 42
+ tm1 = TestMessage2.new(:foo => 100)
+ tm2 = TestMessage2.new(:foo => 200)
+ m.repeated_msg.push tm1
+ assert m.repeated_msg[-1] == tm1
+ m.repeated_msg.push tm2
+ assert m.repeated_msg[-1] == tm2
+ m2 = m.dup
+ assert m == m2
+ m.optional_int32 += 1
+ assert m != m2
+ assert m.repeated_msg[0] == m2.repeated_msg[0]
+ assert m.repeated_msg[0].object_id == m2.repeated_msg[0].object_id
+ end
+
+ def test_deep_copy
+ m = TestMessage.new(:optional_int32 => 42,
+ :repeated_msg => [TestMessage2.new(:foo => 100)])
+ m2 = Google::Protobuf.deep_copy(m)
+ assert m == m2
+ assert m.repeated_msg == m2.repeated_msg
+ assert m.repeated_msg.object_id != m2.repeated_msg.object_id
+ assert m.repeated_msg[0].object_id != m2.repeated_msg[0].object_id
+ end
+
+ def test_eq
+ m = TestMessage.new(:optional_int32 => 42,
+ :repeated_int32 => [1, 2, 3])
+ m2 = TestMessage.new(:optional_int32 => 43,
+ :repeated_int32 => [1, 2, 3])
+ assert m != m2
+ end
+
+ def test_enum_lookup
+ assert TestEnum::A == 1
+ assert TestEnum::B == 2
+ assert TestEnum::C == 3
+
+ assert TestEnum::lookup(1) == :A
+ assert TestEnum::lookup(2) == :B
+ assert TestEnum::lookup(3) == :C
+
+ assert TestEnum::resolve(:A) == 1
+ assert TestEnum::resolve(:B) == 2
+ assert TestEnum::resolve(:C) == 3
+ end
+
+ def test_parse_serialize
+ m = TestMessage.new(:optional_int32 => 42,
+ :optional_string => "hello world",
+ :optional_enum => :B,
+ :repeated_string => ["a", "b", "c"],
+ :repeated_int32 => [42, 43, 44],
+ :repeated_enum => [:A, :B, :C, 100],
+ :repeated_msg => [TestMessage2.new(:foo => 1),
+ TestMessage2.new(:foo => 2)])
+ data = TestMessage.encode m
+ m2 = TestMessage.decode data
+ assert m == m2
+
+ data = Google::Protobuf.encode m
+ m2 = Google::Protobuf.decode(TestMessage, data)
+ assert m == m2
+ end
+
+ def test_encode_decode_helpers
+ m = TestMessage.new(:optional_string => 'foo', :repeated_string => ['bar1', 'bar2'])
+ assert_equal 'foo', m.optional_string
+ assert_equal ['bar1', 'bar2'], m.repeated_string
+
+ json = m.to_json
+ m2 = TestMessage.decode_json(json)
+ assert_equal 'foo', m2.optional_string
+ assert_equal ['bar1', 'bar2'], m2.repeated_string
+ if RUBY_PLATFORM != "java"
+ assert m2.optional_string.frozen?
+ assert m2.repeated_string[0].frozen?
+ end
+
+ proto = m.to_proto
+ m2 = TestMessage.decode(proto)
+ assert_equal 'foo', m2.optional_string
+ assert_equal ['bar1', 'bar2'], m2.repeated_string
+ end
+
+ def test_protobuf_encode_decode_helpers
+ m = TestMessage.new(:optional_string => 'foo', :repeated_string => ['bar1', 'bar2'])
+ encoded_msg = Google::Protobuf.encode(m)
+ assert_equal m.to_proto, encoded_msg
+
+ decoded_msg = Google::Protobuf.decode(TestMessage, encoded_msg)
+ assert_equal TestMessage.decode(m.to_proto), decoded_msg
+ end
+
+ def test_protobuf_encode_decode_json_helpers
+ m = TestMessage.new(:optional_string => 'foo', :repeated_string => ['bar1', 'bar2'])
+ encoded_msg = Google::Protobuf.encode_json(m)
+ assert_equal m.to_json, encoded_msg
+
+ decoded_msg = Google::Protobuf.decode_json(TestMessage, encoded_msg)
+ assert_equal TestMessage.decode_json(m.to_json), decoded_msg
+ end
+
+ def test_to_h
+ m = TestMessage.new(:optional_bool => true, :optional_double => -10.100001, :optional_string => 'foo', :repeated_string => ['bar1', 'bar2'])
+ expected_result = {
+ :optional_bool=>true,
+ :optional_bytes=>"",
+ :optional_double=>-10.100001,
+ :optional_enum=>:Default,
+ :optional_float=>0.0,
+ :optional_int32=>0,
+ :optional_int64=>0,
+ :optional_msg=>nil,
+ :optional_string=>"foo",
+ :optional_uint32=>0,
+ :optional_uint64=>0,
+ :repeated_bool=>[],
+ :repeated_bytes=>[],
+ :repeated_double=>[],
+ :repeated_enum=>[],
+ :repeated_float=>[],
+ :repeated_int32=>[],
+ :repeated_int64=>[],
+ :repeated_msg=>[],
+ :repeated_string=>["bar1", "bar2"],
+ :repeated_uint32=>[],
+ :repeated_uint64=>[]
+ }
+ assert_equal expected_result, m.to_h
+ end
+
+
+ def test_def_errors
+ s = Google::Protobuf::DescriptorPool.new
+ assert_raise TypeError do
+ s.build do
+ # enum with no default (integer value 0)
+ add_enum "MyEnum" do
+ value :A, 1
+ end
+ end
+ end
+ assert_raise TypeError do
+ s.build do
+ # message with required field (unsupported in proto3)
+ add_message "MyMessage" do
+ required :foo, :int32, 1
+ end
+ end
+ end
+ end
+
+ def test_corecursive
+ # just be sure that we can instantiate types with corecursive field-type
+ # references.
+ m = Recursive1.new(:foo => Recursive2.new(:foo => Recursive1.new))
+ assert Recursive1.descriptor.lookup("foo").subtype ==
+ Recursive2.descriptor
+ assert Recursive2.descriptor.lookup("foo").subtype ==
+ Recursive1.descriptor
+
+ serialized = Recursive1.encode(m)
+ m2 = Recursive1.decode(serialized)
+ assert m == m2
+ end
+
+ def test_serialize_cycle
+ m = Recursive1.new(:foo => Recursive2.new)
+ m.foo.foo = m
+ assert_raise RuntimeError do
+ serialized = Recursive1.encode(m)
+ end
+ end
+
+ def test_bad_field_names
+ m = BadFieldNames.new(:dup => 1, :class => 2)
+ m2 = m.dup
+ assert m == m2
+ assert m['dup'] == 1
+ assert m['class'] == 2
+ m['dup'] = 3
+ assert m['dup'] == 3
+ m['a.b'] = 4
+ assert m['a.b'] == 4
+ end
+
+ def test_int_ranges
+ m = TestMessage.new
+
+ m.optional_int32 = 0
+ m.optional_int32 = -0x8000_0000
+ m.optional_int32 = +0x7fff_ffff
+ m.optional_int32 = 1.0
+ m.optional_int32 = -1.0
+ m.optional_int32 = 2e9
+ assert_raise RangeError do
+ m.optional_int32 = -0x8000_0001
+ end
+ assert_raise RangeError do
+ m.optional_int32 = +0x8000_0000
+ end
+ assert_raise RangeError do
+ m.optional_int32 = +0x1000_0000_0000_0000_0000_0000 # force Bignum
+ end
+ assert_raise RangeError do
+ m.optional_int32 = 1e12
+ end
+ assert_raise RangeError do
+ m.optional_int32 = 1.5
+ end
+
+ m.optional_uint32 = 0
+ m.optional_uint32 = +0xffff_ffff
+ m.optional_uint32 = 1.0
+ m.optional_uint32 = 4e9
+ assert_raise RangeError do
+ m.optional_uint32 = -1
+ end
+ assert_raise RangeError do
+ m.optional_uint32 = -1.5
+ end
+ assert_raise RangeError do
+ m.optional_uint32 = -1.5e12
+ end
+ assert_raise RangeError do
+ m.optional_uint32 = -0x1000_0000_0000_0000
+ end
+ assert_raise RangeError do
+ m.optional_uint32 = +0x1_0000_0000
+ end
+ assert_raise RangeError do
+ m.optional_uint32 = +0x1000_0000_0000_0000_0000_0000 # force Bignum
+ end
+ assert_raise RangeError do
+ m.optional_uint32 = 1e12
+ end
+ assert_raise RangeError do
+ m.optional_uint32 = 1.5
+ end
+
+ m.optional_int64 = 0
+ m.optional_int64 = -0x8000_0000_0000_0000
+ m.optional_int64 = +0x7fff_ffff_ffff_ffff
+ m.optional_int64 = 1.0
+ m.optional_int64 = -1.0
+ m.optional_int64 = 8e18
+ m.optional_int64 = -8e18
+ assert_raise RangeError do
+ m.optional_int64 = -0x8000_0000_0000_0001
+ end
+ assert_raise RangeError do
+ m.optional_int64 = +0x8000_0000_0000_0000
+ end
+ assert_raise RangeError do
+ m.optional_int64 = +0x1000_0000_0000_0000_0000_0000 # force Bignum
+ end
+ assert_raise RangeError do
+ m.optional_int64 = 1e50
+ end
+ assert_raise RangeError do
+ m.optional_int64 = 1.5
+ end
+
+ m.optional_uint64 = 0
+ m.optional_uint64 = +0xffff_ffff_ffff_ffff
+ m.optional_uint64 = 1.0
+ m.optional_uint64 = 16e18
+ assert_raise RangeError do
+ m.optional_uint64 = -1
+ end
+ assert_raise RangeError do
+ m.optional_uint64 = -1.5
+ end
+ assert_raise RangeError do
+ m.optional_uint64 = -1.5e12
+ end
+ assert_raise RangeError do
+ m.optional_uint64 = -0x1_0000_0000_0000_0000
+ end
+ assert_raise RangeError do
+ m.optional_uint64 = +0x1_0000_0000_0000_0000
+ end
+ assert_raise RangeError do
+ m.optional_uint64 = +0x1000_0000_0000_0000_0000_0000 # force Bignum
+ end
+ assert_raise RangeError do
+ m.optional_uint64 = 1e50
+ end
+ assert_raise RangeError do
+ m.optional_uint64 = 1.5
+ end
+ end
+
+ def test_stress_test
+ m = TestMessage.new
+ m.optional_int32 = 42
+ m.optional_int64 = 0x100000000
+ m.optional_string = "hello world"
+ 10.times do m.repeated_msg.push TestMessage2.new(:foo => 42) end
+ 10.times do m.repeated_string.push "hello world" end
+
+ data = TestMessage.encode(m)
+
+ l = 0
+ 10_000.times do
+ m = TestMessage.decode(data)
+ data_new = TestMessage.encode(m)
+ assert data_new == data
+ data = data_new
+ end
+ end
+
+ def test_reflection
+ m = TestMessage.new(:optional_int32 => 1234)
+ msgdef = m.class.descriptor
+ assert msgdef.class == Google::Protobuf::Descriptor
+ assert msgdef.any? {|field| field.name == "optional_int32"}
+ optional_int32 = msgdef.lookup "optional_int32"
+ assert optional_int32.class == Google::Protobuf::FieldDescriptor
+ assert optional_int32 != nil
+ assert optional_int32.name == "optional_int32"
+ assert optional_int32.type == :int32
+ optional_int32.set(m, 5678)
+ assert m.optional_int32 == 5678
+ m.optional_int32 = 1000
+ assert optional_int32.get(m) == 1000
+
+ optional_msg = msgdef.lookup "optional_msg"
+ assert optional_msg.subtype == TestMessage2.descriptor
+
+ optional_msg.set(m, optional_msg.subtype.msgclass.new)
+
+ assert msgdef.msgclass == TestMessage
+
+ optional_enum = msgdef.lookup "optional_enum"
+ assert optional_enum.subtype == TestEnum.descriptor
+ assert optional_enum.subtype.class == Google::Protobuf::EnumDescriptor
+ optional_enum.subtype.each do |k, v|
+ # set with integer, check resolution to symbolic name
+ optional_enum.set(m, v)
+ assert optional_enum.get(m) == k
+ end
+ end
+
+ def test_json
+ # TODO: Fix JSON in JRuby version.
+ return if RUBY_PLATFORM == "java"
+ m = TestMessage.new(:optional_int32 => 1234,
+ :optional_int64 => -0x1_0000_0000,
+ :optional_uint32 => 0x8000_0000,
+ :optional_uint64 => 0xffff_ffff_ffff_ffff,
+ :optional_bool => true,
+ :optional_float => 1.0,
+ :optional_double => -1e100,
+ :optional_string => "Test string",
+ :optional_bytes => ["FFFFFFFF"].pack('H*'),
+ :optional_msg => TestMessage2.new(:foo => 42),
+ :repeated_int32 => [1, 2, 3, 4],
+ :repeated_string => ["a", "b", "c"],
+ :repeated_bool => [true, false, true, false],
+ :repeated_msg => [TestMessage2.new(:foo => 1),
+ TestMessage2.new(:foo => 2)])
+
+ json_text = TestMessage.encode_json(m)
+ m2 = TestMessage.decode_json(json_text)
+ assert m == m2
+
+ # Crash case from GitHub issue 283.
+ bar = Bar.new(msg: "bar")
+ baz1 = Baz.new(msg: "baz")
+ baz2 = Baz.new(msg: "quux")
+ Foo.encode_json(Foo.new)
+ Foo.encode_json(Foo.new(bar: bar))
+ Foo.encode_json(Foo.new(bar: bar, baz: [baz1, baz2]))
+ end
+
+ def test_json_maps
+ # TODO: Fix JSON in JRuby version.
+ return if RUBY_PLATFORM == "java"
+ m = MapMessage.new(:map_string_int32 => {"a" => 1})
+ expected = '{"mapStringInt32":{"a":1},"mapStringMsg":{}}'
+ expected_preserve = '{"map_string_int32":{"a":1},"map_string_msg":{}}'
+ assert MapMessage.encode_json(m) == expected
+
+ json = MapMessage.encode_json(m, :preserve_proto_fieldnames => true)
+ assert json == expected_preserve
+
+ m2 = MapMessage.decode_json(MapMessage.encode_json(m))
+ assert m == m2
+ end
+ end
+end
diff --git a/ruby/compatibility_tests/v3.0.0/tests/generated_code.proto b/ruby/compatibility_tests/v3.0.0/tests/generated_code.proto
new file mode 100644
index 00000000..62fd83ed
--- /dev/null
+++ b/ruby/compatibility_tests/v3.0.0/tests/generated_code.proto
@@ -0,0 +1,67 @@
+syntax = "proto3";
+
+package a.b.c;
+
+message TestMessage {
+ int32 optional_int32 = 1;
+ int64 optional_int64 = 2;
+ uint32 optional_uint32 = 3;
+ uint64 optional_uint64 = 4;
+ bool optional_bool = 5;
+ double optional_double = 6;
+ float optional_float = 7;
+ string optional_string = 8;
+ bytes optional_bytes = 9;
+ TestEnum optional_enum = 10;
+ TestMessage optional_msg = 11;
+
+ repeated int32 repeated_int32 = 21;
+ repeated int64 repeated_int64 = 22;
+ repeated uint32 repeated_uint32 = 23;
+ repeated uint64 repeated_uint64 = 24;
+ repeated bool repeated_bool = 25;
+ repeated double repeated_double = 26;
+ repeated float repeated_float = 27;
+ repeated string repeated_string = 28;
+ repeated bytes repeated_bytes = 29;
+ repeated TestEnum repeated_enum = 30;
+ repeated TestMessage repeated_msg = 31;
+
+ oneof my_oneof {
+ int32 oneof_int32 = 41;
+ int64 oneof_int64 = 42;
+ uint32 oneof_uint32 = 43;
+ uint64 oneof_uint64 = 44;
+ bool oneof_bool = 45;
+ double oneof_double = 46;
+ float oneof_float = 47;
+ string oneof_string = 48;
+ bytes oneof_bytes = 49;
+ TestEnum oneof_enum = 50;
+ TestMessage oneof_msg = 51;
+ }
+
+ map<int32, string> map_int32_string = 61;
+ map<int64, string> map_int64_string = 62;
+ map<uint32, string> map_uint32_string = 63;
+ map<uint64, string> map_uint64_string = 64;
+ map<bool, string> map_bool_string = 65;
+ map<string, string> map_string_string = 66;
+ map<string, TestMessage> map_string_msg = 67;
+ map<string, TestEnum> map_string_enum = 68;
+ map<string, int32> map_string_int32 = 69;
+ map<string, bool> map_string_bool = 70;
+
+ message NestedMessage {
+ int32 foo = 1;
+ }
+
+ NestedMessage nested_message = 80;
+}
+
+enum TestEnum {
+ Default = 0;
+ A = 1;
+ B = 2;
+ C = 3;
+}
diff --git a/ruby/compatibility_tests/v3.0.0/tests/generated_code_test.rb b/ruby/compatibility_tests/v3.0.0/tests/generated_code_test.rb
new file mode 100644
index 00000000..b92b0462
--- /dev/null
+++ b/ruby/compatibility_tests/v3.0.0/tests/generated_code_test.rb
@@ -0,0 +1,19 @@
+#!/usr/bin/ruby
+
+# generated_code.rb is in the same directory as this test.
+$LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__)))
+
+require 'generated_code_pb'
+require 'test_import_pb'
+require 'test/unit'
+
+class GeneratedCodeTest < Test::Unit::TestCase
+ def test_generated_msg
+ # just test that we can instantiate the message. The purpose of this test
+ # is to ensure that the output of the code generator is valid Ruby and
+ # successfully creates message definitions and classes, not to test every
+ # aspect of the extension (basic.rb is for that).
+ m = A::B::C::TestMessage.new()
+ m2 = FooBar::TestImportedMessage.new()
+ end
+end
diff --git a/ruby/compatibility_tests/v3.0.0/tests/repeated_field_test.rb b/ruby/compatibility_tests/v3.0.0/tests/repeated_field_test.rb
new file mode 100644
index 00000000..25727b7b
--- /dev/null
+++ b/ruby/compatibility_tests/v3.0.0/tests/repeated_field_test.rb
@@ -0,0 +1,640 @@
+#!/usr/bin/ruby
+
+require 'google/protobuf'
+require 'test/unit'
+
+class RepeatedFieldTest < Test::Unit::TestCase
+
+ def test_acts_like_enumerator
+ m = TestMessage.new
+ (Enumerable.instance_methods - TestMessage.new.repeated_string.methods).each do |method_name|
+ assert m.repeated_string.respond_to?(method_name) == true, "does not respond to #{method_name}"
+ end
+ end
+
+ def test_acts_like_an_array
+ m = TestMessage.new
+ arr_methods = ([].methods - TestMessage.new.repeated_string.methods)
+ # jRuby additions to the Array class that we can ignore
+ arr_methods -= [ :indices, :iter_for_each, :iter_for_each_index,
+ :iter_for_each_with_index, :dimensions, :copy_data, :copy_data_simple,
+ :nitems, :iter_for_reverse_each, :indexes]
+ arr_methods.each do |method_name|
+ assert m.repeated_string.respond_to?(method_name) == true, "does not respond to #{method_name}"
+ end
+ end
+
+ def test_first
+ m = TestMessage.new
+ repeated_field_names(TestMessage).each do |field_name|
+ assert_nil m.send(field_name).first
+ end
+ fill_test_msg(m)
+ assert_equal -10, m.repeated_int32.first
+ assert_equal -1_000_000, m.repeated_int64.first
+ assert_equal 10, m.repeated_uint32.first
+ assert_equal 1_000_000, m.repeated_uint64.first
+ assert_equal true, m.repeated_bool.first
+ assert_equal -1.01, m.repeated_float.first.round(2)
+ assert_equal -1.0000000000001, m.repeated_double.first
+ assert_equal 'foo', m.repeated_string.first
+ assert_equal "bar".encode!('ASCII-8BIT'), m.repeated_bytes.first
+ assert_equal TestMessage2.new(:foo => 1), m.repeated_msg.first
+ assert_equal :A, m.repeated_enum.first
+ end
+
+
+ def test_last
+ m = TestMessage.new
+ repeated_field_names(TestMessage).each do |field_name|
+ assert_nil m.send(field_name).first
+ end
+ fill_test_msg(m)
+ assert_equal -11, m.repeated_int32.last
+ assert_equal -1_000_001, m.repeated_int64.last
+ assert_equal 11, m.repeated_uint32.last
+ assert_equal 1_000_001, m.repeated_uint64.last
+ assert_equal false, m.repeated_bool.last
+ assert_equal -1.02, m.repeated_float.last.round(2)
+ assert_equal -1.0000000000002, m.repeated_double.last
+ assert_equal 'bar', m.repeated_string.last
+ assert_equal "foo".encode!('ASCII-8BIT'), m.repeated_bytes.last
+ assert_equal TestMessage2.new(:foo => 2), m.repeated_msg.last
+ assert_equal :B, m.repeated_enum.last
+ end
+
+
+ def test_pop
+ m = TestMessage.new
+ repeated_field_names(TestMessage).each do |field_name|
+ assert_nil m.send(field_name).pop
+ end
+ fill_test_msg(m)
+
+ assert_equal -11, m.repeated_int32.pop
+ assert_equal -10, m.repeated_int32.pop
+ assert_equal -1_000_001, m.repeated_int64.pop
+ assert_equal -1_000_000, m.repeated_int64.pop
+ assert_equal 11, m.repeated_uint32.pop
+ assert_equal 10, m.repeated_uint32.pop
+ assert_equal 1_000_001, m.repeated_uint64.pop
+ assert_equal 1_000_000, m.repeated_uint64.pop
+ assert_equal false, m.repeated_bool.pop
+ assert_equal true, m.repeated_bool.pop
+ assert_equal -1.02, m.repeated_float.pop.round(2)
+ assert_equal -1.01, m.repeated_float.pop.round(2)
+ assert_equal -1.0000000000002, m.repeated_double.pop
+ assert_equal -1.0000000000001, m.repeated_double.pop
+ assert_equal 'bar', m.repeated_string.pop
+ assert_equal 'foo', m.repeated_string.pop
+ assert_equal "foo".encode!('ASCII-8BIT'), m.repeated_bytes.pop
+ assert_equal "bar".encode!('ASCII-8BIT'), m.repeated_bytes.pop
+ assert_equal TestMessage2.new(:foo => 2), m.repeated_msg.pop
+ assert_equal TestMessage2.new(:foo => 1), m.repeated_msg.pop
+ assert_equal :B, m.repeated_enum.pop
+ assert_equal :A, m.repeated_enum.pop
+ repeated_field_names(TestMessage).each do |field_name|
+ assert_nil m.send(field_name).pop
+ end
+
+ fill_test_msg(m)
+ assert_equal ['bar', 'foo'], m.repeated_string.pop(2)
+ assert_nil m.repeated_string.pop
+ end
+
+
+ def test_each
+ m = TestMessage.new
+ 5.times{|i| m.repeated_string << 'string' }
+ count = 0
+ m.repeated_string.each do |val|
+ assert_equal 'string', val
+ count += 1
+ end
+ assert_equal 5, count
+ result = m.repeated_string.each{|val| val + '_junk'}
+ assert_equal ['string'] * 5, result
+ end
+
+
+ def test_empty?
+ m = TestMessage.new
+ assert_equal true, m.repeated_string.empty?
+ m.repeated_string << 'foo'
+ assert_equal false, m.repeated_string.empty?
+ m.repeated_string << 'bar'
+ assert_equal false, m.repeated_string.empty?
+ end
+
+ def test_array_accessor
+ m = TestMessage.new
+ reference_arr = %w(foo bar baz)
+ m.repeated_string += reference_arr.clone
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr[1]
+ end
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr[-2]
+ end
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr[20]
+ end
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr[1, 2]
+ end
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr[0..2]
+ end
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr[-1, 1]
+ end
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr[10, 12]
+ end
+ end
+
+ def test_array_settor
+ m = TestMessage.new
+ reference_arr = %w(foo bar baz)
+ m.repeated_string += reference_arr.clone
+
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr[1] = 'junk'
+ end
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr[-2] = 'snappy'
+ end
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr[3] = ''
+ end
+ # slight deviation; we are strongly typed, and nil is not allowed
+ # for string types;
+ m.repeated_string[5] = 'spacious'
+ assert_equal ["foo", "snappy", "baz", "", "", "spacious"], m.repeated_string
+
+ #make sure it sests the default types for other fields besides strings
+ %w(repeated_int32 repeated_int64 repeated_uint32 repeated_uint64).each do |field_name|
+ m.send(field_name)[3] = 10
+ assert_equal [0,0,0,10], m.send(field_name)
+ end
+ m.repeated_float[3] = 10.1
+ #wonky mri float handling
+ assert_equal [0,0,0], m.repeated_float.to_a[0..2]
+ assert_equal 10.1, m.repeated_float[3].round(1)
+ m.repeated_double[3] = 10.1
+ assert_equal [0,0,0,10.1], m.repeated_double
+ m.repeated_bool[3] = true
+ assert_equal [false, false, false, true], m.repeated_bool
+ m.repeated_bytes[3] = "bar".encode!('ASCII-8BIT')
+ assert_equal ['', '', '', "bar".encode!('ASCII-8BIT')], m.repeated_bytes
+ m.repeated_msg[3] = TestMessage2.new(:foo => 1)
+ assert_equal [nil, nil, nil, TestMessage2.new(:foo => 1)], m.repeated_msg
+ m.repeated_enum[3] = :A
+ assert_equal [:Default, :Default, :Default, :A], m.repeated_enum
+
+ # check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ # arr[20] = 'spacious'
+ # end
+ # TODO: accessor doesn't allow other ruby-like methods
+ # check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ # arr[1, 2] = 'fizz'
+ # end
+ # check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ # arr[0..2] = 'buzz'
+ # end
+ end
+
+ def test_push
+ m = TestMessage.new
+ reference_arr = %w(foo bar baz)
+ m.repeated_string += reference_arr.clone
+
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.push('fizz')
+ end
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr << 'fizz'
+ end
+ #TODO: push should support multiple
+ # check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ # arr.push('fizz', 'buzz')
+ # end
+ end
+
+ def test_clear
+ m = TestMessage.new
+ reference_arr = %w(foo bar baz)
+ m.repeated_string += reference_arr.clone
+
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.clear
+ end
+ end
+
+ def test_concat
+ m = TestMessage.new
+ reference_arr = %w(foo bar baz)
+ m.repeated_string += reference_arr.clone
+ m.repeated_string.concat(['fizz', 'buzz'])
+ assert_equal %w(foo bar baz fizz buzz), m.repeated_string
+ #TODO: concat should return the orig array
+ # check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ # arr.concat(['fizz', 'buzz'])
+ # end
+ end
+
+ def test_equal
+ m = TestMessage.new
+ reference_arr = %w(foo bar baz)
+ m.repeated_string += reference_arr.clone
+ assert_equal reference_arr, m.repeated_string
+ reference_arr << 'fizz'
+ assert_not_equal reference_arr, m.repeated_string
+ m.repeated_string << 'fizz'
+ assert_equal reference_arr, m.repeated_string
+ end
+
+ def test_hash
+ # just a sanity check
+ m = TestMessage.new
+ reference_arr = %w(foo bar baz)
+ m.repeated_string += reference_arr.clone
+ assert m.repeated_string.hash.is_a?(Integer)
+ hash = m.repeated_string.hash
+ assert_equal hash, m.repeated_string.hash
+ m.repeated_string << 'j'
+ assert_not_equal hash, m.repeated_string.hash
+ end
+
+ def test_plus
+ m = TestMessage.new
+ reference_arr = %w(foo bar baz)
+ m.repeated_string += reference_arr.clone
+
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr + ['fizz', 'buzz']
+ end
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr += ['fizz', 'buzz']
+ end
+ end
+
+ def test_replace
+ m = TestMessage.new
+ reference_arr = %w(foo bar baz)
+ m.repeated_string += reference_arr.clone
+
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.replace(['fizz', 'buzz'])
+ end
+ end
+
+ def test_to_a
+ m = TestMessage.new
+ reference_arr = %w(foo bar baz)
+ m.repeated_string += reference_arr.clone
+
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.to_a
+ end
+ end
+
+ def test_to_ary
+ m = TestMessage.new
+ reference_arr = %w(foo bar baz)
+ m.repeated_string += reference_arr.clone
+
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.to_ary
+ end
+ end
+
+ # emulate Array behavior
+ ##########################
+
+ def test_collect!
+ m = TestMessage.new
+ reference_arr = %w(foo bar baz)
+ m.repeated_string += reference_arr.clone
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.collect!{|x| x + "!" }
+ end
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.collect!.with_index{|x, i| x[0...i] }
+ end
+ end
+
+ def test_compact!
+ m = TestMessage.new
+ m.repeated_msg << TestMessage2.new(:foo => 1)
+ m.repeated_msg << nil
+ m.repeated_msg << TestMessage2.new(:foo => 2)
+ reference_arr = m.repeated_string.to_a
+
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.compact!
+ end
+ end
+
+ def test_delete
+ m = TestMessage.new
+ reference_arr = %w(foo bar baz)
+ m.repeated_string += reference_arr.clone
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.delete('bar')
+ end
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.delete('nope')
+ end
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.delete('nope'){'within'}
+ end
+ end
+
+ def test_delete_at
+ m = TestMessage.new
+ reference_arr = %w(foo bar baz)
+ m.repeated_string += reference_arr.clone
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.delete_at(2)
+ end
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.delete_at(10)
+ end
+ end
+
+ def test_fill
+ m = TestMessage.new
+ reference_arr = %w(foo bar baz)
+ m.repeated_string += reference_arr.clone
+
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.fill("x")
+ end
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.fill("z", 2, 2)
+ end
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.fill("y", 0..1)
+ end
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.fill { |i| (i*i).to_s }
+ end
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.fill(-2) { |i| (i*i*i).to_s }
+ end
+ end
+
+ def test_flatten!
+ m = TestMessage.new
+ reference_arr = %w(foo bar baz)
+ m.repeated_string += reference_arr.clone
+
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.flatten!
+ end
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.flatten!(1)
+ end
+ end
+
+ def test_insert
+ m = TestMessage.new
+ reference_arr = %w(foo bar baz)
+ m.repeated_string += reference_arr.clone
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.insert(2, 'fizz')
+ end
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.insert(3, 'fizz', 'buzz', 'bazz')
+ end
+ end
+
+ def test_inspect
+ m = TestMessage.new
+ assert_equal '[]', m.repeated_string.inspect
+ m.repeated_string << 'foo'
+ assert_equal m.repeated_string.to_a.inspect, m.repeated_string.inspect
+ m.repeated_string << 'bar'
+ assert_equal m.repeated_string.to_a.inspect, m.repeated_string.inspect
+ end
+
+ def test_reverse!
+ m = TestMessage.new
+ reference_arr = %w(foo bar baz)
+ m.repeated_string += reference_arr.clone
+
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.reverse!
+ end
+ end
+
+ def test_rotate!
+ m = TestMessage.new
+ reference_arr = %w(foo bar baz)
+ m.repeated_string += reference_arr.clone
+
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.rotate!
+ end
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.rotate!(2)
+ end
+ end
+
+ def test_select!
+ m = TestMessage.new
+ reference_arr = %w(foo bar baz)
+ m.repeated_string += reference_arr.clone
+
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.select! { |v| v =~ /[aeiou]/ }
+ end
+ end
+
+ def test_shift
+ m = TestMessage.new
+ reference_arr = %w(foo bar baz)
+ m.repeated_string += reference_arr.clone
+
+ # should return an element
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.shift
+ end
+ # should return an array
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.shift(2)
+ end
+ # should return nil
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.shift
+ end
+ end
+
+ def test_shuffle!
+ m = TestMessage.new
+ m.repeated_string += %w(foo bar baz)
+ orig_repeated_string = m.repeated_string.clone
+ result = m.repeated_string.shuffle!
+ assert_equal m.repeated_string, result
+ # NOTE: sometimes it doesn't change the order...
+ # assert_not_equal m.repeated_string.to_a, orig_repeated_string.to_a
+ end
+
+ def test_slice!
+ m = TestMessage.new
+ reference_arr = %w(foo bar baz bar fizz buzz)
+ m.repeated_string += reference_arr.clone
+
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.slice!(2)
+ end
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.slice!(1,2)
+ end
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.slice!(0..1)
+ end
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.slice!(10)
+ end
+ end
+
+ def test_sort!
+ m = TestMessage.new
+ reference_arr = %w(foo bar baz)
+ m.repeated_string += reference_arr.clone
+
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.sort!
+ end
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.sort! { |x,y| y <=> x }
+ end
+ end
+
+ def test_sort_by!
+ m = TestMessage.new
+ reference_arr = %w(foo bar baz)
+ m.repeated_string += reference_arr.clone
+
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.sort_by!
+ end
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.sort_by!(&:hash)
+ end
+ end
+
+ def test_uniq!
+ m = TestMessage.new
+ reference_arr = %w(foo bar baz)
+ m.repeated_string += reference_arr.clone
+
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.uniq!
+ end
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.uniq!{|s| s[0] }
+ end
+ end
+
+ def test_unshift
+ m = TestMessage.new
+ reference_arr = %w(foo bar baz)
+ m.repeated_string += reference_arr.clone
+
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.unshift('1')
+ end
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.unshift('a', 'b')
+ end
+ check_self_modifying_method(m.repeated_string, reference_arr) do |arr|
+ arr.unshift('')
+ end
+ end
+
+
+ ##### HELPER METHODS
+
+ def check_self_modifying_method(repeated_field, ref_array)
+ expected_result = yield(ref_array)
+ actual_result = yield(repeated_field)
+ if expected_result.is_a?(Enumerator)
+ assert_equal expected_result.to_a, actual_result.to_a
+ else
+ assert_equal expected_result, actual_result
+ end
+ assert_equal ref_array, repeated_field
+ end
+
+
+ def repeated_field_names(klass)
+ klass.descriptor.find_all{|f| f.label == :repeated}.map(&:name)
+ end
+
+
+ def fill_test_msg(test_msg)
+ test_msg.repeated_int32 += [-10, -11]
+ test_msg.repeated_int64 += [-1_000_000, -1_000_001]
+ test_msg.repeated_uint32 += [10, 11]
+ test_msg.repeated_uint64 += [1_000_000, 1_000_001]
+ test_msg.repeated_bool += [true, false]
+ test_msg.repeated_float += [-1.01, -1.02]
+ test_msg.repeated_double += [-1.0000000000001, -1.0000000000002]
+ test_msg.repeated_string += %w(foo bar)
+ test_msg.repeated_bytes += ["bar".encode!('ASCII-8BIT'), "foo".encode!('ASCII-8BIT')]
+ test_msg.repeated_msg << TestMessage2.new(:foo => 1)
+ test_msg.repeated_msg << TestMessage2.new(:foo => 2)
+ test_msg.repeated_enum << :A
+ test_msg.repeated_enum << :B
+ end
+
+
+ pool = Google::Protobuf::DescriptorPool.new
+ pool.build do
+
+ add_message "TestMessage" do
+ optional :optional_int32, :int32, 1
+ optional :optional_int64, :int64, 2
+ optional :optional_uint32, :uint32, 3
+ optional :optional_uint64, :uint64, 4
+ optional :optional_bool, :bool, 5
+ optional :optional_float, :float, 6
+ optional :optional_double, :double, 7
+ optional :optional_string, :string, 8
+ optional :optional_bytes, :bytes, 9
+ optional :optional_msg, :message, 10, "TestMessage2"
+ optional :optional_enum, :enum, 11, "TestEnum"
+
+ repeated :repeated_int32, :int32, 12
+ repeated :repeated_int64, :int64, 13
+ repeated :repeated_uint32, :uint32, 14
+ repeated :repeated_uint64, :uint64, 15
+ repeated :repeated_bool, :bool, 16
+ repeated :repeated_float, :float, 17
+ repeated :repeated_double, :double, 18
+ repeated :repeated_string, :string, 19
+ repeated :repeated_bytes, :bytes, 20
+ repeated :repeated_msg, :message, 21, "TestMessage2"
+ repeated :repeated_enum, :enum, 22, "TestEnum"
+ end
+ add_message "TestMessage2" do
+ optional :foo, :int32, 1
+ end
+
+ add_enum "TestEnum" do
+ value :Default, 0
+ value :A, 1
+ value :B, 2
+ value :C, 3
+ end
+ end
+
+ TestMessage = pool.lookup("TestMessage").msgclass
+ TestMessage2 = pool.lookup("TestMessage2").msgclass
+ TestEnum = pool.lookup("TestEnum").enummodule
+
+
+end
diff --git a/ruby/compatibility_tests/v3.0.0/tests/stress.rb b/ruby/compatibility_tests/v3.0.0/tests/stress.rb
new file mode 100644
index 00000000..082d5e22
--- /dev/null
+++ b/ruby/compatibility_tests/v3.0.0/tests/stress.rb
@@ -0,0 +1,38 @@
+#!/usr/bin/ruby
+
+require 'google/protobuf'
+require 'test/unit'
+
+module StressTest
+ pool = Google::Protobuf::DescriptorPool.new
+ pool.build do
+ add_message "TestMessage" do
+ optional :a, :int32, 1
+ repeated :b, :message, 2, "M"
+ end
+ add_message "M" do
+ optional :foo, :string, 1
+ end
+ end
+
+ TestMessage = pool.lookup("TestMessage").msgclass
+ M = pool.lookup("M").msgclass
+
+ class StressTest < Test::Unit::TestCase
+ def get_msg
+ TestMessage.new(:a => 1000,
+ :b => [M.new(:foo => "hello"),
+ M.new(:foo => "world")])
+ end
+ def test_stress
+ m = get_msg
+ data = TestMessage.encode(m)
+ 100_000.times do
+ mnew = TestMessage.decode(data)
+ mnew = mnew.dup
+ assert_equal mnew.inspect, m.inspect
+ assert TestMessage.encode(mnew) == data
+ end
+ end
+ end
+end
diff --git a/ruby/compatibility_tests/v3.0.0/tests/test_import.proto b/ruby/compatibility_tests/v3.0.0/tests/test_import.proto
new file mode 100644
index 00000000..230484ee
--- /dev/null
+++ b/ruby/compatibility_tests/v3.0.0/tests/test_import.proto
@@ -0,0 +1,5 @@
+syntax = "proto3";
+
+package foo_bar;
+
+message TestImportedMessage {}
diff --git a/ruby/ext/google/protobuf_c/defs.c b/ruby/ext/google/protobuf_c/defs.c
index 7e93bafb..34d9663a 100644
--- a/ruby/ext/google/protobuf_c/defs.c
+++ b/ruby/ext/google/protobuf_c/defs.c
@@ -101,7 +101,7 @@ void DescriptorPool_mark(void* _self) {
void DescriptorPool_free(void* _self) {
DescriptorPool* self = _self;
- upb_symtab_unref(self->symtab, &self->symtab);
+ upb_symtab_free(self->symtab);
xfree(self);
}
@@ -113,7 +113,7 @@ void DescriptorPool_free(void* _self) {
*/
VALUE DescriptorPool_alloc(VALUE klass) {
DescriptorPool* self = ALLOC(DescriptorPool);
- self->symtab = upb_symtab_new(&self->symtab);
+ self->symtab = upb_symtab_new();
return TypedData_Wrap_Struct(klass, &_DescriptorPool_type, self);
}
@@ -228,7 +228,6 @@ DEFINE_CLASS(Descriptor, "Google::Protobuf::Descriptor");
void Descriptor_mark(void* _self) {
Descriptor* self = _self;
rb_gc_mark(self->klass);
- rb_gc_mark(self->typeclass_references);
}
void Descriptor_free(void* _self) {
@@ -283,7 +282,6 @@ VALUE Descriptor_alloc(VALUE klass) {
self->pb_serialize_handlers = NULL;
self->json_serialize_handlers = NULL;
self->json_serialize_handlers_preserve = NULL;
- self->typeclass_references = rb_ary_new();
return ret;
}
@@ -1635,7 +1633,7 @@ VALUE Builder_alloc(VALUE klass) {
Builder* self = ALLOC(Builder);
VALUE ret = TypedData_Wrap_Struct(
klass, &_Builder_type, self);
- self->pending_list = rb_ary_new();
+ self->pending_list = Qnil;
self->defs = NULL;
return ret;
}
@@ -1645,6 +1643,7 @@ void Builder_register(VALUE module) {
rb_define_alloc_func(klass, Builder_alloc);
rb_define_method(klass, "add_message", Builder_add_message, 1);
rb_define_method(klass, "add_enum", Builder_add_enum, 1);
+ rb_define_method(klass, "initialize", Builder_initialize, 0);
rb_define_method(klass, "finalize_to_pool", Builder_finalize_to_pool, 1);
cBuilder = klass;
rb_gc_register_address(&cBuilder);
@@ -1652,6 +1651,18 @@ void Builder_register(VALUE module) {
/*
* call-seq:
+ * Builder.new(d) => builder
+ *
+ * Create a new message builder.
+ */
+VALUE Builder_initialize(VALUE _self) {
+ DEFINE_SELF(Builder, self, _self);
+ self->pending_list = rb_ary_new();
+ return Qnil;
+}
+
+/*
+ * call-seq:
* Builder.add_message(name, &block)
*
* Creates a new, empty descriptor with the given name, and invokes the block in
diff --git a/ruby/ext/google/protobuf_c/encode_decode.c b/ruby/ext/google/protobuf_c/encode_decode.c
index 08c72bcc..d1b6e89e 100644
--- a/ruby/ext/google/protobuf_c/encode_decode.c
+++ b/ruby/ext/google/protobuf_c/encode_decode.c
@@ -44,6 +44,56 @@ VALUE noleak_rb_str_cat(VALUE rb_str, const char *str, long len) {
return rb_str;
}
+// The code below also comes from upb's prototype Ruby binding, developed by
+// haberman@.
+
+/* stringsink *****************************************************************/
+
+static void *stringsink_start(void *_sink, const void *hd, size_t size_hint) {
+ stringsink *sink = _sink;
+ sink->len = 0;
+ return sink;
+}
+
+static size_t stringsink_string(void *_sink, const void *hd, const char *ptr,
+ size_t len, const upb_bufhandle *handle) {
+ stringsink *sink = _sink;
+ size_t new_size = sink->size;
+
+ UPB_UNUSED(hd);
+ UPB_UNUSED(handle);
+
+ while (sink->len + len > new_size) {
+ new_size *= 2;
+ }
+
+ if (new_size != sink->size) {
+ sink->ptr = realloc(sink->ptr, new_size);
+ sink->size = new_size;
+ }
+
+ memcpy(sink->ptr + sink->len, ptr, len);
+ sink->len += len;
+
+ return len;
+}
+
+void stringsink_init(stringsink *sink) {
+ upb_byteshandler_init(&sink->handler);
+ upb_byteshandler_setstartstr(&sink->handler, stringsink_start, NULL);
+ upb_byteshandler_setstring(&sink->handler, stringsink_string, NULL);
+
+ upb_bytessink_reset(&sink->sink, &sink->handler, sink);
+
+ sink->size = 32;
+ sink->ptr = malloc(sink->size);
+ sink->len = 0;
+}
+
+void stringsink_uninit(stringsink *sink) {
+ free(sink->ptr);
+}
+
// -----------------------------------------------------------------------------
// Parsing.
// -----------------------------------------------------------------------------
@@ -280,11 +330,6 @@ rb_data_type_t MapParseFrame_type = {
{ MapParseFrame_mark, MapParseFrame_free, NULL },
};
-// Array of Ruby objects wrapping map_parse_frame_t.
-// We don't allow multiple concurrent decodes, so we assume that this global
-// variable is specific to the "current" decode.
-VALUE map_parse_frames;
-
static map_parse_frame_t* map_push_frame(VALUE map,
const map_handlerdata_t* handlerdata) {
map_parse_frame_t* frame = ALLOC(map_parse_frame_t);
@@ -293,16 +338,12 @@ static map_parse_frame_t* map_push_frame(VALUE map,
native_slot_init(handlerdata->key_field_type, &frame->key_storage);
native_slot_init(handlerdata->value_field_type, &frame->value_storage);
- rb_ary_push(map_parse_frames,
+ Map_set_frame(map,
TypedData_Wrap_Struct(rb_cObject, &MapParseFrame_type, frame));
return frame;
}
-static void map_pop_frame() {
- rb_ary_pop(map_parse_frames);
-}
-
// Handler to begin a map entry: allocates a temporary frame. This is the
// 'startsubmsg' handler on the msgdef that contains the map field.
static void *startmapentry_handler(void *closure, const void *hd) {
@@ -336,7 +377,7 @@ static bool endmap_handler(void *closure, const void *hd, upb_status* s) {
&frame->value_storage);
Map_index_set(frame->map, key, value);
- map_pop_frame();
+ Map_set_frame(frame->map, Qnil);
return true;
}
@@ -514,7 +555,7 @@ static void add_handlers_for_singular_field(upb_handlers *h,
case UPB_TYPE_INT64:
case UPB_TYPE_UINT64:
case UPB_TYPE_DOUBLE:
- upb_shim_set(h, f, offset, -1);
+ upb_msg_setscalarhandler(h, f, offset, -1);
break;
case UPB_TYPE_STRING:
case UPB_TYPE_BYTES: {
@@ -622,6 +663,20 @@ static void add_handlers_for_oneof_field(upb_handlers *h,
upb_handlerattr_uninit(&attr);
}
+static bool unknown_field_handler(void* closure, const void* hd,
+ const char* buf, size_t size) {
+ UPB_UNUSED(hd);
+
+ MessageHeader* msg = (MessageHeader*)closure;
+ if (msg->unknown_fields == NULL) {
+ msg->unknown_fields = malloc(sizeof(stringsink));
+ stringsink_init(msg->unknown_fields);
+ }
+
+ stringsink_string(msg->unknown_fields, NULL, buf, size, NULL);
+
+ return true;
+}
static void add_handlers_for_message(const void *closure, upb_handlers *h) {
const upb_msgdef* msgdef = upb_handlers_msgdef(h);
@@ -643,6 +698,9 @@ static void add_handlers_for_message(const void *closure, upb_handlers *h) {
desc->layout = create_layout(desc->msgdef);
}
+ upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
+ upb_handlers_setunknown(h, unknown_field_handler, &attr);
+
for (upb_msg_field_begin(&i, desc->msgdef);
!upb_msg_field_done(&i);
upb_msg_field_next(&i)) {
@@ -775,10 +833,6 @@ VALUE Message_decode(VALUE klass, VALUE data) {
msg_rb = rb_class_new_instance(0, NULL, msgklass);
TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
- // We generally expect this to be clear already, but clear it in case parsing
- // previously got interrupted somehow.
- rb_ary_clear(map_parse_frames);
-
{
const upb_pbdecodermethod* method = msgdef_decodermethod(desc);
const upb_handlers* h = upb_pbdecodermethod_desthandlers(method);
@@ -823,10 +877,6 @@ VALUE Message_decode_json(VALUE klass, VALUE data) {
msg_rb = rb_class_new_instance(0, NULL, msgklass);
TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
- // We generally expect this to be clear already, but clear it in case parsing
- // previously got interrupted somehow.
- rb_ary_clear(map_parse_frames);
-
{
const upb_json_parsermethod* method = msgdef_jsonparsermethod(desc);
stackenv se;
@@ -848,65 +898,6 @@ VALUE Message_decode_json(VALUE klass, VALUE data) {
// -----------------------------------------------------------------------------
// Serializing.
// -----------------------------------------------------------------------------
-//
-// The code below also comes from upb's prototype Ruby binding, developed by
-// haberman@.
-
-/* stringsink *****************************************************************/
-
-// This should probably be factored into a common upb component.
-
-typedef struct {
- upb_byteshandler handler;
- upb_bytessink sink;
- char *ptr;
- size_t len, size;
-} stringsink;
-
-static void *stringsink_start(void *_sink, const void *hd, size_t size_hint) {
- stringsink *sink = _sink;
- sink->len = 0;
- return sink;
-}
-
-static size_t stringsink_string(void *_sink, const void *hd, const char *ptr,
- size_t len, const upb_bufhandle *handle) {
- stringsink *sink = _sink;
- size_t new_size = sink->size;
-
- UPB_UNUSED(hd);
- UPB_UNUSED(handle);
-
- while (sink->len + len > new_size) {
- new_size *= 2;
- }
-
- if (new_size != sink->size) {
- sink->ptr = realloc(sink->ptr, new_size);
- sink->size = new_size;
- }
-
- memcpy(sink->ptr + sink->len, ptr, len);
- sink->len += len;
-
- return len;
-}
-
-void stringsink_init(stringsink *sink) {
- upb_byteshandler_init(&sink->handler);
- upb_byteshandler_setstartstr(&sink->handler, stringsink_start, NULL);
- upb_byteshandler_setstring(&sink->handler, stringsink_string, NULL);
-
- upb_bytessink_reset(&sink->sink, &sink->handler, sink);
-
- sink->size = 32;
- sink->ptr = malloc(sink->size);
- sink->len = 0;
-}
-
-void stringsink_uninit(stringsink *sink) {
- free(sink->ptr);
-}
/* msgvisitor *****************************************************************/
@@ -914,18 +905,14 @@ void stringsink_uninit(stringsink *sink) {
// semantics, which means that we have true field presence, we will want to
// modify msgvisitor so that it emits all present fields rather than all
// non-default-value fields.
-//
-// Likewise, when implementing JSON serialization, we may need to have a
-// 'verbose' mode that outputs all fields and a 'concise' mode that outputs only
-// those with non-default values.
static void putmsg(VALUE msg, const Descriptor* desc,
- upb_sink *sink, int depth);
+ upb_sink *sink, int depth, bool emit_defaults);
static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
upb_selector_t ret;
bool ok = upb_handlers_getselector(f, type, &ret);
- UPB_ASSERT_VAR(ok, ok);
+ UPB_ASSERT(ok);
return ret;
}
@@ -939,9 +926,9 @@ static void putstr(VALUE str, const upb_fielddef *f, upb_sink *sink) {
// We should be guaranteed that the string has the correct encoding because
// we ensured this at assignment time and then froze the string.
if (upb_fielddef_type(f) == UPB_TYPE_STRING) {
- assert(rb_enc_from_index(ENCODING_GET(value)) == kRubyStringUtf8Encoding);
+ assert(rb_enc_from_index(ENCODING_GET(str)) == kRubyStringUtf8Encoding);
} else {
- assert(rb_enc_from_index(ENCODING_GET(value)) == kRubyString8bitEncoding);
+ assert(rb_enc_from_index(ENCODING_GET(str)) == kRubyString8bitEncoding);
}
upb_sink_startstr(sink, getsel(f, UPB_HANDLER_STARTSTR), RSTRING_LEN(str),
@@ -952,7 +939,7 @@ static void putstr(VALUE str, const upb_fielddef *f, upb_sink *sink) {
}
static void putsubmsg(VALUE submsg, const upb_fielddef *f, upb_sink *sink,
- int depth) {
+ int depth, bool emit_defaults) {
upb_sink subsink;
VALUE descriptor;
Descriptor* subdesc;
@@ -963,12 +950,12 @@ static void putsubmsg(VALUE submsg, const upb_fielddef *f, upb_sink *sink,
subdesc = ruby_to_Descriptor(descriptor);
upb_sink_startsubmsg(sink, getsel(f, UPB_HANDLER_STARTSUBMSG), &subsink);
- putmsg(submsg, subdesc, &subsink, depth + 1);
+ putmsg(submsg, subdesc, &subsink, depth + 1, emit_defaults);
upb_sink_endsubmsg(sink, getsel(f, UPB_HANDLER_ENDSUBMSG));
}
static void putary(VALUE ary, const upb_fielddef *f, upb_sink *sink,
- int depth) {
+ int depth, bool emit_defaults) {
upb_sink subsink;
upb_fieldtype_t type = upb_fielddef_type(f);
upb_selector_t sel = 0;
@@ -1005,7 +992,7 @@ static void putary(VALUE ary, const upb_fielddef *f, upb_sink *sink,
putstr(*((VALUE *)memory), f, &subsink);
break;
case UPB_TYPE_MESSAGE:
- putsubmsg(*((VALUE *)memory), f, &subsink, depth);
+ putsubmsg(*((VALUE *)memory), f, &subsink, depth, emit_defaults);
break;
#undef T
@@ -1019,7 +1006,8 @@ static void put_ruby_value(VALUE value,
const upb_fielddef *f,
VALUE type_class,
int depth,
- upb_sink *sink) {
+ upb_sink *sink,
+ bool emit_defaults) {
upb_selector_t sel = 0;
if (upb_fielddef_isprimitive(f)) {
sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
@@ -1059,12 +1047,12 @@ static void put_ruby_value(VALUE value,
putstr(value, f, sink);
break;
case UPB_TYPE_MESSAGE:
- putsubmsg(value, f, sink, depth);
+ putsubmsg(value, f, sink, depth, emit_defaults);
}
}
static void putmap(VALUE map, const upb_fielddef *f, upb_sink *sink,
- int depth) {
+ int depth, bool emit_defaults) {
Map* self;
upb_sink subsink;
const upb_fielddef* key_field;
@@ -1090,9 +1078,9 @@ static void putmap(VALUE map, const upb_fielddef *f, upb_sink *sink,
&entry_sink);
upb_sink_startmsg(&entry_sink);
- put_ruby_value(key, key_field, Qnil, depth + 1, &entry_sink);
+ put_ruby_value(key, key_field, Qnil, depth + 1, &entry_sink, emit_defaults);
put_ruby_value(value, value_field, self->value_type_class, depth + 1,
- &entry_sink);
+ &entry_sink, emit_defaults);
upb_sink_endmsg(&entry_sink, &status);
upb_sink_endsubmsg(&subsink, getsel(f, UPB_HANDLER_ENDSUBMSG));
@@ -1102,7 +1090,7 @@ static void putmap(VALUE map, const upb_fielddef *f, upb_sink *sink,
}
static void putmsg(VALUE msg_rb, const Descriptor* desc,
- upb_sink *sink, int depth) {
+ upb_sink *sink, int depth, bool emit_defaults) {
MessageHeader* msg;
upb_msg_field_iter i;
upb_status status;
@@ -1144,31 +1132,31 @@ static void putmsg(VALUE msg_rb, const Descriptor* desc,
if (is_map_field(f)) {
VALUE map = DEREF(msg, offset, VALUE);
- if (map != Qnil) {
- putmap(map, f, sink, depth);
+ if (map != Qnil || emit_defaults) {
+ putmap(map, f, sink, depth, emit_defaults);
}
} else if (upb_fielddef_isseq(f)) {
VALUE ary = DEREF(msg, offset, VALUE);
if (ary != Qnil) {
- putary(ary, f, sink, depth);
+ putary(ary, f, sink, depth, emit_defaults);
}
} else if (upb_fielddef_isstring(f)) {
VALUE str = DEREF(msg, offset, VALUE);
- if (is_matching_oneof || RSTRING_LEN(str) > 0) {
+ if (is_matching_oneof || emit_defaults || RSTRING_LEN(str) > 0) {
putstr(str, f, sink);
}
} else if (upb_fielddef_issubmsg(f)) {
- putsubmsg(DEREF(msg, offset, VALUE), f, sink, depth);
+ putsubmsg(DEREF(msg, offset, VALUE), f, sink, depth, emit_defaults);
} else {
upb_selector_t sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
-#define T(upbtypeconst, upbtype, ctype, default_value) \
- case upbtypeconst: { \
- ctype value = DEREF(msg, offset, ctype); \
- if (is_matching_oneof || value != default_value) { \
- upb_sink_put##upbtype(sink, sel, value); \
- } \
- } \
+#define T(upbtypeconst, upbtype, ctype, default_value) \
+ case upbtypeconst: { \
+ ctype value = DEREF(msg, offset, ctype); \
+ if (is_matching_oneof || emit_defaults || value != default_value) { \
+ upb_sink_put##upbtype(sink, sel, value); \
+ } \
+ } \
break;
switch (upb_fielddef_type(f)) {
@@ -1191,6 +1179,11 @@ static void putmsg(VALUE msg_rb, const Descriptor* desc,
}
}
+ stringsink* unknown = msg->unknown_fields;
+ if (unknown != NULL) {
+ upb_sink_putunknown(sink, unknown->ptr, unknown->len);
+ }
+
upb_sink_endmsg(sink, &status);
}
@@ -1246,7 +1239,7 @@ VALUE Message_encode(VALUE klass, VALUE msg_rb) {
stackenv_init(&se, "Error occurred during encoding: %s");
encoder = upb_pb_encoder_create(&se.env, serialize_handlers, &sink.sink);
- putmsg(msg_rb, desc, upb_pb_encoder_input(encoder), 0);
+ putmsg(msg_rb, desc, upb_pb_encoder_input(encoder), 0, false);
ret = rb_str_new(sink.ptr, sink.len);
@@ -1268,6 +1261,7 @@ VALUE Message_encode_json(int argc, VALUE* argv, VALUE klass) {
Descriptor* desc = ruby_to_Descriptor(descriptor);
VALUE msg_rb;
VALUE preserve_proto_fieldnames = Qfalse;
+ VALUE emit_defaults = Qfalse;
stringsink sink;
if (argc < 1 || argc > 2) {
@@ -1283,6 +1277,9 @@ VALUE Message_encode_json(int argc, VALUE* argv, VALUE klass) {
}
preserve_proto_fieldnames = rb_hash_lookup2(
hash_args, ID2SYM(rb_intern("preserve_proto_fieldnames")), Qfalse);
+
+ emit_defaults = rb_hash_lookup2(
+ hash_args, ID2SYM(rb_intern("emit_defaults")), Qfalse);
}
stringsink_init(&sink);
@@ -1297,7 +1294,7 @@ VALUE Message_encode_json(int argc, VALUE* argv, VALUE klass) {
stackenv_init(&se, "Error occurred during encoding: %s");
printer = upb_json_printer_create(&se.env, serialize_handlers, &sink.sink);
- putmsg(msg_rb, desc, upb_json_printer_input(printer), 0);
+ putmsg(msg_rb, desc, upb_json_printer_input(printer), 0, RTEST(emit_defaults));
ret = rb_enc_str_new(sink.ptr, sink.len, rb_utf8_encoding());
diff --git a/ruby/ext/google/protobuf_c/extconf.rb b/ruby/ext/google/protobuf_c/extconf.rb
index b368dcc6..0886e607 100644
--- a/ruby/ext/google/protobuf_c/extconf.rb
+++ b/ruby/ext/google/protobuf_c/extconf.rb
@@ -4,7 +4,14 @@ require 'mkmf'
$CFLAGS += " -std=c99 -O3 -DNDEBUG"
+
+if RUBY_PLATFORM =~ /linux/
+ # Instruct the linker to point memcpy calls at our __wrap_memcpy wrapper.
+ $LDFLAGS += " -Wl,-wrap,memcpy"
+end
+
$objs = ["protobuf.o", "defs.o", "storage.o", "message.o",
- "repeated_field.o", "map.o", "encode_decode.o", "upb.o"]
+ "repeated_field.o", "map.o", "encode_decode.o", "upb.o",
+ "wrap_memcpy.o"]
create_makefile("google/protobuf_c")
diff --git a/ruby/ext/google/protobuf_c/map.c b/ruby/ext/google/protobuf_c/map.c
index 12f1f9dd..26e22dc7 100644
--- a/ruby/ext/google/protobuf_c/map.c
+++ b/ruby/ext/google/protobuf_c/map.c
@@ -146,6 +146,7 @@ void Map_mark(void* _self) {
Map* self = _self;
rb_gc_mark(self->value_type_class);
+ rb_gc_mark(self->parse_frame);
if (self->value_type == UPB_TYPE_STRING ||
self->value_type == UPB_TYPE_BYTES ||
@@ -174,6 +175,12 @@ VALUE Map_alloc(VALUE klass) {
return TypedData_Wrap_Struct(klass, &Map_type, self);
}
+VALUE Map_set_frame(VALUE map, VALUE val) {
+ Map* self = ruby_to_Map(map);
+ self->parse_frame = val;
+ return val;
+}
+
static bool needs_typeclass(upb_fieldtype_t type) {
switch (type) {
case UPB_TYPE_MESSAGE:
@@ -227,6 +234,7 @@ VALUE Map_init(int argc, VALUE* argv, VALUE _self) {
self->key_type = ruby_to_fieldtype(argv[0]);
self->value_type = ruby_to_fieldtype(argv[1]);
+ self->parse_frame = Qnil;
// Check that the key type is an allowed type.
switch (self->key_type) {
@@ -654,6 +662,35 @@ VALUE Map_hash(VALUE _self) {
/*
* call-seq:
+ * Map.to_h => {}
+ *
+ * Returns a Ruby Hash object containing all the values within the map
+ */
+VALUE Map_to_h(VALUE _self) {
+ Map* self = ruby_to_Map(_self);
+ VALUE hash = rb_hash_new();
+ upb_strtable_iter it;
+ for (upb_strtable_begin(&it, &self->table);
+ !upb_strtable_done(&it);
+ upb_strtable_next(&it)) {
+ VALUE key = table_key_to_ruby(
+ self, upb_strtable_iter_key(&it), upb_strtable_iter_keylength(&it));
+ upb_value v = upb_strtable_iter_value(&it);
+ void* mem = value_memory(&v);
+ VALUE value = native_slot_get(self->value_type,
+ self->value_type_class,
+ mem);
+
+ if (self->value_type == UPB_TYPE_MESSAGE) {
+ value = Message_to_h(value);
+ }
+ rb_hash_aset(hash, key, value);
+ }
+ return hash;
+}
+
+/*
+ * call-seq:
* Map.inspect => string
*
* Returns a string representing this map's elements. It will be formatted as
@@ -804,6 +841,8 @@ void Map_register(VALUE module) {
rb_define_method(klass, "dup", Map_dup, 0);
rb_define_method(klass, "==", Map_eq, 1);
rb_define_method(klass, "hash", Map_hash, 0);
+ rb_define_method(klass, "to_hash", Map_to_h, 0);
+ rb_define_method(klass, "to_h", Map_to_h, 0);
rb_define_method(klass, "inspect", Map_inspect, 0);
rb_define_method(klass, "merge", Map_merge, 1);
rb_include_module(klass, rb_mEnumerable);
diff --git a/ruby/ext/google/protobuf_c/message.c b/ruby/ext/google/protobuf_c/message.c
index 837a974b..bc73d48c 100644
--- a/ruby/ext/google/protobuf_c/message.c
+++ b/ruby/ext/google/protobuf_c/message.c
@@ -44,6 +44,11 @@ void Message_mark(void* _self) {
}
void Message_free(void* self) {
+ stringsink* unknown = ((MessageHeader *)self)->unknown_fields;
+ if (unknown != NULL) {
+ stringsink_uninit(unknown);
+ free(unknown);
+ }
xfree(self);
}
@@ -67,6 +72,8 @@ VALUE Message_alloc(VALUE klass) {
msg->descriptor = desc;
rb_ivar_set(ret, descriptor_instancevar_interned, descriptor);
+ msg->unknown_fields = NULL;
+
layout_init(desc->layout, Message_data(msg));
return ret;
@@ -217,20 +224,32 @@ VALUE Message_respond_to_missing(int argc, VALUE* argv, VALUE _self) {
return Qtrue;
}
+VALUE create_submsg_from_hash(const upb_fielddef *f, VALUE hash) {
+ const upb_def *d = upb_fielddef_subdef(f);
+ assert(d != NULL);
+
+ VALUE descriptor = get_def_obj(d);
+ VALUE msgclass = rb_funcall(descriptor, rb_intern("msgclass"), 0, NULL);
+
+ VALUE args[1] = { hash };
+ return rb_class_new_instance(1, args, msgclass);
+}
+
int Message_initialize_kwarg(VALUE key, VALUE val, VALUE _self) {
MessageHeader* self;
- VALUE method_str;
- char* name;
+ char *name;
const upb_fielddef* f;
TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
- if (!SYMBOL_P(key)) {
+ if (TYPE(key) == T_STRING) {
+ name = RSTRING_PTR(key);
+ } else if (TYPE(key) == T_SYMBOL) {
+ name = RSTRING_PTR(rb_id2str(SYM2ID(key)));
+ } else {
rb_raise(rb_eArgError,
- "Expected symbols as hash keys in initialization map.");
+ "Expected string or symbols as hash keys when initializing proto from hash.");
}
- method_str = rb_id2str(SYM2ID(key));
- name = RSTRING_PTR(method_str);
f = upb_msgdef_ntofz(self->descriptor->msgdef, name);
if (f == NULL) {
rb_raise(rb_eArgError,
@@ -255,9 +274,18 @@ int Message_initialize_kwarg(VALUE key, VALUE val, VALUE _self) {
}
ary = layout_get(self->descriptor->layout, Message_data(self), f);
for (int i = 0; i < RARRAY_LEN(val); i++) {
- RepeatedField_push(ary, rb_ary_entry(val, i));
+ VALUE entry = rb_ary_entry(val, i);
+ if (TYPE(entry) == T_HASH && upb_fielddef_issubmsg(f)) {
+ entry = create_submsg_from_hash(f, entry);
+ }
+
+ RepeatedField_push(ary, entry);
}
} else {
+ if (TYPE(val) == T_HASH && upb_fielddef_issubmsg(f)) {
+ val = create_submsg_from_hash(f, val);
+ }
+
layout_set(self->descriptor->layout, Message_data(self), f, val);
}
return 0;
@@ -394,7 +422,12 @@ VALUE Message_inspect(VALUE _self) {
return str;
}
-
+/*
+ * call-seq:
+ * Message.to_h => {}
+ *
+ * Returns the message as a Ruby Hash object, with keys as symbols.
+ */
VALUE Message_to_h(VALUE _self) {
MessageHeader* self;
VALUE hash;
@@ -410,8 +443,20 @@ VALUE Message_to_h(VALUE _self) {
VALUE msg_value = layout_get(self->descriptor->layout, Message_data(self),
field);
VALUE msg_key = ID2SYM(rb_intern(upb_fielddef_name(field)));
- if (upb_fielddef_label(field) == UPB_LABEL_REPEATED) {
+ if (upb_fielddef_ismap(field)) {
+ msg_value = Map_to_h(msg_value);
+ } else if (upb_fielddef_label(field) == UPB_LABEL_REPEATED) {
msg_value = RepeatedField_to_ary(msg_value);
+
+ if (upb_fielddef_type(field) == UPB_TYPE_MESSAGE) {
+ for (int i = 0; i < RARRAY_LEN(msg_value); i++) {
+ VALUE elem = rb_ary_entry(msg_value, i);
+ rb_ary_store(msg_value, i, Message_to_h(elem));
+ }
+ }
+ } else if (msg_value != Qnil &&
+ upb_fielddef_type(field) == UPB_TYPE_MESSAGE) {
+ msg_value = Message_to_h(msg_value);
}
rb_hash_aset(hash, msg_key, msg_value);
}
diff --git a/ruby/ext/google/protobuf_c/protobuf.c b/ruby/ext/google/protobuf_c/protobuf.c
index 98963667..c7750c44 100644
--- a/ruby/ext/google/protobuf_c/protobuf.c
+++ b/ruby/ext/google/protobuf_c/protobuf.c
@@ -110,8 +110,6 @@ void Init_protobuf_c() {
kRubyStringASCIIEncoding = rb_usascii_encoding();
kRubyString8bitEncoding = rb_ascii8bit_encoding();
- upb_def_to_ruby_obj_map = rb_hash_new();
rb_gc_register_address(&upb_def_to_ruby_obj_map);
- map_parse_frames = rb_ary_new();
- rb_gc_register_address(&map_parse_frames);
+ upb_def_to_ruby_obj_map = rb_hash_new();
}
diff --git a/ruby/ext/google/protobuf_c/protobuf.h b/ruby/ext/google/protobuf_c/protobuf.h
index d5ced567..1291ac59 100644
--- a/ruby/ext/google/protobuf_c/protobuf.h
+++ b/ruby/ext/google/protobuf_c/protobuf.h
@@ -116,10 +116,6 @@ struct Descriptor {
const upb_handlers* pb_serialize_handlers;
const upb_handlers* json_serialize_handlers;
const upb_handlers* json_serialize_handlers_preserve;
- // Handlers hold type class references for sub-message fields directly in some
- // cases. We need to keep these rooted because they might otherwise be
- // collected.
- VALUE typeclass_references;
};
struct FieldDescriptor {
@@ -166,8 +162,6 @@ extern VALUE cBuilder;
extern VALUE cError;
extern VALUE cParseError;
-extern VALUE map_parse_frames;
-
// We forward-declare all of the Ruby method implementations here because we
// sometimes call the methods directly across .c files, rather than going
// through Ruby's method dispatching (e.g. during message parse). It's cleaner
@@ -282,6 +276,7 @@ void Builder_free(void* _self);
VALUE Builder_alloc(VALUE klass);
void Builder_register(VALUE module);
Builder* ruby_to_Builder(VALUE value);
+VALUE Builder_initialize(VALUE _self);
VALUE Builder_add_message(VALUE _self, VALUE name);
VALUE Builder_add_enum(VALUE _self, VALUE name);
VALUE Builder_finalize_to_pool(VALUE _self, VALUE pool_rb);
@@ -397,6 +392,7 @@ typedef struct {
upb_fieldtype_t key_type;
upb_fieldtype_t value_type;
VALUE value_type_class;
+ VALUE parse_frame;
upb_strtable table;
} Map;
@@ -405,6 +401,7 @@ void Map_free(void* self);
VALUE Map_alloc(VALUE klass);
VALUE Map_init(int argc, VALUE* argv, VALUE self);
void Map_register(VALUE module);
+VALUE Map_set_frame(VALUE self, VALUE val);
extern const rb_data_type_t Map_type;
extern VALUE cMap;
@@ -424,6 +421,7 @@ VALUE Map_dup(VALUE _self);
VALUE Map_deep_copy(VALUE _self);
VALUE Map_eq(VALUE _self, VALUE _other);
VALUE Map_hash(VALUE _self);
+VALUE Map_to_h(VALUE _self);
VALUE Map_inspect(VALUE _self);
VALUE Map_merge(VALUE _self, VALUE hashmap);
VALUE Map_merge_into_self(VALUE _self, VALUE hashmap);
@@ -477,8 +475,20 @@ VALUE layout_inspect(MessageLayout* layout, void* storage);
// Message class creation.
// -----------------------------------------------------------------------------
+// This should probably be factored into a common upb component.
+
+typedef struct {
+ upb_byteshandler handler;
+ upb_bytessink sink;
+ char *ptr;
+ size_t len, size;
+} stringsink;
+
+void stringsink_uninit(stringsink *sink);
+
struct MessageHeader {
- Descriptor* descriptor; // kept alive by self.class.descriptor reference.
+ Descriptor* descriptor; // kept alive by self.class.descriptor reference.
+ stringsink* unknown_fields; // store unknown fields in decoding.
// Data comes after this.
};
@@ -496,6 +506,7 @@ VALUE Message_deep_copy(VALUE _self);
VALUE Message_eq(VALUE _self, VALUE _other);
VALUE Message_hash(VALUE _self);
VALUE Message_inspect(VALUE _self);
+VALUE Message_to_h(VALUE _self);
VALUE Message_index(VALUE _self, VALUE field_name);
VALUE Message_index_set(VALUE _self, VALUE field_name, VALUE value);
VALUE Message_descriptor(VALUE klass);
diff --git a/ruby/ext/google/protobuf_c/storage.c b/ruby/ext/google/protobuf_c/storage.c
index fa2e0257..1437c0b5 100644
--- a/ruby/ext/google/protobuf_c/storage.c
+++ b/ruby/ext/google/protobuf_c/storage.c
@@ -176,6 +176,15 @@ void native_slot_set_value_and_case(upb_fieldtype_t type, VALUE type_class,
break;
}
case UPB_TYPE_STRING:
+ if (CLASS_OF(value) == rb_cSymbol) {
+ value = rb_funcall(value, rb_intern("to_s"), 0, NULL);
+ } else if (CLASS_OF(value) != rb_cString) {
+ rb_raise(rb_eTypeError, "Invalid argument for string field.");
+ }
+
+ DEREF(memory, VALUE) = native_slot_encode_and_freeze_string(type, value);
+ break;
+
case UPB_TYPE_BYTES: {
if (CLASS_OF(value) != rb_cString) {
rb_raise(rb_eTypeError, "Invalid argument for string field.");
@@ -197,7 +206,9 @@ void native_slot_set_value_and_case(upb_fieldtype_t type, VALUE type_class,
}
case UPB_TYPE_ENUM: {
int32_t int_val = 0;
- if (!is_ruby_num(value) && TYPE(value) != T_SYMBOL) {
+ if (TYPE(value) == T_STRING) {
+ value = rb_funcall(value, rb_intern("to_sym"), 0, NULL);
+ } else if (!is_ruby_num(value) && TYPE(value) != T_SYMBOL) {
rb_raise(rb_eTypeError,
"Expected number or symbol type for enum field.");
}
diff --git a/ruby/ext/google/protobuf_c/upb.c b/ruby/ext/google/protobuf_c/upb.c
index 544ebc04..c02a5ce4 100644
--- a/ruby/ext/google/protobuf_c/upb.c
+++ b/ruby/ext/google/protobuf_c/upb.c
@@ -2,6 +2,585 @@
#include "upb.h"
+/* Maps descriptor type -> upb field type. */
+static const uint8_t upb_desctype_to_fieldtype[] = {
+ UPB_WIRE_TYPE_END_GROUP, /* ENDGROUP */
+ UPB_TYPE_DOUBLE, /* DOUBLE */
+ UPB_TYPE_FLOAT, /* FLOAT */
+ UPB_TYPE_INT64, /* INT64 */
+ UPB_TYPE_UINT64, /* UINT64 */
+ UPB_TYPE_INT32, /* INT32 */
+ UPB_TYPE_UINT64, /* FIXED64 */
+ UPB_TYPE_UINT32, /* FIXED32 */
+ UPB_TYPE_BOOL, /* BOOL */
+ UPB_TYPE_STRING, /* STRING */
+ UPB_TYPE_MESSAGE, /* GROUP */
+ UPB_TYPE_MESSAGE, /* MESSAGE */
+ UPB_TYPE_BYTES, /* BYTES */
+ UPB_TYPE_UINT32, /* UINT32 */
+ UPB_TYPE_ENUM, /* ENUM */
+ UPB_TYPE_INT32, /* SFIXED32 */
+ UPB_TYPE_INT64, /* SFIXED64 */
+ UPB_TYPE_INT32, /* SINT32 */
+ UPB_TYPE_INT64, /* SINT64 */
+};
+
+/* Data pertaining to the parse. */
+typedef struct {
+ upb_env *env;
+ /* Current decoding pointer. Points to the beginning of a field until we
+ * have finished decoding the whole field. */
+ const char *ptr;
+} upb_decstate;
+
+/* Data pertaining to a single message frame. */
+typedef struct {
+ const char *limit;
+ int32_t group_number; /* 0 if we are not parsing a group. */
+
+ /* These members are unset for an unknown group frame. */
+ char *msg;
+ const upb_msglayout_msginit_v1 *m;
+} upb_decframe;
+
+#define CHK(x) if (!(x)) { return false; }
+
+static bool upb_skip_unknowngroup(upb_decstate *d, int field_number,
+ const char *limit);
+static bool upb_decode_message(upb_decstate *d, const char *limit,
+ int group_number, char *msg,
+ const upb_msglayout_msginit_v1 *l);
+
+static bool upb_decode_varint(const char **ptr, const char *limit,
+ uint64_t *val) {
+ uint8_t byte;
+ int bitpos = 0;
+ const char *p = *ptr;
+ *val = 0;
+
+ do {
+ CHK(bitpos < 70 && p < limit);
+ byte = *p;
+ *val |= (uint64_t)(byte & 0x7F) << bitpos;
+ p++;
+ bitpos += 7;
+ } while (byte & 0x80);
+
+ *ptr = p;
+ return true;
+}
+
+static bool upb_decode_varint32(const char **ptr, const char *limit,
+ uint32_t *val) {
+ uint64_t u64;
+ CHK(upb_decode_varint(ptr, limit, &u64) && u64 <= UINT32_MAX);
+ *val = u64;
+ return true;
+}
+
+static bool upb_decode_64bit(const char **ptr, const char *limit,
+ uint64_t *val) {
+ CHK(limit - *ptr >= 8);
+ memcpy(val, *ptr, 8);
+ *ptr += 8;
+ return true;
+}
+
+static bool upb_decode_32bit(const char **ptr, const char *limit,
+ uint32_t *val) {
+ CHK(limit - *ptr >= 4);
+ memcpy(val, *ptr, 4);
+ *ptr += 4;
+ return true;
+}
+
+static bool upb_decode_tag(const char **ptr, const char *limit,
+ int *field_number, int *wire_type) {
+ uint32_t tag = 0;
+ CHK(upb_decode_varint32(ptr, limit, &tag));
+ *field_number = tag >> 3;
+ *wire_type = tag & 7;
+ return true;
+}
+
+static int32_t upb_zzdecode_32(uint32_t n) {
+ return (n >> 1) ^ -(int32_t)(n & 1);
+}
+
+static int64_t upb_zzdecode_64(uint64_t n) {
+ return (n >> 1) ^ -(int64_t)(n & 1);
+}
+
+static bool upb_decode_string(const char **ptr, const char *limit,
+ upb_stringview *val) {
+ uint32_t len;
+
+ CHK(upb_decode_varint32(ptr, limit, &len) &&
+ len < INT32_MAX &&
+ limit - *ptr >= (int32_t)len);
+
+ *val = upb_stringview_make(*ptr, len);
+ *ptr += len;
+ return true;
+}
+
+static void upb_set32(void *msg, size_t ofs, uint32_t val) {
+ memcpy((char*)msg + ofs, &val, sizeof(val));
+}
+
+static bool upb_append_unknown(upb_decstate *d, upb_decframe *frame,
+ const char *start) {
+ UPB_UNUSED(d);
+ UPB_UNUSED(frame);
+ UPB_UNUSED(start);
+ return true;
+}
+
+static bool upb_skip_unknownfielddata(upb_decstate *d, upb_decframe *frame,
+ int field_number, int wire_type) {
+ switch (wire_type) {
+ case UPB_WIRE_TYPE_VARINT: {
+ uint64_t val;
+ return upb_decode_varint(&d->ptr, frame->limit, &val);
+ }
+ case UPB_WIRE_TYPE_32BIT: {
+ uint32_t val;
+ return upb_decode_32bit(&d->ptr, frame->limit, &val);
+ }
+ case UPB_WIRE_TYPE_64BIT: {
+ uint64_t val;
+ return upb_decode_64bit(&d->ptr, frame->limit, &val);
+ }
+ case UPB_WIRE_TYPE_DELIMITED: {
+ upb_stringview val;
+ return upb_decode_string(&d->ptr, frame->limit, &val);
+ }
+ case UPB_WIRE_TYPE_START_GROUP:
+ return upb_skip_unknowngroup(d, field_number, frame->limit);
+ case UPB_WIRE_TYPE_END_GROUP:
+ CHK(field_number == frame->group_number);
+ frame->limit = d->ptr;
+ return true;
+ }
+ return false;
+}
+
+static bool upb_array_grow(upb_array *arr, size_t elements) {
+ size_t needed = arr->len + elements;
+ size_t new_size = UPB_MAX(arr->size, 8);
+ size_t new_bytes;
+ size_t old_bytes;
+ void *new_data;
+
+ while (new_size < needed) {
+ new_size *= 2;
+ }
+
+ old_bytes = arr->len * arr->element_size;
+ new_bytes = new_size * arr->element_size;
+ new_data = upb_realloc(arr->alloc, arr->data, old_bytes, new_bytes);
+ CHK(new_data);
+
+ arr->data = new_data;
+ arr->size = new_size;
+ return true;
+}
+
+static void *upb_array_reserve(upb_array *arr, size_t elements) {
+ if (arr->size - arr->len < elements) {
+ CHK(upb_array_grow(arr, elements));
+ }
+ return (char*)arr->data + (arr->len * arr->element_size);
+}
+
+static void *upb_array_add(upb_array *arr, size_t elements) {
+ void *ret = upb_array_reserve(arr, elements);
+ arr->len += elements;
+ return ret;
+}
+
+static upb_array *upb_getarr(upb_decframe *frame,
+ const upb_msglayout_fieldinit_v1 *field) {
+ UPB_ASSERT(field->label == UPB_LABEL_REPEATED);
+ return *(upb_array**)&frame->msg[field->offset];
+}
+
+static upb_array *upb_getorcreatearr(upb_decstate *d,
+ upb_decframe *frame,
+ const upb_msglayout_fieldinit_v1 *field) {
+ upb_array *arr = upb_getarr(frame, field);
+
+ if (!arr) {
+ arr = upb_env_malloc(d->env, sizeof(*arr));
+ if (!arr) {
+ return NULL;
+ }
+ upb_array_init(arr, upb_desctype_to_fieldtype[field->type],
+ upb_arena_alloc(upb_env_arena(d->env)));
+ *(upb_array**)&frame->msg[field->offset] = arr;
+ }
+
+ return arr;
+}
+
+static void upb_sethasbit(upb_decframe *frame,
+ const upb_msglayout_fieldinit_v1 *field) {
+ UPB_ASSERT(field->hasbit != UPB_NO_HASBIT);
+ frame->msg[field->hasbit / 8] |= (1 << (field->hasbit % 8));
+}
+
+static void upb_setoneofcase(upb_decframe *frame,
+ const upb_msglayout_fieldinit_v1 *field) {
+ UPB_ASSERT(field->oneof_index != UPB_NOT_IN_ONEOF);
+ upb_set32(frame->msg, frame->m->oneofs[field->oneof_index].case_offset,
+ field->number);
+}
+
+static char *upb_decode_prepareslot(upb_decstate *d,
+ upb_decframe *frame,
+ const upb_msglayout_fieldinit_v1 *field) {
+ char *field_mem = frame->msg + field->offset;
+ upb_array *arr;
+
+ if (field->label == UPB_LABEL_REPEATED) {
+ arr = upb_getorcreatearr(d, frame, field);
+ field_mem = upb_array_reserve(arr, 1);
+ }
+
+ return field_mem;
+}
+
+static void upb_decode_setpresent(upb_decframe *frame,
+ const upb_msglayout_fieldinit_v1 *field) {
+ if (field->label == UPB_LABEL_REPEATED) {
+ upb_array *arr = upb_getarr(frame, field);
+ UPB_ASSERT(arr->len < arr->size);
+ arr->len++;
+ } else if (field->oneof_index != UPB_NOT_IN_ONEOF) {
+ upb_setoneofcase(frame, field);
+ } else if (field->hasbit != UPB_NO_HASBIT) {
+ upb_sethasbit(frame, field);
+ }
+}
+
+static bool upb_decode_submsg(upb_decstate *d,
+ upb_decframe *frame,
+ const char *limit,
+ const upb_msglayout_fieldinit_v1 *field,
+ int group_number) {
+ char *submsg = *(void**)&frame->msg[field->offset];
+ const upb_msglayout_msginit_v1 *subm;
+
+ UPB_ASSERT(field->submsg_index != UPB_NO_SUBMSG);
+ subm = frame->m->submsgs[field->submsg_index];
+ UPB_ASSERT(subm);
+
+ if (!submsg) {
+ submsg = upb_env_malloc(d->env, upb_msg_sizeof((upb_msglayout *)subm));
+ CHK(submsg);
+ submsg = upb_msg_init(
+ submsg, (upb_msglayout*)subm, upb_arena_alloc(upb_env_arena(d->env)));
+ *(void**)&frame->msg[field->offset] = submsg;
+ }
+
+ upb_decode_message(d, limit, group_number, submsg, subm);
+
+ return true;
+}
+
+static bool upb_decode_varintfield(upb_decstate *d, upb_decframe *frame,
+ const char *field_start,
+ const upb_msglayout_fieldinit_v1 *field) {
+ uint64_t val;
+ void *field_mem;
+
+ field_mem = upb_decode_prepareslot(d, frame, field);
+ CHK(field_mem);
+ CHK(upb_decode_varint(&d->ptr, frame->limit, &val));
+
+ switch ((upb_descriptortype_t)field->type) {
+ case UPB_DESCRIPTOR_TYPE_INT64:
+ case UPB_DESCRIPTOR_TYPE_UINT64:
+ memcpy(field_mem, &val, sizeof(val));
+ break;
+ case UPB_DESCRIPTOR_TYPE_INT32:
+ case UPB_DESCRIPTOR_TYPE_UINT32:
+ case UPB_DESCRIPTOR_TYPE_ENUM: {
+ uint32_t val32 = val;
+ memcpy(field_mem, &val32, sizeof(val32));
+ break;
+ }
+ case UPB_DESCRIPTOR_TYPE_BOOL: {
+ bool valbool = val != 0;
+ memcpy(field_mem, &valbool, sizeof(valbool));
+ break;
+ }
+ case UPB_DESCRIPTOR_TYPE_SINT32: {
+ int32_t decoded = upb_zzdecode_32(val);
+ memcpy(field_mem, &decoded, sizeof(decoded));
+ break;
+ }
+ case UPB_DESCRIPTOR_TYPE_SINT64: {
+ int64_t decoded = upb_zzdecode_64(val);
+ memcpy(field_mem, &decoded, sizeof(decoded));
+ break;
+ }
+ default:
+ return upb_append_unknown(d, frame, field_start);
+ }
+
+ upb_decode_setpresent(frame, field);
+ return true;
+}
+
+static bool upb_decode_64bitfield(upb_decstate *d, upb_decframe *frame,
+ const char *field_start,
+ const upb_msglayout_fieldinit_v1 *field) {
+ void *field_mem;
+ uint64_t val;
+
+ field_mem = upb_decode_prepareslot(d, frame, field);
+ CHK(field_mem);
+ CHK(upb_decode_64bit(&d->ptr, frame->limit, &val));
+
+ switch ((upb_descriptortype_t)field->type) {
+ case UPB_DESCRIPTOR_TYPE_DOUBLE:
+ case UPB_DESCRIPTOR_TYPE_FIXED64:
+ case UPB_DESCRIPTOR_TYPE_SFIXED64:
+ memcpy(field_mem, &val, sizeof(val));
+ break;
+ default:
+ return upb_append_unknown(d, frame, field_start);
+ }
+
+ upb_decode_setpresent(frame, field);
+ return true;
+}
+
+static bool upb_decode_32bitfield(upb_decstate *d, upb_decframe *frame,
+ const char *field_start,
+ const upb_msglayout_fieldinit_v1 *field) {
+ void *field_mem;
+ uint32_t val;
+
+ field_mem = upb_decode_prepareslot(d, frame, field);
+ CHK(field_mem);
+ CHK(upb_decode_32bit(&d->ptr, frame->limit, &val));
+
+ switch ((upb_descriptortype_t)field->type) {
+ case UPB_DESCRIPTOR_TYPE_FLOAT:
+ case UPB_DESCRIPTOR_TYPE_FIXED32:
+ case UPB_DESCRIPTOR_TYPE_SFIXED32:
+ memcpy(field_mem, &val, sizeof(val));
+ break;
+ default:
+ return upb_append_unknown(d, frame, field_start);
+ }
+
+ upb_decode_setpresent(frame, field);
+ return true;
+}
+
+static bool upb_decode_fixedpacked(upb_array *arr, upb_stringview data,
+ int elem_size) {
+ int elements = data.size / elem_size;
+ void *field_mem;
+
+ CHK((size_t)(elements * elem_size) == data.size);
+ field_mem = upb_array_add(arr, elements);
+ CHK(field_mem);
+ memcpy(field_mem, data.data, data.size);
+ return true;
+}
+
+static bool upb_decode_toarray(upb_decstate *d, upb_decframe *frame,
+ const char *field_start,
+ const upb_msglayout_fieldinit_v1 *field,
+ upb_stringview val) {
+ upb_array *arr = upb_getorcreatearr(d, frame, field);
+
+#define VARINT_CASE(ctype, decode) { \
+ const char *ptr = val.data; \
+ const char *limit = ptr + val.size; \
+ while (ptr < limit) { \
+ uint64_t val; \
+ void *field_mem; \
+ ctype decoded; \
+ CHK(upb_decode_varint(&ptr, limit, &val)); \
+ decoded = (decode)(val); \
+ field_mem = upb_array_add(arr, 1); \
+ CHK(field_mem); \
+ memcpy(field_mem, &decoded, sizeof(ctype)); \
+ } \
+ return true; \
+}
+
+ switch ((upb_descriptortype_t)field->type) {
+ case UPB_DESCRIPTOR_TYPE_STRING:
+ case UPB_DESCRIPTOR_TYPE_BYTES: {
+ void *field_mem = upb_array_add(arr, 1);
+ CHK(field_mem);
+ memcpy(field_mem, &val, sizeof(val));
+ return true;
+ }
+ case UPB_DESCRIPTOR_TYPE_FLOAT:
+ case UPB_DESCRIPTOR_TYPE_FIXED32:
+ case UPB_DESCRIPTOR_TYPE_SFIXED32:
+ return upb_decode_fixedpacked(arr, val, sizeof(int32_t));
+ case UPB_DESCRIPTOR_TYPE_DOUBLE:
+ case UPB_DESCRIPTOR_TYPE_FIXED64:
+ case UPB_DESCRIPTOR_TYPE_SFIXED64:
+ return upb_decode_fixedpacked(arr, val, sizeof(int64_t));
+ case UPB_DESCRIPTOR_TYPE_INT32:
+ case UPB_DESCRIPTOR_TYPE_UINT32:
+ case UPB_DESCRIPTOR_TYPE_ENUM:
+ /* TODO: proto2 enum field that isn't in the enum. */
+ VARINT_CASE(uint32_t, uint32_t);
+ case UPB_DESCRIPTOR_TYPE_INT64:
+ case UPB_DESCRIPTOR_TYPE_UINT64:
+ VARINT_CASE(uint64_t, uint64_t);
+ case UPB_DESCRIPTOR_TYPE_BOOL:
+ VARINT_CASE(bool, bool);
+ case UPB_DESCRIPTOR_TYPE_SINT32:
+ VARINT_CASE(int32_t, upb_zzdecode_32);
+ case UPB_DESCRIPTOR_TYPE_SINT64:
+ VARINT_CASE(int64_t, upb_zzdecode_64);
+ case UPB_DESCRIPTOR_TYPE_MESSAGE:
+ CHK(val.size <= (size_t)(frame->limit - val.data));
+ return upb_decode_submsg(d, frame, val.data + val.size, field, 0);
+ case UPB_DESCRIPTOR_TYPE_GROUP:
+ return upb_append_unknown(d, frame, field_start);
+ }
+#undef VARINT_CASE
+ UPB_UNREACHABLE();
+}
+
+static bool upb_decode_delimitedfield(upb_decstate *d, upb_decframe *frame,
+ const char *field_start,
+ const upb_msglayout_fieldinit_v1 *field) {
+ upb_stringview val;
+
+ CHK(upb_decode_string(&d->ptr, frame->limit, &val));
+
+ if (field->label == UPB_LABEL_REPEATED) {
+ return upb_decode_toarray(d, frame, field_start, field, val);
+ } else {
+ switch ((upb_descriptortype_t)field->type) {
+ case UPB_DESCRIPTOR_TYPE_STRING:
+ case UPB_DESCRIPTOR_TYPE_BYTES: {
+ void *field_mem = upb_decode_prepareslot(d, frame, field);
+ CHK(field_mem);
+ memcpy(field_mem, &val, sizeof(val));
+ break;
+ }
+ case UPB_DESCRIPTOR_TYPE_MESSAGE:
+ CHK(val.size <= (size_t)(frame->limit - val.data));
+ CHK(upb_decode_submsg(d, frame, val.data + val.size, field, 0));
+ break;
+ default:
+ /* TODO(haberman): should we accept the last element of a packed? */
+ return upb_append_unknown(d, frame, field_start);
+ }
+ upb_decode_setpresent(frame, field);
+ return true;
+ }
+}
+
+static const upb_msglayout_fieldinit_v1 *upb_find_field(
+ const upb_msglayout_msginit_v1 *l, uint32_t field_number) {
+ /* Lots of optimization opportunities here. */
+ int i;
+ for (i = 0; i < l->field_count; i++) {
+ if (l->fields[i].number == field_number) {
+ return &l->fields[i];
+ }
+ }
+
+ return NULL; /* Unknown field. */
+}
+
+static bool upb_decode_field(upb_decstate *d, upb_decframe *frame) {
+ int field_number;
+ int wire_type;
+ const char *field_start = d->ptr;
+ const upb_msglayout_fieldinit_v1 *field;
+
+ CHK(upb_decode_tag(&d->ptr, frame->limit, &field_number, &wire_type));
+ field = upb_find_field(frame->m, field_number);
+
+ if (field) {
+ switch (wire_type) {
+ case UPB_WIRE_TYPE_VARINT:
+ return upb_decode_varintfield(d, frame, field_start, field);
+ case UPB_WIRE_TYPE_32BIT:
+ return upb_decode_32bitfield(d, frame, field_start, field);
+ case UPB_WIRE_TYPE_64BIT:
+ return upb_decode_64bitfield(d, frame, field_start, field);
+ case UPB_WIRE_TYPE_DELIMITED:
+ return upb_decode_delimitedfield(d, frame, field_start, field);
+ case UPB_WIRE_TYPE_START_GROUP:
+ CHK(field->type == UPB_DESCRIPTOR_TYPE_GROUP);
+ return upb_decode_submsg(d, frame, frame->limit, field, field_number);
+ case UPB_WIRE_TYPE_END_GROUP:
+ CHK(frame->group_number == field_number)
+ frame->limit = d->ptr;
+ return true;
+ default:
+ return false;
+ }
+ } else {
+ CHK(field_number != 0);
+ return upb_skip_unknownfielddata(d, frame, field_number, wire_type);
+ }
+}
+
+static bool upb_skip_unknowngroup(upb_decstate *d, int field_number,
+ const char *limit) {
+ upb_decframe frame;
+ frame.msg = NULL;
+ frame.m = NULL;
+ frame.group_number = field_number;
+ frame.limit = limit;
+
+ while (d->ptr < frame.limit) {
+ int wire_type;
+ int field_number;
+
+ CHK(upb_decode_tag(&d->ptr, frame.limit, &field_number, &wire_type));
+ CHK(upb_skip_unknownfielddata(d, &frame, field_number, wire_type));
+ }
+
+ return true;
+}
+
+static bool upb_decode_message(upb_decstate *d, const char *limit,
+ int group_number, char *msg,
+ const upb_msglayout_msginit_v1 *l) {
+ upb_decframe frame;
+ frame.group_number = group_number;
+ frame.limit = limit;
+ frame.msg = msg;
+ frame.m = l;
+
+ while (d->ptr < frame.limit) {
+ CHK(upb_decode_field(d, &frame));
+ }
+
+ return true;
+}
+
+bool upb_decode(upb_stringview buf, void *msg,
+ const upb_msglayout_msginit_v1 *l, upb_env *env) {
+ upb_decstate state;
+ state.ptr = buf.data;
+ state.env = env;
+
+ return upb_decode_message(&state, buf.data + buf.size, 0, msg, l);
+}
+
+#undef CHK
+
+
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
@@ -103,7 +682,7 @@ const char *upb_def_name(const upb_def *d) {
}
bool upb_def_setfullname(upb_def *def, const char *fullname, upb_status *s) {
- assert(!upb_def_isfrozen(def));
+ UPB_ASSERT(!upb_def_isfrozen(def));
if (!upb_isident(fullname, strlen(fullname), true, s)) {
return false;
}
@@ -121,21 +700,6 @@ bool upb_def_setfullname(upb_def *def, const char *fullname, upb_status *s) {
const upb_filedef *upb_def_file(const upb_def *d) { return d->file; }
-upb_def *upb_def_dup(const upb_def *def, const void *o) {
- switch (def->type) {
- case UPB_DEF_MSG:
- return upb_msgdef_upcast_mutable(
- upb_msgdef_dup(upb_downcast_msgdef(def), o));
- case UPB_DEF_FIELD:
- return upb_fielddef_upcast_mutable(
- upb_fielddef_dup(upb_downcast_fielddef(def), o));
- case UPB_DEF_ENUM:
- return upb_enumdef_upcast_mutable(
- upb_enumdef_dup(upb_downcast_enumdef(def), o));
- default: assert(false); return NULL;
- }
-}
-
static bool upb_def_init(upb_def *def, upb_deftype_t type,
const struct upb_refcounted_vtbl *vtbl,
const void *owner) {
@@ -203,14 +767,14 @@ static bool upb_validate_field(upb_fielddef *f, upb_status *s) {
bool has_default_number = upb_fielddef_enumhasdefaultint32(f);
/* Previously verified by upb_validate_enumdef(). */
- assert(upb_enumdef_numvals(upb_fielddef_enumsubdef(f)) > 0);
+ UPB_ASSERT(upb_enumdef_numvals(upb_fielddef_enumsubdef(f)) > 0);
/* We've already validated that we have an associated enumdef and that it
* has at least one member, so at least one of these should be true.
* Because if the user didn't set anything, we'll pick up the enum's
* default, but if the user *did* set something we should at least pick up
* the one they set (int32 or string). */
- assert(has_default_name || has_default_number);
+ UPB_ASSERT(has_default_name || has_default_number);
if (!has_default_name) {
upb_status_seterrf(s,
@@ -266,7 +830,7 @@ static bool upb_validate_enumdef(const upb_enumdef *e, upb_status *s) {
uint32_t field_rank(const upb_fielddef *f) {
uint32_t ret = upb_fielddef_number(f);
const uint32_t high_bit = 1 << 30;
- assert(ret < high_bit);
+ UPB_ASSERT(ret < high_bit);
if (!upb_fielddef_issubmsg(f))
ret |= high_bit;
return ret;
@@ -282,6 +846,7 @@ static bool assign_msg_indices(upb_msgdef *m, upb_status *s) {
/* Sort fields. upb internally relies on UPB_TYPE_MESSAGE fields having the
* lowest indexes, but we do not publicly guarantee this. */
upb_msg_field_iter j;
+ upb_msg_oneof_iter k;
int i;
uint32_t selector;
int n = upb_msgdef_numfields(m);
@@ -304,7 +869,7 @@ static bool assign_msg_indices(upb_msgdef *m, upb_status *s) {
!upb_msg_field_done(&j);
upb_msg_field_next(&j), i++) {
upb_fielddef *f = upb_msg_iter_field(&j);
- assert(f->msg.def == m);
+ UPB_ASSERT(f->msg.def == m);
if (!upb_validate_field(f, s)) {
upb_gfree(fields);
return false;
@@ -340,6 +905,7 @@ static bool assign_msg_indices(upb_msgdef *m, upb_status *s) {
v = upb_value_bool(true);
upb_inttable_insert(&t, UPB_STARTMSG_SELECTOR, v);
upb_inttable_insert(&t, UPB_ENDMSG_SELECTOR, v);
+ upb_inttable_insert(&t, UPB_UNKNOWN_SELECTOR, v);
for(upb_msg_field_begin(&j, m);
!upb_msg_field_done(&j);
upb_msg_field_next(&j)) {
@@ -366,6 +932,13 @@ static bool assign_msg_indices(upb_msgdef *m, upb_status *s) {
#undef TRY
#endif
+ for(upb_msg_oneof_begin(&k, m), i = 0;
+ !upb_msg_oneof_done(&k);
+ upb_msg_oneof_next(&k), i++) {
+ upb_oneofdef *o = upb_msg_iter_oneof(&k);
+ o->index = i;
+ }
+
upb_gfree(fields);
return true;
}
@@ -384,13 +957,14 @@ bool _upb_def_validate(upb_def *const*defs, size_t n, upb_status *s) {
} else if (def->type == UPB_DEF_FIELD) {
upb_status_seterrmsg(s, "standalone fielddefs can not be frozen");
goto err;
- } else if (def->type == UPB_DEF_ENUM) {
- if (!upb_validate_enumdef(upb_dyncast_enumdef(def), s)) {
- goto err;
- }
} else {
/* Set now to detect transitive closure in the second pass. */
def->came_from_user = true;
+
+ if (def->type == UPB_DEF_ENUM &&
+ !upb_validate_enumdef(upb_dyncast_enumdef(def), s)) {
+ goto err;
+ }
}
}
@@ -417,7 +991,7 @@ err:
upb_def *def = defs[i];
def->came_from_user = false;
}
- assert(!(s && upb_ok(s)));
+ UPB_ASSERT(!(s && upb_ok(s)));
return false;
}
@@ -438,7 +1012,16 @@ bool upb_def_freeze(upb_def *const* defs, size_t n, upb_status *s) {
/* upb_enumdef ****************************************************************/
-static void upb_enumdef_free(upb_refcounted *r) {
+static void visitenum(const upb_refcounted *r, upb_refcounted_visit *visit,
+ void *closure) {
+ const upb_enumdef *e = (const upb_enumdef*)r;
+ const upb_def *def = upb_enumdef_upcast(e);
+ if (upb_def_file(def)) {
+ visit(r, upb_filedef_upcast(upb_def_file(def)), closure);
+ }
+}
+
+static void freeenum(upb_refcounted *r) {
upb_enumdef *e = (upb_enumdef*)r;
upb_inttable_iter i;
upb_inttable_begin(&i, &e->iton);
@@ -452,7 +1035,7 @@ static void upb_enumdef_free(upb_refcounted *r) {
upb_gfree(e);
}
-const struct upb_refcounted_vtbl upb_enumdef_vtbl = {NULL, &upb_enumdef_free};
+const struct upb_refcounted_vtbl upb_enumdef_vtbl = {&visitenum, &freeenum};
upb_enumdef *upb_enumdef_new(const void *owner) {
upb_enumdef *e = upb_gmalloc(sizeof(*e));
@@ -474,21 +1057,6 @@ err2:
return NULL;
}
-upb_enumdef *upb_enumdef_dup(const upb_enumdef *e, const void *owner) {
- upb_enum_iter i;
- upb_enumdef *new_e = upb_enumdef_new(owner);
- if (!new_e) return NULL;
- for(upb_enum_begin(&i, e); !upb_enum_done(&i); upb_enum_next(&i)) {
- bool success = upb_enumdef_addval(
- new_e, upb_enum_iter_name(&i),upb_enum_iter_number(&i), NULL);
- if (!success) {
- upb_enumdef_unref(new_e, owner);
- return NULL;
- }
- }
- return new_e;
-}
-
bool upb_enumdef_freeze(upb_enumdef *e, upb_status *status) {
upb_def *d = upb_enumdef_upcast_mutable(e);
return upb_def_freeze(&d, 1, status);
@@ -536,19 +1104,19 @@ bool upb_enumdef_addval(upb_enumdef *e, const char *name, int32_t num,
if (upb_enumdef_numvals(e) == 1) {
bool ok = upb_enumdef_setdefault(e, num, NULL);
- UPB_ASSERT_VAR(ok, ok);
+ UPB_ASSERT(ok);
}
return true;
}
int32_t upb_enumdef_default(const upb_enumdef *e) {
- assert(upb_enumdef_iton(e, e->defaultval));
+ UPB_ASSERT(upb_enumdef_iton(e, e->defaultval));
return e->defaultval;
}
bool upb_enumdef_setdefault(upb_enumdef *e, int32_t val, upb_status *s) {
- assert(!upb_enumdef_isfrozen(e));
+ UPB_ASSERT(!upb_enumdef_isfrozen(e));
if (!upb_enumdef_iton(e, val)) {
upb_status_seterrf(s, "number '%d' is not in the enum.", val);
return false;
@@ -610,6 +1178,7 @@ const char *upb_fielddef_fullname(const upb_fielddef *e) {
static void visitfield(const upb_refcounted *r, upb_refcounted_visit *visit,
void *closure) {
const upb_fielddef *f = (const upb_fielddef*)r;
+ const upb_def *def = upb_fielddef_upcast(f);
if (upb_fielddef_containingtype(f)) {
visit(r, upb_msgdef_upcast2(upb_fielddef_containingtype(f)), closure);
}
@@ -619,6 +1188,9 @@ static void visitfield(const upb_refcounted *r, upb_refcounted_visit *visit,
if (upb_fielddef_subdef(f)) {
visit(r, upb_def_upcast(upb_fielddef_subdef(f)), closure);
}
+ if (upb_def_file(def)) {
+ visit(r, upb_filedef_upcast(upb_def_file(def)), closure);
+ }
}
static void freefield(upb_refcounted *r) {
@@ -632,7 +1204,7 @@ static void freefield(upb_refcounted *r) {
static const char *enumdefaultstr(const upb_fielddef *f) {
const upb_enumdef *e;
- assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
+ UPB_ASSERT(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
e = upb_fielddef_enumsubdef(f);
if (f->default_is_string && f->defaultval.bytes) {
/* Default was explicitly set as a string. */
@@ -649,7 +1221,7 @@ static const char *enumdefaultstr(const upb_fielddef *f) {
/* Default is completely unset; pull enumdef default. */
if (upb_enumdef_numvals(e) > 0) {
const char *name = upb_enumdef_iton(e, upb_enumdef_default(e));
- assert(name);
+ UPB_ASSERT(name);
return name;
}
}
@@ -659,7 +1231,7 @@ static const char *enumdefaultstr(const upb_fielddef *f) {
static bool enumdefaultint32(const upb_fielddef *f, int32_t *val) {
const upb_enumdef *e;
- assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
+ UPB_ASSERT(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
e = upb_fielddef_enumsubdef(f);
if (!f->default_is_string) {
/* Default was explicitly set as an integer. */
@@ -719,48 +1291,12 @@ upb_fielddef *upb_fielddef_new(const void *o) {
return f;
}
-upb_fielddef *upb_fielddef_dup(const upb_fielddef *f, const void *owner) {
- const char *srcname;
- upb_fielddef *newf = upb_fielddef_new(owner);
- if (!newf) return NULL;
- upb_fielddef_settype(newf, upb_fielddef_type(f));
- upb_fielddef_setlabel(newf, upb_fielddef_label(f));
- upb_fielddef_setnumber(newf, upb_fielddef_number(f), NULL);
- upb_fielddef_setname(newf, upb_fielddef_name(f), NULL);
- if (f->default_is_string && f->defaultval.bytes) {
- str_t *s = f->defaultval.bytes;
- upb_fielddef_setdefaultstr(newf, s->str, s->len, NULL);
- } else {
- newf->default_is_string = f->default_is_string;
- newf->defaultval = f->defaultval;
- }
-
- if (f->subdef_is_symbolic) {
- srcname = f->sub.name; /* Might be NULL. */
- } else {
- srcname = f->sub.def ? upb_def_fullname(f->sub.def) : NULL;
- }
- if (srcname) {
- char *newname = upb_gmalloc(strlen(f->sub.def->fullname) + 2);
- if (!newname) {
- upb_fielddef_unref(newf, owner);
- return NULL;
- }
- strcpy(newname, ".");
- strcat(newname, f->sub.def->fullname);
- upb_fielddef_setsubdefname(newf, newname, NULL);
- upb_gfree(newname);
- }
-
- return newf;
-}
-
bool upb_fielddef_typeisset(const upb_fielddef *f) {
return f->type_is_set_;
}
upb_fieldtype_t upb_fielddef_type(const upb_fielddef *f) {
- assert(f->type_is_set_);
+ UPB_ASSERT(f->type_is_set_);
return f->type_;
}
@@ -862,7 +1398,7 @@ static void release_containingtype(upb_fielddef *f) {
bool upb_fielddef_setcontainingtypename(upb_fielddef *f, const char *name,
upb_status *s) {
char *name_copy;
- assert(!upb_fielddef_isfrozen(f));
+ UPB_ASSERT(!upb_fielddef_isfrozen(f));
if (upb_fielddef_containingtype(f)) {
upb_status_seterrmsg(s, "field has already been added to a message.");
return false;
@@ -893,7 +1429,7 @@ bool upb_fielddef_setname(upb_fielddef *f, const char *name, upb_status *s) {
static void chkdefaulttype(const upb_fielddef *f, upb_fieldtype_t type) {
UPB_UNUSED(f);
UPB_UNUSED(type);
- assert(f->type_is_set_ && upb_fielddef_type(f) == type);
+ UPB_ASSERT(f->type_is_set_ && upb_fielddef_type(f) == type);
}
int64_t upb_fielddef_defaultint64(const upb_fielddef *f) {
@@ -905,7 +1441,7 @@ int32_t upb_fielddef_defaultint32(const upb_fielddef *f) {
if (f->type_is_set_ && upb_fielddef_type(f) == UPB_TYPE_ENUM) {
int32_t val;
bool ok = enumdefaultint32(f, &val);
- UPB_ASSERT_VAR(ok, ok);
+ UPB_ASSERT(ok);
return val;
} else {
chkdefaulttype(f, UPB_TYPE_INT32);
@@ -939,14 +1475,14 @@ double upb_fielddef_defaultdouble(const upb_fielddef *f) {
}
const char *upb_fielddef_defaultstr(const upb_fielddef *f, size_t *len) {
- assert(f->type_is_set_);
- assert(upb_fielddef_type(f) == UPB_TYPE_STRING ||
+ UPB_ASSERT(f->type_is_set_);
+ UPB_ASSERT(upb_fielddef_type(f) == UPB_TYPE_STRING ||
upb_fielddef_type(f) == UPB_TYPE_BYTES ||
upb_fielddef_type(f) == UPB_TYPE_ENUM);
if (upb_fielddef_type(f) == UPB_TYPE_ENUM) {
const char *ret = enumdefaultstr(f);
- assert(ret);
+ UPB_ASSERT(ret);
/* Enum defaults can't have embedded NULLs. */
if (len) *len = strlen(ret);
return ret;
@@ -1028,8 +1564,8 @@ bool upb_fielddef_setnumber(upb_fielddef *f, uint32_t number, upb_status *s) {
}
void upb_fielddef_settype(upb_fielddef *f, upb_fieldtype_t type) {
- assert(!upb_fielddef_isfrozen(f));
- assert(upb_fielddef_checktype(type));
+ UPB_ASSERT(!upb_fielddef_isfrozen(f));
+ UPB_ASSERT(upb_fielddef_checktype(type));
upb_fielddef_uninit_default(f);
f->type_ = type;
f->type_is_set_ = true;
@@ -1037,7 +1573,7 @@ void upb_fielddef_settype(upb_fielddef *f, upb_fieldtype_t type) {
}
void upb_fielddef_setdescriptortype(upb_fielddef *f, int type) {
- assert(!upb_fielddef_isfrozen(f));
+ UPB_ASSERT(!upb_fielddef_isfrozen(f));
switch (type) {
case UPB_DESCRIPTOR_TYPE_DOUBLE:
upb_fielddef_settype(f, UPB_TYPE_DOUBLE);
@@ -1079,7 +1615,7 @@ void upb_fielddef_setdescriptortype(upb_fielddef *f, int type) {
case UPB_DESCRIPTOR_TYPE_ENUM:
upb_fielddef_settype(f, UPB_TYPE_ENUM);
break;
- default: assert(false);
+ default: UPB_ASSERT(false);
}
if (type == UPB_DESCRIPTOR_TYPE_FIXED64 ||
@@ -1137,34 +1673,34 @@ upb_descriptortype_t upb_fielddef_descriptortype(const upb_fielddef *f) {
}
void upb_fielddef_setisextension(upb_fielddef *f, bool is_extension) {
- assert(!upb_fielddef_isfrozen(f));
+ UPB_ASSERT(!upb_fielddef_isfrozen(f));
f->is_extension_ = is_extension;
}
void upb_fielddef_setlazy(upb_fielddef *f, bool lazy) {
- assert(!upb_fielddef_isfrozen(f));
+ UPB_ASSERT(!upb_fielddef_isfrozen(f));
f->lazy_ = lazy;
}
void upb_fielddef_setpacked(upb_fielddef *f, bool packed) {
- assert(!upb_fielddef_isfrozen(f));
+ UPB_ASSERT(!upb_fielddef_isfrozen(f));
f->packed_ = packed;
}
void upb_fielddef_setlabel(upb_fielddef *f, upb_label_t label) {
- assert(!upb_fielddef_isfrozen(f));
- assert(upb_fielddef_checklabel(label));
+ UPB_ASSERT(!upb_fielddef_isfrozen(f));
+ UPB_ASSERT(upb_fielddef_checklabel(label));
f->label_ = label;
}
void upb_fielddef_setintfmt(upb_fielddef *f, upb_intfmt_t fmt) {
- assert(!upb_fielddef_isfrozen(f));
- assert(upb_fielddef_checkintfmt(fmt));
+ UPB_ASSERT(!upb_fielddef_isfrozen(f));
+ UPB_ASSERT(upb_fielddef_checkintfmt(fmt));
f->intfmt = fmt;
}
void upb_fielddef_settagdelim(upb_fielddef *f, bool tag_delim) {
- assert(!upb_fielddef_isfrozen(f));
+ UPB_ASSERT(!upb_fielddef_isfrozen(f));
f->tagdelim = tag_delim;
f->tagdelim = tag_delim;
}
@@ -1172,12 +1708,12 @@ void upb_fielddef_settagdelim(upb_fielddef *f, bool tag_delim) {
static bool checksetdefault(upb_fielddef *f, upb_fieldtype_t type) {
if (!f->type_is_set_ || upb_fielddef_isfrozen(f) ||
upb_fielddef_type(f) != type) {
- assert(false);
+ UPB_ASSERT(false);
return false;
}
if (f->default_is_string) {
str_t *s = f->defaultval.bytes;
- assert(s || type == UPB_TYPE_ENUM);
+ UPB_ASSERT(s || type == UPB_TYPE_ENUM);
if (s) freestr(s);
}
f->default_is_string = false;
@@ -1225,16 +1761,16 @@ void upb_fielddef_setdefaultdouble(upb_fielddef *f, double value) {
bool upb_fielddef_setdefaultstr(upb_fielddef *f, const void *str, size_t len,
upb_status *s) {
str_t *str2;
- assert(upb_fielddef_isstring(f) || f->type_ == UPB_TYPE_ENUM);
+ UPB_ASSERT(upb_fielddef_isstring(f) || f->type_ == UPB_TYPE_ENUM);
if (f->type_ == UPB_TYPE_ENUM && !upb_isident(str, len, false, s))
return false;
if (f->default_is_string) {
str_t *s = f->defaultval.bytes;
- assert(s || f->type_ == UPB_TYPE_ENUM);
+ UPB_ASSERT(s || f->type_ == UPB_TYPE_ENUM);
if (s) freestr(s);
} else {
- assert(f->type_ == UPB_TYPE_ENUM);
+ UPB_ASSERT(f->type_ == UPB_TYPE_ENUM);
}
str2 = newstr(str, len);
@@ -1245,18 +1781,18 @@ bool upb_fielddef_setdefaultstr(upb_fielddef *f, const void *str, size_t len,
void upb_fielddef_setdefaultcstr(upb_fielddef *f, const char *str,
upb_status *s) {
- assert(f->type_is_set_);
+ UPB_ASSERT(f->type_is_set_);
upb_fielddef_setdefaultstr(f, str, str ? strlen(str) : 0, s);
}
bool upb_fielddef_enumhasdefaultint32(const upb_fielddef *f) {
int32_t val;
- assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
+ UPB_ASSERT(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
return enumdefaultint32(f, &val);
}
bool upb_fielddef_enumhasdefaultstr(const upb_fielddef *f) {
- assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
+ UPB_ASSERT(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
return enumdefaultstr(f) != NULL;
}
@@ -1286,8 +1822,8 @@ static void release_subdef(upb_fielddef *f) {
bool upb_fielddef_setsubdef(upb_fielddef *f, const upb_def *subdef,
upb_status *s) {
- assert(!upb_fielddef_isfrozen(f));
- assert(upb_fielddef_hassubdef(f));
+ UPB_ASSERT(!upb_fielddef_isfrozen(f));
+ UPB_ASSERT(upb_fielddef_hassubdef(f));
if (subdef && !upb_subdef_typecheck(f, subdef, s)) return false;
release_subdef(f);
f->sub.def = subdef;
@@ -1309,7 +1845,7 @@ bool upb_fielddef_setenumsubdef(upb_fielddef *f, const upb_enumdef *subdef,
bool upb_fielddef_setsubdefname(upb_fielddef *f, const char *name,
upb_status *s) {
char *name_copy;
- assert(!upb_fielddef_isfrozen(f));
+ UPB_ASSERT(!upb_fielddef_isfrozen(f));
if (!upb_fielddef_hassubdef(f)) {
upb_status_seterrmsg(s, "field type does not accept a subdef");
return false;
@@ -1383,6 +1919,7 @@ static void visitmsg(const upb_refcounted *r, upb_refcounted_visit *visit,
void *closure) {
upb_msg_oneof_iter o;
const upb_msgdef *m = (const upb_msgdef*)r;
+ const upb_def *def = upb_msgdef_upcast(m);
upb_msg_field_iter i;
for(upb_msg_field_begin(&i, m);
!upb_msg_field_done(&i);
@@ -1396,6 +1933,9 @@ static void visitmsg(const upb_refcounted *r, upb_refcounted_visit *visit,
upb_oneofdef *f = upb_msg_iter_oneof(&o);
visit(r, upb_oneofdef_upcast(f), closure);
}
+ if (upb_def_file(def)) {
+ visit(r, upb_filedef_upcast(upb_def_file(def)), closure);
+ }
}
static void freemsg(upb_refcounted *r) {
@@ -1430,42 +1970,6 @@ err2:
return NULL;
}
-upb_msgdef *upb_msgdef_dup(const upb_msgdef *m, const void *owner) {
- bool ok;
- upb_msg_field_iter i;
- upb_msg_oneof_iter o;
-
- upb_msgdef *newm = upb_msgdef_new(owner);
- if (!newm) return NULL;
- ok = upb_def_setfullname(upb_msgdef_upcast_mutable(newm),
- upb_def_fullname(upb_msgdef_upcast(m)),
- NULL);
- newm->map_entry = m->map_entry;
- newm->syntax = m->syntax;
- UPB_ASSERT_VAR(ok, ok);
- for(upb_msg_field_begin(&i, m);
- !upb_msg_field_done(&i);
- upb_msg_field_next(&i)) {
- upb_fielddef *f = upb_fielddef_dup(upb_msg_iter_field(&i), &f);
- /* Fields in oneofs are dup'd below. */
- if (upb_fielddef_containingoneof(f)) continue;
- if (!f || !upb_msgdef_addfield(newm, f, &f, NULL)) {
- upb_msgdef_unref(newm, owner);
- return NULL;
- }
- }
- for(upb_msg_oneof_begin(&o, m);
- !upb_msg_oneof_done(&o);
- upb_msg_oneof_next(&o)) {
- upb_oneofdef *f = upb_oneofdef_dup(upb_msg_iter_oneof(&o), &f);
- if (!f || !upb_msgdef_addoneof(newm, f, &f, NULL)) {
- upb_msgdef_unref(newm, owner);
- return NULL;
- }
- }
- return newm;
-}
-
bool upb_msgdef_freeze(upb_msgdef *m, upb_status *status) {
upb_def *d = upb_msgdef_upcast_mutable(m);
return upb_def_freeze(&d, 1, status);
@@ -1544,6 +2048,7 @@ bool upb_msgdef_addfield(upb_msgdef *m, upb_fielddef *f, const void *ref_donor,
* This method is idempotent. Check if |f| is already part of this msgdef and
* return immediately if so. */
if (upb_fielddef_containingtype(f) == m) {
+ if (ref_donor) upb_fielddef_unref(f, ref_donor);
return true;
}
@@ -1643,7 +2148,7 @@ bool upb_msgdef_lookupname(const upb_msgdef *m, const char *name, size_t len,
*o = upb_trygetoneof(upb_value_getptr(val));
*f = upb_trygetfield(upb_value_getptr(val));
- assert((*o != NULL) ^ (*f != NULL)); /* Exactly one of the two should be set. */
+ UPB_ASSERT((*o != NULL) ^ (*f != NULL)); /* Exactly one of the two should be set. */
return true;
}
@@ -1658,7 +2163,7 @@ int upb_msgdef_numoneofs(const upb_msgdef *m) {
}
void upb_msgdef_setmapentry(upb_msgdef *m, bool map_entry) {
- assert(!upb_msgdef_isfrozen(m));
+ UPB_ASSERT(!upb_msgdef_isfrozen(m));
m->map_entry = map_entry;
}
@@ -1765,27 +2270,10 @@ err2:
return NULL;
}
-upb_oneofdef *upb_oneofdef_dup(const upb_oneofdef *o, const void *owner) {
- bool ok;
- upb_oneof_iter i;
- upb_oneofdef *newo = upb_oneofdef_new(owner);
- if (!newo) return NULL;
- ok = upb_oneofdef_setname(newo, upb_oneofdef_name(o), NULL);
- UPB_ASSERT_VAR(ok, ok);
- for (upb_oneof_begin(&i, o); !upb_oneof_done(&i); upb_oneof_next(&i)) {
- upb_fielddef *f = upb_fielddef_dup(upb_oneof_iter_field(&i), &f);
- if (!f || !upb_oneofdef_addfield(newo, f, &f, NULL)) {
- upb_oneofdef_unref(newo, owner);
- return NULL;
- }
- }
- return newo;
-}
-
const char *upb_oneofdef_name(const upb_oneofdef *o) { return o->name; }
bool upb_oneofdef_setname(upb_oneofdef *o, const char *name, upb_status *s) {
- assert(!upb_oneofdef_isfrozen(o));
+ UPB_ASSERT(!upb_oneofdef_isfrozen(o));
if (upb_oneofdef_containingtype(o)) {
upb_status_seterrmsg(s, "oneof already added to a message");
return false;
@@ -1814,11 +2302,15 @@ int upb_oneofdef_numfields(const upb_oneofdef *o) {
return upb_strtable_count(&o->ntof);
}
+uint32_t upb_oneofdef_index(const upb_oneofdef *o) {
+ return o->index;
+}
+
bool upb_oneofdef_addfield(upb_oneofdef *o, upb_fielddef *f,
const void *ref_donor,
upb_status *s) {
- assert(!upb_oneofdef_isfrozen(o));
- assert(!o->parent || !upb_msgdef_isfrozen(o->parent));
+ UPB_ASSERT(!upb_oneofdef_isfrozen(o));
+ UPB_ASSERT(!o->parent || !upb_msgdef_isfrozen(o->parent));
/* This method is idempotent. Check if |f| is already part of this oneofdef
* and return immediately if so. */
@@ -1946,6 +2438,8 @@ static void freefiledef(upb_refcounted *r) {
upb_inttable_uninit(&f->deps);
upb_gfree((void*)f->name);
upb_gfree((void*)f->package);
+ upb_gfree((void*)f->phpprefix);
+ upb_gfree((void*)f->phpnamespace);
upb_gfree(f);
}
@@ -1960,6 +2454,8 @@ upb_filedef *upb_filedef_new(const void *owner) {
f->package = NULL;
f->name = NULL;
+ f->phpprefix = NULL;
+ f->phpnamespace = NULL;
f->syntax = UPB_SYNTAX_PROTO2;
if (!upb_refcounted_init(upb_filedef_upcast_mutable(f), &upb_filedef_vtbl,
@@ -1994,6 +2490,14 @@ const char *upb_filedef_package(const upb_filedef *f) {
return f->package;
}
+const char *upb_filedef_phpprefix(const upb_filedef *f) {
+ return f->phpprefix;
+}
+
+const char *upb_filedef_phpnamespace(const upb_filedef *f) {
+ return f->phpnamespace;
+}
+
upb_syntax_t upb_filedef_syntax(const upb_filedef *f) {
return f->syntax;
}
@@ -2050,6 +2554,30 @@ bool upb_filedef_setpackage(upb_filedef *f, const char *package,
return true;
}
+bool upb_filedef_setphpprefix(upb_filedef *f, const char *phpprefix,
+ upb_status *s) {
+ phpprefix = upb_gstrdup(phpprefix);
+ if (!phpprefix) {
+ upb_upberr_setoom(s);
+ return false;
+ }
+ upb_gfree((void*)f->phpprefix);
+ f->phpprefix = phpprefix;
+ return true;
+}
+
+bool upb_filedef_setphpnamespace(upb_filedef *f, const char *phpnamespace,
+ upb_status *s) {
+ phpnamespace = upb_gstrdup(phpnamespace);
+ if (!phpnamespace) {
+ upb_upberr_setoom(s);
+ return false;
+ }
+ upb_gfree((void*)f->phpnamespace);
+ f->phpnamespace = phpnamespace;
+ return true;
+}
+
bool upb_filedef_setsyntax(upb_filedef *f, upb_syntax_t syntax,
upb_status *s) {
UPB_UNUSED(s);
@@ -2088,6 +2616,7 @@ bool upb_filedef_adddef(upb_filedef *f, upb_def *def, const void *ref_donor,
if (upb_inttable_push(&f->defs, upb_value_constptr(def))) {
def->file = f;
upb_ref2(def, f);
+ upb_ref2(f, def);
if (ref_donor) upb_def_unref(def, ref_donor);
if (def->type == UPB_DEF_MSG) {
upb_downcast_msgdef_mutable(def)->syntax = f->syntax;
@@ -2108,9 +2637,702 @@ bool upb_filedef_adddep(upb_filedef *f, const upb_filedef *dep) {
return false;
}
}
+
+void upb_symtab_free(upb_symtab *s) {
+ upb_strtable_iter i;
+ upb_strtable_begin(&i, &s->symtab);
+ for (; !upb_strtable_done(&i); upb_strtable_next(&i)) {
+ const upb_def *def = upb_value_getptr(upb_strtable_iter_value(&i));
+ upb_def_unref(def, s);
+ }
+ upb_strtable_uninit(&s->symtab);
+ upb_gfree(s);
+}
+
+upb_symtab *upb_symtab_new() {
+ upb_symtab *s = upb_gmalloc(sizeof(*s));
+ if (!s) {
+ return NULL;
+ }
+
+ upb_strtable_init(&s->symtab, UPB_CTYPE_PTR);
+ return s;
+}
+
+const upb_def *upb_symtab_lookup(const upb_symtab *s, const char *sym) {
+ upb_value v;
+ upb_def *ret = upb_strtable_lookup(&s->symtab, sym, &v) ?
+ upb_value_getptr(v) : NULL;
+ return ret;
+}
+
+const upb_msgdef *upb_symtab_lookupmsg(const upb_symtab *s, const char *sym) {
+ upb_value v;
+ upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
+ upb_value_getptr(v) : NULL;
+ return def ? upb_dyncast_msgdef(def) : NULL;
+}
+
+const upb_enumdef *upb_symtab_lookupenum(const upb_symtab *s, const char *sym) {
+ upb_value v;
+ upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
+ upb_value_getptr(v) : NULL;
+ return def ? upb_dyncast_enumdef(def) : NULL;
+}
+
+/* Given a symbol and the base symbol inside which it is defined, find the
+ * symbol's definition in t. */
+static upb_def *upb_resolvename(const upb_strtable *t,
+ const char *base, const char *sym) {
+ if(strlen(sym) == 0) return NULL;
+ if(sym[0] == '.') {
+ /* Symbols starting with '.' are absolute, so we do a single lookup.
+ * Slice to omit the leading '.' */
+ upb_value v;
+ return upb_strtable_lookup(t, sym + 1, &v) ? upb_value_getptr(v) : NULL;
+ } else {
+ /* Remove components from base until we find an entry or run out.
+ * TODO: This branch is totally broken, but currently not used. */
+ (void)base;
+ UPB_ASSERT(false);
+ return NULL;
+ }
+}
+
+const upb_def *upb_symtab_resolve(const upb_symtab *s, const char *base,
+ const char *sym) {
+ upb_def *ret = upb_resolvename(&s->symtab, base, sym);
+ return ret;
+}
+
+/* TODO(haberman): we need a lot more testing of error conditions. */
+static bool symtab_add(upb_symtab *s, upb_def *const*defs, size_t n,
+ void *ref_donor, upb_refcounted *freeze_also,
+ upb_status *status) {
+ size_t i;
+ size_t add_n;
+ size_t freeze_n;
+ upb_strtable_iter iter;
+ upb_refcounted **add_objs = NULL;
+ upb_def **add_defs = NULL;
+ size_t add_objs_size;
+ upb_strtable addtab;
+
+ if (n == 0 && !freeze_also) {
+ return true;
+ }
+
+ if (!upb_strtable_init(&addtab, UPB_CTYPE_PTR)) {
+ upb_status_seterrmsg(status, "out of memory");
+ return false;
+ }
+
+ /* Add new defs to our "add" set. */
+ for (i = 0; i < n; i++) {
+ upb_def *def = defs[i];
+ const char *fullname;
+ upb_fielddef *f;
+
+ if (upb_def_isfrozen(def)) {
+ upb_status_seterrmsg(status, "added defs must be mutable");
+ goto err;
+ }
+ UPB_ASSERT(!upb_def_isfrozen(def));
+ fullname = upb_def_fullname(def);
+ if (!fullname) {
+ upb_status_seterrmsg(
+ status, "Anonymous defs cannot be added to a symtab");
+ goto err;
+ }
+
+ f = upb_dyncast_fielddef_mutable(def);
+
+ if (f) {
+ if (!upb_fielddef_containingtypename(f)) {
+ upb_status_seterrmsg(status,
+ "Standalone fielddefs must have a containing type "
+ "(extendee) name set");
+ goto err;
+ }
+ } else {
+ if (upb_strtable_lookup(&addtab, fullname, NULL)) {
+ upb_status_seterrf(status, "Conflicting defs named '%s'", fullname);
+ goto err;
+ }
+ if (upb_strtable_lookup(&s->symtab, fullname, NULL)) {
+ upb_status_seterrf(status, "Symtab already has a def named '%s'",
+ fullname);
+ goto err;
+ }
+ if (!upb_strtable_insert(&addtab, fullname, upb_value_ptr(def)))
+ goto oom_err;
+ upb_def_donateref(def, ref_donor, s);
+ }
+
+ if (upb_dyncast_fielddef_mutable(def)) {
+ /* TODO(haberman): allow adding extensions attached to files. */
+ upb_status_seterrf(status, "Can't add extensions to symtab.\n");
+ goto err;
+ }
+ }
+
+ /* Now using the table, resolve symbolic references for subdefs. */
+ upb_strtable_begin(&iter, &addtab);
+ for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
+ const char *base;
+ upb_def *def = upb_value_getptr(upb_strtable_iter_value(&iter));
+ upb_msgdef *m = upb_dyncast_msgdef_mutable(def);
+ upb_msg_field_iter j;
+
+ if (!m) continue;
+ /* Type names are resolved relative to the message in which they appear. */
+ base = upb_msgdef_fullname(m);
+
+ for(upb_msg_field_begin(&j, m);
+ !upb_msg_field_done(&j);
+ upb_msg_field_next(&j)) {
+ upb_fielddef *f = upb_msg_iter_field(&j);
+ const char *name = upb_fielddef_subdefname(f);
+ if (name && !upb_fielddef_subdef(f)) {
+ /* Try the lookup in the current set of to-be-added defs first. If not
+ * there, try existing defs. */
+ upb_def *subdef = upb_resolvename(&addtab, base, name);
+ if (subdef == NULL) {
+ subdef = upb_resolvename(&s->symtab, base, name);
+ }
+ if (subdef == NULL) {
+ upb_status_seterrf(
+ status, "couldn't resolve name '%s' in message '%s'", name, base);
+ goto err;
+ } else if (!upb_fielddef_setsubdef(f, subdef, status)) {
+ goto err;
+ }
+ }
+ }
+ }
+
+ /* We need an array of the defs in addtab, for passing to
+ * upb_refcounted_freeze(). */
+ add_objs_size = upb_strtable_count(&addtab);
+ if (freeze_also) {
+ add_objs_size++;
+ }
+
+ add_defs = upb_gmalloc(sizeof(void*) * add_objs_size);
+ if (add_defs == NULL) goto oom_err;
+ upb_strtable_begin(&iter, &addtab);
+ for (add_n = 0; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
+ add_defs[add_n++] = upb_value_getptr(upb_strtable_iter_value(&iter));
+ }
+
+ /* Validate defs. */
+ if (!_upb_def_validate(add_defs, add_n, status)) {
+ goto err;
+ }
+
+ /* Cheat a little and give the array a new type.
+ * This is probably undefined behavior, but this code will be deleted soon. */
+ add_objs = (upb_refcounted**)add_defs;
+
+ freeze_n = add_n;
+ if (freeze_also) {
+ add_objs[freeze_n++] = freeze_also;
+ }
+
+ if (!upb_refcounted_freeze(add_objs, freeze_n, status,
+ UPB_MAX_MESSAGE_DEPTH * 2)) {
+ goto err;
+ }
+
+ /* This must be delayed until all errors have been detected, since error
+ * recovery code uses this table to cleanup defs. */
+ upb_strtable_uninit(&addtab);
+
+ /* TODO(haberman) we don't properly handle errors after this point (like
+ * OOM in upb_strtable_insert() below). */
+ for (i = 0; i < add_n; i++) {
+ upb_def *def = (upb_def*)add_objs[i];
+ const char *name = upb_def_fullname(def);
+ bool success;
+ success = upb_strtable_insert(&s->symtab, name, upb_value_ptr(def));
+ UPB_ASSERT(success);
+ }
+ upb_gfree(add_defs);
+ return true;
+
+oom_err:
+ upb_status_seterrmsg(status, "out of memory");
+err: {
+ /* We need to donate the refs back. */
+ upb_strtable_begin(&iter, &addtab);
+ for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
+ upb_def *def = upb_value_getptr(upb_strtable_iter_value(&iter));
+ upb_def_donateref(def, s, ref_donor);
+ }
+ }
+ upb_strtable_uninit(&addtab);
+ upb_gfree(add_defs);
+ UPB_ASSERT(!upb_ok(status));
+ return false;
+}
+
+bool upb_symtab_add(upb_symtab *s, upb_def *const*defs, size_t n,
+ void *ref_donor, upb_status *status) {
+ return symtab_add(s, defs, n, ref_donor, NULL, status);
+}
+
+bool upb_symtab_addfile(upb_symtab *s, upb_filedef *file, upb_status *status) {
+ size_t n;
+ size_t i;
+ upb_def **defs;
+ bool ret;
+
+ n = upb_filedef_defcount(file);
+ if (n == 0) {
+ return true;
+ }
+ defs = upb_gmalloc(sizeof(*defs) * n);
+
+ if (defs == NULL) {
+ upb_status_seterrmsg(status, "Out of memory");
+ return false;
+ }
+
+ for (i = 0; i < n; i++) {
+ defs[i] = upb_filedef_mutabledef(file, i);
+ }
+
+ ret = symtab_add(s, defs, n, NULL, upb_filedef_upcast_mutable(file), status);
+
+ upb_gfree(defs);
+ return ret;
+}
+
+/* Iteration. */
+
+static void advance_to_matching(upb_symtab_iter *iter) {
+ if (iter->type == UPB_DEF_ANY)
+ return;
+
+ while (!upb_strtable_done(&iter->iter) &&
+ iter->type != upb_symtab_iter_def(iter)->type) {
+ upb_strtable_next(&iter->iter);
+ }
+}
+
+void upb_symtab_begin(upb_symtab_iter *iter, const upb_symtab *s,
+ upb_deftype_t type) {
+ upb_strtable_begin(&iter->iter, &s->symtab);
+ iter->type = type;
+ advance_to_matching(iter);
+}
+
+void upb_symtab_next(upb_symtab_iter *iter) {
+ upb_strtable_next(&iter->iter);
+ advance_to_matching(iter);
+}
+
+bool upb_symtab_done(const upb_symtab_iter *iter) {
+ return upb_strtable_done(&iter->iter);
+}
+
+const upb_def *upb_symtab_iter_def(const upb_symtab_iter *iter) {
+ return upb_value_getptr(upb_strtable_iter_value(&iter->iter));
+}
+/* We encode backwards, to avoid pre-computing lengths (one-pass encode). */
+
+
+#define UPB_PB_VARINT_MAX_LEN 10
+#define CHK(x) do { if (!(x)) { return false; } } while(0)
+
+/* Maps descriptor type -> upb field type. */
+static const uint8_t upb_desctype_to_fieldtype2[] = {
+ UPB_WIRE_TYPE_END_GROUP, /* ENDGROUP */
+ UPB_TYPE_DOUBLE, /* DOUBLE */
+ UPB_TYPE_FLOAT, /* FLOAT */
+ UPB_TYPE_INT64, /* INT64 */
+ UPB_TYPE_UINT64, /* UINT64 */
+ UPB_TYPE_INT32, /* INT32 */
+ UPB_TYPE_UINT64, /* FIXED64 */
+ UPB_TYPE_UINT32, /* FIXED32 */
+ UPB_TYPE_BOOL, /* BOOL */
+ UPB_TYPE_STRING, /* STRING */
+ UPB_TYPE_MESSAGE, /* GROUP */
+ UPB_TYPE_MESSAGE, /* MESSAGE */
+ UPB_TYPE_BYTES, /* BYTES */
+ UPB_TYPE_UINT32, /* UINT32 */
+ UPB_TYPE_ENUM, /* ENUM */
+ UPB_TYPE_INT32, /* SFIXED32 */
+ UPB_TYPE_INT64, /* SFIXED64 */
+ UPB_TYPE_INT32, /* SINT32 */
+ UPB_TYPE_INT64, /* SINT64 */
+};
+
+static size_t upb_encode_varint(uint64_t val, char *buf) {
+ size_t i;
+ if (val < 128) { buf[0] = val; return 1; }
+ i = 0;
+ while (val) {
+ uint8_t byte = val & 0x7fU;
+ val >>= 7;
+ if (val) byte |= 0x80U;
+ buf[i++] = byte;
+ }
+ return i;
+}
+
+static uint32_t upb_zzencode_32(int32_t n) { return (n << 1) ^ (n >> 31); }
+static uint64_t upb_zzencode_64(int64_t n) { return (n << 1) ^ (n >> 63); }
+
+typedef struct {
+ upb_env *env;
+ char *buf, *ptr, *limit;
+} upb_encstate;
+
+static size_t upb_roundup_pow2(size_t bytes) {
+ size_t ret = 128;
+ while (ret < bytes) {
+ ret *= 2;
+ }
+ return ret;
+}
+
+static bool upb_encode_growbuffer(upb_encstate *e, size_t bytes) {
+ size_t old_size = e->limit - e->buf;
+ size_t new_size = upb_roundup_pow2(bytes + (e->limit - e->ptr));
+ char *new_buf = upb_env_realloc(e->env, e->buf, old_size, new_size);
+ CHK(new_buf);
+
+ /* We want previous data at the end, realloc() put it at the beginning. */
+ memmove(e->limit - old_size, e->buf, old_size);
+
+ e->ptr = new_buf + new_size - (e->limit - e->ptr);
+ e->limit = new_buf + new_size;
+ e->buf = new_buf;
+ return true;
+}
+
+/* Call to ensure that at least "bytes" bytes are available for writing at
+ * e->ptr. Returns false if the bytes could not be allocated. */
+static bool upb_encode_reserve(upb_encstate *e, size_t bytes) {
+ CHK(UPB_LIKELY((size_t)(e->ptr - e->buf) >= bytes) ||
+ upb_encode_growbuffer(e, bytes));
+
+ e->ptr -= bytes;
+ return true;
+}
+
+/* Writes the given bytes to the buffer, handling reserve/advance. */
+static bool upb_put_bytes(upb_encstate *e, const void *data, size_t len) {
+ CHK(upb_encode_reserve(e, len));
+ memcpy(e->ptr, data, len);
+ return true;
+}
+
+static bool upb_put_fixed64(upb_encstate *e, uint64_t val) {
+ /* TODO(haberman): byte-swap for big endian. */
+ return upb_put_bytes(e, &val, sizeof(uint64_t));
+}
+
+static bool upb_put_fixed32(upb_encstate *e, uint32_t val) {
+ /* TODO(haberman): byte-swap for big endian. */
+ return upb_put_bytes(e, &val, sizeof(uint32_t));
+}
+
+static bool upb_put_varint(upb_encstate *e, uint64_t val) {
+ size_t len;
+ char *start;
+ CHK(upb_encode_reserve(e, UPB_PB_VARINT_MAX_LEN));
+ len = upb_encode_varint(val, e->ptr);
+ start = e->ptr + UPB_PB_VARINT_MAX_LEN - len;
+ memmove(start, e->ptr, len);
+ e->ptr = start;
+ return true;
+}
+
+static bool upb_put_double(upb_encstate *e, double d) {
+ uint64_t u64;
+ UPB_ASSERT(sizeof(double) == sizeof(uint64_t));
+ memcpy(&u64, &d, sizeof(uint64_t));
+ return upb_put_fixed64(e, u64);
+}
+
+static bool upb_put_float(upb_encstate *e, float d) {
+ uint32_t u32;
+ UPB_ASSERT(sizeof(float) == sizeof(uint32_t));
+ memcpy(&u32, &d, sizeof(uint32_t));
+ return upb_put_fixed32(e, u32);
+}
+
+static uint32_t upb_readcase(const char *msg, const upb_msglayout_msginit_v1 *m,
+ int oneof_index) {
+ uint32_t ret;
+ memcpy(&ret, msg + m->oneofs[oneof_index].case_offset, sizeof(ret));
+ return ret;
+}
+
+static bool upb_readhasbit(const char *msg,
+ const upb_msglayout_fieldinit_v1 *f) {
+ UPB_ASSERT(f->hasbit != UPB_NO_HASBIT);
+ return msg[f->hasbit / 8] & (1 << (f->hasbit % 8));
+}
+
+static bool upb_put_tag(upb_encstate *e, int field_number, int wire_type) {
+ return upb_put_varint(e, (field_number << 3) | wire_type);
+}
+
+static bool upb_put_fixedarray(upb_encstate *e, const upb_array *arr,
+ size_t size) {
+ size_t bytes = arr->len * size;
+ return upb_put_bytes(e, arr->data, bytes) && upb_put_varint(e, bytes);
+}
+
+bool upb_encode_message(upb_encstate *e, const char *msg,
+ const upb_msglayout_msginit_v1 *m,
+ size_t *size);
+
+static bool upb_encode_array(upb_encstate *e, const char *field_mem,
+ const upb_msglayout_msginit_v1 *m,
+ const upb_msglayout_fieldinit_v1 *f) {
+ const upb_array *arr = *(const upb_array**)field_mem;
+
+ if (arr == NULL || arr->len == 0) {
+ return true;
+ }
+
+ UPB_ASSERT(arr->type == upb_desctype_to_fieldtype2[f->type]);
+
+#define VARINT_CASE(ctype, encode) { \
+ ctype *start = arr->data; \
+ ctype *ptr = start + arr->len; \
+ size_t pre_len = e->limit - e->ptr; \
+ do { \
+ ptr--; \
+ CHK(upb_put_varint(e, encode)); \
+ } while (ptr != start); \
+ CHK(upb_put_varint(e, e->limit - e->ptr - pre_len)); \
+} \
+break; \
+do { ; } while(0)
+
+ switch (f->type) {
+ case UPB_DESCRIPTOR_TYPE_DOUBLE:
+ CHK(upb_put_fixedarray(e, arr, sizeof(double)));
+ break;
+ case UPB_DESCRIPTOR_TYPE_FLOAT:
+ CHK(upb_put_fixedarray(e, arr, sizeof(float)));
+ break;
+ case UPB_DESCRIPTOR_TYPE_SFIXED64:
+ case UPB_DESCRIPTOR_TYPE_FIXED64:
+ CHK(upb_put_fixedarray(e, arr, sizeof(uint64_t)));
+ break;
+ case UPB_DESCRIPTOR_TYPE_FIXED32:
+ case UPB_DESCRIPTOR_TYPE_SFIXED32:
+ CHK(upb_put_fixedarray(e, arr, sizeof(uint32_t)));
+ break;
+ case UPB_DESCRIPTOR_TYPE_INT64:
+ case UPB_DESCRIPTOR_TYPE_UINT64:
+ VARINT_CASE(uint64_t, *ptr);
+ case UPB_DESCRIPTOR_TYPE_UINT32:
+ case UPB_DESCRIPTOR_TYPE_INT32:
+ case UPB_DESCRIPTOR_TYPE_ENUM:
+ VARINT_CASE(uint32_t, *ptr);
+ case UPB_DESCRIPTOR_TYPE_BOOL:
+ VARINT_CASE(bool, *ptr);
+ case UPB_DESCRIPTOR_TYPE_SINT32:
+ VARINT_CASE(int32_t, upb_zzencode_32(*ptr));
+ case UPB_DESCRIPTOR_TYPE_SINT64:
+ VARINT_CASE(int64_t, upb_zzencode_64(*ptr));
+ case UPB_DESCRIPTOR_TYPE_STRING:
+ case UPB_DESCRIPTOR_TYPE_BYTES: {
+ upb_stringview *start = arr->data;
+ upb_stringview *ptr = start + arr->len;
+ do {
+ ptr--;
+ CHK(upb_put_bytes(e, ptr->data, ptr->size) &&
+ upb_put_varint(e, ptr->size) &&
+ upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
+ } while (ptr != start);
+ return true;
+ }
+ case UPB_DESCRIPTOR_TYPE_GROUP: {
+ void **start = arr->data;
+ void **ptr = start + arr->len;
+ const upb_msglayout_msginit_v1 *subm = m->submsgs[f->submsg_index];
+ do {
+ size_t size;
+ ptr--;
+ CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_END_GROUP) &&
+ upb_encode_message(e, *ptr, subm, &size) &&
+ upb_put_tag(e, f->number, UPB_WIRE_TYPE_START_GROUP));
+ } while (ptr != start);
+ return true;
+ }
+ case UPB_DESCRIPTOR_TYPE_MESSAGE: {
+ void **start = arr->data;
+ void **ptr = start + arr->len;
+ const upb_msglayout_msginit_v1 *subm = m->submsgs[f->submsg_index];
+ do {
+ size_t size;
+ ptr--;
+ CHK(upb_encode_message(e, *ptr, subm, &size) &&
+ upb_put_varint(e, size) &&
+ upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
+ } while (ptr != start);
+ return true;
+ }
+ }
+#undef VARINT_CASE
+
+ /* We encode all primitive arrays as packed, regardless of what was specified
+ * in the .proto file. Could special case 1-sized arrays. */
+ CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
+ return true;
+}
+
+static bool upb_encode_scalarfield(upb_encstate *e, const char *field_mem,
+ const upb_msglayout_msginit_v1 *m,
+ const upb_msglayout_fieldinit_v1 *f,
+ bool is_proto3) {
+ bool skip_zero_value = is_proto3 && f->oneof_index == UPB_NOT_IN_ONEOF;
+
+#define CASE(ctype, type, wire_type, encodeval) do { \
+ ctype val = *(ctype*)field_mem; \
+ if (skip_zero_value && val == 0) { \
+ return true; \
+ } \
+ return upb_put_ ## type(e, encodeval) && \
+ upb_put_tag(e, f->number, wire_type); \
+} while(0)
+
+ switch (f->type) {
+ case UPB_DESCRIPTOR_TYPE_DOUBLE:
+ CASE(double, double, UPB_WIRE_TYPE_64BIT, val);
+ case UPB_DESCRIPTOR_TYPE_FLOAT:
+ CASE(float, float, UPB_WIRE_TYPE_32BIT, val);
+ case UPB_DESCRIPTOR_TYPE_INT64:
+ case UPB_DESCRIPTOR_TYPE_UINT64:
+ CASE(uint64_t, varint, UPB_WIRE_TYPE_VARINT, val);
+ case UPB_DESCRIPTOR_TYPE_UINT32:
+ case UPB_DESCRIPTOR_TYPE_INT32:
+ case UPB_DESCRIPTOR_TYPE_ENUM:
+ CASE(uint32_t, varint, UPB_WIRE_TYPE_VARINT, val);
+ case UPB_DESCRIPTOR_TYPE_SFIXED64:
+ case UPB_DESCRIPTOR_TYPE_FIXED64:
+ CASE(uint64_t, fixed64, UPB_WIRE_TYPE_64BIT, val);
+ case UPB_DESCRIPTOR_TYPE_FIXED32:
+ case UPB_DESCRIPTOR_TYPE_SFIXED32:
+ CASE(uint32_t, fixed32, UPB_WIRE_TYPE_32BIT, val);
+ case UPB_DESCRIPTOR_TYPE_BOOL:
+ CASE(bool, varint, UPB_WIRE_TYPE_VARINT, val);
+ case UPB_DESCRIPTOR_TYPE_SINT32:
+ CASE(int32_t, varint, UPB_WIRE_TYPE_VARINT, upb_zzencode_32(val));
+ case UPB_DESCRIPTOR_TYPE_SINT64:
+ CASE(int64_t, varint, UPB_WIRE_TYPE_VARINT, upb_zzencode_64(val));
+ case UPB_DESCRIPTOR_TYPE_STRING:
+ case UPB_DESCRIPTOR_TYPE_BYTES: {
+ upb_stringview view = *(upb_stringview*)field_mem;
+ if (skip_zero_value && view.size == 0) {
+ return true;
+ }
+ return upb_put_bytes(e, view.data, view.size) &&
+ upb_put_varint(e, view.size) &&
+ upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED);
+ }
+ case UPB_DESCRIPTOR_TYPE_GROUP: {
+ size_t size;
+ void *submsg = *(void**)field_mem;
+ const upb_msglayout_msginit_v1 *subm = m->submsgs[f->submsg_index];
+ if (skip_zero_value && submsg == NULL) {
+ return true;
+ }
+ return upb_put_tag(e, f->number, UPB_WIRE_TYPE_END_GROUP) &&
+ upb_encode_message(e, submsg, subm, &size) &&
+ upb_put_tag(e, f->number, UPB_WIRE_TYPE_START_GROUP);
+ }
+ case UPB_DESCRIPTOR_TYPE_MESSAGE: {
+ size_t size;
+ void *submsg = *(void**)field_mem;
+ const upb_msglayout_msginit_v1 *subm = m->submsgs[f->submsg_index];
+ if (skip_zero_value && submsg == NULL) {
+ return true;
+ }
+ return upb_encode_message(e, submsg, subm, &size) &&
+ upb_put_varint(e, size) &&
+ upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED);
+ }
+ }
+#undef CASE
+ UPB_UNREACHABLE();
+}
+
+bool upb_encode_hasscalarfield(const char *msg,
+ const upb_msglayout_msginit_v1 *m,
+ const upb_msglayout_fieldinit_v1 *f) {
+ if (f->oneof_index != UPB_NOT_IN_ONEOF) {
+ return upb_readcase(msg, m, f->oneof_index) == f->number;
+ } else if (m->is_proto2) {
+ return upb_readhasbit(msg, f);
+ } else {
+ /* For proto3, we'll test for the field being empty later. */
+ return true;
+ }
+}
+
+bool upb_encode_message(upb_encstate* e, const char *msg,
+ const upb_msglayout_msginit_v1 *m,
+ size_t *size) {
+ int i;
+ char *buf_end = e->ptr;
+
+ if (msg == NULL) {
+ return true;
+ }
+
+ for (i = m->field_count - 1; i >= 0; i--) {
+ const upb_msglayout_fieldinit_v1 *f = &m->fields[i];
+
+ if (f->label == UPB_LABEL_REPEATED) {
+ CHK(upb_encode_array(e, msg + f->offset, m, f));
+ } else {
+ if (upb_encode_hasscalarfield(msg, m, f)) {
+ CHK(upb_encode_scalarfield(e, msg + f->offset, m, f, !m->is_proto2));
+ }
+ }
+ }
+
+ *size = buf_end - e->ptr;
+ return true;
+}
+
+char *upb_encode(const void *msg, const upb_msglayout_msginit_v1 *m,
+ upb_env *env, size_t *size) {
+ upb_encstate e;
+ e.env = env;
+ e.buf = NULL;
+ e.limit = NULL;
+ e.ptr = NULL;
+
+ if (!upb_encode_message(&e, msg, m, size)) {
+ *size = 0;
+ return NULL;
+ }
+
+ *size = e.limit - e.ptr;
+
+ if (*size == 0) {
+ static char ch;
+ return &ch;
+ } else {
+ UPB_ASSERT(e.ptr);
+ return e.ptr;
+ }
+}
+
+#undef CHK
/*
** TODO(haberman): it's unclear whether a lot of the consistency checks should
-** assert() or return false.
+** UPB_ASSERT() or return false.
*/
@@ -2220,7 +3442,7 @@ oom:
static int32_t trygetsel(upb_handlers *h, const upb_fielddef *f,
upb_handlertype_t type) {
upb_selector_t sel;
- assert(!upb_handlers_isfrozen(h));
+ UPB_ASSERT(!upb_handlers_isfrozen(h));
if (upb_handlers_msgdef(h) != upb_fielddef_containingtype(f)) {
upb_status_seterrf(
&h->status_, "type mismatch: field %s does not belong to message %s",
@@ -2240,7 +3462,7 @@ static int32_t trygetsel(upb_handlers *h, const upb_fielddef *f,
static upb_selector_t handlers_getsel(upb_handlers *h, const upb_fielddef *f,
upb_handlertype_t type) {
int32_t sel = trygetsel(h, f, type);
- assert(sel >= 0);
+ UPB_ASSERT(sel >= 0);
return sel;
}
@@ -2256,7 +3478,7 @@ static bool doset(upb_handlers *h, int32_t sel, const upb_fielddef *f,
const void *closure_type;
const void **context_closure_type;
- assert(!upb_handlers_isfrozen(h));
+ UPB_ASSERT(!upb_handlers_isfrozen(h));
if (sel < 0) {
upb_status_seterrmsg(&h->status_,
@@ -2336,7 +3558,7 @@ const void *effective_closure_type(upb_handlers *h, const upb_fielddef *f,
const void *ret;
upb_selector_t sel;
- assert(type != UPB_HANDLER_STRING);
+ UPB_ASSERT(type != UPB_HANDLER_STRING);
ret = h->top_closure_type;
if (upb_fielddef_isseq(f) &&
@@ -2391,7 +3613,7 @@ upb_handlers *upb_handlers_new(const upb_msgdef *md, const void *owner) {
int extra;
upb_handlers *h;
- assert(upb_msgdef_isfrozen(md));
+ UPB_ASSERT(upb_msgdef_isfrozen(md));
extra = sizeof(upb_handlers_tabent) * (md->selector_count - 1);
h = upb_calloc(sizeof(*h) + extra);
@@ -2440,18 +3662,18 @@ const upb_handlers *upb_handlers_newfrozen(const upb_msgdef *m,
r = upb_handlers_upcast_mutable(ret);
ok = upb_refcounted_freeze(&r, 1, NULL, UPB_MAX_HANDLER_DEPTH);
- UPB_ASSERT_VAR(ok, ok);
+ UPB_ASSERT(ok);
return ret;
}
const upb_status *upb_handlers_status(upb_handlers *h) {
- assert(!upb_handlers_isfrozen(h));
+ UPB_ASSERT(!upb_handlers_isfrozen(h));
return &h->status_;
}
void upb_handlers_clearerr(upb_handlers *h) {
- assert(!upb_handlers_isfrozen(h));
+ UPB_ASSERT(!upb_handlers_isfrozen(h));
upb_status_clear(&h->status_);
}
@@ -2479,6 +3701,12 @@ SETTER(endseq, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSEQ)
#undef SETTER
+bool upb_handlers_setunknown(upb_handlers *h, upb_unknown_handlerfunc *func,
+ upb_handlerattr *attr) {
+ return doset(h, UPB_UNKNOWN_SELECTOR, NULL, UPB_HANDLER_INT32,
+ (upb_func *)func, attr);
+}
+
bool upb_handlers_setstartmsg(upb_handlers *h, upb_startmsg_handlerfunc *func,
upb_handlerattr *attr) {
return doset(h, UPB_STARTMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
@@ -2487,16 +3715,16 @@ bool upb_handlers_setstartmsg(upb_handlers *h, upb_startmsg_handlerfunc *func,
bool upb_handlers_setendmsg(upb_handlers *h, upb_endmsg_handlerfunc *func,
upb_handlerattr *attr) {
- assert(!upb_handlers_isfrozen(h));
+ UPB_ASSERT(!upb_handlers_isfrozen(h));
return doset(h, UPB_ENDMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
(upb_func *)func, attr);
}
bool upb_handlers_setsubhandlers(upb_handlers *h, const upb_fielddef *f,
const upb_handlers *sub) {
- assert(sub);
- assert(!upb_handlers_isfrozen(h));
- assert(upb_fielddef_issubmsg(f));
+ UPB_ASSERT(sub);
+ UPB_ASSERT(!upb_handlers_isfrozen(h));
+ UPB_ASSERT(upb_fielddef_issubmsg(f));
if (SUBH_F(h, f)) return false; /* Can't reset. */
if (upb_msgdef_upcast(upb_handlers_msgdef(sub)) != upb_fielddef_subdef(f)) {
return false;
@@ -2508,7 +3736,7 @@ bool upb_handlers_setsubhandlers(upb_handlers *h, const upb_fielddef *f,
const upb_handlers *upb_handlers_getsubhandlers(const upb_handlers *h,
const upb_fielddef *f) {
- assert(upb_fielddef_issubmsg(f));
+ UPB_ASSERT(upb_fielddef_issubmsg(f));
return SUBH_F(h, f);
}
@@ -2534,7 +3762,7 @@ bool upb_handlers_addcleanup(upb_handlers *h, void *p, upb_handlerfree *func) {
return false;
}
ok = upb_inttable_insertptr(&h->cleanup_, p, upb_value_fptr(func));
- UPB_ASSERT_VAR(ok, ok);
+ UPB_ASSERT(ok);
return true;
}
@@ -2635,7 +3863,7 @@ upb_handlertype_t upb_handlers_getprimitivehandlertype(const upb_fielddef *f) {
case UPB_TYPE_FLOAT: return UPB_HANDLER_FLOAT;
case UPB_TYPE_DOUBLE: return UPB_HANDLER_DOUBLE;
case UPB_TYPE_BOOL: return UPB_HANDLER_BOOL;
- default: assert(false); return -1; /* Invalid input. */
+ default: UPB_ASSERT(false); return -1; /* Invalid input. */
}
}
@@ -2698,7 +3926,7 @@ bool upb_handlers_getselector(const upb_fielddef *f, upb_handlertype_t type,
*s = f->selector_base;
break;
}
- assert((size_t)*s < upb_fielddef_containingtype(f)->selector_count);
+ UPB_ASSERT((size_t)*s < upb_fielddef_containingtype(f)->selector_count);
return true;
}
@@ -2803,6 +4031,1191 @@ bool upb_byteshandler_setendstr(upb_byteshandler *h,
h->table[UPB_ENDSTR_SELECTOR].attr.handler_data_ = d;
return true;
}
+
+
+static bool is_power_of_two(size_t val) {
+ return (val & (val - 1)) == 0;
+}
+
+/* Align up to the given power of 2. */
+static size_t align_up(size_t val, size_t align) {
+ UPB_ASSERT(is_power_of_two(align));
+ return (val + align - 1) & ~(align - 1);
+}
+
+static size_t div_round_up(size_t n, size_t d) {
+ return (n + d - 1) / d;
+}
+
+bool upb_fieldtype_mapkeyok(upb_fieldtype_t type) {
+ return type == UPB_TYPE_BOOL || type == UPB_TYPE_INT32 ||
+ type == UPB_TYPE_UINT32 || type == UPB_TYPE_INT64 ||
+ type == UPB_TYPE_UINT64 || type == UPB_TYPE_STRING;
+}
+
+void *upb_array_pack(const upb_array *arr, void *p, size_t *ofs, size_t size);
+void *upb_map_pack(const upb_map *map, void *p, size_t *ofs, size_t size);
+
+#define PTR_AT(msg, ofs, type) (type*)((char*)msg + ofs)
+#define VOIDPTR_AT(msg, ofs) PTR_AT(msg, ofs, void)
+#define ENCODE_MAX_NESTING 64
+#define CHECK_TRUE(x) if (!(x)) { return false; }
+
+/** upb_msgval ****************************************************************/
+
+#define upb_alignof(t) offsetof(struct { char c; t x; }, x)
+
+/* These functions will generate real memcpy() calls on ARM sadly, because
+ * the compiler assumes they might not be aligned. */
+
+static upb_msgval upb_msgval_read(const void *p, size_t ofs,
+ uint8_t size) {
+ upb_msgval val;
+ p = (char*)p + ofs;
+ memcpy(&val, p, size);
+ return val;
+}
+
+static void upb_msgval_write(void *p, size_t ofs, upb_msgval val,
+ uint8_t size) {
+ p = (char*)p + ofs;
+ memcpy(p, &val, size);
+}
+
+static size_t upb_msgval_sizeof(upb_fieldtype_t type) {
+ switch (type) {
+ case UPB_TYPE_DOUBLE:
+ case UPB_TYPE_INT64:
+ case UPB_TYPE_UINT64:
+ return 8;
+ case UPB_TYPE_ENUM:
+ case UPB_TYPE_INT32:
+ case UPB_TYPE_UINT32:
+ case UPB_TYPE_FLOAT:
+ return 4;
+ case UPB_TYPE_BOOL:
+ return 1;
+ case UPB_TYPE_BYTES:
+ case UPB_TYPE_MESSAGE:
+ return sizeof(void*);
+ case UPB_TYPE_STRING:
+ return sizeof(upb_stringview);
+ }
+ UPB_UNREACHABLE();
+}
+
+static uint8_t upb_msg_fieldsize(const upb_msglayout_fieldinit_v1 *field) {
+ if (field->label == UPB_LABEL_REPEATED) {
+ return sizeof(void*);
+ } else {
+ return upb_msgval_sizeof(field->type);
+ }
+}
+
+static uint8_t upb_msg_fielddefsize(const upb_fielddef *f) {
+ if (upb_fielddef_isseq(f)) {
+ return sizeof(void*);
+ } else {
+ return upb_msgval_sizeof(upb_fielddef_type(f));
+ }
+}
+
+/* TODO(haberman): this is broken right now because upb_msgval can contain
+ * a char* / size_t pair, which is too big for a upb_value. To fix this
+ * we'll probably need to dynamically allocate a upb_msgval and store a
+ * pointer to that in the tables for extensions/maps. */
+static upb_value upb_toval(upb_msgval val) {
+ upb_value ret;
+ UPB_UNUSED(val);
+ memset(&ret, 0, sizeof(upb_value)); /* XXX */
+ return ret;
+}
+
+static upb_msgval upb_msgval_fromval(upb_value val) {
+ upb_msgval ret;
+ UPB_UNUSED(val);
+ memset(&ret, 0, sizeof(upb_msgval)); /* XXX */
+ return ret;
+}
+
+static upb_ctype_t upb_fieldtotabtype(upb_fieldtype_t type) {
+ switch (type) {
+ case UPB_TYPE_FLOAT: return UPB_CTYPE_FLOAT;
+ case UPB_TYPE_DOUBLE: return UPB_CTYPE_DOUBLE;
+ case UPB_TYPE_BOOL: return UPB_CTYPE_BOOL;
+ case UPB_TYPE_BYTES:
+ case UPB_TYPE_MESSAGE:
+ case UPB_TYPE_STRING: return UPB_CTYPE_CONSTPTR;
+ case UPB_TYPE_ENUM:
+ case UPB_TYPE_INT32: return UPB_CTYPE_INT32;
+ case UPB_TYPE_UINT32: return UPB_CTYPE_UINT32;
+ case UPB_TYPE_INT64: return UPB_CTYPE_INT64;
+ case UPB_TYPE_UINT64: return UPB_CTYPE_UINT64;
+ default: UPB_ASSERT(false); return 0;
+ }
+}
+
+static upb_msgval upb_msgval_fromdefault(const upb_fielddef *f) {
+ switch (upb_fielddef_type(f)) {
+ case UPB_TYPE_FLOAT:
+ return upb_msgval_float(upb_fielddef_defaultfloat(f));
+ case UPB_TYPE_DOUBLE:
+ return upb_msgval_double(upb_fielddef_defaultdouble(f));
+ case UPB_TYPE_BOOL:
+ return upb_msgval_bool(upb_fielddef_defaultbool(f));
+ case UPB_TYPE_STRING:
+ case UPB_TYPE_BYTES: {
+ size_t len;
+ const char *ptr = upb_fielddef_defaultstr(f, &len);
+ return upb_msgval_makestr(ptr, len);
+ }
+ case UPB_TYPE_MESSAGE:
+ return upb_msgval_msg(NULL);
+ case UPB_TYPE_ENUM:
+ case UPB_TYPE_INT32:
+ return upb_msgval_int32(upb_fielddef_defaultint32(f));
+ case UPB_TYPE_UINT32:
+ return upb_msgval_uint32(upb_fielddef_defaultuint32(f));
+ case UPB_TYPE_INT64:
+ return upb_msgval_int64(upb_fielddef_defaultint64(f));
+ case UPB_TYPE_UINT64:
+ return upb_msgval_uint64(upb_fielddef_defaultuint64(f));
+ default:
+ UPB_ASSERT(false);
+ return upb_msgval_msg(NULL);
+ }
+}
+
+
+/** upb_msglayout *************************************************************/
+
+struct upb_msglayout {
+ struct upb_msglayout_msginit_v1 data;
+};
+
+static void upb_msglayout_free(upb_msglayout *l) {
+ upb_gfree(l->data.default_msg);
+ upb_gfree(l);
+}
+
+static size_t upb_msglayout_place(upb_msglayout *l, size_t size) {
+ size_t ret;
+
+ l->data.size = align_up(l->data.size, size);
+ ret = l->data.size;
+ l->data.size += size;
+ return ret;
+}
+
+static uint32_t upb_msglayout_offset(const upb_msglayout *l,
+ const upb_fielddef *f) {
+ return l->data.fields[upb_fielddef_index(f)].offset;
+}
+
+static uint32_t upb_msglayout_hasbit(const upb_msglayout *l,
+ const upb_fielddef *f) {
+ return l->data.fields[upb_fielddef_index(f)].hasbit;
+}
+
+static bool upb_msglayout_initdefault(upb_msglayout *l, const upb_msgdef *m) {
+ upb_msg_field_iter it;
+
+ if (upb_msgdef_syntax(m) == UPB_SYNTAX_PROTO2 && l->data.size) {
+ /* Allocate default message and set default values in it. */
+ l->data.default_msg = upb_gmalloc(l->data.size);
+ if (!l->data.default_msg) {
+ return false;
+ }
+
+ memset(l->data.default_msg, 0, l->data.size);
+
+ for (upb_msg_field_begin(&it, m); !upb_msg_field_done(&it);
+ upb_msg_field_next(&it)) {
+ const upb_fielddef* f = upb_msg_iter_field(&it);
+
+ if (upb_fielddef_containingoneof(f)) {
+ continue;
+ }
+
+ /* TODO(haberman): handle strings. */
+ if (!upb_fielddef_isstring(f) &&
+ !upb_fielddef_issubmsg(f) &&
+ !upb_fielddef_isseq(f)) {
+ upb_msg_set(l->data.default_msg,
+ upb_fielddef_index(f),
+ upb_msgval_fromdefault(f),
+ l);
+ }
+ }
+ }
+
+ return true;
+}
+
+static upb_msglayout *upb_msglayout_new(const upb_msgdef *m) {
+ upb_msg_field_iter it;
+ upb_msg_oneof_iter oit;
+ upb_msglayout *l;
+ size_t hasbit;
+ size_t submsg_count = 0;
+ const upb_msglayout_msginit_v1 **submsgs;
+ upb_msglayout_fieldinit_v1 *fields;
+ upb_msglayout_oneofinit_v1 *oneofs;
+
+ for (upb_msg_field_begin(&it, m);
+ !upb_msg_field_done(&it);
+ upb_msg_field_next(&it)) {
+ const upb_fielddef* f = upb_msg_iter_field(&it);
+ if (upb_fielddef_issubmsg(f)) {
+ submsg_count++;
+ }
+ }
+
+ l = upb_gmalloc(sizeof(*l));
+ if (!l) return NULL;
+
+ memset(l, 0, sizeof(*l));
+
+ fields = upb_gmalloc(upb_msgdef_numfields(m) * sizeof(*fields));
+ submsgs = upb_gmalloc(submsg_count * sizeof(*submsgs));
+ oneofs = upb_gmalloc(upb_msgdef_numoneofs(m) * sizeof(*oneofs));
+
+ if ((!fields && upb_msgdef_numfields(m)) ||
+ (!submsgs && submsg_count) ||
+ (!oneofs && upb_msgdef_numoneofs(m))) {
+ /* OOM. */
+ upb_gfree(l);
+ upb_gfree(fields);
+ upb_gfree(submsgs);
+ upb_gfree(oneofs);
+ return NULL;
+ }
+
+ l->data.field_count = upb_msgdef_numfields(m);
+ l->data.oneof_count = upb_msgdef_numoneofs(m);
+ l->data.fields = fields;
+ l->data.submsgs = submsgs;
+ l->data.oneofs = oneofs;
+ l->data.is_proto2 = (upb_msgdef_syntax(m) == UPB_SYNTAX_PROTO2);
+
+ /* Allocate data offsets in three stages:
+ *
+ * 1. hasbits.
+ * 2. regular fields.
+ * 3. oneof fields.
+ *
+ * OPT: There is a lot of room for optimization here to minimize the size.
+ */
+
+ /* Allocate hasbits and set basic field attributes. */
+ for (upb_msg_field_begin(&it, m), hasbit = 0;
+ !upb_msg_field_done(&it);
+ upb_msg_field_next(&it)) {
+ const upb_fielddef* f = upb_msg_iter_field(&it);
+ upb_msglayout_fieldinit_v1 *field = &fields[upb_fielddef_index(f)];
+
+ field->number = upb_fielddef_number(f);
+ field->type = upb_fielddef_type(f);
+ field->label = upb_fielddef_label(f);
+
+ if (upb_fielddef_containingoneof(f)) {
+ field->oneof_index = upb_oneofdef_index(upb_fielddef_containingoneof(f));
+ } else {
+ field->oneof_index = UPB_NOT_IN_ONEOF;
+ }
+
+ if (upb_fielddef_haspresence(f) && !upb_fielddef_containingoneof(f)) {
+ field->hasbit = hasbit++;
+ }
+ }
+
+ /* Account for space used by hasbits. */
+ l->data.size = div_round_up(hasbit, 8);
+
+ /* Allocate non-oneof fields. */
+ for (upb_msg_field_begin(&it, m); !upb_msg_field_done(&it);
+ upb_msg_field_next(&it)) {
+ const upb_fielddef* f = upb_msg_iter_field(&it);
+ size_t field_size = upb_msg_fielddefsize(f);
+ size_t index = upb_fielddef_index(f);
+
+ if (upb_fielddef_containingoneof(f)) {
+ /* Oneofs are handled separately below. */
+ continue;
+ }
+
+ fields[index].offset = upb_msglayout_place(l, field_size);
+ }
+
+ /* Allocate oneof fields. Each oneof field consists of a uint32 for the case
+ * and space for the actual data. */
+ for (upb_msg_oneof_begin(&oit, m); !upb_msg_oneof_done(&oit);
+ upb_msg_oneof_next(&oit)) {
+ const upb_oneofdef* o = upb_msg_iter_oneof(&oit);
+ upb_oneof_iter fit;
+
+ size_t case_size = sizeof(uint32_t); /* Could potentially optimize this. */
+ upb_msglayout_oneofinit_v1 *oneof = &oneofs[upb_oneofdef_index(o)];
+ size_t field_size = 0;
+
+ /* Calculate field size: the max of all field sizes. */
+ for (upb_oneof_begin(&fit, o);
+ !upb_oneof_done(&fit);
+ upb_oneof_next(&fit)) {
+ const upb_fielddef* f = upb_oneof_iter_field(&fit);
+ field_size = UPB_MAX(field_size, upb_msg_fielddefsize(f));
+ }
+
+ /* Align and allocate case offset. */
+ oneof->case_offset = upb_msglayout_place(l, case_size);
+ oneof->data_offset = upb_msglayout_place(l, field_size);
+ }
+
+ /* Size of the entire structure should be a multiple of its greatest
+ * alignment. TODO: track overall alignment for real? */
+ l->data.size = align_up(l->data.size, 8);
+
+ if (upb_msglayout_initdefault(l, m)) {
+ return l;
+ } else {
+ upb_msglayout_free(l);
+ return NULL;
+ }
+}
+
+
+/** upb_msgfactory ************************************************************/
+
+struct upb_msgfactory {
+ const upb_symtab *symtab; /* We own a ref. */
+ upb_inttable layouts;
+ upb_inttable mergehandlers;
+};
+
+upb_msgfactory *upb_msgfactory_new(const upb_symtab *symtab) {
+ upb_msgfactory *ret = upb_gmalloc(sizeof(*ret));
+
+ ret->symtab = symtab;
+ upb_inttable_init(&ret->layouts, UPB_CTYPE_PTR);
+ upb_inttable_init(&ret->mergehandlers, UPB_CTYPE_CONSTPTR);
+
+ return ret;
+}
+
+void upb_msgfactory_free(upb_msgfactory *f) {
+ upb_inttable_iter i;
+ upb_inttable_begin(&i, &f->layouts);
+ for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
+ upb_msglayout *l = upb_value_getptr(upb_inttable_iter_value(&i));
+ upb_msglayout_free(l);
+ }
+
+ upb_inttable_begin(&i, &f->mergehandlers);
+ for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
+ const upb_handlers *h = upb_value_getconstptr(upb_inttable_iter_value(&i));
+ upb_handlers_unref(h, f);
+ }
+
+ upb_inttable_uninit(&f->layouts);
+ upb_inttable_uninit(&f->mergehandlers);
+ upb_gfree(f);
+}
+
+const upb_symtab *upb_msgfactory_symtab(const upb_msgfactory *f) {
+ return f->symtab;
+}
+
+const upb_msglayout *upb_msgfactory_getlayout(upb_msgfactory *f,
+ const upb_msgdef *m) {
+ upb_value v;
+ UPB_ASSERT(upb_symtab_lookupmsg(f->symtab, upb_msgdef_fullname(m)) == m);
+ UPB_ASSERT(!upb_msgdef_mapentry(m));
+
+ if (upb_inttable_lookupptr(&f->layouts, m, &v)) {
+ UPB_ASSERT(upb_value_getptr(v));
+ return upb_value_getptr(v);
+ } else {
+ upb_msgfactory *mutable_f = (void*)f;
+ upb_msglayout *l = upb_msglayout_new(m);
+ upb_inttable_insertptr(&mutable_f->layouts, m, upb_value_ptr(l));
+ UPB_ASSERT(l);
+ return l;
+ }
+}
+
+/* Our handlers that we don't expose externally. */
+
+void *upb_msg_startstr(void *msg, const void *hd, size_t size_hint) {
+ uint32_t ofs = (uintptr_t)hd;
+ upb_alloc *alloc = upb_msg_alloc(msg);
+ upb_msgval val;
+ UPB_UNUSED(size_hint);
+
+ val = upb_msgval_read(msg, ofs, upb_msgval_sizeof(UPB_TYPE_STRING));
+
+ upb_free(alloc, (void*)val.str.data);
+ val.str.data = NULL;
+ val.str.size = 0;
+
+ upb_msgval_write(msg, ofs, val, upb_msgval_sizeof(UPB_TYPE_STRING));
+ return msg;
+}
+
+size_t upb_msg_str(void *msg, const void *hd, const char *ptr, size_t size,
+ const upb_bufhandle *handle) {
+ uint32_t ofs = (uintptr_t)hd;
+ upb_alloc *alloc = upb_msg_alloc(msg);
+ upb_msgval val;
+ size_t newsize;
+ UPB_UNUSED(handle);
+
+ val = upb_msgval_read(msg, ofs, upb_msgval_sizeof(UPB_TYPE_STRING));
+
+ newsize = val.str.size + size;
+ val.str.data = upb_realloc(alloc, (void*)val.str.data, val.str.size, newsize);
+
+ if (!val.str.data) {
+ return false;
+ }
+
+ memcpy((char*)val.str.data + val.str.size, ptr, size);
+ val.str.size = newsize;
+ upb_msgval_write(msg, ofs, val, upb_msgval_sizeof(UPB_TYPE_STRING));
+ return size;
+}
+
+static void callback(const void *closure, upb_handlers *h) {
+ upb_msgfactory *factory = (upb_msgfactory*)closure;
+ const upb_msgdef *md = upb_handlers_msgdef(h);
+ const upb_msglayout* layout = upb_msgfactory_getlayout(factory, md);
+ upb_msg_field_iter i;
+ UPB_UNUSED(factory);
+
+ for(upb_msg_field_begin(&i, md);
+ !upb_msg_field_done(&i);
+ upb_msg_field_next(&i)) {
+ const upb_fielddef *f = upb_msg_iter_field(&i);
+ size_t offset = upb_msglayout_offset(layout, f);
+ upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
+ upb_handlerattr_sethandlerdata(&attr, (void*)offset);
+
+ if (upb_fielddef_isseq(f)) {
+ } else if (upb_fielddef_isstring(f)) {
+ upb_handlers_setstartstr(h, f, upb_msg_startstr, &attr);
+ upb_handlers_setstring(h, f, upb_msg_str, &attr);
+ } else {
+ upb_msg_setscalarhandler(
+ h, f, offset, upb_msglayout_hasbit(layout, f));
+ }
+ }
+}
+
+const upb_handlers *upb_msgfactory_getmergehandlers(upb_msgfactory *f,
+ const upb_msgdef *m) {
+ upb_msgfactory *mutable_f = (void*)f;
+
+ /* TODO(haberman): properly cache these. */
+ const upb_handlers *ret = upb_handlers_newfrozen(m, f, callback, f);
+ upb_inttable_push(&mutable_f->mergehandlers, upb_value_constptr(ret));
+
+ return ret;
+}
+
+const upb_visitorplan *upb_msgfactory_getvisitorplan(upb_msgfactory *f,
+ const upb_handlers *h) {
+ const upb_msgdef *md = upb_handlers_msgdef(h);
+ return (const upb_visitorplan*)upb_msgfactory_getlayout(f, md);
+}
+
+
+/** upb_visitor ***************************************************************/
+
+struct upb_visitor {
+ const upb_msglayout *layout;
+ upb_sink *sink;
+};
+
+static upb_selector_t getsel2(const upb_fielddef *f, upb_handlertype_t type) {
+ upb_selector_t ret;
+ bool ok = upb_handlers_getselector(f, type, &ret);
+ UPB_ASSERT(ok);
+ return ret;
+}
+
+static bool upb_visitor_hasfield(const upb_msg *msg, const upb_fielddef *f,
+ const upb_msglayout *layout) {
+ int field_index = upb_fielddef_index(f);
+ if (upb_fielddef_isseq(f)) {
+ return upb_msgval_getarr(upb_msg_get(msg, field_index, layout)) != NULL;
+ } else if (upb_msgdef_syntax(upb_fielddef_containingtype(f)) ==
+ UPB_SYNTAX_PROTO2) {
+ return upb_msg_has(msg, field_index, layout);
+ } else {
+ upb_msgval val = upb_msg_get(msg, field_index, layout);
+ switch (upb_fielddef_type(f)) {
+ case UPB_TYPE_FLOAT:
+ return upb_msgval_getfloat(val) != 0;
+ case UPB_TYPE_DOUBLE:
+ return upb_msgval_getdouble(val) != 0;
+ case UPB_TYPE_BOOL:
+ return upb_msgval_getbool(val);
+ case UPB_TYPE_ENUM:
+ case UPB_TYPE_INT32:
+ return upb_msgval_getint32(val) != 0;
+ case UPB_TYPE_UINT32:
+ return upb_msgval_getuint32(val) != 0;
+ case UPB_TYPE_INT64:
+ return upb_msgval_getint64(val) != 0;
+ case UPB_TYPE_UINT64:
+ return upb_msgval_getuint64(val) != 0;
+ case UPB_TYPE_STRING:
+ case UPB_TYPE_BYTES:
+ return upb_msgval_getstr(val).size > 0;
+ case UPB_TYPE_MESSAGE:
+ return upb_msgval_getmsg(val) != NULL;
+ }
+ UPB_UNREACHABLE();
+ }
+}
+
+static bool upb_visitor_visitmsg2(const upb_msg *msg,
+ const upb_msglayout *layout, upb_sink *sink,
+ int depth) {
+ const upb_msgdef *md = upb_handlers_msgdef(sink->handlers);
+ upb_msg_field_iter i;
+ upb_status status;
+
+ upb_sink_startmsg(sink);
+
+ /* Protect against cycles (possible because users may freely reassign message
+ * and repeated fields) by imposing a maximum recursion depth. */
+ if (depth > ENCODE_MAX_NESTING) {
+ return false;
+ }
+
+ for (upb_msg_field_begin(&i, md);
+ !upb_msg_field_done(&i);
+ upb_msg_field_next(&i)) {
+ upb_fielddef *f = upb_msg_iter_field(&i);
+ upb_msgval val;
+
+ if (!upb_visitor_hasfield(msg, f, layout)) {
+ continue;
+ }
+
+ val = upb_msg_get(msg, upb_fielddef_index(f), layout);
+
+ if (upb_fielddef_isseq(f)) {
+ const upb_array *arr = upb_msgval_getarr(val);
+ UPB_ASSERT(arr);
+ /* TODO: putary(ary, f, sink, depth);*/
+ } else if (upb_fielddef_issubmsg(f)) {
+ const upb_map *map = upb_msgval_getmap(val);
+ UPB_ASSERT(map);
+ /* TODO: putmap(map, f, sink, depth);*/
+ } else if (upb_fielddef_isstring(f)) {
+ /* TODO putstr(); */
+ } else {
+ upb_selector_t sel = getsel2(f, upb_handlers_getprimitivehandlertype(f));
+ UPB_ASSERT(upb_fielddef_isprimitive(f));
+
+ switch (upb_fielddef_type(f)) {
+ case UPB_TYPE_FLOAT:
+ CHECK_TRUE(upb_sink_putfloat(sink, sel, upb_msgval_getfloat(val)));
+ break;
+ case UPB_TYPE_DOUBLE:
+ CHECK_TRUE(upb_sink_putdouble(sink, sel, upb_msgval_getdouble(val)));
+ break;
+ case UPB_TYPE_BOOL:
+ CHECK_TRUE(upb_sink_putbool(sink, sel, upb_msgval_getbool(val)));
+ break;
+ case UPB_TYPE_ENUM:
+ case UPB_TYPE_INT32:
+ CHECK_TRUE(upb_sink_putint32(sink, sel, upb_msgval_getint32(val)));
+ break;
+ case UPB_TYPE_UINT32:
+ CHECK_TRUE(upb_sink_putuint32(sink, sel, upb_msgval_getuint32(val)));
+ break;
+ case UPB_TYPE_INT64:
+ CHECK_TRUE(upb_sink_putint64(sink, sel, upb_msgval_getint64(val)));
+ break;
+ case UPB_TYPE_UINT64:
+ CHECK_TRUE(upb_sink_putuint64(sink, sel, upb_msgval_getuint64(val)));
+ break;
+ case UPB_TYPE_STRING:
+ case UPB_TYPE_BYTES:
+ case UPB_TYPE_MESSAGE:
+ UPB_UNREACHABLE();
+ }
+ }
+ }
+
+ upb_sink_endmsg(sink, &status);
+ return true;
+}
+
+upb_visitor *upb_visitor_create(upb_env *e, const upb_visitorplan *vp,
+ upb_sink *output) {
+ upb_visitor *visitor = upb_env_malloc(e, sizeof(*visitor));
+ visitor->layout = (const upb_msglayout*)vp;
+ visitor->sink = output;
+ return visitor;
+}
+
+bool upb_visitor_visitmsg(upb_visitor *visitor, const upb_msg *msg) {
+ return upb_visitor_visitmsg2(msg, visitor->layout, visitor->sink, 0);
+}
+
+
+/** upb_msg *******************************************************************/
+
+/* If we always read/write as a consistent type to each address, this shouldn't
+ * violate aliasing.
+ */
+#define DEREF(msg, ofs, type) *PTR_AT(msg, ofs, type)
+
+/* Internal members of a upb_msg. We can change this without breaking binary
+ * compatibility. We put these before the user's data. The user's upb_msg*
+ * points after the upb_msg_internal. */
+
+/* Used when a message is not extendable. */
+typedef struct {
+ /* TODO(haberman): add unknown fields. */
+ upb_alloc *alloc;
+} upb_msg_internal;
+
+/* Used when a message is extendable. */
+typedef struct {
+ upb_inttable *extdict;
+ upb_msg_internal base;
+} upb_msg_internal_withext;
+
+static int upb_msg_internalsize(const upb_msglayout *l) {
+ return sizeof(upb_msg_internal) - l->data.extendable * sizeof(void*);
+}
+
+static upb_msg_internal *upb_msg_getinternal(upb_msg *msg) {
+ return VOIDPTR_AT(msg, -sizeof(upb_msg_internal));
+}
+
+static const upb_msg_internal *upb_msg_getinternal_const(const upb_msg *msg) {
+ return VOIDPTR_AT(msg, -sizeof(upb_msg_internal));
+}
+
+static upb_msg_internal_withext *upb_msg_getinternalwithext(
+ upb_msg *msg, const upb_msglayout *l) {
+ UPB_ASSERT(l->data.extendable);
+ return VOIDPTR_AT(msg, -sizeof(upb_msg_internal_withext));
+}
+
+static const upb_msglayout_fieldinit_v1 *upb_msg_checkfield(
+ int field_index, const upb_msglayout *l) {
+ UPB_ASSERT(field_index >= 0 && field_index < l->data.field_count);
+ return &l->data.fields[field_index];
+}
+
+static bool upb_msg_inoneof(const upb_msglayout_fieldinit_v1 *field) {
+ return field->oneof_index != UPB_NOT_IN_ONEOF;
+}
+
+static uint32_t *upb_msg_oneofcase(const upb_msg *msg, int field_index,
+ const upb_msglayout *l) {
+ const upb_msglayout_fieldinit_v1 *field = upb_msg_checkfield(field_index, l);
+ UPB_ASSERT(upb_msg_inoneof(field));
+ return PTR_AT(msg, l->data.oneofs[field->oneof_index].case_offset, uint32_t);
+}
+
+size_t upb_msg_sizeof(const upb_msglayout *l) {
+ return l->data.size + upb_msg_internalsize(l);
+}
+
+upb_msg *upb_msg_init(void *mem, const upb_msglayout *l, upb_alloc *a) {
+ upb_msg *msg = VOIDPTR_AT(mem, upb_msg_internalsize(l));
+
+ /* Initialize normal members. */
+ if (l->data.default_msg) {
+ memcpy(msg, l->data.default_msg, l->data.size);
+ } else {
+ memset(msg, 0, l->data.size);
+ }
+
+ /* Initialize internal members. */
+ upb_msg_getinternal(msg)->alloc = a;
+
+ if (l->data.extendable) {
+ upb_msg_getinternalwithext(msg, l)->extdict = NULL;
+ }
+
+ return msg;
+}
+
+void *upb_msg_uninit(upb_msg *msg, const upb_msglayout *l) {
+ if (l->data.extendable) {
+ upb_inttable *ext_dict = upb_msg_getinternalwithext(msg, l)->extdict;
+ if (ext_dict) {
+ upb_inttable_uninit2(ext_dict, upb_msg_alloc(msg));
+ upb_free(upb_msg_alloc(msg), ext_dict);
+ }
+ }
+
+ return VOIDPTR_AT(msg, -upb_msg_internalsize(l));
+}
+
+upb_msg *upb_msg_new(const upb_msglayout *l, upb_alloc *a) {
+ void *mem = upb_malloc(a, upb_msg_sizeof(l));
+ return mem ? upb_msg_init(mem, l, a) : NULL;
+}
+
+void upb_msg_free(upb_msg *msg, const upb_msglayout *l) {
+ upb_free(upb_msg_alloc(msg), upb_msg_uninit(msg, l));
+}
+
+upb_alloc *upb_msg_alloc(const upb_msg *msg) {
+ return upb_msg_getinternal_const(msg)->alloc;
+}
+
+bool upb_msg_has(const upb_msg *msg,
+ int field_index,
+ const upb_msglayout *l) {
+ const upb_msglayout_fieldinit_v1 *field = upb_msg_checkfield(field_index, l);
+
+ UPB_ASSERT(l->data.is_proto2);
+
+ if (upb_msg_inoneof(field)) {
+ /* Oneofs are set when the oneof number is set to this field. */
+ return *upb_msg_oneofcase(msg, field_index, l) == field->number;
+ } else {
+ /* Other fields are set when their hasbit is set. */
+ uint32_t hasbit = l->data.fields[field_index].hasbit;
+ return DEREF(msg, hasbit / 8, char) | (1 << (hasbit % 8));
+ }
+}
+
+upb_msgval upb_msg_get(const upb_msg *msg, int field_index,
+ const upb_msglayout *l) {
+ const upb_msglayout_fieldinit_v1 *field = upb_msg_checkfield(field_index, l);
+ int size = upb_msg_fieldsize(field);
+
+ if (upb_msg_inoneof(field)) {
+ if (*upb_msg_oneofcase(msg, field_index, l) == field->number) {
+ size_t ofs = l->data.oneofs[field->oneof_index].data_offset;
+ return upb_msgval_read(msg, ofs, size);
+ } else {
+ /* Return default. */
+ return upb_msgval_read(l->data.default_msg, field->offset, size);
+ }
+ } else {
+ return upb_msgval_read(msg, field->offset, size);
+ }
+}
+
+void upb_msg_set(upb_msg *msg, int field_index, upb_msgval val,
+ const upb_msglayout *l) {
+ const upb_msglayout_fieldinit_v1 *field = upb_msg_checkfield(field_index, l);
+ int size = upb_msg_fieldsize(field);
+
+ if (upb_msg_inoneof(field)) {
+ size_t ofs = l->data.oneofs[field->oneof_index].data_offset;
+ *upb_msg_oneofcase(msg, field_index, l) = field->number;
+ upb_msgval_write(msg, ofs, val, size);
+ } else {
+ upb_msgval_write(msg, field->offset, val, size);
+ }
+}
+
+
+/** upb_array *****************************************************************/
+
+#define DEREF_ARR(arr, i, type) ((type*)arr->data)[i]
+
+size_t upb_array_sizeof(upb_fieldtype_t type) {
+ UPB_UNUSED(type);
+ return sizeof(upb_array);
+}
+
+void upb_array_init(upb_array *arr, upb_fieldtype_t type, upb_alloc *alloc) {
+ arr->type = type;
+ arr->data = NULL;
+ arr->len = 0;
+ arr->size = 0;
+ arr->element_size = upb_msgval_sizeof(type);
+ arr->alloc = alloc;
+}
+
+void upb_array_uninit(upb_array *arr) {
+ upb_free(arr->alloc, arr->data);
+}
+
+upb_array *upb_array_new(upb_fieldtype_t type, upb_alloc *a) {
+ upb_array *ret = upb_malloc(a, upb_array_sizeof(type));
+
+ if (ret) {
+ upb_array_init(ret, type, a);
+ }
+
+ return ret;
+}
+
+void upb_array_free(upb_array *arr) {
+ upb_array_uninit(arr);
+ upb_free(arr->alloc, arr);
+}
+
+size_t upb_array_size(const upb_array *arr) {
+ return arr->len;
+}
+
+upb_fieldtype_t upb_array_type(const upb_array *arr) {
+ return arr->type;
+}
+
+upb_msgval upb_array_get(const upb_array *arr, size_t i) {
+ UPB_ASSERT(i < arr->len);
+ return upb_msgval_read(arr->data, i * arr->element_size, arr->element_size);
+}
+
+bool upb_array_set(upb_array *arr, size_t i, upb_msgval val) {
+ UPB_ASSERT(i <= arr->len);
+
+ if (i == arr->len) {
+ /* Extending the array. */
+
+ if (i == arr->size) {
+ /* Need to reallocate. */
+ size_t new_size = UPB_MAX(arr->size * 2, 8);
+ size_t new_bytes = new_size * arr->element_size;
+ size_t old_bytes = arr->size * arr->element_size;
+ upb_msgval *new_data =
+ upb_realloc(arr->alloc, arr->data, old_bytes, new_bytes);
+
+ if (!new_data) {
+ return false;
+ }
+
+ arr->data = new_data;
+ arr->size = new_size;
+ }
+
+ arr->len = i + 1;
+ }
+
+ upb_msgval_write(arr->data, i * arr->element_size, val, arr->element_size);
+ return true;
+}
+
+
+/** upb_map *******************************************************************/
+
+struct upb_map {
+ upb_fieldtype_t key_type;
+ upb_fieldtype_t val_type;
+ /* We may want to optimize this to use inttable where possible, for greater
+ * efficiency and lower memory footprint. */
+ upb_strtable strtab;
+ upb_alloc *alloc;
+};
+
+static void upb_map_tokey(upb_fieldtype_t type, upb_msgval *key,
+ const char **out_key, size_t *out_len) {
+ switch (type) {
+ case UPB_TYPE_STRING:
+ /* Point to string data of the input key. */
+ *out_key = key->str.data;
+ *out_len = key->str.size;
+ return;
+ case UPB_TYPE_BOOL:
+ case UPB_TYPE_INT32:
+ case UPB_TYPE_UINT32:
+ case UPB_TYPE_INT64:
+ case UPB_TYPE_UINT64:
+ /* Point to the key itself. XXX: big-endian. */
+ *out_key = (const char*)key;
+ *out_len = upb_msgval_sizeof(type);
+ return;
+ case UPB_TYPE_BYTES:
+ case UPB_TYPE_DOUBLE:
+ case UPB_TYPE_ENUM:
+ case UPB_TYPE_FLOAT:
+ case UPB_TYPE_MESSAGE:
+ break; /* Cannot be a map key. */
+ }
+ UPB_UNREACHABLE();
+}
+
+static upb_msgval upb_map_fromkey(upb_fieldtype_t type, const char *key,
+ size_t len) {
+ switch (type) {
+ case UPB_TYPE_STRING:
+ return upb_msgval_makestr(key, len);
+ case UPB_TYPE_BOOL:
+ case UPB_TYPE_INT32:
+ case UPB_TYPE_UINT32:
+ case UPB_TYPE_INT64:
+ case UPB_TYPE_UINT64:
+ return upb_msgval_read(key, 0, upb_msgval_sizeof(type));
+ case UPB_TYPE_BYTES:
+ case UPB_TYPE_DOUBLE:
+ case UPB_TYPE_ENUM:
+ case UPB_TYPE_FLOAT:
+ case UPB_TYPE_MESSAGE:
+ break; /* Cannot be a map key. */
+ }
+ UPB_UNREACHABLE();
+}
+
+size_t upb_map_sizeof(upb_fieldtype_t ktype, upb_fieldtype_t vtype) {
+ /* Size does not currently depend on key/value type. */
+ UPB_UNUSED(ktype);
+ UPB_UNUSED(vtype);
+ return sizeof(upb_map);
+}
+
+bool upb_map_init(upb_map *map, upb_fieldtype_t ktype, upb_fieldtype_t vtype,
+ upb_alloc *a) {
+ upb_ctype_t vtabtype = upb_fieldtotabtype(vtype);
+ UPB_ASSERT(upb_fieldtype_mapkeyok(ktype));
+ map->key_type = ktype;
+ map->val_type = vtype;
+ map->alloc = a;
+
+ if (!upb_strtable_init2(&map->strtab, vtabtype, a)) {
+ return false;
+ }
+
+ return true;
+}
+
+void upb_map_uninit(upb_map *map) {
+ upb_strtable_uninit2(&map->strtab, map->alloc);
+}
+
+upb_map *upb_map_new(upb_fieldtype_t ktype, upb_fieldtype_t vtype,
+ upb_alloc *a) {
+ upb_map *map = upb_malloc(a, upb_map_sizeof(ktype, vtype));
+
+ if (!map) {
+ return NULL;
+ }
+
+ if (!upb_map_init(map, ktype, vtype, a)) {
+ return NULL;
+ }
+
+ return map;
+}
+
+void upb_map_free(upb_map *map) {
+ upb_map_uninit(map);
+ upb_free(map->alloc, map);
+}
+
+size_t upb_map_size(const upb_map *map) {
+ return upb_strtable_count(&map->strtab);
+}
+
+upb_fieldtype_t upb_map_keytype(const upb_map *map) {
+ return map->key_type;
+}
+
+upb_fieldtype_t upb_map_valuetype(const upb_map *map) {
+ return map->val_type;
+}
+
+bool upb_map_get(const upb_map *map, upb_msgval key, upb_msgval *val) {
+ upb_value tabval;
+ const char *key_str;
+ size_t key_len;
+ bool ret;
+
+ upb_map_tokey(map->key_type, &key, &key_str, &key_len);
+ ret = upb_strtable_lookup2(&map->strtab, key_str, key_len, &tabval);
+ if (ret) {
+ memcpy(val, &tabval, sizeof(tabval));
+ }
+
+ return ret;
+}
+
+bool upb_map_set(upb_map *map, upb_msgval key, upb_msgval val,
+ upb_msgval *removed) {
+ const char *key_str;
+ size_t key_len;
+ upb_value tabval = upb_toval(val);
+ upb_value removedtabval;
+ upb_alloc *a = map->alloc;
+
+ upb_map_tokey(map->key_type, &key, &key_str, &key_len);
+
+ /* TODO(haberman): add overwrite operation to minimize number of lookups. */
+ if (upb_strtable_lookup2(&map->strtab, key_str, key_len, NULL)) {
+ upb_strtable_remove3(&map->strtab, key_str, key_len, &removedtabval, a);
+ memcpy(&removed, &removedtabval, sizeof(removed));
+ }
+
+ return upb_strtable_insert3(&map->strtab, key_str, key_len, tabval, a);
+}
+
+bool upb_map_del(upb_map *map, upb_msgval key) {
+ const char *key_str;
+ size_t key_len;
+ upb_alloc *a = map->alloc;
+
+ upb_map_tokey(map->key_type, &key, &key_str, &key_len);
+ return upb_strtable_remove3(&map->strtab, key_str, key_len, NULL, a);
+}
+
+
+/** upb_mapiter ***************************************************************/
+
+struct upb_mapiter {
+ upb_strtable_iter iter;
+ upb_fieldtype_t key_type;
+};
+
+size_t upb_mapiter_sizeof() {
+ return sizeof(upb_mapiter);
+}
+
+void upb_mapiter_begin(upb_mapiter *i, const upb_map *map) {
+ upb_strtable_begin(&i->iter, &map->strtab);
+ i->key_type = map->key_type;
+}
+
+upb_mapiter *upb_mapiter_new(const upb_map *t, upb_alloc *a) {
+ upb_mapiter *ret = upb_malloc(a, upb_mapiter_sizeof());
+
+ if (!ret) {
+ return NULL;
+ }
+
+ upb_mapiter_begin(ret, t);
+ return ret;
+}
+
+void upb_mapiter_free(upb_mapiter *i, upb_alloc *a) {
+ upb_free(a, i);
+}
+
+void upb_mapiter_next(upb_mapiter *i) {
+ upb_strtable_next(&i->iter);
+}
+
+bool upb_mapiter_done(const upb_mapiter *i) {
+ return upb_strtable_done(&i->iter);
+}
+
+upb_msgval upb_mapiter_key(const upb_mapiter *i) {
+ return upb_map_fromkey(i->key_type, upb_strtable_iter_key(&i->iter),
+ upb_strtable_iter_keylength(&i->iter));
+}
+
+upb_msgval upb_mapiter_value(const upb_mapiter *i) {
+ return upb_msgval_fromval(upb_strtable_iter_value(&i->iter));
+}
+
+void upb_mapiter_setdone(upb_mapiter *i) {
+ upb_strtable_iter_setdone(&i->iter);
+}
+
+bool upb_mapiter_isequal(const upb_mapiter *i1, const upb_mapiter *i2) {
+ return upb_strtable_iter_isequal(&i1->iter, &i2->iter);
+}
+
+
+/** Handlers for upb_msg ******************************************************/
+
+typedef struct {
+ size_t offset;
+ int32_t hasbit;
+} upb_msg_handlerdata;
+
+/* Fallback implementation if the handler is not specialized by the producer. */
+#define MSG_WRITER(type, ctype) \
+ bool upb_msg_set ## type (void *c, const void *hd, ctype val) { \
+ uint8_t *m = c; \
+ const upb_msg_handlerdata *d = hd; \
+ if (d->hasbit > 0) \
+ *(uint8_t*)&m[d->hasbit / 8] |= 1 << (d->hasbit % 8); \
+ *(ctype*)&m[d->offset] = val; \
+ return true; \
+ } \
+
+MSG_WRITER(double, double)
+MSG_WRITER(float, float)
+MSG_WRITER(int32, int32_t)
+MSG_WRITER(int64, int64_t)
+MSG_WRITER(uint32, uint32_t)
+MSG_WRITER(uint64, uint64_t)
+MSG_WRITER(bool, bool)
+
+bool upb_msg_setscalarhandler(upb_handlers *h, const upb_fielddef *f,
+ size_t offset, int32_t hasbit) {
+ upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
+ bool ok;
+
+ upb_msg_handlerdata *d = upb_gmalloc(sizeof(*d));
+ if (!d) return false;
+ d->offset = offset;
+ d->hasbit = hasbit;
+
+ upb_handlerattr_sethandlerdata(&attr, d);
+ upb_handlerattr_setalwaysok(&attr, true);
+ upb_handlers_addcleanup(h, d, upb_gfree);
+
+#define TYPE(u, l) \
+ case UPB_TYPE_##u: \
+ ok = upb_handlers_set##l(h, f, upb_msg_set##l, &attr); break;
+
+ ok = false;
+
+ switch (upb_fielddef_type(f)) {
+ TYPE(INT64, int64);
+ TYPE(INT32, int32);
+ TYPE(ENUM, int32);
+ TYPE(UINT64, uint64);
+ TYPE(UINT32, uint32);
+ TYPE(DOUBLE, double);
+ TYPE(FLOAT, float);
+ TYPE(BOOL, bool);
+ default: UPB_ASSERT(false); break;
+ }
+#undef TYPE
+
+ upb_handlerattr_uninit(&attr);
+ return ok;
+}
+
+bool upb_msg_getscalarhandlerdata(const upb_handlers *h,
+ upb_selector_t s,
+ upb_fieldtype_t *type,
+ size_t *offset,
+ int32_t *hasbit) {
+ const upb_msg_handlerdata *d;
+ upb_func *f = upb_handlers_gethandler(h, s);
+
+ if ((upb_int64_handlerfunc*)f == upb_msg_setint64) {
+ *type = UPB_TYPE_INT64;
+ } else if ((upb_int32_handlerfunc*)f == upb_msg_setint32) {
+ *type = UPB_TYPE_INT32;
+ } else if ((upb_uint64_handlerfunc*)f == upb_msg_setuint64) {
+ *type = UPB_TYPE_UINT64;
+ } else if ((upb_uint32_handlerfunc*)f == upb_msg_setuint32) {
+ *type = UPB_TYPE_UINT32;
+ } else if ((upb_double_handlerfunc*)f == upb_msg_setdouble) {
+ *type = UPB_TYPE_DOUBLE;
+ } else if ((upb_float_handlerfunc*)f == upb_msg_setfloat) {
+ *type = UPB_TYPE_FLOAT;
+ } else if ((upb_bool_handlerfunc*)f == upb_msg_setbool) {
+ *type = UPB_TYPE_BOOL;
+ } else {
+ return false;
+ }
+
+ d = upb_handlers_gethandlerdata(h, s);
+ *offset = d->offset;
+ *hasbit = d->hasbit;
+ return true;
+}
/*
** upb::RefCounted Implementation
**
@@ -2938,7 +5351,7 @@ static trackedref *trackedref_new(bool is_ref2) {
static void track(const upb_refcounted *r, const void *owner, bool ref2) {
upb_value v;
- assert(owner);
+ UPB_ASSERT(owner);
if (owner == UPB_UNTRACKED_REF) return;
upb_lock();
@@ -2949,8 +5362,8 @@ static void track(const upb_refcounted *r, const void *owner, bool ref2) {
* tracking behavior we get with regular refs. Since ref2s only happen
* inside upb, we'll accept this limitation until/unless there is a really
* difficult upb-internal bug that can't be figured out without it. */
- assert(ref2);
- assert(ref->is_ref2);
+ UPB_ASSERT(ref2);
+ UPB_ASSERT(ref->is_ref2);
ref->count++;
} else {
trackedref *ref = trackedref_new(ref2);
@@ -2960,7 +5373,7 @@ static void track(const upb_refcounted *r, const void *owner, bool ref2) {
/* We know this cast is safe when it is a ref2, because it's coming from
* another refcounted object. */
const upb_refcounted *from = owner;
- assert(!upb_inttable_lookupptr(from->ref2s, r, NULL));
+ UPB_ASSERT(!upb_inttable_lookupptr(from->ref2s, r, NULL));
upb_inttable_insertptr2(from->ref2s, r, upb_value_ptr(NULL),
&upb_alloc_debugrefs);
}
@@ -2973,15 +5386,15 @@ static void untrack(const upb_refcounted *r, const void *owner, bool ref2) {
bool found;
trackedref *ref;
- assert(owner);
+ UPB_ASSERT(owner);
if (owner == UPB_UNTRACKED_REF) return;
upb_lock();
found = upb_inttable_lookupptr(r->refs, owner, &v);
/* This assert will fail if an owner attempts to release a ref it didn't have. */
- UPB_ASSERT_VAR(found, found);
+ UPB_ASSERT(found);
ref = upb_value_getptr(v);
- assert(ref->is_ref2 == ref2);
+ UPB_ASSERT(ref->is_ref2 == ref2);
if (--ref->count == 0) {
free(ref);
upb_inttable_removeptr(r->refs, owner, NULL);
@@ -2990,7 +5403,7 @@ static void untrack(const upb_refcounted *r, const void *owner, bool ref2) {
* another refcounted object. */
const upb_refcounted *from = owner;
bool removed = upb_inttable_removeptr(from->ref2s, r, NULL);
- assert(removed);
+ UPB_ASSERT(removed);
}
}
upb_unlock();
@@ -3003,9 +5416,9 @@ static void checkref(const upb_refcounted *r, const void *owner, bool ref2) {
upb_lock();
found = upb_inttable_lookupptr(r->refs, owner, &v);
- UPB_ASSERT_VAR(found, found);
+ UPB_ASSERT(found);
ref = upb_value_getptr(v);
- assert(ref->is_ref2 == ref2);
+ UPB_ASSERT(ref->is_ref2 == ref2);
upb_unlock();
}
@@ -3026,7 +5439,7 @@ static void getref2s(const upb_refcounted *owner, upb_inttable *tab) {
/* To get the count we need to look in the target's table. */
found = upb_inttable_lookupptr(to->refs, owner, &v);
- assert(found);
+ UPB_ASSERT(found);
ref = upb_value_getptr(v);
count = upb_value_int32(ref->count);
@@ -3048,12 +5461,12 @@ static void visit_check(const upb_refcounted *obj, const upb_refcounted *subobj,
bool removed;
int32_t newcount;
- assert(obj == s->obj);
- assert(subobj);
+ UPB_ASSERT(obj == s->obj);
+ UPB_ASSERT(subobj);
removed = upb_inttable_removeptr(ref2, subobj, &v);
/* The following assertion will fail if the visit() function visits a subobj
* that it did not have a ref2 on, or visits the same subobj too many times. */
- assert(removed);
+ UPB_ASSERT(removed);
newcount = upb_value_getint32(v) - 1;
if (newcount > 0) {
upb_inttable_insert2(ref2, (uintptr_t)subobj, upb_value_int32(newcount),
@@ -3075,7 +5488,7 @@ static void visit(const upb_refcounted *r, upb_refcounted_visit *v,
if (r->vtbl->visit) r->vtbl->visit(r, visit_check, &state);
/* This assertion will fail if the visit() function missed any children. */
- assert(upb_inttable_count(&state.ref2) == 0);
+ UPB_ASSERT(upb_inttable_count(&state.ref2) == 0);
upb_inttable_uninit2(&state.ref2, &upb_alloc_debugrefs);
if (r->vtbl->visit) r->vtbl->visit(r, v, closure);
}
@@ -3182,7 +5595,7 @@ static uint64_t trygetattr(const tarjan *t, const upb_refcounted *r) {
static uint64_t getattr(const tarjan *t, const upb_refcounted *r) {
upb_value v;
bool found = upb_inttable_lookupptr(&t->objattr, r, &v);
- UPB_ASSERT_VAR(found, found);
+ UPB_ASSERT(found);
return upb_value_getuint64(v);
}
@@ -3196,13 +5609,13 @@ static color_t color(tarjan *t, const upb_refcounted *r) {
}
static void set_gray(tarjan *t, const upb_refcounted *r) {
- assert(color(t, r) == BLACK);
+ UPB_ASSERT(color(t, r) == BLACK);
setattr(t, r, GRAY);
}
/* Pushes an obj onto the Tarjan stack and sets it to GREEN. */
static void push(tarjan *t, const upb_refcounted *r) {
- assert(color(t, r) == BLACK || color(t, r) == GRAY);
+ UPB_ASSERT(color(t, r) == BLACK || color(t, r) == GRAY);
/* This defines the attr layout for the GREEN state. "index" and "lowlink"
* get 31 bits, which is plenty (limit of 2B objects frozen at a time). */
setattr(t, r, GREEN | (t->index << 2) | (t->index << 33));
@@ -3217,7 +5630,7 @@ static void push(tarjan *t, const upb_refcounted *r) {
* SCC group. */
static upb_refcounted *pop(tarjan *t) {
upb_refcounted *r = upb_value_getptr(upb_inttable_pop(&t->stack));
- assert(color(t, r) == GREEN);
+ UPB_ASSERT(color(t, r) == GREEN);
/* This defines the attr layout for nodes in the WHITE state.
* Top of group stack is [group, NULL]; we point at group. */
setattr(t, r, WHITE | (upb_inttable_count(&t->groups) - 2) << 8);
@@ -3237,7 +5650,7 @@ static void tarjan_newgroup(tarjan *t) {
}
static uint32_t idx(tarjan *t, const upb_refcounted *r) {
- assert(color(t, r) == GREEN);
+ UPB_ASSERT(color(t, r) == GREEN);
return (getattr(t, r) >> 2) & 0x7FFFFFFF;
}
@@ -3250,7 +5663,7 @@ static uint32_t lowlink(tarjan *t, const upb_refcounted *r) {
}
static void set_lowlink(tarjan *t, const upb_refcounted *r, uint32_t lowlink) {
- assert(color(t, r) == GREEN);
+ UPB_ASSERT(color(t, r) == GREEN);
setattr(t, r, ((uint64_t)lowlink << 33) | (getattr(t, r) & 0x1FFFFFFFF));
}
@@ -3259,10 +5672,10 @@ static uint32_t *group(tarjan *t, upb_refcounted *r) {
upb_value v;
bool found;
- assert(color(t, r) == WHITE);
+ UPB_ASSERT(color(t, r) == WHITE);
groupnum = getattr(t, r) >> 8;
found = upb_inttable_lookup(&t->groups, groupnum, &v);
- UPB_ASSERT_VAR(found, found);
+ UPB_ASSERT(found);
return upb_value_getptr(v);
}
@@ -3273,10 +5686,10 @@ static upb_refcounted *groupleader(tarjan *t, upb_refcounted *r) {
upb_value v;
bool found;
- assert(color(t, r) == WHITE);
+ UPB_ASSERT(color(t, r) == WHITE);
leader_slot = (getattr(t, r) >> 8) + 1;
found = upb_inttable_lookup(&t->groups, leader_slot, &v);
- UPB_ASSERT_VAR(found, found);
+ UPB_ASSERT(found);
if (upb_value_getptr(v)) {
return upb_value_getptr(v);
} else {
@@ -3336,7 +5749,7 @@ static void do_tarjan(const upb_refcounted *obj, tarjan *t) {
static void crossref(const upb_refcounted *r, const upb_refcounted *subobj,
void *_t) {
tarjan *t = _t;
- assert(color(t, r) > BLACK);
+ UPB_ASSERT(color(t, r) > BLACK);
if (color(t, subobj) > BLACK && r->group != subobj->group) {
/* Previously this ref was not reflected in subobj->group because they
* were in the same group; now that they are split a ref must be taken. */
@@ -3404,13 +5817,13 @@ static bool freeze(upb_refcounted *const*roots, int n, upb_status *s,
upb_refcounted *move = obj->next;
if (obj == move) {
/* Removing the last object from a group. */
- assert(*obj->group == obj->individual_count);
+ UPB_ASSERT(*obj->group == obj->individual_count);
upb_gfree(obj->group);
} else {
obj->next = move->next;
/* This may decrease to zero; we'll collect GRAY objects (if any) that
* remain in the group in the third pass. */
- assert(*move->group >= move->individual_count);
+ UPB_ASSERT(*move->group >= move->individual_count);
*move->group -= move->individual_count;
}
@@ -3423,7 +5836,7 @@ static bool freeze(upb_refcounted *const*roots, int n, upb_status *s,
*move->group = move->individual_count;
} else {
/* Group already has at least one object in it. */
- assert(leader->group == group(&t, move));
+ UPB_ASSERT(leader->group == group(&t, move));
move->group = group(&t, move);
move->next = leader->next;
leader->next = move;
@@ -3513,7 +5926,7 @@ static void merge(upb_refcounted *r, upb_refcounted *from) {
* TODO(haberman): this linear algorithm can result in an overall O(n^2) bound
* if the user continuously extends a group by one object. Prevent this by
* using one of the techniques in this paper:
- * ftp://www.ncedc.org/outgoing/geomorph/dino/orals/p245-tarjan.pdf */
+ * http://bioinfo.ict.ac.cn/~dbu/AlgorithmCourses/Lectures/Union-Find-Tarjan.pdf */
do { from->group = r->group; } while ((from = from->next) != base);
/* Merge the two circularly linked lists by swapping their next pointers. */
@@ -3530,7 +5943,7 @@ static void release_ref2(const upb_refcounted *obj,
UPB_UNUSED(closure);
untrack(subobj, obj, true);
if (!merged(obj, subobj)) {
- assert(subobj->is_frozen);
+ UPB_ASSERT(subobj->is_frozen);
unref(subobj);
}
}
@@ -3549,7 +5962,7 @@ static void unref(const upb_refcounted *r) {
o = r;
do {
const upb_refcounted *next = o->next;
- assert(o->is_frozen || o->individual_count == 0);
+ UPB_ASSERT(o->is_frozen || o->individual_count == 0);
freeobj((upb_refcounted*)o);
o = next;
} while(o != r);
@@ -3573,9 +5986,9 @@ bool upb_refcounted_init(upb_refcounted *r,
* basically every program using upb. */
const int x = 1;
#ifdef UPB_BIG_ENDIAN
- assert(*(char*)&x != 1);
+ UPB_ASSERT(*(char*)&x != 1);
#else
- assert(*(char*)&x == 1);
+ UPB_ASSERT(*(char*)&x == 1);
#endif
#endif
@@ -3610,7 +6023,7 @@ void upb_refcounted_unref(const upb_refcounted *r, const void *owner) {
}
void upb_refcounted_ref2(const upb_refcounted *r, upb_refcounted *from) {
- assert(!from->is_frozen); /* Non-const pointer implies this. */
+ UPB_ASSERT(!from->is_frozen); /* Non-const pointer implies this. */
track(r, from, true);
if (r->is_frozen) {
refgroup(r->group);
@@ -3620,18 +6033,18 @@ void upb_refcounted_ref2(const upb_refcounted *r, upb_refcounted *from) {
}
void upb_refcounted_unref2(const upb_refcounted *r, upb_refcounted *from) {
- assert(!from->is_frozen); /* Non-const pointer implies this. */
+ UPB_ASSERT(!from->is_frozen); /* Non-const pointer implies this. */
untrack(r, from, true);
if (r->is_frozen) {
unref(r);
} else {
- assert(merged(r, from));
+ UPB_ASSERT(merged(r, from));
}
}
void upb_refcounted_donateref(
const upb_refcounted *r, const void *from, const void *to) {
- assert(from != to);
+ UPB_ASSERT(from != to);
if (to != NULL)
upb_refcounted_ref(r, to);
if (from != NULL)
@@ -3647,587 +6060,99 @@ bool upb_refcounted_freeze(upb_refcounted *const*roots, int n, upb_status *s,
int i;
bool ret;
for (i = 0; i < n; i++) {
- assert(!roots[i]->is_frozen);
+ UPB_ASSERT(!roots[i]->is_frozen);
}
ret = freeze(roots, n, s, maxdepth);
- assert(!s || ret == upb_ok(s));
+ UPB_ASSERT(!s || ret == upb_ok(s));
return ret;
}
-/* Fallback implementation if the shim is not specialized by the JIT. */
-#define SHIM_WRITER(type, ctype) \
- bool upb_shim_set ## type (void *c, const void *hd, ctype val) { \
- uint8_t *m = c; \
- const upb_shim_data *d = hd; \
- if (d->hasbit > 0) \
- *(uint8_t*)&m[d->hasbit / 8] |= 1 << (d->hasbit % 8); \
- *(ctype*)&m[d->offset] = val; \
- return true; \
- } \
-
-SHIM_WRITER(double, double)
-SHIM_WRITER(float, float)
-SHIM_WRITER(int32, int32_t)
-SHIM_WRITER(int64, int64_t)
-SHIM_WRITER(uint32, uint32_t)
-SHIM_WRITER(uint64, uint64_t)
-SHIM_WRITER(bool, bool)
-#undef SHIM_WRITER
-
-bool upb_shim_set(upb_handlers *h, const upb_fielddef *f, size_t offset,
- int32_t hasbit) {
- upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
- bool ok;
-
- upb_shim_data *d = upb_gmalloc(sizeof(*d));
- if (!d) return false;
- d->offset = offset;
- d->hasbit = hasbit;
-
- upb_handlerattr_sethandlerdata(&attr, d);
- upb_handlerattr_setalwaysok(&attr, true);
- upb_handlers_addcleanup(h, d, upb_gfree);
-
-#define TYPE(u, l) \
- case UPB_TYPE_##u: \
- ok = upb_handlers_set##l(h, f, upb_shim_set##l, &attr); break;
-
- ok = false;
-
- switch (upb_fielddef_type(f)) {
- TYPE(INT64, int64);
- TYPE(INT32, int32);
- TYPE(ENUM, int32);
- TYPE(UINT64, uint64);
- TYPE(UINT32, uint32);
- TYPE(DOUBLE, double);
- TYPE(FLOAT, float);
- TYPE(BOOL, bool);
- default: assert(false); break;
- }
-#undef TYPE
-
- upb_handlerattr_uninit(&attr);
- return ok;
-}
-
-const upb_shim_data *upb_shim_getdata(const upb_handlers *h, upb_selector_t s,
- upb_fieldtype_t *type) {
- upb_func *f = upb_handlers_gethandler(h, s);
-
- if ((upb_int64_handlerfunc*)f == upb_shim_setint64) {
- *type = UPB_TYPE_INT64;
- } else if ((upb_int32_handlerfunc*)f == upb_shim_setint32) {
- *type = UPB_TYPE_INT32;
- } else if ((upb_uint64_handlerfunc*)f == upb_shim_setuint64) {
- *type = UPB_TYPE_UINT64;
- } else if ((upb_uint32_handlerfunc*)f == upb_shim_setuint32) {
- *type = UPB_TYPE_UINT32;
- } else if ((upb_double_handlerfunc*)f == upb_shim_setdouble) {
- *type = UPB_TYPE_DOUBLE;
- } else if ((upb_float_handlerfunc*)f == upb_shim_setfloat) {
- *type = UPB_TYPE_FLOAT;
- } else if ((upb_bool_handlerfunc*)f == upb_shim_setbool) {
- *type = UPB_TYPE_BOOL;
- } else {
- return NULL;
- }
-
- return (const upb_shim_data*)upb_handlers_gethandlerdata(h, s);
-}
-
-
-#include <string.h>
-
-static void upb_symtab_free(upb_refcounted *r) {
- upb_symtab *s = (upb_symtab*)r;
- upb_strtable_iter i;
- upb_strtable_begin(&i, &s->symtab);
- for (; !upb_strtable_done(&i); upb_strtable_next(&i)) {
- const upb_def *def = upb_value_getptr(upb_strtable_iter_value(&i));
- upb_def_unref(def, s);
- }
- upb_strtable_uninit(&s->symtab);
- upb_gfree(s);
-}
-
-upb_symtab *upb_symtab_new(const void *owner) {
- static const struct upb_refcounted_vtbl vtbl = {NULL, &upb_symtab_free};
-
- upb_symtab *s = upb_gmalloc(sizeof(*s));
- if (!s) {
- return NULL;
+bool upb_bufsrc_putbuf(const char *buf, size_t len, upb_bytessink *sink) {
+ void *subc;
+ bool ret;
+ upb_bufhandle handle;
+ upb_bufhandle_init(&handle);
+ upb_bufhandle_setbuf(&handle, buf, 0);
+ ret = upb_bytessink_start(sink, len, &subc);
+ if (ret && len != 0) {
+ ret = (upb_bytessink_putbuf(sink, subc, buf, len, &handle) >= len);
}
-
- upb_refcounted_init(upb_symtab_upcast_mutable(s), &vtbl, owner);
- upb_strtable_init(&s->symtab, UPB_CTYPE_PTR);
- return s;
-}
-
-void upb_symtab_freeze(upb_symtab *s) {
- upb_refcounted *r;
- bool ok;
-
- assert(!upb_symtab_isfrozen(s));
- r = upb_symtab_upcast_mutable(s);
- /* The symtab does not take ref2's (see refcounted.h) on the defs, because
- * defs cannot refer back to the table and therefore cannot create cycles. So
- * 0 will suffice for maxdepth here. */
- ok = upb_refcounted_freeze(&r, 1, NULL, 0);
- UPB_ASSERT_VAR(ok, ok);
-}
-
-const upb_def *upb_symtab_lookup(const upb_symtab *s, const char *sym) {
- upb_value v;
- upb_def *ret = upb_strtable_lookup(&s->symtab, sym, &v) ?
- upb_value_getptr(v) : NULL;
- return ret;
-}
-
-const upb_msgdef *upb_symtab_lookupmsg(const upb_symtab *s, const char *sym) {
- upb_value v;
- upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
- upb_value_getptr(v) : NULL;
- return def ? upb_dyncast_msgdef(def) : NULL;
-}
-
-const upb_enumdef *upb_symtab_lookupenum(const upb_symtab *s, const char *sym) {
- upb_value v;
- upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
- upb_value_getptr(v) : NULL;
- return def ? upb_dyncast_enumdef(def) : NULL;
-}
-
-/* Given a symbol and the base symbol inside which it is defined, find the
- * symbol's definition in t. */
-static upb_def *upb_resolvename(const upb_strtable *t,
- const char *base, const char *sym) {
- if(strlen(sym) == 0) return NULL;
- if(sym[0] == '.') {
- /* Symbols starting with '.' are absolute, so we do a single lookup.
- * Slice to omit the leading '.' */
- upb_value v;
- return upb_strtable_lookup(t, sym + 1, &v) ? upb_value_getptr(v) : NULL;
- } else {
- /* Remove components from base until we find an entry or run out.
- * TODO: This branch is totally broken, but currently not used. */
- (void)base;
- assert(false);
- return NULL;
+ if (ret) {
+ ret = upb_bytessink_end(sink);
}
-}
-
-const upb_def *upb_symtab_resolve(const upb_symtab *s, const char *base,
- const char *sym) {
- upb_def *ret = upb_resolvename(&s->symtab, base, sym);
+ upb_bufhandle_uninit(&handle);
return ret;
}
-/* Starts a depth-first traversal at "def", recursing into any subdefs
- * (ie. submessage types). Adds duplicates of existing defs to addtab
- * wherever necessary, so that the resulting symtab will be consistent once
- * addtab is added.
- *
- * More specifically, if any def D is found in the DFS that:
- *
- * 1. can reach a def that is being replaced by something in addtab, AND
- *
- * 2. is not itself being replaced already (ie. this name doesn't already
- * exist in addtab)
- *
- * ...then a duplicate (new copy) of D will be added to addtab.
- *
- * Returns true if this happened for any def reachable from "def."
- *
- * It is slightly tricky to do this correctly in the presence of cycles. If we
- * detect that our DFS has hit a cycle, we might not yet know if any SCCs on
- * our stack can reach a def in addtab or not. Once we figure this out, that
- * answer needs to apply to *all* defs in these SCCs, even if we visited them
- * already. So a straight up one-pass cycle-detecting DFS won't work.
- *
- * To work around this problem, we traverse each SCC (which we already
- * computed, since these defs are frozen) as a single node. We first compute
- * whether the SCC as a whole can reach any def in addtab, then we dup (or not)
- * the entire SCC. This requires breaking the encapsulation of upb_refcounted,
- * since that is where we get the data about what SCC we are in. */
-static bool upb_resolve_dfs(const upb_def *def, upb_strtable *addtab,
- const void *new_owner, upb_inttable *seen,
- upb_status *s) {
- upb_value v;
- bool need_dup;
- const upb_def *base;
- const void* memoize_key;
-
- /* Memoize results of this function for efficiency (since we're traversing a
- * DAG this is not needed to limit the depth of the search).
- *
- * We memoize by SCC instead of by individual def. */
- memoize_key = def->base.group;
-
- if (upb_inttable_lookupptr(seen, memoize_key, &v))
- return upb_value_getbool(v);
-
- /* Visit submessages for all messages in the SCC. */
- need_dup = false;
- base = def;
- do {
- upb_value v;
- const upb_msgdef *m;
-
- assert(upb_def_isfrozen(def));
- if (def->type == UPB_DEF_FIELD) continue;
- if (upb_strtable_lookup(addtab, upb_def_fullname(def), &v)) {
- need_dup = true;
- }
-
- /* For messages, continue the recursion by visiting all subdefs, but only
- * ones in different SCCs. */
- m = upb_dyncast_msgdef(def);
- if (m) {
- upb_msg_field_iter i;
- for(upb_msg_field_begin(&i, m);
- !upb_msg_field_done(&i);
- upb_msg_field_next(&i)) {
- upb_fielddef *f = upb_msg_iter_field(&i);
- const upb_def *subdef;
-
- if (!upb_fielddef_hassubdef(f)) continue;
- subdef = upb_fielddef_subdef(f);
-
- /* Skip subdefs in this SCC. */
- if (def->base.group == subdef->base.group) continue;
-
- /* |= to avoid short-circuit; we need its side-effects. */
- need_dup |= upb_resolve_dfs(subdef, addtab, new_owner, seen, s);
- if (!upb_ok(s)) return false;
- }
- }
- } while ((def = (upb_def*)def->base.next) != base);
-
- if (need_dup) {
- /* Dup all defs in this SCC that don't already have entries in addtab. */
- def = base;
- do {
- const char *name;
-
- if (def->type == UPB_DEF_FIELD) continue;
- name = upb_def_fullname(def);
- if (!upb_strtable_lookup(addtab, name, NULL)) {
- upb_def *newdef = upb_def_dup(def, new_owner);
- if (!newdef) goto oom;
- newdef->came_from_user = false;
- if (!upb_strtable_insert(addtab, name, upb_value_ptr(newdef)))
- goto oom;
- }
- } while ((def = (upb_def*)def->base.next) != base);
- }
-
- upb_inttable_insertptr(seen, memoize_key, upb_value_bool(need_dup));
- return need_dup;
-
-oom:
- upb_status_seterrmsg(s, "out of memory");
- return false;
-}
-
-/* TODO(haberman): we need a lot more testing of error conditions.
- * The came_from_user stuff in particular is not tested. */
-static bool symtab_add(upb_symtab *s, upb_def *const*defs, size_t n,
- void *ref_donor, upb_refcounted *freeze_also,
- upb_status *status) {
- size_t i;
- size_t add_n;
- size_t freeze_n;
- upb_strtable_iter iter;
- upb_refcounted **add_objs = NULL;
- upb_def **add_defs = NULL;
- size_t add_objs_size;
- upb_strtable addtab;
- upb_inttable seen;
-
- if (n == 0 && !freeze_also) {
- return true;
- }
-
- assert(!upb_symtab_isfrozen(s));
- if (!upb_strtable_init(&addtab, UPB_CTYPE_PTR)) {
- upb_status_seterrmsg(status, "out of memory");
- return false;
- }
-
- /* Add new defs to our "add" set. */
- for (i = 0; i < n; i++) {
- upb_def *def = defs[i];
- const char *fullname;
- upb_fielddef *f;
-
- if (upb_def_isfrozen(def)) {
- upb_status_seterrmsg(status, "added defs must be mutable");
- goto err;
- }
- assert(!upb_def_isfrozen(def));
- fullname = upb_def_fullname(def);
- if (!fullname) {
- upb_status_seterrmsg(
- status, "Anonymous defs cannot be added to a symtab");
- goto err;
- }
-
- f = upb_dyncast_fielddef_mutable(def);
-
- if (f) {
- if (!upb_fielddef_containingtypename(f)) {
- upb_status_seterrmsg(status,
- "Standalone fielddefs must have a containing type "
- "(extendee) name set");
- goto err;
- }
- } else {
- if (upb_strtable_lookup(&addtab, fullname, NULL)) {
- upb_status_seterrf(status, "Conflicting defs named '%s'", fullname);
- goto err;
- }
- /* We need this to back out properly, because if there is a failure we
- * need to donate the ref back to the caller. */
- def->came_from_user = true;
- upb_def_donateref(def, ref_donor, s);
- if (!upb_strtable_insert(&addtab, fullname, upb_value_ptr(def)))
- goto oom_err;
- }
- }
-
- /* Add standalone fielddefs (ie. extensions) to the appropriate messages.
- * If the appropriate message only exists in the existing symtab, duplicate
- * it so we have a mutable copy we can add the fields to. */
- for (i = 0; i < n; i++) {
- upb_def *def = defs[i];
- upb_fielddef *f = upb_dyncast_fielddef_mutable(def);
- const char *msgname;
- upb_value v;
- upb_msgdef *m;
-
- if (!f) continue;
- msgname = upb_fielddef_containingtypename(f);
- /* We validated this earlier in this function. */
- assert(msgname);
-
- /* If the extendee name is absolutely qualified, move past the initial ".".
- * TODO(haberman): it is not obvious what it would mean if this was not
- * absolutely qualified. */
- if (msgname[0] == '.') {
- msgname++;
- }
-
- if (upb_strtable_lookup(&addtab, msgname, &v)) {
- /* Extendee is in the set of defs the user asked us to add. */
- m = upb_value_getptr(v);
- } else {
- /* Need to find and dup the extendee from the existing symtab. */
- const upb_msgdef *frozen_m = upb_symtab_lookupmsg(s, msgname);
- if (!frozen_m) {
- upb_status_seterrf(status,
- "Tried to extend message %s that does not exist "
- "in this SymbolTable.",
- msgname);
- goto err;
- }
- m = upb_msgdef_dup(frozen_m, s);
- if (!m) goto oom_err;
- if (!upb_strtable_insert(&addtab, msgname, upb_value_ptr(m))) {
- upb_msgdef_unref(m, s);
- goto oom_err;
- }
- }
-
- if (!upb_msgdef_addfield(m, f, ref_donor, status)) {
- goto err;
- }
- }
-
- /* Add dups of any existing def that can reach a def with the same name as
- * anything in our "add" set. */
- if (!upb_inttable_init(&seen, UPB_CTYPE_BOOL)) goto oom_err;
- upb_strtable_begin(&iter, &s->symtab);
- for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
- upb_def *def = upb_value_getptr(upb_strtable_iter_value(&iter));
- upb_resolve_dfs(def, &addtab, s, &seen, status);
- if (!upb_ok(status)) goto err;
- }
- upb_inttable_uninit(&seen);
-
- /* Now using the table, resolve symbolic references for subdefs. */
- upb_strtable_begin(&iter, &addtab);
- for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
- const char *base;
- upb_def *def = upb_value_getptr(upb_strtable_iter_value(&iter));
- upb_msgdef *m = upb_dyncast_msgdef_mutable(def);
- upb_msg_field_iter j;
-
- if (!m) continue;
- /* Type names are resolved relative to the message in which they appear. */
- base = upb_msgdef_fullname(m);
-
- for(upb_msg_field_begin(&j, m);
- !upb_msg_field_done(&j);
- upb_msg_field_next(&j)) {
- upb_fielddef *f = upb_msg_iter_field(&j);
- const char *name = upb_fielddef_subdefname(f);
- if (name && !upb_fielddef_subdef(f)) {
- /* Try the lookup in the current set of to-be-added defs first. If not
- * there, try existing defs. */
- upb_def *subdef = upb_resolvename(&addtab, base, name);
- if (subdef == NULL) {
- subdef = upb_resolvename(&s->symtab, base, name);
- }
- if (subdef == NULL) {
- upb_status_seterrf(
- status, "couldn't resolve name '%s' in message '%s'", name, base);
- goto err;
- } else if (!upb_fielddef_setsubdef(f, subdef, status)) {
- goto err;
- }
- }
- }
- }
-
- /* We need an array of the defs in addtab, for passing to
- * upb_refcounted_freeze(). */
- add_objs_size = upb_strtable_count(&addtab);
- if (freeze_also) {
- add_objs_size++;
- }
-
- add_defs = upb_gmalloc(sizeof(void*) * add_objs_size);
- if (add_defs == NULL) goto oom_err;
- upb_strtable_begin(&iter, &addtab);
- for (add_n = 0; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
- add_defs[add_n++] = upb_value_getptr(upb_strtable_iter_value(&iter));
- }
-
- /* Validate defs. */
- if (!_upb_def_validate(add_defs, add_n, status)) {
- goto err;
- }
-
- /* Cheat a little and give the array a new type.
- * This is probably undefined behavior, but this code will be deleted soon. */
- add_objs = (upb_refcounted**)add_defs;
-
- freeze_n = add_n;
- if (freeze_also) {
- add_objs[freeze_n++] = freeze_also;
- }
-
- if (!upb_refcounted_freeze(add_objs, freeze_n, status,
- UPB_MAX_MESSAGE_DEPTH * 2)) {
- goto err;
- }
-
- /* This must be delayed until all errors have been detected, since error
- * recovery code uses this table to cleanup defs. */
- upb_strtable_uninit(&addtab);
-
- /* TODO(haberman) we don't properly handle errors after this point (like
- * OOM in upb_strtable_insert() below). */
- for (i = 0; i < add_n; i++) {
- upb_def *def = (upb_def*)add_objs[i];
- const char *name = upb_def_fullname(def);
- upb_value v;
- bool success;
-
- if (upb_strtable_remove(&s->symtab, name, &v)) {
- const upb_def *def = upb_value_getptr(v);
- upb_def_unref(def, s);
- }
- success = upb_strtable_insert(&s->symtab, name, upb_value_ptr(def));
- UPB_ASSERT_VAR(success, success == true);
- }
- upb_gfree(add_defs);
- return true;
+struct upb_bufsink {
+ upb_byteshandler handler;
+ upb_bytessink sink;
+ upb_env *env;
+ char *ptr;
+ size_t len, size;
+};
-oom_err:
- upb_status_seterrmsg(status, "out of memory");
-err: {
- /* For defs the user passed in, we need to donate the refs back. For defs
- * we dup'd, we need to just unref them. */
- upb_strtable_begin(&iter, &addtab);
- for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
- upb_def *def = upb_value_getptr(upb_strtable_iter_value(&iter));
- bool came_from_user = def->came_from_user;
- def->came_from_user = false;
- if (came_from_user) {
- upb_def_donateref(def, s, ref_donor);
- } else {
- upb_def_unref(def, s);
- }
- }
- }
- upb_strtable_uninit(&addtab);
- upb_gfree(add_defs);
- assert(!upb_ok(status));
- return false;
+static void *upb_bufsink_start(void *_sink, const void *hd, size_t size_hint) {
+ upb_bufsink *sink = _sink;
+ UPB_UNUSED(hd);
+ UPB_UNUSED(size_hint);
+ sink->len = 0;
+ return sink;
}
-bool upb_symtab_add(upb_symtab *s, upb_def *const*defs, size_t n,
- void *ref_donor, upb_status *status) {
- return symtab_add(s, defs, n, ref_donor, NULL, status);
-}
+static size_t upb_bufsink_string(void *_sink, const void *hd, const char *ptr,
+ size_t len, const upb_bufhandle *handle) {
+ upb_bufsink *sink = _sink;
+ size_t new_size = sink->size;
-bool upb_symtab_addfile(upb_symtab *s, upb_filedef *file, upb_status *status) {
- size_t n;
- size_t i;
- upb_def **defs;
- bool ret;
-
- n = upb_filedef_defcount(file);
- defs = upb_gmalloc(sizeof(*defs) * n);
+ UPB_ASSERT(new_size > 0);
+ UPB_UNUSED(hd);
+ UPB_UNUSED(handle);
- if (defs == NULL) {
- upb_status_seterrmsg(status, "Out of memory");
- return false;
+ while (sink->len + len > new_size) {
+ new_size *= 2;
}
- for (i = 0; i < n; i++) {
- defs[i] = upb_filedef_mutabledef(file, i);
+ if (new_size != sink->size) {
+ sink->ptr = upb_env_realloc(sink->env, sink->ptr, sink->size, new_size);
+ sink->size = new_size;
}
- ret = symtab_add(s, defs, n, NULL, upb_filedef_upcast_mutable(file), status);
+ memcpy(sink->ptr + sink->len, ptr, len);
+ sink->len += len;
- upb_gfree(defs);
- return ret;
+ return len;
}
-/* Iteration. */
+upb_bufsink *upb_bufsink_new(upb_env *env) {
+ upb_bufsink *sink = upb_env_malloc(env, sizeof(upb_bufsink));
+ upb_byteshandler_init(&sink->handler);
+ upb_byteshandler_setstartstr(&sink->handler, upb_bufsink_start, NULL);
+ upb_byteshandler_setstring(&sink->handler, upb_bufsink_string, NULL);
-static void advance_to_matching(upb_symtab_iter *iter) {
- if (iter->type == UPB_DEF_ANY)
- return;
+ upb_bytessink_reset(&sink->sink, &sink->handler, sink);
- while (!upb_strtable_done(&iter->iter) &&
- iter->type != upb_symtab_iter_def(iter)->type) {
- upb_strtable_next(&iter->iter);
- }
-}
+ sink->env = env;
+ sink->size = 32;
+ sink->ptr = upb_env_malloc(env, sink->size);
+ sink->len = 0;
-void upb_symtab_begin(upb_symtab_iter *iter, const upb_symtab *s,
- upb_deftype_t type) {
- upb_strtable_begin(&iter->iter, &s->symtab);
- iter->type = type;
- advance_to_matching(iter);
+ return sink;
}
-void upb_symtab_next(upb_symtab_iter *iter) {
- upb_strtable_next(&iter->iter);
- advance_to_matching(iter);
+void upb_bufsink_free(upb_bufsink *sink) {
+ upb_env_free(sink->env, sink->ptr);
+ upb_env_free(sink->env, sink);
}
-bool upb_symtab_done(const upb_symtab_iter *iter) {
- return upb_strtable_done(&iter->iter);
+upb_bytessink *upb_bufsink_sink(upb_bufsink *sink) {
+ return &sink->sink;
}
-const upb_def *upb_symtab_iter_def(const upb_symtab_iter *iter) {
- return upb_value_getptr(upb_strtable_iter_value(&iter->iter));
+const char *upb_bufsink_getdata(const upb_bufsink *sink, size_t *len) {
+ *len = sink->len;
+ return sink->ptr;
}
/*
** upb_table Implementation
@@ -4244,16 +6169,11 @@ const upb_def *upb_symtab_iter_def(const upb_symtab_iter *iter) {
#define ARRAY_SIZE(x) \
((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
-#ifdef NDEBUG
static void upb_check_alloc(upb_table *t, upb_alloc *a) {
UPB_UNUSED(t);
UPB_UNUSED(a);
+ UPB_ASSERT_DEBUGVAR(t->alloc == a);
}
-#else
-static void upb_check_alloc(upb_table *t, upb_alloc *a) {
- assert(t->alloc == a);
-}
-#endif
static const double MAX_LOAD = 0.85;
@@ -4362,7 +6282,7 @@ static void uninit(upb_table *t, upb_alloc *a) {
static upb_tabent *emptyent(upb_table *t) {
upb_tabent *e = mutable_entries(t) + upb_table_size(t);
- while (1) { if (upb_tabent_isempty(--e)) return e; assert(e > t->entries); }
+ while (1) { if (upb_tabent_isempty(--e)) return e; UPB_ASSERT(e > t->entries); }
}
static upb_tabent *getentry_mutable(upb_table *t, uint32_t hash) {
@@ -4407,10 +6327,8 @@ static void insert(upb_table *t, lookupkey_t key, upb_tabkey tabkey,
upb_tabent *mainpos_e;
upb_tabent *our_e;
- UPB_UNUSED(eql);
- UPB_UNUSED(key);
- assert(findentry(t, key, hash, eql) == NULL);
- assert(val.ctype == t->ctype);
+ UPB_ASSERT(findentry(t, key, hash, eql) == NULL);
+ UPB_ASSERT_DEBUGVAR(val.ctype == t->ctype);
t->count++;
mainpos_e = getentry_mutable(t, hash);
@@ -4437,7 +6355,7 @@ static void insert(upb_table *t, lookupkey_t key, upb_tabkey tabkey,
*new_e = *mainpos_e; /* copies next. */
while (chain->next != mainpos_e) {
chain = (upb_tabent*)chain->next;
- assert(chain);
+ UPB_ASSERT(chain);
}
chain->next = new_e;
our_e = mainpos_e;
@@ -4446,7 +6364,7 @@ static void insert(upb_table *t, lookupkey_t key, upb_tabkey tabkey,
}
our_e->key = tabkey;
our_e->val.val = val.val;
- assert(findentry(t, key, hash, eql) == our_e);
+ UPB_ASSERT(findentry(t, key, hash, eql) == our_e);
}
static bool rm(upb_table *t, lookupkey_t key, upb_value *val,
@@ -4456,38 +6374,33 @@ static bool rm(upb_table *t, lookupkey_t key, upb_value *val,
if (eql(chain->key, key)) {
/* Element to remove is at the head of its chain. */
t->count--;
- if (val) {
- _upb_value_setval(val, chain->val.val, t->ctype);
- }
+ if (val) _upb_value_setval(val, chain->val.val, t->ctype);
+ if (removed) *removed = chain->key;
if (chain->next) {
upb_tabent *move = (upb_tabent*)chain->next;
*chain = *move;
- if (removed) *removed = move->key;
move->key = 0; /* Make the slot empty. */
} else {
- if (removed) *removed = chain->key;
chain->key = 0; /* Make the slot empty. */
}
return true;
} else {
/* Element to remove is either in a non-head position or not in the
* table. */
- while (chain->next && !eql(chain->next->key, key))
+ while (chain->next && !eql(chain->next->key, key)) {
chain = (upb_tabent*)chain->next;
+ }
if (chain->next) {
/* Found element to remove. */
- upb_tabent *rm;
-
- if (val) {
- _upb_value_setval(val, chain->next->val.val, t->ctype);
- }
- rm = (upb_tabent*)chain->next;
+ upb_tabent *rm = (upb_tabent*)chain->next;
+ t->count--;
+ if (val) _upb_value_setval(val, chain->next->val.val, t->ctype);
if (removed) *removed = rm->key;
- rm->key = 0;
+ rm->key = 0; /* Make the slot empty. */
chain->next = rm->next;
- t->count--;
return true;
} else {
+ /* Element to remove is not in the table. */
return false;
}
}
@@ -4596,7 +6509,7 @@ bool upb_strtable_lookup2(const upb_strtable *t, const char *key, size_t len,
bool upb_strtable_remove3(upb_strtable *t, const char *key, size_t len,
upb_value *val, upb_alloc *alloc) {
- uint32_t hash = MurmurHash2(key, strlen(key), 0);
+ uint32_t hash = MurmurHash2(key, len, 0);
upb_tabkey tabkey;
if (rm(&t->t, strkey2(key, len), val, &tabkey, hash, &streql)) {
upb_free(alloc, (void*)tabkey);
@@ -4627,19 +6540,19 @@ bool upb_strtable_done(const upb_strtable_iter *i) {
}
const char *upb_strtable_iter_key(const upb_strtable_iter *i) {
- assert(!upb_strtable_done(i));
+ UPB_ASSERT(!upb_strtable_done(i));
return upb_tabstr(str_tabent(i)->key, NULL);
}
size_t upb_strtable_iter_keylength(const upb_strtable_iter *i) {
uint32_t len;
- assert(!upb_strtable_done(i));
+ UPB_ASSERT(!upb_strtable_done(i));
upb_tabstr(str_tabent(i)->key, &len);
return len;
}
upb_value upb_strtable_iter_value(const upb_strtable_iter *i) {
- assert(!upb_strtable_done(i));
+ UPB_ASSERT(!upb_strtable_done(i));
return _upb_value_val(str_tabent(i)->val.val, i->t->t.ctype);
}
@@ -4698,9 +6611,9 @@ static void check(upb_inttable *t) {
upb_inttable_iter i;
upb_inttable_begin(&i, t);
for(; !upb_inttable_done(&i); upb_inttable_next(&i), count++) {
- assert(upb_inttable_lookup(t, upb_inttable_iter_key(&i), NULL));
+ UPB_ASSERT(upb_inttable_lookup(t, upb_inttable_iter_key(&i), NULL));
}
- assert(count == upb_inttable_count(t));
+ UPB_ASSERT(count == upb_inttable_count(t));
}
#endif
}
@@ -4738,13 +6651,12 @@ bool upb_inttable_insert2(upb_inttable *t, uintptr_t key, upb_value val,
upb_alloc *a) {
upb_tabval tabval;
tabval.val = val.val;
- UPB_UNUSED(tabval);
- assert(upb_arrhas(tabval)); /* This will reject (uint64_t)-1. Fix this. */
+ UPB_ASSERT(upb_arrhas(tabval)); /* This will reject (uint64_t)-1. Fix this. */
upb_check_alloc(&t->t, a);
if (key < t->array_size) {
- assert(!upb_arrhas(t->array[key]));
+ UPB_ASSERT(!upb_arrhas(t->array[key]));
t->array_count++;
mutable_array(t)[key].val = val.val;
} else {
@@ -4767,7 +6679,7 @@ bool upb_inttable_insert2(upb_inttable *t, uintptr_t key, upb_value val,
insert(&new_table, intkey(e->key), e->key, v, hash, &inthash, &inteql);
}
- assert(t->t.count == new_table.count);
+ UPB_ASSERT(t->t.count == new_table.count);
uninit(&t->t, a);
t->t = new_table;
@@ -4807,9 +6719,7 @@ bool upb_inttable_remove(upb_inttable *t, uintptr_t key, upb_value *val) {
success = false;
}
} else {
- upb_tabkey removed;
- uint32_t hash = upb_inthash(key);
- success = rm(&t->t, intkey(key), val, &removed, hash, &inteql);
+ success = rm(&t->t, intkey(key), val, NULL, upb_inthash(key), &inteql);
}
check(t);
return success;
@@ -4823,7 +6733,7 @@ bool upb_inttable_push2(upb_inttable *t, upb_value val, upb_alloc *a) {
upb_value upb_inttable_pop(upb_inttable *t) {
upb_value val;
bool ok = upb_inttable_remove(t, upb_inttable_count(t) - 1, &val);
- UPB_ASSERT_VAR(ok, ok);
+ UPB_ASSERT(ok);
return val;
}
@@ -4879,7 +6789,7 @@ void upb_inttable_compact2(upb_inttable *t, upb_alloc *a) {
arr_count -= counts[size_lg2];
}
- assert(arr_count <= upb_inttable_count(t));
+ UPB_ASSERT(arr_count <= upb_inttable_count(t));
{
/* Insert all elements into new, perfectly-sized table. */
@@ -4894,8 +6804,8 @@ void upb_inttable_compact2(upb_inttable *t, upb_alloc *a) {
uintptr_t k = upb_inttable_iter_key(&i);
upb_inttable_insert2(&new_t, k, upb_inttable_iter_value(&i), a);
}
- assert(new_t.array_size == arr_size);
- assert(new_t.t.size_lg2 == hashsize_lg2);
+ UPB_ASSERT(new_t.array_size == arr_size);
+ UPB_ASSERT(new_t.t.size_lg2 == hashsize_lg2);
}
upb_inttable_uninit2(t, a);
*t = new_t;
@@ -4904,12 +6814,12 @@ void upb_inttable_compact2(upb_inttable *t, upb_alloc *a) {
/* Iteration. */
static const upb_tabent *int_tabent(const upb_inttable_iter *i) {
- assert(!i->array_part);
+ UPB_ASSERT(!i->array_part);
return &i->t->t.entries[i->index];
}
static upb_tabval int_arrent(const upb_inttable_iter *i) {
- assert(i->array_part);
+ UPB_ASSERT(i->array_part);
return i->t->array[i->index];
}
@@ -4946,12 +6856,12 @@ bool upb_inttable_done(const upb_inttable_iter *i) {
}
uintptr_t upb_inttable_iter_key(const upb_inttable_iter *i) {
- assert(!upb_inttable_done(i));
+ UPB_ASSERT(!upb_inttable_done(i));
return i->array_part ? i->index : int_tabent(i)->key;
}
upb_value upb_inttable_iter_value(const upb_inttable_iter *i) {
- assert(!upb_inttable_done(i));
+ UPB_ASSERT(!upb_inttable_done(i));
return _upb_value_val(
i->array_part ? i->t->array[i->index].val : int_tabent(i)->val.val,
i->t->t.ctype);
@@ -5169,7 +7079,7 @@ bool upb_dumptostderr(void *closure, const upb_status* status) {
static void nullz(upb_status *status) {
const char *ellipsis = "...";
size_t len = strlen(ellipsis);
- assert(sizeof(status->msg) > len);
+ UPB_ASSERT(sizeof(status->msg) > len);
memcpy(status->msg + sizeof(status->msg) - len, ellipsis, len);
}
@@ -5252,7 +7162,7 @@ upb_alloc upb_alloc_global = {&upb_global_allocfunc};
/* Be conservative and choose 16 in case anyone is using SSE. */
static const size_t maxalign = 16;
-static size_t align_up(size_t size) {
+static size_t align_up_max(size_t size) {
return ((size + maxalign - 1) / maxalign) * maxalign;
}
@@ -5276,7 +7186,7 @@ static void upb_arena_addblock(upb_arena *a, void *ptr, size_t size,
block->next = a->block_head;
block->size = size;
- block->used = align_up(sizeof(mem_block));
+ block->used = align_up_max(sizeof(mem_block));
block->owned = owned;
a->block_head = block;
@@ -5309,7 +7219,7 @@ static void *upb_arena_doalloc(upb_alloc *alloc, void *ptr, size_t oldsize,
return NULL; /* We are an arena, don't need individual frees. */
}
- size = align_up(size);
+ size = align_up_max(size);
/* TODO(haberman): special-case if this is a realloc of the last alloc? */
@@ -5379,6 +7289,10 @@ void upb_arena_uninit(upb_arena *a) {
block = next;
}
+
+ /* Protect against multiple-uninit. */
+ a->cleanup_head = NULL;
+ a->block_head = NULL;
}
bool upb_arena_addcleanup(upb_arena *a, upb_cleanup_func *func, void *ud) {
@@ -5479,166 +7393,166 @@ size_t upb_env_bytesallocated(const upb_env *e) {
* Do not edit -- your changes will be discarded when the file is
* regenerated. */
-#include <assert.h>
-
static const upb_msgdef msgs[22];
-static const upb_fielddef fields[105];
+static const upb_fielddef fields[107];
static const upb_enumdef enums[5];
static const upb_tabent strentries[236];
static const upb_tabent intentries[18];
-static const upb_tabval arrays[184];
+static const upb_tabval arrays[187];
#ifdef UPB_DEBUG_REFS
-static upb_inttable reftables[264];
+static upb_inttable reftables[268];
#endif
static const upb_msgdef msgs[22] = {
- UPB_MSGDEF_INIT("google.protobuf.DescriptorProto", 40, 8, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[0], 11, 10), UPB_STRTABLE_INIT(10, 15, UPB_CTYPE_PTR, 4, &strentries[0]), false, UPB_SYNTAX_PROTO2, &reftables[0], &reftables[1]),
- UPB_MSGDEF_INIT("google.protobuf.DescriptorProto.ExtensionRange", 4, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[11], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[16]), false, UPB_SYNTAX_PROTO2, &reftables[2], &reftables[3]),
- UPB_MSGDEF_INIT("google.protobuf.DescriptorProto.ReservedRange", 4, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[14], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[20]), false, UPB_SYNTAX_PROTO2, &reftables[4], &reftables[5]),
- UPB_MSGDEF_INIT("google.protobuf.EnumDescriptorProto", 11, 2, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[17], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[24]), false, UPB_SYNTAX_PROTO2, &reftables[6], &reftables[7]),
- UPB_MSGDEF_INIT("google.protobuf.EnumOptions", 8, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[0], &arrays[21], 4, 2), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[28]), false, UPB_SYNTAX_PROTO2, &reftables[8], &reftables[9]),
- UPB_MSGDEF_INIT("google.protobuf.EnumValueDescriptorProto", 8, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[25], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[32]), false, UPB_SYNTAX_PROTO2, &reftables[10], &reftables[11]),
- UPB_MSGDEF_INIT("google.protobuf.EnumValueOptions", 7, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[2], &arrays[29], 2, 1), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[36]), false, UPB_SYNTAX_PROTO2, &reftables[12], &reftables[13]),
- UPB_MSGDEF_INIT("google.protobuf.FieldDescriptorProto", 23, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[31], 11, 10), UPB_STRTABLE_INIT(10, 15, UPB_CTYPE_PTR, 4, &strentries[40]), false, UPB_SYNTAX_PROTO2, &reftables[14], &reftables[15]),
- UPB_MSGDEF_INIT("google.protobuf.FieldOptions", 12, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[4], &arrays[42], 11, 6), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[56]), false, UPB_SYNTAX_PROTO2, &reftables[16], &reftables[17]),
- UPB_MSGDEF_INIT("google.protobuf.FileDescriptorProto", 42, 6, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[53], 13, 12), UPB_STRTABLE_INIT(12, 15, UPB_CTYPE_PTR, 4, &strentries[72]), false, UPB_SYNTAX_PROTO2, &reftables[18], &reftables[19]),
- UPB_MSGDEF_INIT("google.protobuf.FileDescriptorSet", 6, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[66], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[88]), false, UPB_SYNTAX_PROTO2, &reftables[20], &reftables[21]),
- UPB_MSGDEF_INIT("google.protobuf.FileOptions", 31, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[6], &arrays[68], 39, 15), UPB_STRTABLE_INIT(16, 31, UPB_CTYPE_PTR, 5, &strentries[92]), false, UPB_SYNTAX_PROTO2, &reftables[22], &reftables[23]),
- UPB_MSGDEF_INIT("google.protobuf.MessageOptions", 10, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[8], &arrays[107], 8, 4), UPB_STRTABLE_INIT(5, 7, UPB_CTYPE_PTR, 3, &strentries[124]), false, UPB_SYNTAX_PROTO2, &reftables[24], &reftables[25]),
- UPB_MSGDEF_INIT("google.protobuf.MethodDescriptorProto", 15, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[115], 7, 6), UPB_STRTABLE_INIT(6, 7, UPB_CTYPE_PTR, 3, &strentries[132]), false, UPB_SYNTAX_PROTO2, &reftables[26], &reftables[27]),
- UPB_MSGDEF_INIT("google.protobuf.MethodOptions", 7, 1, UPB_INTTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &intentries[10], &arrays[122], 1, 0), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[140]), false, UPB_SYNTAX_PROTO2, &reftables[28], &reftables[29]),
- UPB_MSGDEF_INIT("google.protobuf.OneofDescriptorProto", 5, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[123], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[144]), false, UPB_SYNTAX_PROTO2, &reftables[30], &reftables[31]),
- UPB_MSGDEF_INIT("google.protobuf.ServiceDescriptorProto", 11, 2, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[125], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[148]), false, UPB_SYNTAX_PROTO2, &reftables[32], &reftables[33]),
- UPB_MSGDEF_INIT("google.protobuf.ServiceOptions", 7, 1, UPB_INTTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &intentries[14], &arrays[129], 1, 0), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[152]), false, UPB_SYNTAX_PROTO2, &reftables[34], &reftables[35]),
- UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo", 6, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[130], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[156]), false, UPB_SYNTAX_PROTO2, &reftables[36], &reftables[37]),
- UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo.Location", 19, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[132], 7, 5), UPB_STRTABLE_INIT(5, 7, UPB_CTYPE_PTR, 3, &strentries[160]), false, UPB_SYNTAX_PROTO2, &reftables[38], &reftables[39]),
- UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption", 18, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[139], 9, 7), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[168]), false, UPB_SYNTAX_PROTO2, &reftables[40], &reftables[41]),
- UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption.NamePart", 6, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[148], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[184]), false, UPB_SYNTAX_PROTO2, &reftables[42], &reftables[43]),
+ UPB_MSGDEF_INIT("google.protobuf.DescriptorProto", 41, 8, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[0], 11, 10), UPB_STRTABLE_INIT(10, 15, UPB_CTYPE_PTR, 4, &strentries[0]), false, UPB_SYNTAX_PROTO2, &reftables[0], &reftables[1]),
+ UPB_MSGDEF_INIT("google.protobuf.DescriptorProto.ExtensionRange", 5, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[11], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[16]), false, UPB_SYNTAX_PROTO2, &reftables[2], &reftables[3]),
+ UPB_MSGDEF_INIT("google.protobuf.DescriptorProto.ReservedRange", 5, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[14], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[20]), false, UPB_SYNTAX_PROTO2, &reftables[4], &reftables[5]),
+ UPB_MSGDEF_INIT("google.protobuf.EnumDescriptorProto", 12, 2, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[17], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[24]), false, UPB_SYNTAX_PROTO2, &reftables[6], &reftables[7]),
+ UPB_MSGDEF_INIT("google.protobuf.EnumOptions", 9, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[0], &arrays[21], 4, 2), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[28]), false, UPB_SYNTAX_PROTO2, &reftables[8], &reftables[9]),
+ UPB_MSGDEF_INIT("google.protobuf.EnumValueDescriptorProto", 9, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[25], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[32]), false, UPB_SYNTAX_PROTO2, &reftables[10], &reftables[11]),
+ UPB_MSGDEF_INIT("google.protobuf.EnumValueOptions", 8, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[2], &arrays[29], 2, 1), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[36]), false, UPB_SYNTAX_PROTO2, &reftables[12], &reftables[13]),
+ UPB_MSGDEF_INIT("google.protobuf.FieldDescriptorProto", 24, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[31], 11, 10), UPB_STRTABLE_INIT(10, 15, UPB_CTYPE_PTR, 4, &strentries[40]), false, UPB_SYNTAX_PROTO2, &reftables[14], &reftables[15]),
+ UPB_MSGDEF_INIT("google.protobuf.FieldOptions", 13, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[4], &arrays[42], 11, 6), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[56]), false, UPB_SYNTAX_PROTO2, &reftables[16], &reftables[17]),
+ UPB_MSGDEF_INIT("google.protobuf.FileDescriptorProto", 43, 6, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[53], 13, 12), UPB_STRTABLE_INIT(12, 15, UPB_CTYPE_PTR, 4, &strentries[72]), false, UPB_SYNTAX_PROTO2, &reftables[18], &reftables[19]),
+ UPB_MSGDEF_INIT("google.protobuf.FileDescriptorSet", 7, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[66], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[88]), false, UPB_SYNTAX_PROTO2, &reftables[20], &reftables[21]),
+ UPB_MSGDEF_INIT("google.protobuf.FileOptions", 38, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[6], &arrays[68], 42, 17), UPB_STRTABLE_INIT(18, 31, UPB_CTYPE_PTR, 5, &strentries[92]), false, UPB_SYNTAX_PROTO2, &reftables[22], &reftables[23]),
+ UPB_MSGDEF_INIT("google.protobuf.MessageOptions", 11, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[8], &arrays[110], 8, 4), UPB_STRTABLE_INIT(5, 7, UPB_CTYPE_PTR, 3, &strentries[124]), false, UPB_SYNTAX_PROTO2, &reftables[24], &reftables[25]),
+ UPB_MSGDEF_INIT("google.protobuf.MethodDescriptorProto", 16, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[118], 7, 6), UPB_STRTABLE_INIT(6, 7, UPB_CTYPE_PTR, 3, &strentries[132]), false, UPB_SYNTAX_PROTO2, &reftables[26], &reftables[27]),
+ UPB_MSGDEF_INIT("google.protobuf.MethodOptions", 8, 1, UPB_INTTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &intentries[10], &arrays[125], 1, 0), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[140]), false, UPB_SYNTAX_PROTO2, &reftables[28], &reftables[29]),
+ UPB_MSGDEF_INIT("google.protobuf.OneofDescriptorProto", 6, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[126], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[144]), false, UPB_SYNTAX_PROTO2, &reftables[30], &reftables[31]),
+ UPB_MSGDEF_INIT("google.protobuf.ServiceDescriptorProto", 12, 2, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[128], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[148]), false, UPB_SYNTAX_PROTO2, &reftables[32], &reftables[33]),
+ UPB_MSGDEF_INIT("google.protobuf.ServiceOptions", 8, 1, UPB_INTTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &intentries[14], &arrays[132], 1, 0), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[152]), false, UPB_SYNTAX_PROTO2, &reftables[34], &reftables[35]),
+ UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo", 7, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[133], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[156]), false, UPB_SYNTAX_PROTO2, &reftables[36], &reftables[37]),
+ UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo.Location", 20, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[135], 7, 5), UPB_STRTABLE_INIT(5, 7, UPB_CTYPE_PTR, 3, &strentries[160]), false, UPB_SYNTAX_PROTO2, &reftables[38], &reftables[39]),
+ UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption", 19, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[142], 9, 7), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[168]), false, UPB_SYNTAX_PROTO2, &reftables[40], &reftables[41]),
+ UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption.NamePart", 7, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[151], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[184]), false, UPB_SYNTAX_PROTO2, &reftables[42], &reftables[43]),
};
-static const upb_fielddef fields[105] = {
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "aggregate_value", 8, &msgs[20], NULL, 15, 6, {0},&reftables[44], &reftables[45]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "allow_alias", 2, &msgs[4], NULL, 6, 1, {0},&reftables[46], &reftables[47]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "cc_enable_arenas", 31, &msgs[11], NULL, 23, 12, {0},&reftables[48], &reftables[49]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "cc_generic_services", 16, &msgs[11], NULL, 17, 6, {0},&reftables[50], &reftables[51]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "client_streaming", 5, &msgs[13], NULL, 13, 4, {0},&reftables[52], &reftables[53]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "csharp_namespace", 37, &msgs[11], NULL, 27, 14, {0},&reftables[54], &reftables[55]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "ctype", 1, &msgs[8], (const upb_def*)(&enums[2]), 6, 1, {0},&reftables[56], &reftables[57]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "default_value", 7, &msgs[7], NULL, 16, 7, {0},&reftables[58], &reftables[59]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "dependency", 3, &msgs[9], NULL, 30, 8, {0},&reftables[60], &reftables[61]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[12], NULL, 8, 3, {0},&reftables[62], &reftables[63]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[8], NULL, 8, 3, {0},&reftables[64], &reftables[65]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 33, &msgs[14], NULL, 6, 1, {0},&reftables[66], &reftables[67]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 23, &msgs[11], NULL, 21, 10, {0},&reftables[68], &reftables[69]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[4], NULL, 7, 2, {0},&reftables[70], &reftables[71]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 33, &msgs[17], NULL, 6, 1, {0},&reftables[72], &reftables[73]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 1, &msgs[6], NULL, 6, 1, {0},&reftables[74], &reftables[75]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_DOUBLE, 0, false, false, false, false, "double_value", 6, &msgs[20], NULL, 11, 4, {0},&reftables[76], &reftables[77]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "end", 2, &msgs[2], NULL, 3, 1, {0},&reftables[78], &reftables[79]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "end", 2, &msgs[1], NULL, 3, 1, {0},&reftables[80], &reftables[81]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "enum_type", 4, &msgs[0], (const upb_def*)(&msgs[3]), 18, 2, {0},&reftables[82], &reftables[83]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "enum_type", 5, &msgs[9], (const upb_def*)(&msgs[3]), 13, 1, {0},&reftables[84], &reftables[85]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "extendee", 2, &msgs[7], NULL, 7, 2, {0},&reftables[86], &reftables[87]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension", 6, &msgs[0], (const upb_def*)(&msgs[7]), 24, 4, {0},&reftables[88], &reftables[89]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension", 7, &msgs[9], (const upb_def*)(&msgs[7]), 19, 3, {0},&reftables[90], &reftables[91]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension_range", 5, &msgs[0], (const upb_def*)(&msgs[1]), 21, 3, {0},&reftables[92], &reftables[93]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "field", 2, &msgs[0], (const upb_def*)(&msgs[7]), 12, 0, {0},&reftables[94], &reftables[95]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "file", 1, &msgs[10], (const upb_def*)(&msgs[9]), 5, 0, {0},&reftables[96], &reftables[97]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "go_package", 11, &msgs[11], NULL, 14, 5, {0},&reftables[98], &reftables[99]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "identifier_value", 3, &msgs[20], NULL, 6, 1, {0},&reftables[100], &reftables[101]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "input_type", 2, &msgs[13], NULL, 7, 2, {0},&reftables[102], &reftables[103]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REQUIRED, UPB_TYPE_BOOL, 0, false, false, false, false, "is_extension", 2, &msgs[21], NULL, 5, 1, {0},&reftables[104], &reftables[105]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_generate_equals_and_hash", 20, &msgs[11], NULL, 20, 9, {0},&reftables[106], &reftables[107]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_generic_services", 17, &msgs[11], NULL, 18, 7, {0},&reftables[108], &reftables[109]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_multiple_files", 10, &msgs[11], NULL, 13, 4, {0},&reftables[110], &reftables[111]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "java_outer_classname", 8, &msgs[11], NULL, 9, 2, {0},&reftables[112], &reftables[113]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "java_package", 1, &msgs[11], NULL, 6, 1, {0},&reftables[114], &reftables[115]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_string_check_utf8", 27, &msgs[11], NULL, 22, 11, {0},&reftables[116], &reftables[117]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "javanano_use_deprecated_package", 38, &msgs[11], NULL, 30, 15, {0},&reftables[118], &reftables[119]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "json_name", 10, &msgs[7], NULL, 20, 9, {0},&reftables[120], &reftables[121]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "jstype", 6, &msgs[8], (const upb_def*)(&enums[3]), 10, 5, {0},&reftables[122], &reftables[123]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "label", 4, &msgs[7], (const upb_def*)(&enums[0]), 11, 4, {0},&reftables[124], &reftables[125]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "lazy", 5, &msgs[8], NULL, 9, 4, {0},&reftables[126], &reftables[127]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "leading_comments", 3, &msgs[19], NULL, 8, 2, {0},&reftables[128], &reftables[129]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "leading_detached_comments", 6, &msgs[19], NULL, 16, 4, {0},&reftables[130], &reftables[131]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "location", 1, &msgs[18], (const upb_def*)(&msgs[19]), 5, 0, {0},&reftables[132], &reftables[133]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "map_entry", 7, &msgs[12], NULL, 9, 4, {0},&reftables[134], &reftables[135]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "message_set_wire_format", 1, &msgs[12], NULL, 6, 1, {0},&reftables[136], &reftables[137]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "message_type", 4, &msgs[9], (const upb_def*)(&msgs[0]), 10, 0, {0},&reftables[138], &reftables[139]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "method", 2, &msgs[16], (const upb_def*)(&msgs[13]), 6, 0, {0},&reftables[140], &reftables[141]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[3], NULL, 8, 2, {0},&reftables[142], &reftables[143]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[15], NULL, 2, 0, {0},&reftables[144], &reftables[145]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "name", 2, &msgs[20], (const upb_def*)(&msgs[21]), 5, 0, {0},&reftables[146], &reftables[147]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[0], NULL, 32, 8, {0},&reftables[148], &reftables[149]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[5], NULL, 4, 1, {0},&reftables[150], &reftables[151]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[9], NULL, 22, 6, {0},&reftables[152], &reftables[153]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[7], NULL, 4, 1, {0},&reftables[154], &reftables[155]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[13], NULL, 4, 1, {0},&reftables[156], &reftables[157]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[16], NULL, 8, 2, {0},&reftables[158], &reftables[159]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REQUIRED, UPB_TYPE_STRING, 0, false, false, false, false, "name_part", 1, &msgs[21], NULL, 2, 0, {0},&reftables[160], &reftables[161]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT64, UPB_INTFMT_VARIABLE, false, false, false, false, "negative_int_value", 5, &msgs[20], NULL, 10, 3, {0},&reftables[162], &reftables[163]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "nested_type", 3, &msgs[0], (const upb_def*)(&msgs[0]), 15, 1, {0},&reftables[164], &reftables[165]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "no_standard_descriptor_accessor", 2, &msgs[12], NULL, 7, 2, {0},&reftables[166], &reftables[167]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "number", 2, &msgs[5], NULL, 7, 2, {0},&reftables[168], &reftables[169]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "number", 3, &msgs[7], NULL, 10, 3, {0},&reftables[170], &reftables[171]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "objc_class_prefix", 36, &msgs[11], NULL, 24, 13, {0},&reftables[172], &reftables[173]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "oneof_decl", 8, &msgs[0], (const upb_def*)(&msgs[15]), 28, 6, {0},&reftables[174], &reftables[175]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "oneof_index", 9, &msgs[7], NULL, 19, 8, {0},&reftables[176], &reftables[177]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "optimize_for", 9, &msgs[11], (const upb_def*)(&enums[4]), 12, 3, {0},&reftables[178], &reftables[179]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 7, &msgs[0], (const upb_def*)(&msgs[12]), 25, 5, {0},&reftables[180], &reftables[181]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 8, &msgs[9], (const upb_def*)(&msgs[11]), 20, 4, {0},&reftables[182], &reftables[183]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 4, &msgs[13], (const upb_def*)(&msgs[14]), 3, 0, {0},&reftables[184], &reftables[185]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 8, &msgs[7], (const upb_def*)(&msgs[8]), 3, 0, {0},&reftables[186], &reftables[187]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[16], (const upb_def*)(&msgs[17]), 7, 1, {0},&reftables[188], &reftables[189]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[5], (const upb_def*)(&msgs[6]), 3, 0, {0},&reftables[190], &reftables[191]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[3], (const upb_def*)(&msgs[4]), 7, 1, {0},&reftables[192], &reftables[193]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "output_type", 3, &msgs[13], NULL, 10, 3, {0},&reftables[194], &reftables[195]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "package", 2, &msgs[9], NULL, 25, 7, {0},&reftables[196], &reftables[197]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "packed", 2, &msgs[8], NULL, 7, 2, {0},&reftables[198], &reftables[199]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, true, "path", 1, &msgs[19], NULL, 4, 0, {0},&reftables[200], &reftables[201]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_UINT64, UPB_INTFMT_VARIABLE, false, false, false, false, "positive_int_value", 4, &msgs[20], NULL, 9, 2, {0},&reftables[202], &reftables[203]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "public_dependency", 10, &msgs[9], NULL, 35, 9, {0},&reftables[204], &reftables[205]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "py_generic_services", 18, &msgs[11], NULL, 19, 8, {0},&reftables[206], &reftables[207]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "reserved_name", 10, &msgs[0], NULL, 37, 9, {0},&reftables[208], &reftables[209]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "reserved_range", 9, &msgs[0], (const upb_def*)(&msgs[2]), 31, 7, {0},&reftables[210], &reftables[211]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "server_streaming", 6, &msgs[13], NULL, 14, 5, {0},&reftables[212], &reftables[213]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "service", 6, &msgs[9], (const upb_def*)(&msgs[16]), 16, 2, {0},&reftables[214], &reftables[215]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "source_code_info", 9, &msgs[9], (const upb_def*)(&msgs[18]), 21, 5, {0},&reftables[216], &reftables[217]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, true, "span", 2, &msgs[19], NULL, 7, 1, {0},&reftables[218], &reftables[219]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "start", 1, &msgs[2], NULL, 2, 0, {0},&reftables[220], &reftables[221]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "start", 1, &msgs[1], NULL, 2, 0, {0},&reftables[222], &reftables[223]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BYTES, 0, false, false, false, false, "string_value", 7, &msgs[20], NULL, 12, 5, {0},&reftables[224], &reftables[225]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "syntax", 12, &msgs[9], NULL, 39, 11, {0},&reftables[226], &reftables[227]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "trailing_comments", 4, &msgs[19], NULL, 11, 3, {0},&reftables[228], &reftables[229]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "type", 5, &msgs[7], (const upb_def*)(&enums[1]), 12, 5, {0},&reftables[230], &reftables[231]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "type_name", 6, &msgs[7], NULL, 13, 6, {0},&reftables[232], &reftables[233]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[11], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[234], &reftables[235]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[12], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[236], &reftables[237]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[6], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[238], &reftables[239]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[4], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[240], &reftables[241]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[8], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[242], &reftables[243]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[14], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[244], &reftables[245]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[17], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[246], &reftables[247]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "value", 2, &msgs[3], (const upb_def*)(&msgs[5]), 6, 0, {0},&reftables[248], &reftables[249]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "weak", 10, &msgs[8], NULL, 11, 6, {0},&reftables[250], &reftables[251]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "weak_dependency", 11, &msgs[9], NULL, 38, 10, {0},&reftables[252], &reftables[253]),
+static const upb_fielddef fields[107] = {
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "aggregate_value", 8, &msgs[20], NULL, 16, 6, {0},&reftables[44], &reftables[45]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "allow_alias", 2, &msgs[4], NULL, 7, 1, {0},&reftables[46], &reftables[47]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "cc_enable_arenas", 31, &msgs[11], NULL, 24, 12, {0},&reftables[48], &reftables[49]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "cc_generic_services", 16, &msgs[11], NULL, 18, 6, {0},&reftables[50], &reftables[51]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "client_streaming", 5, &msgs[13], NULL, 14, 4, {0},&reftables[52], &reftables[53]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "csharp_namespace", 37, &msgs[11], NULL, 28, 14, {0},&reftables[54], &reftables[55]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "ctype", 1, &msgs[8], (const upb_def*)(&enums[2]), 7, 1, {0},&reftables[56], &reftables[57]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "default_value", 7, &msgs[7], NULL, 17, 7, {0},&reftables[58], &reftables[59]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "dependency", 3, &msgs[9], NULL, 31, 8, {0},&reftables[60], &reftables[61]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[8], NULL, 9, 3, {0},&reftables[62], &reftables[63]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 33, &msgs[14], NULL, 7, 1, {0},&reftables[64], &reftables[65]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[12], NULL, 9, 3, {0},&reftables[66], &reftables[67]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 23, &msgs[11], NULL, 22, 10, {0},&reftables[68], &reftables[69]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 1, &msgs[6], NULL, 7, 1, {0},&reftables[70], &reftables[71]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[4], NULL, 8, 2, {0},&reftables[72], &reftables[73]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 33, &msgs[17], NULL, 7, 1, {0},&reftables[74], &reftables[75]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_DOUBLE, 0, false, false, false, false, "double_value", 6, &msgs[20], NULL, 12, 4, {0},&reftables[76], &reftables[77]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "end", 2, &msgs[2], NULL, 4, 1, {0},&reftables[78], &reftables[79]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "end", 2, &msgs[1], NULL, 4, 1, {0},&reftables[80], &reftables[81]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "enum_type", 5, &msgs[9], (const upb_def*)(&msgs[3]), 14, 1, {0},&reftables[82], &reftables[83]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "enum_type", 4, &msgs[0], (const upb_def*)(&msgs[3]), 19, 2, {0},&reftables[84], &reftables[85]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "extendee", 2, &msgs[7], NULL, 8, 2, {0},&reftables[86], &reftables[87]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension", 6, &msgs[0], (const upb_def*)(&msgs[7]), 25, 4, {0},&reftables[88], &reftables[89]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension", 7, &msgs[9], (const upb_def*)(&msgs[7]), 20, 3, {0},&reftables[90], &reftables[91]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension_range", 5, &msgs[0], (const upb_def*)(&msgs[1]), 22, 3, {0},&reftables[92], &reftables[93]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "field", 2, &msgs[0], (const upb_def*)(&msgs[7]), 13, 0, {0},&reftables[94], &reftables[95]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "file", 1, &msgs[10], (const upb_def*)(&msgs[9]), 6, 0, {0},&reftables[96], &reftables[97]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "go_package", 11, &msgs[11], NULL, 15, 5, {0},&reftables[98], &reftables[99]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "identifier_value", 3, &msgs[20], NULL, 7, 1, {0},&reftables[100], &reftables[101]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "input_type", 2, &msgs[13], NULL, 8, 2, {0},&reftables[102], &reftables[103]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REQUIRED, UPB_TYPE_BOOL, 0, false, false, false, false, "is_extension", 2, &msgs[21], NULL, 6, 1, {0},&reftables[104], &reftables[105]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_generate_equals_and_hash", 20, &msgs[11], NULL, 21, 9, {0},&reftables[106], &reftables[107]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_generic_services", 17, &msgs[11], NULL, 19, 7, {0},&reftables[108], &reftables[109]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_multiple_files", 10, &msgs[11], NULL, 14, 4, {0},&reftables[110], &reftables[111]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "java_outer_classname", 8, &msgs[11], NULL, 10, 2, {0},&reftables[112], &reftables[113]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "java_package", 1, &msgs[11], NULL, 7, 1, {0},&reftables[114], &reftables[115]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_string_check_utf8", 27, &msgs[11], NULL, 23, 11, {0},&reftables[116], &reftables[117]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "javanano_use_deprecated_package", 38, &msgs[11], NULL, 31, 15, {0},&reftables[118], &reftables[119]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "json_name", 10, &msgs[7], NULL, 21, 9, {0},&reftables[120], &reftables[121]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "jstype", 6, &msgs[8], (const upb_def*)(&enums[3]), 11, 5, {0},&reftables[122], &reftables[123]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "label", 4, &msgs[7], (const upb_def*)(&enums[0]), 12, 4, {0},&reftables[124], &reftables[125]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "lazy", 5, &msgs[8], NULL, 10, 4, {0},&reftables[126], &reftables[127]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "leading_comments", 3, &msgs[19], NULL, 9, 2, {0},&reftables[128], &reftables[129]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "leading_detached_comments", 6, &msgs[19], NULL, 17, 4, {0},&reftables[130], &reftables[131]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "location", 1, &msgs[18], (const upb_def*)(&msgs[19]), 6, 0, {0},&reftables[132], &reftables[133]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "map_entry", 7, &msgs[12], NULL, 10, 4, {0},&reftables[134], &reftables[135]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "message_set_wire_format", 1, &msgs[12], NULL, 7, 1, {0},&reftables[136], &reftables[137]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "message_type", 4, &msgs[9], (const upb_def*)(&msgs[0]), 11, 0, {0},&reftables[138], &reftables[139]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "method", 2, &msgs[16], (const upb_def*)(&msgs[13]), 7, 0, {0},&reftables[140], &reftables[141]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "name", 2, &msgs[20], (const upb_def*)(&msgs[21]), 6, 0, {0},&reftables[142], &reftables[143]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[5], NULL, 5, 1, {0},&reftables[144], &reftables[145]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[9], NULL, 23, 6, {0},&reftables[146], &reftables[147]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[3], NULL, 9, 2, {0},&reftables[148], &reftables[149]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[16], NULL, 9, 2, {0},&reftables[150], &reftables[151]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[15], NULL, 3, 0, {0},&reftables[152], &reftables[153]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[13], NULL, 5, 1, {0},&reftables[154], &reftables[155]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[7], NULL, 5, 1, {0},&reftables[156], &reftables[157]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[0], NULL, 33, 8, {0},&reftables[158], &reftables[159]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REQUIRED, UPB_TYPE_STRING, 0, false, false, false, false, "name_part", 1, &msgs[21], NULL, 3, 0, {0},&reftables[160], &reftables[161]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT64, UPB_INTFMT_VARIABLE, false, false, false, false, "negative_int_value", 5, &msgs[20], NULL, 11, 3, {0},&reftables[162], &reftables[163]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "nested_type", 3, &msgs[0], (const upb_def*)(&msgs[0]), 16, 1, {0},&reftables[164], &reftables[165]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "no_standard_descriptor_accessor", 2, &msgs[12], NULL, 8, 2, {0},&reftables[166], &reftables[167]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "number", 3, &msgs[7], NULL, 11, 3, {0},&reftables[168], &reftables[169]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "number", 2, &msgs[5], NULL, 8, 2, {0},&reftables[170], &reftables[171]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "objc_class_prefix", 36, &msgs[11], NULL, 25, 13, {0},&reftables[172], &reftables[173]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "oneof_decl", 8, &msgs[0], (const upb_def*)(&msgs[15]), 29, 6, {0},&reftables[174], &reftables[175]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "oneof_index", 9, &msgs[7], NULL, 20, 8, {0},&reftables[176], &reftables[177]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "optimize_for", 9, &msgs[11], (const upb_def*)(&enums[4]), 13, 3, {0},&reftables[178], &reftables[179]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 7, &msgs[0], (const upb_def*)(&msgs[12]), 26, 5, {0},&reftables[180], &reftables[181]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 8, &msgs[9], (const upb_def*)(&msgs[11]), 21, 4, {0},&reftables[182], &reftables[183]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 8, &msgs[7], (const upb_def*)(&msgs[8]), 4, 0, {0},&reftables[184], &reftables[185]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 4, &msgs[13], (const upb_def*)(&msgs[14]), 4, 0, {0},&reftables[186], &reftables[187]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[16], (const upb_def*)(&msgs[17]), 8, 1, {0},&reftables[188], &reftables[189]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[3], (const upb_def*)(&msgs[4]), 8, 1, {0},&reftables[190], &reftables[191]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[5], (const upb_def*)(&msgs[6]), 4, 0, {0},&reftables[192], &reftables[193]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "output_type", 3, &msgs[13], NULL, 11, 3, {0},&reftables[194], &reftables[195]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "package", 2, &msgs[9], NULL, 26, 7, {0},&reftables[196], &reftables[197]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "packed", 2, &msgs[8], NULL, 8, 2, {0},&reftables[198], &reftables[199]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, true, "path", 1, &msgs[19], NULL, 5, 0, {0},&reftables[200], &reftables[201]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "php_class_prefix", 40, &msgs[11], NULL, 32, 16, {0},&reftables[202], &reftables[203]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "php_namespace", 41, &msgs[11], NULL, 35, 17, {0},&reftables[204], &reftables[205]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_UINT64, UPB_INTFMT_VARIABLE, false, false, false, false, "positive_int_value", 4, &msgs[20], NULL, 10, 2, {0},&reftables[206], &reftables[207]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "public_dependency", 10, &msgs[9], NULL, 36, 9, {0},&reftables[208], &reftables[209]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "py_generic_services", 18, &msgs[11], NULL, 20, 8, {0},&reftables[210], &reftables[211]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "reserved_name", 10, &msgs[0], NULL, 38, 9, {0},&reftables[212], &reftables[213]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "reserved_range", 9, &msgs[0], (const upb_def*)(&msgs[2]), 32, 7, {0},&reftables[214], &reftables[215]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "server_streaming", 6, &msgs[13], NULL, 15, 5, {0},&reftables[216], &reftables[217]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "service", 6, &msgs[9], (const upb_def*)(&msgs[16]), 17, 2, {0},&reftables[218], &reftables[219]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "source_code_info", 9, &msgs[9], (const upb_def*)(&msgs[18]), 22, 5, {0},&reftables[220], &reftables[221]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, true, "span", 2, &msgs[19], NULL, 8, 1, {0},&reftables[222], &reftables[223]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "start", 1, &msgs[2], NULL, 3, 0, {0},&reftables[224], &reftables[225]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "start", 1, &msgs[1], NULL, 3, 0, {0},&reftables[226], &reftables[227]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BYTES, 0, false, false, false, false, "string_value", 7, &msgs[20], NULL, 13, 5, {0},&reftables[228], &reftables[229]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "syntax", 12, &msgs[9], NULL, 40, 11, {0},&reftables[230], &reftables[231]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "trailing_comments", 4, &msgs[19], NULL, 12, 3, {0},&reftables[232], &reftables[233]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "type", 5, &msgs[7], (const upb_def*)(&enums[1]), 13, 5, {0},&reftables[234], &reftables[235]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "type_name", 6, &msgs[7], NULL, 14, 6, {0},&reftables[236], &reftables[237]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[12], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[238], &reftables[239]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[17], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[240], &reftables[241]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[11], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[242], &reftables[243]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[14], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[244], &reftables[245]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[8], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[246], &reftables[247]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[6], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[248], &reftables[249]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[4], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[250], &reftables[251]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "value", 2, &msgs[3], (const upb_def*)(&msgs[5]), 7, 0, {0},&reftables[252], &reftables[253]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "weak", 10, &msgs[8], NULL, 12, 6, {0},&reftables[254], &reftables[255]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "weak_dependency", 11, &msgs[9], NULL, 39, 10, {0},&reftables[256], &reftables[257]),
};
static const upb_enumdef enums[5] = {
- UPB_ENUMDEF_INIT("google.protobuf.FieldDescriptorProto.Label", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[188]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[151], 4, 3), 0, &reftables[254], &reftables[255]),
- UPB_ENUMDEF_INIT("google.protobuf.FieldDescriptorProto.Type", UPB_STRTABLE_INIT(18, 31, UPB_CTYPE_INT32, 5, &strentries[192]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[155], 19, 18), 0, &reftables[256], &reftables[257]),
- UPB_ENUMDEF_INIT("google.protobuf.FieldOptions.CType", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[224]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[174], 3, 3), 0, &reftables[258], &reftables[259]),
- UPB_ENUMDEF_INIT("google.protobuf.FieldOptions.JSType", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[228]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[177], 3, 3), 0, &reftables[260], &reftables[261]),
- UPB_ENUMDEF_INIT("google.protobuf.FileOptions.OptimizeMode", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[232]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[180], 4, 3), 0, &reftables[262], &reftables[263]),
+ UPB_ENUMDEF_INIT("google.protobuf.FieldDescriptorProto.Label", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[188]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[154], 4, 3), 0, &reftables[258], &reftables[259]),
+ UPB_ENUMDEF_INIT("google.protobuf.FieldDescriptorProto.Type", UPB_STRTABLE_INIT(18, 31, UPB_CTYPE_INT32, 5, &strentries[192]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[158], 19, 18), 0, &reftables[260], &reftables[261]),
+ UPB_ENUMDEF_INIT("google.protobuf.FieldOptions.CType", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[224]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[177], 3, 3), 0, &reftables[262], &reftables[263]),
+ UPB_ENUMDEF_INIT("google.protobuf.FieldOptions.JSType", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[228]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[180], 3, 3), 0, &reftables[264], &reftables[265]),
+ UPB_ENUMDEF_INIT("google.protobuf.FileOptions.OptimizeMode", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[232]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[183], 4, 3), 0, &reftables[266], &reftables[267]),
};
static const upb_tabent strentries[236] = {
{UPB_TABKEY_STR("\011", "\000", "\000", "\000", "extension"), UPB_TABVALUE_PTR_INIT(&fields[22]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "reserved_name"), UPB_TABVALUE_PTR_INIT(&fields[82]), NULL},
- {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[52]), NULL},
+ {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "reserved_name"), UPB_TABVALUE_PTR_INIT(&fields[84]), NULL},
+ {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[57]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
@@ -5647,53 +7561,53 @@ static const upb_tabent strentries[236] = {
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_STR("\013", "\000", "\000", "\000", "nested_type"), UPB_TABVALUE_PTR_INIT(&fields[60]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "reserved_range"), UPB_TABVALUE_PTR_INIT(&fields[83]), NULL},
+ {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "reserved_range"), UPB_TABVALUE_PTR_INIT(&fields[85]), NULL},
{UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[68]), NULL},
{UPB_TABKEY_STR("\012", "\000", "\000", "\000", "oneof_decl"), UPB_TABVALUE_PTR_INIT(&fields[65]), NULL},
- {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "enum_type"), UPB_TABVALUE_PTR_INIT(&fields[19]), &strentries[13]},
- {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "start"), UPB_TABVALUE_PTR_INIT(&fields[89]), NULL},
+ {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "enum_type"), UPB_TABVALUE_PTR_INIT(&fields[20]), &strentries[13]},
+ {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "start"), UPB_TABVALUE_PTR_INIT(&fields[91]), NULL},
{UPB_TABKEY_STR("\003", "\000", "\000", "\000", "end"), UPB_TABVALUE_PTR_INIT(&fields[18]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "start"), UPB_TABVALUE_PTR_INIT(&fields[88]), NULL},
+ {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "start"), UPB_TABVALUE_PTR_INIT(&fields[90]), NULL},
{UPB_TABKEY_STR("\003", "\000", "\000", "\000", "end"), UPB_TABVALUE_PTR_INIT(&fields[17]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "value"), UPB_TABVALUE_PTR_INIT(&fields[102]), NULL},
- {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[74]), NULL},
- {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[49]), &strentries[26]},
- {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[98]), NULL},
- {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[13]), NULL},
+ {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "value"), UPB_TABVALUE_PTR_INIT(&fields[104]), NULL},
+ {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[73]), NULL},
+ {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[52]), &strentries[26]},
+ {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[103]), NULL},
+ {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[14]), NULL},
{UPB_TABKEY_STR("\013", "\000", "\000", "\000", "allow_alias"), UPB_TABVALUE_PTR_INIT(&fields[1]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "number"), UPB_TABVALUE_PTR_INIT(&fields[62]), NULL},
+ {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "number"), UPB_TABVALUE_PTR_INIT(&fields[63]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[73]), NULL},
- {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[53]), &strentries[34]},
- {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[97]), NULL},
- {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[15]), NULL},
+ {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[74]), NULL},
+ {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[50]), &strentries[34]},
+ {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[102]), NULL},
+ {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[13]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_STR("\013", "\000", "\000", "\000", "oneof_index"), UPB_TABVALUE_PTR_INIT(&fields[66]), NULL},
{UPB_TABKEY_STR("\005", "\000", "\000", "\000", "label"), UPB_TABVALUE_PTR_INIT(&fields[40]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[55]), NULL},
+ {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[56]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "number"), UPB_TABVALUE_PTR_INIT(&fields[63]), &strentries[53]},
+ {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "number"), UPB_TABVALUE_PTR_INIT(&fields[62]), &strentries[53]},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_STR("\010", "\000", "\000", "\000", "extendee"), UPB_TABVALUE_PTR_INIT(&fields[21]), NULL},
- {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "type_name"), UPB_TABVALUE_PTR_INIT(&fields[94]), NULL},
+ {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "type_name"), UPB_TABVALUE_PTR_INIT(&fields[96]), NULL},
{UPB_TABKEY_STR("\011", "\000", "\000", "\000", "json_name"), UPB_TABVALUE_PTR_INIT(&fields[38]), NULL},
- {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "type"), UPB_TABVALUE_PTR_INIT(&fields[93]), &strentries[50]},
+ {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "type"), UPB_TABVALUE_PTR_INIT(&fields[95]), &strentries[50]},
{UPB_TABKEY_STR("\015", "\000", "\000", "\000", "default_value"), UPB_TABVALUE_PTR_INIT(&fields[7]), NULL},
- {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[71]), NULL},
- {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[99]), NULL},
+ {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[70]), NULL},
+ {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[101]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "weak"), UPB_TABVALUE_PTR_INIT(&fields[103]), NULL},
+ {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "weak"), UPB_TABVALUE_PTR_INIT(&fields[105]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
@@ -5704,25 +7618,25 @@ static const upb_tabent strentries[236] = {
{UPB_TABKEY_STR("\005", "\000", "\000", "\000", "ctype"), UPB_TABVALUE_PTR_INIT(&fields[6]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_STR("\006", "\000", "\000", "\000", "jstype"), UPB_TABVALUE_PTR_INIT(&fields[39]), NULL},
- {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[10]), NULL},
+ {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[9]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_STR("\011", "\000", "\000", "\000", "extension"), UPB_TABVALUE_PTR_INIT(&fields[23]), NULL},
- {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "weak_dependency"), UPB_TABVALUE_PTR_INIT(&fields[104]), NULL},
+ {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "weak_dependency"), UPB_TABVALUE_PTR_INIT(&fields[106]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[54]), NULL},
- {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "service"), UPB_TABVALUE_PTR_INIT(&fields[85]), NULL},
+ {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[51]), NULL},
+ {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "service"), UPB_TABVALUE_PTR_INIT(&fields[87]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "source_code_info"), UPB_TABVALUE_PTR_INIT(&fields[86]), NULL},
+ {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "source_code_info"), UPB_TABVALUE_PTR_INIT(&fields[88]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "syntax"), UPB_TABVALUE_PTR_INIT(&fields[91]), NULL},
+ {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "syntax"), UPB_TABVALUE_PTR_INIT(&fields[93]), NULL},
{UPB_TABKEY_STR("\012", "\000", "\000", "\000", "dependency"), UPB_TABVALUE_PTR_INIT(&fields[8]), NULL},
{UPB_TABKEY_STR("\014", "\000", "\000", "\000", "message_type"), UPB_TABVALUE_PTR_INIT(&fields[47]), NULL},
{UPB_TABKEY_STR("\007", "\000", "\000", "\000", "package"), UPB_TABVALUE_PTR_INIT(&fields[76]), NULL},
{UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[69]), &strentries[86]},
- {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "enum_type"), UPB_TABVALUE_PTR_INIT(&fields[20]), NULL},
- {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "public_dependency"), UPB_TABVALUE_PTR_INIT(&fields[80]), &strentries[85]},
+ {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "enum_type"), UPB_TABVALUE_PTR_INIT(&fields[19]), NULL},
+ {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "public_dependency"), UPB_TABVALUE_PTR_INIT(&fields[82]), &strentries[85]},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_STR("\004", "\000", "\000", "\000", "file"), UPB_TABVALUE_PTR_INIT(&fields[26]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
@@ -5730,7 +7644,7 @@ static const upb_tabent strentries[236] = {
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_STR("\023", "\000", "\000", "\000", "cc_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[3]), NULL},
- {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "csharp_namespace"), UPB_TABVALUE_PTR_INIT(&fields[5]), NULL},
+ {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "csharp_namespace"), UPB_TABVALUE_PTR_INIT(&fields[5]), &strentries[116]},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
@@ -5743,17 +7657,17 @@ static const upb_tabent strentries[236] = {
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_STR("\024", "\000", "\000", "\000", "java_outer_classname"), UPB_TABVALUE_PTR_INIT(&fields[34]), NULL},
- {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[95]), NULL},
+ {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "php_namespace"), UPB_TABVALUE_PTR_INIT(&fields[80]), &strentries[113]},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_STR("\023", "\000", "\000", "\000", "java_multiple_files"), UPB_TABVALUE_PTR_INIT(&fields[33]), &strentries[117]},
- {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
+ {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[99]), NULL},
{UPB_TABKEY_STR("\025", "\000", "\000", "\000", "java_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[32]), &strentries[118]},
{UPB_TABKEY_STR("\035", "\000", "\000", "\000", "java_generate_equals_and_hash"), UPB_TABVALUE_PTR_INIT(&fields[31]), NULL},
- {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
+ {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "php_class_prefix"), UPB_TABVALUE_PTR_INIT(&fields[79]), NULL},
{UPB_TABKEY_STR("\037", "\000", "\000", "\000", "javanano_use_deprecated_package"), UPB_TABVALUE_PTR_INIT(&fields[37]), &strentries[123]},
- {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "py_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[81]), NULL},
+ {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "py_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[83]), NULL},
{UPB_TABKEY_STR("\014", "\000", "\000", "\000", "optimize_for"), UPB_TABVALUE_PTR_INIT(&fields[67]), NULL},
{UPB_TABKEY_STR("\026", "\000", "\000", "\000", "java_string_check_utf8"), UPB_TABVALUE_PTR_INIT(&fields[36]), NULL},
{UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[12]), &strentries[119]},
@@ -5763,32 +7677,32 @@ static const upb_tabent strentries[236] = {
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[96]), NULL},
- {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[9]), NULL},
+ {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[97]), NULL},
+ {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[11]), NULL},
{UPB_TABKEY_STR("\011", "\000", "\000", "\000", "map_entry"), UPB_TABVALUE_PTR_INIT(&fields[45]), NULL},
{UPB_TABKEY_STR("\037", "\000", "\000", "\000", "no_standard_descriptor_accessor"), UPB_TABVALUE_PTR_INIT(&fields[61]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_STR("\020", "\000", "\000", "\000", "client_streaming"), UPB_TABVALUE_PTR_INIT(&fields[4]), NULL},
- {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "server_streaming"), UPB_TABVALUE_PTR_INIT(&fields[84]), NULL},
- {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[56]), NULL},
+ {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "server_streaming"), UPB_TABVALUE_PTR_INIT(&fields[86]), NULL},
+ {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[55]), NULL},
{UPB_TABKEY_STR("\012", "\000", "\000", "\000", "input_type"), UPB_TABVALUE_PTR_INIT(&fields[29]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_STR("\013", "\000", "\000", "\000", "output_type"), UPB_TABVALUE_PTR_INIT(&fields[75]), NULL},
- {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[70]), NULL},
+ {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[71]), NULL},
{UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[100]), NULL},
- {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[11]), NULL},
+ {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[10]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[50]), NULL},
+ {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[54]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[72]), &strentries[150]},
{UPB_TABKEY_STR("\006", "\000", "\000", "\000", "method"), UPB_TABVALUE_PTR_INIT(&fields[48]), NULL},
- {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[57]), &strentries[149]},
- {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[101]), NULL},
- {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[14]), NULL},
+ {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[53]), &strentries[149]},
+ {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[98]), NULL},
+ {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[15]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
@@ -5798,15 +7712,15 @@ static const upb_tabent strentries[236] = {
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "span"), UPB_TABVALUE_PTR_INIT(&fields[87]), &strentries[167]},
+ {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "span"), UPB_TABVALUE_PTR_INIT(&fields[89]), &strentries[167]},
{UPB_TABKEY_STR("\031", "\000", "\000", "\000", "leading_detached_comments"), UPB_TABVALUE_PTR_INIT(&fields[43]), &strentries[165]},
- {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "trailing_comments"), UPB_TABVALUE_PTR_INIT(&fields[92]), NULL},
+ {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "trailing_comments"), UPB_TABVALUE_PTR_INIT(&fields[94]), NULL},
{UPB_TABKEY_STR("\020", "\000", "\000", "\000", "leading_comments"), UPB_TABVALUE_PTR_INIT(&fields[42]), &strentries[164]},
{UPB_TABKEY_STR("\004", "\000", "\000", "\000", "path"), UPB_TABVALUE_PTR_INIT(&fields[78]), NULL},
{UPB_TABKEY_STR("\014", "\000", "\000", "\000", "double_value"), UPB_TABVALUE_PTR_INIT(&fields[16]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[51]), NULL},
+ {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[49]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
@@ -5816,9 +7730,9 @@ static const upb_tabent strentries[236] = {
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\022", "\000", "\000", "\000", "positive_int_value"), UPB_TABVALUE_PTR_INIT(&fields[79]), NULL},
+ {UPB_TABKEY_STR("\022", "\000", "\000", "\000", "positive_int_value"), UPB_TABVALUE_PTR_INIT(&fields[81]), NULL},
{UPB_TABKEY_STR("\020", "\000", "\000", "\000", "identifier_value"), UPB_TABVALUE_PTR_INIT(&fields[28]), NULL},
- {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "string_value"), UPB_TABVALUE_PTR_INIT(&fields[90]), &strentries[182]},
+ {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "string_value"), UPB_TABVALUE_PTR_INIT(&fields[92]), &strentries[182]},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_STR("\014", "\000", "\000", "\000", "is_extension"), UPB_TABVALUE_PTR_INIT(&fields[30]), NULL},
@@ -5875,92 +7789,92 @@ static const upb_tabent strentries[236] = {
static const upb_tabent intentries[18] = {
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[98]), NULL},
+ {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[103]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[97]), NULL},
+ {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[102]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[99]), NULL},
+ {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[101]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[95]), NULL},
+ {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[99]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[96]), NULL},
+ {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[97]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_NUM(33), UPB_TABVALUE_PTR_INIT(&fields[11]), NULL},
+ {UPB_TABKEY_NUM(33), UPB_TABVALUE_PTR_INIT(&fields[10]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[100]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_NUM(33), UPB_TABVALUE_PTR_INIT(&fields[14]), NULL},
+ {UPB_TABKEY_NUM(33), UPB_TABVALUE_PTR_INIT(&fields[15]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[101]), NULL},
+ {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[98]), NULL},
};
-static const upb_tabval arrays[184] = {
+static const upb_tabval arrays[187] = {
UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[52]),
+ UPB_TABVALUE_PTR_INIT(&fields[57]),
UPB_TABVALUE_PTR_INIT(&fields[25]),
UPB_TABVALUE_PTR_INIT(&fields[60]),
- UPB_TABVALUE_PTR_INIT(&fields[19]),
+ UPB_TABVALUE_PTR_INIT(&fields[20]),
UPB_TABVALUE_PTR_INIT(&fields[24]),
UPB_TABVALUE_PTR_INIT(&fields[22]),
UPB_TABVALUE_PTR_INIT(&fields[68]),
UPB_TABVALUE_PTR_INIT(&fields[65]),
- UPB_TABVALUE_PTR_INIT(&fields[83]),
- UPB_TABVALUE_PTR_INIT(&fields[82]),
+ UPB_TABVALUE_PTR_INIT(&fields[85]),
+ UPB_TABVALUE_PTR_INIT(&fields[84]),
UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[89]),
+ UPB_TABVALUE_PTR_INIT(&fields[91]),
UPB_TABVALUE_PTR_INIT(&fields[18]),
UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[88]),
+ UPB_TABVALUE_PTR_INIT(&fields[90]),
UPB_TABVALUE_PTR_INIT(&fields[17]),
UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[49]),
- UPB_TABVALUE_PTR_INIT(&fields[102]),
- UPB_TABVALUE_PTR_INIT(&fields[74]),
+ UPB_TABVALUE_PTR_INIT(&fields[52]),
+ UPB_TABVALUE_PTR_INIT(&fields[104]),
+ UPB_TABVALUE_PTR_INIT(&fields[73]),
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_PTR_INIT(&fields[1]),
- UPB_TABVALUE_PTR_INIT(&fields[13]),
+ UPB_TABVALUE_PTR_INIT(&fields[14]),
UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[53]),
- UPB_TABVALUE_PTR_INIT(&fields[62]),
- UPB_TABVALUE_PTR_INIT(&fields[73]),
+ UPB_TABVALUE_PTR_INIT(&fields[50]),
+ UPB_TABVALUE_PTR_INIT(&fields[63]),
+ UPB_TABVALUE_PTR_INIT(&fields[74]),
UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[15]),
+ UPB_TABVALUE_PTR_INIT(&fields[13]),
UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[55]),
+ UPB_TABVALUE_PTR_INIT(&fields[56]),
UPB_TABVALUE_PTR_INIT(&fields[21]),
- UPB_TABVALUE_PTR_INIT(&fields[63]),
+ UPB_TABVALUE_PTR_INIT(&fields[62]),
UPB_TABVALUE_PTR_INIT(&fields[40]),
- UPB_TABVALUE_PTR_INIT(&fields[93]),
- UPB_TABVALUE_PTR_INIT(&fields[94]),
+ UPB_TABVALUE_PTR_INIT(&fields[95]),
+ UPB_TABVALUE_PTR_INIT(&fields[96]),
UPB_TABVALUE_PTR_INIT(&fields[7]),
- UPB_TABVALUE_PTR_INIT(&fields[71]),
+ UPB_TABVALUE_PTR_INIT(&fields[70]),
UPB_TABVALUE_PTR_INIT(&fields[66]),
UPB_TABVALUE_PTR_INIT(&fields[38]),
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_PTR_INIT(&fields[6]),
UPB_TABVALUE_PTR_INIT(&fields[77]),
- UPB_TABVALUE_PTR_INIT(&fields[10]),
+ UPB_TABVALUE_PTR_INIT(&fields[9]),
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_PTR_INIT(&fields[41]),
UPB_TABVALUE_PTR_INIT(&fields[39]),
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[103]),
+ UPB_TABVALUE_PTR_INIT(&fields[105]),
UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[54]),
+ UPB_TABVALUE_PTR_INIT(&fields[51]),
UPB_TABVALUE_PTR_INIT(&fields[76]),
UPB_TABVALUE_PTR_INIT(&fields[8]),
UPB_TABVALUE_PTR_INIT(&fields[47]),
- UPB_TABVALUE_PTR_INIT(&fields[20]),
- UPB_TABVALUE_PTR_INIT(&fields[85]),
+ UPB_TABVALUE_PTR_INIT(&fields[19]),
+ UPB_TABVALUE_PTR_INIT(&fields[87]),
UPB_TABVALUE_PTR_INIT(&fields[23]),
UPB_TABVALUE_PTR_INIT(&fields[69]),
- UPB_TABVALUE_PTR_INIT(&fields[86]),
- UPB_TABVALUE_PTR_INIT(&fields[80]),
- UPB_TABVALUE_PTR_INIT(&fields[104]),
- UPB_TABVALUE_PTR_INIT(&fields[91]),
+ UPB_TABVALUE_PTR_INIT(&fields[88]),
+ UPB_TABVALUE_PTR_INIT(&fields[82]),
+ UPB_TABVALUE_PTR_INIT(&fields[106]),
+ UPB_TABVALUE_PTR_INIT(&fields[93]),
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_PTR_INIT(&fields[26]),
UPB_TABVALUE_EMPTY_INIT,
@@ -5981,7 +7895,7 @@ static const upb_tabval arrays[184] = {
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_PTR_INIT(&fields[3]),
UPB_TABVALUE_PTR_INIT(&fields[32]),
- UPB_TABVALUE_PTR_INIT(&fields[81]),
+ UPB_TABVALUE_PTR_INIT(&fields[83]),
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_PTR_INIT(&fields[31]),
UPB_TABVALUE_EMPTY_INIT,
@@ -6003,25 +7917,28 @@ static const upb_tabval arrays[184] = {
UPB_TABVALUE_PTR_INIT(&fields[5]),
UPB_TABVALUE_PTR_INIT(&fields[37]),
UPB_TABVALUE_EMPTY_INIT,
+ UPB_TABVALUE_PTR_INIT(&fields[79]),
+ UPB_TABVALUE_PTR_INIT(&fields[80]),
+ UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_PTR_INIT(&fields[46]),
UPB_TABVALUE_PTR_INIT(&fields[61]),
- UPB_TABVALUE_PTR_INIT(&fields[9]),
+ UPB_TABVALUE_PTR_INIT(&fields[11]),
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_PTR_INIT(&fields[45]),
UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[56]),
+ UPB_TABVALUE_PTR_INIT(&fields[55]),
UPB_TABVALUE_PTR_INIT(&fields[29]),
UPB_TABVALUE_PTR_INIT(&fields[75]),
- UPB_TABVALUE_PTR_INIT(&fields[70]),
+ UPB_TABVALUE_PTR_INIT(&fields[71]),
UPB_TABVALUE_PTR_INIT(&fields[4]),
- UPB_TABVALUE_PTR_INIT(&fields[84]),
+ UPB_TABVALUE_PTR_INIT(&fields[86]),
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[50]),
+ UPB_TABVALUE_PTR_INIT(&fields[54]),
UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[57]),
+ UPB_TABVALUE_PTR_INIT(&fields[53]),
UPB_TABVALUE_PTR_INIT(&fields[48]),
UPB_TABVALUE_PTR_INIT(&fields[72]),
UPB_TABVALUE_EMPTY_INIT,
@@ -6029,19 +7946,19 @@ static const upb_tabval arrays[184] = {
UPB_TABVALUE_PTR_INIT(&fields[44]),
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_PTR_INIT(&fields[78]),
- UPB_TABVALUE_PTR_INIT(&fields[87]),
+ UPB_TABVALUE_PTR_INIT(&fields[89]),
UPB_TABVALUE_PTR_INIT(&fields[42]),
- UPB_TABVALUE_PTR_INIT(&fields[92]),
+ UPB_TABVALUE_PTR_INIT(&fields[94]),
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_PTR_INIT(&fields[43]),
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[51]),
+ UPB_TABVALUE_PTR_INIT(&fields[49]),
UPB_TABVALUE_PTR_INIT(&fields[28]),
- UPB_TABVALUE_PTR_INIT(&fields[79]),
+ UPB_TABVALUE_PTR_INIT(&fields[81]),
UPB_TABVALUE_PTR_INIT(&fields[59]),
UPB_TABVALUE_PTR_INIT(&fields[16]),
- UPB_TABVALUE_PTR_INIT(&fields[90]),
+ UPB_TABVALUE_PTR_INIT(&fields[92]),
UPB_TABVALUE_PTR_INIT(&fields[0]),
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_PTR_INIT(&fields[58]),
@@ -6082,7 +7999,11 @@ static const upb_tabval arrays[184] = {
};
#ifdef UPB_DEBUG_REFS
-static upb_inttable reftables[264] = {
+static upb_inttable reftables[268] = {
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
@@ -6416,6 +8337,8 @@ typedef struct {
/* Index of the first def that is under this scope. For msgdefs, the
* msgdef itself is at start-1. */
int start;
+ uint32_t oneof_start;
+ uint32_t oneof_index;
} upb_descreader_frame;
/* The maximum number of nested declarations that are allowed, ie.
@@ -6433,9 +8356,11 @@ typedef struct {
struct upb_descreader {
upb_sink sink;
upb_inttable files;
+ upb_strtable files_by_name;
upb_filedef *file; /* The last file in files. */
upb_descreader_frame stack[UPB_MAX_MESSAGE_NESTING];
int stack_len;
+ upb_inttable oneofs;
uint32_t number;
char *name;
@@ -6447,7 +8372,7 @@ struct upb_descreader {
upb_fielddef *f;
};
-static char *upb_strndup(const char *buf, size_t n) {
+static char *upb_gstrndup(const char *buf, size_t n) {
char *ret = upb_gmalloc(n + 1);
if (!ret) return NULL;
memcpy(ret, buf, n);
@@ -6498,9 +8423,9 @@ static bool upb_descreader_qualify(upb_filedef *f, char *str, int32_t start) {
static upb_msgdef *upb_descreader_top(upb_descreader *r) {
int index;
- assert(r->stack_len > 1);
+ UPB_ASSERT(r->stack_len > 1);
index = r->stack[r->stack_len-1].start - 1;
- assert(index >= 0);
+ UPB_ASSERT(index >= 0);
return upb_downcast_msgdef_mutable(upb_filedef_mutabledef(r->file, index));
}
@@ -6513,16 +8438,27 @@ static upb_def *upb_descreader_last(upb_descreader *r) {
void upb_descreader_startcontainer(upb_descreader *r) {
upb_descreader_frame *f = &r->stack[r->stack_len++];
f->start = upb_filedef_defcount(r->file);
+ f->oneof_start = upb_inttable_count(&r->oneofs);
+ f->oneof_index = 0;
f->name = NULL;
}
bool upb_descreader_endcontainer(upb_descreader *r) {
- upb_descreader_frame *f = &r->stack[--r->stack_len];
+ upb_descreader_frame *f = &r->stack[r->stack_len - 1];
+
+ while (upb_inttable_count(&r->oneofs) > f->oneof_start) {
+ upb_oneofdef *o = upb_value_getptr(upb_inttable_pop(&r->oneofs));
+ bool ok = upb_msgdef_addoneof(upb_descreader_top(r), o, &r->oneofs, NULL);
+ UPB_ASSERT(ok);
+ }
+
if (!upb_descreader_qualify(r->file, f->name, f->start)) {
return false;
}
upb_gfree(f->name);
f->name = NULL;
+
+ r->stack_len--;
return true;
}
@@ -6532,6 +8468,26 @@ void upb_descreader_setscopename(upb_descreader *r, char *str) {
f->name = str;
}
+static upb_oneofdef *upb_descreader_getoneof(upb_descreader *r,
+ uint32_t index) {
+ bool found;
+ upb_value val;
+ upb_descreader_frame *f = &r->stack[r->stack_len-1];
+
+ /* DescriptorProto messages can be nested, so we will see the nested messages
+ * between when we see the FieldDescriptorProto and the OneofDescriptorProto.
+ * We need to preserve the oneofs in between these two things. */
+ index += f->oneof_start;
+
+ while (upb_inttable_count(&r->oneofs) <= index) {
+ upb_inttable_push(&r->oneofs, upb_value_ptr(upb_oneofdef_new(&r->oneofs)));
+ }
+
+ found = upb_inttable_lookup(&r->oneofs, index, &val);
+ UPB_ASSERT(found);
+ return upb_value_getptr(val);
+}
+
/** Handlers for google.protobuf.FileDescriptorSet. ***************************/
static void *fileset_startfile(void *closure, const void *hd) {
@@ -6566,11 +8522,12 @@ static size_t file_onname(void *closure, const void *hd, const char *buf,
UPB_UNUSED(hd);
UPB_UNUSED(handle);
- name = upb_strndup(buf, n);
+ name = upb_gstrndup(buf, n);
+ upb_strtable_insert(&r->files_by_name, name, upb_value_ptr(r->file));
/* XXX: see comment at the top of the file. */
ok = upb_filedef_setname(r->file, name, NULL);
upb_gfree(name);
- UPB_ASSERT_VAR(ok, ok);
+ UPB_ASSERT(ok);
return n;
}
@@ -6582,11 +8539,54 @@ static size_t file_onpackage(void *closure, const void *hd, const char *buf,
UPB_UNUSED(hd);
UPB_UNUSED(handle);
- package = upb_strndup(buf, n);
+ package = upb_gstrndup(buf, n);
/* XXX: see comment at the top of the file. */
upb_descreader_setscopename(r, package);
ok = upb_filedef_setpackage(r->file, package, NULL);
- UPB_ASSERT_VAR(ok, ok);
+ UPB_ASSERT(ok);
+ return n;
+}
+
+static void *file_startphpnamespace(void *closure, const void *hd,
+ size_t size_hint) {
+ upb_descreader *r = closure;
+ bool ok;
+ UPB_UNUSED(hd);
+ UPB_UNUSED(size_hint);
+
+ ok = upb_filedef_setphpnamespace(r->file, "", NULL);
+ UPB_ASSERT(ok);
+ return closure;
+}
+
+static size_t file_onphpnamespace(void *closure, const void *hd,
+ const char *buf, size_t n,
+ const upb_bufhandle *handle) {
+ upb_descreader *r = closure;
+ char *php_namespace;
+ bool ok;
+ UPB_UNUSED(hd);
+ UPB_UNUSED(handle);
+
+ php_namespace = upb_gstrndup(buf, n);
+ ok = upb_filedef_setphpnamespace(r->file, php_namespace, NULL);
+ upb_gfree(php_namespace);
+ UPB_ASSERT(ok);
+ return n;
+}
+
+static size_t file_onphpprefix(void *closure, const void *hd, const char *buf,
+ size_t n, const upb_bufhandle *handle) {
+ upb_descreader *r = closure;
+ char *prefix;
+ bool ok;
+ UPB_UNUSED(hd);
+ UPB_UNUSED(handle);
+
+ prefix = upb_gstrndup(buf, n);
+ ok = upb_filedef_setphpprefix(r->file, prefix, NULL);
+ upb_gfree(prefix);
+ UPB_ASSERT(ok);
return n;
}
@@ -6605,7 +8605,7 @@ static size_t file_onsyntax(void *closure, const void *hd, const char *buf,
ok = false;
}
- UPB_ASSERT_VAR(ok, ok);
+ UPB_ASSERT(ok);
return n;
}
@@ -6614,7 +8614,7 @@ static void *file_startmsg(void *closure, const void *hd) {
upb_msgdef *m = upb_msgdef_new(&m);
bool ok = upb_filedef_addmsg(r->file, m, &m, NULL);
UPB_UNUSED(hd);
- UPB_ASSERT_VAR(ok, ok);
+ UPB_ASSERT(ok);
return r;
}
@@ -6623,7 +8623,7 @@ static void *file_startenum(void *closure, const void *hd) {
upb_enumdef *e = upb_enumdef_new(&e);
bool ok = upb_filedef_addenum(r->file, e, &e, NULL);
UPB_UNUSED(hd);
- UPB_ASSERT_VAR(ok, ok);
+ UPB_ASSERT(ok);
return r;
}
@@ -6633,10 +8633,22 @@ static void *file_startext(void *closure, const void *hd) {
r->f = upb_fielddef_new(r);
ok = upb_filedef_addext(r->file, r->f, r, NULL);
UPB_UNUSED(hd);
- UPB_ASSERT_VAR(ok, ok);
+ UPB_ASSERT(ok);
return r;
}
+static size_t file_ondep(void *closure, const void *hd, const char *buf,
+ size_t n, const upb_bufhandle *handle) {
+ upb_descreader *r = closure;
+ upb_value val;
+ if (upb_strtable_lookup2(&r->files_by_name, buf, n, &val)) {
+ upb_filedef_adddep(r->file, upb_value_getptr(val));
+ }
+ UPB_UNUSED(hd);
+ UPB_UNUSED(handle);
+ return n;
+}
+
/** Handlers for google.protobuf.EnumValueDescriptorProto. *********************/
static bool enumval_startmsg(void *closure, const void *hd) {
@@ -6654,7 +8666,7 @@ static size_t enumval_onname(void *closure, const void *hd, const char *buf,
UPB_UNUSED(handle);
/* XXX: see comment at the top of the file. */
upb_gfree(r->name);
- r->name = upb_strndup(buf, n);
+ r->name = upb_gstrndup(buf, n);
r->saw_name = true;
return n;
}
@@ -6705,7 +8717,7 @@ static bool enum_endmsg(void *closure, const void *hd, upb_status *status) {
static size_t enum_onname(void *closure, const void *hd, const char *buf,
size_t n, const upb_bufhandle *handle) {
upb_descreader *r = closure;
- char *fullname = upb_strndup(buf, n);
+ char *fullname = upb_gstrndup(buf, n);
UPB_UNUSED(hd);
UPB_UNUSED(handle);
/* XXX: see comment at the top of the file. */
@@ -6719,7 +8731,7 @@ static size_t enum_onname(void *closure, const void *hd, const char *buf,
static bool field_startmsg(void *closure, const void *hd) {
upb_descreader *r = closure;
UPB_UNUSED(hd);
- assert(r->f);
+ UPB_ASSERT(r->f);
upb_gfree(r->default_string);
r->default_string = NULL;
@@ -6805,9 +8817,9 @@ static bool field_endmsg(void *closure, const void *hd, upb_status *status) {
UPB_UNUSED(hd);
/* TODO: verify that all required fields were present. */
- assert(upb_fielddef_number(f) != 0);
- assert(upb_fielddef_name(f) != NULL);
- assert((upb_fielddef_subdefname(f) != NULL) == upb_fielddef_hassubdef(f));
+ UPB_ASSERT(upb_fielddef_number(f) != 0);
+ UPB_ASSERT(upb_fielddef_name(f) != NULL);
+ UPB_ASSERT((upb_fielddef_subdefname(f) != NULL) == upb_fielddef_hassubdef(f));
if (r->default_string) {
if (upb_fielddef_issubmsg(f)) {
@@ -6866,14 +8878,14 @@ static bool field_onnumber(void *closure, const void *hd, int32_t val) {
UPB_UNUSED(hd);
ok = upb_fielddef_setnumber(r->f, val, NULL);
- UPB_ASSERT_VAR(ok, ok);
+ UPB_ASSERT(ok);
return true;
}
static size_t field_onname(void *closure, const void *hd, const char *buf,
size_t n, const upb_bufhandle *handle) {
upb_descreader *r = closure;
- char *name = upb_strndup(buf, n);
+ char *name = upb_gstrndup(buf, n);
UPB_UNUSED(hd);
UPB_UNUSED(handle);
@@ -6886,7 +8898,7 @@ static size_t field_onname(void *closure, const void *hd, const char *buf,
static size_t field_ontypename(void *closure, const void *hd, const char *buf,
size_t n, const upb_bufhandle *handle) {
upb_descreader *r = closure;
- char *name = upb_strndup(buf, n);
+ char *name = upb_gstrndup(buf, n);
UPB_UNUSED(hd);
UPB_UNUSED(handle);
@@ -6899,7 +8911,7 @@ static size_t field_ontypename(void *closure, const void *hd, const char *buf,
static size_t field_onextendee(void *closure, const void *hd, const char *buf,
size_t n, const upb_bufhandle *handle) {
upb_descreader *r = closure;
- char *name = upb_strndup(buf, n);
+ char *name = upb_gstrndup(buf, n);
UPB_UNUSED(hd);
UPB_UNUSED(handle);
@@ -6919,7 +8931,34 @@ static size_t field_ondefaultval(void *closure, const void *hd, const char *buf,
* type yet, so we save it as a string until the end of the field.
* XXX: see comment at the top of the file. */
upb_gfree(r->default_string);
- r->default_string = upb_strndup(buf, n);
+ r->default_string = upb_gstrndup(buf, n);
+ return n;
+}
+
+static bool field_ononeofindex(void *closure, const void *hd, int32_t index) {
+ upb_descreader *r = closure;
+ upb_oneofdef *o = upb_descreader_getoneof(r, index);
+ bool ok = upb_oneofdef_addfield(o, r->f, &r->f, NULL);
+ UPB_UNUSED(hd);
+
+ UPB_ASSERT(ok);
+ return true;
+}
+
+/** Handlers for google.protobuf.OneofDescriptorProto. ************************/
+
+static size_t oneof_name(void *closure, const void *hd, const char *buf,
+ size_t n, const upb_bufhandle *handle) {
+ upb_descreader *r = closure;
+ upb_descreader_frame *f = &r->stack[r->stack_len-1];
+ upb_oneofdef *o = upb_descreader_getoneof(r, f->oneof_index++);
+ char *name_null_terminated = upb_gstrndup(buf, n);
+ bool ok = upb_oneofdef_setname(o, name_null_terminated, NULL);
+ UPB_UNUSED(hd);
+ UPB_UNUSED(handle);
+
+ UPB_ASSERT(ok);
+ free(name_null_terminated);
return n;
}
@@ -6950,7 +8989,7 @@ static size_t msg_name(void *closure, const void *hd, const char *buf,
upb_descreader *r = closure;
upb_msgdef *m = upb_descreader_top(r);
/* XXX: see comment at the top of the file. */
- char *name = upb_strndup(buf, n);
+ char *name = upb_gstrndup(buf, n);
UPB_UNUSED(hd);
UPB_UNUSED(handle);
@@ -6964,7 +9003,7 @@ static void *msg_startmsg(void *closure, const void *hd) {
upb_msgdef *m = upb_msgdef_new(&m);
bool ok = upb_filedef_addmsg(r->file, m, &m, NULL);
UPB_UNUSED(hd);
- UPB_ASSERT_VAR(ok, ok);
+ UPB_ASSERT(ok);
return r;
}
@@ -6973,7 +9012,7 @@ static void *msg_startext(void *closure, const void *hd) {
upb_fielddef *f = upb_fielddef_new(&f);
bool ok = upb_filedef_addext(r->file, f, &f, NULL);
UPB_UNUSED(hd);
- UPB_ASSERT_VAR(ok, ok);
+ UPB_ASSERT(ok);
return r;
}
@@ -6989,9 +9028,15 @@ static void *msg_startfield(void *closure, const void *hd) {
static bool msg_endfield(void *closure, const void *hd) {
upb_descreader *r = closure;
upb_msgdef *m = upb_descreader_top(r);
+ bool ok;
UPB_UNUSED(hd);
- upb_msgdef_addfield(m, r->f, &r->f, NULL);
+ /* Oneof fields are added to the msgdef through their oneof, so don't need to
+ * be added here. */
+ if (upb_fielddef_containingoneof(r->f) == NULL) {
+ ok = upb_msgdef_addfield(m, r->f, &r->f, NULL);
+ UPB_ASSERT(ok);
+ }
r->f = NULL;
return true;
}
@@ -7048,6 +9093,8 @@ static void reghandlers(const void *closure, upb_handlers *h) {
&file_startenum, NULL);
upb_handlers_setstartsubmsg(h, F(FileDescriptorProto, extension),
&file_startext, NULL);
+ upb_handlers_setstring(h, F(FileDescriptorProto, dependency),
+ &file_ondep, NULL);
} else if (upbdefs_google_protobuf_EnumValueDescriptorProto_is(m)) {
upb_handlers_setstartmsg(h, &enumval_startmsg, NULL);
upb_handlers_setendmsg(h, &enumval_endmsg, NULL);
@@ -7074,14 +9121,25 @@ static void reghandlers(const void *closure, upb_handlers *h) {
&field_onextendee, NULL);
upb_handlers_setstring(h, F(FieldDescriptorProto, default_value),
&field_ondefaultval, NULL);
+ upb_handlers_setint32(h, F(FieldDescriptorProto, oneof_index),
+ &field_ononeofindex, NULL);
+ } else if (upbdefs_google_protobuf_OneofDescriptorProto_is(m)) {
+ upb_handlers_setstring(h, F(OneofDescriptorProto, name), &oneof_name, NULL);
} else if (upbdefs_google_protobuf_FieldOptions_is(m)) {
upb_handlers_setbool(h, F(FieldOptions, lazy), &field_onlazy, NULL);
upb_handlers_setbool(h, F(FieldOptions, packed), &field_onpacked, NULL);
} else if (upbdefs_google_protobuf_MessageOptions_is(m)) {
upb_handlers_setbool(h, F(MessageOptions, map_entry), &msg_onmapentry, NULL);
+ } else if (upbdefs_google_protobuf_FileOptions_is(m)) {
+ upb_handlers_setstring(h, F(FileOptions, php_class_prefix),
+ &file_onphpprefix, NULL);
+ upb_handlers_setstartstr(h, F(FileOptions, php_namespace),
+ &file_startphpnamespace, NULL);
+ upb_handlers_setstring(h, F(FileOptions, php_namespace),
+ &file_onphpnamespace, NULL);
}
- assert(upb_ok(upb_handlers_status(h)));
+ UPB_ASSERT(upb_ok(upb_handlers_status(h)));
}
#undef F
@@ -7096,6 +9154,8 @@ void descreader_cleanup(void *_r) {
upb_gfree(r->name);
upb_inttable_uninit(&r->files);
+ upb_strtable_uninit(&r->files_by_name);
+ upb_inttable_uninit(&r->oneofs);
upb_gfree(r->default_string);
while (r->stack_len > 0) {
upb_descreader_frame *f = &r->stack[--r->stack_len];
@@ -7113,6 +9173,8 @@ upb_descreader *upb_descreader_create(upb_env *e, const upb_handlers *h) {
}
upb_inttable_init(&r->files, UPB_CTYPE_PTR);
+ upb_strtable_init(&r->files_by_name, UPB_CTYPE_PTR);
+ upb_inttable_init(&r->oneofs, UPB_CTYPE_PTR);
upb_sink_reset(upb_descreader_input(r), h, r);
r->stack_len = 0;
r->name = NULL;
@@ -7327,7 +9389,7 @@ bool op_has_longofs(int32_t instruction) {
case OP_TAGN:
return false;
default:
- assert(false);
+ UPB_ASSERT(false);
return false;
}
}
@@ -7346,7 +9408,7 @@ static void setofs(uint32_t *instruction, int32_t ofs) {
} else {
*instruction = (*instruction & ~0xff00) | ((ofs & 0xff) << 8);
}
- assert(getofs(*instruction) == ofs); /* Would fail in cases of overflow. */
+ UPB_ASSERT(getofs(*instruction) == ofs); /* Would fail in cases of overflow. */
}
static uint32_t pcofs(compiler *c) { return c->pc - c->group->bytecode; }
@@ -7358,7 +9420,7 @@ static void label(compiler *c, unsigned int label) {
int val;
uint32_t *codep;
- assert(label < MAXLABEL);
+ UPB_ASSERT(label < MAXLABEL);
val = c->fwd_labels[label];
codep = (val == EMPTYLABEL) ? NULL : c->group->bytecode + val;
while (codep) {
@@ -7379,7 +9441,7 @@ static void label(compiler *c, unsigned int label) {
* The returned value is the offset that should be written into the instruction.
*/
static int32_t labelref(compiler *c, int label) {
- assert(label < MAXLABEL);
+ UPB_ASSERT(label < MAXLABEL);
if (label == LABEL_DISPATCH) {
/* No resolving required. */
return 0;
@@ -7411,7 +9473,7 @@ static void put32(compiler *c, uint32_t v) {
*c->pc++ = v;
}
-static void putop(compiler *c, opcode op, ...) {
+static void putop(compiler *c, int op, ...) {
va_list ap;
va_start(ap, op);
@@ -7479,7 +9541,7 @@ static void putop(compiler *c, opcode op, ...) {
int label = va_arg(ap, int);
uint64_t tag = va_arg(ap, uint64_t);
uint32_t instruction = op | (tag << 16);
- assert(tag <= 0xffff);
+ UPB_ASSERT(tag <= 0xffff);
setofs(&instruction, labelref(c, label));
put32(c, instruction);
break;
@@ -7616,7 +9678,7 @@ static uint64_t get_encoded_tag(const upb_fielddef *f, int wire_type) {
uint32_t tag = (upb_fielddef_number(f) << 3) | wire_type;
uint64_t encoded_tag = upb_vencode32(tag);
/* No tag should be greater than 5 bytes. */
- assert(encoded_tag <= 0xffffffffff);
+ UPB_ASSERT(encoded_tag <= 0xffffffffff);
return encoded_tag;
}
@@ -7639,7 +9701,7 @@ static void putchecktag(compiler *c, const upb_fielddef *f,
static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
upb_selector_t selector;
bool ok = upb_handlers_getselector(f, type, &selector);
- UPB_ASSERT_VAR(ok, ok);
+ UPB_ASSERT(ok);
return selector;
}
@@ -7651,7 +9713,7 @@ static uint64_t repack(uint64_t dispatch, int new_wt2) {
uint8_t wt1;
uint8_t old_wt2;
upb_pbdecoder_unpackdispatch(dispatch, &ofs, &wt1, &old_wt2);
- assert(old_wt2 == NO_WIRE_TYPE); /* wt2 should not be set yet. */
+ UPB_ASSERT(old_wt2 == NO_WIRE_TYPE); /* wt2 should not be set yet. */
return upb_pbdecoder_packdispatch(ofs, wt1, new_wt2);
}
@@ -7853,7 +9915,7 @@ static void generate_primitivefield(compiler *c, const upb_fielddef *f,
* setting in the fielddef. This will favor (in speed) whichever was
* specified. */
- assert((int)parse_type >= 0 && parse_type <= OP_MAX);
+ UPB_ASSERT((int)parse_type >= 0 && parse_type <= OP_MAX);
sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
wire_type = upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
if (upb_fielddef_isseq(f)) {
@@ -7895,7 +9957,7 @@ static void compile_method(compiler *c, upb_pbdecodermethod *method) {
upb_msg_field_iter i;
upb_value val;
- assert(method);
+ UPB_ASSERT(method);
/* Clear all entries in the dispatch table. */
upb_inttable_uninit(&method->dispatch);
@@ -8043,7 +10105,7 @@ const mgroup *mgroup_new(const upb_handlers *dest, bool allowjit, bool lazy,
compiler *c;
UPB_UNUSED(allowjit);
- assert(upb_handlers_isfrozen(dest));
+ UPB_ASSERT(upb_handlers_isfrozen(dest));
g = newgroup(owner);
c = newcompiler(g, lazy);
@@ -8064,13 +10126,13 @@ const mgroup *mgroup_new(const upb_handlers *dest, bool allowjit, bool lazy,
#ifdef UPB_DUMP_BYTECODE
{
FILE *f = fopen("/tmp/upb-bytecode", "w");
- assert(f);
+ UPB_ASSERT(f);
dumpbc(g->bytecode, g->bytecode_end, stderr);
dumpbc(g->bytecode, g->bytecode_end, f);
fclose(f);
f = fopen("/tmp/upb-bytecode.bin", "wb");
- assert(f);
+ UPB_ASSERT(f);
fwrite(g->bytecode, 1, g->bytecode_end - g->bytecode, f);
fclose(f);
}
@@ -8120,7 +10182,7 @@ const upb_pbdecodermethod *upb_pbcodecache_getdecodermethod(
upb_inttable_push(&c->groups, upb_value_constptr(g));
ok = upb_inttable_lookupptr(&g->methods, opts->handlers, &v);
- UPB_ASSERT_VAR(ok, ok);
+ UPB_ASSERT(ok);
return upb_value_getptr(v);
}
@@ -8253,7 +10315,7 @@ void upb_pbdecoder_seterr(upb_pbdecoder *d, const char *msg) {
/* How many bytes can be safely read from d->ptr without reading past end-of-buf
* or past the current delimited end. */
static size_t curbufleft(const upb_pbdecoder *d) {
- assert(d->data_end >= d->ptr);
+ UPB_ASSERT(d->data_end >= d->ptr);
return d->data_end - d->ptr;
}
@@ -8274,7 +10336,7 @@ size_t delim_remaining(const upb_pbdecoder *d) {
/* Advances d->ptr. */
static void advance(upb_pbdecoder *d, size_t len) {
- assert(curbufleft(d) >= len);
+ UPB_ASSERT(curbufleft(d) >= len);
d->ptr += len;
}
@@ -8307,7 +10369,7 @@ static void switchtobuf(upb_pbdecoder *d, const char *buf, const char *end) {
}
static void advancetobuf(upb_pbdecoder *d, const char *buf, size_t len) {
- assert(curbufleft(d) == 0);
+ UPB_ASSERT(curbufleft(d) == 0);
d->bufstart_ofs += (d->end - d->buf);
switchtobuf(d, buf, buf + len);
}
@@ -8316,7 +10378,7 @@ static void checkpoint(upb_pbdecoder *d) {
/* The assertion here is in the interests of efficiency, not correctness.
* We are trying to ensure that we don't checkpoint() more often than
* necessary. */
- assert(d->checkpoint != d->ptr);
+ UPB_ASSERT(d->checkpoint != d->ptr);
d->checkpoint = d->ptr;
}
@@ -8327,8 +10389,8 @@ static void checkpoint(upb_pbdecoder *d) {
* won't actually be read.
*/
static int32_t skip(upb_pbdecoder *d, size_t bytes) {
- assert(!in_residual_buf(d, d->ptr) || d->size_param == 0);
- assert(d->skip == 0);
+ UPB_ASSERT(!in_residual_buf(d, d->ptr) || d->size_param == 0);
+ UPB_ASSERT(d->skip == 0);
if (bytes > delim_remaining(d)) {
seterr(d, "Skipped value extended beyond enclosing submessage.");
return upb_pbdecoder_suspend(d);
@@ -8356,7 +10418,7 @@ int32_t upb_pbdecoder_resume(upb_pbdecoder *d, void *p, const char *buf,
/* d->skip and d->residual_end could probably elegantly be represented
* as a single variable, to more easily represent this invariant. */
- assert(!(d->skip && d->residual_end > d->residual));
+ UPB_ASSERT(!(d->skip && d->residual_end > d->residual));
/* We need to remember the original size_param, so that the value we return
* is relative to it, even if we do some skipping first. */
@@ -8389,7 +10451,7 @@ int32_t upb_pbdecoder_resume(upb_pbdecoder *d, void *p, const char *buf,
if (d->residual_end > d->residual) {
/* We have residual bytes from the last buffer. */
- assert(d->ptr == d->residual);
+ UPB_ASSERT(d->ptr == d->residual);
} else {
switchtobuf(d, buf, buf + size);
}
@@ -8423,8 +10485,8 @@ size_t upb_pbdecoder_suspend(upb_pbdecoder *d) {
return 0;
} else {
size_t ret = d->size_param - (d->end - d->checkpoint);
- assert(!in_residual_buf(d, d->checkpoint));
- assert(d->buf == d->buf_param || d->buf == &dummy_char);
+ UPB_ASSERT(!in_residual_buf(d, d->checkpoint));
+ UPB_ASSERT(d->buf == d->buf_param || d->buf == &dummy_char);
d->bufstart_ofs += (d->checkpoint - d->buf);
d->residual_end = d->residual;
@@ -8444,7 +10506,7 @@ static size_t suspend_save(upb_pbdecoder *d) {
if (d->checkpoint == d->residual) {
/* Checkpoint was in residual buf; append user byte(s) to residual buf. */
- assert((d->residual_end - d->residual) + d->size_param <=
+ UPB_ASSERT((d->residual_end - d->residual) + d->size_param <=
sizeof(d->residual));
if (!in_residual_buf(d, d->ptr)) {
d->bufstart_ofs -= (d->residual_end - d->residual);
@@ -8454,11 +10516,11 @@ static size_t suspend_save(upb_pbdecoder *d) {
} else {
/* Checkpoint was in user buf; old residual bytes not needed. */
size_t save;
- assert(!in_residual_buf(d, d->checkpoint));
+ UPB_ASSERT(!in_residual_buf(d, d->checkpoint));
d->ptr = d->checkpoint;
save = curbufleft(d);
- assert(save <= sizeof(d->residual));
+ UPB_ASSERT(save <= sizeof(d->residual));
memcpy(d->residual, d->ptr, save);
d->residual_end = d->residual + save;
d->bufstart_ofs = offset(d);
@@ -8472,7 +10534,7 @@ static size_t suspend_save(upb_pbdecoder *d) {
* Requires that this many bytes are available in the current buffer. */
UPB_FORCEINLINE static void consumebytes(upb_pbdecoder *d, void *buf,
size_t bytes) {
- assert(bytes <= curbufleft(d));
+ UPB_ASSERT(bytes <= curbufleft(d));
memcpy(buf, d->ptr, bytes);
advance(d, bytes);
}
@@ -8485,7 +10547,7 @@ UPB_NOINLINE static int32_t getbytes_slow(upb_pbdecoder *d, void *buf,
const size_t avail = curbufleft(d);
consumebytes(d, buf, avail);
bytes -= avail;
- assert(bytes > 0);
+ UPB_ASSERT(bytes > 0);
if (in_residual_buf(d, d->ptr)) {
advancetobuf(d, d->buf_param, d->size_param);
}
@@ -8668,7 +10730,7 @@ UPB_NOINLINE int32_t upb_pbdecoder_checktag_slow(upb_pbdecoder *d,
if (read == bytes && data == expected) {
/* Advance past matched bytes. */
int32_t ok = getbytes(d, &data, read);
- UPB_ASSERT_VAR(ok, ok < 0);
+ UPB_ASSERT(ok < 0);
return DECODE_OK;
} else if (read < bytes && memcmp(&data, &expected, read) == 0) {
return suspend_save(d);
@@ -8694,7 +10756,6 @@ have_tag:
return upb_pbdecoder_suspend(d);
}
- /* TODO: deliver to unknown field callback. */
switch (wire_type) {
case UPB_WIRE_TYPE_32BIT:
CHECK_RETURN(skip(d, 4));
@@ -8732,6 +10793,8 @@ have_tag:
}
if (d->top->groupnum >= 0) {
+ /* TODO: More code needed for handling unknown groups. */
+ upb_sink_putunknown(&d->top->sink, d->checkpoint, d->ptr - d->checkpoint);
return DECODE_OK;
}
@@ -8743,7 +10806,7 @@ have_tag:
static void goto_endmsg(upb_pbdecoder *d) {
upb_value v;
bool found = upb_inttable_lookup32(d->top->dispatch, DISPATCH_ENDMSG, &v);
- UPB_ASSERT_VAR(found, found);
+ UPB_ASSERT(found);
d->pc = d->top->base + upb_value_getuint64(v);
}
@@ -8777,7 +10840,7 @@ static int32_t dispatch(upb_pbdecoder *d) {
} else if (wire_type == ((v >> 8) & 0xff)) {
bool found =
upb_inttable_lookup(dispatch, fieldnum + UPB_MAX_FIELDNUMBER, &val);
- UPB_ASSERT_VAR(found, found);
+ UPB_ASSERT(found);
d->pc = d->top->base + upb_value_getuint64(val);
return DECODE_OK;
}
@@ -8789,7 +10852,7 @@ static int32_t dispatch(upb_pbdecoder *d) {
* can re-check the delimited end. */
d->last--; /* Necessary if we get suspended */
d->pc = d->last;
- assert(getop(*d->last) == OP_CHECKDELIM);
+ UPB_ASSERT(getop(*d->last) == OP_CHECKDELIM);
/* Unknown field or ENDGROUP. */
retval = upb_pbdecoder_skipunknown(d, fieldnum, wire_type);
@@ -8807,7 +10870,7 @@ static int32_t dispatch(upb_pbdecoder *d) {
/* Callers know that the stack is more than one deep because the opcodes that
* call this only occur after PUSH operations. */
upb_pbdecoder_frame *outer_frame(upb_pbdecoder *d) {
- assert(d->top != d->stack);
+ UPB_ASSERT(d->top != d->stack);
return d->top - 1;
}
@@ -8839,7 +10902,7 @@ size_t run_decoder_vm(upb_pbdecoder *d, const mgroup *group,
op = getop(instruction);
arg = instruction >> 8;
longofs = arg;
- assert(d->ptr != d->residual_end);
+ UPB_ASSERT(d->ptr != d->residual_end);
UPB_UNUSED(group);
#ifdef UPB_DUMP_BYTECODE
fprintf(stderr, "s_ofs=%d buf_ofs=%d data_rem=%d buf_rem=%d delim_rem=%d "
@@ -8914,7 +10977,7 @@ size_t run_decoder_vm(upb_pbdecoder *d, const mgroup *group,
} else {
int32_t ret = skip(d, n);
/* This shouldn't return DECODE_OK, because n > len. */
- assert(ret >= 0);
+ UPB_ASSERT(ret >= 0);
return ret;
}
}
@@ -8936,7 +10999,7 @@ size_t run_decoder_vm(upb_pbdecoder *d, const mgroup *group,
d->top->groupnum = *d->pc++;
)
VMCASE(OP_POP,
- assert(d->top > d->stack);
+ UPB_ASSERT(d->top > d->stack);
decoder_pop(d);
)
VMCASE(OP_PUSHLENDELIM,
@@ -8952,7 +11015,7 @@ size_t run_decoder_vm(upb_pbdecoder *d, const mgroup *group,
/* We are guaranteed of this assert because we never allow ourselves to
* consume bytes beyond data_end, which covers delim_end when non-NULL.
*/
- assert(!(d->delim_end && d->ptr > d->delim_end));
+ UPB_ASSERT(!(d->delim_end && d->ptr > d->delim_end));
if (d->ptr == d->delim_end)
d->pc += longofs;
)
@@ -8961,7 +11024,7 @@ size_t run_decoder_vm(upb_pbdecoder *d, const mgroup *group,
d->pc += longofs;
)
VMCASE(OP_RET,
- assert(d->call_len > 0);
+ UPB_ASSERT(d->call_len > 0);
d->pc = d->callstack[--d->call_len];
)
VMCASE(OP_BRANCH,
@@ -9088,7 +11151,7 @@ bool upb_pbdecoder_end(void *closure, const void *handler_data) {
if (p != method->code_base.ptr) p--;
if (getop(*p) == OP_CHECKDELIM) {
/* Rewind from OP_TAG* to OP_CHECKDELIM. */
- assert(getop(*d->pc) == OP_TAG1 ||
+ UPB_ASSERT(getop(*d->pc) == OP_TAG1 ||
getop(*d->pc) == OP_TAG2 ||
getop(*d->pc) == OP_TAGN ||
getop(*d->pc) == OP_DISPATCH);
@@ -9152,7 +11215,7 @@ upb_pbdecoder *upb_pbdecoder_create(upb_env *e, const upb_pbdecodermethod *m,
upb_pbdecoder_reset(d);
upb_bytessink_reset(&d->input_, &m->input_handler_, d);
- assert(sink);
+ UPB_ASSERT(sink);
if (d->method_->dest_handlers_) {
if (sink->handlers != d->method_->dest_handlers_)
return NULL;
@@ -9160,7 +11223,8 @@ upb_pbdecoder *upb_pbdecoder_create(upb_env *e, const upb_pbdecodermethod *m,
upb_sink_reset(&d->top->sink, sink->handlers, sink->closure);
/* If this fails, increase the value in decoder.h. */
- assert(upb_env_bytesallocated(e) - size_before <= UPB_PB_DECODER_SIZE);
+ UPB_ASSERT_DEBUGVAR(upb_env_bytesallocated(e) - size_before <=
+ UPB_PB_DECODER_SIZE);
return d;
}
@@ -9181,7 +11245,7 @@ size_t upb_pbdecoder_maxnesting(const upb_pbdecoder *d) {
}
bool upb_pbdecoder_setmaxnesting(upb_pbdecoder *d, size_t max) {
- assert(d->top >= d->stack);
+ UPB_ASSERT(d->top >= d->stack);
if (max < (size_t)(d->top - d->stack)) {
/* Can't set a limit smaller than what we are currently at. */
@@ -9340,7 +11404,7 @@ struct upb_pb_encoder {
/* TODO(haberman): handle pushback */
static void putbuf(upb_pb_encoder *e, const char *buf, size_t len) {
size_t n = upb_bytessink_putbuf(e->output_, e->subc, buf, len, NULL);
- UPB_ASSERT_VAR(n, n == len);
+ UPB_ASSERT(n == len);
}
static upb_pb_encoder_segment *top(upb_pb_encoder *e) {
@@ -9380,7 +11444,7 @@ static bool reserve(upb_pb_encoder *e, size_t bytes) {
/* Call when "bytes" bytes have been writte at e->ptr. The caller *must* have
* previously called reserve() with at least this many bytes. */
static void encoder_advance(upb_pb_encoder *e, size_t bytes) {
- assert((size_t)(e->limit - e->ptr) >= bytes);
+ UPB_ASSERT((size_t)(e->limit - e->ptr) >= bytes);
e->ptr += bytes;
}
@@ -9415,7 +11479,7 @@ static bool encode_bytes(upb_pb_encoder *e, const void *data, size_t len) {
* length. */
static void accumulate(upb_pb_encoder *e) {
size_t run_len;
- assert(e->ptr >= e->runbegin);
+ UPB_ASSERT(e->ptr >= e->runbegin);
run_len = e->ptr - e->runbegin;
e->segptr->seglen += run_len;
top(e)->msglen += run_len;
@@ -9586,6 +11650,12 @@ static void *encode_startdelimfield(void *c, const void *hd) {
return ok ? c : UPB_BREAK;
}
+static bool encode_unknown(void *c, const void *hd, const char *buf,
+ size_t len) {
+ UPB_UNUSED(hd);
+ return encode_bytes(c, buf, len) && commit(c);
+}
+
static bool encode_enddelimfield(void *c, const void *hd) {
UPB_UNUSED(hd);
return end_delim(c);
@@ -9623,7 +11693,7 @@ static size_t encode_strbuf(void *c, const void *hd, const char *buf,
T(double, double, dbl2uint64, encode_fixed64)
T(float, float, flt2uint32, encode_fixed32)
T(int64, int64_t, uint64_t, encode_varint)
-T(int32, int32_t, uint32_t, encode_varint)
+T(int32, int32_t, int64_t, encode_varint)
T(fixed64, uint64_t, uint64_t, encode_fixed64)
T(fixed32, uint32_t, uint32_t, encode_fixed32)
T(bool, bool, bool, encode_varint)
@@ -9648,6 +11718,7 @@ static void newhandlers_callback(const void *closure, upb_handlers *h) {
upb_handlers_setstartmsg(h, startmsg, NULL);
upb_handlers_setendmsg(h, endmsg, NULL);
+ upb_handlers_setunknown(h, encode_unknown, NULL);
m = upb_handlers_msgdef(h);
for(upb_msg_field_begin(&i, m);
@@ -9770,7 +11841,8 @@ upb_pb_encoder *upb_pb_encoder_create(upb_env *env, const upb_handlers *h,
e->ptr = e->buf;
/* If this fails, increase the value in encoder.h. */
- assert(upb_env_bytesallocated(env) - size_before <= UPB_PB_ENCODER_SIZE);
+ UPB_ASSERT_DEBUGVAR(upb_env_bytesallocated(env) - size_before <=
+ UPB_PB_ENCODER_SIZE);
return e;
}
@@ -9938,7 +12010,7 @@ bool putf(upb_textprinter *p, const char *fmt, ...) {
if (!str) return false;
written = vsprintf(str, fmt, args);
va_end(args);
- UPB_ASSERT_VAR(written, written == len);
+ UPB_ASSERT(written == len);
ok = upb_bytessink_putbuf(p->output_, p->subc, str, len, NULL);
upb_gfree(str);
@@ -10237,57 +12309,6 @@ done:
return r;
}
-/* Given an encoded varint v, returns an integer with a single bit set that
- * indicates the end of the varint. Subtracting one from this value will
- * yield a mask that leaves only bits that are part of the varint. Returns
- * 0 if the varint is unterminated. */
-static uint64_t upb_get_vstopbit(uint64_t v) {
- uint64_t cbits = v | 0x7f7f7f7f7f7f7f7fULL;
- return ~cbits & (cbits+1);
-}
-
-/* A branchless decoder. Credit to Pascal Massimino for the bit-twiddling. */
-upb_decoderet upb_vdecode_max8_massimino(upb_decoderet r) {
- uint64_t b;
- uint64_t stop_bit;
- upb_decoderet my_r;
- memcpy(&b, r.p, sizeof(b));
- stop_bit = upb_get_vstopbit(b);
- b = (b & 0x7f7f7f7f7f7f7f7fULL) & (stop_bit - 1);
- b += b & 0x007f007f007f007fULL;
- b += 3 * (b & 0x0000ffff0000ffffULL);
- b += 15 * (b & 0x00000000ffffffffULL);
- if (stop_bit == 0) {
- /* Error: unterminated varint. */
- upb_decoderet err_r = {(void*)0, 0};
- return err_r;
- }
- my_r = upb_decoderet_make(r.p + ((__builtin_ctzll(stop_bit) + 1) / 8),
- r.val | (b << 7));
- return my_r;
-}
-
-/* A branchless decoder. Credit to Daniel Wright for the bit-twiddling. */
-upb_decoderet upb_vdecode_max8_wright(upb_decoderet r) {
- uint64_t b;
- uint64_t stop_bit;
- upb_decoderet my_r;
- memcpy(&b, r.p, sizeof(b));
- stop_bit = upb_get_vstopbit(b);
- b &= (stop_bit - 1);
- b = ((b & 0x7f007f007f007f00ULL) >> 1) | (b & 0x007f007f007f007fULL);
- b = ((b & 0xffff0000ffff0000ULL) >> 2) | (b & 0x0000ffff0000ffffULL);
- b = ((b & 0xffffffff00000000ULL) >> 4) | (b & 0x00000000ffffffffULL);
- if (stop_bit == 0) {
- /* Error: unterminated varint. */
- upb_decoderet err_r = {(void*)0, 0};
- return err_r;
- }
- my_r = upb_decoderet_make(r.p + ((__builtin_ctzll(stop_bit) + 1) / 8),
- r.val | (b << 14));
- return my_r;
-}
-
#line 1 "upb/json/parser.rl"
/*
** upb::json::Parser (upb_json_parser)
@@ -10310,8 +12331,9 @@ upb_decoderet upb_vdecode_max8_wright(upb_decoderet r) {
** - handling of keys/escape-sequences/etc that span input buffers.
*/
-#include <assert.h>
#include <errno.h>
+#include <float.h>
+#include <math.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
@@ -10407,7 +12429,7 @@ static upb_selector_t getsel_for_handlertype(upb_json_parser *p,
upb_handlertype_t type) {
upb_selector_t sel;
bool ok = upb_handlers_getselector(p->top->f, type, &sel);
- UPB_ASSERT_VAR(ok, ok);
+ UPB_ASSERT(ok);
return sel;
}
@@ -10429,7 +12451,7 @@ static bool check_stack(upb_json_parser *p) {
static void set_name_table(upb_json_parser *p, upb_jsonparser_frame *frame) {
upb_value v;
bool ok = upb_inttable_lookupptr(&p->method->name_tables, frame->m, &v);
- UPB_ASSERT_VAR(ok, ok);
+ UPB_ASSERT(ok);
frame->name_table = upb_value_getptr(v);
}
@@ -10552,7 +12574,7 @@ otherchar:
val = b64lookup(ptr[0]) << 18 |
b64lookup(ptr[1]) << 12;
- assert(!(val & 0x80000000));
+ UPB_ASSERT(!(val & 0x80000000));
output = val >> 16;
upb_sink_putstring(&p->top->sink, sel, &output, 1, NULL);
return true;
@@ -10606,9 +12628,8 @@ badpadding:
* the true value in a contiguous buffer. */
static void assert_accumulate_empty(upb_json_parser *p) {
- UPB_UNUSED(p);
- assert(p->accumulated == NULL);
- assert(p->accumulated_len == 0);
+ UPB_ASSERT(p->accumulated == NULL);
+ UPB_ASSERT(p->accumulated_len == 0);
}
static void accumulate_clear(upb_json_parser *p) {
@@ -10674,7 +12695,7 @@ static bool accumulate_append(upb_json_parser *p, const char *buf, size_t len,
* call, and writes the length to *len. This with point either to the input
* buffer or a temporary accumulate buffer. */
static const char *accumulate_getptr(upb_json_parser *p, size_t *len) {
- assert(p->accumulated);
+ UPB_ASSERT(p->accumulated);
*len = p->accumulated_len;
return p->accumulated;
}
@@ -10712,7 +12733,7 @@ enum {
* the end. */
static void multipart_startaccum(upb_json_parser *p) {
assert_accumulate_empty(p);
- assert(p->multipart_state == MULTIPART_INACTIVE);
+ UPB_ASSERT(p->multipart_state == MULTIPART_INACTIVE);
p->multipart_state = MULTIPART_ACCUMULATE;
}
@@ -10720,7 +12741,7 @@ static void multipart_startaccum(upb_json_parser *p) {
* value with the given selector. */
static void multipart_start(upb_json_parser *p, upb_selector_t sel) {
assert_accumulate_empty(p);
- assert(p->multipart_state == MULTIPART_INACTIVE);
+ UPB_ASSERT(p->multipart_state == MULTIPART_INACTIVE);
p->multipart_state = MULTIPART_PUSHEAGERLY;
p->string_selector = sel;
}
@@ -10753,7 +12774,7 @@ static bool multipart_text(upb_json_parser *p, const char *buf, size_t len,
/* Note: this invalidates the accumulate buffer! Call only after reading its
* contents. */
static void multipart_end(upb_json_parser *p) {
- assert(p->multipart_state != MULTIPART_INACTIVE);
+ UPB_ASSERT(p->multipart_state != MULTIPART_INACTIVE);
p->multipart_state = MULTIPART_INACTIVE;
accumulate_clear(p);
}
@@ -10766,13 +12787,13 @@ static void multipart_end(upb_json_parser *p) {
* region. */
static void capture_begin(upb_json_parser *p, const char *ptr) {
- assert(p->multipart_state != MULTIPART_INACTIVE);
- assert(p->capture == NULL);
+ UPB_ASSERT(p->multipart_state != MULTIPART_INACTIVE);
+ UPB_ASSERT(p->capture == NULL);
p->capture = ptr;
}
static bool capture_end(upb_json_parser *p, const char *ptr) {
- assert(p->capture);
+ UPB_ASSERT(p->capture);
if (multipart_text(p, p->capture, ptr - p->capture, true)) {
p->capture = NULL;
return true;
@@ -10805,7 +12826,7 @@ static void capture_suspend(upb_json_parser *p, const char **ptr) {
static void capture_resume(upb_json_parser *p, const char *ptr) {
if (p->capture) {
- assert(p->capture == &suspend_capture);
+ UPB_ASSERT(p->capture == &suspend_capture);
p->capture = ptr;
}
}
@@ -10827,7 +12848,7 @@ static char escape_char(char in) {
case '"': return '"';
case '\\': return '\\';
default:
- assert(0);
+ UPB_ASSERT(0);
return 'x';
}
}
@@ -10851,7 +12872,7 @@ static void hexdigit(upb_json_parser *p, const char *ptr) {
} else if (ch >= 'a' && ch <= 'f') {
p->digit += ((ch - 'a') + 10);
} else {
- assert(ch >= 'A' && ch <= 'F');
+ UPB_ASSERT(ch >= 'A' && ch <= 'F');
p->digit += ((ch - 'A') + 10);
}
}
@@ -10897,103 +12918,160 @@ static void start_number(upb_json_parser *p, const char *ptr) {
capture_begin(p, ptr);
}
-static bool parse_number(upb_json_parser *p);
+static bool parse_number(upb_json_parser *p, bool is_quoted);
static bool end_number(upb_json_parser *p, const char *ptr) {
if (!capture_end(p, ptr)) {
return false;
}
- return parse_number(p);
+ return parse_number(p, false);
}
-static bool parse_number(upb_json_parser *p) {
- size_t len;
- const char *buf;
- const char *myend;
+/* |buf| is NULL-terminated. |buf| itself will never include quotes;
+ * |is_quoted| tells us whether this text originally appeared inside quotes. */
+static bool parse_number_from_buffer(upb_json_parser *p, const char *buf,
+ bool is_quoted) {
+ size_t len = strlen(buf);
+ const char *bufend = buf + len;
char *end;
+ upb_fieldtype_t type = upb_fielddef_type(p->top->f);
+ double val;
+ double dummy;
+ double inf = 1.0 / 0.0; /* C89 does not have an INFINITY macro. */
- /* strtol() and friends unfortunately do not support specifying the length of
- * the input string, so we need to force a copy into a NULL-terminated buffer. */
- if (!multipart_text(p, "\0", 1, false)) {
+ errno = 0;
+
+ if (len == 0 || buf[0] == ' ') {
return false;
}
- buf = accumulate_getptr(p, &len);
- myend = buf + len - 1; /* One for NULL. */
-
- /* XXX: We are using strtol to parse integers, but this is wrong as even
- * integers can be represented as 1e6 (for example), which strtol can't
- * handle correctly.
- *
- * XXX: Also, we can't handle large integers properly because strto[u]ll
- * isn't in C89.
- *
- * XXX: Also, we don't properly check floats for overflow, since strtof
- * isn't in C89. */
- switch (upb_fielddef_type(p->top->f)) {
+ /* For integer types, first try parsing with integer-specific routines.
+ * If these succeed, they will be more accurate for int64/uint64 than
+ * strtod().
+ */
+ switch (type) {
case UPB_TYPE_ENUM:
case UPB_TYPE_INT32: {
- long val = strtol(p->accumulated, &end, 0);
- if (val > INT32_MAX || val < INT32_MIN || errno == ERANGE || end != myend)
- goto err;
- else
+ long val = strtol(buf, &end, 0);
+ if (errno == ERANGE || end != bufend) {
+ break;
+ } else if (val > INT32_MAX || val < INT32_MIN) {
+ return false;
+ } else {
upb_sink_putint32(&p->top->sink, parser_getsel(p), val);
- break;
- }
- case UPB_TYPE_INT64: {
- long long val = strtol(p->accumulated, &end, 0);
- if (val > INT64_MAX || val < INT64_MIN || errno == ERANGE || end != myend)
- goto err;
- else
- upb_sink_putint64(&p->top->sink, parser_getsel(p), val);
- break;
+ return true;
+ }
}
case UPB_TYPE_UINT32: {
- unsigned long val = strtoul(p->accumulated, &end, 0);
- if (val > UINT32_MAX || errno == ERANGE || end != myend)
- goto err;
- else
+ unsigned long val = strtoul(buf, &end, 0);
+ if (end != bufend) {
+ break;
+ } else if (val > UINT32_MAX || errno == ERANGE) {
+ return false;
+ } else {
upb_sink_putuint32(&p->top->sink, parser_getsel(p), val);
- break;
+ return true;
+ }
+ }
+ /* XXX: We can't handle [u]int64 properly on 32-bit machines because
+ * strto[u]ll isn't in C89. */
+ case UPB_TYPE_INT64: {
+ long val = strtol(buf, &end, 0);
+ if (errno == ERANGE || end != bufend) {
+ break;
+ } else {
+ upb_sink_putint64(&p->top->sink, parser_getsel(p), val);
+ return true;
+ }
}
case UPB_TYPE_UINT64: {
- unsigned long long val = strtoul(p->accumulated, &end, 0);
- if (val > UINT64_MAX || errno == ERANGE || end != myend)
- goto err;
- else
+ unsigned long val = strtoul(p->accumulated, &end, 0);
+ if (end != bufend) {
+ break;
+ } else if (errno == ERANGE) {
+ return false;
+ } else {
upb_sink_putuint64(&p->top->sink, parser_getsel(p), val);
- break;
+ return true;
+ }
}
- case UPB_TYPE_DOUBLE: {
- double val = strtod(p->accumulated, &end);
- if (errno == ERANGE || end != myend)
- goto err;
- else
- upb_sink_putdouble(&p->top->sink, parser_getsel(p), val);
+ default:
break;
+ }
+
+ if (type != UPB_TYPE_DOUBLE && type != UPB_TYPE_FLOAT && is_quoted) {
+ /* Quoted numbers for integer types are not allowed to be in double form. */
+ return false;
+ }
+
+ if (len == strlen("Infinity") && strcmp(buf, "Infinity") == 0) {
+ /* C89 does not have an INFINITY macro. */
+ val = inf;
+ } else if (len == strlen("-Infinity") && strcmp(buf, "-Infinity") == 0) {
+ val = -inf;
+ } else {
+ val = strtod(buf, &end);
+ if (errno == ERANGE || end != bufend) {
+ return false;
}
- case UPB_TYPE_FLOAT: {
- float val = strtod(p->accumulated, &end);
- if (errno == ERANGE || end != myend)
- goto err;
- else
- upb_sink_putfloat(&p->top->sink, parser_getsel(p), val);
- break;
+ }
+
+ switch (type) {
+#define CASE(capitaltype, smalltype, ctype, min, max) \
+ case UPB_TYPE_ ## capitaltype: { \
+ if (modf(val, &dummy) != 0 || val > max || val < min) { \
+ return false; \
+ } else { \
+ upb_sink_put ## smalltype(&p->top->sink, parser_getsel(p), \
+ (ctype)val); \
+ return true; \
+ } \
+ break; \
}
+ case UPB_TYPE_ENUM:
+ CASE(INT32, int32, int32_t, INT32_MIN, INT32_MAX);
+ CASE(INT64, int64, int64_t, INT64_MIN, INT64_MAX);
+ CASE(UINT32, uint32, uint32_t, 0, UINT32_MAX);
+ CASE(UINT64, uint64, uint64_t, 0, UINT64_MAX);
+#undef CASE
+
+ case UPB_TYPE_DOUBLE:
+ upb_sink_putdouble(&p->top->sink, parser_getsel(p), val);
+ return true;
+ case UPB_TYPE_FLOAT:
+ if ((val > FLT_MAX || val < -FLT_MAX) && val != inf && val != -inf) {
+ return false;
+ } else {
+ upb_sink_putfloat(&p->top->sink, parser_getsel(p), val);
+ return true;
+ }
default:
- assert(false);
+ return false;
}
+}
- multipart_end(p);
+static bool parse_number(upb_json_parser *p, bool is_quoted) {
+ size_t len;
+ const char *buf;
- return true;
+ /* strtol() and friends unfortunately do not support specifying the length of
+ * the input string, so we need to force a copy into a NULL-terminated buffer. */
+ if (!multipart_text(p, "\0", 1, false)) {
+ return false;
+ }
-err:
- upb_status_seterrf(&p->status, "error parsing number: %s", buf);
- upb_env_reporterror(p->env, &p->status);
- multipart_end(p);
- return false;
+ buf = accumulate_getptr(p, &len);
+
+ if (parse_number_from_buffer(p, buf, is_quoted)) {
+ multipart_end(p);
+ return true;
+ } else {
+ upb_status_seterrf(&p->status, "error parsing number: %s", buf);
+ upb_env_reporterror(p->env, &p->status);
+ multipart_end(p);
+ return false;
+ }
}
static bool parser_putbool(upb_json_parser *p, bool val) {
@@ -11008,13 +13086,13 @@ static bool parser_putbool(upb_json_parser *p, bool val) {
}
ok = upb_sink_putbool(&p->top->sink, parser_getsel(p), val);
- UPB_ASSERT_VAR(ok, ok);
+ UPB_ASSERT(ok);
return true;
}
static bool start_stringval(upb_json_parser *p) {
- assert(p->top->f);
+ UPB_ASSERT(p->top->f);
if (upb_fielddef_isstring(p->top->f)) {
upb_jsonparser_frame *inner;
@@ -11046,17 +13124,16 @@ static bool start_stringval(upb_json_parser *p) {
multipart_startaccum(p);
return true;
}
- } else if (upb_fielddef_type(p->top->f) == UPB_TYPE_ENUM) {
- /* No need to push a frame -- symbolic enum names in quotes remain in the
- * current parser frame.
- *
- * Enum string values must accumulate so we can look up the value in a table
- * once it is complete. */
+ } else if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL &&
+ upb_fielddef_type(p->top->f) != UPB_TYPE_MESSAGE) {
+ /* No need to push a frame -- numeric values in quotes remain in the
+ * current parser frame. These values must accmulate so we can convert
+ * them all at once at the end. */
multipart_startaccum(p);
return true;
} else {
upb_status_seterrf(&p->status,
- "String specified for non-string/non-enum field: %s",
+ "String specified for bool or submessage field: %s",
upb_fielddef_name(p->top->f));
upb_env_reporterror(p->env, &p->status);
return false;
@@ -11103,8 +13180,17 @@ static bool end_stringval(upb_json_parser *p) {
break;
}
+ case UPB_TYPE_INT32:
+ case UPB_TYPE_INT64:
+ case UPB_TYPE_UINT32:
+ case UPB_TYPE_UINT64:
+ case UPB_TYPE_DOUBLE:
+ case UPB_TYPE_FLOAT:
+ ok = parse_number(p, true);
+ break;
+
default:
- assert(false);
+ UPB_ASSERT(false);
upb_status_seterrmsg(&p->status, "Internal error in JSON decoder");
upb_env_reporterror(p->env, &p->status);
ok = false;
@@ -11117,7 +13203,7 @@ static bool end_stringval(upb_json_parser *p) {
}
static void start_member(upb_json_parser *p) {
- assert(!p->top->f);
+ UPB_ASSERT(!p->top->f);
multipart_startaccum(p);
}
@@ -11146,7 +13232,7 @@ static bool parse_mapentry_key(upb_json_parser *p) {
case UPB_TYPE_UINT32:
case UPB_TYPE_UINT64:
/* Invoke end_number. The accum buffer has the number's text already. */
- if (!parse_number(p)) {
+ if (!parse_number(p, true)) {
return false;
}
break;
@@ -11246,7 +13332,7 @@ static bool handle_mapentry(upb_json_parser *p) {
}
static bool end_membername(upb_json_parser *p) {
- assert(!p->top->f);
+ UPB_ASSERT(!p->top->f);
if (p->top->is_map) {
return handle_mapentry(p);
@@ -11278,7 +13364,7 @@ static void end_member(upb_json_parser *p) {
bool ok;
const upb_fielddef *mapfield;
- assert(p->top > p->stack);
+ UPB_ASSERT(p->top > p->stack);
/* send ENDMSG on submsg. */
upb_sink_endmsg(&p->top->sink, &s);
mapfield = p->top->mapfield;
@@ -11286,7 +13372,7 @@ static void end_member(upb_json_parser *p) {
/* send ENDSUBMSG in repeated-field-of-mapentries frame. */
p->top--;
ok = upb_handlers_getselector(mapfield, UPB_HANDLER_ENDSUBMSG, &sel);
- UPB_ASSERT_VAR(ok, ok);
+ UPB_ASSERT(ok);
upb_sink_endsubmsg(&p->top->sink, sel);
}
@@ -11294,7 +13380,7 @@ static void end_member(upb_json_parser *p) {
}
static bool start_subobject(upb_json_parser *p) {
- assert(p->top->f);
+ UPB_ASSERT(p->top->f);
if (upb_fielddef_ismap(p->top->f)) {
upb_jsonparser_frame *inner;
@@ -11363,7 +13449,7 @@ static bool start_array(upb_json_parser *p) {
upb_jsonparser_frame *inner;
upb_selector_t sel;
- assert(p->top->f);
+ UPB_ASSERT(p->top->f);
if (!upb_fielddef_isseq(p->top->f)) {
upb_status_seterrf(&p->status,
@@ -11391,7 +13477,7 @@ static bool start_array(upb_json_parser *p) {
static void end_array(upb_json_parser *p) {
upb_selector_t sel;
- assert(p->top > p->stack);
+ UPB_ASSERT(p->top > p->stack);
p->top--;
sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
@@ -11437,11 +13523,11 @@ static void end_object(upb_json_parser *p) {
* final state once, when the closing '"' is seen. */
-#line 1245 "upb/json/parser.rl"
+#line 1310 "upb/json/parser.rl"
-#line 1157 "upb/json/parser.c"
+#line 1222 "upb/json/parser.c"
static const char _json_actions[] = {
0, 1, 0, 1, 2, 1, 3, 1,
5, 1, 6, 1, 7, 1, 8, 1,
@@ -11590,7 +13676,7 @@ static const int json_en_value_machine = 27;
static const int json_en_main = 1;
-#line 1248 "upb/json/parser.rl"
+#line 1313 "upb/json/parser.rl"
size_t parse(void *closure, const void *hd, const char *buf, size_t size,
const upb_bufhandle *handle) {
@@ -11612,7 +13698,7 @@ size_t parse(void *closure, const void *hd, const char *buf, size_t size,
capture_resume(parser, buf);
-#line 1328 "upb/json/parser.c"
+#line 1393 "upb/json/parser.c"
{
int _klen;
unsigned int _trans;
@@ -11687,118 +13773,118 @@ _match:
switch ( *_acts++ )
{
case 0:
-#line 1160 "upb/json/parser.rl"
+#line 1225 "upb/json/parser.rl"
{ p--; {cs = stack[--top]; goto _again;} }
break;
case 1:
-#line 1161 "upb/json/parser.rl"
+#line 1226 "upb/json/parser.rl"
{ p--; {stack[top++] = cs; cs = 10; goto _again;} }
break;
case 2:
-#line 1165 "upb/json/parser.rl"
+#line 1230 "upb/json/parser.rl"
{ start_text(parser, p); }
break;
case 3:
-#line 1166 "upb/json/parser.rl"
+#line 1231 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_text(parser, p)); }
break;
case 4:
-#line 1172 "upb/json/parser.rl"
+#line 1237 "upb/json/parser.rl"
{ start_hex(parser); }
break;
case 5:
-#line 1173 "upb/json/parser.rl"
+#line 1238 "upb/json/parser.rl"
{ hexdigit(parser, p); }
break;
case 6:
-#line 1174 "upb/json/parser.rl"
+#line 1239 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_hex(parser)); }
break;
case 7:
-#line 1180 "upb/json/parser.rl"
+#line 1245 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(escape(parser, p)); }
break;
case 8:
-#line 1186 "upb/json/parser.rl"
+#line 1251 "upb/json/parser.rl"
{ p--; {cs = stack[--top]; goto _again;} }
break;
case 9:
-#line 1189 "upb/json/parser.rl"
+#line 1254 "upb/json/parser.rl"
{ {stack[top++] = cs; cs = 19; goto _again;} }
break;
case 10:
-#line 1191 "upb/json/parser.rl"
+#line 1256 "upb/json/parser.rl"
{ p--; {stack[top++] = cs; cs = 27; goto _again;} }
break;
case 11:
-#line 1196 "upb/json/parser.rl"
+#line 1261 "upb/json/parser.rl"
{ start_member(parser); }
break;
case 12:
-#line 1197 "upb/json/parser.rl"
+#line 1262 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_membername(parser)); }
break;
case 13:
-#line 1200 "upb/json/parser.rl"
+#line 1265 "upb/json/parser.rl"
{ end_member(parser); }
break;
case 14:
-#line 1206 "upb/json/parser.rl"
+#line 1271 "upb/json/parser.rl"
{ start_object(parser); }
break;
case 15:
-#line 1209 "upb/json/parser.rl"
+#line 1274 "upb/json/parser.rl"
{ end_object(parser); }
break;
case 16:
-#line 1215 "upb/json/parser.rl"
+#line 1280 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(start_array(parser)); }
break;
case 17:
-#line 1219 "upb/json/parser.rl"
+#line 1284 "upb/json/parser.rl"
{ end_array(parser); }
break;
case 18:
-#line 1224 "upb/json/parser.rl"
+#line 1289 "upb/json/parser.rl"
{ start_number(parser, p); }
break;
case 19:
-#line 1225 "upb/json/parser.rl"
+#line 1290 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_number(parser, p)); }
break;
case 20:
-#line 1227 "upb/json/parser.rl"
+#line 1292 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(start_stringval(parser)); }
break;
case 21:
-#line 1228 "upb/json/parser.rl"
+#line 1293 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_stringval(parser)); }
break;
case 22:
-#line 1230 "upb/json/parser.rl"
+#line 1295 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(parser_putbool(parser, true)); }
break;
case 23:
-#line 1232 "upb/json/parser.rl"
+#line 1297 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(parser_putbool(parser, false)); }
break;
case 24:
-#line 1234 "upb/json/parser.rl"
+#line 1299 "upb/json/parser.rl"
{ /* null value */ }
break;
case 25:
-#line 1236 "upb/json/parser.rl"
+#line 1301 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(start_subobject(parser)); }
break;
case 26:
-#line 1237 "upb/json/parser.rl"
+#line 1302 "upb/json/parser.rl"
{ end_subobject(parser); }
break;
case 27:
-#line 1242 "upb/json/parser.rl"
+#line 1307 "upb/json/parser.rl"
{ p--; {cs = stack[--top]; goto _again;} }
break;
-#line 1514 "upb/json/parser.c"
+#line 1579 "upb/json/parser.c"
}
}
@@ -11811,7 +13897,7 @@ _again:
_out: {}
}
-#line 1269 "upb/json/parser.rl"
+#line 1334 "upb/json/parser.rl"
if (p != pe) {
upb_status_seterrf(&parser->status, "Parse error at '%.*s'\n", pe - p, p);
@@ -11852,13 +13938,13 @@ static void json_parser_reset(upb_json_parser *p) {
/* Emit Ragel initialization of the parser. */
-#line 1568 "upb/json/parser.c"
+#line 1633 "upb/json/parser.c"
{
cs = json_start;
top = 0;
}
-#line 1309 "upb/json/parser.rl"
+#line 1374 "upb/json/parser.rl"
p->current_state = cs;
p->parser_top = top;
accumulate_clear(p);
@@ -11922,7 +14008,7 @@ static void add_jsonname_table(upb_json_parsermethod *m, const upb_msgdef* md) {
buf = upb_grealloc(buf, 0, field_len);
len = field_len;
len2 = upb_fielddef_getjsonname(f, buf, len);
- UPB_ASSERT_VAR(len2, len == len2);
+ UPB_ASSERT(len == len2);
}
upb_strtable_insert(t, buf, upb_value_constptr(f));
@@ -11966,7 +14052,8 @@ upb_json_parser *upb_json_parser_create(upb_env *env,
/* If this fails, uncomment and increase the value in parser.h. */
/* fprintf(stderr, "%zd\n", upb_env_bytesallocated(env) - size_before); */
- assert(upb_env_bytesallocated(env) - size_before <= UPB_JSON_PARSER_SIZE);
+ UPB_ASSERT_DEBUGVAR(upb_env_bytesallocated(env) - size_before <=
+ UPB_JSON_PARSER_SIZE);
return p;
}
@@ -12054,7 +14141,7 @@ strpc *newstrpc(upb_handlers *h, const upb_fielddef *f,
ret->len = upb_fielddef_getjsonname(f, NULL, 0);
ret->ptr = upb_gmalloc(ret->len);
len = upb_fielddef_getjsonname(f, ret->ptr, ret->len);
- UPB_ASSERT_VAR(len, len == ret->len);
+ UPB_ASSERT(len == ret->len);
ret->len--; /* NULL */
}
@@ -12068,7 +14155,7 @@ static void print_data(
upb_json_printer *p, const char *buf, unsigned int len) {
/* TODO: Will need to change if we support pushback from the sink. */
size_t n = upb_bytessink_putbuf(p->output_, p->subc_, buf, len, NULL);
- UPB_ASSERT_VAR(n, n == len);
+ UPB_ASSERT(n == len);
}
static void print_comma(upb_json_printer *p) {
@@ -12154,10 +14241,23 @@ static void putstring(upb_json_printer *p, const char *buf, unsigned int len) {
* Right now we use %.8g and %.17g for float/double, respectively, to match
* proto2::util::JsonFormat's defaults. May want to change this later. */
+const char neginf[] = "\"-Infinity\"";
+const char inf[] = "\"Infinity\"";
+
static size_t fmt_double(double val, char* buf, size_t length) {
- size_t n = _upb_snprintf(buf, length, "%.17g", val);
- CHKLENGTH(n > 0 && n < length);
- return n;
+ if (val == (1.0 / 0.0)) {
+ CHKLENGTH(length >= strlen(inf));
+ strcpy(buf, inf);
+ return strlen(inf);
+ } else if (val == (-1.0 / 0.0)) {
+ CHKLENGTH(length >= strlen(neginf));
+ strcpy(buf, neginf);
+ return strlen(neginf);
+ } else {
+ size_t n = _upb_snprintf(buf, length, "%.17g", val);
+ CHKLENGTH(n > 0 && n < length);
+ return n;
+ }
}
static size_t fmt_float(float val, char* buf, size_t length) {
@@ -12418,7 +14518,7 @@ static size_t putbytes(void *closure, const void *handler_data, const char *str,
while (remaining > 2) {
/* TODO(haberman): handle encoded lengths > sizeof(data) */
- UPB_ASSERT_VAR(limit, (limit - to) >= 4);
+ UPB_ASSERT((limit - to) >= 4);
to[0] = base64[from[0] >> 2];
to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
@@ -12622,7 +14722,7 @@ void printer_sethandlers_mapentry(const void *closure, bool preserve_fieldnames,
upb_handlers_setstring(h, key_field, mapkey_bytes, &empty_attr);
break;
default:
- assert(false);
+ UPB_ASSERT(false);
break;
}
@@ -12796,7 +14896,8 @@ upb_json_printer *upb_json_printer_create(upb_env *e, const upb_handlers *h,
upb_sink_reset(&p->input_, h, p);
/* If this fails, increase the value in printer.h. */
- assert(upb_env_bytesallocated(e) - size_before <= UPB_JSON_PRINTER_SIZE);
+ UPB_ASSERT_DEBUGVAR(upb_env_bytesallocated(e) - size_before <=
+ UPB_JSON_PRINTER_SIZE);
return p;
}
diff --git a/ruby/ext/google/protobuf_c/upb.h b/ruby/ext/google/protobuf_c/upb.h
index e8b683bd..f441c89c 100644
--- a/ruby/ext/google/protobuf_c/upb.h
+++ b/ruby/ext/google/protobuf_c/upb.h
@@ -1,71 +1,5 @@
// Amalgamated source file
/*
-** Defs are upb's internal representation of the constructs that can appear
-** in a .proto file:
-**
-** - upb::MessageDef (upb_msgdef): describes a "message" construct.
-** - upb::FieldDef (upb_fielddef): describes a message field.
-** - upb::FileDef (upb_filedef): describes a .proto file and its defs.
-** - upb::EnumDef (upb_enumdef): describes an enum.
-** - upb::OneofDef (upb_oneofdef): describes a oneof.
-** - upb::Def (upb_def): base class of all the others.
-**
-** TODO: definitions of services.
-**
-** Like upb_refcounted objects, defs are mutable only until frozen, and are
-** only thread-safe once frozen.
-**
-** This is a mixed C/C++ interface that offers a full API to both languages.
-** See the top-level README for more information.
-*/
-
-#ifndef UPB_DEF_H_
-#define UPB_DEF_H_
-
-/*
-** upb::RefCounted (upb_refcounted)
-**
-** A refcounting scheme that supports circular refs. It accomplishes this by
-** partitioning the set of objects into groups such that no cycle spans groups;
-** we can then reference-count the group as a whole and ignore refs within the
-** group. When objects are mutable, these groups are computed very
-** conservatively; we group any objects that have ever had a link between them.
-** When objects are frozen, we compute strongly-connected components which
-** allows us to be precise and only group objects that are actually cyclic.
-**
-** This is a mixed C/C++ interface that offers a full API to both languages.
-** See the top-level README for more information.
-*/
-
-#ifndef UPB_REFCOUNTED_H_
-#define UPB_REFCOUNTED_H_
-
-/*
-** upb_table
-**
-** This header is INTERNAL-ONLY! Its interfaces are not public or stable!
-** This file defines very fast int->upb_value (inttable) and string->upb_value
-** (strtable) hash tables.
-**
-** The table uses chained scatter with Brent's variation (inspired by the Lua
-** implementation of hash tables). The hash function for strings is Austin
-** Appleby's "MurmurHash."
-**
-** The inttable uses uintptr_t as its key, which guarantees it can be used to
-** store pointers or integers of at least 32 bits (upb isn't really useful on
-** systems where sizeof(void*) < 4).
-**
-** The table must be homogeneous (all values of the same type). In debug
-** mode, we check this on insert and lookup.
-*/
-
-#ifndef UPB_TABLE_H_
-#define UPB_TABLE_H_
-
-#include <assert.h>
-#include <stdint.h>
-#include <string.h>
-/*
** This file contains shared definitions that are widely used across upb.
**
** This is a mixed C/C++ interface that offers a full API to both languages.
@@ -101,6 +35,9 @@ template <int N> class InlinedEnvironment;
#define UPB_INLINE static
#endif
+/* Hints to the compiler about likely/unlikely branches. */
+#define UPB_LIKELY(x) __builtin_expect((x),1)
+
/* Define UPB_BIG_ENDIAN manually if you're on big endian and your compiler
* doesn't provide these preprocessor symbols. */
#if defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
@@ -118,20 +55,21 @@ template <int N> class InlinedEnvironment;
#define UPB_NORETURN
#endif
+#if __STDC_VERSION__ >= 199901L || __cplusplus >= 201103L
+/* C99/C++11 versions. */
+#include <stdio.h>
+#define _upb_snprintf snprintf
+#define _upb_vsnprintf vsnprintf
+#define _upb_va_copy(a, b) va_copy(a, b)
+#elif defined __GNUC__
/* A few hacky workarounds for functions not in C89.
* For internal use only!
* TODO(haberman): fix these by including our own implementations, or finding
* another workaround.
*/
-#ifdef __GNUC__
#define _upb_snprintf __builtin_snprintf
#define _upb_vsnprintf __builtin_vsnprintf
#define _upb_va_copy(a, b) __va_copy(a, b)
-#elif __STDC_VERSION__ >= 199901L
-/* C99 versions. */
-#define _upb_snprintf snprintf
-#define _upb_vsnprintf vsnprintf
-#define _upb_va_copy(a, b) va_copy(a, b)
#else
#error Need implementations of [v]snprintf and va_copy
#endif
@@ -263,10 +201,23 @@ template <int N> class InlinedEnvironment;
#define UPB_UNUSED(var) (void)var
-/* For asserting something about a variable when the variable is not used for
- * anything else. This prevents "unused variable" warnings when compiling in
- * debug mode. */
-#define UPB_ASSERT_VAR(var, predicate) UPB_UNUSED(var); assert(predicate)
+/* UPB_ASSERT(): in release mode, we use the expression without letting it be
+ * evaluated. This prevents "unused variable" warnings. */
+#ifdef NDEBUG
+#define UPB_ASSERT(expr) do {} while (false && (expr))
+#else
+#define UPB_ASSERT(expr) assert(expr)
+#endif
+
+/* UPB_ASSERT_DEBUGVAR(): assert that uses functions or variables that only
+ * exist in debug mode. This turns into regular assert. */
+#define UPB_ASSERT_DEBUGVAR(expr) assert(expr)
+
+#ifdef __GNUC__
+#define UPB_UNREACHABLE() do { assert(0); __builtin_unreachable(); } while(0)
+#else
+#define UPB_UNREACHABLE() do { assert(0); } while(0)
+#endif
/* Generic function type. */
typedef void upb_func();
@@ -348,6 +299,16 @@ class PointerBase2 : public PointerBase<T, Base> {
#endif
+/* A list of types as they are encoded on-the-wire. */
+typedef enum {
+ UPB_WIRE_TYPE_VARINT = 0,
+ UPB_WIRE_TYPE_64BIT = 1,
+ UPB_WIRE_TYPE_DELIMITED = 2,
+ UPB_WIRE_TYPE_START_GROUP = 3,
+ UPB_WIRE_TYPE_END_GROUP = 4,
+ UPB_WIRE_TYPE_32BIT = 5
+} upb_wiretype_t;
+
/* upb::ErrorSpace ************************************************************/
@@ -501,17 +462,18 @@ struct upb_alloc {
};
UPB_INLINE void *upb_malloc(upb_alloc *alloc, size_t size) {
- assert(size > 0);
+ UPB_ASSERT(alloc);
return alloc->func(alloc, NULL, 0, size);
}
UPB_INLINE void *upb_realloc(upb_alloc *alloc, void *ptr, size_t oldsize,
size_t size) {
- assert(size > 0);
+ UPB_ASSERT(alloc);
return alloc->func(alloc, ptr, oldsize, size);
}
UPB_INLINE void upb_free(upb_alloc *alloc, void *ptr) {
+ assert(alloc);
alloc->func(alloc, ptr, 0, 0);
}
@@ -560,11 +522,11 @@ UPB_BEGIN_EXTERN_C
void upb_arena_init(upb_arena *a);
void upb_arena_init2(upb_arena *a, void *mem, size_t n, upb_alloc *alloc);
void upb_arena_uninit(upb_arena *a);
-upb_alloc *upb_arena_alloc(upb_arena *a);
bool upb_arena_addcleanup(upb_arena *a, upb_cleanup_func *func, void *ud);
size_t upb_arena_bytesallocated(const upb_arena *a);
void upb_arena_setnextblocksize(upb_arena *a, size_t size);
void upb_arena_setmaxblocksize(upb_arena *a, size_t size);
+UPB_INLINE upb_alloc *upb_arena_alloc(upb_arena *a) { return (upb_alloc*)a; }
UPB_END_EXTERN_C
@@ -675,7 +637,7 @@ void upb_env_uninit(upb_env *e);
void upb_env_initonly(upb_env *e);
-upb_arena *upb_env_arena(upb_env *e);
+UPB_INLINE upb_arena *upb_env_arena(upb_env *e) { return (upb_arena*)e; }
bool upb_env_ok(const upb_env *e);
void upb_env_seterrorfunc(upb_env *e, upb_error_func *func, void *ud);
@@ -775,6 +737,106 @@ template <int N> class upb::InlinedEnvironment : public upb::Environment {
#endif /* UPB_H_ */
+/*
+** upb_decode: parsing into a upb_msg using a upb_msglayout.
+*/
+
+#ifndef UPB_DECODE_H_
+#define UPB_DECODE_H_
+
+/*
+** upb::Message is a representation for protobuf messages.
+**
+** However it differs from other common representations like
+** google::protobuf::Message in one key way: it does not prescribe any
+** ownership between messages and submessages, and it relies on the
+** client to delete each message/submessage/array/map at the appropriate
+** time.
+**
+** A client can access a upb::Message without knowing anything about
+** ownership semantics, but to create or mutate a message a user needs
+** to implement the memory management themselves.
+**
+** Currently all messages, arrays, and maps store a upb_alloc* internally.
+** Mutating operations use this when they require dynamically-allocated
+** memory. We could potentially eliminate this size overhead later by
+** letting the user flip a bit on the factory that prevents this from
+** being stored. The user would then need to use separate functions where
+** the upb_alloc* is passed explicitly. However for handlers to populate
+** such structures, they would need a place to store this upb_alloc* during
+** parsing; upb_handlers don't currently have a good way to accommodate this.
+**
+** TODO: UTF-8 checking?
+**/
+
+#ifndef UPB_MSG_H_
+#define UPB_MSG_H_
+
+/*
+** Defs are upb's internal representation of the constructs that can appear
+** in a .proto file:
+**
+** - upb::MessageDef (upb_msgdef): describes a "message" construct.
+** - upb::FieldDef (upb_fielddef): describes a message field.
+** - upb::FileDef (upb_filedef): describes a .proto file and its defs.
+** - upb::EnumDef (upb_enumdef): describes an enum.
+** - upb::OneofDef (upb_oneofdef): describes a oneof.
+** - upb::Def (upb_def): base class of all the others.
+**
+** TODO: definitions of services.
+**
+** Like upb_refcounted objects, defs are mutable only until frozen, and are
+** only thread-safe once frozen.
+**
+** This is a mixed C/C++ interface that offers a full API to both languages.
+** See the top-level README for more information.
+*/
+
+#ifndef UPB_DEF_H_
+#define UPB_DEF_H_
+
+/*
+** upb::RefCounted (upb_refcounted)
+**
+** A refcounting scheme that supports circular refs. It accomplishes this by
+** partitioning the set of objects into groups such that no cycle spans groups;
+** we can then reference-count the group as a whole and ignore refs within the
+** group. When objects are mutable, these groups are computed very
+** conservatively; we group any objects that have ever had a link between them.
+** When objects are frozen, we compute strongly-connected components which
+** allows us to be precise and only group objects that are actually cyclic.
+**
+** This is a mixed C/C++ interface that offers a full API to both languages.
+** See the top-level README for more information.
+*/
+
+#ifndef UPB_REFCOUNTED_H_
+#define UPB_REFCOUNTED_H_
+
+/*
+** upb_table
+**
+** This header is INTERNAL-ONLY! Its interfaces are not public or stable!
+** This file defines very fast int->upb_value (inttable) and string->upb_value
+** (strtable) hash tables.
+**
+** The table uses chained scatter with Brent's variation (inspired by the Lua
+** implementation of hash tables). The hash function for strings is Austin
+** Appleby's "MurmurHash."
+**
+** The inttable uses uintptr_t as its key, which guarantees it can be used to
+** store pointers or integers of at least 32 bits (upb isn't really useful on
+** systems where sizeof(void*) < 4).
+**
+** The table must be homogenous (all values of the same type). In debug
+** mode, we check this on insert and lookup.
+*/
+
+#ifndef UPB_TABLE_H_
+#define UPB_TABLE_H_
+
+#include <stdint.h>
+#include <string.h>
#ifdef __cplusplus
extern "C" {
@@ -795,7 +857,9 @@ typedef enum {
UPB_CTYPE_CSTR = 6,
UPB_CTYPE_PTR = 7,
UPB_CTYPE_CONSTPTR = 8,
- UPB_CTYPE_FPTR = 9
+ UPB_CTYPE_FPTR = 9,
+ UPB_CTYPE_FLOAT = 10,
+ UPB_CTYPE_DOUBLE = 11
} upb_ctype_t;
typedef struct {
@@ -854,7 +918,7 @@ UPB_INLINE upb_value _upb_value_val(uint64_t val, upb_ctype_t ctype) {
return ret; \
} \
UPB_INLINE type_t upb_value_get ## name(upb_value val) { \
- assert(val.ctype == proto_type); \
+ UPB_ASSERT_DEBUGVAR(val.ctype == proto_type); \
return (type_t)(converter)val.val; \
}
@@ -869,6 +933,29 @@ FUNCS(constptr, constptr, const void*, uintptr_t, UPB_CTYPE_CONSTPTR)
FUNCS(fptr, fptr, upb_func*, uintptr_t, UPB_CTYPE_FPTR)
#undef FUNCS
+
+UPB_INLINE void upb_value_setfloat(upb_value *val, float cval) {
+ memcpy(&val->val, &cval, sizeof(cval));
+ SET_TYPE(val->ctype, UPB_CTYPE_FLOAT);
+}
+
+UPB_INLINE void upb_value_setdouble(upb_value *val, double cval) {
+ memcpy(&val->val, &cval, sizeof(cval));
+ SET_TYPE(val->ctype, UPB_CTYPE_DOUBLE);
+}
+
+UPB_INLINE upb_value upb_value_float(float cval) {
+ upb_value ret;
+ upb_value_setfloat(&ret, cval);
+ return ret;
+}
+
+UPB_INLINE upb_value upb_value_double(double cval) {
+ upb_value ret;
+ upb_value_setdouble(&ret, cval);
+ return ret;
+}
+
#undef SET_TYPE
@@ -1111,6 +1198,13 @@ UPB_INLINE size_t upb_strtable_count(const upb_strtable *t) {
return t->t.count;
}
+void upb_inttable_packedsize(const upb_inttable *t, size_t *size);
+void upb_strtable_packedsize(const upb_strtable *t, size_t *size);
+upb_inttable *upb_inttable_pack(const upb_inttable *t, void *p, size_t *ofs,
+ size_t size);
+upb_strtable *upb_strtable_pack(const upb_strtable *t, void *p, size_t *ofs,
+ size_t size);
+
/* Inserts the given key into the hashtable with the given value. The key must
* not already exist in the hash table. For string tables, the key must be
* NULL-terminated, and the table will make an internal copy of the key.
@@ -1556,7 +1650,7 @@ template <class T> class upb::reffed_ptr {
reffed_ptr(U* val, const void* ref_donor = NULL)
: ptr_(upb::upcast(val)) {
if (ref_donor) {
- assert(ptr_);
+ UPB_ASSERT(ptr_);
ptr_->DonateRef(ref_donor, this);
} else if (ptr_) {
ptr_->Ref(this);
@@ -1601,12 +1695,12 @@ template <class T> class upb::reffed_ptr {
}
T& operator*() const {
- assert(ptr_);
+ UPB_ASSERT(ptr_);
return *ptr_;
}
T* operator->() const {
- assert(ptr_);
+ UPB_ASSERT(ptr_);
return ptr_;
}
@@ -1657,6 +1751,7 @@ class FieldDef;
class FileDef;
class MessageDef;
class OneofDef;
+class SymbolTable;
}
#endif
@@ -1665,6 +1760,8 @@ UPB_DECLARE_DERIVED_TYPE(upb::OneofDef, upb::RefCounted, upb_oneofdef,
upb_refcounted)
UPB_DECLARE_DERIVED_TYPE(upb::FileDef, upb::RefCounted, upb_filedef,
upb_refcounted)
+UPB_DECLARE_TYPE(upb::SymbolTable, upb_symtab)
+
/* The maximum message depth that the type graph can have. This is a resource
* limit for the C stack since we sometimes need to recursively traverse the
@@ -1698,8 +1795,6 @@ class upb::Def {
public:
typedef upb_deftype_t Type;
- Def* Dup(const void *owner) const;
-
/* upb::RefCounted methods like Ref()/Unref(). */
UPB_REFCOUNTED_CPPMETHODS
@@ -1745,9 +1840,6 @@ class upb::Def {
UPB_BEGIN_EXTERN_C
-/* Native C API. */
-upb_def *upb_def_dup(const upb_def *def, const void *owner);
-
/* Include upb_refcounted methods like upb_def_ref()/upb_def_unref(). */
UPB_REFCOUNTED_CMETHODS(upb_def, upb_def_upcast)
@@ -1808,7 +1900,7 @@ UPB_END_EXTERN_C
return (upb_##lower *)def; \
} \
UPB_INLINE const upb_##lower *upb_downcast_##lower(const upb_def *def) { \
- assert(upb_def_type(def) == UPB_DEF_##upper); \
+ UPB_ASSERT(upb_def_type(def) == UPB_DEF_##upper); \
return (const upb_##lower *)def; \
} \
UPB_INLINE upb_##lower *upb_dyncast_##lower##_mutable(upb_def *def) { \
@@ -1844,15 +1936,19 @@ UPB_DECLARE_DEF_TYPE(upb::EnumDef, enumdef, ENUM)
* types defined in descriptor.proto, which gives INT32 and SINT32 separate
* types (we distinguish the two with the "integer encoding" enum below). */
typedef enum {
- UPB_TYPE_FLOAT = 1,
- UPB_TYPE_DOUBLE = 2,
- UPB_TYPE_BOOL = 3,
- UPB_TYPE_STRING = 4,
- UPB_TYPE_BYTES = 5,
- UPB_TYPE_MESSAGE = 6,
- UPB_TYPE_ENUM = 7, /* Enum values are int32. */
- UPB_TYPE_INT32 = 8,
- UPB_TYPE_UINT32 = 9,
+ /* Types stored in 1 byte. */
+ UPB_TYPE_BOOL = 1,
+ /* Types stored in 4 bytes. */
+ UPB_TYPE_FLOAT = 2,
+ UPB_TYPE_INT32 = 3,
+ UPB_TYPE_UINT32 = 4,
+ UPB_TYPE_ENUM = 5, /* Enum values are int32. */
+ /* Types stored as pointers (probably 4 or 8 bytes). */
+ UPB_TYPE_STRING = 6,
+ UPB_TYPE_BYTES = 7,
+ UPB_TYPE_MESSAGE = 8,
+ /* Types stored as 8 bytes. */
+ UPB_TYPE_DOUBLE = 9,
UPB_TYPE_INT64 = 10,
UPB_TYPE_UINT64 = 11
} upb_fieldtype_t;
@@ -1933,13 +2029,6 @@ class upb::FieldDef {
/* Returns NULL if memory allocation failed. */
static reffed_ptr<FieldDef> New();
- /* Duplicates the given field, returning NULL if memory allocation failed.
- * When a fielddef is duplicated, the subdef (if any) is made symbolic if it
- * wasn't already. If the subdef is set but has no name (which is possible
- * since msgdefs are not required to have a name) the new fielddef's subdef
- * will be unset. */
- FieldDef* Dup(const void* owner) const;
-
/* upb::RefCounted methods like Ref()/Unref(). */
UPB_REFCOUNTED_CPPMETHODS
@@ -2026,16 +2115,10 @@ class upb::FieldDef {
bool IsPrimitive() const;
bool IsMap() const;
- /* Whether this field must be able to explicitly represent presence:
- *
- * * This is always false for repeated fields (an empty repeated field is
- * equivalent to a repeated field with zero entries).
+ /* Returns whether this field explicitly represents presence.
*
- * * This is always true for submessages.
- *
- * * For other fields, it depends on the message (see
- * MessageDef::SetPrimitivesHavePresence())
- */
+ * For proto2 messages: Returns true for any scalar (non-repeated) field.
+ * For proto3 messages: Returns true for scalar submessage or oneof fields. */
bool HasPresence() const;
/* How integers are encoded. Only meaningful for integer types.
@@ -2194,7 +2277,6 @@ UPB_BEGIN_EXTERN_C
/* Native C API. */
upb_fielddef *upb_fielddef_new(const void *owner);
-upb_fielddef *upb_fielddef_dup(const upb_fielddef *f, const void *owner);
/* Include upb_refcounted methods like upb_fielddef_ref(). */
UPB_REFCOUNTED_CMETHODS(upb_fielddef, upb_fielddef_upcast2)
@@ -2404,16 +2486,6 @@ class upb::MessageDef {
return FindOneofByName(str.c_str(), str.size());
}
- /* Returns a new msgdef that is a copy of the given msgdef (and a copy of all
- * the fields) but with any references to submessages broken and replaced
- * with just the name of the submessage. Returns NULL if memory allocation
- * failed.
- *
- * TODO(haberman): which is more useful, keeping fields resolved or
- * unresolving them? If there's no obvious answer, Should this functionality
- * just be moved into symtab.c? */
- MessageDef* Dup(const void* owner) const;
-
/* Is this message a map entry? */
void setmapentry(bool map_entry);
bool mapentry() const;
@@ -2547,7 +2619,6 @@ UPB_REFCOUNTED_CMETHODS(upb_msgdef, upb_msgdef_upcast2)
bool upb_msgdef_freeze(upb_msgdef *m, upb_status *status);
-upb_msgdef *upb_msgdef_dup(const upb_msgdef *m, const void *owner);
const char *upb_msgdef_fullname(const upb_msgdef *m);
const char *upb_msgdef_name(const upb_msgdef *m);
int upb_msgdef_numoneofs(const upb_msgdef *m);
@@ -2697,10 +2768,6 @@ class upb::EnumDef {
* first one that was added. */
const char* FindValueByNumber(int32_t num) const;
- /* Returns a new EnumDef with all the same values. The new EnumDef will be
- * owned by the given owner. */
- EnumDef* Dup(const void* owner) const;
-
/* Iteration over name/value pairs. The order is undefined.
* Adding an enum val invalidates any iterators.
*
@@ -2728,7 +2795,6 @@ UPB_BEGIN_EXTERN_C
/* Native C API. */
upb_enumdef *upb_enumdef_new(const void *owner);
-upb_enumdef *upb_enumdef_dup(const upb_enumdef *e, const void *owner);
/* Include upb_refcounted methods like upb_enumdef_ref(). */
UPB_REFCOUNTED_CMETHODS(upb_enumdef, upb_enumdef_upcast2)
@@ -2773,6 +2839,7 @@ int32_t upb_enum_iter_number(upb_enum_iter *iter);
UPB_END_EXTERN_C
+
/* upb::OneofDef **************************************************************/
typedef upb_inttable_iter upb_oneof_iter;
@@ -2837,10 +2904,6 @@ class upb::OneofDef {
/* Looks up by tag number. */
const FieldDef* FindFieldByNumber(uint32_t num) const;
- /* Returns a new OneofDef with all the same fields. The OneofDef will be owned
- * by the given owner. */
- OneofDef* Dup(const void* owner) const;
-
/* Iteration over fields. The order is undefined. */
class iterator : public std::iterator<std::forward_iterator_tag, FieldDef*> {
public:
@@ -2886,16 +2949,16 @@ UPB_BEGIN_EXTERN_C
/* Native C API. */
upb_oneofdef *upb_oneofdef_new(const void *owner);
-upb_oneofdef *upb_oneofdef_dup(const upb_oneofdef *o, const void *owner);
/* Include upb_refcounted methods like upb_oneofdef_ref(). */
UPB_REFCOUNTED_CMETHODS(upb_oneofdef, upb_oneofdef_upcast)
const char *upb_oneofdef_name(const upb_oneofdef *o);
-bool upb_oneofdef_setname(upb_oneofdef *o, const char *name, upb_status *s);
-
const upb_msgdef *upb_oneofdef_containingtype(const upb_oneofdef *o);
int upb_oneofdef_numfields(const upb_oneofdef *o);
+uint32_t upb_oneofdef_index(const upb_oneofdef *o);
+
+bool upb_oneofdef_setname(upb_oneofdef *o, const char *name, upb_status *s);
bool upb_oneofdef_addfield(upb_oneofdef *o, upb_fielddef *f,
const void *ref_donor,
upb_status *s);
@@ -2951,6 +3014,17 @@ class upb::FileDef {
const char* package() const;
bool set_package(const char* package, Status* s);
+ /* Sets the php class prefix which is prepended to all php generated classes
+ * from this .proto. Default is empty. */
+ const char* phpprefix() const;
+ bool set_phpprefix(const char* phpprefix, Status* s);
+
+ /* Use this option to change the namespace of php generated classes. Default
+ * is empty. When this option is empty, the package name will be used for
+ * determining the namespace. */
+ const char* phpnamespace() const;
+ bool set_phpnamespace(const char* phpnamespace, Status* s);
+
/* Syntax for the file. Defaults to proto2. */
upb_syntax_t syntax() const;
void set_syntax(upb_syntax_t syntax);
@@ -3004,6 +3078,8 @@ UPB_REFCOUNTED_CMETHODS(upb_filedef, upb_filedef_upcast)
const char *upb_filedef_name(const upb_filedef *f);
const char *upb_filedef_package(const upb_filedef *f);
+const char *upb_filedef_phpprefix(const upb_filedef *f);
+const char *upb_filedef_phpnamespace(const upb_filedef *f);
upb_syntax_t upb_filedef_syntax(const upb_filedef *f);
size_t upb_filedef_defcount(const upb_filedef *f);
size_t upb_filedef_depcount(const upb_filedef *f);
@@ -3013,6 +3089,10 @@ const upb_filedef *upb_filedef_dep(const upb_filedef *f, size_t i);
bool upb_filedef_freeze(upb_filedef *f, upb_status *s);
bool upb_filedef_setname(upb_filedef *f, const char *name, upb_status *s);
bool upb_filedef_setpackage(upb_filedef *f, const char *package, upb_status *s);
+bool upb_filedef_setphpprefix(upb_filedef *f, const char *phpprefix,
+ upb_status *s);
+bool upb_filedef_setphpnamespace(upb_filedef *f, const char *phpnamespace,
+ upb_status *s);
bool upb_filedef_setsyntax(upb_filedef *f, upb_syntax_t syntax, upb_status *s);
bool upb_filedef_adddef(upb_filedef *f, upb_def *def, const void *ref_donor,
@@ -3039,19 +3119,163 @@ UPB_INLINE upb_def *upb_filedef_mutabledef(upb_filedef *f, int i) {
UPB_END_EXTERN_C
+typedef struct {
+ UPB_PRIVATE_FOR_CPP
+ upb_strtable_iter iter;
+ upb_deftype_t type;
+} upb_symtab_iter;
+
+#ifdef __cplusplus
+
+/* Non-const methods in upb::SymbolTable are NOT thread-safe. */
+class upb::SymbolTable {
+ public:
+ /* Returns a new symbol table with a single ref owned by "owner."
+ * Returns NULL if memory allocation failed. */
+ static SymbolTable* New();
+ static void Free(upb::SymbolTable* table);
+
+ /* For all lookup functions, the returned pointer is not owned by the
+ * caller; it may be invalidated by any non-const call or unref of the
+ * SymbolTable! To protect against this, take a ref if desired. */
+
+ /* Freezes the symbol table: prevents further modification of it.
+ * After the Freeze() operation is successful, the SymbolTable must only be
+ * accessed via a const pointer.
+ *
+ * Unlike with upb::MessageDef/upb::EnumDef/etc, freezing a SymbolTable is not
+ * a necessary step in using a SymbolTable. If you have no need for it to be
+ * immutable, there is no need to freeze it ever. However sometimes it is
+ * useful, and SymbolTables that are statically compiled into the binary are
+ * always frozen by nature. */
+ void Freeze();
+
+ /* Resolves the given symbol using the rules described in descriptor.proto,
+ * namely:
+ *
+ * If the name starts with a '.', it is fully-qualified. Otherwise,
+ * C++-like scoping rules are used to find the type (i.e. first the nested
+ * types within this message are searched, then within the parent, on up
+ * to the root namespace).
+ *
+ * If not found, returns NULL. */
+ const Def* Resolve(const char* base, const char* sym) const;
+
+ /* Finds an entry in the symbol table with this exact name. If not found,
+ * returns NULL. */
+ const Def* Lookup(const char *sym) const;
+ const MessageDef* LookupMessage(const char *sym) const;
+ const EnumDef* LookupEnum(const char *sym) const;
+
+ /* TODO: introduce a C++ iterator, but make it nice and templated so that if
+ * you ask for an iterator of MessageDef the iterated elements are strongly
+ * typed as MessageDef*. */
+
+ /* Adds the given mutable defs to the symtab, resolving all symbols (including
+ * enum default values) and finalizing the defs. Only one def per name may be
+ * in the list, and the defs may not duplicate any name already in the symtab.
+ * All defs must have a name -- anonymous defs are not allowed. Anonymous
+ * defs can still be frozen by calling upb_def_freeze() directly.
+ *
+ * The entire operation either succeeds or fails. If the operation fails,
+ * the symtab is unchanged, false is returned, and status indicates the
+ * error. The caller passes a ref on all defs to the symtab (even if the
+ * operation fails).
+ *
+ * TODO(haberman): currently failure will leave the symtab unchanged, but may
+ * leave the defs themselves partially resolved. Does this matter? If so we
+ * could do a prepass that ensures that all symbols are resolvable and bail
+ * if not, so we don't mutate anything until we know the operation will
+ * succeed. */
+ bool Add(Def*const* defs, size_t n, void* ref_donor, Status* status);
+
+ bool Add(const std::vector<Def*>& defs, void *owner, Status* status) {
+ return Add((Def*const*)&defs[0], defs.size(), owner, status);
+ }
+
+ /* Resolves all subdefs for messages in this file and attempts to freeze the
+ * file. If this succeeds, adds all the symbols to this SymbolTable
+ * (replacing any existing ones with the same names). */
+ bool AddFile(FileDef* file, Status* s);
+
+ private:
+ UPB_DISALLOW_POD_OPS(SymbolTable, upb::SymbolTable)
+};
+
+#endif /* __cplusplus */
+
+UPB_BEGIN_EXTERN_C
+
+/* Native C API. */
+
+upb_symtab *upb_symtab_new();
+void upb_symtab_free(upb_symtab* s);
+const upb_def *upb_symtab_resolve(const upb_symtab *s, const char *base,
+ const char *sym);
+const upb_def *upb_symtab_lookup(const upb_symtab *s, const char *sym);
+const upb_msgdef *upb_symtab_lookupmsg(const upb_symtab *s, const char *sym);
+const upb_enumdef *upb_symtab_lookupenum(const upb_symtab *s, const char *sym);
+bool upb_symtab_add(upb_symtab *s, upb_def *const*defs, size_t n,
+ void *ref_donor, upb_status *status);
+bool upb_symtab_addfile(upb_symtab *s, upb_filedef *file, upb_status* status);
+
+/* upb_symtab_iter i;
+ * for(upb_symtab_begin(&i, s, type); !upb_symtab_done(&i);
+ * upb_symtab_next(&i)) {
+ * const upb_def *def = upb_symtab_iter_def(&i);
+ * // ...
+ * }
+ *
+ * For C we don't have separate iterators for const and non-const.
+ * It is the caller's responsibility to cast the upb_fielddef* to
+ * const if the upb_msgdef* is const. */
+void upb_symtab_begin(upb_symtab_iter *iter, const upb_symtab *s,
+ upb_deftype_t type);
+void upb_symtab_next(upb_symtab_iter *iter);
+bool upb_symtab_done(const upb_symtab_iter *iter);
+const upb_def *upb_symtab_iter_def(const upb_symtab_iter *iter);
+
+UPB_END_EXTERN_C
+
+#ifdef __cplusplus
+/* C++ inline wrappers. */
+namespace upb {
+inline SymbolTable* SymbolTable::New() {
+ return upb_symtab_new();
+}
+inline void SymbolTable::Free(SymbolTable* s) {
+ upb_symtab_free(s);
+}
+inline const Def *SymbolTable::Resolve(const char *base,
+ const char *sym) const {
+ return upb_symtab_resolve(this, base, sym);
+}
+inline const Def* SymbolTable::Lookup(const char *sym) const {
+ return upb_symtab_lookup(this, sym);
+}
+inline const MessageDef *SymbolTable::LookupMessage(const char *sym) const {
+ return upb_symtab_lookupmsg(this, sym);
+}
+inline bool SymbolTable::Add(
+ Def*const* defs, size_t n, void* ref_donor, Status* status) {
+ return upb_symtab_add(this, (upb_def*const*)defs, n, ref_donor, status);
+}
+inline bool SymbolTable::AddFile(FileDef* file, Status* s) {
+ return upb_symtab_addfile(this, file, s);
+}
+} /* namespace upb */
+#endif
+
#ifdef __cplusplus
UPB_INLINE const char* upb_safecstr(const std::string& str) {
- assert(str.size() == std::strlen(str.c_str()));
+ UPB_ASSERT(str.size() == std::strlen(str.c_str()));
return str.c_str();
}
/* Inline C++ wrappers. */
namespace upb {
-inline Def* Def::Dup(const void* owner) const {
- return upb_def_dup(this, owner);
-}
inline Def::Type Def::def_type() const { return upb_def_type(this); }
inline const char* Def::full_name() const { return upb_def_fullname(this); }
inline const char* Def::name() const { return upb_def_name(this); }
@@ -3081,19 +3305,19 @@ inline bool FieldDef::CheckIntegerFormat(int32_t val) {
return upb_fielddef_checkintfmt(val);
}
inline FieldDef::Type FieldDef::ConvertType(int32_t val) {
- assert(CheckType(val));
+ UPB_ASSERT(CheckType(val));
return static_cast<FieldDef::Type>(val);
}
inline FieldDef::Label FieldDef::ConvertLabel(int32_t val) {
- assert(CheckLabel(val));
+ UPB_ASSERT(CheckLabel(val));
return static_cast<FieldDef::Label>(val);
}
inline FieldDef::DescriptorType FieldDef::ConvertDescriptorType(int32_t val) {
- assert(CheckDescriptorType(val));
+ UPB_ASSERT(CheckDescriptorType(val));
return static_cast<FieldDef::DescriptorType>(val);
}
inline FieldDef::IntegerFormat FieldDef::ConvertIntegerFormat(int32_t val) {
- assert(CheckIntegerFormat(val));
+ UPB_ASSERT(CheckIntegerFormat(val));
return static_cast<FieldDef::IntegerFormat>(val);
}
@@ -3101,9 +3325,6 @@ inline reffed_ptr<FieldDef> FieldDef::New() {
upb_fielddef *f = upb_fielddef_new(&f);
return reffed_ptr<FieldDef>(f, &f);
}
-inline FieldDef* FieldDef::Dup(const void* owner) const {
- return upb_fielddef_dup(this, owner);
-}
inline const char* FieldDef::full_name() const {
return upb_fielddef_fullname(this);
}
@@ -3343,9 +3564,6 @@ inline const OneofDef* MessageDef::FindOneofByName(const char* name,
size_t len) const {
return upb_msgdef_ntoo(this, name, len);
}
-inline MessageDef* MessageDef::Dup(const void *owner) const {
- return upb_msgdef_dup(this, owner);
-}
inline void MessageDef::setmapentry(bool map_entry) {
upb_msgdef_setmapentry(this, map_entry);
}
@@ -3515,9 +3733,6 @@ inline bool EnumDef::FindValueByName(const char* name, int32_t *num) const {
inline const char* EnumDef::FindValueByNumber(int32_t num) const {
return upb_enumdef_iton(this, num);
}
-inline EnumDef* EnumDef::Dup(const void* owner) const {
- return upb_enumdef_dup(this, owner);
-}
inline EnumDef::Iterator::Iterator(const EnumDef* e) {
upb_enum_begin(&iter_, e);
@@ -3636,6 +3851,18 @@ inline const char* FileDef::package() const {
inline bool FileDef::set_package(const char* package, Status* s) {
return upb_filedef_setpackage(this, package, s);
}
+inline const char* FileDef::phpprefix() const {
+ return upb_filedef_phpprefix(this);
+}
+inline bool FileDef::set_phpprefix(const char* phpprefix, Status* s) {
+ return upb_filedef_setphpprefix(this, phpprefix, s);
+}
+inline const char* FileDef::phpnamespace() const {
+ return upb_filedef_phpnamespace(this);
+}
+inline bool FileDef::set_phpnamespace(const char* phpnamespace, Status* s) {
+ return upb_filedef_setphpnamespace(this, phpnamespace, s);
+}
inline int FileDef::def_count() const {
return upb_filedef_defcount(this);
}
@@ -3672,193 +3899,6 @@ inline bool FileDef::AddDependency(const FileDef* file) {
#endif /* UPB_DEF_H_ */
/*
-** This file contains definitions of structs that should be considered private
-** and NOT stable across versions of upb.
-**
-** The only reason they are declared here and not in .c files is to allow upb
-** and the application (if desired) to embed statically-initialized instances
-** of structures like defs.
-**
-** If you include this file, all guarantees of ABI compatibility go out the
-** window! Any code that includes this file needs to recompile against the
-** exact same version of upb that they are linking against.
-**
-** You also need to recompile if you change the value of the UPB_DEBUG_REFS
-** flag.
-*/
-
-
-#ifndef UPB_STATICINIT_H_
-#define UPB_STATICINIT_H_
-
-#ifdef __cplusplus
-/* Because of how we do our typedefs, this header can't be included from C++. */
-#error This file cannot be included from C++
-#endif
-
-/* upb_refcounted *************************************************************/
-
-
-/* upb_def ********************************************************************/
-
-struct upb_def {
- upb_refcounted base;
-
- const char *fullname;
- const upb_filedef* file;
- char type; /* A upb_deftype_t (char to save space) */
-
- /* Used as a flag during the def's mutable stage. Must be false unless
- * it is currently being used by a function on the stack. This allows
- * us to easily determine which defs were passed into the function's
- * current invocation. */
- bool came_from_user;
-};
-
-#define UPB_DEF_INIT(name, type, vtbl, refs, ref2s) \
- { UPB_REFCOUNT_INIT(vtbl, refs, ref2s), name, NULL, type, false }
-
-
-/* upb_fielddef ***************************************************************/
-
-struct upb_fielddef {
- upb_def base;
-
- union {
- int64_t sint;
- uint64_t uint;
- double dbl;
- float flt;
- void *bytes;
- } defaultval;
- union {
- const upb_msgdef *def; /* If !msg_is_symbolic. */
- char *name; /* If msg_is_symbolic. */
- } msg;
- union {
- const upb_def *def; /* If !subdef_is_symbolic. */
- char *name; /* If subdef_is_symbolic. */
- } sub; /* The msgdef or enumdef for this field, if upb_hassubdef(f). */
- bool subdef_is_symbolic;
- bool msg_is_symbolic;
- const upb_oneofdef *oneof;
- bool default_is_string;
- bool type_is_set_; /* False until type is explicitly set. */
- bool is_extension_;
- bool lazy_;
- bool packed_;
- upb_intfmt_t intfmt;
- bool tagdelim;
- upb_fieldtype_t type_;
- upb_label_t label_;
- uint32_t number_;
- uint32_t selector_base; /* Used to index into a upb::Handlers table. */
- uint32_t index_;
-};
-
-extern const struct upb_refcounted_vtbl upb_fielddef_vtbl;
-
-#define UPB_FIELDDEF_INIT(label, type, intfmt, tagdelim, is_extension, lazy, \
- packed, name, num, msgdef, subdef, selector_base, \
- index, defaultval, refs, ref2s) \
- { \
- UPB_DEF_INIT(name, UPB_DEF_FIELD, &upb_fielddef_vtbl, refs, ref2s), \
- defaultval, {msgdef}, {subdef}, NULL, false, false, \
- type == UPB_TYPE_STRING || type == UPB_TYPE_BYTES, true, is_extension, \
- lazy, packed, intfmt, tagdelim, type, label, num, selector_base, index \
- }
-
-
-/* upb_msgdef *****************************************************************/
-
-struct upb_msgdef {
- upb_def base;
-
- size_t selector_count;
- uint32_t submsg_field_count;
-
- /* Tables for looking up fields by number and name. */
- upb_inttable itof; /* int to field */
- upb_strtable ntof; /* name to field/oneof */
-
- /* Is this a map-entry message? */
- bool map_entry;
-
- /* Whether this message has proto2 or proto3 semantics. */
- upb_syntax_t syntax;
-
- /* TODO(haberman): proper extension ranges (there can be multiple). */
-};
-
-extern const struct upb_refcounted_vtbl upb_msgdef_vtbl;
-
-/* TODO: also support static initialization of the oneofs table. This will be
- * needed if we compile in descriptors that contain oneofs. */
-#define UPB_MSGDEF_INIT(name, selector_count, submsg_field_count, itof, ntof, \
- map_entry, syntax, refs, ref2s) \
- { \
- UPB_DEF_INIT(name, UPB_DEF_MSG, &upb_fielddef_vtbl, refs, ref2s), \
- selector_count, submsg_field_count, itof, ntof, map_entry, syntax \
- }
-
-
-/* upb_enumdef ****************************************************************/
-
-struct upb_enumdef {
- upb_def base;
-
- upb_strtable ntoi;
- upb_inttable iton;
- int32_t defaultval;
-};
-
-extern const struct upb_refcounted_vtbl upb_enumdef_vtbl;
-
-#define UPB_ENUMDEF_INIT(name, ntoi, iton, defaultval, refs, ref2s) \
- { UPB_DEF_INIT(name, UPB_DEF_ENUM, &upb_enumdef_vtbl, refs, ref2s), ntoi, \
- iton, defaultval }
-
-
-/* upb_oneofdef ***************************************************************/
-
-struct upb_oneofdef {
- upb_refcounted base;
-
- const char *name;
- upb_strtable ntof;
- upb_inttable itof;
- const upb_msgdef *parent;
-};
-
-extern const struct upb_refcounted_vtbl upb_oneofdef_vtbl;
-
-#define UPB_ONEOFDEF_INIT(name, ntof, itof, refs, ref2s) \
- { UPB_REFCOUNT_INIT(&upb_oneofdef_vtbl, refs, ref2s), name, ntof, itof }
-
-
-/* upb_symtab *****************************************************************/
-
-struct upb_symtab {
- upb_refcounted base;
-
- upb_strtable symtab;
-};
-
-struct upb_filedef {
- upb_refcounted base;
-
- const char *name;
- const char *package;
- upb_syntax_t syntax;
-
- upb_inttable defs;
- upb_inttable deps;
-};
-
-extern const struct upb_refcounted_vtbl upb_filedef_vtbl;
-
-#endif /* UPB_STATICINIT_H_ */
-/*
** upb::Handlers (upb_handlers)
**
** A upb_handlers is like a virtual table for a upb_msgdef. Each field of the
@@ -3962,7 +4002,8 @@ UPB_END_EXTERN_C
/* Static selectors for upb::Handlers. */
#define UPB_STARTMSG_SELECTOR 0
#define UPB_ENDMSG_SELECTOR 1
-#define UPB_STATIC_SELECTOR_COUNT 2
+#define UPB_UNKNOWN_SELECTOR 2
+#define UPB_STATIC_SELECTOR_COUNT 3
/* Static selectors for upb::BytesHandler. */
#define UPB_STARTSTR_SELECTOR 0
@@ -4469,7 +4510,7 @@ template <class T> class Handler {
void AddCleanup(Handlers* h) const {
if (cleanup_func_) {
bool ok = h->AddCleanup(cleanup_data_, cleanup_func_);
- UPB_ASSERT_VAR(ok, ok);
+ UPB_ASSERT(ok);
}
}
@@ -4491,6 +4532,8 @@ UPB_BEGIN_EXTERN_C
/* Native C API. */
/* Handler function typedefs. */
+typedef bool upb_unknown_handlerfunc(void *c, const void *hd, const char *buf,
+ size_t n);
typedef bool upb_startmsg_handlerfunc(void *c, const void*);
typedef bool upb_endmsg_handlerfunc(void *c, const void *, upb_status *status);
typedef void* upb_startfield_handlerfunc(void *c, const void *hd);
@@ -4544,6 +4587,8 @@ const upb_status *upb_handlers_status(upb_handlers *h);
void upb_handlers_clearerr(upb_handlers *h);
const upb_msgdef *upb_handlers_msgdef(const upb_handlers *h);
bool upb_handlers_addcleanup(upb_handlers *h, void *p, upb_handlerfree *hfree);
+bool upb_handlers_setunknown(upb_handlers *h, upb_unknown_handlerfunc *func,
+ upb_handlerattr *attr);
bool upb_handlers_setstartmsg(upb_handlers *h, upb_startmsg_handlerfunc *func,
upb_handlerattr *attr);
@@ -5489,7 +5534,7 @@ struct ConvertParams<BoundFunc5<R, P1, P2, P3, P4, P5, F, I>, T> {
inline bool Handlers::SetValueHandler<vtype>( \
const FieldDef *f, \
const Handlers::utype ## Handler& handler) { \
- assert(!handler.registered_); \
+ UPB_ASSERT(!handler.registered_); \
handler.AddCleanup(this); \
handler.registered_ = true; \
return upb_handlers_set##ltype(this, f, handler.handler_, &handler.attr_); \
@@ -5601,7 +5646,7 @@ inline Handler<T>::Handler(F func)
template <class T>
inline Handler<T>::~Handler() {
- assert(registered_);
+ UPB_ASSERT(registered_);
}
inline HandlerAttributes::HandlerAttributes() { upb_handlerattr_init(this); }
@@ -5687,63 +5732,63 @@ inline bool Handlers::AddCleanup(void *p, upb_handlerfree *func) {
}
inline bool Handlers::SetStartMessageHandler(
const Handlers::StartMessageHandler &handler) {
- assert(!handler.registered_);
+ UPB_ASSERT(!handler.registered_);
handler.registered_ = true;
handler.AddCleanup(this);
return upb_handlers_setstartmsg(this, handler.handler_, &handler.attr_);
}
inline bool Handlers::SetEndMessageHandler(
const Handlers::EndMessageHandler &handler) {
- assert(!handler.registered_);
+ UPB_ASSERT(!handler.registered_);
handler.registered_ = true;
handler.AddCleanup(this);
return upb_handlers_setendmsg(this, handler.handler_, &handler.attr_);
}
inline bool Handlers::SetStartStringHandler(const FieldDef *f,
const StartStringHandler &handler) {
- assert(!handler.registered_);
+ UPB_ASSERT(!handler.registered_);
handler.registered_ = true;
handler.AddCleanup(this);
return upb_handlers_setstartstr(this, f, handler.handler_, &handler.attr_);
}
inline bool Handlers::SetEndStringHandler(const FieldDef *f,
const EndFieldHandler &handler) {
- assert(!handler.registered_);
+ UPB_ASSERT(!handler.registered_);
handler.registered_ = true;
handler.AddCleanup(this);
return upb_handlers_setendstr(this, f, handler.handler_, &handler.attr_);
}
inline bool Handlers::SetStringHandler(const FieldDef *f,
const StringHandler& handler) {
- assert(!handler.registered_);
+ UPB_ASSERT(!handler.registered_);
handler.registered_ = true;
handler.AddCleanup(this);
return upb_handlers_setstring(this, f, handler.handler_, &handler.attr_);
}
inline bool Handlers::SetStartSequenceHandler(
const FieldDef *f, const StartFieldHandler &handler) {
- assert(!handler.registered_);
+ UPB_ASSERT(!handler.registered_);
handler.registered_ = true;
handler.AddCleanup(this);
return upb_handlers_setstartseq(this, f, handler.handler_, &handler.attr_);
}
inline bool Handlers::SetStartSubMessageHandler(
const FieldDef *f, const StartFieldHandler &handler) {
- assert(!handler.registered_);
+ UPB_ASSERT(!handler.registered_);
handler.registered_ = true;
handler.AddCleanup(this);
return upb_handlers_setstartsubmsg(this, f, handler.handler_, &handler.attr_);
}
inline bool Handlers::SetEndSubMessageHandler(const FieldDef *f,
const EndFieldHandler &handler) {
- assert(!handler.registered_);
+ UPB_ASSERT(!handler.registered_);
handler.registered_ = true;
handler.AddCleanup(this);
return upb_handlers_setendsubmsg(this, f, handler.handler_, &handler.attr_);
}
inline bool Handlers::SetEndSequenceHandler(const FieldDef *f,
const EndFieldHandler &handler) {
- assert(!handler.registered_);
+ UPB_ASSERT(!handler.registered_);
handler.registered_ = true;
handler.AddCleanup(this);
return upb_handlers_setendseq(this, f, handler.handler_, &handler.attr_);
@@ -5820,12 +5865,14 @@ inline BytesHandler::~BytesHandler() {}
#ifdef __cplusplus
namespace upb {
+class BufferSink;
class BufferSource;
class BytesSink;
class Sink;
}
#endif
+UPB_DECLARE_TYPE(upb::BufferSink, upb_bufsink)
UPB_DECLARE_TYPE(upb::BufferSource, upb_bufsrc)
UPB_DECLARE_TYPE(upb::BytesSink, upb_bytessink)
UPB_DECLARE_TYPE(upb::Sink, upb_sink)
@@ -6012,6 +6059,13 @@ struct upb_bufsrc {
UPB_BEGIN_EXTERN_C
+/* A class for accumulating output string data in a flat buffer. */
+
+upb_bufsink *upb_bufsink_new(upb_env *env);
+void upb_bufsink_free(upb_bufsink *sink);
+upb_bytessink *upb_bufsink_sink(upb_bufsink *sink);
+const char *upb_bufsink_getdata(const upb_bufsink *sink, size_t *len);
+
/* Inline definitions. */
UPB_INLINE void upb_bytessink_reset(upb_bytessink *s, const upb_byteshandler *h,
@@ -6061,23 +6115,7 @@ UPB_INLINE bool upb_bytessink_end(upb_bytessink *s) {
&s->handler->table[UPB_ENDSTR_SELECTOR].attr));
}
-UPB_INLINE bool upb_bufsrc_putbuf(const char *buf, size_t len,
- upb_bytessink *sink) {
- void *subc;
- bool ret;
- upb_bufhandle handle;
- upb_bufhandle_init(&handle);
- upb_bufhandle_setbuf(&handle, buf, 0);
- ret = upb_bytessink_start(sink, len, &subc);
- if (ret && len != 0) {
- ret = (upb_bytessink_putbuf(sink, subc, buf, len, &handle) >= len);
- }
- if (ret) {
- ret = upb_bytessink_end(sink);
- }
- upb_bufhandle_uninit(&handle);
- return ret;
-}
+bool upb_bufsrc_putbuf(const char *buf, size_t len, upb_bytessink *sink);
#define PUTVAL(type, ctype) \
UPB_INLINE bool upb_sink_put##type(upb_sink *s, upb_selector_t sel, \
@@ -6120,6 +6158,18 @@ UPB_INLINE size_t upb_sink_putstring(upb_sink *s, upb_selector_t sel,
return handler(s->closure, hd, buf, n, handle);
}
+UPB_INLINE bool upb_sink_putunknown(upb_sink *s, const char *buf, size_t n) {
+ typedef upb_unknown_handlerfunc func;
+ func *handler;
+ const void *hd;
+ if (!s->handlers) return true;
+ handler = (func *)upb_handlers_gethandler(s->handlers, UPB_UNKNOWN_SELECTOR);
+
+ if (!handler) return n;
+ hd = upb_handlers_gethandlerdata(s->handlers, UPB_UNKNOWN_SELECTOR);
+ return handler(s->closure, hd, buf, n);
+}
+
UPB_INLINE bool upb_sink_startmsg(upb_sink *s) {
typedef upb_startmsg_handlerfunc func;
func *startmsg;
@@ -6324,268 +6374,642 @@ inline bool BufferSource::PutBuffer(const char *buf, size_t len,
#endif
#endif
-/*
-** For handlers that do very tiny, very simple operations, the function call
-** overhead of calling a handler can be significant. This file allows the
-** user to define handlers that do something very simple like store the value
-** to memory and/or set a hasbit. JIT compilers can then special-case these
-** handlers and emit specialized code for them instead of actually calling the
-** handler.
-**
-** The functionality is very simple/limited right now but may expand to be able
-** to call another function.
-*/
-#ifndef UPB_SHIM_H
-#define UPB_SHIM_H
+#ifdef __cplusplus
+
+namespace upb {
+class Array;
+class Map;
+class MapIterator;
+class MessageFactory;
+class MessageLayout;
+class Visitor;
+class VisitorPlan;
+}
+
+#endif
+
+UPB_DECLARE_TYPE(upb::MessageFactory, upb_msgfactory)
+UPB_DECLARE_TYPE(upb::MessageLayout, upb_msglayout)
+UPB_DECLARE_TYPE(upb::Array, upb_array)
+UPB_DECLARE_TYPE(upb::Map, upb_map)
+UPB_DECLARE_TYPE(upb::MapIterator, upb_mapiter)
+UPB_DECLARE_TYPE(upb::Visitor, upb_visitor)
+UPB_DECLARE_TYPE(upb::VisitorPlan, upb_visitorplan)
+
+/* TODO(haberman): C++ accessors */
+
+UPB_BEGIN_EXTERN_C
+
+typedef void upb_msg;
+
+
+/** upb_msglayout *************************************************************/
+
+/* upb_msglayout represents the memory layout of a given upb_msgdef. You get
+ * instances of this from a upb_msgfactory, and the factory always owns the
+ * msglayout. */
+
+
+/** upb_visitor ***************************************************************/
+
+/* upb_visitor will visit all the fields of a message and its submessages. It
+ * uses a upb_visitorplan which you can obtain from a upb_msgfactory. */
+
+upb_visitor *upb_visitor_create(upb_env *e, const upb_visitorplan *vp,
+ upb_sink *output);
+bool upb_visitor_visitmsg(upb_visitor *v, const upb_msg *msg);
+
+
+/** upb_msgfactory ************************************************************/
+
+/* A upb_msgfactory contains a cache of upb_msglayout, upb_handlers, and
+ * upb_visitorplan objects. These are the objects necessary to represent,
+ * populate, and and visit upb_msg objects.
+ *
+ * These caches are all populated by upb_msgdef, and lazily created on demand.
+ */
+
+/* Creates and destroys a msgfactory, respectively. The messages for this
+ * msgfactory must come from |symtab| (which should outlive the msgfactory). */
+upb_msgfactory *upb_msgfactory_new(const upb_symtab *symtab);
+void upb_msgfactory_free(upb_msgfactory *f);
+
+const upb_symtab *upb_msgfactory_symtab(const upb_msgfactory *f);
+
+/* The functions to get cached objects, lazily creating them on demand. These
+ * all require:
+ *
+ * - m is in upb_msgfactory_symtab(f)
+ * - upb_msgdef_mapentry(m) == false (since map messages can't have layouts).
+ *
+ * The returned objects will live for as long as the msgfactory does.
+ *
+ * TODO(haberman): consider making this thread-safe and take a const
+ * upb_msgfactory. */
+const upb_msglayout *upb_msgfactory_getlayout(upb_msgfactory *f,
+ const upb_msgdef *m);
+const upb_handlers *upb_msgfactory_getmergehandlers(upb_msgfactory *f,
+ const upb_msgdef *m);
+const upb_visitorplan *upb_msgfactory_getvisitorplan(upb_msgfactory *f,
+ const upb_handlers *h);
+
+/** upb_stringview ************************************************************/
typedef struct {
- size_t offset;
- int32_t hasbit;
-} upb_shim_data;
+ const char *data;
+ size_t size;
+} upb_stringview;
+
+UPB_INLINE upb_stringview upb_stringview_make(const char *data, size_t size) {
+ upb_stringview ret;
+ ret.data = data;
+ ret.size = size;
+ return ret;
+}
-#ifdef __cplusplus
+#define UPB_STRINGVIEW_INIT(ptr, len) {ptr, len}
-namespace upb {
-struct Shim {
- typedef upb_shim_data Data;
+/** upb_msgval ****************************************************************/
- /* Sets a handler for the given field that writes the value to the given
- * offset and, if hasbit >= 0, sets a bit at the given bit offset. Returns
- * true if the handler was set successfully. */
- static bool Set(Handlers *h, const FieldDef *f, size_t ofs, int32_t hasbit);
+/* A union representing all possible protobuf values. Used for generic get/set
+ * operations. */
- /* If this handler is a shim, returns the corresponding upb::Shim::Data and
- * stores the type in "type". Otherwise returns NULL. */
- static const Data* GetData(const Handlers* h, Handlers::Selector s,
- FieldDef::Type* type);
-};
+typedef union {
+ bool b;
+ float flt;
+ double dbl;
+ int32_t i32;
+ int64_t i64;
+ uint32_t u32;
+ uint64_t u64;
+ const upb_map* map;
+ const upb_msg* msg;
+ const upb_array* arr;
+ const void* ptr;
+ upb_stringview str;
+} upb_msgval;
+
+#define ACCESSORS(name, membername, ctype) \
+ UPB_INLINE ctype upb_msgval_get ## name(upb_msgval v) { \
+ return v.membername; \
+ } \
+ UPB_INLINE void upb_msgval_set ## name(upb_msgval *v, ctype cval) { \
+ v->membername = cval; \
+ } \
+ UPB_INLINE upb_msgval upb_msgval_ ## name(ctype v) { \
+ upb_msgval ret; \
+ ret.membername = v; \
+ return ret; \
+ }
-} /* namespace upb */
+ACCESSORS(bool, b, bool)
+ACCESSORS(float, flt, float)
+ACCESSORS(double, dbl, double)
+ACCESSORS(int32, i32, int32_t)
+ACCESSORS(int64, i64, int64_t)
+ACCESSORS(uint32, u32, uint32_t)
+ACCESSORS(uint64, u64, uint64_t)
+ACCESSORS(map, map, const upb_map*)
+ACCESSORS(msg, msg, const upb_msg*)
+ACCESSORS(ptr, ptr, const void*)
+ACCESSORS(arr, arr, const upb_array*)
+ACCESSORS(str, str, upb_stringview)
-#endif
+#undef ACCESSORS
+
+UPB_INLINE upb_msgval upb_msgval_makestr(const char *data, size_t size) {
+ return upb_msgval_str(upb_stringview_make(data, size));
+}
+
+
+/** upb_msg *******************************************************************/
+
+/* A upb_msg represents a protobuf message. It always corresponds to a specific
+ * upb_msglayout, which describes how it is laid out in memory.
+ *
+ * The message will have a fixed size, as returned by upb_msg_sizeof(), which
+ * will be used to store fixed-length fields. The upb_msg may also allocate
+ * dynamic memory internally to store data such as:
+ *
+ * - extensions
+ * - unknown fields
+ */
+
+/* Returns the size of a message given this layout. */
+size_t upb_msg_sizeof(const upb_msglayout *l);
+
+/* upb_msg_init() / upb_msg_uninit() allow the user to use a pre-allocated
+ * block of memory as a message. The block's size should be upb_msg_sizeof().
+ * upb_msg_uninit() must be called to release internally-allocated memory
+ * unless the allocator is an arena that does not require freeing.
+ *
+ * Please note that upb_msg_init() may return a value that is different than
+ * |msg|, so you must assign the return value and not cast your memory block
+ * to upb_msg* directly!
+ *
+ * Please note that upb_msg_uninit() does *not* free any submessages, maps,
+ * or arrays referred to by this message's fields. You must free them manually
+ * yourself.
+ *
+ * upb_msg_uninit returns the original memory block, which may be useful if
+ * you dynamically allocated it (though upb_msg_new() would normally be more
+ * appropriate in this case). */
+upb_msg *upb_msg_init(void *msg, const upb_msglayout *l, upb_alloc *a);
+void *upb_msg_uninit(upb_msg *msg, const upb_msglayout *l);
+
+/* Like upb_msg_init() / upb_msg_uninit(), except the message's memory is
+ * allocated / freed from the given upb_alloc. */
+upb_msg *upb_msg_new(const upb_msglayout *l, upb_alloc *a);
+void upb_msg_free(upb_msg *msg, const upb_msglayout *l);
+
+/* Returns the upb_alloc for the given message.
+ * TODO(haberman): get rid of this? Not sure we want to be storing this
+ * for every message. */
+upb_alloc *upb_msg_alloc(const upb_msg *msg);
+
+/* Packs the tree of messages rooted at "msg" into a single hunk of memory,
+ * allocated from the given allocator. */
+void *upb_msg_pack(const upb_msg *msg, const upb_msglayout *l,
+ void *p, size_t *ofs, size_t size);
+
+/* Read-only message API. Can be safely called by anyone. */
+
+/* Returns the value associated with this field:
+ * - for scalar fields (including strings), the value directly.
+ * - return upb_msg*, or upb_map* for msg/map.
+ * If the field is unset for these field types, returns NULL.
+ *
+ * TODO(haberman): should we let users store cached array/map/msg
+ * pointers here for fields that are unset? Could be useful for the
+ * strongly-owned submessage model (ie. generated C API that doesn't use
+ * arenas).
+ */
+upb_msgval upb_msg_get(const upb_msg *msg,
+ int field_index,
+ const upb_msglayout *l);
+
+/* May only be called for fields where upb_fielddef_haspresence(f) == true. */
+bool upb_msg_has(const upb_msg *msg,
+ int field_index,
+ const upb_msglayout *l);
+
+/* Mutable message API. May only be called by the owner of the message who
+ * knows its ownership scheme and how to keep it consistent. */
+
+/* Sets the given field to the given value. Does not perform any memory
+ * management: if you overwrite a pointer to a msg/array/map/string without
+ * cleaning it up (or using an arena) it will leak.
+ */
+void upb_msg_set(upb_msg *msg,
+ int field_index,
+ upb_msgval val,
+ const upb_msglayout *l);
+
+/* For a primitive field, set it back to its default. For repeated, string, and
+ * submessage fields set it back to NULL. This could involve releasing some
+ * internal memory (for example, from an extension dictionary), but it is not
+ * recursive in any way and will not recover any memory that may be used by
+ * arrays/maps/strings/msgs that this field may have pointed to.
+ */
+bool upb_msg_clearfield(upb_msg *msg,
+ int field_index,
+ const upb_msglayout *l);
+
+/* TODO(haberman): copyfrom()/mergefrom()? */
+
+
+/** upb_array *****************************************************************/
+
+/* A upb_array stores data for a repeated field. The memory management
+ * semantics are the same as upb_msg. A upb_array allocates dynamic
+ * memory internally for the array elements. */
+
+size_t upb_array_sizeof(upb_fieldtype_t type);
+void upb_array_init(upb_array *arr, upb_fieldtype_t type, upb_alloc *a);
+void upb_array_uninit(upb_array *arr);
+upb_array *upb_array_new(upb_fieldtype_t type, upb_alloc *a);
+void upb_array_free(upb_array *arr);
+
+/* Read-only interface. Safe for anyone to call. */
+
+size_t upb_array_size(const upb_array *arr);
+upb_fieldtype_t upb_array_type(const upb_array *arr);
+upb_msgval upb_array_get(const upb_array *arr, size_t i);
+
+/* Write interface. May only be called by the message's owner who can enforce
+ * its memory management invariants. */
+
+bool upb_array_set(upb_array *arr, size_t i, upb_msgval val);
+
+
+/** upb_map *******************************************************************/
+
+/* A upb_map stores data for a map field. The memory management semantics are
+ * the same as upb_msg, with one notable exception. upb_map will internally
+ * store a copy of all string keys, but *not* any string values or submessages.
+ * So you must ensure that any string or message values outlive the map, and you
+ * must delete them manually when they are no longer required. */
+
+size_t upb_map_sizeof(upb_fieldtype_t ktype, upb_fieldtype_t vtype);
+bool upb_map_init(upb_map *map, upb_fieldtype_t ktype, upb_fieldtype_t vtype,
+ upb_alloc *a);
+void upb_map_uninit(upb_map *map);
+upb_map *upb_map_new(upb_fieldtype_t ktype, upb_fieldtype_t vtype, upb_alloc *a);
+void upb_map_free(upb_map *map);
+
+/* Read-only interface. Safe for anyone to call. */
+
+size_t upb_map_size(const upb_map *map);
+upb_fieldtype_t upb_map_keytype(const upb_map *map);
+upb_fieldtype_t upb_map_valuetype(const upb_map *map);
+bool upb_map_get(const upb_map *map, upb_msgval key, upb_msgval *val);
+
+/* Write interface. May only be called by the message's owner who can enforce
+ * its memory management invariants. */
+
+/* Sets or overwrites an entry in the map. Return value indicates whether
+ * the operation succeeded or failed with OOM, and also whether an existing
+ * key was replaced or not. */
+bool upb_map_set(upb_map *map,
+ upb_msgval key, upb_msgval val,
+ upb_msgval *valremoved);
+
+/* Deletes an entry in the map. Returns true if the key was present. */
+bool upb_map_del(upb_map *map, upb_msgval key);
+
+
+/** upb_mapiter ***************************************************************/
+
+/* For iterating over a map. Map iterators are invalidated by mutations to the
+ * map, but an invalidated iterator will never return junk or crash the process.
+ * An invalidated iterator may return entries that were already returned though,
+ * and if you keep invalidating the iterator during iteration, the program may
+ * enter an infinite loop. */
+
+size_t upb_mapiter_sizeof();
+
+void upb_mapiter_begin(upb_mapiter *i, const upb_map *t);
+upb_mapiter *upb_mapiter_new(const upb_map *t, upb_alloc *a);
+void upb_mapiter_free(upb_mapiter *i, upb_alloc *a);
+void upb_mapiter_next(upb_mapiter *i);
+bool upb_mapiter_done(const upb_mapiter *i);
+
+upb_msgval upb_mapiter_key(const upb_mapiter *i);
+upb_msgval upb_mapiter_value(const upb_mapiter *i);
+void upb_mapiter_setdone(upb_mapiter *i);
+bool upb_mapiter_isequal(const upb_mapiter *i1, const upb_mapiter *i2);
+
+
+/** Handlers ******************************************************************/
+
+/* These are the handlers used internally by upb_msgfactory_getmergehandlers().
+ * They write scalar data to a known offset from the message pointer.
+ *
+ * These would be trivial for anyone to implement themselves, but it's better
+ * to use these because some JITs will recognize and specialize these instead
+ * of actually calling the function. */
+
+/* Sets a handler for the given primitive field that will write the data at the
+ * given offset. If hasbit > 0, also sets a hasbit at the given bit offset
+ * (addressing each byte low to high). */
+bool upb_msg_setscalarhandler(upb_handlers *h,
+ const upb_fielddef *f,
+ size_t offset,
+ int32_t hasbit);
+
+/* If the given handler is a msghandlers_primitive field, returns true and sets
+ * *type, *offset and *hasbit. Otherwise returns false. */
+bool upb_msg_getscalarhandlerdata(const upb_handlers *h,
+ upb_selector_t s,
+ upb_fieldtype_t *type,
+ size_t *offset,
+ int32_t *hasbit);
+
+
+/** Interfaces for generated code *********************************************/
+
+#define UPB_NOT_IN_ONEOF UINT16_MAX
+#define UPB_NO_HASBIT UINT16_MAX
+#define UPB_NO_SUBMSG UINT16_MAX
+
+typedef struct {
+ uint32_t number;
+ uint32_t offset; /* If in a oneof, offset of default in default_msg below. */
+ uint16_t hasbit; /* UPB_NO_HASBIT if no hasbit. */
+ uint16_t oneof_index; /* UPB_NOT_IN_ONEOF if not in a oneof. */
+ uint16_t submsg_index; /* UPB_NO_SUBMSG if no submsg. */
+ uint8_t type;
+ uint8_t label;
+} upb_msglayout_fieldinit_v1;
+
+typedef struct {
+ uint32_t data_offset;
+ uint32_t case_offset;
+} upb_msglayout_oneofinit_v1;
+
+typedef struct upb_msglayout_msginit_v1 {
+ const struct upb_msglayout_msginit_v1 *const* submsgs;
+ const upb_msglayout_fieldinit_v1 *fields;
+ const upb_msglayout_oneofinit_v1 *oneofs;
+ void *default_msg;
+ /* Must be aligned to sizeof(void*). Doesn't include internal members like
+ * unknown fields, extension dict, pointer to msglayout, etc. */
+ uint32_t size;
+ uint16_t field_count;
+ uint16_t oneof_count;
+ bool extendable;
+ bool is_proto2;
+} upb_msglayout_msginit_v1;
+
+#define UPB_ALIGN_UP_TO(val, align) ((val + (align - 1)) & -align)
+#define UPB_ALIGNED_SIZEOF(type) UPB_ALIGN_UP_TO(sizeof(type), sizeof(void*))
+
+/* Initialize/uninitialize a msglayout from a msginit. If upb uses v1
+ * internally, this will not allocate any memory. Should only be used by
+ * generated code. */
+upb_msglayout *upb_msglayout_frominit_v1(
+ const upb_msglayout_msginit_v1 *init, upb_alloc *a);
+void upb_msglayout_uninit_v1(upb_msglayout *layout, upb_alloc *a);
+
+UPB_END_EXTERN_C
+
+#endif /* UPB_MSG_H_ */
UPB_BEGIN_EXTERN_C
-/* C API. */
-bool upb_shim_set(upb_handlers *h, const upb_fielddef *f, size_t offset,
- int32_t hasbit);
-const upb_shim_data *upb_shim_getdata(const upb_handlers *h, upb_selector_t s,
- upb_fieldtype_t *type);
+bool upb_decode(upb_stringview buf, void *msg,
+ const upb_msglayout_msginit_v1 *l, upb_env *env);
UPB_END_EXTERN_C
-#ifdef __cplusplus
-/* C++ Wrappers. */
-namespace upb {
-inline bool Shim::Set(Handlers* h, const FieldDef* f, size_t ofs,
- int32_t hasbit) {
- return upb_shim_set(h, f, ofs, hasbit);
-}
-inline const Shim::Data* Shim::GetData(const Handlers* h, Handlers::Selector s,
- FieldDef::Type* type) {
- return upb_shim_getdata(h, s, type);
-}
-} /* namespace upb */
-#endif
+#endif /* UPB_DECODE_H_ */
+/*
+** structs.int.h: structures definitions that are internal to upb.
+*/
+
+#ifndef UPB_STRUCTS_H_
+#define UPB_STRUCTS_H_
+
+struct upb_array {
+ upb_fieldtype_t type;
+ uint8_t element_size;
+ void *data; /* Each element is element_size. */
+ size_t len; /* Measured in elements. */
+ size_t size; /* Measured in elements. */
+ upb_alloc *alloc;
+};
+
+#endif /* UPB_STRUCTS_H_ */
-#endif /* UPB_SHIM_H */
/*
-** upb::SymbolTable (upb_symtab)
+** This file contains definitions of structs that should be considered private
+** and NOT stable across versions of upb.
**
-** A symtab (symbol table) stores a name->def map of upb_defs. Clients could
-** always create such tables themselves, but upb_symtab has logic for resolving
-** symbolic references, and in particular, for keeping a whole set of consistent
-** defs when replacing some subset of those defs. This logic is nontrivial.
+** The only reason they are declared here and not in .c files is to allow upb
+** and the application (if desired) to embed statically-initialized instances
+** of structures like defs.
**
-** This is a mixed C/C++ interface that offers a full API to both languages.
-** See the top-level README for more information.
+** If you include this file, all guarantees of ABI compatibility go out the
+** window! Any code that includes this file needs to recompile against the
+** exact same version of upb that they are linking against.
+**
+** You also need to recompile if you change the value of the UPB_DEBUG_REFS
+** flag.
*/
-#ifndef UPB_SYMTAB_H_
-#define UPB_SYMTAB_H_
+#ifndef UPB_STATICINIT_H_
+#define UPB_STATICINIT_H_
#ifdef __cplusplus
-#include <vector>
-namespace upb { class SymbolTable; }
+/* Because of how we do our typedefs, this header can't be included from C++. */
+#error This file cannot be included from C++
#endif
-UPB_DECLARE_DERIVED_TYPE(upb::SymbolTable, upb::RefCounted,
- upb_symtab, upb_refcounted)
+/* upb_refcounted *************************************************************/
-typedef struct {
- UPB_PRIVATE_FOR_CPP
- upb_strtable_iter iter;
- upb_deftype_t type;
-} upb_symtab_iter;
-#ifdef __cplusplus
+/* upb_def ********************************************************************/
-/* Non-const methods in upb::SymbolTable are NOT thread-safe. */
-class upb::SymbolTable {
- public:
- /* Returns a new symbol table with a single ref owned by "owner."
- * Returns NULL if memory allocation failed. */
- static reffed_ptr<SymbolTable> New();
+struct upb_def {
+ upb_refcounted base;
- /* Include RefCounted base methods. */
- UPB_REFCOUNTED_CPPMETHODS
+ const char *fullname;
+ const upb_filedef* file;
+ char type; /* A upb_deftype_t (char to save space) */
- /* For all lookup functions, the returned pointer is not owned by the
- * caller; it may be invalidated by any non-const call or unref of the
- * SymbolTable! To protect against this, take a ref if desired. */
+ /* Used as a flag during the def's mutable stage. Must be false unless
+ * it is currently being used by a function on the stack. This allows
+ * us to easily determine which defs were passed into the function's
+ * current invocation. */
+ bool came_from_user;
+};
- /* Freezes the symbol table: prevents further modification of it.
- * After the Freeze() operation is successful, the SymbolTable must only be
- * accessed via a const pointer.
- *
- * Unlike with upb::MessageDef/upb::EnumDef/etc, freezing a SymbolTable is not
- * a necessary step in using a SymbolTable. If you have no need for it to be
- * immutable, there is no need to freeze it ever. However sometimes it is
- * useful, and SymbolTables that are statically compiled into the binary are
- * always frozen by nature. */
- void Freeze();
+#define UPB_DEF_INIT(name, type, vtbl, refs, ref2s) \
+ { UPB_REFCOUNT_INIT(vtbl, refs, ref2s), name, NULL, type, false }
- /* Resolves the given symbol using the rules described in descriptor.proto,
- * namely:
- *
- * If the name starts with a '.', it is fully-qualified. Otherwise,
- * C++-like scoping rules are used to find the type (i.e. first the nested
- * types within this message are searched, then within the parent, on up
- * to the root namespace).
- *
- * If not found, returns NULL. */
- const Def* Resolve(const char* base, const char* sym) const;
- /* Finds an entry in the symbol table with this exact name. If not found,
- * returns NULL. */
- const Def* Lookup(const char *sym) const;
- const MessageDef* LookupMessage(const char *sym) const;
- const EnumDef* LookupEnum(const char *sym) const;
+/* upb_fielddef ***************************************************************/
- /* TODO: introduce a C++ iterator, but make it nice and templated so that if
- * you ask for an iterator of MessageDef the iterated elements are strongly
- * typed as MessageDef*. */
+struct upb_fielddef {
+ upb_def base;
- /* Adds the given mutable defs to the symtab, resolving all symbols
- * (including enum default values) and finalizing the defs. Only one def per
- * name may be in the list, but defs can replace existing defs in the symtab.
- * All defs must have a name -- anonymous defs are not allowed. Anonymous
- * defs can still be frozen by calling upb_def_freeze() directly.
- *
- * Any existing defs that can reach defs that are being replaced will
- * themselves be replaced also, so that the resulting set of defs is fully
- * consistent.
- *
- * This logic implemented in this method is a convenience; ultimately it
- * calls some combination of upb_fielddef_setsubdef(), upb_def_dup(), and
- * upb_freeze(), any of which the client could call themself. However, since
- * the logic for doing so is nontrivial, we provide it here.
- *
- * The entire operation either succeeds or fails. If the operation fails,
- * the symtab is unchanged, false is returned, and status indicates the
- * error. The caller passes a ref on all defs to the symtab (even if the
- * operation fails).
- *
- * TODO(haberman): currently failure will leave the symtab unchanged, but may
- * leave the defs themselves partially resolved. Does this matter? If so we
- * could do a prepass that ensures that all symbols are resolvable and bail
- * if not, so we don't mutate anything until we know the operation will
- * succeed.
- *
- * TODO(haberman): since the defs must be mutable, refining a frozen def
- * requires making mutable copies of the entire tree. This is wasteful if
- * only a few messages are changing. We may want to add a way of adding a
- * tree of frozen defs to the symtab (perhaps an alternate constructor where
- * you pass the root of the tree?) */
- bool Add(Def*const* defs, size_t n, void* ref_donor, Status* status);
+ union {
+ int64_t sint;
+ uint64_t uint;
+ double dbl;
+ float flt;
+ void *bytes;
+ } defaultval;
+ union {
+ const upb_msgdef *def; /* If !msg_is_symbolic. */
+ char *name; /* If msg_is_symbolic. */
+ } msg;
+ union {
+ const upb_def *def; /* If !subdef_is_symbolic. */
+ char *name; /* If subdef_is_symbolic. */
+ } sub; /* The msgdef or enumdef for this field, if upb_hassubdef(f). */
+ bool subdef_is_symbolic;
+ bool msg_is_symbolic;
+ const upb_oneofdef *oneof;
+ bool default_is_string;
+ bool type_is_set_; /* False until type is explicitly set. */
+ bool is_extension_;
+ bool lazy_;
+ bool packed_;
+ upb_intfmt_t intfmt;
+ bool tagdelim;
+ upb_fieldtype_t type_;
+ upb_label_t label_;
+ uint32_t number_;
+ uint32_t selector_base; /* Used to index into a upb::Handlers table. */
+ uint32_t index_;
+};
- bool Add(const std::vector<Def*>& defs, void *owner, Status* status) {
- return Add((Def*const*)&defs[0], defs.size(), owner, status);
+extern const struct upb_refcounted_vtbl upb_fielddef_vtbl;
+
+#define UPB_FIELDDEF_INIT(label, type, intfmt, tagdelim, is_extension, lazy, \
+ packed, name, num, msgdef, subdef, selector_base, \
+ index, defaultval, refs, ref2s) \
+ { \
+ UPB_DEF_INIT(name, UPB_DEF_FIELD, &upb_fielddef_vtbl, refs, ref2s), \
+ defaultval, {msgdef}, {subdef}, NULL, false, false, \
+ type == UPB_TYPE_STRING || type == UPB_TYPE_BYTES, true, is_extension, \
+ lazy, packed, intfmt, tagdelim, type, label, num, selector_base, index \
}
- /* Resolves all subdefs for messages in this file and attempts to freeze the
- * file. If this succeeds, adds all the symbols to this SymbolTable
- * (replacing any existing ones with the same names). */
- bool AddFile(FileDef* file, Status* s);
- private:
- UPB_DISALLOW_POD_OPS(SymbolTable, upb::SymbolTable)
+/* upb_msgdef *****************************************************************/
+
+struct upb_msgdef {
+ upb_def base;
+
+ size_t selector_count;
+ uint32_t submsg_field_count;
+
+ /* Tables for looking up fields by number and name. */
+ upb_inttable itof; /* int to field */
+ upb_strtable ntof; /* name to field/oneof */
+
+ /* Is this a map-entry message? */
+ bool map_entry;
+
+ /* Whether this message has proto2 or proto3 semantics. */
+ upb_syntax_t syntax;
+
+ /* TODO(haberman): proper extension ranges (there can be multiple). */
};
-#endif /* __cplusplus */
+extern const struct upb_refcounted_vtbl upb_msgdef_vtbl;
-UPB_BEGIN_EXTERN_C
+/* TODO: also support static initialization of the oneofs table. This will be
+ * needed if we compile in descriptors that contain oneofs. */
+#define UPB_MSGDEF_INIT(name, selector_count, submsg_field_count, itof, ntof, \
+ map_entry, syntax, refs, ref2s) \
+ { \
+ UPB_DEF_INIT(name, UPB_DEF_MSG, &upb_fielddef_vtbl, refs, ref2s), \
+ selector_count, submsg_field_count, itof, ntof, map_entry, syntax \
+ }
-/* Native C API. */
-/* Include refcounted methods like upb_symtab_ref(). */
-UPB_REFCOUNTED_CMETHODS(upb_symtab, upb_symtab_upcast)
+/* upb_enumdef ****************************************************************/
-upb_symtab *upb_symtab_new(const void *owner);
-void upb_symtab_freeze(upb_symtab *s);
-const upb_def *upb_symtab_resolve(const upb_symtab *s, const char *base,
- const char *sym);
-const upb_def *upb_symtab_lookup(const upb_symtab *s, const char *sym);
-const upb_msgdef *upb_symtab_lookupmsg(const upb_symtab *s, const char *sym);
-const upb_enumdef *upb_symtab_lookupenum(const upb_symtab *s, const char *sym);
-bool upb_symtab_add(upb_symtab *s, upb_def *const*defs, size_t n,
- void *ref_donor, upb_status *status);
-bool upb_symtab_addfile(upb_symtab *s, upb_filedef *file, upb_status* status);
+struct upb_enumdef {
+ upb_def base;
-/* upb_symtab_iter i;
- * for(upb_symtab_begin(&i, s, type); !upb_symtab_done(&i);
- * upb_symtab_next(&i)) {
- * const upb_def *def = upb_symtab_iter_def(&i);
- * // ...
- * }
- *
- * For C we don't have separate iterators for const and non-const.
- * It is the caller's responsibility to cast the upb_fielddef* to
- * const if the upb_msgdef* is const. */
-void upb_symtab_begin(upb_symtab_iter *iter, const upb_symtab *s,
- upb_deftype_t type);
-void upb_symtab_next(upb_symtab_iter *iter);
-bool upb_symtab_done(const upb_symtab_iter *iter);
-const upb_def *upb_symtab_iter_def(const upb_symtab_iter *iter);
+ upb_strtable ntoi;
+ upb_inttable iton;
+ int32_t defaultval;
+};
-UPB_END_EXTERN_C
+extern const struct upb_refcounted_vtbl upb_enumdef_vtbl;
-#ifdef __cplusplus
-/* C++ inline wrappers. */
-namespace upb {
-inline reffed_ptr<SymbolTable> SymbolTable::New() {
- upb_symtab *s = upb_symtab_new(&s);
- return reffed_ptr<SymbolTable>(s, &s);
-}
+#define UPB_ENUMDEF_INIT(name, ntoi, iton, defaultval, refs, ref2s) \
+ { UPB_DEF_INIT(name, UPB_DEF_ENUM, &upb_enumdef_vtbl, refs, ref2s), ntoi, \
+ iton, defaultval }
-inline void SymbolTable::Freeze() {
- return upb_symtab_freeze(this);
-}
-inline const Def *SymbolTable::Resolve(const char *base,
- const char *sym) const {
- return upb_symtab_resolve(this, base, sym);
-}
-inline const Def* SymbolTable::Lookup(const char *sym) const {
- return upb_symtab_lookup(this, sym);
-}
-inline const MessageDef *SymbolTable::LookupMessage(const char *sym) const {
- return upb_symtab_lookupmsg(this, sym);
-}
-inline bool SymbolTable::Add(
- Def*const* defs, size_t n, void* ref_donor, Status* status) {
- return upb_symtab_add(this, (upb_def*const*)defs, n, ref_donor, status);
-}
-inline bool SymbolTable::AddFile(FileDef* file, Status* s) {
- return upb_symtab_addfile(this, file, s);
-}
-} /* namespace upb */
-#endif
-#endif /* UPB_SYMTAB_H_ */
+/* upb_oneofdef ***************************************************************/
+
+struct upb_oneofdef {
+ upb_refcounted base;
+
+ uint32_t index; /* Index within oneofs. */
+ const char *name;
+ upb_strtable ntof;
+ upb_inttable itof;
+ const upb_msgdef *parent;
+};
+
+extern const struct upb_refcounted_vtbl upb_oneofdef_vtbl;
+
+#define UPB_ONEOFDEF_INIT(name, ntof, itof, refs, ref2s) \
+ { UPB_REFCOUNT_INIT(&upb_oneofdef_vtbl, refs, ref2s), 0, name, ntof, itof }
+
+
+/* upb_symtab *****************************************************************/
+
+struct upb_symtab {
+ upb_refcounted base;
+
+ upb_strtable symtab;
+};
+
+struct upb_filedef {
+ upb_refcounted base;
+
+ const char *name;
+ const char *package;
+ const char *phpprefix;
+ const char *phpnamespace;
+ upb_syntax_t syntax;
+
+ upb_inttable defs;
+ upb_inttable deps;
+};
+
+extern const struct upb_refcounted_vtbl upb_filedef_vtbl;
+
+#endif /* UPB_STATICINIT_H_ */
+/*
+** upb_encode: parsing into a upb_msg using a upb_msglayout.
+*/
+
+#ifndef UPB_ENCODE_H_
+#define UPB_ENCODE_H_
+
+
+UPB_BEGIN_EXTERN_C
+
+char *upb_encode(const void *msg, const upb_msglayout_msginit_v1 *l,
+ upb_env *env, size_t *size);
+
+UPB_END_EXTERN_C
+
+#endif /* UPB_ENCODE_H_ */
/*
** upb::descriptor::Reader (upb_descreader)
**
@@ -6853,111 +7277,113 @@ UPB_INLINE bool upbdefs_google_protobuf_FileOptions_OptimizeMode_is(const upb_en
/* Functions to get a fielddef from a msgdef reference. */
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_ExtensionRange_f_end(const upb_msgdef *m) { assert(upbdefs_google_protobuf_DescriptorProto_ExtensionRange_is(m)); return upb_msgdef_itof(m, 2); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_ExtensionRange_f_start(const upb_msgdef *m) { assert(upbdefs_google_protobuf_DescriptorProto_ExtensionRange_is(m)); return upb_msgdef_itof(m, 1); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_ReservedRange_f_end(const upb_msgdef *m) { assert(upbdefs_google_protobuf_DescriptorProto_ReservedRange_is(m)); return upb_msgdef_itof(m, 2); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_ReservedRange_f_start(const upb_msgdef *m) { assert(upbdefs_google_protobuf_DescriptorProto_ReservedRange_is(m)); return upb_msgdef_itof(m, 1); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_enum_type(const upb_msgdef *m) { assert(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 4); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_extension(const upb_msgdef *m) { assert(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 6); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_extension_range(const upb_msgdef *m) { assert(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 5); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_field(const upb_msgdef *m) { assert(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 2); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_name(const upb_msgdef *m) { assert(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 1); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_nested_type(const upb_msgdef *m) { assert(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 3); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_oneof_decl(const upb_msgdef *m) { assert(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 8); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_options(const upb_msgdef *m) { assert(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 7); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_reserved_name(const upb_msgdef *m) { assert(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 10); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_reserved_range(const upb_msgdef *m) { assert(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 9); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumDescriptorProto_f_name(const upb_msgdef *m) { assert(upbdefs_google_protobuf_EnumDescriptorProto_is(m)); return upb_msgdef_itof(m, 1); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumDescriptorProto_f_options(const upb_msgdef *m) { assert(upbdefs_google_protobuf_EnumDescriptorProto_is(m)); return upb_msgdef_itof(m, 3); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumDescriptorProto_f_value(const upb_msgdef *m) { assert(upbdefs_google_protobuf_EnumDescriptorProto_is(m)); return upb_msgdef_itof(m, 2); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumOptions_f_allow_alias(const upb_msgdef *m) { assert(upbdefs_google_protobuf_EnumOptions_is(m)); return upb_msgdef_itof(m, 2); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumOptions_f_deprecated(const upb_msgdef *m) { assert(upbdefs_google_protobuf_EnumOptions_is(m)); return upb_msgdef_itof(m, 3); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumOptions_f_uninterpreted_option(const upb_msgdef *m) { assert(upbdefs_google_protobuf_EnumOptions_is(m)); return upb_msgdef_itof(m, 999); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumValueDescriptorProto_f_name(const upb_msgdef *m) { assert(upbdefs_google_protobuf_EnumValueDescriptorProto_is(m)); return upb_msgdef_itof(m, 1); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumValueDescriptorProto_f_number(const upb_msgdef *m) { assert(upbdefs_google_protobuf_EnumValueDescriptorProto_is(m)); return upb_msgdef_itof(m, 2); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumValueDescriptorProto_f_options(const upb_msgdef *m) { assert(upbdefs_google_protobuf_EnumValueDescriptorProto_is(m)); return upb_msgdef_itof(m, 3); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumValueOptions_f_deprecated(const upb_msgdef *m) { assert(upbdefs_google_protobuf_EnumValueOptions_is(m)); return upb_msgdef_itof(m, 1); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumValueOptions_f_uninterpreted_option(const upb_msgdef *m) { assert(upbdefs_google_protobuf_EnumValueOptions_is(m)); return upb_msgdef_itof(m, 999); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_default_value(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 7); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_extendee(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 2); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_json_name(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 10); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_label(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 4); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_name(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 1); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_number(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 3); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_oneof_index(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 9); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_options(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 8); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_type(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 5); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_type_name(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 6); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_f_ctype(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FieldOptions_is(m)); return upb_msgdef_itof(m, 1); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_f_deprecated(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FieldOptions_is(m)); return upb_msgdef_itof(m, 3); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_f_jstype(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FieldOptions_is(m)); return upb_msgdef_itof(m, 6); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_f_lazy(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FieldOptions_is(m)); return upb_msgdef_itof(m, 5); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_f_packed(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FieldOptions_is(m)); return upb_msgdef_itof(m, 2); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_f_uninterpreted_option(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FieldOptions_is(m)); return upb_msgdef_itof(m, 999); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_f_weak(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FieldOptions_is(m)); return upb_msgdef_itof(m, 10); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_dependency(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 3); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_enum_type(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 5); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_extension(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 7); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_message_type(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 4); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_name(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 1); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_options(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 8); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_package(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 2); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_public_dependency(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 10); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_service(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 6); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_source_code_info(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 9); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_syntax(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 12); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_weak_dependency(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 11); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorSet_f_file(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileDescriptorSet_is(m)); return upb_msgdef_itof(m, 1); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_cc_enable_arenas(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 31); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_cc_generic_services(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 16); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_csharp_namespace(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 37); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_deprecated(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 23); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_go_package(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 11); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_java_generate_equals_and_hash(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 20); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_java_generic_services(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 17); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_java_multiple_files(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 10); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_java_outer_classname(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 8); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_java_package(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 1); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_java_string_check_utf8(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 27); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_javanano_use_deprecated_package(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 38); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_objc_class_prefix(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 36); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_optimize_for(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 9); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_py_generic_services(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 18); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_uninterpreted_option(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 999); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MessageOptions_f_deprecated(const upb_msgdef *m) { assert(upbdefs_google_protobuf_MessageOptions_is(m)); return upb_msgdef_itof(m, 3); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MessageOptions_f_map_entry(const upb_msgdef *m) { assert(upbdefs_google_protobuf_MessageOptions_is(m)); return upb_msgdef_itof(m, 7); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MessageOptions_f_message_set_wire_format(const upb_msgdef *m) { assert(upbdefs_google_protobuf_MessageOptions_is(m)); return upb_msgdef_itof(m, 1); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MessageOptions_f_no_standard_descriptor_accessor(const upb_msgdef *m) { assert(upbdefs_google_protobuf_MessageOptions_is(m)); return upb_msgdef_itof(m, 2); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MessageOptions_f_uninterpreted_option(const upb_msgdef *m) { assert(upbdefs_google_protobuf_MessageOptions_is(m)); return upb_msgdef_itof(m, 999); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodDescriptorProto_f_client_streaming(const upb_msgdef *m) { assert(upbdefs_google_protobuf_MethodDescriptorProto_is(m)); return upb_msgdef_itof(m, 5); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodDescriptorProto_f_input_type(const upb_msgdef *m) { assert(upbdefs_google_protobuf_MethodDescriptorProto_is(m)); return upb_msgdef_itof(m, 2); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodDescriptorProto_f_name(const upb_msgdef *m) { assert(upbdefs_google_protobuf_MethodDescriptorProto_is(m)); return upb_msgdef_itof(m, 1); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodDescriptorProto_f_options(const upb_msgdef *m) { assert(upbdefs_google_protobuf_MethodDescriptorProto_is(m)); return upb_msgdef_itof(m, 4); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodDescriptorProto_f_output_type(const upb_msgdef *m) { assert(upbdefs_google_protobuf_MethodDescriptorProto_is(m)); return upb_msgdef_itof(m, 3); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodDescriptorProto_f_server_streaming(const upb_msgdef *m) { assert(upbdefs_google_protobuf_MethodDescriptorProto_is(m)); return upb_msgdef_itof(m, 6); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodOptions_f_deprecated(const upb_msgdef *m) { assert(upbdefs_google_protobuf_MethodOptions_is(m)); return upb_msgdef_itof(m, 33); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodOptions_f_uninterpreted_option(const upb_msgdef *m) { assert(upbdefs_google_protobuf_MethodOptions_is(m)); return upb_msgdef_itof(m, 999); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_OneofDescriptorProto_f_name(const upb_msgdef *m) { assert(upbdefs_google_protobuf_OneofDescriptorProto_is(m)); return upb_msgdef_itof(m, 1); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_ServiceDescriptorProto_f_method(const upb_msgdef *m) { assert(upbdefs_google_protobuf_ServiceDescriptorProto_is(m)); return upb_msgdef_itof(m, 2); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_ServiceDescriptorProto_f_name(const upb_msgdef *m) { assert(upbdefs_google_protobuf_ServiceDescriptorProto_is(m)); return upb_msgdef_itof(m, 1); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_ServiceDescriptorProto_f_options(const upb_msgdef *m) { assert(upbdefs_google_protobuf_ServiceDescriptorProto_is(m)); return upb_msgdef_itof(m, 3); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_ServiceOptions_f_deprecated(const upb_msgdef *m) { assert(upbdefs_google_protobuf_ServiceOptions_is(m)); return upb_msgdef_itof(m, 33); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_ServiceOptions_f_uninterpreted_option(const upb_msgdef *m) { assert(upbdefs_google_protobuf_ServiceOptions_is(m)); return upb_msgdef_itof(m, 999); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_SourceCodeInfo_Location_f_leading_comments(const upb_msgdef *m) { assert(upbdefs_google_protobuf_SourceCodeInfo_Location_is(m)); return upb_msgdef_itof(m, 3); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_SourceCodeInfo_Location_f_leading_detached_comments(const upb_msgdef *m) { assert(upbdefs_google_protobuf_SourceCodeInfo_Location_is(m)); return upb_msgdef_itof(m, 6); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_SourceCodeInfo_Location_f_path(const upb_msgdef *m) { assert(upbdefs_google_protobuf_SourceCodeInfo_Location_is(m)); return upb_msgdef_itof(m, 1); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_SourceCodeInfo_Location_f_span(const upb_msgdef *m) { assert(upbdefs_google_protobuf_SourceCodeInfo_Location_is(m)); return upb_msgdef_itof(m, 2); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_SourceCodeInfo_Location_f_trailing_comments(const upb_msgdef *m) { assert(upbdefs_google_protobuf_SourceCodeInfo_Location_is(m)); return upb_msgdef_itof(m, 4); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_SourceCodeInfo_f_location(const upb_msgdef *m) { assert(upbdefs_google_protobuf_SourceCodeInfo_is(m)); return upb_msgdef_itof(m, 1); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_NamePart_f_is_extension(const upb_msgdef *m) { assert(upbdefs_google_protobuf_UninterpretedOption_NamePart_is(m)); return upb_msgdef_itof(m, 2); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_NamePart_f_name_part(const upb_msgdef *m) { assert(upbdefs_google_protobuf_UninterpretedOption_NamePart_is(m)); return upb_msgdef_itof(m, 1); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_f_aggregate_value(const upb_msgdef *m) { assert(upbdefs_google_protobuf_UninterpretedOption_is(m)); return upb_msgdef_itof(m, 8); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_f_double_value(const upb_msgdef *m) { assert(upbdefs_google_protobuf_UninterpretedOption_is(m)); return upb_msgdef_itof(m, 6); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_f_identifier_value(const upb_msgdef *m) { assert(upbdefs_google_protobuf_UninterpretedOption_is(m)); return upb_msgdef_itof(m, 3); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_f_name(const upb_msgdef *m) { assert(upbdefs_google_protobuf_UninterpretedOption_is(m)); return upb_msgdef_itof(m, 2); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_f_negative_int_value(const upb_msgdef *m) { assert(upbdefs_google_protobuf_UninterpretedOption_is(m)); return upb_msgdef_itof(m, 5); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_f_positive_int_value(const upb_msgdef *m) { assert(upbdefs_google_protobuf_UninterpretedOption_is(m)); return upb_msgdef_itof(m, 4); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_f_string_value(const upb_msgdef *m) { assert(upbdefs_google_protobuf_UninterpretedOption_is(m)); return upb_msgdef_itof(m, 7); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_ExtensionRange_f_end(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_DescriptorProto_ExtensionRange_is(m)); return upb_msgdef_itof(m, 2); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_ExtensionRange_f_start(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_DescriptorProto_ExtensionRange_is(m)); return upb_msgdef_itof(m, 1); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_ReservedRange_f_end(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_DescriptorProto_ReservedRange_is(m)); return upb_msgdef_itof(m, 2); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_ReservedRange_f_start(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_DescriptorProto_ReservedRange_is(m)); return upb_msgdef_itof(m, 1); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_enum_type(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 4); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_extension(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 6); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_extension_range(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 5); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_field(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 2); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_name(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 1); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_nested_type(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 3); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_oneof_decl(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 8); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_options(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 7); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_reserved_name(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 10); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_reserved_range(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 9); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumDescriptorProto_f_name(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_EnumDescriptorProto_is(m)); return upb_msgdef_itof(m, 1); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumDescriptorProto_f_options(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_EnumDescriptorProto_is(m)); return upb_msgdef_itof(m, 3); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumDescriptorProto_f_value(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_EnumDescriptorProto_is(m)); return upb_msgdef_itof(m, 2); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumOptions_f_allow_alias(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_EnumOptions_is(m)); return upb_msgdef_itof(m, 2); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumOptions_f_deprecated(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_EnumOptions_is(m)); return upb_msgdef_itof(m, 3); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumOptions_f_uninterpreted_option(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_EnumOptions_is(m)); return upb_msgdef_itof(m, 999); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumValueDescriptorProto_f_name(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_EnumValueDescriptorProto_is(m)); return upb_msgdef_itof(m, 1); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumValueDescriptorProto_f_number(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_EnumValueDescriptorProto_is(m)); return upb_msgdef_itof(m, 2); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumValueDescriptorProto_f_options(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_EnumValueDescriptorProto_is(m)); return upb_msgdef_itof(m, 3); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumValueOptions_f_deprecated(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_EnumValueOptions_is(m)); return upb_msgdef_itof(m, 1); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumValueOptions_f_uninterpreted_option(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_EnumValueOptions_is(m)); return upb_msgdef_itof(m, 999); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_default_value(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 7); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_extendee(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 2); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_json_name(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 10); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_label(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 4); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_name(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 1); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_number(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 3); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_oneof_index(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 9); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_options(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 8); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_type(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 5); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_type_name(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 6); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_f_ctype(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FieldOptions_is(m)); return upb_msgdef_itof(m, 1); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_f_deprecated(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FieldOptions_is(m)); return upb_msgdef_itof(m, 3); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_f_jstype(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FieldOptions_is(m)); return upb_msgdef_itof(m, 6); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_f_lazy(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FieldOptions_is(m)); return upb_msgdef_itof(m, 5); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_f_packed(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FieldOptions_is(m)); return upb_msgdef_itof(m, 2); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_f_uninterpreted_option(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FieldOptions_is(m)); return upb_msgdef_itof(m, 999); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_f_weak(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FieldOptions_is(m)); return upb_msgdef_itof(m, 10); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_dependency(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 3); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_enum_type(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 5); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_extension(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 7); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_message_type(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 4); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_name(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 1); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_options(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 8); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_package(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 2); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_public_dependency(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 10); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_service(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 6); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_source_code_info(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 9); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_syntax(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 12); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_weak_dependency(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 11); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorSet_f_file(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileDescriptorSet_is(m)); return upb_msgdef_itof(m, 1); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_cc_enable_arenas(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 31); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_cc_generic_services(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 16); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_csharp_namespace(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 37); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_deprecated(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 23); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_go_package(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 11); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_java_generate_equals_and_hash(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 20); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_java_generic_services(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 17); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_java_multiple_files(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 10); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_java_outer_classname(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 8); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_java_package(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 1); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_java_string_check_utf8(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 27); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_javanano_use_deprecated_package(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 38); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_objc_class_prefix(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 36); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_optimize_for(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 9); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_php_class_prefix(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 40); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_php_namespace(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 41); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_py_generic_services(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 18); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_uninterpreted_option(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 999); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MessageOptions_f_deprecated(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_MessageOptions_is(m)); return upb_msgdef_itof(m, 3); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MessageOptions_f_map_entry(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_MessageOptions_is(m)); return upb_msgdef_itof(m, 7); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MessageOptions_f_message_set_wire_format(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_MessageOptions_is(m)); return upb_msgdef_itof(m, 1); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MessageOptions_f_no_standard_descriptor_accessor(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_MessageOptions_is(m)); return upb_msgdef_itof(m, 2); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MessageOptions_f_uninterpreted_option(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_MessageOptions_is(m)); return upb_msgdef_itof(m, 999); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodDescriptorProto_f_client_streaming(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_MethodDescriptorProto_is(m)); return upb_msgdef_itof(m, 5); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodDescriptorProto_f_input_type(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_MethodDescriptorProto_is(m)); return upb_msgdef_itof(m, 2); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodDescriptorProto_f_name(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_MethodDescriptorProto_is(m)); return upb_msgdef_itof(m, 1); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodDescriptorProto_f_options(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_MethodDescriptorProto_is(m)); return upb_msgdef_itof(m, 4); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodDescriptorProto_f_output_type(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_MethodDescriptorProto_is(m)); return upb_msgdef_itof(m, 3); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodDescriptorProto_f_server_streaming(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_MethodDescriptorProto_is(m)); return upb_msgdef_itof(m, 6); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodOptions_f_deprecated(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_MethodOptions_is(m)); return upb_msgdef_itof(m, 33); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodOptions_f_uninterpreted_option(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_MethodOptions_is(m)); return upb_msgdef_itof(m, 999); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_OneofDescriptorProto_f_name(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_OneofDescriptorProto_is(m)); return upb_msgdef_itof(m, 1); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_ServiceDescriptorProto_f_method(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_ServiceDescriptorProto_is(m)); return upb_msgdef_itof(m, 2); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_ServiceDescriptorProto_f_name(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_ServiceDescriptorProto_is(m)); return upb_msgdef_itof(m, 1); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_ServiceDescriptorProto_f_options(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_ServiceDescriptorProto_is(m)); return upb_msgdef_itof(m, 3); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_ServiceOptions_f_deprecated(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_ServiceOptions_is(m)); return upb_msgdef_itof(m, 33); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_ServiceOptions_f_uninterpreted_option(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_ServiceOptions_is(m)); return upb_msgdef_itof(m, 999); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_SourceCodeInfo_Location_f_leading_comments(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_SourceCodeInfo_Location_is(m)); return upb_msgdef_itof(m, 3); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_SourceCodeInfo_Location_f_leading_detached_comments(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_SourceCodeInfo_Location_is(m)); return upb_msgdef_itof(m, 6); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_SourceCodeInfo_Location_f_path(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_SourceCodeInfo_Location_is(m)); return upb_msgdef_itof(m, 1); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_SourceCodeInfo_Location_f_span(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_SourceCodeInfo_Location_is(m)); return upb_msgdef_itof(m, 2); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_SourceCodeInfo_Location_f_trailing_comments(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_SourceCodeInfo_Location_is(m)); return upb_msgdef_itof(m, 4); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_SourceCodeInfo_f_location(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_SourceCodeInfo_is(m)); return upb_msgdef_itof(m, 1); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_NamePart_f_is_extension(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_UninterpretedOption_NamePart_is(m)); return upb_msgdef_itof(m, 2); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_NamePart_f_name_part(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_UninterpretedOption_NamePart_is(m)); return upb_msgdef_itof(m, 1); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_f_aggregate_value(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_UninterpretedOption_is(m)); return upb_msgdef_itof(m, 8); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_f_double_value(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_UninterpretedOption_is(m)); return upb_msgdef_itof(m, 6); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_f_identifier_value(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_UninterpretedOption_is(m)); return upb_msgdef_itof(m, 3); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_f_name(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_UninterpretedOption_is(m)); return upb_msgdef_itof(m, 2); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_f_negative_int_value(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_UninterpretedOption_is(m)); return upb_msgdef_itof(m, 5); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_f_positive_int_value(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_UninterpretedOption_is(m)); return upb_msgdef_itof(m, 4); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_f_string_value(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_UninterpretedOption_is(m)); return upb_msgdef_itof(m, 7); }
UPB_END_EXTERN_C
@@ -6971,7 +7397,7 @@ class DescriptorProto : public ::upb::reffed_ptr<const ::upb::MessageDef> {
public:
DescriptorProto(const ::upb::MessageDef* m, const void *ref_donor = NULL)
: reffed_ptr(m, ref_donor) {
- assert(upbdefs_google_protobuf_DescriptorProto_is(m));
+ UPB_ASSERT(upbdefs_google_protobuf_DescriptorProto_is(m));
}
static DescriptorProto get() {
@@ -6983,7 +7409,7 @@ class DescriptorProto : public ::upb::reffed_ptr<const ::upb::MessageDef> {
public:
ExtensionRange(const ::upb::MessageDef* m, const void *ref_donor = NULL)
: reffed_ptr(m, ref_donor) {
- assert(upbdefs_google_protobuf_DescriptorProto_ExtensionRange_is(m));
+ UPB_ASSERT(upbdefs_google_protobuf_DescriptorProto_ExtensionRange_is(m));
}
static ExtensionRange get() {
@@ -6996,7 +7422,7 @@ class DescriptorProto : public ::upb::reffed_ptr<const ::upb::MessageDef> {
public:
ReservedRange(const ::upb::MessageDef* m, const void *ref_donor = NULL)
: reffed_ptr(m, ref_donor) {
- assert(upbdefs_google_protobuf_DescriptorProto_ReservedRange_is(m));
+ UPB_ASSERT(upbdefs_google_protobuf_DescriptorProto_ReservedRange_is(m));
}
static ReservedRange get() {
@@ -7010,7 +7436,7 @@ class EnumDescriptorProto : public ::upb::reffed_ptr<const ::upb::MessageDef> {
public:
EnumDescriptorProto(const ::upb::MessageDef* m, const void *ref_donor = NULL)
: reffed_ptr(m, ref_donor) {
- assert(upbdefs_google_protobuf_EnumDescriptorProto_is(m));
+ UPB_ASSERT(upbdefs_google_protobuf_EnumDescriptorProto_is(m));
}
static EnumDescriptorProto get() {
@@ -7023,7 +7449,7 @@ class EnumOptions : public ::upb::reffed_ptr<const ::upb::MessageDef> {
public:
EnumOptions(const ::upb::MessageDef* m, const void *ref_donor = NULL)
: reffed_ptr(m, ref_donor) {
- assert(upbdefs_google_protobuf_EnumOptions_is(m));
+ UPB_ASSERT(upbdefs_google_protobuf_EnumOptions_is(m));
}
static EnumOptions get() {
@@ -7036,7 +7462,7 @@ class EnumValueDescriptorProto : public ::upb::reffed_ptr<const ::upb::MessageDe
public:
EnumValueDescriptorProto(const ::upb::MessageDef* m, const void *ref_donor = NULL)
: reffed_ptr(m, ref_donor) {
- assert(upbdefs_google_protobuf_EnumValueDescriptorProto_is(m));
+ UPB_ASSERT(upbdefs_google_protobuf_EnumValueDescriptorProto_is(m));
}
static EnumValueDescriptorProto get() {
@@ -7049,7 +7475,7 @@ class EnumValueOptions : public ::upb::reffed_ptr<const ::upb::MessageDef> {
public:
EnumValueOptions(const ::upb::MessageDef* m, const void *ref_donor = NULL)
: reffed_ptr(m, ref_donor) {
- assert(upbdefs_google_protobuf_EnumValueOptions_is(m));
+ UPB_ASSERT(upbdefs_google_protobuf_EnumValueOptions_is(m));
}
static EnumValueOptions get() {
@@ -7062,7 +7488,7 @@ class FieldDescriptorProto : public ::upb::reffed_ptr<const ::upb::MessageDef> {
public:
FieldDescriptorProto(const ::upb::MessageDef* m, const void *ref_donor = NULL)
: reffed_ptr(m, ref_donor) {
- assert(upbdefs_google_protobuf_FieldDescriptorProto_is(m));
+ UPB_ASSERT(upbdefs_google_protobuf_FieldDescriptorProto_is(m));
}
static FieldDescriptorProto get() {
@@ -7074,7 +7500,7 @@ class FieldDescriptorProto : public ::upb::reffed_ptr<const ::upb::MessageDef> {
public:
Label(const ::upb::EnumDef* e, const void *ref_donor = NULL)
: reffed_ptr(e, ref_donor) {
- assert(upbdefs_google_protobuf_FieldDescriptorProto_Label_is(e));
+ UPB_ASSERT(upbdefs_google_protobuf_FieldDescriptorProto_Label_is(e));
}
static Label get() {
const ::upb::EnumDef* e = upbdefs_google_protobuf_FieldDescriptorProto_Label_get(&e);
@@ -7086,7 +7512,7 @@ class FieldDescriptorProto : public ::upb::reffed_ptr<const ::upb::MessageDef> {
public:
Type(const ::upb::EnumDef* e, const void *ref_donor = NULL)
: reffed_ptr(e, ref_donor) {
- assert(upbdefs_google_protobuf_FieldDescriptorProto_Type_is(e));
+ UPB_ASSERT(upbdefs_google_protobuf_FieldDescriptorProto_Type_is(e));
}
static Type get() {
const ::upb::EnumDef* e = upbdefs_google_protobuf_FieldDescriptorProto_Type_get(&e);
@@ -7099,7 +7525,7 @@ class FieldOptions : public ::upb::reffed_ptr<const ::upb::MessageDef> {
public:
FieldOptions(const ::upb::MessageDef* m, const void *ref_donor = NULL)
: reffed_ptr(m, ref_donor) {
- assert(upbdefs_google_protobuf_FieldOptions_is(m));
+ UPB_ASSERT(upbdefs_google_protobuf_FieldOptions_is(m));
}
static FieldOptions get() {
@@ -7111,7 +7537,7 @@ class FieldOptions : public ::upb::reffed_ptr<const ::upb::MessageDef> {
public:
CType(const ::upb::EnumDef* e, const void *ref_donor = NULL)
: reffed_ptr(e, ref_donor) {
- assert(upbdefs_google_protobuf_FieldOptions_CType_is(e));
+ UPB_ASSERT(upbdefs_google_protobuf_FieldOptions_CType_is(e));
}
static CType get() {
const ::upb::EnumDef* e = upbdefs_google_protobuf_FieldOptions_CType_get(&e);
@@ -7123,7 +7549,7 @@ class FieldOptions : public ::upb::reffed_ptr<const ::upb::MessageDef> {
public:
JSType(const ::upb::EnumDef* e, const void *ref_donor = NULL)
: reffed_ptr(e, ref_donor) {
- assert(upbdefs_google_protobuf_FieldOptions_JSType_is(e));
+ UPB_ASSERT(upbdefs_google_protobuf_FieldOptions_JSType_is(e));
}
static JSType get() {
const ::upb::EnumDef* e = upbdefs_google_protobuf_FieldOptions_JSType_get(&e);
@@ -7136,7 +7562,7 @@ class FileDescriptorProto : public ::upb::reffed_ptr<const ::upb::MessageDef> {
public:
FileDescriptorProto(const ::upb::MessageDef* m, const void *ref_donor = NULL)
: reffed_ptr(m, ref_donor) {
- assert(upbdefs_google_protobuf_FileDescriptorProto_is(m));
+ UPB_ASSERT(upbdefs_google_protobuf_FileDescriptorProto_is(m));
}
static FileDescriptorProto get() {
@@ -7149,7 +7575,7 @@ class FileDescriptorSet : public ::upb::reffed_ptr<const ::upb::MessageDef> {
public:
FileDescriptorSet(const ::upb::MessageDef* m, const void *ref_donor = NULL)
: reffed_ptr(m, ref_donor) {
- assert(upbdefs_google_protobuf_FileDescriptorSet_is(m));
+ UPB_ASSERT(upbdefs_google_protobuf_FileDescriptorSet_is(m));
}
static FileDescriptorSet get() {
@@ -7162,7 +7588,7 @@ class FileOptions : public ::upb::reffed_ptr<const ::upb::MessageDef> {
public:
FileOptions(const ::upb::MessageDef* m, const void *ref_donor = NULL)
: reffed_ptr(m, ref_donor) {
- assert(upbdefs_google_protobuf_FileOptions_is(m));
+ UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m));
}
static FileOptions get() {
@@ -7174,7 +7600,7 @@ class FileOptions : public ::upb::reffed_ptr<const ::upb::MessageDef> {
public:
OptimizeMode(const ::upb::EnumDef* e, const void *ref_donor = NULL)
: reffed_ptr(e, ref_donor) {
- assert(upbdefs_google_protobuf_FileOptions_OptimizeMode_is(e));
+ UPB_ASSERT(upbdefs_google_protobuf_FileOptions_OptimizeMode_is(e));
}
static OptimizeMode get() {
const ::upb::EnumDef* e = upbdefs_google_protobuf_FileOptions_OptimizeMode_get(&e);
@@ -7187,7 +7613,7 @@ class MessageOptions : public ::upb::reffed_ptr<const ::upb::MessageDef> {
public:
MessageOptions(const ::upb::MessageDef* m, const void *ref_donor = NULL)
: reffed_ptr(m, ref_donor) {
- assert(upbdefs_google_protobuf_MessageOptions_is(m));
+ UPB_ASSERT(upbdefs_google_protobuf_MessageOptions_is(m));
}
static MessageOptions get() {
@@ -7200,7 +7626,7 @@ class MethodDescriptorProto : public ::upb::reffed_ptr<const ::upb::MessageDef>
public:
MethodDescriptorProto(const ::upb::MessageDef* m, const void *ref_donor = NULL)
: reffed_ptr(m, ref_donor) {
- assert(upbdefs_google_protobuf_MethodDescriptorProto_is(m));
+ UPB_ASSERT(upbdefs_google_protobuf_MethodDescriptorProto_is(m));
}
static MethodDescriptorProto get() {
@@ -7213,7 +7639,7 @@ class MethodOptions : public ::upb::reffed_ptr<const ::upb::MessageDef> {
public:
MethodOptions(const ::upb::MessageDef* m, const void *ref_donor = NULL)
: reffed_ptr(m, ref_donor) {
- assert(upbdefs_google_protobuf_MethodOptions_is(m));
+ UPB_ASSERT(upbdefs_google_protobuf_MethodOptions_is(m));
}
static MethodOptions get() {
@@ -7226,7 +7652,7 @@ class OneofDescriptorProto : public ::upb::reffed_ptr<const ::upb::MessageDef> {
public:
OneofDescriptorProto(const ::upb::MessageDef* m, const void *ref_donor = NULL)
: reffed_ptr(m, ref_donor) {
- assert(upbdefs_google_protobuf_OneofDescriptorProto_is(m));
+ UPB_ASSERT(upbdefs_google_protobuf_OneofDescriptorProto_is(m));
}
static OneofDescriptorProto get() {
@@ -7239,7 +7665,7 @@ class ServiceDescriptorProto : public ::upb::reffed_ptr<const ::upb::MessageDef>
public:
ServiceDescriptorProto(const ::upb::MessageDef* m, const void *ref_donor = NULL)
: reffed_ptr(m, ref_donor) {
- assert(upbdefs_google_protobuf_ServiceDescriptorProto_is(m));
+ UPB_ASSERT(upbdefs_google_protobuf_ServiceDescriptorProto_is(m));
}
static ServiceDescriptorProto get() {
@@ -7252,7 +7678,7 @@ class ServiceOptions : public ::upb::reffed_ptr<const ::upb::MessageDef> {
public:
ServiceOptions(const ::upb::MessageDef* m, const void *ref_donor = NULL)
: reffed_ptr(m, ref_donor) {
- assert(upbdefs_google_protobuf_ServiceOptions_is(m));
+ UPB_ASSERT(upbdefs_google_protobuf_ServiceOptions_is(m));
}
static ServiceOptions get() {
@@ -7265,7 +7691,7 @@ class SourceCodeInfo : public ::upb::reffed_ptr<const ::upb::MessageDef> {
public:
SourceCodeInfo(const ::upb::MessageDef* m, const void *ref_donor = NULL)
: reffed_ptr(m, ref_donor) {
- assert(upbdefs_google_protobuf_SourceCodeInfo_is(m));
+ UPB_ASSERT(upbdefs_google_protobuf_SourceCodeInfo_is(m));
}
static SourceCodeInfo get() {
@@ -7277,7 +7703,7 @@ class SourceCodeInfo : public ::upb::reffed_ptr<const ::upb::MessageDef> {
public:
Location(const ::upb::MessageDef* m, const void *ref_donor = NULL)
: reffed_ptr(m, ref_donor) {
- assert(upbdefs_google_protobuf_SourceCodeInfo_Location_is(m));
+ UPB_ASSERT(upbdefs_google_protobuf_SourceCodeInfo_Location_is(m));
}
static Location get() {
@@ -7291,7 +7717,7 @@ class UninterpretedOption : public ::upb::reffed_ptr<const ::upb::MessageDef> {
public:
UninterpretedOption(const ::upb::MessageDef* m, const void *ref_donor = NULL)
: reffed_ptr(m, ref_donor) {
- assert(upbdefs_google_protobuf_UninterpretedOption_is(m));
+ UPB_ASSERT(upbdefs_google_protobuf_UninterpretedOption_is(m));
}
static UninterpretedOption get() {
@@ -7303,7 +7729,7 @@ class UninterpretedOption : public ::upb::reffed_ptr<const ::upb::MessageDef> {
public:
NamePart(const ::upb::MessageDef* m, const void *ref_donor = NULL)
: reffed_ptr(m, ref_donor) {
- assert(upbdefs_google_protobuf_UninterpretedOption_NamePart_is(m));
+ UPB_ASSERT(upbdefs_google_protobuf_UninterpretedOption_NamePart_is(m));
}
static NamePart get() {
@@ -7973,21 +8399,9 @@ UPB_INLINE void upb_pbdecoder_unpackdispatch(uint64_t dispatch, uint64_t *ofs,
extern "C" {
#endif
-/* A list of types as they are encoded on-the-wire. */
-typedef enum {
- UPB_WIRE_TYPE_VARINT = 0,
- UPB_WIRE_TYPE_64BIT = 1,
- UPB_WIRE_TYPE_DELIMITED = 2,
- UPB_WIRE_TYPE_START_GROUP = 3,
- UPB_WIRE_TYPE_END_GROUP = 4,
- UPB_WIRE_TYPE_32BIT = 5
-} upb_wiretype_t;
-
#define UPB_MAX_WIRE_TYPE 5
-/* The maximum number of bytes that it takes to encode a 64-bit varint.
- * Note that with a better encoding this could be 9 (TODO: write up a
- * wiki document about this). */
+/* The maximum number of bytes that it takes to encode a 64-bit varint. */
#define UPB_PB_VARINT_MAX_LEN 10
/* Array of the "native" (ie. non-packed-repeated) wire type for the given a
@@ -8020,16 +8434,8 @@ UPB_INLINE upb_decoderet upb_decoderet_make(const char *p, uint64_t val) {
return ret;
}
-/* Four functions for decoding a varint of at most eight bytes. They are all
- * functionally identical, but are implemented in different ways and likely have
- * different performance profiles. We keep them around for performance testing.
- *
- * Note that these functions may not read byte-by-byte, so they must not be used
- * unless there are at least eight bytes left in the buffer! */
upb_decoderet upb_vdecode_max8_branch32(upb_decoderet r);
upb_decoderet upb_vdecode_max8_branch64(upb_decoderet r);
-upb_decoderet upb_vdecode_max8_wright(upb_decoderet r);
-upb_decoderet upb_vdecode_max8_massimino(upb_decoderet r);
/* Template for a function that checks the first two bytes with branching
* and dispatches 2-10 bytes with a separate function. Note that this may read
@@ -8054,8 +8460,6 @@ UPB_INLINE upb_decoderet upb_vdecode_check2_ ## name(const char *_p) { \
UPB_VARINT_DECODER_CHECK2(branch32, upb_vdecode_max8_branch32)
UPB_VARINT_DECODER_CHECK2(branch64, upb_vdecode_max8_branch64)
-UPB_VARINT_DECODER_CHECK2(wright, upb_vdecode_max8_wright)
-UPB_VARINT_DECODER_CHECK2(massimino, upb_vdecode_max8_massimino)
#undef UPB_VARINT_DECODER_CHECK2
/* Our canonical functions for decoding varints, based on the currently
@@ -8067,10 +8471,6 @@ UPB_INLINE upb_decoderet upb_vdecode_fast(const char *p) {
return upb_vdecode_check2_branch32(p);
}
-UPB_INLINE upb_decoderet upb_vdecode_max8_fast(upb_decoderet r) {
- return upb_vdecode_max8_massimino(r);
-}
-
/* Encoding *******************************************************************/
@@ -8112,9 +8512,9 @@ UPB_INLINE uint64_t upb_vencode32(uint32_t val) {
char buf[UPB_PB_VARINT_MAX_LEN];
size_t bytes = upb_vencode64(val, buf);
uint64_t ret = 0;
- assert(bytes <= 5);
+ UPB_ASSERT(bytes <= 5);
memcpy(&ret, buf, bytes);
- assert(ret <= 0xffffffffffU);
+ UPB_ASSERT(ret <= 0xffffffffffU);
return ret;
}
diff --git a/ruby/ext/google/protobuf_c/wrap_memcpy.c b/ruby/ext/google/protobuf_c/wrap_memcpy.c
new file mode 100644
index 00000000..394a52f9
--- /dev/null
+++ b/ruby/ext/google/protobuf_c/wrap_memcpy.c
@@ -0,0 +1,51 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2017 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#include <string.h>
+
+// On x86-64 Linux with glibc, we link against the 2.2.5 version of memcpy so
+// that we avoid depending on the 2.14 version of the symbol. This way,
+// distributions that are using pre-2.14 versions of glibc can successfully use
+// the gem we distribute (https://github.com/google/protobuf/issues/2783).
+//
+// This wrapper is enabled by passing the linker flags -Wl,-wrap,memcpy in
+// extconf.rb.
+#ifdef __linux__
+#if defined(__x86_64__) && defined(__GNU_LIBRARY__)
+__asm__(".symver memcpy,memcpy@GLIBC_2.2.5");
+void *__wrap_memcpy(void *dest, const void *src, size_t n) {
+ return memcpy(dest, src, n);
+}
+#else
+void *__wrap_memcpy(void *dest, const void *src, size_t n) {
+ return memmove(dest, src, n);
+}
+#endif
+#endif
diff --git a/ruby/google-protobuf.gemspec b/ruby/google-protobuf.gemspec
index 19be14e5..96606f06 100644
--- a/ruby/google-protobuf.gemspec
+++ b/ruby/google-protobuf.gemspec
@@ -1,7 +1,7 @@
Gem::Specification.new do |s|
s.name = "google-protobuf"
- s.version = "3.1.0"
- s.licenses = ["BSD"]
+ s.version = "3.4.1.1"
+ s.licenses = ["BSD-3-Clause"]
s.summary = "Protocol Buffers"
s.description = "Protocol Buffers are Google's data interchange format."
s.homepage = "https://developers.google.com/protocol-buffers"
@@ -15,12 +15,12 @@ Gem::Specification.new do |s|
else
s.files += Dir.glob('ext/**/*')
s.extensions= ["ext/google/protobuf_c/extconf.rb"]
- s.add_development_dependency "rake-compiler-dock", "~> 0.5.1"
+ s.add_development_dependency "rake-compiler-dock", "~> 0.6.0"
end
s.test_files = ["tests/basic.rb",
"tests/stress.rb",
"tests/generated_code_test.rb"]
s.add_development_dependency "rake-compiler", "~> 0.9.5"
- s.add_development_dependency "test-unit", "~> 3.0.9"
+ s.add_development_dependency "test-unit", '~> 3.0', '>= 3.0.9'
s.add_development_dependency "rubygems-tasks", "~> 0.2.4"
end
diff --git a/ruby/lib/google/protobuf/well_known_types.rb b/ruby/lib/google/protobuf/well_known_types.rb
index 547de874..921ddbc0 100644
--- a/ruby/lib/google/protobuf/well_known_types.rb
+++ b/ruby/lib/google/protobuf/well_known_types.rb
@@ -80,7 +80,7 @@ module Google
end
def to_f
- self.seconds + (self.nanos.to_f / 1_000_000_000)
+ self.seconds + (self.nanos.quo(1_000_000_000))
end
end
diff --git a/ruby/pom.xml b/ruby/pom.xml
index 7b896137..adf6ff20 100644
--- a/ruby/pom.xml
+++ b/ruby/pom.xml
@@ -21,8 +21,8 @@
<url>https://developers.google.com/protocol-buffers/</url>
<licenses>
<license>
- <name>New BSD license</name>
- <url>http://www.opensource.org/licenses/bsd-license.php</url>
+ <name>3-Clause BSD License</name>
+ <url>https://opensource.org/licenses/BSD-3-Clause</url>
<distribution>repo</distribution>
</license>
</licenses>
diff --git a/ruby/src/main/java/com/google/protobuf/jruby/RubyMessage.java b/ruby/src/main/java/com/google/protobuf/jruby/RubyMessage.java
index 733ccfbc..07558fbc 100644
--- a/ruby/src/main/java/com/google/protobuf/jruby/RubyMessage.java
+++ b/ruby/src/main/java/com/google/protobuf/jruby/RubyMessage.java
@@ -82,8 +82,8 @@ public class RubyMessage extends RubyObject {
hash.visitAll(new RubyHash.Visitor() {
@Override
public void visit(IRubyObject key, IRubyObject value) {
- if (!(key instanceof RubySymbol))
- throw runtime.newTypeError("Expected symbols as hash keys in initialization map.");
+ if (!(key instanceof RubySymbol) && !(key instanceof RubyString))
+ throw runtime.newTypeError("Expected string or symbols as hash keys in initialization map.");
final Descriptors.FieldDescriptor fieldDescriptor = findField(context, key);
if (Utils.isMapEntry(fieldDescriptor)) {
@@ -103,9 +103,15 @@ public class RubyMessage extends RubyObject {
if (oneof != null) {
oneofCases.put(oneof, fieldDescriptor);
}
+
+ if (value instanceof RubyHash && fieldDescriptor.getType() == Descriptors.FieldDescriptor.Type.MESSAGE) {
+ RubyDescriptor descriptor = (RubyDescriptor) getDescriptorForField(context, fieldDescriptor);
+ RubyClass typeClass = (RubyClass) descriptor.msgclass(context);
+ value = (IRubyObject) typeClass.newInstance(context, value, Block.NULL_BLOCK);
+ }
+
fields.put(fieldDescriptor, value);
}
-
}
});
}
@@ -367,7 +373,19 @@ public class RubyMessage extends RubyObject {
for (Descriptors.FieldDescriptor fdef : this.descriptor.getFields()) {
IRubyObject value = getField(context, fdef);
if (!value.isNil()) {
- if (value.respondsTo("to_h")) {
+ if (fdef.isRepeated() && !fdef.isMapField()) {
+ if (fdef.getType() != Descriptors.FieldDescriptor.Type.MESSAGE) {
+ value = Helpers.invoke(context, value, "to_a");
+ } else {
+ RubyArray ary = value.convertToArray();
+ for (int i = 0; i < ary.size(); i++) {
+ IRubyObject submsg = Helpers.invoke(context, ary.eltInternal(i), "to_h");
+ ary.eltInternalSet(i, submsg);
+ }
+
+ value = ary.to_ary();
+ }
+ } else if (value.respondsTo("to_h")) {
value = Helpers.invoke(context, value, "to_h");
} else if (value.respondsTo("to_a")) {
value = Helpers.invoke(context, value, "to_a");
@@ -518,19 +536,12 @@ public class RubyMessage extends RubyObject {
val = value.isTrue();
break;
case BYTES:
+ Utils.validateStringEncoding(context, fieldDescriptor.getType(), value);
+ val = ByteString.copyFrom(((RubyString) value).getBytes());
+ break;
case STRING:
Utils.validateStringEncoding(context, fieldDescriptor.getType(), value);
- RubyString str = (RubyString) value;
- switch (fieldDescriptor.getType()) {
- case BYTES:
- val = ByteString.copyFrom(str.getBytes());
- break;
- case STRING:
- val = str.asJavaString();
- break;
- default:
- break;
- }
+ val = ((RubyString) value).asJavaString();
break;
case MESSAGE:
RubyClass typeClass = (RubyClass) ((RubyDescriptor) getDescriptorForField(context, fieldDescriptor)).msgclass(context);
@@ -543,7 +554,7 @@ public class RubyMessage extends RubyObject {
if (Utils.isRubyNum(value)) {
val = enumDescriptor.findValueByNumberCreatingIfUnknown(RubyNumeric.num2int(value));
- } else if (value instanceof RubySymbol) {
+ } else if (value instanceof RubySymbol || value instanceof RubyString) {
val = enumDescriptor.findValueByName(value.asJavaString());
} else {
throw runtime.newTypeError("Expected number or symbol type for enum field.");
@@ -741,8 +752,20 @@ public class RubyMessage extends RubyObject {
Descriptors.FieldDescriptor fieldDescriptor, IRubyObject value) {
RubyArray arr = value.convertToArray();
RubyRepeatedField repeatedField = repeatedFieldForFieldDescriptor(context, fieldDescriptor);
+
+ RubyClass typeClass = null;
+ if (fieldDescriptor.getType() == Descriptors.FieldDescriptor.Type.MESSAGE) {
+ RubyDescriptor descriptor = (RubyDescriptor) getDescriptorForField(context, fieldDescriptor);
+ typeClass = (RubyClass) descriptor.msgclass(context);
+ }
+
for (int i = 0; i < arr.size(); i++) {
- repeatedField.push(context, arr.eltInternal(i));
+ IRubyObject row = arr.eltInternal(i);
+ if (row instanceof RubyHash && typeClass != null) {
+ row = (IRubyObject) typeClass.newInstance(context, row, Block.NULL_BLOCK);
+ }
+
+ repeatedField.push(context, row);
}
return repeatedField;
}
diff --git a/ruby/tests/basic.rb b/ruby/tests/basic.rb
index e0dba8bd..ad34d53d 100644
--- a/ruby/tests/basic.rb
+++ b/ruby/tests/basic.rb
@@ -1,6 +1,7 @@
#!/usr/bin/ruby
require 'google/protobuf'
+require 'json'
require 'test/unit'
# ------------- generated code --------------
@@ -50,6 +51,17 @@ module BasicTest
optional :foo, :int32, 1
end
+ add_message "TestEmbeddedMessageParent" do
+ optional :child_msg, :message, 1, "TestEmbeddedMessageChild"
+ optional :number, :int32, 2
+
+ repeated :repeated_msg, :message, 3, "TestEmbeddedMessageChild"
+ repeated :repeated_number, :int32, 4
+ end
+ add_message "TestEmbeddedMessageChild" do
+ optional :sub_child, :message, 1, "TestMessage"
+ end
+
add_message "Recursive1" do
optional :foo, :message, 1, "Recursive2"
end
@@ -95,13 +107,25 @@ module BasicTest
optional :d, :enum, 4, "TestEnum"
end
end
+
+ add_message "repro.Outer" do
+ map :items, :int32, :message, 1, "repro.Inner"
+ end
+
+ add_message "repro.Inner" do
+ end
end
+
+ Outer = pool.lookup("repro.Outer").msgclass
+ Inner = pool.lookup("repro.Inner").msgclass
Foo = pool.lookup("Foo").msgclass
Bar = pool.lookup("Bar").msgclass
Baz = pool.lookup("Baz").msgclass
TestMessage = pool.lookup("TestMessage").msgclass
TestMessage2 = pool.lookup("TestMessage2").msgclass
+ TestEmbeddedMessageParent = pool.lookup("TestEmbeddedMessageParent").msgclass
+ TestEmbeddedMessageChild = pool.lookup("TestEmbeddedMessageChild").msgclass
Recursive1 = pool.lookup("Recursive1").msgclass
Recursive2 = pool.lookup("Recursive2").msgclass
TestEnum = pool.lookup("TestEnum").enummodule
@@ -150,12 +174,18 @@ module BasicTest
m.optional_double = 0.5
m.optional_string = "hello"
assert m.optional_string == "hello"
+ m.optional_string = :hello
+ assert m.optional_string == "hello"
m.optional_bytes = "world".encode!('ASCII-8BIT')
assert m.optional_bytes == "world"
m.optional_msg = TestMessage2.new(:foo => 42)
assert m.optional_msg == TestMessage2.new(:foo => 42)
m.optional_msg = nil
assert m.optional_msg == nil
+ m.optional_enum = :C
+ assert m.optional_enum == :C
+ m.optional_enum = 'C'
+ assert m.optional_enum == :C
end
def test_ctor_args
@@ -172,6 +202,34 @@ module BasicTest
assert m.repeated_string[2] == "world"
end
+ def test_ctor_string_symbol_args
+ m = TestMessage.new(:optional_enum => 'C', :repeated_enum => ['A', 'B'])
+ assert_equal :C, m.optional_enum
+ assert_equal [:A, :B], m.repeated_enum
+
+ m = TestMessage.new(:optional_string => :foo, :repeated_string => [:foo, :bar])
+ assert_equal 'foo', m.optional_string
+ assert_equal ['foo', 'bar'], m.repeated_string
+ end
+
+ def test_embeddedmsg_hash_init
+ m = TestEmbeddedMessageParent.new(:child_msg => {sub_child: {optional_int32: 1}},
+ :number => 2,
+ :repeated_msg => [{sub_child: {optional_int32: 3}}],
+ :repeated_number => [10, 20, 30])
+
+ assert_equal 2, m.number
+ assert_equal [10, 20, 30], m.repeated_number
+
+ assert_not_nil m.child_msg
+ assert_not_nil m.child_msg.sub_child
+ assert_equal m.child_msg.sub_child.optional_int32, 1
+
+ assert_not_nil m.repeated_msg
+ assert_equal 1, m.repeated_msg.length
+ assert_equal 3, m.repeated_msg.first.sub_child.optional_int32
+ end
+
def test_inspect
m = TestMessage.new(:optional_int32 => -42,
:optional_enum => :A,
@@ -603,7 +661,7 @@ module BasicTest
assert_raise RangeError do
m["z"] = :Z
end
- assert_raise TypeError do
+ assert_raise RangeError do
m["z"] = "z"
end
end
@@ -667,6 +725,28 @@ module BasicTest
end
end
+ def test_map_corruption
+ # This pattern led to a crash in a previous version of upb/protobuf.
+ m = MapMessage.new(map_string_int32: { "aaa" => 1 })
+ m.map_string_int32['podid'] = 2
+ m.map_string_int32['aaa'] = 3
+ end
+
+ def test_concurrent_decoding
+ o = Outer.new
+ o.items[0] = Inner.new
+ raw = Outer.encode(o)
+
+ thds = 2.times.map do
+ Thread.new do
+ 100000.times do
+ assert_equal o, Outer.decode(raw)
+ end
+ end
+ end
+ thds.map(&:join)
+ end
+
def test_map_encode_decode
m = MapMessage.new(
:map_string_int32 => {"a" => 1, "b" => 2},
@@ -894,7 +974,7 @@ module BasicTest
end
def test_to_h
- m = TestMessage.new(:optional_bool => true, :optional_double => -10.100001, :optional_string => 'foo', :repeated_string => ['bar1', 'bar2'])
+ m = TestMessage.new(:optional_bool => true, :optional_double => -10.100001, :optional_string => 'foo', :repeated_string => ['bar1', 'bar2'], :repeated_msg => [TestMessage2.new(:foo => 100)])
expected_result = {
:optional_bool=>true,
:optional_bytes=>"",
@@ -914,12 +994,22 @@ module BasicTest
:repeated_float=>[],
:repeated_int32=>[],
:repeated_int64=>[],
- :repeated_msg=>[],
+ :repeated_msg=>[{:foo => 100}],
:repeated_string=>["bar1", "bar2"],
:repeated_uint32=>[],
:repeated_uint64=>[]
}
assert_equal expected_result, m.to_h
+
+ m = MapMessage.new(
+ :map_string_int32 => {"a" => 1, "b" => 2},
+ :map_string_msg => {"a" => TestMessage2.new(:foo => 1),
+ "b" => TestMessage2.new(:foo => 2)})
+ expected_result = {
+ :map_string_int32 => {"a" => 1, "b" => 2},
+ :map_string_msg => {"a" => {:foo => 1}, "b" => {:foo => 2}}
+ }
+ assert_equal expected_result, m.to_h
end
@@ -1156,6 +1246,8 @@ module BasicTest
json_text = TestMessage.encode_json(m)
m2 = TestMessage.decode_json(json_text)
+ puts m.inspect
+ puts m2.inspect
assert m == m2
# Crash case from GitHub issue 283.
@@ -1167,21 +1259,135 @@ module BasicTest
Foo.encode_json(Foo.new(bar: bar, baz: [baz1, baz2]))
end
+ def test_json_emit_defaults
+ # TODO: Fix JSON in JRuby version.
+ return if RUBY_PLATFORM == "java"
+ m = TestMessage.new
+
+ expected = {
+ optionalInt32: 0,
+ optionalInt64: 0,
+ optionalUint32: 0,
+ optionalUint64: 0,
+ optionalBool: false,
+ optionalFloat: 0,
+ optionalDouble: 0,
+ optionalString: "",
+ optionalBytes: "",
+ optionalEnum: "Default",
+ repeatedInt32: [],
+ repeatedInt64: [],
+ repeatedUint32: [],
+ repeatedUint64: [],
+ repeatedBool: [],
+ repeatedFloat: [],
+ repeatedDouble: [],
+ repeatedString: [],
+ repeatedBytes: [],
+ repeatedMsg: [],
+ repeatedEnum: []
+ }
+
+ actual = TestMessage.encode_json(m, :emit_defaults => true)
+
+ assert JSON.parse(actual, :symbolize_names => true) == expected
+ end
+
+ def test_json_emit_defaults_submsg
+ # TODO: Fix JSON in JRuby version.
+ return if RUBY_PLATFORM == "java"
+ m = TestMessage.new(optional_msg: TestMessage2.new)
+
+ expected = {
+ optionalInt32: 0,
+ optionalInt64: 0,
+ optionalUint32: 0,
+ optionalUint64: 0,
+ optionalBool: false,
+ optionalFloat: 0,
+ optionalDouble: 0,
+ optionalString: "",
+ optionalBytes: "",
+ optionalMsg: {foo: 0},
+ optionalEnum: "Default",
+ repeatedInt32: [],
+ repeatedInt64: [],
+ repeatedUint32: [],
+ repeatedUint64: [],
+ repeatedBool: [],
+ repeatedFloat: [],
+ repeatedDouble: [],
+ repeatedString: [],
+ repeatedBytes: [],
+ repeatedMsg: [],
+ repeatedEnum: []
+ }
+
+ actual = TestMessage.encode_json(m, :emit_defaults => true)
+
+ assert JSON.parse(actual, :symbolize_names => true) == expected
+ end
+
+ def test_json_emit_defaults_repeated_submsg
+ # TODO: Fix JSON in JRuby version.
+ return if RUBY_PLATFORM == "java"
+ m = TestMessage.new(repeated_msg: [TestMessage2.new])
+
+ expected = {
+ optionalInt32: 0,
+ optionalInt64: 0,
+ optionalUint32: 0,
+ optionalUint64: 0,
+ optionalBool: false,
+ optionalFloat: 0,
+ optionalDouble: 0,
+ optionalString: "",
+ optionalBytes: "",
+ optionalEnum: "Default",
+ repeatedInt32: [],
+ repeatedInt64: [],
+ repeatedUint32: [],
+ repeatedUint64: [],
+ repeatedBool: [],
+ repeatedFloat: [],
+ repeatedDouble: [],
+ repeatedString: [],
+ repeatedBytes: [],
+ repeatedMsg: [{foo: 0}],
+ repeatedEnum: []
+ }
+
+ actual = TestMessage.encode_json(m, :emit_defaults => true)
+
+ assert JSON.parse(actual, :symbolize_names => true) == expected
+ end
+
def test_json_maps
# TODO: Fix JSON in JRuby version.
return if RUBY_PLATFORM == "java"
m = MapMessage.new(:map_string_int32 => {"a" => 1})
- expected = '{"mapStringInt32":{"a":1},"mapStringMsg":{}}'
- expected_preserve = '{"map_string_int32":{"a":1},"map_string_msg":{}}'
- assert MapMessage.encode_json(m) == expected
+ expected = {mapStringInt32: {a: 1}, mapStringMsg: {}}
+ expected_preserve = {map_string_int32: {a: 1}, map_string_msg: {}}
+ assert JSON.parse(MapMessage.encode_json(m), :symbolize_names => true) == expected
json = MapMessage.encode_json(m, :preserve_proto_fieldnames => true)
- assert json == expected_preserve
+ assert JSON.parse(json, :symbolize_names => true) == expected_preserve
m2 = MapMessage.decode_json(MapMessage.encode_json(m))
assert m == m2
end
+ def test_json_maps_emit_defaults_submsg
+ # TODO: Fix JSON in JRuby version.
+ return if RUBY_PLATFORM == "java"
+ m = MapMessage.new(:map_string_msg => {"a" => TestMessage2.new})
+ expected = {mapStringInt32: {}, mapStringMsg: {a: {foo: 0}}}
+
+ actual = MapMessage.encode_json(m, :emit_defaults => true)
+
+ assert JSON.parse(actual, :symbolize_names => true) == expected
+ end
+
def test_comparison_with_arbitrary_object
assert MapMessage.new != nil
end
diff --git a/ruby/tests/gc_test.rb b/ruby/tests/gc_test.rb
new file mode 100644
index 00000000..f3470cca
--- /dev/null
+++ b/ruby/tests/gc_test.rb
@@ -0,0 +1,58 @@
+#!/usr/bin/ruby
+#
+# generated_code.rb is in the same directory as this test.
+$LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__)))
+
+old_gc = GC.stress
+GC.stress = 0x01 | 0x04
+require 'generated_code_pb'
+GC.stress = old_gc
+
+require 'test/unit'
+
+class GCTest < Test::Unit::TestCase
+ def get_msg
+ A::B::C::TestMessage.new(
+ :optional_int32 => 1,
+ :optional_int64 => 1,
+ :optional_uint32 => 1,
+ :optional_uint64 => 1,
+ :optional_bool => true,
+ :optional_double => 1.0,
+ :optional_float => 1.0,
+ :optional_string => "a",
+ :optional_bytes => "b",
+ :optional_enum => A::B::C::TestEnum::A,
+ :optional_msg => A::B::C::TestMessage.new(),
+ :repeated_int32 => [1],
+ :repeated_int64 => [1],
+ :repeated_uint32 => [1],
+ :repeated_uint64 => [1],
+ :repeated_bool => [true],
+ :repeated_double => [1.0],
+ :repeated_float => [1.0],
+ :repeated_string => ["a"],
+ :repeated_bytes => ["b"],
+ :repeated_enum => [A::B::C::TestEnum::A],
+ :repeated_msg => [A::B::C::TestMessage.new()],
+ :map_int32_string => {1 => "a"},
+ :map_int64_string => {1 => "a"},
+ :map_uint32_string => {1 => "a"},
+ :map_uint64_string => {1 => "a"},
+ :map_bool_string => {true => "a"},
+ :map_string_string => {"a" => "a"},
+ :map_string_msg => {"a" => A::B::C::TestMessage.new()},
+ :map_string_int32 => {"a" => 1},
+ :map_string_bool => {"a" => true},
+ )
+ end
+ def test_generated_msg
+ old_gc = GC.stress
+ GC.stress = 0x01 | 0x04
+ from = get_msg
+ data = A::B::C::TestMessage.encode(from)
+ to = A::B::C::TestMessage.decode(data)
+ GC.stress = old_gc
+ puts "passed"
+ end
+end
diff --git a/ruby/tests/well_known_types_test.rb b/ruby/tests/well_known_types_test.rb
index 9b46632b..bd24c328 100644
--- a/ruby/tests/well_known_types_test.rb
+++ b/ruby/tests/well_known_types_test.rb
@@ -13,10 +13,18 @@ class TestWellKnownTypes < Test::Unit::TestCase
assert_equal Time.at(12345), ts.to_time
assert_equal 12345, ts.to_i
- ts.from_time(Time.at(123456, 654321))
+ # millisecond accuracy
+ time = Time.at(123456, 654321)
+ ts.from_time(time)
assert_equal 123456, ts.seconds
assert_equal 654321000, ts.nanos
- assert_equal Time.at(123456.654321), ts.to_time
+ assert_equal time, ts.to_time
+
+ # nanosecond accuracy
+ time = Time.at(123456, Rational(654321321, 1000))
+ ts.from_time(time)
+ assert_equal 654321321, ts.nanos
+ assert_equal time, ts.to_time
end
def test_duration
diff --git a/ruby/travis-test.sh b/ruby/travis-test.sh
index 930165e6..cbe7cd98 100755
--- a/ruby/travis-test.sh
+++ b/ruby/travis-test.sh
@@ -20,7 +20,9 @@ test_version() {
git clean -f && \
gem install bundler && bundle && \
rake test &&
- cd ../conformance && make test_ruby"
+ rake gc_test &&
+ cd ../conformance && make test_ruby &&
+ cd ../ruby/compatibility_tests/v3.0.0 && ./test.sh"
fi
}
diff --git a/src/Makefile.am b/src/Makefile.am
index d6f27fa8..9df104cc 100644
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -37,17 +37,17 @@ protodir = $(includedir)
# If you are adding new files here, also remember to change the build files for
# all other languages, //protoc-artifacts/build-zip.sh and run
# //update_file_list.sh for bazel.
-nobase_dist_proto_DATA = google/protobuf/descriptor.proto \
- google/protobuf/any.proto \
- google/protobuf/api.proto \
- google/protobuf/duration.proto \
- google/protobuf/empty.proto \
- google/protobuf/field_mask.proto \
- google/protobuf/source_context.proto \
- google/protobuf/struct.proto \
- google/protobuf/timestamp.proto \
- google/protobuf/type.proto \
- google/protobuf/wrappers.proto \
+nobase_dist_proto_DATA = google/protobuf/descriptor.proto \
+ google/protobuf/any.proto \
+ google/protobuf/api.proto \
+ google/protobuf/duration.proto \
+ google/protobuf/empty.proto \
+ google/protobuf/field_mask.proto \
+ google/protobuf/source_context.proto \
+ google/protobuf/struct.proto \
+ google/protobuf/timestamp.proto \
+ google/protobuf/type.proto \
+ google/protobuf/wrappers.proto \
google/protobuf/compiler/plugin.proto
# Not sure why these don't get cleaned automatically.
@@ -56,7 +56,9 @@ clean-local:
CLEANFILES = $(protoc_outputs) unittest_proto_middleman \
testzip.jar testzip.list testzip.proto testzip.zip \
- no_warning_test.cc
+ no_warning_test.cc \
+ google/protobuf/compiler/js/well_known_types_embed.cc \
+ js_embed$(EXEEXT)
MAINTAINERCLEANFILES = \
Makefile.in
@@ -72,7 +74,6 @@ nobase_include_HEADERS = \
google/protobuf/stubs/atomicops_internals_atomicword_compat.h \
google/protobuf/stubs/atomicops_internals_generic_c11_atomic.h \
google/protobuf/stubs/atomicops_internals_generic_gcc.h \
- google/protobuf/stubs/atomicops_internals_macosx.h \
google/protobuf/stubs/atomicops_internals_mips_gcc.h \
google/protobuf/stubs/atomicops_internals_solaris.h \
google/protobuf/stubs/atomicops_internals_tsan.h \
@@ -102,6 +103,7 @@ nobase_include_HEADERS = \
google/protobuf/api.pb.h \
google/protobuf/any.h \
google/protobuf/arena.h \
+ google/protobuf/arena_impl.h \
google/protobuf/arenastring.h \
google/protobuf/descriptor_database.h \
google/protobuf/descriptor.h \
@@ -114,6 +116,7 @@ nobase_include_HEADERS = \
google/protobuf/generated_enum_reflection.h \
google/protobuf/generated_enum_util.h \
google/protobuf/generated_message_reflection.h \
+ google/protobuf/generated_message_table_driven.h \
google/protobuf/generated_message_util.h \
google/protobuf/has_bits.h \
google/protobuf/map_entry.h \
@@ -126,6 +129,7 @@ nobase_include_HEADERS = \
google/protobuf/message.h \
google/protobuf/message_lite.h \
google/protobuf/metadata.h \
+ google/protobuf/metadata_lite.h \
google/protobuf/reflection.h \
google/protobuf/reflection_ops.h \
google/protobuf/repeated_field.h \
@@ -168,6 +172,7 @@ nobase_include_HEADERS = \
google/protobuf/compiler/python/python_generator.h \
google/protobuf/compiler/ruby/ruby_generator.h \
google/protobuf/util/type_resolver.h \
+ google/protobuf/util/delimited_message_util.h \
google/protobuf/util/field_comparator.h \
google/protobuf/util/field_mask_util.h \
google/protobuf/util/json_util.h \
@@ -178,7 +183,11 @@ nobase_include_HEADERS = \
lib_LTLIBRARIES = libprotobuf-lite.la libprotobuf.la libprotoc.la
libprotobuf_lite_la_LIBADD = $(PTHREAD_LIBS)
-libprotobuf_lite_la_LDFLAGS = -version-info 11:0:0 -export-dynamic -no-undefined
+libprotobuf_lite_la_LDFLAGS = -version-info 14:0:0 -export-dynamic -no-undefined
+if HAVE_LD_VERSION_SCRIPT
+libprotobuf_lite_la_LDFLAGS += -Wl,--version-script=$(srcdir)/libprotobuf-lite.map
+EXTRA_libprotobuf_lite_la_DEPENDENCIES = libprotobuf-lite.map
+endif
libprotobuf_lite_la_SOURCES = \
google/protobuf/stubs/atomicops_internals_x86_gcc.cc \
google/protobuf/stubs/atomicops_internals_x86_msvc.cc \
@@ -188,6 +197,8 @@ libprotobuf_lite_la_SOURCES = \
google/protobuf/stubs/hash.h \
google/protobuf/stubs/int128.cc \
google/protobuf/stubs/int128.h \
+ google/protobuf/stubs/io_win32.cc \
+ google/protobuf/stubs/io_win32.h \
google/protobuf/stubs/map_util.h \
google/protobuf/stubs/mathutil.h \
google/protobuf/stubs/once.cc \
@@ -210,6 +221,8 @@ libprotobuf_lite_la_SOURCES = \
google/protobuf/arenastring.cc \
google/protobuf/extension_set.cc \
google/protobuf/generated_message_util.cc \
+ google/protobuf/generated_message_table_driven_lite.h \
+ google/protobuf/generated_message_table_driven_lite.cc \
google/protobuf/message_lite.cc \
google/protobuf/repeated_field.cc \
google/protobuf/wire_format_lite.cc \
@@ -219,7 +232,11 @@ libprotobuf_lite_la_SOURCES = \
google/protobuf/io/zero_copy_stream_impl_lite.cc
libprotobuf_la_LIBADD = $(PTHREAD_LIBS)
-libprotobuf_la_LDFLAGS = -version-info 11:0:0 -export-dynamic -no-undefined
+libprotobuf_la_LDFLAGS = -version-info 14:0:0 -export-dynamic -no-undefined
+if HAVE_LD_VERSION_SCRIPT
+libprotobuf_la_LDFLAGS += -Wl,--version-script=$(srcdir)/libprotobuf.map
+EXTRA_libprotobuf_la_DEPENDENCIES = libprotobuf.map
+endif
libprotobuf_la_SOURCES = \
$(libprotobuf_lite_la_SOURCES) \
google/protobuf/any.pb.cc \
@@ -236,6 +253,8 @@ libprotobuf_la_SOURCES = \
google/protobuf/extension_set_heavy.cc \
google/protobuf/field_mask.pb.cc \
google/protobuf/generated_message_reflection.cc \
+ google/protobuf/generated_message_table_driven_lite.h \
+ google/protobuf/generated_message_table_driven.cc \
google/protobuf/map_field.cc \
google/protobuf/message.cc \
google/protobuf/reflection_internal.h \
@@ -258,6 +277,7 @@ libprotobuf_la_SOURCES = \
google/protobuf/io/zero_copy_stream_impl.cc \
google/protobuf/compiler/importer.cc \
google/protobuf/compiler/parser.cc \
+ google/protobuf/util/delimited_message_util.cc \
google/protobuf/util/field_comparator.cc \
google/protobuf/util/field_mask_util.cc \
google/protobuf/util/internal/constants.h \
@@ -303,7 +323,11 @@ libprotobuf_la_SOURCES = \
nodist_libprotobuf_la_SOURCES = $(nodist_libprotobuf_lite_la_SOURCES)
libprotoc_la_LIBADD = $(PTHREAD_LIBS) libprotobuf.la
-libprotoc_la_LDFLAGS = -version-info 11:0:0 -export-dynamic -no-undefined
+libprotoc_la_LDFLAGS = -version-info 14:0:0 -export-dynamic -no-undefined
+if HAVE_LD_VERSION_SCRIPT
+libprotoc_la_LDFLAGS += -Wl,--version-script=$(srcdir)/libprotoc.map
+EXTRA_libprotoc_la_DEPENDENCIES = libprotoc.map
+endif
libprotoc_la_SOURCES = \
google/protobuf/compiler/code_generator.cc \
google/protobuf/compiler/command_line_interface.cc \
@@ -332,7 +356,10 @@ libprotoc_la_SOURCES = \
google/protobuf/compiler/cpp/cpp_message.h \
google/protobuf/compiler/cpp/cpp_message_field.cc \
google/protobuf/compiler/cpp/cpp_message_field.h \
+ google/protobuf/compiler/cpp/cpp_message_layout_helper.h \
google/protobuf/compiler/cpp/cpp_options.h \
+ google/protobuf/compiler/cpp/cpp_padding_optimizer.cc \
+ google/protobuf/compiler/cpp/cpp_padding_optimizer.h \
google/protobuf/compiler/cpp/cpp_primitive_field.cc \
google/protobuf/compiler/cpp/cpp_primitive_field.h \
google/protobuf/compiler/cpp/cpp_service.cc \
@@ -487,6 +514,21 @@ bin_PROGRAMS = protoc
protoc_LDADD = $(PTHREAD_LIBS) libprotobuf.la libprotoc.la
protoc_SOURCES = google/protobuf/compiler/main.cc
+# The special JS code for the well-known types is linked into the compiler via
+# well_known_types_embed.cc, which is generated from .js source files. We have
+# to build the js_embed binary using $(CXX_FOR_BUILD) so that it is executable
+# on the build machine in a cross-compilation setup.
+js_embed$(EXEEXT): $(srcdir)/google/protobuf/compiler/js/embed.cc
+ $(CXX_FOR_BUILD) -o $@ $<
+js_well_known_types_sources = \
+ google/protobuf/compiler/js/well_known_types/any.js \
+ google/protobuf/compiler/js/well_known_types/struct.js \
+ google/protobuf/compiler/js/well_known_types/timestamp.js
+# We have to cd to $(srcdir) so that out-of-tree builds work properly.
+google/protobuf/compiler/js/well_known_types_embed.cc: js_embed$(EXEEXT) $(js_well_known_types_sources)
+ oldpwd=`pwd` && cd $(srcdir) && \
+ $$oldpwd/js_embed$(EXEEXT) $(js_well_known_types_sources) > $$oldpwd/$@
+
# Tests ==============================================================
protoc_inputs = \
@@ -505,6 +547,9 @@ protoc_inputs = \
google/protobuf/unittest_import.proto \
google/protobuf/unittest_import_public_lite.proto \
google/protobuf/unittest_import_public.proto \
+ google/protobuf/unittest_lazy_dependencies.proto \
+ google/protobuf/unittest_lazy_dependencies_custom_option.proto \
+ google/protobuf/unittest_lazy_dependencies_enum.proto \
google/protobuf/unittest_lite_imports_nonlite.proto \
google/protobuf/unittest_lite.proto \
google/protobuf/unittest_mset.proto \
@@ -519,8 +564,8 @@ protoc_inputs = \
google/protobuf/unittest_preserve_unknown_enum.proto \
google/protobuf/unittest.proto \
google/protobuf/unittest_proto3_arena.proto \
- google/protobuf/unittest_proto3_arena_lite.proto \
- google/protobuf/unittest_proto3_lite.proto \
+ google/protobuf/unittest_proto3_arena_lite.proto \
+ google/protobuf/unittest_proto3_lite.proto \
google/protobuf/unittest_well_known_types.proto \
google/protobuf/util/internal/testdata/anys.proto \
google/protobuf/util/internal/testdata/books.proto \
@@ -539,7 +584,11 @@ protoc_inputs = \
EXTRA_DIST = \
$(protoc_inputs) \
+ $(js_well_known_types_sources) \
solaris/libstdc++.la \
+ google/protobuf/unittest_proto3.proto \
+ google/protobuf/test_messages_proto3.proto \
+ google/protobuf/test_messages_proto2.proto \
google/protobuf/io/gzip_stream.h \
google/protobuf/io/gzip_stream_unittest.sh \
google/protobuf/testdata/golden_message \
@@ -558,10 +607,14 @@ EXTRA_DIST = \
google/protobuf/package_info.h \
google/protobuf/io/package_info.h \
google/protobuf/util/package_info.h \
+ google/protobuf/compiler/js/embed.cc \
google/protobuf/compiler/ruby/ruby_generated_code.proto \
google/protobuf/compiler/ruby/ruby_generated_code_pb.rb \
google/protobuf/compiler/package_info.h \
google/protobuf/compiler/zip_output_unittest.sh \
+ libprotobuf-lite.map \
+ libprotobuf.map \
+ libprotoc.map \
README.md
protoc_lite_outputs = \
@@ -604,6 +657,12 @@ protoc_outputs = \
google/protobuf/unittest_import.pb.h \
google/protobuf/unittest_import_public.pb.cc \
google/protobuf/unittest_import_public.pb.h \
+ google/protobuf/unittest_lazy_dependencies.pb.cc \
+ google/protobuf/unittest_lazy_dependencies.pb.h \
+ google/protobuf/unittest_lazy_dependencies_custom_option.pb.cc \
+ google/protobuf/unittest_lazy_dependencies_custom_option.pb.h \
+ google/protobuf/unittest_lazy_dependencies_enum.pb.cc \
+ google/protobuf/unittest_lazy_dependencies_enum.pb.h \
google/protobuf/unittest_lite_imports_nonlite.pb.cc \
google/protobuf/unittest_lite_imports_nonlite.pb.h \
google/protobuf/unittest_mset.pb.cc \
@@ -628,10 +687,10 @@ protoc_outputs = \
google/protobuf/unittest_preserve_unknown_enum.pb.h \
google/protobuf/unittest_proto3_arena.pb.cc \
google/protobuf/unittest_proto3_arena.pb.h \
- google/protobuf/unittest_proto3_arena_lite.pb.cc \
- google/protobuf/unittest_proto3_arena_lite.pb.h \
- google/protobuf/unittest_proto3_lite.pb.cc \
- google/protobuf/unittest_proto3_lite.pb.h \
+ google/protobuf/unittest_proto3_arena_lite.pb.cc \
+ google/protobuf/unittest_proto3_arena_lite.pb.h \
+ google/protobuf/unittest_proto3_lite.pb.cc \
+ google/protobuf/unittest_proto3_lite.pb.h \
google/protobuf/unittest_well_known_types.pb.cc \
google/protobuf/unittest_well_known_types.pb.h \
google/protobuf/util/internal/testdata/anys.pb.cc \
@@ -661,7 +720,7 @@ protoc_outputs = \
google/protobuf/util/message_differencer_unittest.pb.cc \
google/protobuf/util/message_differencer_unittest.pb.h
-BUILT_SOURCES = $(protoc_outputs)
+BUILT_SOURCES = $(protoc_outputs) google/protobuf/compiler/js/well_known_types_embed.cc
if USE_EXTERNAL_PROTOC
@@ -712,6 +771,7 @@ protobuf_test_SOURCES = \
google/protobuf/stubs/bytestream_unittest.cc \
google/protobuf/stubs/common_unittest.cc \
google/protobuf/stubs/int128_unittest.cc \
+ google/protobuf/stubs/io_win32_unittest.cc \
google/protobuf/stubs/once_unittest.cc \
google/protobuf/stubs/statusor_test.cc \
google/protobuf/stubs/status_test.cc \
@@ -737,8 +797,8 @@ protobuf_test_SOURCES = \
google/protobuf/no_field_presence_test.cc \
google/protobuf/preserve_unknown_enum_test.cc \
google/protobuf/proto3_arena_unittest.cc \
- google/protobuf/proto3_arena_lite_unittest.cc \
- google/protobuf/proto3_lite_unittest.cc \
+ google/protobuf/proto3_arena_lite_unittest.cc \
+ google/protobuf/proto3_lite_unittest.cc \
google/protobuf/reflection_ops_unittest.cc \
google/protobuf/repeated_field_reflection_unittest.cc \
google/protobuf/repeated_field_unittest.cc \
@@ -750,12 +810,15 @@ protobuf_test_SOURCES = \
google/protobuf/io/printer_unittest.cc \
google/protobuf/io/tokenizer_unittest.cc \
google/protobuf/io/zero_copy_stream_unittest.cc \
+ google/protobuf/compiler/annotation_test_util.h \
+ google/protobuf/compiler/annotation_test_util.cc \
google/protobuf/compiler/command_line_interface_unittest.cc \
google/protobuf/compiler/importer_unittest.cc \
google/protobuf/compiler/mock_code_generator.cc \
google/protobuf/compiler/mock_code_generator.h \
google/protobuf/compiler/parser_unittest.cc \
google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc \
+ google/protobuf/compiler/cpp/cpp_move_unittest.cc \
google/protobuf/compiler/cpp/cpp_unittest.h \
google/protobuf/compiler/cpp/cpp_unittest.cc \
google/protobuf/compiler/cpp/cpp_plugin_unittest.cc \
@@ -765,7 +828,9 @@ protobuf_test_SOURCES = \
google/protobuf/compiler/objectivec/objectivec_helpers_unittest.cc \
google/protobuf/compiler/python/python_plugin_unittest.cc \
google/protobuf/compiler/ruby/ruby_generator_unittest.cc \
+ google/protobuf/compiler/csharp/csharp_bootstrap_unittest.cc \
google/protobuf/compiler/csharp/csharp_generator_unittest.cc \
+ google/protobuf/util/delimited_message_util_test.cc \
google/protobuf/util/field_comparator_test.cc \
google/protobuf/util/field_mask_util_test.cc \
google/protobuf/util/internal/default_value_objectwriter_test.cc \
@@ -810,7 +875,12 @@ COMMON_LITE_TEST_SOURCES = \
# depend on gtest because our internal version of gtest depend on proto
# full runtime and we want to make sure this test builds without full
# runtime.
-protobuf_lite_test_LDADD = $(PTHREAD_LIBS) libprotobuf-lite.la
+protobuf_lite_test_LDADD = $(PTHREAD_LIBS) libprotobuf-lite.la \
+ ../gmock/gtest/lib/libgtest.la \
+ ../gmock/lib/libgmock.la \
+ ../gmock/lib/libgmock_main.la
+protobuf_lite_test_CPPFLAGS= -I$(srcdir)/../gmock/include \
+ -I$(srcdir)/../gmock/gtest/include
protobuf_lite_test_CXXFLAGS = $(NO_OPT_CXXFLAGS)
protobuf_lite_test_SOURCES = \
google/protobuf/lite_unittest.cc \
@@ -860,15 +930,11 @@ no_warning_test.cc:
echo "#include <$${FILE}>" >> no_warning_test.cc; \
fi \
done
- echo "#include <gtest/gtest.h>" >> no_warning_test.cc
- echo "TEST(NoWarningTest, Empty) {}" >> no_warning_test.cc
+ echo "int main(int, char**) { return 0; }" >> no_warning_test.cc
-no_warning_test_LDADD = $(PTHREAD_LIBS) libprotobuf.la \
- ../gmock/gtest/lib/libgtest.la \
- ../gmock/gtest/lib/libgtest_main.la
-no_warning_test_CPPFLAGS = -I$(srcdir)/../gmock/gtest/include
+no_warning_test_LDADD = $(PTHREAD_LIBS) libprotobuf.la libprotoc.la
no_warning_test_CXXFLAGS = $(PTHREAD_CFLAGS) $(PTHREAD_DEF) $(ZLIB_DEF) \
- -Wall -Werror
+ -Wall -Wextra -Werror -Wno-unused-parameter
nodist_no_warning_test_SOURCES = no_warning_test.cc $(protoc_outputs)
TESTS = protobuf-test protobuf-lazy-descriptor-test protobuf-lite-test \
diff --git a/src/google/protobuf/any.h b/src/google/protobuf/any.h
index 04e54166..c2c27ec3 100644
--- a/src/google/protobuf/any.h
+++ b/src/google/protobuf/any.h
@@ -63,7 +63,7 @@ class LIBPROTOBUF_EXPORT AnyMetadata {
// Unpacks the payload into the given message. Returns false if the message's
// type doesn't match the type specified in the type URL (i.e., the full
- // name after the last "/" of the type URL doesn't match the message's actaul
+ // name after the last "/" of the type URL doesn't match the message's actual
// full name) or parsing the payload has failed.
bool UnpackTo(Message* message) const;
@@ -90,8 +90,8 @@ extern const char kTypeGoogleProdComPrefix[]; // "type.googleprod.com/".
// Get the proto type name from Any::type_url value. For example, passing
// "type.googleapis.com/rpc.QueryOrigin" will return "rpc.QueryOrigin" in
-// *full_type_name. Returns false if type_url does not start with
-// "type.googleapis.com" or "type.googleprod.com".
+// *full_type_name. Returns false if the type_url does not have a "/"
+// in the type url separating the full type name.
bool ParseAnyTypeUrl(const string& type_url, string* full_type_name);
// See if message is of type google.protobuf.Any, if so, return the descriptors
diff --git a/src/google/protobuf/any.pb.cc b/src/google/protobuf/any.pb.cc
index e73ebffd..29687477 100644
--- a/src/google/protobuf/any.pb.cc
+++ b/src/google/protobuf/any.pb.cc
@@ -1,7 +1,6 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/any.proto
-#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include <google/protobuf/any.pb.h>
#include <algorithm>
@@ -15,48 +14,66 @@
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
+// This is a temporary google only hack
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+#include "third_party/protobuf/version.h"
+#endif
// @@protoc_insertion_point(includes)
-
namespace google {
namespace protobuf {
-class AnyDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<Any> {};
-AnyDefaultTypeInternal _Any_default_instance_;
-
-namespace {
-
-::google::protobuf::Metadata file_level_metadata[1];
-
-} // namespace
+class AnyDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<Any>
+ _instance;
+} _Any_default_instance_;
+} // namespace protobuf
+} // namespace google
+namespace protobuf_google_2fprotobuf_2fany_2eproto {
+void InitDefaultsAnyImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ {
+ void* ptr = &::google::protobuf::_Any_default_instance_;
+ new (ptr) ::google::protobuf::Any();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::Any::InitAsDefaultInstance();
+}
-const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fany_2eproto() GOOGLE_ATTRIBUTE_COLD;
-const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fany_2eproto() {
- static const ::google::protobuf::uint32 offsets[] = {
- ~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Any, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Any, type_url_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Any, value_),
- };
- return offsets;
+void InitDefaultsAny() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsAnyImpl);
}
-static const ::google::protobuf::internal::MigrationSchema schemas[] = {
- { 0, -1, sizeof(Any)},
-};
+::google::protobuf::Metadata file_level_metadata[1];
-static const ::google::protobuf::internal::DefaultInstanceData file_default_instances[] = {
- {reinterpret_cast<const ::google::protobuf::Message*>(&_Any_default_instance_), NULL},
+const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+ ~0u, // no _has_bits_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Any, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Any, type_url_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Any, value_),
+};
+static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+ { 0, -1, sizeof(::google::protobuf::Any)},
};
-namespace {
+static ::google::protobuf::Message const * const file_default_instances[] = {
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_Any_default_instance_),
+};
void protobuf_AssignDescriptors() {
- protobuf_AddDesc_google_2fprotobuf_2fany_2eproto();
+ AddDescriptors();
::google::protobuf::MessageFactory* factory = NULL;
AssignDescriptors(
- "google/protobuf/any.proto", schemas, file_default_instances, protobuf_Offsets_google_2fprotobuf_2fany_2eproto(), factory,
+ "google/protobuf/any.proto", schemas, file_default_instances, TableStruct::offsets, factory,
file_level_metadata, NULL, NULL);
}
@@ -65,33 +82,15 @@ void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);
}
-void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
+void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 1);
}
-} // namespace
-
-void protobuf_ShutdownFile_google_2fprotobuf_2fany_2eproto() {
- _Any_default_instance_.Shutdown();
- delete file_level_metadata[0].reflection;
-}
-
-void protobuf_InitDefaults_google_2fprotobuf_2fany_2eproto_impl() {
- GOOGLE_PROTOBUF_VERIFY_VERSION;
-
- ::google::protobuf::internal::InitProtobufDefaults();
- _Any_default_instance_.DefaultConstruct();
-}
-
-void protobuf_InitDefaults_google_2fprotobuf_2fany_2eproto() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &protobuf_InitDefaults_google_2fprotobuf_2fany_2eproto_impl);
-}
-void protobuf_AddDesc_google_2fprotobuf_2fany_2eproto_impl() {
- protobuf_InitDefaults_google_2fprotobuf_2fany_2eproto();
- static const char descriptor[] = {
+void AddDescriptorsImpl() {
+ InitDefaults();
+ static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n\031google/protobuf/any.proto\022\017google.prot"
"obuf\"&\n\003Any\022\020\n\010type_url\030\001 \001(\t\022\r\n\005value\030\002"
" \001(\014Bo\n\023com.google.protobufB\010AnyProtoP\001Z"
@@ -103,23 +102,26 @@ void protobuf_AddDesc_google_2fprotobuf_2fany_2eproto_impl() {
descriptor, 205);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"google/protobuf/any.proto", &protobuf_RegisterTypes);
- ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_google_2fprotobuf_2fany_2eproto);
}
-GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AddDesc_google_2fprotobuf_2fany_2eproto_once_);
-void protobuf_AddDesc_google_2fprotobuf_2fany_2eproto() {
- ::google::protobuf::GoogleOnceInit(&protobuf_AddDesc_google_2fprotobuf_2fany_2eproto_once_,
- &protobuf_AddDesc_google_2fprotobuf_2fany_2eproto_impl);
+void AddDescriptors() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);
}
-// Force AddDescriptors() to be called at static initialization time.
-struct StaticDescriptorInitializer_google_2fprotobuf_2fany_2eproto {
- StaticDescriptorInitializer_google_2fprotobuf_2fany_2eproto() {
- protobuf_AddDesc_google_2fprotobuf_2fany_2eproto();
+// Force AddDescriptors() to be called at dynamic initialization time.
+struct StaticDescriptorInitializer {
+ StaticDescriptorInitializer() {
+ AddDescriptors();
}
-} static_descriptor_initializer_google_2fprotobuf_2fany_2eproto_;
+} static_descriptor_initializer;
+} // namespace protobuf_google_2fprotobuf_2fany_2eproto
+namespace google {
+namespace protobuf {
// ===================================================================
+void Any::InitAsDefaultInstance() {
+}
void Any::PackFrom(const ::google::protobuf::Message& message) {
_any_metadata_.PackFrom(message);
}
@@ -141,7 +143,7 @@ const int Any::kValueFieldNumber;
Any::Any()
: ::google::protobuf::Message(), _internal_metadata_(NULL), _any_metadata_(&type_url_, &value_) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fany_2eproto();
+ ::protobuf_google_2fprotobuf_2fany_2eproto::InitDefaultsAny();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Any)
@@ -185,12 +187,12 @@ void Any::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* Any::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[0].descriptor;
+ ::protobuf_google_2fprotobuf_2fany_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fany_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const Any& Any::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fany_2eproto();
+ ::protobuf_google_2fprotobuf_2fany_2eproto::InitDefaultsAny();
return *internal_default_instance();
}
@@ -204,8 +206,13 @@ Any* Any::New(::google::protobuf::Arena* arena) const {
void Any::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Any)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
type_url_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ _internal_metadata_.Clear();
}
bool Any::MergePartialFromCodedStream(
@@ -220,11 +227,12 @@ bool Any::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// string type_url = 1;
case 1: {
- if (tag == 10u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_type_url()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->type_url().data(), this->type_url().length(),
+ this->type_url().data(), static_cast<int>(this->type_url().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.protobuf.Any.type_url"));
} else {
@@ -235,7 +243,8 @@ bool Any::MergePartialFromCodedStream(
// bytes value = 2;
case 2: {
- if (tag == 18u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadBytes(
input, this->mutable_value()));
} else {
@@ -246,12 +255,11 @@ bool Any::MergePartialFromCodedStream(
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
- DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
+ DO_(::google::protobuf::internal::WireFormat::SkipField(
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -268,10 +276,13 @@ failure:
void Any::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.Any)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// string type_url = 1;
if (this->type_url().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->type_url().data(), this->type_url().length(),
+ this->type_url().data(), static_cast<int>(this->type_url().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Any.type_url");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -284,6 +295,10 @@ void Any::SerializeWithCachedSizes(
2, this->value(), output);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ }
// @@protoc_insertion_point(serialize_end:google.protobuf.Any)
}
@@ -291,10 +306,13 @@ void Any::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Any)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// string type_url = 1;
if (this->type_url().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->type_url().data(), this->type_url().length(),
+ this->type_url().data(), static_cast<int>(this->type_url().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Any.type_url");
target =
@@ -309,6 +327,10 @@ void Any::SerializeWithCachedSizes(
2, this->value(), target);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ }
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Any)
return target;
}
@@ -317,6 +339,11 @@ size_t Any::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.Any)
size_t total_size = 0;
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ total_size +=
+ ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ }
// string type_url = 1;
if (this->type_url().size() > 0) {
total_size += 1 +
@@ -357,6 +384,9 @@ void Any::MergeFrom(const Any& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Any)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
if (from.type_url().size() > 0) {
type_url_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.type_url_);
@@ -390,111 +420,20 @@ void Any::Swap(Any* other) {
InternalSwap(other);
}
void Any::InternalSwap(Any* other) {
+ using std::swap;
type_url_.Swap(&other->type_url_);
value_.Swap(&other->value_);
- std::swap(_cached_size_, other->_cached_size_);
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Any::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[0];
+ protobuf_google_2fprotobuf_2fany_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fany_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// Any
-
-// string type_url = 1;
-void Any::clear_type_url() {
- type_url_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-const ::std::string& Any::type_url() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Any.type_url)
- return type_url_.GetNoArena();
-}
-void Any::set_type_url(const ::std::string& value) {
-
- type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.Any.type_url)
-}
-void Any::set_type_url(const char* value) {
-
- type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.Any.type_url)
-}
-void Any::set_type_url(const char* value, size_t size) {
-
- type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.Any.type_url)
-}
-::std::string* Any::mutable_type_url() {
-
- // @@protoc_insertion_point(field_mutable:google.protobuf.Any.type_url)
- return type_url_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* Any::release_type_url() {
- // @@protoc_insertion_point(field_release:google.protobuf.Any.type_url)
-
- return type_url_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void Any::set_allocated_type_url(::std::string* type_url) {
- if (type_url != NULL) {
-
- } else {
-
- }
- type_url_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), type_url);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.Any.type_url)
-}
-
-// bytes value = 2;
-void Any::clear_value() {
- value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-const ::std::string& Any::value() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Any.value)
- return value_.GetNoArena();
-}
-void Any::set_value(const ::std::string& value) {
-
- value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.Any.value)
-}
-void Any::set_value(const char* value) {
-
- value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.Any.value)
-}
-void Any::set_value(const void* value, size_t size) {
-
- value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.Any.value)
-}
-::std::string* Any::mutable_value() {
-
- // @@protoc_insertion_point(field_mutable:google.protobuf.Any.value)
- return value_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* Any::release_value() {
- // @@protoc_insertion_point(field_release:google.protobuf.Any.value)
-
- return value_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void Any::set_allocated_value(::std::string* value) {
- if (value != NULL) {
-
- } else {
-
- }
- value_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.Any.value)
-}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
-
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/any.pb.h b/src/google/protobuf/any.pb.h
index 0d8deab6..20a1cbed 100644
--- a/src/google/protobuf/any.pb.h
+++ b/src/google/protobuf/any.pb.h
@@ -8,19 +8,21 @@
#include <google/protobuf/stubs/common.h>
-#if GOOGLE_PROTOBUF_VERSION < 3001000
+#if GOOGLE_PROTOBUF_VERSION < 3004000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3001000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3004000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
+#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
+#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
@@ -29,6 +31,24 @@
#include <google/protobuf/unknown_field_set.h>
#include <google/protobuf/any.h>
// @@protoc_insertion_point(includes)
+
+namespace protobuf_google_2fprotobuf_2fany_2eproto {
+// Internal implementation detail -- do not use these members.
+struct LIBPROTOBUF_EXPORT TableStruct {
+ static const ::google::protobuf::internal::ParseTableField entries[];
+ static const ::google::protobuf::internal::AuxillaryParseTableField aux[];
+ static const ::google::protobuf::internal::ParseTable schema[1];
+ static const ::google::protobuf::internal::FieldMetadata field_metadata[];
+ static const ::google::protobuf::internal::SerializationTable serialization_table[];
+ static const ::google::protobuf::uint32 offsets[];
+};
+void LIBPROTOBUF_EXPORT AddDescriptors();
+void LIBPROTOBUF_EXPORT InitDefaultsAnyImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsAny();
+inline void LIBPROTOBUF_EXPORT InitDefaults() {
+ InitDefaultsAny();
+}
+} // namespace protobuf_google_2fprotobuf_2fany_2eproto
namespace google {
namespace protobuf {
class Any;
@@ -36,14 +56,9 @@ class AnyDefaultTypeInternal;
LIBPROTOBUF_EXPORT extern AnyDefaultTypeInternal _Any_default_instance_;
} // namespace protobuf
} // namespace google
-
namespace google {
namespace protobuf {
-// Internal implementation detail -- do not call these.
-void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fany_2eproto();
-void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fany_2eproto();
-
// ===================================================================
class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Any) */ {
@@ -57,14 +72,31 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ Any(Any&& from) noexcept
+ : Any() {
+ *this = ::std::move(from);
+ }
+ inline Any& operator=(Any&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
static const ::google::protobuf::Descriptor* descriptor();
static const Any& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const Any* internal_default_instance() {
return reinterpret_cast<const Any*>(
&_Any_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 0;
// implements Any -----------------------------------------------
@@ -77,6 +109,9 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in
}
void Swap(Any* other);
+ friend void swap(Any& a, Any& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -97,10 +132,6 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
@@ -127,6 +158,9 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in
static const int kTypeUrlFieldNumber = 1;
const ::std::string& type_url() const;
void set_type_url(const ::std::string& value);
+ #if LANG_CXX11
+ void set_type_url(::std::string&& value);
+ #endif
void set_type_url(const char* value);
void set_type_url(const char* value, size_t size);
::std::string* mutable_type_url();
@@ -138,6 +172,9 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in
static const int kValueFieldNumber = 2;
const ::std::string& value() const;
void set_value(const ::std::string& value);
+ #if LANG_CXX11
+ void set_value(::std::string&& value);
+ #endif
void set_value(const char* value);
void set_value(const void* value, size_t size);
::std::string* mutable_value();
@@ -152,18 +189,18 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in
::google::protobuf::internal::ArenaStringPtr value_;
mutable int _cached_size_;
::google::protobuf::internal::AnyMetadata _any_metadata_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fany_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fany_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fany_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fany_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fany_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fany_2eproto::InitDefaultsAnyImpl();
};
// ===================================================================
// ===================================================================
-#if !PROTOBUF_INLINE_NOT_IN_HEADERS
+#ifdef __GNUC__
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wstrict-aliasing"
+#endif // __GNUC__
// Any
// string type_url = 1;
@@ -179,7 +216,16 @@ inline void Any::set_type_url(const ::std::string& value) {
type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.Any.type_url)
}
+#if LANG_CXX11
+inline void Any::set_type_url(::std::string&& value) {
+
+ type_url_.SetNoArena(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.Any.type_url)
+}
+#endif
inline void Any::set_type_url(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.Any.type_url)
@@ -223,7 +269,16 @@ inline void Any::set_value(const ::std::string& value) {
value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.Any.value)
}
+#if LANG_CXX11
+inline void Any::set_value(::std::string&& value) {
+
+ value_.SetNoArena(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.Any.value)
+}
+#endif
inline void Any::set_value(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.Any.value)
@@ -254,11 +309,12 @@ inline void Any::set_allocated_value(::std::string* value) {
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Any.value)
}
-#endif // !PROTOBUF_INLINE_NOT_IN_HEADERS
+#ifdef __GNUC__
+ #pragma GCC diagnostic pop
+#endif // __GNUC__
// @@protoc_insertion_point(namespace_scope)
-
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/any.proto b/src/google/protobuf/any.proto
index 9bd3f50a..c7486676 100644
--- a/src/google/protobuf/any.proto
+++ b/src/google/protobuf/any.proto
@@ -74,6 +74,16 @@ option objc_class_prefix = "GPB";
// any.Unpack(foo)
// ...
//
+// Example 4: Pack and unpack a message in Go
+//
+// foo := &pb.Foo{...}
+// any, err := ptypes.MarshalAny(foo)
+// ...
+// foo := &pb.Foo{}
+// if err := ptypes.UnmarshalAny(any, foo); err != nil {
+// ...
+// }
+//
// The pack methods provided by protobuf library will by default use
// 'type.googleapis.com/full.type.name' as the type URL and the unpack
// methods only use the fully qualified type name after the last '/'
diff --git a/src/google/protobuf/api.pb.cc b/src/google/protobuf/api.pb.cc
index 2bc6153a..439a47c6 100644
--- a/src/google/protobuf/api.pb.cc
+++ b/src/google/protobuf/api.pb.cc
@@ -1,7 +1,6 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/api.proto
-#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include <google/protobuf/api.pb.h>
#include <algorithm>
@@ -15,78 +14,151 @@
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
+// This is a temporary google only hack
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+#include "third_party/protobuf/version.h"
+#endif
// @@protoc_insertion_point(includes)
-
namespace google {
namespace protobuf {
-class ApiDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<Api> {};
-ApiDefaultTypeInternal _Api_default_instance_;
-class MethodDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<Method> {};
-MethodDefaultTypeInternal _Method_default_instance_;
-class MixinDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<Mixin> {};
-MixinDefaultTypeInternal _Mixin_default_instance_;
+class ApiDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<Api>
+ _instance;
+} _Api_default_instance_;
+class MethodDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<Method>
+ _instance;
+} _Method_default_instance_;
+class MixinDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<Mixin>
+ _instance;
+} _Mixin_default_instance_;
+} // namespace protobuf
+} // namespace google
+namespace protobuf_google_2fprotobuf_2fapi_2eproto {
+void InitDefaultsApiImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
-namespace {
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMethod();
+ protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOption();
+ protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::InitDefaultsSourceContext();
+ protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMixin();
+ {
+ void* ptr = &::google::protobuf::_Api_default_instance_;
+ new (ptr) ::google::protobuf::Api();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::Api::InitAsDefaultInstance();
+}
-::google::protobuf::Metadata file_level_metadata[3];
+void InitDefaultsApi() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsApiImpl);
+}
-} // namespace
-
-
-const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fapi_2eproto() GOOGLE_ATTRIBUTE_COLD;
-const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fapi_2eproto() {
- static const ::google::protobuf::uint32 offsets[] = {
- ~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Api, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Api, name_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Api, methods_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Api, options_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Api, version_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Api, source_context_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Api, mixins_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Api, syntax_),
- ~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Method, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Method, name_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Method, request_type_url_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Method, request_streaming_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Method, response_type_url_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Method, response_streaming_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Method, options_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Method, syntax_),
- ~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Mixin, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Mixin, name_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Mixin, root_),
- };
- return offsets;
+void InitDefaultsMethodImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOption();
+ {
+ void* ptr = &::google::protobuf::_Method_default_instance_;
+ new (ptr) ::google::protobuf::Method();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::Method::InitAsDefaultInstance();
}
-static const ::google::protobuf::internal::MigrationSchema schemas[] = {
- { 0, -1, sizeof(Api)},
- { 11, -1, sizeof(Method)},
- { 22, -1, sizeof(Mixin)},
-};
+void InitDefaultsMethod() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsMethodImpl);
+}
-static const ::google::protobuf::internal::DefaultInstanceData file_default_instances[] = {
- {reinterpret_cast<const ::google::protobuf::Message*>(&_Api_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_Method_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_Mixin_default_instance_), NULL},
+void InitDefaultsMixinImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ {
+ void* ptr = &::google::protobuf::_Mixin_default_instance_;
+ new (ptr) ::google::protobuf::Mixin();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::Mixin::InitAsDefaultInstance();
+}
+
+void InitDefaultsMixin() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsMixinImpl);
+}
+
+::google::protobuf::Metadata file_level_metadata[3];
+
+const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+ ~0u, // no _has_bits_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Api, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Api, name_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Api, methods_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Api, options_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Api, version_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Api, source_context_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Api, mixins_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Api, syntax_),
+ ~0u, // no _has_bits_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Method, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Method, name_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Method, request_type_url_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Method, request_streaming_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Method, response_type_url_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Method, response_streaming_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Method, options_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Method, syntax_),
+ ~0u, // no _has_bits_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Mixin, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Mixin, name_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Mixin, root_),
+};
+static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+ { 0, -1, sizeof(::google::protobuf::Api)},
+ { 12, -1, sizeof(::google::protobuf::Method)},
+ { 24, -1, sizeof(::google::protobuf::Mixin)},
};
-namespace {
+static ::google::protobuf::Message const * const file_default_instances[] = {
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_Api_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_Method_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_Mixin_default_instance_),
+};
void protobuf_AssignDescriptors() {
- protobuf_AddDesc_google_2fprotobuf_2fapi_2eproto();
+ AddDescriptors();
::google::protobuf::MessageFactory* factory = NULL;
AssignDescriptors(
- "google/protobuf/api.proto", schemas, file_default_instances, protobuf_Offsets_google_2fprotobuf_2fapi_2eproto(), factory,
+ "google/protobuf/api.proto", schemas, file_default_instances, TableStruct::offsets, factory,
file_level_metadata, NULL, NULL);
}
@@ -95,43 +167,15 @@ void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);
}
-void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
+void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 3);
}
-} // namespace
-
-void protobuf_ShutdownFile_google_2fprotobuf_2fapi_2eproto() {
- _Api_default_instance_.Shutdown();
- delete file_level_metadata[0].reflection;
- _Method_default_instance_.Shutdown();
- delete file_level_metadata[1].reflection;
- _Mixin_default_instance_.Shutdown();
- delete file_level_metadata[2].reflection;
-}
-
-void protobuf_InitDefaults_google_2fprotobuf_2fapi_2eproto_impl() {
- GOOGLE_PROTOBUF_VERIFY_VERSION;
-
- ::google::protobuf::protobuf_InitDefaults_google_2fprotobuf_2fsource_5fcontext_2eproto();
- ::google::protobuf::protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto();
- ::google::protobuf::internal::InitProtobufDefaults();
- _Api_default_instance_.DefaultConstruct();
- _Method_default_instance_.DefaultConstruct();
- _Mixin_default_instance_.DefaultConstruct();
- _Api_default_instance_.get_mutable()->source_context_ = const_cast< ::google::protobuf::SourceContext*>(
- ::google::protobuf::SourceContext::internal_default_instance());
-}
-
-void protobuf_InitDefaults_google_2fprotobuf_2fapi_2eproto() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &protobuf_InitDefaults_google_2fprotobuf_2fapi_2eproto_impl);
-}
-void protobuf_AddDesc_google_2fprotobuf_2fapi_2eproto_impl() {
- protobuf_InitDefaults_google_2fprotobuf_2fapi_2eproto();
- static const char descriptor[] = {
+void AddDescriptorsImpl() {
+ InitDefaults();
+ static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n\031google/protobuf/api.proto\022\017google.prot"
"obuf\032$google/protobuf/source_context.pro"
"to\032\032google/protobuf/type.proto\"\201\002\n\003Api\022\014"
@@ -156,25 +200,39 @@ void protobuf_AddDesc_google_2fprotobuf_2fapi_2eproto_impl() {
descriptor, 750);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"google/protobuf/api.proto", &protobuf_RegisterTypes);
- ::google::protobuf::protobuf_AddDesc_google_2fprotobuf_2fsource_5fcontext_2eproto();
- ::google::protobuf::protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto();
- ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_google_2fprotobuf_2fapi_2eproto);
+ ::protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::AddDescriptors();
+ ::protobuf_google_2fprotobuf_2ftype_2eproto::AddDescriptors();
}
-GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AddDesc_google_2fprotobuf_2fapi_2eproto_once_);
-void protobuf_AddDesc_google_2fprotobuf_2fapi_2eproto() {
- ::google::protobuf::GoogleOnceInit(&protobuf_AddDesc_google_2fprotobuf_2fapi_2eproto_once_,
- &protobuf_AddDesc_google_2fprotobuf_2fapi_2eproto_impl);
+void AddDescriptors() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);
}
-// Force AddDescriptors() to be called at static initialization time.
-struct StaticDescriptorInitializer_google_2fprotobuf_2fapi_2eproto {
- StaticDescriptorInitializer_google_2fprotobuf_2fapi_2eproto() {
- protobuf_AddDesc_google_2fprotobuf_2fapi_2eproto();
+// Force AddDescriptors() to be called at dynamic initialization time.
+struct StaticDescriptorInitializer {
+ StaticDescriptorInitializer() {
+ AddDescriptors();
}
-} static_descriptor_initializer_google_2fprotobuf_2fapi_2eproto_;
+} static_descriptor_initializer;
+} // namespace protobuf_google_2fprotobuf_2fapi_2eproto
+namespace google {
+namespace protobuf {
// ===================================================================
+void Api::InitAsDefaultInstance() {
+ ::google::protobuf::_Api_default_instance_._instance.get_mutable()->source_context_ = const_cast< ::google::protobuf::SourceContext*>(
+ ::google::protobuf::SourceContext::internal_default_instance());
+}
+void Api::clear_options() {
+ options_.Clear();
+}
+void Api::clear_source_context() {
+ if (GetArenaNoVirtual() == NULL && source_context_ != NULL) {
+ delete source_context_;
+ }
+ source_context_ = NULL;
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Api::kNameFieldNumber;
const int Api::kMethodsFieldNumber;
@@ -188,7 +246,7 @@ const int Api::kSyntaxFieldNumber;
Api::Api()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fapi_2eproto();
+ ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsApi();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Api)
@@ -221,8 +279,9 @@ Api::Api(const Api& from)
void Api::SharedCtor() {
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
version_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- ::memset(&source_context_, 0, reinterpret_cast<char*>(&syntax_) -
- reinterpret_cast<char*>(&source_context_) + sizeof(syntax_));
+ ::memset(&source_context_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&syntax_) -
+ reinterpret_cast<char*>(&source_context_)) + sizeof(syntax_));
_cached_size_ = 0;
}
@@ -234,9 +293,7 @@ Api::~Api() {
void Api::SharedDtor() {
name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
version_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- if (this != internal_default_instance()) {
- delete source_context_;
- }
+ if (this != internal_default_instance()) delete source_context_;
}
void Api::SetCachedSize(int size) const {
@@ -245,12 +302,12 @@ void Api::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* Api::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[0].descriptor;
+ ::protobuf_google_2fprotobuf_2fapi_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fapi_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const Api& Api::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fapi_2eproto();
+ ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsApi();
return *internal_default_instance();
}
@@ -264,6 +321,10 @@ Api* Api::New(::google::protobuf::Arena* arena) const {
void Api::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Api)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
methods_.Clear();
options_.Clear();
mixins_.Clear();
@@ -274,6 +335,7 @@ void Api::Clear() {
}
source_context_ = NULL;
syntax_ = 0;
+ _internal_metadata_.Clear();
}
bool Api::MergePartialFromCodedStream(
@@ -288,11 +350,12 @@ bool Api::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// string name = 1;
case 1: {
- if (tag == 10u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.protobuf.Api.name"));
} else {
@@ -303,37 +366,34 @@ bool Api::MergePartialFromCodedStream(
// repeated .google.protobuf.Method methods = 2;
case 2: {
- if (tag == 18u) {
- DO_(input->IncrementRecursionDepth());
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
- input, add_methods()));
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_methods()));
} else {
goto handle_unusual;
}
- input->UnsafeDecrementRecursionDepth();
break;
}
// repeated .google.protobuf.Option options = 3;
case 3: {
- if (tag == 26u) {
- DO_(input->IncrementRecursionDepth());
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
- input, add_options()));
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_options()));
} else {
goto handle_unusual;
}
- input->UnsafeDecrementRecursionDepth();
break;
}
// string version = 4;
case 4: {
- if (tag == 34u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_version()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->version().data(), this->version().length(),
+ this->version().data(), static_cast<int>(this->version().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.protobuf.Api.version"));
} else {
@@ -344,8 +404,9 @@ bool Api::MergePartialFromCodedStream(
// .google.protobuf.SourceContext source_context = 5;
case 5: {
- if (tag == 42u) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(42u /* 42 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_source_context()));
} else {
goto handle_unusual;
@@ -355,20 +416,19 @@ bool Api::MergePartialFromCodedStream(
// repeated .google.protobuf.Mixin mixins = 6;
case 6: {
- if (tag == 50u) {
- DO_(input->IncrementRecursionDepth());
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
- input, add_mixins()));
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(50u /* 50 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_mixins()));
} else {
goto handle_unusual;
}
- input->UnsafeDecrementRecursionDepth();
break;
}
// .google.protobuf.Syntax syntax = 7;
case 7: {
- if (tag == 56u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(56u /* 56 & 0xFF */)) {
int value;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
@@ -382,12 +442,11 @@ bool Api::MergePartialFromCodedStream(
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
- DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
+ DO_(::google::protobuf::internal::WireFormat::SkipField(
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -404,10 +463,13 @@ failure:
void Api::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.Api)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// string name = 1;
if (this->name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Api.name");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -415,21 +477,23 @@ void Api::SerializeWithCachedSizes(
}
// repeated .google.protobuf.Method methods = 2;
- for (unsigned int i = 0, n = this->methods_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->methods_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 2, this->methods(i), output);
+ 2, this->methods(static_cast<int>(i)), output);
}
// repeated .google.protobuf.Option options = 3;
- for (unsigned int i = 0, n = this->options_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->options_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 3, this->options(i), output);
+ 3, this->options(static_cast<int>(i)), output);
}
// string version = 4;
if (this->version().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->version().data(), this->version().length(),
+ this->version().data(), static_cast<int>(this->version().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Api.version");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -443,9 +507,10 @@ void Api::SerializeWithCachedSizes(
}
// repeated .google.protobuf.Mixin mixins = 6;
- for (unsigned int i = 0, n = this->mixins_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->mixins_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 6, this->mixins(i), output);
+ 6, this->mixins(static_cast<int>(i)), output);
}
// .google.protobuf.Syntax syntax = 7;
@@ -454,6 +519,10 @@ void Api::SerializeWithCachedSizes(
7, this->syntax(), output);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ }
// @@protoc_insertion_point(serialize_end:google.protobuf.Api)
}
@@ -461,10 +530,13 @@ void Api::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Api)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// string name = 1;
if (this->name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Api.name");
target =
@@ -473,23 +545,25 @@ void Api::SerializeWithCachedSizes(
}
// repeated .google.protobuf.Method methods = 2;
- for (unsigned int i = 0, n = this->methods_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->methods_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 2, this->methods(i), false, target);
+ InternalWriteMessageToArray(
+ 2, this->methods(static_cast<int>(i)), deterministic, target);
}
// repeated .google.protobuf.Option options = 3;
- for (unsigned int i = 0, n = this->options_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->options_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 3, this->options(i), false, target);
+ InternalWriteMessageToArray(
+ 3, this->options(static_cast<int>(i)), deterministic, target);
}
// string version = 4;
if (this->version().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->version().data(), this->version().length(),
+ this->version().data(), static_cast<int>(this->version().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Api.version");
target =
@@ -500,15 +574,16 @@ void Api::SerializeWithCachedSizes(
// .google.protobuf.SourceContext source_context = 5;
if (this->has_source_context()) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 5, *this->source_context_, false, target);
+ InternalWriteMessageToArray(
+ 5, *this->source_context_, deterministic, target);
}
// repeated .google.protobuf.Mixin mixins = 6;
- for (unsigned int i = 0, n = this->mixins_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->mixins_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 6, this->mixins(i), false, target);
+ InternalWriteMessageToArray(
+ 6, this->mixins(static_cast<int>(i)), deterministic, target);
}
// .google.protobuf.Syntax syntax = 7;
@@ -517,6 +592,10 @@ void Api::SerializeWithCachedSizes(
7, this->syntax(), target);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ }
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Api)
return target;
}
@@ -525,36 +604,41 @@ size_t Api::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.Api)
size_t total_size = 0;
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ total_size +=
+ ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ }
// repeated .google.protobuf.Method methods = 2;
{
- unsigned int count = this->methods_size();
+ unsigned int count = static_cast<unsigned int>(this->methods_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->methods(i));
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->methods(static_cast<int>(i)));
}
}
// repeated .google.protobuf.Option options = 3;
{
- unsigned int count = this->options_size();
+ unsigned int count = static_cast<unsigned int>(this->options_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->options(i));
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->options(static_cast<int>(i)));
}
}
// repeated .google.protobuf.Mixin mixins = 6;
{
- unsigned int count = this->mixins_size();
+ unsigned int count = static_cast<unsigned int>(this->mixins_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->mixins(i));
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->mixins(static_cast<int>(i)));
}
}
@@ -575,7 +659,7 @@ size_t Api::ByteSizeLong() const {
// .google.protobuf.SourceContext source_context = 5;
if (this->has_source_context()) {
total_size += 1 +
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
*this->source_context_);
}
@@ -611,6 +695,9 @@ void Api::MergeFrom(const Api& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Api)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
methods_.MergeFrom(from.methods_);
options_.MergeFrom(from.options_);
mixins_.MergeFrom(from.mixins_);
@@ -653,259 +740,31 @@ void Api::Swap(Api* other) {
InternalSwap(other);
}
void Api::InternalSwap(Api* other) {
- methods_.UnsafeArenaSwap(&other->methods_);
- options_.UnsafeArenaSwap(&other->options_);
- mixins_.UnsafeArenaSwap(&other->mixins_);
+ using std::swap;
+ methods_.InternalSwap(&other->methods_);
+ options_.InternalSwap(&other->options_);
+ mixins_.InternalSwap(&other->mixins_);
name_.Swap(&other->name_);
version_.Swap(&other->version_);
- std::swap(source_context_, other->source_context_);
- std::swap(syntax_, other->syntax_);
- std::swap(_cached_size_, other->_cached_size_);
+ swap(source_context_, other->source_context_);
+ swap(syntax_, other->syntax_);
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Api::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[0];
+ protobuf_google_2fprotobuf_2fapi_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fapi_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// Api
-// string name = 1;
-void Api::clear_name() {
- name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-const ::std::string& Api::name() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Api.name)
- return name_.GetNoArena();
-}
-void Api::set_name(const ::std::string& value) {
-
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.Api.name)
-}
-void Api::set_name(const char* value) {
-
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.Api.name)
-}
-void Api::set_name(const char* value, size_t size) {
-
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.Api.name)
-}
-::std::string* Api::mutable_name() {
-
- // @@protoc_insertion_point(field_mutable:google.protobuf.Api.name)
- return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* Api::release_name() {
- // @@protoc_insertion_point(field_release:google.protobuf.Api.name)
-
- return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void Api::set_allocated_name(::std::string* name) {
- if (name != NULL) {
-
- } else {
-
- }
- name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.Api.name)
-}
-
-// repeated .google.protobuf.Method methods = 2;
-int Api::methods_size() const {
- return methods_.size();
-}
-void Api::clear_methods() {
- methods_.Clear();
-}
-const ::google::protobuf::Method& Api::methods(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.Api.methods)
- return methods_.Get(index);
-}
-::google::protobuf::Method* Api::mutable_methods(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.Api.methods)
- return methods_.Mutable(index);
-}
-::google::protobuf::Method* Api::add_methods() {
- // @@protoc_insertion_point(field_add:google.protobuf.Api.methods)
- return methods_.Add();
-}
-::google::protobuf::RepeatedPtrField< ::google::protobuf::Method >*
-Api::mutable_methods() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.Api.methods)
- return &methods_;
-}
-const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Method >&
-Api::methods() const {
- // @@protoc_insertion_point(field_list:google.protobuf.Api.methods)
- return methods_;
-}
+// ===================================================================
-// repeated .google.protobuf.Option options = 3;
-int Api::options_size() const {
- return options_.size();
+void Method::InitAsDefaultInstance() {
}
-void Api::clear_options() {
+void Method::clear_options() {
options_.Clear();
}
-const ::google::protobuf::Option& Api::options(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.Api.options)
- return options_.Get(index);
-}
-::google::protobuf::Option* Api::mutable_options(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.Api.options)
- return options_.Mutable(index);
-}
-::google::protobuf::Option* Api::add_options() {
- // @@protoc_insertion_point(field_add:google.protobuf.Api.options)
- return options_.Add();
-}
-::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >*
-Api::mutable_options() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.Api.options)
- return &options_;
-}
-const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >&
-Api::options() const {
- // @@protoc_insertion_point(field_list:google.protobuf.Api.options)
- return options_;
-}
-
-// string version = 4;
-void Api::clear_version() {
- version_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-const ::std::string& Api::version() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Api.version)
- return version_.GetNoArena();
-}
-void Api::set_version(const ::std::string& value) {
-
- version_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.Api.version)
-}
-void Api::set_version(const char* value) {
-
- version_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.Api.version)
-}
-void Api::set_version(const char* value, size_t size) {
-
- version_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.Api.version)
-}
-::std::string* Api::mutable_version() {
-
- // @@protoc_insertion_point(field_mutable:google.protobuf.Api.version)
- return version_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* Api::release_version() {
- // @@protoc_insertion_point(field_release:google.protobuf.Api.version)
-
- return version_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void Api::set_allocated_version(::std::string* version) {
- if (version != NULL) {
-
- } else {
-
- }
- version_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), version);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.Api.version)
-}
-
-// .google.protobuf.SourceContext source_context = 5;
-bool Api::has_source_context() const {
- return this != internal_default_instance() && source_context_ != NULL;
-}
-void Api::clear_source_context() {
- if (GetArenaNoVirtual() == NULL && source_context_ != NULL) delete source_context_;
- source_context_ = NULL;
-}
-const ::google::protobuf::SourceContext& Api::source_context() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Api.source_context)
- return source_context_ != NULL ? *source_context_
- : *::google::protobuf::SourceContext::internal_default_instance();
-}
-::google::protobuf::SourceContext* Api::mutable_source_context() {
-
- if (source_context_ == NULL) {
- source_context_ = new ::google::protobuf::SourceContext;
- }
- // @@protoc_insertion_point(field_mutable:google.protobuf.Api.source_context)
- return source_context_;
-}
-::google::protobuf::SourceContext* Api::release_source_context() {
- // @@protoc_insertion_point(field_release:google.protobuf.Api.source_context)
-
- ::google::protobuf::SourceContext* temp = source_context_;
- source_context_ = NULL;
- return temp;
-}
-void Api::set_allocated_source_context(::google::protobuf::SourceContext* source_context) {
- delete source_context_;
- source_context_ = source_context;
- if (source_context) {
-
- } else {
-
- }
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.Api.source_context)
-}
-
-// repeated .google.protobuf.Mixin mixins = 6;
-int Api::mixins_size() const {
- return mixins_.size();
-}
-void Api::clear_mixins() {
- mixins_.Clear();
-}
-const ::google::protobuf::Mixin& Api::mixins(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.Api.mixins)
- return mixins_.Get(index);
-}
-::google::protobuf::Mixin* Api::mutable_mixins(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.Api.mixins)
- return mixins_.Mutable(index);
-}
-::google::protobuf::Mixin* Api::add_mixins() {
- // @@protoc_insertion_point(field_add:google.protobuf.Api.mixins)
- return mixins_.Add();
-}
-::google::protobuf::RepeatedPtrField< ::google::protobuf::Mixin >*
-Api::mutable_mixins() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.Api.mixins)
- return &mixins_;
-}
-const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Mixin >&
-Api::mixins() const {
- // @@protoc_insertion_point(field_list:google.protobuf.Api.mixins)
- return mixins_;
-}
-
-// .google.protobuf.Syntax syntax = 7;
-void Api::clear_syntax() {
- syntax_ = 0;
-}
-::google::protobuf::Syntax Api::syntax() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Api.syntax)
- return static_cast< ::google::protobuf::Syntax >(syntax_);
-}
-void Api::set_syntax(::google::protobuf::Syntax value) {
-
- syntax_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.Api.syntax)
-}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
-
-// ===================================================================
-
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Method::kNameFieldNumber;
const int Method::kRequestTypeUrlFieldNumber;
@@ -919,7 +778,7 @@ const int Method::kSyntaxFieldNumber;
Method::Method()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fapi_2eproto();
+ ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMethod();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Method)
@@ -943,8 +802,8 @@ Method::Method(const Method& from)
response_type_url_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.response_type_url_);
}
::memcpy(&request_streaming_, &from.request_streaming_,
- reinterpret_cast<char*>(&syntax_) -
- reinterpret_cast<char*>(&request_streaming_) + sizeof(syntax_));
+ static_cast<size_t>(reinterpret_cast<char*>(&syntax_) -
+ reinterpret_cast<char*>(&request_streaming_)) + sizeof(syntax_));
// @@protoc_insertion_point(copy_constructor:google.protobuf.Method)
}
@@ -952,8 +811,9 @@ void Method::SharedCtor() {
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
request_type_url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
response_type_url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- ::memset(&request_streaming_, 0, reinterpret_cast<char*>(&syntax_) -
- reinterpret_cast<char*>(&request_streaming_) + sizeof(syntax_));
+ ::memset(&request_streaming_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&syntax_) -
+ reinterpret_cast<char*>(&request_streaming_)) + sizeof(syntax_));
_cached_size_ = 0;
}
@@ -974,12 +834,12 @@ void Method::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* Method::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[1].descriptor;
+ ::protobuf_google_2fprotobuf_2fapi_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fapi_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const Method& Method::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fapi_2eproto();
+ ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMethod();
return *internal_default_instance();
}
@@ -993,12 +853,18 @@ Method* Method::New(::google::protobuf::Arena* arena) const {
void Method::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Method)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
options_.Clear();
name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
request_type_url_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
response_type_url_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- ::memset(&request_streaming_, 0, reinterpret_cast<char*>(&syntax_) -
- reinterpret_cast<char*>(&request_streaming_) + sizeof(syntax_));
+ ::memset(&request_streaming_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&syntax_) -
+ reinterpret_cast<char*>(&request_streaming_)) + sizeof(syntax_));
+ _internal_metadata_.Clear();
}
bool Method::MergePartialFromCodedStream(
@@ -1013,11 +879,12 @@ bool Method::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// string name = 1;
case 1: {
- if (tag == 10u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.protobuf.Method.name"));
} else {
@@ -1028,11 +895,12 @@ bool Method::MergePartialFromCodedStream(
// string request_type_url = 2;
case 2: {
- if (tag == 18u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_request_type_url()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->request_type_url().data(), this->request_type_url().length(),
+ this->request_type_url().data(), static_cast<int>(this->request_type_url().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.protobuf.Method.request_type_url"));
} else {
@@ -1043,7 +911,8 @@ bool Method::MergePartialFromCodedStream(
// bool request_streaming = 3;
case 3: {
- if (tag == 24u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
@@ -1056,11 +925,12 @@ bool Method::MergePartialFromCodedStream(
// string response_type_url = 4;
case 4: {
- if (tag == 34u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_response_type_url()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->response_type_url().data(), this->response_type_url().length(),
+ this->response_type_url().data(), static_cast<int>(this->response_type_url().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.protobuf.Method.response_type_url"));
} else {
@@ -1071,7 +941,8 @@ bool Method::MergePartialFromCodedStream(
// bool response_streaming = 5;
case 5: {
- if (tag == 40u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
@@ -1084,20 +955,19 @@ bool Method::MergePartialFromCodedStream(
// repeated .google.protobuf.Option options = 6;
case 6: {
- if (tag == 50u) {
- DO_(input->IncrementRecursionDepth());
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
- input, add_options()));
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(50u /* 50 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_options()));
} else {
goto handle_unusual;
}
- input->UnsafeDecrementRecursionDepth();
break;
}
// .google.protobuf.Syntax syntax = 7;
case 7: {
- if (tag == 56u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(56u /* 56 & 0xFF */)) {
int value;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
@@ -1111,12 +981,11 @@ bool Method::MergePartialFromCodedStream(
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
- DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
+ DO_(::google::protobuf::internal::WireFormat::SkipField(
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -1133,10 +1002,13 @@ failure:
void Method::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.Method)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// string name = 1;
if (this->name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Method.name");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -1146,7 +1018,7 @@ void Method::SerializeWithCachedSizes(
// string request_type_url = 2;
if (this->request_type_url().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->request_type_url().data(), this->request_type_url().length(),
+ this->request_type_url().data(), static_cast<int>(this->request_type_url().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Method.request_type_url");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -1161,7 +1033,7 @@ void Method::SerializeWithCachedSizes(
// string response_type_url = 4;
if (this->response_type_url().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->response_type_url().data(), this->response_type_url().length(),
+ this->response_type_url().data(), static_cast<int>(this->response_type_url().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Method.response_type_url");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -1174,9 +1046,10 @@ void Method::SerializeWithCachedSizes(
}
// repeated .google.protobuf.Option options = 6;
- for (unsigned int i = 0, n = this->options_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->options_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 6, this->options(i), output);
+ 6, this->options(static_cast<int>(i)), output);
}
// .google.protobuf.Syntax syntax = 7;
@@ -1185,6 +1058,10 @@ void Method::SerializeWithCachedSizes(
7, this->syntax(), output);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ }
// @@protoc_insertion_point(serialize_end:google.protobuf.Method)
}
@@ -1192,10 +1069,13 @@ void Method::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Method)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// string name = 1;
if (this->name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Method.name");
target =
@@ -1206,7 +1086,7 @@ void Method::SerializeWithCachedSizes(
// string request_type_url = 2;
if (this->request_type_url().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->request_type_url().data(), this->request_type_url().length(),
+ this->request_type_url().data(), static_cast<int>(this->request_type_url().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Method.request_type_url");
target =
@@ -1222,7 +1102,7 @@ void Method::SerializeWithCachedSizes(
// string response_type_url = 4;
if (this->response_type_url().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->response_type_url().data(), this->response_type_url().length(),
+ this->response_type_url().data(), static_cast<int>(this->response_type_url().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Method.response_type_url");
target =
@@ -1236,10 +1116,11 @@ void Method::SerializeWithCachedSizes(
}
// repeated .google.protobuf.Option options = 6;
- for (unsigned int i = 0, n = this->options_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->options_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 6, this->options(i), false, target);
+ InternalWriteMessageToArray(
+ 6, this->options(static_cast<int>(i)), deterministic, target);
}
// .google.protobuf.Syntax syntax = 7;
@@ -1248,6 +1129,10 @@ void Method::SerializeWithCachedSizes(
7, this->syntax(), target);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ }
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Method)
return target;
}
@@ -1256,14 +1141,19 @@ size_t Method::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.Method)
size_t total_size = 0;
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ total_size +=
+ ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ }
// repeated .google.protobuf.Option options = 6;
{
- unsigned int count = this->options_size();
+ unsigned int count = static_cast<unsigned int>(this->options_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->options(i));
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->options(static_cast<int>(i)));
}
}
@@ -1330,6 +1220,9 @@ void Method::MergeFrom(const Method& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Method)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
options_.MergeFrom(from.options_);
if (from.name().size() > 0) {
@@ -1377,232 +1270,28 @@ void Method::Swap(Method* other) {
InternalSwap(other);
}
void Method::InternalSwap(Method* other) {
- options_.UnsafeArenaSwap(&other->options_);
+ using std::swap;
+ options_.InternalSwap(&other->options_);
name_.Swap(&other->name_);
request_type_url_.Swap(&other->request_type_url_);
response_type_url_.Swap(&other->response_type_url_);
- std::swap(request_streaming_, other->request_streaming_);
- std::swap(response_streaming_, other->response_streaming_);
- std::swap(syntax_, other->syntax_);
- std::swap(_cached_size_, other->_cached_size_);
+ swap(request_streaming_, other->request_streaming_);
+ swap(response_streaming_, other->response_streaming_);
+ swap(syntax_, other->syntax_);
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Method::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[1];
-}
-
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// Method
-
-// string name = 1;
-void Method::clear_name() {
- name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-const ::std::string& Method::name() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Method.name)
- return name_.GetNoArena();
-}
-void Method::set_name(const ::std::string& value) {
-
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.Method.name)
-}
-void Method::set_name(const char* value) {
-
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.Method.name)
-}
-void Method::set_name(const char* value, size_t size) {
-
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.Method.name)
-}
-::std::string* Method::mutable_name() {
-
- // @@protoc_insertion_point(field_mutable:google.protobuf.Method.name)
- return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* Method::release_name() {
- // @@protoc_insertion_point(field_release:google.protobuf.Method.name)
-
- return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void Method::set_allocated_name(::std::string* name) {
- if (name != NULL) {
-
- } else {
-
- }
- name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.Method.name)
-}
-
-// string request_type_url = 2;
-void Method::clear_request_type_url() {
- request_type_url_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-const ::std::string& Method::request_type_url() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Method.request_type_url)
- return request_type_url_.GetNoArena();
-}
-void Method::set_request_type_url(const ::std::string& value) {
-
- request_type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.Method.request_type_url)
-}
-void Method::set_request_type_url(const char* value) {
-
- request_type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.Method.request_type_url)
-}
-void Method::set_request_type_url(const char* value, size_t size) {
-
- request_type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.Method.request_type_url)
-}
-::std::string* Method::mutable_request_type_url() {
-
- // @@protoc_insertion_point(field_mutable:google.protobuf.Method.request_type_url)
- return request_type_url_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* Method::release_request_type_url() {
- // @@protoc_insertion_point(field_release:google.protobuf.Method.request_type_url)
-
- return request_type_url_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void Method::set_allocated_request_type_url(::std::string* request_type_url) {
- if (request_type_url != NULL) {
-
- } else {
-
- }
- request_type_url_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), request_type_url);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.Method.request_type_url)
-}
-
-// bool request_streaming = 3;
-void Method::clear_request_streaming() {
- request_streaming_ = false;
-}
-bool Method::request_streaming() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Method.request_streaming)
- return request_streaming_;
-}
-void Method::set_request_streaming(bool value) {
-
- request_streaming_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.Method.request_streaming)
-}
-
-// string response_type_url = 4;
-void Method::clear_response_type_url() {
- response_type_url_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-const ::std::string& Method::response_type_url() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Method.response_type_url)
- return response_type_url_.GetNoArena();
-}
-void Method::set_response_type_url(const ::std::string& value) {
-
- response_type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.Method.response_type_url)
-}
-void Method::set_response_type_url(const char* value) {
-
- response_type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.Method.response_type_url)
-}
-void Method::set_response_type_url(const char* value, size_t size) {
-
- response_type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.Method.response_type_url)
-}
-::std::string* Method::mutable_response_type_url() {
-
- // @@protoc_insertion_point(field_mutable:google.protobuf.Method.response_type_url)
- return response_type_url_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* Method::release_response_type_url() {
- // @@protoc_insertion_point(field_release:google.protobuf.Method.response_type_url)
-
- return response_type_url_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void Method::set_allocated_response_type_url(::std::string* response_type_url) {
- if (response_type_url != NULL) {
-
- } else {
-
- }
- response_type_url_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), response_type_url);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.Method.response_type_url)
-}
-
-// bool response_streaming = 5;
-void Method::clear_response_streaming() {
- response_streaming_ = false;
-}
-bool Method::response_streaming() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Method.response_streaming)
- return response_streaming_;
-}
-void Method::set_response_streaming(bool value) {
-
- response_streaming_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.Method.response_streaming)
-}
-
-// repeated .google.protobuf.Option options = 6;
-int Method::options_size() const {
- return options_.size();
-}
-void Method::clear_options() {
- options_.Clear();
-}
-const ::google::protobuf::Option& Method::options(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.Method.options)
- return options_.Get(index);
-}
-::google::protobuf::Option* Method::mutable_options(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.Method.options)
- return options_.Mutable(index);
-}
-::google::protobuf::Option* Method::add_options() {
- // @@protoc_insertion_point(field_add:google.protobuf.Method.options)
- return options_.Add();
-}
-::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >*
-Method::mutable_options() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.Method.options)
- return &options_;
-}
-const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >&
-Method::options() const {
- // @@protoc_insertion_point(field_list:google.protobuf.Method.options)
- return options_;
+ protobuf_google_2fprotobuf_2fapi_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fapi_2eproto::file_level_metadata[kIndexInFileMessages];
}
-// .google.protobuf.Syntax syntax = 7;
-void Method::clear_syntax() {
- syntax_ = 0;
-}
-::google::protobuf::Syntax Method::syntax() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Method.syntax)
- return static_cast< ::google::protobuf::Syntax >(syntax_);
-}
-void Method::set_syntax(::google::protobuf::Syntax value) {
-
- syntax_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.Method.syntax)
-}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
+void Mixin::InitAsDefaultInstance() {
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Mixin::kNameFieldNumber;
const int Mixin::kRootFieldNumber;
@@ -1611,7 +1300,7 @@ const int Mixin::kRootFieldNumber;
Mixin::Mixin()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fapi_2eproto();
+ ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMixin();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Mixin)
@@ -1654,12 +1343,12 @@ void Mixin::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* Mixin::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[2].descriptor;
+ ::protobuf_google_2fprotobuf_2fapi_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fapi_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const Mixin& Mixin::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fapi_2eproto();
+ ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMixin();
return *internal_default_instance();
}
@@ -1673,8 +1362,13 @@ Mixin* Mixin::New(::google::protobuf::Arena* arena) const {
void Mixin::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Mixin)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
root_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ _internal_metadata_.Clear();
}
bool Mixin::MergePartialFromCodedStream(
@@ -1689,11 +1383,12 @@ bool Mixin::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// string name = 1;
case 1: {
- if (tag == 10u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.protobuf.Mixin.name"));
} else {
@@ -1704,11 +1399,12 @@ bool Mixin::MergePartialFromCodedStream(
// string root = 2;
case 2: {
- if (tag == 18u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_root()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->root().data(), this->root().length(),
+ this->root().data(), static_cast<int>(this->root().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.protobuf.Mixin.root"));
} else {
@@ -1719,12 +1415,11 @@ bool Mixin::MergePartialFromCodedStream(
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
- DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
+ DO_(::google::protobuf::internal::WireFormat::SkipField(
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -1741,10 +1436,13 @@ failure:
void Mixin::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.Mixin)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// string name = 1;
if (this->name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Mixin.name");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -1754,13 +1452,17 @@ void Mixin::SerializeWithCachedSizes(
// string root = 2;
if (this->root().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->root().data(), this->root().length(),
+ this->root().data(), static_cast<int>(this->root().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Mixin.root");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
2, this->root(), output);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ }
// @@protoc_insertion_point(serialize_end:google.protobuf.Mixin)
}
@@ -1768,10 +1470,13 @@ void Mixin::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Mixin)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// string name = 1;
if (this->name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Mixin.name");
target =
@@ -1782,7 +1487,7 @@ void Mixin::SerializeWithCachedSizes(
// string root = 2;
if (this->root().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->root().data(), this->root().length(),
+ this->root().data(), static_cast<int>(this->root().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Mixin.root");
target =
@@ -1790,6 +1495,10 @@ void Mixin::SerializeWithCachedSizes(
2, this->root(), target);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ }
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Mixin)
return target;
}
@@ -1798,6 +1507,11 @@ size_t Mixin::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.Mixin)
size_t total_size = 0;
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ total_size +=
+ ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ }
// string name = 1;
if (this->name().size() > 0) {
total_size += 1 +
@@ -1838,6 +1552,9 @@ void Mixin::MergeFrom(const Mixin& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Mixin)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
if (from.name().size() > 0) {
name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_);
@@ -1871,111 +1588,20 @@ void Mixin::Swap(Mixin* other) {
InternalSwap(other);
}
void Mixin::InternalSwap(Mixin* other) {
+ using std::swap;
name_.Swap(&other->name_);
root_.Swap(&other->root_);
- std::swap(_cached_size_, other->_cached_size_);
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Mixin::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[2];
+ protobuf_google_2fprotobuf_2fapi_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fapi_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// Mixin
-
-// string name = 1;
-void Mixin::clear_name() {
- name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-const ::std::string& Mixin::name() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Mixin.name)
- return name_.GetNoArena();
-}
-void Mixin::set_name(const ::std::string& value) {
-
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.Mixin.name)
-}
-void Mixin::set_name(const char* value) {
-
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.Mixin.name)
-}
-void Mixin::set_name(const char* value, size_t size) {
-
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.Mixin.name)
-}
-::std::string* Mixin::mutable_name() {
-
- // @@protoc_insertion_point(field_mutable:google.protobuf.Mixin.name)
- return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* Mixin::release_name() {
- // @@protoc_insertion_point(field_release:google.protobuf.Mixin.name)
-
- return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void Mixin::set_allocated_name(::std::string* name) {
- if (name != NULL) {
-
- } else {
-
- }
- name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.Mixin.name)
-}
-
-// string root = 2;
-void Mixin::clear_root() {
- root_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-const ::std::string& Mixin::root() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Mixin.root)
- return root_.GetNoArena();
-}
-void Mixin::set_root(const ::std::string& value) {
-
- root_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.Mixin.root)
-}
-void Mixin::set_root(const char* value) {
-
- root_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.Mixin.root)
-}
-void Mixin::set_root(const char* value, size_t size) {
-
- root_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.Mixin.root)
-}
-::std::string* Mixin::mutable_root() {
-
- // @@protoc_insertion_point(field_mutable:google.protobuf.Mixin.root)
- return root_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* Mixin::release_root() {
- // @@protoc_insertion_point(field_release:google.protobuf.Mixin.root)
-
- return root_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void Mixin::set_allocated_root(::std::string* root) {
- if (root != NULL) {
-
- } else {
-
- }
- root_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), root);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.Mixin.root)
-}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
-
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/api.pb.h b/src/google/protobuf/api.pb.h
index f4699a5c..e74528e1 100644
--- a/src/google/protobuf/api.pb.h
+++ b/src/google/protobuf/api.pb.h
@@ -8,19 +8,21 @@
#include <google/protobuf/stubs/common.h>
-#if GOOGLE_PROTOBUF_VERSION < 3001000
+#if GOOGLE_PROTOBUF_VERSION < 3004000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3001000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3004000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
+#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
+#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
@@ -30,45 +32,46 @@
#include <google/protobuf/source_context.pb.h>
#include <google/protobuf/type.pb.h>
// @@protoc_insertion_point(includes)
+
+namespace protobuf_google_2fprotobuf_2fapi_2eproto {
+// Internal implementation detail -- do not use these members.
+struct LIBPROTOBUF_EXPORT TableStruct {
+ static const ::google::protobuf::internal::ParseTableField entries[];
+ static const ::google::protobuf::internal::AuxillaryParseTableField aux[];
+ static const ::google::protobuf::internal::ParseTable schema[3];
+ static const ::google::protobuf::internal::FieldMetadata field_metadata[];
+ static const ::google::protobuf::internal::SerializationTable serialization_table[];
+ static const ::google::protobuf::uint32 offsets[];
+};
+void LIBPROTOBUF_EXPORT AddDescriptors();
+void LIBPROTOBUF_EXPORT InitDefaultsApiImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsApi();
+void LIBPROTOBUF_EXPORT InitDefaultsMethodImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsMethod();
+void LIBPROTOBUF_EXPORT InitDefaultsMixinImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsMixin();
+inline void LIBPROTOBUF_EXPORT InitDefaults() {
+ InitDefaultsApi();
+ InitDefaultsMethod();
+ InitDefaultsMixin();
+}
+} // namespace protobuf_google_2fprotobuf_2fapi_2eproto
namespace google {
namespace protobuf {
class Api;
class ApiDefaultTypeInternal;
LIBPROTOBUF_EXPORT extern ApiDefaultTypeInternal _Api_default_instance_;
-class Enum;
-class EnumDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern EnumDefaultTypeInternal _Enum_default_instance_;
-class EnumValue;
-class EnumValueDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern EnumValueDefaultTypeInternal _EnumValue_default_instance_;
-class Field;
-class FieldDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern FieldDefaultTypeInternal _Field_default_instance_;
class Method;
class MethodDefaultTypeInternal;
LIBPROTOBUF_EXPORT extern MethodDefaultTypeInternal _Method_default_instance_;
class Mixin;
class MixinDefaultTypeInternal;
LIBPROTOBUF_EXPORT extern MixinDefaultTypeInternal _Mixin_default_instance_;
-class Option;
-class OptionDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern OptionDefaultTypeInternal _Option_default_instance_;
-class SourceContext;
-class SourceContextDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern SourceContextDefaultTypeInternal _SourceContext_default_instance_;
-class Type;
-class TypeDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern TypeDefaultTypeInternal _Type_default_instance_;
} // namespace protobuf
} // namespace google
-
namespace google {
namespace protobuf {
-// Internal implementation detail -- do not call these.
-void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fapi_2eproto();
-void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fapi_2eproto();
-
// ===================================================================
class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Api) */ {
@@ -82,16 +85,36 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ Api(Api&& from) noexcept
+ : Api() {
+ *this = ::std::move(from);
+ }
+ inline Api& operator=(Api&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
static const ::google::protobuf::Descriptor* descriptor();
static const Api& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const Api* internal_default_instance() {
return reinterpret_cast<const Api*>(
&_Api_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 0;
void Swap(Api* other);
+ friend void swap(Api& a, Api& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -112,10 +135,6 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
@@ -137,17 +156,6 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in
// accessors -------------------------------------------------------
- // string name = 1;
- void clear_name();
- static const int kNameFieldNumber = 1;
- const ::std::string& name() const;
- void set_name(const ::std::string& value);
- void set_name(const char* value);
- void set_name(const char* value, size_t size);
- ::std::string* mutable_name();
- ::std::string* release_name();
- void set_allocated_name(::std::string* name);
-
// repeated .google.protobuf.Method methods = 2;
int methods_size() const;
void clear_methods();
@@ -172,11 +180,40 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >&
options() const;
+ // repeated .google.protobuf.Mixin mixins = 6;
+ int mixins_size() const;
+ void clear_mixins();
+ static const int kMixinsFieldNumber = 6;
+ const ::google::protobuf::Mixin& mixins(int index) const;
+ ::google::protobuf::Mixin* mutable_mixins(int index);
+ ::google::protobuf::Mixin* add_mixins();
+ ::google::protobuf::RepeatedPtrField< ::google::protobuf::Mixin >*
+ mutable_mixins();
+ const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Mixin >&
+ mixins() const;
+
+ // string name = 1;
+ void clear_name();
+ static const int kNameFieldNumber = 1;
+ const ::std::string& name() const;
+ void set_name(const ::std::string& value);
+ #if LANG_CXX11
+ void set_name(::std::string&& value);
+ #endif
+ void set_name(const char* value);
+ void set_name(const char* value, size_t size);
+ ::std::string* mutable_name();
+ ::std::string* release_name();
+ void set_allocated_name(::std::string* name);
+
// string version = 4;
void clear_version();
static const int kVersionFieldNumber = 4;
const ::std::string& version() const;
void set_version(const ::std::string& value);
+ #if LANG_CXX11
+ void set_version(::std::string&& value);
+ #endif
void set_version(const char* value);
void set_version(const char* value, size_t size);
::std::string* mutable_version();
@@ -188,22 +225,10 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in
void clear_source_context();
static const int kSourceContextFieldNumber = 5;
const ::google::protobuf::SourceContext& source_context() const;
- ::google::protobuf::SourceContext* mutable_source_context();
::google::protobuf::SourceContext* release_source_context();
+ ::google::protobuf::SourceContext* mutable_source_context();
void set_allocated_source_context(::google::protobuf::SourceContext* source_context);
- // repeated .google.protobuf.Mixin mixins = 6;
- int mixins_size() const;
- void clear_mixins();
- static const int kMixinsFieldNumber = 6;
- const ::google::protobuf::Mixin& mixins(int index) const;
- ::google::protobuf::Mixin* mutable_mixins(int index);
- ::google::protobuf::Mixin* add_mixins();
- ::google::protobuf::RepeatedPtrField< ::google::protobuf::Mixin >*
- mutable_mixins();
- const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Mixin >&
- mixins() const;
-
// .google.protobuf.Syntax syntax = 7;
void clear_syntax();
static const int kSyntaxFieldNumber = 7;
@@ -222,11 +247,8 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in
::google::protobuf::SourceContext* source_context_;
int syntax_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fapi_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fapi_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fapi_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fapi_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fapi_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsApiImpl();
};
// -------------------------------------------------------------------
@@ -241,16 +263,36 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ Method(Method&& from) noexcept
+ : Method() {
+ *this = ::std::move(from);
+ }
+ inline Method& operator=(Method&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
static const ::google::protobuf::Descriptor* descriptor();
static const Method& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const Method* internal_default_instance() {
return reinterpret_cast<const Method*>(
&_Method_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 1;
void Swap(Method* other);
+ friend void swap(Method& a, Method& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -271,10 +313,6 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
@@ -296,11 +334,26 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc
// accessors -------------------------------------------------------
+ // repeated .google.protobuf.Option options = 6;
+ int options_size() const;
+ void clear_options();
+ static const int kOptionsFieldNumber = 6;
+ const ::google::protobuf::Option& options(int index) const;
+ ::google::protobuf::Option* mutable_options(int index);
+ ::google::protobuf::Option* add_options();
+ ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >*
+ mutable_options();
+ const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >&
+ options() const;
+
// string name = 1;
void clear_name();
static const int kNameFieldNumber = 1;
const ::std::string& name() const;
void set_name(const ::std::string& value);
+ #if LANG_CXX11
+ void set_name(::std::string&& value);
+ #endif
void set_name(const char* value);
void set_name(const char* value, size_t size);
::std::string* mutable_name();
@@ -312,47 +365,41 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc
static const int kRequestTypeUrlFieldNumber = 2;
const ::std::string& request_type_url() const;
void set_request_type_url(const ::std::string& value);
+ #if LANG_CXX11
+ void set_request_type_url(::std::string&& value);
+ #endif
void set_request_type_url(const char* value);
void set_request_type_url(const char* value, size_t size);
::std::string* mutable_request_type_url();
::std::string* release_request_type_url();
void set_allocated_request_type_url(::std::string* request_type_url);
- // bool request_streaming = 3;
- void clear_request_streaming();
- static const int kRequestStreamingFieldNumber = 3;
- bool request_streaming() const;
- void set_request_streaming(bool value);
-
// string response_type_url = 4;
void clear_response_type_url();
static const int kResponseTypeUrlFieldNumber = 4;
const ::std::string& response_type_url() const;
void set_response_type_url(const ::std::string& value);
+ #if LANG_CXX11
+ void set_response_type_url(::std::string&& value);
+ #endif
void set_response_type_url(const char* value);
void set_response_type_url(const char* value, size_t size);
::std::string* mutable_response_type_url();
::std::string* release_response_type_url();
void set_allocated_response_type_url(::std::string* response_type_url);
+ // bool request_streaming = 3;
+ void clear_request_streaming();
+ static const int kRequestStreamingFieldNumber = 3;
+ bool request_streaming() const;
+ void set_request_streaming(bool value);
+
// bool response_streaming = 5;
void clear_response_streaming();
static const int kResponseStreamingFieldNumber = 5;
bool response_streaming() const;
void set_response_streaming(bool value);
- // repeated .google.protobuf.Option options = 6;
- int options_size() const;
- void clear_options();
- static const int kOptionsFieldNumber = 6;
- const ::google::protobuf::Option& options(int index) const;
- ::google::protobuf::Option* mutable_options(int index);
- ::google::protobuf::Option* add_options();
- ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >*
- mutable_options();
- const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >&
- options() const;
-
// .google.protobuf.Syntax syntax = 7;
void clear_syntax();
static const int kSyntaxFieldNumber = 7;
@@ -371,11 +418,8 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc
bool response_streaming_;
int syntax_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fapi_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fapi_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fapi_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fapi_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fapi_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMethodImpl();
};
// -------------------------------------------------------------------
@@ -390,16 +434,36 @@ class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ Mixin(Mixin&& from) noexcept
+ : Mixin() {
+ *this = ::std::move(from);
+ }
+ inline Mixin& operator=(Mixin&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
static const ::google::protobuf::Descriptor* descriptor();
static const Mixin& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const Mixin* internal_default_instance() {
return reinterpret_cast<const Mixin*>(
&_Mixin_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 2;
void Swap(Mixin* other);
+ friend void swap(Mixin& a, Mixin& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -420,10 +484,6 @@ class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
@@ -450,6 +510,9 @@ class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_
static const int kNameFieldNumber = 1;
const ::std::string& name() const;
void set_name(const ::std::string& value);
+ #if LANG_CXX11
+ void set_name(::std::string&& value);
+ #endif
void set_name(const char* value);
void set_name(const char* value, size_t size);
::std::string* mutable_name();
@@ -461,6 +524,9 @@ class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_
static const int kRootFieldNumber = 2;
const ::std::string& root() const;
void set_root(const ::std::string& value);
+ #if LANG_CXX11
+ void set_root(::std::string&& value);
+ #endif
void set_root(const char* value);
void set_root(const char* value, size_t size);
::std::string* mutable_root();
@@ -474,18 +540,18 @@ class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_
::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::internal::ArenaStringPtr root_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fapi_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fapi_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fapi_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fapi_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fapi_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMixinImpl();
};
// ===================================================================
// ===================================================================
-#if !PROTOBUF_INLINE_NOT_IN_HEADERS
+#ifdef __GNUC__
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wstrict-aliasing"
+#endif // __GNUC__
// Api
// string name = 1;
@@ -501,7 +567,16 @@ inline void Api::set_name(const ::std::string& value) {
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.Api.name)
}
+#if LANG_CXX11
+inline void Api::set_name(::std::string&& value) {
+
+ name_.SetNoArena(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.Api.name)
+}
+#endif
inline void Api::set_name(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.Api.name)
@@ -566,9 +641,6 @@ Api::methods() const {
inline int Api::options_size() const {
return options_.size();
}
-inline void Api::clear_options() {
- options_.Clear();
-}
inline const ::google::protobuf::Option& Api::options(int index) const {
// @@protoc_insertion_point(field_get:google.protobuf.Api.options)
return options_.Get(index);
@@ -605,7 +677,16 @@ inline void Api::set_version(const ::std::string& value) {
version_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.Api.version)
}
+#if LANG_CXX11
+inline void Api::set_version(::std::string&& value) {
+
+ version_.SetNoArena(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.Api.version)
+}
+#endif
inline void Api::set_version(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
version_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.Api.version)
@@ -640,14 +721,18 @@ inline void Api::set_allocated_version(::std::string* version) {
inline bool Api::has_source_context() const {
return this != internal_default_instance() && source_context_ != NULL;
}
-inline void Api::clear_source_context() {
- if (GetArenaNoVirtual() == NULL && source_context_ != NULL) delete source_context_;
- source_context_ = NULL;
-}
inline const ::google::protobuf::SourceContext& Api::source_context() const {
+ const ::google::protobuf::SourceContext* p = source_context_;
// @@protoc_insertion_point(field_get:google.protobuf.Api.source_context)
- return source_context_ != NULL ? *source_context_
- : *::google::protobuf::SourceContext::internal_default_instance();
+ return p != NULL ? *p : *reinterpret_cast<const ::google::protobuf::SourceContext*>(
+ &::google::protobuf::_SourceContext_default_instance_);
+}
+inline ::google::protobuf::SourceContext* Api::release_source_context() {
+ // @@protoc_insertion_point(field_release:google.protobuf.Api.source_context)
+
+ ::google::protobuf::SourceContext* temp = source_context_;
+ source_context_ = NULL;
+ return temp;
}
inline ::google::protobuf::SourceContext* Api::mutable_source_context() {
@@ -657,21 +742,22 @@ inline ::google::protobuf::SourceContext* Api::mutable_source_context() {
// @@protoc_insertion_point(field_mutable:google.protobuf.Api.source_context)
return source_context_;
}
-inline ::google::protobuf::SourceContext* Api::release_source_context() {
- // @@protoc_insertion_point(field_release:google.protobuf.Api.source_context)
-
- ::google::protobuf::SourceContext* temp = source_context_;
- source_context_ = NULL;
- return temp;
-}
inline void Api::set_allocated_source_context(::google::protobuf::SourceContext* source_context) {
- delete source_context_;
- source_context_ = source_context;
+ ::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
+ if (message_arena == NULL) {
+ delete reinterpret_cast< ::google::protobuf::MessageLite*>(source_context_);
+ }
if (source_context) {
+ ::google::protobuf::Arena* submessage_arena = NULL;
+ if (message_arena != submessage_arena) {
+ source_context = ::google::protobuf::internal::GetOwnedMessage(
+ message_arena, source_context, submessage_arena);
+ }
} else {
}
+ source_context_ = source_context;
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Api.source_context)
}
@@ -736,7 +822,16 @@ inline void Method::set_name(const ::std::string& value) {
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.Method.name)
}
+#if LANG_CXX11
+inline void Method::set_name(::std::string&& value) {
+
+ name_.SetNoArena(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.Method.name)
+}
+#endif
inline void Method::set_name(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.Method.name)
@@ -780,7 +875,16 @@ inline void Method::set_request_type_url(const ::std::string& value) {
request_type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.Method.request_type_url)
}
+#if LANG_CXX11
+inline void Method::set_request_type_url(::std::string&& value) {
+
+ request_type_url_.SetNoArena(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.Method.request_type_url)
+}
+#endif
inline void Method::set_request_type_url(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
request_type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.Method.request_type_url)
@@ -838,7 +942,16 @@ inline void Method::set_response_type_url(const ::std::string& value) {
response_type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.Method.response_type_url)
}
+#if LANG_CXX11
+inline void Method::set_response_type_url(::std::string&& value) {
+
+ response_type_url_.SetNoArena(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.Method.response_type_url)
+}
+#endif
inline void Method::set_response_type_url(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
response_type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.Method.response_type_url)
@@ -887,9 +1000,6 @@ inline void Method::set_response_streaming(bool value) {
inline int Method::options_size() const {
return options_.size();
}
-inline void Method::clear_options() {
- options_.Clear();
-}
inline const ::google::protobuf::Option& Method::options(int index) const {
// @@protoc_insertion_point(field_get:google.protobuf.Method.options)
return options_.Get(index);
@@ -944,7 +1054,16 @@ inline void Mixin::set_name(const ::std::string& value) {
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.Mixin.name)
}
+#if LANG_CXX11
+inline void Mixin::set_name(::std::string&& value) {
+
+ name_.SetNoArena(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.Mixin.name)
+}
+#endif
inline void Mixin::set_name(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.Mixin.name)
@@ -988,7 +1107,16 @@ inline void Mixin::set_root(const ::std::string& value) {
root_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.Mixin.root)
}
+#if LANG_CXX11
+inline void Mixin::set_root(::std::string&& value) {
+
+ root_.SetNoArena(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.Mixin.root)
+}
+#endif
inline void Mixin::set_root(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
root_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.Mixin.root)
@@ -1019,7 +1147,9 @@ inline void Mixin::set_allocated_root(::std::string* root) {
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Mixin.root)
}
-#endif // !PROTOBUF_INLINE_NOT_IN_HEADERS
+#ifdef __GNUC__
+ #pragma GCC diagnostic pop
+#endif // __GNUC__
// -------------------------------------------------------------------
// -------------------------------------------------------------------
@@ -1027,7 +1157,6 @@ inline void Mixin::set_allocated_root(::std::string* root) {
// @@protoc_insertion_point(namespace_scope)
-
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/api.proto b/src/google/protobuf/api.proto
index 7c30e8b7..f37ee2fa 100644
--- a/src/google/protobuf/api.proto
+++ b/src/google/protobuf/api.proto
@@ -42,26 +42,33 @@ option java_multiple_files = true;
option objc_class_prefix = "GPB";
option go_package = "google.golang.org/genproto/protobuf/api;api";
-// Api is a light-weight descriptor for a protocol buffer service.
+// Api is a light-weight descriptor for an API Interface.
+//
+// Interfaces are also described as "protocol buffer services" in some contexts,
+// such as by the "service" keyword in a .proto file, but they are different
+// from API Services, which represent a concrete implementation of an interface
+// as opposed to simply a description of methods and bindings. They are also
+// sometimes simply referred to as "APIs" in other contexts, such as the name of
+// this message itself. See https://cloud.google.com/apis/design/glossary for
+// detailed terminology.
message Api {
- // The fully qualified name of this api, including package name
- // followed by the api's simple name.
+ // The fully qualified name of this interface, including package name
+ // followed by the interface's simple name.
string name = 1;
- // The methods of this api, in unspecified order.
+ // The methods of this interface, in unspecified order.
repeated Method methods = 2;
- // Any metadata attached to the API.
+ // Any metadata attached to the interface.
repeated Option options = 3;
- // A version string for this api. If specified, must have the form
- // `major-version.minor-version`, as in `1.10`. If the minor version
- // is omitted, it defaults to zero. If the entire version field is
- // empty, the major version is derived from the package name, as
- // outlined below. If the field is not empty, the version in the
- // package name will be verified to be consistent with what is
- // provided here.
+ // A version string for this interface. If specified, must have the form
+ // `major-version.minor-version`, as in `1.10`. If the minor version is
+ // omitted, it defaults to zero. If the entire version field is empty, the
+ // major version is derived from the package name, as outlined below. If the
+ // field is not empty, the version in the package name will be verified to be
+ // consistent with what is provided here.
//
// The versioning schema uses [semantic
// versioning](http://semver.org) where the major version number
@@ -71,10 +78,10 @@ message Api {
// chosen based on the product plan.
//
// The major version is also reflected in the package name of the
- // API, which must end in `v<major-version>`, as in
+ // interface, which must end in `v<major-version>`, as in
// `google.feature.v1`. For major versions 0 and 1, the suffix can
// be omitted. Zero major versions must only be used for
- // experimental, none-GA apis.
+ // experimental, non-GA interfaces.
//
//
string version = 4;
@@ -83,14 +90,14 @@ message Api {
// message.
SourceContext source_context = 5;
- // Included APIs. See [Mixin][].
+ // Included interfaces. See [Mixin][].
repeated Mixin mixins = 6;
// The source syntax of the service.
Syntax syntax = 7;
}
-// Method represents a method of an api.
+// Method represents a method of an API interface.
message Method {
// The simple name of this method.
@@ -115,9 +122,9 @@ message Method {
Syntax syntax = 7;
}
-// Declares an API to be included in this API. The including API must
-// redeclare all the methods from the included API, but documentation
-// and options are inherited as follows:
+// Declares an API Interface to be included in this interface. The including
+// interface must redeclare all the methods from the included interface, but
+// documentation and options are inherited as follows:
//
// - If after comment and whitespace stripping, the documentation
// string of the redeclared method is empty, it will be inherited
@@ -129,7 +136,8 @@ message Method {
//
// - If an http annotation is inherited, the path pattern will be
// modified as follows. Any version prefix will be replaced by the
-// version of the including API plus the [root][] path if specified.
+// version of the including interface plus the [root][] path if
+// specified.
//
// Example of a simple mixin:
//
@@ -193,7 +201,7 @@ message Method {
// ...
// }
message Mixin {
- // The fully qualified name of the API which is included.
+ // The fully qualified name of the interface which is included.
string name = 1;
// If non-empty specifies a path under which inherited HTTP paths
diff --git a/src/google/protobuf/arena.cc b/src/google/protobuf/arena.cc
index 21fd1be6..e9289988 100755
--- a/src/google/protobuf/arena.cc
+++ b/src/google/protobuf/arena.cc
@@ -38,169 +38,187 @@
#include <sanitizer/asan_interface.h>
#endif // ADDRESS_SANITIZER
+#include <google/protobuf/stubs/port.h>
+
namespace google {
+static const size_t kMinCleanupListElements = 8;
+static const size_t kMaxCleanupListElements = 64; // 1kB on 64-bit.
+
namespace protobuf {
+namespace internal {
-google::protobuf::internal::SequenceNumber Arena::lifecycle_id_generator_;
+google::protobuf::internal::SequenceNumber ArenaImpl::lifecycle_id_generator_;
#if defined(GOOGLE_PROTOBUF_NO_THREADLOCAL)
-Arena::ThreadCache& Arena::thread_cache() {
+ArenaImpl::ThreadCache& ArenaImpl::thread_cache() {
static internal::ThreadLocalStorage<ThreadCache>* thread_cache_ =
new internal::ThreadLocalStorage<ThreadCache>();
return *thread_cache_->Get();
}
#elif defined(PROTOBUF_USE_DLLS)
-Arena::ThreadCache& Arena::thread_cache() {
+ArenaImpl::ThreadCache& ArenaImpl::thread_cache() {
static GOOGLE_THREAD_LOCAL ThreadCache thread_cache_ = { -1, NULL };
return thread_cache_;
}
#else
-GOOGLE_THREAD_LOCAL Arena::ThreadCache Arena::thread_cache_ = { -1, NULL };
+GOOGLE_THREAD_LOCAL ArenaImpl::ThreadCache ArenaImpl::thread_cache_ = {-1, NULL};
#endif
-void Arena::Init() {
+void ArenaImpl::Init() {
lifecycle_id_ = lifecycle_id_generator_.GetNext();
- blocks_ = 0;
- hint_ = 0;
- owns_first_block_ = true;
- cleanup_list_ = 0;
-
- if (options_.initial_block != NULL && options_.initial_block_size > 0) {
- GOOGLE_CHECK_GE(options_.initial_block_size, sizeof(Block))
- << ": Initial block size too small for header.";
-
- // Add first unowned block to list.
- Block* first_block = reinterpret_cast<Block*>(options_.initial_block);
- first_block->size = options_.initial_block_size;
- first_block->pos = kHeaderSize;
- first_block->next = NULL;
- // Thread which calls Init() owns the first block. This allows the
- // single-threaded case to allocate on the first block without taking any
- // locks.
- first_block->owner = &thread_cache();
- SetThreadCacheBlock(first_block);
- AddBlockInternal(first_block);
- owns_first_block_ = false;
- }
+ google::protobuf::internal::NoBarrier_Store(&hint_, 0);
+ google::protobuf::internal::NoBarrier_Store(&threads_, 0);
- // Call the initialization hook
- if (options_.on_arena_init != NULL) {
- hooks_cookie_ = options_.on_arena_init(this);
+ if (initial_block_) {
+ // Thread which calls Init() owns the first block. This allows the
+ // single-threaded case to allocate on the first block without having to
+ // perform atomic operations.
+ InitBlock(initial_block_, &thread_cache(), options_.initial_block_size);
+ ThreadInfo* info = NewThreadInfo(initial_block_);
+ info->next = NULL;
+ google::protobuf::internal::NoBarrier_Store(&threads_,
+ reinterpret_cast<google::protobuf::internal::AtomicWord>(info));
+ google::protobuf::internal::NoBarrier_Store(&space_allocated_,
+ options_.initial_block_size);
+ CacheBlock(initial_block_);
} else {
- hooks_cookie_ = NULL;
- }
-}
-
-Arena::~Arena() {
- uint64 space_allocated = ResetInternal();
-
- // Call the destruction hook
- if (options_.on_arena_destruction != NULL) {
- options_.on_arena_destruction(this, hooks_cookie_, space_allocated);
+ google::protobuf::internal::NoBarrier_Store(&space_allocated_, 0);
}
}
-uint64 Arena::Reset() {
- // Invalidate any ThreadCaches pointing to any blocks we just destroyed.
- lifecycle_id_ = lifecycle_id_generator_.GetNext();
- return ResetInternal();
+ArenaImpl::~ArenaImpl() {
+ // Have to do this in a first pass, because some of the destructors might
+ // refer to memory in other blocks.
+ CleanupList();
+ FreeBlocks();
}
-uint64 Arena::ResetInternal() {
+uint64 ArenaImpl::Reset() {
+ // Have to do this in a first pass, because some of the destructors might
+ // refer to memory in other blocks.
CleanupList();
uint64 space_allocated = FreeBlocks();
-
- // Call the reset hook
- if (options_.on_arena_reset != NULL) {
- options_.on_arena_reset(this, hooks_cookie_, space_allocated);
- }
+ Init();
return space_allocated;
}
-Arena::Block* Arena::NewBlock(void* me, Block* my_last_block, size_t n,
- size_t start_block_size, size_t max_block_size) {
+ArenaImpl::Block* ArenaImpl::NewBlock(void* me, Block* my_last_block,
+ size_t min_bytes) {
size_t size;
if (my_last_block != NULL) {
// Double the current block size, up to a limit.
- size = 2 * (my_last_block->size);
- if (size > max_block_size) size = max_block_size;
+ size = std::min(2 * my_last_block->size, options_.max_block_size);
} else {
- size = start_block_size;
+ size = options_.start_block_size;
}
- // Verify that n + kHeaderSize won't overflow.
- GOOGLE_CHECK_LE(n, std::numeric_limits<size_t>::max() - kHeaderSize);
- size = std::max(size, kHeaderSize + n);
+ // Verify that min_bytes + kHeaderSize won't overflow.
+ GOOGLE_CHECK_LE(min_bytes, std::numeric_limits<size_t>::max() - kHeaderSize);
+ size = std::max(size, kHeaderSize + min_bytes);
Block* b = reinterpret_cast<Block*>(options_.block_alloc(size));
- b->pos = kHeaderSize + n;
+ InitBlock(b, me, size);
+ google::protobuf::internal::NoBarrier_AtomicIncrement(&space_allocated_, size);
+ return b;
+}
+
+void ArenaImpl::InitBlock(Block* b, void *me, size_t size) {
+ b->pos = kHeaderSize;
b->size = size;
b->owner = me;
+ b->next = NULL;
#ifdef ADDRESS_SANITIZER
// Poison the rest of the block for ASAN. It was unpoisoned by the underlying
// malloc but it's not yet usable until we return it as part of an allocation.
ASAN_POISON_MEMORY_REGION(
reinterpret_cast<char*>(b) + b->pos, b->size - b->pos);
#endif // ADDRESS_SANITIZER
- return b;
}
-void Arena::AddBlock(Block* b) {
- MutexLock l(&blocks_lock_);
- AddBlockInternal(b);
+ArenaImpl::CleanupChunk* ArenaImpl::ExpandCleanupList(CleanupChunk* cleanup,
+ Block* b) {
+ size_t size = cleanup ? cleanup->size * 2 : kMinCleanupListElements;
+ size = std::min(size, kMaxCleanupListElements);
+ size_t bytes = internal::AlignUpTo8(CleanupChunk::SizeOf(size));
+ if (b->avail() < bytes) {
+ b = GetBlock(bytes);
+ }
+ CleanupChunk* list =
+ reinterpret_cast<CleanupChunk*>(AllocFromBlock(b, bytes));
+ list->next = b->thread_info->cleanup;
+ list->size = size;
+ list->len = 0;
+ b->thread_info->cleanup = list;
+ return list;
}
-void Arena::AddBlockInternal(Block* b) {
- b->next = reinterpret_cast<Block*>(google::protobuf::internal::NoBarrier_Load(&blocks_));
- google::protobuf::internal::Release_Store(&blocks_, reinterpret_cast<google::protobuf::internal::AtomicWord>(b));
- if (b->avail() != 0) {
- // Direct future allocations to this block.
- google::protobuf::internal::Release_Store(&hint_, reinterpret_cast<google::protobuf::internal::AtomicWord>(b));
+inline GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+void ArenaImpl::AddCleanupInBlock(
+ Block* b, void* elem, void (*func)(void*)) {
+ CleanupChunk* cleanup = b->thread_info->cleanup;
+ if (cleanup == NULL || cleanup->len == cleanup->size) {
+ cleanup = ExpandCleanupList(cleanup, b);
}
-}
-void Arena::AddListNode(void* elem, void (*cleanup)(void*)) {
- Node* node = reinterpret_cast<Node*>(AllocateAligned(sizeof(Node)));
+ CleanupNode* node = &cleanup->nodes[cleanup->len++];
+
node->elem = elem;
- node->cleanup = cleanup;
- node->next = reinterpret_cast<Node*>(
- google::protobuf::internal::NoBarrier_AtomicExchange(&cleanup_list_,
- reinterpret_cast<google::protobuf::internal::AtomicWord>(node)));
+ node->cleanup = func;
}
-void* Arena::AllocateAligned(const std::type_info* allocated, size_t n) {
- // Align n to next multiple of 8 (from Hacker's Delight, Chapter 3.)
- n = (n + 7) & -8;
+void ArenaImpl::AddCleanup(void* elem, void (*cleanup)(void*)) {
+ return AddCleanupInBlock(GetBlock(0), elem, cleanup);
+}
- // Monitor allocation if needed.
- if (GOOGLE_PREDICT_FALSE(hooks_cookie_ != NULL) &&
- options_.on_arena_allocation != NULL) {
- options_.on_arena_allocation(allocated, n, hooks_cookie_);
- }
+void* ArenaImpl::AllocateAligned(size_t n) {
+ GOOGLE_DCHECK_EQ(internal::AlignUpTo8(n), n); // Must be already aligned.
+
+ return AllocFromBlock(GetBlock(n), n);
+}
+
+void* ArenaImpl::AllocateAlignedAndAddCleanup(size_t n,
+ void (*cleanup)(void*)) {
+ GOOGLE_DCHECK_EQ(internal::AlignUpTo8(n), n); // Must be already aligned.
+
+ Block* b = GetBlock(n);
+ void* mem = AllocFromBlock(b, n);
+ AddCleanupInBlock(b, mem, cleanup);
+ return mem;
+}
+
+inline GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+ArenaImpl::Block* ArenaImpl::GetBlock(size_t n) {
+ Block* my_block = NULL;
// If this thread already owns a block in this arena then try to use that.
// This fast path optimizes the case where multiple threads allocate from the
// same arena.
- if (thread_cache().last_lifecycle_id_seen == lifecycle_id_ &&
- thread_cache().last_block_used_ != NULL) {
- if (thread_cache().last_block_used_->avail() < n) {
- return SlowAlloc(n);
+ ThreadCache* tc = &thread_cache();
+ if (tc->last_lifecycle_id_seen == lifecycle_id_) {
+ my_block = tc->last_block_used_;
+ if (my_block->avail() >= n) {
+ return my_block;
}
- return AllocFromBlock(thread_cache().last_block_used_, n);
}
// Check whether we own the last accessed block on this arena.
// This fast path optimizes the case where a single thread uses multiple
// arenas.
- void* me = &thread_cache();
Block* b = reinterpret_cast<Block*>(google::protobuf::internal::Acquire_Load(&hint_));
- if (!b || b->owner != me || b->avail() < n) {
- return SlowAlloc(n);
+ if (b != NULL && b->owner == tc) {
+ my_block = b;
+ if (my_block->avail() >= n) {
+ return my_block;
+ }
}
- return AllocFromBlock(b, n);
+ return GetBlockSlow(tc, my_block, n);
}
-void* Arena::AllocFromBlock(Block* b, size_t n) {
+inline GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+void* ArenaImpl::AllocFromBlock(Block* b, size_t n) {
+ GOOGLE_DCHECK_EQ(internal::AlignUpTo8(b->pos), b->pos); // Must be already aligned.
+ GOOGLE_DCHECK_EQ(internal::AlignUpTo8(n), n); // Must be already aligned.
+ GOOGLE_DCHECK_GE(b->avail(), n);
size_t p = b->pos;
b->pos = p + n;
#ifdef ADDRESS_SANITIZER
@@ -209,117 +227,158 @@ void* Arena::AllocFromBlock(Block* b, size_t n) {
return reinterpret_cast<char*>(b) + p;
}
-void* Arena::SlowAlloc(size_t n) {
- void* me = &thread_cache();
- Block* b = FindBlock(me); // Find block owned by me.
- // See if allocation fits in my latest block.
- if (b != NULL && b->avail() >= n) {
- SetThreadCacheBlock(b);
- google::protobuf::internal::NoBarrier_Store(&hint_, reinterpret_cast<google::protobuf::internal::AtomicWord>(b));
- return AllocFromBlock(b, n);
+ArenaImpl::Block* ArenaImpl::GetBlockSlow(void* me, Block* my_full_block,
+ size_t n) {
+ ThreadInfo* info =
+ my_full_block ? my_full_block->thread_info : GetThreadInfo(me, n);
+ GOOGLE_DCHECK(info != NULL);
+ Block* b = info->head;
+ if (b->avail() < n) {
+ Block* new_b = NewBlock(me, b, n);
+ new_b->thread_info = info;
+ new_b->next = b;
+ info->head = new_b;
+ b = new_b;
}
- b = NewBlock(me, b, n, options_.start_block_size, options_.max_block_size);
- AddBlock(b);
- SetThreadCacheBlock(b);
- return reinterpret_cast<char*>(b) + kHeaderSize;
+ CacheBlock(b);
+ return b;
}
-uint64 Arena::SpaceAllocated() const {
- uint64 space_allocated = 0;
- Block* b = reinterpret_cast<Block*>(google::protobuf::internal::NoBarrier_Load(&blocks_));
- while (b != NULL) {
- space_allocated += (b->size);
- b = b->next;
- }
- return space_allocated;
+uint64 ArenaImpl::SpaceAllocated() const {
+ return google::protobuf::internal::NoBarrier_Load(&space_allocated_);
}
-uint64 Arena::SpaceUsed() const {
+uint64 ArenaImpl::SpaceUsed() const {
+ ThreadInfo* info =
+ reinterpret_cast<ThreadInfo*>(google::protobuf::internal::Acquire_Load(&threads_));
uint64 space_used = 0;
- Block* b = reinterpret_cast<Block*>(google::protobuf::internal::NoBarrier_Load(&blocks_));
- while (b != NULL) {
- space_used += (b->pos - kHeaderSize);
- b = b->next;
- }
- return space_used;
-}
-
-std::pair<uint64, uint64> Arena::SpaceAllocatedAndUsed() const {
- uint64 allocated = 0;
- uint64 used = 0;
- Block* b = reinterpret_cast<Block*>(google::protobuf::internal::NoBarrier_Load(&blocks_));
- while (b != NULL) {
- allocated += b->size;
- used += (b->pos - kHeaderSize);
- b = b->next;
+ for ( ; info; info = info->next) {
+ // Remove the overhead of the ThreadInfo itself.
+ space_used -= sizeof(ThreadInfo);
+ for (Block* b = info->head; b; b = b->next) {
+ space_used += (b->pos - kHeaderSize);
+ }
}
- return std::make_pair(allocated, used);
+
+ return space_used;
}
-uint64 Arena::FreeBlocks() {
+uint64 ArenaImpl::FreeBlocks() {
uint64 space_allocated = 0;
- Block* b = reinterpret_cast<Block*>(google::protobuf::internal::NoBarrier_Load(&blocks_));
- Block* first_block = NULL;
- while (b != NULL) {
- space_allocated += (b->size);
- Block* next = b->next;
- if (next != NULL) {
+ // By omitting an Acquire barrier we ensure that any user code that doesn't
+ // properly synchronize Reset() or the destructor will throw a TSAN warning.
+ ThreadInfo* info =
+ reinterpret_cast<ThreadInfo*>(google::protobuf::internal::NoBarrier_Load(&threads_));
+
+ while (info) {
+ // This is inside the block we are freeing, so we need to read it now.
+ ThreadInfo* next_info = info->next;
+ for (Block* b = info->head; b; ) {
+ // This is inside the block we are freeing, so we need to read it now.
+ Block* next_block = b->next;
+ space_allocated += (b->size);
+
#ifdef ADDRESS_SANITIZER
// This memory was provided by the underlying allocator as unpoisoned, so
// return it in an unpoisoned state.
ASAN_UNPOISON_MEMORY_REGION(reinterpret_cast<char*>(b), b->size);
#endif // ADDRESS_SANITIZER
- options_.block_dealloc(b, b->size);
- } else {
- if (owns_first_block_) {
-#ifdef ADDRESS_SANITIZER
- // This memory was provided by the underlying allocator as unpoisoned,
- // so return it in an unpoisoned state.
- ASAN_UNPOISON_MEMORY_REGION(reinterpret_cast<char*>(b), b->size);
-#endif // ADDRESS_SANITIZER
+
+ if (b != initial_block_) {
options_.block_dealloc(b, b->size);
- } else {
- // User passed in the first block, skip free'ing the memory.
- first_block = b;
}
+
+ b = next_block;
}
- b = next;
- }
- blocks_ = 0;
- hint_ = 0;
- if (!owns_first_block_) {
- // Make the first block that was passed in through ArenaOptions
- // available for reuse.
- first_block->pos = kHeaderSize;
- // Thread which calls Reset() owns the first block. This allows the
- // single-threaded case to allocate on the first block without taking any
- // locks.
- first_block->owner = &thread_cache();
- SetThreadCacheBlock(first_block);
- AddBlockInternal(first_block);
+ info = next_info;
}
+
return space_allocated;
}
-void Arena::CleanupList() {
- Node* head =
- reinterpret_cast<Node*>(google::protobuf::internal::NoBarrier_Load(&cleanup_list_));
- while (head != NULL) {
- head->cleanup(head->elem);
- head = head->next;
+void ArenaImpl::CleanupList() {
+ // By omitting an Acquire barrier we ensure that any user code that doesn't
+ // properly synchronize Reset() or the destructor will throw a TSAN warning.
+ ThreadInfo* info =
+ reinterpret_cast<ThreadInfo*>(google::protobuf::internal::NoBarrier_Load(&threads_));
+
+ for ( ; info; info = info->next) {
+ CleanupChunk* list = info->cleanup;
+ while (list) {
+ size_t n = list->len;
+ CleanupNode* node = &list->nodes[list->len - 1];
+ for (size_t i = 0; i < n; i++, node--) {
+ node->cleanup(node->elem);
+ }
+ list = list->next;
+ }
}
- cleanup_list_ = 0;
}
-Arena::Block* Arena::FindBlock(void* me) {
- // TODO(sanjay): We might want to keep a separate list with one
- // entry per thread.
- Block* b = reinterpret_cast<Block*>(google::protobuf::internal::Acquire_Load(&blocks_));
- while (b != NULL && b->owner != me) {
- b = b->next;
+ArenaImpl::ThreadInfo* ArenaImpl::NewThreadInfo(Block* b) {
+ GOOGLE_DCHECK(FindThreadInfo(b->owner) == NULL);
+ ThreadInfo* info =
+ reinterpret_cast<ThreadInfo*>(AllocFromBlock(b, sizeof(ThreadInfo)));
+ b->thread_info = info;
+ info->owner = b->owner;
+ info->head = b;
+ info->cleanup = NULL;
+ return info;
+}
+
+ArenaImpl::ThreadInfo* ArenaImpl::FindThreadInfo(void* me) {
+ ThreadInfo* info =
+ reinterpret_cast<ThreadInfo*>(google::protobuf::internal::Acquire_Load(&threads_));
+ for ( ; info; info = info->next) {
+ if (info->owner == me) {
+ return info;
+ }
+ }
+
+ return NULL;
+}
+
+ArenaImpl::ThreadInfo* ArenaImpl::GetThreadInfo(void* me, size_t n) {
+ ThreadInfo* info = FindThreadInfo(me);
+
+ if (!info) {
+ // This thread doesn't have any ThreadInfo, which also means it doesn't have
+ // any blocks yet. So we'll allocate its first block now.
+ Block* b = NewBlock(me, NULL, sizeof(ThreadInfo) + n);
+ info = NewThreadInfo(b);
+
+ google::protobuf::internal::AtomicWord head;
+ do {
+ head = google::protobuf::internal::NoBarrier_Load(&threads_);
+ info->next = reinterpret_cast<ThreadInfo*>(head);
+ } while (google::protobuf::internal::Release_CompareAndSwap(
+ &threads_, head, reinterpret_cast<google::protobuf::internal::AtomicWord>(info)) != head);
+ }
+
+ return info;
+}
+
+} // namespace internal
+
+void Arena::CallDestructorHooks() {
+ uint64 space_allocated = impl_.SpaceAllocated();
+ // Call the reset hook
+ if (on_arena_reset_ != NULL) {
+ on_arena_reset_(this, hooks_cookie_, space_allocated);
+ }
+
+ // Call the destruction hook
+ if (on_arena_destruction_ != NULL) {
+ on_arena_destruction_(this, hooks_cookie_, space_allocated);
+ }
+}
+
+void Arena::OnArenaAllocation(const std::type_info* allocated_type,
+ size_t n) const {
+ if (on_arena_allocation_ != NULL) {
+ on_arena_allocation_(allocated_type, n, hooks_cookie_);
}
- return b;
}
} // namespace protobuf
diff --git a/src/google/protobuf/arena.h b/src/google/protobuf/arena.h
index 87066507..32be9a17 100644
--- a/src/google/protobuf/arena.h
+++ b/src/google/protobuf/arena.h
@@ -37,7 +37,7 @@
#ifdef max
#undef max // Visual Studio defines this macro
#endif
-#if __cplusplus >= 201103L
+#if LANG_CXX11
#include <google/protobuf/stubs/type_traits.h>
#endif
#if defined(_MSC_VER) && !_HAS_EXCEPTIONS
@@ -51,13 +51,8 @@ using type_info = ::type_info;
#include <typeinfo>
#endif
-#include <google/protobuf/stubs/atomic_sequence_num.h>
-#include <google/protobuf/stubs/atomicops.h>
-#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/stubs/logging.h>
-#include <google/protobuf/stubs/mutex.h>
-#include <google/protobuf/stubs/type_traits.h>
-
+#include <google/protobuf/arena_impl.h>
+#include <google/protobuf/stubs/port.h>
namespace google {
namespace protobuf {
@@ -66,7 +61,7 @@ class Arena; // defined below
class Message; // message.h
namespace internal {
-class ArenaString; // arenastring.h
+struct ArenaStringPtr; // arenastring.h
class LazyField; // lazy_field.h
template<typename Type>
@@ -122,7 +117,6 @@ struct ArenaOptions {
// from the arena. By default, it contains a ptr to a wrapper function that
// calls free.
void (*block_dealloc)(void*, size_t);
-
// Hooks for adding external functionality such as user-specific metrics
// collection, specific debugging abilities, etc.
// Init hook may return a pointer to a cookie to be stored in the arena.
@@ -225,21 +219,39 @@ class LIBPROTOBUF_EXPORT Arena {
public:
// Arena constructor taking custom options. See ArenaOptions below for
// descriptions of the options available.
- explicit Arena(const ArenaOptions& options) : options_(options) {
- Init();
+ explicit Arena(const ArenaOptions& options) : impl_(options) {
+ Init(options);
}
+ // Block overhead. Use this as a guide for how much to over-allocate the
+ // initial block if you want an allocation of size N to fit inside it.
+ //
+ // WARNING: if you allocate multiple objects, it is difficult to guarantee
+ // that a series of allocations will fit in the initial block, especially if
+ // Arena changes its alignment guarantees in the future!
+ static const size_t kBlockOverhead = internal::ArenaImpl::kHeaderSize;
+
// Default constructor with sensible default options, tuned for average
// use-cases.
- Arena() {
- Init();
+ Arena() : impl_(ArenaOptions()) { Init(ArenaOptions()); }
+
+ ~Arena() {
+ if (on_arena_reset_ != NULL || on_arena_destruction_ != NULL) {
+ CallDestructorHooks();
+ }
}
- // Destructor deletes all owned heap allocated objects, and destructs objects
- // that have non-trivial destructors, except for proto2 message objects whose
- // destructors can be skipped. Also, frees all blocks except the initial block
- // if it was passed in.
- ~Arena();
+ void Init(const ArenaOptions& options) {
+ on_arena_allocation_ = options.on_arena_allocation;
+ on_arena_reset_ = options.on_arena_reset;
+ on_arena_destruction_ = options.on_arena_destruction;
+ // Call the initialization hook
+ if (options.on_arena_init != NULL) {
+ hooks_cookie_ = options.on_arena_init(this);
+ } else {
+ hooks_cookie_ = NULL;
+ }
+ }
// API to create proto2 message objects on the arena. If the arena passed in
// is NULL, then a heap allocated object is returned. Type T must be a message
@@ -251,40 +263,68 @@ class LIBPROTOBUF_EXPORT Arena {
//
// This function also accepts any type T that satisfies the arena message
// allocation protocol, documented above.
- template <typename T> GOOGLE_ATTRIBUTE_ALWAYS_INLINE
+#if LANG_CXX11
+ template <typename T, typename... Args>
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateMessage(
+ ::google::protobuf::Arena* arena, Args&&... args) {
+ static_assert(
+ InternalHelper<T>::is_arena_constructable::value,
+ "CreateMessage can only construct types that are ArenaConstructable");
+ if (arena == NULL) {
+ return new T(NULL, std::forward<Args>(args)...);
+ } else {
+ return arena->CreateMessageInternal<T>(std::forward<Args>(args)...);
+ }
+ }
+#endif
+ template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
static T* CreateMessage(::google::protobuf::Arena* arena) {
+#if LANG_CXX11
+ static_assert(
+ InternalHelper<T>::is_arena_constructable::value,
+ "CreateMessage can only construct types that are ArenaConstructable");
+#endif
if (arena == NULL) {
return new T;
} else {
- return arena->CreateMessageInternal<T>(static_cast<T*>(0));
+ return arena->CreateMessageInternal<T>();
}
}
// One-argument form of CreateMessage. This is useful for constructing objects
// that implement the arena message construction protocol described above but
// take additional constructor arguments.
- template <typename T, typename Arg> GOOGLE_ATTRIBUTE_ALWAYS_INLINE
+ template <typename T, typename Arg> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
static T* CreateMessage(::google::protobuf::Arena* arena, const Arg& arg) {
+#if LANG_CXX11
+ static_assert(
+ InternalHelper<T>::is_arena_constructable::value,
+ "CreateMessage can only construct types that are ArenaConstructable");
+#endif
if (arena == NULL) {
return new T(NULL, arg);
} else {
- return arena->CreateMessageInternal<T>(static_cast<T*>(0),
- arg);
+ return arena->CreateMessageInternal<T>(arg);
}
}
// Two-argument form of CreateMessage. This is useful for constructing objects
// that implement the arena message construction protocol described above but
// take additional constructor arguments.
- template <typename T, typename Arg1, typename Arg2> GOOGLE_ATTRIBUTE_ALWAYS_INLINE
+ template <typename T, typename Arg1, typename Arg2>
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
static T* CreateMessage(::google::protobuf::Arena* arena,
const Arg1& arg1,
const Arg2& arg2) {
+#if LANG_CXX11
+ static_assert(
+ InternalHelper<T>::is_arena_constructable::value,
+ "CreateMessage can only construct types that are ArenaConstructable");
+#endif
if (arena == NULL) {
return new T(NULL, arg1, arg2);
} else {
- return arena->CreateMessageInternal<T>(static_cast<T*>(0),
- arg1, arg2);
+ return arena->CreateMessageInternal<T>(arg1, arg2);
}
}
@@ -303,7 +343,19 @@ class LIBPROTOBUF_EXPORT Arena {
// (unless the destructor is trivial). Hence, from T's point of view, it is as
// if the object were allocated on the heap (except that the underlying memory
// is obtained from the arena).
- template <typename T> GOOGLE_ATTRIBUTE_ALWAYS_INLINE
+#if LANG_CXX11
+ template <typename T, typename... Args>
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+ static T* Create(::google::protobuf::Arena* arena, Args&&... args) {
+ if (arena == NULL) {
+ return new T(std::forward<Args>(args)...);
+ } else {
+ return arena->CreateInternal<T>(google::protobuf::internal::has_trivial_destructor<T>::value,
+ std::forward<Args>(args)...);
+ }
+ }
+#endif
+ template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
static T* Create(::google::protobuf::Arena* arena) {
if (arena == NULL) {
return new T();
@@ -313,7 +365,7 @@ class LIBPROTOBUF_EXPORT Arena {
}
// Version of the above with one constructor argument for the created object.
- template <typename T, typename Arg> GOOGLE_ATTRIBUTE_ALWAYS_INLINE
+ template <typename T, typename Arg> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
static T* Create(::google::protobuf::Arena* arena, const Arg& arg) {
if (arena == NULL) {
return new T(arg);
@@ -324,7 +376,8 @@ class LIBPROTOBUF_EXPORT Arena {
}
// Version of the above with two constructor arguments for the created object.
- template <typename T, typename Arg1, typename Arg2> GOOGLE_ATTRIBUTE_ALWAYS_INLINE
+ template <typename T, typename Arg1, typename Arg2>
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
static T* Create(::google::protobuf::Arena* arena, const Arg1& arg1, const Arg2& arg2) {
if (arena == NULL) {
return new T(arg1, arg2);
@@ -337,9 +390,11 @@ class LIBPROTOBUF_EXPORT Arena {
// Version of the above with three constructor arguments for the created
// object.
template <typename T, typename Arg1, typename Arg2, typename Arg3>
- GOOGLE_ATTRIBUTE_ALWAYS_INLINE static T* Create(::google::protobuf::Arena* arena,
- const Arg1& arg1, const Arg2& arg2,
- const Arg3& arg3) {
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+ static T* Create(::google::protobuf::Arena* arena,
+ const Arg1& arg1,
+ const Arg2& arg2,
+ const Arg3& arg3) {
if (arena == NULL) {
return new T(arg1, arg2, arg3);
} else {
@@ -352,9 +407,10 @@ class LIBPROTOBUF_EXPORT Arena {
// object.
template <typename T, typename Arg1, typename Arg2, typename Arg3,
typename Arg4>
- GOOGLE_ATTRIBUTE_ALWAYS_INLINE static T* Create(::google::protobuf::Arena* arena,
- const Arg1& arg1, const Arg2& arg2,
- const Arg3& arg3, const Arg4& arg4) {
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+ static T* Create(::google::protobuf::Arena* arena,
+ const Arg1& arg1, const Arg2& arg2,
+ const Arg3& arg3, const Arg4& arg4) {
if (arena == NULL) {
return new T(arg1, arg2, arg3, arg4);
} else {
@@ -367,10 +423,11 @@ class LIBPROTOBUF_EXPORT Arena {
// object.
template <typename T, typename Arg1, typename Arg2, typename Arg3,
typename Arg4, typename Arg5>
- GOOGLE_ATTRIBUTE_ALWAYS_INLINE static T* Create(::google::protobuf::Arena* arena,
- const Arg1& arg1, const Arg2& arg2,
- const Arg3& arg3, const Arg4& arg4,
- const Arg5& arg5) {
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+ static T* Create(::google::protobuf::Arena* arena,
+ const Arg1& arg1, const Arg2& arg2,
+ const Arg3& arg3, const Arg4& arg4,
+ const Arg5& arg5) {
if (arena == NULL) {
return new T(arg1, arg2, arg3, arg4, arg5);
} else {
@@ -383,10 +440,11 @@ class LIBPROTOBUF_EXPORT Arena {
// object.
template <typename T, typename Arg1, typename Arg2, typename Arg3,
typename Arg4, typename Arg5, typename Arg6>
- GOOGLE_ATTRIBUTE_ALWAYS_INLINE static T* Create(::google::protobuf::Arena* arena,
- const Arg1& arg1, const Arg2& arg2,
- const Arg3& arg3, const Arg4& arg4,
- const Arg5& arg5, const Arg6& arg6) {
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+ static T* Create(::google::protobuf::Arena* arena,
+ const Arg1& arg1, const Arg2& arg2,
+ const Arg3& arg3, const Arg4& arg4,
+ const Arg5& arg5, const Arg6& arg6) {
if (arena == NULL) {
return new T(arg1, arg2, arg3, arg4, arg5, arg6);
} else {
@@ -399,11 +457,12 @@ class LIBPROTOBUF_EXPORT Arena {
// object.
template <typename T, typename Arg1, typename Arg2, typename Arg3,
typename Arg4, typename Arg5, typename Arg6, typename Arg7>
- GOOGLE_ATTRIBUTE_ALWAYS_INLINE static T* Create(::google::protobuf::Arena* arena,
- const Arg1& arg1, const Arg2& arg2,
- const Arg3& arg3, const Arg4& arg4,
- const Arg5& arg5, const Arg6& arg6,
- const Arg7& arg7) {
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+ static T* Create(::google::protobuf::Arena* arena,
+ const Arg1& arg1, const Arg2& arg2,
+ const Arg3& arg3, const Arg4& arg4,
+ const Arg5& arg5, const Arg6& arg6,
+ const Arg7& arg7) {
if (arena == NULL) {
return new T(arg1, arg2, arg3, arg4, arg5, arg6, arg7);
} else {
@@ -417,11 +476,12 @@ class LIBPROTOBUF_EXPORT Arena {
template <typename T, typename Arg1, typename Arg2, typename Arg3,
typename Arg4, typename Arg5, typename Arg6, typename Arg7,
typename Arg8>
- GOOGLE_ATTRIBUTE_ALWAYS_INLINE static T* Create(::google::protobuf::Arena* arena,
- const Arg1& arg1, const Arg2& arg2,
- const Arg3& arg3, const Arg4& arg4,
- const Arg5& arg5, const Arg6& arg6,
- const Arg7& arg7, const Arg8& arg8) {
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+ static T* Create(::google::protobuf::Arena* arena,
+ const Arg1& arg1, const Arg2& arg2,
+ const Arg3& arg3, const Arg4& arg4,
+ const Arg5& arg5, const Arg6& arg6,
+ const Arg7& arg7, const Arg8& arg8) {
if (arena == NULL) {
return new T(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
} else {
@@ -437,7 +497,7 @@ class LIBPROTOBUF_EXPORT Arena {
// To ensure safe uses, this function checks at compile time
// (when compiled as C++11) that T is trivially default-constructible and
// trivially destructible.
- template <typename T> GOOGLE_ATTRIBUTE_ALWAYS_INLINE
+ template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
static T* CreateArray(::google::protobuf::Arena* arena, size_t num_elements) {
GOOGLE_CHECK_LE(num_elements,
std::numeric_limits<size_t>::max() / sizeof(T))
@@ -449,28 +509,39 @@ class LIBPROTOBUF_EXPORT Arena {
}
}
- // Returns the total space used by the arena, which is the sums of the sizes
- // of the underlying blocks. The total space used may not include the new
- // blocks that are allocated by this arena from other threads concurrently
- // with the call to this method.
- GOOGLE_ATTRIBUTE_NOINLINE uint64 SpaceAllocated() const;
- // As above, but does not include any free space in underlying blocks.
- GOOGLE_ATTRIBUTE_NOINLINE uint64 SpaceUsed() const;
-
+ // Returns the total space allocated by the arena, which is the sum of the
+ // sizes of the underlying blocks. This method is relatively fast; a counter
+ // is kept as blocks are allocated.
+ uint64 SpaceAllocated() const { return impl_.SpaceAllocated(); }
+ // Returns the total space used by the arena. Similar to SpaceAllocated but
+ // does not include free space and block overhead. The total space returned
+ // may not include space used by other threads executing concurrently with
+ // the call to this method.
+ uint64 SpaceUsed() const { return impl_.SpaceUsed(); }
+ // DEPRECATED. Please use SpaceAllocated() and SpaceUsed().
+ //
// Combines SpaceAllocated and SpaceUsed. Returns a pair of
// <space_allocated, space_used>.
- GOOGLE_ATTRIBUTE_NOINLINE std::pair<uint64, uint64> SpaceAllocatedAndUsed() const;
+ std::pair<uint64, uint64> SpaceAllocatedAndUsed() const {
+ return std::make_pair(SpaceAllocated(), SpaceUsed());
+ }
// Frees all storage allocated by this arena after calling destructors
// registered with OwnDestructor() and freeing objects registered with Own().
// Any objects allocated on this arena are unusable after this call. It also
// returns the total space used by the arena which is the sums of the sizes
// of the allocated blocks. This method is not thread-safe.
- GOOGLE_ATTRIBUTE_NOINLINE uint64 Reset();
+ GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE uint64 Reset() {
+ // Call the reset hook
+ if (on_arena_reset_ != NULL) {
+ on_arena_reset_(this, hooks_cookie_, impl_.SpaceAllocated());
+ }
+ return impl_.Reset();
+ }
// Adds |object| to a list of heap-allocated objects to be freed with |delete|
// when the arena is destroyed or reset.
- template <typename T> GOOGLE_ATTRIBUTE_NOINLINE
+ template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
void Own(T* object) {
OwnInternal(object, google::protobuf::internal::is_convertible<T*, ::google::protobuf::Message*>());
}
@@ -480,10 +551,10 @@ class LIBPROTOBUF_EXPORT Arena {
// that it does not free the underlying memory with |delete|; hence, it is
// normally only used for objects that are placement-newed into
// arena-allocated memory.
- template <typename T> GOOGLE_ATTRIBUTE_NOINLINE
+ template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
void OwnDestructor(T* object) {
if (object != NULL) {
- AddListNode(object, &internal::arena_destruct_object<T>);
+ impl_.AddCleanup(object, &internal::arena_destruct_object<T>);
}
}
@@ -491,30 +562,70 @@ class LIBPROTOBUF_EXPORT Arena {
// will be manually called when the arena is destroyed or reset. This differs
// from OwnDestructor() in that any member function may be specified, not only
// the class destructor.
- GOOGLE_ATTRIBUTE_NOINLINE void OwnCustomDestructor(void* object,
- void (*destruct)(void*)) {
- AddListNode(object, destruct);
+ GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE void OwnCustomDestructor(
+ void* object, void (*destruct)(void*)) {
+ impl_.AddCleanup(object, destruct);
}
// Retrieves the arena associated with |value| if |value| is an arena-capable
// message, or NULL otherwise. This differs from value->GetArena() in that the
// latter is a virtual call, while this method is a templated call that
// resolves at compile-time.
- template<typename T> GOOGLE_ATTRIBUTE_ALWAYS_INLINE
+ template<typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
static ::google::protobuf::Arena* GetArena(const T* value) {
- return GetArenaInternal(value, static_cast<T*>(0));
+ return GetArenaInternal(value, is_arena_constructable<T>());
}
- private:
- struct InternalIsArenaConstructableHelper {
+ template <typename T>
+ class InternalHelper {
+ template <typename U>
+ static char DestructorSkippable(const typename U::DestructorSkippable_*);
+ template <typename U>
+ static double DestructorSkippable(...);
+
+ typedef google::protobuf::internal::integral_constant<
+ bool, sizeof(DestructorSkippable<T>(static_cast<const T*>(0))) ==
+ sizeof(char) ||
+ google::protobuf::internal::has_trivial_destructor<T>::value>
+ is_destructor_skippable;
+
template<typename U>
static char ArenaConstructable(
const typename U::InternalArenaConstructable_*);
template<typename U>
static double ArenaConstructable(...);
+
+ typedef google::protobuf::internal::integral_constant<bool, sizeof(ArenaConstructable<T>(
+ static_cast<const T*>(0))) ==
+ sizeof(char)>
+ is_arena_constructable;
+
+#if LANG_CXX11
+ template <typename... Args>
+ static T* Construct(void* ptr, Args&&... args) {
+ return new (ptr) T(std::forward<Args>(args)...);
+ }
+#else
+ template <typename Arg1>
+ static T* Construct(void* ptr, const Arg1& arg1) {
+ return new (ptr) T(arg1);
+ }
+ template <typename Arg1, typename Arg2>
+ static T* Construct(void* ptr, const Arg1& arg1, const Arg2& arg2) {
+ return new (ptr) T(arg1, arg2);
+ }
+ template <typename Arg1, typename Arg2, typename Arg3>
+ static T* Construct(void* ptr, const Arg1& arg1,
+ const Arg2& arg2, const Arg3& arg3) {
+ return new (ptr) T(arg1, arg2, arg3);
+ }
+#endif // LANG_CXX11
+
+ static Arena* GetArena(const T* p) { return p->GetArenaNoVirtual(); }
+
+ friend class Arena;
};
- public:
// Helper typetrait that indicates support for arenas in a type T at compile
// time. This is public only to allow construction of higher-level templated
// utilities. is_arena_constructable<T>::value is true if the message type T
@@ -523,269 +634,202 @@ class LIBPROTOBUF_EXPORT Arena {
// This is inside Arena because only Arena has the friend relationships
// necessary to see the underlying generated code traits.
template <typename T>
- struct is_arena_constructable
- : public google::protobuf::internal::integral_constant<
- bool, sizeof(InternalIsArenaConstructableHelper::ArenaConstructable<
- const T>(static_cast<const T*>(0))) == sizeof(char)> {
- };
+ struct is_arena_constructable : InternalHelper<T>::is_arena_constructable {};
private:
- // Blocks are variable length malloc-ed objects. The following structure
- // describes the common header for all blocks.
- struct Block {
- void* owner; // &ThreadCache of thread that owns this block, or
- // &this->owner if not yet owned by a thread.
- Block* next; // Next block in arena (may have different owner)
- // ((char*) &block) + pos is next available byte. It is always
- // aligned at a multiple of 8 bytes.
- size_t pos;
- size_t size; // total size of the block.
- GOOGLE_ATTRIBUTE_ALWAYS_INLINE size_t avail() const { return size - pos; }
- // data follows
- };
-
- template<typename Type> friend class ::google::protobuf::internal::GenericTypeHandler;
- friend class MockArena; // For unit-testing.
- friend class internal::ArenaString; // For AllocateAligned.
- friend class internal::LazyField; // For CreateMaybeMessage.
-
- struct ThreadCache {
- // The ThreadCache is considered valid as long as this matches the
- // lifecycle_id of the arena being used.
- int64 last_lifecycle_id_seen;
- Block* last_block_used_;
- };
-
- static const size_t kHeaderSize = sizeof(Block);
- static google::protobuf::internal::SequenceNumber lifecycle_id_generator_;
-#if defined(GOOGLE_PROTOBUF_NO_THREADLOCAL)
- // Android ndk does not support GOOGLE_THREAD_LOCAL keyword so we use a custom thread
- // local storage class we implemented.
- // iOS also does not support the GOOGLE_THREAD_LOCAL keyword.
- static ThreadCache& thread_cache();
-#elif defined(PROTOBUF_USE_DLLS)
- // Thread local variables cannot be exposed through DLL interface but we can
- // wrap them in static functions.
- static ThreadCache& thread_cache();
-#else
- static GOOGLE_THREAD_LOCAL ThreadCache thread_cache_;
- static ThreadCache& thread_cache() { return thread_cache_; }
-#endif
-
- // SFINAE for skipping addition to delete list for a message type when created
- // with CreateMessage. This is mainly to skip proto2/proto1 message objects
- // with cc_enable_arenas=true from being part of the delete list. Also, note,
- // compiler will optimize out the branch in CreateInternal<T>.
- template<typename T>
- static inline bool SkipDeleteList(typename T::DestructorSkippable_*) {
- return true;
+ void CallDestructorHooks();
+ void OnArenaAllocation(const std::type_info* allocated_type, size_t n) const;
+ inline void AllocHook(const std::type_info* allocated_type, size_t n) const {
+ if (GOOGLE_PREDICT_FALSE(hooks_cookie_ != NULL)) {
+ OnArenaAllocation(allocated_type, n);
+ }
}
- // For message objects that don't have the DestructorSkippable_ trait, we
- // always add to the delete list.
- template<typename T>
- static inline bool SkipDeleteList(...) {
- return google::protobuf::internal::has_trivial_destructor<T>::value;
+ // Allocate and also optionally call on_arena_allocation callback with the
+ // allocated type info when the hooks are in place in ArenaOptions and
+ // the cookie is not null.
+ template<typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+ void* AllocateInternal(bool skip_explicit_ownership) {
+ const size_t n = internal::AlignUpTo8(sizeof(T));
+ AllocHook(RTTI_TYPE_ID(T), n);
+ // Monitor allocation if needed.
+ if (skip_explicit_ownership) {
+ return impl_.AllocateAligned(n);
+ } else {
+ return impl_.AllocateAlignedAndAddCleanup(
+ n, &internal::arena_destruct_object<T>);
+ }
}
- private:
- struct InternalIsDestructorSkippableHelper {
- template<typename U>
- static char DestructorSkippable(
- const typename U::DestructorSkippable_*);
- template<typename U>
- static double DestructorSkippable(...);
- };
-
- public:
- // Helper typetrait that indicates whether the desctructor of type T should be
- // called when arena is destroyed at compile time. This is only to allow
- // construction of higher-level templated utilities.
- // is_destructor_skippable<T>::value is true if the destructor of the message
- // type T should not be called when arena is destroyed or false otherwise.
- // This is inside Arena because only Arena has the friend relationships
- // necessary to see the underlying generated code traits.
- template<typename T>
- struct is_destructor_skippable
- : public google::protobuf::internal::integral_constant<
- bool,
- sizeof(InternalIsDestructorSkippableHelper::DestructorSkippable<
- const T>(static_cast<const T*>(0))) == sizeof(char) ||
- google::protobuf::internal::has_trivial_destructor<T>::value> {};
-
- private:
// CreateMessage<T> requires that T supports arenas, but this private method
// works whether or not T supports arenas. These are not exposed to user code
// as it can cause confusing API usages, and end up having double free in
// user code. These are used only internally from LazyField and Repeated
// fields, since they are designed to work in all mode combinations.
- template<typename Msg> GOOGLE_ATTRIBUTE_ALWAYS_INLINE
- static Msg* CreateMaybeMessage(
- Arena* arena, typename Msg::InternalArenaConstructable_*) {
+ template <typename Msg> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+ static Msg* CreateMaybeMessage(Arena* arena, google::protobuf::internal::true_type) {
return CreateMessage<Msg>(arena);
}
- template<typename T> GOOGLE_ATTRIBUTE_ALWAYS_INLINE
- static T* CreateMaybeMessage(Arena* arena, ...) {
+ template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+ static T* CreateMaybeMessage(Arena* arena, google::protobuf::internal::false_type) {
return Create<T>(arena);
}
+ template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+ static T* CreateMaybeMessage(Arena* arena) {
+ return CreateMaybeMessage<T>(arena, is_arena_constructable<T>());
+ }
+
// Just allocate the required size for the given type assuming the
// type has a trivial constructor.
- template<typename T> GOOGLE_ATTRIBUTE_ALWAYS_INLINE
+ template<typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
T* CreateInternalRawArray(size_t num_elements) {
GOOGLE_CHECK_LE(num_elements,
std::numeric_limits<size_t>::max() / sizeof(T))
<< "Requested size is too large to fit into size_t.";
- return static_cast<T*>(
- AllocateAligned(RTTI_TYPE_ID(T), sizeof(T) * num_elements));
+ const size_t n = internal::AlignUpTo8(sizeof(T) * num_elements);
+ // Monitor allocation if needed.
+ AllocHook(RTTI_TYPE_ID(T), n);
+ return static_cast<T*>(impl_.AllocateAligned(n));
}
- template <typename T> GOOGLE_ATTRIBUTE_ALWAYS_INLINE
+#if LANG_CXX11
+ template <typename T, typename... Args>
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+ T* CreateInternal(bool skip_explicit_ownership, Args&&... args) {
+ return new (AllocateInternal<T>(skip_explicit_ownership))
+ T(std::forward<Args>(args)...);
+ }
+#else
+ template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
T* CreateInternal(bool skip_explicit_ownership) {
- T* t = new (AllocateAligned(RTTI_TYPE_ID(T), sizeof(T))) T();
- if (!skip_explicit_ownership) {
- AddListNode(t, &internal::arena_destruct_object<T>);
- }
- return t;
+ return new (AllocateInternal<T>(skip_explicit_ownership)) T();
}
- template <typename T, typename Arg> GOOGLE_ATTRIBUTE_ALWAYS_INLINE
+ template <typename T, typename Arg> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
T* CreateInternal(bool skip_explicit_ownership, const Arg& arg) {
- T* t = new (AllocateAligned(RTTI_TYPE_ID(T), sizeof(T))) T(arg);
- if (!skip_explicit_ownership) {
- AddListNode(t, &internal::arena_destruct_object<T>);
- }
- return t;
+ return new (AllocateInternal<T>(skip_explicit_ownership)) T(arg);
}
- template <typename T, typename Arg1, typename Arg2> GOOGLE_ATTRIBUTE_ALWAYS_INLINE
- T* CreateInternal(
- bool skip_explicit_ownership, const Arg1& arg1, const Arg2& arg2) {
- T* t = new (AllocateAligned(RTTI_TYPE_ID(T), sizeof(T))) T(arg1, arg2);
- if (!skip_explicit_ownership) {
- AddListNode(t, &internal::arena_destruct_object<T>);
- }
- return t;
+ template <typename T, typename Arg1, typename Arg2>
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+ T* CreateInternal(bool skip_explicit_ownership,
+ const Arg1& arg1,
+ const Arg2& arg2) {
+ return new (AllocateInternal<T>(skip_explicit_ownership)) T(arg1, arg2);
}
template <typename T, typename Arg1, typename Arg2, typename Arg3>
- GOOGLE_ATTRIBUTE_ALWAYS_INLINE T* CreateInternal(bool skip_explicit_ownership,
- const Arg1& arg1,
- const Arg2& arg2,
- const Arg3& arg3) {
- T* t = new (AllocateAligned(RTTI_TYPE_ID(T), sizeof(T)))
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+ T* CreateInternal(bool skip_explicit_ownership,
+ const Arg1& arg1,
+ const Arg2& arg2,
+ const Arg3& arg3) {
+ return new (AllocateInternal<T>(skip_explicit_ownership))
T(arg1, arg2, arg3);
- if (!skip_explicit_ownership) {
- AddListNode(t, &internal::arena_destruct_object<T>);
- }
- return t;
}
template <typename T, typename Arg1, typename Arg2, typename Arg3,
typename Arg4>
- GOOGLE_ATTRIBUTE_ALWAYS_INLINE T* CreateInternal(bool skip_explicit_ownership,
- const Arg1& arg1,
- const Arg2& arg2,
- const Arg3& arg3,
- const Arg4& arg4) {
- T* t = new (AllocateAligned(RTTI_TYPE_ID(T), sizeof(T)))
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+ T* CreateInternal(bool skip_explicit_ownership,
+ const Arg1& arg1,
+ const Arg2& arg2,
+ const Arg3& arg3,
+ const Arg4& arg4) {
+ return new (AllocateInternal<T>(skip_explicit_ownership))
T(arg1, arg2, arg3, arg4);
- if (!skip_explicit_ownership) {
- AddListNode(t, &internal::arena_destruct_object<T>);
- }
- return t;
}
template <typename T, typename Arg1, typename Arg2, typename Arg3,
typename Arg4, typename Arg5>
- GOOGLE_ATTRIBUTE_ALWAYS_INLINE T* CreateInternal(bool skip_explicit_ownership,
- const Arg1& arg1,
- const Arg2& arg2,
- const Arg3& arg3,
- const Arg4& arg4,
- const Arg5& arg5) {
- T* t = new (AllocateAligned(RTTI_TYPE_ID(T), sizeof(T)))
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+ T* CreateInternal(bool skip_explicit_ownership,
+ const Arg1& arg1,
+ const Arg2& arg2,
+ const Arg3& arg3,
+ const Arg4& arg4,
+ const Arg5& arg5) {
+ return new (AllocateInternal<T>(skip_explicit_ownership))
T(arg1, arg2, arg3, arg4, arg5);
- if (!skip_explicit_ownership) {
- AddListNode(t, &internal::arena_destruct_object<T>);
- }
- return t;
}
template <typename T, typename Arg1, typename Arg2, typename Arg3,
typename Arg4, typename Arg5, typename Arg6>
- GOOGLE_ATTRIBUTE_ALWAYS_INLINE T* CreateInternal(bool skip_explicit_ownership,
- const Arg1& arg1,
- const Arg2& arg2,
- const Arg3& arg3,
- const Arg4& arg4,
- const Arg5& arg5,
- const Arg6& arg6) {
- T* t = new (AllocateAligned(RTTI_TYPE_ID(T), sizeof(T)))
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+ T* CreateInternal(bool skip_explicit_ownership,
+ const Arg1& arg1,
+ const Arg2& arg2,
+ const Arg3& arg3,
+ const Arg4& arg4,
+ const Arg5& arg5,
+ const Arg6& arg6) {
+ return new (AllocateInternal<T>(skip_explicit_ownership))
T(arg1, arg2, arg3, arg4, arg5, arg6);
- if (!skip_explicit_ownership) {
- AddListNode(t, &internal::arena_destruct_object<T>);
- }
- return t;
}
template <typename T, typename Arg1, typename Arg2, typename Arg3,
typename Arg4, typename Arg5, typename Arg6, typename Arg7>
- GOOGLE_ATTRIBUTE_ALWAYS_INLINE T* CreateInternal(bool skip_explicit_ownership,
- const Arg1& arg1,
- const Arg2& arg2,
- const Arg3& arg3,
- const Arg4& arg4,
- const Arg5& arg5,
- const Arg6& arg6,
- const Arg7& arg7) {
- T* t = new (AllocateAligned(RTTI_TYPE_ID(T), sizeof(T)))
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+ T* CreateInternal(bool skip_explicit_ownership,
+ const Arg1& arg1,
+ const Arg2& arg2,
+ const Arg3& arg3,
+ const Arg4& arg4,
+ const Arg5& arg5,
+ const Arg6& arg6,
+ const Arg7& arg7) {
+ return new (AllocateInternal<T>(skip_explicit_ownership))
T(arg1, arg2, arg3, arg4, arg5, arg6, arg7);
- if (!skip_explicit_ownership) {
- AddListNode(t, &internal::arena_destruct_object<T>);
- }
- return t;
}
template <typename T, typename Arg1, typename Arg2, typename Arg3,
typename Arg4, typename Arg5, typename Arg6, typename Arg7,
typename Arg8>
- GOOGLE_ATTRIBUTE_ALWAYS_INLINE T* CreateInternal(bool skip_explicit_ownership,
- const Arg1& arg1,
- const Arg2& arg2,
- const Arg3& arg3,
- const Arg4& arg4,
- const Arg5& arg5,
- const Arg6& arg6,
- const Arg7& arg7,
- const Arg8& arg8) {
- T* t = new (AllocateAligned(RTTI_TYPE_ID(T), sizeof(T)))
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+ T* CreateInternal(bool skip_explicit_ownership,
+ const Arg1& arg1,
+ const Arg2& arg2,
+ const Arg3& arg3,
+ const Arg4& arg4,
+ const Arg5& arg5,
+ const Arg6& arg6,
+ const Arg7& arg7,
+ const Arg8& arg8) {
+ return new (AllocateInternal<T>(skip_explicit_ownership))
T(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
- if (!skip_explicit_ownership) {
- AddListNode(t, &internal::arena_destruct_object<T>);
- }
- return t;
}
-
- template <typename T> GOOGLE_ATTRIBUTE_ALWAYS_INLINE
- T* CreateMessageInternal(typename T::InternalArenaConstructable_*) {
- return CreateInternal<T, Arena*>(SkipDeleteList<T>(static_cast<T*>(0)),
- this);
+#endif
+#if LANG_CXX11
+ template <typename T, typename... Args>
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* CreateMessageInternal(
+ Args&&... args) {
+ return InternalHelper<T>::Construct(
+ AllocateInternal<T>(InternalHelper<T>::is_destructor_skippable::value),
+ this, std::forward<Args>(args)...);
+ }
+#endif
+ template <typename T>
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* CreateMessageInternal() {
+ return InternalHelper<T>::Construct(
+ AllocateInternal<T>(InternalHelper<T>::is_destructor_skippable::value),
+ this);
}
- template <typename T, typename Arg> GOOGLE_ATTRIBUTE_ALWAYS_INLINE
- T* CreateMessageInternal(typename T::InternalArenaConstructable_*,
- const Arg& arg) {
- return CreateInternal<T, Arena*>(SkipDeleteList<T>(static_cast<T*>(0)),
- this, arg);
+ template <typename T, typename Arg> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+ T* CreateMessageInternal(const Arg& arg) {
+ return InternalHelper<T>::Construct(
+ AllocateInternal<T>(InternalHelper<T>::is_destructor_skippable::value),
+ this, arg);
}
- template <typename T, typename Arg1, typename Arg2> GOOGLE_ATTRIBUTE_ALWAYS_INLINE
- T* CreateMessageInternal(typename T::InternalArenaConstructable_*,
- const Arg1& arg1, const Arg2& arg2) {
- return CreateInternal<T, Arena*>(SkipDeleteList<T>(static_cast<T*>(0)),
- this, arg1, arg2);
+ template <typename T, typename Arg1, typename Arg2>
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+ T* CreateMessageInternal(const Arg1& arg1, const Arg2& arg2) {
+ return InternalHelper<T>::Construct(
+ AllocateInternal<T>(InternalHelper<T>::is_destructor_skippable::value),
+ this, arg1, arg2);
}
// CreateInArenaStorage is used to implement map field. Without it,
@@ -795,24 +839,25 @@ class LIBPROTOBUF_EXPORT Arena {
static void CreateInArenaStorage(T* ptr, Arena* arena) {
CreateInArenaStorageInternal(ptr, arena,
typename is_arena_constructable<T>::type());
- RegisterDestructorInternal(ptr, arena,
- typename is_destructor_skippable<T>::type());
+ RegisterDestructorInternal(
+ ptr, arena,
+ typename InternalHelper<T>::is_destructor_skippable::type());
}
template <typename T>
static void CreateInArenaStorageInternal(
T* ptr, Arena* arena, google::protobuf::internal::true_type) {
- new (ptr) T(arena);
+ InternalHelper<T>::Construct(ptr, arena);
}
template <typename T>
static void CreateInArenaStorageInternal(
- T* ptr, Arena* arena, google::protobuf::internal::false_type) {
+ T* ptr, Arena* /* arena */, google::protobuf::internal::false_type) {
new (ptr) T();
}
template <typename T>
static void RegisterDestructorInternal(
- T* ptr, Arena* arena, google::protobuf::internal::true_type) {}
+ T* /* ptr */, Arena* /* arena */, google::protobuf::internal::true_type) {}
template <typename T>
static void RegisterDestructorInternal(
T* ptr, Arena* arena, google::protobuf::internal::false_type) {
@@ -824,102 +869,60 @@ class LIBPROTOBUF_EXPORT Arena {
// is a subtype of ::google::protobuf::Message and 'false_type' otherwise. Collapsing
// all template instantiations to one for generic Message reduces code size,
// using the virtual destructor instead.
- template<typename T> GOOGLE_ATTRIBUTE_ALWAYS_INLINE
+ template<typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
void OwnInternal(T* object, google::protobuf::internal::true_type) {
if (object != NULL) {
- AddListNode(object, &internal::arena_delete_object< ::google::protobuf::Message >);
+ impl_.AddCleanup(object,
+ &internal::arena_delete_object< ::google::protobuf::Message>);
}
}
- template<typename T> GOOGLE_ATTRIBUTE_ALWAYS_INLINE
+ template<typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
void OwnInternal(T* object, google::protobuf::internal::false_type) {
if (object != NULL) {
- AddListNode(object, &internal::arena_delete_object<T>);
+ impl_.AddCleanup(object, &internal::arena_delete_object<T>);
}
}
// Implementation for GetArena(). Only message objects with
// InternalArenaConstructable_ tags can be associated with an arena, and such
// objects must implement a GetArenaNoVirtual() method.
- template<typename T> GOOGLE_ATTRIBUTE_ALWAYS_INLINE
+ template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
static ::google::protobuf::Arena* GetArenaInternal(
- const T* value, typename T::InternalArenaConstructable_*) {
- return value->GetArenaNoVirtual();
+ const T* value, google::protobuf::internal::true_type) {
+ return InternalHelper<T>::GetArena(value);
}
- template<typename T> GOOGLE_ATTRIBUTE_ALWAYS_INLINE
- static ::google::protobuf::Arena* GetArenaInternal(const T* value, ...) {
+ template <typename T>
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+ static ::google::protobuf::Arena* GetArenaInternal(
+ const T* /* value */, google::protobuf::internal::false_type) {
return NULL;
}
- // Allocate and also optionally call on_arena_allocation callback with the
- // allocated type info when the hooks are in place in ArenaOptions and
- // the cookie is not null.
- void* AllocateAligned(const std::type_info* allocated, size_t n);
-
- // Allocate an internal allocation, avoiding optional typed monitoring.
- GOOGLE_ATTRIBUTE_ALWAYS_INLINE void* AllocateAligned(size_t n) {
- return AllocateAligned(NULL, n);
+ // For friends of arena.
+ void* AllocateAligned(size_t n) {
+ AllocHook(NULL, n);
+ return impl_.AllocateAligned(internal::AlignUpTo8(n));
}
- void Init();
-
- // Free all blocks and return the total space used which is the sums of sizes
- // of the all the allocated blocks.
- uint64 FreeBlocks();
+ internal::ArenaImpl impl_;
- // Add object pointer and cleanup function pointer to the list.
- // TODO(rohananil, cfallin): We could pass in a sub-arena into this method
- // to avoid polluting blocks of this arena with list nodes. This would help in
- // mixed mode (where many protobufs have cc_enable_arenas=false), and is an
- // alternative to a chunked linked-list, but with extra overhead of *next.
- void AddListNode(void* elem, void (*cleanup)(void*));
- // Delete or Destruct all objects owned by the arena.
- void CleanupList();
- uint64 ResetInternal();
-
- inline void SetThreadCacheBlock(Block* block) {
- thread_cache().last_block_used_ = block;
- thread_cache().last_lifecycle_id_seen = lifecycle_id_;
- }
-
- int64 lifecycle_id_; // Unique for each arena. Changes on Reset().
-
- google::protobuf::internal::AtomicWord blocks_; // Head of linked list of all allocated blocks
- google::protobuf::internal::AtomicWord hint_; // Fast thread-local block access
-
- // Node contains the ptr of the object to be cleaned up and the associated
- // cleanup function ptr.
- struct Node {
- void* elem; // Pointer to the object to be cleaned up.
- void (*cleanup)(void*); // Function pointer to the destructor or deleter.
- Node* next; // Next node in the list.
- };
-
- google::protobuf::internal::AtomicWord cleanup_list_; // Head of a linked list of nodes containing object
- // ptrs and cleanup methods.
-
- bool owns_first_block_; // Indicates that arena owns the first block
- Mutex blocks_lock_;
-
- void AddBlock(Block* b);
- // Access must be synchronized, either by blocks_lock_ or by being called from
- // Init()/Reset().
- void AddBlockInternal(Block* b);
- void* SlowAlloc(size_t n);
- Block* FindBlock(void* me);
- Block* NewBlock(void* me, Block* my_last_block, size_t n,
- size_t start_block_size, size_t max_block_size);
- static void* AllocFromBlock(Block* b, size_t n);
- template <typename Key, typename T>
- friend class Map;
+ void* (*on_arena_init_)(Arena* arena);
+ void (*on_arena_allocation_)(const std::type_info* allocated_type,
+ uint64 alloc_size, void* cookie);
+ void (*on_arena_reset_)(Arena* arena, void* cookie, uint64 space_used);
+ void (*on_arena_destruction_)(Arena* arena, void* cookie, uint64 space_used);
// The arena may save a cookie it receives from the external on_init hook
// and then use it when calling the on_reset and on_destruction hooks.
void* hooks_cookie_;
- ArenaOptions options_;
-
- GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Arena);
+ template <typename Type>
+ friend class ::google::protobuf::internal::GenericTypeHandler;
+ friend struct internal::ArenaStringPtr; // For AllocateAligned.
+ friend class internal::LazyField; // For CreateMaybeMessage.
+ template <typename Key, typename T>
+ friend class Map;
};
// Defined above for supporting environments without RTTI.
diff --git a/src/google/protobuf/arena_impl.h b/src/google/protobuf/arena_impl.h
new file mode 100644
index 00000000..6cc7096b
--- /dev/null
+++ b/src/google/protobuf/arena_impl.h
@@ -0,0 +1,242 @@
+// 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.
+
+// This file defines an Arena allocator for better allocation performance.
+
+#ifndef GOOGLE_PROTOBUF_ARENA_IMPL_H__
+#define GOOGLE_PROTOBUF_ARENA_IMPL_H__
+
+#include <limits>
+
+#include <google/protobuf/stubs/atomic_sequence_num.h>
+#include <google/protobuf/stubs/atomicops.h>
+#include <google/protobuf/stubs/common.h>
+#include <google/protobuf/stubs/logging.h>
+#include <google/protobuf/stubs/mutex.h>
+#include <google/protobuf/stubs/type_traits.h>
+
+#include <google/protobuf/stubs/port.h>
+
+namespace google {
+
+namespace protobuf {
+namespace internal {
+
+inline size_t AlignUpTo8(size_t n) {
+ // Align n to next multiple of 8 (from Hacker's Delight, Chapter 3.)
+ return (n + 7) & -8;
+}
+
+// This class provides the core Arena memory allocation library. Different
+// implementations only need to implement the public interface below.
+// Arena is not a template type as that would only be useful if all protos
+// in turn would be templates, which will/cannot happen. However separating
+// the memory allocation part from the cruft of the API users expect we can
+// use #ifdef the select the best implementation based on hardware / OS.
+class LIBPROTOBUF_EXPORT ArenaImpl {
+ public:
+ struct Options {
+ size_t start_block_size;
+ size_t max_block_size;
+ char* initial_block;
+ size_t initial_block_size;
+ void* (*block_alloc)(size_t);
+ void (*block_dealloc)(void*, size_t);
+
+ template <typename O>
+ explicit Options(const O& options)
+ : start_block_size(options.start_block_size),
+ max_block_size(options.max_block_size),
+ initial_block(options.initial_block),
+ initial_block_size(options.initial_block_size),
+ block_alloc(options.block_alloc),
+ block_dealloc(options.block_dealloc) {}
+ };
+
+ template <typename O>
+ explicit ArenaImpl(const O& options) : options_(options) {
+ if (options_.initial_block != NULL && options_.initial_block_size > 0) {
+ GOOGLE_CHECK_GE(options_.initial_block_size, sizeof(Block))
+ << ": Initial block size too small for header.";
+ initial_block_ = reinterpret_cast<Block*>(options_.initial_block);
+ } else {
+ initial_block_ = NULL;
+ }
+
+ Init();
+ }
+
+ // Destructor deletes all owned heap allocated objects, and destructs objects
+ // that have non-trivial destructors, except for proto2 message objects whose
+ // destructors can be skipped. Also, frees all blocks except the initial block
+ // if it was passed in.
+ ~ArenaImpl();
+
+ uint64 Reset();
+
+ uint64 SpaceAllocated() const;
+ uint64 SpaceUsed() const;
+
+ void* AllocateAligned(size_t n);
+
+ void* AllocateAlignedAndAddCleanup(size_t n, void (*cleanup)(void*));
+
+ // Add object pointer and cleanup function pointer to the list.
+ void AddCleanup(void* elem, void (*cleanup)(void*));
+
+ private:
+ // Node contains the ptr of the object to be cleaned up and the associated
+ // cleanup function ptr.
+ struct CleanupNode {
+ void* elem; // Pointer to the object to be cleaned up.
+ void (*cleanup)(void*); // Function pointer to the destructor or deleter.
+ };
+
+ // Cleanup uses a chunked linked list, to reduce pointer chasing.
+ struct CleanupChunk {
+ static size_t SizeOf(size_t i) {
+ return sizeof(CleanupChunk) + (sizeof(CleanupNode) * (i - 1));
+ }
+ size_t len; // Number of elements currently present.
+ size_t size; // Total elements in the list.
+ CleanupChunk* next; // Next node in the list.
+ CleanupNode nodes[1]; // True length is |size|.
+ };
+
+ struct Block;
+
+ // Tracks per-thread info. ThreadInfos are kept in a linked list.
+ struct ThreadInfo {
+ void *owner; // &ThreadCache of this thread;
+ Block* head; // Head of linked list of blocks.
+ CleanupChunk* cleanup; // Head of cleanup list.
+ ThreadInfo* next; // Next ThreadInfo in this linked list.
+ };
+
+ // Blocks are variable length malloc-ed objects. The following structure
+ // describes the common header for all blocks.
+ struct Block {
+ void* owner; // &ThreadCache of thread that owns this block.
+ ThreadInfo* thread_info; // ThreadInfo of thread that owns this block.
+ Block* next; // Next block in arena (may have different owner)
+ // ((char*) &block) + pos is next available byte. It is always
+ // aligned at a multiple of 8 bytes.
+ size_t pos;
+ size_t size; // total size of the block.
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+ size_t avail() const { return size - pos; }
+ // data follows
+ };
+
+ struct ThreadCache {
+#if defined(GOOGLE_PROTOBUF_NO_THREADLOCAL)
+ // If we are using the ThreadLocalStorage class to store the ThreadCache,
+ // then the ThreadCache's default constructor has to be responsible for
+ // initializing it.
+ ThreadCache() : last_lifecycle_id_seen(-1), last_block_used_(NULL) {}
+#endif
+
+ // The ThreadCache is considered valid as long as this matches the
+ // lifecycle_id of the arena being used.
+ int64 last_lifecycle_id_seen;
+ Block* last_block_used_;
+ };
+ static google::protobuf::internal::SequenceNumber lifecycle_id_generator_;
+#if defined(GOOGLE_PROTOBUF_NO_THREADLOCAL)
+ // Android ndk does not support GOOGLE_THREAD_LOCAL keyword so we use a custom thread
+ // local storage class we implemented.
+ // iOS also does not support the GOOGLE_THREAD_LOCAL keyword.
+ static ThreadCache& thread_cache();
+#elif defined(PROTOBUF_USE_DLLS)
+ // Thread local variables cannot be exposed through DLL interface but we can
+ // wrap them in static functions.
+ static ThreadCache& thread_cache();
+#else
+ static GOOGLE_THREAD_LOCAL ThreadCache thread_cache_;
+ static ThreadCache& thread_cache() { return thread_cache_; }
+#endif
+
+ void Init();
+
+ // Free all blocks and return the total space used which is the sums of sizes
+ // of the all the allocated blocks.
+ uint64 FreeBlocks();
+
+ void AddCleanupInBlock(Block* b, void* elem, void (*func)(void*));
+ CleanupChunk* ExpandCleanupList(CleanupChunk* cleanup, Block* b);
+ // Delete or Destruct all objects owned by the arena.
+ void CleanupList();
+
+ inline void CacheBlock(Block* block) {
+ thread_cache().last_block_used_ = block;
+ thread_cache().last_lifecycle_id_seen = lifecycle_id_;
+ // TODO(haberman): evaluate whether we would gain efficiency by getting rid
+ // of hint_. It's the only write we do to ArenaImpl in the allocation path,
+ // which will dirty the cache line.
+ google::protobuf::internal::Release_Store(&hint_, reinterpret_cast<google::protobuf::internal::AtomicWord>(block));
+ }
+
+ google::protobuf::internal::AtomicWord threads_; // Pointer to a linked list of ThreadInfo.
+ google::protobuf::internal::AtomicWord hint_; // Fast thread-local block access
+ google::protobuf::internal::AtomicWord space_allocated_; // Sum of sizes of all allocated blocks.
+
+ Block *initial_block_; // If non-NULL, points to the block that came from
+ // user data.
+
+ // Returns a block owned by this thread.
+ Block* GetBlock(size_t n);
+ Block* GetBlockSlow(void* me, Block* my_full_block, size_t n);
+ Block* NewBlock(void* me, Block* my_last_block, size_t min_bytes);
+ void InitBlock(Block* b, void *me, size_t size);
+ static void* AllocFromBlock(Block* b, size_t n);
+ ThreadInfo* NewThreadInfo(Block* b);
+ ThreadInfo* FindThreadInfo(void* me);
+ ThreadInfo* GetThreadInfo(void* me, size_t n);
+
+ int64 lifecycle_id_; // Unique for each arena. Changes on Reset().
+
+ Options options_;
+
+ GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ArenaImpl);
+
+ public:
+ // kHeaderSize is sizeof(Block), aligned up to the nearest multiple of 8 to
+ // protect the invariant that pos is always at a multiple of 8.
+ static const size_t kHeaderSize = (sizeof(Block) + 7) & -8;
+#if LANG_CXX11
+ static_assert(kHeaderSize % 8 == 0, "kHeaderSize must be a multiple of 8.");
+#endif
+};
+
+} // namespace internal
+} // namespace protobuf
+
+} // namespace google
+#endif // GOOGLE_PROTOBUF_ARENA_IMPL_H__
diff --git a/src/google/protobuf/arena_unittest.cc b/src/google/protobuf/arena_unittest.cc
index 4f9571db..c6ff25e8 100644
--- a/src/google/protobuf/arena_unittest.cc
+++ b/src/google/protobuf/arena_unittest.cc
@@ -180,6 +180,35 @@ TEST(ArenaTest, BasicCreate) {
EXPECT_EQ(2, notifier.GetCount());
}
+TEST(ArenaTest, CreateAndConstCopy) {
+ Arena arena;
+ const string s("foo");
+ const string* s_copy = Arena::Create<string>(&arena, s);
+ EXPECT_TRUE(s_copy != NULL);
+ EXPECT_EQ("foo", s);
+ EXPECT_EQ("foo", *s_copy);
+}
+
+TEST(ArenaTest, CreateAndNonConstCopy) {
+ Arena arena;
+ string s("foo");
+ const string* s_copy = Arena::Create<string>(&arena, s);
+ EXPECT_TRUE(s_copy != NULL);
+ EXPECT_EQ("foo", s);
+ EXPECT_EQ("foo", *s_copy);
+}
+
+#if LANG_CXX11
+TEST(ArenaTest, CreateAndMove) {
+ Arena arena;
+ string s("foo");
+ const string* s_move = Arena::Create<string>(&arena, std::move(s));
+ EXPECT_TRUE(s_move != NULL);
+ EXPECT_TRUE(s.empty()); // NOLINT
+ EXPECT_EQ("foo", *s_move);
+}
+#endif
+
TEST(ArenaTest, CreateWithFourConstructorArguments) {
Arena arena;
const string three("3");
@@ -214,11 +243,34 @@ TEST(ArenaTest, CreateWithEightConstructorArguments) {
ASSERT_EQ("8", new_object->eight_);
}
+#if LANG_CXX11
+class PleaseMoveMe {
+ public:
+ explicit PleaseMoveMe(const string& value) : value_(value) {}
+ PleaseMoveMe(PleaseMoveMe&&) = default;
+ PleaseMoveMe(const PleaseMoveMe&) = delete;
+
+ const string& value() const { return value_; }
+
+ private:
+ string value_;
+};
+
+TEST(ArenaTest, CreateWithMoveArguments) {
+ Arena arena;
+ PleaseMoveMe one("1");
+ const PleaseMoveMe* new_object =
+ Arena::Create<PleaseMoveMe>(&arena, std::move(one));
+ EXPECT_TRUE(new_object);
+ ASSERT_EQ("1", new_object->value());
+}
+#endif
+
TEST(ArenaTest, InitialBlockTooSmall) {
// Construct a small (64 byte) initial block of memory to be used by the
// arena allocator; then, allocate an object which will not fit in the
// initial block.
- std::vector<char> arena_block(64);
+ std::vector<char> arena_block(72);
ArenaOptions options;
options.initial_block = &arena_block[0];
options.initial_block_size = arena_block.size();
@@ -1247,12 +1299,12 @@ TEST(ArenaTest, SpaceAllocated_and_Used) {
options.initial_block_size = 0;
Arena arena_3(options);
EXPECT_EQ(0, arena_3.SpaceUsed());
- ::google::protobuf::Arena::CreateArray<char>(&arena_3, 190);
+ ::google::protobuf::Arena::CreateArray<char>(&arena_3, 182);
EXPECT_EQ(256, arena_3.SpaceAllocated());
- EXPECT_EQ(Align8(190), arena_3.SpaceUsed());
+ EXPECT_EQ(Align8(182), arena_3.SpaceUsed());
::google::protobuf::Arena::CreateArray<char>(&arena_3, 70);
EXPECT_EQ(256 + 512, arena_3.SpaceAllocated());
- EXPECT_EQ(Align8(190) + Align8(70), arena_3.SpaceUsed());
+ EXPECT_EQ(Align8(182) + Align8(70), arena_3.SpaceUsed());
EXPECT_EQ(256 + 512, arena_3.Reset());
}
diff --git a/src/google/protobuf/arenastring.cc b/src/google/protobuf/arenastring.cc
index f10732c0..7f33a0c8 100644
--- a/src/google/protobuf/arenastring.cc
+++ b/src/google/protobuf/arenastring.cc
@@ -38,16 +38,6 @@ namespace protobuf {
namespace internal {
-void ArenaStringPtr::AssignWithDefault(const ::std::string* default_value,
- ArenaStringPtr value) {
- const ::std::string* me = *UnsafeRawStringPointer();
- const ::std::string* other = *value.UnsafeRawStringPointer();
- // If the pointers are the same then do nothing.
- if (me != other) {
- SetNoArena(default_value, value.GetNoArena());
- }
-}
-
} // namespace internal
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/arenastring.h b/src/google/protobuf/arenastring.h
index b60ee379..c9d045a1 100755
--- a/src/google/protobuf/arenastring.h
+++ b/src/google/protobuf/arenastring.h
@@ -33,12 +33,11 @@
#include <string>
-#include <google/protobuf/stubs/logging.h>
+#include <google/protobuf/arena.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/fastmem.h>
-#include <google/protobuf/arena.h>
-
-
+#include <google/protobuf/stubs/logging.h>
+#include <google/protobuf/stubs/port.h>
// This is the implementation of arena string fields written for the open-source
// release. The ArenaStringPtr struct below is an internal implementation class
@@ -62,6 +61,12 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr {
}
}
+ inline void SetLite(const ::std::string* default_value,
+ const ::std::string& value,
+ ::google::protobuf::Arena* arena) {
+ Set(default_value, value, arena);
+ }
+
// Basic accessors.
inline const ::std::string& Get() const { return *ptr_; }
@@ -84,8 +89,9 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr {
}
::std::string* released = NULL;
if (arena != NULL) {
- // ptr_ is owned by the arena -- we need to return a copy.
- released = new ::std::string(*ptr_);
+ // ptr_ is owned by the arena.
+ released = new ::std::string;
+ released->swap(*ptr_);
} else {
released = ptr_;
}
@@ -143,7 +149,7 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr {
// Swaps internal pointers. Arena-safety semantics: this is guarded by the
// logic in Swap()/UnsafeArenaSwap() at the message level, so this method is
// 'unsafe' if called directly.
- GOOGLE_ATTRIBUTE_ALWAYS_INLINE void Swap(ArenaStringPtr* other) {
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void Swap(ArenaStringPtr* other) {
std::swap(ptr_, other->ptr_);
}
@@ -210,6 +216,16 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr {
}
}
+#if LANG_CXX11
+ void SetNoArena(const ::std::string* default_value, ::std::string&& value) {
+ if (IsDefault(default_value)) {
+ ptr_ = new ::std::string(std::move(value));
+ } else {
+ *ptr_ = std::move(value);
+ }
+ }
+#endif
+
void AssignWithDefault(const ::std::string* default_value, ArenaStringPtr value);
inline const ::std::string& GetNoArena() const { return *ptr_; }
@@ -281,24 +297,19 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr {
private:
::std::string* ptr_;
- GOOGLE_ATTRIBUTE_NOINLINE void CreateInstance(::google::protobuf::Arena* arena,
- const ::std::string* initial_value) {
- // Assumes ptr_ is not NULL.
- if (initial_value != NULL) {
- ptr_ = new ::std::string(*initial_value);
- } else {
- ptr_ = new ::std::string();
- }
+ GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
+ void CreateInstance(::google::protobuf::Arena* arena,
+ const ::std::string* initial_value) {
+ GOOGLE_DCHECK(initial_value != NULL);
+ ptr_ = new ::std::string(*initial_value);
if (arena != NULL) {
arena->Own(ptr_);
}
}
- GOOGLE_ATTRIBUTE_NOINLINE void CreateInstanceNoArena(const ::std::string* initial_value) {
- if (initial_value != NULL) {
- ptr_ = new ::std::string(*initial_value);
- } else {
- ptr_ = new ::std::string();
- }
+ GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
+ void CreateInstanceNoArena(const ::std::string* initial_value) {
+ GOOGLE_DCHECK(initial_value != NULL);
+ ptr_ = new ::std::string(*initial_value);
}
};
@@ -307,5 +318,21 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr {
+namespace protobuf {
+namespace internal {
+
+inline void ArenaStringPtr::AssignWithDefault(const ::std::string* default_value,
+ ArenaStringPtr value) {
+ const ::std::string* me = *UnsafeRawStringPointer();
+ const ::std::string* other = *value.UnsafeRawStringPointer();
+ // If the pointers are the same then do nothing.
+ if (me != other) {
+ SetNoArena(default_value, value.GetNoArena());
+ }
+}
+
+} // namespace internal
+} // namespace protobuf
+
} // namespace google
#endif // GOOGLE_PROTOBUF_ARENASTRING_H__
diff --git a/src/google/protobuf/arenastring_unittest.cc b/src/google/protobuf/arenastring_unittest.cc
index e5afe42d..d5d995a6 100644
--- a/src/google/protobuf/arenastring_unittest.cc
+++ b/src/google/protobuf/arenastring_unittest.cc
@@ -32,19 +32,23 @@
#include <google/protobuf/arenastring.h>
-#include <string>
+#include <algorithm>
+#include <cstdlib>
#include <memory>
#ifndef _SHARED_PTR_H
#include <google/protobuf/stubs/shared_ptr.h>
#endif
-#include <cstdlib>
+#include <string>
+#include <vector>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
#include <gtest/gtest.h>
+#include <google/protobuf/io/coded_stream.h>
+#include <google/protobuf/io/zero_copy_stream_impl.h>
+
namespace google {
-using google::protobuf::internal::ArenaString;
using google::protobuf::internal::ArenaStringPtr;
namespace protobuf {
@@ -87,7 +91,35 @@ TEST(ArenaStringPtrTest, ArenaStringPtrOnArena) {
EXPECT_EQ(string("default"), field.Get());
field.Set(&default_value, WrapString("Test short"), &arena);
EXPECT_EQ(string("Test short"), field.Get());
- field.Set(&default_value, WrapString("Test long long long long value"), &arena);
+ field.Set(&default_value, WrapString("Test long long long long value"),
+ &arena);
+ EXPECT_EQ(string("Test long long long long value"), field.Get());
+ field.Set(&default_value, string(""), &arena);
+ field.Destroy(&default_value, &arena);
+
+ ArenaStringPtr field2;
+ field2.UnsafeSetDefault(&default_value);
+ ::std::string* mut = field2.Mutable(&default_value, &arena);
+ EXPECT_EQ(mut, field2.Mutable(&default_value, &arena));
+ EXPECT_EQ(mut, &field2.Get());
+ EXPECT_NE(&default_value, mut);
+ EXPECT_EQ(string("default"), *mut);
+ *mut = "Test long long long long value"; // ensure string allocates storage
+ EXPECT_EQ(string("Test long long long long value"), field2.Get());
+ field2.Destroy(&default_value, &arena);
+}
+
+TEST(ArenaStringPtrTest, ArenaStringPtrOnArenaNoSSO) {
+ google::protobuf::Arena arena;
+ ArenaStringPtr field;
+ ::std::string default_value = "default";
+ field.UnsafeSetDefault(&default_value);
+ EXPECT_EQ(string("default"), field.Get());
+
+ // Avoid triggering the SSO optimization by setting the string to something
+ // larger than the internal buffer.
+ field.Set(&default_value, WrapString("Test long long long long value"),
+ &arena);
EXPECT_EQ(string("Test long long long long value"), field.Get());
field.Set(&default_value, string(""), &arena);
field.Destroy(&default_value, &arena);
@@ -104,5 +136,6 @@ TEST(ArenaStringPtrTest, ArenaStringPtrOnArena) {
field2.Destroy(&default_value, &arena);
}
+
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/compiler/annotation_test_util.cc b/src/google/protobuf/compiler/annotation_test_util.cc
new file mode 100644
index 00000000..aa14faf6
--- /dev/null
+++ b/src/google/protobuf/compiler/annotation_test_util.cc
@@ -0,0 +1,187 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#include <google/protobuf/compiler/annotation_test_util.h>
+
+#include <memory>
+#ifndef _SHARED_PTR_H
+#include <google/protobuf/stubs/shared_ptr.h>
+#endif
+#include <google/protobuf/compiler/code_generator.h>
+#include <google/protobuf/compiler/command_line_interface.h>
+#include <google/protobuf/io/printer.h>
+#include <google/protobuf/io/zero_copy_stream.h>
+#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
+#include <google/protobuf/descriptor.pb.h>
+
+#include <google/protobuf/testing/file.h>
+#include <google/protobuf/testing/file.h>
+#include <google/protobuf/testing/googletest.h>
+#include <gtest/gtest.h>
+
+namespace google {
+namespace protobuf {
+namespace compiler {
+namespace annotation_test_util {
+namespace {
+
+// A CodeGenerator that captures the FileDescriptor it's passed as a
+// FileDescriptorProto.
+class DescriptorCapturingGenerator : public CodeGenerator {
+ public:
+ // Does not own file; file must outlive the Generator.
+ explicit DescriptorCapturingGenerator(FileDescriptorProto* file)
+ : file_(file) {}
+
+ virtual bool Generate(const FileDescriptor* file, const string& parameter,
+ GeneratorContext* context, string* error) const {
+ file->CopyTo(file_);
+ return true;
+ }
+
+ private:
+ FileDescriptorProto* file_;
+};
+} // namespace
+
+void AddFile(const string& filename, const string& data) {
+ GOOGLE_CHECK_OK(File::SetContents(TestTempDir() + "/" + filename, data,
+ true));
+}
+
+bool CaptureMetadata(const string& filename, const string& plugin_specific_args,
+ const string& meta_file_suffix, CommandLineInterface* cli,
+ FileDescriptorProto* file,
+ std::vector<ExpectedOutput>* outputs) {
+ cli->SetInputsAreProtoPathRelative(true);
+
+ DescriptorCapturingGenerator capturing_generator(file);
+ cli->RegisterGenerator("--capture_out", &capturing_generator, "");
+
+ string proto_path = "-I" + TestTempDir();
+ string capture_out = "--capture_out=" + TestTempDir();
+
+ const char* argv[] = {"protoc", proto_path.c_str(),
+ plugin_specific_args.c_str(), capture_out.c_str(),
+ filename.c_str()};
+
+ if (cli->Run(5, argv) != 0) {
+ return false;
+ }
+
+ if (outputs != NULL) {
+ for (std::vector<ExpectedOutput>::iterator i = outputs->begin();
+ i != outputs->end(); ++i) {
+ GOOGLE_CHECK_OK(File::GetContents(TestTempDir() + "/" + i->file_path,
+ &i->file_content, true));
+ if (!DecodeMetadata(
+ TestTempDir() + "/" + i->file_path + meta_file_suffix,
+ &i->file_info)) {
+ return false;
+ }
+ }
+ }
+
+ return true;
+}
+
+bool DecodeMetadata(const string& path, GeneratedCodeInfo* info) {
+ string data;
+ GOOGLE_CHECK_OK(File::GetContents(path, &data, true));
+ io::ArrayInputStream input(data.data(), data.size());
+ return info->ParseFromZeroCopyStream(&input);
+}
+
+void FindAnnotationsOnPath(
+ const GeneratedCodeInfo& info, const string& source_file,
+ const std::vector<int>& path,
+ std::vector<const GeneratedCodeInfo::Annotation*>* annotations) {
+ for (int i = 0; i < info.annotation_size(); ++i) {
+ const GeneratedCodeInfo::Annotation* annotation = &info.annotation(i);
+ if (annotation->source_file() != source_file ||
+ annotation->path_size() != path.size()) {
+ continue;
+ }
+ int node = 0;
+ for (; node < path.size(); ++node) {
+ if (annotation->path(node) != path[node]) {
+ break;
+ }
+ }
+ if (node == path.size()) {
+ annotations->push_back(annotation);
+ }
+ }
+}
+
+const GeneratedCodeInfo::Annotation* FindAnnotationOnPath(
+ const GeneratedCodeInfo& info, const string& source_file,
+ const std::vector<int>& path) {
+ std::vector<const GeneratedCodeInfo::Annotation*> annotations;
+ FindAnnotationsOnPath(info, source_file, path, &annotations);
+ if (annotations.empty()) {
+ return NULL;
+ }
+ return annotations[0];
+}
+
+bool AtLeastOneAnnotationMatchesSubstring(
+ const string& file_content,
+ const std::vector<const GeneratedCodeInfo::Annotation*>& annotations,
+ const string& expected_text) {
+ for (std::vector<const GeneratedCodeInfo::Annotation*>::const_iterator
+ i = annotations.begin(),
+ e = annotations.end();
+ i != e; ++i) {
+ const GeneratedCodeInfo::Annotation* annotation = *i;
+ uint32 begin = annotation->begin();
+ uint32 end = annotation->end();
+ if (end < begin || end > file_content.size()) {
+ return false;
+ }
+ if (file_content.substr(begin, end - begin) == expected_text) {
+ return true;
+ }
+ }
+ return false;
+}
+
+bool AnnotationMatchesSubstring(const string& file_content,
+ const GeneratedCodeInfo::Annotation* annotation,
+ const string& expected_text) {
+ std::vector<const GeneratedCodeInfo::Annotation*> annotations;
+ annotations.push_back(annotation);
+ return AtLeastOneAnnotationMatchesSubstring(file_content, annotations,
+ expected_text);
+}
+} // namespace annotation_test_util
+} // namespace compiler
+} // namespace protobuf
+} // namespace google
diff --git a/src/google/protobuf/compiler/annotation_test_util.h b/src/google/protobuf/compiler/annotation_test_util.h
new file mode 100644
index 00000000..4598a45a
--- /dev/null
+++ b/src/google/protobuf/compiler/annotation_test_util.h
@@ -0,0 +1,119 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#ifndef GOOGLE_PROTOBUF_COMPILER_ANNOTATION_TEST_UTIL_H__
+#define GOOGLE_PROTOBUF_COMPILER_ANNOTATION_TEST_UTIL_H__
+
+#include <google/protobuf/descriptor.pb.h>
+#include <google/protobuf/testing/googletest.h>
+#include <gtest/gtest.h>
+
+// Utilities that assist in writing tests for generator annotations.
+// See java/internal/annotation_unittest.cc for an example.
+namespace google {
+namespace protobuf {
+namespace compiler {
+namespace annotation_test_util {
+
+// Struct that contains the file generated from a .proto file and its
+// GeneratedCodeInfo. For example, the Java generator will fill this struct
+// (for some 'foo.proto') with:
+// file_path = "Foo.java"
+// file_content = content of Foo.java
+// file_info = parsed content of Foo.java.pb.meta
+struct ExpectedOutput {
+ string file_path;
+ string file_content;
+ GeneratedCodeInfo file_info;
+ explicit ExpectedOutput(const string& file_path) : file_path(file_path) {}
+};
+
+// Creates a file with name `filename` and content `data` in temp test
+// directory.
+void AddFile(const string& filename, const string& data);
+
+// Tries to capture a FileDescriptorProto, GeneratedCodeInfo, and output
+// code from the previously added file with name `filename`.
+//
+// filename: source .proto file used to generate code.
+// plugin_specific_args: command line arguments specific to current generator.
+// For Java, this value might be "--java_out=annotate_code:test_temp_dir"
+// meta_file_suffix: suffix of meta files that contain annotations. For Java
+// it is ".pb.meta" because for file Foo.java meta file is Foo.java.pb.meta
+// cli: instance of command line interface to run generator. See Java's
+// annotation_unittest.cc for an example of how to initialize it.
+// file: output parameter, will be set to the descriptor of the proto file
+// specified in filename.
+// outputs: output parameter. If not NULL, each ExpectedOutput in the vector
+// should have its file_path set; CaptureMetadata will fill the rest of
+// the fields appropriately.
+bool CaptureMetadata(const string& filename, const string& plugin_specific_args,
+ const string& meta_file_suffix, CommandLineInterface* cli,
+ FileDescriptorProto* file,
+ std::vector<ExpectedOutput>* outputs);
+
+bool DecodeMetadata(const string& path, GeneratedCodeInfo* info);
+
+// Finds all of the Annotations for a given source file and path.
+// See Location.path in http://google/protobuf/descriptor.proto for
+// explanation of what path vector is.
+void FindAnnotationsOnPath(
+ const GeneratedCodeInfo& info, const string& source_file,
+ const std::vector<int>& path,
+ std::vector<const GeneratedCodeInfo::Annotation*>* annotations);
+
+// Finds the Annotation for a given source file and path (or returns null if it
+// couldn't). If there are several annotations for given path, returns the first
+// one. See Location.path in
+// http://google/protobuf/descriptor.proto for explanation of what path
+// vector is.
+const GeneratedCodeInfo::Annotation* FindAnnotationOnPath(
+ const GeneratedCodeInfo& info, const string& source_file,
+ const std::vector<int>& path);
+
+// Returns true if at least one of the provided annotations covers a given
+// substring in file_content.
+bool AtLeastOneAnnotationMatchesSubstring(
+ const string& file_content,
+ const std::vector<const GeneratedCodeInfo::Annotation*>& annotations,
+ const string& expected_text);
+
+// Returns true if the provided annotation covers a given substring in
+// file_content.
+bool AnnotationMatchesSubstring(const string& file_content,
+ const GeneratedCodeInfo::Annotation* annotation,
+ const string& expected_text);
+
+} // namespace annotation_test_util
+} // namespace compiler
+} // namespace protobuf
+
+} // namespace google
+#endif // GOOGLE_PROTOBUF_COMPILER_ANNOTATION_TEST_UTIL_H__
diff --git a/src/google/protobuf/compiler/code_generator.h b/src/google/protobuf/compiler/code_generator.h
index e2b2a661..4c2b3ee1 100644
--- a/src/google/protobuf/compiler/code_generator.h
+++ b/src/google/protobuf/compiler/code_generator.h
@@ -50,6 +50,8 @@ namespace io { class ZeroCopyOutputStream; }
class FileDescriptor;
namespace compiler {
+class AccessInfoMap;
+
class Version;
// Defined in this file.
@@ -112,7 +114,8 @@ class LIBPROTOC_EXPORT CodeGenerator {
// runs.
class LIBPROTOC_EXPORT GeneratorContext {
public:
- inline GeneratorContext() {}
+ inline GeneratorContext() {
+ }
virtual ~GeneratorContext();
// Opens the given file, truncating it if it exists, and returns a
@@ -148,6 +151,7 @@ class LIBPROTOC_EXPORT GeneratorContext {
// this GeneratorContext.
virtual void GetCompilerVersion(Version* version) const;
+
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(GeneratorContext);
};
@@ -162,8 +166,8 @@ typedef GeneratorContext OutputDirectory;
// "foo=bar,baz,qux=corge"
// parses to the pairs:
// ("foo", "bar"), ("baz", ""), ("qux", "corge")
-extern void LIBPROTOC_EXPORT ParseGeneratorParameter(const string&,
- std::vector<std::pair<string, string> >*);
+LIBPROTOC_EXPORT void ParseGeneratorParameter(
+ const string&, std::vector<std::pair<string, string> >*);
} // namespace compiler
} // namespace protobuf
diff --git a/src/google/protobuf/compiler/command_line_interface.cc b/src/google/protobuf/compiler/command_line_interface.cc
index bef0fe5a..6c2fc164 100644
--- a/src/google/protobuf/compiler/command_line_interface.cc
+++ b/src/google/protobuf/compiler/command_line_interface.cc
@@ -33,16 +33,21 @@
// Sanjay Ghemawat, Jeff Dean, and others.
#include <google/protobuf/compiler/command_line_interface.h>
+
+
#include <google/protobuf/stubs/platform_macros.h>
#include <stdio.h>
#include <sys/types.h>
+#ifdef major
+#undef major
+#endif
+#ifdef minor
+#undef minor
+#endif
#include <sys/stat.h>
#include <fcntl.h>
-#ifdef _MSC_VER
-#include <io.h>
-#include <direct.h>
-#else
+#ifndef _MSC_VER
#include <unistd.h>
#endif
#include <errno.h>
@@ -62,45 +67,30 @@
#endif
#include <google/protobuf/stubs/common.h>
+#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/stringprintf.h>
-#include <google/protobuf/compiler/importer.h>
-#include <google/protobuf/compiler/code_generator.h>
-#include <google/protobuf/compiler/plugin.pb.h>
#include <google/protobuf/compiler/subprocess.h>
#include <google/protobuf/compiler/zip_writer.h>
-#include <google/protobuf/descriptor.h>
-#include <google/protobuf/text_format.h>
-#include <google/protobuf/dynamic_message.h>
+#include <google/protobuf/compiler/plugin.pb.h>
+#include <google/protobuf/compiler/code_generator.h>
+#include <google/protobuf/compiler/importer.h>
#include <google/protobuf/io/coded_stream.h>
-#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/io/printer.h>
-#include <google/protobuf/stubs/logging.h>
+#include <google/protobuf/io/zero_copy_stream_impl.h>
+#include <google/protobuf/descriptor.h>
+#include <google/protobuf/dynamic_message.h>
+#include <google/protobuf/text_format.h>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/substitute.h>
#include <google/protobuf/stubs/map_util.h>
#include <google/protobuf/stubs/stl_util.h>
+#include <google/protobuf/stubs/io_win32.h>
namespace google {
namespace protobuf {
namespace compiler {
-#if defined(_WIN32)
-#define mkdir(name, mode) mkdir(name)
-#ifndef W_OK
-#define W_OK 02 // not defined by MSVC for whatever reason
-#endif
-#ifndef F_OK
-#define F_OK 00 // not defined by MSVC for whatever reason
-#endif
-#ifndef STDIN_FILENO
-#define STDIN_FILENO 0
-#endif
-#ifndef STDOUT_FILENO
-#define STDOUT_FILENO 1
-#endif
-#endif
-
#ifndef O_BINARY
#ifdef _O_BINARY
#define O_BINARY _O_BINARY
@@ -110,12 +100,20 @@ namespace compiler {
#endif
namespace {
-#if defined(_WIN32) && !defined(__CYGWIN__)
-static const char* kPathSeparator = ";";
-#else
-static const char* kPathSeparator = ":";
+#if defined(_MSC_VER)
+// DO NOT include <io.h>, instead create functions in io_win32.{h,cc} and import
+// them like we do below.
+using google::protobuf::internal::win32::access;
+using google::protobuf::internal::win32::close;
+using google::protobuf::internal::win32::mkdir;
+using google::protobuf::internal::win32::open;
+using google::protobuf::internal::win32::setmode;
+using google::protobuf::internal::win32::write;
#endif
+static const char* kDefaultDirectDependenciesViolationMsg =
+ "File is imported but not declared in --direct_dependencies: %s";
+
// Returns true if the text looks like a Windows-style absolute path, starting
// with a drive letter. Example: "C:\foo". TODO(kenton): Share this with
// copy in importer.cc?
@@ -132,9 +130,9 @@ static bool IsWindowsAbsolutePath(const string& text) {
void SetFdToTextMode(int fd) {
#ifdef _WIN32
- if (_setmode(fd, _O_TEXT) == -1) {
+ if (setmode(fd, _O_TEXT) == -1) {
// This should never happen, I think.
- GOOGLE_LOG(WARNING) << "_setmode(" << fd << ", _O_TEXT): " << strerror(errno);
+ GOOGLE_LOG(WARNING) << "setmode(" << fd << ", _O_TEXT): " << strerror(errno);
}
#endif
// (Text and binary are the same on non-Windows platforms.)
@@ -142,9 +140,9 @@ void SetFdToTextMode(int fd) {
void SetFdToBinaryMode(int fd) {
#ifdef _WIN32
- if (_setmode(fd, _O_BINARY) == -1) {
+ if (setmode(fd, _O_BINARY) == -1) {
// This should never happen, I think.
- GOOGLE_LOG(WARNING) << "_setmode(" << fd << ", _O_BINARY): " << strerror(errno);
+ GOOGLE_LOG(WARNING) << "setmode(" << fd << ", _O_BINARY): " << strerror(errno);
}
#endif
// (Text and binary are the same on non-Windows platforms.)
@@ -226,7 +224,7 @@ bool IsInstalledProtoPath(const string& path) {
return access(file_path.c_str(), F_OK) != -1;
}
-// Add the paths where google/protobuf/descritor.proto and other well-known
+// Add the paths where google/protobuf/descriptor.proto and other well-known
// type protos are installed.
void AddDefaultProtoPaths(vector<pair<string, string> >* paths) {
// TODO(xiaofeng): The code currently only checks relative paths of where
@@ -269,19 +267,23 @@ string PluginName(const string& plugin_prefix, const string& directive) {
// strip the "--" and "_out/_opt" and add the plugin prefix.
return plugin_prefix + "gen-" + directive.substr(2, directive.size() - 6);
}
+
} // namespace
// A MultiFileErrorCollector that prints errors to stderr.
-class CommandLineInterface::ErrorPrinter : public MultiFileErrorCollector,
- public io::ErrorCollector {
+class CommandLineInterface::ErrorPrinter
+ : public MultiFileErrorCollector,
+ public io::ErrorCollector,
+ public DescriptorPool::ErrorCollector {
public:
ErrorPrinter(ErrorFormat format, DiskSourceTree *tree = NULL)
- : format_(format), tree_(tree) {}
+ : format_(format), tree_(tree), found_errors_(false) {}
~ErrorPrinter() {}
// implements MultiFileErrorCollector ------------------------------
void AddError(const string& filename, int line, int column,
const string& message) {
+ found_errors_ = true;
AddErrorOrWarning(filename, line, column, message, "error", std::cerr);
}
@@ -299,10 +301,31 @@ class CommandLineInterface::ErrorPrinter : public MultiFileErrorCollector,
AddErrorOrWarning("input", line, column, message, "warning", std::clog);
}
+ // implements DescriptorPool::ErrorCollector-------------------------
+ void AddError(
+ const string& filename,
+ const string& element_name,
+ const Message* descriptor,
+ ErrorLocation location,
+ const string& message) {
+ AddErrorOrWarning(filename, -1, -1, message, "error", std::cerr);
+ }
+
+ void AddWarning(
+ const string& filename,
+ const string& element_name,
+ const Message* descriptor,
+ ErrorLocation location,
+ const string& message) {
+ AddErrorOrWarning(filename, -1, -1, message, "warning", std::clog);
+ }
+
+ bool FoundErrors() const { return found_errors_; }
+
private:
- void AddErrorOrWarning(
- const string& filename, int line, int column,
- const string& message, const string& type, ostream& out) {
+ void AddErrorOrWarning(const string& filename, int line, int column,
+ const string& message, const string& type,
+ std::ostream& out) {
// Print full path when running under MSVS
string dfile;
if (format_ == CommandLineInterface::ERROR_FORMAT_MSVS &&
@@ -337,6 +360,7 @@ class CommandLineInterface::ErrorPrinter : public MultiFileErrorCollector,
const ErrorFormat format_;
DiskSourceTree *tree_;
+ bool found_errors_;
};
// -------------------------------------------------------------------
@@ -397,6 +421,13 @@ class CommandLineInterface::MemoryOutputStream
virtual int64 ByteCount() const { return inner_->ByteCount(); }
private:
+ // Checks to see if "filename_.meta" exists in directory_; if so, fixes the
+ // offsets in that GeneratedCodeInfo record to reflect bytes inserted in
+ // filename_ at original offset insertion_offset with length insertion_length.
+ // We assume that insertions will not occur within any given annotated span
+ // of text.
+ void UpdateMetadata(size_t insertion_offset, size_t insertion_length);
+
// Where to insert the string when it's done.
GeneratorContextImpl* directory_;
string filename_;
@@ -417,8 +448,7 @@ class CommandLineInterface::MemoryOutputStream
CommandLineInterface::GeneratorContextImpl::GeneratorContextImpl(
const std::vector<const FileDescriptor*>& parsed_files)
: parsed_files_(parsed_files),
- had_error_(false) {
-}
+ had_error_(false) {}
CommandLineInterface::GeneratorContextImpl::~GeneratorContextImpl() {
STLDeleteValues(&files_);
@@ -594,6 +624,44 @@ CommandLineInterface::MemoryOutputStream::MemoryOutputStream(
inner_(new io::StringOutputStream(&data_)) {
}
+void CommandLineInterface::MemoryOutputStream::UpdateMetadata(
+ size_t insertion_offset, size_t insertion_length) {
+ std::map<string, string*>::iterator meta_file =
+ directory_->files_.find(filename_ + ".meta");
+ if (meta_file == directory_->files_.end() || !meta_file->second) {
+ // No metadata was recorded for this file.
+ return;
+ }
+ string* encoded_data = meta_file->second;
+ GeneratedCodeInfo metadata;
+ bool is_text_format = false;
+ if (!metadata.ParseFromString(*encoded_data)) {
+ if (!TextFormat::ParseFromString(*encoded_data, &metadata)) {
+ // The metadata is invalid.
+ std::cerr << filename_
+ << ".meta: Could not parse metadata as wire or text format."
+ << std::endl;
+ return;
+ }
+ // Generators that use the public plugin interface emit text-format
+ // metadata (because in the public plugin protocol, file content must be
+ // UTF8-encoded strings).
+ is_text_format = true;
+ }
+ for (int i = 0; i < metadata.annotation_size(); ++i) {
+ GeneratedCodeInfo::Annotation* annotation = metadata.mutable_annotation(i);
+ if (annotation->begin() >= insertion_offset) {
+ annotation->set_begin(annotation->begin() + insertion_length);
+ annotation->set_end(annotation->end() + insertion_length);
+ }
+ }
+ if (is_text_format) {
+ TextFormat::PrintToString(metadata, encoded_data);
+ } else {
+ metadata.SerializeToString(encoded_data);
+ }
+}
+
CommandLineInterface::MemoryOutputStream::~MemoryOutputStream() {
// Make sure all data has been written.
inner_.reset();
@@ -671,6 +739,7 @@ CommandLineInterface::MemoryOutputStream::~MemoryOutputStream() {
if (indent_.empty()) {
// No indent. This makes things easier.
target->insert(pos, data_);
+ UpdateMetadata(pos, data_.size());
} else {
// Calculate how much space we need.
int indent_size = 0;
@@ -680,6 +749,7 @@ CommandLineInterface::MemoryOutputStream::~MemoryOutputStream() {
// Make a hole for it.
target->insert(pos, data_.size() + indent_size, '\0');
+ UpdateMetadata(pos, data_.size() + indent_size);
// Now copy in the data.
string::size_type data_pos = 0;
@@ -707,15 +777,22 @@ CommandLineInterface::MemoryOutputStream::~MemoryOutputStream() {
// ===================================================================
+#if defined(_WIN32) && !defined(__CYGWIN__)
+const char* const CommandLineInterface::kPathSeparator = ";";
+#else
+const char* const CommandLineInterface::kPathSeparator = ":";
+#endif
+
CommandLineInterface::CommandLineInterface()
- : mode_(MODE_COMPILE),
- print_mode_(PRINT_NONE),
- error_format_(ERROR_FORMAT_GCC),
- direct_dependencies_explicitly_set_(false),
- imports_in_descriptor_set_(false),
- source_info_in_descriptor_set_(false),
- disallow_services_(false),
- inputs_are_proto_path_relative_(false) {}
+ : mode_(MODE_COMPILE),
+ print_mode_(PRINT_NONE),
+ error_format_(ERROR_FORMAT_GCC),
+ direct_dependencies_explicitly_set_(false),
+ direct_dependencies_violation_msg_(
+ kDefaultDirectDependenciesViolationMsg),
+ imports_in_descriptor_set_(false),
+ source_info_in_descriptor_set_(false),
+ disallow_services_(false) {}
CommandLineInterface::~CommandLineInterface() {}
void CommandLineInterface::RegisterGenerator(const string& flag_name,
@@ -756,61 +833,41 @@ int CommandLineInterface::Run(int argc, const char* const argv[]) {
break;
}
- AddDefaultProtoPaths(&proto_path_);
-
- // Set up the source tree.
- DiskSourceTree source_tree;
- for (int i = 0; i < proto_path_.size(); i++) {
- source_tree.MapPath(proto_path_[i].first, proto_path_[i].second);
- }
-
- // Map input files to virtual paths if necessary.
- if (!inputs_are_proto_path_relative_) {
- if (!MakeInputsBeProtoPathRelative(&source_tree)) {
+ std::vector<const FileDescriptor*> parsed_files;
+ // null unless descriptor_set_in_names_.empty()
+ google::protobuf::scoped_ptr<DiskSourceTree> disk_source_tree;
+ google::protobuf::scoped_ptr<ErrorPrinter> error_collector;
+ google::protobuf::scoped_ptr<DescriptorPool> descriptor_pool;
+ google::protobuf::scoped_ptr<DescriptorDatabase> descriptor_database;
+ if (descriptor_set_in_names_.empty()) {
+ disk_source_tree.reset(new DiskSourceTree());
+ if (!InitializeDiskSourceTree(disk_source_tree.get())) {
return 1;
}
- }
+ error_collector.reset(
+ new ErrorPrinter(error_format_, disk_source_tree.get()));
- // Allocate the Importer.
- ErrorPrinter error_collector(error_format_, &source_tree);
- Importer importer(&source_tree, &error_collector);
-
- std::vector<const FileDescriptor*> parsed_files;
-
- // Parse each file.
- for (int i = 0; i < input_files_.size(); i++) {
- // Import the file.
- importer.AddUnusedImportTrackFile(input_files_[i]);
- const FileDescriptor* parsed_file = importer.Import(input_files_[i]);
- importer.ClearUnusedImportTrackFiles();
- if (parsed_file == NULL) return 1;
- parsed_files.push_back(parsed_file);
+ SourceTreeDescriptorDatabase* database =
+ new SourceTreeDescriptorDatabase(disk_source_tree.get());
+ database->RecordErrorsTo(error_collector.get());
+ descriptor_database.reset(database);
+ descriptor_pool.reset(new DescriptorPool(
+ descriptor_database.get(), database->GetValidationErrorCollector()));
+ } else {
+ error_collector.reset(new ErrorPrinter(error_format_));
- // Enforce --disallow_services.
- if (disallow_services_ && parsed_file->service_count() > 0) {
- cerr << parsed_file->name() << ": This file contains services, but "
- "--disallow_services was used." << endl;
+ SimpleDescriptorDatabase* database = new SimpleDescriptorDatabase();
+ descriptor_database.reset(database);
+ if (!PopulateSimpleDescriptorDatabase(database)) {
return 1;
}
-
- // Enforce --direct_dependencies
- if (direct_dependencies_explicitly_set_) {
- bool indirect_imports = false;
- for (int i = 0; i < parsed_file->dependency_count(); i++) {
- if (direct_dependencies_.find(parsed_file->dependency(i)->name()) ==
- direct_dependencies_.end()) {
- indirect_imports = true;
- cerr << parsed_file->name()
- << ": File is imported but not declared in "
- << "--direct_dependencies: "
- << parsed_file->dependency(i)->name() << std::endl;
- }
- }
- if (indirect_imports) {
- return 1;
- }
- }
+ descriptor_pool.reset(new DescriptorPool(database, error_collector.get()));
}
+ descriptor_pool->EnforceWeakDependencies(true);
+ if (!ParseInputFiles(descriptor_pool.get(), &parsed_files)) {
+ return 1;
+ }
+
// We construct a separate GeneratorContext for each output location. Note
// that two code generators may output to the same location, in which case
@@ -862,15 +919,16 @@ int CommandLineInterface::Run(int argc, const char* const argv[]) {
}
if (!dependency_out_name_.empty()) {
+ GOOGLE_DCHECK(disk_source_tree.get());
if (!GenerateDependencyManifestFile(parsed_files, output_directories,
- &source_tree)) {
+ disk_source_tree.get())) {
return 1;
}
}
STLDeleteValues(&output_directories);
- if (!descriptor_set_name_.empty()) {
+ if (!descriptor_set_out_name_.empty()) {
if (!WriteDescriptorSet(parsed_files)) {
return 1;
}
@@ -889,12 +947,16 @@ int CommandLineInterface::Run(int argc, const char* const argv[]) {
return 1;
}
} else {
- if (!EncodeOrDecode(importer.pool())) {
+ if (!EncodeOrDecode(descriptor_pool.get())) {
return 1;
}
}
}
+ if (error_collector->FoundErrors()) {
+ return 1;
+ }
+
if (mode_ == MODE_PRINT) {
switch (print_mode_) {
case PRINT_FREE_FIELDS:
@@ -907,7 +969,7 @@ int CommandLineInterface::Run(int argc, const char* const argv[]) {
break;
case PRINT_NONE:
GOOGLE_LOG(ERROR) << "If the code reaches here, it usually means a bug of "
- "flag parsing in the CommonadLineInterface.";
+ "flag parsing in the CommandLineInterface.";
return 1;
// Do not add a default case.
@@ -917,6 +979,113 @@ int CommandLineInterface::Run(int argc, const char* const argv[]) {
return 0;
}
+bool CommandLineInterface::InitializeDiskSourceTree(
+ DiskSourceTree* source_tree) {
+ AddDefaultProtoPaths(&proto_path_);
+
+ // Set up the source tree.
+ for (int i = 0; i < proto_path_.size(); i++) {
+ source_tree->MapPath(proto_path_[i].first, proto_path_[i].second);
+ }
+
+ // Map input files to virtual paths if possible.
+ if (!MakeInputsBeProtoPathRelative(source_tree)) {
+ return false;
+ }
+ return true;
+}
+
+bool CommandLineInterface::PopulateSimpleDescriptorDatabase(
+ SimpleDescriptorDatabase* database) {
+ for (int i = 0; i < descriptor_set_in_names_.size(); i++) {
+ int fd;
+ do {
+ fd = open(descriptor_set_in_names_[i].c_str(), O_RDONLY | O_BINARY);
+ } while (fd < 0 && errno == EINTR);
+ if (fd < 0) {
+ std::cerr << descriptor_set_in_names_[i] << ": "
+ << strerror(ENOENT) << std::endl;
+ return false;
+ }
+
+ FileDescriptorSet file_descriptor_set;
+ bool parsed = file_descriptor_set.ParseFromFileDescriptor(fd);
+ if (close(fd) != 0) {
+ std::cerr << descriptor_set_in_names_[i] << ": close: "
+ << strerror(errno)
+ << std::endl;
+ return false;
+ }
+
+ if (!parsed) {
+ std::cerr << descriptor_set_in_names_[i] << ": Unable to parse."
+ << std::endl;
+ return false;
+ }
+
+ for (int j = 0; j < file_descriptor_set.file_size(); j++) {
+ FileDescriptorProto previously_added_file_descriptor_proto;
+ if (database->FindFileByName(file_descriptor_set.file(j).name(),
+ &previously_added_file_descriptor_proto)) {
+ // already present - skip
+ continue;
+ }
+ if (!database->Add(file_descriptor_set.file(j))) {
+ return false;
+ }
+ }
+ }
+ return true;
+}
+
+bool CommandLineInterface::ParseInputFiles(
+ DescriptorPool* descriptor_pool,
+ std::vector<const FileDescriptor*>* parsed_files) {
+
+ // Parse each file.
+ for (int i = 0; i < input_files_.size(); i++) {
+ // Import the file.
+ descriptor_pool->AddUnusedImportTrackFile(input_files_[i]);
+ const FileDescriptor* parsed_file =
+ descriptor_pool->FindFileByName(input_files_[i]);
+ descriptor_pool->ClearUnusedImportTrackFiles();
+ if (parsed_file == NULL) {
+ if (!descriptor_set_in_names_.empty()) {
+ std::cerr << input_files_[i] << ": " << strerror(ENOENT) << std::endl;
+ }
+ return false;
+ }
+ parsed_files->push_back(parsed_file);
+
+ // Enforce --disallow_services.
+ if (disallow_services_ && parsed_file->service_count() > 0) {
+ std::cerr << parsed_file->name() << ": This file contains services, but "
+ "--disallow_services was used." << std::endl;
+ return false;
+ }
+
+ // Enforce --direct_dependencies
+ if (direct_dependencies_explicitly_set_) {
+ bool indirect_imports = false;
+ for (int i = 0; i < parsed_file->dependency_count(); i++) {
+ if (direct_dependencies_.find(parsed_file->dependency(i)->name()) ==
+ direct_dependencies_.end()) {
+ indirect_imports = true;
+ std::cerr << parsed_file->name() << ": "
+ << StringReplace(direct_dependencies_violation_msg_, "%s",
+ parsed_file->dependency(i)->name(),
+ true /* replace_all */)
+ << std::endl;
+ }
+ }
+ if (indirect_imports) {
+ return false;
+ }
+ }
+ }
+ return true;
+}
+
void CommandLineInterface::Clear() {
// Clear all members that are set by Run(). Note that we must not clear
// members which are set by other methods before Run() is called.
@@ -924,9 +1093,11 @@ void CommandLineInterface::Clear() {
proto_path_.clear();
input_files_.clear();
direct_dependencies_.clear();
+ direct_dependencies_violation_msg_ = kDefaultDirectDependenciesViolationMsg;
output_directives_.clear();
codec_type_.clear();
- descriptor_set_name_.clear();
+ descriptor_set_in_names_.clear();
+ descriptor_set_out_name_.clear();
dependency_out_name_.clear();
mode_ = MODE_COMPILE;
@@ -940,6 +1111,17 @@ void CommandLineInterface::Clear() {
bool CommandLineInterface::MakeInputsBeProtoPathRelative(
DiskSourceTree* source_tree) {
for (int i = 0; i < input_files_.size(); i++) {
+ // If the input file path is not a physical file path, it must be a virtual
+ // path.
+ if (access(input_files_[i].c_str(), F_OK) < 0) {
+ string disk_file;
+ if (source_tree->VirtualFileToDiskFile(input_files_[i], &disk_file)) {
+ return true;
+ } else {
+ std::cerr << input_files_[i] << ": " << strerror(ENOENT) << std::endl;
+ return false;
+ }
+ }
string virtual_file, shadowing_disk_file;
switch (source_tree->DiskFileToVirtualFile(
input_files_[i], &virtual_file, &shadowing_disk_file)) {
@@ -957,12 +1139,14 @@ bool CommandLineInterface::MakeInputsBeProtoPathRelative(
case DiskSourceTree::CANNOT_OPEN:
std::cerr << input_files_[i] << ": " << strerror(errno) << std::endl;
return false;
- case DiskSourceTree::NO_MAPPING:
- // First check if the file exists at all.
- if (access(input_files_[i].c_str(), F_OK) < 0) {
- // File does not even exist.
- std::cerr << input_files_[i] << ": " << strerror(ENOENT) << std::endl;
+ case DiskSourceTree::NO_MAPPING: {
+ // Try to interpret the path as a virtual path.
+ string disk_file;
+ if (source_tree->VirtualFileToDiskFile(input_files_[i], &disk_file)) {
+ return true;
} else {
+ // The input file path can't be mapped to any --proto_path and it also
+ // can't be interpreted as a virtual path.
std::cerr
<< input_files_[i]
<< ": File does not reside within any path "
@@ -971,15 +1155,32 @@ bool CommandLineInterface::MakeInputsBeProtoPathRelative(
"proto_path must be an exact prefix of the .proto file "
"names -- protoc is too dumb to figure out when two paths "
"(e.g. absolute and relative) are equivalent (it's harder "
- "than you think)." << std::endl;
+ "than you think)."
+ << std::endl;
+ return false;
}
- return false;
+ }
}
}
return true;
}
+bool CommandLineInterface::ExpandArgumentFile(const string& file,
+ std::vector<string>* arguments) {
+ // The argument file is searched in the working directory only. We don't
+ // use the proto import path here.
+ std::ifstream file_stream(file.c_str());
+ if (!file_stream.is_open()) {
+ return false;
+ }
+ string argument;
+ // We don't support any kind of shell expansion right now.
+ while (std::getline(file_stream, argument)) {
+ arguments->push_back(argument);
+ }
+ return true;
+}
CommandLineInterface::ParseArgumentStatus
CommandLineInterface::ParseArguments(int argc, const char* const argv[]) {
@@ -987,9 +1188,23 @@ CommandLineInterface::ParseArguments(int argc, const char* const argv[]) {
std::vector<string> arguments;
for (int i = 1; i < argc; ++i) {
+ if (argv[i][0] == '@') {
+ if (!ExpandArgumentFile(argv[i] + 1, &arguments)) {
+ std::cerr << "Failed to open argument file: " << (argv[i] + 1)
+ << std::endl;
+ return PARSE_ARGUMENT_FAIL;
+ }
+ continue;
+ }
arguments.push_back(argv[i]);
}
+ // if no arguments are given, show help
+ if (arguments.empty()) {
+ PrintHelpText();
+ return PARSE_ARGUMENT_DONE_AND_EXIT; // Exit without running compiler.
+ }
+
// Iterate through all arguments and parse them.
for (int i = 0; i < arguments.size(); ++i) {
string name, value;
@@ -1015,16 +1230,34 @@ CommandLineInterface::ParseArguments(int argc, const char* const argv[]) {
}
// Make sure each plugin option has a matching plugin output.
- for (map<string, string>::const_iterator i = plugin_parameters_.begin();
+ bool foundUnknownPluginOption = false;
+ for (std::map<string, string>::const_iterator i = plugin_parameters_.begin();
i != plugin_parameters_.end(); ++i) {
- if (plugins_.find(i->first) == plugins_.end()) {
+ if (plugins_.find(i->first) != plugins_.end()) {
+ continue;
+ }
+ bool foundImplicitPlugin = false;
+ for (std::vector<OutputDirective>::const_iterator j = output_directives_.begin();
+ j != output_directives_.end(); ++j) {
+ if (j->generator == NULL) {
+ string plugin_name = PluginName(plugin_prefix_ , j->name);
+ if (plugin_name == i->first) {
+ foundImplicitPlugin = true;
+ break;
+ }
+ }
+ }
+ if (!foundImplicitPlugin) {
std::cerr << "Unknown flag: "
// strip prefix + "gen-" and add back "_opt"
<< "--" + i->first.substr(plugin_prefix_.size() + 4) + "_opt"
<< std::endl;
- return PARSE_ARGUMENT_FAIL;
+ foundUnknownPluginOption = true;
}
}
+ if (foundUnknownPluginOption) {
+ return PARSE_ARGUMENT_FAIL;
+ }
// If no --proto_path was given, use the current working directory.
if (proto_path_.empty()) {
@@ -1045,7 +1278,7 @@ CommandLineInterface::ParseArguments(int argc, const char* const argv[]) {
return PARSE_ARGUMENT_FAIL;
}
if (mode_ == MODE_COMPILE && output_directives_.empty() &&
- descriptor_set_name_.empty()) {
+ descriptor_set_out_name_.empty()) {
std::cerr << "Missing output directives." << std::endl;
return PARSE_ARGUMENT_FAIL;
}
@@ -1060,11 +1293,11 @@ CommandLineInterface::ParseArguments(int argc, const char* const argv[]) {
<< std::endl;
return PARSE_ARGUMENT_FAIL;
}
- if (imports_in_descriptor_set_ && descriptor_set_name_.empty()) {
+ if (imports_in_descriptor_set_ && descriptor_set_out_name_.empty()) {
std::cerr << "--include_imports only makes sense when combined with "
"--descriptor_set_out." << std::endl;
}
- if (source_info_in_descriptor_set_ && descriptor_set_name_.empty()) {
+ if (source_info_in_descriptor_set_ && descriptor_set_out_name_.empty()) {
std::cerr << "--include_source_info only makes sense when combined with "
"--descriptor_set_out." << std::endl;
}
@@ -1151,11 +1384,20 @@ CommandLineInterface::InterpretArgument(const string& name,
input_files_.push_back(value);
} else if (name == "-I" || name == "--proto_path") {
+ if (!descriptor_set_in_names_.empty()) {
+ std::cerr << "Only one of " << name
+ << " and --descriptor_set_in can be specified."
+ << std::endl;
+ return PARSE_ARGUMENT_FAIL;
+ }
+
// Java's -classpath (and some other languages) delimits path components
// with colons. Let's accept that syntax too just to make things more
// intuitive.
std::vector<string> parts = Split(
- value, kPathSeparator, true);
+ value,
+ CommandLineInterface::kPathSeparator,
+ true);
for (int i = 0; i < parts.size(); i++) {
string virtual_path;
@@ -1181,7 +1423,8 @@ CommandLineInterface::InterpretArgument(const string& name,
if (access(disk_path.c_str(), F_OK) < 0) {
// Try the original path; it may have just happed to have a '=' in it.
if (access(parts[i].c_str(), F_OK) < 0) {
- cerr << disk_path << ": warning: directory does not exist." << endl;
+ std::cerr << disk_path << ": warning: directory does not exist."
+ << std::endl;
} else {
virtual_path = "";
disk_path = parts[i];
@@ -1209,8 +1452,41 @@ CommandLineInterface::InterpretArgument(const string& name,
GOOGLE_DCHECK(direct_dependencies_.empty());
direct_dependencies_.insert(direct.begin(), direct.end());
+ } else if (name == "--direct_dependencies_violation_msg") {
+ direct_dependencies_violation_msg_ = value;
+
+ } else if (name == "--descriptor_set_in") {
+ if (!descriptor_set_in_names_.empty()) {
+ std::cerr << name << " may only be passed once. To specify multiple "
+ "descriptor sets, pass them all as a single "
+ "parameter separated by '"
+ << CommandLineInterface::kPathSeparator << "'."
+ << std::endl;
+ return PARSE_ARGUMENT_FAIL;
+ }
+ if (value.empty()) {
+ std::cerr << name << " requires a non-empty value." << std::endl;
+ return PARSE_ARGUMENT_FAIL;
+ }
+ if (!proto_path_.empty()) {
+ std::cerr << "Only one of " << name
+ << " and --proto_path can be specified."
+ << std::endl;
+ return PARSE_ARGUMENT_FAIL;
+ }
+ if (!dependency_out_name_.empty()) {
+ std::cerr << name << " cannot be used with --dependency_out."
+ << std::endl;
+ return PARSE_ARGUMENT_FAIL;
+ }
+
+ descriptor_set_in_names_ = Split(
+ value,
+ CommandLineInterface::kPathSeparator,
+ true);
+
} else if (name == "-o" || name == "--descriptor_set_out") {
- if (!descriptor_set_name_.empty()) {
+ if (!descriptor_set_out_name_.empty()) {
std::cerr << name << " may only be passed once." << std::endl;
return PARSE_ARGUMENT_FAIL;
}
@@ -1224,7 +1500,7 @@ CommandLineInterface::InterpretArgument(const string& name,
"same time." << std::endl;
return PARSE_ARGUMENT_FAIL;
}
- descriptor_set_name_ = value;
+ descriptor_set_out_name_ = value;
} else if (name == "--dependency_out") {
if (!dependency_out_name_.empty()) {
@@ -1235,6 +1511,11 @@ CommandLineInterface::InterpretArgument(const string& name,
std::cerr << name << " requires a non-empty value." << std::endl;
return PARSE_ARGUMENT_FAIL;
}
+ if (!descriptor_set_in_names_.empty()) {
+ std::cerr << name << " cannot be used with --descriptor_set_in."
+ << std::endl;
+ return PARSE_ARGUMENT_FAIL;
+ }
dependency_out_name_ = value;
} else if (name == "--include_imports") {
@@ -1259,9 +1540,9 @@ CommandLineInterface::InterpretArgument(const string& name,
if (!version_info_.empty()) {
std::cout << version_info_ << std::endl;
}
- cout << "libprotoc "
+ std::cout << "libprotoc "
<< protobuf::internal::VersionString(GOOGLE_PROTOBUF_VERSION)
- << endl;
+ << std::endl;
return PARSE_ARGUMENT_DONE_AND_EXIT; // Exit without running compiler.
} else if (name == "--disallow_services") {
@@ -1274,7 +1555,7 @@ CommandLineInterface::InterpretArgument(const string& name,
<< std::endl;
return PARSE_ARGUMENT_FAIL;
}
- if (!output_directives_.empty() || !descriptor_set_name_.empty()) {
+ if (!output_directives_.empty() || !descriptor_set_out_name_.empty()) {
std::cerr << "Cannot use " << name
<< " and generate code or descriptors at the same time."
<< std::endl;
@@ -1340,7 +1621,7 @@ CommandLineInterface::InterpretArgument(const string& name,
<< "other info at the same time." << std::endl;
return PARSE_ARGUMENT_FAIL;
}
- if (!output_directives_.empty() || !descriptor_set_name_.empty()) {
+ if (!output_directives_.empty() || !descriptor_set_out_name_.empty()) {
std::cerr << "Cannot use " << name
<< " and generate code or descriptors at the same time."
<< std::endl;
@@ -1348,6 +1629,7 @@ CommandLineInterface::InterpretArgument(const string& name,
}
mode_ = MODE_PRINT;
print_mode_ = PRINT_FREE_FIELDS;
+ } else if (name == "--profile_path") {
} else {
// Some other flag. Look it up in the generators list.
const GeneratorInfo* generator_info =
@@ -1409,7 +1691,7 @@ CommandLineInterface::InterpretArgument(const string& name,
void CommandLineInterface::PrintHelpText() {
// Sorry for indentation here; line wrapping would be uglier.
- std::cerr <<
+ std::cout <<
"Usage: " << executable_name_ << " [OPTION] PROTO_FILES\n"
"Parse PROTO_FILES and generate output based on the options given:\n"
" -IPATH, --proto_path=PATH Specify the directory in which to search for\n"
@@ -1431,6 +1713,14 @@ void CommandLineInterface::PrintHelpText() {
" pairs in text format to standard output. No\n"
" PROTO_FILES should be given when using this\n"
" flag.\n"
+" --descriptor_set_in=FILES Specifies a delimited list of FILES\n"
+" each containing a FileDescriptorSet (a\n"
+" protocol buffer defined in descriptor.proto).\n"
+" The FileDescriptor for each of the PROTO_FILES\n"
+" provided will be loaded from these\n"
+" FileDescriptorSets. If a FileDescriptor\n"
+" appears multiple times, the first occurrence\n"
+" will be used.\n"
" -oFILE, Writes a FileDescriptorSet (a protocol buffer,\n"
" --descriptor_set_out=FILE defined in descriptor.proto) containing all of\n"
" the input files to FILE.\n"
@@ -1456,7 +1746,7 @@ void CommandLineInterface::PrintHelpText() {
" occupied fields numbers.\n"
<< std::endl;
if (!plugin_prefix_.empty()) {
- std::cerr <<
+ std::cout <<
" --plugin=EXECUTABLE Specifies a plugin executable to use.\n"
" Normally, protoc searches the PATH for\n"
" plugins, but you may specify additional\n"
@@ -1472,10 +1762,24 @@ void CommandLineInterface::PrintHelpText() {
// FIXME(kenton): If the text is long enough it will wrap, which is ugly,
// but fixing this nicely (e.g. splitting on spaces) is probably more
// trouble than it's worth.
- std::cerr << " " << iter->first << "=OUT_DIR "
+ std::cout << " " << iter->first << "=OUT_DIR "
<< string(19 - iter->first.size(), ' ') // Spaces for alignment.
<< iter->second.help_text << std::endl;
}
+ std::cerr <<
+" @<filename> Read options and filenames from file. If a\n"
+" relative file path is specified, the file\n"
+" will be searched in the working directory.\n"
+" The --proto_path option will not affect how\n"
+" this argument file is searched. Content of\n"
+" the file will be expanded in the position of\n"
+" @<filename> as in the argument list. Note\n"
+" that shell expansion is not applied to the\n"
+" content of the file (i.e., you cannot use\n"
+" quotes, wildcards, escapes, commands, etc.).\n"
+" Each line corresponds to a single argument,\n"
+" even if it contains spaces."
+ << std::endl;
}
bool CommandLineInterface::GenerateOutput(
@@ -1610,6 +1914,7 @@ bool CommandLineInterface::GeneratePluginOutput(
request.set_parameter(parameter);
}
+
std::set<const FileDescriptor*> already_seen;
for (int i = 0; i < parsed_files.size(); i++) {
request.add_file_to_generate(parsed_files[i]->name());
@@ -1747,52 +2052,55 @@ bool CommandLineInterface::EncodeOrDecode(const DescriptorPool* pool) {
}
bool CommandLineInterface::WriteDescriptorSet(
- const std::vector<const FileDescriptor*> parsed_files) {
+ const std::vector<const FileDescriptor*>& parsed_files) {
FileDescriptorSet file_set;
- if (imports_in_descriptor_set_) {
- std::set<const FileDescriptor*> already_seen;
- for (int i = 0; i < parsed_files.size(); i++) {
- GetTransitiveDependencies(parsed_files[i],
- true, // Include json_name
- source_info_in_descriptor_set_,
- &already_seen, file_set.mutable_file());
- }
- } else {
- std::set<const FileDescriptor*> already_seen;
+ std::set<const FileDescriptor*> already_seen;
+ if (!imports_in_descriptor_set_) {
+ // Since we don't want to output transitive dependencies, but we do want
+ // things to be in dependency order, add all dependencies that aren't in
+ // parsed_files to already_seen. This will short circuit the recursion
+ // in GetTransitiveDependencies.
+ std::set<const FileDescriptor*> to_output;
+ to_output.insert(parsed_files.begin(), parsed_files.end());
for (int i = 0; i < parsed_files.size(); i++) {
- if (!already_seen.insert(parsed_files[i]).second) {
- continue;
- }
- FileDescriptorProto* file_proto = file_set.add_file();
- parsed_files[i]->CopyTo(file_proto);
- parsed_files[i]->CopyJsonNameTo(file_proto);
- if (source_info_in_descriptor_set_) {
- parsed_files[i]->CopySourceCodeInfoTo(file_proto);
+ const FileDescriptor* file = parsed_files[i];
+ for (int i = 0; i < file->dependency_count(); i++) {
+ const FileDescriptor* dependency = file->dependency(i);
+ // if the dependency isn't in parsed files, mark it as already seen
+ if (to_output.find(dependency) == to_output.end()) {
+ already_seen.insert(dependency);
+ }
}
}
}
+ for (int i = 0; i < parsed_files.size(); i++) {
+ GetTransitiveDependencies(parsed_files[i],
+ true, // Include json_name
+ source_info_in_descriptor_set_,
+ &already_seen, file_set.mutable_file());
+ }
int fd;
do {
- fd = open(descriptor_set_name_.c_str(),
+ fd = open(descriptor_set_out_name_.c_str(),
O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666);
} while (fd < 0 && errno == EINTR);
if (fd < 0) {
- perror(descriptor_set_name_.c_str());
+ perror(descriptor_set_out_name_.c_str());
return false;
}
io::FileOutputStream out(fd);
if (!file_set.SerializeToZeroCopyStream(&out)) {
- std::cerr << descriptor_set_name_ << ": " << strerror(out.GetErrno())
+ std::cerr << descriptor_set_out_name_ << ": " << strerror(out.GetErrno())
<< std::endl;
out.Close();
return false;
}
if (!out.Close()) {
- std::cerr << descriptor_set_name_ << ": " << strerror(out.GetErrno())
+ std::cerr << descriptor_set_out_name_ << ": " << strerror(out.GetErrno())
<< std::endl;
return false;
}
diff --git a/src/google/protobuf/compiler/command_line_interface.h b/src/google/protobuf/compiler/command_line_interface.h
index 28471ee7..d5d85f2d 100644
--- a/src/google/protobuf/compiler/command_line_interface.h
+++ b/src/google/protobuf/compiler/command_line_interface.h
@@ -52,17 +52,16 @@ namespace protobuf {
class Descriptor; // descriptor.h
class DescriptorPool; // descriptor.h
class FileDescriptor; // descriptor.h
+class FileDescriptorSet; // descriptor.h
class FileDescriptorProto; // descriptor.pb.h
template<typename T> class RepeatedPtrField; // repeated_field.h
+class SimpleDescriptorDatabase; // descriptor_database.h
-} // namespace protobuf
-
-namespace protobuf {
namespace compiler {
-class CodeGenerator; // code_generator.h
-class GeneratorContext; // code_generator.h
-class DiskSourceTree; // importer.h
+class CodeGenerator; // code_generator.h
+class GeneratorContext; // code_generator.h
+class DiskSourceTree; // importer.h
// This class implements the command-line interface to the protocol compiler.
// It is designed to make it very easy to create a custom protocol compiler
@@ -91,9 +90,21 @@ class DiskSourceTree; // importer.h
// The compiler is invoked with syntax like:
// protoc --cpp_out=outdir --foo_out=outdir --proto_path=src src/foo.proto
//
+// The .proto file to compile can be specified on the command line using either
+// its physical file path, or a virtual path relative to a diretory specified
+// in --proto_path. For example, for src/foo.proto, the following two protoc
+// invocations work the same way:
+// 1. protoc --proto_path=src src/foo.proto (physical file path)
+// 2. protoc --proto_path=src foo.proto (virtual path relative to src)
+//
+// If a file path can be interpreted both as a physical file path and as a
+// relative virtual path, the physical file path takes precendence.
+//
// For a full description of the command-line syntax, invoke it with --help.
class LIBPROTOC_EXPORT CommandLineInterface {
public:
+ static const char* const kPathSeparator;
+
CommandLineInterface();
~CommandLineInterface();
@@ -175,17 +186,11 @@ class LIBPROTOC_EXPORT CommandLineInterface {
// it calls strerror(). I'm not sure why you'd want to do this anyway.
int Run(int argc, const char* const argv[]);
- // Call SetInputsAreCwdRelative(true) if the input files given on the command
- // line should be interpreted relative to the proto import path specified
- // using --proto_path or -I flags. Otherwise, input file names will be
- // interpreted relative to the current working directory (or as absolute
- // paths if they start with '/'), though they must still reside inside
- // a directory given by --proto_path or the compiler will fail. The latter
- // mode is generally more intuitive and easier to use, especially e.g. when
- // defining implicit rules in Makefiles.
- void SetInputsAreProtoPathRelative(bool enable) {
- inputs_are_proto_path_relative_ = enable;
- }
+ // DEPRECATED. Calling this method has no effect. Protocol compiler now
+ // always try to find the .proto file relative to the current directory
+ // first and if the file is not found, it will then treat the input path
+ // as a virutal path.
+ void SetInputsAreProtoPathRelative(bool /* enable */) {}
// Provides some text which will be printed when the --version flag is
// used. The version of libprotoc will also be printed on the next line
@@ -222,6 +227,9 @@ class LIBPROTOC_EXPORT CommandLineInterface {
// Parse all command-line arguments.
ParseArgumentStatus ParseArguments(int argc, const char* const argv[]);
+ // Read an argument file and append the file's content to the list of
+ // arguments. Return false if the file cannot be read.
+ bool ExpandArgumentFile(const string& file, std::vector<string>* arguments);
// Parses a command-line argument into a name/value pair. Returns
// true if the next argument in the argv should be used as the value,
@@ -243,6 +251,16 @@ class LIBPROTOC_EXPORT CommandLineInterface {
// Print the --help text to stderr.
void PrintHelpText();
+ // Loads proto_path_ into the provided source_tree.
+ bool InitializeDiskSourceTree(DiskSourceTree* source_tree);
+
+ // Loads descriptor_set_in into the provided database
+ bool PopulateSimpleDescriptorDatabase(SimpleDescriptorDatabase* database);
+
+ // Parses input_files_ into parsed_files
+ bool ParseInputFiles(DescriptorPool* descriptor_pool,
+ std::vector<const FileDescriptor*>* parsed_files);
+
// Generate the given output file from the given input.
struct OutputDirective; // see below
bool GenerateOutput(const std::vector<const FileDescriptor*>& parsed_files,
@@ -258,7 +276,7 @@ class LIBPROTOC_EXPORT CommandLineInterface {
// Implements the --descriptor_set_out option.
bool WriteDescriptorSet(
- const std::vector<const FileDescriptor*> parsed_files);
+ const std::vector<const FileDescriptor*>& parsed_files);
// Implements the --dependency_out option
bool GenerateDependencyManifestFile(
@@ -365,6 +383,10 @@ class LIBPROTOC_EXPORT CommandLineInterface {
std::set<string> direct_dependencies_;
bool direct_dependencies_explicitly_set_;
+ // If there's a violation of depend-on-what-you-import, this string will be
+ // presented to the user. "%s" will be replaced with the violating import.
+ string direct_dependencies_violation_msg_;
+
// output_directives_ lists all the files we are supposed to output and what
// generator to use for each.
struct OutputDirective {
@@ -379,14 +401,23 @@ class LIBPROTOC_EXPORT CommandLineInterface {
// decoding. (Empty string indicates --decode_raw.)
string codec_type_;
+ // If --descriptor_set_in was given, these are filenames containing
+ // parsed FileDescriptorSets to be used for loading protos. Otherwise, empty.
+ std::vector<string> descriptor_set_in_names_;
+
// If --descriptor_set_out was given, this is the filename to which the
// FileDescriptorSet should be written. Otherwise, empty.
- string descriptor_set_name_;
+ string descriptor_set_out_name_;
// If --dependency_out was given, this is the path to the file where the
// dependency file will be written. Otherwise, empty.
string dependency_out_name_;
+ // Path to a file that contains serialized AccessInfo which provides
+ // relative hotness of fields per message. This helps protoc to generate
+ // better code.
+ string profile_path_;
+
// True if --include_imports was given, meaning that we should
// write all transitive dependencies to the DescriptorSet. Otherwise, only
// the .proto files listed on the command-line are added.
@@ -399,9 +430,6 @@ class LIBPROTOC_EXPORT CommandLineInterface {
// Was the --disallow_services flag used?
bool disallow_services_;
- // See SetInputsAreProtoPathRelative().
- bool inputs_are_proto_path_relative_;
-
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CommandLineInterface);
};
diff --git a/src/google/protobuf/compiler/command_line_interface_unittest.cc b/src/google/protobuf/compiler/command_line_interface_unittest.cc
index b2ec8426..38d0e388 100644
--- a/src/google/protobuf/compiler/command_line_interface_unittest.cc
+++ b/src/google/protobuf/compiler/command_line_interface_unittest.cc
@@ -32,12 +32,11 @@
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
-#include <sys/types.h>
-#include <sys/stat.h>
#include <fcntl.h>
-#ifdef _MSC_VER
-#include <io.h>
-#else
+#include <sys/stat.h>
+#include <sys/types.h>
+
+#ifndef _MSC_VER
#include <unistd.h>
#endif
#include <memory>
@@ -46,45 +45,46 @@
#endif
#include <vector>
-#include <google/protobuf/descriptor.pb.h>
-#include <google/protobuf/descriptor.h>
-#include <google/protobuf/io/zero_copy_stream.h>
-#include <google/protobuf/compiler/command_line_interface.h>
-#include <google/protobuf/compiler/code_generator.h>
+#include <google/protobuf/stubs/stringprintf.h>
+#include <google/protobuf/testing/file.h>
#include <google/protobuf/testing/file.h>
#include <google/protobuf/compiler/mock_code_generator.h>
#include <google/protobuf/compiler/subprocess.h>
-#include <google/protobuf/io/printer.h>
+#include <google/protobuf/compiler/code_generator.h>
+#include <google/protobuf/compiler/command_line_interface.h>
#include <google/protobuf/unittest.pb.h>
-#include <google/protobuf/testing/file.h>
-#include <google/protobuf/stubs/stringprintf.h>
-#include <google/protobuf/stubs/strutil.h>
+#include <google/protobuf/io/printer.h>
+#include <google/protobuf/io/zero_copy_stream.h>
+#include <google/protobuf/descriptor.pb.h>
+#include <google/protobuf/descriptor.h>
#include <google/protobuf/stubs/substitute.h>
#include <google/protobuf/testing/file.h>
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
+#include <google/protobuf/stubs/strutil.h>
+#include <google/protobuf/stubs/io_win32.h>
namespace google {
namespace protobuf {
namespace compiler {
+#if defined(_MSC_VER)
+// DO NOT include <io.h>, instead create functions in io_win32.{h,cc} and import
+// them like we do below.
+using google::protobuf::internal::win32::access;
+using google::protobuf::internal::win32::dup;
+using google::protobuf::internal::win32::dup2;
+using google::protobuf::internal::win32::close;
+using google::protobuf::internal::win32::open;
+using google::protobuf::internal::win32::write;
+#endif
+
// Disable the whole test when we use tcmalloc for "draconian" heap checks, in
// which case tcmalloc will print warnings that fail the plugin tests.
#if !GOOGLE_PROTOBUF_HEAP_CHECK_DRACONIAN
-#if defined(_WIN32)
-#ifndef STDIN_FILENO
-#define STDIN_FILENO 0
-#endif
-#ifndef STDOUT_FILENO
-#define STDOUT_FILENO 1
-#endif
-#ifndef F_OK
-#define F_OK 00 // not defined by MSVC for whatever reason
-#endif
-#endif
namespace {
@@ -101,6 +101,7 @@ class CommandLineInterfaceTest : public testing::Test {
// command is automatically split on spaces, and the string "$tmpdir"
// is replaced with TestTempDir().
void Run(const string& command);
+ void RunWithArgs(std::vector<string> args);
// -----------------------------------------------------------------
// Methods to set up the test (called before Run()).
@@ -128,10 +129,6 @@ class CommandLineInterfaceTest : public testing::Test {
// google3.
#endif // !PROTOBUF_OPENSOURCE
- void SetInputsAreProtoPathRelative(bool enable) {
- cli_.SetInputsAreProtoPathRelative(enable);
- }
-
// -----------------------------------------------------------------
// Methods to check the test results (called after Run()).
@@ -155,6 +152,11 @@ class CommandLineInterfaceTest : public testing::Test {
// Checks that the captured stdout is the same as the expected_text.
void ExpectCapturedStdout(const string& expected_text);
+ // Checks that Run() returned zero and the stdout contains the given
+ // substring.
+ void ExpectCapturedStdoutSubstringWithZeroReturnCode(
+ const string& expected_substring);
+
// Returns true if ExpectErrorSubstring(expected_substring) would pass, but
// does not fail otherwise.
bool HasAlternateErrorSubstring(const string& expected_substring);
@@ -186,12 +188,17 @@ class CommandLineInterfaceTest : public testing::Test {
const string& insertions,
const string& proto_name,
const string& message_name);
+ void CheckGeneratedAnnotations(const string& name, const string& file);
void ExpectNullCodeGeneratorCalled(const string& parameter);
+
void ReadDescriptorSet(const string& filename,
FileDescriptorSet* descriptor_set);
+ void WriteDescriptorSet(const string& filename,
+ const FileDescriptorSet* descriptor_set);
+
void ExpectFileContent(const string& filename,
const string& content);
@@ -245,11 +252,6 @@ class CommandLineInterfaceTest::NullCodeGenerator : public CodeGenerator {
// ===================================================================
void CommandLineInterfaceTest::SetUp() {
- // Most of these tests were written before this option was added, so we
- // run with the option on (which used to be the only way) except in certain
- // tests where we turn it off.
- cli_.SetInputsAreProtoPathRelative(true);
-
temp_directory_ = TestTempDir() + "/proto2_cli_test_temp";
// If the temp directory already exists, it must be left over from a
@@ -275,6 +277,7 @@ void CommandLineInterfaceTest::SetUp() {
mock_generators_to_delete_.push_back(generator);
cli_.RegisterGenerator("--null_out", generator, "Null output.");
+
disallow_plugins_ = false;
}
@@ -292,8 +295,10 @@ void CommandLineInterfaceTest::TearDown() {
}
void CommandLineInterfaceTest::Run(const string& command) {
- std::vector<string> args = Split(command, " ", true);
+ RunWithArgs(Split(command, " ", true));
+}
+void CommandLineInterfaceTest::RunWithArgs(std::vector<string> args) {
if (!disallow_plugins_) {
cli_.AllowPlugins("prefix-");
#ifndef GOOGLE_THIRD_PARTY_PROTOBUF
@@ -463,12 +468,18 @@ void CommandLineInterfaceTest::ExpectGeneratedWithInsertions(
proto_name, temp_directory_);
}
+void CommandLineInterfaceTest::CheckGeneratedAnnotations(const string& name,
+ const string& file) {
+ MockCodeGenerator::CheckGeneratedAnnotations(name, file, temp_directory_);
+}
+
void CommandLineInterfaceTest::ExpectNullCodeGeneratorCalled(
const string& parameter) {
EXPECT_TRUE(null_generator_->called_);
EXPECT_EQ(parameter, null_generator_->parameter_);
}
+
void CommandLineInterfaceTest::ReadDescriptorSet(
const string& filename, FileDescriptorSet* descriptor_set) {
string path = temp_directory_ + "/" + filename;
@@ -480,11 +491,24 @@ void CommandLineInterfaceTest::ReadDescriptorSet(
}
}
+void CommandLineInterfaceTest::WriteDescriptorSet(
+ const string& filename, const FileDescriptorSet* descriptor_set) {
+ string binary_proto;
+ GOOGLE_CHECK(descriptor_set->SerializeToString(&binary_proto));
+ CreateTempFile(filename, binary_proto);
+}
+
void CommandLineInterfaceTest::ExpectCapturedStdout(
const string& expected_text) {
EXPECT_EQ(expected_text, captured_stdout_);
}
+void CommandLineInterfaceTest::ExpectCapturedStdoutSubstringWithZeroReturnCode(
+ const string& expected_substring) {
+ EXPECT_EQ(0, return_code_);
+ EXPECT_PRED_FORMAT2(
+ testing::IsSubstring, expected_substring, captured_stdout_);
+}
void CommandLineInterfaceTest::ExpectFileContent(
const string& filename, const string& content) {
@@ -512,6 +536,22 @@ TEST_F(CommandLineInterfaceTest, BasicOutput) {
ExpectGenerated("test_generator", "", "foo.proto", "Foo");
}
+TEST_F(CommandLineInterfaceTest, BasicOutput_DescriptorSetIn) {
+ // Test that the common case works.
+ FileDescriptorSet file_descriptor_set;
+ FileDescriptorProto* file_descriptor_proto = file_descriptor_set.add_file();
+ file_descriptor_proto->set_name("foo.proto");
+ file_descriptor_proto->add_message_type()->set_name("Foo");
+
+ WriteDescriptorSet("foo.bin", &file_descriptor_set);
+
+ Run("protocol_compiler --test_out=$tmpdir "
+ "--descriptor_set_in=$tmpdir/foo.bin foo.proto");
+
+ ExpectNoErrors();
+ ExpectGenerated("test_generator", "", "foo.proto", "Foo");
+}
+
TEST_F(CommandLineInterfaceTest, BasicPlugin) {
// Test that basic plugins work.
@@ -526,6 +566,23 @@ TEST_F(CommandLineInterfaceTest, BasicPlugin) {
ExpectGenerated("test_plugin", "", "foo.proto", "Foo");
}
+TEST_F(CommandLineInterfaceTest, BasicPlugin_DescriptorSetIn) {
+ // Test that basic plugins work.
+
+ FileDescriptorSet file_descriptor_set;
+ FileDescriptorProto* file_descriptor_proto = file_descriptor_set.add_file();
+ file_descriptor_proto->set_name("foo.proto");
+ file_descriptor_proto->add_message_type()->set_name("Foo");
+
+ WriteDescriptorSet("foo.bin", &file_descriptor_set);
+
+ Run("protocol_compiler --plug_out=$tmpdir "
+ "--descriptor_set_in=$tmpdir/foo.bin foo.proto");
+
+ ExpectNoErrors();
+ ExpectGenerated("test_plugin", "", "foo.proto", "Foo");
+}
+
TEST_F(CommandLineInterfaceTest, GeneratorAndPlugin) {
// Invoke a generator and a plugin at the same time.
@@ -541,6 +598,24 @@ TEST_F(CommandLineInterfaceTest, GeneratorAndPlugin) {
ExpectGenerated("test_plugin", "", "foo.proto", "Foo");
}
+TEST_F(CommandLineInterfaceTest, GeneratorAndPlugin_DescriptorSetIn) {
+ // Invoke a generator and a plugin at the same time.
+
+ FileDescriptorSet file_descriptor_set;
+ FileDescriptorProto* file_descriptor_proto = file_descriptor_set.add_file();
+ file_descriptor_proto->set_name("foo.proto");
+ file_descriptor_proto->add_message_type()->set_name("Foo");
+
+ WriteDescriptorSet("foo.bin", &file_descriptor_set);
+
+ Run("protocol_compiler --test_out=$tmpdir --plug_out=$tmpdir "
+ "--descriptor_set_in=$tmpdir/foo.bin foo.proto");
+
+ ExpectNoErrors();
+ ExpectGenerated("test_generator", "", "foo.proto", "Foo");
+ ExpectGenerated("test_plugin", "", "foo.proto", "Foo");
+}
+
TEST_F(CommandLineInterfaceTest, MultipleInputs) {
// Test parsing multiple input files.
@@ -565,6 +640,34 @@ TEST_F(CommandLineInterfaceTest, MultipleInputs) {
"bar.proto", "Bar");
}
+TEST_F(CommandLineInterfaceTest, MultipleInputs_DescriptorSetIn) {
+ // Test parsing multiple input files.
+ FileDescriptorSet file_descriptor_set;
+
+ FileDescriptorProto* file_descriptor_proto = file_descriptor_set.add_file();
+ file_descriptor_proto->set_name("foo.proto");
+ file_descriptor_proto->add_message_type()->set_name("Foo");
+
+ file_descriptor_proto = file_descriptor_set.add_file();
+ file_descriptor_proto->set_name("bar.proto");
+ file_descriptor_proto->add_message_type()->set_name("Bar");
+
+ WriteDescriptorSet("foo.bin", &file_descriptor_set);
+
+ Run("protocol_compiler --test_out=$tmpdir --plug_out=$tmpdir "
+ "--descriptor_set_in=$tmpdir/foo.bin foo.proto bar.proto");
+
+ ExpectNoErrors();
+ ExpectGeneratedWithMultipleInputs("test_generator", "foo.proto,bar.proto",
+ "foo.proto", "Foo");
+ ExpectGeneratedWithMultipleInputs("test_generator", "foo.proto,bar.proto",
+ "bar.proto", "Bar");
+ ExpectGeneratedWithMultipleInputs("test_plugin", "foo.proto,bar.proto",
+ "foo.proto", "Foo");
+ ExpectGeneratedWithMultipleInputs("test_plugin", "foo.proto,bar.proto",
+ "bar.proto", "Bar");
+}
+
TEST_F(CommandLineInterfaceTest, MultipleInputsWithImport) {
// Test parsing multiple input files with an import of a separate file.
@@ -595,6 +698,165 @@ TEST_F(CommandLineInterfaceTest, MultipleInputsWithImport) {
"bar.proto", "Bar");
}
+TEST_F(CommandLineInterfaceTest, MultipleInputsWithImport_DescriptorSetIn) {
+ // Test parsing multiple input files with an import of a separate file.
+ FileDescriptorSet file_descriptor_set;
+
+ FileDescriptorProto* file_descriptor_proto = file_descriptor_set.add_file();
+ file_descriptor_proto->set_name("foo.proto");
+ file_descriptor_proto->add_message_type()->set_name("Foo");
+
+ file_descriptor_proto = file_descriptor_set.add_file();
+ file_descriptor_proto->set_name("bar.proto");
+ file_descriptor_proto->add_dependency("baz.proto");
+ DescriptorProto* message = file_descriptor_proto->add_message_type();
+ message->set_name("Bar");
+ FieldDescriptorProto* field = message->add_field();
+ field->set_type_name("Baz");
+ field->set_name("a");
+ field->set_number(1);
+
+ WriteDescriptorSet("foo_and_bar.bin", &file_descriptor_set);
+
+ file_descriptor_set.clear_file();
+ file_descriptor_proto = file_descriptor_set.add_file();
+ file_descriptor_proto->set_name("baz.proto");
+ file_descriptor_proto->add_message_type()->set_name("Baz");
+
+ file_descriptor_proto = file_descriptor_set.add_file();
+ file_descriptor_proto->set_name("bat.proto");
+ file_descriptor_proto->add_dependency("baz.proto");
+ message = file_descriptor_proto->add_message_type();
+ message->set_name("Bat");
+ field = message->add_field();
+ field->set_type_name("Baz");
+ field->set_name("a");
+ field->set_number(1);
+
+ WriteDescriptorSet("baz_and_bat.bin", &file_descriptor_set);
+ Run(strings::Substitute(
+ "protocol_compiler --test_out=$$tmpdir --plug_out=$$tmpdir "
+ "--descriptor_set_in=$0 foo.proto bar.proto",
+ string("$tmpdir/foo_and_bar.bin") +
+ CommandLineInterface::kPathSeparator +
+ "$tmpdir/baz_and_bat.bin"));
+
+ ExpectNoErrors();
+ ExpectGeneratedWithMultipleInputs("test_generator", "foo.proto,bar.proto",
+ "foo.proto", "Foo");
+ ExpectGeneratedWithMultipleInputs("test_generator", "foo.proto,bar.proto",
+ "bar.proto", "Bar");
+ ExpectGeneratedWithMultipleInputs("test_plugin", "foo.proto,bar.proto",
+ "foo.proto", "Foo");
+ ExpectGeneratedWithMultipleInputs("test_plugin", "foo.proto,bar.proto",
+ "bar.proto", "Bar");
+
+ Run(strings::Substitute(
+ "protocol_compiler --test_out=$$tmpdir --plug_out=$$tmpdir "
+ "--descriptor_set_in=$0 baz.proto bat.proto",
+ string("$tmpdir/foo_and_bar.bin") +
+ CommandLineInterface::kPathSeparator +
+ "$tmpdir/baz_and_bat.bin"));
+
+ ExpectNoErrors();
+ ExpectGeneratedWithMultipleInputs("test_generator", "baz.proto,bat.proto",
+ "baz.proto", "Baz");
+ ExpectGeneratedWithMultipleInputs("test_generator", "baz.proto,bat.proto",
+ "bat.proto", "Bat");
+ ExpectGeneratedWithMultipleInputs("test_plugin", "baz.proto,bat.proto",
+ "baz.proto", "Baz");
+ ExpectGeneratedWithMultipleInputs("test_plugin", "baz.proto,bat.proto",
+ "bat.proto", "Bat");
+}
+
+TEST_F(CommandLineInterfaceTest,
+ MultipleInputsWithImport_DescriptorSetIn_DuplicateFileDescriptor) {
+ // Test parsing multiple input files with an import of a separate file.
+ FileDescriptorSet file_descriptor_set;
+
+ FileDescriptorProto foo_file_descriptor_proto;
+ foo_file_descriptor_proto.set_name("foo.proto");
+ foo_file_descriptor_proto.add_message_type()->set_name("Foo");
+
+ file_descriptor_set.add_file()->CopyFrom(foo_file_descriptor_proto);
+
+ FileDescriptorProto* file_descriptor_proto = file_descriptor_set.add_file();
+ file_descriptor_proto->set_name("bar.proto");
+ file_descriptor_proto->add_dependency("baz.proto");
+ file_descriptor_proto->add_dependency("foo.proto");
+ DescriptorProto* message = file_descriptor_proto->add_message_type();
+ message->set_name("Bar");
+ FieldDescriptorProto* field = message->add_field();
+ field->set_type_name("Baz");
+ field->set_name("a");
+ field->set_number(1);
+ field = message->add_field();
+ field->set_type_name("Foo");
+ field->set_name("f");
+ field->set_number(2);
+ WriteDescriptorSet("foo_and_bar.bin", &file_descriptor_set);
+
+ file_descriptor_set.clear_file();
+ file_descriptor_set.add_file()->CopyFrom(foo_file_descriptor_proto);
+
+ file_descriptor_proto = file_descriptor_set.add_file();
+ file_descriptor_proto->set_name("baz.proto");
+ file_descriptor_proto->add_dependency("foo.proto");
+ message = file_descriptor_proto->add_message_type();
+ message->set_name("Baz");
+ field = message->add_field();
+ field->set_type_name("Foo");
+ field->set_name("f");
+ field->set_number(1);
+ WriteDescriptorSet("foo_and_baz.bin", &file_descriptor_set);
+
+ Run(strings::Substitute(
+ "protocol_compiler --test_out=$$tmpdir --plug_out=$$tmpdir "
+ "--descriptor_set_in=$0 bar.proto",
+ string("$tmpdir/foo_and_bar.bin") +
+ CommandLineInterface::kPathSeparator +
+ "$tmpdir/foo_and_baz.bin"));
+
+ ExpectNoErrors();
+ ExpectGenerated("test_generator", "", "bar.proto", "Bar");
+ ExpectGenerated("test_plugin", "", "bar.proto", "Bar");
+}
+
+TEST_F(CommandLineInterfaceTest,
+ MultipleInputsWithImport_DescriptorSetIn_MissingImport) {
+ // Test parsing multiple input files with an import of a separate file.
+ FileDescriptorSet file_descriptor_set;
+
+ FileDescriptorProto* file_descriptor_proto = file_descriptor_set.add_file();
+ file_descriptor_proto->set_name("foo.proto");
+ file_descriptor_proto->add_message_type()->set_name("Foo");
+
+ file_descriptor_proto = file_descriptor_set.add_file();
+ file_descriptor_proto->set_name("bar.proto");
+ file_descriptor_proto->add_dependency("baz.proto");
+ DescriptorProto* message = file_descriptor_proto->add_message_type();
+ message->set_name("Bar");
+ FieldDescriptorProto* field = message->add_field();
+ field->set_type_name("Baz");
+ field->set_name("a");
+ field->set_number(1);
+
+ WriteDescriptorSet("foo_and_bar.bin", &file_descriptor_set);
+
+ file_descriptor_set.clear_file();
+ file_descriptor_proto = file_descriptor_set.add_file();
+ file_descriptor_proto->set_name("baz.proto");
+ file_descriptor_proto->add_message_type()->set_name("Baz");
+
+ WriteDescriptorSet("baz.bin", &file_descriptor_set);
+ Run("protocol_compiler --test_out=$tmpdir --plug_out=$tmpdir "
+ "--descriptor_set_in=$tmpdir/foo_and_bar.bin "
+ "foo.proto bar.proto");
+ ExpectErrorSubstring(
+ "bar.proto: Import \"baz.proto\" was not found or had errors.");
+ ExpectErrorSubstring("bar.proto: \"Baz\" is not defined.");
+}
+
TEST_F(CommandLineInterfaceTest, CreateDirectory) {
// Test that when we output to a sub-directory, it is created.
@@ -686,10 +948,36 @@ TEST_F(CommandLineInterfaceTest, UnrecognizedExtraParameters) {
"message Foo {}\n");
Run("protocol_compiler --plug_out=TestParameter:$tmpdir "
+ "--unknown_plug_a_opt=Foo "
+ "--unknown_plug_b_opt=Bar "
+ "--proto_path=$tmpdir foo.proto");
+
+ ExpectErrorSubstring("Unknown flag: --unknown_plug_a_opt");
+ ExpectErrorSubstring("Unknown flag: --unknown_plug_b_opt");
+}
+
+TEST_F(CommandLineInterfaceTest, ExtraPluginParametersForOutParameters) {
+ // This doesn't rely on the plugin having been registred and instead that
+ // the existence of --[name]_out is enough to make the --[name]_opt valid.
+ // However, running out of process plugins found via the search path (i.e. -
+ // not pre registered with --plugin) isn't support in this test suite, so we
+ // list the options pre/post the _out directive, and then include _opt that
+ // will be unknown, and confirm the failure output is about the expected
+ // unknown directive, which means the other were accepted.
+ // NOTE: UnrecognizedExtraParameters confirms that if two unknown _opt
+ // directives appear, they both are reported.
+
+ CreateTempFile("foo.proto",
+ "syntax = \"proto2\";\n"
+ "message Foo {}\n");
+
+ Run("protocol_compiler --plug_out=TestParameter:$tmpdir "
+ "--xyz_opt=foo=bar --xyz_out=$tmpdir "
+ "--abc_out=$tmpdir --abc_opt=foo=bar "
"--unknown_plug_opt=Foo "
"--proto_path=$tmpdir foo.proto");
- ExpectErrorSubstring("Unknown flag: --unknown_plug_opt");
+ ExpectErrorText("Unknown flag: --unknown_plug_opt\n");
}
TEST_F(CommandLineInterfaceTest, Insert) {
@@ -715,6 +1003,25 @@ TEST_F(CommandLineInterfaceTest, Insert) {
"foo.proto", "Foo");
}
+TEST_F(CommandLineInterfaceTest, InsertWithAnnotationFixup) {
+ // Check that annotation spans are updated after insertions.
+
+ CreateTempFile("foo.proto",
+ "syntax = \"proto2\";\n"
+ "message MockCodeGenerator_Annotate {}\n");
+
+ Run("protocol_compiler "
+ "--test_out=TestParameter:$tmpdir "
+ "--plug_out=TestPluginParameter:$tmpdir "
+ "--test_out=insert=test_generator,test_plugin:$tmpdir "
+ "--plug_out=insert=test_generator,test_plugin:$tmpdir "
+ "--proto_path=$tmpdir foo.proto");
+
+ ExpectNoErrors();
+ CheckGeneratedAnnotations("test_generator", "foo.proto");
+ CheckGeneratedAnnotations("test_plugin", "foo.proto");
+}
+
#if defined(_WIN32)
TEST_F(CommandLineInterfaceTest, WindowsOutputPath) {
@@ -800,17 +1107,11 @@ TEST_F(CommandLineInterfaceTest, ColonDelimitedPath) {
"}\n");
CreateTempFile("b/foo.proto", "this should not be parsed\n");
-#undef PATH_SEPARATOR
-#if defined(_WIN32)
-#define PATH_SEPARATOR ";"
-#else
-#define PATH_SEPARATOR ":"
-#endif
-
- Run("protocol_compiler --test_out=$tmpdir "
- "--proto_path=$tmpdir/a" PATH_SEPARATOR "$tmpdir/b foo.proto");
-
-#undef PATH_SEPARATOR
+ Run(strings::Substitute(
+ "protocol_compiler --test_out=$$tmpdir --proto_path=$0 foo.proto",
+ string("$tmpdir/a") +
+ CommandLineInterface::kPathSeparator +
+ "$tmpdir/b"));
ExpectNoErrors();
ExpectGenerated("test_generator", "", "foo.proto", "Foo");
@@ -996,11 +1297,30 @@ TEST_F(CommandLineInterfaceTest, DirectDependencies_ProvidedMultipleTimes) {
"':'.\n");
}
+TEST_F(CommandLineInterfaceTest, DirectDependencies_CustomErrorMessage) {
+ CreateTempFile("foo.proto",
+ "syntax = \"proto2\";\n"
+ "import \"bar.proto\";\n"
+ "message Foo { optional Bar bar = 1; }");
+ CreateTempFile("bar.proto",
+ "syntax = \"proto2\";\n"
+ "message Bar { optional string text = 1; }");
+
+ std::vector<string> commands;
+ commands.push_back("protocol_compiler");
+ commands.push_back("--test_out=$tmpdir");
+ commands.push_back("--proto_path=$tmpdir");
+ commands.push_back("--direct_dependencies=");
+ commands.push_back("--direct_dependencies_violation_msg=Bla \"%s\" Bla");
+ commands.push_back("foo.proto");
+ RunWithArgs(commands);
+
+ ExpectErrorText("foo.proto: Bla \"bar.proto\" Bla\n");
+}
+
TEST_F(CommandLineInterfaceTest, CwdRelativeInputs) {
// Test that we can accept working-directory-relative input files.
- SetInputsAreProtoPathRelative(false);
-
CreateTempFile("foo.proto",
"syntax = \"proto2\";\n"
"message Foo {}\n");
@@ -1067,15 +1387,17 @@ TEST_F(CommandLineInterfaceTest, WriteDescriptorSetWithDuplicates) {
ReadDescriptorSet("descriptor_set", &descriptor_set);
if (HasFatalFailure()) return;
EXPECT_EQ(3, descriptor_set.file_size());
- EXPECT_EQ("bar.proto", descriptor_set.file(0).name());
- EXPECT_EQ("foo.proto", descriptor_set.file(1).name());
+ // foo should come first since the output is in dependency order.
+ // since bar and baz are unordered, they should be in command line order.
+ EXPECT_EQ("foo.proto", descriptor_set.file(0).name());
+ EXPECT_EQ("bar.proto", descriptor_set.file(1).name());
EXPECT_EQ("baz.proto", descriptor_set.file(2).name());
// Descriptor set should not have source code info.
EXPECT_FALSE(descriptor_set.file(0).has_source_code_info());
// Descriptor set should have json_name.
- EXPECT_EQ("Bar", descriptor_set.file(0).message_type(0).name());
- EXPECT_EQ("foo", descriptor_set.file(0).message_type(0).field(0).name());
- EXPECT_TRUE(descriptor_set.file(0).message_type(0).field(0).has_json_name());
+ EXPECT_EQ("Bar", descriptor_set.file(1).message_type(0).name());
+ EXPECT_EQ("foo", descriptor_set.file(1).message_type(0).field(0).name());
+ EXPECT_TRUE(descriptor_set.file(1).message_type(0).field(0).has_json_name());
}
TEST_F(CommandLineInterfaceTest, WriteDescriptorSetWithSourceInfo) {
@@ -1239,6 +1561,36 @@ TEST_F(CommandLineInterfaceTest, WriteDependencyManifestFileForAbsolutePath) {
}
#endif // !_WIN32
+TEST_F(CommandLineInterfaceTest, TestArgumentFile) {
+ // Test parsing multiple input files using an argument file.
+
+ CreateTempFile("foo.proto",
+ "syntax = \"proto2\";\n"
+ "message Foo {}\n");
+ CreateTempFile("bar.proto",
+ "syntax = \"proto2\";\n"
+ "message Bar {}\n");
+ CreateTempFile("arguments.txt",
+ "--test_out=$tmpdir\n"
+ "--plug_out=$tmpdir\n"
+ "--proto_path=$tmpdir\n"
+ "--direct_dependencies_violation_msg=%s is not imported\n"
+ "foo.proto\n"
+ "bar.proto");
+
+ Run("protocol_compiler @$tmpdir/arguments.txt");
+
+ ExpectNoErrors();
+ ExpectGeneratedWithMultipleInputs("test_generator", "foo.proto,bar.proto",
+ "foo.proto", "Foo");
+ ExpectGeneratedWithMultipleInputs("test_generator", "foo.proto,bar.proto",
+ "bar.proto", "Bar");
+ ExpectGeneratedWithMultipleInputs("test_plugin", "foo.proto,bar.proto",
+ "foo.proto", "Foo");
+ ExpectGeneratedWithMultipleInputs("test_plugin", "foo.proto,bar.proto",
+ "bar.proto", "Bar");
+}
+
// -------------------------------------------------------------------
@@ -1256,6 +1608,17 @@ TEST_F(CommandLineInterfaceTest, ParseErrors) {
"foo.proto:2:1: Expected top-level statement (e.g. \"message\").\n");
}
+TEST_F(CommandLineInterfaceTest, ParseErrors_DescriptorSetIn) {
+ // Test that parse errors are reported.
+ CreateTempFile("foo.bin", "not a FileDescriptorSet");
+
+ Run("protocol_compiler --test_out=$tmpdir "
+ "--descriptor_set_in=$tmpdir/foo.bin foo.proto");
+
+ ExpectErrorText(
+ "$tmpdir/foo.bin: Unable to parse.\n");
+}
+
TEST_F(CommandLineInterfaceTest, ParseErrorsMultipleFiles) {
// Test that parse errors are reported from multiple files.
@@ -1283,22 +1646,42 @@ TEST_F(CommandLineInterfaceTest, ParseErrorsMultipleFiles) {
"foo.proto: Import \"baz.proto\" was not found or had errors.\n");
}
+TEST_F(CommandLineInterfaceTest, RecursiveImportFails) {
+ // Create a proto file that imports itself.
+ CreateTempFile("foo.proto",
+ "syntax = \"proto2\";\n"
+ "import \"foo.proto\";\n");
+
+ Run("protocol_compiler --test_out=$tmpdir "
+ "--proto_path=$tmpdir foo.proto");
+
+ ExpectErrorSubstring(
+ "foo.proto: File recursively imports itself: foo.proto -> foo.proto\n");
+}
+
TEST_F(CommandLineInterfaceTest, InputNotFoundError) {
// Test what happens if the input file is not found.
Run("protocol_compiler --test_out=$tmpdir "
"--proto_path=$tmpdir foo.proto");
+ ExpectErrorText("foo.proto: No such file or directory\n");
+}
+
+TEST_F(CommandLineInterfaceTest, InputNotFoundError_DescriptorSetIn) {
+ // Test what happens if the input file is not found.
+
+ Run("protocol_compiler --test_out=$tmpdir "
+ "--descriptor_set_in=$tmpdir/foo.bin foo.proto");
+
ExpectErrorText(
- "foo.proto: File not found.\n");
+ "$tmpdir/foo.bin: No such file or directory\n");
}
TEST_F(CommandLineInterfaceTest, CwdRelativeInputNotFoundError) {
// Test what happens when a working-directory-relative input file is not
// found.
- SetInputsAreProtoPathRelative(false);
-
Run("protocol_compiler --test_out=$tmpdir "
"--proto_path=$tmpdir $tmpdir/foo.proto");
@@ -1310,8 +1693,6 @@ TEST_F(CommandLineInterfaceTest, CwdRelativeInputNotMappedError) {
// Test what happens when a working-directory-relative input file is not
// mapped to a virtual path.
- SetInputsAreProtoPathRelative(false);
-
CreateTempFile("foo.proto",
"syntax = \"proto2\";\n"
"message Foo {}\n");
@@ -1336,8 +1717,6 @@ TEST_F(CommandLineInterfaceTest, CwdRelativeInputNotFoundAndNotMappedError) {
// Check what happens if the input file is not found *and* is not mapped
// in the proto_path.
- SetInputsAreProtoPathRelative(false);
-
// Create a directory called "bar" so that we can point --proto_path at it.
CreateTempFile("bar/dummy", "");
@@ -1352,8 +1731,6 @@ TEST_F(CommandLineInterfaceTest, CwdRelativeInputShadowedError) {
// Test what happens when a working-directory-relative input file is shadowed
// by another file in the virtual path.
- SetInputsAreProtoPathRelative(false);
-
CreateTempFile("foo/foo.proto",
"syntax = \"proto2\";\n"
"message Foo {}\n");
@@ -1379,8 +1756,34 @@ TEST_F(CommandLineInterfaceTest, ProtoPathNotFoundError) {
"--proto_path=$tmpdir/foo foo.proto");
ExpectErrorText(
- "$tmpdir/foo: warning: directory does not exist.\n"
- "foo.proto: File not found.\n");
+ "$tmpdir/foo: warning: directory does not exist.\n"
+ "foo.proto: No such file or directory\n");
+}
+
+TEST_F(CommandLineInterfaceTest, ProtoPathAndDescriptorSetIn) {
+ Run("protocol_compiler --test_out=$tmpdir "
+ "--proto_path=$tmpdir --descriptor_set_in=$tmpdir/foo.bin foo.proto");
+ ExpectErrorText(
+ "Only one of --descriptor_set_in and --proto_path can be specified.\n");
+
+ Run("protocol_compiler --test_out=$tmpdir "
+ "--descriptor_set_in=$tmpdir/foo.bin --proto_path=$tmpdir foo.proto");
+ ExpectErrorText(
+ "Only one of --proto_path and --descriptor_set_in can be specified.\n");
+}
+
+TEST_F(CommandLineInterfaceTest, ProtoPathAndDependencyOut) {
+ Run("protocol_compiler --test_out=$tmpdir "
+ "--dependency_out=$tmpdir/manifest "
+ "--descriptor_set_in=$tmpdir/foo.bin foo.proto");
+ ExpectErrorText(
+ "--descriptor_set_in cannot be used with --dependency_out.\n");
+
+ Run("protocol_compiler --test_out=$tmpdir "
+ "--descriptor_set_in=$tmpdir/foo.bin "
+ "--dependency_out=$tmpdir/manifest foo.proto");
+ ExpectErrorText(
+ "--dependency_out cannot be used with --descriptor_set_in.\n");
}
TEST_F(CommandLineInterfaceTest, MissingInputError) {
@@ -1640,11 +2043,11 @@ TEST_F(CommandLineInterfaceTest, GeneratorPluginNotAllowed) {
TEST_F(CommandLineInterfaceTest, HelpText) {
Run("test_exec_name --help");
- ExpectErrorSubstringWithZeroReturnCode("Usage: test_exec_name ");
- ExpectErrorSubstringWithZeroReturnCode("--test_out=OUT_DIR");
- ExpectErrorSubstringWithZeroReturnCode("Test output.");
- ExpectErrorSubstringWithZeroReturnCode("--alt_out=OUT_DIR");
- ExpectErrorSubstringWithZeroReturnCode("Alt output.");
+ ExpectCapturedStdoutSubstringWithZeroReturnCode("Usage: test_exec_name ");
+ ExpectCapturedStdoutSubstringWithZeroReturnCode("--test_out=OUT_DIR");
+ ExpectCapturedStdoutSubstringWithZeroReturnCode("Test output.");
+ ExpectCapturedStdoutSubstringWithZeroReturnCode("--alt_out=OUT_DIR");
+ ExpectCapturedStdoutSubstringWithZeroReturnCode("Alt output.");
}
TEST_F(CommandLineInterfaceTest, GccFormatErrors) {
@@ -1830,9 +2233,16 @@ TEST_F(CommandLineInterfaceTest, PrintFreeFieldNumbers) {
// test as a shell script, but we'd like to be able to run the test on
// platforms that don't have a Bourne-compatible shell available (especially
// Windows/MSVC).
-class EncodeDecodeTest : public testing::Test {
+
+enum EncodeDecodeTestMode {
+ PROTO_PATH,
+ DESCRIPTOR_SET_IN
+};
+
+class EncodeDecodeTest : public testing::TestWithParam<EncodeDecodeTestMode> {
protected:
virtual void SetUp() {
+ WriteUnittestProtoDescriptorSet();
duped_stdin_ = dup(STDIN_FILENO);
}
@@ -1875,7 +2285,18 @@ class EncodeDecodeTest : public testing::Test {
std::vector<string> args;
args.push_back("protoc");
SplitStringUsing(command, " ", &args);
- args.push_back("--proto_path=" + TestSourceDir());
+ switch (GetParam()) {
+ case PROTO_PATH:
+ args.push_back("--proto_path=" + TestSourceDir());
+ break;
+ case DESCRIPTOR_SET_IN:
+ args.push_back(StrCat(
+ "--descriptor_set_in=",
+ unittest_proto_descriptor_set_filename_));
+ break;
+ default:
+ ADD_FAILURE() << "unexpected EncodeDecodeTestMode: " << GetParam();
+ }
google::protobuf::scoped_array<const char * > argv(new const char* [args.size()]);
for (int i = 0; i < args.size(); i++) {
@@ -1883,7 +2304,6 @@ class EncodeDecodeTest : public testing::Test {
}
CommandLineInterface cli;
- cli.SetInputsAreProtoPathRelative(true);
CaptureTestStdout();
CaptureTestStderr();
@@ -1921,12 +2341,37 @@ class EncodeDecodeTest : public testing::Test {
}
private:
+ void WriteUnittestProtoDescriptorSet() {
+ unittest_proto_descriptor_set_filename_ =
+ TestTempDir() + "/unittest_proto_descriptor_set.bin";
+ FileDescriptorSet file_descriptor_set;
+ protobuf_unittest::TestAllTypes test_all_types;
+ test_all_types.descriptor()->file()->CopyTo(file_descriptor_set.add_file());
+
+ protobuf_unittest_import::ImportMessage import_message;
+ import_message.descriptor()->file()->CopyTo(file_descriptor_set.add_file());
+
+
+ protobuf_unittest_import::PublicImportMessage public_import_message;
+ public_import_message.descriptor()->file()->CopyTo(
+ file_descriptor_set.add_file());
+ GOOGLE_DCHECK(file_descriptor_set.IsInitialized());
+
+ string binary_proto;
+ GOOGLE_CHECK(file_descriptor_set.SerializeToString(&binary_proto));
+ GOOGLE_CHECK_OK(File::SetContents(
+ unittest_proto_descriptor_set_filename_,
+ binary_proto,
+ true));
+ }
+
int duped_stdin_;
string captured_stdout_;
string captured_stderr_;
+ string unittest_proto_descriptor_set_filename_;
};
-TEST_F(EncodeDecodeTest, Encode) {
+TEST_P(EncodeDecodeTest, Encode) {
RedirectStdinFromFile(TestSourceDir() + "/google/protobuf/"
"testdata/text_format_unittest_data_oneof_implemented.txt");
EXPECT_TRUE(Run("google/protobuf/unittest.proto "
@@ -1936,7 +2381,7 @@ TEST_F(EncodeDecodeTest, Encode) {
ExpectStderrMatchesText("");
}
-TEST_F(EncodeDecodeTest, Decode) {
+TEST_P(EncodeDecodeTest, Decode) {
RedirectStdinFromFile(TestSourceDir() +
"/google/protobuf/testdata/golden_message_oneof_implemented");
EXPECT_TRUE(Run("google/protobuf/unittest.proto "
@@ -1947,7 +2392,7 @@ TEST_F(EncodeDecodeTest, Decode) {
ExpectStderrMatchesText("");
}
-TEST_F(EncodeDecodeTest, Partial) {
+TEST_P(EncodeDecodeTest, Partial) {
RedirectStdinFromText("");
EXPECT_TRUE(Run("google/protobuf/unittest.proto "
"--encode=protobuf_unittest.TestRequired"));
@@ -1956,7 +2401,7 @@ TEST_F(EncodeDecodeTest, Partial) {
"warning: Input message is missing required fields: a, b, c\n");
}
-TEST_F(EncodeDecodeTest, DecodeRaw) {
+TEST_P(EncodeDecodeTest, DecodeRaw) {
protobuf_unittest::TestAllTypes message;
message.set_optional_int32(123);
message.set_optional_string("foo");
@@ -1970,21 +2415,24 @@ TEST_F(EncodeDecodeTest, DecodeRaw) {
ExpectStderrMatchesText("");
}
-TEST_F(EncodeDecodeTest, UnknownType) {
+TEST_P(EncodeDecodeTest, UnknownType) {
EXPECT_FALSE(Run("google/protobuf/unittest.proto "
"--encode=NoSuchType"));
ExpectStdoutMatchesText("");
ExpectStderrMatchesText("Type not defined: NoSuchType\n");
}
-TEST_F(EncodeDecodeTest, ProtoParseError) {
+TEST_P(EncodeDecodeTest, ProtoParseError) {
EXPECT_FALSE(Run("google/protobuf/no_such_file.proto "
"--encode=NoSuchType"));
ExpectStdoutMatchesText("");
ExpectStderrMatchesText(
- "google/protobuf/no_such_file.proto: File not found.\n");
+ "google/protobuf/no_such_file.proto: No such file or directory\n");
}
+INSTANTIATE_TEST_CASE_P(FileDescriptorSetSource,
+ EncodeDecodeTest,
+ testing::Values(PROTO_PATH, DESCRIPTOR_SET_IN));
} // anonymous namespace
#endif // !GOOGLE_PROTOBUF_HEAP_CHECK_DRACONIAN
diff --git a/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc b/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc
index bf4e5831..f99159f5 100644
--- a/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc
@@ -46,12 +46,11 @@
#include <google/protobuf/compiler/cpp/cpp_generator.h>
#include <google/protobuf/compiler/importer.h>
-#include <google/protobuf/descriptor.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
+#include <google/protobuf/descriptor.h>
+#include <google/protobuf/stubs/substitute.h>
#include <google/protobuf/stubs/map_util.h>
#include <google/protobuf/stubs/stl_util.h>
-#include <google/protobuf/stubs/strutil.h>
-#include <google/protobuf/stubs/substitute.h>
#include <google/protobuf/testing/file.h>
#include <google/protobuf/testing/file.h>
diff --git a/src/google/protobuf/compiler/cpp/cpp_enum.cc b/src/google/protobuf/compiler/cpp/cpp_enum.cc
index 9493d5f8..8adee0f5 100644
--- a/src/google/protobuf/compiler/cpp/cpp_enum.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_enum.cc
@@ -81,10 +81,16 @@ void EnumGenerator::GenerateDefinition(io::Printer* printer) {
std::map<string, string> vars;
vars["classname"] = classname_;
vars["short_name"] = descriptor_->name();
- vars["enumbase"] = classname_ + (options_.proto_h ? " : int" : "");
-
- printer->Print(vars, "enum $enumbase$ {\n");
- printer->Annotate("enumbase", descriptor_);
+ vars["enumbase"] = options_.proto_h ? " : int" : "";
+ // These variables are placeholders to pick out the beginning and ends of
+ // identifiers for annotations (when doing so with existing variables would
+ // be ambiguous or impossible). They should never be set to anything but the
+ // empty string.
+ vars["{"] = "";
+ vars["}"] = "";
+
+ printer->Print(vars, "enum $classname$$enumbase$ {\n");
+ printer->Annotate("classname", descriptor_);
printer->Indent();
const EnumValueDescriptor* min_value = descriptor_->value(0);
@@ -102,7 +108,8 @@ void EnumGenerator::GenerateDefinition(io::Printer* printer) {
" PROTOBUF_DEPRECATED" : "";
if (i > 0) printer->Print(",\n");
- printer->Print(vars, "$prefix$$name$$deprecation$ = $number$");
+ printer->Print(vars, "${$$prefix$$name$$}$$deprecation$ = $number$");
+ printer->Annotate("{", "}", descriptor_->value(i));
if (descriptor_->value(i)->number() < min_value->number()) {
min_value = descriptor_->value(i);
@@ -134,14 +141,20 @@ void EnumGenerator::GenerateDefinition(io::Printer* printer) {
}
printer->Print(vars,
- "$dllexport$bool $classname$_IsValid(int value);\n"
- "const $classname$ $prefix$$short_name$_MIN = $prefix$$min_name$;\n"
- "const $classname$ $prefix$$short_name$_MAX = $prefix$$max_name$;\n");
+ "$dllexport$bool $classname$_IsValid(int value);\n"
+ "const $classname$ ${$$prefix$$short_name$_MIN$}$ = "
+ "$prefix$$min_name$;\n");
+ printer->Annotate("{", "}", descriptor_);
+ printer->Print(vars,
+ "const $classname$ ${$$prefix$$short_name$_MAX$}$ = "
+ "$prefix$$max_name$;\n");
+ printer->Annotate("{", "}", descriptor_);
if (generate_array_size_) {
printer->Print(vars,
- "const int $prefix$$short_name$_ARRAYSIZE = "
- "$prefix$$short_name$_MAX + 1;\n\n");
+ "const int ${$$prefix$$short_name$_ARRAYSIZE$}$ = "
+ "$prefix$$short_name$_MAX + 1;\n\n");
+ printer->Annotate("{", "}", descriptor_);
}
if (HasDescriptorMethods(descriptor_->file(), options_)) {
@@ -184,6 +197,8 @@ void EnumGenerator::GenerateSymbolImports(io::Printer* printer) {
vars["nested_name"] = descriptor_->name();
vars["classname"] = classname_;
vars["constexpr"] = options_.proto_h ? "constexpr " : "";
+ vars["{"] = "";
+ vars["}"] = "";
printer->Print(vars, "typedef $classname$ $nested_name$;\n");
for (int j = 0; j < descriptor_->value_count(); j++) {
@@ -191,22 +206,27 @@ void EnumGenerator::GenerateSymbolImports(io::Printer* printer) {
vars["deprecated_attr"] = descriptor_->value(j)->options().deprecated() ?
"GOOGLE_PROTOBUF_DEPRECATED_ATTR " : "";
printer->Print(vars,
- "$deprecated_attr$static $constexpr$const $nested_name$ $tag$ =\n"
+ "$deprecated_attr$static $constexpr$const $nested_name$ ${$$tag$$}$ =\n"
" $classname$_$tag$;\n");
+ printer->Annotate("{", "}", descriptor_->value(j));
}
printer->Print(vars,
"static inline bool $nested_name$_IsValid(int value) {\n"
" return $classname$_IsValid(value);\n"
"}\n"
- "static const $nested_name$ $nested_name$_MIN =\n"
- " $classname$_$nested_name$_MIN;\n"
- "static const $nested_name$ $nested_name$_MAX =\n"
+ "static const $nested_name$ ${$$nested_name$_MIN$}$ =\n"
+ " $classname$_$nested_name$_MIN;\n");
+ printer->Annotate("{", "}", descriptor_);
+ printer->Print(vars,
+ "static const $nested_name$ ${$$nested_name$_MAX$}$ =\n"
" $classname$_$nested_name$_MAX;\n");
+ printer->Annotate("{", "}", descriptor_);
if (generate_array_size_) {
printer->Print(vars,
- "static const int $nested_name$_ARRAYSIZE =\n"
+ "static const int ${$$nested_name$_ARRAYSIZE$}$ =\n"
" $classname$_$nested_name$_ARRAYSIZE;\n");
+ printer->Annotate("{", "}", descriptor_);
}
if (HasDescriptorMethods(descriptor_->file(), options_)) {
@@ -229,35 +249,20 @@ void EnumGenerator::GenerateSymbolImports(io::Printer* printer) {
}
}
-void EnumGenerator::GenerateDescriptorInitializer(io::Printer* printer) {
- std::map<string, string> vars;
- vars["index"] = SimpleItoa(descriptor_->index());
- vars["index_in_metadata"] = SimpleItoa(index_in_metadata_);
-
- if (descriptor_->containing_type() == NULL) {
- printer->Print(vars,
- "file_level_enum_descriptors[$index_in_metadata$] = "
- "file->enum_type($index$);\n");
- } else {
- vars["parent"] = ClassName(descriptor_->containing_type(), false);
- printer->Print(vars,
- "file_level_enum_descriptors[$index_in_metadata$] = "
- "$parent$_descriptor->enum_type($index$);\n");
- }
-}
-
-void EnumGenerator::GenerateMethods(io::Printer* printer) {
+void EnumGenerator::GenerateMethods(int idx, io::Printer* printer) {
std::map<string, string> vars;
vars["classname"] = classname_;
- vars["index_in_metadata"] = SimpleItoa(index_in_metadata_);
+ vars["index_in_metadata"] = SimpleItoa(idx);
vars["constexpr"] = options_.proto_h ? "constexpr " : "";
+ vars["file_namespace"] = FileLevelNamespace(descriptor_->file()->name());
if (HasDescriptorMethods(descriptor_->file(), options_)) {
printer->Print(
vars,
"const ::google::protobuf::EnumDescriptor* $classname$_descriptor() {\n"
- " protobuf_AssignDescriptorsOnce();\n"
- " return file_level_enum_descriptors[$index_in_metadata$];\n"
+ " $file_namespace$::protobuf_AssignDescriptorsOnce();\n"
+ " return "
+ "$file_namespace$::file_level_enum_descriptors[$index_in_metadata$];\n"
"}\n");
}
diff --git a/src/google/protobuf/compiler/cpp/cpp_enum.h b/src/google/protobuf/compiler/cpp/cpp_enum.h
index 0b568c57..0d2488a9 100644
--- a/src/google/protobuf/compiler/cpp/cpp_enum.h
+++ b/src/google/protobuf/compiler/cpp/cpp_enum.h
@@ -86,13 +86,10 @@ class EnumGenerator {
// Source file stuff.
- // Generate code that initializes the global variable storing the enum's
- // descriptor.
- void GenerateDescriptorInitializer(io::Printer* printer);
-
// Generate non-inline methods related to the enum, such as IsValidValue().
- // Goes in the .cc file.
- void GenerateMethods(io::Printer* printer);
+ // Goes in the .cc file. EnumDescriptors are stored in an array, idx is
+ // the index in this array that corresponds with this enum.
+ void GenerateMethods(int idx, io::Printer* printer);
private:
const EnumDescriptor* descriptor_;
@@ -101,8 +98,6 @@ class EnumGenerator {
// whether to generate the *_ARRAYSIZE constant.
const bool generate_array_size_;
- int index_in_metadata_;
-
friend class FileGenerator;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumGenerator);
};
diff --git a/src/google/protobuf/compiler/cpp/cpp_enum_field.cc b/src/google/protobuf/compiler/cpp/cpp_enum_field.cc
index b6658079..3d5b5b8d 100644
--- a/src/google/protobuf/compiler/cpp/cpp_enum_field.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_enum_field.cc
@@ -74,27 +74,26 @@ GeneratePrivateMembers(io::Printer* printer) const {
void EnumFieldGenerator::
GenerateAccessorDeclarations(io::Printer* printer) const {
+ printer->Print(variables_, "$deprecated_attr$$type$ $name$() const;\n");
+ printer->Annotate("name", descriptor_);
printer->Print(variables_,
- "$deprecated_attr$$type$ $name$() const;\n"
- "$deprecated_attr$void set_$name$($type$ value);\n");
+ "$deprecated_attr$void ${$set_$name$$}$($type$ value);\n");
+ printer->Annotate("{", "}", descriptor_);
}
void EnumFieldGenerator::
-GenerateInlineAccessorDefinitions(io::Printer* printer,
- bool is_inline) const {
- std::map<string, string> variables(variables_);
- variables["inline"] = is_inline ? "inline " : "";
- printer->Print(variables,
- "$inline$$type$ $classname$::$name$() const {\n"
+GenerateInlineAccessorDefinitions(io::Printer* printer) const {
+ printer->Print(variables_,
+ "inline $type$ $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" return static_cast< $type$ >($name$_);\n"
"}\n"
- "$inline$void $classname$::set_$name$($type$ value) {\n");
+ "inline void $classname$::set_$name$($type$ value) {\n");
if (!HasPreservingUnknownEnumSemantics(descriptor_->file())) {
- printer->Print(variables,
+ printer->Print(variables_,
" assert($type$_IsValid(value));\n");
}
- printer->Print(variables,
+ printer->Print(variables_,
" $set_hasbit$\n"
" $name$_ = value;\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
@@ -113,7 +112,7 @@ GenerateMergingCode(io::Printer* printer) const {
void EnumFieldGenerator::
GenerateSwappingCode(io::Printer* printer) const {
- printer->Print(variables_, "std::swap($name$_, other->$name$_);\n");
+ printer->Print(variables_, "swap($name$_, other->$name$_);\n");
}
void EnumFieldGenerator::
@@ -143,12 +142,14 @@ GenerateMergeFromCodedStream(io::Printer* printer) const {
if (UseUnknownFieldSet(descriptor_->file(), options_)) {
printer->Print(variables_,
"} else {\n"
- " mutable_unknown_fields()->AddVarint($number$, value);\n");
+ " mutable_unknown_fields()->AddVarint(\n"
+ " $number$, static_cast< ::google::protobuf::uint64>(value));\n");
} else {
printer->Print(
"} else {\n"
" unknown_fields_stream.WriteVarint32($tag$u);\n"
- " unknown_fields_stream.WriteVarint32(value);\n",
+ " unknown_fields_stream.WriteVarint32(\n"
+ " static_cast< ::google::protobuf::uint32>(value));\n",
"tag", SimpleItoa(internal::WireFormat::MakeTag(descriptor_)));
}
printer->Print(variables_,
@@ -189,24 +190,21 @@ EnumOneofFieldGenerator(const FieldDescriptor* descriptor,
EnumOneofFieldGenerator::~EnumOneofFieldGenerator() {}
void EnumOneofFieldGenerator::
-GenerateInlineAccessorDefinitions(io::Printer* printer,
- bool is_inline) const {
- std::map<string, string> variables(variables_);
- variables["inline"] = is_inline ? "inline " : "";
- printer->Print(variables,
- "$inline$$type$ $classname$::$name$() const {\n"
+GenerateInlineAccessorDefinitions(io::Printer* printer) const {
+ printer->Print(variables_,
+ "inline $type$ $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" if (has_$name$()) {\n"
" return static_cast< $type$ >($oneof_prefix$$name$_);\n"
" }\n"
" return static_cast< $type$ >($default$);\n"
"}\n"
- "$inline$void $classname$::set_$name$($type$ value) {\n");
+ "inline void $classname$::set_$name$($type$ value) {\n");
if (!HasPreservingUnknownEnumSemantics(descriptor_->file())) {
- printer->Print(variables,
+ printer->Print(variables_,
" assert($type$_IsValid(value));\n");
}
- printer->Print(variables,
+ printer->Print(variables_,
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
@@ -228,9 +226,8 @@ GenerateSwappingCode(io::Printer* printer) const {
void EnumOneofFieldGenerator::
GenerateConstructorCode(io::Printer* printer) const {
- printer->Print(
- variables_,
- " $classname$_default_oneof_instance_.$name$_ = $default$;\n");
+ printer->Print(variables_,
+ "$ns$::_$classname$_default_instance_.$name$_ = $default$;\n");
}
// ===================================================================
@@ -257,49 +254,56 @@ GeneratePrivateMembers(io::Printer* printer) const {
void RepeatedEnumFieldGenerator::
GenerateAccessorDeclarations(io::Printer* printer) const {
printer->Print(variables_,
- "$deprecated_attr$$type$ $name$(int index) const;\n"
- "$deprecated_attr$void set_$name$(int index, $type$ value);\n"
- "$deprecated_attr$void add_$name$($type$ value);\n");
+ "$deprecated_attr$$type$ $name$(int index) const;\n");
+ printer->Annotate("name", descriptor_);
+ printer->Print(
+ variables_,
+ "$deprecated_attr$void ${$set_$name$$}$(int index, $type$ value);\n");
+ printer->Annotate("{", "}", descriptor_);
+ printer->Print(variables_,
+ "$deprecated_attr$void ${$add_$name$$}$($type$ value);\n");
+ printer->Annotate("{", "}", descriptor_);
+ printer->Print(
+ variables_,
+ "$deprecated_attr$const ::google::protobuf::RepeatedField<int>& $name$() const;\n");
+ printer->Annotate("name", descriptor_);
printer->Print(variables_,
- "$deprecated_attr$const ::google::protobuf::RepeatedField<int>& $name$() const;\n"
- "$deprecated_attr$::google::protobuf::RepeatedField<int>* mutable_$name$();\n");
+ "$deprecated_attr$::google::protobuf::RepeatedField<int>* "
+ "${$mutable_$name$$}$();\n");
+ printer->Annotate("{", "}", descriptor_);
}
void RepeatedEnumFieldGenerator::
-GenerateInlineAccessorDefinitions(io::Printer* printer,
- bool is_inline) const {
- std::map<string, string> variables(variables_);
- variables["inline"] = is_inline ? "inline " : "";
- printer->Print(variables,
- "$inline$$type$ $classname$::$name$(int index) const {\n"
+GenerateInlineAccessorDefinitions(io::Printer* printer) const {
+ printer->Print(variables_,
+ "inline $type$ $classname$::$name$(int index) const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" return static_cast< $type$ >($name$_.Get(index));\n"
"}\n"
- "$inline$void $classname$::set_$name$(int index, $type$ value) {\n");
+ "inline void $classname$::set_$name$(int index, $type$ value) {\n");
if (!HasPreservingUnknownEnumSemantics(descriptor_->file())) {
- printer->Print(variables,
+ printer->Print(variables_,
" assert($type$_IsValid(value));\n");
}
- printer->Print(variables,
+ printer->Print(variables_,
" $name$_.Set(index, value);\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n"
- "$inline$void $classname$::add_$name$($type$ value) {\n");
+ "inline void $classname$::add_$name$($type$ value) {\n");
if (!HasPreservingUnknownEnumSemantics(descriptor_->file())) {
- printer->Print(variables,
+ printer->Print(variables_,
" assert($type$_IsValid(value));\n");
}
- printer->Print(variables,
+ printer->Print(variables_,
" $name$_.Add(value);\n"
" // @@protoc_insertion_point(field_add:$full_name$)\n"
- "}\n");
- printer->Print(variables,
- "$inline$const ::google::protobuf::RepeatedField<int>&\n"
+ "}\n"
+ "inline const ::google::protobuf::RepeatedField<int>&\n"
"$classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_list:$full_name$)\n"
" return $name$_;\n"
"}\n"
- "$inline$::google::protobuf::RepeatedField<int>*\n"
+ "inline ::google::protobuf::RepeatedField<int>*\n"
"$classname$::mutable_$name$() {\n"
" // @@protoc_insertion_point(field_mutable_list:$full_name$)\n"
" return &$name$_;\n"
@@ -318,7 +322,7 @@ GenerateMergingCode(io::Printer* printer) const {
void RepeatedEnumFieldGenerator::
GenerateSwappingCode(io::Printer* printer) const {
- printer->Print(variables_, "$name$_.UnsafeArenaSwap(&other->$name$_);\n");
+ printer->Print(variables_, "$name$_.InternalSwap(&other->$name$_);\n");
}
void RepeatedEnumFieldGenerator::
@@ -344,12 +348,14 @@ GenerateMergeFromCodedStream(io::Printer* printer) const {
if (UseUnknownFieldSet(descriptor_->file(), options_)) {
printer->Print(variables_,
"} else {\n"
- " mutable_unknown_fields()->AddVarint($number$, value);\n");
+ " mutable_unknown_fields()->AddVarint(\n"
+ " $number$, static_cast< ::google::protobuf::uint64>(value));\n");
} else {
printer->Print(
"} else {\n"
" unknown_fields_stream.WriteVarint32(tag);\n"
- " unknown_fields_stream.WriteVarint32(value);\n");
+ " unknown_fields_stream.WriteVarint32(\n"
+ " static_cast< ::google::protobuf::uint32>(value));\n");
}
printer->Print("}\n");
}
@@ -391,7 +397,7 @@ GenerateMergeFromCodedStreamWithPacking(io::Printer* printer) const {
"::google::protobuf::uint32 length;\n"
"DO_(input->ReadVarint32(&length));\n"
"::google::protobuf::io::CodedInputStream::Limit limit = "
- "input->PushLimit(length);\n"
+ "input->PushLimit(static_cast<int>(length));\n"
"while (input->BytesUntilLimit() > 0) {\n"
" int value;\n"
" DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<\n"
@@ -407,11 +413,13 @@ GenerateMergeFromCodedStreamWithPacking(io::Printer* printer) const {
" } else {\n");
if (UseUnknownFieldSet(descriptor_->file(), options_)) {
printer->Print(variables_,
- " mutable_unknown_fields()->AddVarint($number$, value);\n");
+ " mutable_unknown_fields()->AddVarint(\n"
+ " $number$, static_cast< ::google::protobuf::uint64>(value));\n");
} else {
printer->Print(variables_,
" unknown_fields_stream.WriteVarint32(tag);\n"
- " unknown_fields_stream.WriteVarint32(value);\n");
+ " unknown_fields_stream.WriteVarint32(\n"
+ " static_cast< ::google::protobuf::uint32>(value));\n");
}
printer->Print(
" }\n");
@@ -432,11 +440,12 @@ GenerateSerializeWithCachedSizes(io::Printer* printer) const {
" $number$,\n"
" ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,\n"
" output);\n"
- " output->WriteVarint32(_$name$_cached_byte_size_);\n"
+ " output->WriteVarint32(\n"
+ " static_cast< ::google::protobuf::uint32>(_$name$_cached_byte_size_));\n"
"}\n");
}
printer->Print(variables_,
- "for (int i = 0; i < this->$name$_size(); i++) {\n");
+ "for (int i = 0, n = this->$name$_size(); i < n; i++) {\n");
if (descriptor_->is_packed()) {
printer->Print(variables_,
" ::google::protobuf::internal::WireFormatLite::WriteEnumNoTag(\n"
@@ -460,21 +469,16 @@ GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const {
" ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,\n"
" target);\n"
" target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray("
- " _$name$_cached_byte_size_, target);\n"
- "}\n");
- }
- printer->Print(variables_,
- "for (int i = 0; i < this->$name$_size(); i++) {\n");
- if (descriptor_->is_packed()) {
- printer->Print(variables_,
+ " static_cast< ::google::protobuf::uint32>(\n"
+ " _$name$_cached_byte_size_), target);\n"
" target = ::google::protobuf::internal::WireFormatLite::WriteEnumNoTagToArray(\n"
- " this->$name$(i), target);\n");
+ " this->$name$_, target);\n"
+ "}\n");
} else {
printer->Print(variables_,
- " target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray(\n"
- " $number$, this->$name$(i), target);\n");
+ "target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray(\n"
+ " $number$, this->$name$_, target);\n");
}
- printer->Print("}\n");
}
void RepeatedEnumFieldGenerator::
@@ -482,19 +486,20 @@ GenerateByteSize(io::Printer* printer) const {
printer->Print(variables_,
"{\n"
" size_t data_size = 0;\n"
- " unsigned int count = this->$name$_size();");
+ " unsigned int count = static_cast<unsigned int>(this->$name$_size());");
printer->Indent();
printer->Print(variables_,
"for (unsigned int i = 0; i < count; i++) {\n"
" data_size += ::google::protobuf::internal::WireFormatLite::EnumSize(\n"
- " this->$name$(i));\n"
+ " this->$name$(static_cast<int>(i)));\n"
"}\n");
if (descriptor_->is_packed()) {
printer->Print(variables_,
"if (data_size > 0) {\n"
" total_size += $tag_size$ +\n"
- " ::google::protobuf::internal::WireFormatLite::Int32Size(data_size);\n"
+ " ::google::protobuf::internal::WireFormatLite::Int32Size(\n"
+ " static_cast< ::google::protobuf::int32>(data_size));\n"
"}\n"
"int cached_size = ::google::protobuf::internal::ToCachedSize(data_size);\n"
"GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();\n"
diff --git a/src/google/protobuf/compiler/cpp/cpp_enum_field.h b/src/google/protobuf/compiler/cpp/cpp_enum_field.h
index 3ecd7ba8..d0e87b79 100644
--- a/src/google/protobuf/compiler/cpp/cpp_enum_field.h
+++ b/src/google/protobuf/compiler/cpp/cpp_enum_field.h
@@ -52,8 +52,7 @@ class EnumFieldGenerator : public FieldGenerator {
// implements FieldGenerator ---------------------------------------
void GeneratePrivateMembers(io::Printer* printer) const;
void GenerateAccessorDeclarations(io::Printer* printer) const;
- void GenerateInlineAccessorDefinitions(io::Printer* printer,
- bool is_inline) const;
+ void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateMergingCode(io::Printer* printer) const;
void GenerateSwappingCode(io::Printer* printer) const;
@@ -79,8 +78,7 @@ class EnumOneofFieldGenerator : public EnumFieldGenerator {
~EnumOneofFieldGenerator();
// implements FieldGenerator ---------------------------------------
- void GenerateInlineAccessorDefinitions(io::Printer* printer,
- bool is_inline) const;
+ void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateSwappingCode(io::Printer* printer) const;
void GenerateConstructorCode(io::Printer* printer) const;
@@ -98,8 +96,7 @@ class RepeatedEnumFieldGenerator : public FieldGenerator {
// implements FieldGenerator ---------------------------------------
void GeneratePrivateMembers(io::Printer* printer) const;
void GenerateAccessorDeclarations(io::Printer* printer) const;
- void GenerateInlineAccessorDefinitions(io::Printer* printer,
- bool is_inline) const;
+ void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateMergingCode(io::Printer* printer) const;
void GenerateSwappingCode(io::Printer* printer) const;
diff --git a/src/google/protobuf/compiler/cpp/cpp_extension.cc b/src/google/protobuf/compiler/cpp/cpp_extension.cc
index e4fce461..0a4e0bb9 100644
--- a/src/google/protobuf/compiler/cpp/cpp_extension.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_extension.cc
@@ -35,9 +35,10 @@
#include <google/protobuf/compiler/cpp/cpp_extension.h>
#include <map>
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
-#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/descriptor.pb.h>
+#include <google/protobuf/stubs/strutil.h>
+
namespace google {
namespace protobuf {
@@ -166,46 +167,6 @@ void ExtensionGenerator::GenerateDefinition(io::Printer* printer) {
" $name$($constant_name$, $default$);\n");
}
-void ExtensionGenerator::GenerateRegistration(io::Printer* printer) {
- std::map<string, string> vars;
- vars["extendee" ] = ExtendeeClassName(descriptor_);
- vars["number" ] = SimpleItoa(descriptor_->number());
- vars["field_type" ] = SimpleItoa(static_cast<int>(descriptor_->type()));
- vars["is_repeated"] = descriptor_->is_repeated() ? "true" : "false";
- vars["is_packed" ] = (descriptor_->is_repeated() &&
- descriptor_->options().packed())
- ? "true" : "false";
-
- switch (descriptor_->cpp_type()) {
- case FieldDescriptor::CPPTYPE_ENUM:
- printer->Print(
- vars,
- "::google::protobuf::internal::ExtensionSet::RegisterEnumExtension(\n"
- " $extendee$::internal_default_instance(),\n"
- " $number$, $field_type$, $is_repeated$, $is_packed$,\n");
- printer->Print(
- " &$type$_IsValid);\n",
- "type", ClassName(descriptor_->enum_type(), true));
- break;
- case FieldDescriptor::CPPTYPE_MESSAGE:
- printer->Print(
- vars,
- "::google::protobuf::internal::ExtensionSet::RegisterMessageExtension(\n"
- " $extendee$::internal_default_instance(),\n"
- " $number$, $field_type$, $is_repeated$, $is_packed$,\n");
- printer->Print(" $type$::internal_default_instance());\n", "type",
- ClassName(descriptor_->message_type(), true));
- break;
- default:
- printer->Print(
- vars,
- "::google::protobuf::internal::ExtensionSet::RegisterExtension(\n"
- " $extendee$::internal_default_instance(),\n"
- " $number$, $field_type$, $is_repeated$, $is_packed$);\n");
- break;
- }
-}
-
} // namespace cpp
} // namespace compiler
} // namespace protobuf
diff --git a/src/google/protobuf/compiler/cpp/cpp_extension.h b/src/google/protobuf/compiler/cpp/cpp_extension.h
index 1c1caf1f..30236d71 100644
--- a/src/google/protobuf/compiler/cpp/cpp_extension.h
+++ b/src/google/protobuf/compiler/cpp/cpp_extension.h
@@ -67,9 +67,6 @@ class ExtensionGenerator {
// Source file stuff.
void GenerateDefinition(io::Printer* printer);
- // Generate code to register the extension.
- void GenerateRegistration(io::Printer* printer);
-
private:
const FieldDescriptor* descriptor_;
string type_traits_;
diff --git a/src/google/protobuf/compiler/cpp/cpp_field.cc b/src/google/protobuf/compiler/cpp/cpp_field.cc
index 4480a9d2..f8e11855 100644
--- a/src/google/protobuf/compiler/cpp/cpp_field.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_field.cc
@@ -61,6 +61,7 @@ using internal::WireFormat;
void SetCommonFieldVariables(const FieldDescriptor* descriptor,
std::map<string, string>* variables,
const Options& options) {
+ (*variables)["ns"] = Namespace(descriptor);
(*variables)["name"] = FieldName(descriptor);
(*variables)["index"] = SimpleItoa(descriptor->index());
(*variables)["number"] = SimpleItoa(descriptor->number());
@@ -95,6 +96,13 @@ void SetCommonFieldVariables(const FieldDescriptor* descriptor,
// By default, empty string, so that generic code used for both oneofs and
// singular fields can be written.
(*variables)["oneof_prefix"] = "";
+
+ // These variables are placeholders to pick out the beginning and ends of
+ // identifiers for annotations (when doing so with existing variables would
+ // be ambiguous or impossible). They should never be set to anything but the
+ // empty string.
+ (*variables)["{"] = "";
+ (*variables)["}"] = "";
}
void SetCommonOneofFieldVariables(const FieldDescriptor* descriptor,
@@ -194,7 +202,6 @@ const FieldGenerator& FieldGeneratorMap::get(
return *field_generators_[field->index()];
}
-
} // namespace cpp
} // namespace compiler
} // namespace protobuf
diff --git a/src/google/protobuf/compiler/cpp/cpp_field.h b/src/google/protobuf/compiler/cpp/cpp_field.h
index 00dc25d4..891e30f6 100644
--- a/src/google/protobuf/compiler/cpp/cpp_field.h
+++ b/src/google/protobuf/compiler/cpp/cpp_field.h
@@ -109,19 +109,19 @@ class FieldGenerator {
// Generate inline definitions of depenent accessor functions for this field.
// These are placed inside the header after all class definitions.
virtual void GenerateDependentInlineAccessorDefinitions(
- io::Printer* printer) const {}
+ io::Printer* printer) const {}
// Generate inline definitions of accessor functions for this field.
// These are placed inside the header after all class definitions.
// In non-.proto.h mode, this generates dependent accessor functions as well.
virtual void GenerateInlineAccessorDefinitions(
- io::Printer* printer, bool is_inline) const = 0;
+ io::Printer* printer) const = 0;
// Generate definitions of accessors that aren't inlined. These are
// placed somewhere in the .cc file.
// Most field types don't need this, so the default implementation is empty.
virtual void GenerateNonInlineAccessorDefinitions(
- io::Printer* /*printer*/) const {}
+ io::Printer* /*printer*/) const {}
// Generate lines of code (statements, not declarations) which clear the
// field. This is used to define the clear_$name$() method
@@ -180,10 +180,6 @@ class FieldGenerator {
virtual void GenerateDefaultInstanceAllocator(io::Printer* /*printer*/)
const {}
- // Generate code that should be run when ShutdownProtobufLibrary() is called,
- // to delete all dynamically-allocated objects.
- virtual void GenerateShutdownCode(io::Printer* /*printer*/) const {}
-
// Generate lines to decode this field, which will be placed inside the
// message's MergeFromCodedStream() method.
virtual void GenerateMergeFromCodedStream(io::Printer* printer) const = 0;
@@ -233,7 +229,6 @@ class FieldGeneratorMap {
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGeneratorMap);
};
-
} // namespace cpp
} // namespace compiler
} // namespace protobuf
diff --git a/src/google/protobuf/compiler/cpp/cpp_file.cc b/src/google/protobuf/compiler/cpp/cpp_file.cc
index d8fda59c..52a16835 100644
--- a/src/google/protobuf/compiler/cpp/cpp_file.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_file.cc
@@ -39,6 +39,7 @@
#include <google/protobuf/stubs/shared_ptr.h>
#endif
#include <set>
+#include <vector>
#include <google/protobuf/compiler/cpp/cpp_enum.h>
#include <google/protobuf/compiler/cpp/cpp_service.h>
@@ -55,29 +56,23 @@ namespace protobuf {
namespace compiler {
namespace cpp {
-// ===================================================================
-
FileGenerator::FileGenerator(const FileDescriptor* file, const Options& options)
: file_(file),
options_(options),
- message_generators_owner_(
- new google::protobuf::scoped_ptr<MessageGenerator>[ file->message_type_count() ]),
+ scc_analyzer_(options),
enum_generators_owner_(
- new google::protobuf::scoped_ptr<EnumGenerator>[ file->enum_type_count() ]),
+ new google::protobuf::scoped_ptr<EnumGenerator>[file->enum_type_count()]),
service_generators_owner_(
- new google::protobuf::scoped_ptr<ServiceGenerator>[ file->service_count() ]),
+ new google::protobuf::scoped_ptr<ServiceGenerator>[file->service_count()]),
extension_generators_owner_(
- new google::protobuf::scoped_ptr<ExtensionGenerator>[ file->extension_count() ]) {
-
- for (int i = 0; i < file->message_type_count(); i++) {
- message_generators_owner_[i].reset(
- new MessageGenerator(file->message_type(i), options));
- message_generators_owner_[i]->Flatten(&message_generators_);
- }
-
- for (int i = 0; i < message_generators_.size(); i++) {
- message_generators_[i]->AddGenerators(&enum_generators_,
- &extension_generators_);
+ new google::protobuf::scoped_ptr<ExtensionGenerator>[file->extension_count()]) {
+ std::vector<const Descriptor*> msgs = FlattenMessagesInFile(file);
+ for (int i = 0; i < msgs.size(); i++) {
+ // Deleted in destructor
+ MessageGenerator* msg_gen =
+ new MessageGenerator(msgs[i], i, options, &scc_analyzer_);
+ message_generators_.push_back(msg_gen);
+ msg_gen->AddGenerators(&enum_generators_, &extension_generators_);
}
for (int i = 0; i < file->enum_type_count(); i++) {
@@ -91,6 +86,11 @@ FileGenerator::FileGenerator(const FileDescriptor* file, const Options& options)
new ServiceGenerator(file->service(i), options));
service_generators_.push_back(service_generators_owner_[i].get());
}
+ if (HasGenericServices(file_, options_)) {
+ for (int i = 0; i < service_generators_.size(); i++) {
+ service_generators_[i]->index_in_metadata_ = i;
+ }
+ }
for (int i = 0; i < file->extension_count(); i++) {
extension_generators_owner_[i].reset(
@@ -98,53 +98,86 @@ FileGenerator::FileGenerator(const FileDescriptor* file, const Options& options)
extension_generators_.push_back(extension_generators_owner_[i].get());
}
+
package_parts_ = Split(file_->package(), ".", true);
}
-FileGenerator::~FileGenerator() {}
+FileGenerator::~FileGenerator() {
+ for (int i = 0; i < message_generators_.size(); i++) {
+ delete message_generators_[i];
+ }
+}
+
+void FileGenerator::GenerateMacroUndefs(io::Printer* printer) {
+ // Only do this for protobuf's own types. There are some google3 protos using
+ // macros as field names and the generated code compiles after the macro
+ // expansion. Undefing these macros actually breaks such code.
+ if (file_->name() != "google/protobuf/compiler/plugin.proto") {
+ return;
+ }
+ std::vector<string> names_to_undef;
+ std::vector<const FieldDescriptor*> fields;
+ ListAllFields(file_, &fields);
+ for (int i = 0; i < fields.size(); i++) {
+ const string& name = fields[i]->name();
+ static const char* kMacroNames[] = {"major", "minor"};
+ for (int i = 0; i < GOOGLE_ARRAYSIZE(kMacroNames); ++i) {
+ if (name == kMacroNames[i]) {
+ names_to_undef.push_back(name);
+ break;
+ }
+ }
+ }
+ for (int i = 0; i < names_to_undef.size(); ++i) {
+ printer->Print(
+ "#ifdef $name$\n"
+ "#undef $name$\n"
+ "#endif\n",
+ "name", names_to_undef[i]);
+ }
+}
void FileGenerator::GenerateHeader(io::Printer* printer) {
printer->Print(
"// @@protoc_insertion_point(includes)\n");
-
- GenerateForwardDeclarations(printer);
-
- // Open namespace.
- GenerateNamespaceOpeners(printer);
+ GenerateMacroUndefs(printer);
GenerateGlobalStateFunctionDeclarations(printer);
- printer->Print("\n");
+ GenerateForwardDeclarations(printer);
- GenerateEnumDefinitions(printer);
+ {
+ NamespaceOpener ns(Namespace(file_), printer);
- printer->Print(kThickSeparator);
- printer->Print("\n");
+ printer->Print("\n");
- GenerateMessageDefinitions(printer);
+ GenerateEnumDefinitions(printer);
- printer->Print("\n");
- printer->Print(kThickSeparator);
- printer->Print("\n");
+ printer->Print(kThickSeparator);
+ printer->Print("\n");
- GenerateServiceDefinitions(printer);
+ GenerateMessageDefinitions(printer);
- GenerateExtensionIdentifiers(printer);
+ printer->Print("\n");
+ printer->Print(kThickSeparator);
+ printer->Print("\n");
- printer->Print("\n");
- printer->Print(kThickSeparator);
- printer->Print("\n");
+ GenerateServiceDefinitions(printer);
- GenerateInlineFunctionDefinitions(printer);
+ GenerateExtensionIdentifiers(printer);
- printer->Print(
- "\n"
- "// @@protoc_insertion_point(namespace_scope)\n"
- "\n");
+ printer->Print("\n");
+ printer->Print(kThickSeparator);
+ printer->Print("\n");
+
+ GenerateInlineFunctionDefinitions(printer);
- // Close up namespace.
- GenerateNamespaceClosers(printer);
+ printer->Print(
+ "\n"
+ "// @@protoc_insertion_point(namespace_scope)\n"
+ "\n");
+ }
// We need to specialize some templates in the ::google::protobuf namespace:
GenerateProto2NamespaceEnumSpecializations(printer);
@@ -195,6 +228,7 @@ void FileGenerator::GeneratePBHeader(io::Printer* printer,
} else {
GenerateLibraryIncludes(printer);
}
+
GenerateDependencyIncludes(printer);
GenerateMetadataPragma(printer, info_path);
@@ -206,15 +240,12 @@ void FileGenerator::GeneratePBHeader(io::Printer* printer,
// TODO(gerbens) remove this.
printer->Print(
"// @@protoc_insertion_point(includes)\n");
-
- // Open namespace.
- GenerateNamespaceOpeners(printer);
- printer->Print(
- "\n"
- "// @@protoc_insertion_point(namespace_scope)\n");
- // Close up namespace.
- GenerateNamespaceClosers(printer);
-
+ {
+ NamespaceOpener ns(Namespace(file_), printer);
+ printer->Print(
+ "\n"
+ "// @@protoc_insertion_point(namespace_scope)\n");
+ }
printer->Print(
"\n"
"// @@protoc_insertion_point(global_scope)\n"
@@ -224,7 +255,7 @@ void FileGenerator::GeneratePBHeader(io::Printer* printer,
GenerateBottomHeaderGuard(printer, filename_identifier);
}
-void FileGenerator::GenerateSource(io::Printer* printer) {
+void FileGenerator::GenerateSourceIncludes(io::Printer* printer) {
const bool use_system_include = IsWellKnownMessage(file_);
string header =
StripProto(file_->name()) + (options_.proto_h ? ".proto.h" : ".pb.h");
@@ -232,9 +263,6 @@ void FileGenerator::GenerateSource(io::Printer* printer) {
"// Generated by the protocol buffer compiler. DO NOT EDIT!\n"
"// source: $filename$\n"
"\n"
- // The generated code calls accessors that might be deprecated. We don't
- // want the compiler to warn in generated code.
- "#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION\n"
"#include $left$$header$$right$\n"
"\n"
"#include <algorithm>\n" // for swap()
@@ -275,83 +303,147 @@ void FileGenerator::GenerateSource(io::Printer* printer) {
}
}
+ // TODO(gerbens) Remove this when all code in google is using the same
+ // proto library. This is a temporary hack to force build errors if
+ // the proto library is compiled with GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ // and is also linking internal proto2. This is to prevent regressions while
+ // we work cleaning up the code base. After this is completed and we have
+ // one proto lib all code uses this should be removed.
+ printer->Print(
+ "// This is a temporary google only hack\n"
+ "#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS\n"
+ "#include \"third_party/protobuf/version.h\"\n"
+ "#endif\n");
+
printer->Print(
"// @@protoc_insertion_point(includes)\n");
+}
+
+void FileGenerator::GenerateSourceDefaultInstance(int idx,
+ io::Printer* printer) {
+ printer->Print(
+ "class $classname$DefaultTypeInternal {\n"
+ " public:\n"
+ " ::google::protobuf::internal::ExplicitlyConstructed<$classname$>\n"
+ " _instance;\n",
+ "classname", message_generators_[idx]->classname_);
+ printer->Indent();
+ message_generators_[idx]->GenerateExtraDefaultFields(printer);
+ printer->Outdent();
+ printer->Print("} _$classname$_default_instance_;\n", "classname",
+ message_generators_[idx]->classname_);
+}
- GenerateNamespaceOpeners(printer);
+namespace {
- for (int i = 0; i < message_generators_.size(); i++) {
- if (IsMapEntryMessage(message_generators_[i]->descriptor_)) continue;
- printer->Print(
- "class $classname$DefaultTypeInternal : "
- "public ::google::protobuf::internal::ExplicitlyConstructed<$classname$> {};\n"
- "$classname$DefaultTypeInternal _$classname$_default_instance_;\n",
- "classname", message_generators_[i]->classname_);
+// Generates weak symbol declarations for types that are to be considered weakly
+// referenced.
+void GenerateWeakDeclarations(
+ const FileDescriptor* file, const Options& options,
+ SCCAnalyzer* scc_analyzer,
+ io::Printer* printer) {
+ std::vector<const FieldDescriptor*> fields;
+ ListAllFields(file, &fields);
+
+ // To ensure determinism and minimize the number of namespace statements,
+ // we output the forward declarations sorted on namespace and type / function
+ // name.
+ std::set<std::pair<string, string> > messages;
+ std::set<std::pair<string, string> > inits;
+ for (int i = 0; i < fields.size(); ++i) {
+ const FieldDescriptor* field = fields[i];
+ bool is_weak = IsImplicitWeakField(field, options);
+ if (is_weak) {
+ const Descriptor* msg = field->message_type();
+ string flns = FileLevelNamespace(msg);
+ string repr = ClassName(scc_analyzer->GetSCC(msg)->GetRepresentative());
+ inits.insert(std::make_pair(flns, "InitDefaults" + repr));
+ inits.insert(std::make_pair(flns, "AddDescriptors"));
+ messages.insert(std::make_pair(Namespace(msg), ClassName(msg)));
+ }
}
- if (HasDescriptorMethods(file_, options_)) {
+ if (messages.empty()) {
+ return;
+ }
+
+ printer->Print("\n");
+ NamespaceOpener ns(printer);
+ for (std::set<std::pair<string, string> >::const_iterator it =
+ messages.begin();
+ it != messages.end(); ++it) {
+ ns.ChangeTo(it->first);
printer->Print(
- "\n"
- "namespace {\n"
- "\n");
+ "extern __attribute__((weak)) $classname$DefaultTypeInternal "
+ "_$classname$_default_instance_;\n",
+ "classname", it->second);
+ }
+ for (std::set<std::pair<string, string> >::const_iterator it = inits.begin();
+ it != inits.end(); ++it) {
+ ns.ChangeTo(it->first);
+ printer->Print("void $name$() __attribute__((weak));\n",
+ "name", it->second);
+ }
+}
- if (!message_generators_.empty()) {
- printer->Print("::google::protobuf::Metadata file_level_metadata[$size$];\n",
- "size", SimpleItoa(message_generators_.size()));
- }
- if (!enum_generators_.empty()) {
- printer->Print(
- "const ::google::protobuf::EnumDescriptor* "
- "file_level_enum_descriptors[$size$];\n",
- "size", SimpleItoa(enum_generators_.size()));
- }
- if (HasGenericServices(file_, options_) && file_->service_count() > 0) {
- printer->Print(
- "const ::google::protobuf::ServiceDescriptor* "
- "file_level_service_descriptors[$size$];\n",
- "size", SimpleItoa(file_->service_count()));
- }
+} // namespace
- for (int i = 0; i < message_generators_.size(); i++) {
- message_generators_[i]->index_in_metadata_ = i;
- message_generators_[i]->GenerateDescriptorDeclarations(printer);
- }
- for (int i = 0; i < enum_generators_.size(); i++) {
- enum_generators_[i]->index_in_metadata_ = i;
- }
- if (HasGenericServices(file_, options_)) {
- for (int i = 0; i < service_generators_.size(); i++) {
- service_generators_[i]->index_in_metadata_ = i;
- }
+void FileGenerator::GenerateSourceForMessage(int idx, io::Printer* printer) {
+ GenerateSourceIncludes(printer);
+ GenerateWeakDeclarations(file_, options_, &scc_analyzer_, printer);
+
+ { // package namespace
+ NamespaceOpener ns(Namespace(file_), printer);
+
+ // Define default instances
+ GenerateSourceDefaultInstance(idx, printer);
+ if (UsingImplicitWeakFields(file_, options_)) {
+ printer->Print("void $classname$_ReferenceStrong() {}\n", "classname",
+ message_generators_[idx]->classname_);
}
+ // Generate classes.
+ printer->Print("\n");
+ message_generators_[idx]->GenerateClassMethods(printer);
+
printer->Print(
+ "\n"
+ "// @@protoc_insertion_point(namespace_scope)\n");
+ } // end package namespace
+
+ if (IsSCCRepresentative(message_generators_[idx]->descriptor_)) {
+ NamespaceOpener ns(FileLevelNamespace(file_), printer);
+ GenerateInitForSCC(GetSCC(message_generators_[idx]->descriptor_), printer);
+ }
+
+ printer->Print(
"\n"
- "} // namespace\n"
- "\n");
+ "// @@protoc_insertion_point(global_scope)\n");
+}
+
+void FileGenerator::GenerateGlobalSource(io::Printer* printer) {
+ GenerateSourceIncludes(printer);
+ GenerateWeakDeclarations(file_, options_, &scc_analyzer_, printer);
+
+ // TODO(gerbens) Generate tables here
+
+ // Define the code to initialize reflection. This code uses a global
+ // constructor to register reflection data with the runtime pre-main.
+ if (HasDescriptorMethods(file_, options_)) {
+ NamespaceOpener ns(FileLevelNamespace(file_), printer);
+ GenerateReflectionInitializationCode(printer);
}
- // Define our externally-visible BuildDescriptors() function. (For the lite
- // library, all this does is initialize default instances.)
- GenerateBuildDescriptors(printer);
+ NamespaceOpener ns(Namespace(file_), printer);
// Generate enums.
for (int i = 0; i < enum_generators_.size(); i++) {
- enum_generators_[i]->GenerateMethods(printer);
+ enum_generators_[i]->GenerateMethods(i, printer);
}
- // Generate classes.
- for (int i = 0; i < message_generators_.size(); i++) {
- printer->Print("\n");
- printer->Print(kThickSeparator);
- printer->Print("\n");
- message_generators_[i]->GenerateClassMethods(printer);
-
- printer->Print("#if PROTOBUF_INLINE_NOT_IN_HEADERS\n");
- // Generate class inline methods.
- message_generators_[i]->GenerateInlineMethods(printer,
- /* is_inline = */ false);
- printer->Print("#endif // PROTOBUF_INLINE_NOT_IN_HEADERS\n");
+ // Define extensions.
+ for (int i = 0; i < extension_generators_.size(); i++) {
+ extension_generators_[i]->GenerateDefinition(printer);
}
if (HasGenericServices(file_, options_)) {
@@ -363,18 +455,76 @@ void FileGenerator::GenerateSource(io::Printer* printer) {
service_generators_[i]->GenerateImplementation(printer);
}
}
+}
- // Define extensions.
- for (int i = 0; i < extension_generators_.size(); i++) {
- extension_generators_[i]->GenerateDefinition(printer);
+void FileGenerator::GenerateSource(io::Printer* printer) {
+ GenerateSourceIncludes(printer);
+ GenerateWeakDeclarations(file_, options_, &scc_analyzer_, printer);
+
+ {
+ NamespaceOpener ns(Namespace(file_), printer);
+
+ // Define default instances
+ for (int i = 0; i < message_generators_.size(); i++) {
+ GenerateSourceDefaultInstance(i, printer);
+ if (UsingImplicitWeakFields(file_, options_)) {
+ printer->Print("void $classname$_ReferenceStrong() {}\n", "classname",
+ message_generators_[i]->classname_);
+ }
+ }
}
- printer->Print(
- "\n"
- "// @@protoc_insertion_point(namespace_scope)\n");
+ {
+ NamespaceOpener ns(FileLevelNamespace(file_), printer);
+ // Define the initialization code to initialize the default instances.
+ // This code doesn't use a global constructor.
+ GenerateInitializationCode(printer);
+
+ // Define the code to initialize reflection. This code uses a global
+ // constructor to register reflection data with the runtime pre-main.
+ if (HasDescriptorMethods(file_, options_)) {
+ GenerateReflectionInitializationCode(printer);
+ }
+ }
+
+
+ {
+ NamespaceOpener ns(Namespace(file_), printer);
+
+ // Actually implement the protos
+
+ // Generate enums.
+ for (int i = 0; i < enum_generators_.size(); i++) {
+ enum_generators_[i]->GenerateMethods(i, printer);
+ }
+
+ // Generate classes.
+ for (int i = 0; i < message_generators_.size(); i++) {
+ printer->Print("\n");
+ printer->Print(kThickSeparator);
+ printer->Print("\n");
+ message_generators_[i]->GenerateClassMethods(printer);
+ }
+
+ if (HasGenericServices(file_, options_)) {
+ // Generate services.
+ for (int i = 0; i < service_generators_.size(); i++) {
+ if (i == 0) printer->Print("\n");
+ printer->Print(kThickSeparator);
+ printer->Print("\n");
+ service_generators_[i]->GenerateImplementation(printer);
+ }
+ }
- GenerateNamespaceClosers(printer);
+ // Define extensions.
+ for (int i = 0; i < extension_generators_.size(); i++) {
+ extension_generators_[i]->GenerateDefinition(printer);
+ }
+ printer->Print(
+ "\n"
+ "// @@protoc_insertion_point(namespace_scope)\n");
+ }
printer->Print(
"\n"
"// @@protoc_insertion_point(global_scope)\n");
@@ -429,6 +579,10 @@ class FileGenerator::ForwardDeclarations {
options.dllexport_decl.empty() ? "" : options.dllexport_decl + " ",
"classname",
it->first);
+ if (options.lite_implicit_weak_fields) {
+ printer->Print("void $classname$_ReferenceStrong();\n",
+ "classname", it->first);
+ }
}
for (std::map<string, ForwardDeclarations *>::const_iterator
it = namespaces_.begin(),
@@ -449,14 +603,11 @@ class FileGenerator::ForwardDeclarations {
std::map<string, const EnumDescriptor*> enums_;
};
-void FileGenerator::GenerateBuildDescriptors(io::Printer* printer) {
+void FileGenerator::GenerateReflectionInitializationCode(io::Printer* printer) {
// AddDescriptors() is a file-level procedure which adds the encoded
// FileDescriptorProto for this .proto file to the global DescriptorPool for
- // generated files (DescriptorPool::generated_pool()). It either runs at
- // static initialization time (by default) or when default_instance() is
- // called for the first time (in LITE_RUNTIME mode with
- // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER flag enabled). This procedure also
- // constructs default instances and registers extensions.
+ // generated files (DescriptorPool::generated_pool()). It ordinarily runs at
+ // static initialization time, but is not used at all in LITE_RUNTIME mode.
//
// Its sibling, AssignDescriptors(), actually pulls the compiled
// FileDescriptor from the DescriptorPool and uses it to populate all of
@@ -465,101 +616,104 @@ void FileGenerator::GenerateBuildDescriptors(io::Printer* printer) {
// anyone calls descriptor() or GetReflection() on one of the types defined
// in the file.
- // In optimize_for = LITE_RUNTIME mode, we don't generate AssignDescriptors()
- // and we only use AddDescriptors() to allocate default instances.
-
- if (HasDescriptorMethods(file_, options_)) {
- if (!message_generators_.empty()) {
- printer->Print(
- "\n"
- "const ::google::protobuf::uint32* $offsetfunname$() GOOGLE_ATTRIBUTE_COLD;\n"
- "const ::google::protobuf::uint32* $offsetfunname$() {\n",
- "offsetfunname", GlobalOffsetTableName(file_->name()));
- printer->Indent();
-
- printer->Print("static const ::google::protobuf::uint32 offsets[] = {\n");
- printer->Indent();
- std::vector<std::pair<size_t, size_t> > pairs;
- for (int i = 0; i < message_generators_.size(); i++) {
- pairs.push_back(message_generators_[i]->GenerateOffsets(printer));
- }
- printer->Outdent();
- printer->Outdent();
- printer->Print(
- " };\n"
- " return offsets;\n"
- "}\n"
- "\n");
+ if (!message_generators_.empty()) {
+ printer->Print("::google::protobuf::Metadata file_level_metadata[$size$];\n", "size",
+ SimpleItoa(message_generators_.size()));
+ }
+ if (!enum_generators_.empty()) {
+ printer->Print(
+ "const ::google::protobuf::EnumDescriptor* "
+ "file_level_enum_descriptors[$size$];\n",
+ "size", SimpleItoa(enum_generators_.size()));
+ }
+ if (HasGenericServices(file_, options_) && file_->service_count() > 0) {
+ printer->Print(
+ "const ::google::protobuf::ServiceDescriptor* "
+ "file_level_service_descriptors[$size$];\n",
+ "size", SimpleItoa(file_->service_count()));
+ }
- printer->Print(
- "static const ::google::protobuf::internal::MigrationSchema schemas[] = {\n");
- printer->Indent();
- {
- int offset = 0;
- for (int i = 0; i < message_generators_.size(); i++) {
- message_generators_[i]->GenerateSchema(printer, offset,
- pairs[i].second);
- offset += pairs[i].first;
- }
- }
- printer->Outdent();
- printer->Print(
- "};\n"
- "\n"
- "static const ::google::protobuf::internal::DefaultInstanceData "
- "file_default_instances[] = {\n");
- printer->Indent();
+ if (!message_generators_.empty()) {
+ printer->Print(
+ "\n"
+ "const ::google::protobuf::uint32 TableStruct::offsets[] "
+ "GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {\n");
+ printer->Indent();
+ std::vector<std::pair<size_t, size_t> > pairs;
+ pairs.reserve(message_generators_.size());
+ for (int i = 0; i < message_generators_.size(); i++) {
+ pairs.push_back(message_generators_[i]->GenerateOffsets(printer));
+ }
+ printer->Outdent();
+ printer->Print(
+ "};\n"
+ "static const ::google::protobuf::internal::MigrationSchema schemas[] "
+ "GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {\n");
+ printer->Indent();
+ {
+ int offset = 0;
for (int i = 0; i < message_generators_.size(); i++) {
- const Descriptor* descriptor = message_generators_[i]->descriptor_;
- if (IsMapEntryMessage(descriptor)) continue;
-
- string oneof_default = "NULL";
- if (message_generators_[i]->descriptor_->oneof_decl_count()) {
- oneof_default =
- "&" + ClassName(descriptor, false) + "_default_oneof_instance_";
- }
- printer->Print(
- "{reinterpret_cast<const "
- "::google::protobuf::Message*>(&_$classname$_default_instance_), "
- "$oneof_default$},\n",
- "classname", ClassName(descriptor, false), "oneof_default",
- oneof_default);
+ message_generators_[i]->GenerateSchema(printer, offset,
+ pairs[i].second);
+ offset += pairs[i].first;
}
- printer->Outdent();
- printer->Print(
- "};\n"
- "\n");
- } else {
- // we still need these symbols to exist
+ }
+ printer->Outdent();
+ printer->Print(
+ "};\n"
+ "\nstatic "
+ "::google::protobuf::Message const * const file_default_instances[] = {\n");
+ printer->Indent();
+ for (int i = 0; i < message_generators_.size(); i++) {
+ const Descriptor* descriptor = message_generators_[i]->descriptor_;
printer->Print(
- "inline ::google::protobuf::uint32* $offsetfunname$() { return NULL; }\n"
- "static const ::google::protobuf::internal::MigrationSchema* schemas = NULL;\n"
- "static const ::google::protobuf::internal::DefaultInstanceData* "
- "file_default_instances = NULL;\n",
- "offsetfunname",
- GlobalOffsetTableName(file_->name()));
+ "reinterpret_cast<const "
+ "::google::protobuf::Message*>(&$ns$::_$classname$_default_instance_),\n",
+ "classname", ClassName(descriptor), "ns", Namespace(descriptor));
}
+ printer->Outdent();
+ printer->Print(
+ "};\n"
+ "\n");
+ } else {
+ // we still need these symbols to exist
+ printer->Print(
+ // MSVC doesn't like empty arrays, so we add a dummy.
+ "const ::google::protobuf::uint32 TableStruct::offsets[1] = {};\n"
+ "static const ::google::protobuf::internal::MigrationSchema* schemas = NULL;\n"
+ "static const ::google::protobuf::Message* const* "
+ "file_default_instances = NULL;\n"
+ "\n");
+ }
- // ---------------------------------------------------------------
+ // ---------------------------------------------------------------
- // protobuf_AssignDescriptorsOnce(): The first time it is called, calls
- // AssignDescriptors(). All later times, waits for the first call to
- // complete and then returns.
- string message_factory = "NULL";
+ // protobuf_AssignDescriptorsOnce(): The first time it is called, calls
+ // AssignDescriptors(). All later times, waits for the first call to
+ // complete and then returns.
+ string message_factory = "NULL";
printer->Print(
- "namespace {\n"
- "\n"
"void protobuf_AssignDescriptors() {\n"
// Make sure the file has found its way into the pool. If a descriptor
// is requested *during* static init then AddDescriptors() may not have
// been called yet, so we call it manually. Note that it's fine if
// AddDescriptors() is called multiple times.
- " $adddescriptorsname$();\n"
+ " AddDescriptors();\n"
" ::google::protobuf::MessageFactory* factory = $factory$;\n"
" AssignDescriptors(\n"
" \"$filename$\", schemas, file_default_instances, "
- "$offsetfunname$(), factory,\n"
- " $metadata$, $enum_descriptors$, $service_descriptors$);\n"
+ "TableStruct::offsets, factory,\n"
+ " $metadata$, $enum_descriptors$, $service_descriptors$);\n",
+ "filename", file_->name(), "metadata",
+ !message_generators_.empty() ? "file_level_metadata" : "NULL",
+ "enum_descriptors",
+ !enum_generators_.empty() ? "file_level_enum_descriptors" : "NULL",
+ "service_descriptors",
+ HasGenericServices(file_, options_) && file_->service_count() > 0
+ ? "file_level_service_descriptors"
+ : "NULL",
+ "factory", message_factory);
+ printer->Print(
"}\n"
"\n"
"void protobuf_AssignDescriptorsOnce() {\n"
@@ -567,9 +721,7 @@ void FileGenerator::GenerateBuildDescriptors(io::Printer* printer) {
" ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);\n"
"}\n"
"\n",
- "adddescriptorsname", GlobalAddDescriptorsName(file_->name()),
- "offsetfunname", GlobalOffsetTableName(file_->name()), "filename",
- file_->name(), "metadata",
+ "filename", file_->name(), "metadata",
!message_generators_.empty() ? "file_level_metadata" : "NULL",
"enum_descriptors",
!enum_generators_.empty() ? "file_level_enum_descriptors" : "NULL",
@@ -583,7 +735,8 @@ void FileGenerator::GenerateBuildDescriptors(io::Printer* printer) {
// protobuf_AssignDescriptorsOnce, because that is called from all the
// GetMetadata member methods.
printer->Print(
- "void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;\n"
+ "void protobuf_RegisterTypes(const ::std::string&) "
+ "GOOGLE_PROTOBUF_ATTRIBUTE_COLD;\n"
"void protobuf_RegisterTypes(const ::std::string&) {\n"
" protobuf_AssignDescriptorsOnce();\n");
printer->Indent();
@@ -595,98 +748,17 @@ void FileGenerator::GenerateBuildDescriptors(io::Printer* printer) {
"size", SimpleItoa(message_generators_.size()));
}
- // Map types are treated special
- // TODO(gerbens) find a way to treat maps more like normal messages.
- for (int i = 0; i < message_generators_.size(); i++) {
- message_generators_[i]->GenerateTypeRegistrations(printer);
- }
-
printer->Outdent();
printer->Print(
- "}\n"
- "\n"
- "} // namespace\n");
- }
-
- // -----------------------------------------------------------------
-
- // ShutdownFile(): Deletes descriptors, default instances, etc. on shutdown.
- printer->Print(
- "\n"
- "void $shutdownfilename$() {\n",
- "shutdownfilename", GlobalShutdownFileName(file_->name()));
- printer->Indent();
-
- for (int i = 0; i < message_generators_.size(); i++) {
- message_generators_[i]->GenerateShutdownCode(printer);
- }
-
- printer->Outdent();
- printer->Print(
- "}\n\n");
-
- // -----------------------------------------------------------------
-
- // Now generate the InitDefaults() function.
- printer->Print(
- "void $initdefaultsname$_impl() {\n"
- " GOOGLE_PROTOBUF_VERIFY_VERSION;\n\n"
- "",
- // Vars.
- "initdefaultsname", GlobalInitDefaultsName(file_->name()));
-
- printer->Indent();
+ "}\n"
+ "\n");
- // Call the InitDefaults() methods for all of our dependencies, to make
- // sure they get added first.
- for (int i = 0; i < file_->dependency_count(); i++) {
- const FileDescriptor* dependency = file_->dependency(i);
- // Print the namespace prefix for the dependency.
- string add_desc_name = QualifiedFileLevelSymbol(
- dependency->package(), GlobalInitDefaultsName(dependency->name()));
- // Call its AddDescriptors function.
+ // Now generate the AddDescriptors() function.
printer->Print(
- "$name$();\n",
- "name", add_desc_name);
- }
-
- // Force initialization of primitive values we depend on.
- printer->Print("::google::protobuf::internal::InitProtobufDefaults();\n");
-
- // Allocate and initialize default instances. This can't be done lazily
- // since default instances are returned by simple accessors and are used with
- // extensions. Speaking of which, we also register extensions at this time.
- for (int i = 0; i < message_generators_.size(); i++) {
- message_generators_[i]->GenerateDefaultInstanceAllocator(printer);
- }
- for (int i = 0; i < extension_generators_.size(); i++) {
- extension_generators_[i]->GenerateRegistration(printer);
- }
- for (int i = 0; i < message_generators_.size(); i++) {
- message_generators_[i]->GenerateDefaultInstanceInitializer(printer);
- }
- printer->Outdent();
- printer->Print(
- "}\n"
- "\n"
- "void $initdefaultsname$() {\n"
- " static GOOGLE_PROTOBUF_DECLARE_ONCE(once);\n"
- " ::google::protobuf::GoogleOnceInit(&once, &$initdefaultsname$_impl);\n"
- "}\n",
- "initdefaultsname", GlobalInitDefaultsName(file_->name()));
-
- // -----------------------------------------------------------------
-
- // Now generate the AddDescriptors() function.
- printer->Print(
- "void $adddescriptorsname$_impl() {\n"
- " $initdefaultsname$();\n",
- // Vars.
- "adddescriptorsname", GlobalAddDescriptorsName(file_->name()),
- "initdefaultsname", GlobalInitDefaultsName(file_->name()));
+ "void AddDescriptorsImpl() {\n"
+ " InitDefaults();\n");
+ printer->Indent();
- printer->Indent();
- if (HasDescriptorMethods(file_, options_)) {
// Embed the descriptor. We simply serialize the entire
// FileDescriptorProto
// and embed it as a string literal, which is parsed and built into real
@@ -696,15 +768,12 @@ void FileGenerator::GenerateBuildDescriptors(io::Printer* printer) {
string file_data;
file_proto.SerializeToString(&file_data);
- printer->Print("static const char descriptor[] = {\n");
+ printer->Print("static const char descriptor[] "
+ "GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) "
+ "= {\n");
printer->Indent();
-#ifdef _MSC_VER
- bool breakdown_large_file = true;
-#else
- bool breakdown_large_file = false;
-#endif
- if (breakdown_large_file && file_data.size() > 66538) {
+ if (file_data.size() > 65535) {
// Workaround for MSVC: "Error C1091: compiler limit: string exceeds 65535
// bytes in length". Declare a static array of characters rather than use
// a string literal. Only write 25 bytes per line.
@@ -738,87 +807,256 @@ void FileGenerator::GenerateBuildDescriptors(io::Printer* printer) {
"::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(\n"
" \"$filename$\", &protobuf_RegisterTypes);\n",
"filename", file_->name());
- }
// Call the AddDescriptors() methods for all of our dependencies, to make
// sure they get added first.
for (int i = 0; i < file_->dependency_count(); i++) {
const FileDescriptor* dependency = file_->dependency(i);
// Print the namespace prefix for the dependency.
- string add_desc_name = QualifiedFileLevelSymbol(
- dependency->package(), GlobalAddDescriptorsName(dependency->name()));
+ string file_namespace = FileLevelNamespace(dependency);
// Call its AddDescriptors function.
- printer->Print("$adddescriptorsname$();\n", "adddescriptorsname",
- add_desc_name);
+ printer->Print("::$file_namespace$::AddDescriptors();\n", "file_namespace",
+ file_namespace);
}
- printer->Print(
- "::google::protobuf::internal::OnShutdown(&$shutdownfilename$);\n",
- "shutdownfilename", GlobalShutdownFileName(file_->name()));
-
printer->Outdent();
printer->Print(
"}\n"
"\n"
- "GOOGLE_PROTOBUF_DECLARE_ONCE($adddescriptorsname$_once_);\n"
- "void $adddescriptorsname$() {\n"
- " ::google::protobuf::GoogleOnceInit(&$adddescriptorsname$_once_,\n"
- " &$adddescriptorsname$_impl);\n"
- "}\n",
- "adddescriptorsname", GlobalAddDescriptorsName(file_->name()));
+ "void AddDescriptors() {\n"
+ " static GOOGLE_PROTOBUF_DECLARE_ONCE(once);\n"
+ " ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);\n"
+ "}\n");
- if (!StaticInitializersForced(file_, options_)) {
- printer->Print("#ifndef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER\n");
- }
+ printer->Print(
+ "// Force AddDescriptors() to be called at dynamic initialization "
+ "time.\n"
+ "struct StaticDescriptorInitializer {\n"
+ " StaticDescriptorInitializer() {\n"
+ " AddDescriptors();\n"
+ " }\n"
+ "} static_descriptor_initializer;\n");
+}
+
+void FileGenerator::GenerateInitForSCC(const SCC* scc, io::Printer* printer) {
+ const string scc_name = ClassName(scc->GetRepresentative());
printer->Print(
- // With static initializers.
- "// Force AddDescriptors() to be called at static initialization time.\n"
- "struct StaticDescriptorInitializer_$filename$ {\n"
- " StaticDescriptorInitializer_$filename$() {\n"
- " $adddescriptorsname$();\n"
- " }\n"
- "} static_descriptor_initializer_$filename$_;\n",
- // Vars.
- "adddescriptorsname", GlobalAddDescriptorsName(file_->name()), "filename",
- FilenameIdentifier(file_->name()));
- if (!StaticInitializersForced(file_, options_)) {
- printer->Print("#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER\n");
+ "void InitDefaults$scc_name$Impl() {\n"
+ " GOOGLE_PROTOBUF_VERIFY_VERSION;\n\n"
+ "#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS\n"
+ " ::google::protobuf::internal::InitProtobufDefaultsForceUnique();\n"
+ "#else\n"
+ " ::google::protobuf::internal::InitProtobufDefaults();\n"
+ "#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS\n",
+ // Force initialization of primitive values we depend on.
+ "scc_name", scc_name);
+
+ printer->Indent();
+
+ // Call the InitDefaults() methods for all of our dependencies, to make
+ // sure they get added first.
+ for (int i = 0; i < scc->children.size(); i++) {
+ const SCC* child_scc = scc->children[i];
+ const FileDescriptor* dependency = child_scc->GetRepresentative()->file();
+ // Print the namespace prefix for the dependency.
+ string file_namespace = FileLevelNamespace(dependency);
+ std::map<string, string> variables;
+ variables["file_namespace"] = file_namespace;
+ variables["scc_name"] = ClassName(child_scc->GetRepresentative(), false);
+ bool using_weak_fields = UsingImplicitWeakFields(file_, options_);
+ if (using_weak_fields) {
+ // We're building for lite with implicit weak fields, so we need to handle
+ // the possibility that this InitDefaults function is not linked into the
+ // binary. Some of these might actually be guaranteed to be non-null since
+ // we might have a strong reference to the dependency (via a required
+ // field, for example), but it's simplest to just assume that any of them
+ // could be null.
+ printer->Print(
+ variables,
+ "if (&$file_namespace$::InitDefaults$scc_name$ != NULL) {\n"
+ " $file_namespace$::InitDefaults$scc_name$();\n"
+ "}\n");
+ } else {
+ printer->Print(variables,
+ "$file_namespace$::InitDefaults$scc_name$();\n");
+ }
}
-}
-void FileGenerator::GenerateNamespaceOpeners(io::Printer* printer) {
- if (package_parts_.size() > 0) printer->Print("\n");
+ // First construct all the necessary default instances.
+ for (int i = 0; i < message_generators_.size(); i++) {
+ if (scc_analyzer_.GetSCC(message_generators_[i]->descriptor_) != scc) {
+ continue;
+ }
+ // TODO(gerbens) This requires this function to be friend. Remove
+ // the need for this.
+ message_generators_[i]->GenerateFieldDefaultInstances(printer);
+ printer->Print(
+ "{\n"
+ " void* ptr = &$ns$::_$classname$_default_instance_;\n"
+ " new (ptr) $ns$::$classname$();\n",
+ "ns", Namespace(message_generators_[i]->descriptor_),
+ "classname", ClassName(message_generators_[i]->descriptor_));
+ if (!IsMapEntryMessage(message_generators_[i]->descriptor_)) {
+ printer->Print(
+ " ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);\n");
+ }
+ printer->Print("}\n");
+ }
- for (int i = 0; i < package_parts_.size(); i++) {
- printer->Print("namespace $part$ {\n",
- "part", package_parts_[i]);
+ // TODO(gerbens) make default instances be the same as normal instances.
+ // Default instances differ from normal instances because they have cross
+ // linked message fields.
+ for (int i = 0; i < message_generators_.size(); i++) {
+ if (scc_analyzer_.GetSCC(message_generators_[i]->descriptor_) != scc) {
+ continue;
+ }
+ printer->Print("$classname$::InitAsDefaultInstance();\n", "classname",
+ QualifiedClassName(message_generators_[i]->descriptor_));
}
+ printer->Outdent();
+ printer->Print("}\n\n");
+ printer->Print(
+ "void InitDefaults$scc_name$() {\n"
+ " static GOOGLE_PROTOBUF_DECLARE_ONCE(once);\n"
+ " ::google::protobuf::GoogleOnceInit(&once, "
+ "&InitDefaults$scc_name$Impl);\n"
+ "}\n\n",
+ "scc_name", scc_name);
}
-void FileGenerator::GenerateNamespaceClosers(io::Printer* printer) {
- if (package_parts_.size() > 0) printer->Print("\n");
+void FileGenerator::GenerateInitializationCode(io::Printer* printer) {
+ // Messages depend on the existence of a default instance, which has to
+ // initialized properly. The default instances are allocated in the data
+ // segment, but we can't quite allocate the type directly. The destructors
+ // cannot run at program exit as this could lead to segfaults in a threaded
+ // environment. Hence these instances must be inplace constructed at first
+ // use.
+
+ if (options_.table_driven_parsing) {
+ // TODO(ckennelly): Gate this with the same options flag to enable
+ // table-driven parsing.
+ printer->Print(
+ "PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::ParseTableField\n"
+ " const TableStruct::entries[] "
+ "GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {\n");
+ printer->Indent();
+
+ std::vector<size_t> entries;
+ size_t count = 0;
+ for (int i = 0; i < message_generators_.size(); i++) {
+ size_t value = message_generators_[i]->GenerateParseOffsets(printer);
+ entries.push_back(value);
+ count += value;
+ }
+
+ // We need these arrays to exist, and MSVC does not like empty arrays.
+ if (count == 0) {
+ printer->Print("{0, 0, 0, ::google::protobuf::internal::kInvalidMask, 0, 0},\n");
+ }
+
+ printer->Outdent();
+ printer->Print(
+ "};\n"
+ "\n"
+ "PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::AuxillaryParseTableField\n"
+ " const TableStruct::aux[] "
+ "GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {\n");
+ printer->Indent();
+
+ std::vector<size_t> aux_entries;
+ count = 0;
+ for (int i = 0; i < message_generators_.size(); i++) {
+ size_t value = message_generators_[i]->GenerateParseAuxTable(printer);
+ aux_entries.push_back(value);
+ count += value;
+ }
+
+ if (count == 0) {
+ printer->Print("::google::protobuf::internal::AuxillaryParseTableField(),\n");
+ }
+
+ printer->Outdent();
+ printer->Print(
+ "};\n"
+ "PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::ParseTable const\n"
+ " TableStruct::schema[] "
+ "GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {\n");
+ printer->Indent();
+
+ size_t offset = 0;
+ size_t aux_offset = 0;
+ for (int i = 0; i < message_generators_.size(); i++) {
+ message_generators_[i]->GenerateParseTable(printer, offset, aux_offset);
+ offset += entries[i];
+ aux_offset += aux_entries[i];
+ }
+
+ if (message_generators_.empty()) {
+ printer->Print("{ NULL, NULL, 0, -1, -1, false },\n");
+ }
+
+ printer->Outdent();
+ printer->Print(
+ "};\n"
+ "\n");
+ }
+
+ if (!message_generators_.empty() && options_.table_driven_serialization) {
+ printer->Print(
+ "const ::google::protobuf::internal::FieldMetadata TableStruct::field_metadata[] "
+ "= {\n");
+ printer->Indent();
+ std::vector<int> field_metadata_offsets;
+ int idx = 0;
+ for (int i = 0; i < message_generators_.size(); i++) {
+ field_metadata_offsets.push_back(idx);
+ idx += message_generators_[i]->GenerateFieldMetadata(printer);
+ }
+ field_metadata_offsets.push_back(idx);
+ printer->Outdent();
+ printer->Print(
+ "};\n"
+ "const ::google::protobuf::internal::SerializationTable "
+ "TableStruct::serialization_table[] = {\n");
+ printer->Indent();
+ // We rely on the order we layout the tables to match the order we
+ // calculate them with FlattenMessagesInFile, so we check here that
+ // these match exactly.
+ std::vector<const Descriptor*> calculated_order =
+ FlattenMessagesInFile(file_);
+ GOOGLE_CHECK_EQ(calculated_order.size(), message_generators_.size());
+ for (int i = 0; i < message_generators_.size(); i++) {
+ GOOGLE_CHECK_EQ(calculated_order[i], message_generators_[i]->descriptor_);
+ printer->Print(
+ "{$num_fields$, TableStruct::field_metadata + $index$},\n",
+ "classname", message_generators_[i]->classname_, "num_fields",
+ SimpleItoa(field_metadata_offsets[i + 1] - field_metadata_offsets[i]),
+ "index", SimpleItoa(field_metadata_offsets[i]));
+ }
+ printer->Outdent();
+ printer->Print(
+ "};\n"
+ "\n");
+ }
+
+ // -----------------------------------------------------------------
+ // All functionality that need private access.
- for (int i = package_parts_.size() - 1; i >= 0; i--) {
- printer->Print("} // namespace $part$\n",
- "part", package_parts_[i]);
+ // Now generate the InitDefaults for each SCC.
+ for (int i = 0; i < message_generators_.size(); i++) {
+ if (IsSCCRepresentative(message_generators_[i]->descriptor_)) {
+ GenerateInitForSCC(GetSCC(message_generators_[i]->descriptor_), printer);
+ }
}
}
void FileGenerator::GenerateForwardDeclarations(io::Printer* printer) {
ForwardDeclarations decls;
- for (int i = 0; i < file_->dependency_count(); i++) {
- FileGenerator dependency(file_->dependency(i), options_);
- dependency.FillForwardDeclarations(&decls);
- }
FillForwardDeclarations(&decls);
decls.Print(printer, options_);
}
void FileGenerator::FillForwardDeclarations(ForwardDeclarations* decls) {
- for (int i = 0; i < file_->public_dependency_count(); i++) {
- FileGenerator dependency(file_->public_dependency(i), options_);
- dependency.FillForwardDeclarations(decls);
- }
for (int i = 0; i < package_parts_.size(); i++) {
decls = decls->AddOrGetNamespace(package_parts_[i]);
}
@@ -856,6 +1094,9 @@ void FileGenerator::GenerateBottomHeaderGuard(
}
void FileGenerator::GenerateLibraryIncludes(io::Printer* printer) {
+ if (UsingImplicitWeakFields(file_, options_)) {
+ printer->Print("#include <google/protobuf/implicit_weak_message.h>\n");
+ }
printer->Print(
"#include <google/protobuf/stubs/common.h>\n"
@@ -881,10 +1122,19 @@ void FileGenerator::GenerateLibraryIncludes(io::Printer* printer) {
// OK, it's now safe to #include other files.
printer->Print(
- "#include <google/protobuf/arena.h>\n"
- "#include <google/protobuf/arenastring.h>\n"
- "#include <google/protobuf/generated_message_util.h>\n"
- "#include <google/protobuf/metadata.h>\n");
+ "#include <google/protobuf/io/coded_stream.h>\n"
+ "#include <google/protobuf/arena.h>\n"
+ "#include <google/protobuf/arenastring.h>\n"
+ "#include <google/protobuf/generated_message_table_driven.h>\n"
+ "#include <google/protobuf/generated_message_util.h>\n");
+
+ if (HasDescriptorMethods(file_, options_)) {
+ printer->Print(
+ "#include <google/protobuf/metadata.h>\n");
+ } else {
+ printer->Print(
+ "#include <google/protobuf/metadata_lite.h>\n");
+ }
if (!message_generators_.empty()) {
if (HasDescriptorMethods(file_, options_)) {
@@ -902,13 +1152,14 @@ void FileGenerator::GenerateLibraryIncludes(io::Printer* printer) {
" // IWYU pragma: export\n");
if (HasMapFields(file_)) {
printer->Print(
- "#include <google/protobuf/map.h>\n");
+ "#include <google/protobuf/map.h>"
+ " // IWYU pragma: export\n");
if (HasDescriptorMethods(file_, options_)) {
- printer->Print(
- "#include <google/protobuf/map_field_inl.h>\n");
+ printer->Print("#include <google/protobuf/map_entry.h>\n");
+ printer->Print("#include <google/protobuf/map_field_inl.h>\n");
} else {
- printer->Print(
- "#include <google/protobuf/map_field_lite.h>\n");
+ printer->Print("#include <google/protobuf/map_entry_lite.h>\n");
+ printer->Print("#include <google/protobuf/map_field_lite.h>\n");
}
}
@@ -975,17 +1226,56 @@ void FileGenerator::GenerateDependencyIncludes(io::Printer* printer) {
void FileGenerator::GenerateGlobalStateFunctionDeclarations(
io::Printer* printer) {
- // Forward-declare the AddDescriptors, AssignDescriptors, and ShutdownFile
- // functions, so that we can declare them to be friends of each class.
+// Forward-declare the AddDescriptors, InitDefaults because these are called
+// by .pb.cc files depending on this file.
printer->Print(
"\n"
- "// Internal implementation detail -- do not call these.\n"
- "void $dllexport_decl$$adddescriptorsname$();\n"
- "void $dllexport_decl$$initdefaultsname$();\n",
- "initdefaultsname", GlobalInitDefaultsName(file_->name()),
- "adddescriptorsname", GlobalAddDescriptorsName(file_->name()),
- "dllexport_decl",
+ "namespace $file_namespace$ {\n"
+ "// Internal implementation detail -- do not use these members.\n"
+ "struct $dllexport_decl$TableStruct {\n"
+ // These tables describe how to serialize and parse messages. Used
+ // for table driven code.
+ " static const ::google::protobuf::internal::ParseTableField entries[];\n"
+ " static const ::google::protobuf::internal::AuxillaryParseTableField aux[];\n"
+ " static const ::google::protobuf::internal::ParseTable schema[$num$];\n"
+ " static const ::google::protobuf::internal::FieldMetadata field_metadata[];\n"
+ " static const ::google::protobuf::internal::SerializationTable "
+ "serialization_table[];\n"
+ " static const ::google::protobuf::uint32 offsets[];\n"
+ "};\n",
+ "file_namespace", FileLevelNamespace(file_), "dllexport_decl",
+ options_.dllexport_decl.empty() ? "" : options_.dllexport_decl + " ",
+ "num", SimpleItoa(std::max(size_t(1), message_generators_.size())));
+ if (HasDescriptorMethods(file_, options_)) {
+ printer->Print(
+ "void $dllexport_decl$AddDescriptors();\n", "dllexport_decl",
+ options_.dllexport_decl.empty() ? "" : options_.dllexport_decl + " ");
+ }
+ for (int i = 0; i < message_generators_.size(); i++) {
+ if (!IsSCCRepresentative(message_generators_[i]->descriptor_)) continue;
+ string scc_name = ClassName(message_generators_[i]->descriptor_);
+ // TODO(gerbens) Remove the Impl from header. This is solely because
+ // it currently still needs to be a friend of the protos.
+ printer->Print(
+ "void $dllexport_decl$InitDefaults$scc_name$Impl();\n"
+ "void $dllexport_decl$InitDefaults$scc_name$();\n",
+ "scc_name", scc_name, "dllexport_decl",
+ options_.dllexport_decl.empty() ? "" : options_.dllexport_decl + " ");
+ }
+ // TODO(gerbens) This is for proto1 interoperability. Remove when proto1
+ // is gone.
+ printer->Print(
+ "inline void $dllexport_decl$InitDefaults() {\n", "dllexport_decl",
options_.dllexport_decl.empty() ? "" : options_.dllexport_decl + " ");
+ for (int i = 0; i < message_generators_.size(); i++) {
+ if (!IsSCCRepresentative(message_generators_[i]->descriptor_)) continue;
+ string scc_name = ClassName(message_generators_[i]->descriptor_);
+ printer->Print(" InitDefaults$scc_name$();\n", "scc_name", scc_name);
+ }
+ printer->Print("}\n");
+ printer->Print(
+ "} // namespace $file_namespace$\n",
+ "file_namespace", FileLevelNamespace(file_));
}
void FileGenerator::GenerateMessageDefinitions(io::Printer* printer) {
@@ -1034,51 +1324,25 @@ void FileGenerator::GenerateExtensionIdentifiers(io::Printer* printer) {
}
void FileGenerator::GenerateInlineFunctionDefinitions(io::Printer* printer) {
- // An aside about inline functions in .proto.h mode:
- //
- // The PROTOBUF_INLINE_NOT_IN_HEADERS symbol controls conditionally
- // moving much of the inline functions to the .pb.cc file, which can be a
- // significant performance benefit for compilation time, at the expense
- // of non-inline function calls.
- //
- // However, in .proto.h mode, the definition of the internal dependent
- // base class must remain in the header, and can never be out-lined. The
- // dependent base class also needs access to has-bit manipuation
- // functions, so the has-bit functions must be unconditionally inlined in
- // proto_h mode.
- //
- // This gives us three flavors of functions:
- //
- // 1. Functions on the message not used by the internal dependent base
- // class: in .proto.h mode, only some functions are defined on the
- // message class; others are defined on the dependent base class.
- // These are guarded and can be out-lined. These are generated by
- // GenerateInlineMethods, and include has_* bit functions in
- // non-proto_h mode.
- //
- // 2. Functions on the internal dependent base class: these functions
- // are dependent on a template parameter, so they always need to
- // remain in the header.
- //
- // 3. Functions on the message that are used by the dependent base: the
- // dependent base class down casts itself to the message
- // implementation class to access these functions (the has_* bit
- // manipulation functions). Unlike #1, these functions must
- // unconditionally remain in the header. These are emitted by
- // GenerateDependentInlineMethods, even though they are not actually
- // dependent.
-
- printer->Print("#if !PROTOBUF_INLINE_NOT_IN_HEADERS\n");
+ // TODO(gerbens) remove pragmas when gcc is no longer used. Current version
+ // of gcc fires a bogus error when compiled with strict-aliasing.
+ printer->Print(
+ "#ifdef __GNUC__\n"
+ " #pragma GCC diagnostic push\n"
+ " #pragma GCC diagnostic ignored \"-Wstrict-aliasing\"\n"
+ "#endif // __GNUC__\n");
// Generate class inline methods.
for (int i = 0; i < message_generators_.size(); i++) {
if (i > 0) {
printer->Print(kThinSeparator);
printer->Print("\n");
}
- message_generators_[i]->GenerateInlineMethods(printer,
- /* is_inline = */ true);
+ message_generators_[i]->GenerateInlineMethods(printer);
}
- printer->Print("#endif // !PROTOBUF_INLINE_NOT_IN_HEADERS\n");
+ printer->Print(
+ "#ifdef __GNUC__\n"
+ " #pragma GCC diagnostic pop\n"
+ "#endif // __GNUC__\n");
for (int i = 0; i < message_generators_.size(); i++) {
if (i > 0) {
@@ -1094,13 +1358,8 @@ void FileGenerator::GenerateProto2NamespaceEnumSpecializations(
io::Printer* printer) {
// Emit GetEnumDescriptor specializations into google::protobuf namespace:
if (HasEnumDefinitions(file_)) {
- // The SWIG conditional is to avoid a null-pointer dereference
- // (bug 1984964) in swig-1.3.21 resulting from the following syntax:
- // namespace X { void Y<Z::W>(); }
- // which appears in GetEnumDescriptor() specializations.
printer->Print(
"\n"
- "#ifndef SWIG\n"
"namespace google {\nnamespace protobuf {\n"
"\n");
for (int i = 0; i < enum_generators_.size(); i++) {
@@ -1108,8 +1367,7 @@ void FileGenerator::GenerateProto2NamespaceEnumSpecializations(
}
printer->Print(
"\n"
- "} // namespace protobuf\n} // namespace google\n"
- "#endif // SWIG\n");
+ "} // namespace protobuf\n} // namespace google\n");
}
}
diff --git a/src/google/protobuf/compiler/cpp/cpp_file.h b/src/google/protobuf/compiler/cpp/cpp_file.h
index 25d6eabf..7e61cbad 100644
--- a/src/google/protobuf/compiler/cpp/cpp_file.h
+++ b/src/google/protobuf/compiler/cpp/cpp_file.h
@@ -35,14 +35,17 @@
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_FILE_H__
#define GOOGLE_PROTOBUF_COMPILER_CPP_FILE_H__
+#include <algorithm>
#include <memory>
#ifndef _SHARED_PTR_H
#include <google/protobuf/stubs/shared_ptr.h>
#endif
+#include <set>
#include <string>
#include <vector>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/compiler/cpp/cpp_field.h>
+#include <google/protobuf/compiler/cpp/cpp_helpers.h>
#include <google/protobuf/compiler/cpp/cpp_options.h>
namespace google {
@@ -81,16 +84,21 @@ class FileGenerator {
const string& info_path);
void GenerateSource(io::Printer* printer);
+ int NumMessages() const { return message_generators_.size(); }
+ // Similar to GenerateSource but generates only one message
+ void GenerateSourceForMessage(int idx, io::Printer* printer);
+ void GenerateGlobalSource(io::Printer* printer);
+
private:
// Internal type used by GenerateForwardDeclarations (defined in file.cc).
class ForwardDeclarations;
- // Generate the BuildDescriptors() procedure, which builds all descriptors
- // for types defined in the file.
- void GenerateBuildDescriptors(io::Printer* printer);
+ void GenerateSourceIncludes(io::Printer* printer);
+ void GenerateSourceDefaultInstance(int idx, io::Printer* printer);
- void GenerateNamespaceOpeners(io::Printer* printer);
- void GenerateNamespaceClosers(io::Printer* printer);
+ void GenerateInitForSCC(const SCC* scc, io::Printer* printer);
+ void GenerateInitializationCode(io::Printer* printer);
+ void GenerateReflectionInitializationCode(io::Printer* printer);
// For other imports, generates their forward-declarations.
void GenerateForwardDeclarations(io::Printer* printer);
@@ -133,9 +141,32 @@ class FileGenerator {
void GenerateProto2NamespaceEnumSpecializations(io::Printer* printer);
+ // Sometimes the names we use in a .proto file happen to be defined as macros
+ // on some platforms (e.g., macro/minor used in plugin.proto are defined as
+ // macros in sys/types.h on FreeBSD and a few other platforms). To make the
+ // generated code compile on these platforms, we either have to undef the
+ // macro for these few platforms, or rename the field name for all platforms.
+ // Since these names are part of protobuf public API, renaming is generally
+ // a breaking change so we prefer the #undef approach.
+ void GenerateMacroUndefs(io::Printer* printer);
+
+ bool IsSCCRepresentative(const Descriptor* d) {
+ return GetSCCRepresentative(d) == d;
+ }
+ const Descriptor* GetSCCRepresentative(const Descriptor* d) {
+ return GetSCC(d)->GetRepresentative();
+ }
+ const SCC* GetSCC(const Descriptor* d) {
+ return scc_analyzer_.GetSCC(d);
+ }
+
+
const FileDescriptor* file_;
const Options options_;
+ SCCAnalyzer scc_analyzer_;
+
+
// Contains the post-order walk of all the messages (and child messages) in
// this file. If you need a pre-order walk just reverse iterate.
std::vector<MessageGenerator*> message_generators_;
@@ -143,10 +174,8 @@ class FileGenerator {
std::vector<ServiceGenerator*> service_generators_;
std::vector<ExtensionGenerator*> extension_generators_;
- // These members are just for owning (and thus proper deleting). Some of the
- // message_ and enum_generators above are owned by child messages.
- google::protobuf::scoped_array<google::protobuf::scoped_ptr<MessageGenerator> >
- message_generators_owner_;
+ // These members are just for owning (and thus proper deleting).
+ // Nested (enum/extension)_generators are owned by child messages.
google::protobuf::scoped_array<google::protobuf::scoped_ptr<EnumGenerator> > enum_generators_owner_;
google::protobuf::scoped_array<google::protobuf::scoped_ptr<ServiceGenerator> >
service_generators_owner_;
diff --git a/src/google/protobuf/compiler/cpp/cpp_generator.cc b/src/google/protobuf/compiler/cpp/cpp_generator.cc
index 648ab28a..e01e5dca 100644
--- a/src/google/protobuf/compiler/cpp/cpp_generator.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_generator.cc
@@ -46,6 +46,7 @@
#include <google/protobuf/io/printer.h>
#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/descriptor.pb.h>
+#include <google/protobuf/stubs/strutil.h>
namespace google {
namespace protobuf {
@@ -84,7 +85,7 @@ bool CppGenerator::Generate(const FileDescriptor* file,
// __declspec(dllimport) depending on what is being compiled.
//
Options file_options;
-
+ bool split_source = false;
for (int i = 0; i < options.size(); i++) {
if (options[i].first == "dllexport_decl") {
file_options.dllexport_decl = options[i].second;
@@ -98,6 +99,14 @@ bool CppGenerator::Generate(const FileDescriptor* file,
file_options.annotation_guard_name = options[i].second;
} else if (options[i].first == "lite") {
file_options.enforce_lite = true;
+ } else if (options[i].first == "lite_implicit_weak_fields") {
+ file_options.lite_implicit_weak_fields = true;
+ } else if (options[i].first == "table_driven_parsing") {
+ file_options.table_driven_parsing = true;
+ } else if (options[i].first == "table_driven_serialization") {
+ file_options.table_driven_serialization = true;
+ } else if (options[i].first == "split_source") {
+ split_source = true;
} else {
*error = "Unknown generator option: " + options[i].first;
return false;
@@ -131,14 +140,13 @@ bool CppGenerator::Generate(const FileDescriptor* file,
}
}
- basename.append(".pb");
{
google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(
- generator_context->Open(basename + ".h"));
+ generator_context->Open(basename + ".pb.h"));
GeneratedCodeInfo annotations;
io::AnnotationProtoCollector<GeneratedCodeInfo> annotation_collector(
&annotations);
- string info_path = basename + ".h.meta";
+ string info_path = basename + ".pb.h.meta";
io::Printer printer(output.get(), '$', file_options.annotate_headers
? &annotation_collector
: NULL);
@@ -152,9 +160,24 @@ bool CppGenerator::Generate(const FileDescriptor* file,
}
// Generate cc file.
- {
+ if (split_source) {
+ {
+ // This is the global .cc file, containing enum/services/tables/reflection
+ google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(
+ generator_context->Open(basename + ".pb.cc"));
+ io::Printer printer(output.get(), '$');
+ file_generator.GenerateGlobalSource(&printer);
+ }
+ for (int i = 0; i < file_generator.NumMessages(); i++) {
+ // TODO(gerbens) Agree on naming scheme.
+ google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(
+ generator_context->Open(basename + "." + SimpleItoa(i) + ".cc"));
+ io::Printer printer(output.get(), '$');
+ file_generator.GenerateSourceForMessage(i, &printer);
+ }
+ } else {
google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(
- generator_context->Open(basename + ".cc"));
+ generator_context->Open(basename + ".pb.cc"));
io::Printer printer(output.get(), '$');
file_generator.GenerateSource(&printer);
}
diff --git a/src/google/protobuf/compiler/cpp/cpp_helpers.cc b/src/google/protobuf/compiler/cpp/cpp_helpers.cc
index 5a37b9d7..96950e52 100644
--- a/src/google/protobuf/compiler/cpp/cpp_helpers.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_helpers.cc
@@ -32,19 +32,22 @@
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
+#include <google/protobuf/stubs/hash.h>
#include <limits>
#include <map>
+#include <queue>
#include <vector>
-#include <google/protobuf/stubs/hash.h>
-#include <google/protobuf/compiler/cpp/cpp_helpers.h>
-#include <google/protobuf/io/printer.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
+#include <google/protobuf/compiler/cpp/cpp_helpers.h>
+#include <google/protobuf/io/printer.h>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/substitute.h>
+
+
namespace google {
namespace protobuf {
namespace compiler {
@@ -103,6 +106,30 @@ bool HasExtension(const Descriptor* descriptor) {
return false;
}
+// Encode [0..63] as 'A'-'Z', 'a'-'z', '0'-'9', '_'
+char Base63Char(int value) {
+ GOOGLE_CHECK_GE(value, 0);
+ if (value < 26) return 'A' + value;
+ value -= 26;
+ if (value < 26) return 'a' + value;
+ value -= 26;
+ if (value < 10) return '0' + value;
+ GOOGLE_CHECK_EQ(value, 10);
+ return '_';
+}
+
+// Given a c identifier has 63 legal characters we can't implement base64
+// encoding. So we return the k least significant "digits" in base 63.
+template <typename I>
+string Base63(I n, int k) {
+ string res;
+ while (k-- > 0) {
+ res += Base63Char(static_cast<int>(n % 63));
+ n /= 63;
+ }
+ return res;
+}
+
} // namespace
string UnderscoresToCamelCase(const string& input, bool cap_next_letter) {
@@ -135,38 +162,62 @@ const char kThickSeparator[] =
const char kThinSeparator[] =
"// -------------------------------------------------------------------\n";
-string ClassName(const Descriptor* descriptor, bool qualified) {
-
- // Find "outer", the descriptor of the top-level message in which
- // "descriptor" is embedded.
- const Descriptor* outer = descriptor;
- while (outer->containing_type() != NULL) outer = outer->containing_type();
-
- const string& outer_name = outer->full_name();
- string inner_name = descriptor->full_name().substr(outer_name.size());
-
- if (qualified) {
- return "::" + DotsToColons(outer_name) + DotsToUnderscores(inner_name);
- } else {
- return outer->name() + DotsToUnderscores(inner_name);
+bool CanInitializeByZeroing(const FieldDescriptor* field) {
+ if (field->is_repeated() || field->is_extension()) return false;
+ switch (field->cpp_type()) {
+ case FieldDescriptor::CPPTYPE_ENUM:
+ return field->default_value_enum()->number() == 0;
+ case FieldDescriptor::CPPTYPE_INT32:
+ return field->default_value_int32() == 0;
+ case FieldDescriptor::CPPTYPE_INT64:
+ return field->default_value_int64() == 0;
+ case FieldDescriptor::CPPTYPE_UINT32:
+ return field->default_value_uint32() == 0;
+ case FieldDescriptor::CPPTYPE_UINT64:
+ return field->default_value_uint64() == 0;
+ case FieldDescriptor::CPPTYPE_FLOAT:
+ return field->default_value_float() == 0;
+ case FieldDescriptor::CPPTYPE_DOUBLE:
+ return field->default_value_double() == 0;
+ case FieldDescriptor::CPPTYPE_BOOL:
+ return field->default_value_bool() == false;
+ default:
+ return false;
}
}
-string ClassName(const EnumDescriptor* enum_descriptor, bool qualified) {
+string ClassName(const Descriptor* descriptor) {
+ const Descriptor* parent = descriptor->containing_type();
+ string res;
+ if (parent) res += ClassName(parent) + "_";
+ res += descriptor->name();
+ if (IsMapEntryMessage(descriptor)) res += "_DoNotUse";
+ return res;
+}
+
+string ClassName(const EnumDescriptor* enum_descriptor) {
if (enum_descriptor->containing_type() == NULL) {
- if (qualified) {
- return "::" + DotsToColons(enum_descriptor->full_name());
- } else {
- return enum_descriptor->name();
- }
+ return enum_descriptor->name();
} else {
- string result = ClassName(enum_descriptor->containing_type(), qualified);
- result += '_';
- result += enum_descriptor->name();
- return result;
+ return ClassName(enum_descriptor->containing_type()) + "_" +
+ enum_descriptor->name();
}
}
+string Namespace(const string& package) {
+ if (package.empty()) return "";
+ return "::" + DotsToColons(package);
+}
+
+string DefaultInstanceName(const Descriptor* descriptor) {
+ string prefix = descriptor->file()->package().empty() ? "" : "::";
+ return prefix + DotsToColons(descriptor->file()->package()) + "::_" +
+ ClassName(descriptor, false) + "_default_instance_";
+}
+
+string ReferenceFunctionName(const Descriptor* descriptor) {
+ return QualifiedClassName(descriptor) + "_ReferenceStrong";
+}
string DependentBaseClassTemplateName(const Descriptor* descriptor) {
return ClassName(descriptor, false) + "_InternalBase";
@@ -203,6 +254,30 @@ string EnumValueName(const EnumValueDescriptor* enum_value) {
return result;
}
+int EstimateAlignmentSize(const FieldDescriptor* field) {
+ if (field == NULL) return 0;
+ if (field->is_repeated()) return 8;
+ switch (field->cpp_type()) {
+ case FieldDescriptor::CPPTYPE_BOOL:
+ return 1;
+
+ case FieldDescriptor::CPPTYPE_INT32:
+ case FieldDescriptor::CPPTYPE_UINT32:
+ case FieldDescriptor::CPPTYPE_ENUM:
+ case FieldDescriptor::CPPTYPE_FLOAT:
+ return 4;
+
+ case FieldDescriptor::CPPTYPE_INT64:
+ case FieldDescriptor::CPPTYPE_UINT64:
+ case FieldDescriptor::CPPTYPE_DOUBLE:
+ case FieldDescriptor::CPPTYPE_STRING:
+ case FieldDescriptor::CPPTYPE_MESSAGE:
+ return 8;
+ }
+ GOOGLE_LOG(FATAL) << "Can't get here.";
+ return -1; // Make compiler happy.
+}
+
string FieldConstantName(const FieldDescriptor *field) {
string field_name = UnderscoresToCamelCase(field->name(), true);
string result = "k" + field_name + "FieldNumber";
@@ -440,23 +515,8 @@ string FilenameIdentifier(const string& filename) {
return result;
}
-// Return the name of the AddDescriptors() function for a given file.
-string GlobalAddDescriptorsName(const string& filename) {
- return "protobuf_AddDesc_" + FilenameIdentifier(filename);
-}
-
-string GlobalInitDefaultsName(const string& filename) {
- return "protobuf_InitDefaults_" + FilenameIdentifier(filename);
-}
-
-// Return the name of the AssignDescriptors() function for a given file.
-string GlobalOffsetTableName(const string& filename) {
- return "protobuf_Offsets_" + FilenameIdentifier(filename);
-}
-
-// Return the name of the ShutdownFile() function for a given file.
-string GlobalShutdownFileName(const string& filename) {
- return "protobuf_ShutdownFile_" + FilenameIdentifier(filename);
+string FileLevelNamespace(const string& filename) {
+ return "protobuf_" + FilenameIdentifier(filename);
}
// Return the qualified C++ name for a file level symbol.
@@ -492,19 +552,6 @@ string SafeFunctionName(const Descriptor* descriptor,
return function_name;
}
-bool StaticInitializersForced(const FileDescriptor* file,
- const Options& options) {
- if (HasDescriptorMethods(file, options) || file->extension_count() > 0) {
- return true;
- }
- for (int i = 0; i < file->message_type_count(); ++i) {
- if (HasExtension(file->message_type(i))) {
- return true;
- }
- }
- return false;
-}
-
static bool HasMapFields(const Descriptor* descriptor) {
for (int i = 0; i < descriptor->field_count(); ++i) {
@@ -669,6 +716,210 @@ void GenerateUtf8CheckCodeForCord(const FieldDescriptor* field,
"VerifyUtf8Cord", "VerifyUTF8CordNamedField", printer);
}
+namespace {
+
+void Flatten(const Descriptor* descriptor,
+ std::vector<const Descriptor*>* flatten) {
+ for (int i = 0; i < descriptor->nested_type_count(); i++)
+ Flatten(descriptor->nested_type(i), flatten);
+ flatten->push_back(descriptor);
+}
+
+} // namespace
+
+void FlattenMessagesInFile(const FileDescriptor* file,
+ std::vector<const Descriptor*>* result) {
+ for (int i = 0; i < file->message_type_count(); i++) {
+ Flatten(file->message_type(i), result);
+ }
+}
+
+bool HasWeakFields(const Descriptor* descriptor) {
+ return false;
+}
+
+bool HasWeakFields(const FileDescriptor* file) {
+ return false;
+}
+
+bool UsingImplicitWeakFields(const FileDescriptor* file,
+ const Options& options) {
+ return options.lite_implicit_weak_fields &&
+ GetOptimizeFor(file, options) == FileOptions::LITE_RUNTIME;
+}
+
+
+bool IsImplicitWeakField(const FieldDescriptor* field, const Options& options) {
+ return UsingImplicitWeakFields(field->file(), options) &&
+ field->type() == FieldDescriptor::TYPE_MESSAGE &&
+ !field->is_required() && !field->is_repeated() && !field->is_map() &&
+ field->containing_oneof() == NULL;
+}
+
+struct CompareDescriptors {
+ bool operator()(const Descriptor* a, const Descriptor* b) {
+ return a->full_name() < b->full_name();
+ }
+};
+
+SCCAnalyzer::NodeData SCCAnalyzer::DFS(const Descriptor* descriptor) {
+ // Must not have visited already.
+ GOOGLE_DCHECK_EQ(cache_.count(descriptor), 0);
+
+ // Mark visited by inserting in map.
+ NodeData& result = cache_[descriptor];
+ // Initialize data structures.
+ result.index = result.lowlink = index_++;
+ stack_.push_back(descriptor);
+
+ // Recurse the fields / nodes in graph
+ for (int i = 0; i < descriptor->field_count(); i++) {
+ const Descriptor* child = descriptor->field(i)->message_type();
+ if (child) {
+ if (cache_.count(child) == 0) {
+ // unexplored node
+ NodeData child_data = DFS(child);
+ result.lowlink = std::min(result.lowlink, child_data.lowlink);
+ } else {
+ NodeData child_data = cache_[child];
+ if (child_data.scc == NULL) {
+ // Still in the stack_ so we found a back edge
+ result.lowlink = std::min(result.lowlink, child_data.index);
+ }
+ }
+ }
+ }
+ if (result.index == result.lowlink) {
+ // This is the root of a strongly connected component
+ SCC* scc = CreateSCC();
+ while (true) {
+ const Descriptor* scc_desc = stack_.back();
+ scc->descriptors.push_back(scc_desc);
+ // Remove from stack
+ stack_.pop_back();
+ cache_[scc_desc].scc = scc;
+
+ if (scc_desc == descriptor) break;
+ }
+
+ // The order of descriptors is random and depends how this SCC was
+ // discovered. In-order to ensure maximum stability we sort it by name.
+ std::sort(scc->descriptors.begin(), scc->descriptors.end(),
+ CompareDescriptors());
+ AddChildren(scc);
+ }
+ return result;
+}
+
+void SCCAnalyzer::AddChildren(SCC* scc) {
+ std::set<const SCC*> seen;
+ for (int i = 0; i < scc->descriptors.size(); i++) {
+ const Descriptor* descriptor = scc->descriptors[i];
+ for (int j = 0; j < descriptor->field_count(); j++) {
+ const Descriptor* child_msg = descriptor->field(j)->message_type();
+ if (child_msg) {
+ const SCC* child = GetSCC(child_msg);
+ if (child == scc) continue;
+ if (seen.insert(child).second) {
+ scc->children.push_back(child);
+ }
+ }
+ }
+ }
+}
+
+MessageAnalysis SCCAnalyzer::GetSCCAnalysis(const SCC* scc) {
+ if (analysis_cache_.count(scc)) return analysis_cache_[scc];
+ MessageAnalysis result = MessageAnalysis();
+ for (int i = 0; i < scc->descriptors.size(); i++) {
+ const Descriptor* descriptor = scc->descriptors[i];
+ if (descriptor->extension_range_count() > 0) {
+ result.contains_extension = true;
+ }
+ for (int i = 0; i < descriptor->field_count(); i++) {
+ const FieldDescriptor* field = descriptor->field(i);
+ if (field->is_required()) {
+ result.contains_required = true;
+ }
+ switch (field->type()) {
+ case FieldDescriptor::TYPE_STRING:
+ case FieldDescriptor::TYPE_BYTES: {
+ if (field->options().ctype() == FieldOptions::CORD) {
+ result.contains_cord = true;
+ }
+ break;
+ }
+ case FieldDescriptor::TYPE_GROUP:
+ case FieldDescriptor::TYPE_MESSAGE: {
+ const SCC* child = GetSCC(field->message_type());
+ if (child != scc) {
+ MessageAnalysis analysis = GetSCCAnalysis(child);
+ result.contains_cord |= analysis.contains_cord;
+ result.contains_extension |= analysis.contains_extension;
+ if (!ShouldIgnoreRequiredFieldCheck(field, options_)) {
+ result.contains_required |= analysis.contains_required;
+ }
+ } else {
+ // This field points back into the same SCC hence the messages
+ // in the SCC are recursive. Note if SCC contains more than two
+ // nodes it has to be recursive, however this test also works for
+ // a single node that is recursive.
+ result.is_recursive = true;
+ }
+ break;
+ }
+ default:
+ break;
+ }
+ }
+ }
+ // We deliberately only insert the result here. After we contracted the SCC
+ // in the graph, the graph should be a DAG. Hence we shouldn't need to mark
+ // nodes visited as we can never return to them. By inserting them here
+ // we will go in an infinite loop if the SCC is not correct.
+ return analysis_cache_[scc] = result;
+}
+
+void ListAllFields(const Descriptor* d,
+ std::vector<const FieldDescriptor*>* fields) {
+ // Collect sub messages
+ for (int i = 0; i < d->nested_type_count(); i++) {
+ ListAllFields(d->nested_type(i), fields);
+ }
+ // Collect message level extensions.
+ for (int i = 0; i < d->extension_count(); i++) {
+ fields->push_back(d->extension(i));
+ }
+ // Add types of fields necessary
+ for (int i = 0; i < d->field_count(); i++) {
+ fields->push_back(d->field(i));
+ }
+}
+
+void ListAllFields(const FileDescriptor* d,
+ std::vector<const FieldDescriptor*>* fields) {
+ // Collect file level message.
+ for (int i = 0; i < d->message_type_count(); i++) {
+ ListAllFields(d->message_type(i), fields);
+ }
+ // Collect message level extensions.
+ for (int i = 0; i < d->extension_count(); i++) {
+ fields->push_back(d->extension(i));
+ }
+}
+
+void ListAllTypesForServices(const FileDescriptor* fd,
+ std::vector<const Descriptor*>* types) {
+ for (int i = 0; i < fd->service_count(); i++) {
+ const ServiceDescriptor* sd = fd->service(i);
+ for (int j = 0; j < sd->method_count(); j++) {
+ const MethodDescriptor* method = sd->method(j);
+ types->push_back(method->input_type());
+ types->push_back(method->output_type());
+ }
+ }
+}
+
} // namespace cpp
} // namespace compiler
} // namespace protobuf
diff --git a/src/google/protobuf/compiler/cpp/cpp_helpers.h b/src/google/protobuf/compiler/cpp/cpp_helpers.h
index c988bda8..e0f809c9 100644
--- a/src/google/protobuf/compiler/cpp/cpp_helpers.h
+++ b/src/google/protobuf/compiler/cpp/cpp_helpers.h
@@ -38,16 +38,13 @@
#include <map>
#include <string>
#include <google/protobuf/compiler/cpp/cpp_options.h>
+#include <google/protobuf/io/printer.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/descriptor.h>
+#include <google/protobuf/stubs/strutil.h>
namespace google {
namespace protobuf {
-
-namespace io {
-class Printer;
-}
-
namespace compiler {
namespace cpp {
@@ -56,6 +53,31 @@ namespace cpp {
extern const char kThickSeparator[];
extern const char kThinSeparator[];
+// Name space of the proto file. This namespace is such that the string
+// "<namespace>::some_name" is the correct fully qualified namespace.
+// This means if the package is empty the namespace is "", and otherwise
+// the namespace is "::foo::bar::...::baz" without trailing semi-colons.
+string Namespace(const string& package);
+inline string Namespace(const FileDescriptor* d) {
+ return Namespace(d->package());
+}
+template <typename Desc>
+string Namespace(const Desc* d) {
+ return Namespace(d->file());
+}
+
+// Returns true if it's safe to reset "field" to zero.
+bool CanInitializeByZeroing(const FieldDescriptor* field);
+
+string ClassName(const Descriptor* descriptor);
+string ClassName(const EnumDescriptor* enum_descriptor);
+template <typename Desc>
+string QualifiedClassName(const Desc* d) {
+ return Namespace(d) + "::" + ClassName(d);
+}
+
+// DEPRECATED just use ClassName or QualifiedClassName, a boolean is very
+// unreadable at the callsite.
// Returns the non-nested type name for the given type. If "qualified" is
// true, prefix the type with the full namespace. For example, if you had:
// package foo.bar;
@@ -64,8 +86,21 @@ extern const char kThinSeparator[];
// ::foo::bar::Baz_Qux
// While the non-qualified version would be:
// Baz_Qux
-string ClassName(const Descriptor* descriptor, bool qualified);
-string ClassName(const EnumDescriptor* enum_descriptor, bool qualified);
+inline string ClassName(const Descriptor* descriptor, bool qualified) {
+ return qualified ? QualifiedClassName(descriptor) : ClassName(descriptor);
+}
+
+inline string ClassName(const EnumDescriptor* descriptor, bool qualified) {
+ return qualified ? QualifiedClassName(descriptor) : ClassName(descriptor);
+}
+
+// Fully qualified name of the default_instance of this message.
+string DefaultInstanceName(const Descriptor* descriptor);
+
+// Returns the name of a no-op function that we can call to introduce a linker
+// dependency on the given message type. This is used to implement implicit weak
+// fields.
+string ReferenceFunctionName(const Descriptor* descriptor);
// Name of the CRTP class template (for use with proto_h).
// This is a class name, like "ProtoName_InternalBase".
@@ -89,6 +124,12 @@ string FieldName(const FieldDescriptor* field);
// Get the sanitized name that should be used for the given enum in C++ code.
string EnumValueName(const EnumValueDescriptor* enum_value);
+// Returns an estimate of the compiler's alignment for the field. This
+// can't guarantee to be correct because the generated code could be compiled on
+// different systems with different alignment rules. The estimates below assume
+// 64-bit pointers.
+int EstimateAlignmentSize(const FieldDescriptor* field);
+
// Get the unqualified name that should be used for a field's field
// number constant.
string FieldConstantName(const FieldDescriptor *field);
@@ -144,21 +185,19 @@ string DefaultValue(const FieldDescriptor* field);
// Convert a file name into a valid identifier.
string FilenameIdentifier(const string& filename);
-// Return the name of the AddDescriptors() function for a given file.
-string GlobalAddDescriptorsName(const string& filename);
-
-// Return the name of the InitDefaults() function for a given file.
-string GlobalInitDefaultsName(const string& filename);
-
-// Return the name of the offset table function for a given file.
-string GlobalOffsetTableName(const string& filename);
+// For each .proto file generates a unique namespace. In this namespace global
+// definitions are put to prevent collisions.
+string FileLevelNamespace(const string& filename);
+inline string FileLevelNamespace(const FileDescriptor* file) {
+ return FileLevelNamespace(file->name());
+}
+inline string FileLevelNamespace(const Descriptor* d) {
+ return FileLevelNamespace(d->file());
+}
// Return the qualified C++ name for a file level symbol.
string QualifiedFileLevelSymbol(const string& package, const string& name);
-// Return the name of the ShutdownFile() function for a given file.
-string GlobalShutdownFileName(const string& filename);
-
// Escape C++ trigraphs by escaping question marks to \?
string EscapeTrigraphs(const string& to_escape);
@@ -167,8 +206,18 @@ string SafeFunctionName(const Descriptor* descriptor,
const FieldDescriptor* field,
const string& prefix);
-// Returns true if unknown fields are preseved after parsing.
-inline bool PreserveUnknownFields(const Descriptor* message) {
+// Returns true if unknown fields are always preserved after parsing.
+inline bool AlwaysPreserveUnknownFields(const FileDescriptor* file) {
+ return file->syntax() != FileDescriptor::SYNTAX_PROTO3;
+}
+
+// Returns true if unknown fields are preserved after parsing.
+inline bool AlwaysPreserveUnknownFields(const Descriptor* message) {
+ return AlwaysPreserveUnknownFields(message->file());
+}
+
+// Returns true if generated messages have public unknown fields accessors
+inline bool PublicUnknownFieldsAccessors(const Descriptor* message) {
return message->file()->syntax() != FileDescriptor::SYNTAX_PROTO3;
}
@@ -176,10 +225,8 @@ inline bool PreserveUnknownFields(const Descriptor* message) {
::google::protobuf::FileOptions_OptimizeMode GetOptimizeFor(
const FileDescriptor* file, const Options& options);
-// If PreserveUnknownFields() is true, determines whether unknown
-// fields will be stored in an UnknownFieldSet or a string.
-// If PreserveUnknownFields() is false, this method will not be
-// used.
+// Determines whether unknown fields will be stored in an UnknownFieldSet or
+// a string.
inline bool UseUnknownFieldSet(const FileDescriptor* file,
const Options& options) {
return GetOptimizeFor(file, options) != FileOptions::LITE_RUNTIME;
@@ -222,10 +269,6 @@ inline bool HasFastArraySerialization(const FileDescriptor* file,
return GetOptimizeFor(file, options) == FileOptions::SPEED;
}
-// Returns whether we have to generate code with static initializers.
-bool StaticInitializersForced(const FileDescriptor* file,
- const Options& options);
-
inline bool IsMapEntryMessage(const Descriptor* descriptor) {
return descriptor->options().map_entry();
@@ -262,6 +305,11 @@ inline bool SupportsArenas(const FieldDescriptor* field) {
return SupportsArenas(field->file());
}
+inline bool IsCrossFileMessage(const FieldDescriptor* field) {
+ return field->type() == FieldDescriptor::TYPE_MESSAGE &&
+ field->message_type()->file() != field->file();
+}
+
bool IsAnyMessage(const FileDescriptor* descriptor);
bool IsAnyMessage(const Descriptor* descriptor);
@@ -285,6 +333,136 @@ inline ::google::protobuf::FileOptions_OptimizeMode GetOptimizeFor(
: file->options().optimize_for();
}
+// This orders the messages in a .pb.cc as it's outputted by file.cc
+void FlattenMessagesInFile(const FileDescriptor* file,
+ std::vector<const Descriptor*>* result);
+inline std::vector<const Descriptor*> FlattenMessagesInFile(
+ const FileDescriptor* file) {
+ std::vector<const Descriptor*> result;
+ FlattenMessagesInFile(file, &result);
+ return result;
+}
+
+bool HasWeakFields(const Descriptor* desc);
+bool HasWeakFields(const FileDescriptor* desc);
+
+// Indicates whether we should use implicit weak fields for this file.
+bool UsingImplicitWeakFields(const FileDescriptor* file,
+ const Options& options);
+
+// Indicates whether to treat this field as implicitly weak.
+bool IsImplicitWeakField(const FieldDescriptor* field, const Options& options);
+
+// Returns true if the "required" restriction check should be ignored for the
+// given field.
+inline static bool ShouldIgnoreRequiredFieldCheck(const FieldDescriptor* field,
+ const Options& options) {
+ return false;
+}
+
+class LIBPROTOC_EXPORT NamespaceOpener {
+ public:
+ explicit NamespaceOpener(io::Printer* printer) : printer_(printer) {}
+ NamespaceOpener(const string& name, io::Printer* printer)
+ : printer_(printer) {
+ ChangeTo(name);
+ }
+ ~NamespaceOpener() { ChangeTo(""); }
+
+ void ChangeTo(const string& name) {
+ std::vector<string> new_stack_ =
+ Split(name, "::", true);
+ int len = std::min(name_stack_.size(), new_stack_.size());
+ int common_idx = 0;
+ while (common_idx < len) {
+ if (name_stack_[common_idx] != new_stack_[common_idx]) break;
+ common_idx++;
+ }
+ for (int i = name_stack_.size() - 1; i >= common_idx; i--) {
+ printer_->Print("} // namespace $ns$\n", "ns", name_stack_[i]);
+ }
+ name_stack_.swap(new_stack_);
+ for (int i = common_idx; i < name_stack_.size(); i++) {
+ printer_->Print("namespace $ns$ {\n", "ns", name_stack_[i]);
+ }
+ }
+
+ private:
+ io::Printer* printer_;
+ std::vector<string> name_stack_;
+};
+
+// Description of each strongly connected component. Note that the order
+// of both the descriptors in this SCC and the order of children is
+// deterministic.
+struct SCC {
+ std::vector<const Descriptor*> descriptors;
+ std::vector<const SCC*> children;
+
+ const Descriptor* GetRepresentative() const { return descriptors[0]; }
+};
+
+struct MessageAnalysis {
+ bool is_recursive;
+ bool contains_cord;
+ bool contains_extension;
+ bool contains_required;
+};
+
+// This class is used in FileGenerator, to ensure linear instead of
+// quadratic performance, if we do this per message we would get O(V*(V+E)).
+// Logically this is just only used in message.cc, but in the header for
+// FileGenerator to help share it.
+class LIBPROTOC_EXPORT SCCAnalyzer {
+ public:
+ explicit SCCAnalyzer(const Options& options) : options_(options), index_(0) {}
+ ~SCCAnalyzer() {
+ for (int i = 0; i < garbage_bin_.size(); i++) delete garbage_bin_[i];
+ }
+
+ const SCC* GetSCC(const Descriptor* descriptor) {
+ if (cache_.count(descriptor)) return cache_[descriptor].scc;
+ return DFS(descriptor).scc;
+ }
+
+ MessageAnalysis GetSCCAnalysis(const SCC* scc);
+
+ bool HasRequiredFields(const Descriptor* descriptor) {
+ MessageAnalysis result = GetSCCAnalysis(GetSCC(descriptor));
+ return result.contains_required || result.contains_extension;
+ }
+
+ private:
+ struct NodeData {
+ const SCC* scc; // if null it means its still on the stack
+ int index;
+ int lowlink;
+ };
+
+ Options options_;
+ std::map<const Descriptor*, NodeData> cache_;
+ std::map<const SCC*, MessageAnalysis> analysis_cache_;
+ std::vector<const Descriptor*> stack_;
+ int index_;
+ std::vector<SCC*> garbage_bin_;
+
+ SCC* CreateSCC() {
+ garbage_bin_.push_back(new SCC());
+ return garbage_bin_.back();
+ }
+
+ // Tarjan's Strongly Connected Components algo
+ NodeData DFS(const Descriptor* descriptor);
+
+ // Add the SCC's that are children of this SCC to its children.
+ void AddChildren(SCC* scc);
+};
+
+void ListAllFields(const FileDescriptor* d,
+ std::vector<const FieldDescriptor*>* fields);
+void ListAllTypesForServices(const FileDescriptor* fd,
+ std::vector<const Descriptor*>* types);
+
} // namespace cpp
} // namespace compiler
} // namespace protobuf
diff --git a/src/google/protobuf/compiler/cpp/cpp_map_field.cc b/src/google/protobuf/compiler/cpp/cpp_map_field.cc
index 5c4b56f7..b22c0754 100644
--- a/src/google/protobuf/compiler/cpp/cpp_map_field.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_map_field.cc
@@ -32,6 +32,7 @@
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/wire_format.h>
+
#include <google/protobuf/stubs/strutil.h>
namespace google {
@@ -49,6 +50,8 @@ void SetMessageVariables(const FieldDescriptor* descriptor,
const Options& options) {
SetCommonFieldVariables(descriptor, variables, options);
(*variables)["type"] = ClassName(descriptor->message_type(), false);
+ (*variables)["file_namespace"] =
+ FileLevelNamespace(descriptor->file()->name());
(*variables)["stream_writer"] =
(*variables)["declared_type"] +
(HasFastArraySerialization(descriptor->message_type()->file(), options)
@@ -112,40 +115,36 @@ MapFieldGenerator::~MapFieldGenerator() {}
void MapFieldGenerator::
GeneratePrivateMembers(io::Printer* printer) const {
printer->Print(variables_,
- "typedef ::google::protobuf::internal::MapEntryLite<\n"
- " $key_cpp$, $val_cpp$,\n"
- " $key_wire_type$,\n"
- " $val_wire_type$,\n"
- " $default_enum_value$ >\n"
- " $map_classname$;\n"
- "::google::protobuf::internal::MapField$lite$<\n"
- " $key_cpp$, $val_cpp$,\n"
- " $key_wire_type$,\n"
- " $val_wire_type$,\n"
- " $default_enum_value$ > $name$_;\n");
+ "::google::protobuf::internal::MapField$lite$<\n"
+ " $map_classname$,\n"
+ " $key_cpp$, $val_cpp$,\n"
+ " $key_wire_type$,\n"
+ " $val_wire_type$,\n"
+ " $default_enum_value$ > $name$_;\n");
}
void MapFieldGenerator::
GenerateAccessorDeclarations(io::Printer* printer) const {
- printer->Print(variables_,
+ printer->Print(
+ variables_,
"$deprecated_attr$const ::google::protobuf::Map< $key_cpp$, $val_cpp$ >&\n"
- " $name$() const;\n"
- "$deprecated_attr$::google::protobuf::Map< $key_cpp$, $val_cpp$ >*\n"
- " mutable_$name$();\n");
+ " $name$() const;\n");
+ printer->Annotate("name", descriptor_);
+ printer->Print(variables_,
+ "$deprecated_attr$::google::protobuf::Map< $key_cpp$, $val_cpp$ >*\n"
+ " ${$mutable_$name$$}$();\n");
+ printer->Annotate("{", "}", descriptor_);
}
void MapFieldGenerator::
-GenerateInlineAccessorDefinitions(io::Printer* printer,
- bool is_inline) const {
- std::map<string, string> variables(variables_);
- variables["inline"] = is_inline ? "inline" : "";
- printer->Print(variables,
- "$inline$ const ::google::protobuf::Map< $key_cpp$, $val_cpp$ >&\n"
+GenerateInlineAccessorDefinitions(io::Printer* printer) const {
+ printer->Print(variables_,
+ "inline const ::google::protobuf::Map< $key_cpp$, $val_cpp$ >&\n"
"$classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_map:$full_name$)\n"
" return $name$_.GetMap();\n"
"}\n"
- "$inline$ ::google::protobuf::Map< $key_cpp$, $val_cpp$ >*\n"
+ "inline ::google::protobuf::Map< $key_cpp$, $val_cpp$ >*\n"
"$classname$::mutable_$name$() {\n"
" // @@protoc_insertion_point(field_mutable_map:$full_name$)\n"
" return $name$_.MutableMap();\n"
@@ -154,9 +153,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
void MapFieldGenerator::
GenerateClearingCode(io::Printer* printer) const {
- std::map<string, string> variables(variables_);
- variables["this_message"] = dependent_field_ ? DependentBaseDownCast() : "";
- printer->Print(variables, "$this_message$$name$_.Clear();\n");
+ printer->Print(variables_, "$name$_.Clear();\n");
}
void MapFieldGenerator::
@@ -170,17 +167,6 @@ GenerateSwappingCode(io::Printer* printer) const {
}
void MapFieldGenerator::
-GenerateConstructorCode(io::Printer* printer) const {
- if (HasDescriptorMethods(descriptor_->file(), options_)) {
- printer->Print(variables_,
- "$name$_.SetAssignDescriptorCallback(\n"
- " protobuf_AssignDescriptorsOnce);\n"
- "$name$_.SetEntryDescriptor(\n"
- " &$type$_descriptor);\n");
- }
-}
-
-void MapFieldGenerator::
GenerateCopyConstructorCode(io::Printer* printer) const {
GenerateConstructorCode(printer);
GenerateMergingCode(printer);
@@ -197,13 +183,15 @@ GenerateMergeFromCodedStream(io::Printer* printer) const {
string value;
if (IsProto3Field(descriptor_) ||
value_field->type() != FieldDescriptor::TYPE_ENUM) {
- printer->Print(variables_,
+ printer->Print(
+ variables_,
"$map_classname$::Parser< ::google::protobuf::internal::MapField$lite$<\n"
- " $key_cpp$, $val_cpp$,\n"
- " $key_wire_type$,\n"
- " $val_wire_type$,\n"
- " $default_enum_value$ >,\n"
- " ::google::protobuf::Map< $key_cpp$, $val_cpp$ > >"
+ " $map_classname$,\n"
+ " $key_cpp$, $val_cpp$,\n"
+ " $key_wire_type$,\n"
+ " $val_wire_type$,\n"
+ " $default_enum_value$ >,\n"
+ " ::google::protobuf::Map< $key_cpp$, $val_cpp$ > >"
" parser(&$name$_);\n"
"DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(\n"
" input, &parser));\n");
@@ -231,7 +219,8 @@ GenerateMergeFromCodedStream(io::Printer* printer) const {
} else {
printer->Print(variables_,
" unknown_fields_stream.WriteVarint32($tag$u);\n"
- " unknown_fields_stream.WriteVarint32(data.size());\n"
+ " unknown_fields_stream.WriteVarint32(\n"
+ " static_cast< ::google::protobuf::uint32>(data.size()));\n"
" unknown_fields_stream.WriteString(data);\n");
}
@@ -242,12 +231,16 @@ GenerateMergeFromCodedStream(io::Printer* printer) const {
if (key_field->type() == FieldDescriptor::TYPE_STRING) {
GenerateUtf8CheckCodeForString(
- key_field, options_, true, variables_,
- StrCat(key, ".data(), ", key, ".length(),\n").data(), printer);
+ key_field, options_, true, variables_,
+ StrCat(key, ".data(), static_cast<int>(", key, ".length()),\n").data(),
+ printer);
}
if (value_field->type() == FieldDescriptor::TYPE_STRING) {
- GenerateUtf8CheckCodeForString(value_field, options_, true, variables_,
- StrCat(value, ".data(), ", value, ".length(),\n").data(), printer);
+ GenerateUtf8CheckCodeForString(
+ value_field, options_, true, variables_,
+ StrCat(value, ".data(), static_cast<int>(", value, ".length()),\n")
+ .data(),
+ printer);
}
// If entry is allocated by arena, its desctructor should be avoided.
@@ -351,14 +344,14 @@ void MapFieldGenerator::GenerateSerializeWithCachedSizes(
printer->Indent();
printer->Indent();
if (string_key) {
- GenerateUtf8CheckCodeForString(key_field, options_, false, variables,
- "p->first.data(), p->first.length(),\n",
- printer);
+ GenerateUtf8CheckCodeForString(
+ key_field, options_, false, variables,
+ "p->first.data(), static_cast<int>(p->first.length()),\n", printer);
}
if (string_value) {
- GenerateUtf8CheckCodeForString(value_field, options_, false, variables,
- "p->second.data(), p->second.length(),\n",
- printer);
+ GenerateUtf8CheckCodeForString(
+ value_field, options_, false, variables,
+ "p->second.data(), static_cast<int>(p->second.length()),\n", printer);
}
printer->Outdent();
printer->Outdent();
@@ -379,13 +372,14 @@ void MapFieldGenerator::GenerateSerializeWithCachedSizes(
" for (::google::protobuf::Map< $key_cpp$, $val_cpp$ >::const_iterator\n"
" it = this->$name$().begin();\n"
" it != this->$name$().end(); ++it, ++n) {\n"
- " items[n] = SortItem(&*it);\n"
+ " items[static_cast<ptrdiff_t>(n)] = SortItem(&*it);\n"
" }\n"
- " ::std::sort(&items[0], &items[n], Less());\n");
+ " ::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less());\n");
printer->Indent();
GenerateSerializationLoop(printer, variables, SupportsArenas(descriptor_),
- utf8_check, "for (size_type i = 0; i < n; i++)",
- string_key ? "items[i]" : "items[i].second", false);
+ utf8_check, "for (size_type i = 0; i < n; i++)",
+ string_key ? "items[static_cast<ptrdiff_t>(i)]" :
+ "items[static_cast<ptrdiff_t>(i)].second", false);
printer->Outdent();
printer->Print(
"} else {\n");
diff --git a/src/google/protobuf/compiler/cpp/cpp_map_field.h b/src/google/protobuf/compiler/cpp/cpp_map_field.h
index 816687b3..88e3b464 100644
--- a/src/google/protobuf/compiler/cpp/cpp_map_field.h
+++ b/src/google/protobuf/compiler/cpp/cpp_map_field.h
@@ -49,12 +49,11 @@ class MapFieldGenerator : public FieldGenerator {
// implements FieldGenerator ---------------------------------------
void GeneratePrivateMembers(io::Printer* printer) const;
void GenerateAccessorDeclarations(io::Printer* printer) const;
- void GenerateInlineAccessorDefinitions(io::Printer* printer,
- bool is_inline) const;
+ void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateMergingCode(io::Printer* printer) const;
void GenerateSwappingCode(io::Printer* printer) const;
- void GenerateConstructorCode(io::Printer* printer) const;
+ void GenerateConstructorCode(io::Printer* printer) const {}
void GenerateCopyConstructorCode(io::Printer* printer) const;
void GenerateMergeFromCodedStream(io::Printer* printer) const;
void GenerateSerializeWithCachedSizes(io::Printer* printer) const;
diff --git a/src/google/protobuf/compiler/cpp/cpp_message.cc b/src/google/protobuf/compiler/cpp/cpp_message.cc
index 2b71acb5..60467598 100644
--- a/src/google/protobuf/compiler/cpp/cpp_message.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_message.cc
@@ -32,6 +32,8 @@
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
+#include <google/protobuf/compiler/cpp/cpp_message.h>
+
#include <algorithm>
#include <google/protobuf/stubs/hash.h>
#include <map>
@@ -41,16 +43,21 @@
#endif
#include <utility>
#include <vector>
-#include <google/protobuf/compiler/cpp/cpp_message.h>
-#include <google/protobuf/compiler/cpp/cpp_field.h>
+
#include <google/protobuf/compiler/cpp/cpp_enum.h>
#include <google/protobuf/compiler/cpp/cpp_extension.h>
+#include <google/protobuf/compiler/cpp/cpp_field.h>
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
-#include <google/protobuf/stubs/strutil.h>
-#include <google/protobuf/io/printer.h>
+#include <google/protobuf/compiler/cpp/cpp_padding_optimizer.h>
#include <google/protobuf/io/coded_stream.h>
-#include <google/protobuf/wire_format.h>
+#include <google/protobuf/io/printer.h>
#include <google/protobuf/descriptor.pb.h>
+#include <google/protobuf/generated_message_table_driven.h>
+#include <google/protobuf/generated_message_util.h>
+#include <google/protobuf/map_entry_lite.h>
+#include <google/protobuf/wire_format.h>
+#include <google/protobuf/stubs/strutil.h>
+#include <google/protobuf/stubs/substitute.h>
namespace google {
@@ -103,154 +110,6 @@ struct ExtensionRangeSorter {
}
};
-// Returns true if the "required" restriction check should be ignored for the
-// given field.
-inline static bool ShouldIgnoreRequiredFieldCheck(const FieldDescriptor* field,
- const Options& options) {
- return false;
-}
-
-// Returns true if the message type has any required fields. If it doesn't,
-// we can optimize out calls to its IsInitialized() method.
-//
-// already_seen is used to avoid checking the same type multiple times
-// (and also to protect against recursion).
-static bool HasRequiredFields(const Descriptor* type, const Options& options,
- hash_set<const Descriptor*>* already_seen) {
- if (already_seen->count(type) > 0) {
- // Since the first occurrence of a required field causes the whole
- // function to return true, we can assume that if the type is already
- // in the cache it didn't have any required fields.
- return false;
- }
- already_seen->insert(type);
-
- // If the type has extensions, an extension with message type could contain
- // required fields, so we have to be conservative and assume such an
- // extension exists.
- if (type->extension_range_count() > 0) return true;
-
- for (int i = 0; i < type->field_count(); i++) {
- const FieldDescriptor* field = type->field(i);
- if (field->is_required()) {
- return true;
- }
- if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE &&
- !ShouldIgnoreRequiredFieldCheck(field, options)) {
- if (HasRequiredFields(field->message_type(), options, already_seen)) {
- return true;
- }
- }
- }
-
- return false;
-}
-
-static bool HasRequiredFields(const Descriptor* type, const Options& options) {
- hash_set<const Descriptor*> already_seen;
- return HasRequiredFields(type, options, &already_seen);
-}
-
-// This returns an estimate of the compiler's alignment for the field. This
-// can't guarantee to be correct because the generated code could be compiled on
-// different systems with different alignment rules. The estimates below assume
-// 64-bit pointers.
-int EstimateAlignmentSize(const FieldDescriptor* field) {
- if (field == NULL) return 0;
- if (field->is_repeated()) return 8;
- switch (field->cpp_type()) {
- case FieldDescriptor::CPPTYPE_BOOL:
- return 1;
-
- case FieldDescriptor::CPPTYPE_INT32:
- case FieldDescriptor::CPPTYPE_UINT32:
- case FieldDescriptor::CPPTYPE_ENUM:
- case FieldDescriptor::CPPTYPE_FLOAT:
- return 4;
-
- case FieldDescriptor::CPPTYPE_INT64:
- case FieldDescriptor::CPPTYPE_UINT64:
- case FieldDescriptor::CPPTYPE_DOUBLE:
- case FieldDescriptor::CPPTYPE_STRING:
- case FieldDescriptor::CPPTYPE_MESSAGE:
- return 8;
- }
- GOOGLE_LOG(FATAL) << "Can't get here.";
- return -1; // Make compiler happy.
-}
-
-// FieldGroup is just a helper for OptimizePadding below. It holds a vector of
-// fields that are grouped together because they have compatible alignment, and
-// a preferred location in the final field ordering.
-class FieldGroup {
- public:
- FieldGroup()
- : preferred_location_(0) {}
-
- // A group with a single field.
- FieldGroup(float preferred_location, const FieldDescriptor* field)
- : preferred_location_(preferred_location),
- fields_(1, field) {}
-
- // Append the fields in 'other' to this group.
- void Append(const FieldGroup& other) {
- if (other.fields_.empty()) {
- return;
- }
- // Preferred location is the average among all the fields, so we weight by
- // the number of fields on each FieldGroup object.
- preferred_location_ =
- (preferred_location_ * fields_.size() +
- (other.preferred_location_ * other.fields_.size())) /
- (fields_.size() + other.fields_.size());
- fields_.insert(fields_.end(), other.fields_.begin(), other.fields_.end());
- }
-
- void SetPreferredLocation(float location) { preferred_location_ = location; }
- const std::vector<const FieldDescriptor*>& fields() const { return fields_; }
-
- // FieldGroup objects sort by their preferred location.
- bool operator<(const FieldGroup& other) const {
- return preferred_location_ < other.preferred_location_;
- }
-
- private:
- // "preferred_location_" is an estimate of where this group should go in the
- // final list of fields. We compute this by taking the average index of each
- // field in this group in the original ordering of fields. This is very
- // approximate, but should put this group close to where its member fields
- // originally went.
- float preferred_location_;
- std::vector<const FieldDescriptor*> fields_;
- // We rely on the default copy constructor and operator= so this type can be
- // used in a vector.
-};
-
-// Helper for the code that emits the Clear() method.
-bool CanInitializeByZeroing(const FieldDescriptor* field) {
- if (field->is_repeated() || field->is_extension()) return false;
- switch (field->cpp_type()) {
- case internal::WireFormatLite::CPPTYPE_ENUM:
- return field->default_value_enum()->number() == 0;
- case internal::WireFormatLite::CPPTYPE_INT32:
- return field->default_value_int32() == 0;
- case internal::WireFormatLite::CPPTYPE_INT64:
- return field->default_value_int64() == 0;
- case internal::WireFormatLite::CPPTYPE_UINT32:
- return field->default_value_uint32() == 0;
- case internal::WireFormatLite::CPPTYPE_UINT64:
- return field->default_value_uint64() == 0;
- case internal::WireFormatLite::CPPTYPE_FLOAT:
- return field->default_value_float() == 0;
- case internal::WireFormatLite::CPPTYPE_DOUBLE:
- return field->default_value_double() == 0;
- case internal::WireFormatLite::CPPTYPE_BOOL:
- return field->default_value_bool() == false;
- default:
- return false;
- }
-}
-
bool IsPOD(const FieldDescriptor* field) {
if (field->is_repeated() || field->is_extension()) return false;
switch (field->cpp_type()) {
@@ -284,132 +143,6 @@ bool CanConstructByZeroing(const FieldDescriptor* field,
return ret;
}
-// Reorder 'fields' so that if the fields are output into a c++ class in the new
-// order, fields of similiar family (see below) are together and within each
-// family, alignment padding is minimized.
-//
-// We try to do this while keeping each field as close as possible to its
-// declaration order (from the .proto file) so that we don't reduce cache
-// locality much for function that access each field in order. This is also the
-// only (weak) signal we have for author intent concerning field layout.
-//
-// TODO(ckennelly): If/when we have profiles available for the compiler, use
-// those rather than respect declaration order.
-//
-// We classify each field into a particular "family" of fields, that we perform
-// the same operation on in our generated functions.
-//
-// REPEATED is placed first, as the C++ compiler automatically initializes
-// these fields in layout order.
-//
-// STRING is grouped next, as our Clear/SharedCtor/SharedDtor walks it and
-// calls ArenaStringPtr::Destroy on each.
-//
-//
-// MESSAGE is grouped next, as our Clear/SharedDtor code walks it and calls
-// delete on each. We initialize these fields with a NULL pointer (see
-// MessageFieldGenerator::GenerateConstructorCode), which allows them to be
-// memset.
-//
-// ZERO_INITIALIZABLE is memset in Clear/SharedCtor
-//
-// OTHER these fields are initialized one-by-one.
-void OptimizePadding(std::vector<const FieldDescriptor*>* fields,
- const Options& options) {
- // The sorted numeric order of Family determines the declaration order in the
- // memory layout.
- enum Family {
- REPEATED = 0,
- STRING = 1,
- MESSAGE = 2,
- ZERO_INITIALIZABLE = 4,
- OTHER = 5,
- kMaxFamily
- };
-
- // First divide fields into those that align to 1 byte, 4 bytes or 8 bytes.
- std::vector<FieldGroup> aligned_to_1[kMaxFamily];
- std::vector<FieldGroup> aligned_to_4[kMaxFamily];
- std::vector<FieldGroup> aligned_to_8[kMaxFamily];
- for (int i = 0; i < fields->size(); ++i) {
- const FieldDescriptor* field = (*fields)[i];
-
- Family f = OTHER;
- if (field->is_repeated()) {
- f = REPEATED;
- } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_STRING) {
- f = STRING;
- } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
- f = MESSAGE;
-
- } else if (CanInitializeByZeroing(field)) {
- f = ZERO_INITIALIZABLE;
- }
-
- switch (EstimateAlignmentSize(field)) {
- case 1: aligned_to_1[f].push_back(FieldGroup(i, field)); break;
- case 4: aligned_to_4[f].push_back(FieldGroup(i, field)); break;
- case 8: aligned_to_8[f].push_back(FieldGroup(i, field)); break;
- default:
- GOOGLE_LOG(FATAL) << "Unknown alignment size.";
- }
- }
-
- // For each family, group fields to optimize padding.
- for (int f = 0; f < kMaxFamily; f++) {
- // Now group fields aligned to 1 byte into sets of 4, and treat those like a
- // single field aligned to 4 bytes.
- for (int i = 0; i < aligned_to_1[f].size(); i += 4) {
- FieldGroup field_group;
- for (int j = i; j < aligned_to_1[f].size() && j < i + 4; ++j) {
- field_group.Append(aligned_to_1[f][j]);
- }
- aligned_to_4[f].push_back(field_group);
- }
- // Sort by preferred location to keep fields as close to their declaration
- // order as possible. Using stable_sort ensures that the output is
- // consistent across runs.
- std::stable_sort(aligned_to_4[f].begin(), aligned_to_4[f].end());
-
- // Now group fields aligned to 4 bytes (or the 4-field groups created above)
- // into pairs, and treat those like a single field aligned to 8 bytes.
- for (int i = 0; i < aligned_to_4[f].size(); i += 2) {
- FieldGroup field_group;
- for (int j = i; j < aligned_to_4[f].size() && j < i + 2; ++j) {
- field_group.Append(aligned_to_4[f][j]);
- }
- if (i == aligned_to_4[f].size() - 1) {
- if (f == OTHER) {
- // Move incomplete 4-byte block to the beginning. This is done to
- // pair with the (possible) leftover blocks from the
- // ZERO_INITIALIZABLE family.
- field_group.SetPreferredLocation(-1);
- } else {
- // Move incomplete 4-byte block to the end.
- field_group.SetPreferredLocation(fields->size() + 1);
- }
- }
- aligned_to_8[f].push_back(field_group);
- }
- // Sort by preferred location.
- std::stable_sort(aligned_to_8[f].begin(), aligned_to_8[f].end());
- }
-
- // Now pull out all the FieldDescriptors in order.
- fields->clear();
- for (int f = 0; f < kMaxFamily; ++f) {
- for (int i = 0; i < aligned_to_8[f].size(); ++i) {
- fields->insert(fields->end(),
- aligned_to_8[f][i].fields().begin(),
- aligned_to_8[f][i].fields().end());
- }
- }
-}
-
-string MessageTypeProtoName(const FieldDescriptor* field) {
- return field->message_type()->full_name();
-}
-
// Emits an if-statement with a condition that evaluates to true if |field| is
// considered non-default (will be sent over the wire), for message types
// without true field presence. Should only be called if
@@ -464,25 +197,31 @@ bool HasHasMethod(const FieldDescriptor* field) {
void CollectMapInfo(const Descriptor* descriptor,
std::map<string, string>* variables) {
GOOGLE_CHECK(IsMapEntryMessage(descriptor));
+ std::map<string, string>& vars = *variables;
const FieldDescriptor* key = descriptor->FindFieldByName("key");
const FieldDescriptor* val = descriptor->FindFieldByName("value");
- (*variables)["key"] = PrimitiveTypeName(key->cpp_type());
+ vars["key_cpp"] = PrimitiveTypeName(key->cpp_type());
switch (val->cpp_type()) {
case FieldDescriptor::CPPTYPE_MESSAGE:
- (*variables)["val"] = FieldMessageTypeName(val);
+ vars["val_cpp"] = FieldMessageTypeName(val);
break;
case FieldDescriptor::CPPTYPE_ENUM:
- (*variables)["val"] = ClassName(val->enum_type(), true);
+ vars["val_cpp"] = ClassName(val->enum_type(), true);
break;
default:
- (*variables)["val"] = PrimitiveTypeName(val->cpp_type());
+ vars["val_cpp"] = PrimitiveTypeName(val->cpp_type());
+ }
+ vars["key_wire_type"] = "::google::protobuf::internal::WireFormatLite::TYPE_" +
+ ToUpper(DeclaredTypeMethodName(key->type()));
+ vars["val_wire_type"] = "::google::protobuf::internal::WireFormatLite::TYPE_" +
+ ToUpper(DeclaredTypeMethodName(val->type()));
+ if (descriptor->file()->syntax() != FileDescriptor::SYNTAX_PROTO3 &&
+ val->type() == FieldDescriptor::TYPE_ENUM) {
+ const EnumValueDescriptor* default_value = val->default_value_enum();
+ vars["default_enum_value"] = Int32ToString(default_value->number());
+ } else {
+ vars["default_enum_value"] = "0";
}
- (*variables)["key_wire_type"] =
- "::google::protobuf::internal::WireFormatLite::TYPE_" +
- ToUpper(DeclaredTypeMethodName(key->type()));
- (*variables)["val_wire_type"] =
- "::google::protobuf::internal::WireFormatLite::TYPE_" +
- ToUpper(DeclaredTypeMethodName(val->type()));
}
// Does the given field have a private (internal helper only) has_$name$()
@@ -495,35 +234,134 @@ bool HasPrivateHasMethod(const FieldDescriptor* field) {
}
+bool TableDrivenParsingEnabled(
+ const Descriptor* descriptor, const Options& options) {
+ if (!options.table_driven_parsing) {
+ return false;
+ }
+
+ // Consider table-driven parsing. We only do this if:
+ // - We have has_bits for fields. This avoids a check on every field we set
+ // when are present (the common case).
+ if (!HasFieldPresence(descriptor->file())) {
+ return false;
+ }
+
+ const double table_sparseness = 0.5;
+ int max_field_number = 0;
+ for (int i = 0; i < descriptor->field_count(); i++) {
+ const FieldDescriptor* field = descriptor->field(i);
+ if (max_field_number < field->number()) {
+ max_field_number = field->number();
+ }
+
+ // - There are no weak fields.
+ if (field->options().weak()) {
+ return false;
+ }
+ }
+
+ // - There range of field numbers is "small"
+ if (max_field_number >= (2 << 14)) {
+ return false;
+ }
+
+ // - Field numbers are relatively dense within the actual number of fields.
+ // We check for strictly greater than in the case where there are no fields
+ // (only extensions) so max_field_number == descriptor->field_count() == 0.
+ if (max_field_number * table_sparseness > descriptor->field_count()) {
+ return false;
+ }
+
+ // - This is not a MapEntryMessage.
+ if (IsMapEntryMessage(descriptor)) {
+ return false;
+ }
+
+ return true;
+}
+
+void SetUnknkownFieldsVariable(const Descriptor* descriptor,
+ const Options& options,
+ std::map<string, string>* variables) {
+ if (UseUnknownFieldSet(descriptor->file(), options)) {
+ (*variables)["unknown_fields_type"] = "::google::protobuf::UnknownFieldSet";
+ } else {
+ (*variables)["unknown_fields_type"] = "::std::string";
+ }
+ if (AlwaysPreserveUnknownFields(descriptor)) {
+ (*variables)["have_unknown_fields"] =
+ "_internal_metadata_.have_unknown_fields()";
+ (*variables)["unknown_fields"] = "_internal_metadata_.unknown_fields()";
+ } else {
+ (*variables)["have_unknown_fields"] =
+ "(_internal_metadata_.have_unknown_fields() && "
+ " ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())";
+ (*variables)["unknown_fields"] =
+ "(::google::protobuf::internal::GetProto3PreserveUnknownsDefault()"
+ " ? _internal_metadata_.unknown_fields()"
+ " : _internal_metadata_.default_instance())";
+ }
+ (*variables)["mutable_unknown_fields"] =
+ "_internal_metadata_.mutable_unknown_fields()";
+}
+
+bool IsCrossFileMapField(const FieldDescriptor* field) {
+ if (!field->is_map()) {
+ return false;
+ }
+
+ const Descriptor* d = field->message_type();
+ const FieldDescriptor* value = d->FindFieldByNumber(2);
+
+ return IsCrossFileMessage(value);
+}
+
+bool IsCrossFileMaybeMap(const FieldDescriptor* field) {
+ if (IsCrossFileMapField(field)) {
+ return true;
+ }
+
+ return IsCrossFileMessage(field);
+}
+
} // anonymous namespace
// ===================================================================
MessageGenerator::MessageGenerator(const Descriptor* descriptor,
- const Options& options)
+ int index_in_file_messages,
+ const Options& options,
+ SCCAnalyzer* scc_analyzer)
: descriptor_(descriptor),
+ index_in_file_messages_(index_in_file_messages),
classname_(ClassName(descriptor, false)),
options_(options),
field_generators_(descriptor, options),
- nested_generators_(new google::protobuf::scoped_ptr<
- MessageGenerator>[descriptor->nested_type_count()]),
+ max_has_bit_index_(0),
enum_generators_(
new google::protobuf::scoped_ptr<EnumGenerator>[descriptor->enum_type_count()]),
extension_generators_(new google::protobuf::scoped_ptr<
- ExtensionGenerator>[descriptor->extension_count()]),
- use_dependent_base_(false) {
-
+ ExtensionGenerator>[descriptor->extension_count()]),
+ use_dependent_base_(false),
+ num_weak_fields_(0),
+ message_layout_helper_(new PaddingOptimizer()),
+ scc_analyzer_(scc_analyzer) {
// Compute optimized field order to be used for layout and initialization
// purposes.
for (int i = 0; i < descriptor_->field_count(); i++) {
- if (!descriptor_->field(i)->containing_oneof()) {
- optimized_order_.push_back(descriptor_->field(i));
+ const FieldDescriptor* field = descriptor_->field(i);
+ if (field->options().weak()) {
+ num_weak_fields_++;
+ } else if (!field->containing_oneof()) {
+ optimized_order_.push_back(field);
}
}
- OptimizePadding(&optimized_order_, options_);
+
+ message_layout_helper_->OptimizeLayout(&optimized_order_, options_);
if (HasFieldPresence(descriptor_->file())) {
- int has_bit_index = 0;
+ // We use -1 as a sentinel.
has_bit_indices_.resize(descriptor_->field_count(), -1);
for (int i = 0; i < optimized_order_.size(); i++) {
const FieldDescriptor* field = optimized_order_[i];
@@ -532,25 +370,8 @@ MessageGenerator::MessageGenerator(const Descriptor* descriptor,
continue;
}
- has_bit_indices_[field->index()] = has_bit_index;
- has_bit_index++;
+ has_bit_indices_[field->index()] = max_has_bit_index_++;
}
-
- // Assign fields that do not use has bits to be at the end. This can be
- // removed once we shrink the has bits we assign.
- //
- // TODO(ckennelly): Shrink the has bits for these fields.
- for (int i = 0; i < descriptor_->field_count(); i++) {
- const FieldDescriptor* field = descriptor_->field(i);
- if (has_bit_indices_[field->index()] < 0) {
- has_bit_indices_[field->index()] = has_bit_index++;
- }
- }
- }
-
- for (int i = 0; i < descriptor->nested_type_count(); i++) {
- nested_generators_[i].reset(
- new MessageGenerator(descriptor->nested_type(i), options));
}
for (int i = 0; i < descriptor->enum_type_count(); i++) {
@@ -576,14 +397,18 @@ MessageGenerator::MessageGenerator(const Descriptor* descriptor,
// Always make oneofs dependent.
use_dependent_base_ = true;
}
+
+ table_driven_ = TableDrivenParsingEnabled(descriptor_, options_);
+
+ scc_name_ =
+ ClassName(scc_analyzer_->GetSCC(descriptor_)->GetRepresentative(), false);
}
MessageGenerator::~MessageGenerator() {}
size_t MessageGenerator::HasBitsSize() const {
- // TODO(jieluo) - Optimize _has_bits_ for repeated and oneof fields.
- size_t sizeof_has_bits = (descriptor_->field_count() + 31) / 32 * 4;
- if (descriptor_->field_count() == 0) {
+ size_t sizeof_has_bits = (max_has_bit_index_ + 31) / 32 * 4;
+ if (sizeof_has_bits == 0) {
// Zero-size arrays aren't technically allowed, and MSVC in particular
// doesn't like them. We still need to declare these arrays to make
// other code compile. Since this is an uncommon case, we'll just declare
@@ -594,13 +419,6 @@ size_t MessageGenerator::HasBitsSize() const {
return sizeof_has_bits;
}
-void MessageGenerator::Flatten(std::vector<MessageGenerator*>* list) {
- for (int i = 0; i < descriptor_->nested_type_count(); i++) {
- nested_generators_[i]->Flatten(list);
- }
- list->push_back(this);
-}
-
void MessageGenerator::AddGenerators(
std::vector<EnumGenerator*>* enum_generators,
std::vector<ExtensionGenerator*>* extension_generators) {
@@ -614,7 +432,6 @@ void MessageGenerator::AddGenerators(
void MessageGenerator::FillMessageForwardDeclarations(
std::map<string, const Descriptor*>* class_names) {
- if (IsMapEntryMessage(descriptor_)) return;
(*class_names)[classname_] = descriptor_;
}
@@ -628,12 +445,6 @@ GenerateDependentFieldAccessorDeclarations(io::Printer* printer) {
std::map<string, string> vars;
SetCommonFieldVariables(field, &vars, options_);
- if (use_dependent_base_ && IsFieldDependent(field)) {
- // If the message is dependent, the inline clear_*() method will need
- // to delete the message type, so it must be in the dependent base
- // class. (See also GenerateFieldAccessorDeclarations.)
- printer->Print(vars, "$deprecated_attr$void clear_$name$();\n");
- }
// Generate type-specific accessor declarations.
field_generators_.get(field).GenerateDependentAccessorDeclarations(printer);
printer->Print("\n");
@@ -642,8 +453,28 @@ GenerateDependentFieldAccessorDeclarations(io::Printer* printer) {
void MessageGenerator::
GenerateFieldAccessorDeclarations(io::Printer* printer) {
+ // optimized_fields_ does not contain fields where
+ // field->containing_oneof() != NULL
+ // so we need to iterate over those as well.
+ //
+ // We place the non-oneof fields in optimized_order_, as that controls the
+ // order of the _has_bits_ entries and we want GDB's pretty printers to be
+ // able to infer these indices from the k[FIELDNAME]FieldNumber order.
+ std::vector<const FieldDescriptor*> ordered_fields;
+ ordered_fields.reserve(descriptor_->field_count());
+
+ ordered_fields.insert(
+ ordered_fields.begin(), optimized_order_.begin(), optimized_order_.end());
for (int i = 0; i < descriptor_->field_count(); i++) {
const FieldDescriptor* field = descriptor_->field(i);
+ if (field->containing_oneof() == NULL && !field->options().weak()) {
+ continue;
+ }
+ ordered_fields.push_back(field);
+ }
+
+ for (int i = 0; i < ordered_fields.size(); i++) {
+ const FieldDescriptor* field = ordered_fields[i];
PrintFieldComment(printer, field);
@@ -667,24 +498,25 @@ GenerateFieldAccessorDeclarations(io::Printer* printer) {
}
if (field->is_repeated()) {
- printer->Print(vars, "$deprecated_attr$int $name$_size() const;\n");
+ printer->Print(vars, "$deprecated_attr$int ${$$name$_size$}$() const;\n");
+ printer->Annotate("{", "}", field);
} else if (HasHasMethod(field)) {
- printer->Print(vars, "$deprecated_attr$bool has_$name$() const;\n");
+ printer->Print(vars, "$deprecated_attr$bool ${$has_$name$$}$() const;\n");
+ printer->Annotate("{", "}", field);
} else if (HasPrivateHasMethod(field)) {
printer->Print(vars,
- "private:\n"
- "bool has_$name$() const;\n"
- "public:\n");
+ "private:\n"
+ "bool ${$has_$name$$}$() const;\n"
+ "public:\n");
+ printer->Annotate("{", "}", field);
}
- if (!dependent_field) {
- // If this field is dependent, then its clear_() method is in the
- // depenent base class. (See also GenerateDependentAccessorDeclarations.)
- printer->Print(vars, "$deprecated_attr$void clear_$name$();\n");
- }
+ printer->Print(vars, "$deprecated_attr$void ${$clear_$name$$}$();\n");
+ printer->Annotate("{", "}", field);
printer->Print(vars,
"$deprecated_attr$static const int $constant_name$ = "
"$number$;\n");
+ printer->Annotate("constant_name", field);
// Generate type-specific accessor declarations.
field_generators_.get(field).GenerateAccessorDeclarations(printer);
@@ -722,36 +554,6 @@ GenerateDependentFieldAccessorDefinitions(io::Printer* printer) {
if (field->options().weak()) continue;
PrintFieldComment(printer, field);
-
- // These functions are not really dependent: they are part of the
- // (non-dependent) derived class. However, they need to live outside
- // any #ifdef guards, so we treat them as if they were dependent.
- //
- // See the comment in FileGenerator::GenerateInlineFunctionDefinitions
- // for a more complete explanation.
- if (use_dependent_base_ && IsFieldDependent(field)) {
- std::map<string, string> vars;
- SetCommonFieldVariables(field, &vars, options_);
- vars["inline"] = "inline ";
- if (field->containing_oneof()) {
- vars["field_name"] = UnderscoresToCamelCase(field->name(), true);
- vars["oneof_name"] = field->containing_oneof()->name();
- vars["oneof_index"] = SimpleItoa(field->containing_oneof()->index());
- GenerateOneofMemberHasBits(field, vars, printer);
- } else if (!field->is_repeated()) {
- // There will be no header guard, so this always has to be inline.
- GenerateSingularFieldHasBits(field, vars, printer);
- }
- // vars needed for clear_(), which is in the dependent base:
- // (See also GenerateDependentFieldAccessorDeclarations.)
- vars["tmpl"] = "template<class T>\n";
- vars["dependent_classname"] =
- DependentBaseClassTemplateName(descriptor_) + "<T>";
- vars["this_message"] = DependentBaseDownCast();
- vars["this_const_message"] = DependentBaseConstDownCast();
- GenerateFieldClear(field, vars, printer);
- }
-
// Generate type-specific accessors.
field_generators_.get(field)
.GenerateDependentInlineAccessorDefinitions(printer);
@@ -762,13 +564,21 @@ GenerateDependentFieldAccessorDefinitions(io::Printer* printer) {
// Generate has_$name$() and clear_has_$name$() functions for oneofs
// Similar to other has-bits, these must always be in the header if we
// are using a dependent base class.
- GenerateOneofHasBits(printer, true /* is_inline */);
+ GenerateOneofHasBits(printer);
}
void MessageGenerator::
GenerateSingularFieldHasBits(const FieldDescriptor* field,
std::map<string, string> vars,
io::Printer* printer) {
+ if (field->options().weak()) {
+ printer->Print(
+ vars,
+ "inline bool $classname$::has_$name$() const {\n"
+ " return _weak_field_map_.Has($number$);\n"
+ "}\n");
+ return;
+ }
if (HasFieldPresence(descriptor_->file())) {
// N.B.: without field presence, we do not use has-bits or generate
// has_$name$() methods.
@@ -779,16 +589,13 @@ GenerateSingularFieldHasBits(const FieldDescriptor* field,
vars["has_mask"] = StrCat(strings::Hex(1u << (has_bit_index % 32),
strings::ZERO_PAD_8));
printer->Print(vars,
- "$inline$"
- "bool $classname$::has_$name$() const {\n"
+ "inline bool $classname$::has_$name$() const {\n"
" return (_has_bits_[$has_array_index$] & 0x$has_mask$u) != 0;\n"
"}\n"
- "$inline$"
- "void $classname$::set_has_$name$() {\n"
+ "inline void $classname$::set_has_$name$() {\n"
" _has_bits_[$has_array_index$] |= 0x$has_mask$u;\n"
"}\n"
- "$inline$"
- "void $classname$::clear_has_$name$() {\n"
+ "inline void $classname$::clear_has_$name$() {\n"
" _has_bits_[$has_array_index$] &= ~0x$has_mask$u;\n"
"}\n");
} else {
@@ -797,15 +604,13 @@ GenerateSingularFieldHasBits(const FieldDescriptor* field,
bool is_lazy = false;
if (is_lazy) {
printer->Print(vars,
- "$inline$"
- "bool $classname$::has_$name$() const {\n"
+ "inline bool $classname$::has_$name$() const {\n"
" return !$name$_.IsCleared();\n"
"}\n");
} else {
printer->Print(
vars,
- "$inline$"
- "bool $classname$::has_$name$() const {\n"
+ "inline bool $classname$::has_$name$() const {\n"
" return this != internal_default_instance() && $name$_ != NULL;\n"
"}\n");
}
@@ -814,7 +619,7 @@ GenerateSingularFieldHasBits(const FieldDescriptor* field,
}
void MessageGenerator::
-GenerateOneofHasBits(io::Printer* printer, bool is_inline) {
+GenerateOneofHasBits(io::Printer* printer) {
for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
std::map<string, string> vars;
vars["oneof_name"] = descriptor_->oneof_decl(i)->name();
@@ -822,15 +627,12 @@ GenerateOneofHasBits(io::Printer* printer, bool is_inline) {
vars["cap_oneof_name"] =
ToUpper(descriptor_->oneof_decl(i)->name());
vars["classname"] = classname_;
- vars["inline"] = (is_inline ? "inline " : "");
printer->Print(
vars,
- "$inline$"
- "bool $classname$::has_$oneof_name$() const {\n"
+ "inline bool $classname$::has_$oneof_name$() const {\n"
" return $oneof_name$_case() != $cap_oneof_name$_NOT_SET;\n"
"}\n"
- "$inline$"
- "void $classname$::clear_has_$oneof_name$() {\n"
+ "inline void $classname$::clear_has_$oneof_name$() {\n"
" _oneof_case_[$oneof_index$] = $cap_oneof_name$_NOT_SET;\n"
"}\n");
}
@@ -847,13 +649,11 @@ GenerateOneofMemberHasBits(const FieldDescriptor* field,
// method, so that generated code is slightly cleaner (vs. comparing
// _oneof_case_[index] against a constant everywhere).
printer->Print(vars,
- "$inline$"
- "bool $classname$::has_$name$() const {\n"
+ "inline bool $classname$::has_$name$() const {\n"
" return $oneof_name$_case() == k$field_name$;\n"
"}\n");
printer->Print(vars,
- "$inline$"
- "void $classname$::set_has_$name$() {\n"
+ "inline void $classname$::set_has_$name$() {\n"
" _oneof_case_[$oneof_index$] = k$field_name$;\n"
"}\n");
}
@@ -861,14 +661,14 @@ GenerateOneofMemberHasBits(const FieldDescriptor* field,
void MessageGenerator::
GenerateFieldClear(const FieldDescriptor* field,
const std::map<string, string>& vars,
+ bool is_inline,
io::Printer* printer) {
- // Generate clear_$name$() (See GenerateFieldAccessorDeclarations and
- // GenerateDependentFieldAccessorDeclarations, $dependent_classname$ is
- // set by the Generate*Definitions functions.)
+ // Generate clear_$name$().
+ if (is_inline) {
+ printer->Print("inline ");
+ }
printer->Print(vars,
- "$tmpl$"
- "$inline$"
- "void $dependent_classname$::clear_$name$() {\n");
+ "void $classname$::clear_$name$() {\n");
printer->Indent();
@@ -876,21 +676,20 @@ GenerateFieldClear(const FieldDescriptor* field,
// Clear this field only if it is the active field in this oneof,
// otherwise ignore
printer->Print(vars,
- "if ($this_message$has_$name$()) {\n");
+ "if (has_$name$()) {\n");
printer->Indent();
field_generators_.get(field)
.GenerateClearingCode(printer);
printer->Print(vars,
- "$this_message$clear_has_$oneof_name$();\n");
+ "clear_has_$oneof_name$();\n");
printer->Outdent();
printer->Print("}\n");
} else {
field_generators_.get(field)
.GenerateClearingCode(printer);
if (HasFieldPresence(descriptor_->file())) {
- if (!field->is_repeated()) {
- printer->Print(vars,
- "$this_message$clear_has_$name$();\n");
+ if (!field->is_repeated() && !field->options().weak()) {
+ printer->Print(vars, "clear_has_$name$();\n");
}
}
}
@@ -900,7 +699,7 @@ GenerateFieldClear(const FieldDescriptor* field,
}
void MessageGenerator::
-GenerateFieldAccessorDefinitions(io::Printer* printer, bool is_inline) {
+GenerateFieldAccessorDefinitions(io::Printer* printer) {
printer->Print("// $classname$\n\n", "classname", classname_);
for (int i = 0; i < descriptor_->field_count(); i++) {
@@ -910,7 +709,6 @@ GenerateFieldAccessorDefinitions(io::Printer* printer, bool is_inline) {
std::map<string, string> vars;
SetCommonFieldVariables(field, &vars, options_);
- vars["inline"] = is_inline ? "inline " : "";
if (use_dependent_base_ && IsFieldDependent(field)) {
vars["tmpl"] = "template<class T>\n";
vars["dependent_classname"] =
@@ -927,31 +725,25 @@ GenerateFieldAccessorDefinitions(io::Printer* printer, bool is_inline) {
// Generate has_$name$() or $name$_size().
if (field->is_repeated()) {
printer->Print(vars,
- "$inline$"
- "int $classname$::$name$_size() const {\n"
+ "inline int $classname$::$name$_size() const {\n"
" return $name$_.size();\n"
"}\n");
} else if (field->containing_oneof()) {
vars["field_name"] = UnderscoresToCamelCase(field->name(), true);
vars["oneof_name"] = field->containing_oneof()->name();
vars["oneof_index"] = SimpleItoa(field->containing_oneof()->index());
- if (!use_dependent_base_ || !IsFieldDependent(field)) {
- GenerateOneofMemberHasBits(field, vars, printer);
- }
+ GenerateOneofMemberHasBits(field, vars, printer);
} else {
// Singular field.
- if (!use_dependent_base_ || !IsFieldDependent(field)) {
- GenerateSingularFieldHasBits(field, vars, printer);
- }
+ GenerateSingularFieldHasBits(field, vars, printer);
}
- if (!use_dependent_base_ || !IsFieldDependent(field)) {
- GenerateFieldClear(field, vars, printer);
+ if (!IsCrossFileMaybeMap(field)) {
+ GenerateFieldClear(field, vars, true, printer);
}
// Generate type-specific accessors.
- field_generators_.get(field).GenerateInlineAccessorDefinitions(printer,
- is_inline);
+ field_generators_.get(field).GenerateInlineAccessorDefinitions(printer);
printer->Print("\n");
}
@@ -960,7 +752,7 @@ GenerateFieldAccessorDefinitions(io::Printer* printer, bool is_inline) {
// Generate has_$name$() and clear_has_$name$() functions for oneofs
// If we aren't using a dependent base, they can be with the other functions
// that are #ifdef-guarded.
- GenerateOneofHasBits(printer, is_inline);
+ GenerateOneofHasBits(printer);
}
}
@@ -996,7 +788,42 @@ GenerateDependentBaseClassDefinition(io::Printer* printer) {
void MessageGenerator::
GenerateClassDefinition(io::Printer* printer) {
- if (IsMapEntryMessage(descriptor_)) return;
+ if (IsMapEntryMessage(descriptor_)) {
+ std::map<string, string> vars;
+ vars["classname"] = classname_;
+ CollectMapInfo(descriptor_, &vars);
+ vars["lite"] =
+ HasDescriptorMethods(descriptor_->file(), options_) ? "" : "Lite";
+ printer->Print(
+ vars,
+ "class $classname$ : public "
+ "::google::protobuf::internal::MapEntry$lite$<$classname$, \n"
+ " $key_cpp$, $val_cpp$,\n"
+ " $key_wire_type$,\n"
+ " $val_wire_type$,\n"
+ " $default_enum_value$ > {\n"
+ "public:\n"
+ " typedef ::google::protobuf::internal::MapEntry$lite$<$classname$, \n"
+ " $key_cpp$, $val_cpp$,\n"
+ " $key_wire_type$,\n"
+ " $val_wire_type$,\n"
+ " $default_enum_value$ > SuperType;\n"
+ " $classname$();\n"
+ " $classname$(::google::protobuf::Arena* arena);\n"
+ " void MergeFrom(const $classname$& other);\n"
+ " static const $classname$* internal_default_instance() { return "
+ "reinterpret_cast<const "
+ "$classname$*>(&_$classname$_default_instance_); }\n");
+ if (HasDescriptorMethods(descriptor_->file(), options_)) {
+ printer->Print(
+ " void MergeFrom(const ::google::protobuf::Message& other) PROTOBUF_FINAL;\n"
+ " ::google::protobuf::Metadata GetMetadata() const;\n"
+ "};\n");
+ } else {
+ printer->Print("};\n");
+ }
+ return;
+ }
if (use_dependent_base_) {
GenerateDependentBaseClassDefinition(printer);
printer->Print("\n");
@@ -1029,32 +856,54 @@ GenerateClassDefinition(io::Printer* printer) {
printer->Print(" public:\n");
printer->Indent();
+ printer->Print(
+ vars,
+ "$classname$();\n"
+ "virtual ~$classname$();\n"
+ "\n"
+ "$classname$(const $classname$& from);\n"
+ "\n"
+ "inline $classname$& operator=(const $classname$& from) {\n"
+ " CopyFrom(from);\n"
+ " return *this;\n"
+ "}\n");
+
+ if (options_.table_driven_serialization) {
+ printer->Print(
+ "private:\n"
+ "const void* InternalGetTable() const;\n"
+ "public:\n"
+ "\n");
+ }
+
+ // Generate move constructor and move assignment operator.
printer->Print(vars,
- "$classname$();\n"
- "virtual ~$classname$();\n"
- "\n"
- "$classname$(const $classname$& from);\n"
+ "#if LANG_CXX11\n"
+ "$classname$($classname$&& from) noexcept\n"
+ " : $classname$() {\n"
+ " *this = ::std::move(from);\n"
+ "}\n"
"\n"
- "inline $classname$& operator=(const $classname$& from) {\n"
- " CopyFrom(from);\n"
+ "inline $classname$& operator=($classname$&& from) noexcept {\n"
+ " if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {\n"
+ " if (this != &from) InternalSwap(&from);\n"
+ " } else {\n"
+ " CopyFrom(from);\n"
+ " }\n"
" return *this;\n"
"}\n"
- "\n");
+ "#endif\n");
- if (PreserveUnknownFields(descriptor_)) {
- string type = UseUnknownFieldSet(descriptor_->file(), options_)
- ? "::google::protobuf::UnknownFieldSet"
- : "::std::string";
- printer->Print(
- "inline const $type$& unknown_fields() const {\n"
- " return _internal_metadata_.unknown_fields();\n"
- "}\n"
- "\n"
- "inline $type$* mutable_unknown_fields() {\n"
- " return _internal_metadata_.mutable_unknown_fields();\n"
- "}\n"
- "\n",
- "type", type );
+ SetUnknkownFieldsVariable(descriptor_, options_, &vars);
+ if (PublicUnknownFieldsAccessors(descriptor_)) {
+ printer->Print(vars,
+ "inline const $unknown_fields_type$& unknown_fields() const {\n"
+ " return $unknown_fields$;\n"
+ "}\n"
+ "inline $unknown_fields_type$* mutable_unknown_fields() {\n"
+ " return $mutable_unknown_fields$;\n"
+ "}\n"
+ "\n");
}
// N.B.: We exclude GetArena() when arena support is disabled, falling back on
@@ -1111,15 +960,18 @@ GenerateClassDefinition(io::Printer* printer) {
}
// TODO(gerbens) make this private, while still granting other protos access.
+ vars["message_index"] = SimpleItoa(index_in_file_messages_);
printer->Print(
vars,
+ "static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY\n"
"static inline const $classname$* internal_default_instance() {\n"
" return reinterpret_cast<const $classname$*>(\n"
" &_$classname$_default_instance_);\n"
"}\n"
+ "static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =\n"
+ " $message_index$;\n"
"\n");
-
if (SupportsArenas(descriptor_)) {
printer->Print(vars,
"void UnsafeArenaSwap($classname$* other);\n");
@@ -1143,6 +995,9 @@ GenerateClassDefinition(io::Printer* printer) {
printer->Print(vars,
"void Swap($classname$* other);\n"
+ "friend void swap($classname$& a, $classname$& b) {\n"
+ " a.Swap(&b);\n"
+ "}\n"
"\n"
"// implements Message ----------------------------------------------\n"
"\n"
@@ -1179,9 +1034,14 @@ GenerateClassDefinition(io::Printer* printer) {
"\n"
"size_t ByteSizeLong() const PROTOBUF_FINAL;\n"
"bool MergePartialFromCodedStream(\n"
- " ::google::protobuf::io::CodedInputStream* input)$merge_partial_final$;\n"
- "void SerializeWithCachedSizes(\n"
- " ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;\n");
+ " ::google::protobuf::io::CodedInputStream* input)$merge_partial_final$;\n");
+ if (!options_.table_driven_serialization ||
+ descriptor_->options().message_set_wire_format()) {
+ printer->Print(
+ "void SerializeWithCachedSizes(\n"
+ " ::google::protobuf::io::CodedOutputStream* output) const "
+ "PROTOBUF_FINAL;\n");
+ }
// DiscardUnknownFields() is implemented in message.cc using reflections. We
// need to implement this function in generated code for messages.
if (!UseUnknownFieldSet(descriptor_->file(), options_)) {
@@ -1192,11 +1052,7 @@ GenerateClassDefinition(io::Printer* printer) {
if (HasFastArraySerialization(descriptor_->file(), options_)) {
printer->Print(
"::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(\n"
- " bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;\n"
- "::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)\n"
- " const PROTOBUF_FINAL {\n"
- " return InternalSerializeWithCachedSizesToArray(false, output);\n"
- "}\n");
+ " bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;\n");
}
}
@@ -1211,6 +1067,9 @@ GenerateClassDefinition(io::Printer* printer) {
"final", use_final);
if (SupportsArenas(descriptor_)) {
printer->Print(
+ // TODO(gerbens) Make this private! Currently people are deriving from
+ // protos to give access to this constructor, breaking the invariants
+ // we rely on.
"protected:\n"
"explicit $classname$(::google::protobuf::Arena* arena);\n"
"private:\n"
@@ -1264,6 +1123,8 @@ GenerateClassDefinition(io::Printer* printer) {
printer->Print("typedef $nested_full_name$ $nested_name$;\n",
"nested_name", nested_type->name(),
"nested_full_name", ClassName(nested_type, false));
+ printer->Annotate("nested_full_name", nested_type);
+ printer->Annotate("nested_name", nested_type);
}
}
@@ -1302,7 +1163,8 @@ GenerateClassDefinition(io::Printer* printer) {
for (int i = 0; i < descriptor_->field_count(); i++) {
- if (!descriptor_->field(i)->is_repeated()) {
+ if (!descriptor_->field(i)->is_repeated() &&
+ !descriptor_->field(i)->options().weak()) {
// set_has_***() generated in all proto1/2 code and in oneofs (only) for
// messages without true field presence.
if (HasFieldPresence(descriptor_->file()) ||
@@ -1375,7 +1237,7 @@ GenerateClassDefinition(io::Printer* printer) {
if (SupportsArenas(descriptor_)) {
printer->Print(
- "friend class ::google::protobuf::Arena;\n"
+ "template <typename T> friend class ::google::protobuf::Arena::InternalHelper;\n"
"typedef void InternalArenaConstructable_;\n"
"typedef void DestructorSkippable_;\n");
}
@@ -1441,31 +1303,25 @@ GenerateClassDefinition(io::Printer* printer) {
"\n");
}
+ if (num_weak_fields_) {
+ printer->Print(
+ "::google::protobuf::internal::WeakFieldMap _weak_field_map_;\n");
+ }
// Generate _any_metadata_ for the Any type.
if (IsAnyMessage(descriptor_)) {
printer->Print(vars,
"::google::protobuf::internal::AnyMetadata _any_metadata_;\n");
}
- // Declare AddDescriptors(), BuildDescriptors(), and ShutdownFile() as
- // friends so that they can access private static variables like
- // default_instance_ and reflection_.
- printer->Print("friend void $dllexport_decl$ $initdefaultsname$_impl();\n",
- // Vars.
- "dllexport_decl", options_.dllexport_decl, "initdefaultsname",
- GlobalInitDefaultsName(descriptor_->file()->name()));
- printer->Print("friend void $dllexport_decl$ $adddescriptorsname$_impl();\n",
- // Vars.
- "dllexport_decl", options_.dllexport_decl,
- "adddescriptorsname",
- GlobalAddDescriptorsName(descriptor_->file()->name()));
-
+ // The TableStruct struct needs access to the private parts, in order to
+ // construct the offsets of all members.
+ // TODO(gerbens) Remove the friend for InitDefaults.
printer->Print(
- "friend const ::google::protobuf::uint32* $offsetfunname$();\n"
- "friend void $shutdownfilename$();\n"
- "\n",
- "offsetfunname", GlobalOffsetTableName(descriptor_->file()->name()),
- "shutdownfilename", GlobalShutdownFileName(descriptor_->file()->name()));
+ "friend struct ::$file_namespace$::TableStruct;\n"
+ "friend void ::$file_namespace$::InitDefaults$scc_name$Impl();\n",
+ // Vars.
+ "scc_name", scc_name_, "file_namespace",
+ FileLevelNamespace(descriptor_));
printer->Outdent();
printer->Print("};");
@@ -1485,9 +1341,9 @@ GenerateDependentInlineMethods(io::Printer* printer) {
}
void MessageGenerator::
-GenerateInlineMethods(io::Printer* printer, bool is_inline) {
+GenerateInlineMethods(io::Printer* printer) {
if (IsMapEntryMessage(descriptor_)) return;
- GenerateFieldAccessorDefinitions(printer, is_inline);
+ GenerateFieldAccessorDefinitions(printer);
// Generate oneof_case() functions.
for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
@@ -1497,11 +1353,9 @@ GenerateInlineMethods(io::Printer* printer, bool is_inline) {
descriptor_->oneof_decl(i)->name(), true);
vars["oneof_name"] = descriptor_->oneof_decl(i)->name();
vars["oneof_index"] = SimpleItoa(descriptor_->oneof_decl(i)->index());
- vars["inline"] = is_inline ? "inline " : "";
printer->Print(
vars,
- "$inline$"
- "$class_name$::$camel_oneof_name$Case $class_name$::"
+ "inline $class_name$::$camel_oneof_name$Case $class_name$::"
"$oneof_name$_case() const {\n"
" return $class_name$::$camel_oneof_name$Case("
"_oneof_case_[$oneof_index$]);\n"
@@ -1510,15 +1364,13 @@ GenerateInlineMethods(io::Printer* printer, bool is_inline) {
}
void MessageGenerator::
-GenerateDescriptorDeclarations(io::Printer* printer) {
- // Generate oneof default instance for reflection usage.
- if (descriptor_->oneof_decl_count() > 0) {
- printer->Print("struct $name$OneofInstance {\n",
- "name", classname_);
+GenerateExtraDefaultFields(io::Printer* printer) {
+ // Generate oneof default instance and weak field instances for reflection
+ // usage.
+ if (descriptor_->oneof_decl_count() > 0 || num_weak_fields_ > 0) {
for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) {
const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j);
- printer->Print(" ");
if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE ||
(field->cpp_type() == FieldDescriptor::CPPTYPE_STRING &&
EffectiveStringCType(field) != FieldOptions::STRING)) {
@@ -1527,84 +1379,344 @@ GenerateDescriptorDeclarations(io::Printer* printer) {
field_generators_.get(field).GeneratePrivateMembers(printer);
}
}
+ for (int i = 0; i < descriptor_->field_count(); i++) {
+ const FieldDescriptor* field = descriptor_->field(i);
+ if (field->options().weak()) {
+ printer->Print(
+ " const ::google::protobuf::Message* $name$_;\n", "name", FieldName(field));
+ }
+ }
+ }
+}
+
+bool MessageGenerator::GenerateParseTable(io::Printer* printer, size_t offset,
+ size_t aux_offset) {
+ if (!table_driven_) {
+ printer->Print("{ NULL, NULL, 0, -1, -1, -1, -1, NULL, false },\n");
+ return false;
+ }
+
+ std::map<string, string> vars;
+
+ vars["classname"] = ClassName(descriptor_);
+ vars["classtype"] = QualifiedClassName(descriptor_);
+ vars["offset"] = SimpleItoa(offset);
+ vars["aux_offset"] = SimpleItoa(aux_offset);
+
+ int max_field_number = 0;
+ for (int i = 0; i < descriptor_->field_count(); i++) {
+ const FieldDescriptor* field = descriptor_->field(i);
+ if (max_field_number < field->number()) {
+ max_field_number = field->number();
+ }
+ }
+
+ vars["max_field_number"] = SimpleItoa(max_field_number);
+
+ printer->Print("{\n");
+ printer->Indent();
+
+ printer->Print(vars,
+ "TableStruct::entries + $offset$,\n"
+ "TableStruct::aux + $aux_offset$,\n"
+ "$max_field_number$,\n");
+
+ if (!HasFieldPresence(descriptor_->file())) {
+ // If we don't have field presence, then _has_bits_ does not exist.
+ printer->Print(vars, "-1,\n");
+ } else {
+ printer->Print(vars,
+ "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(\n"
+ " $classtype$, _has_bits_),\n");
+ }
+
+ if (descriptor_->oneof_decl_count() > 0) {
+ printer->Print(vars,
+ "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(\n"
+ " $classtype$, _oneof_case_),\n");
+ } else {
+ printer->Print("-1, // no _oneof_case_\n");
+ }
+
+ if (descriptor_->extension_range_count() > 0) {
+ printer->Print(vars,
+ "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classtype$, "
+ "_extensions_),\n");
+ } else {
+ printer->Print("-1, // no _extensions_\n");
+ }
+
+ // TODO(ckennelly): Consolidate this with the calculation for
+ // AuxillaryParseTableField.
+ vars["ns"] = Namespace(descriptor_);
- printer->Print("} $name$_default_oneof_instance_;\n", "name", classname_);
+ printer->Print(vars,
+ "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(\n"
+ " $classtype$, _internal_metadata_),\n"
+ "&$ns$::_$classname$_default_instance_,\n");
+
+ if (UseUnknownFieldSet(descriptor_->file(), options_)) {
+ printer->Print(vars, "true,\n");
+ } else {
+ printer->Print(vars, "false,\n");
}
+
+ printer->Outdent();
+ printer->Print("},\n");
+ return true;
}
void MessageGenerator::GenerateSchema(io::Printer* printer, int offset,
int has_offset) {
- if (IsMapEntryMessage(descriptor_)) return;
-
std::map<string, string> vars;
- vars["classname"] = classname_;
+ vars["classname"] = QualifiedClassName(descriptor_);
vars["offset"] = SimpleItoa(offset);
- vars["has_bits_offsets"] = HasFieldPresence(descriptor_->file())
- ? SimpleItoa(offset + has_offset)
- : "-1";
+ vars["has_bits_offsets"] =
+ HasFieldPresence(descriptor_->file()) || IsMapEntryMessage(descriptor_)
+ ? SimpleItoa(offset + has_offset)
+ : "-1";
printer->Print(vars,
"{ $offset$, $has_bits_offsets$, sizeof($classname$)},\n");
}
-void MessageGenerator::
-GenerateTypeRegistrations(io::Printer* printer) {
- // Register this message type with the message factory.
+namespace {
+
+// TODO(gerbens) remove this after the next sync with GitHub code base.
+// Then the opensource testing has gained the functionality to compile
+// the CalcFieldNum given the symbols defined in generated-message-util.
+#ifdef OPENSOURCE_PROTOBUF_CPP_BOOTSTRAP
+// We need a clean version of CalcFieldNum that doesn't use new functionality
+// in the runtime, because this functionality is not yet in the opensource
+// runtime
+
+uint32 CalculateType(uint32 type, uint32 type_class) {
+ return (type - 1) + type_class * 20;
+}
+
+uint32 CalcFieldNum(const FieldDescriptor* field, const Options& options) {
+ bool is_a_map = IsMapEntryMessage(field->containing_type());
+ int type = field->type();
+ if (field->containing_oneof()) {
+ return CalculateType(type, 4);
+ }
+ if (field->is_packed()) {
+ return CalculateType(type, 3);
+ } else if (field->is_repeated()) {
+ return CalculateType(type, 2);
+ } else if (!HasFieldPresence(field->file()) &&
+ field->containing_oneof() == NULL && !is_a_map) {
+ return CalculateType(type, 1);
+ } else {
+ return CalculateType(type, 0);
+ }
+}
+
+#else
+// We need to calculate for each field what function the table driven code
+// should use to serialize it. This returns the index in a lookup table.
+uint32 CalcFieldNum(const FieldDescriptor* field, const Options& options) {
+ bool is_a_map = IsMapEntryMessage(field->containing_type());
+ int type = field->type();
+ if (field->containing_oneof()) {
+ return internal::FieldMetadata::CalculateType(
+ type, internal::FieldMetadata::kOneOf);
+ }
+ if (field->is_packed()) {
+ return internal::FieldMetadata::CalculateType(
+ type, internal::FieldMetadata::kPacked);
+ } else if (field->is_repeated()) {
+ return internal::FieldMetadata::CalculateType(
+ type, internal::FieldMetadata::kRepeated);
+ } else if (!HasFieldPresence(field->file()) &&
+ field->containing_oneof() == NULL && !is_a_map) {
+ return internal::FieldMetadata::CalculateType(
+ type, internal::FieldMetadata::kNoPresence);
+ } else {
+ return internal::FieldMetadata::CalculateType(
+ type, internal::FieldMetadata::kPresence);
+ }
+}
+#endif
+
+int FindMessageIndexInFile(const Descriptor* descriptor) {
+ std::vector<const Descriptor*> flatten =
+ FlattenMessagesInFile(descriptor->file());
+ return std::find(flatten.begin(), flatten.end(), descriptor) -
+ flatten.begin();
+}
+
+} // namespace
+
+int MessageGenerator::GenerateFieldMetadata(io::Printer* printer) {
+ if (!options_.table_driven_serialization) {
+ return 0;
+ }
+
+ string full_classname = QualifiedClassName(descriptor_);
+
+ std::vector<const FieldDescriptor*> sorted = SortFieldsByNumber(descriptor_);
if (IsMapEntryMessage(descriptor_)) {
- std::map<string, string> vars;
- CollectMapInfo(descriptor_, &vars);
- vars["classname"] = classname_;
+ for (int i = 0; i < 2; i++) {
+ const FieldDescriptor* field = sorted[i];
+ uint32 tag = internal::WireFormatLite::MakeTag(
+ field->number(), WireFormat::WireTypeForFieldType(field->type()));
- const FieldDescriptor* val = descriptor_->FindFieldByName("value");
- if (descriptor_->file()->syntax() == FileDescriptor::SYNTAX_PROTO2 &&
- val->type() == FieldDescriptor::TYPE_ENUM) {
- const EnumValueDescriptor* default_value = val->default_value_enum();
- vars["default_enum_value"] = Int32ToString(default_value->number());
- } else {
- vars["default_enum_value"] = "0";
+ std::map<string, string> vars;
+ vars["classname"] = QualifiedClassName(descriptor_);
+ vars["field_name"] = FieldName(field);
+ vars["tag"] = SimpleItoa(tag);
+ vars["hasbit"] = SimpleItoa(i);
+ vars["type"] = SimpleItoa(CalcFieldNum(field, options_));
+ vars["ptr"] = "NULL";
+ if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
+ GOOGLE_CHECK(!IsMapEntryMessage(field->message_type()));
+ {
+ vars["ptr"] =
+ "::" + FileLevelNamespace(field->message_type()) +
+ "::TableStruct::serialization_table + " +
+ SimpleItoa(FindMessageIndexInFile(field->message_type()));
+ }
+ }
+ printer->Print(vars,
+ "{GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET("
+ "::google::protobuf::internal::MapEntryHelper<$classname$::"
+ "SuperType>, $field_name$_), $tag$,"
+ "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET("
+ "::google::protobuf::internal::MapEntryHelper<$classname$::"
+ "SuperType>, _has_bits_) * 8 + $hasbit$, $type$, "
+ "$ptr$},\n");
+ }
+ return 2;
+ }
+ printer->Print(
+ "{GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, "
+ "_cached_size_), 0, 0, 0, NULL},\n",
+ "classname", full_classname);
+ std::vector<const Descriptor::ExtensionRange*> sorted_extensions;
+ for (int i = 0; i < descriptor_->extension_range_count(); ++i) {
+ sorted_extensions.push_back(descriptor_->extension_range(i));
+ }
+ std::sort(sorted_extensions.begin(), sorted_extensions.end(),
+ ExtensionRangeSorter());
+ for (int i = 0, extension_idx = 0; /* no range */; i++) {
+ for (; extension_idx < sorted_extensions.size() &&
+ (i == sorted.size() ||
+ sorted_extensions[extension_idx]->start < sorted[i]->number());
+ extension_idx++) {
+ const Descriptor::ExtensionRange* range =
+ sorted_extensions[extension_idx];
+ printer->Print(
+ "{GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, "
+ "_extensions_), $start$, $end$, "
+ "::google::protobuf::internal::FieldMetadata::kSpecial, "
+ "reinterpret_cast<const "
+ "void*>(::google::protobuf::internal::ExtensionSerializer)},\n",
+ "classname", full_classname, "start", SimpleItoa(range->start), "end",
+ SimpleItoa(range->end));
+ }
+ if (i == sorted.size()) break;
+ const FieldDescriptor* field = sorted[i];
+
+ uint32 tag = internal::WireFormatLite::MakeTag(
+ field->number(), WireFormat::WireTypeForFieldType(field->type()));
+ if (field->is_packed()) {
+ tag = internal::WireFormatLite::MakeTag(
+ field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED);
}
- vars["index_in_metadata"] = SimpleItoa(index_in_metadata_);
+ string classfieldname = FieldName(field);
+ if (field->containing_oneof()) {
+ classfieldname = field->containing_oneof()->name();
+ }
+ std::map<string, string> vars;
+ vars["classname"] = full_classname;
+ vars["field_name"] = classfieldname;
+ vars["tag"] = SimpleItoa(tag);
+ vars["ptr"] = "NULL";
+ if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
+ if (IsMapEntryMessage(field->message_type())) {
+ vars["idx"] = SimpleItoa(FindMessageIndexInFile(field->message_type()));
+ vars["fieldclassname"] = QualifiedClassName(field->message_type());
+ printer->Print(vars,
+ "{GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($"
+ "classname$, $field_name$_), $tag$, $idx$, "
+ "::google::protobuf::internal::FieldMetadata::kSpecial, "
+ "reinterpret_cast<const void*>(static_cast< "
+ "::google::protobuf::internal::SpecialSerializer>("
+ "::google::protobuf::internal::MapFieldSerializer< "
+ "::google::protobuf::internal::MapEntryToMapField<"
+ "$fieldclassname$>::MapFieldType, "
+ "TableStruct::serialization_table>))},\n");
+ continue;
+ } else {
+ vars["ptr"] =
+ "::" + FileLevelNamespace(field->message_type()) +
+ "::TableStruct::serialization_table + " +
+ SimpleItoa(FindMessageIndexInFile(field->message_type()));
+ }
+ }
+ vars["type"] = SimpleItoa(CalcFieldNum(field, options_));
- printer->Print(
- vars,
- "const ::google::protobuf::Descriptor* $classname$_descriptor = "
- "file_level_metadata[$index_in_metadata$].descriptor;\n"
- "::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(\n"
- " $classname$_descriptor,\n"
- " ::google::protobuf::internal::MapEntry<\n"
- " $key$,\n"
- " $val$,\n"
- " $key_wire_type$,\n"
- " $val_wire_type$,\n"
- " $default_enum_value$>::CreateDefaultInstance(\n"
- " $classname$_descriptor));\n");
+
+ if (field->options().weak()) {
+ // TODO(gerbens) merge weak fields into ranges
+ printer->Print(vars,
+ "{GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($"
+ "classname$, _weak_field_map_), $tag$, $tag$, "
+ "::google::protobuf::internal::FieldMetadata::kSpecial, "
+ "reinterpret_cast<const "
+ "void*>(::google::protobuf::internal::WeakFieldSerializer)},\n");
+ } else if (field->containing_oneof()) {
+ vars["oneofoffset"] =
+ SimpleItoa(sizeof(uint32) * field->containing_oneof()->index());
+ printer->Print(vars,
+ "{GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($"
+ "classname$, $field_name$_), $tag$, "
+ "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($"
+ "classname$, _oneof_case_) + $oneofoffset$, "
+ "$type$, $ptr$},\n");
+ } else if (HasFieldPresence(descriptor_->file()) &&
+ has_bit_indices_[field->index()] != -1) {
+ vars["hasbitsoffset"] = SimpleItoa(has_bit_indices_[field->index()]);
+ printer->Print(vars,
+ "{GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($"
+ "classname$, $field_name$_), $tag$, "
+ "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($"
+ "classname$, _has_bits_) * 8 + $hasbitsoffset$, $type$, "
+ "$ptr$},\n");
+ } else {
+ printer->Print(vars,
+ "{GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($"
+ "classname$, $field_name$_), $tag$, ~0u, $type$, "
+ "$ptr$},\n");
+ }
}
+ int num_field_metadata = 1 + sorted.size() + sorted_extensions.size();
+ num_field_metadata++;
+ string serializer = UseUnknownFieldSet(descriptor_->file(), options_)
+ ? "::google::protobuf::internal::UnknownFieldSetSerializer"
+ : "::google::protobuf::internal::UnknownFieldSerializerLite";
+ printer->Print(
+ "{GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, "
+ "_internal_metadata_), 0, ~0u, "
+ "::google::protobuf::internal::FieldMetadata::kSpecial, reinterpret_cast<const "
+ "void*>($serializer$)},\n",
+ "classname", full_classname, "serializer", serializer);
+ return num_field_metadata;
}
-void MessageGenerator::
-GenerateDefaultInstanceAllocator(io::Printer* printer) {
- if (IsMapEntryMessage(descriptor_)) return;
-
- // Construct the default instances of all fields, as they will be used
- // when creating the default instance of the entire message.
+void MessageGenerator::GenerateFieldDefaultInstances(io::Printer* printer) {
+ // Construct the default instances for all fields that need one.
for (int i = 0; i < descriptor_->field_count(); i++) {
field_generators_.get(descriptor_->field(i))
.GenerateDefaultInstanceAllocator(printer);
}
-
- // Construct the default instance. We can't call InitAsDefaultInstance() yet
- // because we need to make sure all default instances that this one might
- // depend on are constructed first.
- printer->Print("_$classname$_default_instance_.DefaultConstruct();\n",
- "classname", classname_);
}
void MessageGenerator::
GenerateDefaultInstanceInitializer(io::Printer* printer) {
- if (IsMapEntryMessage(descriptor_)) return;
-
// The default instance needs all of its embedded message pointers
// cross-linked to other default instances. We can't do this initialization
// in the constructor because some other default instances may not have been
@@ -1619,17 +1731,19 @@ GenerateDefaultInstanceInitializer(io::Printer* printer) {
(field->containing_oneof() == NULL ||
HasDescriptorMethods(descriptor_->file(), options_))) {
string name;
- if (field->containing_oneof()) {
- name = classname_ + "_default_oneof_instance_.";
+ if (field->containing_oneof() || field->options().weak()) {
+ name = "_" + classname_ + "_default_instance_.";
} else {
- name = "_" + classname_ + "_default_instance_.get_mutable()->";
+ name =
+ "_" + classname_ + "_default_instance_._instance.get_mutable()->";
}
name += FieldName(field);
printer->Print(
- "$name$_ = const_cast< $type$*>(\n"
+ "$ns$::$name$_ = const_cast< $type$*>(\n"
" $type$::internal_default_instance());\n",
// Vars.
- "name", name, "type", FieldMessageTypeName(field));
+ "name", name, "type", FieldMessageTypeName(field), "ns",
+ Namespace(descriptor_));
} else if (field->containing_oneof() &&
HasDescriptorMethods(descriptor_->file(), options_)) {
field_generators_.get(descriptor_->field(i))
@@ -1639,40 +1753,43 @@ GenerateDefaultInstanceInitializer(io::Printer* printer) {
}
void MessageGenerator::
-GenerateShutdownCode(io::Printer* printer) {
- if (IsMapEntryMessage(descriptor_)) return;
-
- printer->Print("_$classname$_default_instance_.Shutdown();\n", "classname",
- classname_);
-
- if (HasDescriptorMethods(descriptor_->file(), options_)) {
- printer->Print("delete file_level_metadata[$index$].reflection;\n", "index",
- SimpleItoa(index_in_metadata_));
- }
-
- // Handle default instances of fields.
- for (int i = 0; i < descriptor_->field_count(); i++) {
- field_generators_.get(descriptor_->field(i))
- .GenerateShutdownCode(printer);
- }
-}
-
-void MessageGenerator::
GenerateClassMethods(io::Printer* printer) {
- if (IsMapEntryMessage(descriptor_)) return;
-
- // mutable_unknown_fields wrapper function for LazyStringOutputStream
- // callback.
- if (PreserveUnknownFields(descriptor_) &&
- !UseUnknownFieldSet(descriptor_->file(), options_)) {
+ if (IsMapEntryMessage(descriptor_)) {
printer->Print(
- "static ::std::string* MutableUnknownFieldsFor$classname$(\n"
- " $classname$* ptr) {\n"
- " return ptr->mutable_unknown_fields();\n"
- "}\n"
- "\n",
+ "$classname$::$classname$() {}\n"
+ "$classname$::$classname$(::google::protobuf::Arena* arena) : "
+ "SuperType(arena) {}\n"
+ "void $classname$::MergeFrom(const $classname$& other) {\n"
+ " MergeFromInternal(other);\n"
+ "}\n",
"classname", classname_);
+ if (HasDescriptorMethods(descriptor_->file(), options_)) {
+ printer->Print(
+ "::google::protobuf::Metadata $classname$::GetMetadata() const {\n"
+ " ::$file_namespace$::protobuf_AssignDescriptorsOnce();\n"
+ " return ::$file_namespace$::file_level_metadata[$index$];\n"
+ "}\n"
+ "void $classname$::MergeFrom(\n"
+ " const ::google::protobuf::Message& other) {\n"
+ " ::google::protobuf::Message::MergeFrom(other);\n"
+ "}\n"
+ "\n",
+ "file_namespace", FileLevelNamespace(descriptor_),
+ "classname", classname_, "index",
+ SimpleItoa(index_in_file_messages_));
+ }
+ return;
}
+
+ // TODO(gerbens) Remove this function. With a little bit of cleanup and
+ // refactoring this is superfluous.
+ printer->Print("void $classname$::InitAsDefaultInstance() {\n", "classname",
+ classname_);
+ printer->Indent();
+ GenerateDefaultInstanceInitializer(printer);
+ printer->Outdent();
+ printer->Print("}\n");
+
if (IsAnyMessage(descriptor_)) {
printer->Print(
"void $classname$::PackFrom(const ::google::protobuf::Message& message) {\n"
@@ -1693,8 +1810,17 @@ GenerateClassMethods(io::Printer* printer) {
// Generate non-inline field definitions.
for (int i = 0; i < descriptor_->field_count(); i++) {
- field_generators_.get(descriptor_->field(i))
+ const FieldDescriptor* field = descriptor_->field(i);
+ field_generators_.get(field)
.GenerateNonInlineAccessorDefinitions(printer);
+ if (IsCrossFileMaybeMap(field)) {
+ std::map<string, string> vars;
+ SetCommonFieldVariables(field, &vars, options_);
+ if (field->containing_oneof()) {
+ SetCommonOneofFieldVariables(field, &vars);
+ }
+ GenerateFieldClear(field, vars, false, printer);
+ }
}
// Generate field number constants.
@@ -1749,14 +1875,26 @@ GenerateClassMethods(io::Printer* printer) {
GenerateSwap(printer);
printer->Print("\n");
+ if (options_.table_driven_serialization) {
+ printer->Print(
+ "const void* $classname$::InternalGetTable() const {\n"
+ " return ::$file_namespace$::TableStruct::serialization_table + "
+ "$index$;\n"
+ "}\n"
+ "\n",
+ "classname", classname_, "index", SimpleItoa(index_in_file_messages_),
+ "file_namespace", FileLevelNamespace(descriptor_));
+ }
if (HasDescriptorMethods(descriptor_->file(), options_)) {
printer->Print(
"::google::protobuf::Metadata $classname$::GetMetadata() const {\n"
- " protobuf_AssignDescriptorsOnce();\n"
- " return file_level_metadata[$index$];\n"
+ " $file_namespace$::protobuf_AssignDescriptorsOnce();\n"
+ " return ::"
+ "$file_namespace$::file_level_metadata[kIndexInFileMessages];\n"
"}\n"
"\n",
- "classname", classname_, "index", SimpleItoa(index_in_metadata_));
+ "classname", classname_, "file_namespace",
+ FileLevelNamespace(descriptor_));
} else {
printer->Print(
"::std::string $classname$::GetTypeName() const {\n"
@@ -1769,16 +1907,200 @@ GenerateClassMethods(io::Printer* printer) {
}
+size_t MessageGenerator::GenerateParseOffsets(io::Printer* printer) {
+ if (!table_driven_) {
+ return 0;
+ }
+
+ // Field "0" is special: We use it in our switch statement of processing
+ // types to handle the successful end tag case.
+ printer->Print("{0, 0, 0, ::google::protobuf::internal::kInvalidMask, 0, 0},\n");
+ int last_field_number = 1;
+
+ std::vector<const FieldDescriptor*> ordered_fields =
+ SortFieldsByNumber(descriptor_);
+
+ for (int i = 0; i < descriptor_->field_count(); i++) {
+ const FieldDescriptor* field = ordered_fields[i];
+ GOOGLE_CHECK_GE(field->number(), last_field_number);
+
+ for (; last_field_number < field->number(); last_field_number++) {
+ printer->Print(
+ "{ 0, 0, ::google::protobuf::internal::kInvalidMask,\n"
+ " ::google::protobuf::internal::kInvalidMask, 0, 0 },\n");
+ }
+ last_field_number++;
+
+ unsigned char normal_wiretype, packed_wiretype, processing_type;
+ normal_wiretype = WireFormat::WireTypeForFieldType(field->type());
+
+ if (field->is_packable()) {
+ packed_wiretype = WireFormatLite::WIRETYPE_LENGTH_DELIMITED;
+ } else {
+ packed_wiretype = internal::kNotPackedMask;
+ }
+
+ processing_type = static_cast<unsigned>(field->type());
+ if (field->type() == FieldDescriptor::TYPE_STRING) {
+ switch (EffectiveStringCType(field)) {
+ case FieldOptions::STRING:
+ default:
+ break;
+ }
+ } else if (field->type() == FieldDescriptor::TYPE_BYTES) {
+ switch (EffectiveStringCType(field)) {
+ case FieldOptions::STRING:
+ default:
+ break;
+ }
+ }
+
+ processing_type |= static_cast<unsigned>(
+ field->is_repeated() ? internal::kRepeatedMask : 0);
+ processing_type |= static_cast<unsigned>(
+ field->containing_oneof() ? internal::kOneofMask : 0);
+
+ if (field->is_map()) {
+ processing_type = internal::TYPE_MAP;
+ }
+
+ const unsigned char tag_size =
+ WireFormat::TagSize(field->number(), field->type());
+
+ std::map<string, string> vars;
+ vars["classname"] = QualifiedClassName(descriptor_);
+ if (field->containing_oneof() != NULL) {
+ vars["name"] = field->containing_oneof()->name();
+ vars["presence"] = SimpleItoa(field->containing_oneof()->index());
+ } else {
+ vars["name"] = FieldName(field);
+ vars["presence"] = SimpleItoa(has_bit_indices_[field->index()]);
+ }
+ vars["nwtype"] = SimpleItoa(normal_wiretype);
+ vars["pwtype"] = SimpleItoa(packed_wiretype);
+ vars["ptype"] = SimpleItoa(processing_type);
+ vars["tag_size"] = SimpleItoa(tag_size);
+
+ printer->Print(vars,
+ "{\n"
+ " GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(\n"
+ " $classname$, $name$_),\n"
+ " static_cast< ::google::protobuf::uint32>($presence$),\n"
+ " $nwtype$, $pwtype$, $ptype$, $tag_size$\n"
+ "},\n");
+ }
+
+ return last_field_number;
+}
+
+size_t MessageGenerator::GenerateParseAuxTable(io::Printer* printer) {
+ if (!table_driven_) {
+ return 0;
+ }
+
+ std::vector<const FieldDescriptor*> ordered_fields =
+ SortFieldsByNumber(descriptor_);
+
+ printer->Print("::google::protobuf::internal::AuxillaryParseTableField(),\n");
+ int last_field_number = 1;
+ for (int i = 0; i < descriptor_->field_count(); i++) {
+ const FieldDescriptor* field = ordered_fields[i];
+
+ GOOGLE_CHECK_GE(field->number(), last_field_number);
+ for (; last_field_number < field->number(); last_field_number++) {
+ printer->Print("::google::protobuf::internal::AuxillaryParseTableField(),\n");
+ }
+
+ std::map<string, string> vars;
+ SetCommonFieldVariables(field, &vars, options_);
+
+ switch (field->cpp_type()) {
+ case FieldDescriptor::CPPTYPE_ENUM:
+ vars["type"] = ClassName(field->enum_type(), true);
+ printer->Print(
+ vars,
+ "{::google::protobuf::internal::AuxillaryParseTableField::enum_aux{"
+ "$type$_IsValid}},\n");
+ last_field_number++;
+ break;
+ case FieldDescriptor::CPPTYPE_MESSAGE: {
+ if (field->is_map()) {
+ vars["classname"] = QualifiedClassName(field->message_type());
+ printer->Print(vars,
+ "{::google::protobuf::internal::AuxillaryParseTableField::map_"
+ "aux{&::google::protobuf::internal::ParseMap<$classname$>}},\n");
+ last_field_number++;
+ break;
+ } else {
+ vars["classname"] = ClassName(field->message_type(), false);
+ }
+ vars["ns"] = Namespace(field->message_type());
+ vars["type"] = FieldMessageTypeName(field);
+ vars["file_namespace"] =
+ FileLevelNamespace(field->message_type());
+
+ printer->Print(
+ vars,
+ "{::google::protobuf::internal::AuxillaryParseTableField::message_aux{\n"
+ " &$ns$::_$classname$_default_instance_,\n");
+
+ bool dont_emit_table =
+ !TableDrivenParsingEnabled(field->message_type(), options_);
+
+ if (dont_emit_table) {
+ printer->Print(" NULL,\n");
+ } else {
+ printer->Print(vars,
+ " ::$file_namespace$::TableStruct::schema +\n"
+ " $ns$::$classname$::kIndexInFileMessages,\n");
+ }
+
+ printer->Print("}},\n");
+ last_field_number++;
+ break;
+ }
+ case FieldDescriptor::CPPTYPE_STRING:
+ switch (EffectiveStringCType(field)) {
+ case FieldOptions::STRING:
+ vars["default"] =
+ field->default_value_string().empty()
+ ? "&::google::protobuf::internal::fixed_address_empty_string"
+ : "&" + Namespace(field) + " ::" + classname_ +
+ "::_default_" + FieldName(field) + "_";
+ break;
+ case FieldOptions::CORD:
+ case FieldOptions::STRING_PIECE:
+ vars["default"] =
+ "\"" + CEscape(field->default_value_string()) + "\"";
+ break;
+ }
+ vars["full_name"] = field->full_name();
+ printer->Print(vars,
+ "{::google::protobuf::internal::AuxillaryParseTableField::string_aux{\n"
+ " $default$,\n"
+ " \"$full_name$\"\n"
+ "}},\n");
+ last_field_number++;
+ break;
+ default:
+ break;
+ }
+ }
+
+ return last_field_number;
+}
+
std::pair<size_t, size_t> MessageGenerator::GenerateOffsets(
io::Printer* printer) {
- if (IsMapEntryMessage(descriptor_)) return std::make_pair(0, 0);
std::map<string, string> variables;
- variables["classname"] = classname_;
+ string full_classname = QualifiedClassName(descriptor_);
+ variables["classname"] = full_classname;
- if (HasFieldPresence(descriptor_->file())) {
+ if (HasFieldPresence(descriptor_->file()) || IsMapEntryMessage(descriptor_)) {
printer->Print(
variables,
- "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, _has_bits_),\n");
+ "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, "
+ "_has_bits_),\n");
} else {
printer->Print("~0u, // no _has_bits_\n");
}
@@ -1788,51 +2110,61 @@ std::pair<size_t, size_t> MessageGenerator::GenerateOffsets(
if (descriptor_->extension_range_count() > 0) {
printer->Print(
variables,
- "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, _extensions_),\n");
+ "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, "
+ "_extensions_),\n");
} else {
printer->Print("~0u, // no _extensions_\n");
}
if (descriptor_->oneof_decl_count() > 0) {
printer->Print(variables,
- "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, "
- "_oneof_case_[0]),\n");
+ "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET("
+ "$classname$, _oneof_case_[0]),\n");
} else {
printer->Print("~0u, // no _oneof_case_\n");
}
-
- const int kNumGenericOffsets = 4; // the number of fixed offsets above
+ if (num_weak_fields_ > 0) {
+ printer->Print(variables,
+ "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$,"
+ " _weak_field_map_),\n");
+ } else {
+ printer->Print("~0u, // no _weak_field_map_\n");
+ }
+ const int kNumGenericOffsets = 5; // the number of fixed offsets above
const size_t offsets = kNumGenericOffsets +
descriptor_->field_count() +
descriptor_->oneof_decl_count();
size_t entries = offsets;
for (int i = 0; i < descriptor_->field_count(); i++) {
const FieldDescriptor* field = descriptor_->field(i);
- if (field->containing_oneof()) {
- printer->Print(
- "PROTO2_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET("
- "(&$classname$_default_oneof_instance_), $name$_),\n",
- "classname", classname_, "name", FieldName(field));
+ if (field->containing_oneof() || field->options().weak()) {
+ printer->Print("offsetof($classname$DefaultTypeInternal, $name$_),\n",
+ "classname", full_classname, "name", FieldName(field));
} else {
printer->Print(
"GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, "
- "$name$_),\n",
- "classname", classname_,
- "name", FieldName(field));
+ "$name$_),\n",
+ "classname", full_classname, "name", FieldName(field));
}
}
for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
const OneofDescriptor* oneof = descriptor_->oneof_decl(i);
printer->Print(
- "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, $name$_),\n",
- "classname", classname_,
- "name", oneof->name());
+ "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, $name$_),\n",
+ "classname", full_classname, "name", oneof->name());
}
- if (HasFieldPresence(descriptor_->file())) {
+ if (IsMapEntryMessage(descriptor_)) {
+ entries += 2;
+ printer->Print(
+ "0,\n"
+ "1,\n");
+ } else if (HasFieldPresence(descriptor_->file())) {
entries += has_bit_indices_.size();
for (int i = 0; i < has_bit_indices_.size(); i++) {
- printer->Print("$index$,\n", "index", SimpleItoa(has_bit_indices_[i]));
+ const string index = has_bit_indices_[i] >= 0 ?
+ SimpleItoa(has_bit_indices_[i]) : "~0u";
+ printer->Print("$index$,\n", "index", index);
}
}
@@ -1855,18 +2187,6 @@ GenerateSharedConstructorCode(io::Printer* printer) {
need_to_clear_cached_size = false;
}
- // TODO(gerbens) Clean this hack, and why do i need a reference to a pointer??
- for (int i = 0; i < descriptor_->nested_type_count(); i++) {
- if (HasDescriptorMethods(descriptor_->file(), options_) &&
- IsMapEntryMessage(descriptor_->nested_type(i))) {
- printer->Print(
- "const ::google::protobuf::Descriptor*& $type$_descriptor = "
- "file_level_metadata[$index$].descriptor;\n",
- "type", ClassName(descriptor_->nested_type(i), false), "index",
- SimpleItoa(nested_generators_[i]->index_in_metadata_));
- }
- }
-
std::vector<bool> processed(optimized_order_.size(), false);
GenerateConstructorBody(printer, processed, false);
@@ -1891,15 +2211,9 @@ GenerateSharedDestructorCode(io::Printer* printer) {
"classname", classname_);
printer->Indent();
if (SupportsArenas(descriptor_)) {
- // Do nothing when the message is allocated in an arena.
printer->Print(
- "::google::protobuf::Arena* arena = GetArenaNoVirtual();\n"
- "if (arena != NULL) {\n"
- " return;\n"
- "}\n"
- "\n");
+ "GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);\n");
}
-
// Write the destructors for each field except oneof members.
// optimized_order_ does not contain oneof fields.
for (int i = 0; i < optimized_order_.size(); i++) {
@@ -1916,6 +2230,9 @@ GenerateSharedDestructorCode(io::Printer* printer) {
"oneof_name", descriptor_->oneof_decl(i)->name());
}
+ if (num_weak_fields_) {
+ printer->Print("_weak_field_map_.ClearAll();\n");
+ }
printer->Outdent();
printer->Print(
"}\n"
@@ -1966,6 +2283,12 @@ GenerateArenaDestructorCode(io::Printer* printer) {
}
}
}
+ if (num_weak_fields_) {
+ // _this is the object being destructed (we are inside a static method
+ // here).
+ printer->Print("_this->_weak_field_map_.ClearAll();\n");
+ need_registration = true;
+ }
printer->Outdent();
printer->Print(
@@ -2015,12 +2338,13 @@ void MessageGenerator::GenerateConstructorBody(io::Printer* printer,
if (copy_constructor) {
pod_template =
"::memcpy(&$first$_, &from.$first$_,\n"
- " reinterpret_cast<char*>(&$last$_) -\n"
- " reinterpret_cast<char*>(&$first$_) + sizeof($last$_));\n";
+ " static_cast<size_t>(reinterpret_cast<char*>(&$last$_) -\n"
+ " reinterpret_cast<char*>(&$first$_)) + sizeof($last$_));\n";
} else {
pod_template =
- "::memset(&$first$_, 0, reinterpret_cast<char*>(&$last$_) -\n"
- " reinterpret_cast<char*>(&$first$_) + sizeof($last$_));\n";
+ "::memset(&$first$_, 0, static_cast<size_t>(\n"
+ " reinterpret_cast<char*>(&$last$_) -\n"
+ " reinterpret_cast<char*>(&$first$_)) + sizeof($last$_));\n";
}
for (int i = 0; i < optimized_order_.size(); ++i) {
@@ -2087,43 +2411,44 @@ GenerateStructors(io::Printer* printer) {
if (IsAnyMessage(descriptor_)) {
initializer_with_arena += ",\n _any_metadata_(&type_url_, &value_)";
}
+ if (num_weak_fields_ > 0) {
+ initializer_with_arena += ", _weak_field_map_(arena)";
+ }
- string initializer_null;
- initializer_null = ", _internal_metadata_(NULL)";
+ string initializer_null = superclass + "(), _internal_metadata_(NULL)";
if (IsAnyMessage(descriptor_)) {
initializer_null += ", _any_metadata_(&type_url_, &value_)";
}
+ if (num_weak_fields_ > 0) {
+ initializer_null += ", _weak_field_map_(NULL)";
+ }
printer->Print(
"$classname$::$classname$()\n"
- " : $superclass$()$initializer$ {\n"
+ " : $initializer$ {\n"
" if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {\n"
- " $initdefaultsname$();\n"
+ " ::$file_namespace$::InitDefaults$scc_name$();\n"
" }\n"
" SharedCtor();\n"
" // @@protoc_insertion_point(constructor:$full_name$)\n"
"}\n",
- "classname", classname_, "superclass", superclass, "full_name",
- descriptor_->full_name(), "initializer", initializer_null,
- "initdefaultsname", GlobalInitDefaultsName(descriptor_->file()->name()));
+ "classname", classname_, "full_name", descriptor_->full_name(),
+ "scc_name", scc_name_, "initializer", initializer_null, "file_namespace",
+ FileLevelNamespace(descriptor_));
if (SupportsArenas(descriptor_)) {
printer->Print(
"$classname$::$classname$(::google::protobuf::Arena* arena)\n"
" : $initializer$ {\n"
- // When arenas are used it's safe to assume we have finished
- // static init time (protos with arenas are unsafe during static init)
- "#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER\n"
- " $initdefaultsname$();\n"
- "#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER\n"
+ " ::$file_namespace$::InitDefaults$scc_name$();\n"
" SharedCtor();\n"
" RegisterArenaDtor(arena);\n"
" // @@protoc_insertion_point(arena_constructor:$full_name$)\n"
"}\n",
"initializer", initializer_with_arena, "classname", classname_,
"superclass", superclass, "full_name", descriptor_->full_name(),
- "initdefaultsname",
- GlobalInitDefaultsName(descriptor_->file()->name()));
+ "scc_name", scc_name_, "file_namespace",
+ FileLevelNamespace(descriptor_));
}
// Generate the copy constructor.
@@ -2176,6 +2501,9 @@ GenerateStructors(io::Printer* printer) {
if (IsAnyMessage(descriptor_)) {
printer->Print(",\n_any_metadata_(&type_url_, &value_)");
}
+ if (num_weak_fields_ > 0) {
+ printer->Print(",\n_weak_field_map_(from._weak_field_map_)");
+ }
printer->Outdent();
printer->Outdent();
@@ -2188,18 +2516,6 @@ GenerateStructors(io::Printer* printer) {
printer->Print("_extensions_.MergeFrom(from._extensions_);\n");
}
- // TODO(gerbens) Clean this hack, and why do i need a reference to a pointer??
- for (int i = 0; i < descriptor_->nested_type_count(); i++) {
- if (HasDescriptorMethods(descriptor_->file(), options_) &&
- IsMapEntryMessage(descriptor_->nested_type(i))) {
- printer->Print(
- "const ::google::protobuf::Descriptor*& $type$_descriptor = "
- "file_level_metadata[$index$].descriptor;\n",
- "type", ClassName(descriptor_->nested_type(i), false), "index",
- SimpleItoa(nested_generators_[i]->index_in_metadata_));
- }
- }
-
GenerateConstructorBody(printer, processed, true);
// Copy oneof fields. Oneof field requires oneof case check.
@@ -2277,20 +2593,23 @@ GenerateStructors(io::Printer* printer) {
!descriptor_->options().no_standard_descriptor_accessor()) {
printer->Print(
"const ::google::protobuf::Descriptor* $classname$::descriptor() {\n"
- " protobuf_AssignDescriptorsOnce();\n"
- " return file_level_metadata[$index$].descriptor;\n"
+ " ::$file_namespace$::protobuf_AssignDescriptorsOnce();\n"
+ " return ::"
+ "$file_namespace$::file_level_metadata[kIndexInFileMessages]."
+ "descriptor;\n"
"}\n"
"\n",
- "index", SimpleItoa(index_in_metadata_), "classname", classname_);
+ "classname", classname_, "file_namespace",
+ FileLevelNamespace(descriptor_));
}
printer->Print(
"const $classname$& $classname$::default_instance() {\n"
- " $initdefaultsname$();\n"
+ " ::$file_namespace$::InitDefaults$scc_name$();\n"
" return *internal_default_instance();\n"
"}\n\n",
- "classname", classname_, "initdefaultsname",
- GlobalInitDefaultsName(descriptor_->file()->name()));
+ "classname", classname_, "scc_name", scc_name_, "file_namespace",
+ FileLevelNamespace(descriptor_));
if (SupportsArenas(descriptor_)) {
printer->Print(
@@ -2309,7 +2628,6 @@ GenerateStructors(io::Printer* printer) {
"}\n",
"classname", classname_);
}
-
}
// Return the number of bits set in n, a non-negative integer.
@@ -2322,20 +2640,59 @@ static int popcnt(uint32 n) {
return result;
}
+bool MessageGenerator::MaybeGenerateOptionalFieldCondition(
+ io::Printer* printer, const FieldDescriptor* field,
+ int expected_has_bits_index) {
+ int has_bit_index = has_bit_indices_[field->index()];
+ if (!field->options().weak() &&
+ expected_has_bits_index == has_bit_index / 32) {
+ const string mask =
+ StrCat(strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8));
+ printer->Print(
+ "if (cached_has_bits & 0x$mask$u) {\n",
+ "mask", mask);
+ return true;
+ }
+ return false;
+}
+
void MessageGenerator::
GenerateClear(io::Printer* printer) {
+ // Performance tuning parameters
+ const int kMaxUnconditionalPrimitiveBytesClear = 4;
+
printer->Print(
"void $classname$::Clear() {\n"
"// @@protoc_insertion_point(message_clear_start:$full_name$)\n",
"classname", classname_, "full_name", descriptor_->full_name());
printer->Indent();
+ printer->Print(
+ // TODO(jwb): It would be better to avoid emitting this if it is not used,
+ // rather than emitting a workaround for the resulting warning.
+ "::google::protobuf::uint32 cached_has_bits = 0;\n"
+ "// Prevent compiler warnings about cached_has_bits being unused\n"
+ "(void) cached_has_bits;\n\n");
+
+ int cached_has_bit_index = -1;
+
// Step 1: Extensions
if (descriptor_->extension_range_count() > 0) {
printer->Print("_extensions_.Clear();\n");
}
int last_i = -1;
+ int unconditional_budget = kMaxUnconditionalPrimitiveBytesClear;
+ for (int i = 0; i < optimized_order_.size(); i++) {
+ const FieldDescriptor* field = optimized_order_[i];
+
+ if (!CanInitializeByZeroing(field)) {
+ continue;
+ }
+
+ unconditional_budget -= EstimateAlignmentSize(field);
+ }
+
for (int i = 0; i < optimized_order_.size(); ) {
// Detect infinite loops.
GOOGLE_CHECK_NE(i, last_i);
@@ -2351,11 +2708,7 @@ GenerateClear(io::Printer* printer) {
break;
}
- if (use_dependent_base_ && IsFieldDependent(field)) {
- printer->Print("clear_$name$();\n", "name", FieldName(field));
- } else {
- generator.GenerateMessageClearingCode(printer);
- }
+ generator.GenerateMessageClearingCode(printer);
}
// Step 3: Greedily seek runs of fields that can be cleared by
@@ -2397,6 +2750,11 @@ GenerateClear(io::Printer* printer) {
last_chunk_mask |= static_cast<uint32>(1) << (index % 32);
}
+ if (memset_run_start != memset_run_end && unconditional_budget >= 0) {
+ // Flush the memset fields.
+ goto flush;
+ }
+
// Step 4: Non-repeated, non-zero initializable fields.
for (; i < optimized_order_.size(); i++) {
const FieldDescriptor* field = optimized_order_[i];
@@ -2422,6 +2780,8 @@ GenerateClear(io::Printer* printer) {
last_chunk_mask |= static_cast<uint32>(1) << (index % 32);
}
+flush:
+
if (last_chunk != -1) {
GOOGLE_DCHECK_NE(-1, last_chunk_start);
GOOGLE_DCHECK_NE(-1, last_chunk_end);
@@ -2429,7 +2789,10 @@ GenerateClear(io::Printer* printer) {
const int count = popcnt(last_chunk_mask);
const bool have_outer_if = HasFieldPresence(descriptor_->file()) &&
- (last_chunk_start != last_chunk_end);
+ (last_chunk_start != last_chunk_end) &&
+ (memset_run_start != last_chunk_start ||
+ memset_run_end != last_chunk_end ||
+ unconditional_budget < 0);
if (have_outer_if) {
// Check (up to) 8 has_bits at a time if we have more than one field in
@@ -2438,9 +2801,14 @@ GenerateClear(io::Printer* printer) {
GOOGLE_DCHECK_LE(2, count);
GOOGLE_DCHECK_GE(8, count);
+ if (cached_has_bit_index != last_chunk / 4) {
+ cached_has_bit_index = last_chunk / 4;
+ printer->Print(
+ "cached_has_bits = _has_bits_[$idx$];\n",
+ "idx", SimpleItoa(cached_has_bit_index));
+ }
printer->Print(
- "if (_has_bits_[$index$ / 32] & $mask$u) {\n",
- "index", SimpleItoa(last_chunk * 8),
+ "if (cached_has_bits & $mask$u) {\n",
"mask", SimpleItoa(last_chunk_mask));
printer->Indent();
}
@@ -2458,8 +2826,9 @@ GenerateClear(io::Printer* printer) {
FieldName(optimized_order_[memset_run_end]);
printer->Print(
- "::memset(&$first$_, 0, reinterpret_cast<char*>(&$last$_) -\n"
- " reinterpret_cast<char*>(&$first$_) + sizeof($last$_));\n",
+ "::memset(&$first$_, 0, static_cast<size_t>(\n"
+ " reinterpret_cast<char*>(&$last$_) -\n"
+ " reinterpret_cast<char*>(&$first$_)) + sizeof($last$_));\n",
"first", first_field_name,
"last", last_field_name);
}
@@ -2486,7 +2855,18 @@ GenerateClear(io::Printer* printer) {
if (should_check_bit &&
// If no field presence, then always clear strings/messages as well.
HasFieldPresence(descriptor_->file())) {
- printer->Print("if (has_$name$()) {\n", "name", fieldname);
+ if (!field->options().weak() &&
+ cached_has_bit_index != (has_bit_indices_[field->index()] / 32)) {
+ cached_has_bit_index = (has_bit_indices_[field->index()] / 32);
+ printer->Print("cached_has_bits = _has_bits_[$new_index$];\n",
+ "new_index", SimpleItoa(cached_has_bit_index));
+ }
+ if (!MaybeGenerateOptionalFieldCondition(printer, field,
+ cached_has_bit_index)) {
+ printer->Print(
+ "if (has_$name$()) {\n",
+ "name", fieldname);
+ }
printer->Indent();
have_enclosing_if = true;
}
@@ -2513,14 +2893,16 @@ GenerateClear(io::Printer* printer) {
"oneof_name", descriptor_->oneof_decl(i)->name());
}
+ if (num_weak_fields_) {
+ printer->Print("_weak_field_map_.ClearAll();\n");
+ }
+
if (HasFieldPresence(descriptor_->file())) {
// Step 5: Everything else.
printer->Print("_has_bits_.Clear();\n");
}
- if (PreserveUnknownFields(descriptor_)) {
- printer->Print("_internal_metadata_.Clear();\n");
- }
+ printer->Print("_internal_metadata_.Clear();\n");
printer->Outdent();
printer->Print("}\n");
@@ -2624,6 +3006,7 @@ GenerateSwap(io::Printer* printer) {
printer->Print("void $classname$::InternalSwap($classname$* other) {\n",
"classname", classname_);
printer->Indent();
+ printer->Print("using std::swap;\n");
if (HasGeneratedMethods(descriptor_->file(), options_)) {
for (int i = 0; i < optimized_order_.size(); i++) {
@@ -2635,27 +3018,29 @@ GenerateSwap(io::Printer* printer) {
for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
printer->Print(
- "std::swap($oneof_name$_, other->$oneof_name$_);\n"
- "std::swap(_oneof_case_[$i$], other->_oneof_case_[$i$]);\n",
+ "swap($oneof_name$_, other->$oneof_name$_);\n"
+ "swap(_oneof_case_[$i$], other->_oneof_case_[$i$]);\n",
"oneof_name", descriptor_->oneof_decl(i)->name(),
"i", SimpleItoa(i));
}
if (HasFieldPresence(descriptor_->file())) {
- for (int i = 0; i < (descriptor_->field_count() + 31) / 32; ++i) {
- printer->Print("std::swap(_has_bits_[$i$], other->_has_bits_[$i$]);\n",
+ for (int i = 0; i < HasBitsSize() / 4; ++i) {
+ printer->Print("swap(_has_bits_[$i$], other->_has_bits_[$i$]);\n",
"i", SimpleItoa(i));
}
}
- if (PreserveUnknownFields(descriptor_)) {
- printer->Print("_internal_metadata_.Swap(&other->_internal_metadata_);\n");
- }
+ printer->Print("_internal_metadata_.Swap(&other->_internal_metadata_);\n");
- printer->Print("std::swap(_cached_size_, other->_cached_size_);\n");
+ printer->Print("swap(_cached_size_, other->_cached_size_);\n");
if (descriptor_->extension_range_count() > 0) {
printer->Print("_extensions_.Swap(&other->_extensions_);\n");
}
+ if (num_weak_fields_) {
+ printer->Print(
+ "_weak_field_map_.UnsafeArenaSwap(&other->_weak_field_map_);\n");
+ }
} else {
printer->Print("GetReflection()->Swap(this, other);");
}
@@ -2723,7 +3108,14 @@ GenerateMergeFrom(io::Printer* printer) {
}
printer->Print(
- "_internal_metadata_.MergeFrom(from._internal_metadata_);\n");
+ "_internal_metadata_.MergeFrom(from._internal_metadata_);\n"
+ "::google::protobuf::uint32 cached_has_bits = 0;\n"
+ "(void) cached_has_bits;\n\n");
+
+ // cached_has_bit_index maintains that:
+ // cached_has_bits = from._has_bits_[cached_has_bit_index]
+ // for cached_has_bit_index >= 0
+ int cached_has_bit_index = -1;
int last_i = -1;
for (int i = 0; i < optimized_order_.size(); ) {
@@ -2743,7 +3135,7 @@ GenerateMergeFrom(io::Printer* printer) {
generator.GenerateMergingCode(printer);
}
- // Merge Optional and Required fields (after a _has_bit check).
+ // Merge Optional and Required fields (after a _has_bit_ check).
int last_chunk = -1;
int last_chunk_start = -1;
int last_chunk_end = -1;
@@ -2788,23 +3180,43 @@ GenerateMergeFrom(io::Printer* printer) {
GOOGLE_DCHECK_LE(2, count);
GOOGLE_DCHECK_GE(8, count);
+ if (cached_has_bit_index != last_chunk / 4) {
+ int new_index = last_chunk / 4;
+ printer->Print("cached_has_bits = from._has_bits_[$new_index$];\n",
+ "new_index", SimpleItoa(new_index));
+ cached_has_bit_index = new_index;
+ }
+
printer->Print(
- "if (from._has_bits_[$index$ / 32] & $mask$u) {\n",
- "index", SimpleItoa(last_chunk * 8),
+ "if (cached_has_bits & $mask$u) {\n",
"mask", SimpleItoa(last_chunk_mask));
printer->Indent();
}
// Go back and emit clears for each of the fields we processed.
+ bool deferred_has_bit_changes = false;
for (int j = last_chunk_start; j <= last_chunk_end; j++) {
const FieldDescriptor* field = optimized_order_[j];
const FieldGenerator& generator = field_generators_.get(field);
bool have_enclosing_if = false;
if (HasFieldPresence(descriptor_->file())) {
- printer->Print(
- "if (from.has_$name$()) {\n",
- "name", FieldName(field));
+ // Attempt to use the state of cached_has_bits, if possible.
+ int has_bit_index = has_bit_indices_[field->index()];
+ if (!field->options().weak() &&
+ cached_has_bit_index == has_bit_index / 32) {
+ const string mask = StrCat(
+ strings::Hex(1u << (has_bit_index % 32),
+ strings::ZERO_PAD_8));
+
+ printer->Print(
+ "if (cached_has_bits & 0x$mask$u) {\n", "mask", mask);
+ } else {
+ printer->Print(
+ "if (from.has_$name$()) {\n",
+ "name", FieldName(field));
+ }
+
printer->Indent();
have_enclosing_if = true;
} else {
@@ -2814,7 +3226,17 @@ GenerateMergeFrom(io::Printer* printer) {
printer, "from.", field);
}
- generator.GenerateMergingCode(printer);
+ if (have_outer_if && IsPOD(field)) {
+ // GenerateCopyConstructorCode for enum and primitive scalar fields
+ // does not do _has_bits_ modifications. We defer _has_bits_
+ // manipulation until the end of the outer if.
+ //
+ // This can reduce the number of loads/stores by up to 7 per 8 fields.
+ deferred_has_bit_changes = true;
+ generator.GenerateCopyConstructorCode(printer);
+ } else {
+ generator.GenerateMergingCode(printer);
+ }
if (have_enclosing_if) {
printer->Outdent();
@@ -2823,6 +3245,14 @@ GenerateMergeFrom(io::Printer* printer) {
}
if (have_outer_if) {
+ if (deferred_has_bit_changes) {
+ // Flush the has bits for the primitives we deferred.
+ GOOGLE_CHECK_LE(0, cached_has_bit_index);
+ printer->Print(
+ "_has_bits_[$index$] |= cached_has_bits;\n",
+ "index", SimpleItoa(cached_has_bit_index));
+ }
+
printer->Outdent();
printer->Print("}\n");
}
@@ -2858,6 +3288,9 @@ GenerateMergeFrom(io::Printer* printer) {
printer->Print(
"}\n");
}
+ if (num_weak_fields_) {
+ printer->Print("_weak_field_map_.MergeFrom(from._weak_field_map_);\n");
+ }
printer->Outdent();
printer->Print("}\n");
@@ -2903,44 +3336,62 @@ GenerateCopyFrom(io::Printer* printer) {
void MessageGenerator::
GenerateMergeFromCodedStream(io::Printer* printer) {
+ std::map<string, string> vars;
+ SetUnknkownFieldsVariable(descriptor_, options_, &vars);
if (descriptor_->options().message_set_wire_format()) {
// Special-case MessageSet.
- printer->Print(
+ vars["classname"] = classname_;
+ printer->Print(vars,
"bool $classname$::MergePartialFromCodedStream(\n"
- " ::google::protobuf::io::CodedInputStream* input) {\n",
- "classname", classname_);
+ " ::google::protobuf::io::CodedInputStream* input) {\n"
+ " return _extensions_.ParseMessageSet(input,\n"
+ " internal_default_instance(), $mutable_unknown_fields$);\n"
+ "}\n");
+ return;
+ }
- printer->Print(
- " return _extensions_.ParseMessageSet(input, "
- "internal_default_instance(),\n"
- " mutable_unknown_fields());\n",
- // Vars.
- "classname", classname_);
+ std::vector<const FieldDescriptor*> ordered_fields =
+ SortFieldsByNumber(descriptor_);
+
+ printer->Print(
+ "bool $classname$::MergePartialFromCodedStream(\n"
+ " ::google::protobuf::io::CodedInputStream* input) {\n",
+ "classname", classname_);
+
+ if (table_driven_) {
+ printer->Indent();
+
+ const string lite = UseUnknownFieldSet(descriptor_->file(), options_) ?
+ "" : "Lite";
printer->Print(
- "}\n");
+ "return ::google::protobuf::internal::MergePartialFromCodedStream$lite$(\n"
+ " this,\n"
+ " ::$file_namespace$::TableStruct::schema[\n"
+ " $classname$::kIndexInFileMessages],\n"
+ " input);\n",
+ "classname", classname_, "file_namespace",
+ FileLevelNamespace(descriptor_), "lite", lite);
+
+ printer->Outdent();
+
+ printer->Print("}\n");
return;
}
printer->Print(
- "bool $classname$::MergePartialFromCodedStream(\n"
- " ::google::protobuf::io::CodedInputStream* input) {\n"
"#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure\n"
- " ::google::protobuf::uint32 tag;\n",
- "classname", classname_);
+ " ::google::protobuf::uint32 tag;\n");
- if (PreserveUnknownFields(descriptor_) &&
- !UseUnknownFieldSet(descriptor_->file(), options_)) {
- // Use LazyStringOutputString to avoid initializing unknown fields string
- // unless it is actually needed. For the same reason, disable eager refresh
- // on the CodedOutputStream.
- printer->Print(
- " ::google::protobuf::io::LazyStringOutputStream unknown_fields_string(\n"
- " NewPermanentCallback(\n"
- " &MutableUnknownFieldsFor$classname$, this));\n"
- " ::google::protobuf::io::CodedOutputStream unknown_fields_stream(\n"
- " &unknown_fields_string, false);\n",
- "classname", classname_);
+ if (!UseUnknownFieldSet(descriptor_->file(), options_)) {
+ printer->Print(
+ " ::google::protobuf::internal::LiteUnknownFieldSetter unknown_fields_setter(\n"
+ " &_internal_metadata_);\n"
+ " ::google::protobuf::io::StringOutputStream unknown_fields_output(\n"
+ " unknown_fields_setter.buffer());\n"
+ " ::google::protobuf::io::CodedOutputStream unknown_fields_stream(\n"
+ " &unknown_fields_output, false);\n",
+ "classname", classname_);
}
printer->Print(
@@ -2951,8 +3402,6 @@ GenerateMergeFromCodedStream(io::Printer* printer) {
printer->Print("for (;;) {\n");
printer->Indent();
- std::vector<const FieldDescriptor*> ordered_fields =
- SortFieldsByNumber(descriptor_);
uint32 maxtag = descriptor_->field_count() == 0 ? 0 :
WireFormat::MakeTag(ordered_fields[descriptor_->field_count() - 1]);
const int kCutoff0 = 127; // fits in 1-byte varint
@@ -2984,13 +3433,12 @@ GenerateMergeFromCodedStream(io::Printer* printer) {
}
printer->Print("::std::pair< ::google::protobuf::uint32, bool> p = "
- "input->ReadTagWithCutoff$lasttag$($max$u);\n"
+ "input->ReadTagWithCutoffNoLastTag($max$u);\n"
"tag = p.first;\n"
"if (!p.second) goto handle_unusual;\n",
"max", SimpleItoa(maxtag <= kCutoff0 ? kCutoff0 :
(maxtag <= kCutoff1 ? kCutoff1 :
- maxtag)),
- "lasttag", !capture_last_tag ? "NoLastTag" : "");
+ maxtag)));
if (descriptor_->field_count() > 0) {
// We don't even want to print the switch() if we have no fields because
@@ -3013,20 +3461,8 @@ GenerateMergeFromCodedStream(io::Printer* printer) {
printer->Indent();
- // Find repeated messages and groups now, to simplify what follows.
- hash_set<int> fields_with_parse_loop;
for (int i = 0; i < ordered_fields.size(); i++) {
const FieldDescriptor* field = ordered_fields[i];
- if (field->is_repeated() &&
- (field->type() == FieldDescriptor::TYPE_MESSAGE ||
- field->type() == FieldDescriptor::TYPE_GROUP)) {
- fields_with_parse_loop.insert(i);
- }
- }
-
- for (int i = 0; i < ordered_fields.size(); i++) {
- const FieldDescriptor* field = ordered_fields[i];
- const bool loops = fields_with_parse_loop.count(i) > 0;
PrintFieldComment(printer, field);
@@ -3037,12 +3473,11 @@ GenerateMergeFromCodedStream(io::Printer* printer) {
const FieldGenerator& field_generator = field_generators_.get(field);
// Emit code to parse the common, expected case.
- printer->Print("if (tag == $commontag$u) {\n",
- "commontag", SimpleItoa(WireFormat::MakeTag(field)));
-
- if (loops) {
- printer->Print(" DO_(input->IncrementRecursionDepth());\n");
- }
+ printer->Print(
+ "if (static_cast< ::google::protobuf::uint8>(tag) ==\n"
+ " static_cast< ::google::protobuf::uint8>($truncated$u /* $full$ & 0xFF */)) {\n",
+ "truncated", SimpleItoa(WireFormat::MakeTag(field) & 0xFF),
+ "full", SimpleItoa(WireFormat::MakeTag(field)));
printer->Indent();
if (field->is_packed()) {
@@ -3056,20 +3491,30 @@ GenerateMergeFromCodedStream(io::Printer* printer) {
if (field->is_packed()) {
internal::WireFormatLite::WireType wiretype =
WireFormat::WireTypeForFieldType(field->type());
- printer->Print("} else if (tag == $uncommontag$u) {\n",
- "uncommontag", SimpleItoa(
- internal::WireFormatLite::MakeTag(
- field->number(), wiretype)));
+ const uint32 tag = internal::WireFormatLite::MakeTag(
+ field->number(), wiretype);
+ printer->Print(
+ "} else if (\n"
+ " static_cast< ::google::protobuf::uint8>(tag) ==\n"
+ " static_cast< ::google::protobuf::uint8>($truncated$u /* $full$ & 0xFF */)) {\n",
+ "truncated", SimpleItoa(tag & 0xFF),
+ "full", SimpleItoa(tag));
+
printer->Indent();
field_generator.GenerateMergeFromCodedStream(printer);
printer->Outdent();
} else if (field->is_packable() && !field->is_packed()) {
internal::WireFormatLite::WireType wiretype =
internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED;
- printer->Print("} else if (tag == $uncommontag$u) {\n",
- "uncommontag", SimpleItoa(
- internal::WireFormatLite::MakeTag(
- field->number(), wiretype)));
+ const uint32 tag = internal::WireFormatLite::MakeTag(
+ field->number(), wiretype);
+
+ printer->Print(
+ "} else if (\n"
+ " static_cast< ::google::protobuf::uint8>(tag) ==\n"
+ " static_cast< ::google::protobuf::uint8>($truncated$u /* $full$ & 0xFF */)) {\n",
+ "truncated", SimpleItoa(tag & 0xFF),
+ "full", SimpleItoa(tag));
printer->Indent();
field_generator.GenerateMergeFromCodedStreamWithPacking(printer);
printer->Outdent();
@@ -3080,12 +3525,6 @@ GenerateMergeFromCodedStream(io::Printer* printer) {
" goto handle_unusual;\n"
"}\n");
- // For repeated messages/groups, we need to decrement recursion depth.
- if (loops) {
- printer->Print(
- "input->UnsafeDecrementRecursionDepth();\n");
- }
-
printer->Print(
"break;\n");
@@ -3101,12 +3540,20 @@ GenerateMergeFromCodedStream(io::Printer* printer) {
printer->Print("handle_unusual:\n");
printer->Indent();
// If tag is 0 or an end-group tag then this must be the end of the message.
- printer->Print(
- "if (tag == 0 ||\n"
- " ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==\n"
- " ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {\n"
- " goto success;\n"
- "}\n");
+ if (capture_last_tag) {
+ printer->Print(
+ "if (tag == 0 ||\n"
+ " ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==\n"
+ " ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {\n"
+ " input->SetLastTag(tag);\n"
+ " goto success;\n"
+ "}\n");
+ } else {
+ printer->Print(
+ "if (tag == 0) {\n"
+ " goto success;\n"
+ "}\n");
+ }
// Handle extension ranges.
if (descriptor_->extension_range_count() > 0) {
@@ -3134,23 +3581,16 @@ GenerateMergeFromCodedStream(io::Printer* printer) {
}
}
printer->Print(") {\n");
- if (PreserveUnknownFields(descriptor_)) {
- if (UseUnknownFieldSet(descriptor_->file(), options_)) {
- printer->Print(
- " DO_(_extensions_.ParseField(tag, input, "
- "internal_default_instance(),\n"
- " mutable_unknown_fields()));\n");
- } else {
- printer->Print(
- " DO_(_extensions_.ParseField(tag, input, "
- "internal_default_instance(),\n"
- " &unknown_fields_stream));\n");
- }
+ if (UseUnknownFieldSet(descriptor_->file(), options_)) {
+ printer->Print(vars,
+ " DO_(_extensions_.ParseField(tag, input,\n"
+ " internal_default_instance(),\n"
+ " $mutable_unknown_fields$));\n");
} else {
printer->Print(
- // With static initializers.
- " DO_(_extensions_.ParseField(tag, input, "
- "internal_default_instance());\n");
+ " DO_(_extensions_.ParseField(tag, input,\n"
+ " internal_default_instance(),\n"
+ " &unknown_fields_stream));\n");
}
printer->Print(
" continue;\n"
@@ -3158,19 +3598,14 @@ GenerateMergeFromCodedStream(io::Printer* printer) {
}
// We really don't recognize this tag. Skip it.
- if (PreserveUnknownFields(descriptor_)) {
- if (UseUnknownFieldSet(descriptor_->file(), options_)) {
- printer->Print(
+ if (UseUnknownFieldSet(descriptor_->file(), options_)) {
+ printer->Print(vars,
"DO_(::google::protobuf::internal::WireFormat::SkipField(\n"
- " input, tag, mutable_unknown_fields()));\n");
- } else {
- printer->Print(
- "DO_(::google::protobuf::internal::WireFormatLite::SkipField(\n"
- " input, tag, &unknown_fields_stream));\n");
- }
+ " input, tag, $mutable_unknown_fields$));\n");
} else {
printer->Print(
- "DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));\n");
+ "DO_(::google::protobuf::internal::WireFormatLite::SkipField(\n"
+ " input, tag, &unknown_fields_stream));\n");
}
if (descriptor_->field_count() > 0) {
@@ -3200,7 +3635,7 @@ void MessageGenerator::GenerateSerializeOneofFields(
bool to_array) {
GOOGLE_CHECK(!fields.empty());
if (fields.size() == 1) {
- GenerateSerializeOneField(printer, fields[0], to_array);
+ GenerateSerializeOneField(printer, fields[0], to_array, -1);
return;
}
// We have multiple mutually exclusive choices. Emit a switch statement.
@@ -3233,14 +3668,31 @@ void MessageGenerator::GenerateSerializeOneofFields(
}
void MessageGenerator::GenerateSerializeOneField(
- io::Printer* printer, const FieldDescriptor* field, bool to_array) {
- PrintFieldComment(printer, field);
+ io::Printer* printer, const FieldDescriptor* field, bool to_array,
+ int cached_has_bits_index) {
+ if (!field->options().weak()) {
+ // For weakfields, PrintFieldComment is called during iteration.
+ PrintFieldComment(printer, field);
+ }
bool have_enclosing_if = false;
- if (!field->is_repeated() && HasFieldPresence(descriptor_->file())) {
- printer->Print(
- "if (has_$name$()) {\n",
- "name", FieldName(field));
+ if (field->options().weak()) {
+ } else if (!field->is_repeated() && HasFieldPresence(descriptor_->file())) {
+ // Attempt to use the state of cached_has_bits, if possible.
+ int has_bit_index = has_bit_indices_[field->index()];
+ if (cached_has_bits_index == has_bit_index / 32) {
+ const string mask = StrCat(
+ strings::Hex(1u << (has_bit_index % 32),
+ strings::ZERO_PAD_8));
+
+ printer->Print(
+ "if (cached_has_bits & 0x$mask$u) {\n", "mask", mask);
+ } else {
+ printer->Print(
+ "if (has_$name$()) {\n",
+ "name", FieldName(field));
+ }
+
printer->Indent();
have_enclosing_if = true;
} else if (!HasFieldPresence(descriptor_->file())) {
@@ -3272,7 +3724,7 @@ void MessageGenerator::GenerateSerializeOneExtensionRange(
if (to_array) {
printer->Print(vars,
"target = _extensions_.InternalSerializeWithCachedSizesToArray(\n"
- " $start$, $end$, false, target);\n\n");
+ " $start$, $end$, deterministic, target);\n\n");
} else {
printer->Print(vars,
"_extensions_.SerializeWithCachedSizes(\n"
@@ -3290,13 +3742,16 @@ GenerateSerializeWithCachedSizes(io::Printer* printer) {
" _extensions_.SerializeMessageSetWithCachedSizes(output);\n",
"classname", classname_);
GOOGLE_CHECK(UseUnknownFieldSet(descriptor_->file(), options_));
- printer->Print(
+ std::map<string, string> vars;
+ SetUnknkownFieldsVariable(descriptor_, options_, &vars);
+ printer->Print(vars,
" ::google::protobuf::internal::WireFormat::SerializeUnknownMessageSetItems(\n"
- " unknown_fields(), output);\n");
+ " $unknown_fields$, output);\n");
printer->Print(
"}\n");
return;
}
+ if (options_.table_driven_serialization) return;
printer->Print(
"void $classname$::SerializeWithCachedSizes(\n"
@@ -3331,10 +3786,12 @@ GenerateSerializeWithCachedSizesToArray(io::Printer* printer) {
" deterministic, target);\n",
"classname", classname_);
GOOGLE_CHECK(UseUnknownFieldSet(descriptor_->file(), options_));
- printer->Print(
+ std::map<string, string> vars;
+ SetUnknkownFieldsVariable(descriptor_, options_, &vars);
+ printer->Print(vars,
" target = ::google::protobuf::internal::WireFormat::\n"
" SerializeUnknownMessageSetItemsToArray(\n"
- " unknown_fields(), target);\n");
+ " $unknown_fields$, target);\n");
printer->Print(
" return target;\n"
"}\n");
@@ -3378,7 +3835,8 @@ GenerateSerializeWithCachedSizesBody(io::Printer* printer, bool to_array) {
: mg_(mg),
printer_(printer),
to_array_(to_array),
- eager_(!HasFieldPresence(mg->descriptor_->file())) {}
+ eager_(!HasFieldPresence(mg->descriptor_->file())),
+ cached_has_bit_index_(-1) {}
~LazySerializerEmitter() { Flush(); }
@@ -3389,7 +3847,27 @@ GenerateSerializeWithCachedSizesBody(io::Printer* printer, bool to_array) {
Flush();
}
if (field->containing_oneof() == NULL) {
- mg_->GenerateSerializeOneField(printer_, field, to_array_);
+ // TODO(ckennelly): Defer non-oneof fields similarly to oneof fields.
+
+ if (!field->options().weak() && !field->is_repeated() && !eager_) {
+ // We speculatively load the entire _has_bits_[index] contents, even
+ // if it is for only one field. Deferring non-oneof emitting would
+ // allow us to determine whether this is going to be useful.
+ int has_bit_index = mg_->has_bit_indices_[field->index()];
+ if (cached_has_bit_index_ != has_bit_index / 32) {
+ // Reload.
+ int new_index = has_bit_index / 32;
+
+ printer_->Print(
+ "cached_has_bits = _has_bits_[$new_index$];\n",
+ "new_index", SimpleItoa(new_index));
+
+ cached_has_bit_index_ = new_index;
+ }
+ }
+
+ mg_->GenerateSerializeOneField(
+ printer_, field, to_array_, cached_has_bit_index_);
} else {
v_.push_back(field);
}
@@ -3415,6 +3893,11 @@ GenerateSerializeWithCachedSizesBody(io::Printer* printer, bool to_array) {
const bool to_array_;
const bool eager_;
std::vector<const FieldDescriptor*> v_;
+
+ // cached_has_bit_index_ maintains that:
+ // cached_has_bits = from._has_bits_[cached_has_bit_index_]
+ // for cached_has_bit_index_ >= 0
+ int cached_has_bit_index_;
};
std::vector<const FieldDescriptor*> ordered_fields =
@@ -3426,54 +3909,76 @@ GenerateSerializeWithCachedSizesBody(io::Printer* printer, bool to_array) {
}
std::sort(sorted_extensions.begin(), sorted_extensions.end(),
ExtensionRangeSorter());
+ if (num_weak_fields_) {
+ printer->Print(
+ "::google::protobuf::internal::WeakFieldMap::FieldWriter field_writer("
+ "_weak_field_map_);\n");
+ }
+
+ printer->Print(
+ "::google::protobuf::uint32 cached_has_bits = 0;\n"
+ "(void) cached_has_bits;\n\n");
// Merge the fields and the extension ranges, both sorted by field number.
{
LazySerializerEmitter e(this, printer, to_array);
+ const FieldDescriptor* last_weak_field = NULL;
int i, j;
for (i = 0, j = 0;
i < ordered_fields.size() || j < sorted_extensions.size();) {
- if (i == descriptor_->field_count()) {
- e.Flush();
- GenerateSerializeOneExtensionRange(printer,
- sorted_extensions[j++],
- to_array);
- } else if (j == sorted_extensions.size()) {
- e.Emit(ordered_fields[i++]);
- } else if (ordered_fields[i]->number() < sorted_extensions[j]->start) {
- e.Emit(ordered_fields[i++]);
- } else {
+ if ((j == sorted_extensions.size()) ||
+ (i < descriptor_->field_count() &&
+ ordered_fields[i]->number() < sorted_extensions[j]->start)) {
+ const FieldDescriptor* field = ordered_fields[i++];
+ if (field->options().weak()) {
+ last_weak_field = field;
+ PrintFieldComment(printer, field);
+ } else {
+ if (last_weak_field != NULL) {
+ e.Emit(last_weak_field);
+ last_weak_field = NULL;
+ }
+ e.Emit(field);
+ }
+ } else {
+ if (last_weak_field != NULL) {
+ e.Emit(last_weak_field);
+ last_weak_field = NULL;
+ }
e.Flush();
GenerateSerializeOneExtensionRange(printer,
sorted_extensions[j++],
to_array);
}
}
+ if (last_weak_field != NULL) {
+ e.Emit(last_weak_field);
+ }
}
- if (PreserveUnknownFields(descriptor_)) {
- if (UseUnknownFieldSet(descriptor_->file(), options_)) {
- printer->Print("if (_internal_metadata_.have_unknown_fields()) {\n");
- printer->Indent();
- if (to_array) {
- printer->Print(
- "target = "
- "::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(\n"
- " unknown_fields(), target);\n");
- } else {
- printer->Print(
- "::google::protobuf::internal::WireFormat::SerializeUnknownFields(\n"
- " unknown_fields(), output);\n");
- }
- printer->Outdent();
-
- printer->Print(
- "}\n");
+ std::map<string, string> vars;
+ SetUnknkownFieldsVariable(descriptor_, options_, &vars);
+ if (UseUnknownFieldSet(descriptor_->file(), options_)) {
+ printer->Print(vars,
+ "if ($have_unknown_fields$) {\n");
+ printer->Indent();
+ if (to_array) {
+ printer->Print(vars,
+ "target = "
+ "::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(\n"
+ " $unknown_fields$, target);\n");
} else {
- printer->Print(
- "output->WriteRaw(unknown_fields().data(),\n"
- " static_cast<int>(unknown_fields().size()));\n");
+ printer->Print(vars,
+ "::google::protobuf::internal::WireFormat::SerializeUnknownFields(\n"
+ " $unknown_fields$, output);\n");
}
+ printer->Outdent();
+
+ printer->Print("}\n");
+ } else {
+ printer->Print(vars,
+ "output->WriteRaw($unknown_fields$.data(),\n"
+ " static_cast<int>($unknown_fields$.size()));\n");
}
}
@@ -3517,18 +4022,19 @@ void MessageGenerator::
GenerateByteSize(io::Printer* printer) {
if (descriptor_->options().message_set_wire_format()) {
// Special-case MessageSet.
- printer->Print(
- "size_t $classname$::ByteSizeLong() const {\n"
- "// @@protoc_insertion_point(message_set_byte_size_start:$full_name$)\n"
- " size_t total_size = _extensions_.MessageSetByteSize();\n",
- "classname", classname_, "full_name", descriptor_->full_name());
GOOGLE_CHECK(UseUnknownFieldSet(descriptor_->file(), options_));
- printer->Print(
- "if (_internal_metadata_.have_unknown_fields()) {\n"
- " total_size += ::google::protobuf::internal::WireFormat::\n"
- " ComputeUnknownMessageSetItemsSize(unknown_fields());\n"
- "}\n");
- printer->Print(
+ std::map<string, string> vars;
+ SetUnknkownFieldsVariable(descriptor_, options_, &vars);
+ vars["classname"] = classname_;
+ vars["full_name"] = descriptor_->full_name();
+ printer->Print(vars,
+ "size_t $classname$::ByteSizeLong() const {\n"
+ "// @@protoc_insertion_point(message_set_byte_size_start:$full_name$)\n"
+ " size_t total_size = _extensions_.MessageSetByteSize();\n"
+ " if ($have_unknown_fields$) {\n"
+ " total_size += ::google::protobuf::internal::WireFormat::\n"
+ " ComputeUnknownMessageSetItemsSize($unknown_fields$);\n"
+ " }\n"
" int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);\n"
" GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();\n"
" _cached_size_ = cached_size;\n"
@@ -3582,19 +4088,19 @@ GenerateByteSize(io::Printer* printer) {
"\n");
}
- if (PreserveUnknownFields(descriptor_)) {
- if (UseUnknownFieldSet(descriptor_->file(), options_)) {
- printer->Print(
- "if (_internal_metadata_.have_unknown_fields()) {\n"
- " total_size +=\n"
- " ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(\n"
- " unknown_fields());\n"
- "}\n");
- } else {
- printer->Print(
- "total_size += unknown_fields().size();\n"
- "\n");
- }
+ std::map<string, string> vars;
+ SetUnknkownFieldsVariable(descriptor_, options_, &vars);
+ if (UseUnknownFieldSet(descriptor_->file(), options_)) {
+ printer->Print(vars,
+ "if ($have_unknown_fields$) {\n"
+ " total_size +=\n"
+ " ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(\n"
+ " $unknown_fields$);\n"
+ "}\n");
+ } else {
+ printer->Print(vars,
+ "total_size += $unknown_fields$.size();\n"
+ "\n");
}
// Handle required fields (if any). We expect all of them to be
@@ -3789,6 +4295,11 @@ GenerateByteSize(io::Printer* printer) {
"}\n");
}
+ if (num_weak_fields_) {
+ // TagSize + MessageSize
+ printer->Print("total_size += _weak_field_map_.ByteSizeLong();\n");
+ }
+
// We update _cached_size_ even though this is a const method. In theory,
// this is not thread-compatible, because concurrent writes have undefined
// results. In practice, since any concurrent writes will be writing the
@@ -3846,26 +4357,28 @@ GenerateIsInitialized(io::Printer* printer) {
// TODO(ckennelly): Push this down into a generator?
if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE &&
!ShouldIgnoreRequiredFieldCheck(field, options_) &&
- HasRequiredFields(field->message_type(), options_)) {
+ scc_analyzer_->HasRequiredFields(field->message_type())) {
if (field->is_repeated()) {
printer->Print(
"if (!::google::protobuf::internal::AllAreInitialized(this->$name$()))"
" return false;\n",
"name", FieldName(field));
+ } else if (field->options().weak()) {
+ continue;
} else {
- GOOGLE_CHECK(field->options().weak() || !field->containing_oneof());
- // For weak fields, use the data member (::google::protobuf::Message*) instead
- // of the getter to avoid a link dependency on the weak message type
- // which is only forward declared.
+ GOOGLE_CHECK(!field->containing_oneof());
printer->Print(
"if (has_$name$()) {\n"
" if (!this->$name$_->IsInitialized()) return false;\n"
"}\n",
- "name", FieldName(field));
+ "name", FieldName(field));
}
}
}
-
+ if (num_weak_fields_) {
+ // For Weak fields.
+ printer->Print("if (!_weak_field_map_.IsInitialized()) return false;\n");
+ }
// Go through the oneof fields, emitting a switch if any might have required
// fields.
for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
@@ -3877,7 +4390,7 @@ GenerateIsInitialized(io::Printer* printer) {
if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE &&
!ShouldIgnoreRequiredFieldCheck(field, options_) &&
- HasRequiredFields(field->message_type(), options_)) {
+ scc_analyzer_->HasRequiredFields(field->message_type())) {
has_required_fields = true;
break;
}
@@ -3900,17 +4413,10 @@ GenerateIsInitialized(io::Printer* printer) {
if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE &&
!ShouldIgnoreRequiredFieldCheck(field, options_) &&
- HasRequiredFields(field->message_type(), options_)) {
+ scc_analyzer_->HasRequiredFields(field->message_type())) {
GOOGLE_CHECK(!(field->options().weak() || !field->containing_oneof()));
if (field->options().weak()) {
- // For weak fields, use the data member (::google::protobuf::Message*) instead
- // of the getter to avoid a link dependency on the weak message type
- // which is only forward declared.
- printer->Print(
- "if (has_$name$()) {\n"
- " if (!this->$name$_->IsInitialized()) return false;\n"
- "}\n",
- "name", FieldName(field));
+ // Just skip.
} else {
printer->Print(
"if (has_$name$()) {\n"
@@ -3943,7 +4449,6 @@ GenerateIsInitialized(io::Printer* printer) {
"}\n");
}
-
} // namespace cpp
} // namespace compiler
} // namespace protobuf
diff --git a/src/google/protobuf/compiler/cpp/cpp_message.h b/src/google/protobuf/compiler/cpp/cpp_message.h
index c5efff12..0387f0ca 100644
--- a/src/google/protobuf/compiler/cpp/cpp_message.h
+++ b/src/google/protobuf/compiler/cpp/cpp_message.h
@@ -42,6 +42,8 @@
#include <set>
#include <string>
#include <google/protobuf/compiler/cpp/cpp_field.h>
+#include <google/protobuf/compiler/cpp/cpp_helpers.h>
+#include <google/protobuf/compiler/cpp/cpp_message_layout_helper.h>
#include <google/protobuf/compiler/cpp/cpp_options.h>
namespace google {
@@ -61,11 +63,10 @@ class ExtensionGenerator; // extension.h
class MessageGenerator {
public:
// See generator.cc for the meaning of dllexport_decl.
- MessageGenerator(const Descriptor* descriptor, const Options& options);
+ MessageGenerator(const Descriptor* descriptor, int index_in_file_messages,
+ const Options& options, SCCAnalyzer* scc_analyzer);
~MessageGenerator();
- // Appends the pre-order walk of the nested generators to list.
- void Flatten(std::vector<MessageGenerator*>* list);
// Append the two types of nested generators to the corresponding vector.
void AddGenerators(std::vector<EnumGenerator*>* enum_generators,
std::vector<ExtensionGenerator*>* extension_generators);
@@ -84,33 +85,24 @@ class MessageGenerator {
// Generate definitions of inline methods (placed at the end of the header
// file).
- void GenerateInlineMethods(io::Printer* printer, bool is_inline);
+ void GenerateInlineMethods(io::Printer* printer);
// Dependent methods are always inline.
void GenerateDependentInlineMethods(io::Printer* printer);
// Source file stuff.
- // Generate code which declares all the global descriptor pointers which
- // will be initialized by the methods below.
- void GenerateDescriptorDeclarations(io::Printer* printer);
+ // Generate extra fields
+ void GenerateExtraDefaultFields(io::Printer* printer);
- // Generate code that calls MessageFactory::InternalRegisterGeneratedMessage()
- // for all types.
- void GenerateTypeRegistrations(io::Printer* printer);
-
- // Generates code that allocates the message's default instance.
- void GenerateDefaultInstanceAllocator(io::Printer* printer);
+ // Generates code that creates default instances for fields.
+ void GenerateFieldDefaultInstances(io::Printer* printer);
// Generates code that initializes the message's default instance. This
// is separate from allocating because all default instances must be
// allocated before any can be initialized.
void GenerateDefaultInstanceInitializer(io::Printer* printer);
- // Generates code that should be run when ShutdownProtobufLibrary() is called,
- // to delete all dynamically-allocated objects.
- void GenerateShutdownCode(io::Printer* printer);
-
// Generate all non-inline methods for this class.
void GenerateClassMethods(io::Printer* printer);
@@ -120,12 +112,24 @@ class MessageGenerator {
void GenerateDependentFieldAccessorDeclarations(io::Printer* printer);
void GenerateFieldAccessorDeclarations(io::Printer* printer);
void GenerateDependentFieldAccessorDefinitions(io::Printer* printer);
- void GenerateFieldAccessorDefinitions(io::Printer* printer, bool is_inline);
+ void GenerateFieldAccessorDefinitions(io::Printer* printer);
+
+ // Generate the table-driven parsing array. Returns the number of entries
+ // generated.
+ size_t GenerateParseOffsets(io::Printer* printer);
+ size_t GenerateParseAuxTable(io::Printer* printer);
+ // Generates a ParseTable entry. Returns whether the proto uses table-driven
+ // parsing.
+ bool GenerateParseTable(io::Printer* printer, size_t offset,
+ size_t aux_offset);
// Generate the field offsets array. Returns the a pair of the total numer
// of entries generated and the index of the first has_bit entry.
std::pair<size_t, size_t> GenerateOffsets(io::Printer* printer);
void GenerateSchema(io::Printer* printer, int offset, int has_offset);
+ // For each field generates a table entry describing the field for the
+ // table driven serializer.
+ int GenerateFieldMetadata(io::Printer* printer);
// Generate constructors and destructor.
void GenerateStructors(io::Printer* printer);
@@ -141,6 +145,13 @@ class MessageGenerator {
// Generate the arena-specific destructor code.
void GenerateArenaDestructorCode(io::Printer* printer);
+ // Helper for GenerateClear and others. Optionally emits a condition that
+ // assumes the existence of the cached_has_bits variable, and returns true if
+ // the condition was printed.
+ bool MaybeGenerateOptionalFieldCondition(io::Printer* printer,
+ const FieldDescriptor* field,
+ int expected_has_bits_index);
+
// Generate standard Message methods.
void GenerateClear(io::Printer* printer);
void GenerateOneofClear(io::Printer* printer);
@@ -156,9 +167,14 @@ class MessageGenerator {
void GenerateIsInitialized(io::Printer* printer);
// Helpers for GenerateSerializeWithCachedSizes().
+ //
+ // cached_has_bit_index maintains that:
+ // cached_has_bits = _has_bits_[cached_has_bit_index]
+ // for cached_has_bit_index >= 0
void GenerateSerializeOneField(io::Printer* printer,
const FieldDescriptor* field,
- bool unbounded);
+ bool unbounded,
+ int cached_has_bits_index);
// Generate a switch statement to serialize 2+ fields from the same oneof.
// Or, if fields.size() == 1, just call GenerateSerializeOneField().
void GenerateSerializeOneofFields(
@@ -168,13 +184,12 @@ class MessageGenerator {
io::Printer* printer, const Descriptor::ExtensionRange* range,
bool unbounded);
-
// Generates has_foo() functions and variables for singular field has-bits.
void GenerateSingularFieldHasBits(const FieldDescriptor* field,
std::map<string, string> vars,
io::Printer* printer);
// Generates has_foo() functions and variables for oneof field has-bits.
- void GenerateOneofHasBits(io::Printer* printer, bool is_inline);
+ void GenerateOneofHasBits(io::Printer* printer);
// Generates has_foo_bar() functions for oneof members.
void GenerateOneofMemberHasBits(const FieldDescriptor* field,
const std::map<string, string>& vars,
@@ -182,6 +197,7 @@ class MessageGenerator {
// Generates the clear_foo() method for a field.
void GenerateFieldClear(const FieldDescriptor* field,
const std::map<string, string>& vars,
+ bool is_inline,
io::Printer* printer);
void GenerateConstructorBody(io::Printer* printer,
@@ -192,22 +208,29 @@ class MessageGenerator {
std::vector<uint32> RequiredFieldsBitMask() const;
const Descriptor* descriptor_;
+ int index_in_file_messages_;
string classname_;
Options options_;
FieldGeneratorMap field_generators_;
// optimized_order_ is the order we layout the message's fields in the class.
// This is reused to initialize the fields in-order for cache efficiency.
//
- // optimized_order_ excludes oneof fields.
+ // optimized_order_ excludes oneof fields and weak fields.
std::vector<const FieldDescriptor *> optimized_order_;
std::vector<int> has_bit_indices_;
- google::protobuf::scoped_array<google::protobuf::scoped_ptr<MessageGenerator> > nested_generators_;
+ int max_has_bit_index_;
google::protobuf::scoped_array<google::protobuf::scoped_ptr<EnumGenerator> > enum_generators_;
google::protobuf::scoped_array<google::protobuf::scoped_ptr<ExtensionGenerator> > extension_generators_;
int num_required_fields_;
bool use_dependent_base_;
+ int num_weak_fields_;
+ // table_driven_ indicates the generated message uses table-driven parsing.
+ bool table_driven_;
+
+ google::protobuf::scoped_ptr<MessageLayoutHelper> message_layout_helper_;
- int index_in_metadata_;
+ SCCAnalyzer* scc_analyzer_;
+ string scc_name_;
friend class FileGenerator;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageGenerator);
diff --git a/src/google/protobuf/compiler/cpp/cpp_message_field.cc b/src/google/protobuf/compiler/cpp/cpp_message_field.cc
index 91449657..fe60a283 100644
--- a/src/google/protobuf/compiler/cpp/cpp_message_field.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_message_field.cc
@@ -35,6 +35,7 @@
#include <google/protobuf/compiler/cpp/cpp_message_field.h>
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
#include <google/protobuf/io/printer.h>
+
#include <google/protobuf/stubs/strutil.h>
namespace google {
@@ -44,11 +45,42 @@ namespace cpp {
namespace {
+// When we are generating code for implicit weak fields, we need to insert some
+// additional casts. These functions return the casted expression if
+// implicit_weak_field is true but otherwise return the original expression.
+// Ordinarily a static_cast is enough to cast google::protobuf::MessageLite* to a class
+// deriving from it, but we need a reinterpret_cast in cases where the generated
+// message is forward-declared but its full definition is not visible.
+string StaticCast(const string& type, const string& expression,
+ bool implicit_weak_field) {
+ if (implicit_weak_field) {
+ return "static_cast< " + type + " >(" + expression + ")";
+ } else {
+ return expression;
+ }
+}
+
+string ReinterpretCast(const string& type, const string& expression,
+ bool implicit_weak_field) {
+ if (implicit_weak_field) {
+ return "reinterpret_cast< " + type + " >(" + expression + ")";
+ } else {
+ return expression;
+ }
+}
+
void SetMessageVariables(const FieldDescriptor* descriptor,
std::map<string, string>* variables,
const Options& options) {
SetCommonFieldVariables(descriptor, variables, options);
(*variables)["type"] = FieldMessageTypeName(descriptor);
+ (*variables)["casted_member"] =
+ ReinterpretCast((*variables)["type"] + "*", (*variables)["name"] + "_",
+ IsImplicitWeakField(descriptor, options));
+ (*variables)["type_default_instance"] =
+ DefaultInstanceName(descriptor->message_type());
+ (*variables)["type_reference_function"] =
+ ReferenceFunctionName(descriptor->message_type());
if (descriptor->options().weak() || !descriptor->containing_oneof()) {
(*variables)["non_null_ptr_to_name"] =
StrCat("this->", (*variables)["name"], "_");
@@ -82,7 +114,8 @@ MessageFieldGenerator::MessageFieldGenerator(const FieldDescriptor* descriptor,
const Options& options)
: FieldGenerator(options),
descriptor_(descriptor),
- dependent_field_(options.proto_h && IsFieldDependent(descriptor)) {
+ dependent_field_(options.proto_h && IsFieldDependent(descriptor)),
+ implicit_weak_field_(IsImplicitWeakField(descriptor, options)) {
SetMessageVariables(descriptor, &variables_, options);
}
@@ -90,13 +123,11 @@ MessageFieldGenerator::~MessageFieldGenerator() {}
void MessageFieldGenerator::
GeneratePrivateMembers(io::Printer* printer) const {
- printer->Print(variables_, "$type$* $name$_;\n");
-}
-
-void MessageFieldGenerator::
-GenerateGetterDeclaration(io::Printer* printer) const {
- printer->Print(variables_,
- "$deprecated_attr$const $type$& $name$() const;\n");
+ if (implicit_weak_field_) {
+ printer->Print(variables_, "google::protobuf::MessageLite* $name$_;\n");
+ } else {
+ printer->Print(variables_, "$type$* $name$_;\n");
+ }
}
void MessageFieldGenerator::
@@ -104,48 +135,91 @@ GenerateDependentAccessorDeclarations(io::Printer* printer) const {
if (!dependent_field_) {
return;
}
- // Arena manipulation code is out-of-line in the derived message class.
printer->Print(variables_,
- "$deprecated_attr$$type$* mutable_$name$();\n"
- "$deprecated_attr$$type$* $release_name$();\n"
- "$deprecated_attr$void set_allocated_$name$($type$* $name$);\n");
+ "$deprecated_attr$$type$* ${$mutable_$name$$}$();\n");
+ printer->Annotate("{", "}", descriptor_);
}
void MessageFieldGenerator::
GenerateAccessorDeclarations(io::Printer* printer) const {
- if (SupportsArenas(descriptor_)) {
+ if (SupportsArenas(descriptor_) && !implicit_weak_field_) {
printer->Print(variables_,
"private:\n"
- "void _slow_mutable_$name$();\n");
- if (SupportsArenas(descriptor_->message_type())) {
- printer->Print(variables_,
- "void _slow_set_allocated_$name$(\n"
- " ::google::protobuf::Arena* message_arena, $type$** $name$);\n");
- }
+ "void _slow_mutable_$name$();\n"
+ "public:\n");
+ }
+ if (implicit_weak_field_) {
+ // These private accessors are used by MergeFrom and
+ // MergePartialFromCodedStream, and their purpose is to provide access to
+ // the field without creating a strong dependency on the message type.
printer->Print(variables_,
- "$type$* _slow_$release_name$();\n"
+ "private:\n"
+ "const google::protobuf::MessageLite& _internal_$name$() const;\n"
+ "google::protobuf::MessageLite* _internal_mutable_$name$();\n"
"public:\n");
}
- GenerateGetterDeclaration(printer);
+ printer->Print(variables_,
+ "$deprecated_attr$const $type$& $name$() const;\n");
+ printer->Annotate("name", descriptor_);
+ printer->Print(variables_, "$deprecated_attr$$type$* $release_name$();\n");
+ printer->Annotate("release_name", descriptor_);
if (!dependent_field_) {
printer->Print(variables_,
- "$deprecated_attr$$type$* mutable_$name$();\n"
- "$deprecated_attr$$type$* $release_name$();\n"
- "$deprecated_attr$void set_allocated_$name$($type$* $name$);\n");
+ "$deprecated_attr$$type$* ${$mutable_$name$$}$();\n");
+ printer->Annotate("{", "}", descriptor_);
}
+ printer->Print(variables_,
+ "$deprecated_attr$void ${$set_allocated_$name$$}$"
+ "($type$* $name$);\n");
+ printer->Annotate("{", "}", descriptor_);
if (SupportsArenas(descriptor_)) {
printer->Print(variables_,
- "$deprecated_attr$$type$* unsafe_arena_release_$name$();\n"
- "$deprecated_attr$void unsafe_arena_set_allocated_$name$(\n"
- " $type$* $name$);\n");
+ "$deprecated_attr$void "
+ "${$unsafe_arena_set_allocated_$name$$}$(\n"
+ " $type$* $name$);\n");
+ printer->Annotate("{", "}", descriptor_);
+ printer->Print(
+ variables_,
+ "$deprecated_attr$$type$* ${$unsafe_arena_release_$name$$}$();\n");
+ printer->Annotate("{", "}", descriptor_);
}
}
void MessageFieldGenerator::GenerateNonInlineAccessorDefinitions(
io::Printer* printer) const {
- if (SupportsArenas(descriptor_)) {
+ if (implicit_weak_field_) {
printer->Print(variables_,
- "void $classname$::_slow_mutable_$name$() {\n");
+ "const google::protobuf::MessageLite& $classname$::_internal_$name$() const {\n"
+ " if ($name$_ != NULL) {\n"
+ " return *$name$_;\n"
+ " } else if (&$type_default_instance$ != NULL) {\n"
+ " return *reinterpret_cast<const google::protobuf::MessageLite*>(\n"
+ " &$type_default_instance$);\n"
+ " } else {\n"
+ " return *reinterpret_cast<const google::protobuf::MessageLite*>(\n"
+ " &::google::protobuf::internal::implicit_weak_message_default_instance);\n"
+ " }\n"
+ "}\n");
+ }
+ if (SupportsArenas(descriptor_)) {
+ if (implicit_weak_field_) {
+ printer->Print(variables_,
+ "google::protobuf::MessageLite* $classname$::_internal_mutable_$name$() {\n"
+ " $set_hasbit$\n"
+ " if ($name$_ == NULL) {\n"
+ " if (&$type_default_instance$ == NULL) {\n"
+ " $name$_ = ::google::protobuf::Arena::CreateMessage<\n"
+ " ::google::protobuf::internal::ImplicitWeakMessage>(\n"
+ " GetArenaNoVirtual());\n"
+ " } else {\n"
+ " $name$_ = reinterpret_cast<const google::protobuf::MessageLite*>(\n"
+ " &$type_default_instance$)->New(GetArenaNoVirtual());\n"
+ " }\n"
+ " }\n"
+ " return $name$_;\n");
+ } else {
+ printer->Print(variables_,
+ "void $classname$::_slow_mutable_$name$() {\n");
if (SupportsArenas(descriptor_->message_type())) {
printer->Print(variables_,
" $name$_ = ::google::protobuf::Arena::CreateMessage< $type$ >(\n"
@@ -155,43 +229,10 @@ void MessageFieldGenerator::GenerateNonInlineAccessorDefinitions(
" $name$_ = ::google::protobuf::Arena::Create< $type$ >(\n"
" GetArenaNoVirtual());\n");
}
+ }
printer->Print(variables_,
- "}\n"
- "$type$* $classname$::_slow_$release_name$() {\n"
- " if ($name$_ == NULL) {\n"
- " return NULL;\n"
- " } else {\n"
- " $type$* temp = new $type$(*$name$_);\n"
- " $name$_ = NULL;\n"
- " return temp;\n"
- " }\n"
- "}\n"
- "$type$* $classname$::unsafe_arena_release_$name$() {\n"
- " // @@protoc_insertion_point(field_unsafe_arena_release:$full_name$)\n"
- " $clear_hasbit$\n"
- " $type$* temp = $name$_;\n"
- " $name$_ = NULL;\n"
- " return temp;\n"
"}\n");
- if (SupportsArenas(descriptor_->message_type())) {
- // NOTE: the same logic is mirrored in weak_message_field.cc. Any
- // arena-related semantics changes should be made in both places.
- printer->Print(variables_,
- "void $classname$::_slow_set_allocated_$name$(\n"
- " ::google::protobuf::Arena* message_arena, $type$** $name$) {\n"
- " if (message_arena != NULL && \n"
- " ::google::protobuf::Arena::GetArena(*$name$) == NULL) {\n"
- " message_arena->Own(*$name$);\n"
- " } else if (message_arena !=\n"
- " ::google::protobuf::Arena::GetArena(*$name$)) {\n"
- " $type$* new_$name$ = \n"
- " ::google::protobuf::Arena::CreateMessage< $type$ >(\n"
- " message_arena);\n"
- " new_$name$->CopyFrom(**$name$);\n"
- " *$name$ = new_$name$;\n"
- " }\n"
- "}\n");
- }
+
printer->Print(variables_,
"void $classname$::unsafe_arena_set_allocated_$name$(\n"
" $type$* $name$) {\n"
@@ -209,6 +250,20 @@ void MessageFieldGenerator::GenerateNonInlineAccessorDefinitions(
" // @@protoc_insertion_point(field_unsafe_arena_set_allocated"
":$full_name$)\n"
"}\n");
+ } else if (implicit_weak_field_) {
+ printer->Print(variables_,
+ "google::protobuf::MessageLite* $classname$::_internal_mutable_$name$() {\n"
+ " $set_hasbit$\n"
+ " if ($name$_ == NULL) {\n"
+ " if (&$type_default_instance$ == NULL) {\n"
+ " $name$_ = new ::google::protobuf::internal::ImplicitWeakMessage;\n"
+ " } else {\n"
+ " $name$_ = reinterpret_cast<const google::protobuf::MessageLite*>(\n"
+ " &$type_default_instance$)->New();\n"
+ " }\n"
+ " }\n"
+ " return $name$_;\n"
+ "}\n");
}
}
@@ -224,6 +279,10 @@ GenerateDependentInlineAccessorDefinitions(io::Printer* printer) const {
variables["dependent_classname"] =
DependentBaseClassTemplateName(descriptor_->containing_type()) + "<T>";
variables["this_message"] = DependentBaseDownCast();
+ variables["casted_reference"] =
+ ReinterpretCast(variables["dependent_typename"] + "*&",
+ variables["this_message"] + variables["name"] + "_",
+ implicit_weak_field_);
if (!variables["set_hasbit"].empty()) {
variables["set_hasbit"] =
variables["this_message"] + variables["set_hasbit"];
@@ -236,260 +295,201 @@ GenerateDependentInlineAccessorDefinitions(io::Printer* printer) const {
if (SupportsArenas(descriptor_)) {
printer->Print(variables,
"template <class T>\n"
- "inline $type$* $dependent_classname$::mutable_$name$() {\n"
+ "inline $type$* $dependent_classname$::mutable_$name$() {\n");
+ if (implicit_weak_field_) {
+ printer->Print(variables, " $type_reference_function$();\n");
+ }
+ printer->Print(variables,
" $set_hasbit$\n"
- " $dependent_typename$*& $name$_ = $this_message$$name$_;\n"
- " if ($name$_ == NULL) {\n"
- " $this_message$_slow_mutable_$name$();\n"
- " }\n"
- " // @@protoc_insertion_point(field_mutable:$full_name$)\n"
- " return $name$_;\n"
- "}\n"
- "template <class T>\n"
- "inline $type$* $dependent_classname$::$release_name$() {\n"
- " // @@protoc_insertion_point(field_release:$full_name$)\n"
- " $dependent_typename$*& $name$_ = $this_message$$name$_;\n"
- " $clear_hasbit$\n"
- " if ($this_message$GetArenaNoVirtual() != NULL) {\n"
- " return $this_message$_slow_$release_name$();\n"
- " } else {\n"
- " $dependent_typename$* temp = $name$_;\n"
- " $name$_ = NULL;\n"
- " return temp;\n"
- " }\n"
- "}\n"
- "template <class T>\n"
- "inline void $dependent_classname$::"
- "set_allocated_$name$($type$* $name$) {\n"
- " ::google::protobuf::Arena* message_arena = $this_message$GetArenaNoVirtual();\n"
- " $dependent_typename$*& $name$_ = $this_message$$name$_;\n"
- " if (message_arena == NULL) {\n"
- " delete $name$_;\n"
- " }\n"
- " if ($name$ != NULL) {\n");
- if (SupportsArenas(descriptor_->message_type())) {
- // If we're on an arena and the incoming message is not, simply Own() it
- // rather than copy to the arena -- either way we need a heap dealloc,
- // so we might as well defer it. Otherwise, if incoming message is on a
- // different ownership domain (specific arena, or the heap) than we are,
- // copy to our arena (or heap, as the case may be).
+ " $dependent_typename$*& $name$_ = $casted_reference$;\n"
+ " if ($name$_ == NULL) {\n");
+ if (implicit_weak_field_) {
printer->Print(variables,
- " $this_message$_slow_set_allocated_$name$(message_arena, "
- "&$name$);\n");
+ " $name$_ = reinterpret_cast<$dependent_typename$*>(\n"
+ " reinterpret_cast<const google::protobuf::MessageLite*>(\n"
+ " &$type_default_instance$)->New(\n"
+ " $this_message$GetArenaNoVirtual()));\n");
} else {
printer->Print(variables,
- " if (message_arena != NULL) {\n"
- " message_arena->Own($name$);\n"
- " }\n");
+ " $this_message$_slow_mutable_$name$();\n");
}
printer->Print(variables,
" }\n"
- " $name$_ = $name$;\n"
- " if ($name$) {\n"
- " $set_hasbit$\n"
- " } else {\n"
- " $clear_hasbit$\n"
- " }\n"
- // TODO(dlj): move insertion points to message class.
- " // @@protoc_insertion_point(field_set_allocated:$full_name$)\n"
+ " // @@protoc_insertion_point(field_mutable:$full_name$)\n"
+ " return $name$_;\n"
"}\n");
} else {
printer->Print(variables,
"template <class T>\n"
"inline $type$* $dependent_classname$::mutable_$name$() {\n"
" $set_hasbit$\n"
- " $dependent_typename$*& $name$_ = $this_message$$name$_;\n"
+ " $dependent_typename$*& $name$_ = $casted_reference$;\n"
" if ($name$_ == NULL) {\n"
" $name$_ = new $dependent_typename$;\n"
" }\n"
" // @@protoc_insertion_point(field_mutable:$full_name$)\n"
" return $name$_;\n"
- "}\n"
- "template <class T>\n"
- "inline $type$* $dependent_classname$::$release_name$() {\n"
- " // @@protoc_insertion_point(field_release:$full_name$)\n"
- " $clear_hasbit$\n"
- " $dependent_typename$*& $name$_ = $this_message$$name$_;\n"
- " $dependent_typename$* temp = $name$_;\n"
- " $name$_ = NULL;\n"
- " return temp;\n"
- "}\n"
- "template <class T>\n"
- "inline void $dependent_classname$::"
- "set_allocated_$name$($type$* $name$) {\n"
- " $dependent_typename$*& $name$_ = $this_message$$name$_;\n"
- " delete $name$_;\n");
-
- if (SupportsArenas(descriptor_->message_type())) {
- printer->Print(variables,
- " if ($name$ != NULL && static_cast< $dependent_typename$* >($name$)"
- "->GetArena() != NULL) {\n"
- " $dependent_typename$* new_$name$ = new $dependent_typename$;\n"
- " new_$name$->CopyFrom(*$name$);\n"
- " $name$ = new_$name$;\n"
- " }\n");
- }
-
- printer->Print(variables,
- " $name$_ = $name$;\n"
- " if ($name$) {\n"
- " $set_hasbit$\n"
- " } else {\n"
- " $clear_hasbit$\n"
- " }\n"
- " // @@protoc_insertion_point(field_set_allocated:$full_name$)\n"
"}\n");
}
}
void MessageFieldGenerator::
-GenerateInlineAccessorDefinitions(io::Printer* printer,
- bool is_inline) const {
- if (dependent_field_) {
- // for dependent fields we cannot access its internal_default_instance,
- // because the type is incomplete.
- // TODO(gerbens) deprecate dependent base class.
- std::map<string, string> variables(variables_);
- variables["inline"] = is_inline ? "inline " : "";
- printer->Print(variables,
- "$inline$const $type$& $classname$::$name$() const {\n"
- " // @@protoc_insertion_point(field_get:$full_name$)\n"
- " return $name$_ != NULL ? *$name$_\n"
- " : *internal_default_instance()->$name$_;\n"
- "}\n");
- return;
- }
-
+GenerateInlineAccessorDefinitions(io::Printer* printer) const {
std::map<string, string> variables(variables_);
- variables["inline"] = is_inline ? "inline " : "";
+ variables["const_member"] = ReinterpretCast(
+ "const " + variables["type"] + "*", variables["name"] + "_",
+ implicit_weak_field_);
printer->Print(variables,
- "$inline$const $type$& $classname$::$name$() const {\n"
+ "inline const $type$& $classname$::$name$() const {\n");
+ if (implicit_weak_field_) {
+ printer->Print(variables, " $type_reference_function$();\n");
+ }
+ printer->Print(variables,
+ " const $type$* p = $const_member$;\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
- " return $name$_ != NULL ? *$name$_\n"
- " : *$type$::internal_default_instance();\n"
+ " return p != NULL ? *p : *reinterpret_cast<const $type$*>(\n"
+ " &$type_default_instance$);\n"
"}\n");
+ printer->Print(variables,
+ "inline $type$* $classname$::$release_name$() {\n"
+ " // @@protoc_insertion_point(field_release:$full_name$)\n");
+ if (implicit_weak_field_) {
+ printer->Print(variables, " $type_reference_function$();\n");
+ }
+ printer->Print(variables,
+ " $clear_hasbit$\n"
+ " $type$* temp = $casted_member$;\n");
if (SupportsArenas(descriptor_)) {
printer->Print(variables,
- "$inline$"
- "$type$* $classname$::mutable_$name$() {\n"
- " $set_hasbit$\n"
- " if ($name$_ == NULL) {\n"
- " _slow_mutable_$name$();\n"
- " }\n"
- " // @@protoc_insertion_point(field_mutable:$full_name$)\n"
- " return $name$_;\n"
- "}\n"
- "$inline$"
- "$type$* $classname$::$release_name$() {\n"
- " // @@protoc_insertion_point(field_release:$full_name$)\n"
- " $clear_hasbit$\n"
" if (GetArenaNoVirtual() != NULL) {\n"
- " return _slow_$release_name$();\n"
- " } else {\n"
- " $type$* temp = $name$_;\n"
- " $name$_ = NULL;\n"
- " return temp;\n"
- " }\n"
- "}\n"
- "$inline$ "
- "void $classname$::set_allocated_$name$($type$* $name$) {\n"
- " ::google::protobuf::Arena* message_arena = GetArenaNoVirtual();\n"
- " if (message_arena == NULL) {\n"
- " delete $name$_;\n"
- " }\n"
- " if ($name$ != NULL) {\n");
- if (SupportsArenas(descriptor_->message_type())) {
- // If we're on an arena and the incoming message is not, simply Own() it
- // rather than copy to the arena -- either way we need a heap dealloc,
- // so we might as well defer it. Otherwise, if incoming message is on a
- // different ownership domain (specific arena, or the heap) than we are,
- // copy to our arena (or heap, as the case may be).
- printer->Print(variables,
- " _slow_set_allocated_$name$(message_arena, &$name$);\n");
- } else {
- printer->Print(variables,
- " if (message_arena != NULL) {\n"
- " message_arena->Own($name$);\n"
- " }\n");
- }
+ " temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL);\n"
+ " }\n");
+ }
+ printer->Print(variables,
+ " $name$_ = NULL;\n"
+ " return temp;\n"
+ "}\n");
+
+ if (SupportsArenas(descriptor_)) {
printer->Print(variables,
- " }\n"
- " $name$_ = $name$;\n"
- " if ($name$) {\n"
- " $set_hasbit$\n"
- " } else {\n"
- " $clear_hasbit$\n"
- " }\n"
- " // @@protoc_insertion_point(field_set_allocated:$full_name$)\n"
- "}\n");
- } else {
+ "inline $type$* $classname$::unsafe_arena_release_$name$() {\n"
+ " // @@protoc_insertion_point("
+ "field_unsafe_arena_release:$full_name$)\n");
+ if (implicit_weak_field_) {
+ printer->Print(variables, " $type_reference_function$();\n");
+ }
printer->Print(variables,
- "$inline$"
- "$type$* $classname$::mutable_$name$() {\n"
- " $set_hasbit$\n"
- " if ($name$_ == NULL) {\n"
- " $name$_ = new $type$;\n"
- " }\n"
- " // @@protoc_insertion_point(field_mutable:$full_name$)\n"
- " return $name$_;\n"
- "}\n"
- "$inline$"
- "$type$* $classname$::$release_name$() {\n"
- " // @@protoc_insertion_point(field_release:$full_name$)\n"
" $clear_hasbit$\n"
- " $type$* temp = $name$_;\n"
+ " $type$* temp = $casted_member$;\n"
" $name$_ = NULL;\n"
" return temp;\n"
- "}\n"
- "$inline$"
- "void $classname$::set_allocated_$name$($type$* $name$) {\n"
- " delete $name$_;\n");
+ "}\n");
+ }
- if (SupportsArenas(descriptor_->message_type())) {
+ if (!dependent_field_) {
+ if (SupportsArenas(descriptor_)) {
printer->Print(variables,
- " if ($name$ != NULL && $name$->GetArena() != NULL) {\n"
- " $type$* new_$name$ = new $type$;\n"
- " new_$name$->CopyFrom(*$name$);\n"
- " $name$ = new_$name$;\n"
- " }\n");
+ "inline $type$* $classname$::mutable_$name$() {\n"
+ " $set_hasbit$\n"
+ " if ($name$_ == NULL) {\n");
+ if (implicit_weak_field_) {
+ printer->Print(variables,
+ " _internal_mutable_$name$();\n");
+ } else {
+ printer->Print(variables,
+ " _slow_mutable_$name$();\n");
+ }
+ printer->Print(variables,
+ " }\n"
+ " // @@protoc_insertion_point(field_mutable:$full_name$)\n"
+ " return $casted_member$;\n"
+ "}\n");
+ } else {
+ printer->Print(variables,
+ "inline $type$* $classname$::mutable_$name$() {\n"
+ " $set_hasbit$\n"
+ " if ($name$_ == NULL) {\n"
+ " $name$_ = new $type$;\n"
+ " }\n"
+ " // @@protoc_insertion_point(field_mutable:$full_name$)\n"
+ " return $casted_member$;\n"
+ "}\n");
}
+ }
+
+ // We handle the most common case inline, and delegate less common cases to
+ // the slow fallback function.
+ printer->Print(variables,
+ "inline void $classname$::set_allocated_$name$($type$* $name$) {\n"
+ " ::google::protobuf::Arena* message_arena = GetArenaNoVirtual();\n");
+ printer->Print(variables,
+ " if (message_arena == NULL) {\n");
+ if (IsCrossFileMessage(descriptor_)) {
printer->Print(variables,
- " $name$_ = $name$;\n"
- " if ($name$) {\n"
- " $set_hasbit$\n"
- " } else {\n"
- " $clear_hasbit$\n"
- " }\n"
- " // @@protoc_insertion_point(field_set_allocated:$full_name$)\n"
- "}\n");
+ " delete reinterpret_cast< ::google::protobuf::MessageLite*>($name$_);\n");
+ } else {
+ printer->Print(variables,
+ " delete $name$_;\n");
+ }
+ printer->Print(variables,
+ " }\n"
+ " if ($name$) {\n");
+ if (SupportsArenas(descriptor_->message_type()) &&
+ IsCrossFileMessage(descriptor_)) {
+ // We have to read the arena through the virtual method, because the type
+ // isn't defined in this file.
+ printer->Print(variables,
+ " ::google::protobuf::Arena* submessage_arena =\n"
+ " reinterpret_cast< ::google::protobuf::MessageLite*>($name$)->GetArena();\n");
+ } else if (!SupportsArenas(descriptor_->message_type())) {
+ printer->Print(variables,
+ " ::google::protobuf::Arena* submessage_arena = NULL;\n");
+ } else {
+ printer->Print(variables,
+ " ::google::protobuf::Arena* submessage_arena =\n"
+ " ::google::protobuf::Arena::GetArena($name$);\n");
+ }
+ printer->Print(variables,
+ " if (message_arena != submessage_arena) {\n"
+ " $name$ = ::google::protobuf::internal::GetOwnedMessage(\n"
+ " message_arena, $name$, submessage_arena);\n"
+ " }\n"
+ " $set_hasbit$\n"
+ " } else {\n"
+ " $clear_hasbit$\n"
+ " }\n");
+ if (implicit_weak_field_) {
+ printer->Print(variables,
+ " $name$_ = reinterpret_cast<MessageLite*>($name$);\n");
+ } else {
+ printer->Print(variables,
+ " $name$_ = $name$;\n");
}
+ printer->Print(variables,
+ " // @@protoc_insertion_point(field_set_allocated:$full_name$)\n"
+ "}\n");
}
void MessageFieldGenerator::
GenerateClearingCode(io::Printer* printer) const {
- std::map<string, string> variables(variables_);
- variables["this_message"] = dependent_field_ ? DependentBaseDownCast() : "";
if (!HasFieldPresence(descriptor_->file())) {
// If we don't have has-bits, message presence is indicated only by ptr !=
// NULL. Thus on clear, we need to delete the object.
- printer->Print(variables,
- "if ($this_message$GetArenaNoVirtual() == NULL && "
- "$this_message$$name$_ != NULL) delete $this_message$$name$_;\n"
- "$this_message$$name$_ = NULL;\n");
+ printer->Print(variables_,
+ "if (GetArenaNoVirtual() == NULL && $name$_ != NULL) {\n"
+ " delete $name$_;\n"
+ "}\n"
+ "$name$_ = NULL;\n");
} else {
- printer->Print(variables,
- "if ($this_message$$name$_ != NULL) $this_message$$name$_->"
- "$dependent_type$::Clear();\n");
+ printer->Print(variables_,
+ "if ($name$_ != NULL) $name$_->Clear();\n");
}
}
void MessageFieldGenerator::
GenerateMessageClearingCode(io::Printer* printer) const {
- std::map<string, string> variables(variables_);
- variables["type"] = FieldMessageTypeName(descriptor_);
-
if (!HasFieldPresence(descriptor_->file())) {
// If we don't have has-bits, message presence is indicated only by ptr !=
// NULL. Thus on clear, we need to delete the object.
@@ -501,30 +501,36 @@ GenerateMessageClearingCode(io::Printer* printer) const {
} else {
printer->Print(variables_,
"GOOGLE_DCHECK($name$_ != NULL);\n"
- "$name$_->$type$::Clear();\n");
+ "$name$_->Clear();\n");
}
}
void MessageFieldGenerator::
GenerateMergingCode(io::Printer* printer) const {
- printer->Print(variables_,
- "mutable_$name$()->$type$::MergeFrom(from.$name$());\n");
+ if (implicit_weak_field_) {
+ printer->Print(variables_,
+ "_internal_mutable_$name$()->CheckTypeAndMergeFrom(\n"
+ " from._internal_$name$());\n");
+ } else {
+ printer->Print(variables_,
+ "mutable_$name$()->$type$::MergeFrom(from.$name$());\n");
+ }
}
void MessageFieldGenerator::
GenerateSwappingCode(io::Printer* printer) const {
- printer->Print(variables_, "std::swap($name$_, other->$name$_);\n");
+ printer->Print(variables_, "swap($name$_, other->$name$_);\n");
}
void MessageFieldGenerator::
GenerateDestructorCode(io::Printer* printer) const {
+ // TODO(gerbens) Remove this when we don't need to destruct default instances.
// In google3 a default instance will never get deleted so we don't need to
// worry about that but in opensource protobuf default instances are deleted
// in shutdown process and we need to take special care when handling them.
printer->Print(variables_,
- "if (this != internal_default_instance()) {\n"
- " delete $name$_;\n"
- "}\n");
+ "if (this != internal_default_instance()) ");
+ printer->Print(variables_, "delete $name$_;\n");
}
void MessageFieldGenerator::
@@ -553,23 +559,30 @@ GenerateCopyConstructorCode(io::Printer* printer) const {
// wasn't copied, so both of these methods allocate the submessage on the
// heap.
- printer->Print(variables_,
- "if (from.has_$name$()) {\n"
- " $name$_ = new $type$(*from.$name$_);\n"
- "} else {\n"
- " $name$_ = NULL;\n"
- "}\n");
+ string new_expression = (implicit_weak_field_ ? "from.$name$_->New()"
+ : "new $type$(*from.$name$_)");
+ string output =
+ "if (from.has_$name$()) {\n"
+ " $name$_ = " + new_expression + ";\n"
+ "} else {\n"
+ " $name$_ = NULL;\n"
+ "}\n";
+ printer->Print(variables_, output.c_str());
}
void MessageFieldGenerator::
GenerateMergeFromCodedStream(io::Printer* printer) const {
- if (descriptor_->type() == FieldDescriptor::TYPE_MESSAGE) {
+ if (implicit_weak_field_) {
+ printer->Print(variables_,
+ "DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(\n"
+ " input, _internal_mutable_$name$()));\n");
+ } else if (descriptor_->type() == FieldDescriptor::TYPE_MESSAGE) {
printer->Print(variables_,
- "DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(\n"
+ "DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(\n"
" input, mutable_$name$()));\n");
} else {
printer->Print(variables_,
- "DO_(::google::protobuf::internal::WireFormatLite::ReadGroupNoVirtual(\n"
+ "DO_(::google::protobuf::internal::WireFormatLite::ReadGroup(\n"
" $number$, input, mutable_$name$()));\n");
}
}
@@ -585,15 +598,15 @@ void MessageFieldGenerator::
GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const {
printer->Print(variables_,
"target = ::google::protobuf::internal::WireFormatLite::\n"
- " InternalWrite$declared_type$NoVirtualToArray(\n"
- " $number$, *$non_null_ptr_to_name$, false, target);\n");
+ " InternalWrite$declared_type$ToArray(\n"
+ " $number$, *$non_null_ptr_to_name$, deterministic, target);\n");
}
void MessageFieldGenerator::
GenerateByteSize(io::Printer* printer) const {
printer->Print(variables_,
"total_size += $tag_size$ +\n"
- " ::google::protobuf::internal::WireFormatLite::$declared_type$SizeNoVirtual(\n"
+ " ::google::protobuf::internal::WireFormatLite::$declared_type$Size(\n"
" *$non_null_ptr_to_name$);\n");
}
@@ -609,29 +622,38 @@ MessageOneofFieldGenerator(const FieldDescriptor* descriptor,
MessageOneofFieldGenerator::~MessageOneofFieldGenerator() {}
-
-void MessageOneofFieldGenerator::
-GenerateDependentAccessorDeclarations(io::Printer* printer) const {
- // Oneof field getters must be dependent as they call default_instance().
- // Otherwise, the logic is the same as MessageFields.
- if (!dependent_field_) {
- return;
- }
+void MessageOneofFieldGenerator::GenerateNonInlineAccessorDefinitions(
+ io::Printer* printer) const {
printer->Print(variables_,
- "$deprecated_attr$const $type$& $name$() const;\n");
- MessageFieldGenerator::GenerateDependentAccessorDeclarations(printer);
-}
-
-void MessageOneofFieldGenerator::
-GenerateGetterDeclaration(io::Printer* printer) const {
- // Oneof field getters must be dependent as they call default_instance().
- // Unlike MessageField, this means there is no (non-dependent) getter to
- // generate.
- if (dependent_field_) {
- return;
+ "void $classname$::set_allocated_$name$($type$* $name$) {\n"
+ " ::google::protobuf::Arena* message_arena = GetArenaNoVirtual();\n"
+ " clear_$oneof_name$();\n"
+ " if ($name$) {\n");
+ if (SupportsArenas(descriptor_->message_type()) &&
+ descriptor_->file() != descriptor_->message_type()->file()) {
+ // We have to read the arena through the virtual method, because the type
+ // isn't defined in this file.
+ printer->Print(variables_,
+ " ::google::protobuf::Arena* submessage_arena =\n"
+ " reinterpret_cast< ::google::protobuf::MessageLite*>($name$)->GetArena();\n");
+ } else if (!SupportsArenas(descriptor_->message_type())) {
+ printer->Print(variables_,
+ " ::google::protobuf::Arena* submessage_arena = NULL;\n");
+ } else {
+ printer->Print(variables_,
+ " ::google::protobuf::Arena* submessage_arena =\n"
+ " ::google::protobuf::Arena::GetArena($name$);\n");
}
printer->Print(variables_,
- "$deprecated_attr$const $type$& $name$() const;\n");
+ " if (message_arena != submessage_arena) {\n"
+ " $name$ = ::google::protobuf::internal::GetOwnedMessage(\n"
+ " message_arena, $name$, submessage_arena);\n"
+ " }\n"
+ " set_has_$name$();\n"
+ " $oneof_prefix$$name$_ = $name$;\n"
+ " }\n"
+ " // @@protoc_insertion_point(field_set_allocated:$full_name$)\n"
+ "}\n");
}
void MessageOneofFieldGenerator::
@@ -642,7 +664,6 @@ GenerateDependentInlineAccessorDefinitions(io::Printer* printer) const {
return;
}
std::map<string, string> variables(variables_);
- variables["inline"] = "inline ";
variables["dependent_classname"] =
DependentBaseClassTemplateName(descriptor_->containing_type()) + "<T>";
variables["this_message"] = "reinterpret_cast<T*>(this)->";
@@ -656,13 +677,9 @@ GenerateDependentInlineAccessorDefinitions(io::Printer* printer) const {
}
void MessageOneofFieldGenerator::
-GenerateInlineAccessorDefinitions(io::Printer* printer,
- bool is_inline) const {
- if (dependent_base_) {
- return;
- }
+GenerateInlineAccessorDefinitions(io::Printer* printer) const {
+
std::map<string, string> variables(variables_);
- variables["inline"] = is_inline ? "inline " : "";
variables["dependent_classname"] = variables["classname"];
variables["this_message"] = "";
variables["this_const_message"] = "";
@@ -670,35 +687,77 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
variables["field_member"] =
variables["oneof_prefix"] + variables["name"] + "_";
variables["dependent_type"] = variables["type"];
- InternalGenerateInlineAccessorDefinitions(variables, printer);
-}
-void MessageOneofFieldGenerator::
-GenerateNonInlineAccessorDefinitions(io::Printer* printer) const {
- std::map<string, string> variables(variables_);
- variables["field_member"] =
- variables["oneof_prefix"] + variables["name"] + "_";
-
- //printer->Print(variables,
-}
+ printer->Print(variables,
+ "inline $type$* $classname$::$release_name$() {\n"
+ " // @@protoc_insertion_point(field_release:$full_name$)\n"
+ " if ($this_message$has_$name$()) {\n"
+ " $this_message$clear_has_$oneof_name$();\n"
+ " $type$* temp = $field_member$;\n");
+ if (SupportsArenas(descriptor_)) {
+ printer->Print(variables,
+ " if ($this_message$GetArenaNoVirtual() != NULL) {\n"
+ " temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL);\n"
+ " }\n");
+ }
+ printer->Print(variables,
+ " $field_member$ = NULL;\n"
+ " return temp;\n"
+ " } else {\n"
+ " return NULL;\n"
+ " }\n"
+ "}\n");
-void MessageOneofFieldGenerator::InternalGenerateInlineAccessorDefinitions(
- const std::map<string, string>& variables, io::Printer* printer) const {
printer->Print(variables,
- "$tmpl$"
- "$inline$ "
- "const $type$& $dependent_classname$::$name$() const {\n"
+ "inline const $type$& $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" return $this_const_message$has_$name$()\n"
" ? *$this_const_message$$oneof_prefix$$name$_\n"
- " : $dependent_type$::default_instance();\n"
+ " : *reinterpret_cast< $type$*>(&$type_default_instance$);\n"
"}\n");
if (SupportsArenas(descriptor_)) {
printer->Print(variables,
+ "inline $type$* $dependent_classname$::unsafe_arena_release_$name$() {\n"
+ " // @@protoc_insertion_point(field_unsafe_arena_release"
+ ":$full_name$)\n"
+ " if ($this_message$has_$name$()) {\n"
+ " $this_message$clear_has_$oneof_name$();\n"
+ " $type$* temp = $this_message$$oneof_prefix$$name$_;\n"
+ " $this_message$$oneof_prefix$$name$_ = NULL;\n"
+ " return temp;\n"
+ " } else {\n"
+ " return NULL;\n"
+ " }\n"
+ "}\n"
+ "inline void $classname$::unsafe_arena_set_allocated_$name$"
+ "($type$* $name$) {\n"
+ // We rely on the oneof clear method to free the earlier contents of this
+ // oneof. We can directly use the pointer we're given to set the new
+ // value.
+ " clear_$oneof_name$();\n"
+ " if ($name$) {\n"
+ " set_has_$name$();\n"
+ " $oneof_prefix$$name$_ = $name$;\n"
+ " }\n"
+ " // @@protoc_insertion_point(field_unsafe_arena_set_allocated:"
+ "$full_name$)\n"
+ "}\n");
+ }
+
+ if (dependent_base_) {
+ return;
+ }
+
+ InternalGenerateInlineAccessorDefinitions(variables, printer);
+}
+
+void MessageOneofFieldGenerator::InternalGenerateInlineAccessorDefinitions(
+ const std::map<string, string>& variables, io::Printer* printer) const {
+ if (SupportsArenas(descriptor_)) {
+ printer->Print(variables,
"$tmpl$"
- "$inline$"
- "$type$* $dependent_classname$::mutable_$name$() {\n"
+ "inline $type$* $dependent_classname$::mutable_$name$() {\n"
" if (!$this_message$has_$name$()) {\n"
" $this_message$clear_$oneof_name$();\n"
" $this_message$set_has_$name$();\n");
@@ -717,95 +776,11 @@ void MessageOneofFieldGenerator::InternalGenerateInlineAccessorDefinitions(
" }\n"
" // @@protoc_insertion_point(field_mutable:$full_name$)\n"
" return $field_member$;\n"
- "}\n"
- "$tmpl$"
- "$inline$"
- "$type$* $dependent_classname$::$release_name$() {\n"
- " // @@protoc_insertion_point(field_release:$full_name$)\n"
- " if ($this_message$has_$name$()) {\n"
- " $this_message$clear_has_$oneof_name$();\n"
- " if ($this_message$GetArenaNoVirtual() != NULL) {\n"
- // N.B.: safe to use the underlying field pointer here because we are sure
- // that it is non-NULL (because has_$name$() returned true).
- " $dependent_typename$* temp = "
- "new $dependent_typename$(*$field_member$);\n"
- " $field_member$ = NULL;\n"
- " return temp;\n"
- " } else {\n"
- " $dependent_typename$* temp = $field_member$;\n"
- " $field_member$ = NULL;\n"
- " return temp;\n"
- " }\n"
- " } else {\n"
- " return NULL;\n"
- " }\n"
- "}\n"
- "$tmpl$"
- "$inline$"
- "void $dependent_classname$::"
- "set_allocated_$name$($type$* $name$) {\n"
- " $this_message$clear_$oneof_name$();\n"
- " if ($name$) {\n");
-
- if (SupportsArenas(descriptor_->message_type())) {
- printer->Print(variables,
- // If incoming message is on the heap and we are on an arena, just Own()
- // it (see above). If it's on a different arena than we are or one of us
- // is on the heap, we make a copy to our arena/heap.
- " if ($this_message$GetArenaNoVirtual() != NULL &&\n"
- " ::google::protobuf::Arena::GetArena($name$) == NULL) {\n"
- " $this_message$GetArenaNoVirtual()->Own($name$);\n"
- " } else if ($this_message$GetArenaNoVirtual() !=\n"
- " ::google::protobuf::Arena::GetArena($name$)) {\n"
- " $dependent_typename$* new_$name$ = \n"
- " ::google::protobuf::Arena::CreateMessage< $dependent_typename$ >(\n"
- " $this_message$GetArenaNoVirtual());\n"
- " new_$name$->CopyFrom(*$name$);\n"
- " $name$ = new_$name$;\n"
- " }\n");
- } else {
- printer->Print(variables,
- " if ($this_message$GetArenaNoVirtual() != NULL) {\n"
- " $this_message$GetArenaNoVirtual()->Own($name$);\n"
- " }\n");
- }
-
- printer->Print(variables,
- " $this_message$set_has_$name$();\n"
- " $field_member$ = $name$;\n"
- " }\n"
- " // @@protoc_insertion_point(field_set_allocated:$full_name$)\n"
- "}\n"
- "$inline$ $type$* $classname$::unsafe_arena_release_$name$() {\n"
- " // @@protoc_insertion_point(field_unsafe_arena_release"
- ":$full_name$)\n"
- " if (has_$name$()) {\n"
- " clear_has_$oneof_name$();\n"
- " $type$* temp = $oneof_prefix$$name$_;\n"
- " $oneof_prefix$$name$_ = NULL;\n"
- " return temp;\n"
- " } else {\n"
- " return NULL;\n"
- " }\n"
- "}\n"
- "$inline$ void $classname$::unsafe_arena_set_allocated_$name$"
- "($type$* $name$) {\n"
- // We rely on the oneof clear method to free the earlier contents of this
- // oneof. We can directly use the pointer we're given to set the new
- // value.
- " clear_$oneof_name$();\n"
- " if ($name$) {\n"
- " set_has_$name$();\n"
- " $oneof_prefix$$name$_ = $name$;\n"
- " }\n"
- " // @@protoc_insertion_point(field_unsafe_arena_set_allocated:"
- "$full_name$)\n"
"}\n");
} else {
printer->Print(variables,
"$tmpl$"
- "$inline$"
- "$type$* $dependent_classname$::mutable_$name$() {\n"
+ "inline $type$* $dependent_classname$::mutable_$name$() {\n"
" if (!$this_message$has_$name$()) {\n"
" $this_message$clear_$oneof_name$();\n"
" $this_message$set_has_$name$();\n"
@@ -813,56 +788,20 @@ void MessageOneofFieldGenerator::InternalGenerateInlineAccessorDefinitions(
" }\n"
" // @@protoc_insertion_point(field_mutable:$full_name$)\n"
" return $field_member$;\n"
- "}\n"
- "$tmpl$"
- "$inline$"
- "$type$* $dependent_classname$::$release_name$() {\n"
- " // @@protoc_insertion_point(field_release:$full_name$)\n"
- " if ($this_message$has_$name$()) {\n"
- " $this_message$clear_has_$oneof_name$();\n"
- " $dependent_typename$* temp = $field_member$;\n"
- " $field_member$ = NULL;\n"
- " return temp;\n"
- " } else {\n"
- " return NULL;\n"
- " }\n"
- "}\n"
- "$tmpl$"
- "$inline$"
- "void $dependent_classname$::"
- "set_allocated_$name$($type$* $name$) {\n"
- " $this_message$clear_$oneof_name$();\n"
- " if ($name$) {\n");
- if (SupportsArenas(descriptor_->message_type())) {
- printer->Print(variables,
- " if (static_cast< $dependent_typename$*>($name$)->"
- "GetArena() != NULL) {\n"
- " $dependent_typename$* new_$name$ = new $dependent_typename$;\n"
- " new_$name$->CopyFrom(*$name$);\n"
- " $name$ = new_$name$;\n"
- " }\n");
- }
- printer->Print(variables,
- " $this_message$set_has_$name$();\n"
- " $field_member$ = $name$;\n"
- " }\n"
- " // @@protoc_insertion_point(field_set_allocated:$full_name$)\n"
"}\n");
}
}
void MessageOneofFieldGenerator::
GenerateClearingCode(io::Printer* printer) const {
- std::map<string, string> variables(variables_);
- variables["this_message"] = dependent_field_ ? DependentBaseDownCast() : "";
if (SupportsArenas(descriptor_)) {
- printer->Print(variables,
- "if ($this_message$GetArenaNoVirtual() == NULL) {\n"
- " delete $this_message$$oneof_prefix$$name$_;\n"
+ printer->Print(variables_,
+ "if (GetArenaNoVirtual() == NULL) {\n"
+ " delete $oneof_prefix$$name$_;\n"
"}\n");
} else {
- printer->Print(variables,
- "delete $this_message$$oneof_prefix$$name$_;\n");
+ printer->Print(variables_,
+ "delete $oneof_prefix$$name$_;\n");
}
}
@@ -910,16 +849,20 @@ GeneratePrivateMembers(io::Printer* printer) const {
void RepeatedMessageFieldGenerator::
InternalGenerateTypeDependentAccessorDeclarations(io::Printer* printer) const {
printer->Print(variables_,
- "$deprecated_attr$$type$* mutable_$name$(int index);\n"
- "$deprecated_attr$$type$* add_$name$();\n");
+ "$deprecated_attr$$type$* ${$mutable_$name$$}$(int index);\n");
+ printer->Annotate("{", "}", descriptor_);
+ printer->Print(variables_, "$deprecated_attr$$type$* ${$add_$name$$}$();\n");
+ printer->Annotate("{", "}", descriptor_);
if (dependent_getter_) {
printer->Print(variables_,
"$deprecated_attr$const ::google::protobuf::RepeatedPtrField< $type$ >&\n"
" $name$() const;\n");
+ printer->Annotate("name", descriptor_);
}
printer->Print(variables_,
- "$deprecated_attr$::google::protobuf::RepeatedPtrField< $type$ >*\n"
- " mutable_$name$();\n");
+ "$deprecated_attr$::google::protobuf::RepeatedPtrField< $type$ >*\n"
+ " ${$mutable_$name$$}$();\n");
+ printer->Annotate("{", "}", descriptor_);
}
void RepeatedMessageFieldGenerator::
@@ -927,6 +870,7 @@ GenerateDependentAccessorDeclarations(io::Printer* printer) const {
if (dependent_getter_) {
printer->Print(variables_,
"$deprecated_attr$const $type$& $name$(int index) const;\n");
+ printer->Annotate("name", descriptor_);
}
if (dependent_field_) {
InternalGenerateTypeDependentAccessorDeclarations(printer);
@@ -938,6 +882,7 @@ GenerateAccessorDeclarations(io::Printer* printer) const {
if (!dependent_getter_) {
printer->Print(variables_,
"$deprecated_attr$const $type$& $name$(int index) const;\n");
+ printer->Annotate("name", descriptor_);
}
if (!dependent_field_) {
InternalGenerateTypeDependentAccessorDeclarations(printer);
@@ -946,6 +891,7 @@ GenerateAccessorDeclarations(io::Printer* printer) const {
printer->Print(variables_,
"$deprecated_attr$const ::google::protobuf::RepeatedPtrField< $type$ >&\n"
" $name$() const;\n");
+ printer->Annotate("name", descriptor_);
}
}
@@ -1006,49 +952,39 @@ GenerateDependentInlineAccessorDefinitions(io::Printer* printer) const {
}
void RepeatedMessageFieldGenerator::
-GenerateInlineAccessorDefinitions(io::Printer* printer,
- bool is_inline) const {
- std::map<string, string> variables(variables_);
- variables["inline"] = is_inline ? "inline " : "";
-
+GenerateInlineAccessorDefinitions(io::Printer* printer) const {
if (!dependent_getter_) {
- printer->Print(variables,
- "$inline$"
- "const $type$& $classname$::$name$(int index) const {\n"
+ printer->Print(variables_,
+ "inline const $type$& $classname$::$name$(int index) const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" return $name$_.$cppget$(index);\n"
"}\n");
}
if (!dependent_field_) {
- printer->Print(variables,
- "$inline$"
- "$type$* $classname$::mutable_$name$(int index) {\n"
+ printer->Print(variables_,
+ "inline $type$* $classname$::mutable_$name$(int index) {\n"
// TODO(dlj): move insertion points
" // @@protoc_insertion_point(field_mutable:$full_name$)\n"
" return $name$_.Mutable(index);\n"
"}\n"
- "$inline$"
- "$type$* $classname$::add_$name$() {\n"
+ "inline $type$* $classname$::add_$name$() {\n"
" // @@protoc_insertion_point(field_add:$full_name$)\n"
" return $name$_.Add();\n"
"}\n");
}
-
if (!dependent_field_) {
- printer->Print(variables,
- "$inline$"
- "::google::protobuf::RepeatedPtrField< $type$ >*\n"
+ printer->Print(variables_,
+ "inline ::google::protobuf::RepeatedPtrField< $type$ >*\n"
"$classname$::mutable_$name$() {\n"
" // @@protoc_insertion_point(field_mutable_list:$full_name$)\n"
" return &$name$_;\n"
"}\n");
}
if (!dependent_getter_) {
- printer->Print(variables,
- "$inline$"
- "const ::google::protobuf::RepeatedPtrField< $type$ >&\n"
+ printer->Print(variables_,
+ "inline const ::google::protobuf::RepeatedPtrField< $type$ >&\n"
"$classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_list:$full_name$)\n"
" return $name$_;\n"
@@ -1058,9 +994,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
void RepeatedMessageFieldGenerator::
GenerateClearingCode(io::Printer* printer) const {
- std::map<string, string> variables(variables_);
- variables["this_message"] = dependent_field_ ? DependentBaseDownCast() : "";
- printer->Print(variables, "$this_message$$name$_.Clear();\n");
+ printer->Print(variables_, "$name$_.Clear();\n");
}
void RepeatedMessageFieldGenerator::
@@ -1070,7 +1004,7 @@ GenerateMergingCode(io::Printer* printer) const {
void RepeatedMessageFieldGenerator::
GenerateSwappingCode(io::Printer* printer) const {
- printer->Print(variables_, "$name$_.UnsafeArenaSwap(&other->$name$_);\n");
+ printer->Print(variables_, "$name$_.InternalSwap(&other->$name$_);\n");
}
void RepeatedMessageFieldGenerator::
@@ -1083,32 +1017,32 @@ GenerateMergeFromCodedStream(io::Printer* printer) const {
if (descriptor_->type() == FieldDescriptor::TYPE_MESSAGE) {
printer->Print(variables_,
"DO_(::google::protobuf::internal::WireFormatLite::"
- "ReadMessageNoVirtualNoRecursionDepth(\n"
- " input, add_$name$()));\n");
+ "ReadMessage(input, add_$name$()));\n");
} else {
printer->Print(variables_,
"DO_(::google::protobuf::internal::WireFormatLite::"
- "ReadGroupNoVirtualNoRecursionDepth(\n"
- " $number$, input, add_$name$()));\n");
+ "ReadGroup($number$, input, add_$name$()));\n");
}
}
void RepeatedMessageFieldGenerator::
GenerateSerializeWithCachedSizes(io::Printer* printer) const {
printer->Print(variables_,
- "for (unsigned int i = 0, n = this->$name$_size(); i < n; i++) {\n"
+ "for (unsigned int i = 0,\n"
+ " n = static_cast<unsigned int>(this->$name$_size()); i < n; i++) {\n"
" ::google::protobuf::internal::WireFormatLite::Write$stream_writer$(\n"
- " $number$, this->$name$(i), output);\n"
+ " $number$, this->$name$(static_cast<int>(i)), output);\n"
"}\n");
}
void RepeatedMessageFieldGenerator::
GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const {
printer->Print(variables_,
- "for (unsigned int i = 0, n = this->$name$_size(); i < n; i++) {\n"
+ "for (unsigned int i = 0,\n"
+ " n = static_cast<unsigned int>(this->$name$_size()); i < n; i++) {\n"
" target = ::google::protobuf::internal::WireFormatLite::\n"
- " InternalWrite$declared_type$NoVirtualToArray(\n"
- " $number$, this->$name$(i), false, target);\n"
+ " InternalWrite$declared_type$ToArray(\n"
+ " $number$, this->$name$(static_cast<int>(i)), deterministic, target);\n"
"}\n");
}
@@ -1116,14 +1050,14 @@ void RepeatedMessageFieldGenerator::
GenerateByteSize(io::Printer* printer) const {
printer->Print(variables_,
"{\n"
- " unsigned int count = this->$name$_size();\n");
+ " unsigned int count = static_cast<unsigned int>(this->$name$_size());\n");
printer->Indent();
printer->Print(variables_,
"total_size += $tag_size$UL * count;\n"
"for (unsigned int i = 0; i < count; i++) {\n"
" total_size +=\n"
- " ::google::protobuf::internal::WireFormatLite::$declared_type$SizeNoVirtual(\n"
- " this->$name$(i));\n"
+ " ::google::protobuf::internal::WireFormatLite::$declared_type$Size(\n"
+ " this->$name$(static_cast<int>(i)));\n"
"}\n");
printer->Outdent();
printer->Print("}\n");
diff --git a/src/google/protobuf/compiler/cpp/cpp_message_field.h b/src/google/protobuf/compiler/cpp/cpp_message_field.h
index 9ca91153..3be505e3 100644
--- a/src/google/protobuf/compiler/cpp/cpp_message_field.h
+++ b/src/google/protobuf/compiler/cpp/cpp_message_field.h
@@ -44,6 +44,8 @@ namespace protobuf {
namespace compiler {
namespace cpp {
+bool IsImplicitWeakField(const FieldDescriptor* field, const Options& options);
+
class MessageFieldGenerator : public FieldGenerator {
public:
MessageFieldGenerator(const FieldDescriptor* descriptor,
@@ -55,8 +57,7 @@ class MessageFieldGenerator : public FieldGenerator {
void GenerateDependentAccessorDeclarations(io::Printer* printer) const;
void GenerateAccessorDeclarations(io::Printer* printer) const;
void GenerateDependentInlineAccessorDefinitions(io::Printer* printer) const;
- void GenerateInlineAccessorDefinitions(io::Printer* printer,
- bool is_inline) const;
+ void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateNonInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateMessageClearingCode(io::Printer* printer) const;
@@ -71,13 +72,9 @@ class MessageFieldGenerator : public FieldGenerator {
void GenerateByteSize(io::Printer* printer) const;
protected:
- void GenerateArenaManipulationCode(const std::map<string, string>& variables,
- io::Printer* printer) const;
-
- virtual void GenerateGetterDeclaration(io::Printer* printer) const;
-
const FieldDescriptor* descriptor_;
const bool dependent_field_;
+ const bool implicit_weak_field_;
std::map<string, string> variables_;
private:
@@ -91,10 +88,8 @@ class MessageOneofFieldGenerator : public MessageFieldGenerator {
~MessageOneofFieldGenerator();
// implements FieldGenerator ---------------------------------------
- void GenerateDependentAccessorDeclarations(io::Printer* printer) const;
void GenerateDependentInlineAccessorDefinitions(io::Printer* printer) const;
- void GenerateInlineAccessorDefinitions(io::Printer* printer,
- bool is_inline) const;
+ void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateNonInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
@@ -105,9 +100,6 @@ class MessageOneofFieldGenerator : public MessageFieldGenerator {
void GenerateDestructorCode(io::Printer* printer) const;
void GenerateConstructorCode(io::Printer* printer) const;
- protected:
- void GenerateGetterDeclaration(io::Printer* printer) const;
-
private:
void InternalGenerateInlineAccessorDefinitions(
const std::map<string, string>& variables, io::Printer* printer) const;
@@ -127,8 +119,7 @@ class RepeatedMessageFieldGenerator : public FieldGenerator {
void GenerateDependentAccessorDeclarations(io::Printer* printer) const;
void GenerateAccessorDeclarations(io::Printer* printer) const;
void GenerateDependentInlineAccessorDefinitions(io::Printer* printer) const;
- void GenerateInlineAccessorDefinitions(io::Printer* printer,
- bool is_inline) const;
+ void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateMergingCode(io::Printer* printer) const;
void GenerateSwappingCode(io::Printer* printer) const;
diff --git a/src/google/protobuf/compiler/cpp/cpp_message_layout_helper.h b/src/google/protobuf/compiler/cpp/cpp_message_layout_helper.h
new file mode 100644
index 00000000..d502a6f0
--- /dev/null
+++ b/src/google/protobuf/compiler/cpp/cpp_message_layout_helper.h
@@ -0,0 +1,61 @@
+// 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: seongkim@google.com (Seong Beom Kim)
+// Based on original Protocol Buffers design by
+// Sanjay Ghemawat, Jeff Dean, and others.
+
+#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_LAYOUT_HELPER_H__
+#define GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_LAYOUT_HELPER_H__
+
+#include <google/protobuf/compiler/cpp/cpp_options.h>
+#include <google/protobuf/descriptor.h>
+
+namespace google {
+namespace protobuf {
+namespace compiler {
+namespace cpp {
+
+// Provides an abstract interface to optimize message layout
+// by rearranging the fields of a message.
+class MessageLayoutHelper {
+ public:
+ virtual ~MessageLayoutHelper() {}
+
+ virtual void OptimizeLayout(std::vector<const FieldDescriptor*>* fields,
+ const Options& options) = 0;
+};
+
+} // namespace cpp
+} // namespace compiler
+} // namespace protobuf
+
+} // namespace google
+#endif // GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_LAYOUT_HELPER_H__
diff --git a/src/google/protobuf/compiler/cpp/cpp_move_unittest.cc b/src/google/protobuf/compiler/cpp/cpp_move_unittest.cc
new file mode 100644
index 00000000..f72a7d60
--- /dev/null
+++ b/src/google/protobuf/compiler/cpp/cpp_move_unittest.cc
@@ -0,0 +1,169 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#include <google/protobuf/stubs/common.h>
+#include <google/protobuf/test_util.h>
+#include <google/protobuf/unittest.pb.h>
+#include <gtest/gtest.h>
+
+#if LANG_CXX11
+#include <google/protobuf/stubs/type_traits.h>
+#endif
+
+namespace google {
+namespace protobuf {
+namespace compiler {
+namespace cpp {
+
+// Can't use an anonymous namespace here due to brokenness of Tru64 compiler.
+namespace cpp_unittest {
+
+// Moves are enabled only when compiling with a C++11 compiler or newer.
+#if LANG_CXX11
+
+TEST(MovableMessageTest, MoveConstructor) {
+ protobuf_unittest::TestAllTypes message1;
+ TestUtil::SetAllFields(&message1);
+ const auto* nested = &message1.optional_nested_message();
+
+ protobuf_unittest::TestAllTypes message2(std::move(message1));
+ TestUtil::ExpectAllFieldsSet(message2);
+
+ // Check if the optional_nested_message was actually moved (and not just
+ // copied).
+ EXPECT_EQ(nested, &message2.optional_nested_message());
+ EXPECT_NE(nested, &message1.optional_nested_message());
+}
+
+TEST(MovableMessageTest, MoveAssignmentOperator) {
+ protobuf_unittest::TestAllTypes message1;
+ TestUtil::SetAllFields(&message1);
+ const auto* nested = &message1.optional_nested_message();
+
+ protobuf_unittest::TestAllTypes message2;
+ message2 = std::move(message1);
+ TestUtil::ExpectAllFieldsSet(message2);
+
+ // Check if the optional_nested_message was actually moved (and not just
+ // copied).
+ EXPECT_EQ(nested, &message2.optional_nested_message());
+ EXPECT_NE(nested, &message1.optional_nested_message());
+}
+
+TEST(MovableMessageTest, SelfMoveAssignment) {
+ // The `self` reference is necessary to defeat -Wself-move.
+ protobuf_unittest::TestAllTypes message, &self = message;
+ TestUtil::SetAllFields(&message);
+ message = std::move(self);
+ TestUtil::ExpectAllFieldsSet(message);
+}
+
+TEST(MovableMessageTest, MoveSameArena) {
+ Arena arena;
+
+ auto* message1_on_arena =
+ Arena::CreateMessage<protobuf_unittest::TestAllTypes>(&arena);
+ TestUtil::SetAllFields(message1_on_arena);
+ const auto* nested = &message1_on_arena->optional_nested_message();
+
+ auto* message2_on_arena =
+ Arena::CreateMessage<protobuf_unittest::TestAllTypes>(&arena);
+
+ // Moving messages on the same arena should lead to swapped pointers.
+ *message2_on_arena = std::move(*message1_on_arena);
+ EXPECT_EQ(nested, &message2_on_arena->optional_nested_message());
+}
+
+TEST(MovableMessageTest, MoveDifferentArenas) {
+ Arena arena1, arena2;
+
+ auto* message1_on_arena =
+ Arena::CreateMessage<protobuf_unittest::TestAllTypes>(&arena1);
+ TestUtil::SetAllFields(message1_on_arena);
+ const auto* nested = &message1_on_arena->optional_nested_message();
+
+ auto* message2_on_arena =
+ Arena::CreateMessage<protobuf_unittest::TestAllTypes>(&arena2);
+
+ // Moving messages on two different arenas should lead to a copy.
+ *message2_on_arena = std::move(*message1_on_arena);
+ EXPECT_NE(nested, &message2_on_arena->optional_nested_message());
+ TestUtil::ExpectAllFieldsSet(*message1_on_arena);
+ TestUtil::ExpectAllFieldsSet(*message2_on_arena);
+}
+
+TEST(MovableMessageTest, MoveFromArena) {
+ Arena arena;
+
+ auto* message1_on_arena =
+ Arena::CreateMessage<protobuf_unittest::TestAllTypes>(&arena);
+ TestUtil::SetAllFields(message1_on_arena);
+ const auto* nested = &message1_on_arena->optional_nested_message();
+
+ protobuf_unittest::TestAllTypes message2;
+
+ // Moving from a message on the arena should lead to a copy.
+ message2 = std::move(*message1_on_arena);
+ EXPECT_NE(nested, &message2.optional_nested_message());
+ TestUtil::ExpectAllFieldsSet(*message1_on_arena);
+ TestUtil::ExpectAllFieldsSet(message2);
+}
+
+TEST(MovableMessageTest, MoveToArena) {
+ Arena arena;
+
+ protobuf_unittest::TestAllTypes message1;
+ TestUtil::SetAllFields(&message1);
+ const auto* nested = &message1.optional_nested_message();
+
+ auto* message2_on_arena =
+ Arena::CreateMessage<protobuf_unittest::TestAllTypes>(&arena);
+
+ // Moving to a message on the arena should lead to a copy.
+ *message2_on_arena = std::move(message1);
+ EXPECT_NE(nested, &message2_on_arena->optional_nested_message());
+ TestUtil::ExpectAllFieldsSet(message1);
+ TestUtil::ExpectAllFieldsSet(*message2_on_arena);
+}
+
+TEST(MovableMessageTest, Noexcept) {
+ EXPECT_TRUE(
+ std::is_nothrow_move_constructible<protobuf_unittest::TestAllTypes>());
+ EXPECT_TRUE(std::is_nothrow_move_assignable<protobuf_unittest::TestAllTypes>());
+}
+
+#endif // LANG_CXX11
+
+} // namespace cpp_unittest
+
+} // namespace cpp
+} // namespace compiler
+} // namespace protobuf
+} // namespace google
diff --git a/src/google/protobuf/compiler/cpp/cpp_options.h b/src/google/protobuf/compiler/cpp/cpp_options.h
index ee44fb0a..4a29ad0e 100644
--- a/src/google/protobuf/compiler/cpp/cpp_options.h
+++ b/src/google/protobuf/compiler/cpp/cpp_options.h
@@ -39,6 +39,8 @@
namespace google {
namespace protobuf {
namespace compiler {
+class AccessInfoMap;
+
namespace cpp {
// Generator options (see generator.cc for a description of each):
@@ -46,18 +48,26 @@ struct Options {
Options()
: safe_boundary_check(false),
proto_h(false),
- allow_import_public(true),
+ transitive_pb_h(true),
annotate_headers(false),
- enforce_lite(false) {}
+ enforce_lite(false),
+ table_driven_parsing(false),
+ table_driven_serialization(false),
+ lite_implicit_weak_fields(false),
+ access_info_map(NULL) {}
string dllexport_decl;
bool safe_boundary_check;
bool proto_h;
- bool allow_import_public;
+ bool transitive_pb_h;
bool annotate_headers;
bool enforce_lite;
+ bool table_driven_parsing;
+ bool table_driven_serialization;
+ bool lite_implicit_weak_fields;
string annotation_pragma_name;
string annotation_guard_name;
+ const AccessInfoMap* access_info_map;
};
} // namespace cpp
diff --git a/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.cc b/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.cc
new file mode 100644
index 00000000..e9303865
--- /dev/null
+++ b/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.cc
@@ -0,0 +1,220 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#include <google/protobuf/compiler/cpp/cpp_padding_optimizer.h>
+
+#include <google/protobuf/compiler/cpp/cpp_helpers.h>
+
+namespace google {
+namespace protobuf {
+namespace compiler {
+namespace cpp {
+
+namespace {
+
+// FieldGroup is just a helper for PaddingOptimizer below. It holds a vector of
+// fields that are grouped together because they have compatible alignment, and
+// a preferred location in the final field ordering.
+class FieldGroup {
+ public:
+ FieldGroup() : preferred_location_(0) {}
+
+ // A group with a single field.
+ FieldGroup(float preferred_location, const FieldDescriptor* field)
+ : preferred_location_(preferred_location), fields_(1, field) {}
+
+ // Append the fields in 'other' to this group.
+ void Append(const FieldGroup& other) {
+ if (other.fields_.empty()) {
+ return;
+ }
+ // Preferred location is the average among all the fields, so we weight by
+ // the number of fields on each FieldGroup object.
+ preferred_location_ = (preferred_location_ * fields_.size() +
+ (other.preferred_location_ * other.fields_.size())) /
+ (fields_.size() + other.fields_.size());
+ fields_.insert(fields_.end(), other.fields_.begin(), other.fields_.end());
+ }
+
+ void SetPreferredLocation(float location) { preferred_location_ = location; }
+ const std::vector<const FieldDescriptor*>& fields() const { return fields_; }
+
+ // FieldGroup objects sort by their preferred location.
+ bool operator<(const FieldGroup& other) const {
+ return preferred_location_ < other.preferred_location_;
+ }
+
+ private:
+ // "preferred_location_" is an estimate of where this group should go in the
+ // final list of fields. We compute this by taking the average index of each
+ // field in this group in the original ordering of fields. This is very
+ // approximate, but should put this group close to where its member fields
+ // originally went.
+ float preferred_location_;
+ std::vector<const FieldDescriptor*> fields_;
+ // We rely on the default copy constructor and operator= so this type can be
+ // used in a vector.
+};
+
+} // namespace
+
+// Reorder 'fields' so that if the fields are output into a c++ class in the new
+// order, fields of similar family (see below) are together and within each
+// family, alignment padding is minimized.
+//
+// We try to do this while keeping each field as close as possible to its field
+// number order so that we don't reduce cache locality much for function that
+// access each field in order. Originally, OptimizePadding used declaration
+// order for its decisions, but generated code minus the serializer/parsers uses
+// the output of OptimizePadding as well (stored in
+// MessageGenerator::optimized_order_). Since the serializers use field number
+// order, we use that as a tie-breaker.
+//
+// We classify each field into a particular "family" of fields, that we perform
+// the same operation on in our generated functions.
+//
+// REPEATED is placed first, as the C++ compiler automatically initializes
+// these fields in layout order.
+//
+// STRING is grouped next, as our Clear/SharedCtor/SharedDtor walks it and
+// calls ArenaStringPtr::Destroy on each.
+//
+//
+// MESSAGE is grouped next, as our Clear/SharedDtor code walks it and calls
+// delete on each. We initialize these fields with a NULL pointer (see
+// MessageFieldGenerator::GenerateConstructorCode), which allows them to be
+// memset.
+//
+// ZERO_INITIALIZABLE is memset in Clear/SharedCtor
+//
+// OTHER these fields are initialized one-by-one.
+void PaddingOptimizer::OptimizeLayout(
+ std::vector<const FieldDescriptor*>* fields, const Options& options) {
+ // The sorted numeric order of Family determines the declaration order in the
+ // memory layout.
+ enum Family {
+ REPEATED = 0,
+ STRING = 1,
+ MESSAGE = 3,
+ ZERO_INITIALIZABLE = 4,
+ OTHER = 5,
+ kMaxFamily
+ };
+
+ // First divide fields into those that align to 1 byte, 4 bytes or 8 bytes.
+ std::vector<FieldGroup> aligned_to_1[kMaxFamily];
+ std::vector<FieldGroup> aligned_to_4[kMaxFamily];
+ std::vector<FieldGroup> aligned_to_8[kMaxFamily];
+ for (int i = 0; i < fields->size(); ++i) {
+ const FieldDescriptor* field = (*fields)[i];
+
+ Family f = OTHER;
+ if (field->is_repeated()) {
+ f = REPEATED;
+ } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_STRING) {
+ f = STRING;
+ } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
+ f = MESSAGE;
+
+ } else if (CanInitializeByZeroing(field)) {
+ f = ZERO_INITIALIZABLE;
+ }
+
+ const int j = field->number();
+ switch (EstimateAlignmentSize(field)) {
+ case 1:
+ aligned_to_1[f].push_back(FieldGroup(j, field));
+ break;
+ case 4:
+ aligned_to_4[f].push_back(FieldGroup(j, field));
+ break;
+ case 8:
+ aligned_to_8[f].push_back(FieldGroup(j, field));
+ break;
+ default:
+ GOOGLE_LOG(FATAL) << "Unknown alignment size " << EstimateAlignmentSize(field)
+ << "for a field " << field->full_name() << ".";
+ }
+ }
+
+ // For each family, group fields to optimize padding.
+ for (int f = 0; f < kMaxFamily; f++) {
+ // Now group fields aligned to 1 byte into sets of 4, and treat those like a
+ // single field aligned to 4 bytes.
+ for (int i = 0; i < aligned_to_1[f].size(); i += 4) {
+ FieldGroup field_group;
+ for (int j = i; j < aligned_to_1[f].size() && j < i + 4; ++j) {
+ field_group.Append(aligned_to_1[f][j]);
+ }
+ aligned_to_4[f].push_back(field_group);
+ }
+ // Sort by preferred location to keep fields as close to their field number
+ // order as possible. Using stable_sort ensures that the output is
+ // consistent across runs.
+ std::stable_sort(aligned_to_4[f].begin(), aligned_to_4[f].end());
+
+ // Now group fields aligned to 4 bytes (or the 4-field groups created above)
+ // into pairs, and treat those like a single field aligned to 8 bytes.
+ for (int i = 0; i < aligned_to_4[f].size(); i += 2) {
+ FieldGroup field_group;
+ for (int j = i; j < aligned_to_4[f].size() && j < i + 2; ++j) {
+ field_group.Append(aligned_to_4[f][j]);
+ }
+ if (i == aligned_to_4[f].size() - 1) {
+ if (f == OTHER) {
+ // Move incomplete 4-byte block to the beginning. This is done to
+ // pair with the (possible) leftover blocks from the
+ // ZERO_INITIALIZABLE family.
+ field_group.SetPreferredLocation(-1);
+ } else {
+ // Move incomplete 4-byte block to the end.
+ field_group.SetPreferredLocation(fields->size() + 1);
+ }
+ }
+ aligned_to_8[f].push_back(field_group);
+ }
+ // Sort by preferred location.
+ std::stable_sort(aligned_to_8[f].begin(), aligned_to_8[f].end());
+ }
+
+ // Now pull out all the FieldDescriptors in order.
+ fields->clear();
+ for (int f = 0; f < kMaxFamily; ++f) {
+ for (int i = 0; i < aligned_to_8[f].size(); ++i) {
+ fields->insert(fields->end(), aligned_to_8[f][i].fields().begin(),
+ aligned_to_8[f][i].fields().end());
+ }
+ }
+}
+
+} // namespace cpp
+} // namespace compiler
+} // namespace protobuf
+} // namespace google
diff --git a/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.h b/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.h
new file mode 100644
index 00000000..9641ba40
--- /dev/null
+++ b/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.h
@@ -0,0 +1,64 @@
+// 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: seongkim@google.com (Seong Beom Kim)
+// Based on original Protocol Buffers design by
+// Sanjay Ghemawat, Jeff Dean, and others.
+
+#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_PADDING_OPTIMIZER_H__
+#define GOOGLE_PROTOBUF_COMPILER_CPP_PADDING_OPTIMIZER_H__
+
+#include <google/protobuf/compiler/cpp/cpp_message_layout_helper.h>
+
+namespace google {
+namespace protobuf {
+namespace compiler {
+namespace cpp {
+
+// Rearranges the fields of a message to minimize padding.
+// Fields are grouped by the type and the size.
+// For example, grouping four boolean fields and one int32
+// field results in zero padding overhead. See OptimizeLayout's
+// comment for details.
+class PaddingOptimizer : public MessageLayoutHelper {
+ public:
+ PaddingOptimizer() {}
+ ~PaddingOptimizer() {}
+
+ void OptimizeLayout(std::vector<const FieldDescriptor*>* fields,
+ const Options& options);
+};
+
+} // namespace cpp
+} // namespace compiler
+} // namespace protobuf
+
+} // namespace google
+#endif // GOOGLE_PROTOBUF_COMPILER_CPP_PADDING_OPTIMIZER_H__
diff --git a/src/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc b/src/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc
index 34a41d82..ceb2270e 100644
--- a/src/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc
@@ -132,7 +132,7 @@ class TestGenerator : public CodeGenerator {
// Check field accessors for a message inside oneof{}:
TryInsert("test.pb.h", "field_get:foo.Bar.oneOfMessage", context);
TryInsert("test.pb.h", "field_mutable:foo.Bar.oneOfMessage", context);
- TryInsert("test.pb.h", "field_set_allocated:foo.Bar.oneOfMessage", context);
+ TryInsert("test.pb.cc", "field_set_allocated:foo.Bar.oneOfMessage", context);
// Check field accessors for an optional enum:
TryInsert("test.pb.h", "field_get:foo.Bar.optEnum", context);
diff --git a/src/google/protobuf/compiler/cpp/cpp_primitive_field.cc b/src/google/protobuf/compiler/cpp/cpp_primitive_field.cc
index 240a6e0a..bc2d02ea 100644
--- a/src/google/protobuf/compiler/cpp/cpp_primitive_field.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_primitive_field.cc
@@ -115,21 +115,21 @@ GeneratePrivateMembers(io::Printer* printer) const {
void PrimitiveFieldGenerator::
GenerateAccessorDeclarations(io::Printer* printer) const {
+ printer->Print(variables_, "$deprecated_attr$$type$ $name$() const;\n");
+ printer->Annotate("name", descriptor_);
printer->Print(variables_,
- "$deprecated_attr$$type$ $name$() const;\n"
- "$deprecated_attr$void set_$name$($type$ value);\n");
+ "$deprecated_attr$void ${$set_$name$$}$($type$ value);\n");
+ printer->Annotate("{", "}", descriptor_);
}
void PrimitiveFieldGenerator::
-GenerateInlineAccessorDefinitions(io::Printer* printer, bool is_inline) const {
- std::map<string, string> variables(variables_);
- variables["inline"] = is_inline ? "inline " : "";
- printer->Print(variables,
- "$inline$$type$ $classname$::$name$() const {\n"
+GenerateInlineAccessorDefinitions(io::Printer* printer) const {
+ printer->Print(variables_,
+ "inline $type$ $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" return $name$_;\n"
"}\n"
- "$inline$void $classname$::set_$name$($type$ value) {\n"
+ "inline void $classname$::set_$name$($type$ value) {\n"
" $set_hasbit$\n"
" $name$_ = value;\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
@@ -148,7 +148,7 @@ GenerateMergingCode(io::Printer* printer) const {
void PrimitiveFieldGenerator::
GenerateSwappingCode(io::Printer* printer) const {
- printer->Print(variables_, "std::swap($name$_, other->$name$_);\n");
+ printer->Print(variables_, "swap($name$_, other->$name$_);\n");
}
void PrimitiveFieldGenerator::
@@ -210,18 +210,16 @@ PrimitiveOneofFieldGenerator(const FieldDescriptor* descriptor,
PrimitiveOneofFieldGenerator::~PrimitiveOneofFieldGenerator() {}
void PrimitiveOneofFieldGenerator::
-GenerateInlineAccessorDefinitions(io::Printer* printer, bool is_inline) const {
- std::map<string, string> variables(variables_);
- variables["inline"] = is_inline ? "inline " : "";
- printer->Print(variables,
- "$inline$$type$ $classname$::$name$() const {\n"
+GenerateInlineAccessorDefinitions(io::Printer* printer) const {
+ printer->Print(variables_,
+ "inline $type$ $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" if (has_$name$()) {\n"
" return $oneof_prefix$$name$_;\n"
" }\n"
" return $default$;\n"
"}\n"
- "$inline$void $classname$::set_$name$($type$ value) {\n"
+ "inline void $classname$::set_$name$($type$ value) {\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
@@ -243,9 +241,8 @@ GenerateSwappingCode(io::Printer* printer) const {
void PrimitiveOneofFieldGenerator::
GenerateConstructorCode(io::Printer* printer) const {
- printer->Print(
- variables_,
- " $classname$_default_oneof_instance_.$name$_ = $default$;\n");
+ printer->Print(variables_,
+ "$ns$::_$classname$_default_instance_.$name$_ = $default$;\n");
}
void PrimitiveOneofFieldGenerator::
@@ -290,40 +287,46 @@ GeneratePrivateMembers(io::Printer* printer) const {
void RepeatedPrimitiveFieldGenerator::
GenerateAccessorDeclarations(io::Printer* printer) const {
printer->Print(variables_,
- "$deprecated_attr$$type$ $name$(int index) const;\n"
- "$deprecated_attr$void set_$name$(int index, $type$ value);\n"
- "$deprecated_attr$void add_$name$($type$ value);\n");
+ "$deprecated_attr$$type$ $name$(int index) const;\n");
+ printer->Annotate("name", descriptor_);
+ printer->Print(
+ variables_,
+ "$deprecated_attr$void ${$set_$name$$}$(int index, $type$ value);\n");
+ printer->Annotate("{", "}", descriptor_);
+ printer->Print(variables_,
+ "$deprecated_attr$void ${$add_$name$$}$($type$ value);\n");
+ printer->Annotate("{", "}", descriptor_);
+ printer->Print(variables_,
+ "$deprecated_attr$const ::google::protobuf::RepeatedField< $type$ >&\n"
+ " $name$() const;\n");
+ printer->Annotate("name", descriptor_);
printer->Print(variables_,
- "$deprecated_attr$const ::google::protobuf::RepeatedField< $type$ >&\n"
- " $name$() const;\n"
- "$deprecated_attr$::google::protobuf::RepeatedField< $type$ >*\n"
- " mutable_$name$();\n");
+ "$deprecated_attr$::google::protobuf::RepeatedField< $type$ >*\n"
+ " ${$mutable_$name$$}$();\n");
+ printer->Annotate("{", "}", descriptor_);
}
void RepeatedPrimitiveFieldGenerator::
-GenerateInlineAccessorDefinitions(io::Printer* printer, bool is_inline) const {
- std::map<string, string> variables(variables_);
- variables["inline"] = is_inline ? "inline " : "";
- printer->Print(variables,
- "$inline$$type$ $classname$::$name$(int index) const {\n"
+GenerateInlineAccessorDefinitions(io::Printer* printer) const {
+ printer->Print(variables_,
+ "inline $type$ $classname$::$name$(int index) const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" return $name$_.Get(index);\n"
"}\n"
- "$inline$void $classname$::set_$name$(int index, $type$ value) {\n"
+ "inline void $classname$::set_$name$(int index, $type$ value) {\n"
" $name$_.Set(index, value);\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n"
- "$inline$void $classname$::add_$name$($type$ value) {\n"
+ "inline void $classname$::add_$name$($type$ value) {\n"
" $name$_.Add(value);\n"
" // @@protoc_insertion_point(field_add:$full_name$)\n"
- "}\n");
- printer->Print(variables,
- "$inline$const ::google::protobuf::RepeatedField< $type$ >&\n"
+ "}\n"
+ "inline const ::google::protobuf::RepeatedField< $type$ >&\n"
"$classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_list:$full_name$)\n"
" return $name$_;\n"
"}\n"
- "$inline$::google::protobuf::RepeatedField< $type$ >*\n"
+ "inline ::google::protobuf::RepeatedField< $type$ >*\n"
"$classname$::mutable_$name$() {\n"
" // @@protoc_insertion_point(field_mutable_list:$full_name$)\n"
" return &$name$_;\n"
@@ -342,7 +345,7 @@ GenerateMergingCode(io::Printer* printer) const {
void RepeatedPrimitiveFieldGenerator::
GenerateSwappingCode(io::Printer* printer) const {
- printer->Print(variables_, "$name$_.UnsafeArenaSwap(&other->$name$_);\n");
+ printer->Print(variables_, "$name$_.InternalSwap(&other->$name$_);\n");
}
void RepeatedPrimitiveFieldGenerator::
@@ -373,6 +376,7 @@ GenerateMergeFromCodedStreamWithPacking(io::Printer* printer) const {
void RepeatedPrimitiveFieldGenerator::
GenerateSerializeWithCachedSizes(io::Printer* printer) const {
+ bool array_written = false;
if (descriptor_->is_packed()) {
// Write the tag and the size.
printer->Print(variables_,
@@ -381,21 +385,34 @@ GenerateSerializeWithCachedSizes(io::Printer* printer) const {
"$number$, "
"::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, "
"output);\n"
- " output->WriteVarint32(_$name$_cached_byte_size_);\n"
- "}\n");
+ " output->WriteVarint32(static_cast< ::google::protobuf::uint32>(\n"
+ " _$name$_cached_byte_size_));\n");
+
+ if (FixedSize(descriptor_->type()) > 0) {
+ // TODO(ckennelly): Use RepeatedField<T>::unsafe_data() via
+ // WireFormatLite to access the contents of this->$name$_ to save a branch
+ // here.
+ printer->Print(variables_,
+ " ::google::protobuf::internal::WireFormatLite::Write$declared_type$Array(\n"
+ " this->$name$().data(), this->$name$_size(), output);\n");
+ array_written = true; // Wrote array all at once
+ }
+ printer->Print(variables_, "}\n");
}
- printer->Print(variables_,
- "for (int i = 0; i < this->$name$_size(); i++) {\n");
- if (descriptor_->is_packed()) {
- printer->Print(variables_,
- " ::google::protobuf::internal::WireFormatLite::Write$declared_type$NoTag(\n"
- " this->$name$(i), output);\n");
- } else {
+ if (!array_written) {
printer->Print(variables_,
- " ::google::protobuf::internal::WireFormatLite::Write$declared_type$(\n"
- " $number$, this->$name$(i), output);\n");
+ "for (int i = 0, n = this->$name$_size(); i < n; i++) {\n");
+ if (descriptor_->is_packed()) {
+ printer->Print(variables_,
+ " ::google::protobuf::internal::WireFormatLite::Write$declared_type$NoTag(\n"
+ " this->$name$(i), output);\n");
+ } else {
+ printer->Print(variables_,
+ " ::google::protobuf::internal::WireFormatLite::Write$declared_type$(\n"
+ " $number$, this->$name$(i), output);\n");
+ }
+ printer->Print("}\n");
}
- printer->Print("}\n");
}
void RepeatedPrimitiveFieldGenerator::
@@ -409,47 +426,39 @@ GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const {
" ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,\n"
" target);\n"
" target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray(\n"
- " _$name$_cached_byte_size_, target);\n"
- "}\n");
- }
- printer->Print(variables_,
- "for (int i = 0; i < this->$name$_size(); i++) {\n");
- if (descriptor_->is_packed()) {
- printer->Print(variables_,
+ " static_cast< ::google::protobuf::int32>(\n"
+ " _$name$_cached_byte_size_), target);\n"
" target = ::google::protobuf::internal::WireFormatLite::\n"
- " Write$declared_type$NoTagToArray(this->$name$(i), target);\n");
+ " Write$declared_type$NoTagToArray(this->$name$_, target);\n"
+ "}\n");
} else {
printer->Print(variables_,
- " target = ::google::protobuf::internal::WireFormatLite::\n"
- " Write$declared_type$ToArray($number$, this->$name$(i), target);\n");
+ "target = ::google::protobuf::internal::WireFormatLite::\n"
+ " Write$declared_type$ToArray($number$, this->$name$_, target);\n");
}
- printer->Print("}\n");
}
void RepeatedPrimitiveFieldGenerator::
GenerateByteSize(io::Printer* printer) const {
- printer->Print(variables_,
- "{\n"
- " size_t data_size = 0;\n"
- " unsigned int count = this->$name$_size();\n");
+ printer->Print(variables_, "{\n");
printer->Indent();
int fixed_size = FixedSize(descriptor_->type());
if (fixed_size == -1) {
printer->Print(variables_,
- "for (unsigned int i = 0; i < count; i++) {\n"
- " data_size += ::google::protobuf::internal::WireFormatLite::\n"
- " $declared_type$Size(this->$name$(i));\n"
- "}\n");
+ "size_t data_size = ::google::protobuf::internal::WireFormatLite::\n"
+ " $declared_type$Size(this->$name$_);\n");
} else {
printer->Print(variables_,
- "data_size = $fixed_size$UL * count;\n");
+ "unsigned int count = static_cast<unsigned int>(this->$name$_size());\n"
+ "size_t data_size = $fixed_size$UL * count;\n");
}
if (descriptor_->is_packed()) {
printer->Print(variables_,
"if (data_size > 0) {\n"
" total_size += $tag_size$ +\n"
- " ::google::protobuf::internal::WireFormatLite::Int32Size(data_size);\n"
+ " ::google::protobuf::internal::WireFormatLite::Int32Size(\n"
+ " static_cast< ::google::protobuf::int32>(data_size));\n"
"}\n"
"int cached_size = ::google::protobuf::internal::ToCachedSize(data_size);\n"
"GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();\n"
diff --git a/src/google/protobuf/compiler/cpp/cpp_primitive_field.h b/src/google/protobuf/compiler/cpp/cpp_primitive_field.h
index 44c9ff3e..d52228e9 100644
--- a/src/google/protobuf/compiler/cpp/cpp_primitive_field.h
+++ b/src/google/protobuf/compiler/cpp/cpp_primitive_field.h
@@ -53,8 +53,7 @@ class PrimitiveFieldGenerator : public FieldGenerator {
// implements FieldGenerator ---------------------------------------
void GeneratePrivateMembers(io::Printer* printer) const;
void GenerateAccessorDeclarations(io::Printer* printer) const;
- void GenerateInlineAccessorDefinitions(io::Printer* printer,
- bool is_inline) const;
+ void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateMergingCode(io::Printer* printer) const;
void GenerateSwappingCode(io::Printer* printer) const;
@@ -80,8 +79,7 @@ class PrimitiveOneofFieldGenerator : public PrimitiveFieldGenerator {
~PrimitiveOneofFieldGenerator();
// implements FieldGenerator ---------------------------------------
- void GenerateInlineAccessorDefinitions(io::Printer* printer,
- bool is_inline) const;
+ void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateSwappingCode(io::Printer* printer) const;
void GenerateConstructorCode(io::Printer* printer) const;
@@ -100,8 +98,7 @@ class RepeatedPrimitiveFieldGenerator : public FieldGenerator {
// implements FieldGenerator ---------------------------------------
void GeneratePrivateMembers(io::Printer* printer) const;
void GenerateAccessorDeclarations(io::Printer* printer) const;
- void GenerateInlineAccessorDefinitions(io::Printer* printer,
- bool is_inline) const;
+ void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateMergingCode(io::Printer* printer) const;
void GenerateSwappingCode(io::Printer* printer) const;
diff --git a/src/google/protobuf/compiler/cpp/cpp_service.cc b/src/google/protobuf/compiler/cpp/cpp_service.cc
index d6b1ddc5..95357d9f 100644
--- a/src/google/protobuf/compiler/cpp/cpp_service.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_service.cc
@@ -46,6 +46,7 @@ ServiceGenerator::ServiceGenerator(const ServiceDescriptor* descriptor,
const Options& options)
: descriptor_(descriptor) {
vars_["classname"] = descriptor_->name();
+ vars_["file_namespace"] = FileLevelNamespace(descriptor_->file()->name());
vars_["full_name"] = descriptor_->full_name();
if (options.dllexport_decl.empty()) {
vars_["dllexport"] = "";
@@ -178,8 +179,8 @@ void ServiceGenerator::GenerateImplementation(io::Printer* printer) {
"$classname$::~$classname$() {}\n"
"\n"
"const ::google::protobuf::ServiceDescriptor* $classname$::descriptor() {\n"
- " protobuf_AssignDescriptorsOnce();\n"
- " return file_level_service_descriptors[$index$];\n"
+ " $file_namespace$::protobuf_AssignDescriptorsOnce();\n"
+ " return $file_namespace$::file_level_service_descriptors[$index$];\n"
"}\n"
"\n"
"const ::google::protobuf::ServiceDescriptor* $classname$::GetDescriptor() {\n"
@@ -241,7 +242,7 @@ void ServiceGenerator::GenerateCallMethod(io::Printer* printer) {
" ::google::protobuf::Message* response,\n"
" ::google::protobuf::Closure* done) {\n"
" GOOGLE_DCHECK_EQ(method->service(), "
- "file_level_service_descriptors[$index$]);\n"
+ "$file_namespace$::file_level_service_descriptors[$index$]);\n"
" switch(method->index()) {\n");
for (int i = 0; i < descriptor_->method_count(); i++) {
diff --git a/src/google/protobuf/compiler/cpp/cpp_string_field.cc b/src/google/protobuf/compiler/cpp/cpp_string_field.cc
index a9505e3d..264f6124 100644
--- a/src/google/protobuf/compiler/cpp/cpp_string_field.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_string_field.cc
@@ -36,6 +36,7 @@
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/descriptor.pb.h>
+
#include <google/protobuf/stubs/strutil.h>
namespace google {
@@ -57,10 +58,11 @@ void SetStringVariables(const FieldDescriptor* descriptor,
(*variables)["default_variable"] =
descriptor->default_value_string().empty()
? "&::google::protobuf::internal::GetEmptyStringAlreadyInited()"
- : "&" + (*variables)["classname"] + "::" + default_variable_string +
- ".get()";
+ : "&" + Namespace(descriptor) + "::" + (*variables)["classname"] +
+ "::" + default_variable_string + ".get()";
(*variables)["pointer_type"] =
descriptor->type() == FieldDescriptor::TYPE_BYTES ? "void" : "char";
+ (*variables)["null_check"] = "GOOGLE_DCHECK(value != NULL);\n";
// NOTE: Escaped here to unblock proto1->proto2 migration.
// TODO(liujisi): Extend this to apply for other conflicting methods.
(*variables)["release_name"] =
@@ -69,6 +71,9 @@ void SetStringVariables(const FieldDescriptor* descriptor,
(*variables)["full_name"] = descriptor->full_name();
(*variables)["string_piece"] = "::std::string";
+
+ (*variables)["lite"] =
+ HasDescriptorMethods(descriptor->file(), options) ? "" : "Lite";
}
} // namespace
@@ -77,7 +82,8 @@ void SetStringVariables(const FieldDescriptor* descriptor,
StringFieldGenerator::StringFieldGenerator(const FieldDescriptor* descriptor,
const Options& options)
- : FieldGenerator(options), descriptor_(descriptor) {
+ : FieldGenerator(options), descriptor_(descriptor),
+ lite_(!HasDescriptorMethods(descriptor->file(), options)) {
SetStringVariables(descriptor, &variables_, options);
}
@@ -140,22 +146,55 @@ GenerateAccessorDeclarations(io::Printer* printer) const {
}
printer->Print(variables_,
- "$deprecated_attr$const ::std::string& $name$() const;\n"
- "$deprecated_attr$void set_$name$(const ::std::string& value);\n"
- "$deprecated_attr$void set_$name$(const char* value);\n"
- "$deprecated_attr$void set_$name$(const $pointer_type$* value, size_t size)"
- ";\n"
- "$deprecated_attr$::std::string* mutable_$name$();\n"
- "$deprecated_attr$::std::string* $release_name$();\n"
- "$deprecated_attr$void set_allocated_$name$(::std::string* $name$);\n");
+ "$deprecated_attr$const ::std::string& $name$() const;\n");
+ printer->Annotate("name", descriptor_);
+ printer->Print(
+ variables_,
+ "$deprecated_attr$void ${$set_$name$$}$(const ::std::string& value);\n");
+ printer->Annotate("{", "}", descriptor_);
+
+ printer->Print(variables_,
+ "#if LANG_CXX11\n"
+ "$deprecated_attr$void ${$set_$name$$}$(::std::string&& value);\n"
+ "#endif\n");
+ printer->Annotate("{", "}", descriptor_);
+
+ printer->Print(
+ variables_,
+ "$deprecated_attr$void ${$set_$name$$}$(const char* value);\n");
+ printer->Annotate("{", "}", descriptor_);
+ printer->Print(variables_,
+ "$deprecated_attr$void ${$set_$name$$}$(const $pointer_type$* "
+ "value, size_t size)"
+ ";\n");
+ printer->Annotate("{", "}", descriptor_);
+ printer->Print(variables_,
+ "$deprecated_attr$::std::string* ${$mutable_$name$$}$();\n");
+ printer->Annotate("{", "}", descriptor_);
+ printer->Print(variables_, "$deprecated_attr$::std::string* $release_name$();\n");
+ printer->Annotate("release_name", descriptor_);
+ printer->Print(
+ variables_,
+ "$deprecated_attr$void ${$set_allocated_$name$$}$(::std::string* $name$);\n");
+ printer->Annotate("{", "}", descriptor_);
if (SupportsArenas(descriptor_)) {
- printer->Print(variables_,
- "$deprecated_attr$::std::string* unsafe_arena_release_$name$();\n"
- "$deprecated_attr$void unsafe_arena_set_allocated_$name$(\n"
- " ::std::string* $name$);\n");
+ printer->Print(
+ variables_,
+ "PROTOBUF_RUNTIME_DEPRECATED(\"The unsafe_arena_ accessors for\"\n"
+ "\" string fields are deprecated and will be removed in a\"\n"
+ "\" future release.\")\n"
+ "::std::string* ${$unsafe_arena_release_$name$$}$();\n");
+ printer->Annotate("{", "}", descriptor_);
+ printer->Print(
+ variables_,
+ "PROTOBUF_RUNTIME_DEPRECATED(\"The unsafe_arena_ accessors for\"\n"
+ "\" string fields are deprecated and will be removed in a\"\n"
+ "\" future release.\")\n"
+ "void ${$unsafe_arena_set_allocated_$name$$}$(\n"
+ " ::std::string* $name$);\n");
+ printer->Annotate("{", "}", descriptor_);
}
-
if (unknown_ctype) {
printer->Outdent();
printer->Print(" public:\n");
@@ -164,56 +203,54 @@ GenerateAccessorDeclarations(io::Printer* printer) const {
}
void StringFieldGenerator::
-GenerateInlineAccessorDefinitions(io::Printer* printer,
- bool is_inline) const {
- std::map<string, string> variables(variables_);
- variables["inline"] = is_inline ? "inline " : "";
+GenerateInlineAccessorDefinitions(io::Printer* printer) const {
if (SupportsArenas(descriptor_)) {
printer->Print(
- variables,
- "$inline$const ::std::string& $classname$::$name$() const {\n"
+ variables_,
+ "inline const ::std::string& $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" return $name$_.Get();\n"
"}\n"
- "$inline$void $classname$::set_$name$(const ::std::string& value) {\n"
+ "inline void $classname$::set_$name$(const ::std::string& value) {\n"
" $set_hasbit$\n"
- " $name$_.Set($default_variable$, value, GetArenaNoVirtual());\n"
+ " $name$_.Set$lite$($default_variable$, value, GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n"
- "$inline$void $classname$::set_$name$(const char* value) {\n"
+ "#if LANG_CXX11\n"
+ "inline void $classname$::set_$name$(::std::string&& value) {\n"
+ " $set_hasbit$\n"
+ " $name$_.Set$lite$(\n"
+ " $default_variable$, ::std::move(value), GetArenaNoVirtual());\n"
+ " // @@protoc_insertion_point(field_set_rvalue:$full_name$)\n"
+ "}\n"
+ "#endif\n"
+ "inline void $classname$::set_$name$(const char* value) {\n"
+ " $null_check$"
" $set_hasbit$\n"
- " $name$_.Set($default_variable$, $string_piece$(value),\n"
+ " $name$_.Set$lite$($default_variable$, $string_piece$(value),\n"
" GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set_char:$full_name$)\n"
"}\n"
- "$inline$"
+ "inline "
"void $classname$::set_$name$(const $pointer_type$* value,\n"
" size_t size) {\n"
" $set_hasbit$\n"
- " $name$_.Set($default_variable$, $string_piece$(\n"
+ " $name$_.Set$lite$($default_variable$, $string_piece$(\n"
" reinterpret_cast<const char*>(value), size), "
"GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set_pointer:$full_name$)\n"
"}\n"
- "$inline$::std::string* $classname$::mutable_$name$() {\n"
+ "inline ::std::string* $classname$::mutable_$name$() {\n"
" $set_hasbit$\n"
" // @@protoc_insertion_point(field_mutable:$full_name$)\n"
" return $name$_.Mutable($default_variable$, GetArenaNoVirtual());\n"
"}\n"
- "$inline$::std::string* $classname$::$release_name$() {\n"
+ "inline ::std::string* $classname$::$release_name$() {\n"
" // @@protoc_insertion_point(field_release:$full_name$)\n"
" $clear_hasbit$\n"
" return $name$_.Release($default_variable$, GetArenaNoVirtual());\n"
"}\n"
- "$inline$::std::string* $classname$::unsafe_arena_release_$name$() {\n"
- " // "
- "@@protoc_insertion_point(field_unsafe_arena_release:$full_name$)\n"
- " GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);\n"
- " $clear_hasbit$\n"
- " return $name$_.UnsafeArenaRelease($default_variable$,\n"
- " GetArenaNoVirtual());\n"
- "}\n"
- "$inline$void $classname$::set_allocated_$name$(::std::string* $name$) {\n"
+ "inline void $classname$::set_allocated_$name$(::std::string* $name$) {\n"
" if ($name$ != NULL) {\n"
" $set_hasbit$\n"
" } else {\n"
@@ -223,7 +260,15 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set_allocated:$full_name$)\n"
"}\n"
- "$inline$void $classname$::unsafe_arena_set_allocated_$name$(\n"
+ "inline ::std::string* $classname$::unsafe_arena_release_$name$() {\n"
+ " // "
+ "@@protoc_insertion_point(field_unsafe_arena_release:$full_name$)\n"
+ " GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);\n"
+ " $clear_hasbit$\n"
+ " return $name$_.UnsafeArenaRelease($default_variable$,\n"
+ " GetArenaNoVirtual());\n"
+ "}\n"
+ "inline void $classname$::unsafe_arena_set_allocated_$name$(\n"
" ::std::string* $name$) {\n"
" GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);\n"
" if ($name$ != NULL) {\n"
@@ -239,22 +284,31 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
} else {
// No-arena case.
printer->Print(
- variables,
- "$inline$const ::std::string& $classname$::$name$() const {\n"
+ variables_,
+ "inline const ::std::string& $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" return $name$_.GetNoArena();\n"
"}\n"
- "$inline$void $classname$::set_$name$(const ::std::string& value) {\n"
+ "inline void $classname$::set_$name$(const ::std::string& value) {\n"
" $set_hasbit$\n"
" $name$_.SetNoArena($default_variable$, value);\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n"
- "$inline$void $classname$::set_$name$(const char* value) {\n"
+ "#if LANG_CXX11\n"
+ "inline void $classname$::set_$name$(::std::string&& value) {\n"
+ " $set_hasbit$\n"
+ " $name$_.SetNoArena(\n"
+ " $default_variable$, ::std::move(value));\n"
+ " // @@protoc_insertion_point(field_set_rvalue:$full_name$)\n"
+ "}\n"
+ "#endif\n"
+ "inline void $classname$::set_$name$(const char* value) {\n"
+ " $null_check$"
" $set_hasbit$\n"
" $name$_.SetNoArena($default_variable$, $string_piece$(value));\n"
" // @@protoc_insertion_point(field_set_char:$full_name$)\n"
"}\n"
- "$inline$"
+ "inline "
"void $classname$::set_$name$(const $pointer_type$* value, "
"size_t size) {\n"
" $set_hasbit$\n"
@@ -262,17 +316,17 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" $string_piece$(reinterpret_cast<const char*>(value), size));\n"
" // @@protoc_insertion_point(field_set_pointer:$full_name$)\n"
"}\n"
- "$inline$::std::string* $classname$::mutable_$name$() {\n"
+ "inline ::std::string* $classname$::mutable_$name$() {\n"
" $set_hasbit$\n"
" // @@protoc_insertion_point(field_mutable:$full_name$)\n"
" return $name$_.MutableNoArena($default_variable$);\n"
"}\n"
- "$inline$::std::string* $classname$::$release_name$() {\n"
+ "inline ::std::string* $classname$::$release_name$() {\n"
" // @@protoc_insertion_point(field_release:$full_name$)\n"
" $clear_hasbit$\n"
" return $name$_.ReleaseNoArena($default_variable$);\n"
"}\n"
- "$inline$void $classname$::set_allocated_$name$(::std::string* $name$) {\n"
+ "inline void $classname$::set_allocated_$name$(::std::string* $name$) {\n"
" if ($name$ != NULL) {\n"
" $set_hasbit$\n"
" } else {\n"
@@ -405,7 +459,7 @@ GenerateCopyConstructorCode(io::Printer* printer) const {
if (SupportsArenas(descriptor_) || descriptor_->containing_oneof() != NULL) {
// TODO(gpike): improve this
printer->Print(variables_,
- "$name$_.Set($default_variable$, from.$name$(),\n"
+ "$name$_.Set$lite$($default_variable$, from.$name$(),\n"
" GetArenaNoVirtual());\n");
} else {
printer->Print(variables_,
@@ -418,32 +472,21 @@ GenerateCopyConstructorCode(io::Printer* printer) const {
void StringFieldGenerator::
GenerateDestructorCode(io::Printer* printer) const {
- if (SupportsArenas(descriptor_)) {
- // The variable |arena| is defined by the enclosing code.
- // See MessageGenerator::GenerateSharedDestructorCode.
- printer->Print(variables_,
- "$name$_.Destroy($default_variable$, arena);\n");
- } else {
- printer->Print(variables_,
- "$name$_.DestroyNoArena($default_variable$);\n");
- }
+ printer->Print(variables_,
+ "$name$_.DestroyNoArena($default_variable$);\n");
}
void StringFieldGenerator::
GenerateDefaultInstanceAllocator(io::Printer* printer) const {
if (!descriptor_->default_value_string().empty()) {
- printer->Print(variables_,
- "$classname$::$default_variable_name$.DefaultConstruct();\n"
- "*$classname$::$default_variable_name$.get_mutable() = "
- "::std::string($default$, $default_length$);\n");
- }
-}
-
-void StringFieldGenerator::
-GenerateShutdownCode(io::Printer* printer) const {
- if (!descriptor_->default_value_string().empty()) {
- printer->Print(variables_,
- "$classname$::$default_variable_name$.Shutdown();\n");
+ printer->Print(
+ variables_,
+ "$ns$::$classname$::$default_variable_name$.DefaultConstruct();\n"
+ "*$ns$::$classname$::$default_variable_name$.get_mutable() = "
+ "::std::string($default$, $default_length$);\n"
+ "::google::protobuf::internal::OnShutdownDestroyString(\n"
+ " $ns$::$classname$::$default_variable_name$.get_mutable());\n"
+ );
}
}
@@ -456,7 +499,8 @@ GenerateMergeFromCodedStream(io::Printer* printer) const {
if (descriptor_->type() == FieldDescriptor::TYPE_STRING) {
GenerateUtf8CheckCodeForString(
descriptor_, options_, true, variables_,
- "this->$name$().data(), this->$name$().length(),\n", printer);
+ "this->$name$().data(), static_cast<int>(this->$name$().length()),\n",
+ printer);
}
}
@@ -465,7 +509,8 @@ GenerateSerializeWithCachedSizes(io::Printer* printer) const {
if (descriptor_->type() == FieldDescriptor::TYPE_STRING) {
GenerateUtf8CheckCodeForString(
descriptor_, options_, false, variables_,
- "this->$name$().data(), this->$name$().length(),\n", printer);
+ "this->$name$().data(), static_cast<int>(this->$name$().length()),\n",
+ printer);
}
printer->Print(variables_,
"::google::protobuf::internal::WireFormatLite::Write$declared_type$MaybeAliased(\n"
@@ -477,7 +522,8 @@ GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const {
if (descriptor_->type() == FieldDescriptor::TYPE_STRING) {
GenerateUtf8CheckCodeForString(
descriptor_, options_, false, variables_,
- "this->$name$().data(), this->$name$().length(),\n", printer);
+ "this->$name$().data(), static_cast<int>(this->$name$().length()),\n",
+ printer);
}
printer->Print(variables_,
"target =\n"
@@ -506,41 +552,52 @@ StringOneofFieldGenerator(const FieldDescriptor* descriptor,
StringOneofFieldGenerator::~StringOneofFieldGenerator() {}
void StringOneofFieldGenerator::
-GenerateInlineAccessorDefinitions(io::Printer* printer,
- bool is_inline) const {
- std::map<string, string> variables(variables_);
- variables["inline"] = is_inline ? "inline " : "";
+GenerateInlineAccessorDefinitions(io::Printer* printer) const {
if (SupportsArenas(descriptor_)) {
printer->Print(
- variables,
- "$inline$const ::std::string& $classname$::$name$() const {\n"
+ variables_,
+ "inline const ::std::string& $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" if (has_$name$()) {\n"
" return $oneof_prefix$$name$_.Get();\n"
" }\n"
" return *$default_variable$;\n"
"}\n"
- "$inline$void $classname$::set_$name$(const ::std::string& value) {\n"
+ "inline void $classname$::set_$name$(const ::std::string& value) {\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
" $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
" }\n"
- " $oneof_prefix$$name$_.Set($default_variable$, value,\n"
+ " $oneof_prefix$$name$_.Set$lite$($default_variable$, value,\n"
" GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n"
- "$inline$void $classname$::set_$name$(const char* value) {\n"
+ "#if LANG_CXX11\n"
+ "inline void $classname$::set_$name$(::std::string&& value) {\n"
+ " // @@protoc_insertion_point(field_set:$full_name$)\n"
+ " if (!has_$name$()) {\n"
+ " clear_$oneof_name$();\n"
+ " set_has_$name$();\n"
+ " $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
+ " }\n"
+ " $oneof_prefix$$name$_.Set$lite$(\n"
+ " $default_variable$, ::std::move(value), GetArenaNoVirtual());\n"
+ " // @@protoc_insertion_point(field_set_rvalue:$full_name$)\n"
+ "}\n"
+ "#endif\n"
+ "inline void $classname$::set_$name$(const char* value) {\n"
+ " $null_check$"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
" $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
" }\n"
- " $oneof_prefix$$name$_.Set($default_variable$,\n"
+ " $oneof_prefix$$name$_.Set$lite$($default_variable$,\n"
" $string_piece$(value), GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set_char:$full_name$)\n"
"}\n"
- "$inline$"
+ "inline "
"void $classname$::set_$name$(const $pointer_type$* value,\n"
" size_t size) {\n"
" if (!has_$name$()) {\n"
@@ -548,12 +605,13 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" set_has_$name$();\n"
" $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
" }\n"
- " $oneof_prefix$$name$_.Set($default_variable$, $string_piece$(\n"
+ " $oneof_prefix$$name$_.Set$lite$(\n"
+ " $default_variable$, $string_piece$(\n"
" reinterpret_cast<const char*>(value), size),\n"
" GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set_pointer:$full_name$)\n"
"}\n"
- "$inline$::std::string* $classname$::mutable_$name$() {\n"
+ "inline ::std::string* $classname$::mutable_$name$() {\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
@@ -563,7 +621,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_mutable:$full_name$)\n"
"}\n"
- "$inline$::std::string* $classname$::$release_name$() {\n"
+ "inline ::std::string* $classname$::$release_name$() {\n"
" // @@protoc_insertion_point(field_release:$full_name$)\n"
" if (has_$name$()) {\n"
" clear_has_$oneof_name$();\n"
@@ -573,19 +631,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" return NULL;\n"
" }\n"
"}\n"
- "$inline$::std::string* $classname$::unsafe_arena_release_$name$() {\n"
- " // "
- "@@protoc_insertion_point(field_unsafe_arena_release:$full_name$)\n"
- " GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);\n"
- " if (has_$name$()) {\n"
- " clear_has_$oneof_name$();\n"
- " return $oneof_prefix$$name$_.UnsafeArenaRelease(\n"
- " $default_variable$, GetArenaNoVirtual());\n"
- " } else {\n"
- " return NULL;\n"
- " }\n"
- "}\n"
- "$inline$void $classname$::set_allocated_$name$(::std::string* $name$) {\n"
+ "inline void $classname$::set_allocated_$name$(::std::string* $name$) {\n"
" if (!has_$name$()) {\n"
" $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
" }\n"
@@ -597,7 +643,19 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" }\n"
" // @@protoc_insertion_point(field_set_allocated:$full_name$)\n"
"}\n"
- "$inline$void $classname$::unsafe_arena_set_allocated_$name$("
+ "inline ::std::string* $classname$::unsafe_arena_release_$name$() {\n"
+ " // "
+ "@@protoc_insertion_point(field_unsafe_arena_release:$full_name$)\n"
+ " GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);\n"
+ " if (has_$name$()) {\n"
+ " clear_has_$oneof_name$();\n"
+ " return $oneof_prefix$$name$_.UnsafeArenaRelease(\n"
+ " $default_variable$, GetArenaNoVirtual());\n"
+ " } else {\n"
+ " return NULL;\n"
+ " }\n"
+ "}\n"
+ "inline void $classname$::unsafe_arena_set_allocated_$name$("
"::std::string* $name$) {\n"
" GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);\n"
" if (!has_$name$()) {\n"
@@ -615,15 +673,15 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
} else {
// No-arena case.
printer->Print(
- variables,
- "$inline$const ::std::string& $classname$::$name$() const {\n"
+ variables_,
+ "inline const ::std::string& $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" if (has_$name$()) {\n"
" return $oneof_prefix$$name$_.GetNoArena();\n"
" }\n"
" return *$default_variable$;\n"
"}\n"
- "$inline$void $classname$::set_$name$(const ::std::string& value) {\n"
+ "inline void $classname$::set_$name$(const ::std::string& value) {\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
@@ -633,7 +691,21 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" $oneof_prefix$$name$_.SetNoArena($default_variable$, value);\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n"
- "$inline$void $classname$::set_$name$(const char* value) {\n"
+ "#if LANG_CXX11\n"
+ "inline void $classname$::set_$name$(::std::string&& value) {\n"
+ " // @@protoc_insertion_point(field_set:$full_name$)\n"
+ " if (!has_$name$()) {\n"
+ " clear_$oneof_name$();\n"
+ " set_has_$name$();\n"
+ " $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
+ " }\n"
+ " $oneof_prefix$$name$_.SetNoArena(\n"
+ " $default_variable$, ::std::move(value));\n"
+ " // @@protoc_insertion_point(field_set_rvalue:$full_name$)\n"
+ "}\n"
+ "#endif\n"
+ "inline void $classname$::set_$name$(const char* value) {\n"
+ " $null_check$"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
@@ -643,7 +715,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" $string_piece$(value));\n"
" // @@protoc_insertion_point(field_set_char:$full_name$)\n"
"}\n"
- "$inline$"
+ "inline "
"void $classname$::set_$name$(const $pointer_type$* value, size_t "
"size) {\n"
" if (!has_$name$()) {\n"
@@ -656,7 +728,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" reinterpret_cast<const char*>(value), size));\n"
" // @@protoc_insertion_point(field_set_pointer:$full_name$)\n"
"}\n"
- "$inline$::std::string* $classname$::mutable_$name$() {\n"
+ "inline ::std::string* $classname$::mutable_$name$() {\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
@@ -665,7 +737,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" // @@protoc_insertion_point(field_mutable:$full_name$)\n"
" return $oneof_prefix$$name$_.MutableNoArena($default_variable$);\n"
"}\n"
- "$inline$::std::string* $classname$::$release_name$() {\n"
+ "inline ::std::string* $classname$::$release_name$() {\n"
" // @@protoc_insertion_point(field_release:$full_name$)\n"
" if (has_$name$()) {\n"
" clear_has_$oneof_name$();\n"
@@ -674,7 +746,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" return NULL;\n"
" }\n"
"}\n"
- "$inline$void $classname$::set_allocated_$name$(::std::string* $name$) {\n"
+ "inline void $classname$::set_allocated_$name$(::std::string* $name$) {\n"
" if (!has_$name$()) {\n"
" $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
" }\n"
@@ -691,29 +763,13 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
void StringOneofFieldGenerator::
GenerateClearingCode(io::Printer* printer) const {
- std::map<string, string> variables(variables_);
- if (dependent_field_) {
- variables["this_message"] = DependentBaseDownCast();
- // This clearing code may be in the dependent base class. If the default
- // value is an empty string, then the $default_variable$ is a global
- // singleton. If the default is not empty, we need to down-cast to get the
- // default value's global singleton instance. See SetStringVariables() for
- // possible values of default_variable.
- if (!descriptor_->default_value_string().empty()) {
- variables["default_variable"] = "&" + DependentBaseDownCast() +
- variables["default_variable_name"] +
- ".get()";
- }
- } else {
- variables["this_message"] = "";
- }
if (SupportsArenas(descriptor_)) {
- printer->Print(variables,
- "$this_message$$oneof_prefix$$name$_.Destroy($default_variable$,\n"
- " $this_message$GetArenaNoVirtual());\n");
+ printer->Print(variables_,
+ "$oneof_prefix$$name$_.Destroy($default_variable$,\n"
+ " GetArenaNoVirtual());\n");
} else {
- printer->Print(variables,
- "$this_message$$oneof_prefix$$name$_."
+ printer->Print(variables_,
+ "$oneof_prefix$$name$_."
"DestroyNoArena($default_variable$);\n");
}
}
@@ -732,24 +788,16 @@ void StringOneofFieldGenerator::
GenerateConstructorCode(io::Printer* printer) const {
printer->Print(
variables_,
- "$classname$_default_oneof_instance_.$name$_.UnsafeSetDefault(\n"
+ "$ns$::_$classname$_default_instance_.$name$_.UnsafeSetDefault(\n"
" $default_variable$);\n");
}
void StringOneofFieldGenerator::
GenerateDestructorCode(io::Printer* printer) const {
- if (SupportsArenas(descriptor_)) {
- printer->Print(variables_,
- "if (has_$name$()) {\n"
- " $oneof_prefix$$name$_.Destroy($default_variable$,\n"
- " GetArenaNoVirtual());\n"
- "}\n");
- } else {
- printer->Print(variables_,
- "if (has_$name$()) {\n"
- " $oneof_prefix$$name$_.DestroyNoArena($default_variable$);\n"
- "}\n");
- }
+ printer->Print(variables_,
+ "if (has_$name$()) {\n"
+ " $oneof_prefix$$name$_.DestroyNoArena($default_variable$);\n"
+ "}\n");
}
void StringOneofFieldGenerator::
@@ -761,7 +809,8 @@ GenerateMergeFromCodedStream(io::Printer* printer) const {
if (descriptor_->type() == FieldDescriptor::TYPE_STRING) {
GenerateUtf8CheckCodeForString(
descriptor_, options_, true, variables_,
- "this->$name$().data(), this->$name$().length(),\n", printer);
+ "this->$name$().data(), static_cast<int>(this->$name$().length()),\n",
+ printer);
}
}
@@ -797,24 +846,62 @@ GenerateAccessorDeclarations(io::Printer* printer) const {
}
printer->Print(variables_,
- "$deprecated_attr$const ::std::string& $name$(int index) const;\n"
- "$deprecated_attr$::std::string* mutable_$name$(int index);\n"
- "$deprecated_attr$void set_$name$(int index, const ::std::string& value);\n"
- "$deprecated_attr$void set_$name$(int index, const char* value);\n"
- ""
- "$deprecated_attr$void set_$name$("
- "int index, const $pointer_type$* value, size_t size);\n"
- "$deprecated_attr$::std::string* add_$name$();\n"
- "$deprecated_attr$void add_$name$(const ::std::string& value);\n"
- "$deprecated_attr$void add_$name$(const char* value);\n"
- "$deprecated_attr$void add_$name$(const $pointer_type$* value, size_t size)"
+ "$deprecated_attr$const ::std::string& $name$(int index) const;\n");
+ printer->Annotate("name", descriptor_);
+ printer->Print(
+ variables_,
+ "$deprecated_attr$::std::string* ${$mutable_$name$$}$(int index);\n");
+ printer->Annotate("{", "}", descriptor_);
+ printer->Print(variables_,
+ "$deprecated_attr$void ${$set_$name$$}$(int index, const "
+ "::std::string& value);\n");
+ printer->Annotate("{", "}", descriptor_);
+ printer->Print(
+ variables_,
+ "#if LANG_CXX11\n"
+ "$deprecated_attr$void ${$set_$name$$}$(int index, ::std::string&& value);\n"
+ "#endif\n");
+ printer->Annotate("{", "}", descriptor_);
+ printer->Print(variables_,
+ "$deprecated_attr$void ${$set_$name$$}$(int index, const "
+ "char* value);\n");
+ printer->Annotate("{", "}", descriptor_);
+ printer->Print(variables_,
+ ""
+ "$deprecated_attr$void ${$set_$name$$}$("
+ "int index, const $pointer_type$* value, size_t size);\n");
+ printer->Annotate("{", "}", descriptor_);
+ printer->Print(variables_,
+ "$deprecated_attr$::std::string* ${$add_$name$$}$();\n");
+ printer->Annotate("{", "}", descriptor_);
+ printer->Print(
+ variables_,
+ "$deprecated_attr$void ${$add_$name$$}$(const ::std::string& value);\n");
+ printer->Annotate("{", "}", descriptor_);
+ printer->Print(variables_,
+ "#if LANG_CXX11\n"
+ "$deprecated_attr$void ${$add_$name$$}$(::std::string&& value);\n"
+ "#endif\n");
+ printer->Annotate("{", "}", descriptor_);
+ printer->Print(
+ variables_,
+ "$deprecated_attr$void ${$add_$name$$}$(const char* value);\n");
+ printer->Annotate("{", "}", descriptor_);
+ printer->Print(variables_,
+ "$deprecated_attr$void ${$add_$name$$}$(const $pointer_type$* "
+ "value, size_t size)"
";\n");
-
+ printer->Annotate("{", "}", descriptor_);
+ printer->Print(
+ variables_,
+ "$deprecated_attr$const ::google::protobuf::RepeatedPtrField< ::std::string>& $name$() "
+ "const;\n");
+ printer->Annotate("name", descriptor_);
printer->Print(variables_,
- "$deprecated_attr$const ::google::protobuf::RepeatedPtrField< ::std::string>& $name$() "
- "const;\n"
- "$deprecated_attr$::google::protobuf::RepeatedPtrField< ::std::string>* mutable_$name$()"
+ "$deprecated_attr$::google::protobuf::RepeatedPtrField< ::std::string>* "
+ "${$mutable_$name$$}$()"
";\n");
+ printer->Annotate("{", "}", descriptor_);
if (unknown_ctype) {
printer->Outdent();
@@ -824,58 +911,68 @@ GenerateAccessorDeclarations(io::Printer* printer) const {
}
void RepeatedStringFieldGenerator::
-GenerateInlineAccessorDefinitions(io::Printer* printer,
- bool is_inline) const {
- std::map<string, string> variables(variables_);
- variables["inline"] = is_inline ? "inline " : "";
- printer->Print(variables,
- "$inline$const ::std::string& $classname$::$name$(int index) const {\n"
+GenerateInlineAccessorDefinitions(io::Printer* printer) const {
+ printer->Print(variables_,
+ "inline const ::std::string& $classname$::$name$(int index) const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" return $name$_.$cppget$(index);\n"
"}\n"
- "$inline$::std::string* $classname$::mutable_$name$(int index) {\n"
+ "inline ::std::string* $classname$::mutable_$name$(int index) {\n"
" // @@protoc_insertion_point(field_mutable:$full_name$)\n"
" return $name$_.Mutable(index);\n"
"}\n"
- "$inline$void $classname$::set_$name$(int index, const ::std::string& value) {\n"
+ "inline void $classname$::set_$name$(int index, const ::std::string& value) {\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
" $name$_.Mutable(index)->assign(value);\n"
"}\n"
- "$inline$void $classname$::set_$name$(int index, const char* value) {\n"
+ "#if LANG_CXX11\n"
+ "inline void $classname$::set_$name$(int index, ::std::string&& value) {\n"
+ " // @@protoc_insertion_point(field_set:$full_name$)\n"
+ " $name$_.Mutable(index)->assign(std::move(value));\n"
+ "}\n"
+ "#endif\n"
+ "inline void $classname$::set_$name$(int index, const char* value) {\n"
+ " $null_check$"
" $name$_.Mutable(index)->assign(value);\n"
" // @@protoc_insertion_point(field_set_char:$full_name$)\n"
"}\n"
- "$inline$void "
+ "inline void "
"$classname$::set_$name$"
"(int index, const $pointer_type$* value, size_t size) {\n"
" $name$_.Mutable(index)->assign(\n"
" reinterpret_cast<const char*>(value), size);\n"
" // @@protoc_insertion_point(field_set_pointer:$full_name$)\n"
"}\n"
- "$inline$::std::string* $classname$::add_$name$() {\n"
+ "inline ::std::string* $classname$::add_$name$() {\n"
" // @@protoc_insertion_point(field_add_mutable:$full_name$)\n"
" return $name$_.Add();\n"
"}\n"
- "$inline$void $classname$::add_$name$(const ::std::string& value) {\n"
+ "inline void $classname$::add_$name$(const ::std::string& value) {\n"
" $name$_.Add()->assign(value);\n"
" // @@protoc_insertion_point(field_add:$full_name$)\n"
"}\n"
- "$inline$void $classname$::add_$name$(const char* value) {\n"
+ "#if LANG_CXX11\n"
+ "inline void $classname$::add_$name$(::std::string&& value) {\n"
+ " $name$_.Add(std::move(value));\n"
+ " // @@protoc_insertion_point(field_add:$full_name$)\n"
+ "}\n"
+ "#endif\n"
+ "inline void $classname$::add_$name$(const char* value) {\n"
+ " $null_check$"
" $name$_.Add()->assign(value);\n"
" // @@protoc_insertion_point(field_add_char:$full_name$)\n"
"}\n"
- "$inline$void "
+ "inline void "
"$classname$::add_$name$(const $pointer_type$* value, size_t size) {\n"
" $name$_.Add()->assign(reinterpret_cast<const char*>(value), size);\n"
" // @@protoc_insertion_point(field_add_pointer:$full_name$)\n"
- "}\n");
- printer->Print(variables,
- "$inline$const ::google::protobuf::RepeatedPtrField< ::std::string>&\n"
+ "}\n"
+ "inline const ::google::protobuf::RepeatedPtrField< ::std::string>&\n"
"$classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_list:$full_name$)\n"
" return $name$_;\n"
"}\n"
- "$inline$::google::protobuf::RepeatedPtrField< ::std::string>*\n"
+ "inline ::google::protobuf::RepeatedPtrField< ::std::string>*\n"
"$classname$::mutable_$name$() {\n"
" // @@protoc_insertion_point(field_mutable_list:$full_name$)\n"
" return &$name$_;\n"
@@ -894,7 +991,7 @@ GenerateMergingCode(io::Printer* printer) const {
void RepeatedStringFieldGenerator::
GenerateSwappingCode(io::Printer* printer) const {
- printer->Print(variables_, "$name$_.UnsafeArenaSwap(&other->$name$_);\n");
+ printer->Print(variables_, "$name$_.InternalSwap(&other->$name$_);\n");
}
void RepeatedStringFieldGenerator::
@@ -916,7 +1013,7 @@ GenerateMergeFromCodedStream(io::Printer* printer) const {
GenerateUtf8CheckCodeForString(
descriptor_, options_, true, variables_,
"this->$name$(this->$name$_size() - 1).data(),\n"
- "this->$name$(this->$name$_size() - 1).length(),\n",
+ "static_cast<int>(this->$name$(this->$name$_size() - 1).length()),\n",
printer);
}
}
@@ -924,12 +1021,13 @@ GenerateMergeFromCodedStream(io::Printer* printer) const {
void RepeatedStringFieldGenerator::
GenerateSerializeWithCachedSizes(io::Printer* printer) const {
printer->Print(variables_,
- "for (int i = 0; i < this->$name$_size(); i++) {\n");
+ "for (int i = 0, n = this->$name$_size(); i < n; i++) {\n");
printer->Indent();
if (descriptor_->type() == FieldDescriptor::TYPE_STRING) {
GenerateUtf8CheckCodeForString(
descriptor_, options_, false, variables_,
- "this->$name$(i).data(), this->$name$(i).length(),\n", printer);
+ "this->$name$(i).data(), static_cast<int>(this->$name$(i).length()),\n",
+ printer);
}
printer->Outdent();
printer->Print(variables_,
@@ -941,12 +1039,13 @@ GenerateSerializeWithCachedSizes(io::Printer* printer) const {
void RepeatedStringFieldGenerator::
GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const {
printer->Print(variables_,
- "for (int i = 0; i < this->$name$_size(); i++) {\n");
+ "for (int i = 0, n = this->$name$_size(); i < n; i++) {\n");
printer->Indent();
if (descriptor_->type() == FieldDescriptor::TYPE_STRING) {
GenerateUtf8CheckCodeForString(
descriptor_, options_, false, variables_,
- "this->$name$(i).data(), this->$name$(i).length(),\n", printer);
+ "this->$name$(i).data(), static_cast<int>(this->$name$(i).length()),\n",
+ printer);
}
printer->Outdent();
printer->Print(variables_,
@@ -960,7 +1059,7 @@ GenerateByteSize(io::Printer* printer) const {
printer->Print(variables_,
"total_size += $tag_size$ *\n"
" ::google::protobuf::internal::FromIntSize(this->$name$_size());\n"
- "for (int i = 0; i < this->$name$_size(); i++) {\n"
+ "for (int i = 0, n = this->$name$_size(); i < n; i++) {\n"
" total_size += ::google::protobuf::internal::WireFormatLite::$declared_type$Size(\n"
" this->$name$(i));\n"
"}\n");
diff --git a/src/google/protobuf/compiler/cpp/cpp_string_field.h b/src/google/protobuf/compiler/cpp/cpp_string_field.h
index af263c1a..f56f0721 100644
--- a/src/google/protobuf/compiler/cpp/cpp_string_field.h
+++ b/src/google/protobuf/compiler/cpp/cpp_string_field.h
@@ -54,8 +54,7 @@ class StringFieldGenerator : public FieldGenerator {
void GeneratePrivateMembers(io::Printer* printer) const;
void GenerateStaticMembers(io::Printer* printer) const;
void GenerateAccessorDeclarations(io::Printer* printer) const;
- void GenerateInlineAccessorDefinitions(io::Printer* printer,
- bool is_inline) const;
+ void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateNonInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateMessageClearingCode(io::Printer* printer) const;
@@ -65,7 +64,6 @@ class StringFieldGenerator : public FieldGenerator {
void GenerateCopyConstructorCode(io::Printer* printer) const;
void GenerateDestructorCode(io::Printer* printer) const;
void GenerateDefaultInstanceAllocator(io::Printer* printer) const;
- void GenerateShutdownCode(io::Printer* printer) const;
void GenerateMergeFromCodedStream(io::Printer* printer) const;
void GenerateSerializeWithCachedSizes(io::Printer* printer) const;
void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const;
@@ -74,6 +72,7 @@ class StringFieldGenerator : public FieldGenerator {
protected:
const FieldDescriptor* descriptor_;
std::map<string, string> variables_;
+ const bool lite_;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(StringFieldGenerator);
@@ -86,8 +85,7 @@ class StringOneofFieldGenerator : public StringFieldGenerator {
~StringOneofFieldGenerator();
// implements FieldGenerator ---------------------------------------
- void GenerateInlineAccessorDefinitions(io::Printer* printer,
- bool is_inline) const;
+ void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
// StringFieldGenerator, from which we inherit, overrides this so we need to
@@ -112,8 +110,7 @@ class RepeatedStringFieldGenerator : public FieldGenerator {
// implements FieldGenerator ---------------------------------------
void GeneratePrivateMembers(io::Printer* printer) const;
void GenerateAccessorDeclarations(io::Printer* printer) const;
- void GenerateInlineAccessorDefinitions(io::Printer* printer,
- bool is_inline) const;
+ void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateMergingCode(io::Printer* printer) const;
void GenerateSwappingCode(io::Printer* printer) const;
diff --git a/src/google/protobuf/compiler/cpp/cpp_test_bad_identifiers.proto b/src/google/protobuf/compiler/cpp/cpp_test_bad_identifiers.proto
index 4e25b2ea..7fe98759 100644
--- a/src/google/protobuf/compiler/cpp/cpp_test_bad_identifiers.proto
+++ b/src/google/protobuf/compiler/cpp/cpp_test_bad_identifiers.proto
@@ -151,6 +151,10 @@ enum ConflictingEnum { // NO_PROTO3
message DummyMessage {}
+// Message names that could conflict.
+message Shutdown {}
+message TableStruct {}
+
service TestConflictingMethodNames {
rpc Closure(DummyMessage) returns (DummyMessage);
}
diff --git a/src/google/protobuf/compiler/cpp/cpp_unittest.cc b/src/google/protobuf/compiler/cpp/cpp_unittest.cc
index 8eaddb87..61cc32a4 100644
--- a/src/google/protobuf/compiler/cpp/cpp_unittest.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_unittest.cc
@@ -53,6 +53,7 @@
#include <vector>
#include <google/protobuf/unittest.pb.h>
+#include <google/protobuf/unittest_no_arena.pb.h>
#include <google/protobuf/unittest_optimize_for.pb.h>
#include <google/protobuf/unittest_embed_optimize_for.pb.h>
#if !defined(GOOGLE_PROTOBUF_CMAKE_BUILD) && !defined(_MSC_VER)
@@ -75,7 +76,6 @@
#include <google/protobuf/stubs/callback.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/logging.h>
-#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/substitute.h>
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
@@ -420,6 +420,71 @@ TEST(GeneratedMessageTest, StringCharStarLength) {
EXPECT_EQ("wx", message.repeated_string(0));
}
+#if LANG_CXX11
+TEST(GeneratedMessageTest, StringMove) {
+ // Verify that we trigger the move behavior on a scalar setter.
+ protobuf_unittest_no_arena::TestAllTypes message;
+ {
+ string tmp(32, 'a');
+
+ const char* old_data = tmp.data();
+ message.set_optional_string(std::move(tmp));
+ const char* new_data = message.optional_string().data();
+
+ EXPECT_EQ(old_data, new_data);
+ EXPECT_EQ(string(32, 'a'), message.optional_string());
+
+ string tmp2(32, 'b');
+ old_data = tmp2.data();
+ message.set_optional_string(std::move(tmp2));
+ new_data = message.optional_string().data();
+
+ EXPECT_EQ(old_data, new_data);
+ EXPECT_EQ(string(32, 'b'), message.optional_string());
+ }
+
+ // Verify that we trigger the move behavior on a oneof setter.
+ {
+ string tmp(32, 'a');
+
+ const char* old_data = tmp.data();
+ message.set_oneof_string(std::move(tmp));
+ const char* new_data = message.oneof_string().data();
+
+ EXPECT_EQ(old_data, new_data);
+ EXPECT_EQ(string(32, 'a'), message.oneof_string());
+
+ string tmp2(32, 'b');
+ old_data = tmp2.data();
+ message.set_oneof_string(std::move(tmp2));
+ new_data = message.oneof_string().data();
+
+ EXPECT_EQ(old_data, new_data);
+ EXPECT_EQ(string(32, 'b'), message.oneof_string());
+ }
+
+ // Verify that we trigger the move behavior on a repeated setter.
+ {
+ string tmp(32, 'a');
+
+ const char* old_data = tmp.data();
+ message.add_repeated_string(std::move(tmp));
+ const char* new_data = message.repeated_string(0).data();
+
+ EXPECT_EQ(old_data, new_data);
+ EXPECT_EQ(string(32, 'a'), message.repeated_string(0));
+
+ string tmp2(32, 'b');
+ old_data = tmp2.data();
+ message.set_repeated_string(0, std::move(tmp2));
+ new_data = message.repeated_string(0).data();
+
+ EXPECT_EQ(old_data, new_data);
+ EXPECT_EQ(string(32, 'b'), message.repeated_string(0));
+ }
+}
+#endif
+
TEST(GeneratedMessageTest, CopyFrom) {
unittest::TestAllTypes message1, message2;
@@ -511,12 +576,73 @@ TEST(GeneratedMessageTest, SwapWithOther) {
EXPECT_EQ(unittest::TestAllTypes::BAR, message2.repeated_nested_enum(1));
}
-TEST(GeneratedMessageTest, CopyConstructor) {
- unittest::TestAllTypes message1;
+TEST(GeneratedMessageTest, ADLSwap) {
+ unittest::TestAllTypes message1, message2;
TestUtil::SetAllFields(&message1);
- unittest::TestAllTypes message2(message1);
+ // Note the address of one of the repeated fields, to verify it was swapped
+ // rather than copied.
+ const int32* addr = &message1.repeated_int32().Get(0);
+
+ using std::swap;
+ swap(message1, message2);
+
TestUtil::ExpectAllFieldsSet(message2);
+ TestUtil::ExpectClear(message1);
+
+ EXPECT_EQ(addr, &message2.repeated_int32().Get(0));
+}
+
+TEST(GeneratedMessageTest, CopyConstructor) {
+ // All set.
+ {
+ unittest::TestAllTypes message1;
+ TestUtil::SetAllFields(&message1);
+
+ unittest::TestAllTypes message2(message1);
+ TestUtil::ExpectAllFieldsSet(message2);
+ }
+
+ // None set.
+ {
+ unittest::TestAllTypes message1;
+ unittest::TestAllTypes message2(message1);
+
+ EXPECT_FALSE(message1.has_optional_string());
+ EXPECT_FALSE(message2.has_optional_string());
+ EXPECT_EQ(&message1.optional_string(),
+ &message2.optional_string());
+
+ EXPECT_FALSE(message1.has_optional_bytes());
+ EXPECT_FALSE(message2.has_optional_bytes());
+ EXPECT_EQ(&message1.optional_bytes(),
+ &message2.optional_bytes());
+
+ EXPECT_FALSE(message1.has_optional_nested_message());
+ EXPECT_FALSE(message2.has_optional_nested_message());
+ EXPECT_EQ(&message1.optional_nested_message(),
+ &message2.optional_nested_message());
+
+ EXPECT_FALSE(message1.has_optional_foreign_message());
+ EXPECT_FALSE(message2.has_optional_foreign_message());
+ EXPECT_EQ(&message1.optional_foreign_message(),
+ &message2.optional_foreign_message());
+
+ EXPECT_FALSE(message1.has_optional_import_message());
+ EXPECT_FALSE(message2.has_optional_import_message());
+ EXPECT_EQ(&message1.optional_import_message(),
+ &message2.optional_import_message());
+
+ EXPECT_FALSE(message1.has_optional_public_import_message());
+ EXPECT_FALSE(message2.has_optional_public_import_message());
+ EXPECT_EQ(&message1.optional_public_import_message(),
+ &message2.optional_public_import_message());
+
+ EXPECT_FALSE(message1.has_optional_lazy_message());
+ EXPECT_FALSE(message2.has_optional_lazy_message());
+ EXPECT_EQ(&message1.optional_lazy_message(),
+ &message2.optional_lazy_message());
+ }
}
TEST(GeneratedMessageTest, CopyConstructorWithArenas) {
@@ -618,21 +744,6 @@ TEST(GeneratedMessageTest, NonEmptyMergeFrom) {
TestUtil::ExpectAllFieldsSet(message1);
}
-#if !defined(PROTOBUF_TEST_NO_DESCRIPTORS) || \
- !defined(GOOGLE_PROTOBUF_NO_RTTI)
-#ifdef PROTOBUF_HAS_DEATH_TEST
-#ifndef NDEBUG
-
-TEST(GeneratedMessageTest, MergeFromSelf) {
- unittest::TestAllTypes message;
- EXPECT_DEATH(message.MergeFrom(message), "pb[.]cc.*Check failed:");
- EXPECT_DEATH(message.MergeFrom(implicit_cast<const Message&>(message)),
- "pb[.]cc.*Check failed:");
-}
-
-#endif // NDEBUG
-#endif // PROTOBUF_HAS_DEATH_TEST
-#endif // !PROTOBUF_TEST_NO_DESCRIPTORS || !GOOGLE_PROTOBUF_NO_RTTI
// Test the generated SerializeWithCachedSizesToArray(),
TEST(GeneratedMessageTest, SerializationToArray) {
@@ -1275,7 +1386,7 @@ class GeneratedServiceTest : public testing::Test {
foo_(descriptor_->FindMethodByName("Foo")),
bar_(descriptor_->FindMethodByName("Bar")),
stub_(&mock_channel_),
- done_(NewPermanentCallback(&DoNothing)) {}
+ done_(::google::protobuf::NewPermanentCallback(&DoNothing)) {}
virtual void SetUp() {
ASSERT_TRUE(foo_ != NULL);
@@ -2096,6 +2207,61 @@ TEST_F(OneofTest, MergeFrom) {
}
+TEST(HelpersTest, TestSCC) {
+ protobuf_unittest::TestMutualRecursionA a;
+ SCCAnalyzer scc_analyzer((Options()));
+ const SCC* scc = scc_analyzer.GetSCC(a.GetDescriptor());
+ std::vector<string> names;
+ for (int i = 0; i < scc->descriptors.size(); i++) {
+ names.push_back(scc->descriptors[i]->full_name());
+ }
+ ASSERT_EQ(names.size(), 4);
+ std::sort(names.begin(), names.end());
+ EXPECT_EQ(names[0], "protobuf_unittest.TestMutualRecursionA");
+ EXPECT_EQ(names[1], "protobuf_unittest.TestMutualRecursionA.SubGroup");
+ EXPECT_EQ(names[2], "protobuf_unittest.TestMutualRecursionA.SubMessage");
+ EXPECT_EQ(names[3], "protobuf_unittest.TestMutualRecursionB");
+
+ MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc);
+ EXPECT_EQ(result.is_recursive, true);
+ EXPECT_EQ(result.contains_required, false);
+ EXPECT_EQ(result.contains_cord, true); // TestAllTypes
+ EXPECT_EQ(result.contains_extension, false); // TestAllTypes
+}
+
+TEST(HelpersTest, TestSCCAnalysis) {
+ {
+ protobuf_unittest::TestRecursiveMessage msg;
+ SCCAnalyzer scc_analyzer((Options()));
+ const SCC* scc = scc_analyzer.GetSCC(msg.GetDescriptor());
+ MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc);
+ EXPECT_EQ(result.is_recursive, true);
+ EXPECT_EQ(result.contains_required, false);
+ EXPECT_EQ(result.contains_cord, false);
+ EXPECT_EQ(result.contains_extension, false);
+ }
+ {
+ protobuf_unittest::TestAllExtensions msg;
+ SCCAnalyzer scc_analyzer((Options()));
+ const SCC* scc = scc_analyzer.GetSCC(msg.GetDescriptor());
+ MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc);
+ EXPECT_EQ(result.is_recursive, false);
+ EXPECT_EQ(result.contains_required, false);
+ EXPECT_EQ(result.contains_cord, false);
+ EXPECT_EQ(result.contains_extension, true);
+ }
+ {
+ protobuf_unittest::TestRequired msg;
+ SCCAnalyzer scc_analyzer((Options()));
+ const SCC* scc = scc_analyzer.GetSCC(msg.GetDescriptor());
+ MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc);
+ EXPECT_EQ(result.is_recursive, false);
+ EXPECT_EQ(result.contains_required, true);
+ EXPECT_EQ(result.contains_cord, false);
+ EXPECT_EQ(result.contains_extension, false);
+ }
+}
+
} // namespace cpp_unittest
} // namespace cpp
} // namespace compiler
diff --git a/src/google/protobuf/compiler/cpp/metadata_test.cc b/src/google/protobuf/compiler/cpp/metadata_test.cc
index 03f6b12b..d1bb3194 100644
--- a/src/google/protobuf/compiler/cpp/metadata_test.cc
+++ b/src/google/protobuf/compiler/cpp/metadata_test.cc
@@ -35,10 +35,8 @@
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
#include <google/protobuf/compiler/cpp/cpp_generator.h>
+#include <google/protobuf/compiler/annotation_test_util.h>
#include <google/protobuf/compiler/command_line_interface.h>
-#include <google/protobuf/io/zero_copy_stream.h>
-#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
-#include <google/protobuf/io/printer.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/testing/file.h>
@@ -47,37 +45,15 @@
#include <gtest/gtest.h>
namespace google {
+namespace atu = ::google::protobuf::compiler::annotation_test_util;
+
namespace protobuf {
namespace compiler {
namespace cpp {
namespace {
-// A CodeGenerator that captures the FileDescriptor it's passed as a
-// FileDescriptorProto.
-class DescriptorCapturingGenerator : public CodeGenerator {
- public:
- // Does not own file; file must outlive the Generator.
- explicit DescriptorCapturingGenerator(FileDescriptorProto* file)
- : file_(file) {}
-
- virtual bool Generate(const FileDescriptor* file, const string& parameter,
- GeneratorContext* context, string* error) const {
- file->CopyTo(file_);
- return true;
- }
-
- private:
- FileDescriptorProto* file_;
-};
-
class CppMetadataTest : public ::testing::Test {
public:
- // Adds a file with name `filename` and content `data`.
- void AddFile(const string& filename, const string& data) {
- GOOGLE_CHECK_OK(File::SetContents(TestTempDir() + "/" + filename, data,
- true));
- }
-
// Tries to capture a FileDescriptorProto, GeneratedCodeInfo, and output
// code from the previously added file with name `filename`. Returns true on
// success. If pb_h is non-null, expects a .pb.h and a .pb.h.meta (copied to
@@ -87,26 +63,21 @@ class CppMetadataTest : public ::testing::Test {
string* proto_h, GeneratedCodeInfo* proto_h_info,
string* pb_cc) {
google::protobuf::compiler::CommandLineInterface cli;
- cli.SetInputsAreProtoPathRelative(true);
-
CppGenerator cpp_generator;
- DescriptorCapturingGenerator capturing_generator(file);
cli.RegisterGenerator("--cpp_out", &cpp_generator, "");
- cli.RegisterGenerator("--capture_out", &capturing_generator, "");
-
- string proto_path = "-I" + TestTempDir();
string cpp_out =
"--cpp_out=annotate_headers=true,"
"annotation_pragma_name=pragma_name,"
"annotation_guard_name=guard_name:" +
TestTempDir();
- string capture_out = "--capture_out=" + TestTempDir();
- const char* argv[] = {"protoc", proto_path.c_str(), cpp_out.c_str(),
- capture_out.c_str(), filename.c_str()};
+ const bool result =
+ atu::CaptureMetadata(filename, cpp_out,
+ /* meta_file_suffix */ "", &cli, file,
+ /* outputs */ NULL);
- if (cli.Run(5, argv) != 0) {
- return false;
+ if (!result) {
+ return result;
}
string output_base = TestTempDir() + "/" + StripProto(filename);
@@ -119,7 +90,7 @@ class CppMetadataTest : public ::testing::Test {
if (pb_h != NULL && pb_h_info != NULL) {
GOOGLE_CHECK_OK(
File::GetContents(output_base + ".pb.h", pb_h, true));
- if (!DecodeMetadata(output_base + ".pb.h.meta", pb_h_info)) {
+ if (!atu::DecodeMetadata(output_base + ".pb.h.meta", pb_h_info)) {
return false;
}
}
@@ -127,23 +98,13 @@ class CppMetadataTest : public ::testing::Test {
if (proto_h != NULL && proto_h_info != NULL) {
GOOGLE_CHECK_OK(File::GetContents(output_base + ".proto.h", proto_h,
true));
- if (!DecodeMetadata(output_base + ".proto.h.meta", proto_h_info)) {
+ if (!atu::DecodeMetadata(output_base + ".proto.h.meta", proto_h_info)) {
return false;
}
}
return true;
}
-
- private:
- // Decodes GeneratedCodeInfo stored in path and copies it to info.
- // Returns true on success.
- bool DecodeMetadata(const string& path, GeneratedCodeInfo* info) {
- string data;
- GOOGLE_CHECK_OK(File::GetContents(path, &data, true));
- io::ArrayInputStream input(data.data(), data.size());
- return info->ParseFromZeroCopyStream(&input);
- }
};
const char kSmallTestFile[] =
@@ -152,48 +113,11 @@ const char kSmallTestFile[] =
"enum Enum { VALUE = 0; }\n"
"message Message { }\n";
-// Finds the Annotation for a given source file and path (or returns null if it
-// couldn't).
-const GeneratedCodeInfo::Annotation* FindAnnotationOnPath(
- const GeneratedCodeInfo& info, const string& source_file,
- const std::vector<int>& path) {
- for (int i = 0; i < info.annotation_size(); ++i) {
- const GeneratedCodeInfo::Annotation* annotation = &info.annotation(i);
- if (annotation->source_file() != source_file ||
- annotation->path_size() != path.size()) {
- continue;
- }
- int node = 0;
- for (; node < path.size(); ++node) {
- if (annotation->path(node) != path[node]) {
- break;
- }
- }
- if (node == path.size()) {
- return annotation;
- }
- }
- return NULL;
-}
-
-// Returns true if the provided annotation covers a given substring in
-// file_content.
-bool AnnotationMatchesSubstring(const string& file_content,
- const GeneratedCodeInfo::Annotation* annotation,
- const string& expected_text) {
- uint32 begin = annotation->begin();
- uint32 end = annotation->end();
- if (end < begin || end > file_content.size()) {
- return false;
- }
- return file_content.substr(begin, end - begin) == expected_text;
-}
-
TEST_F(CppMetadataTest, CapturesEnumNames) {
FileDescriptorProto file;
GeneratedCodeInfo info;
string pb_h;
- AddFile("test.proto", kSmallTestFile);
+ atu::AddFile("test.proto", kSmallTestFile);
EXPECT_TRUE(
CaptureMetadata("test.proto", &file, &pb_h, &info, NULL, NULL, NULL));
EXPECT_EQ("Enum", file.enum_type(0).name());
@@ -201,16 +125,16 @@ TEST_F(CppMetadataTest, CapturesEnumNames) {
enum_path.push_back(FileDescriptorProto::kEnumTypeFieldNumber);
enum_path.push_back(0);
const GeneratedCodeInfo::Annotation* enum_annotation =
- FindAnnotationOnPath(info, "test.proto", enum_path);
+ atu::FindAnnotationOnPath(info, "test.proto", enum_path);
EXPECT_TRUE(NULL != enum_annotation);
- EXPECT_TRUE(AnnotationMatchesSubstring(pb_h, enum_annotation, "Enum"));
+ EXPECT_TRUE(atu::AnnotationMatchesSubstring(pb_h, enum_annotation, "Enum"));
}
TEST_F(CppMetadataTest, AddsPragma) {
FileDescriptorProto file;
GeneratedCodeInfo info;
string pb_h;
- AddFile("test.proto", kSmallTestFile);
+ atu::AddFile("test.proto", kSmallTestFile);
EXPECT_TRUE(
CaptureMetadata("test.proto", &file, &pb_h, &info, NULL, NULL, NULL));
EXPECT_TRUE(pb_h.find("#ifdef guard_name") != string::npos);
@@ -222,7 +146,7 @@ TEST_F(CppMetadataTest, CapturesMessageNames) {
FileDescriptorProto file;
GeneratedCodeInfo info;
string pb_h;
- AddFile("test.proto", kSmallTestFile);
+ atu::AddFile("test.proto", kSmallTestFile);
EXPECT_TRUE(
CaptureMetadata("test.proto", &file, &pb_h, &info, NULL, NULL, NULL));
EXPECT_EQ("Message", file.message_type(0).name());
@@ -230,9 +154,10 @@ TEST_F(CppMetadataTest, CapturesMessageNames) {
message_path.push_back(FileDescriptorProto::kMessageTypeFieldNumber);
message_path.push_back(0);
const GeneratedCodeInfo::Annotation* message_annotation =
- FindAnnotationOnPath(info, "test.proto", message_path);
+ atu::FindAnnotationOnPath(info, "test.proto", message_path);
EXPECT_TRUE(NULL != message_annotation);
- EXPECT_TRUE(AnnotationMatchesSubstring(pb_h, message_annotation, "Message"));
+ EXPECT_TRUE(
+ atu::AnnotationMatchesSubstring(pb_h, message_annotation, "Message"));
}
} // namespace
diff --git a/src/google/protobuf/compiler/csharp/csharp_bootstrap_unittest.cc b/src/google/protobuf/compiler/csharp/csharp_bootstrap_unittest.cc
new file mode 100644
index 00000000..8c38e52f
--- /dev/null
+++ b/src/google/protobuf/compiler/csharp/csharp_bootstrap_unittest.cc
@@ -0,0 +1,200 @@
+// 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.
+
+// This test insures that
+// csharp/src/Google.Protobuf/Reflection/Descriptor.cs match exactly
+// what would be generated by the protocol compiler. The file is not
+// generated automatically at build time.
+//
+// If this test fails, run the script
+// "generate_descriptor_proto.sh" and add the changed files under
+// csharp/src/ to your changelist.
+
+#include <map>
+
+#include <google/protobuf/compiler/csharp/csharp_generator.h>
+#include <google/protobuf/compiler/importer.h>
+#include <google/protobuf/descriptor.h>
+#include <google/protobuf/io/zero_copy_stream_impl.h>
+#include <google/protobuf/stubs/map_util.h>
+#include <google/protobuf/stubs/stl_util.h>
+#include <google/protobuf/stubs/strutil.h>
+#include <google/protobuf/stubs/substitute.h>
+
+#include <google/protobuf/testing/file.h>
+#include <google/protobuf/testing/file.h>
+#include <google/protobuf/testing/googletest.h>
+#include <gtest/gtest.h>
+
+namespace google {
+namespace protobuf {
+namespace compiler {
+namespace csharp {
+
+namespace {
+
+class MockErrorCollector : public MultiFileErrorCollector {
+ public:
+ MockErrorCollector() {}
+ ~MockErrorCollector() {}
+
+ string text_;
+
+ // implements ErrorCollector ---------------------------------------
+ void AddError(const string& filename, int line, int column,
+ const string& message) {
+ strings::SubstituteAndAppend(&text_, "$0:$1:$2: $3\n",
+ filename, line, column, message);
+ }
+};
+
+class MockGeneratorContext : public GeneratorContext {
+ public:
+ MockGeneratorContext() {}
+ ~MockGeneratorContext() {
+ STLDeleteValues(&files_);
+ }
+
+ void ExpectFileMatches(const string& virtual_filename,
+ const string& physical_filename) {
+ string* expected_contents = FindPtrOrNull(files_, virtual_filename);
+ ASSERT_TRUE(expected_contents != NULL)
+ << "Generator failed to generate file: " << virtual_filename;
+
+ string actual_contents;
+ GOOGLE_CHECK_OK(
+ File::GetContents(TestSourceDir() + "/" + physical_filename,
+ &actual_contents, true))
+ << "Unable to get " << physical_filename;
+ EXPECT_TRUE(actual_contents == *expected_contents)
+ << physical_filename << " needs to be regenerated. Please run "
+ "generate_descriptor_proto.sh. Then add this file "
+ "to your CL.";
+ }
+
+ // implements GeneratorContext --------------------------------------
+
+ virtual io::ZeroCopyOutputStream* Open(const string& filename) {
+ string** map_slot = &files_[filename];
+ delete *map_slot;
+ *map_slot = new string;
+
+ return new io::StringOutputStream(*map_slot);
+ }
+
+ private:
+ std::map<string, string*> files_;
+};
+
+class GenerateAndTest {
+ public:
+ GenerateAndTest() {}
+ void Run(const FileDescriptor* proto_file, string file1, string file2) {
+ ASSERT_TRUE(proto_file != NULL) << TestSourceDir();
+ ASSERT_TRUE(generator_.Generate(proto_file, parameter_,
+ &context_, &error_));
+ context_.ExpectFileMatches(file1, file2);
+ }
+ void SetParameter(string parameter) {
+ parameter_ = parameter;
+ }
+
+ private:
+ Generator generator_;
+ MockGeneratorContext context_;
+ string error_;
+ string parameter_;
+};
+
+TEST(CsharpBootstrapTest, GeneratedCsharpDescriptorMatches) {
+ // Skip this whole test if the csharp directory doesn't exist (i.e., a C++11
+ // only distribution).
+ string descriptor_file_name =
+ "../csharp/src/Google.Protobuf/Reflection/Descriptor.cs";
+ if (!File::Exists(TestSourceDir() + "/" + descriptor_file_name)) {
+ return;
+ }
+
+ MockErrorCollector error_collector;
+ DiskSourceTree source_tree;
+ Importer importer(&source_tree, &error_collector);
+ GenerateAndTest generate_test;
+
+ generate_test.SetParameter("base_namespace=Google.Protobuf");
+ source_tree.MapPath("", TestSourceDir());
+ generate_test.Run(importer.Import("google/protobuf/descriptor.proto"),
+ "Reflection/Descriptor.cs",
+ "../csharp/src/Google.Protobuf/Reflection/Descriptor.cs");
+ generate_test.Run(importer.Import("google/protobuf/any.proto"),
+ "WellKnownTypes/Any.cs",
+ "../csharp/src/Google.Protobuf/WellKnownTypes/Any.cs");
+ generate_test.Run(importer.Import("google/protobuf/api.proto"),
+ "WellKnownTypes/Api.cs",
+ "../csharp/src/Google.Protobuf/WellKnownTypes/Api.cs");
+ generate_test.Run(importer.Import("google/protobuf/duration.proto"),
+ "WellKnownTypes/Duration.cs",
+ "../csharp/src/Google.Protobuf/WellKnownTypes/Duration.cs");
+ generate_test.Run(importer.Import("google/protobuf/empty.proto"),
+ "WellKnownTypes/Empty.cs",
+ "../csharp/src/Google.Protobuf/WellKnownTypes/Empty.cs");
+ generate_test.Run(importer.Import("google/protobuf/field_mask.proto"),
+ "WellKnownTypes/FieldMask.cs",
+ "../csharp/src/Google.Protobuf/WellKnownTypes/FieldMask.cs");
+ generate_test.Run(importer.Import("google/protobuf/source_context.proto"),
+ "WellKnownTypes/SourceContext.cs",
+ "../csharp/src/Google.Protobuf/WellKnownTypes/SourceContext.cs");
+ generate_test.Run(importer.Import("google/protobuf/struct.proto"),
+ "WellKnownTypes/Struct.cs",
+ "../csharp/src/Google.Protobuf/WellKnownTypes/Struct.cs");
+ generate_test.Run(importer.Import("google/protobuf/timestamp.proto"),
+ "WellKnownTypes/Timestamp.cs",
+ "../csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs");
+ generate_test.Run(importer.Import("google/protobuf/type.proto"),
+ "WellKnownTypes/Type.cs",
+ "../csharp/src/Google.Protobuf/WellKnownTypes/Type.cs");
+ generate_test.Run(importer.Import("google/protobuf/wrappers.proto"),
+ "WellKnownTypes/Wrappers.cs",
+ "../csharp/src/Google.Protobuf/WellKnownTypes/Wrappers.cs");
+
+ generate_test.SetParameter("");
+ source_tree.MapPath("", TestSourceDir() + "/../conformance");
+ generate_test.Run(importer.Import("conformance.proto"),
+ "Conformance.cs",
+ "../csharp/src/Google.Protobuf.Conformance/Conformance.cs");
+
+ EXPECT_EQ("", error_collector.text_);
+}
+
+} // namespace
+
+} // namespace csharp
+} // namespace compiler
+} // namespace protobuf
+} // namespace google
diff --git a/src/google/protobuf/compiler/csharp/csharp_enum.cc b/src/google/protobuf/compiler/csharp/csharp_enum.cc
index 9e4da1ed..9759e3ef 100644
--- a/src/google/protobuf/compiler/csharp/csharp_enum.cc
+++ b/src/google/protobuf/compiler/csharp/csharp_enum.cc
@@ -65,6 +65,7 @@ void EnumGenerator::Generate(io::Printer* printer) {
"name", descriptor_->name());
printer->Indent();
std::set<string> used_names;
+ std::set<int> used_number;
for (int i = 0; i < descriptor_->value_count(); i++) {
WriteEnumValueDocComment(printer, descriptor_->value(i));
string original_name = descriptor_->value(i)->name();
@@ -76,10 +77,18 @@ void EnumGenerator::Generate(io::Printer* printer) {
<< ") in " << descriptor_->name() << "; adding underscore to distinguish";
name += "_";
}
- printer->Print("[pbr::OriginalName(\"$original_name$\")] $name$ = $number$,\n",
- "original_name", original_name,
- "name", name,
- "number", SimpleItoa(descriptor_->value(i)->number()));
+ int number = descriptor_->value(i)->number();
+ if (!used_number.insert(number).second) {
+ printer->Print("[pbr::OriginalName(\"$original_name$\", PreferredAlias = false)] $name$ = $number$,\n",
+ "original_name", original_name,
+ "name", name,
+ "number", SimpleItoa(number));
+ } else {
+ printer->Print("[pbr::OriginalName(\"$original_name$\")] $name$ = $number$,\n",
+ "original_name", original_name,
+ "name", name,
+ "number", SimpleItoa(number));
+ }
}
printer->Outdent();
printer->Print("}\n");
diff --git a/src/google/protobuf/compiler/csharp/csharp_enum_field.cc b/src/google/protobuf/compiler/csharp/csharp_enum_field.cc
index 67c0b596..9ceffa8c 100644
--- a/src/google/protobuf/compiler/csharp/csharp_enum_field.cc
+++ b/src/google/protobuf/compiler/csharp/csharp_enum_field.cc
@@ -89,6 +89,10 @@ EnumOneofFieldGenerator::EnumOneofFieldGenerator(
EnumOneofFieldGenerator::~EnumOneofFieldGenerator() {
}
+void EnumOneofFieldGenerator::GenerateMergingCode(io::Printer* printer) {
+ printer->Print(variables_, "$property_name$ = other.$property_name$;\n");
+}
+
void EnumOneofFieldGenerator::GenerateParsingCode(io::Printer* printer) {
// TODO(jonskeet): What about if we read the default value?
printer->Print(
diff --git a/src/google/protobuf/compiler/csharp/csharp_enum_field.h b/src/google/protobuf/compiler/csharp/csharp_enum_field.h
index 9b7669ba..631632bc 100644
--- a/src/google/protobuf/compiler/csharp/csharp_enum_field.h
+++ b/src/google/protobuf/compiler/csharp/csharp_enum_field.h
@@ -64,6 +64,7 @@ class EnumOneofFieldGenerator : public PrimitiveOneofFieldGenerator {
const Options *options);
~EnumOneofFieldGenerator();
+ virtual void GenerateMergingCode(io::Printer* printer);
virtual void GenerateParsingCode(io::Printer* printer);
virtual void GenerateSerializationCode(io::Printer* printer);
virtual void GenerateSerializedSizeCode(io::Printer* printer);
diff --git a/src/google/protobuf/compiler/csharp/csharp_field_base.cc b/src/google/protobuf/compiler/csharp/csharp_field_base.cc
index e2011b76..ecf29ece 100644
--- a/src/google/protobuf/compiler/csharp/csharp_field_base.cc
+++ b/src/google/protobuf/compiler/csharp/csharp_field_base.cc
@@ -54,7 +54,7 @@ namespace compiler {
namespace csharp {
void FieldGeneratorBase::SetCommonFieldVariables(
- map<string, string>* variables) {
+ std::map<string, string>* 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.
@@ -92,7 +92,7 @@ void FieldGeneratorBase::SetCommonFieldVariables(
}
void FieldGeneratorBase::SetCommonOneofFieldVariables(
- map<string, string>* variables) {
+ std::map<string, string>* variables) {
(*variables)["oneof_name"] = oneof_name();
(*variables)["has_property_check"] =
oneof_name() + "Case_ == " + oneof_property_name() +
@@ -122,8 +122,10 @@ void FieldGeneratorBase::GenerateCodecCode(io::Printer* printer) {
}
void FieldGeneratorBase::AddDeprecatedFlag(io::Printer* printer) {
- if (descriptor_->options().deprecated())
- {
+ if (descriptor_->options().deprecated()) {
+ printer->Print("[global::System.ObsoleteAttribute]\n");
+ } else if (descriptor_->type() == FieldDescriptor::TYPE_MESSAGE &&
+ descriptor_->message_type()->options().deprecated()) {
printer->Print("[global::System.ObsoleteAttribute]\n");
}
}
@@ -320,9 +322,9 @@ std::string FieldGeneratorBase::default_value(const FieldDescriptor* descriptor)
}
case FieldDescriptor::TYPE_DOUBLE: {
double value = descriptor->default_value_double();
- if (value == numeric_limits<double>::infinity()) {
+ if (value == std::numeric_limits<double>::infinity()) {
return "double.PositiveInfinity";
- } else if (value == -numeric_limits<double>::infinity()) {
+ } else if (value == -std::numeric_limits<double>::infinity()) {
return "double.NegativeInfinity";
} else if (MathLimits<double>::IsNaN(value)) {
return "double.NaN";
@@ -331,9 +333,9 @@ std::string FieldGeneratorBase::default_value(const FieldDescriptor* descriptor)
}
case FieldDescriptor::TYPE_FLOAT: {
float value = descriptor->default_value_float();
- if (value == numeric_limits<float>::infinity()) {
+ if (value == std::numeric_limits<float>::infinity()) {
return "float.PositiveInfinity";
- } else if (value == -numeric_limits<float>::infinity()) {
+ } else if (value == -std::numeric_limits<float>::infinity()) {
return "float.NegativeInfinity";
} else if (MathLimits<float>::IsNaN(value)) {
return "float.NaN";
diff --git a/src/google/protobuf/compiler/csharp/csharp_field_base.h b/src/google/protobuf/compiler/csharp/csharp_field_base.h
index 4109f3ca..df26853b 100644
--- a/src/google/protobuf/compiler/csharp/csharp_field_base.h
+++ b/src/google/protobuf/compiler/csharp/csharp_field_base.h
@@ -66,14 +66,14 @@ class FieldGeneratorBase : public SourceGeneratorBase {
protected:
const FieldDescriptor* descriptor_;
const int fieldOrdinal_;
- map<string, string> variables_;
+ std::map<string, string> variables_;
void AddDeprecatedFlag(io::Printer* printer);
void AddNullCheck(io::Printer* printer);
void AddNullCheck(io::Printer* printer, const std::string& name);
void AddPublicMemberAttributes(io::Printer* printer);
- void SetCommonOneofFieldVariables(map<string, string>* variables);
+ void SetCommonOneofFieldVariables(std::map<string, string>* variables);
std::string oneof_property_name();
std::string oneof_name();
@@ -89,7 +89,7 @@ class FieldGeneratorBase : public SourceGeneratorBase {
std::string capitalized_type_name();
private:
- void SetCommonFieldVariables(map<string, string>* variables);
+ void SetCommonFieldVariables(std::map<string, string>* variables);
std::string GetStringDefaultValueInternal();
std::string GetBytesDefaultValueInternal();
diff --git a/src/google/protobuf/compiler/csharp/csharp_generator.h b/src/google/protobuf/compiler/csharp/csharp_generator.h
index fd41d852..c8b19529 100644
--- a/src/google/protobuf/compiler/csharp/csharp_generator.h
+++ b/src/google/protobuf/compiler/csharp/csharp_generator.h
@@ -48,6 +48,7 @@ namespace csharp {
// CodeGenerator with the CommandLineInterface in your main() function.
class LIBPROTOC_EXPORT Generator
: public google::protobuf::compiler::CodeGenerator {
+public:
virtual bool Generate(
const FileDescriptor* file,
const string& parameter,
@@ -61,4 +62,3 @@ class LIBPROTOC_EXPORT Generator
} // namespace google
#endif // GOOGLE_PROTOBUF_COMPILER_CSHARP_GENERATOR_H__
-
diff --git a/src/google/protobuf/compiler/csharp/csharp_helpers.h b/src/google/protobuf/compiler/csharp/csharp_helpers.h
index 1563ca7e..c317ad0e 100644
--- a/src/google/protobuf/compiler/csharp/csharp_helpers.h
+++ b/src/google/protobuf/compiler/csharp/csharp_helpers.h
@@ -120,6 +120,22 @@ inline bool IsDescriptorProto(const FileDescriptor* descriptor) {
return descriptor->name() == "google/protobuf/descriptor.proto";
}
+// Determines whether the given message is an options message within descriptor.proto.
+inline bool IsDescriptorOptionMessage(const Descriptor* descriptor) {
+ if (!IsDescriptorProto(descriptor->file())) {
+ return false;
+ }
+ const string name = descriptor->full_name();
+ return name == "google.protobuf.FileOptions" ||
+ name == "google.protobuf.MessageOptions" ||
+ name == "google.protobuf.FieldOptions" ||
+ name == "google.protobuf.OneofOptions" ||
+ name == "google.protobuf.EnumOptions" ||
+ name == "google.protobuf.EnumValueOptions" ||
+ name == "google.protobuf.ServiceOptions" ||
+ name == "google.protobuf.MethodOptions";
+}
+
inline bool IsWrapperType(const FieldDescriptor* descriptor) {
return descriptor->type() == FieldDescriptor::TYPE_MESSAGE &&
descriptor->message_type()->file()->name() == "google/protobuf/wrappers.proto";
diff --git a/src/google/protobuf/compiler/csharp/csharp_message.cc b/src/google/protobuf/compiler/csharp/csharp_message.cc
index ed744854..ad9f8a16 100644
--- a/src/google/protobuf/compiler/csharp/csharp_message.cc
+++ b/src/google/protobuf/compiler/csharp/csharp_message.cc
@@ -98,12 +98,20 @@ const std::vector<const FieldDescriptor*>& MessageGenerator::fields_by_number()
return fields_by_number_;
}
+void MessageGenerator::AddDeprecatedFlag(io::Printer* printer) {
+ if (descriptor_->options().deprecated()) {
+ printer->Print("[global::System.ObsoleteAttribute]\n");
+ }
+}
+
void MessageGenerator::Generate(io::Printer* printer) {
- map<string, string> vars;
+ std::map<string, string> vars;
vars["class_name"] = class_name();
vars["access_level"] = class_access_level();
WriteMessageDocComment(printer, descriptor_);
+ AddDeprecatedFlag(printer);
+
printer->Print(
vars,
"$access_level$ sealed partial class $class_name$ : pb::IMessage<$class_name$> {\n");
@@ -115,6 +123,7 @@ void MessageGenerator::Generate(io::Printer* printer) {
"private static readonly pb::MessageParser<$class_name$> _parser = new pb::MessageParser<$class_name$>(() => new $class_name$());\n");
WriteGeneratedCodeAttributes(printer);
+
printer->Print(
vars,
"public static pb::MessageParser<$class_name$> Parser { get { return _parser; } }\n\n");
@@ -142,6 +151,12 @@ void MessageGenerator::Generate(io::Printer* printer) {
" get { return Descriptor; }\n"
"}\n"
"\n");
+ // CustomOptions property, only for options messages
+ if (IsDescriptorOptionMessage(descriptor_)) {
+ printer->Print(
+ "internal CustomOptions CustomOptions{ get; private set; } = CustomOptions.Empty;\n"
+ "\n");
+ }
// Parameterless constructor and partial OnConstruction method.
WriteGeneratedCodeAttributes(printer);
@@ -265,7 +280,7 @@ bool MessageGenerator::HasNestedGeneratedTypes()
}
void MessageGenerator::GenerateCloningCode(io::Printer* printer) {
- map<string, string> vars;
+ std::map<string, string> vars;
WriteGeneratedCodeAttributes(printer);
vars["class_name"] = class_name();
printer->Print(
@@ -318,7 +333,7 @@ void MessageGenerator::GenerateFreezingCode(io::Printer* printer) {
}
void MessageGenerator::GenerateFrameworkMethods(io::Printer* printer) {
- map<string, string> vars;
+ std::map<string, string> vars;
vars["class_name"] = class_name();
// Equality
@@ -417,7 +432,7 @@ void MessageGenerator::GenerateMergingMethods(io::Printer* printer) {
// Note: These are separate from GenerateMessageSerializationMethods()
// because they need to be generated even for messages that are optimized
// for code size.
- map<string, string> vars;
+ std::map<string, string> vars;
vars["class_name"] = class_name();
WriteGeneratedCodeAttributes(printer);
@@ -448,9 +463,12 @@ void MessageGenerator::GenerateMergingMethods(io::Printer* printer) {
vars["field_property_name"] = GetPropertyName(field);
printer->Print(
vars,
- "case $property_name$OneofCase.$field_property_name$:\n"
- " $field_property_name$ = other.$field_property_name$;\n"
- " break;\n");
+ "case $property_name$OneofCase.$field_property_name$:\n");
+ printer->Indent();
+ scoped_ptr<FieldGeneratorBase> generator(CreateFieldGeneratorInternal(field));
+ generator->GenerateMergingCode(printer);
+ printer->Print("break;\n");
+ printer->Outdent();
}
printer->Outdent();
printer->Print("}\n\n");
@@ -466,10 +484,18 @@ void MessageGenerator::GenerateMergingMethods(io::Printer* printer) {
" switch(tag) {\n");
printer->Indent();
printer->Indent();
- printer->Print(
- "default:\n"
- " input.SkipLastField();\n" // We're not storing the data, but we still need to consume it.
- " break;\n");
+ // Option messages need to store unknown fields so that options can be parsed later.
+ if (IsDescriptorOptionMessage(descriptor_)) {
+ printer->Print(
+ "default:\n"
+ " CustomOptions = CustomOptions.ReadOrSkipUnknownField(input);\n"
+ " break;\n");
+ } else {
+ printer->Print(
+ "default:\n"
+ " input.SkipLastField();\n" // We're not storing the data, but we still need to consume it.
+ " break;\n");
+ }
for (int i = 0; i < fields_by_number().size(); i++) {
const FieldDescriptor* field = fields_by_number()[i];
internal::WireFormatLite::WireType wt =
diff --git a/src/google/protobuf/compiler/csharp/csharp_message.h b/src/google/protobuf/compiler/csharp/csharp_message.h
index f794d68d..e7f3b4d0 100644
--- a/src/google/protobuf/compiler/csharp/csharp_message.h
+++ b/src/google/protobuf/compiler/csharp/csharp_message.h
@@ -69,6 +69,8 @@ class MessageGenerator : public SourceGeneratorBase {
bool HasNestedGeneratedTypes();
+ void AddDeprecatedFlag(io::Printer* printer);
+
std::string class_name();
std::string full_class_name();
diff --git a/src/google/protobuf/compiler/csharp/csharp_message_field.cc b/src/google/protobuf/compiler/csharp/csharp_message_field.cc
index 438f3102..59b7edfb 100644
--- a/src/google/protobuf/compiler/csharp/csharp_message_field.cc
+++ b/src/google/protobuf/compiler/csharp/csharp_message_field.cc
@@ -171,6 +171,14 @@ void MessageOneofFieldGenerator::GenerateMembers(io::Printer* printer) {
"}\n");
}
+void MessageOneofFieldGenerator::GenerateMergingCode(io::Printer* printer) {
+ printer->Print(variables_,
+ "if ($property_name$ == null) {\n"
+ " $property_name$ = new $type_name$();\n"
+ "}\n"
+ "$property_name$.MergeFrom(other.$property_name$);\n");
+}
+
void MessageOneofFieldGenerator::GenerateParsingCode(io::Printer* printer) {
// TODO(jonskeet): We may be able to do better than this
printer->Print(
diff --git a/src/google/protobuf/compiler/csharp/csharp_message_field.h b/src/google/protobuf/compiler/csharp/csharp_message_field.h
index 7d614756..c41ee88a 100644
--- a/src/google/protobuf/compiler/csharp/csharp_message_field.h
+++ b/src/google/protobuf/compiler/csharp/csharp_message_field.h
@@ -74,6 +74,7 @@ class MessageOneofFieldGenerator : public MessageFieldGenerator {
virtual void GenerateCloningCode(io::Printer* printer);
virtual void GenerateMembers(io::Printer* printer);
+ virtual void GenerateMergingCode(io::Printer* printer);
virtual void WriteToString(io::Printer* printer);
virtual void GenerateParsingCode(io::Printer* printer);
diff --git a/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc b/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc
index 169122e6..931adb4a 100644
--- a/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc
+++ b/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc
@@ -196,6 +196,10 @@ void PrimitiveOneofFieldGenerator::GenerateMembers(io::Printer* printer) {
"}\n");
}
+void PrimitiveOneofFieldGenerator::GenerateMergingCode(io::Printer* printer) {
+ printer->Print(variables_, "$property_name$ = other.$property_name$;\n");
+}
+
void PrimitiveOneofFieldGenerator::WriteToString(io::Printer* printer) {
printer->Print(variables_,
"PrintField(\"$descriptor_name$\", $has_property_check$, $oneof_name$_, writer);\n");
diff --git a/src/google/protobuf/compiler/csharp/csharp_primitive_field.h b/src/google/protobuf/compiler/csharp/csharp_primitive_field.h
index 5f466fc4..ca7b8b3d 100644
--- a/src/google/protobuf/compiler/csharp/csharp_primitive_field.h
+++ b/src/google/protobuf/compiler/csharp/csharp_primitive_field.h
@@ -78,6 +78,7 @@ class PrimitiveOneofFieldGenerator : public PrimitiveFieldGenerator {
virtual void GenerateCloningCode(io::Printer* printer);
virtual void GenerateMembers(io::Printer* printer);
+ virtual void GenerateMergingCode(io::Printer* printer);
virtual void WriteToString(io::Printer* printer);
virtual void GenerateParsingCode(io::Printer* printer);
diff --git a/src/google/protobuf/compiler/csharp/csharp_wrapper_field.cc b/src/google/protobuf/compiler/csharp/csharp_wrapper_field.cc
index 797d498e..997969a0 100644
--- a/src/google/protobuf/compiler/csharp/csharp_wrapper_field.cc
+++ b/src/google/protobuf/compiler/csharp/csharp_wrapper_field.cc
@@ -181,6 +181,10 @@ void WrapperOneofFieldGenerator::GenerateMembers(io::Printer* printer) {
"}\n");
}
+void WrapperOneofFieldGenerator::GenerateMergingCode(io::Printer* printer) {
+ printer->Print(variables_, "$property_name$ = other.$property_name$;\n");
+}
+
void WrapperOneofFieldGenerator::GenerateParsingCode(io::Printer* printer) {
printer->Print(
variables_,
diff --git a/src/google/protobuf/compiler/csharp/csharp_wrapper_field.h b/src/google/protobuf/compiler/csharp/csharp_wrapper_field.h
index 250dfd25..452531fb 100644
--- a/src/google/protobuf/compiler/csharp/csharp_wrapper_field.h
+++ b/src/google/protobuf/compiler/csharp/csharp_wrapper_field.h
@@ -75,6 +75,7 @@ class WrapperOneofFieldGenerator : public WrapperFieldGenerator {
~WrapperOneofFieldGenerator();
virtual void GenerateMembers(io::Printer* printer);
+ virtual void GenerateMergingCode(io::Printer* printer);
virtual void GenerateParsingCode(io::Printer* printer);
virtual void GenerateSerializationCode(io::Printer* printer);
virtual void GenerateSerializedSizeCode(io::Printer* printer);
diff --git a/src/google/protobuf/compiler/importer.cc b/src/google/protobuf/compiler/importer.cc
index 462748b9..9792ffe8 100644
--- a/src/google/protobuf/compiler/importer.cc
+++ b/src/google/protobuf/compiler/importer.cc
@@ -32,8 +32,9 @@
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
+
#ifdef _MSC_VER
-#include <io.h>
+#include <direct.h>
#else
#include <unistd.h>
#endif
@@ -54,16 +55,21 @@
#include <google/protobuf/io/tokenizer.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/stubs/strutil.h>
+#include <google/protobuf/stubs/io_win32.h>
+
+#ifdef _WIN32
+#include <ctype.h>
+#endif
namespace google {
namespace protobuf {
namespace compiler {
-#ifdef _WIN32
-#ifndef F_OK
-#define F_OK 00 // not defined by MSVC for whatever reason
-#endif
-#include <ctype.h>
+#ifdef _MSC_VER
+// DO NOT include <io.h>, instead create functions in io_win32.{h,cc} and import
+// them like we do below.
+using google::protobuf::internal::win32::access;
+using google::protobuf::internal::win32::open;
#endif
// Returns true if the text looks like a Windows-style absolute path, starting
@@ -222,6 +228,7 @@ void Importer::ClearUnusedImportTrackFiles() {
pool_.ClearUnusedImportTrackFiles();
}
+
// ===================================================================
SourceTree::~SourceTree() {}
@@ -294,10 +301,8 @@ static string CanonicalizePath(string path) {
}
static inline bool ContainsParentReference(const string& path) {
- return path == ".." ||
- HasPrefixString(path, "../") ||
- HasSuffixString(path, "/..") ||
- path.find("/../") != string::npos;
+ return path == ".." || HasPrefixString(path, "../") ||
+ HasSuffixString(path, "/..") || path.find("/../") != string::npos;
}
// Maps a file from an old location to a new one. Typically, old_prefix is
@@ -327,8 +332,7 @@ static bool ApplyMapping(const string& filename,
// We do not allow the file name to use "..".
return false;
}
- if (HasPrefixString(filename, "/") ||
- IsWindowsAbsolutePath(filename)) {
+ if (HasPrefixString(filename, "/") || IsWindowsAbsolutePath(filename)) {
// This is an absolute path, so it isn't matched by the empty string.
return false;
}
diff --git a/src/google/protobuf/compiler/importer.h b/src/google/protobuf/compiler/importer.h
index 759636e1..a4ffcf87 100644
--- a/src/google/protobuf/compiler/importer.h
+++ b/src/google/protobuf/compiler/importer.h
@@ -175,6 +175,7 @@ class LIBPROTOBUF_EXPORT Importer {
void AddUnusedImportTrackFile(const string& file_name);
void ClearUnusedImportTrackFiles();
+
private:
SourceTreeDescriptorDatabase database_;
DescriptorPool pool_;
diff --git a/src/google/protobuf/compiler/importer_unittest.cc b/src/google/protobuf/compiler/importer_unittest.cc
index 00285bcc..a96ac853 100644
--- a/src/google/protobuf/compiler/importer_unittest.cc
+++ b/src/google/protobuf/compiler/importer_unittest.cc
@@ -47,11 +47,11 @@
#include <google/protobuf/testing/file.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/descriptor.h>
-#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/substitute.h>
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
#include <google/protobuf/stubs/map_util.h>
+#include <google/protobuf/stubs/strutil.h>
namespace google {
namespace protobuf {
diff --git a/src/google/protobuf/compiler/java/java_context.cc b/src/google/protobuf/compiler/java/java_context.cc
index b82fb3dd..0771d5e1 100644
--- a/src/google/protobuf/compiler/java/java_context.cc
+++ b/src/google/protobuf/compiler/java/java_context.cc
@@ -50,7 +50,7 @@ Context::Context(const FileDescriptor* file, const Options& options)
Context::~Context() {
}
-ClassNameResolver* Context::GetNameResolver() {
+ClassNameResolver* Context::GetNameResolver() const {
return name_resolver_.get();
}
@@ -154,7 +154,7 @@ void Context::InitializeFieldGeneratorInfoForFields(
for (int i = 0; i < fields.size(); ++i) {
const FieldDescriptor* field = fields[i];
FieldGeneratorInfo info;
- info.name = UnderscoresToCamelCase(field);
+ info.name = CamelCaseFieldName(field);
info.capitalized_name = UnderscoresToCapitalizedCamelCase(field);
// For fields conflicting with some other fields, we append the field
// number to their field names in generated code to avoid conflicts.
diff --git a/src/google/protobuf/compiler/java/java_context.h b/src/google/protobuf/compiler/java/java_context.h
index b22e7e3a..9a74c430 100644
--- a/src/google/protobuf/compiler/java/java_context.h
+++ b/src/google/protobuf/compiler/java/java_context.h
@@ -70,7 +70,7 @@ class Context {
// Get the name resolver associated with this context. The resolver
// can be used to map descriptors to Java class names.
- ClassNameResolver* GetNameResolver();
+ ClassNameResolver* GetNameResolver() const;
// Get the FieldGeneratorInfo for a given field.
const FieldGeneratorInfo* GetFieldGeneratorInfo(
diff --git a/src/google/protobuf/compiler/java/java_enum.cc b/src/google/protobuf/compiler/java/java_enum.cc
index b9ee00ff..d125ebe5 100644
--- a/src/google/protobuf/compiler/java/java_enum.cc
+++ b/src/google/protobuf/compiler/java/java_enum.cc
@@ -109,14 +109,16 @@ void EnumGenerator::Generate(io::Printer* printer) {
printer->Print(vars,
"$name$($index$, $number$),\n");
}
+ printer->Annotate("name", canonical_values_[i]);
}
if (SupportUnknownEnumValue(descriptor_->file())) {
if (ordinal_is_index) {
- printer->Print("UNRECOGNIZED(-1),\n");
+ printer->Print("${$UNRECOGNIZED$}$(-1),\n", "{", "", "}", "");
} else {
- printer->Print("UNRECOGNIZED(-1, -1),\n");
+ printer->Print("${$UNRECOGNIZED$}$(-1, -1),\n", "{", "", "}", "");
}
+ printer->Annotate("{", "}", descriptor_);
}
printer->Print(
@@ -133,15 +135,19 @@ void EnumGenerator::Generate(io::Printer* printer) {
WriteEnumValueDocComment(printer, aliases_[i].value);
printer->Print(vars,
"public static final $classname$ $name$ = $canonical_name$;\n");
+ printer->Annotate("name", aliases_[i].value);
}
for (int i = 0; i < descriptor_->value_count(); i++) {
std::map<string, string> vars;
vars["name"] = descriptor_->value(i)->name();
vars["number"] = SimpleItoa(descriptor_->value(i)->number());
+ vars["{"] = "";
+ vars["}"] = "";
WriteEnumValueDocComment(printer, descriptor_->value(i));
printer->Print(vars,
- "public static final int $name$_VALUE = $number$;\n");
+ "public static final int ${$$name$_VALUE$}$ = $number$;\n");
+ printer->Annotate("{", "}", descriptor_->value(i));
}
printer->Print("\n");
diff --git a/src/google/protobuf/compiler/java/java_enum_field.cc b/src/google/protobuf/compiler/java/java_enum_field.cc
index 279b9da4..9f7bb349 100644
--- a/src/google/protobuf/compiler/java/java_enum_field.cc
+++ b/src/google/protobuf/compiler/java/java_enum_field.cc
@@ -183,23 +183,26 @@ GenerateMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
+ "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $get_has_field_bit_message$;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
if (SupportUnknownEnumValue(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public int get$capitalized_name$Value() {\n"
+ "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n"
" return $name$_;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$() {\n"
+ "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" $type$ result = $type$.$for_number$($name$_);\n"
" return result == null ? $unknown$ : result;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
void ImmutableEnumFieldGenerator::
@@ -209,33 +212,38 @@ GenerateBuilderMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
+ "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $get_has_field_bit_builder$;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
if (SupportUnknownEnumValue(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public int get$capitalized_name$Value() {\n"
+ "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n"
" return $name$_;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder set$capitalized_name$Value(int value) {\n"
+ "$deprecation$public Builder "
+ "${$set$capitalized_name$Value$}$(int value) {\n"
" $name$_ = value;\n"
" $on_changed$\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$() {\n"
+ "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" $type$ result = $type$.$for_number$($name$_);\n"
" return result == null ? $unknown$ : result;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder set$capitalized_name$($type$ value) {\n"
+ "$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n"
" if (value == null) {\n"
" throw new NullPointerException();\n"
" }\n"
@@ -244,14 +252,16 @@ GenerateBuilderMembers(io::Printer* printer) const {
" $on_changed$\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder clear$capitalized_name$() {\n"
+ "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" $clear_has_field_bit_builder$\n"
" $name$_ = $default_number$;\n"
" $on_changed$\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
void ImmutableEnumFieldGenerator::
@@ -311,12 +321,8 @@ GenerateParsingCode(io::Printer* printer) const {
printer->Print(variables_,
"int rawValue = input.readEnum();\n"
"$type$ value = $type$.$for_number$(rawValue);\n"
- "if (value == null) {\n");
- if (PreserveUnknownFields(descriptor_->containing_type())) {
- printer->Print(variables_,
- " unknownFields.mergeVarintField($number$, rawValue);\n");
- }
- printer->Print(variables_,
+ "if (value == null) {\n"
+ " unknownFields.mergeVarintField($number$, rawValue);\n"
"} else {\n"
" $set_has_field_bit_message$\n"
" $name$_ = rawValue;\n"
@@ -386,23 +392,25 @@ GenerateMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
+ "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $has_oneof_case_message$;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
if (SupportUnknownEnumValue(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public int get$capitalized_name$Value() {\n"
+ "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" return (java.lang.Integer) $oneof_name$_;\n"
" }\n"
" return $default_number$;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$() {\n"
+ "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" $type$ result = $type$.$for_number$(\n"
" (java.lang.Integer) $oneof_name$_);\n"
@@ -410,6 +418,7 @@ GenerateMembers(io::Printer* printer) const {
" }\n"
" return $default$;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
void ImmutableEnumOneofFieldGenerator::
@@ -417,31 +426,35 @@ GenerateBuilderMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
+ "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $has_oneof_case_message$;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
if (SupportUnknownEnumValue(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public int get$capitalized_name$Value() {\n"
+ "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" return ((java.lang.Integer) $oneof_name$_).intValue();\n"
" }\n"
" return $default_number$;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder set$capitalized_name$Value(int value) {\n"
+ "$deprecation$public Builder "
+ "${$set$capitalized_name$Value$}$(int value) {\n"
" $set_oneof_case_message$;\n"
" $oneof_name$_ = value;\n"
" $on_changed$\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$() {\n"
+ "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" $type$ result = $type$.$for_number$(\n"
" (java.lang.Integer) $oneof_name$_);\n"
@@ -449,9 +462,10 @@ GenerateBuilderMembers(io::Printer* printer) const {
" }\n"
" return $default$;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder set$capitalized_name$($type$ value) {\n"
+ "$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n"
" if (value == null) {\n"
" throw new NullPointerException();\n"
" }\n"
@@ -460,9 +474,10 @@ GenerateBuilderMembers(io::Printer* printer) const {
" $on_changed$\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder clear$capitalized_name$() {\n"
+ "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" $clear_oneof_case_message$;\n"
" $oneof_name$_ = null;\n"
@@ -470,6 +485,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
" }\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
void ImmutableEnumOneofFieldGenerator::
@@ -502,12 +518,8 @@ GenerateParsingCode(io::Printer* printer) const {
printer->Print(variables_,
"int rawValue = input.readEnum();\n"
"$type$ value = $type$.$for_number$(rawValue);\n"
- "if (value == null) {\n");
- if (PreserveUnknownFields(descriptor_->containing_type())) {
- printer->Print(variables_,
- " unknownFields.mergeVarintField($number$, rawValue);\n");
- }
- printer->Print(variables_,
+ "if (value == null) {\n"
+ " unknownFields.mergeVarintField($number$, rawValue);\n"
"} else {\n"
" $set_oneof_case_message$;\n"
" $oneof_name$_ = rawValue;\n"
@@ -621,32 +633,38 @@ GenerateMembers(io::Printer* printer) const {
PrintExtraFieldInfo(variables_, printer);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public java.util.List<$type$> get$capitalized_name$List() {\n"
+ "$deprecation$public java.util.List<$type$> "
+ "${$get$capitalized_name$List$}$() {\n"
" return new com.google.protobuf.Internal.ListAdapter<\n"
" java.lang.Integer, $type$>($name$_, $name$_converter_);\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public int get$capitalized_name$Count() {\n"
+ "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n"
" return $name$_.size();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$(int index) {\n"
+ "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n"
" return $name$_converter_.convert($name$_.get(index));\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
if (SupportUnknownEnumValue(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.util.List<java.lang.Integer>\n"
- "get$capitalized_name$ValueList() {\n"
+ "${$get$capitalized_name$ValueList$}$() {\n"
" return $name$_;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public int get$capitalized_name$Value(int index) {\n"
+ "$deprecation$public int ${$get$capitalized_name$Value$}$(int index) {\n"
" return $name$_.get(index);\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
if (descriptor_->is_packed() &&
@@ -684,23 +702,27 @@ GenerateBuilderMembers(io::Printer* printer) const {
// could hold on to the returned list and modify it after the message
// has been built, thus mutating the message which is supposed to be
// immutable.
- "$deprecation$public java.util.List<$type$> get$capitalized_name$List() {\n"
+ "$deprecation$public java.util.List<$type$> "
+ "${$get$capitalized_name$List$}$() {\n"
" return new com.google.protobuf.Internal.ListAdapter<\n"
" java.lang.Integer, $type$>($name$_, $name$_converter_);\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public int get$capitalized_name$Count() {\n"
+ "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n"
" return $name$_.size();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$(int index) {\n"
+ "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n"
" return $name$_converter_.convert($name$_.get(index));\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder set$capitalized_name$(\n"
+ "$deprecation$public Builder ${$set$capitalized_name$$}$(\n"
" int index, $type$ value) {\n"
" if (value == null) {\n"
" throw new NullPointerException();\n"
@@ -710,9 +732,10 @@ GenerateBuilderMembers(io::Printer* printer) const {
" $on_changed$\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder add$capitalized_name$($type$ value) {\n"
+ "$deprecation$public Builder ${$add$capitalized_name$$}$($type$ value) {\n"
" if (value == null) {\n"
" throw new NullPointerException();\n"
" }\n"
@@ -721,9 +744,10 @@ GenerateBuilderMembers(io::Printer* printer) const {
" $on_changed$\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder addAll$capitalized_name$(\n"
+ "$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n"
" java.lang.Iterable<? extends $type$> values) {\n"
" ensure$capitalized_name$IsMutable();\n"
" for ($type$ value : values) {\n"
@@ -732,47 +756,54 @@ GenerateBuilderMembers(io::Printer* printer) const {
" $on_changed$\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder clear$capitalized_name$() {\n"
+ "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" $name$_ = java.util.Collections.emptyList();\n"
" $clear_mutable_bit_builder$;\n"
" $on_changed$\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
if (SupportUnknownEnumValue(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.util.List<java.lang.Integer>\n"
- "get$capitalized_name$ValueList() {\n"
+ "${$get$capitalized_name$ValueList$}$() {\n"
" return java.util.Collections.unmodifiableList($name$_);\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public int get$capitalized_name$Value(int index) {\n"
+ "$deprecation$public int ${$get$capitalized_name$Value$}$(int index) {\n"
" return $name$_.get(index);\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder set$capitalized_name$Value(\n"
+ "$deprecation$public Builder ${$set$capitalized_name$Value$}$(\n"
" int index, int value) {\n"
" ensure$capitalized_name$IsMutable();\n"
" $name$_.set(index, value);\n"
" $on_changed$\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder add$capitalized_name$Value(int value) {\n"
+ "$deprecation$public Builder "
+ "${$add$capitalized_name$Value$}$(int value) {\n"
" ensure$capitalized_name$IsMutable();\n"
" $name$_.add(value);\n"
" $on_changed$\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder addAll$capitalized_name$Value(\n"
+ "$deprecation$public Builder ${$addAll$capitalized_name$Value$}$(\n"
" java.lang.Iterable<java.lang.Integer> values) {\n"
" ensure$capitalized_name$IsMutable();\n"
" for (int value : values) {\n"
@@ -781,6 +812,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
" $on_changed$\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
}
@@ -848,12 +880,8 @@ GenerateParsingCode(io::Printer* printer) const {
printer->Print(variables_,
"int rawValue = input.readEnum();\n"
"$type$ value = $type$.$for_number$(rawValue);\n"
- "if (value == null) {\n");
- if (PreserveUnknownFields(descriptor_->containing_type())) {
- printer->Print(variables_,
- " unknownFields.mergeVarintField($number$, rawValue);\n");
- }
- printer->Print(variables_,
+ "if (value == null) {\n"
+ " unknownFields.mergeVarintField($number$, rawValue);\n"
"} else {\n"
" if (!$get_mutable_bit_parser$) {\n"
" $name$_ = new java.util.ArrayList<java.lang.Integer>();\n"
diff --git a/src/google/protobuf/compiler/java/java_enum_field_lite.cc b/src/google/protobuf/compiler/java/java_enum_field_lite.cc
index f1dc47fc..a4de1e23 100644
--- a/src/google/protobuf/compiler/java/java_enum_field_lite.cc
+++ b/src/google/protobuf/compiler/java/java_enum_field_lite.cc
@@ -76,6 +76,7 @@ void SetEnumVariables(const FieldDescriptor* descriptor,
// by the proto compiler
(*variables)["deprecation"] = descriptor->options().deprecated()
? "@java.lang.Deprecated " : "";
+ (*variables)["required"] = descriptor->is_required() ? "true" : "false";
if (SupportFieldPresence(descriptor->file())) {
// For singular messages and builders, one bit is used for the hasField bit.
@@ -164,23 +165,26 @@ GenerateMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
+ "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $get_has_field_bit_message$;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
if (SupportUnknownEnumValue(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public int get$capitalized_name$Value() {\n"
+ "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n"
" return $name$_;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$() {\n"
+ "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" $type$ result = $type$.forNumber($name$_);\n"
" return result == null ? $unknown$ : result;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
// Generate private setters for the builder to proxy into.
if (SupportUnknownEnumValue(descriptor_->file())) {
@@ -213,43 +217,50 @@ GenerateBuilderMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
+ "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return instance.has$capitalized_name$();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
if (SupportUnknownEnumValue(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public int get$capitalized_name$Value() {\n"
+ "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n"
" return instance.get$capitalized_name$Value();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder set$capitalized_name$Value(int value) {\n"
+ "$deprecation$public Builder "
+ "${$set$capitalized_name$Value$}$(int value) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$Value(value);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$() {\n"
+ "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return instance.get$capitalized_name$();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder set$capitalized_name$($type$ value) {\n"
+ "$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$(value);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder clear$capitalized_name$() {\n"
+ "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" copyOnWrite();\n"
" instance.clear$capitalized_name$();\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
void ImmutableEnumFieldLiteGenerator::
@@ -295,12 +306,8 @@ GenerateParsingCode(io::Printer* printer) const {
printer->Print(variables_,
"int rawValue = input.readEnum();\n"
"$type$ value = $type$.forNumber(rawValue);\n"
- "if (value == null) {\n");
- if (PreserveUnknownFields(descriptor_->containing_type())) {
- printer->Print(variables_,
- " super.mergeVarintField($number$, rawValue);\n");
- }
- printer->Print(variables_,
+ "if (value == null) {\n"
+ " super.mergeVarintField($number$, rawValue);\n"
"} else {\n"
" $set_has_field_bit_message$\n"
" $name$_ = rawValue;\n"
@@ -313,6 +320,7 @@ GenerateParsingDoneCode(io::Printer* printer) const {
// noop for enums
}
+
void ImmutableEnumFieldLiteGenerator::
GenerateSerializationCode(io::Printer* printer) const {
printer->Print(variables_,
@@ -370,29 +378,32 @@ GenerateMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
+ "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $has_oneof_case_message$;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
if (SupportUnknownEnumValue(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public int get$capitalized_name$Value() {\n"
+ "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" return (java.lang.Integer) $oneof_name$_;\n"
" }\n"
" return $default_number$;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$() {\n"
+ "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" $type$ result = $type$.forNumber((java.lang.Integer) $oneof_name$_);\n"
" return result == null ? $unknown$ : result;\n"
" }\n"
" return $default$;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
// Generate private setters for the builder to proxy into.
if (SupportUnknownEnumValue(descriptor_->file())) {
@@ -422,48 +433,56 @@ GenerateMembers(io::Printer* printer) const {
"}\n");
}
+
void ImmutableEnumOneofFieldLiteGenerator::
GenerateBuilderMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
+ "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return instance.has$capitalized_name$();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
if (SupportUnknownEnumValue(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public int get$capitalized_name$Value() {\n"
+ "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n"
" return instance.get$capitalized_name$Value();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder set$capitalized_name$Value(int value) {\n"
+ "$deprecation$public Builder "
+ "${$set$capitalized_name$Value$}$(int value) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$Value(value);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$() {\n"
+ "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return instance.get$capitalized_name$();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder set$capitalized_name$($type$ value) {\n"
+ "$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$(value);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder clear$capitalized_name$() {\n"
+ "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" copyOnWrite();\n"
" instance.clear$capitalized_name$();\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
void ImmutableEnumOneofFieldLiteGenerator::
@@ -484,12 +503,8 @@ GenerateParsingCode(io::Printer* printer) const {
printer->Print(variables_,
"int rawValue = input.readEnum();\n"
"$type$ value = $type$.forNumber(rawValue);\n"
- "if (value == null) {\n");
- if (PreserveUnknownFields(descriptor_->containing_type())) {
- printer->Print(variables_,
- " super.mergeVarintField($number$, rawValue);\n");
- }
- printer->Print(variables_,
+ "if (value == null) {\n"
+ " super.mergeVarintField($number$, rawValue);\n"
"} else {\n"
" $set_oneof_case_message$;\n"
" $oneof_name$_ = rawValue;\n"
@@ -604,35 +619,41 @@ GenerateMembers(io::Printer* printer) const {
PrintExtraFieldInfo(variables_, printer);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public java.util.List<$type$> get$capitalized_name$List() {\n"
+ "$deprecation$public java.util.List<$type$> "
+ "${$get$capitalized_name$List$}$() {\n"
" return new com.google.protobuf.Internal.ListAdapter<\n"
" java.lang.Integer, $type$>($name$_, $name$_converter_);\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public int get$capitalized_name$Count() {\n"
+ "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n"
" return $name$_.size();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$(int index) {\n"
+ "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n"
" return $name$_converter_.convert($name$_.getInt(index));\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
if (SupportUnknownEnumValue(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.util.List<java.lang.Integer>\n"
- "get$capitalized_name$ValueList() {\n"
+ "${$get$capitalized_name$ValueList$}$() {\n"
" return $name$_;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public int get$capitalized_name$Value(int index) {\n"
+ "$deprecation$public int ${$get$capitalized_name$Value$}$(int index) {\n"
" return $name$_.getInt(index);\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
- if (descriptor_->options().packed() &&
+ if (descriptor_->is_packed() &&
context_->HasGeneratedMethods(descriptor_->containing_type())) {
printer->Print(variables_,
"private int $name$MemoizedSerializedSize;\n");
@@ -706,89 +727,104 @@ GenerateMembers(io::Printer* printer) const {
}
}
+
void RepeatedImmutableEnumFieldLiteGenerator::
GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public java.util.List<$type$> get$capitalized_name$List() {\n"
+ "$deprecation$public java.util.List<$type$> "
+ "${$get$capitalized_name$List$}$() {\n"
" return instance.get$capitalized_name$List();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public int get$capitalized_name$Count() {\n"
+ "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n"
" return instance.get$capitalized_name$Count();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$(int index) {\n"
+ "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n"
" return instance.get$capitalized_name$(index);\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder set$capitalized_name$(\n"
+ "$deprecation$public Builder ${$set$capitalized_name$$}$(\n"
" int index, $type$ value) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$(index, value);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder add$capitalized_name$($type$ value) {\n"
+ "$deprecation$public Builder ${$add$capitalized_name$$}$($type$ value) {\n"
" copyOnWrite();\n"
" instance.add$capitalized_name$(value);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder addAll$capitalized_name$(\n"
+ "$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n"
" java.lang.Iterable<? extends $type$> values) {\n"
" copyOnWrite();\n"
" instance.addAll$capitalized_name$(values);"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder clear$capitalized_name$() {\n"
+ "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" copyOnWrite();\n"
" instance.clear$capitalized_name$();\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
if (SupportUnknownEnumValue(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.util.List<java.lang.Integer>\n"
- "get$capitalized_name$ValueList() {\n"
+ "${$get$capitalized_name$ValueList$}$() {\n"
" return java.util.Collections.unmodifiableList(\n"
" instance.get$capitalized_name$ValueList());\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public int get$capitalized_name$Value(int index) {\n"
+ "$deprecation$public int ${$get$capitalized_name$Value$}$(int index) {\n"
" return instance.get$capitalized_name$Value(index);\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder set$capitalized_name$Value(\n"
+ "$deprecation$public Builder ${$set$capitalized_name$Value$}$(\n"
" int index, int value) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$Value(index, value);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder add$capitalized_name$Value(int value) {\n"
+ "$deprecation$public Builder "
+ "${$add$capitalized_name$Value$}$(int value) {\n"
" instance.add$capitalized_name$Value(value);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder addAll$capitalized_name$Value(\n"
+ "$deprecation$public Builder ${$addAll$capitalized_name$Value$}$(\n"
" java.lang.Iterable<java.lang.Integer> values) {\n"
" copyOnWrite();\n"
" instance.addAll$capitalized_name$Value(values);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
}
@@ -885,7 +921,7 @@ GenerateParsingDoneCode(io::Printer* printer) const {
void RepeatedImmutableEnumFieldLiteGenerator::
GenerateSerializationCode(io::Printer* printer) const {
- if (descriptor_->options().packed()) {
+ if (descriptor_->is_packed()) {
printer->Print(variables_,
"if (get$capitalized_name$List().size() > 0) {\n"
" output.writeUInt32NoTag($tag$);\n"
@@ -916,7 +952,7 @@ GenerateSerializedSizeCode(io::Printer* printer) const {
"}\n");
printer->Print(
"size += dataSize;\n");
- if (descriptor_->options().packed()) {
+ if (descriptor_->is_packed()) {
printer->Print(variables_,
"if (!get$capitalized_name$List().isEmpty()) {"
" size += $tag_size$;\n"
@@ -929,7 +965,7 @@ GenerateSerializedSizeCode(io::Printer* printer) const {
}
// cache the data size for packed fields.
- if (descriptor_->options().packed()) {
+ if (descriptor_->is_packed()) {
printer->Print(variables_,
"$name$MemoizedSerializedSize = dataSize;\n");
}
diff --git a/src/google/protobuf/compiler/java/java_enum_lite.cc b/src/google/protobuf/compiler/java/java_enum_lite.cc
index 96815920..ab3b3323 100644
--- a/src/google/protobuf/compiler/java/java_enum_lite.cc
+++ b/src/google/protobuf/compiler/java/java_enum_lite.cc
@@ -49,17 +49,6 @@ namespace protobuf {
namespace compiler {
namespace java {
-namespace {
-bool EnumHasCustomOptions(const EnumDescriptor* descriptor) {
- if (descriptor->options().unknown_fields().field_count() > 0) return true;
- for (int i = 0; i < descriptor->value_count(); ++i) {
- const EnumValueDescriptor* value = descriptor->value(i);
- if (value->options().unknown_fields().field_count() > 0) return true;
- }
- return false;
-}
-} // namespace
-
EnumLiteGenerator::EnumLiteGenerator(const EnumDescriptor* descriptor,
bool immutable_api, Context* context)
: descriptor_(descriptor),
@@ -104,10 +93,12 @@ void EnumLiteGenerator::Generate(io::Printer* printer) {
}
printer->Print(vars,
"$name$($number$),\n");
+ printer->Annotate("name", canonical_values_[i]);
}
if (SupportUnknownEnumValue(descriptor_->file())) {
- printer->Print("UNRECOGNIZED(-1),\n");
+ printer->Print("${$UNRECOGNIZED$}$(-1),\n", "{", "", "}", "");
+ printer->Annotate("{", "}", descriptor_);
}
printer->Print(
@@ -124,37 +115,49 @@ void EnumLiteGenerator::Generate(io::Printer* printer) {
WriteEnumValueDocComment(printer, aliases_[i].value);
printer->Print(vars,
"public static final $classname$ $name$ = $canonical_name$;\n");
+ printer->Annotate("name", aliases_[i].value);
}
for (int i = 0; i < descriptor_->value_count(); i++) {
std::map<string, string> vars;
vars["name"] = descriptor_->value(i)->name();
vars["number"] = SimpleItoa(descriptor_->value(i)->number());
+ vars["{"] = "";
+ vars["}"] = "";
WriteEnumValueDocComment(printer, descriptor_->value(i));
printer->Print(vars,
- "public static final int $name$_VALUE = $number$;\n");
+ "public static final int ${$$name$_VALUE$}$ = $number$;\n");
+ printer->Annotate("{", "}", descriptor_->value(i));
}
printer->Print("\n");
// -----------------------------------------------------------------
printer->Print(
- "\n"
- "public final int getNumber() {\n"
- " return value;\n"
- "}\n"
- "\n"
- "/**\n"
- " * @deprecated Use {@link #forNumber(int)} instead.\n"
- " */\n"
- "@java.lang.Deprecated\n"
- "public static $classname$ valueOf(int value) {\n"
- " return forNumber(value);\n"
- "}\n"
- "\n"
- "public static $classname$ forNumber(int value) {\n"
- " switch (value) {\n",
- "classname", descriptor_->name());
+ "\n"
+ "public final int getNumber() {\n");
+ if (SupportUnknownEnumValue(descriptor_->file())) {
+ printer->Print(
+ " if (this == UNRECOGNIZED) {\n"
+ " throw new java.lang.IllegalArgumentException(\n"
+ " \"Can't get the number of an unknown enum value.\");\n"
+ " }\n");
+ }
+ printer->Print(
+ " return value;\n"
+ "}\n"
+ "\n"
+ "/**\n"
+ " * @deprecated Use {@link #forNumber(int)} instead.\n"
+ " */\n"
+ "@java.lang.Deprecated\n"
+ "public static $classname$ valueOf(int value) {\n"
+ " return forNumber(value);\n"
+ "}\n"
+ "\n"
+ "public static $classname$ forNumber(int value) {\n"
+ " switch (value) {\n",
+ "classname", descriptor_->name());
printer->Indent();
printer->Indent();
diff --git a/src/google/protobuf/compiler/java/java_extension.cc b/src/google/protobuf/compiler/java/java_extension.cc
index cb237bf6..9b9be55b 100644
--- a/src/google/protobuf/compiler/java/java_extension.cc
+++ b/src/google/protobuf/compiler/java/java_extension.cc
@@ -75,7 +75,7 @@ void ExtensionGenerator::InitTemplateVars(
vars["default"] = descriptor->is_repeated() ?
"" : DefaultValue(descriptor, immutable, name_resolver);
vars["type_constant"] = FieldTypeName(GetType(descriptor));
- vars["packed"] = descriptor->options().packed() ? "true" : "false";
+ vars["packed"] = descriptor->is_packed() ? "true" : "false";
vars["enum_map"] = "null";
vars["prototype"] = "null";
diff --git a/src/google/protobuf/compiler/java/java_field.cc b/src/google/protobuf/compiler/java/java_field.cc
index 04917296..1ab18629 100644
--- a/src/google/protobuf/compiler/java/java_field.cc
+++ b/src/google/protobuf/compiler/java/java_field.cc
@@ -45,8 +45,6 @@
#include <google/protobuf/compiler/java/java_enum_field.h>
#include <google/protobuf/compiler/java/java_enum_field_lite.h>
#include <google/protobuf/compiler/java/java_helpers.h>
-#include <google/protobuf/compiler/java/java_lazy_message_field.h>
-#include <google/protobuf/compiler/java/java_lazy_message_field_lite.h>
#include <google/protobuf/compiler/java/java_map_field.h>
#include <google/protobuf/compiler/java/java_map_field_lite.h>
#include <google/protobuf/compiler/java/java_message_field.h>
@@ -77,13 +75,8 @@ ImmutableFieldGenerator* MakeImmutableGenerator(
return new ImmutableMapFieldGenerator(
field, messageBitIndex, builderBitIndex, context);
} else {
- if (IsLazy(field, context->EnforceLite())) {
- return new RepeatedImmutableLazyMessageFieldGenerator(
- field, messageBitIndex, builderBitIndex, context);
- } else {
- return new RepeatedImmutableMessageFieldGenerator(
- field, messageBitIndex, builderBitIndex, context);
- }
+ return new RepeatedImmutableMessageFieldGenerator(
+ field, messageBitIndex, builderBitIndex, context);
}
case JAVATYPE_ENUM:
return new RepeatedImmutableEnumFieldGenerator(
@@ -99,13 +92,8 @@ ImmutableFieldGenerator* MakeImmutableGenerator(
if (field->containing_oneof()) {
switch (GetJavaType(field)) {
case JAVATYPE_MESSAGE:
- if (IsLazy(field, context->EnforceLite())) {
- return new ImmutableLazyMessageOneofFieldGenerator(
- field, messageBitIndex, builderBitIndex, context);
- } else {
- return new ImmutableMessageOneofFieldGenerator(
- field, messageBitIndex, builderBitIndex, context);
- }
+ return new ImmutableMessageOneofFieldGenerator(
+ field, messageBitIndex, builderBitIndex, context);
case JAVATYPE_ENUM:
return new ImmutableEnumOneofFieldGenerator(
field, messageBitIndex, builderBitIndex, context);
@@ -119,13 +107,8 @@ ImmutableFieldGenerator* MakeImmutableGenerator(
} else {
switch (GetJavaType(field)) {
case JAVATYPE_MESSAGE:
- if (IsLazy(field, context->EnforceLite())) {
- return new ImmutableLazyMessageFieldGenerator(
- field, messageBitIndex, builderBitIndex, context);
- } else {
- return new ImmutableMessageFieldGenerator(
- field, messageBitIndex, builderBitIndex, context);
- }
+ return new ImmutableMessageFieldGenerator(
+ field, messageBitIndex, builderBitIndex, context);
case JAVATYPE_ENUM:
return new ImmutableEnumFieldGenerator(
field, messageBitIndex, builderBitIndex, context);
@@ -150,13 +133,8 @@ ImmutableFieldLiteGenerator* MakeImmutableLiteGenerator(
return new ImmutableMapFieldLiteGenerator(
field, messageBitIndex, builderBitIndex, context);
} else {
- if (IsLazy(field, context->EnforceLite())) {
- return new RepeatedImmutableLazyMessageFieldLiteGenerator(
- field, messageBitIndex, builderBitIndex, context);
- } else {
- return new RepeatedImmutableMessageFieldLiteGenerator(
- field, messageBitIndex, builderBitIndex, context);
- }
+ return new RepeatedImmutableMessageFieldLiteGenerator(
+ field, messageBitIndex, builderBitIndex, context);
}
case JAVATYPE_ENUM:
return new RepeatedImmutableEnumFieldLiteGenerator(
@@ -172,13 +150,8 @@ ImmutableFieldLiteGenerator* MakeImmutableLiteGenerator(
if (field->containing_oneof()) {
switch (GetJavaType(field)) {
case JAVATYPE_MESSAGE:
- if (IsLazy(field, context->EnforceLite())) {
- return new ImmutableLazyMessageOneofFieldLiteGenerator(
- field, messageBitIndex, builderBitIndex, context);
- } else {
- return new ImmutableMessageOneofFieldLiteGenerator(
- field, messageBitIndex, builderBitIndex, context);
- }
+ return new ImmutableMessageOneofFieldLiteGenerator(
+ field, messageBitIndex, builderBitIndex, context);
case JAVATYPE_ENUM:
return new ImmutableEnumOneofFieldLiteGenerator(
field, messageBitIndex, builderBitIndex, context);
@@ -192,13 +165,8 @@ ImmutableFieldLiteGenerator* MakeImmutableLiteGenerator(
} else {
switch (GetJavaType(field)) {
case JAVATYPE_MESSAGE:
- if (IsLazy(field, context->EnforceLite())) {
- return new ImmutableLazyMessageFieldLiteGenerator(
- field, messageBitIndex, builderBitIndex, context);
- } else {
- return new ImmutableMessageFieldLiteGenerator(
- field, messageBitIndex, builderBitIndex, context);
- }
+ return new ImmutableMessageFieldLiteGenerator(
+ field, messageBitIndex, builderBitIndex, context);
case JAVATYPE_ENUM:
return new ImmutableEnumFieldLiteGenerator(
field, messageBitIndex, builderBitIndex, context);
@@ -293,10 +261,17 @@ void SetCommonFieldVariables(const FieldDescriptor* descriptor,
std::map<string, string>* variables) {
(*variables)["field_name"] = descriptor->name();
(*variables)["name"] = info->name;
+ (*variables)["classname"] = descriptor->containing_type()->name();
(*variables)["capitalized_name"] = info->capitalized_name;
(*variables)["disambiguated_reason"] = info->disambiguated_reason;
(*variables)["constant_name"] = FieldConstantName(descriptor);
(*variables)["number"] = SimpleItoa(descriptor->number());
+ // These variables are placeholders to pick out the beginning and ends of
+ // identifiers for annotations (when doing so with existing variables would
+ // be ambiguous or impossible). They should never be set to anything but the
+ // empty string.
+ (*variables)["{"] = "";
+ (*variables)["}"] = "";
}
void SetCommonOneofVariables(const FieldDescriptor* descriptor,
diff --git a/src/google/protobuf/compiler/java/java_field.h b/src/google/protobuf/compiler/java/java_field.h
index 434e610c..cc1d83d9 100644
--- a/src/google/protobuf/compiler/java/java_field.h
+++ b/src/google/protobuf/compiler/java/java_field.h
@@ -119,6 +119,7 @@ class ImmutableFieldLiteGenerator {
virtual void GenerateEqualsCode(io::Printer* printer) const = 0;
virtual void GenerateHashCode(io::Printer* printer) const = 0;
+
virtual string GetBoxedType() const = 0;
private:
diff --git a/src/google/protobuf/compiler/java/java_file.cc b/src/google/protobuf/compiler/java/java_file.cc
index cb4503f6..21133a15 100644
--- a/src/google/protobuf/compiler/java/java_file.cc
+++ b/src/google/protobuf/compiler/java/java_file.cc
@@ -65,7 +65,7 @@ namespace java {
namespace {
struct FieldDescriptorCompare {
- bool operator ()(const FieldDescriptor* f1, const FieldDescriptor* f2) {
+ bool operator ()(const FieldDescriptor* f1, const FieldDescriptor* f2) const {
if(f1 == NULL) {
return false;
}
@@ -154,12 +154,6 @@ void CollectExtensions(const FileDescriptorProto& file_proto,
}
}
-// Compare two field descriptors, returning true if the first should come
-// before the second.
-bool CompareFieldsByName(const FieldDescriptor *a, const FieldDescriptor *b) {
- return a->full_name() < b->full_name();
-}
-
// Our static initialization methods can become very, very large.
// So large that if we aren't careful we end up blowing the JVM's
// 64K bytes of bytecode/method. Fortunately, since these static
@@ -254,9 +248,12 @@ void FileGenerator::Generate(io::Printer* printer) {
PrintGeneratedAnnotation(
printer, '$', options_.annotate_code ? classname_ + ".java.pb.meta" : "");
printer->Print(
- "public final class $classname$ {\n"
+ "$deprecation$public final class $classname$ {\n"
" private $ctor$() {}\n",
- "classname", classname_, "ctor", classname_);
+ "deprecation", file_->options().deprecated() ?
+ "@java.lang.Deprecated " : "",
+ "classname", classname_,
+ "ctor", classname_);
printer->Annotate("classname", file_->name());
printer->Indent();
@@ -505,19 +502,57 @@ void FileGenerator::GenerateDescriptorInitializationCodeForMutable(io::Printer*
// Try to load immutable messages' outer class. Its initialization code
// will take care of interpreting custom options.
printer->Print(
- "try {\n"
- // Note that we have to load the immutable class dynamically here as
- // we want the mutable code to be independent from the immutable code
- // at compile time. It is required to implement dual-compile for
- // mutable and immutable API in blaze.
- " java.lang.Class immutableClass = java.lang.Class.forName(\n"
- " \"$immutable_classname$\");\n"
- "} catch (java.lang.ClassNotFoundException e) {\n"
- // The immutable class can not be found. Custom options are left
- // as unknown fields.
- // TODO(xiaofeng): inform the user with a warning?
- "}\n",
- "immutable_classname", name_resolver_->GetImmutableClassName(file_));
+ "try {\n"
+ // Note that we have to load the immutable class dynamically here as
+ // we want the mutable code to be independent from the immutable code
+ // at compile time. It is required to implement dual-compile for
+ // mutable and immutable API in blaze.
+ " java.lang.Class immutableClass = java.lang.Class.forName(\n"
+ " \"$immutable_classname$\");\n"
+ "} catch (java.lang.ClassNotFoundException e) {\n",
+ "immutable_classname", name_resolver_->GetImmutableClassName(file_));
+ printer->Indent();
+
+ // The immutable class can not be found. We try our best to collect all
+ // custom option extensions to interpret the custom options.
+ printer->Print(
+ "com.google.protobuf.ExtensionRegistry registry =\n"
+ " com.google.protobuf.ExtensionRegistry.newInstance();\n"
+ "com.google.protobuf.MessageLite defaultExtensionInstance = null;\n");
+ FieldDescriptorSet::iterator it;
+ for (it = extensions.begin(); it != extensions.end(); it++) {
+ const FieldDescriptor* field = *it;
+ string scope;
+ if (field->extension_scope() != NULL) {
+ scope = name_resolver_->GetMutableClassName(field->extension_scope()) +
+ ".getDescriptor()";
+ } else {
+ scope = FileJavaPackage(field->file(), true) + "." +
+ name_resolver_->GetDescriptorClassName(field->file()) +
+ ".descriptor";
+ }
+ if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
+ printer->Print(
+ "defaultExtensionInstance = com.google.protobuf.Internal\n"
+ " .getDefaultInstance(\"$class$\");\n"
+ "if (defaultExtensionInstance != null) {\n"
+ " registry.add(\n"
+ " $scope$.getExtensions().get($index$),\n"
+ " (com.google.protobuf.Message) defaultExtensionInstance);\n"
+ "}\n",
+ "scope", scope, "index", SimpleItoa(field->index()), "class",
+ name_resolver_->GetImmutableClassName(field->message_type()));
+ } else {
+ printer->Print("registry.add($scope$.getExtensions().get($index$));\n",
+ "scope", scope, "index", SimpleItoa(field->index()));
+ }
+ }
+ printer->Print(
+ "com.google.protobuf.Descriptors.FileDescriptor\n"
+ " .internalUpdateFileDescriptor(descriptor, registry);\n");
+
+ printer->Outdent();
+ printer->Print("}\n");
}
// Force descriptor initialization of all dependencies.
diff --git a/src/google/protobuf/compiler/java/java_generator.cc b/src/google/protobuf/compiler/java/java_generator.cc
index 2c02d996..84a3b90d 100644
--- a/src/google/protobuf/compiler/java/java_generator.cc
+++ b/src/google/protobuf/compiler/java/java_generator.cc
@@ -42,11 +42,13 @@
#include <google/protobuf/compiler/java/java_file.h>
#include <google/protobuf/compiler/java/java_generator_factory.h>
#include <google/protobuf/compiler/java/java_helpers.h>
+#include <google/protobuf/compiler/java/java_name_resolver.h>
#include <google/protobuf/compiler/java/java_options.h>
#include <google/protobuf/compiler/java/java_shared_code_generator.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/descriptor.pb.h>
+
#include <google/protobuf/stubs/strutil.h>
namespace google {
diff --git a/src/google/protobuf/compiler/java/java_helpers.cc b/src/google/protobuf/compiler/java/java_helpers.cc
index efb5fd45..dbb86b87 100644
--- a/src/google/protobuf/compiler/java/java_helpers.cc
+++ b/src/google/protobuf/compiler/java/java_helpers.cc
@@ -37,6 +37,7 @@
#include <limits>
#include <vector>
+#include <google/protobuf/stubs/stringprintf.h>
#include <google/protobuf/compiler/java/java_helpers.h>
#include <google/protobuf/compiler/java/java_name_resolver.h>
#include <google/protobuf/descriptor.pb.h>
@@ -44,6 +45,9 @@
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/substitute.h>
+
+#include <google/protobuf/stubs/hash.h> // for hash<T *>
+
namespace google {
namespace protobuf {
namespace compiler {
@@ -166,6 +170,14 @@ string UniqueFileScopeIdentifier(const Descriptor* descriptor) {
return "static_" + StringReplace(descriptor->full_name(), ".", "_", true);
}
+string CamelCaseFieldName(const FieldDescriptor* field) {
+ string fieldName = UnderscoresToCamelCase(field);
+ if ('0' <= fieldName[0] && fieldName[0] <= '9') {
+ return '_' + fieldName;
+ }
+ return fieldName;
+}
+
string StripProto(const string& filename) {
if (HasSuffixString(filename, ".protodevel")) {
return StripSuffixString(filename, ".protodevel");
@@ -245,6 +257,7 @@ string ClassName(const FileDescriptor* descriptor) {
return name_resolver.GetClassName(descriptor, true);
}
+
string ExtraMessageInterfaces(const Descriptor* descriptor) {
string interfaces = "// @@protoc_insertion_point(message_implements:"
+ descriptor->full_name() + ")";
@@ -771,6 +784,137 @@ bool HasRepeatedFields(const Descriptor* descriptor) {
return false;
}
+// Encode an unsigned 32-bit value into a sequence of UTF-16 characters.
+//
+// If the value is in [0x0000, 0xD7FF], we encode it with a single character
+// with the same numeric value.
+//
+// If the value is larger than 0xD7FF, we encode its lowest 13 bits into a
+// character in the range [0xE000, 0xFFFF] by combining these 13 bits with
+// 0xE000 using logic-or. Then we shift the value to the right by 13 bits, and
+// encode the remaining value by repeating this same process until we get to
+// a value in [0x0000, 0xD7FF] where we will encode it using a character with
+// the same numeric value.
+//
+// Note that we only use code points in [0x0000, 0xD7FF] and [0xE000, 0xFFFF].
+// There will be no surrogate pairs in the encoded character sequence.
+void WriteUInt32ToUtf16CharSequence(uint32 number,
+ std::vector<uint16>* output) {
+ // For values in [0x0000, 0xD7FF], only use one char to encode it.
+ if (number < 0xD800) {
+ output->push_back(static_cast<uint16>(number));
+ return;
+ }
+ // Encode into multiple chars. All except the last char will be in the range
+ // [0xE000, 0xFFFF], and the last char will be in the range [0x0000, 0xD7FF].
+ // Note that we don't use any value in range [0xD800, 0xDFFF] because they
+ // have to come in pairs and the encoding is just more space-efficient w/o
+ // them.
+ while (number >= 0xD800) {
+ // [0xE000, 0xFFFF] can represent 13 bits of info.
+ output->push_back(static_cast<uint16>(0xE000 | (number & 0x1FFF)));
+ number >>= 13;
+ }
+ output->push_back(static_cast<uint16>(number));
+}
+
+int GetExperimentalJavaFieldTypeForSingular(const FieldDescriptor* field) {
+ // j/c/g/protobuf/FieldType.java lists field types in a slightly different
+ // order from FieldDescriptor::Type so we can't do a simple cast.
+ //
+ // TODO(xiaofeng): Make j/c/g/protobuf/FieldType.java follow the same order.
+ int result = field->type();
+ if (result == FieldDescriptor::TYPE_GROUP) {
+ return 17;
+ } else if (result < FieldDescriptor::TYPE_GROUP) {
+ return result - 1;
+ } else {
+ return result - 2;
+ }
+}
+
+int GetExperimentalJavaFieldTypeForRepeated(const FieldDescriptor* field) {
+ if (field->type() == FieldDescriptor::TYPE_GROUP) {
+ return 49;
+ } else {
+ return GetExperimentalJavaFieldTypeForSingular(field) + 18;
+ }
+}
+
+int GetExperimentalJavaFieldTypeForPacked(const FieldDescriptor* field) {
+ int result = field->type();
+ if (result < FieldDescriptor::TYPE_STRING) {
+ return result + 34;
+ } else if (result > FieldDescriptor::TYPE_BYTES) {
+ return result + 30;
+ } else {
+ GOOGLE_LOG(FATAL) << field->full_name() << " can't be packed.";
+ return 0;
+ }
+}
+
+int GetExperimentalJavaFieldType(const FieldDescriptor* field) {
+ static const int kMapFieldType = 50;
+ static const int kOneofFieldTypeOffset = 51;
+ static const int kRequiredBit = 0x100;
+ static const int kUtf8CheckBit = 0x200;
+ static const int kCheckInitialized = 0x400;
+ static const int kMapWithProto2EnumValue = 0x800;
+ int extra_bits = field->is_required() ? kRequiredBit : 0;
+ if (field->type() == FieldDescriptor::TYPE_STRING && CheckUtf8(field)) {
+ extra_bits |= kUtf8CheckBit;
+ }
+ if (field->is_required() || (GetJavaType(field) == JAVATYPE_MESSAGE &&
+ HasRequiredFields(field->message_type()))) {
+ extra_bits |= kCheckInitialized;
+ }
+
+ if (field->is_map()) {
+ if (SupportFieldPresence(field->file())) {
+ const FieldDescriptor* value =
+ field->message_type()->FindFieldByName("value");
+ if (GetJavaType(value) == JAVATYPE_ENUM) {
+ extra_bits |= kMapWithProto2EnumValue;
+ }
+ }
+ return kMapFieldType | extra_bits;
+ } else if (field->is_packed()) {
+ return GetExperimentalJavaFieldTypeForPacked(field);
+ } else if (field->is_repeated()) {
+ return GetExperimentalJavaFieldTypeForRepeated(field) | extra_bits;
+ } else if (field->containing_oneof() != NULL) {
+ return (GetExperimentalJavaFieldTypeForSingular(field) +
+ kOneofFieldTypeOffset) |
+ extra_bits;
+ } else {
+ return GetExperimentalJavaFieldTypeForSingular(field) | extra_bits;
+ }
+}
+
+// Escape a UTF-16 character to be embedded in a Java string.
+void EscapeUtf16ToString(uint16 code, string* output) {
+ if (code == '\t') {
+ output->append("\\t");
+ } else if (code == '\b') {
+ output->append("\\b");
+ } else if (code == '\n') {
+ output->append("\\n");
+ } else if (code == '\r') {
+ output->append("\\r");
+ } else if (code == '\f') {
+ output->append("\\f");
+ } else if (code == '\'') {
+ output->append("\\'");
+ } else if (code == '\"') {
+ output->append("\\\"");
+ } else if (code == '\\') {
+ output->append("\\\\");
+ } else if (code >= 0x20 && code <= 0x7f) {
+ output->push_back(static_cast<char>(code));
+ } else {
+ output->append(StringPrintf("\\u%04x", code));
+ }
+}
} // namespace java
} // namespace compiler
} // namespace protobuf
diff --git a/src/google/protobuf/compiler/java/java_helpers.h b/src/google/protobuf/compiler/java/java_helpers.h
index 829ec3d7..00d683db 100644
--- a/src/google/protobuf/compiler/java/java_helpers.h
+++ b/src/google/protobuf/compiler/java/java_helpers.h
@@ -74,6 +74,10 @@ string UnderscoresToCapitalizedCamelCase(const FieldDescriptor* field);
// of lower-casing the first letter of the name.)
string UnderscoresToCamelCase(const MethodDescriptor* method);
+// Similar to UnderscoresToCamelCase, but guarentees that the result is a
+// complete Java identifier by adding a _ if needed.
+string CamelCaseFieldName(const FieldDescriptor* field);
+
// Get an identifier that uniquely identifies this type within the file.
// This is used to declare static variables related to this type at the
// outermost file scope.
@@ -132,6 +136,13 @@ inline string ShortMutableJavaClassName(const Descriptor* descriptor) {
return descriptor->name();
}
+// Whether the given descriptor is for one of the core descriptor protos. We
+// cannot currently use the new runtime with core protos since there is a
+// bootstrapping problem with obtaining their descriptors.
+inline bool IsDescriptorProto(const Descriptor* descriptor) {
+ return descriptor->file()->name() == "google/protobuf/descriptor.proto";
+}
+
// Whether we should generate multiple java files for messages.
inline bool MultipleJavaFiles(
@@ -242,15 +253,6 @@ inline bool HasGenericServices(const FileDescriptor *file, bool enforce_lite) {
file->options().java_generic_services();
}
-inline bool IsLazy(const FieldDescriptor* descriptor, bool enforce_lite) {
- // Currently, the proto-lite version supports lazy field.
- // TODO(niwasaki): Support lazy fields also for other proto runtimes.
- if (HasDescriptorMethods(descriptor->file(), enforce_lite)) {
- return false;
- }
- return descriptor->options().lazy();
-}
-
// Methods for shared bitfields.
// Gets the name of the shared bitfield for the given index.
@@ -372,14 +374,14 @@ inline bool IsMapField(const FieldDescriptor* descriptor) {
return descriptor->is_map();
}
-inline bool PreserveUnknownFields(const Descriptor* descriptor) {
- return descriptor->file()->syntax() != FileDescriptor::SYNTAX_PROTO3;
-}
-
inline bool IsAnyMessage(const Descriptor* descriptor) {
return descriptor->full_name() == "google.protobuf.Any";
}
+inline bool IsWrappersProtoFile(const FileDescriptor* descriptor) {
+ return descriptor->name() == "google/protobuf/wrappers.proto";
+}
+
inline bool CheckUtf8(const FieldDescriptor* descriptor) {
return descriptor->file()->syntax() == FileDescriptor::SYNTAX_PROTO3 ||
descriptor->file()->options().java_string_check_utf8();
@@ -388,6 +390,30 @@ inline bool CheckUtf8(const FieldDescriptor* descriptor) {
inline string GeneratedCodeVersionSuffix() {
return "V3";
}
+
+inline bool EnableExperimentalRuntime(Context* context) {
+ return false;
+}
+
+void WriteUInt32ToUtf16CharSequence(uint32 number, std::vector<uint16>* output);
+
+inline void WriteIntToUtf16CharSequence(int value,
+ std::vector<uint16>* output) {
+ WriteUInt32ToUtf16CharSequence(static_cast<uint32>(value), output);
+}
+
+// Escape a UTF-16 character so it can be embedded in a Java string literal.
+void EscapeUtf16ToString(uint16 code, string* output);
+
+// Only the lowest two bytes of the return value are used. The lowest byte
+// is the integer value of a j/c/g/protobuf/FieldType enum. For the other
+// byte:
+// bit 0: whether the field is required.
+// bit 1: whether the field requires UTF-8 validation.
+// bit 2: whether the field needs isInitialized check.
+// bit 3: whether the field is a map field with proto2 enum value.
+// bits 4-7: unused
+int GetExperimentalJavaFieldType(const FieldDescriptor* field);
} // namespace java
} // namespace compiler
} // namespace protobuf
diff --git a/src/google/protobuf/compiler/java/java_lazy_message_field_lite.cc b/src/google/protobuf/compiler/java/java_lazy_message_field_lite.cc
index 49070ba0..51bb11f1 100644
--- a/src/google/protobuf/compiler/java/java_lazy_message_field_lite.cc
+++ b/src/google/protobuf/compiler/java/java_lazy_message_field_lite.cc
@@ -232,6 +232,7 @@ GenerateSerializedSizeCode(io::Printer* printer) const {
"}\n");
}
+
// ===================================================================
ImmutableLazyMessageOneofFieldLiteGenerator::
@@ -415,6 +416,7 @@ GenerateSerializedSizeCode(io::Printer* printer) const {
"}\n");
}
+
// ===================================================================
RepeatedImmutableLazyMessageFieldLiteGenerator::
@@ -716,6 +718,7 @@ GenerateSerializedSizeCode(io::Printer* printer) const {
"}\n");
}
+
} // namespace java
} // namespace compiler
} // namespace protobuf
diff --git a/src/google/protobuf/compiler/java/java_lazy_message_field_lite.h b/src/google/protobuf/compiler/java/java_lazy_message_field_lite.h
index 47ebeb49..65b84fbc 100644
--- a/src/google/protobuf/compiler/java/java_lazy_message_field_lite.h
+++ b/src/google/protobuf/compiler/java/java_lazy_message_field_lite.h
@@ -68,6 +68,7 @@ class ImmutableLazyMessageFieldLiteGenerator
void GenerateSerializationCode(io::Printer* printer) const;
void GenerateSerializedSizeCode(io::Printer* printer) const;
+
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableLazyMessageFieldLiteGenerator);
};
@@ -87,6 +88,7 @@ class ImmutableLazyMessageOneofFieldLiteGenerator
void GenerateSerializationCode(io::Printer* printer) const;
void GenerateSerializedSizeCode(io::Printer* printer) const;
+
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableLazyMessageOneofFieldLiteGenerator);
};
@@ -106,6 +108,7 @@ class RepeatedImmutableLazyMessageFieldLiteGenerator
void GenerateSerializationCode(io::Printer* printer) const;
void GenerateSerializedSizeCode(io::Printer* printer) const;
+
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedImmutableLazyMessageFieldLiteGenerator);
};
diff --git a/src/google/protobuf/compiler/java/java_map_field.cc b/src/google/protobuf/compiler/java/java_map_field.cc
index 3fe68ae3..b22a2199 100644
--- a/src/google/protobuf/compiler/java/java_map_field.cc
+++ b/src/google/protobuf/compiler/java/java_map_field.cc
@@ -183,12 +183,14 @@ GenerateInterfaceMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
- "$deprecation$int get$capitalized_name$Count();\n");
+ "$deprecation$int ${$get$capitalized_name$Count$}$();\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
- "$deprecation$boolean contains$capitalized_name$(\n"
+ "$deprecation$boolean ${$contains$capitalized_name$$}$(\n"
" $key_type$ key);\n");
+ printer->Annotate("{", "}", descriptor_);
if (GetJavaType(ValueField(descriptor_)) == JAVATYPE_ENUM) {
printer->Print(
variables_,
@@ -197,23 +199,27 @@ GenerateInterfaceMembers(io::Printer* printer) const {
" */\n"
"@java.lang.Deprecated\n"
"java.util.Map<$boxed_key_type$, $value_enum_type$>\n"
- "get$capitalized_name$();\n");
+ "${$get$capitalized_name$$}$();\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$java.util.Map<$boxed_key_type$, $value_enum_type$>\n"
- "get$capitalized_name$Map();\n");
+ "${$get$capitalized_name$Map$}$();\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
- "$deprecation$$value_enum_type$ get$capitalized_name$OrDefault(\n"
+ "$deprecation$$value_enum_type$ ${$get$capitalized_name$OrDefault$}$(\n"
" $key_type$ key,\n"
" $value_enum_type$ defaultValue);\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
- "$deprecation$$value_enum_type$ get$capitalized_name$OrThrow(\n"
+ "$deprecation$$value_enum_type$ ${$get$capitalized_name$OrThrow$}$(\n"
" $key_type$ key);\n");
+ printer->Annotate("{", "}", descriptor_);
if (SupportUnknownEnumValue(descriptor_->file())) {
printer->Print(
variables_,
@@ -222,25 +228,29 @@ GenerateInterfaceMembers(io::Printer* printer) const {
" */\n"
"@java.lang.Deprecated\n"
"java.util.Map<$type_parameters$>\n"
- "get$capitalized_name$Value();\n");
+ "${$get$capitalized_name$Value$}$();\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$java.util.Map<$type_parameters$>\n"
- "get$capitalized_name$ValueMap();\n");
+ "${$get$capitalized_name$ValueMap$}$();\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
- "$value_type$ get$capitalized_name$ValueOrDefault(\n"
+ "$value_type$ ${$get$capitalized_name$ValueOrDefault$}$(\n"
" $key_type$ key,\n"
" $value_type$ defaultValue);\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
- "$value_type$ get$capitalized_name$ValueOrThrow(\n"
+ "$value_type$ ${$get$capitalized_name$ValueOrThrow$}$(\n"
" $key_type$ key);\n");
+ printer->Annotate("{", "}", descriptor_);
}
} else {
printer->Print(
@@ -250,25 +260,29 @@ GenerateInterfaceMembers(io::Printer* printer) const {
" */\n"
"@java.lang.Deprecated\n"
"java.util.Map<$type_parameters$>\n"
- "get$capitalized_name$();\n");
+ "${$get$capitalized_name$$}$();\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$java.util.Map<$type_parameters$>\n"
- "get$capitalized_name$Map();\n");
+ "${$get$capitalized_name$Map$}$();\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
- "$value_type$ get$capitalized_name$OrDefault(\n"
+ "$value_type$ ${$get$capitalized_name$OrDefault$}$(\n"
" $key_type$ key,\n"
" $value_type$ defaultValue);\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
- "$value_type$ get$capitalized_name$OrThrow(\n"
+ "$value_type$ ${$get$capitalized_name$OrThrow$}$(\n"
" $key_type$ key);\n");
+ printer->Annotate("{", "}", descriptor_);
}
}
@@ -349,23 +363,27 @@ GenerateBuilderMembers(io::Printer* printer) const {
" return $name$_;\n"
"}\n");
GenerateMapGetters(printer);
- printer->Print(variables_,
- "$deprecation$\n"
- "public Builder clear$capitalized_name$() {\n"
- " internalGetMutable$capitalized_name$().getMutableMap()\n"
- " .clear();\n"
- " return this;\n"
- "}\n");
+ printer->Print(
+ variables_,
+ "$deprecation$\n"
+ "public Builder ${$clear$capitalized_name$$}$() {\n"
+ " internalGetMutable$capitalized_name$().getMutableMap()\n"
+ " .clear();\n"
+ " return this;\n"
+ "}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$\n"
- "public Builder remove$capitalized_name$(\n"
- " $key_type$ key) {\n"
- " $key_null_check$\n"
- " internalGetMutable$capitalized_name$().getMutableMap()\n"
- " .remove(key);\n"
- " return this;\n"
- "}\n");
+ printer->Print(
+ variables_,
+ "$deprecation$\n"
+ "public Builder ${$remove$capitalized_name$$}$(\n"
+ " $key_type$ key) {\n"
+ " $key_null_check$\n"
+ " internalGetMutable$capitalized_name$().getMutableMap()\n"
+ " .remove(key);\n"
+ " return this;\n"
+ "}\n");
+ printer->Annotate("{", "}", descriptor_);
if (GetJavaType(ValueField(descriptor_)) == JAVATYPE_ENUM) {
printer->Print(
variables_,
@@ -374,13 +392,14 @@ GenerateBuilderMembers(io::Printer* printer) const {
" */\n"
"@java.lang.Deprecated\n"
"public java.util.Map<$boxed_key_type$, $value_enum_type$>\n"
- "getMutable$capitalized_name$() {\n"
+ "${$getMutable$capitalized_name$$}$() {\n"
" return internalGetAdapted$capitalized_name$Map(\n"
" internalGetMutable$capitalized_name$().getMutableMap());\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder put$capitalized_name$(\n"
+ "$deprecation$public Builder ${$put$capitalized_name$$}$(\n"
" $key_type$ key,\n"
" $value_enum_type$ value) {\n"
" $key_null_check$\n"
@@ -389,16 +408,18 @@ GenerateBuilderMembers(io::Printer* printer) const {
" .put(key, $name$ValueConverter.doBackward(value));\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
- "$deprecation$public Builder putAll$capitalized_name$(\n"
+ "$deprecation$public Builder ${$putAll$capitalized_name$$}$(\n"
" java.util.Map<$boxed_key_type$, $value_enum_type$> values) {\n"
" internalGetAdapted$capitalized_name$Map(\n"
" internalGetMutable$capitalized_name$().getMutableMap())\n"
" .putAll(values);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
if (SupportUnknownEnumValue(descriptor_->file())) {
printer->Print(
variables_,
@@ -407,32 +428,32 @@ GenerateBuilderMembers(io::Printer* printer) const {
" */\n"
"@java.lang.Deprecated\n"
"public java.util.Map<$boxed_key_type$, $boxed_value_type$>\n"
- "getMutable$capitalized_name$Value() {\n"
+ "${$getMutable$capitalized_name$Value$}$() {\n"
" return internalGetMutable$capitalized_name$().getMutableMap();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
- "$deprecation$public Builder put$capitalized_name$Value(\n"
+ "$deprecation$public Builder ${$put$capitalized_name$Value$}$(\n"
" $key_type$ key,\n"
" $value_type$ value) {\n"
" $key_null_check$\n"
- " if ($value_enum_type$.forNumber(value) == null) {\n"
- " throw new java.lang.IllegalArgumentException();\n"
- " }\n"
" internalGetMutable$capitalized_name$().getMutableMap()\n"
" .put(key, value);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
- "$deprecation$public Builder putAll$capitalized_name$Value(\n"
+ "$deprecation$public Builder ${$putAll$capitalized_name$Value$}$(\n"
" java.util.Map<$boxed_key_type$, $boxed_value_type$> values) {\n"
" internalGetMutable$capitalized_name$().getMutableMap()\n"
" .putAll(values);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
} else {
printer->Print(
@@ -442,30 +463,35 @@ GenerateBuilderMembers(io::Printer* printer) const {
" */\n"
"@java.lang.Deprecated\n"
"public java.util.Map<$type_parameters$>\n"
- "getMutable$capitalized_name$() {\n"
+ "${$getMutable$capitalized_name$$}$() {\n"
" return internalGetMutable$capitalized_name$().getMutableMap();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$"
- "public Builder put$capitalized_name$(\n"
- " $key_type$ key,\n"
- " $value_type$ value) {\n"
- " $key_null_check$\n"
- " $value_null_check$\n"
- " internalGetMutable$capitalized_name$().getMutableMap()\n"
- " .put(key, value);\n"
- " return this;\n"
- "}\n");
+ printer->Print(
+ variables_,
+ "$deprecation$"
+ "public Builder ${$put$capitalized_name$$}$(\n"
+ " $key_type$ key,\n"
+ " $value_type$ value) {\n"
+ " $key_null_check$\n"
+ " $value_null_check$\n"
+ " internalGetMutable$capitalized_name$().getMutableMap()\n"
+ " .put(key, value);\n"
+ " return this;\n"
+ "}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$\n"
- "public Builder putAll$capitalized_name$(\n"
- " java.util.Map<$type_parameters$> values) {\n"
- " internalGetMutable$capitalized_name$().getMutableMap()\n"
- " .putAll(values);\n"
- " return this;\n"
- "}\n");
+ printer->Print(
+ variables_,
+ "$deprecation$\n"
+ "public Builder ${$putAll$capitalized_name$$}$(\n"
+ " java.util.Map<$type_parameters$> values) {\n"
+ " internalGetMutable$capitalized_name$().getMutableMap()\n"
+ " .putAll(values);\n"
+ " return this;\n"
+ "}\n");
+ printer->Annotate("{", "}", descriptor_);
}
}
@@ -474,18 +500,20 @@ GenerateMapGetters(io::Printer* printer) const {
printer->Print(
variables_,
"$deprecation$\n"
- "public int get$capitalized_name$Count() {\n"
+ "public int ${$get$capitalized_name$Count$}$() {\n"
" return internalGet$capitalized_name$().getMap().size();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
- "public boolean contains$capitalized_name$(\n"
+ "public boolean ${$contains$capitalized_name$$}$(\n"
" $key_type$ key) {\n"
" $key_null_check$\n"
" return internalGet$capitalized_name$().getMap().containsKey(key);\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
if (GetJavaType(ValueField(descriptor_)) == JAVATYPE_ENUM) {
printer->Print(
variables_,
@@ -494,22 +522,25 @@ GenerateMapGetters(io::Printer* printer) const {
" */\n"
"@java.lang.Deprecated\n"
"public java.util.Map<$boxed_key_type$, $value_enum_type$>\n"
- "get$capitalized_name$() {\n"
+ "${$get$capitalized_name$$}$() {\n"
" return get$capitalized_name$Map();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$\n"
- "public java.util.Map<$boxed_key_type$, $value_enum_type$>\n"
- "get$capitalized_name$Map() {\n"
- " return internalGetAdapted$capitalized_name$Map(\n"
- " internalGet$capitalized_name$().getMap());"
- "}\n");
+ printer->Print(
+ variables_,
+ "$deprecation$\n"
+ "public java.util.Map<$boxed_key_type$, $value_enum_type$>\n"
+ "${$get$capitalized_name$Map$}$() {\n"
+ " return internalGetAdapted$capitalized_name$Map(\n"
+ " internalGet$capitalized_name$().getMap());"
+ "}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
- "public $value_enum_type$ get$capitalized_name$OrDefault(\n"
+ "public $value_enum_type$ ${$get$capitalized_name$OrDefault$}$(\n"
" $key_type$ key,\n"
" $value_enum_type$ defaultValue) {\n"
" $key_null_check$\n"
@@ -519,11 +550,12 @@ GenerateMapGetters(io::Printer* printer) const {
" ? $name$ValueConverter.doForward(map.get(key))\n"
" : defaultValue;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
- "public $value_enum_type$ get$capitalized_name$OrThrow(\n"
+ "public $value_enum_type$ ${$get$capitalized_name$OrThrow$}$(\n"
" $key_type$ key) {\n"
" $key_null_check$\n"
" java.util.Map<$boxed_key_type$, $boxed_value_type$> map =\n"
@@ -533,6 +565,7 @@ GenerateMapGetters(io::Printer* printer) const {
" }\n"
" return $name$ValueConverter.doForward(map.get(key));\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
if (SupportUnknownEnumValue(descriptor_->file())) {
printer->Print(
variables_,
@@ -541,22 +574,24 @@ GenerateMapGetters(io::Printer* printer) const {
" */\n"
"@java.lang.Deprecated\n"
"public java.util.Map<$boxed_key_type$, $boxed_value_type$>\n"
- "get$capitalized_name$Value() {\n"
+ "${$get$capitalized_name$Value$}$() {\n"
" return get$capitalized_name$ValueMap();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"public java.util.Map<$boxed_key_type$, $boxed_value_type$>\n"
- "get$capitalized_name$ValueMap() {\n"
+ "${$get$capitalized_name$ValueMap$}$() {\n"
" return internalGet$capitalized_name$().getMap();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
- "public $value_type$ get$capitalized_name$ValueOrDefault(\n"
+ "public $value_type$ ${$get$capitalized_name$ValueOrDefault$}$(\n"
" $key_type$ key,\n"
" $value_type$ defaultValue) {\n"
" $key_null_check$\n"
@@ -564,11 +599,12 @@ GenerateMapGetters(io::Printer* printer) const {
" internalGet$capitalized_name$().getMap();\n"
" return map.containsKey(key) ? map.get(key) : defaultValue;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
- "public $value_type$ get$capitalized_name$ValueOrThrow(\n"
+ "public $value_type$ ${$get$capitalized_name$ValueOrThrow$}$(\n"
" $key_type$ key) {\n"
" $key_null_check$\n"
" java.util.Map<$boxed_key_type$, $boxed_value_type$> map =\n"
@@ -578,6 +614,7 @@ GenerateMapGetters(io::Printer* printer) const {
" }\n"
" return map.get(key);\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
} else {
printer->Print(
@@ -586,21 +623,25 @@ GenerateMapGetters(io::Printer* printer) const {
" * Use {@link #get$capitalized_name$Map()} instead.\n"
" */\n"
"@java.lang.Deprecated\n"
- "public java.util.Map<$type_parameters$> get$capitalized_name$() {\n"
+ "public java.util.Map<$type_parameters$> "
+ "${$get$capitalized_name$$}$() {\n"
" return get$capitalized_name$Map();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
- "public java.util.Map<$type_parameters$> get$capitalized_name$Map() {\n"
+ "public java.util.Map<$type_parameters$> "
+ "${$get$capitalized_name$Map$}$() {\n"
" return internalGet$capitalized_name$().getMap();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
- "public $value_type$ get$capitalized_name$OrDefault(\n"
+ "public $value_type$ ${$get$capitalized_name$OrDefault$}$(\n"
" $key_type$ key,\n"
" $value_type$ defaultValue) {\n"
" $key_null_check$\n"
@@ -608,11 +649,12 @@ GenerateMapGetters(io::Printer* printer) const {
" internalGet$capitalized_name$().getMap();\n"
" return map.containsKey(key) ? map.get(key) : defaultValue;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
- "public $value_type$ get$capitalized_name$OrThrow(\n"
+ "public $value_type$ ${$get$capitalized_name$OrThrow$}$(\n"
" $key_type$ key) {\n"
" $key_null_check$\n"
" java.util.Map<$type_parameters$> map =\n"
@@ -622,6 +664,7 @@ GenerateMapGetters(io::Printer* printer) const {
" }\n"
" return map.get(key);\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
}
diff --git a/src/google/protobuf/compiler/java/java_map_field_lite.cc b/src/google/protobuf/compiler/java/java_map_field_lite.cc
index 523052cc..f19ec271 100644
--- a/src/google/protobuf/compiler/java/java_map_field_lite.cc
+++ b/src/google/protobuf/compiler/java/java_map_field_lite.cc
@@ -166,12 +166,14 @@ GenerateInterfaceMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
- "$deprecation$int get$capitalized_name$Count();\n");
+ "$deprecation$int ${$get$capitalized_name$Count$}$();\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
- "$deprecation$boolean contains$capitalized_name$(\n"
+ "$deprecation$boolean ${$contains$capitalized_name$$}$(\n"
" $key_type$ key);\n");
+ printer->Annotate("{", "}", descriptor_);
if (GetJavaType(ValueField(descriptor_)) == JAVATYPE_ENUM) {
printer->Print(
variables_,
@@ -180,23 +182,27 @@ GenerateInterfaceMembers(io::Printer* printer) const {
" */\n"
"@java.lang.Deprecated\n"
"java.util.Map<$boxed_key_type$, $value_enum_type$>\n"
- "get$capitalized_name$();\n");
+ "${$get$capitalized_name$$}$();\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$java.util.Map<$boxed_key_type$, $value_enum_type$>\n"
- "get$capitalized_name$Map();\n");
+ "${$get$capitalized_name$Map$}$();\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
- "$deprecation$$value_enum_type$ get$capitalized_name$OrDefault(\n"
+ "$deprecation$$value_enum_type$ ${$get$capitalized_name$OrDefault$}$(\n"
" $key_type$ key,\n"
" $value_enum_type$ defaultValue);\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
- "$deprecation$$value_enum_type$ get$capitalized_name$OrThrow(\n"
+ "$deprecation$$value_enum_type$ ${$get$capitalized_name$OrThrow$}$(\n"
" $key_type$ key);\n");
+ printer->Annotate("{", "}", descriptor_);
if (SupportUnknownEnumValue(descriptor_->file())) {
printer->Print(
variables_,
@@ -205,25 +211,29 @@ GenerateInterfaceMembers(io::Printer* printer) const {
" */\n"
"@java.lang.Deprecated\n"
"java.util.Map<$type_parameters$>\n"
- "get$capitalized_name$Value();\n");
+ "${$get$capitalized_name$Value$}$();\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$java.util.Map<$type_parameters$>\n"
- "get$capitalized_name$ValueMap();\n");
+ "${$get$capitalized_name$ValueMap$}$();\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
- "$value_type$ get$capitalized_name$ValueOrDefault(\n"
+ "$value_type$ ${$get$capitalized_name$ValueOrDefault$}$(\n"
" $key_type$ key,\n"
" $value_type$ defaultValue);\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
- "$value_type$ get$capitalized_name$ValueOrThrow(\n"
+ "$value_type$ ${$get$capitalized_name$ValueOrThrow$}$(\n"
" $key_type$ key);\n");
+ printer->Annotate("{", "}", descriptor_);
}
} else {
printer->Print(
@@ -233,25 +243,29 @@ GenerateInterfaceMembers(io::Printer* printer) const {
" */\n"
"@java.lang.Deprecated\n"
"java.util.Map<$type_parameters$>\n"
- "get$capitalized_name$();\n");
+ "${$get$capitalized_name$$}$();\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$java.util.Map<$type_parameters$>\n"
- "get$capitalized_name$Map();\n");
+ "${$get$capitalized_name$Map$}$();\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
- "$value_type$ get$capitalized_name$OrDefault(\n"
+ "$value_type$ ${$get$capitalized_name$OrDefault$}$(\n"
" $key_type$ key,\n"
" $value_type$ defaultValue);\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
- "$value_type$ get$capitalized_name$OrThrow(\n"
+ "$value_type$ ${$get$capitalized_name$OrThrow$}$(\n"
" $key_type$ key);\n");
+ printer->Annotate("{", "}", descriptor_);
}
}
@@ -288,18 +302,20 @@ GenerateMembers(io::Printer* printer) const {
printer->Print(
variables_,
"$deprecation$\n"
- "public int get$capitalized_name$Count() {\n"
+ "public int ${$get$capitalized_name$Count$}$() {\n"
" return internalGet$capitalized_name$().size();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
- "public boolean contains$capitalized_name$(\n"
+ "public boolean ${$contains$capitalized_name$$}$(\n"
" $key_type$ key) {\n"
" $key_null_check$\n"
" return internalGet$capitalized_name$().containsKey(key);\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
if (GetJavaType(ValueField(descriptor_)) == JAVATYPE_ENUM) {
printer->Print(
variables_,
@@ -316,26 +332,28 @@ GenerateMembers(io::Printer* printer) const {
" */\n"
"@java.lang.Deprecated\n"
"public java.util.Map<$boxed_key_type$, $value_enum_type$>\n"
- "get$capitalized_name$() {\n"
+ "${$get$capitalized_name$$}$() {\n"
" return get$capitalized_name$Map();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"public java.util.Map<$boxed_key_type$, $value_enum_type$>\n"
- "get$capitalized_name$Map() {\n"
+ "${$get$capitalized_name$Map$}$() {\n"
" return java.util.Collections.unmodifiableMap(\n"
" new com.google.protobuf.Internal.MapAdapter<\n"
" $boxed_key_type$, $value_enum_type$, java.lang.Integer>(\n"
" internalGet$capitalized_name$(),\n"
" $name$ValueConverter));\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
- "public $value_enum_type$ get$capitalized_name$OrDefault(\n"
+ "public $value_enum_type$ ${$get$capitalized_name$OrDefault$}$(\n"
" $key_type$ key,\n"
" $value_enum_type$ defaultValue) {\n"
" $key_null_check$\n"
@@ -345,11 +363,12 @@ GenerateMembers(io::Printer* printer) const {
" ? $name$ValueConverter.doForward(map.get(key))\n"
" : defaultValue;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
- "public $value_enum_type$ get$capitalized_name$OrThrow(\n"
+ "public $value_enum_type$ ${$get$capitalized_name$OrThrow$}$(\n"
" $key_type$ key) {\n"
" $key_null_check$\n"
" java.util.Map<$boxed_key_type$, $boxed_value_type$> map =\n"
@@ -359,6 +378,7 @@ GenerateMembers(io::Printer* printer) const {
" }\n"
" return $name$ValueConverter.doForward(map.get(key));\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
if (SupportUnknownEnumValue(descriptor_->file())) {
printer->Print(
variables_,
@@ -367,23 +387,25 @@ GenerateMembers(io::Printer* printer) const {
" */\n"
"@java.lang.Deprecated\n"
"public java.util.Map<$boxed_key_type$, $boxed_value_type$>\n"
- "get$capitalized_name$Value() {\n"
+ "${$get$capitalized_name$Value$}$() {\n"
" return get$capitalized_name$ValueMap();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"public java.util.Map<$boxed_key_type$, $boxed_value_type$>\n"
- "get$capitalized_name$ValueMap() {\n"
+ "${$get$capitalized_name$ValueMap$}$() {\n"
" return java.util.Collections.unmodifiableMap(\n"
" internalGet$capitalized_name$());\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
- "public $value_type$ get$capitalized_name$ValueOrDefault(\n"
+ "public $value_type$ ${$get$capitalized_name$ValueOrDefault$}$(\n"
" $key_type$ key,\n"
" $value_type$ defaultValue) {\n"
" $key_null_check$\n"
@@ -391,11 +413,12 @@ GenerateMembers(io::Printer* printer) const {
" internalGet$capitalized_name$();\n"
" return map.containsKey(key) ? map.get(key) : defaultValue;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
- "public $value_type$ get$capitalized_name$ValueOrThrow(\n"
+ "public $value_type$ ${$get$capitalized_name$ValueOrThrow$}$(\n"
" $key_type$ key) {\n"
" $key_null_check$\n"
" java.util.Map<$boxed_key_type$, $boxed_value_type$> map =\n"
@@ -405,6 +428,7 @@ GenerateMembers(io::Printer* printer) const {
" }\n"
" return map.get(key);\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
} else {
printer->Print(
@@ -413,22 +437,26 @@ GenerateMembers(io::Printer* printer) const {
" * Use {@link #get$capitalized_name$Map()} instead.\n"
" */\n"
"@java.lang.Deprecated\n"
- "public java.util.Map<$type_parameters$> get$capitalized_name$() {\n"
+ "public java.util.Map<$type_parameters$> "
+ "${$get$capitalized_name$$}$() {\n"
" return get$capitalized_name$Map();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
- "public java.util.Map<$type_parameters$> get$capitalized_name$Map() {\n"
+ "public java.util.Map<$type_parameters$> "
+ "${$get$capitalized_name$Map$}$() {\n"
" return java.util.Collections.unmodifiableMap(\n"
" internalGet$capitalized_name$());\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
- "public $value_type$ get$capitalized_name$OrDefault(\n"
+ "public $value_type$ ${$get$capitalized_name$OrDefault$}$(\n"
" $key_type$ key,\n"
" $value_type$ defaultValue) {\n"
" $key_null_check$\n"
@@ -436,11 +464,12 @@ GenerateMembers(io::Printer* printer) const {
" internalGet$capitalized_name$();\n"
" return map.containsKey(key) ? map.get(key) : defaultValue;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
- "public $value_type$ get$capitalized_name$OrThrow(\n"
+ "public $value_type$ ${$get$capitalized_name$OrThrow$}$(\n"
" $key_type$ key) {\n"
" $key_null_check$\n"
" java.util.Map<$type_parameters$> map =\n"
@@ -450,6 +479,7 @@ GenerateMembers(io::Printer* printer) const {
" }\n"
" return map.get(key);\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
// Generate private setters for the builder to proxy into.
@@ -484,42 +514,47 @@ GenerateMembers(io::Printer* printer) const {
}
}
+
void ImmutableMapFieldLiteGenerator::
GenerateBuilderMembers(io::Printer* printer) const {
printer->Print(
variables_,
"$deprecation$\n"
- "public int get$capitalized_name$Count() {\n"
+ "public int ${$get$capitalized_name$Count$}$() {\n"
" return instance.get$capitalized_name$Map().size();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
- "public boolean contains$capitalized_name$(\n"
+ "public boolean ${$contains$capitalized_name$$}$(\n"
" $key_type$ key) {\n"
" $key_null_check$\n"
" return instance.get$capitalized_name$Map().containsKey(key);\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
- "public Builder clear$capitalized_name$() {\n"
+ "public Builder ${$clear$capitalized_name$$}$() {\n"
" copyOnWrite();\n"
" instance.getMutable$capitalized_name$Map().clear();\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
- "public Builder remove$capitalized_name$(\n"
+ "public Builder ${$remove$capitalized_name$$}$(\n"
" $key_type$ key) {\n"
" $key_null_check$\n"
" copyOnWrite();\n"
" instance.getMutable$capitalized_name$Map().remove(key);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
if (GetJavaType(ValueField(descriptor_)) == JAVATYPE_ENUM) {
printer->Print(
variables_,
@@ -528,23 +563,25 @@ GenerateBuilderMembers(io::Printer* printer) const {
" */\n"
"@java.lang.Deprecated\n"
"public java.util.Map<$boxed_key_type$, $value_enum_type$>\n"
- "get$capitalized_name$() {\n"
+ "${$get$capitalized_name$$}$() {\n"
" return get$capitalized_name$Map();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"public java.util.Map<$boxed_key_type$, $value_enum_type$>\n"
- "get$capitalized_name$Map() {\n"
+ "${$get$capitalized_name$Map$}$() {\n"
" return java.util.Collections.unmodifiableMap(\n"
" instance.get$capitalized_name$Map());\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
- "public $value_enum_type$ get$capitalized_name$OrDefault(\n"
+ "public $value_enum_type$ ${$get$capitalized_name$OrDefault$}$(\n"
" $key_type$ key,\n"
" $value_enum_type$ defaultValue) {\n"
" $key_null_check$\n"
@@ -554,11 +591,12 @@ GenerateBuilderMembers(io::Printer* printer) const {
" ? map.get(key)\n"
" : defaultValue;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
- "public $value_enum_type$ get$capitalized_name$OrThrow(\n"
+ "public $value_enum_type$ ${$get$capitalized_name$OrThrow$}$(\n"
" $key_type$ key) {\n"
" $key_null_check$\n"
" java.util.Map<$boxed_key_type$, $value_enum_type$> map =\n"
@@ -568,10 +606,11 @@ GenerateBuilderMembers(io::Printer* printer) const {
" }\n"
" return map.get(key);\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
- "$deprecation$public Builder put$capitalized_name$(\n"
+ "$deprecation$public Builder ${$put$capitalized_name$$}$(\n"
" $key_type$ key,\n"
" $value_enum_type$ value) {\n"
" $key_null_check$\n"
@@ -580,15 +619,17 @@ GenerateBuilderMembers(io::Printer* printer) const {
" instance.getMutable$capitalized_name$Map().put(key, value);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
- "$deprecation$public Builder putAll$capitalized_name$(\n"
+ "$deprecation$public Builder ${$putAll$capitalized_name$$}$(\n"
" java.util.Map<$boxed_key_type$, $value_enum_type$> values) {\n"
" copyOnWrite();\n"
" instance.getMutable$capitalized_name$Map().putAll(values);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
if (SupportUnknownEnumValue(descriptor_->file())) {
printer->Print(
variables_,
@@ -597,23 +638,25 @@ GenerateBuilderMembers(io::Printer* printer) const {
" */\n"
"@java.lang.Deprecated\n"
"public java.util.Map<$boxed_key_type$, $boxed_value_type$>\n"
- "get$capitalized_name$Value() {\n"
+ "${$get$capitalized_name$Value$}$() {\n"
" return get$capitalized_name$ValueMap();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"public java.util.Map<$boxed_key_type$, $boxed_value_type$>\n"
- "get$capitalized_name$ValueMap() {\n"
+ "${$get$capitalized_name$ValueMap$}$() {\n"
" return java.util.Collections.unmodifiableMap(\n"
" instance.get$capitalized_name$ValueMap());\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
- "public $value_type$ get$capitalized_name$ValueOrDefault(\n"
+ "public $value_type$ ${$get$capitalized_name$ValueOrDefault$}$(\n"
" $key_type$ key,\n"
" $value_type$ defaultValue) {\n"
" $key_null_check$\n"
@@ -621,11 +664,12 @@ GenerateBuilderMembers(io::Printer* printer) const {
" instance.get$capitalized_name$ValueMap();\n"
" return map.containsKey(key) ? map.get(key) : defaultValue;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
- "public $value_type$ get$capitalized_name$ValueOrThrow(\n"
+ "public $value_type$ ${$get$capitalized_name$ValueOrThrow$}$(\n"
" $key_type$ key) {\n"
" $key_null_check$\n"
" java.util.Map<$boxed_key_type$, $boxed_value_type$> map =\n"
@@ -635,29 +679,29 @@ GenerateBuilderMembers(io::Printer* printer) const {
" }\n"
" return map.get(key);\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
- "$deprecation$public Builder put$capitalized_name$Value(\n"
+ "$deprecation$public Builder ${$put$capitalized_name$Value$}$(\n"
" $key_type$ key,\n"
" $value_type$ value) {\n"
" $key_null_check$\n"
- " if ($value_enum_type$.forNumber(value) == null) {\n"
- " throw new java.lang.IllegalArgumentException();\n"
- " }\n"
" copyOnWrite();\n"
" instance.getMutable$capitalized_name$ValueMap().put(key, value);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
- "$deprecation$public Builder putAll$capitalized_name$Value(\n"
+ "$deprecation$public Builder ${$putAll$capitalized_name$Value$}$(\n"
" java.util.Map<$boxed_key_type$, $boxed_value_type$> values) {\n"
" copyOnWrite();\n"
" instance.getMutable$capitalized_name$ValueMap().putAll(values);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
} else {
printer->Print(
@@ -666,22 +710,26 @@ GenerateBuilderMembers(io::Printer* printer) const {
" * Use {@link #get$capitalized_name$Map()} instead.\n"
" */\n"
"@java.lang.Deprecated\n"
- "public java.util.Map<$type_parameters$> get$capitalized_name$() {\n"
+ "public java.util.Map<$type_parameters$> "
+ "${$get$capitalized_name$$}$() {\n"
" return get$capitalized_name$Map();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$"
- "public java.util.Map<$type_parameters$> get$capitalized_name$Map() {\n"
+ "public java.util.Map<$type_parameters$> "
+ "${$get$capitalized_name$Map$}$() {\n"
" return java.util.Collections.unmodifiableMap(\n"
" instance.get$capitalized_name$Map());\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
- "public $value_type$ get$capitalized_name$OrDefault(\n"
+ "public $value_type$ ${$get$capitalized_name$OrDefault$}$(\n"
" $key_type$ key,\n"
" $value_type$ defaultValue) {\n"
" $key_null_check$\n"
@@ -689,11 +737,12 @@ GenerateBuilderMembers(io::Printer* printer) const {
" instance.get$capitalized_name$Map();\n"
" return map.containsKey(key) ? map.get(key) : defaultValue;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
- "public $value_type$ get$capitalized_name$OrThrow(\n"
+ "public $value_type$ ${$get$capitalized_name$OrThrow$}$(\n"
" $key_type$ key) {\n"
" $key_null_check$\n"
" java.util.Map<$type_parameters$> map =\n"
@@ -703,11 +752,12 @@ GenerateBuilderMembers(io::Printer* printer) const {
" }\n"
" return map.get(key);\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$"
- "public Builder put$capitalized_name$(\n"
+ "public Builder ${$put$capitalized_name$$}$(\n"
" $key_type$ key,\n"
" $value_type$ value) {\n"
" $key_null_check$\n"
@@ -716,16 +766,18 @@ GenerateBuilderMembers(io::Printer* printer) const {
" instance.getMutable$capitalized_name$Map().put(key, value);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$"
- "public Builder putAll$capitalized_name$(\n"
+ "public Builder ${$putAll$capitalized_name$$}$(\n"
" java.util.Map<$type_parameters$> values) {\n"
" copyOnWrite();\n"
" instance.getMutable$capitalized_name$Map().putAll(values);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
}
diff --git a/src/google/protobuf/compiler/java/java_map_field_lite.h b/src/google/protobuf/compiler/java/java_map_field_lite.h
index 63dedbc2..94aa4813 100644
--- a/src/google/protobuf/compiler/java/java_map_field_lite.h
+++ b/src/google/protobuf/compiler/java/java_map_field_lite.h
@@ -62,6 +62,7 @@ class ImmutableMapFieldLiteGenerator : public ImmutableFieldLiteGenerator {
void GenerateEqualsCode(io::Printer* printer) const;
void GenerateHashCode(io::Printer* printer) const;
+
string GetBoxedType() const;
private:
diff --git a/src/google/protobuf/compiler/java/java_message.cc b/src/google/protobuf/compiler/java/java_message.cc
index df4db463..2486b739 100644
--- a/src/google/protobuf/compiler/java/java_message.cc
+++ b/src/google/protobuf/compiler/java/java_message.cc
@@ -56,8 +56,9 @@
#include <google/protobuf/io/printer.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/wire_format.h>
-#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/substitute.h>
+#include <google/protobuf/stubs/strutil.h>
+
namespace google {
namespace protobuf {
@@ -253,23 +254,27 @@ void ImmutableMessageGenerator::GenerateInterface(io::Printer* printer) {
/* immutable = */ true, "OrBuilder");
if (descriptor_->extension_range_count() > 0) {
printer->Print(
- "public interface $classname$OrBuilder$idend$ extends\n"
+ "$deprecation$public interface ${$$classname$OrBuilder$}$ extends\n"
" $extra_interfaces$\n"
" com.google.protobuf.GeneratedMessage$ver$.\n"
" ExtendableMessageOrBuilder<$classname$> {\n",
+ "deprecation", descriptor_->options().deprecated() ?
+ "@java.lang.Deprecated " : "",
"extra_interfaces", ExtraMessageOrBuilderInterfaces(descriptor_),
"classname", descriptor_->name(),
- "idend", "", "ver", GeneratedCodeVersionSuffix());
+ "{", "", "}", "", "ver", GeneratedCodeVersionSuffix());
} else {
printer->Print(
- "public interface $classname$OrBuilder$idend$ extends\n"
+ "$deprecation$public interface ${$$classname$OrBuilder$}$ extends\n"
" $extra_interfaces$\n"
" com.google.protobuf.MessageOrBuilder {\n",
+ "deprecation", descriptor_->options().deprecated() ?
+ "@java.lang.Deprecated " : "",
"extra_interfaces", ExtraMessageOrBuilderInterfaces(descriptor_),
"classname", descriptor_->name(),
- "idend", "");
+ "{", "", "}", "");
}
- printer->Annotate("classname", "idend", descriptor_);
+ printer->Annotate("{", "}", descriptor_);
printer->Indent();
for (int i = 0; i < descriptor_->field_count(); i++) {
@@ -304,6 +309,8 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) {
variables["classname"] = descriptor_->name();
variables["extra_interfaces"] = ExtraMessageInterfaces(descriptor_);
variables["ver"] = GeneratedCodeVersionSuffix();
+ variables["deprecation"] = descriptor_->options().deprecated()
+ ? "@java.lang.Deprecated " : "";
WriteMessageDocComment(printer, descriptor_);
MaybePrintGeneratedAnnotation(context_, printer, descriptor_,
@@ -312,8 +319,9 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) {
// The builder_type stores the super type name of the nested Builder class.
string builder_type;
if (descriptor_->extension_range_count() > 0) {
- printer->Print(variables,
- "public $static$final class $classname$ extends\n");
+ printer->Print(
+ variables,
+ "$deprecation$public $static$final class $classname$ extends\n");
printer->Annotate("classname", descriptor_);
printer->Print(
variables,
@@ -326,8 +334,9 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) {
name_resolver_->GetImmutableClassName(descriptor_),
GeneratedCodeVersionSuffix());
} else {
- printer->Print(variables,
- "public $static$final class $classname$ extends\n");
+ printer->Print(
+ variables,
+ "$deprecation$public $static$final class $classname$ extends\n");
printer->Annotate("classname", descriptor_);
printer->Print(variables,
" com.google.protobuf.GeneratedMessage$ver$ implements\n"
@@ -337,6 +346,9 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) {
"com.google.protobuf.GeneratedMessage$0.Builder<?>",
GeneratedCodeVersionSuffix());
}
+ printer->Print(
+ "private static final long serialVersionUID = 0L;\n");
+
printer->Indent();
// Using builder_type, instead of Builder, prevents the Builder class from
// being loaded into PermGen space when the default instance is created.
@@ -359,22 +371,19 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) {
"}\n"
"\n");
+
printer->Print(
"@java.lang.Override\n"
"public final com.google.protobuf.UnknownFieldSet\n"
- "getUnknownFields() {\n");
- if (PreserveUnknownFields(descriptor_)) {
- printer->Print(
- " return this.unknownFields;\n");
- } else {
- printer->Print(
- " return com.google.protobuf.UnknownFieldSet.getDefaultInstance();\n");
- }
- printer->Print(
+ "getUnknownFields() {\n"
+ " return this.unknownFields;\n"
"}\n");
if (context_->HasGeneratedMethods(descriptor_)) {
- GenerateParsingConstructor(printer);
+ if (!EnableExperimentalRuntime(context_) ||
+ IsDescriptorProto(descriptor_)) {
+ GenerateParsingConstructor(printer);
+ }
}
GenerateDescriptorMethods(printer);
@@ -532,6 +541,17 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) {
"\n",
"classname", name_resolver_->GetImmutableClassName(descriptor_));
+ // 'of' method for Wrappers
+ if (IsWrappersProtoFile(descriptor_->file())) {
+ printer->Print(
+ "public static $classname$ of($field_type$ value) {\n"
+ " return newBuilder().setValue(value).build();\n"
+ "}\n"
+ "\n",
+ "classname", name_resolver_->GetImmutableClassName(descriptor_),
+ "field_type", PrimitiveTypeName(GetJavaType(descriptor_->field(0))));
+ }
+
GenerateParser(printer);
printer->Print(
@@ -571,104 +591,105 @@ GenerateMessageSerializationMethods(io::Printer* printer) {
"public void writeTo(com.google.protobuf.CodedOutputStream output)\n"
" throws java.io.IOException {\n");
printer->Indent();
- if (HasPackedFields(descriptor_)) {
- // writeTo(CodedOutputStream output) might be invoked without
- // getSerializedSize() ever being called, but we need the memoized
- // sizes in case this message has packed fields. Rather than emit checks for
- // each packed field, just call getSerializedSize() up front.
- // In most cases, getSerializedSize() will have already been called anyway
- // by one of the wrapper writeTo() methods, making this call cheap.
- printer->Print(
- "getSerializedSize();\n");
- }
- if (descriptor_->extension_range_count() > 0) {
- if (descriptor_->options().message_set_wire_format()) {
- printer->Print(
- "com.google.protobuf.GeneratedMessage$ver$\n"
- " .ExtendableMessage<$classname$>.ExtensionWriter\n"
- " extensionWriter = newMessageSetExtensionWriter();\n",
- "classname", name_resolver_->GetImmutableClassName(descriptor_),
- "ver", GeneratedCodeVersionSuffix());
- } else {
- printer->Print(
- "com.google.protobuf.GeneratedMessage$ver$\n"
- " .ExtendableMessage<$classname$>.ExtensionWriter\n"
- " extensionWriter = newExtensionWriter();\n",
- "classname", name_resolver_->GetImmutableClassName(descriptor_),
- "ver", GeneratedCodeVersionSuffix());
+ if (EnableExperimentalRuntime(context_) && !IsDescriptorProto(descriptor_)) {
+ printer->Print("writeToInternal(output);\n");
+ } else {
+ if (HasPackedFields(descriptor_)) {
+ // writeTo(CodedOutputStream output) might be invoked without
+ // getSerializedSize() ever being called, but we need the memoized
+ // sizes in case this message has packed fields. Rather than emit checks
+ // for each packed field, just call getSerializedSize() up front. In most
+ // cases, getSerializedSize() will have already been called anyway by one
+ // of the wrapper writeTo() methods, making this call cheap.
+ printer->Print("getSerializedSize();\n");
}
- }
- // Merge the fields and the extension ranges, both sorted by field number.
- for (int i = 0, j = 0;
- i < descriptor_->field_count() || j < sorted_extensions.size();
- ) {
- if (i == descriptor_->field_count()) {
- GenerateSerializeOneExtensionRange(printer, sorted_extensions[j++]);
- } else if (j == sorted_extensions.size()) {
- GenerateSerializeOneField(printer, sorted_fields[i++]);
- } else if (sorted_fields[i]->number() < sorted_extensions[j]->start) {
- GenerateSerializeOneField(printer, sorted_fields[i++]);
- } else {
- GenerateSerializeOneExtensionRange(printer, sorted_extensions[j++]);
+ if (descriptor_->extension_range_count() > 0) {
+ if (descriptor_->options().message_set_wire_format()) {
+ printer->Print(
+ "com.google.protobuf.GeneratedMessage$ver$\n"
+ " .ExtendableMessage<$classname$>.ExtensionWriter\n"
+ " extensionWriter = newMessageSetExtensionWriter();\n",
+ "classname", name_resolver_->GetImmutableClassName(descriptor_),
+ "ver", GeneratedCodeVersionSuffix());
+ } else {
+ printer->Print(
+ "com.google.protobuf.GeneratedMessage$ver$\n"
+ " .ExtendableMessage<$classname$>.ExtensionWriter\n"
+ " extensionWriter = newExtensionWriter();\n",
+ "classname", name_resolver_->GetImmutableClassName(descriptor_),
+ "ver", GeneratedCodeVersionSuffix());
+ }
+ }
+
+ // Merge the fields and the extension ranges, both sorted by field number.
+ for (int i = 0, j = 0;
+ i < descriptor_->field_count() || j < sorted_extensions.size();) {
+ if (i == descriptor_->field_count()) {
+ GenerateSerializeOneExtensionRange(printer, sorted_extensions[j++]);
+ } else if (j == sorted_extensions.size()) {
+ GenerateSerializeOneField(printer, sorted_fields[i++]);
+ } else if (sorted_fields[i]->number() < sorted_extensions[j]->start) {
+ GenerateSerializeOneField(printer, sorted_fields[i++]);
+ } else {
+ GenerateSerializeOneExtensionRange(printer, sorted_extensions[j++]);
+ }
}
- }
- if (PreserveUnknownFields(descriptor_)) {
if (descriptor_->options().message_set_wire_format()) {
- printer->Print(
- "unknownFields.writeAsMessageSetTo(output);\n");
+ printer->Print("unknownFields.writeAsMessageSetTo(output);\n");
} else {
- printer->Print(
- "unknownFields.writeTo(output);\n");
+ printer->Print("unknownFields.writeTo(output);\n");
}
}
printer->Outdent();
printer->Print(
- "}\n"
- "\n"
- "public int getSerializedSize() {\n"
- " int size = memoizedSize;\n"
- " if (size != -1) return size;\n"
- "\n"
- " size = 0;\n");
+ "}\n"
+ "\n"
+ "public int getSerializedSize() {\n"
+ " int size = memoizedSize;\n"
+ " if (size != -1) return size;\n"
+ "\n");
printer->Indent();
+ if (EnableExperimentalRuntime(context_) && !IsDescriptorProto(descriptor_)) {
+ printer->Print(
+ "memoizedSize = getSerializedSizeInternal();\n"
+ "return memoizedSize;\n");
+ } else {
- for (int i = 0; i < descriptor_->field_count(); i++) {
- field_generators_.get(sorted_fields[i]).GenerateSerializedSizeCode(printer);
- }
+ printer->Print("size = 0;\n");
- if (descriptor_->extension_range_count() > 0) {
- if (descriptor_->options().message_set_wire_format()) {
- printer->Print(
- "size += extensionsSerializedSizeAsMessageSet();\n");
- } else {
- printer->Print(
- "size += extensionsSerializedSize();\n");
+ for (int i = 0; i < descriptor_->field_count(); i++) {
+ field_generators_.get(sorted_fields[i])
+ .GenerateSerializedSizeCode(printer);
+ }
+
+ if (descriptor_->extension_range_count() > 0) {
+ if (descriptor_->options().message_set_wire_format()) {
+ printer->Print("size += extensionsSerializedSizeAsMessageSet();\n");
+ } else {
+ printer->Print("size += extensionsSerializedSize();\n");
+ }
}
- }
- if (PreserveUnknownFields(descriptor_)) {
if (descriptor_->options().message_set_wire_format()) {
printer->Print(
- "size += unknownFields.getSerializedSizeAsMessageSet();\n");
+ "size += unknownFields.getSerializedSizeAsMessageSet();\n");
} else {
- printer->Print(
- "size += unknownFields.getSerializedSize();\n");
+ printer->Print("size += unknownFields.getSerializedSize();\n");
}
+
+ printer->Print(
+ "memoizedSize = size;\n"
+ "return size;\n");
}
printer->Outdent();
printer->Print(
- " memoizedSize = size;\n"
- " return size;\n"
"}\n"
"\n");
-
- printer->Print(
- "private static final long serialVersionUID = 0L;\n");
}
void ImmutableMessageGenerator::
@@ -678,6 +699,17 @@ GenerateParseFromMethods(io::Printer* printer) {
// for code size.
printer->Print(
"public static $classname$ parseFrom(\n"
+ " java.nio.ByteBuffer data)\n"
+ " throws com.google.protobuf.InvalidProtocolBufferException {\n"
+ " return PARSER.parseFrom(data);\n"
+ "}\n"
+ "public static $classname$ parseFrom(\n"
+ " java.nio.ByteBuffer data,\n"
+ " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n"
+ " throws com.google.protobuf.InvalidProtocolBufferException {\n"
+ " return PARSER.parseFrom(data, extensionRegistry);\n"
+ "}\n"
+ "public static $classname$ parseFrom(\n"
" com.google.protobuf.ByteString data)\n"
" throws com.google.protobuf.InvalidProtocolBufferException {\n"
" return PARSER.parseFrom(data);\n"
@@ -1059,13 +1091,11 @@ GenerateEqualsAndHashCode(io::Printer* printer) {
printer->Print("}\n");
}
- if (PreserveUnknownFields(descriptor_)) {
- // Always consider unknown fields for equality. This will sometimes return
- // false for non-canonical ordering when running in LITE_RUNTIME but it's
- // the best we can do.
- printer->Print(
+ // Always consider unknown fields for equality. This will sometimes return
+ // false for non-canonical ordering when running in LITE_RUNTIME but it's
+ // the best we can do.
+ printer->Print(
"result = result && unknownFields.equals(other.unknownFields);\n");
- }
if (descriptor_->extension_range_count() > 0) {
printer->Print(
"result = result &&\n"
@@ -1192,7 +1222,10 @@ GenerateParsingConstructor(io::Printer* printer) {
// Initialize all fields to default.
printer->Print(
- "this();\n");
+ "this();\n"
+ "if (extensionRegistry == null) {\n"
+ " throw new java.lang.NullPointerException();\n"
+ "}\n");
// Use builder bits to track mutable repeated fields.
int totalBuilderBits = 0;
@@ -1207,11 +1240,9 @@ GenerateParsingConstructor(io::Printer* printer) {
"bit_field_name", GetBitFieldName(i));
}
- if (PreserveUnknownFields(descriptor_)) {
- printer->Print(
+ printer->Print(
"com.google.protobuf.UnknownFieldSet.Builder unknownFields =\n"
" com.google.protobuf.UnknownFieldSet.newBuilder();\n");
- }
printer->Print(
"try {\n");
@@ -1228,28 +1259,19 @@ GenerateParsingConstructor(io::Printer* printer) {
printer->Indent();
printer->Print(
- "case 0:\n" // zero signals EOF / limit reached
+ "case 0:\n" // zero signals EOF / limit reached
" done = true;\n"
- " break;\n");
-
- if (PreserveUnknownFields(descriptor_)) {
- printer->Print(
- "default: {\n"
- " if (!parseUnknownField(input, unknownFields,\n"
- " extensionRegistry, tag)) {\n"
- " done = true;\n" // it's an endgroup tag
- " }\n"
- " break;\n"
- "}\n");
- } else {
- printer->Print(
- "default: {\n"
- " if (!input.skipField(tag)) {\n"
- " done = true;\n" // it's an endgroup tag
- " }\n"
- " break;\n"
- "}\n");
- }
+ " break;\n"
+ "default: {\n"
+ " if (!parseUnknownField$suffix$(\n"
+ " input, unknownFields, extensionRegistry, tag)) {\n"
+ " done = true;\n" // it's an endgroup tag
+ " }\n"
+ " break;\n"
+ "}\n",
+ "suffix",
+ descriptor_->file()->syntax() == FileDescriptor::SYNTAX_PROTO3 ? "Proto3"
+ : "");
for (int i = 0; i < descriptor_->field_count(); i++) {
const FieldDescriptor* field = sorted_fields[i];
@@ -1309,10 +1331,8 @@ GenerateParsingConstructor(io::Printer* printer) {
field_generators_.get(field).GenerateParsingDoneCode(printer);
}
- if (PreserveUnknownFields(descriptor_)) {
- // Make unknown fields immutable.
- printer->Print("this.unknownFields = unknownFields.build();\n");
- }
+ // Make unknown fields immutable.
+ printer->Print("this.unknownFields = unknownFields.build();\n");
// Make extensions immutable.
printer->Print(
@@ -1341,10 +1361,18 @@ void ImmutableMessageGenerator::GenerateParser(io::Printer* printer) {
" com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n"
" throws com.google.protobuf.InvalidProtocolBufferException {\n",
"classname", descriptor_->name());
- if (context_->HasGeneratedMethods(descriptor_)) {
+ if (EnableExperimentalRuntime(context_) && !IsDescriptorProto(descriptor_)) {
+ printer->Indent();
printer->Print(
- " return new $classname$(input, extensionRegistry);\n",
+ "$classname$ msg = new $classname$();\n"
+ "msg.mergeFromInternal(input, extensionRegistry);\n"
+ "msg.makeImmutableInternal();\n"
+ "return msg;\n",
"classname", descriptor_->name());
+ printer->Outdent();
+ } else if (context_->HasGeneratedMethods(descriptor_)) {
+ printer->Print(" return new $classname$(input, extensionRegistry);\n",
+ "classname", descriptor_->name());
} else {
// When parsing constructor isn't generated, use builder to parse
// messages. Note, will fallback to use reflection based mergeFieldFrom()
@@ -1445,6 +1473,7 @@ void ImmutableMessageGenerator::GenerateAnyMethods(io::Printer* printer) {
"\n"
"private volatile com.google.protobuf.Message cachedUnpackValue;\n"
"\n"
+ "@java.lang.SuppressWarnings(\"unchecked\")\n"
"public <T extends com.google.protobuf.Message> T unpack(\n"
" java.lang.Class<T> clazz)\n"
" throws com.google.protobuf.InvalidProtocolBufferException {\n"
diff --git a/src/google/protobuf/compiler/java/java_message_builder.cc b/src/google/protobuf/compiler/java/java_message_builder.cc
index f5643abc..f9bbfbf4 100644
--- a/src/google/protobuf/compiler/java/java_message_builder.cc
+++ b/src/google/protobuf/compiler/java/java_message_builder.cc
@@ -54,8 +54,9 @@
#include <google/protobuf/io/printer.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/wire_format.h>
-#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/substitute.h>
+#include <google/protobuf/stubs/strutil.h>
+
namespace google {
namespace protobuf {
@@ -171,36 +172,25 @@ Generate(io::Printer* printer) {
.GenerateBuilderMembers(printer);
}
- if (!PreserveUnknownFields(descriptor_)) {
- printer->Print(
- "public final Builder setUnknownFields(\n"
- " final com.google.protobuf.UnknownFieldSet unknownFields) {\n"
- " return this;\n"
- "}\n"
- "\n"
- "public final Builder mergeUnknownFields(\n"
- " final com.google.protobuf.UnknownFieldSet unknownFields) {\n"
- " return this;\n"
- "}\n"
- "\n");
- } else {
+ bool is_proto3 =
+ descriptor_->file()->syntax() == FileDescriptor::SYNTAX_PROTO3;
// Override methods declared in GeneratedMessage to return the concrete
// generated type so callsites won't depend on GeneratedMessage. This
// is needed to keep binary compatibility when we change generated code
// to subclass a different GeneratedMessage class (e.g., in v3.0.0 release
// we changed all generated code to subclass GeneratedMessageV3).
- printer->Print(
- "public final Builder setUnknownFields(\n"
- " final com.google.protobuf.UnknownFieldSet unknownFields) {\n"
- " return super.setUnknownFields(unknownFields);\n"
- "}\n"
- "\n"
- "public final Builder mergeUnknownFields(\n"
- " final com.google.protobuf.UnknownFieldSet unknownFields) {\n"
- " return super.mergeUnknownFields(unknownFields);\n"
- "}\n"
- "\n");
- }
+ printer->Print(
+ "public final Builder setUnknownFields(\n"
+ " final com.google.protobuf.UnknownFieldSet unknownFields) {\n"
+ " return super.setUnknownFields$suffix$(unknownFields);\n"
+ "}\n"
+ "\n"
+ "public final Builder mergeUnknownFields(\n"
+ " final com.google.protobuf.UnknownFieldSet unknownFields) {\n"
+ " return super.mergeUnknownFields(unknownFields);\n"
+ "}\n"
+ "\n",
+ "suffix", is_proto3 ? "Proto3" : "");
printer->Print(
"\n"
@@ -472,7 +462,7 @@ GenerateCommonBuilderMethods(io::Printer* printer) {
"}\n"
"public Builder setField(\n"
" com.google.protobuf.Descriptors.FieldDescriptor field,\n"
- " Object value) {\n"
+ " java.lang.Object value) {\n"
" return (Builder) super.setField(field, value);\n"
"}\n"
"public Builder clearField(\n"
@@ -485,12 +475,12 @@ GenerateCommonBuilderMethods(io::Printer* printer) {
"}\n"
"public Builder setRepeatedField(\n"
" com.google.protobuf.Descriptors.FieldDescriptor field,\n"
- " int index, Object value) {\n"
+ " int index, java.lang.Object value) {\n"
" return (Builder) super.setRepeatedField(field, index, value);\n"
"}\n"
"public Builder addRepeatedField(\n"
" com.google.protobuf.Descriptors.FieldDescriptor field,\n"
- " Object value) {\n"
+ " java.lang.Object value) {\n"
" return (Builder) super.addRepeatedField(field, value);\n"
"}\n");
@@ -594,10 +584,8 @@ GenerateCommonBuilderMethods(io::Printer* printer) {
" this.mergeExtensionFields(other);\n");
}
- if (PreserveUnknownFields(descriptor_)) {
- printer->Print(
- " this.mergeUnknownFields(other.unknownFields);\n");
- }
+ printer->Print(
+ " this.mergeUnknownFields(other.unknownFields);\n");
printer->Print(
" onChanged();\n");
diff --git a/src/google/protobuf/compiler/java/java_message_builder_lite.cc b/src/google/protobuf/compiler/java/java_message_builder_lite.cc
index 7e404ba1..1ad58c09 100644
--- a/src/google/protobuf/compiler/java/java_message_builder_lite.cc
+++ b/src/google/protobuf/compiler/java/java_message_builder_lite.cc
@@ -67,13 +67,6 @@ bool GenerateHasBits(const Descriptor* descriptor) {
return SupportFieldPresence(descriptor->file()) ||
HasRepeatedFields(descriptor);
}
-
-string MapValueImmutableClassdName(const Descriptor* descriptor,
- ClassNameResolver* name_resolver) {
- const FieldDescriptor* value_field = descriptor->FindFieldByName("value");
- GOOGLE_CHECK_EQ(FieldDescriptor::TYPE_MESSAGE, value_field->type());
- return name_resolver->GetImmutableClassName(value_field->message_type());
-}
} // namespace
MessageBuilderLiteGenerator::MessageBuilderLiteGenerator(
diff --git a/src/google/protobuf/compiler/java/java_message_field.cc b/src/google/protobuf/compiler/java/java_message_field.cc
index ae84db1c..baa7f872 100644
--- a/src/google/protobuf/compiler/java/java_message_field.cc
+++ b/src/google/protobuf/compiler/java/java_message_field.cc
@@ -150,12 +150,9 @@ GenerateInterfaceMembers(io::Printer* printer) const {
// interface so that builders can choose dynamically to either return a
// message or a nested builder, so that asking for the interface doesn't
// cause a message to ever be built.
- if (SupportFieldPresence(descriptor_->file()) ||
- descriptor_->containing_oneof() == NULL) {
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$boolean has$capitalized_name$();\n");
- }
+ WriteFieldDocComment(printer, descriptor_);
+ printer->Print(variables_,
+ "$deprecation$boolean has$capitalized_name$();\n");
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$$type$ get$capitalized_name$();\n");
@@ -174,39 +171,45 @@ GenerateMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
+ "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $get_has_field_bit_message$;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$() {\n"
+ "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$OrBuilder "
- "get$capitalized_name$OrBuilder() {\n"
+ "${$get$capitalized_name$OrBuilder$}$() {\n"
" return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
} else {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
+ "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $name$_ != null;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$() {\n"
+ "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$OrBuilder "
- "get$capitalized_name$OrBuilder() {\n"
+ "${$get$capitalized_name$OrBuilder$}$() {\n"
" return get$capitalized_name$();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
}
@@ -232,6 +235,7 @@ void ImmutableMessageFieldGenerator::PrintNestedBuilderFunction(
const char* nested_builder_case,
const char* trailing_code) const {
printer->Print(variables_, method_prototype);
+ printer->Annotate("{", "}", descriptor_);
printer->Print(" {\n");
printer->Indent();
PrintNestedBuilderCondition(printer, regular_case, nested_builder_case);
@@ -267,20 +271,22 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
if (support_field_presence) {
printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
+ "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $get_has_field_bit_builder$;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
} else {
printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
+ "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $name$Builder_ != null || $name$_ != null;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
// Field getField()
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
- "$deprecation$public $type$ get$capitalized_name$()",
+ "$deprecation$public $type$ ${$get$capitalized_name$$}$()",
"return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n",
"return $name$Builder_.getMessage();\n",
NULL);
@@ -288,7 +294,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// Field.Builder setField(Field value)
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
- "$deprecation$public Builder set$capitalized_name$($type$ value)",
+ "$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value)",
"if (value == null) {\n"
" throw new NullPointerException();\n"
@@ -304,7 +310,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// Field.Builder setField(Field.Builder builderForValue)
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
- "$deprecation$public Builder set$capitalized_name$(\n"
+ "$deprecation$public Builder ${$set$capitalized_name$$}$(\n"
" $type$.Builder builderForValue)",
"$name$_ = builderForValue.build();\n"
@@ -318,7 +324,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// Field.Builder mergeField(Field value)
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
- "$deprecation$public Builder merge$capitalized_name$($type$ value)",
+ "$deprecation$public Builder ${$merge$capitalized_name$$}$($type$ value)",
support_field_presence
? "if ($get_has_field_bit_builder$ &&\n"
@@ -346,7 +352,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// Field.Builder clearField()
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
- "$deprecation$public Builder clear$capitalized_name$()",
+ "$deprecation$public Builder ${$clear$capitalized_name$$}$()",
"$name$_ = null;\n"
"$on_changed$\n",
@@ -361,14 +367,17 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$.Builder get$capitalized_name$Builder() {\n"
+ "$deprecation$public $type$.Builder "
+ "${$get$capitalized_name$Builder$}$() {\n"
" $set_has_field_bit_builder$\n"
" $on_changed$\n"
" return get$capitalized_name$FieldBuilder().getBuilder();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$OrBuilder get$capitalized_name$OrBuilder() {\n"
+ "$deprecation$public $type$OrBuilder "
+ "${$get$capitalized_name$OrBuilder$}$() {\n"
" if ($name$Builder_ != null) {\n"
" return $name$Builder_.getMessageOrBuilder();\n"
" } else {\n"
@@ -376,6 +385,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
" $type$.getDefaultInstance() : $name$_;\n"
" }\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"private com.google.protobuf.SingleFieldBuilder$ver$<\n"
@@ -530,30 +540,32 @@ ImmutableMessageOneofFieldGenerator::
void ImmutableMessageOneofFieldGenerator::
GenerateMembers(io::Printer* printer) const {
PrintExtraFieldInfo(variables_, printer);
- if (SupportFieldPresence(descriptor_->file())) {
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
- " return $has_oneof_case_message$;\n"
- "}\n");
- }
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$() {\n"
+ "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
+ " return $has_oneof_case_message$;\n"
+ "}\n");
+ printer->Annotate("{", "}", descriptor_);
+ WriteFieldDocComment(printer, descriptor_);
+ printer->Print(variables_,
+ "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" return ($type$) $oneof_name$_;\n"
" }\n"
" return $type$.getDefaultInstance();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$OrBuilder get$capitalized_name$OrBuilder() {\n"
+ "$deprecation$public $type$OrBuilder "
+ "${$get$capitalized_name$OrBuilder$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" return ($type$) $oneof_name$_;\n"
" }\n"
" return $type$.getDefaultInstance();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
void ImmutableMessageOneofFieldGenerator::
@@ -571,19 +583,18 @@ GenerateBuilderMembers(io::Printer* printer) const {
// The comments above the methods below are based on a hypothetical
// field of type "Field" called "Field".
- if (SupportFieldPresence(descriptor_->file())) {
- // boolean hasField()
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
- " return $has_oneof_case_message$;\n"
- "}\n");
- }
+ // boolean hasField()
+ WriteFieldDocComment(printer, descriptor_);
+ printer->Print(variables_,
+ "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
+ " return $has_oneof_case_message$;\n"
+ "}\n");
+ printer->Annotate("{", "}", descriptor_);
// Field getField()
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
- "$deprecation$public $type$ get$capitalized_name$()",
+ "$deprecation$public $type$ ${$get$capitalized_name$$}$()",
"if ($has_oneof_case_message$) {\n"
" return ($type$) $oneof_name$_;\n"
@@ -600,7 +611,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// Field.Builder setField(Field value)
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
- "$deprecation$public Builder set$capitalized_name$($type$ value)",
+ "$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value)",
"if (value == null) {\n"
" throw new NullPointerException();\n"
@@ -616,7 +627,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// Field.Builder setField(Field.Builder builderForValue)
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
- "$deprecation$public Builder set$capitalized_name$(\n"
+ "$deprecation$public Builder ${$set$capitalized_name$$}$(\n"
" $type$.Builder builderForValue)",
"$oneof_name$_ = builderForValue.build();\n"
@@ -630,7 +641,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// Field.Builder mergeField(Field value)
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
- "$deprecation$public Builder merge$capitalized_name$($type$ value)",
+ "$deprecation$public Builder ${$merge$capitalized_name$$}$($type$ value)",
"if ($has_oneof_case_message$ &&\n"
" $oneof_name$_ != $type$.getDefaultInstance()) {\n"
@@ -652,7 +663,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// Field.Builder clearField()
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
- "$deprecation$public Builder clear$capitalized_name$()",
+ "$deprecation$public Builder ${$clear$capitalized_name$$}$()",
"if ($has_oneof_case_message$) {\n"
" $clear_oneof_case_message$;\n"
@@ -670,12 +681,15 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$.Builder get$capitalized_name$Builder() {\n"
+ "$deprecation$public $type$.Builder "
+ "${$get$capitalized_name$Builder$}$() {\n"
" return get$capitalized_name$FieldBuilder().getBuilder();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$OrBuilder get$capitalized_name$OrBuilder() {\n"
+ "$deprecation$public $type$OrBuilder "
+ "${$get$capitalized_name$OrBuilder$}$() {\n"
" if (($has_oneof_case_message$) && ($name$Builder_ != null)) {\n"
" return $name$Builder_.getMessageOrBuilder();\n"
" } else {\n"
@@ -685,11 +699,12 @@ GenerateBuilderMembers(io::Printer* printer) const {
" return $type$.getDefaultInstance();\n"
" }\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"private com.google.protobuf.SingleFieldBuilder$ver$<\n"
" $type$, $type$.Builder, $type$OrBuilder> \n"
- " get$capitalized_name$FieldBuilder() {\n"
+ " ${$get$capitalized_name$FieldBuilder$}$() {\n"
" if ($name$Builder_ == null) {\n"
" if (!($has_oneof_case_message$)) {\n"
" $oneof_name$_ = $type$.getDefaultInstance();\n"
@@ -705,6 +720,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
" $on_changed$;\n"
" return $name$Builder_;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
void ImmutableMessageOneofFieldGenerator::
@@ -833,31 +849,38 @@ GenerateMembers(io::Printer* printer) const {
PrintExtraFieldInfo(variables_, printer);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public java.util.List<$type$> get$capitalized_name$List() {\n"
+ "$deprecation$public java.util.List<$type$> "
+ "${$get$capitalized_name$List$}$() {\n"
" return $name$_;\n" // note: unmodifiable list
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.util.List<? extends $type$OrBuilder> \n"
- " get$capitalized_name$OrBuilderList() {\n"
+ " ${$get$capitalized_name$OrBuilderList$}$() {\n"
" return $name$_;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public int get$capitalized_name$Count() {\n"
+ "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n"
" return $name$_.size();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$(int index) {\n"
+ "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n"
" return $name$_.get(index);\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$OrBuilder get$capitalized_name$OrBuilder(\n"
+ "$deprecation$public $type$OrBuilder "
+ "${$get$capitalized_name$OrBuilder$}$(\n"
" int index) {\n"
" return $name$_.get(index);\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
@@ -883,6 +906,7 @@ void RepeatedImmutableMessageFieldGenerator::PrintNestedBuilderFunction(
const char* nested_builder_case,
const char* trailing_code) const {
printer->Print(variables_, method_prototype);
+ printer->Annotate("{", "}", descriptor_);
printer->Print(" {\n");
printer->Indent();
PrintNestedBuilderCondition(printer, regular_case, nested_builder_case);
@@ -934,7 +958,8 @@ GenerateBuilderMembers(io::Printer* printer) const {
// List<Field> getRepeatedFieldList()
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
- "$deprecation$public java.util.List<$type$> get$capitalized_name$List()",
+ "$deprecation$public java.util.List<$type$> "
+ "${$get$capitalized_name$List$}$()",
"return java.util.Collections.unmodifiableList($name$_);\n",
"return $name$Builder_.getMessageList();\n",
@@ -944,7 +969,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// int getRepeatedFieldCount()
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
- "$deprecation$public int get$capitalized_name$Count()",
+ "$deprecation$public int ${$get$capitalized_name$Count$}$()",
"return $name$_.size();\n",
"return $name$Builder_.getCount();\n",
@@ -954,7 +979,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// Field getRepeatedField(int index)
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
- "$deprecation$public $type$ get$capitalized_name$(int index)",
+ "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index)",
"return $name$_.get(index);\n",
@@ -965,7 +990,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// Builder setRepeatedField(int index, Field value)
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
- "$deprecation$public Builder set$capitalized_name$(\n"
+ "$deprecation$public Builder ${$set$capitalized_name$$}$(\n"
" int index, $type$ value)",
"if (value == null) {\n"
" throw new NullPointerException();\n"
@@ -979,7 +1004,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// Builder setRepeatedField(int index, Field.Builder builderForValue)
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
- "$deprecation$public Builder set$capitalized_name$(\n"
+ "$deprecation$public Builder ${$set$capitalized_name$$}$(\n"
" int index, $type$.Builder builderForValue)",
"ensure$capitalized_name$IsMutable();\n"
@@ -993,7 +1018,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// Builder addRepeatedField(Field value)
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
- "$deprecation$public Builder add$capitalized_name$($type$ value)",
+ "$deprecation$public Builder ${$add$capitalized_name$$}$($type$ value)",
"if (value == null) {\n"
" throw new NullPointerException();\n"
@@ -1010,7 +1035,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// Builder addRepeatedField(int index, Field value)
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
- "$deprecation$public Builder add$capitalized_name$(\n"
+ "$deprecation$public Builder ${$add$capitalized_name$$}$(\n"
" int index, $type$ value)",
"if (value == null) {\n"
@@ -1027,7 +1052,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// Builder addRepeatedField(Field.Builder builderForValue)
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
- "$deprecation$public Builder add$capitalized_name$(\n"
+ "$deprecation$public Builder ${$add$capitalized_name$$}$(\n"
" $type$.Builder builderForValue)",
"ensure$capitalized_name$IsMutable();\n"
@@ -1041,7 +1066,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// Builder addRepeatedField(int index, Field.Builder builderForValue)
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
- "$deprecation$public Builder add$capitalized_name$(\n"
+ "$deprecation$public Builder ${$add$capitalized_name$$}$(\n"
" int index, $type$.Builder builderForValue)",
"ensure$capitalized_name$IsMutable();\n"
@@ -1055,7 +1080,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// Builder addAllRepeatedField(Iterable<Field> values)
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
- "$deprecation$public Builder addAll$capitalized_name$(\n"
+ "$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n"
" java.lang.Iterable<? extends $type$> values)",
"ensure$capitalized_name$IsMutable();\n"
@@ -1070,7 +1095,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// Builder clearAllRepeatedField()
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
- "$deprecation$public Builder clear$capitalized_name$()",
+ "$deprecation$public Builder ${$clear$capitalized_name$$}$()",
"$name$_ = java.util.Collections.emptyList();\n"
"$clear_mutable_bit_builder$;\n"
@@ -1083,7 +1108,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// Builder removeRepeatedField(int index)
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
- "$deprecation$public Builder remove$capitalized_name$(int index)",
+ "$deprecation$public Builder ${$remove$capitalized_name$$}$(int index)",
"ensure$capitalized_name$IsMutable();\n"
"$name$_.remove(index);\n"
@@ -1095,14 +1120,16 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$.Builder get$capitalized_name$Builder(\n"
+ "$deprecation$public $type$.Builder ${$get$capitalized_name$Builder$}$(\n"
" int index) {\n"
" return get$capitalized_name$FieldBuilder().getBuilder(index);\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$OrBuilder get$capitalized_name$OrBuilder(\n"
+ "$deprecation$public $type$OrBuilder "
+ "${$get$capitalized_name$OrBuilder$}$(\n"
" int index) {\n"
" if ($name$Builder_ == null) {\n"
" return $name$_.get(index);"
@@ -1110,35 +1137,40 @@ GenerateBuilderMembers(io::Printer* printer) const {
" return $name$Builder_.getMessageOrBuilder(index);\n"
" }\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.util.List<? extends $type$OrBuilder> \n"
- " get$capitalized_name$OrBuilderList() {\n"
+ " ${$get$capitalized_name$OrBuilderList$}$() {\n"
" if ($name$Builder_ != null) {\n"
" return $name$Builder_.getMessageOrBuilderList();\n"
" } else {\n"
" return java.util.Collections.unmodifiableList($name$_);\n"
" }\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$.Builder add$capitalized_name$Builder() {\n"
+ "$deprecation$public $type$.Builder "
+ "${$add$capitalized_name$Builder$}$() {\n"
" return get$capitalized_name$FieldBuilder().addBuilder(\n"
" $type$.getDefaultInstance());\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$.Builder add$capitalized_name$Builder(\n"
+ "$deprecation$public $type$.Builder ${$add$capitalized_name$Builder$}$(\n"
" int index) {\n"
" return get$capitalized_name$FieldBuilder().addBuilder(\n"
" index, $type$.getDefaultInstance());\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.util.List<$type$.Builder> \n"
- " get$capitalized_name$BuilderList() {\n"
+ " ${$get$capitalized_name$BuilderList$}$() {\n"
" return get$capitalized_name$FieldBuilder().getBuilderList();\n"
"}\n"
"private com.google.protobuf.RepeatedFieldBuilder$ver$<\n"
@@ -1155,6 +1187,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
" }\n"
" return $name$Builder_;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
void RepeatedImmutableMessageFieldGenerator::
diff --git a/src/google/protobuf/compiler/java/java_message_field_lite.cc b/src/google/protobuf/compiler/java/java_message_field_lite.cc
index fd78f75a..df3e80d4 100644
--- a/src/google/protobuf/compiler/java/java_message_field_lite.cc
+++ b/src/google/protobuf/compiler/java/java_message_field_lite.cc
@@ -70,6 +70,7 @@ void SetMessageVariables(const FieldDescriptor* descriptor,
// by the proto compiler
(*variables)["deprecation"] = descriptor->options().deprecated()
? "@java.lang.Deprecated " : "";
+ (*variables)["required"] = descriptor->is_required() ? "true" : "false";
if (SupportFieldPresence(descriptor->file())) {
// For singular messages and builders, one bit is used for the hasField bit.
@@ -128,16 +129,9 @@ int ImmutableMessageFieldLiteGenerator::GetNumBitsForBuilder() const {
void ImmutableMessageFieldLiteGenerator::
GenerateInterfaceMembers(io::Printer* printer) const {
- // TODO(jonp): In the future, consider having a method specific to the
- // interface so that builders can choose dynamically to either return a
- // message or a nested builder, so that asking for the interface doesn't
- // cause a message to ever be built.
- if (SupportFieldPresence(descriptor_->file()) ||
- descriptor_->containing_oneof() == NULL) {
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$boolean has$capitalized_name$();\n");
- }
+ WriteFieldDocComment(printer, descriptor_);
+ printer->Print(variables_,
+ "$deprecation$boolean has$capitalized_name$();\n");
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$$type$ get$capitalized_name$();\n");
@@ -153,25 +147,29 @@ GenerateMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
+ "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $get_has_field_bit_message$;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$() {\n"
+ "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
} else {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
+ "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $name$_ != null;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$() {\n"
+ "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
// Field.Builder setField(Field value)
@@ -225,53 +223,60 @@ GenerateBuilderMembers(io::Printer* printer) const {
// boolean hasField()
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
+ "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return instance.has$capitalized_name$();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
// Field getField()
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$() {\n"
+ "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return instance.get$capitalized_name$();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
// Field.Builder setField(Field value)
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder set$capitalized_name$($type$ value) {\n"
+ "$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$(value);\n"
" return this;\n"
" }\n");
+ printer->Annotate("{", "}", descriptor_);
// Field.Builder setField(Field.Builder builderForValue)
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder set$capitalized_name$(\n"
+ "$deprecation$public Builder ${$set$capitalized_name$$}$(\n"
" $type$.Builder builderForValue) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$(builderForValue);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
// Field.Builder mergeField(Field value)
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder merge$capitalized_name$($type$ value) {\n"
+ "$deprecation$public Builder "
+ "${$merge$capitalized_name$$}$($type$ value) {\n"
" copyOnWrite();\n"
" instance.merge$capitalized_name$(value);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
// Field.Builder clearField()
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder clear$capitalized_name$() {"
+ "$deprecation$public Builder ${$clear$capitalized_name$$}$() {"
" copyOnWrite();\n"
" instance.clear$capitalized_name$();\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
void ImmutableMessageFieldLiteGenerator::
@@ -389,21 +394,21 @@ ImmutableMessageOneofFieldLiteGenerator::
void ImmutableMessageOneofFieldLiteGenerator::
GenerateMembers(io::Printer* printer) const {
PrintExtraFieldInfo(variables_, printer);
- if (SupportFieldPresence(descriptor_->file())) {
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
- " return $has_oneof_case_message$;\n"
- "}\n");
- }
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$() {\n"
+ "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
+ " return $has_oneof_case_message$;\n"
+ "}\n");
+ printer->Annotate("{", "}", descriptor_);
+ WriteFieldDocComment(printer, descriptor_);
+ printer->Print(variables_,
+ "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" return ($type$) $oneof_name$_;\n"
" }\n"
" return $type$.getDefaultInstance();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
// Field.Builder setField(Field value)
WriteFieldDocComment(printer, descriptor_);
@@ -450,63 +455,69 @@ GenerateMembers(io::Printer* printer) const {
"}\n");
}
+
void ImmutableMessageOneofFieldLiteGenerator::
GenerateBuilderMembers(io::Printer* printer) const {
// The comments above the methods below are based on a hypothetical
// field of type "Field" called "Field".
- if (SupportFieldPresence(descriptor_->file())) {
- // boolean hasField()
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
- " return instance.has$capitalized_name$();\n"
- "}\n");
- }
+ // boolean hasField()
+ WriteFieldDocComment(printer, descriptor_);
+ printer->Print(variables_,
+ "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
+ " return instance.has$capitalized_name$();\n"
+ "}\n");
+ printer->Annotate("{", "}", descriptor_);
// Field getField()
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$() {\n"
+ "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return instance.get$capitalized_name$();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
// Field.Builder setField(Field value)
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder set$capitalized_name$($type$ value) {\n"
+ "$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$(value);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
// Field.Builder setField(Field.Builder builderForValue)
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder set$capitalized_name$(\n"
+ "$deprecation$public Builder ${$set$capitalized_name$$}$(\n"
" $type$.Builder builderForValue) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$(builderForValue);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
// Field.Builder mergeField(Field value)
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder merge$capitalized_name$($type$ value) {\n"
+ "$deprecation$public Builder "
+ "${$merge$capitalized_name$$}$($type$ value) {\n"
" copyOnWrite();\n"
" instance.merge$capitalized_name$(value);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
// Field.Builder clearField()
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder clear$capitalized_name$() {\n"
+ "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" copyOnWrite();\n"
" instance.clear$capitalized_name$();\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
void ImmutableMessageOneofFieldLiteGenerator::
@@ -613,31 +624,38 @@ GenerateMembers(io::Printer* printer) const {
PrintExtraFieldInfo(variables_, printer);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public java.util.List<$type$> get$capitalized_name$List() {\n"
+ "$deprecation$public java.util.List<$type$> "
+ "${$get$capitalized_name$List$}$() {\n"
" return $name$_;\n" // note: unmodifiable list
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.util.List<? extends $type$OrBuilder> \n"
- " get$capitalized_name$OrBuilderList() {\n"
+ " ${$get$capitalized_name$OrBuilderList$}$() {\n"
" return $name$_;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public int get$capitalized_name$Count() {\n"
+ "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n"
" return $name$_.size();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$(int index) {\n"
+ "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n"
" return $name$_.get(index);\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$OrBuilder get$capitalized_name$OrBuilder(\n"
+ "$deprecation$public $type$OrBuilder "
+ "${$get$capitalized_name$OrBuilder$}$(\n"
" int index) {\n"
" return $name$_.get(index);\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
printer->Print(variables_,
"private void ensure$capitalized_name$IsMutable() {\n"
@@ -743,110 +761,123 @@ GenerateBuilderMembers(io::Printer* printer) const {
// List<Field> getRepeatedFieldList()
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public java.util.List<$type$> get$capitalized_name$List() {\n"
+ "$deprecation$public java.util.List<$type$> "
+ "${$get$capitalized_name$List$}$() {\n"
" return java.util.Collections.unmodifiableList(\n"
" instance.get$capitalized_name$List());\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
// int getRepeatedFieldCount()
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public int get$capitalized_name$Count() {\n"
+ "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n"
" return instance.get$capitalized_name$Count();\n"
"}");
+ printer->Annotate("{", "}", descriptor_);
// Field getRepeatedField(int index)
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$(int index) {\n"
+ "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n"
" return instance.get$capitalized_name$(index);\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
// Builder setRepeatedField(int index, Field value)
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder set$capitalized_name$(\n"
+ "$deprecation$public Builder ${$set$capitalized_name$$}$(\n"
" int index, $type$ value) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$(index, value);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
// Builder setRepeatedField(int index, Field.Builder builderForValue)
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder set$capitalized_name$(\n"
+ "$deprecation$public Builder ${$set$capitalized_name$$}$(\n"
" int index, $type$.Builder builderForValue) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$(index, builderForValue);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
// Builder addRepeatedField(Field value)
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder add$capitalized_name$($type$ value) {\n"
+ "$deprecation$public Builder ${$add$capitalized_name$$}$($type$ value) {\n"
" copyOnWrite();\n"
" instance.add$capitalized_name$(value);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
// Builder addRepeatedField(int index, Field value)
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder add$capitalized_name$(\n"
+ "$deprecation$public Builder ${$add$capitalized_name$$}$(\n"
" int index, $type$ value) {\n"
" copyOnWrite();\n"
" instance.add$capitalized_name$(index, value);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
// Builder addRepeatedField(Field.Builder builderForValue)
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder add$capitalized_name$(\n"
+ "$deprecation$public Builder ${$add$capitalized_name$$}$(\n"
" $type$.Builder builderForValue) {\n"
" copyOnWrite();\n"
" instance.add$capitalized_name$(builderForValue);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
// Builder addRepeatedField(int index, Field.Builder builderForValue)
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder add$capitalized_name$(\n"
+ "$deprecation$public Builder ${$add$capitalized_name$$}$(\n"
" int index, $type$.Builder builderForValue) {\n"
" copyOnWrite();\n"
" instance.add$capitalized_name$(index, builderForValue);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
// Builder addAllRepeatedField(Iterable<Field> values)
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder addAll$capitalized_name$(\n"
+ "$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n"
" java.lang.Iterable<? extends $type$> values) {\n"
" copyOnWrite();\n"
" instance.addAll$capitalized_name$(values);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
// Builder clearAllRepeatedField()
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder clear$capitalized_name$() {\n"
+ "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" copyOnWrite();\n"
" instance.clear$capitalized_name$();\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
// Builder removeRepeatedField(int index)
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder remove$capitalized_name$(int index) {\n"
+ "$deprecation$public Builder ${$remove$capitalized_name$$}$(int index) {\n"
" copyOnWrite();\n"
" instance.remove$capitalized_name$(index);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
void RepeatedImmutableMessageFieldLiteGenerator::
@@ -855,6 +886,7 @@ GenerateFieldBuilderInitializationCode(io::Printer* printer) const {
"get$capitalized_name$FieldBuilder();\n");
}
+
void RepeatedImmutableMessageFieldLiteGenerator::
GenerateInitializationCode(io::Printer* printer) const {
printer->Print(variables_, "$name$_ = emptyProtobufList();\n");
diff --git a/src/google/protobuf/compiler/java/java_message_field_lite.h b/src/google/protobuf/compiler/java/java_message_field_lite.h
index dbb263de..7c814c6d 100644
--- a/src/google/protobuf/compiler/java/java_message_field_lite.h
+++ b/src/google/protobuf/compiler/java/java_message_field_lite.h
@@ -106,6 +106,7 @@ class ImmutableMessageOneofFieldLiteGenerator
void GenerateSerializationCode(io::Printer* printer) const;
void GenerateSerializedSizeCode(io::Printer* printer) const;
+
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableMessageOneofFieldLiteGenerator);
};
@@ -135,6 +136,7 @@ class RepeatedImmutableMessageFieldLiteGenerator
void GenerateEqualsCode(io::Printer* printer) const;
void GenerateHashCode(io::Printer* printer) const;
+
string GetBoxedType() const;
protected:
diff --git a/src/google/protobuf/compiler/java/java_message_lite.cc b/src/google/protobuf/compiler/java/java_message_lite.cc
index 8cc0f01d..d828be43 100644
--- a/src/google/protobuf/compiler/java/java_message_lite.cc
+++ b/src/google/protobuf/compiler/java/java_message_lite.cc
@@ -56,8 +56,9 @@
#include <google/protobuf/io/printer.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/wire_format.h>
-#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/substitute.h>
+#include <google/protobuf/stubs/strutil.h>
+
namespace google {
namespace protobuf {
@@ -68,6 +69,14 @@ using internal::WireFormat;
using internal::WireFormatLite;
namespace {
+bool EnableExperimentalRuntimeForLite() {
+#ifdef PROTOBUF_EXPERIMENT
+ return PROTOBUF_EXPERIMENT;
+#else // PROTOBUF_EXPERIMENT
+ return false;
+#endif // !PROTOBUF_EXPERIMENT
+}
+
bool GenerateHasBits(const Descriptor* descriptor) {
return SupportFieldPresence(descriptor->file()) ||
HasRepeatedFields(descriptor);
@@ -124,24 +133,28 @@ void ImmutableMessageLiteGenerator::GenerateInterface(io::Printer* printer) {
/* immutable = */ true, "OrBuilder");
if (descriptor_->extension_range_count() > 0) {
printer->Print(
- "public interface $classname$OrBuilder$idend$ extends \n"
+ "$deprecation$public interface ${$$classname$OrBuilder$}$ extends \n"
" $extra_interfaces$\n"
" com.google.protobuf.GeneratedMessageLite.\n"
" ExtendableMessageOrBuilder<\n"
" $classname$, $classname$.Builder> {\n",
+ "deprecation", descriptor_->options().deprecated() ?
+ "@java.lang.Deprecated " : "",
"extra_interfaces", ExtraMessageOrBuilderInterfaces(descriptor_),
"classname", descriptor_->name(),
- "idend", "");
+ "{", "", "}", "");
} else {
printer->Print(
- "public interface $classname$OrBuilder$idend$ extends\n"
+ "$deprecation$public interface ${$$classname$OrBuilder$}$ extends\n"
" $extra_interfaces$\n"
" com.google.protobuf.MessageLiteOrBuilder {\n",
+ "deprecation", descriptor_->options().deprecated() ?
+ "@java.lang.Deprecated " : "",
"extra_interfaces", ExtraMessageOrBuilderInterfaces(descriptor_),
"classname", descriptor_->name(),
- "idend", "");
+ "{", "", "}", "");
}
- printer->Annotate("classname", "idend", descriptor_);
+ printer->Annotate("{", "}", descriptor_);
printer->Indent();
for (int i = 0; i < descriptor_->field_count(); i++) {
@@ -174,6 +187,8 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
variables["static"] = is_own_file ? " " : " static ";
variables["classname"] = descriptor_->name();
variables["extra_interfaces"] = ExtraMessageInterfaces(descriptor_);
+ variables["deprecation"] = descriptor_->options().deprecated()
+ ? "@java.lang.Deprecated " : "";
WriteMessageDocComment(printer, descriptor_);
MaybePrintGeneratedAnnotation(context_, printer, descriptor_,
@@ -184,7 +199,7 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
string builder_type;
if (descriptor_->extension_range_count() > 0) {
printer->Print(variables,
- "public $static$final class $classname$ extends\n"
+ "$deprecation$public $static$final class $classname$ extends\n"
" com.google.protobuf.GeneratedMessageLite.ExtendableMessage<\n"
" $classname$, $classname$.Builder> implements\n"
" $extra_interfaces$\n"
@@ -194,7 +209,7 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
name_resolver_->GetImmutableClassName(descriptor_));
} else {
printer->Print(variables,
- "public $static$final class $classname$ extends\n"
+ "$deprecation$public $static$final class $classname$ extends\n"
" com.google.protobuf.GeneratedMessageLite<\n"
" $classname$, $classname$.Builder> implements\n"
" $extra_interfaces$\n"
@@ -325,40 +340,43 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
printer->Print("\n");
}
- GenerateMessageSerializationMethods(printer);
+ if (!EnableExperimentalRuntime(context_)) {
+ GenerateMessageSerializationMethods(printer);
+ }
GenerateParseFromMethods(printer);
GenerateBuilder(printer);
if (HasRequiredFields(descriptor_)) {
// Memoizes whether the protocol buffer is fully initialized (has all
- // required fields). -1 means not yet computed. 0 means false and 1 means
- // true.
+ // required fields). 0 means false, 1 means true, and all other values
+ // mean not yet computed.
printer->Print(
- "private byte memoizedIsInitialized = -1;\n");
+ "private byte memoizedIsInitialized = 2;\n");
}
printer->Print(
- "protected final Object dynamicMethod(\n"
- " com.google.protobuf.GeneratedMessageLite.MethodToInvoke method,\n"
- " Object arg0, Object arg1) {\n"
- " switch (method) {\n"
- " case NEW_MUTABLE_INSTANCE: {\n"
- " return new $classname$();\n"
- " }\n",
- "classname", name_resolver_->GetImmutableClassName(descriptor_));
+ "@java.lang.SuppressWarnings({\"unchecked\", \"fallthrough\"})\n"
+ "protected final java.lang.Object dynamicMethod(\n"
+ " com.google.protobuf.GeneratedMessageLite.MethodToInvoke method,\n"
+ " java.lang.Object arg0, java.lang.Object arg1) {\n"
+ " switch (method) {\n"
+ " case NEW_MUTABLE_INSTANCE: {\n"
+ " return new $classname$();\n"
+ " }\n",
+ "classname", name_resolver_->GetImmutableClassName(descriptor_));
printer->Indent();
printer->Indent();
- printer->Print(
- "case IS_INITIALIZED: {\n");
+ printer->Print("case IS_INITIALIZED: {\n");
printer->Indent();
GenerateDynamicMethodIsInitialized(printer);
printer->Outdent();
+ printer->Print("}\n");
+
printer->Print(
- "}\n"
"case MAKE_IMMUTABLE: {\n");
printer->Indent();
@@ -373,13 +391,15 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
GenerateDynamicMethodNewBuilder(printer);
printer->Outdent();
- printer->Print(
- "}\n"
- "case VISIT: {\n");
+ if (!EnableExperimentalRuntimeForLite()) {
+ printer->Print(
+ "}\n"
+ "case VISIT: {\n");
- printer->Indent();
- GenerateDynamicMethodVisit(printer);
- printer->Outdent();
+ printer->Indent();
+ GenerateDynamicMethodVisit(printer);
+ printer->Outdent();
+ }
printer->Print(
"}\n"
@@ -391,6 +411,7 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
printer->Print(
"}\n"
+ "// fall through\n"
"case GET_DEFAULT_INSTANCE: {\n"
" return DEFAULT_INSTANCE;\n"
"}\n"
@@ -406,13 +427,33 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
" }\n"
" }\n"
" }\n"
- " return PARSER;\n"
- "}\n",
+ " return PARSER;\n",
"classname", name_resolver_->GetImmutableClassName(descriptor_));
printer->Outdent();
- printer->Outdent();
+ if (HasRequiredFields(descriptor_)) {
+ printer->Print(
+ "}\n"
+ "case GET_MEMOIZED_IS_INITIALIZED: {\n"
+ " return memoizedIsInitialized;\n"
+ "}\n"
+ "case SET_MEMOIZED_IS_INITIALIZED: {\n"
+ " memoizedIsInitialized = (byte) (arg0 == null ? 0 : 1);\n"
+ " return null;\n"
+ "}\n");
+ } else {
+ printer->Print(
+ "}\n"
+ "case GET_MEMOIZED_IS_INITIALIZED: {\n"
+ " return (byte) 1;\n"
+ "}\n"
+ "case SET_MEMOIZED_IS_INITIALIZED: {\n"
+ " return null;\n"
+ "}\n");
+ }
+
+ printer->Outdent();
printer->Print(
" }\n"
" throw new UnsupportedOperationException();\n"
@@ -439,6 +480,17 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
"}\n"
"\n",
"classname", descriptor_->name());
+ if (EnableExperimentalRuntimeForLite()) {
+ // Register the default instance in a map. This map will be used by
+ // experimental runtime to lookup default instance given a class instance
+ // without using Java reflection.
+ printer->Print(
+ "static {\n"
+ " com.google.protobuf.GeneratedMessageLite.registerDefaultInstance(\n"
+ " $classname$.class, DEFAULT_INSTANCE);\n"
+ "}\n",
+ "classname", descriptor_->name());
+ }
printer->Print(
"public static $classname$ getDefaultInstance() {\n"
" return DEFAULT_INSTANCE;\n"
@@ -446,6 +498,17 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
"\n",
"classname", name_resolver_->GetImmutableClassName(descriptor_));
+ // 'of' method for Wrappers
+ if (IsWrappersProtoFile(descriptor_->file())) {
+ printer->Print(
+ "public static $classname$ of($field_type$ value) {\n"
+ " return newBuilder().setValue(value).build();\n"
+ "}\n"
+ "\n",
+ "classname", name_resolver_->GetImmutableClassName(descriptor_),
+ "field_type", PrimitiveTypeName(GetJavaType(descriptor_->field(0))));
+ }
+
GenerateParser(printer);
// Extensions must be declared after the DEFAULT_INSTANCE is initialized
@@ -460,6 +523,7 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
printer->Print("}\n\n");
}
+
// ===================================================================
void ImmutableMessageLiteGenerator::
@@ -481,36 +545,34 @@ GenerateMessageSerializationMethods(io::Printer* printer) {
if (HasPackedFields(descriptor_)) {
// writeTo(CodedOutputStream output) might be invoked without
// getSerializedSize() ever being called, but we need the memoized
- // sizes in case this message has packed fields. Rather than emit checks for
- // each packed field, just call getSerializedSize() up front.
- // In most cases, getSerializedSize() will have already been called anyway
- // by one of the wrapper writeTo() methods, making this call cheap.
- printer->Print(
- "getSerializedSize();\n");
+ // sizes in case this message has packed fields. Rather than emit checks
+ // for each packed field, just call getSerializedSize() up front. In most
+ // cases, getSerializedSize() will have already been called anyway by one
+ // of the wrapper writeTo() methods, making this call cheap.
+ printer->Print("getSerializedSize();\n");
}
if (descriptor_->extension_range_count() > 0) {
if (descriptor_->options().message_set_wire_format()) {
printer->Print(
- "com.google.protobuf.GeneratedMessageLite\n"
- " .ExtendableMessage<$classname$, $classname$.Builder>\n"
- " .ExtensionWriter extensionWriter =\n"
- " newMessageSetExtensionWriter();\n",
- "classname", name_resolver_->GetImmutableClassName(descriptor_));
+ "com.google.protobuf.GeneratedMessageLite\n"
+ " .ExtendableMessage<$classname$, $classname$.Builder>\n"
+ " .ExtensionWriter extensionWriter =\n"
+ " newMessageSetExtensionWriter();\n",
+ "classname", name_resolver_->GetImmutableClassName(descriptor_));
} else {
printer->Print(
- "com.google.protobuf.GeneratedMessageLite\n"
- " .ExtendableMessage<$classname$, $classname$.Builder>\n"
- " .ExtensionWriter extensionWriter =\n"
- " newExtensionWriter();\n",
- "classname", name_resolver_->GetImmutableClassName(descriptor_));
+ "com.google.protobuf.GeneratedMessageLite\n"
+ " .ExtendableMessage<$classname$, $classname$.Builder>\n"
+ " .ExtensionWriter extensionWriter =\n"
+ " newExtensionWriter();\n",
+ "classname", name_resolver_->GetImmutableClassName(descriptor_));
}
}
// Merge the fields and the extension ranges, both sorted by field number.
for (int i = 0, j = 0;
- i < descriptor_->field_count() || j < sorted_extensions.size();
- ) {
+ i < descriptor_->field_count() || j < sorted_extensions.size();) {
if (i == descriptor_->field_count()) {
GenerateSerializeOneExtensionRange(printer, sorted_extensions[j++]);
} else if (j == sorted_extensions.size()) {
@@ -522,26 +584,23 @@ GenerateMessageSerializationMethods(io::Printer* printer) {
}
}
- if (PreserveUnknownFields(descriptor_)) {
- if (descriptor_->options().message_set_wire_format()) {
- printer->Print(
- "unknownFields.writeAsMessageSetTo(output);\n");
- } else {
- printer->Print(
- "unknownFields.writeTo(output);\n");
- }
+ if (descriptor_->options().message_set_wire_format()) {
+ printer->Print("unknownFields.writeAsMessageSetTo(output);\n");
+ } else {
+ printer->Print("unknownFields.writeTo(output);\n");
}
printer->Outdent();
printer->Print(
- "}\n"
- "\n"
- "public int getSerializedSize() {\n"
- " int size = memoizedSerializedSize;\n"
- " if (size != -1) return size;\n"
- "\n"
- " size = 0;\n");
+ "}\n"
+ "\n"
+ "public int getSerializedSize() {\n"
+ " int size = memoizedSerializedSize;\n"
+ " if (size != -1) return size;\n"
+ "\n");
printer->Indent();
+ printer->Print(
+ "size = 0;\n");
for (int i = 0; i < descriptor_->field_count(); i++) {
field_generators_.get(sorted_fields[i]).GenerateSerializedSizeCode(printer);
@@ -549,28 +608,24 @@ GenerateMessageSerializationMethods(io::Printer* printer) {
if (descriptor_->extension_range_count() > 0) {
if (descriptor_->options().message_set_wire_format()) {
- printer->Print(
- "size += extensionsSerializedSizeAsMessageSet();\n");
+ printer->Print("size += extensionsSerializedSizeAsMessageSet();\n");
} else {
- printer->Print(
- "size += extensionsSerializedSize();\n");
+ printer->Print("size += extensionsSerializedSize();\n");
}
}
- if (PreserveUnknownFields(descriptor_)) {
- if (descriptor_->options().message_set_wire_format()) {
- printer->Print(
- "size += unknownFields.getSerializedSizeAsMessageSet();\n");
- } else {
- printer->Print(
- "size += unknownFields.getSerializedSize();\n");
- }
+ if (descriptor_->options().message_set_wire_format()) {
+ printer->Print("size += unknownFields.getSerializedSizeAsMessageSet();\n");
+ } else {
+ printer->Print("size += unknownFields.getSerializedSize();\n");
}
+ printer->Print(
+ "memoizedSerializedSize = size;\n"
+ "return size;\n");
+
printer->Outdent();
printer->Print(
- " memoizedSerializedSize = size;\n"
- " return size;\n"
"}\n"
"\n");
}
@@ -582,6 +637,19 @@ GenerateParseFromMethods(io::Printer* printer) {
// for code size.
printer->Print(
"public static $classname$ parseFrom(\n"
+ " java.nio.ByteBuffer data)\n"
+ " throws com.google.protobuf.InvalidProtocolBufferException {\n"
+ " return com.google.protobuf.GeneratedMessageLite.parseFrom(\n"
+ " DEFAULT_INSTANCE, data);\n"
+ "}\n"
+ "public static $classname$ parseFrom(\n"
+ " java.nio.ByteBuffer data,\n"
+ " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n"
+ " throws com.google.protobuf.InvalidProtocolBufferException {\n"
+ " return com.google.protobuf.GeneratedMessageLite.parseFrom(\n"
+ " DEFAULT_INSTANCE, data, extensionRegistry);\n"
+ "}\n"
+ "public static $classname$ parseFrom(\n"
" com.google.protobuf.ByteString data)\n"
" throws com.google.protobuf.InvalidProtocolBufferException {\n"
" return com.google.protobuf.GeneratedMessageLite.parseFrom(\n"
@@ -662,10 +730,10 @@ void ImmutableMessageLiteGenerator::GenerateSerializeOneExtensionRange(
void ImmutableMessageLiteGenerator::GenerateBuilder(io::Printer* printer) {
printer->Print(
"public static Builder newBuilder() {\n"
- " return DEFAULT_INSTANCE.toBuilder();\n"
+ " return (Builder) DEFAULT_INSTANCE.createBuilder();\n"
"}\n"
"public static Builder newBuilder($classname$ prototype) {\n"
- " return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);\n"
+ " return (Builder) DEFAULT_INSTANCE.createBuilder(prototype);\n"
"}\n"
"\n",
"classname", name_resolver_->GetImmutableClassName(descriptor_));
@@ -684,7 +752,10 @@ void ImmutableMessageLiteGenerator::GenerateDynamicMethodIsInitialized(
return;
}
- // Don't directly compare to -1 to avoid an Android x86 JIT bug.
+ // TODO(xiaofeng): Remove this when b/64445758 is fixed. We don't need to
+ // check memoizedIsInitialized here because the caller does that already,
+ // but right now proguard proto shrinker asserts on the bytecode layout of
+ // this code so it can't be removed until proguard is updated.
printer->Print(
"byte isInitialized = memoizedIsInitialized;\n"
"if (isInitialized == 1) return DEFAULT_INSTANCE;\n"
@@ -702,9 +773,6 @@ void ImmutableMessageLiteGenerator::GenerateDynamicMethodIsInitialized(
if (field->is_required()) {
printer->Print(
"if (!has$name$()) {\n"
- " if (shouldMemoize) {\n"
- " memoizedIsInitialized = 0;\n"
- " }\n"
" return null;\n"
"}\n",
"name", info->capitalized_name);
@@ -721,9 +789,6 @@ void ImmutableMessageLiteGenerator::GenerateDynamicMethodIsInitialized(
case FieldDescriptor::LABEL_REQUIRED:
printer->Print(
"if (!get$name$().isInitialized()) {\n"
- " if (shouldMemoize) {\n"
- " memoizedIsInitialized = 0;\n"
- " }\n"
" return null;\n"
"}\n",
"type", name_resolver_->GetImmutableClassName(
@@ -747,9 +812,6 @@ void ImmutableMessageLiteGenerator::GenerateDynamicMethodIsInitialized(
}
printer->Print(
" if (!get$name$().isInitialized()) {\n"
- " if (shouldMemoize) {\n"
- " memoizedIsInitialized = 0;\n"
- " }\n"
" return null;\n"
" }\n"
"}\n",
@@ -760,9 +822,6 @@ void ImmutableMessageLiteGenerator::GenerateDynamicMethodIsInitialized(
printer->Print(
"for ($type$ item : get$name$Map().values()) {\n"
" if (!item.isInitialized()) {\n"
- " if (shouldMemoize) {\n"
- " memoizedIsInitialized = 0;\n"
- " }\n"
" return null;\n"
" }\n"
"}\n",
@@ -773,9 +832,6 @@ void ImmutableMessageLiteGenerator::GenerateDynamicMethodIsInitialized(
printer->Print(
"for (int i = 0; i < get$name$Count(); i++) {\n"
" if (!get$name$(i).isInitialized()) {\n"
- " if (shouldMemoize) {\n"
- " memoizedIsInitialized = 0;\n"
- " }\n"
" return null;\n"
" }\n"
"}\n",
@@ -791,17 +847,11 @@ void ImmutableMessageLiteGenerator::GenerateDynamicMethodIsInitialized(
if (descriptor_->extension_range_count() > 0) {
printer->Print(
"if (!extensionsAreInitialized()) {\n"
- " if (shouldMemoize) {\n"
- " memoizedIsInitialized = 0;\n"
- " }\n"
" return null;\n"
"}\n");
}
printer->Print(
- "if (shouldMemoize) memoizedIsInitialized = 1;\n");
-
- printer->Print(
"return DEFAULT_INSTANCE;\n"
"\n");
}
@@ -929,25 +979,32 @@ void ImmutableMessageLiteGenerator::GenerateDynamicMethodMergeFromStream(
" (com.google.protobuf.CodedInputStream) arg0;\n"
"com.google.protobuf.ExtensionRegistryLite extensionRegistry =\n"
" (com.google.protobuf.ExtensionRegistryLite) arg1;\n"
- "try {\n");
- printer->Indent();
-
+ "if (extensionRegistry == null) {\n"
+ " throw new java.lang.NullPointerException();\n"
+ "}\n");
printer->Print(
- "boolean done = false;\n"
- "while (!done) {\n");
+ "try {\n");
printer->Indent();
+ if (EnableExperimentalRuntime(context_)) {
+ printer->Print(
+ "mergeFromInternal(input, extensionRegistry);\n"
+ "return DEFAULT_INSTANCE;\n");
+ } else {
+ printer->Print(
+ "boolean done = false;\n"
+ "while (!done) {\n");
+ printer->Indent();
- printer->Print(
- "int tag = input.readTag();\n"
- "switch (tag) {\n");
- printer->Indent();
+ printer->Print(
+ "int tag = input.readTag();\n"
+ "switch (tag) {\n");
+ printer->Indent();
- printer->Print(
- "case 0:\n" // zero signals EOF / limit reached
- " done = true;\n"
- " break;\n");
+ printer->Print(
+ "case 0:\n" // zero signals EOF / limit reached
+ " done = true;\n"
+ " break;\n");
- if (PreserveUnknownFields(descriptor_)) {
if (descriptor_->extension_range_count() > 0) {
if (descriptor_->options().message_set_wire_format()) {
printer->Print(
@@ -971,66 +1028,57 @@ void ImmutableMessageLiteGenerator::GenerateDynamicMethodMergeFromStream(
}
} else {
printer->Print(
- "default: {\n"
- " if (!parseUnknownField(tag, input)) {\n"
- " done = true;\n" // it's an endgroup tag
- " }\n"
- " break;\n"
- "}\n");
+ "default: {\n"
+ " if (!parseUnknownField(tag, input)) {\n"
+ " done = true;\n" // it's an endgroup tag
+ " }\n"
+ " break;\n"
+ "}\n");
}
- } else {
- printer->Print(
- "default: {\n"
- " if (!input.skipField(tag)) {\n"
- " done = true;\n" // it's an endgroup tag
- " }\n"
- " break;\n"
- "}\n");
- }
- google::protobuf::scoped_array<const FieldDescriptor * > sorted_fields(
- SortFieldsByNumber(descriptor_));
- for (int i = 0; i < descriptor_->field_count(); i++) {
- const FieldDescriptor* field = sorted_fields[i];
- uint32 tag = WireFormatLite::MakeTag(field->number(),
- WireFormat::WireTypeForFieldType(field->type()));
-
- printer->Print(
- "case $tag$: {\n",
- "tag", SimpleItoa(static_cast<int32>(tag)));
- printer->Indent();
-
- field_generators_.get(field).GenerateParsingCode(printer);
-
- printer->Outdent();
- printer->Print(
- " break;\n"
- "}\n");
+ google::protobuf::scoped_array<const FieldDescriptor* > sorted_fields(
+ SortFieldsByNumber(descriptor_));
+ for (int i = 0; i < descriptor_->field_count(); i++) {
+ const FieldDescriptor* field = sorted_fields[i];
+ uint32 tag = WireFormatLite::MakeTag(
+ field->number(), WireFormat::WireTypeForFieldType(field->type()));
- if (field->is_packable()) {
- // To make packed = true wire compatible, we generate parsing code from a
- // packed version of this field regardless of field->options().packed().
- uint32 packed_tag = WireFormatLite::MakeTag(field->number(),
- WireFormatLite::WIRETYPE_LENGTH_DELIMITED);
- printer->Print(
- "case $tag$: {\n",
- "tag", SimpleItoa(static_cast<int32>(packed_tag)));
+ printer->Print("case $tag$: {\n", "tag",
+ SimpleItoa(static_cast<int32>(tag)));
printer->Indent();
- field_generators_.get(field).GenerateParsingCodeFromPacked(printer);
+ field_generators_.get(field).GenerateParsingCode(printer);
printer->Outdent();
printer->Print(
" break;\n"
"}\n");
+
+ if (field->is_packable()) {
+ // To make packed = true wire compatible, we generate parsing code from
+ // a packed version of this field regardless of
+ // field->options().packed().
+ uint32 packed_tag = WireFormatLite::MakeTag(
+ field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED);
+ printer->Print("case $tag$: {\n", "tag",
+ SimpleItoa(static_cast<int32>(packed_tag)));
+ printer->Indent();
+
+ field_generators_.get(field).GenerateParsingCodeFromPacked(printer);
+
+ printer->Outdent();
+ printer->Print(
+ " break;\n"
+ "}\n");
+ }
}
- }
- printer->Outdent();
- printer->Outdent();
- printer->Print(
- " }\n" // switch (tag)
- "}\n"); // while (!done)
+ printer->Outdent();
+ printer->Outdent();
+ printer->Print(
+ " }\n" // switch (tag)
+ "}\n"); // while (!done)
+ }
printer->Outdent();
printer->Print(
@@ -1050,21 +1098,6 @@ void ImmutableMessageLiteGenerator::GenerateDynamicMethodMergeFromStream(
// ===================================================================
-namespace {
-bool CheckHasBitsForEqualsAndHashCode(const FieldDescriptor* field) {
- if (field->is_repeated()) {
- return false;
- }
- if (SupportFieldPresence(field->file())) {
- return true;
- }
- return GetJavaType(field) == JAVATYPE_MESSAGE &&
- field->containing_oneof() == NULL;
-}
-} // namespace
-
-// ===================================================================
-
void ImmutableMessageLiteGenerator::
GenerateExtensionRegistrationCode(io::Printer* printer) {
for (int i = 0; i < descriptor_->extension_count(); i++) {
diff --git a/src/google/protobuf/compiler/java/java_name_resolver.cc b/src/google/protobuf/compiler/java/java_name_resolver.cc
index bffe4f16..1673b4ee 100644
--- a/src/google/protobuf/compiler/java/java_name_resolver.cc
+++ b/src/google/protobuf/compiler/java/java_name_resolver.cc
@@ -33,6 +33,7 @@
#include <map>
#include <string>
+
#include <google/protobuf/compiler/java/java_helpers.h>
#include <google/protobuf/stubs/substitute.h>
diff --git a/src/google/protobuf/compiler/java/java_options.h b/src/google/protobuf/compiler/java/java_options.h
index 7bce1447..e4e7d5e2 100644
--- a/src/google/protobuf/compiler/java/java_options.h
+++ b/src/google/protobuf/compiler/java/java_options.h
@@ -59,10 +59,10 @@ struct Options {
bool annotate_code;
// Name of a file where we will write a list of generated .meta file names,
// one per line.
- string annotation_list_file;
+ std::string annotation_list_file;
// Name of a file where we will write a list of generated file names, one
// per line.
- string output_list_file;
+ std::string output_list_file;
};
} // namespace java
diff --git a/src/google/protobuf/compiler/java/java_primitive_field.cc b/src/google/protobuf/compiler/java/java_primitive_field.cc
index fa1047e8..074a6be8 100644
--- a/src/google/protobuf/compiler/java/java_primitive_field.cc
+++ b/src/google/protobuf/compiler/java/java_primitive_field.cc
@@ -190,16 +190,18 @@ GenerateMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
+ "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $get_has_field_bit_message$;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$() {\n"
+ "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return $name$_;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
void ImmutablePrimitiveFieldGenerator::
@@ -210,31 +212,35 @@ GenerateBuilderMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
+ "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $get_has_field_bit_builder$;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$() {\n"
+ "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return $name$_;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder set$capitalized_name$($type$ value) {\n"
+ "$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n"
"$null_check$"
" $set_has_field_bit_builder$\n"
" $name$_ = value;\n"
" $on_changed$\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder clear$capitalized_name$() {\n"
+ "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" $clear_has_field_bit_builder$\n");
+ printer->Annotate("{", "}", descriptor_);
JavaType type = GetJavaType(descriptor_);
if (type == JAVATYPE_STRING || type == JAVATYPE_BYTES) {
// The default value is not a simple literal so we want to avoid executing
@@ -441,19 +447,21 @@ GenerateMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
+ "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $has_oneof_case_message$;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$() {\n"
+ "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" return ($boxed_type$) $oneof_name$_;\n"
" }\n"
" return $default$;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
@@ -462,33 +470,36 @@ GenerateBuilderMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
+ "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $has_oneof_case_message$;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$() {\n"
+ "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" return ($boxed_type$) $oneof_name$_;\n"
" }\n"
" return $default$;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder set$capitalized_name$($type$ value) {\n"
+ "$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n"
"$null_check$"
" $set_oneof_case_message$;\n"
" $oneof_name$_ = value;\n"
" $on_changed$\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder clear$capitalized_name$() {\n"
+ "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" $clear_oneof_case_message$;\n"
" $oneof_name$_ = null;\n"
@@ -496,6 +507,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
" }\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
void ImmutablePrimitiveOneofFieldGenerator::
@@ -523,8 +535,17 @@ void ImmutablePrimitiveOneofFieldGenerator::
GenerateSerializationCode(io::Printer* printer) const {
printer->Print(variables_,
"if ($has_oneof_case_message$) {\n"
- " output.write$capitalized_type$(\n"
- " $number$, ($type$)(($boxed_type$) $oneof_name$_));\n"
+ " output.write$capitalized_type$(\n");
+ // $type$ and $boxed_type$ is the same for bytes fields so we don't need to
+ // do redundant casts.
+ if (GetJavaType(descriptor_) == JAVATYPE_BYTES) {
+ printer->Print(variables_,
+ " $number$, ($type$) $oneof_name$_);\n");
+ } else {
+ printer->Print(variables_,
+ " $number$, ($type$)(($boxed_type$) $oneof_name$_));\n");
+ }
+ printer->Print(
"}\n");
}
@@ -533,8 +554,17 @@ GenerateSerializedSizeCode(io::Printer* printer) const {
printer->Print(variables_,
"if ($has_oneof_case_message$) {\n"
" size += com.google.protobuf.CodedOutputStream\n"
- " .compute$capitalized_type$Size(\n"
- " $number$, ($type$)(($boxed_type$) $oneof_name$_));\n"
+ " .compute$capitalized_type$Size(\n");
+ // $type$ and $boxed_type$ is the same for bytes fields so we don't need to
+ // do redundant casts.
+ if (GetJavaType(descriptor_) == JAVATYPE_BYTES) {
+ printer->Print(variables_,
+ " $number$, ($type$) $oneof_name$_);\n");
+ } else {
+ printer->Print(variables_,
+ " $number$, ($type$)(($boxed_type$) $oneof_name$_));\n");
+ }
+ printer->Print(
"}\n");
}
@@ -586,19 +616,22 @@ GenerateMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.util.List<$boxed_type$>\n"
- " get$capitalized_name$List() {\n"
+ " ${$get$capitalized_name$List$}$() {\n"
" return $name$_;\n" // note: unmodifiable list
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public int get$capitalized_name$Count() {\n"
+ "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n"
" return $name$_.size();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$(int index) {\n"
+ "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n"
" return $name$_.get(index);\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
if (descriptor_->is_packed() &&
context_->HasGeneratedMethods(descriptor_->containing_type())) {
@@ -636,22 +669,25 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.util.List<$boxed_type$>\n"
- " get$capitalized_name$List() {\n"
+ " ${$get$capitalized_name$List$}$() {\n"
" return java.util.Collections.unmodifiableList($name$_);\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public int get$capitalized_name$Count() {\n"
+ "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n"
" return $name$_.size();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$(int index) {\n"
+ "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n"
" return $name$_.get(index);\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder set$capitalized_name$(\n"
+ "$deprecation$public Builder ${$set$capitalized_name$$}$(\n"
" int index, $type$ value) {\n"
"$null_check$"
" ensure$capitalized_name$IsMutable();\n"
@@ -659,18 +695,20 @@ GenerateBuilderMembers(io::Printer* printer) const {
" $on_changed$\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder add$capitalized_name$($type$ value) {\n"
+ "$deprecation$public Builder ${$add$capitalized_name$$}$($type$ value) {\n"
"$null_check$"
" ensure$capitalized_name$IsMutable();\n"
" $name$_.add(value);\n"
" $on_changed$\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder addAll$capitalized_name$(\n"
+ "$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n"
" java.lang.Iterable<? extends $boxed_type$> values) {\n"
" ensure$capitalized_name$IsMutable();\n"
" com.google.protobuf.AbstractMessageLite.Builder.addAll(\n"
@@ -678,14 +716,16 @@ GenerateBuilderMembers(io::Printer* printer) const {
" $on_changed$\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder clear$capitalized_name$() {\n"
+ "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" $name$_ = $empty_list$;\n"
" $clear_mutable_bit_builder$;\n"
" $on_changed$\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
void RepeatedImmutablePrimitiveFieldGenerator::
diff --git a/src/google/protobuf/compiler/java/java_primitive_field_lite.cc b/src/google/protobuf/compiler/java/java_primitive_field_lite.cc
index ac39f4cf..f9293171 100644
--- a/src/google/protobuf/compiler/java/java_primitive_field_lite.cc
+++ b/src/google/protobuf/compiler/java/java_primitive_field_lite.cc
@@ -74,6 +74,7 @@ void SetPrimitiveVariables(const FieldDescriptor* descriptor,
SimpleItoa(static_cast<int32>(WireFormat::MakeTag(descriptor)));
(*variables)["tag_size"] = SimpleItoa(
WireFormat::TagSize(descriptor->number(), GetType(descriptor)));
+ (*variables)["required"] = descriptor->is_required() ? "true" : "false";
string capitalized_type = UnderscoresToCamelCase(PrimitiveTypeName(javaType),
true /* cap_next_letter */);
@@ -221,16 +222,18 @@ GenerateMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
+ "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $get_has_field_bit_message$;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$() {\n"
+ "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return $name$_;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
@@ -263,32 +266,36 @@ GenerateBuilderMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
+ "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return instance.has$capitalized_name$();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$() {\n"
+ "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return instance.get$capitalized_name$();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder set$capitalized_name$($type$ value) {\n"
+ "$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$(value);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder clear$capitalized_name$() {\n"
+ "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" copyOnWrite();\n"
" instance.clear$capitalized_name$();\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
void ImmutablePrimitiveFieldLiteGenerator::
@@ -296,6 +303,7 @@ GenerateFieldBuilderInitializationCode(io::Printer* printer) const {
// noop for primitives
}
+
void ImmutablePrimitiveFieldLiteGenerator::
GenerateInitializationCode(io::Printer* printer) const {
if (IsByteStringWithCustomDefaultValue(descriptor_)) {
@@ -480,19 +488,21 @@ GenerateMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
+ "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $has_oneof_case_message$;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$() {\n"
+ "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" return ($boxed_type$) $oneof_name$_;\n"
" }\n"
" return $default$;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
@@ -518,32 +528,36 @@ GenerateBuilderMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
+ "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return instance.has$capitalized_name$();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$() {\n"
+ "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return instance.get$capitalized_name$();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder set$capitalized_name$($type$ value) {\n"
+ "$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$(value);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder clear$capitalized_name$() {\n"
+ "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" copyOnWrite();\n"
" instance.clear$capitalized_name$();\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
void ImmutablePrimitiveOneofFieldLiteGenerator::
@@ -632,21 +646,24 @@ GenerateMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.util.List<$boxed_type$>\n"
- " get$capitalized_name$List() {\n"
+ " ${$get$capitalized_name$List$}$() {\n"
" return $name$_;\n" // note: unmodifiable list
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public int get$capitalized_name$Count() {\n"
+ "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n"
" return $name$_.size();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$(int index) {\n"
+ "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n"
" return $repeated_get$(index);\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
- if (descriptor_->options().packed() &&
+ if (descriptor_->is_packed() &&
context_->HasGeneratedMethods(descriptor_->containing_type())) {
printer->Print(variables_,
"private int $name$MemoizedSerializedSize = -1;\n");
@@ -695,50 +712,57 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.util.List<$boxed_type$>\n"
- " get$capitalized_name$List() {\n"
+ " ${$get$capitalized_name$List$}$() {\n"
" return java.util.Collections.unmodifiableList(\n"
" instance.get$capitalized_name$List());\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public int get$capitalized_name$Count() {\n"
+ "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n"
" return instance.get$capitalized_name$Count();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$(int index) {\n"
+ "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n"
" return instance.get$capitalized_name$(index);\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder set$capitalized_name$(\n"
+ "$deprecation$public Builder ${$set$capitalized_name$$}$(\n"
" int index, $type$ value) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$(index, value);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder add$capitalized_name$($type$ value) {\n"
+ "$deprecation$public Builder ${$add$capitalized_name$$}$($type$ value) {\n"
" copyOnWrite();\n"
" instance.add$capitalized_name$(value);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder addAll$capitalized_name$(\n"
+ "$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n"
" java.lang.Iterable<? extends $boxed_type$> values) {\n"
" copyOnWrite();\n"
" instance.addAll$capitalized_name$(values);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder clear$capitalized_name$() {\n"
+ "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" copyOnWrite();\n"
" instance.clear$capitalized_name$();\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
void RepeatedImmutablePrimitiveFieldLiteGenerator::
@@ -746,6 +770,7 @@ GenerateFieldBuilderInitializationCode(io::Printer* printer) const {
// noop for primitives
}
+
void RepeatedImmutablePrimitiveFieldLiteGenerator::
GenerateInitializationCode(io::Printer* printer) const {
printer->Print(variables_, "$name$_ = $empty_list$;\n");
@@ -826,7 +851,7 @@ GenerateParsingDoneCode(io::Printer* printer) const {
void RepeatedImmutablePrimitiveFieldLiteGenerator::
GenerateSerializationCode(io::Printer* printer) const {
- if (descriptor_->options().packed()) {
+ if (descriptor_->is_packed()) {
// We invoke getSerializedSize in writeTo for messages that have packed
// fields in ImmutableMessageGenerator::GenerateMessageSerializationMethods.
// That makes it safe to rely on the memoized size here.
@@ -867,7 +892,7 @@ GenerateSerializedSizeCode(io::Printer* printer) const {
printer->Print(
"size += dataSize;\n");
- if (descriptor_->options().packed()) {
+ if (descriptor_->is_packed()) {
printer->Print(variables_,
"if (!get$capitalized_name$List().isEmpty()) {\n"
" size += $tag_size$;\n"
@@ -880,7 +905,7 @@ GenerateSerializedSizeCode(io::Printer* printer) const {
}
// cache the data size for packed fields.
- if (descriptor_->options().packed()) {
+ if (descriptor_->is_packed()) {
printer->Print(variables_,
"$name$MemoizedSerializedSize = dataSize;\n");
}
diff --git a/src/google/protobuf/compiler/java/java_primitive_field_lite.h b/src/google/protobuf/compiler/java/java_primitive_field_lite.h
index dc59f0cf..93416f0b 100644
--- a/src/google/protobuf/compiler/java/java_primitive_field_lite.h
+++ b/src/google/protobuf/compiler/java/java_primitive_field_lite.h
@@ -80,6 +80,7 @@ class ImmutablePrimitiveFieldLiteGenerator
void GenerateEqualsCode(io::Printer* printer) const;
void GenerateHashCode(io::Printer* printer) const;
+
string GetBoxedType() const;
protected:
@@ -110,6 +111,7 @@ class ImmutablePrimitiveOneofFieldLiteGenerator
void GenerateSerializationCode(io::Printer* printer) const;
void GenerateSerializedSizeCode(io::Printer* printer) const;
+
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutablePrimitiveOneofFieldLiteGenerator);
};
@@ -142,6 +144,7 @@ class RepeatedImmutablePrimitiveFieldLiteGenerator
void GenerateEqualsCode(io::Printer* printer) const;
void GenerateHashCode(io::Printer* printer) const;
+
string GetBoxedType() const;
private:
diff --git a/src/google/protobuf/compiler/java/java_shared_code_generator.cc b/src/google/protobuf/compiler/java/java_shared_code_generator.cc
index 5fe68245..9a42aba9 100644
--- a/src/google/protobuf/compiler/java/java_shared_code_generator.cc
+++ b/src/google/protobuf/compiler/java/java_shared_code_generator.cc
@@ -140,13 +140,16 @@ void SharedCodeGenerator::GenerateDescriptors(io::Printer* printer) {
"java.lang.String[] descriptorData = {\n");
printer->Indent();
- // Only write 40 bytes per line.
+ // Limit the number of bytes per line.
static const int kBytesPerLine = 40;
+ // Limit the number of lines per string part.
+ static const int kLinesPerPart = 400;
+ // Every block of bytes, start a new string literal, in order to avoid the
+ // 64k length limit. Note that this value needs to be <64k.
+ static const int kBytesPerPart = kBytesPerLine * kLinesPerPart;
for (int i = 0; i < file_data.size(); i += kBytesPerLine) {
if (i > 0) {
- // Every 400 lines, start a new string literal, in order to avoid the
- // 64k length limit.
- if (i % 400 == 0) {
+ if (i % kBytesPerPart == 0) {
printer->Print(",\n");
} else {
printer->Print(" +\n");
@@ -181,13 +184,17 @@ void SharedCodeGenerator::GenerateDescriptors(io::Printer* printer) {
// Find out all dependencies.
std::vector<std::pair<string, string> > dependencies;
for (int i = 0; i < file_->dependency_count(); i++) {
- if (ShouldIncludeDependency(file_->dependency(i))) {
- string filename = file_->dependency(i)->name();
- string classname = FileJavaPackage(file_->dependency(i)) + "." +
- name_resolver_->GetDescriptorClassName(
- file_->dependency(i));
- dependencies.push_back(std::make_pair(filename, classname));
+ string filename = file_->dependency(i)->name();
+ string package = FileJavaPackage(file_->dependency(i));
+ string classname = name_resolver_->GetDescriptorClassName(
+ file_->dependency(i));
+ string full_name;
+ if (package.empty()) {
+ full_name = classname;
+ } else {
+ full_name = package + "." + classname;
}
+ dependencies.push_back(std::make_pair(filename, full_name));
}
// -----------------------------------------------------------------
@@ -209,11 +216,6 @@ void SharedCodeGenerator::GenerateDescriptors(io::Printer* printer) {
" }, assigner);\n");
}
-bool SharedCodeGenerator::ShouldIncludeDependency(
- const FileDescriptor* descriptor) {
- return true;
-}
-
} // namespace java
} // namespace compiler
} // namespace protobuf
diff --git a/src/google/protobuf/compiler/java/java_shared_code_generator.h b/src/google/protobuf/compiler/java/java_shared_code_generator.h
index c8ead47a..40502270 100644
--- a/src/google/protobuf/compiler/java/java_shared_code_generator.h
+++ b/src/google/protobuf/compiler/java/java_shared_code_generator.h
@@ -77,11 +77,6 @@ class SharedCodeGenerator {
void GenerateDescriptors(io::Printer* printer);
private:
- // Returns whether the dependency should be included in the output file.
- // Always returns true for opensource, but used internally at Google to help
- // improve compatibility with version 1 of protocol buffers.
- bool ShouldIncludeDependency(const FileDescriptor* descriptor);
-
google::protobuf::scoped_ptr<ClassNameResolver> name_resolver_;
const FileDescriptor* file_;
const Options options_;
diff --git a/src/google/protobuf/compiler/java/java_string_field.cc b/src/google/protobuf/compiler/java/java_string_field.cc
index 5c2900ce..2b6e9381 100644
--- a/src/google/protobuf/compiler/java/java_string_field.cc
+++ b/src/google/protobuf/compiler/java/java_string_field.cc
@@ -217,14 +217,15 @@ GenerateMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
+ "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $get_has_field_bit_message$;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public java.lang.String get$capitalized_name$() {\n"
+ "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n"
" java.lang.Object ref = $name$_;\n"
" if (ref instanceof java.lang.String) {\n"
" return (java.lang.String) ref;\n"
@@ -232,6 +233,7 @@ GenerateMembers(io::Printer* printer) const {
" com.google.protobuf.ByteString bs = \n"
" (com.google.protobuf.ByteString) ref;\n"
" java.lang.String s = bs.toStringUtf8();\n");
+ printer->Annotate("{", "}", descriptor_);
if (CheckUtf8(descriptor_)) {
printer->Print(variables_,
" $name$_ = s;\n");
@@ -248,7 +250,7 @@ GenerateMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public com.google.protobuf.ByteString\n"
- " get$capitalized_name$Bytes() {\n"
+ " ${$get$capitalized_name$Bytes$}$() {\n"
" java.lang.Object ref = $name$_;\n"
" if (ref instanceof java.lang.String) {\n"
" com.google.protobuf.ByteString b = \n"
@@ -260,6 +262,7 @@ GenerateMembers(io::Printer* printer) const {
" return (com.google.protobuf.ByteString) ref;\n"
" }\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
void ImmutableStringFieldGenerator::
@@ -269,19 +272,21 @@ GenerateBuilderMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
+ "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $get_has_field_bit_builder$;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public java.lang.String get$capitalized_name$() {\n"
+ "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n"
" java.lang.Object ref = $name$_;\n"
" if (!(ref instanceof java.lang.String)) {\n"
" com.google.protobuf.ByteString bs =\n"
" (com.google.protobuf.ByteString) ref;\n"
" java.lang.String s = bs.toStringUtf8();\n");
+ printer->Annotate("{", "}", descriptor_);
if (CheckUtf8(descriptor_)) {
printer->Print(variables_,
" $name$_ = s;\n");
@@ -301,7 +306,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public com.google.protobuf.ByteString\n"
- " get$capitalized_name$Bytes() {\n"
+ " ${$get$capitalized_name$Bytes$}$() {\n"
" java.lang.Object ref = $name$_;\n"
" if (ref instanceof String) {\n"
" com.google.protobuf.ByteString b = \n"
@@ -313,10 +318,11 @@ GenerateBuilderMembers(io::Printer* printer) const {
" return (com.google.protobuf.ByteString) ref;\n"
" }\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder set$capitalized_name$(\n"
+ "$deprecation$public Builder ${$set$capitalized_name$$}$(\n"
" java.lang.String value) {\n"
"$null_check$"
" $set_has_field_bit_builder$\n"
@@ -324,10 +330,12 @@ GenerateBuilderMembers(io::Printer* printer) const {
" $on_changed$\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder clear$capitalized_name$() {\n"
+ "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" $clear_has_field_bit_builder$\n");
+ printer->Annotate("{", "}", descriptor_);
// The default value is not a simple literal so we want to avoid executing
// it multiple times. Instead, get the default out of the default instance.
printer->Print(variables_,
@@ -339,9 +347,10 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder set$capitalized_name$Bytes(\n"
+ "$deprecation$public Builder ${$set$capitalized_name$Bytes$}$(\n"
" com.google.protobuf.ByteString value) {\n"
"$null_check$");
+ printer->Annotate("{", "}", descriptor_);
if (CheckUtf8(descriptor_)) {
printer->Print(variables_,
" checkByteStringIsUtf8(value);\n");
@@ -482,14 +491,15 @@ GenerateMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
+ "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $has_oneof_case_message$;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public java.lang.String get$capitalized_name$() {\n"
+ "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n"
" java.lang.Object ref $default_init$;\n"
" if ($has_oneof_case_message$) {\n"
" ref = $oneof_name$_;\n"
@@ -500,6 +510,7 @@ GenerateMembers(io::Printer* printer) const {
" com.google.protobuf.ByteString bs = \n"
" (com.google.protobuf.ByteString) ref;\n"
" java.lang.String s = bs.toStringUtf8();\n");
+ printer->Annotate("{", "}", descriptor_);
if (CheckUtf8(descriptor_)) {
printer->Print(variables_,
" if ($has_oneof_case_message$) {\n"
@@ -519,7 +530,7 @@ GenerateMembers(io::Printer* printer) const {
printer->Print(variables_,
"$deprecation$public com.google.protobuf.ByteString\n"
- " get$capitalized_name$Bytes() {\n"
+ " ${$get$capitalized_name$Bytes$}$() {\n"
" java.lang.Object ref $default_init$;\n"
" if ($has_oneof_case_message$) {\n"
" ref = $oneof_name$_;\n"
@@ -536,6 +547,7 @@ GenerateMembers(io::Printer* printer) const {
" return (com.google.protobuf.ByteString) ref;\n"
" }\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
void ImmutableStringOneofFieldGenerator::
@@ -543,14 +555,15 @@ GenerateBuilderMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
+ "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $has_oneof_case_message$;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public java.lang.String get$capitalized_name$() {\n"
+ "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n"
" java.lang.Object ref $default_init$;\n"
" if ($has_oneof_case_message$) {\n"
" ref = $oneof_name$_;\n"
@@ -560,6 +573,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
" (com.google.protobuf.ByteString) ref;\n"
" java.lang.String s = bs.toStringUtf8();\n"
" if ($has_oneof_case_message$) {\n");
+ printer->Annotate("{", "}", descriptor_);
if (CheckUtf8(descriptor_)) {
printer->Print(variables_,
" $oneof_name$_ = s;\n");
@@ -580,7 +594,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public com.google.protobuf.ByteString\n"
- " get$capitalized_name$Bytes() {\n"
+ " ${$get$capitalized_name$Bytes$}$() {\n"
" java.lang.Object ref $default_init$;\n"
" if ($has_oneof_case_message$) {\n"
" ref = $oneof_name$_;\n"
@@ -597,10 +611,11 @@ GenerateBuilderMembers(io::Printer* printer) const {
" return (com.google.protobuf.ByteString) ref;\n"
" }\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder set$capitalized_name$(\n"
+ "$deprecation$public Builder ${$set$capitalized_name$$}$(\n"
" java.lang.String value) {\n"
"$null_check$"
" $set_oneof_case_message$;\n"
@@ -608,9 +623,10 @@ GenerateBuilderMembers(io::Printer* printer) const {
" $on_changed$\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder clear$capitalized_name$() {\n"
+ "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" $clear_oneof_case_message$;\n"
" $oneof_name$_ = null;\n"
@@ -618,12 +634,14 @@ GenerateBuilderMembers(io::Printer* printer) const {
" }\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder set$capitalized_name$Bytes(\n"
+ "$deprecation$public Builder ${$set$capitalized_name$Bytes$}$(\n"
" com.google.protobuf.ByteString value) {\n"
"$null_check$");
+ printer->Annotate("{", "}", descriptor_);
if (CheckUtf8(descriptor_)) {
printer->Print(variables_,
" checkByteStringIsUtf8(value);\n");
@@ -744,25 +762,30 @@ GenerateMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public com.google.protobuf.ProtocolStringList\n"
- " get$capitalized_name$List() {\n"
+ " ${$get$capitalized_name$List$}$() {\n"
" return $name$_;\n" // note: unmodifiable list
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public int get$capitalized_name$Count() {\n"
+ "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n"
" return $name$_.size();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public java.lang.String get$capitalized_name$(int index) {\n"
+ "$deprecation$public java.lang.String "
+ "${$get$capitalized_name$$}$(int index) {\n"
" return $name$_.get(index);\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public com.google.protobuf.ByteString\n"
- " get$capitalized_name$Bytes(int index) {\n"
+ " ${$get$capitalized_name$Bytes$}$(int index) {\n"
" return $name$_.getByteString(index);\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
void RepeatedImmutableStringFieldGenerator::
@@ -794,28 +817,33 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public com.google.protobuf.ProtocolStringList\n"
- " get$capitalized_name$List() {\n"
+ " ${$get$capitalized_name$List$}$() {\n"
" return $name$_.getUnmodifiableView();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public int get$capitalized_name$Count() {\n"
+ "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n"
" return $name$_.size();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public java.lang.String get$capitalized_name$(int index) {\n"
+ "$deprecation$public java.lang.String "
+ "${$get$capitalized_name$$}$(int index) {\n"
" return $name$_.get(index);\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public com.google.protobuf.ByteString\n"
- " get$capitalized_name$Bytes(int index) {\n"
+ " ${$get$capitalized_name$Bytes$}$(int index) {\n"
" return $name$_.getByteString(index);\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder set$capitalized_name$(\n"
+ "$deprecation$public Builder ${$set$capitalized_name$$}$(\n"
" int index, java.lang.String value) {\n"
"$null_check$"
" ensure$capitalized_name$IsMutable();\n"
@@ -823,9 +851,10 @@ GenerateBuilderMembers(io::Printer* printer) const {
" $on_changed$\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder add$capitalized_name$(\n"
+ "$deprecation$public Builder ${$add$capitalized_name$$}$(\n"
" java.lang.String value) {\n"
"$null_check$"
" ensure$capitalized_name$IsMutable();\n"
@@ -833,9 +862,10 @@ GenerateBuilderMembers(io::Printer* printer) const {
" $on_changed$\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder addAll$capitalized_name$(\n"
+ "$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n"
" java.lang.Iterable<java.lang.String> values) {\n"
" ensure$capitalized_name$IsMutable();\n"
" com.google.protobuf.AbstractMessageLite.Builder.addAll(\n"
@@ -843,20 +873,23 @@ GenerateBuilderMembers(io::Printer* printer) const {
" $on_changed$\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder clear$capitalized_name$() {\n"
+ "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" $name$_ = $empty_list$;\n"
" $clear_mutable_bit_builder$;\n"
" $on_changed$\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder add$capitalized_name$Bytes(\n"
+ "$deprecation$public Builder ${$add$capitalized_name$Bytes$}$(\n"
" com.google.protobuf.ByteString value) {\n"
"$null_check$");
+ printer->Annotate("{", "}", descriptor_);
if (CheckUtf8(descriptor_)) {
printer->Print(variables_,
" checkByteStringIsUtf8(value);\n");
diff --git a/src/google/protobuf/compiler/java/java_string_field_lite.cc b/src/google/protobuf/compiler/java/java_string_field_lite.cc
index 4d2dcad8..adda307c 100644
--- a/src/google/protobuf/compiler/java/java_string_field_lite.cc
+++ b/src/google/protobuf/compiler/java/java_string_field_lite.cc
@@ -71,7 +71,7 @@ void SetPrimitiveVariables(const FieldDescriptor* descriptor,
(*variables)["default"] = ImmutableDefaultValue(descriptor, name_resolver);
(*variables)["default_init"] =
"= " + ImmutableDefaultValue(descriptor, name_resolver);
- (*variables)["capitalized_type"] = "String";
+ (*variables)["capitalized_type"] = "java.lang.String";
(*variables)["tag"] =
SimpleItoa(static_cast<int32>(WireFormat::MakeTag(descriptor)));
(*variables)["tag_size"] = SimpleItoa(
@@ -85,6 +85,7 @@ void SetPrimitiveVariables(const FieldDescriptor* descriptor,
// by the proto compiler
(*variables)["deprecation"] = descriptor->options().deprecated()
? "@java.lang.Deprecated " : "";
+ (*variables)["required"] = descriptor->is_required() ? "true" : "false";
if (SupportFieldPresence(descriptor->file())) {
// For singular messages and builders, one bit is used for the hasField bit.
@@ -191,22 +192,25 @@ GenerateMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
+ "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $get_has_field_bit_message$;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public java.lang.String get$capitalized_name$() {\n"
+ "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n"
" return $name$_;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public com.google.protobuf.ByteString\n"
- " get$capitalized_name$Bytes() {\n"
+ " ${$get$capitalized_name$Bytes$}$() {\n"
" return com.google.protobuf.ByteString.copyFromUtf8($name$_);\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
@@ -245,48 +249,54 @@ GenerateBuilderMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
+ "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return instance.has$capitalized_name$();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public java.lang.String get$capitalized_name$() {\n"
+ "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n"
" return instance.get$capitalized_name$();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public com.google.protobuf.ByteString\n"
- " get$capitalized_name$Bytes() {\n"
+ " ${$get$capitalized_name$Bytes$}$() {\n"
" return instance.get$capitalized_name$Bytes();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder set$capitalized_name$(\n"
+ "$deprecation$public Builder ${$set$capitalized_name$$}$(\n"
" java.lang.String value) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$(value);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder clear$capitalized_name$() {\n"
+ "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" copyOnWrite();\n"
" instance.clear$capitalized_name$();\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder set$capitalized_name$Bytes(\n"
+ "$deprecation$public Builder ${$set$capitalized_name$Bytes$}$(\n"
" com.google.protobuf.ByteString value) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$Bytes(value);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
void ImmutableStringFieldLiteGenerator::
@@ -294,6 +304,7 @@ GenerateFieldBuilderInitializationCode(io::Printer* printer) const {
// noop for strings
}
+
void ImmutableStringFieldLiteGenerator::
GenerateInitializationCode(io::Printer* printer) const {
printer->Print(variables_, "$name$_ = $default$;\n");
@@ -322,7 +333,7 @@ void ImmutableStringFieldLiteGenerator::
GenerateParsingCode(io::Printer* printer) const {
if (CheckUtf8(descriptor_)) {
printer->Print(variables_,
- "String s = input.readStringRequireUtf8();\n"
+ "java.lang.String s = input.readStringRequireUtf8();\n"
"$set_has_field_bit_message$\n"
"$name$_ = s;\n");
} else {
@@ -331,7 +342,7 @@ GenerateParsingCode(io::Printer* printer) const {
// spurious intermediary ByteString allocations, cutting overall allocations
// in half.
printer->Print(variables_,
- "String s = input.readString();\n"
+ "java.lang.String s = input.readString();\n"
"$set_has_field_bit_message$\n"
"$name$_ = s;\n");
}
@@ -408,54 +419,60 @@ GenerateMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
+ "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $has_oneof_case_message$;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public java.lang.String get$capitalized_name$() {\n"
+ "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n"
" java.lang.String ref $default_init$;\n"
" if ($has_oneof_case_message$) {\n"
" ref = (java.lang.String) $oneof_name$_;\n"
" }\n"
" return ref;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public com.google.protobuf.ByteString\n"
- " get$capitalized_name$Bytes() {\n"
+ " ${$get$capitalized_name$Bytes$}$() {\n"
" java.lang.String ref $default_init$;\n"
" if ($has_oneof_case_message$) {\n"
" ref = (java.lang.String) $oneof_name$_;\n"
" }\n"
" return com.google.protobuf.ByteString.copyFromUtf8(ref);\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "private void set$capitalized_name$(\n"
+ "private void ${$set$capitalized_name$$}$(\n"
" java.lang.String value) {\n"
"$null_check$"
" $set_oneof_case_message$;\n"
" $oneof_name$_ = value;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "private void clear$capitalized_name$() {\n"
+ "private void ${$clear$capitalized_name$$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" $clear_oneof_case_message$;\n"
" $oneof_name$_ = null;\n"
" }\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "private void set$capitalized_name$Bytes(\n"
+ "private void ${$set$capitalized_name$Bytes$}$(\n"
" com.google.protobuf.ByteString value) {\n"
"$null_check$");
+ printer->Annotate("{", "}", descriptor_);
if (CheckUtf8(descriptor_)) {
printer->Print(variables_,
" checkByteStringIsUtf8(value);\n");
@@ -466,53 +483,60 @@ GenerateMembers(io::Printer* printer) const {
"}\n");
}
+
void ImmutableStringOneofFieldLiteGenerator::
GenerateBuilderMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
+ "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return instance.has$capitalized_name$();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public java.lang.String get$capitalized_name$() {\n"
+ "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n"
" return instance.get$capitalized_name$();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public com.google.protobuf.ByteString\n"
- " get$capitalized_name$Bytes() {\n"
+ " ${$get$capitalized_name$Bytes$}$() {\n"
" return instance.get$capitalized_name$Bytes();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder set$capitalized_name$(\n"
+ "$deprecation$public Builder ${$set$capitalized_name$$}$(\n"
" java.lang.String value) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$(value);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder clear$capitalized_name$() {\n"
+ "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" copyOnWrite();\n"
" instance.clear$capitalized_name$();\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder set$capitalized_name$Bytes(\n"
+ "$deprecation$public Builder ${$set$capitalized_name$Bytes$}$(\n"
" com.google.protobuf.ByteString value) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$Bytes(value);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
void ImmutableStringOneofFieldLiteGenerator::
@@ -526,7 +550,7 @@ void ImmutableStringOneofFieldLiteGenerator::
GenerateParsingCode(io::Printer* printer) const {
if (CheckUtf8(descriptor_)) {
printer->Print(variables_,
- "String s = input.readStringRequireUtf8();\n"
+ "java.lang.String s = input.readStringRequireUtf8();\n"
"$set_oneof_case_message$;\n"
"$oneof_name$_ = s;\n");
} else {
@@ -535,7 +559,7 @@ GenerateParsingCode(io::Printer* printer) const {
// spurious intermediary ByteString allocations, cutting overall allocations
// in half.
printer->Print(variables_,
- "String s = input.readString();\n"
+ "java.lang.String s = input.readString();\n"
"$set_oneof_case_message$;\n"
"$oneof_name$_ = s;\n");
}
@@ -594,7 +618,7 @@ void RepeatedImmutableStringFieldLiteGenerator::
GenerateInterfaceMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$java.util.List<String>\n"
+ "$deprecation$java.util.List<java.lang.String>\n"
" get$capitalized_name$List();\n");
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
@@ -612,30 +636,37 @@ GenerateInterfaceMembers(io::Printer* printer) const {
void RepeatedImmutableStringFieldLiteGenerator::
GenerateMembers(io::Printer* printer) const {
printer->Print(variables_,
- "private com.google.protobuf.Internal.ProtobufList<String> $name$_;\n");
+ "private com.google.protobuf.Internal.ProtobufList<java.lang.String> "
+ "$name$_;\n");
PrintExtraFieldInfo(variables_, printer);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public java.util.List<String> get$capitalized_name$List() {\n"
- " return $name$_;\n" // note: unmodifiable list
+ "$deprecation$public java.util.List<java.lang.String> "
+ "${$get$capitalized_name$List$}$() {\n"
+ " return $name$_;\n" // note: unmodifiable list
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public int get$capitalized_name$Count() {\n"
+ "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n"
" return $name$_.size();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public java.lang.String get$capitalized_name$(int index) {\n"
+ "$deprecation$public java.lang.String "
+ "${$get$capitalized_name$$}$(int index) {\n"
" return $name$_.get(index);\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public com.google.protobuf.ByteString\n"
- " get$capitalized_name$Bytes(int index) {\n"
+ " ${$get$capitalized_name$Bytes$}$(int index) {\n"
" return com.google.protobuf.ByteString.copyFromUtf8(\n"
" $name$_.get(index));\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
printer->Print(variables_,
"private void ensure$capitalized_name$IsMutable() {\n"
@@ -694,67 +725,77 @@ void RepeatedImmutableStringFieldLiteGenerator::
GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public java.util.List<String>\n"
- " get$capitalized_name$List() {\n"
+ "$deprecation$public java.util.List<java.lang.String>\n"
+ " ${$get$capitalized_name$List$}$() {\n"
" return java.util.Collections.unmodifiableList(\n"
" instance.get$capitalized_name$List());\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public int get$capitalized_name$Count() {\n"
+ "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n"
" return instance.get$capitalized_name$Count();\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public java.lang.String get$capitalized_name$(int index) {\n"
+ "$deprecation$public java.lang.String "
+ "${$get$capitalized_name$$}$(int index) {\n"
" return instance.get$capitalized_name$(index);\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public com.google.protobuf.ByteString\n"
- " get$capitalized_name$Bytes(int index) {\n"
+ " ${$get$capitalized_name$Bytes$}$(int index) {\n"
" return instance.get$capitalized_name$Bytes(index);\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder set$capitalized_name$(\n"
+ "$deprecation$public Builder ${$set$capitalized_name$$}$(\n"
" int index, java.lang.String value) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$(index, value);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder add$capitalized_name$(\n"
+ "$deprecation$public Builder ${$add$capitalized_name$$}$(\n"
" java.lang.String value) {\n"
" copyOnWrite();\n"
" instance.add$capitalized_name$(value);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder addAll$capitalized_name$(\n"
+ "$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n"
" java.lang.Iterable<java.lang.String> values) {\n"
" copyOnWrite();\n"
" instance.addAll$capitalized_name$(values);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder clear$capitalized_name$() {\n"
+ "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" copyOnWrite();\n"
" instance.clear$capitalized_name$();\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
- "$deprecation$public Builder add$capitalized_name$Bytes(\n"
+ "$deprecation$public Builder ${$add$capitalized_name$Bytes$}$(\n"
" com.google.protobuf.ByteString value) {\n"
" copyOnWrite();\n"
" instance.add$capitalized_name$Bytes(value);\n"
" return this;\n"
"}\n");
+ printer->Annotate("{", "}", descriptor_);
}
void RepeatedImmutableStringFieldLiteGenerator::
@@ -762,6 +803,7 @@ GenerateFieldBuilderInitializationCode(io::Printer* printer) const {
// noop for strings
}
+
void RepeatedImmutableStringFieldLiteGenerator::
GenerateInitializationCode(io::Printer* printer) const {
printer->Print(variables_, "$name$_ = $empty_list$;\n");
@@ -783,14 +825,14 @@ void RepeatedImmutableStringFieldLiteGenerator::
GenerateParsingCode(io::Printer* printer) const {
if (CheckUtf8(descriptor_)) {
printer->Print(variables_,
- "String s = input.readStringRequireUtf8();\n");
+ "java.lang.String s = input.readStringRequireUtf8();\n");
} else {
// Lite runtime should attempt to reduce allocations by attempting to
// construct the string directly from the input stream buffer. This avoids
// spurious intermediary ByteString allocations, cutting overall allocations
// in half.
printer->Print(variables_,
- "String s = input.readString();\n");
+ "java.lang.String s = input.readString();\n");
}
printer->Print(variables_,
"if (!$is_mutable$) {\n"
@@ -864,7 +906,7 @@ GenerateHashCode(io::Printer* printer) const {
}
string RepeatedImmutableStringFieldLiteGenerator::GetBoxedType() const {
- return "String";
+ return "java.lang.String";
}
} // namespace java
diff --git a/src/google/protobuf/compiler/java/java_string_field_lite.h b/src/google/protobuf/compiler/java/java_string_field_lite.h
index 80496c87..b7fb6409 100644
--- a/src/google/protobuf/compiler/java/java_string_field_lite.h
+++ b/src/google/protobuf/compiler/java/java_string_field_lite.h
@@ -78,6 +78,7 @@ class ImmutableStringFieldLiteGenerator : public ImmutableFieldLiteGenerator {
void GenerateEqualsCode(io::Printer* printer) const;
void GenerateHashCode(io::Printer* printer) const;
+
string GetBoxedType() const;
protected:
@@ -108,6 +109,7 @@ class ImmutableStringOneofFieldLiteGenerator
void GenerateSerializationCode(io::Printer* printer) const;
void GenerateSerializedSizeCode(io::Printer* printer) const;
+
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableStringOneofFieldLiteGenerator);
};
@@ -136,6 +138,7 @@ class RepeatedImmutableStringFieldLiteGenerator
void GenerateEqualsCode(io::Printer* printer) const;
void GenerateHashCode(io::Printer* printer) const;
+
string GetBoxedType() const;
private:
diff --git a/src/google/protobuf/compiler/javanano/javanano_enum_field.cc b/src/google/protobuf/compiler/javanano/javanano_enum_field.cc
index 7666db38..26bc7f85 100644
--- a/src/google/protobuf/compiler/javanano/javanano_enum_field.cc
+++ b/src/google/protobuf/compiler/javanano/javanano_enum_field.cc
@@ -52,7 +52,7 @@ namespace {
// TODO(kenton): Factor out a "SetCommonFieldVariables()" to get rid of
// repeat code between this and the other field types.
void SetEnumVariables(const Params& params,
- const FieldDescriptor* descriptor, map<string, string>* variables) {
+ const FieldDescriptor* descriptor, std::map<string, string>* variables) {
(*variables)["name"] =
RenameJavaKeywords(UnderscoresToCamelCase(descriptor));
(*variables)["capitalized_name"] =
diff --git a/src/google/protobuf/compiler/javanano/javanano_enum_field.h b/src/google/protobuf/compiler/javanano/javanano_enum_field.h
index b94790d6..1be25d10 100644
--- a/src/google/protobuf/compiler/javanano/javanano_enum_field.h
+++ b/src/google/protobuf/compiler/javanano/javanano_enum_field.h
@@ -62,7 +62,7 @@ class EnumFieldGenerator : public FieldGenerator {
private:
const FieldDescriptor* descriptor_;
- map<string, string> variables_;
+ std::map<string, string> variables_;
vector<string> canonical_values_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumFieldGenerator);
@@ -85,7 +85,7 @@ class AccessorEnumFieldGenerator : public FieldGenerator {
private:
const FieldDescriptor* descriptor_;
- map<string, string> variables_;
+ std::map<string, string> variables_;
vector<string> canonical_values_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(AccessorEnumFieldGenerator);
@@ -112,7 +112,7 @@ class RepeatedEnumFieldGenerator : public FieldGenerator {
void GenerateRepeatedDataSizeCode(io::Printer* printer) const;
const FieldDescriptor* descriptor_;
- map<string, string> variables_;
+ std::map<string, string> variables_;
vector<string> canonical_values_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedEnumFieldGenerator);
diff --git a/src/google/protobuf/compiler/javanano/javanano_extension.cc b/src/google/protobuf/compiler/javanano/javanano_extension.cc
index 0b9d1d8d..4c61f915 100644
--- a/src/google/protobuf/compiler/javanano/javanano_extension.cc
+++ b/src/google/protobuf/compiler/javanano/javanano_extension.cc
@@ -78,7 +78,7 @@ const char* GetTypeConstantName(const FieldDescriptor::Type type) {
} // namespace
void SetVariables(const FieldDescriptor* descriptor, const Params params,
- map<string, string>* variables) {
+ std::map<string, string>* variables) {
(*variables)["extends"] = ClassName(params, descriptor->containing_type());
(*variables)["name"] = RenameJavaKeywords(UnderscoresToCamelCase(descriptor));
bool repeated = descriptor->is_repeated();
diff --git a/src/google/protobuf/compiler/javanano/javanano_extension.h b/src/google/protobuf/compiler/javanano/javanano_extension.h
index 4843e296..f4e9eb2d 100644
--- a/src/google/protobuf/compiler/javanano/javanano_extension.h
+++ b/src/google/protobuf/compiler/javanano/javanano_extension.h
@@ -61,7 +61,7 @@ class ExtensionGenerator {
private:
const Params& params_;
const FieldDescriptor* descriptor_;
- map<string, string> variables_;
+ std::map<string, string> variables_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ExtensionGenerator);
};
diff --git a/src/google/protobuf/compiler/javanano/javanano_field.cc b/src/google/protobuf/compiler/javanano/javanano_field.cc
index 85257f3f..e31d1177 100644
--- a/src/google/protobuf/compiler/javanano/javanano_field.cc
+++ b/src/google/protobuf/compiler/javanano/javanano_field.cc
@@ -151,7 +151,7 @@ const FieldGenerator& FieldGeneratorMap::get(
}
void SetCommonOneofVariables(const FieldDescriptor* descriptor,
- map<string, string>* variables) {
+ std::map<string, string>* variables) {
(*variables)["oneof_name"] =
UnderscoresToCamelCase(descriptor->containing_oneof());
(*variables)["oneof_capitalized_name"] =
@@ -169,7 +169,7 @@ void SetCommonOneofVariables(const FieldDescriptor* descriptor,
}
void GenerateOneofFieldEquals(const FieldDescriptor* descriptor,
- const map<string, string>& variables,
+ const std::map<string, string>& variables,
io::Printer* printer) {
if (GetJavaType(descriptor) == JAVATYPE_BYTES) {
printer->Print(variables,
@@ -190,7 +190,7 @@ void GenerateOneofFieldEquals(const FieldDescriptor* descriptor,
}
void GenerateOneofFieldHashCode(const FieldDescriptor* descriptor,
- const map<string, string>& variables,
+ const std::map<string, string>& variables,
io::Printer* printer) {
if (GetJavaType(descriptor) == JAVATYPE_BYTES) {
printer->Print(variables,
diff --git a/src/google/protobuf/compiler/javanano/javanano_field.h b/src/google/protobuf/compiler/javanano/javanano_field.h
index 57c221f4..347c888c 100644
--- a/src/google/protobuf/compiler/javanano/javanano_field.h
+++ b/src/google/protobuf/compiler/javanano/javanano_field.h
@@ -114,12 +114,12 @@ class FieldGeneratorMap {
};
void SetCommonOneofVariables(const FieldDescriptor* descriptor,
- map<string, string>* variables);
+ std::map<string, string>* variables);
void GenerateOneofFieldEquals(const FieldDescriptor* descriptor,
- const map<string, string>& variables,
+ const std::map<string, string>& variables,
io::Printer* printer);
void GenerateOneofFieldHashCode(const FieldDescriptor* descriptor,
- const map<string, string>& variables,
+ const std::map<string, string>& variables,
io::Printer* printer);
} // namespace javanano
diff --git a/src/google/protobuf/compiler/javanano/javanano_file.cc b/src/google/protobuf/compiler/javanano/javanano_file.cc
index 3676ab9d..17f7386e 100644
--- a/src/google/protobuf/compiler/javanano/javanano_file.cc
+++ b/src/google/protobuf/compiler/javanano/javanano_file.cc
@@ -120,12 +120,12 @@ bool FileGenerator::Validate(string* error) {
if (!params_.has_java_outer_classname(file_->name())
&& file_->message_type_count() == 1
&& file_->enum_type_count() == 0 && file_->extension_count() == 0) {
- cout << "INFO: " << file_->name() << ":" << endl;
- cout << "Javanano generator has changed to align with java generator. "
+ std::cout << "INFO: " << file_->name() << ":" << std::endl;
+ std::cout << "Javanano generator has changed to align with java generator. "
"An outer class will be created for this file and the single message "
"in the file will become a nested class. Use java_multiple_files to "
"skip generating the outer class, or set an explicit "
- "java_outer_classname to suppress this message." << endl;
+ "java_outer_classname to suppress this message." << std::endl;
}
// Check that no class name matches the file's class name. This is a common
diff --git a/src/google/protobuf/compiler/javanano/javanano_helpers.cc b/src/google/protobuf/compiler/javanano/javanano_helpers.cc
index 02811a24..1927ba12 100644
--- a/src/google/protobuf/compiler/javanano/javanano_helpers.cc
+++ b/src/google/protobuf/compiler/javanano/javanano_helpers.cc
@@ -428,9 +428,9 @@ string DefaultValue(const Params& params, const FieldDescriptor* field) {
"L";
case FieldDescriptor::CPPTYPE_DOUBLE: {
double value = field->default_value_double();
- if (value == numeric_limits<double>::infinity()) {
+ if (value == std::numeric_limits<double>::infinity()) {
return "Double.POSITIVE_INFINITY";
- } else if (value == -numeric_limits<double>::infinity()) {
+ } else if (value == -std::numeric_limits<double>::infinity()) {
return "Double.NEGATIVE_INFINITY";
} else if (value != value) {
return "Double.NaN";
@@ -440,9 +440,9 @@ string DefaultValue(const Params& params, const FieldDescriptor* field) {
}
case FieldDescriptor::CPPTYPE_FLOAT: {
float value = field->default_value_float();
- if (value == numeric_limits<float>::infinity()) {
+ if (value == std::numeric_limits<float>::infinity()) {
return "Float.POSITIVE_INFINITY";
- } else if (value == -numeric_limits<float>::infinity()) {
+ } else if (value == -std::numeric_limits<float>::infinity()) {
return "Float.NEGATIVE_INFINITY";
} else if (value != value) {
return "Float.NaN";
@@ -567,7 +567,7 @@ string GenerateDifferentBit(int bit_index) {
}
void SetBitOperationVariables(const string name,
- int bitIndex, map<string, string>* variables) {
+ int bitIndex, std::map<string, string>* variables) {
(*variables)["get_" + name] = GenerateGetBit(bitIndex);
(*variables)["set_" + name] = GenerateSetBit(bitIndex);
(*variables)["clear_" + name] = GenerateClearBit(bitIndex);
diff --git a/src/google/protobuf/compiler/javanano/javanano_helpers.h b/src/google/protobuf/compiler/javanano/javanano_helpers.h
index 014c85ae..04b2d633 100644
--- a/src/google/protobuf/compiler/javanano/javanano_helpers.h
+++ b/src/google/protobuf/compiler/javanano/javanano_helpers.h
@@ -181,7 +181,7 @@ string GenerateDifferentBit(int bit_index);
// the given name of the bit, to the appropriate Java expressions for the given
// bit index.
void SetBitOperationVariables(const string name,
- int bitIndex, map<string, string>* variables);
+ int bitIndex, std::map<string, string>* variables);
inline bool IsMapEntry(const Descriptor* descriptor) {
// TODO(liujisi): Add an option to turn on maps for proto2 syntax as well.
diff --git a/src/google/protobuf/compiler/javanano/javanano_map_field.cc b/src/google/protobuf/compiler/javanano/javanano_map_field.cc
index 83b2b0ce..a4ab8858 100644
--- a/src/google/protobuf/compiler/javanano/javanano_map_field.cc
+++ b/src/google/protobuf/compiler/javanano/javanano_map_field.cc
@@ -84,7 +84,7 @@ const FieldDescriptor* ValueField(const FieldDescriptor* descriptor) {
}
void SetMapVariables(const Params& params,
- const FieldDescriptor* descriptor, map<string, string>* variables) {
+ const FieldDescriptor* descriptor, std::map<string, string>* variables) {
const FieldDescriptor* key = KeyField(descriptor);
const FieldDescriptor* value = ValueField(descriptor);
(*variables)["name"] =
diff --git a/src/google/protobuf/compiler/javanano/javanano_map_field.h b/src/google/protobuf/compiler/javanano/javanano_map_field.h
index c01bde38..81e5915d 100644
--- a/src/google/protobuf/compiler/javanano/javanano_map_field.h
+++ b/src/google/protobuf/compiler/javanano/javanano_map_field.h
@@ -58,7 +58,7 @@ class MapFieldGenerator : public FieldGenerator {
private:
const FieldDescriptor* descriptor_;
- map<string, string> variables_;
+ std::map<string, string> variables_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapFieldGenerator);
};
diff --git a/src/google/protobuf/compiler/javanano/javanano_message.cc b/src/google/protobuf/compiler/javanano/javanano_message.cc
index a41da5ae..78421887 100644
--- a/src/google/protobuf/compiler/javanano/javanano_message.cc
+++ b/src/google/protobuf/compiler/javanano/javanano_message.cc
@@ -69,7 +69,7 @@ const FieldDescriptor** SortFieldsByNumber(const Descriptor* descriptor) {
for (int i = 0; i < descriptor->field_count(); i++) {
fields[i] = descriptor->field(i);
}
- sort(fields, fields + descriptor->field_count(),
+ std::sort(fields, fields + descriptor->field_count(),
FieldOrderingByNumber());
return fields;
}
@@ -182,7 +182,7 @@ void MessageGenerator::Generate(io::Printer* printer) {
}
// oneof
- map<string, string> vars;
+ std::map<string, string> vars;
vars["message_name"] = descriptor_->name();
for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
const OneofDescriptor* oneof_desc = descriptor_->oneof_decl(i);
diff --git a/src/google/protobuf/compiler/javanano/javanano_message_field.cc b/src/google/protobuf/compiler/javanano/javanano_message_field.cc
index d1d04b52..2ed8a3aa 100644
--- a/src/google/protobuf/compiler/javanano/javanano_message_field.cc
+++ b/src/google/protobuf/compiler/javanano/javanano_message_field.cc
@@ -54,7 +54,7 @@ namespace {
// TODO(kenton): Factor out a "SetCommonFieldVariables()" to get rid of
// repeat code between this and the other field types.
void SetMessageVariables(const Params& params,
- const FieldDescriptor* descriptor, map<string, string>* variables) {
+ const FieldDescriptor* descriptor, std::map<string, string>* variables) {
(*variables)["name"] =
RenameJavaKeywords(UnderscoresToCamelCase(descriptor));
(*variables)["capitalized_name"] =
diff --git a/src/google/protobuf/compiler/javanano/javanano_message_field.h b/src/google/protobuf/compiler/javanano/javanano_message_field.h
index e074735c..0ae8879b 100644
--- a/src/google/protobuf/compiler/javanano/javanano_message_field.h
+++ b/src/google/protobuf/compiler/javanano/javanano_message_field.h
@@ -62,7 +62,7 @@ class MessageFieldGenerator : public FieldGenerator {
private:
const FieldDescriptor* descriptor_;
- map<string, string> variables_;
+ std::map<string, string> variables_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageFieldGenerator);
};
@@ -85,7 +85,7 @@ class MessageOneofFieldGenerator : public FieldGenerator {
private:
const FieldDescriptor* descriptor_;
- map<string, string> variables_;
+ std::map<string, string> variables_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageOneofFieldGenerator);
};
@@ -108,7 +108,7 @@ class RepeatedMessageFieldGenerator : public FieldGenerator {
private:
const FieldDescriptor* descriptor_;
- map<string, string> variables_;
+ std::map<string, string> variables_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedMessageFieldGenerator);
};
diff --git a/src/google/protobuf/compiler/javanano/javanano_params.h b/src/google/protobuf/compiler/javanano/javanano_params.h
index e3b4bb93..3594767d 100644
--- a/src/google/protobuf/compiler/javanano/javanano_params.h
+++ b/src/google/protobuf/compiler/javanano/javanano_params.h
@@ -47,8 +47,8 @@ enum eMultipleFiles { JAVANANO_MUL_UNSET, JAVANANO_MUL_FALSE, JAVANANO_MUL_TRUE
// Parameters for used by the generators
class Params {
public:
- typedef map<string, string> NameMap;
- typedef set<string> NameSet;
+ typedef std::map<string, string> NameMap;
+ typedef std::set<string> NameSet;
private:
string empty_;
string base_name_;
diff --git a/src/google/protobuf/compiler/javanano/javanano_primitive_field.cc b/src/google/protobuf/compiler/javanano/javanano_primitive_field.cc
index 978abf2c..66a0ff05 100644
--- a/src/google/protobuf/compiler/javanano/javanano_primitive_field.cc
+++ b/src/google/protobuf/compiler/javanano/javanano_primitive_field.cc
@@ -166,7 +166,7 @@ bool AllAscii(const string& text) {
void SetPrimitiveVariables(const FieldDescriptor* descriptor, const Params params,
- map<string, string>* variables) {
+ std::map<string, string>* variables) {
(*variables)["name"] =
RenameJavaKeywords(UnderscoresToCamelCase(descriptor));
(*variables)["capitalized_name"] =
diff --git a/src/google/protobuf/compiler/javanano/javanano_primitive_field.h b/src/google/protobuf/compiler/javanano/javanano_primitive_field.h
index a01981dd..d7d72d57 100644
--- a/src/google/protobuf/compiler/javanano/javanano_primitive_field.h
+++ b/src/google/protobuf/compiler/javanano/javanano_primitive_field.h
@@ -65,7 +65,7 @@ class PrimitiveFieldGenerator : public FieldGenerator {
void GenerateSerializationConditional(io::Printer* printer) const;
const FieldDescriptor* descriptor_;
- map<string, string> variables_;
+ std::map<string, string> variables_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(PrimitiveFieldGenerator);
};
@@ -89,7 +89,7 @@ class AccessorPrimitiveFieldGenerator : public FieldGenerator {
private:
const FieldDescriptor* descriptor_;
- map<string, string> variables_;
+ std::map<string, string> variables_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(AccessorPrimitiveFieldGenerator);
};
@@ -111,7 +111,7 @@ class PrimitiveOneofFieldGenerator : public FieldGenerator {
private:
const FieldDescriptor* descriptor_;
- map<string, string> variables_;
+ std::map<string, string> variables_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(PrimitiveOneofFieldGenerator);
};
@@ -137,7 +137,7 @@ class RepeatedPrimitiveFieldGenerator : public FieldGenerator {
void GenerateRepeatedDataSizeCode(io::Printer* printer) const;
const FieldDescriptor* descriptor_;
- map<string, string> variables_;
+ std::map<string, string> variables_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedPrimitiveFieldGenerator);
};
diff --git a/src/google/protobuf/compiler/js/embed.cc b/src/google/protobuf/compiler/js/embed.cc
index be2ffdd4..a725b62e 100644
--- a/src/google/protobuf/compiler/js/embed.cc
+++ b/src/google/protobuf/compiler/js/embed.cc
@@ -48,7 +48,8 @@ static char ToDecimalDigit(int num) {
static std::string CEscape(const std::string& str) {
std::string dest;
- for (unsigned char ch : str) {
+ for (size_t i = 0; i < str.size(); ++i) {
+ unsigned char ch = str[i];
switch (ch) {
case '\n': dest += "\\n"; break;
case '\r': dest += "\\r"; break;
@@ -96,18 +97,16 @@ static void AddFile(const char* name, std::basic_ostream<char>* out) {
}
int main(int argc, char *argv[]) {
- auto& out = std::cout;
-
- out << "#include "
- "\"google/protobuf/compiler/js/well_known_types_embed.h\"\n";
- out << "struct FileToc well_known_types_js[] = {\n";
+ std::cout << "#include "
+ "\"google/protobuf/compiler/js/well_known_types_embed.h\"\n";
+ std::cout << "struct FileToc well_known_types_js[] = {\n";
for (int i = 1; i < argc; i++) {
- AddFile(argv[i], &out);
+ AddFile(argv[i], &std::cout);
}
- out << " {NULL, NULL} // Terminate the list.\n";
- out << "};\n";
+ std::cout << " {NULL, NULL} // Terminate the list.\n";
+ std::cout << "};\n";
return EXIT_SUCCESS;
}
diff --git a/src/google/protobuf/compiler/js/js_generator.cc b/src/google/protobuf/compiler/js/js_generator.cc
index e6571f6f..16fe19ad 100755
--- a/src/google/protobuf/compiler/js/js_generator.cc
+++ b/src/google/protobuf/compiler/js/js_generator.cc
@@ -143,12 +143,16 @@ bool IsReserved(const string& ident) {
return false;
}
+bool StrEndsWith(StringPiece sp, StringPiece x) {
+ return sp.size() >= x.size() && sp.substr(sp.size() - x.size()) == x;
+}
+
// Returns a copy of |filename| with any trailing ".protodevel" or ".proto
// suffix stripped.
// TODO(haberman): Unify with copy in compiler/cpp/internal/helpers.cc.
string StripProto(const string& filename) {
- const char* suffix = HasSuffixString(filename, ".protodevel")
- ? ".protodevel" : ".proto";
+ const char* suffix =
+ StrEndsWith(filename, ".protodevel") ? ".protodevel" : ".proto";
return StripSuffixString(filename, suffix);
}
@@ -193,13 +197,14 @@ string ModuleAlias(const string& filename) {
string basename = StripProto(filename);
StripString(&basename, "-", '$');
StripString(&basename, "/", '_');
+ StripString(&basename, ".", '_');
return basename + "_pb";
}
// Returns the fully normalized JavaScript path for the given
// file descriptor's package.
-string GetPath(const GeneratorOptions& options,
- const FileDescriptor* file) {
+string GetFilePath(const GeneratorOptions& options,
+ const FileDescriptor* file) {
if (!options.namespace_prefix.empty()) {
return options.namespace_prefix;
} else if (!file->package().empty()) {
@@ -231,49 +236,43 @@ string GetNestedMessageName(const Descriptor* descriptor) {
string GetPrefix(const GeneratorOptions& options,
const FileDescriptor* file_descriptor,
const Descriptor* containing_type) {
- string prefix =
- GetPath(options, file_descriptor) + GetNestedMessageName(containing_type);
+ string prefix = GetFilePath(options, file_descriptor) +
+ GetNestedMessageName(containing_type);
if (!prefix.empty()) {
prefix += ".";
}
return prefix;
}
-
-// Returns the fully normalized JavaScript path for the given
+// Returns the fully normalized JavaScript path prefix for the given
// message descriptor.
-string GetPath(const GeneratorOptions& options,
- const Descriptor* descriptor) {
+string GetMessagePathPrefix(const GeneratorOptions& options,
+ const Descriptor* descriptor) {
return GetPrefix(
options, descriptor->file(),
- descriptor->containing_type()) + descriptor->name();
+ descriptor->containing_type());
}
-
// Returns the fully normalized JavaScript path for the given
-// field's containing message descriptor.
-string GetPath(const GeneratorOptions& options,
- const FieldDescriptor* descriptor) {
- return GetPath(options, descriptor->containing_type());
+// message descriptor.
+string GetMessagePath(const GeneratorOptions& options,
+ const Descriptor* descriptor) {
+ return GetMessagePathPrefix(options, descriptor) + descriptor->name();
}
-// Returns the fully normalized JavaScript path for the given
+// Returns the fully normalized JavaScript path prefix for the given
// enumeration descriptor.
-string GetPath(const GeneratorOptions& options,
- const EnumDescriptor* enum_descriptor) {
- return GetPrefix(
- options, enum_descriptor->file(),
- enum_descriptor->containing_type()) + enum_descriptor->name();
+string GetEnumPathPrefix(const GeneratorOptions& options,
+ const EnumDescriptor* enum_descriptor) {
+ return GetPrefix(options, enum_descriptor->file(),
+ enum_descriptor->containing_type());
}
-
// Returns the fully normalized JavaScript path for the given
-// enumeration value descriptor.
-string GetPath(const GeneratorOptions& options,
- const EnumValueDescriptor* value_descriptor) {
- return GetPath(
- options,
- value_descriptor->type()) + "." + value_descriptor->name();
+// enumeration descriptor.
+string GetEnumPath(const GeneratorOptions& options,
+ const EnumDescriptor* enum_descriptor) {
+ return GetEnumPathPrefix(options, enum_descriptor) + enum_descriptor->name();
}
string MaybeCrossFileRef(const GeneratorOptions& options,
@@ -288,7 +287,7 @@ string MaybeCrossFileRef(const GeneratorOptions& options,
to_message->name();
} else {
// Within a single file we use a full name.
- return GetPath(options, to_message);
+ return GetMessagePath(options, to_message);
}
}
@@ -413,7 +412,7 @@ string ToFileName(const string& input) {
// that top-level extensions should go in.
string GetExtensionFileName(const GeneratorOptions& options,
const FileDescriptor* file) {
- return options.output_dir + "/" + ToFileName(GetPath(options, file)) +
+ return options.output_dir + "/" + ToFileName(GetFilePath(options, file)) +
options.GetFileNameExtension();
}
@@ -550,14 +549,6 @@ string JSGetterName(const GeneratorOptions& options,
return name;
}
-string JSMapGetterName(const GeneratorOptions& options,
- const FieldDescriptor* field) {
- return JSIdent(options, field,
- /* is_upper_camel = */ true,
- /* is_map = */ true,
- /* drop_list = */ false);
-}
-
string JSOneofName(const OneofDescriptor* oneof) {
@@ -783,8 +774,22 @@ string DoubleToString(double value) {
return PostProcessFloat(result);
}
+// Return true if this is an integral field that should be represented as string
+// in JS.
+bool IsIntegralFieldWithStringJSType(const FieldDescriptor* field) {
+ switch (field->cpp_type()) {
+ case FieldDescriptor::CPPTYPE_INT64:
+ case FieldDescriptor::CPPTYPE_UINT64:
+ // The default value of JSType is JS_NORMAL, which behaves the same as
+ // JS_NUMBER.
+ return field->options().jstype() == google::protobuf::FieldOptions::JS_STRING;
+ default:
+ return false;
+ }
+}
+
string MaybeNumberString(const FieldDescriptor* field, const string& orig) {
- return orig;
+ return IsIntegralFieldWithStringJSType(field) ? ("\"" + orig + "\"") : orig;
}
string JSFieldDefault(const FieldDescriptor* field) {
@@ -872,18 +877,18 @@ string ProtoTypeName(const GeneratorOptions& options,
case FieldDescriptor::TYPE_BYTES:
return "bytes";
case FieldDescriptor::TYPE_GROUP:
- return GetPath(options, field->message_type());
+ return GetMessagePath(options, field->message_type());
case FieldDescriptor::TYPE_ENUM:
- return GetPath(options, field->enum_type());
+ return GetEnumPath(options, field->enum_type());
case FieldDescriptor::TYPE_MESSAGE:
- return GetPath(options, field->message_type());
+ return GetMessagePath(options, field->message_type());
default:
return "";
}
}
string JSIntegerTypeName(const FieldDescriptor* field) {
- return "number";
+ return IsIntegralFieldWithStringJSType(field) ? "string" : "number";
}
string JSStringTypeName(const GeneratorOptions& options,
@@ -925,9 +930,9 @@ string JSTypeName(const GeneratorOptions& options,
case FieldDescriptor::CPPTYPE_STRING:
return JSStringTypeName(options, field, bytes_mode);
case FieldDescriptor::CPPTYPE_ENUM:
- return GetPath(options, field->enum_type());
+ return GetEnumPath(options, field->enum_type());
case FieldDescriptor::CPPTYPE_MESSAGE:
- return GetPath(options, field->message_type());
+ return GetMessagePath(options, field->message_type());
default:
return "";
}
@@ -1060,8 +1065,7 @@ string JSBinaryReaderMethodType(const FieldDescriptor* field) {
if (name[0] >= 'a' && name[0] <= 'z') {
name[0] = (name[0] - 'a') + 'A';
}
-
- return name;
+ return IsIntegralFieldWithStringJSType(field) ? (name + "String") : name;
}
string JSBinaryReadWriteMethodName(const FieldDescriptor* field,
@@ -1091,6 +1095,40 @@ string JSReturnClause(const FieldDescriptor* desc) {
return "";
}
+string JSTypeTag(const FieldDescriptor* desc) {
+ switch (desc->type()) {
+ case FieldDescriptor::TYPE_DOUBLE:
+ case FieldDescriptor::TYPE_FLOAT:
+ return "Float";
+ case FieldDescriptor::TYPE_INT32:
+ case FieldDescriptor::TYPE_UINT32:
+ case FieldDescriptor::TYPE_INT64:
+ case FieldDescriptor::TYPE_UINT64:
+ case FieldDescriptor::TYPE_FIXED32:
+ case FieldDescriptor::TYPE_FIXED64:
+ case FieldDescriptor::TYPE_SINT32:
+ case FieldDescriptor::TYPE_SINT64:
+ case FieldDescriptor::TYPE_SFIXED32:
+ case FieldDescriptor::TYPE_SFIXED64:
+ if (IsIntegralFieldWithStringJSType(desc)) {
+ return "StringInt";
+ } else {
+ return "Int";
+ }
+ case FieldDescriptor::TYPE_BOOL:
+ return "Boolean";
+ case FieldDescriptor::TYPE_STRING:
+ return "String";
+ case FieldDescriptor::TYPE_BYTES:
+ return "Bytes";
+ case FieldDescriptor::TYPE_ENUM:
+ return "Enum";
+ default:
+ assert(false);
+ }
+ return "";
+}
+
string JSReturnDoc(const GeneratorOptions& options,
const FieldDescriptor* desc) {
return "";
@@ -1111,7 +1149,7 @@ static const char* kRepeatedFieldArrayName = ".repeatedFields_";
string RepeatedFieldsArrayName(const GeneratorOptions& options,
const Descriptor* desc) {
return HasRepeatedFields(options, desc)
- ? (GetPath(options, desc) + kRepeatedFieldArrayName)
+ ? (GetMessagePath(options, desc) + kRepeatedFieldArrayName)
: "null";
}
@@ -1128,8 +1166,9 @@ static const char* kOneofGroupArrayName = ".oneofGroups_";
string OneofFieldsArrayName(const GeneratorOptions& options,
const Descriptor* desc) {
- return HasOneofFields(desc) ?
- (GetPath(options, desc) + kOneofGroupArrayName) : "null";
+ return HasOneofFields(desc)
+ ? (GetMessagePath(options, desc) + kOneofGroupArrayName)
+ : "null";
}
string RepeatedFieldNumberList(const GeneratorOptions& options,
@@ -1270,13 +1309,6 @@ string FieldComments(const FieldDescriptor* field, BytesMode bytes_mode) {
" * You should avoid comparisons like {@code val === true/false} in "
"those cases.\n";
}
- if (field->is_repeated()) {
- comments +=
- " * If you change this array by adding, removing or replacing "
- "elements, or if you\n"
- " * replace the array itself, then you must call the setter to "
- "update it.\n";
- }
if (field->type() == FieldDescriptor::TYPE_BYTES && bytes_mode == BYTES_U8) {
comments +=
" * Note that Uint8Array is not supported on all browsers.\n"
@@ -1349,7 +1381,7 @@ bool IsExtendable(const Descriptor* desc) {
// Returns the max index in the underlying data storage array beyond which the
// extension object is used.
string GetPivot(const Descriptor* desc) {
- static const int kDefaultPivot = (1 << 29); // max field number (29 bits)
+ static const int kDefaultPivot = 500;
// Find the max field number
int max_field_number = 0;
@@ -1361,7 +1393,7 @@ string GetPivot(const Descriptor* desc) {
}
int pivot = -1;
- if (IsExtendable(desc)) {
+ if (IsExtendable(desc) || (max_field_number >= kDefaultPivot)) {
pivot = ((max_field_number + 1) < kDefaultPivot) ?
(max_field_number + 1) : kDefaultPivot;
}
@@ -1533,6 +1565,10 @@ void Generator::GenerateHeader(const GeneratorOptions& options,
printer->Print("/**\n"
" * @fileoverview\n"
" * @enhanceable\n"
+ " * @suppress {messageConventions} JS Compiler reports an "
+ "error if a variable or\n"
+ " * field starts with 'MSG_' and isn't a translatable "
+ "message.\n"
" * @public\n"
" */\n"
"// GENERATED CODE -- DO NOT EDIT!\n"
@@ -1571,7 +1607,7 @@ void Generator::FindProvidesForMessage(
return;
}
- string name = GetPath(options, desc);
+ string name = GetMessagePath(options, desc);
provided->insert(name);
for (int i = 0; i < desc->enum_type_count(); i++) {
@@ -1588,7 +1624,7 @@ void Generator::FindProvidesForEnum(const GeneratorOptions& options,
io::Printer* printer,
const EnumDescriptor* enumdesc,
std::set<string>* provided) const {
- string name = GetPath(options, enumdesc);
+ string name = GetEnumPath(options, enumdesc);
provided->insert(name);
}
@@ -1604,9 +1640,8 @@ void Generator::FindProvidesForFields(
continue;
}
- string name =
- GetPath(options, field->file()) + "." +
- JSObjectFieldName(options, field);
+ string name = GetFilePath(options, field->file()) + "." +
+ JSObjectFieldName(options, field);
provided->insert(name);
}
}
@@ -1684,7 +1719,7 @@ void Generator::GenerateRequiresForLibrary(
}
if (extension->containing_type()->full_name() !=
"google.protobuf.bridge.MessageSet") {
- required.insert(GetPath(options, extension->containing_type()));
+ required.insert(GetMessagePath(options, extension->containing_type()));
}
FindRequiresForField(options, extension, &required, &forwards);
have_extensions = true;
@@ -1725,18 +1760,16 @@ void Generator::GenerateRequiresImpl(const GeneratorOptions& options,
bool require_jspb, bool require_extension,
bool require_map) const {
if (require_jspb) {
- printer->Print(
- "goog.require('jspb.Message');\n"
- "goog.require('jspb.BinaryReader');\n"
- "goog.require('jspb.BinaryWriter');\n");
+ required->insert("jspb.Message");
+ required->insert("jspb.BinaryReader");
+ required->insert("jspb.BinaryWriter");
}
if (require_extension) {
- printer->Print("goog.require('jspb.ExtensionFieldBinaryInfo');\n");
- printer->Print(
- "goog.require('jspb.ExtensionFieldInfo');\n");
+ required->insert("jspb.ExtensionFieldBinaryInfo");
+ required->insert("jspb.ExtensionFieldInfo");
}
if (require_map) {
- printer->Print("goog.require('jspb.Map');\n");
+ required->insert("jspb.Map");
}
std::set<string>::iterator it;
@@ -1805,13 +1838,13 @@ void Generator::FindRequiresForField(const GeneratorOptions& options,
// dependencies, as per original codegen.
!(field->is_extension() && field->extension_scope() == NULL)) {
if (options.add_require_for_enums) {
- required->insert(GetPath(options, field->enum_type()));
+ required->insert(GetEnumPath(options, field->enum_type()));
} else {
- forwards->insert(GetPath(options, field->enum_type()));
+ forwards->insert(GetEnumPath(options, field->enum_type()));
}
} else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
if (!IgnoreMessage(options, field->message_type())) {
- required->insert(GetPath(options, field->message_type()));
+ required->insert(GetMessagePath(options, field->message_type()));
}
}
}
@@ -1821,7 +1854,7 @@ void Generator::FindRequiresForExtension(const GeneratorOptions& options,
std::set<string>* required,
std::set<string>* forwards) const {
if (field->containing_type()->full_name() != "google.protobuf.bridge.MessageSet") {
- required->insert(GetPath(options, field->containing_type()));
+ required->insert(GetMessagePath(options, field->containing_type()));
}
FindRequiresForField(options, field, required, forwards);
}
@@ -1865,7 +1898,19 @@ void Generator::GenerateClass(const GeneratorOptions& options,
// objects.
GenerateClassDeserializeBinary(options, printer, desc);
GenerateClassSerializeBinary(options, printer, desc);
+ }
+ // Recurse on nested types. These must come *before* the extension-field
+ // info generation in GenerateClassRegistration so that extensions that
+ // reference nested types proceed the definitions of the nested types.
+ for (int i = 0; i < desc->enum_type_count(); i++) {
+ GenerateEnum(options, printer, desc->enum_type(i));
+ }
+ for (int i = 0; i < desc->nested_type_count(); i++) {
+ GenerateClass(options, printer, desc->nested_type(i));
+ }
+
+ if (!NamespaceOnly(desc)) {
GenerateClassRegistration(options, printer, desc);
GenerateClassFields(options, printer, desc);
if (IsExtendable(desc) && desc->full_name() != "google.protobuf.bridge.MessageSet") {
@@ -1878,14 +1923,6 @@ void Generator::GenerateClass(const GeneratorOptions& options,
}
}
}
-
- // Recurse on nested types.
- for (int i = 0; i < desc->enum_type_count(); i++) {
- GenerateEnum(options, printer, desc->enum_type(i));
- }
- for (int i = 0; i < desc->nested_type_count(); i++) {
- GenerateClass(options, printer, desc->nested_type(i));
- }
}
void Generator::GenerateClassConstructor(const GeneratorOptions& options,
@@ -1906,8 +1943,10 @@ void Generator::GenerateClassConstructor(const GeneratorOptions& options,
" * @extends {jspb.Message}\n"
" * @constructor\n"
" */\n"
- "$classname$ = function(opt_data) {\n",
- "classname", GetPath(options, desc));
+ "$classprefix$$classname$ = function(opt_data) {\n",
+ "classprefix", GetMessagePathPrefix(options, desc),
+ "classname", desc->name());
+ printer->Annotate("classname", desc);
string message_id = GetMessageId(desc);
printer->Print(
" jspb.Message.initialize(this, opt_data, $messageId$, $pivot$, "
@@ -1924,7 +1963,7 @@ void Generator::GenerateClassConstructor(const GeneratorOptions& options,
"if (goog.DEBUG && !COMPILED) {\n"
" $classname$.displayName = '$classname$';\n"
"}\n",
- "classname", GetPath(options, desc));
+ "classname", GetMessagePath(options, desc));
}
void Generator::GenerateClassFieldInfo(const GeneratorOptions& options,
@@ -1939,7 +1978,7 @@ void Generator::GenerateClassFieldInfo(const GeneratorOptions& options,
" */\n"
"$classname$$rptfieldarray$ = $rptfields$;\n"
"\n",
- "classname", GetPath(options, desc),
+ "classname", GetMessagePath(options, desc),
"rptfieldarray", kRepeatedFieldArrayName,
"rptfields", RepeatedFieldNumberList(options, desc));
}
@@ -1960,7 +1999,7 @@ void Generator::GenerateClassFieldInfo(const GeneratorOptions& options,
" */\n"
"$classname$$oneofgrouparray$ = $oneofgroups$;\n"
"\n",
- "classname", GetPath(options, desc),
+ "classname", GetMessagePath(options, desc),
"oneofgrouparray", kOneofGroupArrayName,
"oneofgroups", OneofGroupList(desc));
@@ -1980,7 +2019,7 @@ void Generator::GenerateClassXid(const GeneratorOptions& options,
"\n"
"\n"
"$class$.prototype.messageXid = xid('$class$');\n",
- "class", GetPath(options, desc));
+ "class", GetMessagePath(options, desc));
}
void Generator::GenerateOneofCaseDefinition(
@@ -1993,7 +2032,7 @@ void Generator::GenerateOneofCaseDefinition(
" */\n"
"$classname$.$oneof$Case = {\n"
" $upcase$_NOT_SET: 0",
- "classname", GetPath(options, oneof->containing_type()),
+ "classname", GetMessagePath(options, oneof->containing_type()),
"oneof", JSOneofName(oneof),
"upcase", ToEnumCase(oneof->name()));
@@ -2021,7 +2060,7 @@ void Generator::GenerateOneofCaseDefinition(
"computeOneofCase(this, $class$.oneofGroups_[$oneofindex$]));\n"
"};\n"
"\n",
- "class", GetPath(options, oneof->containing_type()),
+ "class", GetMessagePath(options, oneof->containing_type()),
"oneof", JSOneofName(oneof),
"oneofindex", JSOneofIndex(oneof));
}
@@ -2060,10 +2099,11 @@ void Generator::GenerateClassToObject(const GeneratorOptions& options,
" * http://goto/soy-param-migration\n"
" * @param {!$classname$} msg The msg instance to transform.\n"
" * @return {!Object}\n"
+ " * @suppress {unusedLocalVariables} f is only used for nested messages\n"
" */\n"
"$classname$.toObject = function(includeInstance, msg) {\n"
" var f, obj = {",
- "classname", GetPath(options, desc));
+ "classname", GetMessagePath(options, desc));
bool first = true;
for (int i = 0; i < desc->field_count(); i++) {
@@ -2095,7 +2135,7 @@ void Generator::GenerateClassToObject(const GeneratorOptions& options,
" $extObject$, $class$.prototype.getExtension,\n"
" includeInstance);\n",
"extObject", JSExtensionsObjectName(options, desc->file(), desc),
- "class", GetPath(options, desc));
+ "class", GetMessagePath(options, desc));
}
printer->Print(
@@ -2107,7 +2147,7 @@ void Generator::GenerateClassToObject(const GeneratorOptions& options,
"}\n"
"\n"
"\n",
- "classname", GetPath(options, desc));
+ "classname", GetMessagePath(options, desc));
}
void Generator::GenerateFieldValueExpression(io::Printer* printer,
@@ -2148,7 +2188,8 @@ void Generator::GenerateFieldValueExpression(io::Printer* printer,
"obj", obj_reference);
}
} else {
- printer->Print("jspb.Message.getField($obj$, $index$)",
+ printer->Print("jspb.Message.get$cardinality$Field($obj$, $index$)",
+ "cardinality", field->is_repeated() ? "Repeated" : "",
"index", JSFieldIndex(field),
"obj", obj_reference);
}
@@ -2168,7 +2209,7 @@ void Generator::GenerateClassFieldToObject(const GeneratorOptions& options,
string value_to_object;
if (value_field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
value_to_object =
- GetPath(options, value_field->message_type()) + ".toObject";
+ GetMessagePath(options, value_field->message_type()) + ".toObject";
} else {
value_to_object = "undefined";
}
@@ -2230,7 +2271,7 @@ void Generator::GenerateClassFromObject(const GeneratorOptions& options,
" */\n"
"$classname$.fromObject = function(obj) {\n"
" var f, msg = new $classname$();\n",
- "classname", GetPath(options, desc));
+ "classname", GetMessagePath(options, desc));
for (int i = 0; i < desc->field_count(); i++) {
const FieldDescriptor* field = desc->field(i);
@@ -2258,7 +2299,7 @@ void Generator::GenerateClassFieldFromObject(
"$fieldclass$.fromObject));\n",
"name", JSObjectFieldName(options, field),
"index", JSFieldIndex(field),
- "fieldclass", GetPath(options, value_field->message_type()));
+ "fieldclass", GetMessagePath(options, value_field->message_type()));
} else {
// `msg` is a newly-constructed message object that has not yet built any
// map containers wrapping underlying arrays, so we can simply directly
@@ -2349,14 +2390,13 @@ void GenerateBytesWrapper(const GeneratorOptions& options,
"fielddef", FieldDefinition(options, field),
"comment", FieldComments(field, bytes_mode),
"type", type,
- "class", GetPath(options, field->containing_type()),
+ "class", GetMessagePath(options, field->containing_type()),
"name", JSGetterName(options, field, bytes_mode),
"list", field->is_repeated() ? "List" : "",
"suffix", JSByteGetterSuffix(bytes_mode),
"defname", JSGetterName(options, field, BYTES_DEFAULT));
}
-
void Generator::GenerateClassField(const GeneratorOptions& options,
io::Printer* printer,
const FieldDescriptor* field) const {
@@ -2388,20 +2428,22 @@ void Generator::GenerateClassField(const GeneratorOptions& options,
"keytype", key_type,
"valuetype", value_type);
printer->Print(
- "$class$.prototype.get$name$ = function(opt_noLazyCreate) {\n"
+ "$class$.prototype.$gettername$ = function(opt_noLazyCreate) {\n"
" return /** @type {!jspb.Map<$keytype$,$valuetype$>} */ (\n",
- "class", GetPath(options, field->containing_type()),
- "name", JSGetterName(options, field),
+ "class", GetMessagePath(options, field->containing_type()),
+ "gettername", "get" + JSGetterName(options, field),
"keytype", key_type,
"valuetype", value_type);
+ printer->Annotate("gettername", field);
printer->Print(
" jspb.Message.getMapField(this, $index$, opt_noLazyCreate",
"index", JSFieldIndex(field));
if (value_field->type() == FieldDescriptor::TYPE_MESSAGE) {
- printer->Print(",\n"
+ printer->Print(
+ ",\n"
" $messageType$",
- "messageType", GetPath(options, value_field->message_type()));
+ "messageType", GetMessagePath(options, value_field->message_type()));
} else {
printer->Print(",\n"
" null");
@@ -2431,15 +2473,15 @@ void Generator::GenerateClassField(const GeneratorOptions& options,
/* force_present = */ false,
/* singular_if_not_packed = */ false));
printer->Print(
- "$class$.prototype.get$name$ = function() {\n"
+ "$class$.prototype.$gettername$ = function() {\n"
" return /** @type{$type$} */ (\n"
" jspb.Message.get$rpt$WrapperField(this, $wrapperclass$, "
"$index$$required$));\n"
"};\n"
"\n"
"\n",
- "class", GetPath(options, field->containing_type()),
- "name", JSGetterName(options, field),
+ "class", GetMessagePath(options, field->containing_type()),
+ "gettername", "get" + JSGetterName(options, field),
"type", JSFieldTypeAnnotation(options, field,
/* is_setter_argument = */ false,
/* force_present = */ false,
@@ -2449,9 +2491,10 @@ void Generator::GenerateClassField(const GeneratorOptions& options,
"wrapperclass", SubmessageTypeRef(options, field),
"required", (field->label() == FieldDescriptor::LABEL_REQUIRED ?
", 1" : ""));
+ printer->Annotate("gettername", field);
printer->Print(
"/** @param {$optionaltype$} value$returndoc$ */\n"
- "$class$.prototype.set$name$ = function(value) {\n"
+ "$class$.prototype.$settername$ = function(value) {\n"
" jspb.Message.set$oneoftag$$repeatedtag$WrapperField(",
"optionaltype",
JSFieldTypeAnnotation(options, field,
@@ -2459,10 +2502,11 @@ void Generator::GenerateClassField(const GeneratorOptions& options,
/* force_present = */ false,
/* singular_if_not_packed = */ false),
"returndoc", JSReturnDoc(options, field),
- "class", GetPath(options, field->containing_type()),
- "name", JSGetterName(options, field),
+ "class", GetMessagePath(options, field->containing_type()),
+ "settername", "set" + JSGetterName(options, field),
"oneoftag", (field->containing_oneof() ? "Oneof" : ""),
"repeatedtag", (field->is_repeated() ? "Repeated" : ""));
+ printer->Annotate("settername", field);
printer->Print(
"this, $index$$oneofgroup$, value);$returnvalue$\n"
@@ -2485,7 +2529,7 @@ void Generator::GenerateClassField(const GeneratorOptions& options,
// Simple (primitive) field, either singular or repeated.
// TODO(b/26173701): Always use BYTES_DEFAULT for the getter return type;
- // at this point we "lie" to non-binary users and tell the the return
+ // at this point we "lie" to non-binary users and tell the return
// type is always base64 string, pending a LSC to migrate to typed getters.
BytesMode bytes_mode =
field->type() == FieldDescriptor::TYPE_BYTES && !options.binary ?
@@ -2514,9 +2558,10 @@ void Generator::GenerateClassField(const GeneratorOptions& options,
}
printer->Print(
- "$class$.prototype.get$name$ = function() {\n",
- "class", GetPath(options, field->containing_type()),
- "name", JSGetterName(options, field));
+ "$class$.prototype.$gettername$ = function() {\n",
+ "class", GetMessagePath(options, field->containing_type()),
+ "gettername", "get" + JSGetterName(options, field));
+ printer->Annotate("gettername", field);
if (untyped) {
printer->Print(
@@ -2577,26 +2622,47 @@ void Generator::GenerateClassField(const GeneratorOptions& options,
/* singular_if_not_packed = */ false),
"returndoc", JSReturnDoc(options, field));
}
- printer->Print(
- "$class$.prototype.set$name$ = function(value) {\n"
- " jspb.Message.set$oneoftag$Field(this, $index$",
- "class", GetPath(options, field->containing_type()),
- "name", JSGetterName(options, field),
- "oneoftag", (field->containing_oneof() ? "Oneof" : ""),
- "index", JSFieldIndex(field));
- printer->Print(
- "$oneofgroup$, $type$value$rptvalueinit$$typeclose$);$returnvalue$\n"
- "};\n"
- "\n"
- "\n",
- "type",
- untyped ? "/** @type{string|number|boolean|Array|undefined} */(" : "",
- "typeclose", untyped ? ")" : "",
- "oneofgroup",
- (field->containing_oneof() ? (", " + JSOneofArray(options, field))
- : ""),
- "returnvalue", JSReturnClause(field), "rptvalueinit",
- (field->is_repeated() ? " || []" : ""));
+
+ if (field->file()->syntax() == FileDescriptor::SYNTAX_PROTO3 &&
+ !field->is_repeated() && !field->is_map() &&
+ !HasFieldPresence(options, field)) {
+ // Proto3 non-repeated and non-map fields without presence use the
+ // setProto3*Field function.
+ printer->Print(
+ "$class$.prototype.$settername$ = function(value) {\n"
+ " jspb.Message.setProto3$typetag$Field(this, $index$, "
+ "value);$returnvalue$\n"
+ "};\n"
+ "\n"
+ "\n",
+ "class", GetMessagePath(options, field->containing_type()),
+ "settername", "set" + JSGetterName(options, field), "typetag",
+ JSTypeTag(field), "index", JSFieldIndex(field), "returnvalue",
+ JSReturnClause(field));
+ printer->Annotate("settername", field);
+ } else {
+ // Otherwise, use the regular setField function.
+ printer->Print(
+ "$class$.prototype.$settername$ = function(value) {\n"
+ " jspb.Message.set$oneoftag$Field(this, $index$",
+ "class", GetMessagePath(options, field->containing_type()),
+ "settername", "set" + JSGetterName(options, field), "oneoftag",
+ (field->containing_oneof() ? "Oneof" : ""), "index",
+ JSFieldIndex(field));
+ printer->Annotate("settername", field);
+ printer->Print(
+ "$oneofgroup$, $type$value$rptvalueinit$$typeclose$);$returnvalue$\n"
+ "};\n"
+ "\n"
+ "\n",
+ "type",
+ untyped ? "/** @type{string|number|boolean|Array|undefined} */(" : "",
+ "typeclose", untyped ? ")" : "", "oneofgroup",
+ (field->containing_oneof() ? (", " + JSOneofArray(options, field))
+ : ""),
+ "returnvalue", JSReturnClause(field), "rptvalueinit",
+ (field->is_repeated() ? " || []" : ""));
+ }
if (untyped) {
printer->Print(
@@ -2616,41 +2682,46 @@ void Generator::GenerateClassField(const GeneratorOptions& options,
// fields with presence.
if (IsMap(options, field)) {
printer->Print(
- "$class$.prototype.clear$name$ = function() {\n"
- " this.get$name$().clear();$returnvalue$\n"
+ "$class$.prototype.$clearername$ = function() {\n"
+ " this.$gettername$().clear();$returnvalue$\n"
"};\n"
"\n"
"\n",
- "class", GetPath(options, field->containing_type()),
- "name", JSGetterName(options, field),
+ "class", GetMessagePath(options, field->containing_type()),
+ "clearername", "clear" + JSGetterName(options, field),
+ "gettername", "get" + JSGetterName(options, field),
"returnvalue", JSReturnClause(field));
+ printer->Annotate("clearername", field);
} else if (field->is_repeated() ||
(field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE &&
!field->is_required())) {
// Fields where we can delegate to the regular setter.
printer->Print(
- "$class$.prototype.clear$name$ = function() {\n"
- " this.set$name$($clearedvalue$);$returnvalue$\n"
+ "$class$.prototype.$clearername$ = function() {\n"
+ " this.$settername$($clearedvalue$);$returnvalue$\n"
"};\n"
"\n"
"\n",
- "class", GetPath(options, field->containing_type()),
- "name", JSGetterName(options, field),
+ "class", GetMessagePath(options, field->containing_type()),
+ "clearername", "clear" + JSGetterName(options, field),
+ "settername", "set" + JSGetterName(options, field),
"clearedvalue", (field->is_repeated() ? "[]" : "undefined"),
"returnvalue", JSReturnClause(field));
+ printer->Annotate("clearername", field);
} else if (HasFieldPresence(options, field)) {
// Fields where we can't delegate to the regular setter because it doesn't
// accept "undefined" as an argument.
printer->Print(
- "$class$.prototype.clear$name$ = function() {\n"
+ "$class$.prototype.$clearername$ = function() {\n"
" jspb.Message.set$maybeoneof$Field(this, "
"$index$$maybeoneofgroup$, ",
- "class", GetPath(options, field->containing_type()),
- "name", JSGetterName(options, field),
+ "class", GetMessagePath(options, field->containing_type()),
+ "clearername", "clear" + JSGetterName(options, field),
"maybeoneof", (field->containing_oneof() ? "Oneof" : ""),
"maybeoneofgroup", (field->containing_oneof() ?
(", " + JSOneofArray(options, field)) : ""),
"index", JSFieldIndex(field));
+ printer->Annotate("clearername", field);
printer->Print(
"$clearedvalue$);$returnvalue$\n"
"};\n"
@@ -2666,14 +2737,15 @@ void Generator::GenerateClassField(const GeneratorOptions& options,
" * Returns whether this field is set.\n"
" * @return {!boolean}\n"
" */\n"
- "$class$.prototype.has$name$ = function() {\n"
+ "$class$.prototype.$hasername$ = function() {\n"
" return jspb.Message.getField(this, $index$) != null;\n"
"};\n"
"\n"
"\n",
- "class", GetPath(options, field->containing_type()),
- "name", JSGetterName(options, field),
+ "class", GetMessagePath(options, field->containing_type()),
+ "hasername", "has" + JSGetterName(options, field),
"index", JSFieldIndex(field));
+ printer->Annotate("hasername", field);
}
}
@@ -2685,13 +2757,14 @@ void Generator::GenerateRepeatedPrimitiveHelperMethods(
" * @param {!$optionaltype$} value\n"
" * @param {number=} opt_index\n"
" */\n"
- "$class$.prototype.add$name$ = function(value, opt_index) {\n"
+ "$class$.prototype.$addername$ = function(value, opt_index) {\n"
" jspb.Message.addToRepeatedField(this, $index$",
- "class", GetPath(options, field->containing_type()), "name",
- JSGetterName(options, field, BYTES_DEFAULT,
- /* drop_list = */ true),
+ "class", GetMessagePath(options, field->containing_type()), "addername",
+ "add" + JSGetterName(options, field, BYTES_DEFAULT,
+ /* drop_list = */ true),
"optionaltype", JSTypeName(options, field, BYTES_DEFAULT), "index",
JSFieldIndex(field));
+ printer->Annotate("addername", field);
printer->Print(
"$oneofgroup$, $type$value$rptvalueinit$$typeclose$, opt_index);\n"
"};\n"
@@ -2714,9 +2787,9 @@ void Generator::GenerateRepeatedMessageHelperMethods(
" */\n"
"$class$.prototype.add$name$ = function(opt_value, opt_index) {\n"
" return jspb.Message.addTo$repeatedtag$WrapperField(",
- "optionaltype", JSTypeName(options, field, BYTES_DEFAULT), "class",
- GetPath(options, field->containing_type()), "name",
- JSGetterName(options, field, BYTES_DEFAULT,
+ "optionaltype", JSTypeName(options, field, BYTES_DEFAULT),
+ "class", GetMessagePath(options, field->containing_type()),
+ "name", JSGetterName(options, field, BYTES_DEFAULT,
/* drop_list = */ true),
"repeatedtag", (field->is_repeated() ? "Repeated" : ""));
@@ -2727,7 +2800,7 @@ void Generator::GenerateRepeatedMessageHelperMethods(
"\n",
"index", JSFieldIndex(field), "oneofgroup",
(field->containing_oneof() ? (", " + JSOneofArray(options, field)) : ""),
- "ctor", GetPath(options, field->message_type()));
+ "ctor", GetMessagePath(options, field->message_type()));
}
void Generator::GenerateClassExtensionFieldInfo(const GeneratorOptions& options,
@@ -2753,7 +2826,7 @@ void Generator::GenerateClassExtensionFieldInfo(const GeneratorOptions& options,
" */\n"
"$class$.extensions = {};\n"
"\n",
- "class", GetPath(options, desc));
+ "class", GetMessagePath(options, desc));
printer->Print(
"\n"
@@ -2774,7 +2847,7 @@ void Generator::GenerateClassExtensionFieldInfo(const GeneratorOptions& options,
" */\n"
"$class$.extensionsBinary = {};\n"
"\n",
- "class", GetPath(options, desc));
+ "class", GetMessagePath(options, desc));
}
}
@@ -2812,7 +2885,7 @@ void Generator::GenerateClassDeserializeBinary(const GeneratorOptions& options,
" }\n"
" var field = reader.getFieldNumber();\n"
" switch (field) {\n",
- "class", GetPath(options, desc));
+ "class", GetMessagePath(options, desc));
for (int i = 0; i < desc->field_count(); i++) {
if (!IgnoreField(desc->field(i))) {
@@ -2829,7 +2902,7 @@ void Generator::GenerateClassDeserializeBinary(const GeneratorOptions& options,
" $class$.prototype.setExtension);\n"
" break;\n",
"extobj", JSExtensionsObjectName(options, desc->file(), desc),
- "class", GetPath(options, desc));
+ "class", GetMessagePath(options, desc));
} else {
printer->Print(
" reader.skipField();\n"
@@ -2868,7 +2941,7 @@ void Generator::GenerateClassDeserializeBinaryField(
if (value_field->type() == FieldDescriptor::TYPE_MESSAGE) {
printer->Print(", $messageType$.deserializeBinaryFromReader",
- "messageType", GetPath(options, value_field->message_type()));
+ "messageType", GetMessagePath(options, value_field->message_type()));
}
printer->Print(");\n");
@@ -2932,11 +3005,12 @@ void Generator::GenerateClassSerializeBinary(const GeneratorOptions& options,
" * format), writing to the given BinaryWriter.\n"
" * @param {!$class$} message\n"
" * @param {!jspb.BinaryWriter} writer\n"
+ " * @suppress {unusedLocalVariables} f is only used for nested messages\n"
" */\n"
"$class$.serializeBinaryToWriter = function(message, "
"writer) {\n"
" var f = undefined;\n",
- "class", GetPath(options, desc));
+ "class", GetMessagePath(options, desc));
for (int i = 0; i < desc->field_count(); i++) {
if (!IgnoreField(desc->field(i))) {
@@ -2949,7 +3023,7 @@ void Generator::GenerateClassSerializeBinary(const GeneratorOptions& options,
" jspb.Message.serializeBinaryExtensions(message, writer,\n"
" $extobj$Binary, $class$.prototype.getExtension);\n",
"extobj", JSExtensionsObjectName(options, desc->file(), desc),
- "class", GetPath(options, desc));
+ "class", GetMessagePath(options, desc));
}
printer->Print(
@@ -3004,7 +3078,13 @@ void Generator::GenerateClassSerializeBinaryField(
case FieldDescriptor::CPPTYPE_INT64:
case FieldDescriptor::CPPTYPE_UINT32:
case FieldDescriptor::CPPTYPE_UINT64: {
- {
+ if (IsIntegralFieldWithStringJSType(field)) {
+ // We can use `parseInt` here even though it will not be precise for
+ // 64-bit quantities because we are only testing for zero/nonzero,
+ // and JS numbers (64-bit floating point values, i.e., doubles) are
+ // integer-precise in the range that includes zero.
+ printer->Print(" if (parseInt(f, 10) !== 0) {\n");
+ } else {
printer->Print(" if (f !== 0) {\n");
}
break;
@@ -3044,7 +3124,7 @@ void Generator::GenerateClassSerializeBinaryField(
if (value_field->type() == FieldDescriptor::TYPE_MESSAGE) {
printer->Print(", $messageType$.serializeBinaryToWriter",
- "messageType", GetPath(options, value_field->message_type()));
+ "messageType", GetMessagePath(options, value_field->message_type()));
}
printer->Print(");\n");
@@ -3082,8 +3162,10 @@ void Generator::GenerateEnum(const GeneratorOptions& options,
"/**\n"
" * @enum {number}\n"
" */\n"
- "$name$ = {\n",
- "name", GetPath(options, enumdesc));
+ "$enumprefix$$name$ = {\n",
+ "enumprefix", GetEnumPathPrefix(options, enumdesc),
+ "name", enumdesc->name());
+ printer->Annotate("name", enumdesc);
for (int i = 0; i < enumdesc->value_count(); i++) {
const EnumValueDescriptor* value = enumdesc->value(i);
@@ -3092,6 +3174,7 @@ void Generator::GenerateEnum(const GeneratorOptions& options,
"name", ToEnumCase(value->name()),
"value", SimpleItoa(value->number()),
"comma", (i == enumdesc->value_count() - 1) ? "" : ",");
+ printer->Annotate("name", value);
}
printer->Print(
@@ -3103,9 +3186,9 @@ void Generator::GenerateExtension(const GeneratorOptions& options,
io::Printer* printer,
const FieldDescriptor* field) const {
string extension_scope =
- (field->extension_scope() ?
- GetPath(options, field->extension_scope()) :
- GetPath(options, field->file()));
+ (field->extension_scope()
+ ? GetMessagePath(options, field->extension_scope())
+ : GetFilePath(options, field->file()));
printer->Print(
"\n"
@@ -3231,6 +3314,12 @@ bool GeneratorOptions::ParseFromOptions(
return false;
}
one_output_file_per_input_file = true;
+ } else if (options[i].first == "annotate_code") {
+ if (!options[i].second.empty()) {
+ *error = "Unexpected option value for annotate_code";
+ return false;
+ }
+ annotate_code = true;
} else {
// Assume any other option is an output directory, as long as it is a bare
// `key` rather than a `key=value` option.
@@ -3328,7 +3417,8 @@ void Generator::GenerateFile(const GeneratorOptions& options,
printer->Print(
"var $alias$ = require('$file$');\n",
"alias", ModuleAlias(name),
- "file", GetRootPath(file->name(), name) + GetJSFilename(options, name));
+ "file",
+ GetRootPath(file->name(), name) + GetJSFilename(options, name));
}
}
@@ -3342,7 +3432,7 @@ void Generator::GenerateFile(const GeneratorOptions& options,
IgnoreField(file->extension(i))) {
continue;
}
- provided.insert(GetPath(options, file) + "." +
+ provided.insert(GetFilePath(options, file) + "." +
JSObjectFieldName(options, file->extension(i)));
extensions.insert(file->extension(i));
}
@@ -3366,7 +3456,7 @@ void Generator::GenerateFile(const GeneratorOptions& options,
if (options.import_style == GeneratorOptions::kImportCommonJs) {
printer->Print("goog.object.extend(exports, $package$);\n",
- "package", GetPath(options, file));
+ "package", GetFilePath(options, file));
}
// Emit well-known type methods.
@@ -3530,16 +3620,27 @@ bool Generator::GenerateAll(const std::vector<const FileDescriptor*>& files,
options.output_dir + "/" + GetJSFilename(options, file->name());
google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(context->Open(filename));
GOOGLE_CHECK(output.get());
- io::Printer printer(output.get(), '$');
+ GeneratedCodeInfo annotations;
+ io::AnnotationProtoCollector<GeneratedCodeInfo> annotation_collector(
+ &annotations);
+ io::Printer printer(output.get(), '$',
+ options.annotate_code ? &annotation_collector : NULL);
+
GenerateFile(options, &printer, file);
if (printer.failed()) {
return false;
}
+
+ if (options.annotate_code) {
+ const string meta_file = filename + ".meta";
+ google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> info_output(
+ context->Open(meta_file));
+ annotations.SerializeToZeroCopyStream(info_output.get());
+ }
}
}
-
return true;
}
diff --git a/src/google/protobuf/compiler/js/js_generator.h b/src/google/protobuf/compiler/js/js_generator.h
index 6e932d7f..3cc60e22 100755
--- a/src/google/protobuf/compiler/js/js_generator.h
+++ b/src/google/protobuf/compiler/js/js_generator.h
@@ -79,7 +79,8 @@ struct GeneratorOptions {
library(""),
error_on_name_conflict(false),
extension(".js"),
- one_output_file_per_input_file(false) {}
+ one_output_file_per_input_file(false),
+ annotate_code(false) {}
bool ParseFromOptions(
const std::vector< std::pair< string, string > >& options,
@@ -118,6 +119,9 @@ struct GeneratorOptions {
string extension;
// Create a separate output file for each input file?
bool one_output_file_per_input_file;
+ // If true, we should build .meta files that contain annotations for
+ // generated code. See GeneratedCodeInfo in descriptor.proto.
+ bool annotate_code;
};
// CodeGenerator implementation which generates a JavaScript source file and
diff --git a/src/google/protobuf/compiler/js/well_known_types/any.js b/src/google/protobuf/compiler/js/well_known_types/any.js
index 22f18919..d7ca6e3a 100644
--- a/src/google/protobuf/compiler/js/well_known_types/any.js
+++ b/src/google/protobuf/compiler/js/well_known_types/any.js
@@ -69,7 +69,7 @@ proto.google.protobuf.Any.prototype.pack = function(serialized, name,
* the binary data properly.
* @param {string} name The expected type name of this message object.
* @return {?T} If the name matched the expected name, returns the deserialized
- * object, otherwise returns undefined.
+ * object, otherwise returns null.
*/
proto.google.protobuf.Any.prototype.unpack = function(deserialize, name) {
if (this.getTypeName() == name) {
diff --git a/src/google/protobuf/compiler/js/well_known_types/timestamp.js b/src/google/protobuf/compiler/js/well_known_types/timestamp.js
index 77c07bb4..b7e43f19 100644
--- a/src/google/protobuf/compiler/js/well_known_types/timestamp.js
+++ b/src/google/protobuf/compiler/js/well_known_types/timestamp.js
@@ -48,7 +48,6 @@ proto.google.protobuf.Timestamp.prototype.toDate = function() {
* @param {!Date} value The value to set.
*/
proto.google.protobuf.Timestamp.prototype.fromDate = function(value) {
- var millis = value.getTime();
this.setSeconds(Math.floor(value.getTime() / 1000));
this.setNanos(value.getMilliseconds() * 1000000);
};
diff --git a/src/google/protobuf/compiler/js/well_known_types_embed.cc b/src/google/protobuf/compiler/js/well_known_types_embed.cc
deleted file mode 100755
index 71fd557f..00000000
--- a/src/google/protobuf/compiler/js/well_known_types_embed.cc
+++ /dev/null
@@ -1,314 +0,0 @@
-#include <google/protobuf/compiler/js/well_known_types_embed.h>
-struct FileToc well_known_types_js[] = {
-{"any.js",
- "// Protocol Buffers - Google's data interchange format\n"
- "// Copyright 2008 Google Inc. All rights reserved.\n"
- "// https://developers.google.com/protocol-buffers/\n"
- "//\n"
- "// Redistribution and use in source and binary forms, with or without\n"
- "// modification, are permitted provided that the following conditions are\n"
- "// met:\n"
- "//\n"
- "// * Redistributions of source code must retain the above copyright\n"
- "// notice, this list of conditions and the following disclaimer.\n"
- "// * Redistributions in binary form must reproduce the above\n"
- "// copyright notice, this list of conditions and the following disclaimer\n"
- "// in the documentation and/or other materials provided with the\n"
- "// distribution.\n"
- "// * Neither the name of Google Inc. nor the names of its\n"
- "// contributors may be used to endorse or promote products derived from\n"
- "// this software without specific prior written permission.\n"
- "//\n"
- "// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n"
- "// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n"
- "// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n"
- "// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n"
- "// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n"
- "// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n"
- "// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n"
- "// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n"
- "// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n"
- "// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n"
- "// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
- "\n"
- "/* This code will be inserted into generated code for\n"
- " * google/protobuf/any.proto. */\n"
- "\n"
- "/**\n"
- " * Returns the type name contained in this instance, if any.\n"
- " * @return {string|undefined}\n"
- " */\n"
- "proto.google.protobuf.Any.prototype.getTypeName = function() {\n"
- " return this.getTypeUrl().split('/').pop();\n"
- "};\n"
- "\n"
- "\n"
- "/**\n"
- " * Packs the given message instance into this Any.\n"
- " * @param {!Uint8Array} serialized The serialized data to pack.\n"
- " * @param {string} name The type name of this message object.\n"
- " * @param {string=} opt_typeUrlPrefix the type URL prefix.\n"
- " */\n"
- "proto.google.protobuf.Any.prototype.pack = function(serialized, name,\n"
- " opt_typeUrlPrefix) {\n"
- " if (!opt_typeUrlPrefix) {\n"
- " opt_typeUrlPrefix = 'type.googleapis.com/';\n"
- " }\n"
- "\n"
- " if (opt_typeUrlPrefix.substr(-1) != '/') {\n"
- " this.setTypeUrl(opt_typeUrlPrefix + '/' + name);\n"
- " } else {\n"
- " this.setTypeUrl(opt_typeUrlPrefix + name);\n"
- " }\n"
- "\n"
- " this.setValue(serialized);\n"
- "};\n"
- "\n"
- "\n"
- "/**\n"
- " * @template T\n"
- " * Unpacks this Any into the given message object.\n"
- " * @param {function(Uint8Array):T} deserialize Function that will deserialize\n"
- " * the binary data properly.\n"
- " * @param {string} name The expected type name of this message object.\n"
- " * @return {?T} If the name matched the expected name, returns the deserialized\n"
- " * object, otherwise returns undefined.\n"
- " */\n"
- "proto.google.protobuf.Any.prototype.unpack = function(deserialize, name) {\n"
- " if (this.getTypeName() == name) {\n"
- " return deserialize(this.getValue_asU8());\n"
- " } else {\n"
- " return null;\n"
- " }\n"
- "};\n"
-},
-{"timestamp.js",
- "// Protocol Buffers - Google's data interchange format\n"
- "// Copyright 2008 Google Inc. All rights reserved.\n"
- "// https://developers.google.com/protocol-buffers/\n"
- "//\n"
- "// Redistribution and use in source and binary forms, with or without\n"
- "// modification, are permitted provided that the following conditions are\n"
- "// met:\n"
- "//\n"
- "// * Redistributions of source code must retain the above copyright\n"
- "// notice, this list of conditions and the following disclaimer.\n"
- "// * Redistributions in binary form must reproduce the above\n"
- "// copyright notice, this list of conditions and the following disclaimer\n"
- "// in the documentation and/or other materials provided with the\n"
- "// distribution.\n"
- "// * Neither the name of Google Inc. nor the names of its\n"
- "// contributors may be used to endorse or promote products derived from\n"
- "// this software without specific prior written permission.\n"
- "//\n"
- "// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n"
- "// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n"
- "// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n"
- "// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n"
- "// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n"
- "// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n"
- "// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n"
- "// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n"
- "// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n"
- "// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n"
- "// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
- "\n"
- "/* This code will be inserted into generated code for\n"
- " * google/protobuf/timestamp.proto. */\n"
- "\n"
- "/**\n"
- " * Returns a JavaScript 'Date' object corresponding to this Timestamp.\n"
- " * @return {!Date}\n"
- " */\n"
- "proto.google.protobuf.Timestamp.prototype.toDate = function() {\n"
- " // The '|| 0' clauses are necessary for as long as\n"
- " // broken_proto3_semantics are specified for this rule inside Google.\n"
- " var seconds = this.getSeconds() || 0;\n"
- " var nanos = this.getNanos() || 0;\n"
- "\n"
- " return new Date((seconds * 1000) + (nanos / 1000000));\n"
- "};\n"
- "\n"
- "\n"
- "/**\n"
- " * Sets the value of this Timestamp object to be the given Date.\n"
- " * @param {!Date} value The value to set.\n"
- " */\n"
- "proto.google.protobuf.Timestamp.prototype.fromDate = function(value) {\n"
- " var millis = value.getTime();\n"
- " this.setSeconds(Math.floor(value.getTime() / 1000));\n"
- " this.setNanos(value.getMilliseconds() * 1000000);\n"
- "};\n"
-},
-{"struct.js",
- "// Protocol Buffers - Google's data interchange format\n"
- "// Copyright 2008 Google Inc. All rights reserved.\n"
- "// https://developers.google.com/protocol-buffers/\n"
- "//\n"
- "// Redistribution and use in source and binary forms, with or without\n"
- "// modification, are permitted provided that the following conditions are\n"
- "// met:\n"
- "//\n"
- "// * Redistributions of source code must retain the above copyright\n"
- "// notice, this list of conditions and the following disclaimer.\n"
- "// * Redistributions in binary form must reproduce the above\n"
- "// copyright notice, this list of conditions and the following disclaimer\n"
- "// in the documentation and/or other materials provided with the\n"
- "// distribution.\n"
- "// * Neither the name of Google Inc. nor the names of its\n"
- "// contributors may be used to endorse or promote products derived from\n"
- "// this software without specific prior written permission.\n"
- "//\n"
- "// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n"
- "// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n"
- "// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n"
- "// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n"
- "// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n"
- "// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n"
- "// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n"
- "// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n"
- "// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n"
- "// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n"
- "// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
- "\n"
- "/* This code will be inserted into generated code for\n"
- " * google/protobuf/struct.proto. */\n"
- "\n"
- "/**\n"
- " * Typedef representing plain JavaScript values that can go into a\n"
- " * Struct.\n"
- " * @typedef {null|number|string|boolean|Array|Object}\n"
- " */\n"
- "proto.google.protobuf.JavaScriptValue;\n"
- "\n"
- "\n"
- "/**\n"
- " * Converts this Value object to a plain JavaScript value.\n"
- " * @return {?proto.google.protobuf.JavaScriptValue} a plain JavaScript\n"
- " * value representing this Struct.\n"
- " */\n"
- "proto.google.protobuf.Value.prototype.toJavaScript = function() {\n"
- " var kindCase = proto.google.protobuf.Value.KindCase;\n"
- " switch (this.getKindCase()) {\n"
- " case kindCase.NULL_VALUE:\n"
- " return null;\n"
- " case kindCase.NUMBER_VALUE:\n"
- " return this.getNumberValue();\n"
- " case kindCase.STRING_VALUE:\n"
- " return this.getStringValue();\n"
- " case kindCase.BOOL_VALUE:\n"
- " return this.getBoolValue();\n"
- " case kindCase.STRUCT_VALUE:\n"
- " return this.getStructValue().toJavaScript();\n"
- " case kindCase.LIST_VALUE:\n"
- " return this.getListValue().toJavaScript();\n"
- " default:\n"
- " throw new Error('Unexpected struct type');\n"
- " }\n"
- "};\n"
- "\n"
- "\n"
- "/**\n"
- " * Converts this JavaScript value to a new Value proto.\n"
- " * @param {!proto.google.protobuf.JavaScriptValue} value The value to\n"
- " * convert.\n"
- " * @return {!proto.google.protobuf.Value} The newly constructed value.\n"
- " */\n"
- "proto.google.protobuf.Value.fromJavaScript = function(value) {\n"
- " var ret = new proto.google.protobuf.Value();\n"
- " switch (goog.typeOf(value)) {\n"
- " case 'string':\n"
- " ret.setStringValue(/** @type {string} */ (value));\n"
- " break;\n"
- " case 'number':\n"
- " ret.setNumberValue(/** @type {number} */ (value));\n"
- " break;\n"
- " case 'boolean':\n"
- " ret.setBoolValue(/** @type {boolean} */ (value));\n"
- " break;\n"
- " case 'null':\n"
- " ret.setNullValue(proto.google.protobuf.NullValue.NULL_VALUE);\n"
- " break;\n"
- " case 'array':\n"
- " ret.setListValue(proto.google.protobuf.ListValue.fromJavaScript(\n"
- " /** @type{!Array} */ (value)));\n"
- " break;\n"
- " case 'object':\n"
- " ret.setStructValue(proto.google.protobuf.Struct.fromJavaScript(\n"
- " /** @type{!Object} */ (value)));\n"
- " break;\n"
- " default:\n"
- " throw new Error('Unexpected struct type.');\n"
- " }\n"
- "\n"
- " return ret;\n"
- "};\n"
- "\n"
- "\n"
- "/**\n"
- " * Converts this ListValue object to a plain JavaScript array.\n"
- " * @return {!Array} a plain JavaScript array representing this List.\n"
- " */\n"
- "proto.google.protobuf.ListValue.prototype.toJavaScript = function() {\n"
- " var ret = [];\n"
- " var values = this.getValuesList();\n"
- "\n"
- " for (var i = 0; i < values.length; i++) {\n"
- " ret[i] = values[i].toJavaScript();\n"
- " }\n"
- "\n"
- " return ret;\n"
- "};\n"
- "\n"
- "\n"
- "/**\n"
- " * Constructs a ListValue protobuf from this plain JavaScript array.\n"
- " * @param {!Array} array a plain JavaScript array\n"
- " * @return {proto.google.protobuf.ListValue} a new ListValue object\n"
- " */\n"
- "proto.google.protobuf.ListValue.fromJavaScript = function(array) {\n"
- " var ret = new proto.google.protobuf.ListValue();\n"
- "\n"
- " for (var i = 0; i < array.length; i++) {\n"
- " ret.addValues(proto.google.protobuf.Value.fromJavaScript(array[i]));\n"
- " }\n"
- "\n"
- " return ret;\n"
- "};\n"
- "\n"
- "\n"
- "/**\n"
- " * Converts this Struct object to a plain JavaScript object.\n"
- " * @return {!Object<string, !proto.google.protobuf.JavaScriptValue>} a plain\n"
- " * JavaScript object representing this Struct.\n"
- " */\n"
- "proto.google.protobuf.Struct.prototype.toJavaScript = function() {\n"
- " var ret = {};\n"
- "\n"
- " this.getFieldsMap().forEach(function(value, key) {\n"
- " ret[key] = value.toJavaScript();\n"
- " });\n"
- "\n"
- " return ret;\n"
- "};\n"
- "\n"
- "\n"
- "/**\n"
- " * Constructs a Struct protobuf from this plain JavaScript object.\n"
- " * @param {!Object} obj a plain JavaScript object\n"
- " * @return {proto.google.protobuf.Struct} a new Struct object\n"
- " */\n"
- "proto.google.protobuf.Struct.fromJavaScript = function(obj) {\n"
- " var ret = new proto.google.protobuf.Struct();\n"
- " var map = ret.getFieldsMap();\n"
- "\n"
- " for (var property in obj) {\n"
- " var val = obj[property];\n"
- " map.set(property, proto.google.protobuf.Value.fromJavaScript(val));\n"
- " }\n"
- "\n"
- " return ret;\n"
- "};\n"
-},
- {NULL, NULL} // Terminate the list.
-};
diff --git a/src/google/protobuf/compiler/mock_code_generator.cc b/src/google/protobuf/compiler/mock_code_generator.cc
index e82e6ae1..bfcb83df 100644
--- a/src/google/protobuf/compiler/mock_code_generator.cc
+++ b/src/google/protobuf/compiler/mock_code_generator.cc
@@ -40,20 +40,30 @@
#endif
#include <vector>
-#include <google/protobuf/compiler/plugin.pb.h>
+
+#include <google/protobuf/stubs/strutil.h>
+
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/testing/file.h>
#include <google/protobuf/testing/file.h>
#include <google/protobuf/testing/file.h>
+#include <google/protobuf/compiler/plugin.pb.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/descriptor.h>
-#include <google/protobuf/stubs/strutil.h>
+#include <google/protobuf/text_format.h>
#include <google/protobuf/stubs/substitute.h>
#include <gtest/gtest.h>
+#ifdef major
+#undef major
+#endif
+#ifdef minor
+#undef minor
+#endif
+
namespace google {
namespace protobuf {
namespace compiler {
@@ -128,11 +138,48 @@ void MockCodeGenerator::ExpectGenerated(
}
}
+namespace {
+void CheckSingleAnnotation(const string& expected_file,
+ const string& expected_text,
+ const string& file_content,
+ const GeneratedCodeInfo::Annotation& annotation) {
+ EXPECT_EQ(expected_file, annotation.source_file());
+ ASSERT_GE(file_content.size(), annotation.begin());
+ ASSERT_GE(file_content.size(), annotation.end());
+ ASSERT_LE(annotation.begin(), annotation.end());
+ EXPECT_EQ(expected_text.size(), annotation.end() - annotation.begin());
+ EXPECT_EQ(expected_text,
+ file_content.substr(annotation.begin(), expected_text.size()));
+}
+} // anonymous namespace
+
+void MockCodeGenerator::CheckGeneratedAnnotations(
+ const string& name, const string& file, const string& output_directory) {
+ string file_content;
+ GOOGLE_CHECK_OK(
+ File::GetContents(output_directory + "/" + GetOutputFileName(name, file),
+ &file_content, true));
+ string meta_content;
+ GOOGLE_CHECK_OK(File::GetContents(
+ output_directory + "/" + GetOutputFileName(name, file) + ".meta",
+ &meta_content, true));
+ GeneratedCodeInfo annotations;
+ GOOGLE_CHECK(TextFormat::ParseFromString(meta_content, &annotations));
+ ASSERT_EQ(3, annotations.annotation_size());
+ CheckSingleAnnotation("first_annotation", "first", file_content,
+ annotations.annotation(0));
+ CheckSingleAnnotation("second_annotation", "second", file_content,
+ annotations.annotation(1));
+ CheckSingleAnnotation("third_annotation", "third", file_content,
+ annotations.annotation(2));
+}
+
bool MockCodeGenerator::Generate(
const FileDescriptor* file,
const string& parameter,
GeneratorContext* context,
string* error) const {
+ bool annotate = false;
for (int i = 0; i < file->message_type_count(); i++) {
if (HasPrefixString(file->message_type(i)->name(), "MockCodeGenerator_")) {
string command = StripPrefixString(file->message_type(i)->name(),
@@ -161,6 +208,8 @@ bool MockCodeGenerator::Generate(
std::cerr << "Saw json_name: "
<< field_descriptor_proto.has_json_name() << std::endl;
abort();
+ } else if (command == "Annotate") {
+ annotate = true;
} else if (command == "ShowVersionNumber") {
Version compiler_version;
context->GetCompilerVersion(&compiler_version);
@@ -211,16 +260,40 @@ bool MockCodeGenerator::Generate(
google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(
context->Open(GetOutputFileName(name_, file)));
- io::Printer printer(output.get(), '$');
- printer.PrintRaw(GetOutputFileContent(name_, parameter,
- file, context));
+ GeneratedCodeInfo annotations;
+ io::AnnotationProtoCollector<GeneratedCodeInfo> annotation_collector(
+ &annotations);
+ io::Printer printer(output.get(), '$',
+ annotate ? &annotation_collector : NULL);
+ printer.PrintRaw(GetOutputFileContent(name_, parameter, file, context));
+ string annotate_suffix = "_annotation";
+ if (annotate) {
+ printer.Print("$p$", "p", "first");
+ printer.Annotate("p", "first" + annotate_suffix);
+ }
printer.PrintRaw(kFirstInsertionPoint);
+ if (annotate) {
+ printer.Print("$p$", "p", "second");
+ printer.Annotate("p", "second" + annotate_suffix);
+ }
printer.PrintRaw(kSecondInsertionPoint);
+ if (annotate) {
+ printer.Print("$p$", "p", "third");
+ printer.Annotate("p", "third" + annotate_suffix);
+ }
if (printer.failed()) {
*error = "MockCodeGenerator detected write error.";
return false;
}
+ if (annotate) {
+ google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> meta_output(
+ context->Open(GetOutputFileName(name_, file) + ".meta"));
+ if (!TextFormat::Print(annotations, meta_output.get())) {
+ *error = "MockCodeGenerator couldn't write .meta";
+ return false;
+ }
+ }
}
return true;
diff --git a/src/google/protobuf/compiler/mock_code_generator.h b/src/google/protobuf/compiler/mock_code_generator.h
index e1665f88..cdd9138c 100644
--- a/src/google/protobuf/compiler/mock_code_generator.h
+++ b/src/google/protobuf/compiler/mock_code_generator.h
@@ -68,6 +68,8 @@ namespace compiler {
// printing "Saw message type MockCodeGenerator_HasSourceCodeInfo: FOO." to
// stderr, where FOO is "1" if the supplied FileDescriptorProto has source
// code info, and "0" otherwise.
+// MockCodeGenerator_Annotate: Generate() will add annotations to its output
+// that can later be verified with CheckGeneratedAnnotations.
class MockCodeGenerator : public CodeGenerator {
public:
MockCodeGenerator(const string& name);
@@ -88,6 +90,12 @@ class MockCodeGenerator : public CodeGenerator {
const string& parsed_file_list,
const string& output_directory);
+ // Checks that the correct text ranges were annotated by the
+ // MockCodeGenerator_Annotate directive.
+ static void CheckGeneratedAnnotations(const string& name,
+ const string& file,
+ const string& output_directory);
+
// Get the name of the file which would be written by the given generator.
static string GetOutputFileName(const string& generator_name,
const FileDescriptor* file);
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_enum_field.cc b/src/google/protobuf/compiler/objectivec/objectivec_enum_field.cc
index 7a774a09..8899a13a 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_enum_field.cc
+++ b/src/google/protobuf/compiler/objectivec/objectivec_enum_field.cc
@@ -46,7 +46,7 @@ namespace objectivec {
namespace {
void SetEnumVariables(const FieldDescriptor* descriptor,
- map<string, string>* variables) {
+ std::map<string, string>* variables) {
string type = EnumName(descriptor->enum_type());
(*variables)["storage_type"] = type;
// For non repeated fields, if it was defined in a different file, the
@@ -118,7 +118,7 @@ void EnumFieldGenerator::GenerateCFunctionImplementations(
}
void EnumFieldGenerator::DetermineForwardDeclarations(
- set<string>* fwd_decls) const {
+ std::set<string>* fwd_decls) const {
SingleFieldGenerator::DetermineForwardDeclarations(fwd_decls);
// If it is an enum defined in a different file, then we'll need a forward
// declaration for it. When it is in our file, all the enums are output
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_enum_field.h b/src/google/protobuf/compiler/objectivec/objectivec_enum_field.h
index 946faa81..ae56c069 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_enum_field.h
+++ b/src/google/protobuf/compiler/objectivec/objectivec_enum_field.h
@@ -47,7 +47,7 @@ class EnumFieldGenerator : public SingleFieldGenerator {
public:
virtual void GenerateCFunctionDeclarations(io::Printer* printer) const;
virtual void GenerateCFunctionImplementations(io::Printer* printer) const;
- virtual void DetermineForwardDeclarations(set<string>* fwd_decls) const;
+ virtual void DetermineForwardDeclarations(std::set<string>* fwd_decls) const;
protected:
EnumFieldGenerator(const FieldDescriptor* descriptor, const Options& options);
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_extension.cc b/src/google/protobuf/compiler/objectivec/objectivec_extension.cc
index 7073173c..b788d0a3 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_extension.cc
+++ b/src/google/protobuf/compiler/objectivec/objectivec_extension.cc
@@ -49,9 +49,9 @@ ExtensionGenerator::ExtensionGenerator(const string& root_class_name,
if (descriptor->is_map()) {
// NOTE: src/google/protobuf/compiler/plugin.cc makes use of cerr for some
// error cases, so it seems to be ok to use as a back door for errors.
- cerr << "error: Extension is a map<>!"
- << " That used to be blocked by the compiler." << endl;
- cerr.flush();
+ std::cerr << "error: Extension is a map<>!"
+ << " That used to be blocked by the compiler." << std::endl;
+ std::cerr.flush();
abort();
}
}
@@ -59,7 +59,7 @@ ExtensionGenerator::ExtensionGenerator(const string& root_class_name,
ExtensionGenerator::~ExtensionGenerator() {}
void ExtensionGenerator::GenerateMembersHeader(io::Printer* printer) {
- map<string, string> vars;
+ std::map<string, string> vars;
vars["method_name"] = method_name_;
SourceLocation location;
if (descriptor_->GetSourceLocation(&location)) {
@@ -77,7 +77,7 @@ void ExtensionGenerator::GenerateMembersHeader(io::Printer* printer) {
void ExtensionGenerator::GenerateStaticVariablesInitialization(
io::Printer* printer) {
- map<string, string> vars;
+ std::map<string, string> vars;
vars["root_class_and_method_name"] = root_class_and_method_name_;
vars["extended_type"] = ClassName(descriptor_->containing_type());
vars["number"] = SimpleItoa(descriptor_->number());
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_field.cc b/src/google/protobuf/compiler/objectivec/objectivec_field.cc
index 527b7c0c..b6123fad 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_field.cc
+++ b/src/google/protobuf/compiler/objectivec/objectivec_field.cc
@@ -49,7 +49,7 @@ namespace objectivec {
namespace {
void SetCommonFieldVariables(const FieldDescriptor* descriptor,
- map<string, string>* variables) {
+ std::map<string, string>* variables) {
string camel_case_name = FieldName(descriptor);
string raw_field_name;
if (descriptor->type() == FieldDescriptor::TYPE_GROUP) {
@@ -178,7 +178,7 @@ void FieldGenerator::GenerateCFunctionImplementations(
}
void FieldGenerator::DetermineForwardDeclarations(
- set<string>* fwd_decls) const {
+ std::set<string>* fwd_decls) const {
// Nothing
}
@@ -228,8 +228,8 @@ int FieldGenerator::ExtraRuntimeHasBitsNeeded(void) const {
void FieldGenerator::SetExtraRuntimeHasBitsBase(int index_base) {
// NOTE: src/google/protobuf/compiler/plugin.cc makes use of cerr for some
// error cases, so it seems to be ok to use as a back door for errors.
- cerr << "Error: should have overridden SetExtraRuntimeHasBitsBase()." << endl;
- cerr.flush();
+ std::cerr << "Error: should have overridden SetExtraRuntimeHasBitsBase()." << std::endl;
+ std::cerr.flush();
abort();
}
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_field.h b/src/google/protobuf/compiler/objectivec/objectivec_field.h
index a3a4b1b6..6bd5db2e 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_field.h
+++ b/src/google/protobuf/compiler/objectivec/objectivec_field.h
@@ -67,7 +67,7 @@ class FieldGenerator {
virtual void GenerateCFunctionImplementations(io::Printer* printer) const;
// Exposed for subclasses, should always call it on the parent class also.
- virtual void DetermineForwardDeclarations(set<string>* fwd_decls) const;
+ virtual void DetermineForwardDeclarations(std::set<string>* fwd_decls) const;
// Used during generation, not intended to be extended by subclasses.
void GenerateFieldDescription(
@@ -100,7 +100,7 @@ class FieldGenerator {
virtual bool WantsHasProperty(void) const = 0;
const FieldDescriptor* descriptor_;
- map<string, string> variables_;
+ std::map<string, string> variables_;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGenerator);
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_file.cc b/src/google/protobuf/compiler/objectivec/objectivec_file.cc
index 7ad127bb..954b2688 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_file.cc
+++ b/src/google/protobuf/compiler/objectivec/objectivec_file.cc
@@ -89,7 +89,7 @@ bool FileContainsExtensions(const FileDescriptor* file) {
void PruneFileAndDepsMarkingAsVisited(
const FileDescriptor* file,
vector<const FileDescriptor*>* files,
- set<const FileDescriptor*>* files_visited) {
+ std::set<const FileDescriptor*>* files_visited) {
vector<const FileDescriptor*>::iterator iter =
std::find(files->begin(), files->end(), file);
if (iter != files->end()) {
@@ -105,7 +105,7 @@ void PruneFileAndDepsMarkingAsVisited(
void CollectMinimalFileDepsContainingExtensionsWorker(
const FileDescriptor* file,
vector<const FileDescriptor*>* files,
- set<const FileDescriptor*>* files_visited) {
+ std::set<const FileDescriptor*>* files_visited) {
if (files_visited->find(file) != files_visited->end()) {
return;
}
@@ -138,7 +138,7 @@ void CollectMinimalFileDepsContainingExtensionsWorker(
void CollectMinimalFileDepsContainingExtensions(
const FileDescriptor* file,
vector<const FileDescriptor*>* files) {
- set<const FileDescriptor*> files_visited;
+ std::set<const FileDescriptor*> files_visited;
for (int i = 0; i < file->dependency_count(); i++) {
const FileDescriptor* dep = file->dependency(i);
CollectMinimalFileDepsContainingExtensionsWorker(dep, files,
@@ -229,12 +229,12 @@ void FileGenerator::GenerateHeader(io::Printer *printer) {
"CF_EXTERN_C_BEGIN\n"
"\n");
- set<string> fwd_decls;
+ std::set<string> fwd_decls;
for (vector<MessageGenerator *>::iterator iter = message_generators_.begin();
iter != message_generators_.end(); ++iter) {
(*iter)->DetermineForwardDeclarations(&fwd_decls);
}
- for (set<string>::const_iterator i(fwd_decls.begin());
+ for (std::set<string>::const_iterator i(fwd_decls.begin());
i != fwd_decls.end(); ++i) {
printer->Print("$value$;\n", "value", *i);
}
@@ -325,7 +325,7 @@ void FileGenerator::GenerateSource(io::Printer *printer) {
// #import the headers for anything that a plain dependency of this proto
// file (that means they were just an include, not a "public" include).
- set<string> public_import_names;
+ std::set<string> public_import_names;
for (int i = 0; i < file_->public_dependency_count(); i++) {
public_import_names.insert(file_->public_dependency(i)->name());
}
@@ -468,7 +468,7 @@ void FileGenerator::GenerateSource(io::Printer *printer) {
// File descriptor only needed if there are messages to use it.
if (message_generators_.size() > 0) {
- map<string, string> vars;
+ std::map<string, string> vars;
vars["root_class_name"] = root_class_name_;
vars["package"] = file_->package();
vars["objc_prefix"] = FileClassPrefix(file_);
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc b/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc
index c7fd96ac..54dc7455 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc
+++ b/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc
@@ -28,9 +28,7 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-#ifdef _MSC_VER
-#include <io.h>
-#else
+#ifndef _MSC_VER
#include <unistd.h>
#endif
#include <climits>
@@ -49,8 +47,15 @@
#include <google/protobuf/io/printer.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/stubs/common.h>
+#include <google/protobuf/stubs/io_win32.h>
#include <google/protobuf/stubs/strutil.h>
+#if defined(_MSC_VER)
+// DO NOT include <io.h>, instead create functions in io_win32.{h,cc} and import
+// them like we do below.
+using google::protobuf::internal::win32::open;
+#endif
+
// NOTE: src/google/protobuf/compiler/plugin.cc makes use of cerr for some
// error cases, so it seems to be ok to use as a back door for errors.
@@ -196,7 +201,7 @@ const char* const kReservedWordList[] = {
// method declared in protos. The main cases are methods
// that take no arguments, or setFoo:/hasFoo: type methods.
"clear", "data", "delimitedData", "descriptor", "extensionRegistry",
- "extensionsCurrentlySet", "isInitialized", "serializedSize",
+ "extensionsCurrentlySet", "initialized", "isInitialized", "serializedSize",
"sortedExtensionsInUse", "unknownFields",
// MacTypes.h names
@@ -980,13 +985,13 @@ namespace {
class ExpectedPrefixesCollector : public LineConsumer {
public:
- ExpectedPrefixesCollector(map<string, string>* inout_package_to_prefix_map)
+ ExpectedPrefixesCollector(std::map<string, string>* inout_package_to_prefix_map)
: prefix_map_(inout_package_to_prefix_map) {}
virtual bool ConsumeLine(const StringPiece& line, string* out_error);
private:
- map<string, string>* prefix_map_;
+ std::map<string, string>* prefix_map_;
};
bool ExpectedPrefixesCollector::ConsumeLine(
@@ -1009,7 +1014,7 @@ bool ExpectedPrefixesCollector::ConsumeLine(
}
bool LoadExpectedPackagePrefixes(const Options &generation_options,
- map<string, string>* prefix_map,
+ std::map<string, string>* prefix_map,
string* out_error) {
if (generation_options.expected_prefixes_path.empty()) {
return true;
@@ -1023,7 +1028,7 @@ bool LoadExpectedPackagePrefixes(const Options &generation_options,
bool ValidateObjCClassPrefix(
const FileDescriptor* file,
const string& expected_prefixes_path,
- const map<string, string>& expected_package_prefixes,
+ const std::map<string, string>& expected_package_prefixes,
string* out_error) {
const string prefix = file->options().objc_class_prefix();
const string package = file->package();
@@ -1033,7 +1038,7 @@ bool ValidateObjCClassPrefix(
// Check: Error - See if there was an expected prefix for the package and
// report if it doesn't match (wrong or missing).
- map<string, string>::const_iterator package_match =
+ std::map<string, string>::const_iterator package_match =
expected_package_prefixes.find(package);
if (package_match != expected_package_prefixes.end()) {
// There was an entry, and...
@@ -1063,26 +1068,26 @@ bool ValidateObjCClassPrefix(
// to Apple's rules (the checks above implicitly whitelist anything that
// doesn't meet these rules).
if (!ascii_isupper(prefix[0])) {
- cerr << endl
+ std::cerr << std::endl
<< "protoc:0: warning: Invalid 'option objc_class_prefix = \""
<< prefix << "\";' in '" << file->name() << "';"
- << " it should start with a capital letter." << endl;
- cerr.flush();
+ << " it should start with a capital letter." << std::endl;
+ std::cerr.flush();
}
if (prefix.length() < 3) {
// Apple reserves 2 character prefixes for themselves. They do use some
// 3 character prefixes, but they haven't updated the rules/docs.
- cerr << endl
+ std::cerr << std::endl
<< "protoc:0: warning: Invalid 'option objc_class_prefix = \""
<< prefix << "\";' in '" << file->name() << "';"
<< " Apple recommends they should be at least 3 characters long."
- << endl;
- cerr.flush();
+ << std::endl;
+ std::cerr.flush();
}
// Look for any other package that uses the same prefix.
string other_package_for_prefix;
- for (map<string, string>::const_iterator i = expected_package_prefixes.begin();
+ for (std::map<string, string>::const_iterator i = expected_package_prefixes.begin();
i != expected_package_prefixes.end(); ++i) {
if (i->second == prefix) {
other_package_for_prefix = i->first;
@@ -1096,22 +1101,22 @@ bool ValidateObjCClassPrefix(
// The file does not have a package and ...
if (other_package_for_prefix.empty()) {
// ... no other package has declared that prefix.
- cerr << endl
+ std::cerr << std::endl
<< "protoc:0: warning: File '" << file->name() << "' has no "
<< "package. Consider adding a new package to the proto and adding '"
<< "new.package = " << prefix << "' to the expected prefixes file ("
- << expected_prefixes_path << ")." << endl;
- cerr.flush();
+ << expected_prefixes_path << ")." << std::endl;
+ std::cerr.flush();
} else {
// ... another package has declared the same prefix.
- cerr << endl
+ std::cerr << std::endl
<< "protoc:0: warning: File '" << file->name() << "' has no package "
<< "and package '" << other_package_for_prefix << "' already uses '"
<< prefix << "' as its prefix. Consider either adding a new package "
<< "to the proto, or reusing one of the packages already using this "
<< "prefix in the expected prefixes file ("
- << expected_prefixes_path << ")." << endl;
- cerr.flush();
+ << expected_prefixes_path << ")." << std::endl;
+ std::cerr.flush();
}
return true;
}
@@ -1133,12 +1138,12 @@ bool ValidateObjCClassPrefix(
// Check: Warning - If the given package/prefix pair wasn't expected, issue a
// warning issue a warning suggesting it gets added to the file.
if (!expected_package_prefixes.empty()) {
- cerr << endl
+ std::cerr << std::endl
<< "protoc:0: warning: Found unexpected 'option objc_class_prefix = \""
<< prefix << "\";' in '" << file->name() << "';"
<< " consider adding it to the expected prefixes file ("
- << expected_prefixes_path << ")." << endl;
- cerr.flush();
+ << expected_prefixes_path << ")." << std::endl;
+ std::cerr.flush();
}
return true;
@@ -1150,7 +1155,7 @@ bool ValidateObjCClassPrefixes(const vector<const FileDescriptor*>& files,
const Options& generation_options,
string* out_error) {
// Load the expected package prefixes, if available, to validate against.
- map<string, string> expected_package_prefixes;
+ std::map<string, string> expected_package_prefixes;
if (!LoadExpectedPackagePrefixes(generation_options,
&expected_package_prefixes,
out_error)) {
@@ -1180,10 +1185,10 @@ void TextFormatDecodeData::AddString(int32 key,
for (vector<DataEntry>::const_iterator i = entries_.begin();
i != entries_.end(); ++i) {
if (i->first == key) {
- cerr << "error: duplicate key (" << key
+ std::cerr << "error: duplicate key (" << key
<< ") making TextFormat data, input: \"" << input_for_decode
- << "\", desired: \"" << desired_output << "\"." << endl;
- cerr.flush();
+ << "\", desired: \"" << desired_output << "\"." << std::endl;
+ std::cerr.flush();
abort();
}
}
@@ -1194,7 +1199,7 @@ void TextFormatDecodeData::AddString(int32 key,
}
string TextFormatDecodeData::Data() const {
- ostringstream data_stringstream;
+ std::ostringstream data_stringstream;
if (num_entries() > 0) {
io::OstreamOutputStream data_outputstream(&data_stringstream);
@@ -1335,18 +1340,18 @@ string DirectDecodeString(const string& str) {
string TextFormatDecodeData::DecodeDataForString(const string& input_for_decode,
const string& desired_output) {
if ((input_for_decode.size() == 0) || (desired_output.size() == 0)) {
- cerr << "error: got empty string for making TextFormat data, input: \""
+ std::cerr << "error: got empty string for making TextFormat data, input: \""
<< input_for_decode << "\", desired: \"" << desired_output << "\"."
- << endl;
- cerr.flush();
+ << std::endl;
+ std::cerr.flush();
abort();
}
if ((input_for_decode.find('\0') != string::npos) ||
(desired_output.find('\0') != string::npos)) {
- cerr << "error: got a null char in a string for making TextFormat data,"
+ std::cerr << "error: got a null char in a string for making TextFormat data,"
<< " input: \"" << CEscape(input_for_decode) << "\", desired: \""
- << CEscape(desired_output) << "\"." << endl;
- cerr.flush();
+ << CEscape(desired_output) << "\"." << std::endl;
+ std::cerr.flush();
abort();
}
@@ -1519,7 +1524,7 @@ void ImportWriter::AddFile(const FileDescriptor* file,
ParseFrameworkMappings();
}
- map<string, string>::iterator proto_lookup =
+ std::map<string, string>::iterator proto_lookup =
proto_file_to_framework_name_.find(file->name());
if (proto_lookup != proto_file_to_framework_name_.end()) {
other_framework_imports_.push_back(
@@ -1611,9 +1616,9 @@ void ImportWriter::ParseFrameworkMappings() {
string parse_error;
if (!ParseSimpleFile(named_framework_to_proto_path_mappings_path_,
&collector, &parse_error)) {
- cerr << "error parsing " << named_framework_to_proto_path_mappings_path_
- << " : " << parse_error << endl;
- cerr.flush();
+ std::cerr << "error parsing " << named_framework_to_proto_path_mappings_path_
+ << " : " << parse_error << std::endl;
+ std::cerr.flush();
}
}
@@ -1640,19 +1645,19 @@ bool ImportWriter::ProtoFrameworkCollector::ConsumeLine(
StringPiece proto_file(proto_file_list, start, offset - start);
StringPieceTrimWhitespace(&proto_file);
if (proto_file.size() != 0) {
- map<string, string>::iterator existing_entry =
+ std::map<string, string>::iterator existing_entry =
map_->find(proto_file.ToString());
if (existing_entry != map_->end()) {
- cerr << "warning: duplicate proto file reference, replacing framework entry for '"
+ std::cerr << "warning: duplicate proto file reference, replacing framework entry for '"
<< proto_file.ToString() << "' with '" << framework_name.ToString()
- << "' (was '" << existing_entry->second << "')." << endl;
- cerr.flush();
+ << "' (was '" << existing_entry->second << "')." << std::endl;
+ std::cerr.flush();
}
if (proto_file.find(' ') != StringPiece::npos) {
- cerr << "note: framework mapping file had a proto file with a space in, hopefully that isn't a missing comma: '"
- << proto_file.ToString() << "'" << endl;
- cerr.flush();
+ std::cerr << "note: framework mapping file had a proto file with a space in, hopefully that isn't a missing comma: '"
+ << proto_file.ToString() << "'" << std::endl;
+ std::cerr.flush();
}
(*map_)[proto_file.ToString()] = framework_name.ToString();
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_helpers.h b/src/google/protobuf/compiler/objectivec/objectivec_helpers.h
index c99262a1..daea7609 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_helpers.h
+++ b/src/google/protobuf/compiler/objectivec/objectivec_helpers.h
@@ -262,20 +262,20 @@ class LIBPROTOC_EXPORT ImportWriter {
private:
class ProtoFrameworkCollector : public LineConsumer {
public:
- ProtoFrameworkCollector(map<string, string>* inout_proto_file_to_framework_name)
+ ProtoFrameworkCollector(std::map<string, string>* inout_proto_file_to_framework_name)
: map_(inout_proto_file_to_framework_name) {}
virtual bool ConsumeLine(const StringPiece& line, string* out_error);
private:
- map<string, string>* map_;
+ std::map<string, string>* map_;
};
void ParseFrameworkMappings();
const string generate_for_named_framework_;
const string named_framework_to_proto_path_mappings_path_;
- map<string, string> proto_file_to_framework_name_;
+ std::map<string, string> proto_file_to_framework_name_;
bool need_to_parse_mapping_file_;
vector<string> protobuf_framework_imports_;
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_map_field.cc b/src/google/protobuf/compiler/objectivec/objectivec_map_field.cc
index 0bc9dc10..bcaf5709 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_map_field.cc
+++ b/src/google/protobuf/compiler/objectivec/objectivec_map_field.cc
@@ -162,7 +162,7 @@ void MapFieldGenerator::FinishInitialization(void) {
}
void MapFieldGenerator::DetermineForwardDeclarations(
- set<string>* fwd_decls) const {
+ std::set<string>* fwd_decls) const {
RepeatedFieldGenerator::DetermineForwardDeclarations(fwd_decls);
const FieldDescriptor* value_descriptor =
descriptor_->message_type()->FindFieldByName("value");
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_map_field.h b/src/google/protobuf/compiler/objectivec/objectivec_map_field.h
index bc68a682..6664d849 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_map_field.h
+++ b/src/google/protobuf/compiler/objectivec/objectivec_map_field.h
@@ -51,7 +51,7 @@ class MapFieldGenerator : public RepeatedFieldGenerator {
MapFieldGenerator(const FieldDescriptor* descriptor, const Options& options);
virtual ~MapFieldGenerator();
- virtual void DetermineForwardDeclarations(set<string>* fwd_decls) const;
+ virtual void DetermineForwardDeclarations(std::set<string>* fwd_decls) const;
private:
scoped_ptr<FieldGenerator> value_field_generator_;
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_message.cc b/src/google/protobuf/compiler/objectivec/objectivec_message.cc
index e0bd3dac..4f22e290 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_message.cc
+++ b/src/google/protobuf/compiler/objectivec/objectivec_message.cc
@@ -156,7 +156,7 @@ const FieldDescriptor** SortFieldsByNumber(const Descriptor* descriptor) {
for (int i = 0; i < descriptor->field_count(); i++) {
fields[i] = descriptor->field(i);
}
- sort(fields, fields + descriptor->field_count(), FieldOrderingByNumber());
+ std::sort(fields, fields + descriptor->field_count(), FieldOrderingByNumber());
return fields;
}
@@ -168,7 +168,7 @@ const FieldDescriptor** SortFieldsByStorageSize(const Descriptor* descriptor) {
for (int i = 0; i < descriptor->field_count(); i++) {
fields[i] = descriptor->field(i);
}
- sort(fields, fields + descriptor->field_count(),
+ std::sort(fields, fields + descriptor->field_count(),
FieldOrderingByStorageSize());
return fields;
}
@@ -233,7 +233,7 @@ void MessageGenerator::GenerateStaticVariablesInitialization(
}
}
-void MessageGenerator::DetermineForwardDeclarations(set<string>* fwd_decls) {
+void MessageGenerator::DetermineForwardDeclarations(std::set<string>* fwd_decls) {
if (!IsMapEntryMessage(descriptor_)) {
for (int i = 0; i < descriptor_->field_count(); i++) {
const FieldDescriptor* fieldDescriptor = descriptor_->field(i);
@@ -430,7 +430,7 @@ void MessageGenerator::GenerateSource(io::Printer* printer) {
sorted_extensions.push_back(descriptor_->extension_range(i));
}
- sort(sorted_extensions.begin(), sorted_extensions.end(),
+ std::sort(sorted_extensions.begin(), sorted_extensions.end(),
ExtensionRangeOrdering());
// Assign has bits:
@@ -514,7 +514,7 @@ void MessageGenerator::GenerateSource(io::Printer* printer) {
" };\n");
}
- map<string, string> vars;
+ std::map<string, string> vars;
vars["classname"] = class_name_;
vars["rootclassname"] = root_classname_;
vars["fields"] = has_fields ? "fields" : "NULL";
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_message.h b/src/google/protobuf/compiler/objectivec/objectivec_message.h
index 0fb78bc0..8f317ac0 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_message.h
+++ b/src/google/protobuf/compiler/objectivec/objectivec_message.h
@@ -64,7 +64,7 @@ class MessageGenerator {
void GenerateMessageHeader(io::Printer* printer);
void GenerateSource(io::Printer* printer);
void GenerateExtensionRegistrationSource(io::Printer* printer);
- void DetermineForwardDeclarations(set<string>* fwd_decls);
+ void DetermineForwardDeclarations(std::set<string>* fwd_decls);
// Checks if the message or a nested message includes a oneof definition.
bool IncludesOneOfDefinition() const;
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_message_field.cc b/src/google/protobuf/compiler/objectivec/objectivec_message_field.cc
index d6ccd6d1..699d25b3 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_message_field.cc
+++ b/src/google/protobuf/compiler/objectivec/objectivec_message_field.cc
@@ -45,7 +45,7 @@ namespace objectivec {
namespace {
void SetMessageVariables(const FieldDescriptor* descriptor,
- map<string, string>* variables) {
+ std::map<string, string>* variables) {
const string& message_type = ClassName(descriptor->message_type());
(*variables)["type"] = message_type;
(*variables)["containing_class"] = ClassName(descriptor->containing_type());
@@ -67,7 +67,7 @@ MessageFieldGenerator::MessageFieldGenerator(const FieldDescriptor* descriptor,
MessageFieldGenerator::~MessageFieldGenerator() {}
void MessageFieldGenerator::DetermineForwardDeclarations(
- set<string>* fwd_decls) const {
+ std::set<string>* fwd_decls) const {
ObjCObjFieldGenerator::DetermineForwardDeclarations(fwd_decls);
// Class name is already in "storage_type".
fwd_decls->insert("@class " + variable("storage_type"));
@@ -95,7 +95,7 @@ RepeatedMessageFieldGenerator::RepeatedMessageFieldGenerator(
RepeatedMessageFieldGenerator::~RepeatedMessageFieldGenerator() {}
void RepeatedMessageFieldGenerator::DetermineForwardDeclarations(
- set<string>* fwd_decls) const {
+ std::set<string>* fwd_decls) const {
RepeatedFieldGenerator::DetermineForwardDeclarations(fwd_decls);
// Class name is already in "storage_type".
fwd_decls->insert("@class " + variable("storage_type"));
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_message_field.h b/src/google/protobuf/compiler/objectivec/objectivec_message_field.h
index d2dba153..50f4b6d4 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_message_field.h
+++ b/src/google/protobuf/compiler/objectivec/objectivec_message_field.h
@@ -51,7 +51,7 @@ class MessageFieldGenerator : public ObjCObjFieldGenerator {
virtual bool WantsHasProperty(void) const;
public:
- virtual void DetermineForwardDeclarations(set<string>* fwd_decls) const;
+ virtual void DetermineForwardDeclarations(std::set<string>* fwd_decls) const;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageFieldGenerator);
@@ -67,7 +67,7 @@ class RepeatedMessageFieldGenerator : public RepeatedFieldGenerator {
virtual ~RepeatedMessageFieldGenerator();
public:
- virtual void DetermineForwardDeclarations(set<string>* fwd_decls) const;
+ virtual void DetermineForwardDeclarations(std::set<string>* fwd_decls) const;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedMessageFieldGenerator);
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_oneof.h b/src/google/protobuf/compiler/objectivec/objectivec_oneof.h
index 3d9df4db..ff353a6c 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_oneof.h
+++ b/src/google/protobuf/compiler/objectivec/objectivec_oneof.h
@@ -67,7 +67,7 @@ class OneofGenerator {
private:
const OneofDescriptor* descriptor_;
- map<string, string> variables_;
+ std::map<string, string> variables_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(OneofGenerator);
};
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_primitive_field.cc b/src/google/protobuf/compiler/objectivec/objectivec_primitive_field.cc
index d49350f4..aa8ac324 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_primitive_field.cc
+++ b/src/google/protobuf/compiler/objectivec/objectivec_primitive_field.cc
@@ -118,7 +118,7 @@ const char* PrimitiveArrayTypeName(const FieldDescriptor* descriptor) {
}
void SetPrimitiveVariables(const FieldDescriptor* descriptor,
- map<string, string>* variables) {
+ std::map<string, string>* variables) {
std::string primitive_name = PrimitiveTypeName(descriptor);
(*variables)["type"] = primitive_name;
(*variables)["storage_type"] = primitive_name;
diff --git a/src/google/protobuf/compiler/parser.cc b/src/google/protobuf/compiler/parser.cc
index 09c7a2b6..03d05ad4 100644
--- a/src/google/protobuf/compiler/parser.cc
+++ b/src/google/protobuf/compiler/parser.cc
@@ -249,11 +249,11 @@ bool Parser::ConsumeNumber(double* output, const char* error) {
input_->Next();
return true;
} else if (LookingAt("inf")) {
- *output = numeric_limits<double>::infinity();
+ *output = std::numeric_limits<double>::infinity();
input_->Next();
return true;
} else if (LookingAt("nan")) {
- *output = numeric_limits<double>::quiet_NaN();
+ *output = std::numeric_limits<double>::quiet_NaN();
input_->Next();
return true;
} else {
@@ -282,7 +282,7 @@ bool Parser::TryConsumeEndOfDeclaration(
const char* text, const LocationRecorder* location) {
if (LookingAt(text)) {
string leading, trailing;
- vector<string> detached;
+ std::vector<string> detached;
input_->NextWithComments(&trailing, &detached, &leading);
// Save the leading comments for next time, and recall the leading comments
@@ -404,7 +404,7 @@ void Parser::LocationRecorder::RecordLegacyLocation(const Message* descriptor,
void Parser::LocationRecorder::AttachComments(
string* leading, string* trailing,
- vector<string>* detached_comments) const {
+ std::vector<string>* detached_comments) const {
GOOGLE_CHECK(!location_->has_leading_comments());
GOOGLE_CHECK(!location_->has_trailing_comments());
@@ -487,7 +487,7 @@ bool Parser::ValidateEnum(const EnumDescriptorProto* proto) {
return false;
}
- set<int> used_values;
+ std::set<int> used_values;
bool has_duplicates = false;
for (int i = 0; i < proto->value_size(); ++i) {
const EnumValueDescriptorProto enum_value = proto->value(i);
@@ -664,7 +664,7 @@ bool Parser::ParseMessageDefinition(
namespace {
-const int kMaxExtensionRangeSentinel = -1;
+const int kMaxRangeSentinel = -1;
bool IsMessageSetWireFormatMessage(const DescriptorProto& message) {
const MessageOptions& options = message.options();
@@ -688,12 +688,27 @@ void AdjustExtensionRangesWithMaxEndNumber(DescriptorProto* message) {
kint32max :
FieldDescriptor::kMaxNumber + 1;
for (int i = 0; i < message->extension_range_size(); ++i) {
- if (message->extension_range(i).end() == kMaxExtensionRangeSentinel) {
+ if (message->extension_range(i).end() == kMaxRangeSentinel) {
message->mutable_extension_range(i)->set_end(max_extension_number);
}
}
}
+// Modifies any reserved ranges that specified 'max' as the end of the
+// reserved range, and sets them to the type-specific maximum. The actual max
+// tag number can only be determined after all options have been parsed.
+void AdjustReservedRangesWithMaxEndNumber(DescriptorProto* message) {
+ const bool is_message_set = IsMessageSetWireFormatMessage(*message);
+ const int max_field_number = is_message_set ?
+ kint32max :
+ FieldDescriptor::kMaxNumber + 1;
+ for (int i = 0; i < message->reserved_range_size(); ++i) {
+ if (message->reserved_range(i).end() == kMaxRangeSentinel) {
+ message->mutable_reserved_range(i)->set_end(max_field_number);
+ }
+ }
+}
+
} // namespace
bool Parser::ParseMessageBlock(DescriptorProto* message,
@@ -717,6 +732,9 @@ bool Parser::ParseMessageBlock(DescriptorProto* message,
if (message->extension_range_size() > 0) {
AdjustExtensionRangesWithMaxEndNumber(message);
}
+ if (message->reserved_range_size() > 0) {
+ AdjustReservedRangesWithMaxEndNumber(message);
+ }
return true;
}
@@ -1373,7 +1391,7 @@ bool Parser::ParseOption(Message* options,
value_location.AddPath(
UninterpretedOption::kNegativeIntValueFieldNumber);
uninterpreted_option->set_negative_int_value(
- -static_cast<int64>(value));
+ static_cast<int64>(-value));
} else {
value_location.AddPath(
UninterpretedOption::kPositiveIntValueFieldNumber);
@@ -1429,6 +1447,8 @@ bool Parser::ParseExtensions(DescriptorProto* message,
// Parse the declaration.
DO(Consume("extensions"));
+ int old_range_size = message->extension_range_size();
+
do {
// Note that kExtensionRangeFieldNumber was already pushed by the parent.
LocationRecorder location(extensions_location,
@@ -1455,7 +1475,7 @@ bool Parser::ParseExtensions(DescriptorProto* message,
// Set to the sentinel value - 1 since we increment the value below.
// The actual value of the end of the range should be set with
// AdjustExtensionRangesWithMaxEndNumber.
- end = kMaxExtensionRangeSentinel - 1;
+ end = kMaxRangeSentinel - 1;
} else {
DO(ConsumeInteger(&end, "Expected integer."));
}
@@ -1475,12 +1495,36 @@ bool Parser::ParseExtensions(DescriptorProto* message,
range->set_end(end);
} while (TryConsume(","));
+ if (LookingAt("[")) {
+ LocationRecorder location(
+ extensions_location,
+ DescriptorProto::ExtensionRange::kOptionsFieldNumber);
+
+ DO(Consume("["));
+
+ // Parse extension range options in the first range.
+ ExtensionRangeOptions* options =
+ message->mutable_extension_range(old_range_size)->mutable_options();
+ do {
+ DO(ParseOption(options, location, containing_file, OPTION_ASSIGNMENT));
+ } while (TryConsume(","));
+
+ DO(Consume("]"));
+
+ // Then copy the extension range options to all of the other ranges we've
+ // parsed.
+ for (int i = old_range_size + 1; i < message->extension_range_size(); i++) {
+ message->mutable_extension_range(i)->mutable_options()
+ ->CopyFrom(*options);
+ }
+ }
+
DO(ConsumeEndOfDeclaration(";", &extensions_location));
return true;
}
-// This is similar to extension range parsing, except that "max" is not
-// supported, and accepts field name literals.
+// This is similar to extension range parsing, except that it accepts field
+// name literals.
bool Parser::ParseReserved(DescriptorProto* message,
const LocationRecorder& message_location) {
// Parse the declaration.
@@ -1496,7 +1540,6 @@ bool Parser::ParseReserved(DescriptorProto* message,
}
}
-
bool Parser::ParseReservedNames(DescriptorProto* message,
const LocationRecorder& parent_location) {
do {
@@ -1528,7 +1571,14 @@ bool Parser::ParseReservedNumbers(DescriptorProto* message,
if (TryConsume("to")) {
LocationRecorder end_location(
location, DescriptorProto::ReservedRange::kEndFieldNumber);
- DO(ConsumeInteger(&end, "Expected integer."));
+ if (TryConsume("max")) {
+ // Set to the sentinel value - 1 since we increment the value below.
+ // The actual value of the end of the range should be set with
+ // AdjustExtensionRangesWithMaxEndNumber.
+ end = kMaxRangeSentinel - 1;
+ } else {
+ DO(ConsumeInteger(&end, "Expected integer."));
+ }
} else {
LocationRecorder end_location(
location, DescriptorProto::ReservedRange::kEndFieldNumber);
@@ -1550,6 +1600,81 @@ bool Parser::ParseReservedNumbers(DescriptorProto* message,
return true;
}
+bool Parser::ParseReserved(EnumDescriptorProto* message,
+ const LocationRecorder& message_location) {
+ // Parse the declaration.
+ DO(Consume("reserved"));
+ if (LookingAtType(io::Tokenizer::TYPE_STRING)) {
+ LocationRecorder location(message_location,
+ DescriptorProto::kReservedNameFieldNumber);
+ return ParseReservedNames(message, location);
+ } else {
+ LocationRecorder location(message_location,
+ DescriptorProto::kReservedRangeFieldNumber);
+ return ParseReservedNumbers(message, location);
+ }
+}
+
+bool Parser::ParseReservedNames(EnumDescriptorProto* message,
+ const LocationRecorder& parent_location) {
+ do {
+ LocationRecorder location(parent_location, message->reserved_name_size());
+ DO(ConsumeString(message->add_reserved_name(), "Expected enum value."));
+ } while (TryConsume(","));
+ DO(ConsumeEndOfDeclaration(";", &parent_location));
+ return true;
+}
+
+bool Parser::ParseReservedNumbers(EnumDescriptorProto* message,
+ const LocationRecorder& parent_location) {
+ bool first = true;
+ do {
+ LocationRecorder location(parent_location, message->reserved_range_size());
+
+ EnumDescriptorProto::EnumReservedRange* range =
+ message->add_reserved_range();
+ int start, end;
+ io::Tokenizer::Token start_token;
+ {
+ LocationRecorder start_location(
+ location, EnumDescriptorProto::EnumReservedRange::kStartFieldNumber);
+ start_token = input_->current();
+ DO(ConsumeSignedInteger(&start, (first ?
+ "Expected enum value or number range." :
+ "Expected enum number range.")));
+ }
+
+ if (TryConsume("to")) {
+ LocationRecorder end_location(
+ location, EnumDescriptorProto::EnumReservedRange::kEndFieldNumber);
+ if (TryConsume("max")) {
+ // This is in the enum descriptor path, which doesn't have the message
+ // set duality to fix up, so it doesn't integrate with the sentinel.
+
+ // Evaluate 'max' to INT_MAX - 1 so that incrementing to create the
+ // exclusive range end doesn't cause an overflow.
+ // Note, this prevents reserving the actual INT_MAX enum value.
+ end = INT_MAX;
+ } else {
+ DO(ConsumeSignedInteger(&end, "Expected integer."));
+ }
+ } else {
+ LocationRecorder end_location(
+ location, EnumDescriptorProto::EnumReservedRange::kEndFieldNumber);
+ end_location.StartAt(start_token);
+ end_location.EndAt(start_token);
+ end = start;
+ }
+
+ range->set_start(start);
+ range->set_end(end);
+ first = false;
+ } while (TryConsume(","));
+
+ DO(ConsumeEndOfDeclaration(";", &parent_location));
+ return true;
+}
+
bool Parser::ParseExtend(RepeatedPtrField<FieldDescriptorProto>* extensions,
RepeatedPtrField<DescriptorProto>* messages,
const LocationRecorder& parent_location,
@@ -1730,6 +1855,8 @@ bool Parser::ParseEnumStatement(EnumDescriptorProto* enum_type,
EnumDescriptorProto::kOptionsFieldNumber);
return ParseOption(enum_type->mutable_options(), location,
containing_file, OPTION_STATEMENT);
+ } else if (LookingAt("reserved")) {
+ return ParseReserved(enum_type, enum_location);
} else {
LocationRecorder location(enum_location,
EnumDescriptorProto::kValueFieldNumber, enum_type->value_size());
@@ -2089,7 +2216,7 @@ bool SourceLocationTable::Find(
const Message* descriptor,
DescriptorPool::ErrorCollector::ErrorLocation location,
int* line, int* column) const {
- const pair<int, int>* result =
+ const std::pair<int, int>* result =
FindOrNull(location_map_, std::make_pair(descriptor, location));
if (result == NULL) {
*line = -1;
@@ -2116,4 +2243,5 @@ void SourceLocationTable::Clear() {
} // namespace compiler
} // namespace protobuf
+
} // namespace google
diff --git a/src/google/protobuf/compiler/parser.h b/src/google/protobuf/compiler/parser.h
index dd8b6586..33b4c700 100644
--- a/src/google/protobuf/compiler/parser.h
+++ b/src/google/protobuf/compiler/parser.h
@@ -371,6 +371,12 @@ class LIBPROTOBUF_EXPORT Parser {
const LocationRecorder& parent_location);
bool ParseReservedNumbers(DescriptorProto* message,
const LocationRecorder& parent_location);
+ bool ParseReserved(EnumDescriptorProto* message,
+ const LocationRecorder& message_location);
+ bool ParseReservedNames(EnumDescriptorProto* message,
+ const LocationRecorder& parent_location);
+ bool ParseReservedNumbers(EnumDescriptorProto* message,
+ const LocationRecorder& parent_location);
// Parse an "extend" declaration. (See also comments for
// ParseMessageField().)
diff --git a/src/google/protobuf/compiler/parser_unittest.cc b/src/google/protobuf/compiler/parser_unittest.cc
index 20140f8e..9b59842e 100644
--- a/src/google/protobuf/compiler/parser_unittest.cc
+++ b/src/google/protobuf/compiler/parser_unittest.cc
@@ -42,14 +42,13 @@
#include <google/protobuf/compiler/parser.h>
+#include <google/protobuf/unittest.pb.h>
+#include <google/protobuf/unittest_custom_options.pb.h>
#include <google/protobuf/io/tokenizer.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/descriptor.pb.h>
-#include <google/protobuf/wire_format.h>
#include <google/protobuf/text_format.h>
-#include <google/protobuf/unittest.pb.h>
-#include <google/protobuf/unittest_custom_options.pb.h>
-#include <google/protobuf/stubs/strutil.h>
+#include <google/protobuf/wire_format.h>
#include <google/protobuf/stubs/substitute.h>
#include <google/protobuf/stubs/map_util.h>
@@ -664,7 +663,7 @@ TEST_F(ParseMessageTest, ReservedRange) {
ExpectParsesTo(
"message TestMessage {\n"
" required int32 foo = 1;\n"
- " reserved 2, 15, 9 to 11, 3;\n"
+ " reserved 2, 15, 9 to 11, 3, 20 to max;\n"
"}\n",
"message_type {"
@@ -674,6 +673,29 @@ TEST_F(ParseMessageTest, ReservedRange) {
" reserved_range { start:15 end:16 }"
" reserved_range { start:9 end:12 }"
" reserved_range { start:3 end:4 }"
+ " reserved_range { start:20 end:536870912 }"
+ "}");
+}
+
+TEST_F(ParseMessageTest, ReservedRangeOnMessageSet) {
+ ExpectParsesTo(
+ "message TestMessage {\n"
+ " option message_set_wire_format = true;\n"
+ " reserved 20 to max;\n"
+ "}\n",
+
+ "message_type {"
+ " name: \"TestMessage\""
+ " options {"
+ " uninterpreted_option {"
+ " name {"
+ " name_part: \"message_set_wire_format\""
+ " is_extension: false"
+ " }"
+ " identifier_value: \"true\""
+ " }"
+ " }"
+ " reserved_range { start:20 end:2147483647 }"
"}");
}
@@ -704,6 +726,30 @@ TEST_F(ParseMessageTest, ExtensionRange) {
"}");
}
+TEST_F(ParseMessageTest, ExtensionRangeWithOptions) {
+ ExpectParsesTo(
+ "message TestMessage {\n"
+ " extensions 10 to 19 [(i) = 5];\n"
+ "}\n",
+
+ "message_type {"
+ " name: \"TestMessage\""
+ " extension_range {"
+ " start:10"
+ " end:20"
+ " options {"
+ " uninterpreted_option {"
+ " name {"
+ " name_part: \"i\""
+ " is_extension: true"
+ " }"
+ " positive_int_value: 5"
+ " }"
+ " }"
+ " }"
+ "}");
+}
+
TEST_F(ParseMessageTest, CompoundExtensionRange) {
ExpectParsesTo(
"message TestMessage {\n"
@@ -720,6 +766,82 @@ TEST_F(ParseMessageTest, CompoundExtensionRange) {
"}");
}
+TEST_F(ParseMessageTest, CompoundExtensionRangeWithOptions) {
+ ExpectParsesTo(
+ "message TestMessage {\n"
+ " extensions 2, 15, 9 to 11, 100 to max, 3 [(i) = 5];\n"
+ "}\n",
+
+ "message_type {"
+ " name: \"TestMessage\""
+ " extension_range {"
+ " start:2"
+ " end:3"
+ " options {"
+ " uninterpreted_option {"
+ " name {"
+ " name_part: \"i\""
+ " is_extension: true"
+ " }"
+ " positive_int_value: 5"
+ " }"
+ " }"
+ " }"
+ " extension_range {"
+ " start:15"
+ " end:16"
+ " options {"
+ " uninterpreted_option {"
+ " name {"
+ " name_part: \"i\""
+ " is_extension: true"
+ " }"
+ " positive_int_value: 5"
+ " }"
+ " }"
+ " }"
+ " extension_range {"
+ " start:9"
+ " end:12"
+ " options {"
+ " uninterpreted_option {"
+ " name {"
+ " name_part: \"i\""
+ " is_extension: true"
+ " }"
+ " positive_int_value: 5"
+ " }"
+ " }"
+ " }"
+ " extension_range {"
+ " start:100"
+ " end:536870912"
+ " options {"
+ " uninterpreted_option {"
+ " name {"
+ " name_part: \"i\""
+ " is_extension: true"
+ " }"
+ " positive_int_value: 5"
+ " }"
+ " }"
+ " }"
+ " extension_range {"
+ " start:3"
+ " end:4"
+ " options {"
+ " uninterpreted_option {"
+ " name {"
+ " name_part: \"i\""
+ " is_extension: true"
+ " }"
+ " positive_int_value: 5"
+ " }"
+ " }"
+ " }"
+ "}");
+}
+
TEST_F(ParseMessageTest, LargerMaxForMessageSetWireFormatMessages) {
// Messages using the message_set_wire_format option can accept larger
// extension numbers, as the numbers are not encoded as int32 field values
@@ -872,6 +994,42 @@ TEST_F(ParseEnumTest, ValueOptions) {
"}");
}
+TEST_F(ParseEnumTest, ReservedRange) {
+ ExpectParsesTo(
+ "enum TestEnum {\n"
+ " FOO = 0;\n"
+ " reserved -2147483648, -6 to -4, -1 to 1, 2, 15, 9 to 11, 3, 20 to max;\n"
+ "}\n",
+
+ "enum_type {"
+ " name: \"TestEnum\""
+ " value { name:\"FOO\" number:0 }"
+ " reserved_range { start:-2147483648 end:-2147483648 }"
+ " reserved_range { start:-6 end:-4 }"
+ " reserved_range { start:-1 end:1 }"
+ " reserved_range { start:2 end:2 }"
+ " reserved_range { start:15 end:15 }"
+ " reserved_range { start:9 end:11 }"
+ " reserved_range { start:3 end:3 }"
+ " reserved_range { start:20 end:2147483647 }"
+ "}");
+}
+
+TEST_F(ParseEnumTest, ReservedNames) {
+ ExpectParsesTo(
+ "enum TestEnum {\n"
+ " FOO = 0;\n"
+ " reserved \"foo\", \"bar\";\n"
+ "}\n",
+
+ "enum_type {"
+ " name: \"TestEnum\""
+ " value { name:\"FOO\" number:0 }"
+ " reserved_name: \"foo\""
+ " reserved_name: \"bar\""
+ "}");
+}
+
// ===================================================================
typedef ParserTest ParseServiceTest;
@@ -1366,15 +1524,60 @@ TEST_F(ParseErrorTest, EnumValueMissingNumber) {
"1:5: Missing numeric value for enum constant.\n");
}
+TEST_F(ParseErrorTest, EnumReservedStandaloneMaxNotAllowed) {
+ ExpectHasErrors(
+ "enum TestEnum {\n"
+ " FOO = 1;\n"
+ " reserved max;\n"
+ "}\n",
+ "2:11: Expected enum value or number range.\n");
+}
+
+TEST_F(ParseErrorTest, EnumReservedMixNameAndNumber) {
+ ExpectHasErrors(
+ "enum TestEnum {\n"
+ " FOO = 1;\n"
+ " reserved 10, \"foo\";\n"
+ "}\n",
+ "2:15: Expected enum number range.\n");
+}
+
+TEST_F(ParseErrorTest, EnumReservedPositiveNumberOutOfRange) {
+ ExpectHasErrors(
+ "enum TestEnum {\n"
+ "FOO = 1;\n"
+ " reserved 2147483648;\n"
+ "}\n",
+ "2:11: Integer out of range.\n");
+}
+
+TEST_F(ParseErrorTest, EnumReservedNegativeNumberOutOfRange) {
+ ExpectHasErrors(
+ "enum TestEnum {\n"
+ "FOO = 1;\n"
+ " reserved -2147483649;\n"
+ "}\n",
+ "2:12: Integer out of range.\n");
+}
+
+TEST_F(ParseErrorTest, EnumReservedMissingQuotes) {
+ ExpectHasErrors(
+ "enum TestEnum {\n"
+ " FOO = 1;\n"
+ " reserved foo;\n"
+ "}\n",
+ "2:11: Expected enum value or number range.\n");
+}
+
// -------------------------------------------------------------------
// Reserved field number errors
-TEST_F(ParseErrorTest, ReservedMaxNotAllowed) {
+TEST_F(ParseErrorTest, ReservedStandaloneMaxNotAllowed) {
ExpectHasErrors(
"message Foo {\n"
- " reserved 10 to max;\n"
+ " reserved max;\n"
"}\n",
- "1:17: Expected integer.\n");
+ "1:11: Expected field name or number range.\n");
}
TEST_F(ParseErrorTest, ReservedMixNameAndNumber) {
@@ -1393,6 +1596,23 @@ TEST_F(ParseErrorTest, ReservedMissingQuotes) {
"1:11: Expected field name or number range.\n");
}
+TEST_F(ParseErrorTest, ReservedNegativeNumber) {
+ ExpectHasErrors(
+ "message Foo {\n"
+ " reserved -10;\n"
+ "}\n",
+ "1:11: Expected field name or number range.\n");
+}
+
+TEST_F(ParseErrorTest, ReservedNumberOutOfRange) {
+ ExpectHasErrors(
+ "message Foo {\n"
+ " reserved 2147483648;\n"
+ "}\n",
+ "1:11: Integer out of range.\n");
+}
+
+
// -------------------------------------------------------------------
// Service errors
diff --git a/src/google/protobuf/compiler/php/php_generator.cc b/src/google/protobuf/compiler/php/php_generator.cc
index be2739ff..e4364ac2 100644
--- a/src/google/protobuf/compiler/php/php_generator.cc
+++ b/src/google/protobuf/compiler/php/php_generator.cc
@@ -49,6 +49,31 @@ const std::string kDescriptorMetadataFile =
"GPBMetadata/Google/Protobuf/Internal/Descriptor.php";
const std::string kDescriptorDirName = "Google/Protobuf/Internal";
const std::string kDescriptorPackageName = "Google\\Protobuf\\Internal";
+const char* const kReservedNames[] = {
+ "abstract", "and", "array", "as", "break",
+ "callable", "case", "catch", "class", "clone",
+ "const", "continue", "declare", "default", "die",
+ "do", "echo", "else", "elseif", "empty",
+ "enddeclare", "endfor", "endforeach", "endif", "endswitch",
+ "endwhile", "eval", "exit", "extends", "final",
+ "for", "foreach", "function", "global", "goto",
+ "if", "implements", "include", "include_once", "instanceof",
+ "insteadof", "interface", "isset", "list", "namespace",
+ "new", "or", "print", "private", "protected",
+ "public", "require", "require_once", "return", "static",
+ "switch", "throw", "trait", "try", "unset",
+ "use", "var", "while", "xor", "int",
+ "float", "bool", "string", "true", "false",
+ "null", "void", "iterable"};
+const char* const kValidConstantNames[] = {
+ "int", "float", "bool", "string", "true",
+ "false", "null", "void", "iterable",
+};
+const int kReservedNamesSize = 73;
+const int kValidConstantNamesSize = 9;
+const int kFieldSetter = 1;
+const int kFieldGetter = 2;
+const int kFieldProperty = 3;
namespace google {
namespace protobuf {
@@ -69,12 +94,18 @@ std::string EscapeDollor(const string& to_escape);
std::string BinaryToHex(const string& binary);
void Indent(io::Printer* printer);
void Outdent(io::Printer* printer);
-void GenerateMessageDocComment(io::Printer* printer, const Descriptor* message);
-void GenerateFieldDocComment(io::Printer* printer,
- const FieldDescriptor* field);
-void GenerateEnumDocComment(io::Printer* printer, const EnumDescriptor* enum_);
+void GenerateMessageDocComment(io::Printer* printer, const Descriptor* message,
+ int is_descriptor);
+void GenerateFieldDocComment(io::Printer* printer, const FieldDescriptor* field,
+ int is_descriptor, int function_type);
+void GenerateEnumDocComment(io::Printer* printer, const EnumDescriptor* enum_,
+ int is_descriptor);
void GenerateEnumValueDocComment(io::Printer* printer,
const EnumValueDescriptor* value);
+void GenerateServiceDocComment(io::Printer* printer,
+ const ServiceDescriptor* service);
+void GenerateServiceMethodDocComment(io::Printer* printer,
+ const MethodDescriptor* method);
std::string RenameEmpty(const std::string& name) {
if (name == "Empty") {
@@ -84,29 +115,6 @@ std::string RenameEmpty(const std::string& name) {
}
}
-std::string MessagePrefix(const Descriptor* message) {
- // Empty cannot be php class name.
- if (message->name() == "Empty" &&
- message->file()->package() == "google.protobuf") {
- return "GPB";
- } else {
- return "";
- }
-}
-
-std::string MessageName(const Descriptor* message, bool is_descriptor) {
- string message_name = message->name();
- const Descriptor* descriptor = message->containing_type();
- while (descriptor != NULL) {
- message_name = descriptor->name() + '_' + message_name;
- descriptor = descriptor->containing_type();
- }
- message_name = MessagePrefix(message) + message_name;
-
- return PhpName(message->file()->package(), is_descriptor) + '\\' +
- message_name;
-}
-
std::string MessageFullName(const Descriptor* message, bool is_descriptor) {
if (is_descriptor) {
return StringReplace(message->full_name(),
@@ -127,19 +135,100 @@ std::string EnumFullName(const EnumDescriptor* envm, bool is_descriptor) {
}
}
-std::string EnumClassName(const EnumDescriptor* envm) {
- string enum_class_name = envm->name();
- const Descriptor* descriptor = envm->containing_type();
- while (descriptor != NULL) {
- enum_class_name = descriptor->name() + '_' + enum_class_name;
- descriptor = descriptor->containing_type();
+template <typename DescriptorType>
+std::string ClassNamePrefix(const string& classname,
+ const DescriptorType* desc) {
+ const string& prefix = (desc->file()->options()).php_class_prefix();
+ if (prefix != "") {
+ return prefix;
+ }
+
+ bool is_reserved = false;
+
+ string lower = classname;
+ transform(lower.begin(), lower.end(), lower.begin(), ::tolower);
+
+ for (int i = 0; i < kReservedNamesSize; i++) {
+ if (lower == kReservedNames[i]) {
+ is_reserved = true;
+ break;
+ }
+ }
+
+ if (is_reserved) {
+ if (desc->file()->package() == "google.protobuf") {
+ return "GPB";
+ } else {
+ return "PB";
+ }
}
- return enum_class_name;
+
+ return "";
}
-std::string EnumName(const EnumDescriptor* envm, bool is_descriptor) {
- string enum_name = EnumClassName(envm);
- return PhpName(envm->file()->package(), is_descriptor) + '\\' + enum_name;
+std::string ConstantNamePrefix(const string& classname) {
+ bool is_reserved = false;
+
+ string lower = classname;
+ transform(lower.begin(), lower.end(), lower.begin(), ::tolower);
+
+ for (int i = 0; i < kReservedNamesSize; i++) {
+ if (lower == kReservedNames[i]) {
+ is_reserved = true;
+ break;
+ }
+ }
+
+ for (int i = 0; i < kValidConstantNamesSize; i++) {
+ if (lower == kValidConstantNames[i]) {
+ is_reserved = false;
+ break;
+ }
+ }
+
+ if (is_reserved) {
+ return "PB";
+ }
+
+ return "";
+}
+
+template <typename DescriptorType>
+std::string NamespacedName(const string& classname,
+ const DescriptorType* desc, bool is_descriptor) {
+ if (desc->file()->options().has_php_namespace()) {
+ const string& php_namespace = desc->file()->options().php_namespace();
+ if (php_namespace != "") {
+ return php_namespace + '\\' + classname;
+ } else {
+ return classname;
+ }
+ }
+
+ if (desc->file()->package() == "") {
+ return classname;
+ } else {
+ return PhpName(desc->file()->package(), is_descriptor) + '\\' +
+ classname;
+ }
+}
+
+template <typename DescriptorType>
+std::string FullClassName(const DescriptorType* desc, bool is_descriptor) {
+ string classname = desc->name();
+ const Descriptor* containing = desc->containing_type();
+ while (containing != NULL) {
+ classname = containing->name() + '_' + classname;
+ containing = containing->containing_type();
+ }
+ classname = ClassNamePrefix(classname, desc) + classname;
+ return NamespacedName(classname, desc, is_descriptor);
+}
+
+std::string FullClassName(const ServiceDescriptor* desc, bool is_descriptor) {
+ string classname = desc->name();
+ classname = ClassNamePrefix(classname, desc) + classname;
+ return NamespacedName(classname, desc, is_descriptor);
}
std::string PhpName(const std::string& full_name, bool is_descriptor) {
@@ -227,7 +316,7 @@ std::string GeneratedMetadataFileName(const std::string& proto_file,
std::string GeneratedMessageFileName(const Descriptor* message,
bool is_descriptor) {
- std::string result = MessageName(message, is_descriptor);
+ std::string result = FullClassName(message, is_descriptor);
for (int i = 0; i < result.size(); i++) {
if (result[i] == '\\') {
result[i] = '/';
@@ -238,7 +327,18 @@ std::string GeneratedMessageFileName(const Descriptor* message,
std::string GeneratedEnumFileName(const EnumDescriptor* en,
bool is_descriptor) {
- std::string result = EnumName(en, is_descriptor);
+ std::string result = FullClassName(en, is_descriptor);
+ for (int i = 0; i < result.size(); i++) {
+ if (result[i] == '\\') {
+ result[i] = '/';
+ }
+ }
+ return result + ".php";
+}
+
+std::string GeneratedServiceFileName(const ServiceDescriptor* service,
+ bool is_descriptor) {
+ std::string result = FullClassName(service, is_descriptor) + "Interface";
for (int i = 0; i < result.size(); i++) {
if (result[i] == '\\') {
result[i] = '/';
@@ -286,6 +386,87 @@ std::string TypeName(const FieldDescriptor* field) {
}
}
+std::string PhpSetterTypeName(const FieldDescriptor* field, bool is_descriptor) {
+ if (field->is_map()) {
+ return "array|\\Google\\Protobuf\\Internal\\MapField";
+ }
+ string type;
+ switch (field->type()) {
+ case FieldDescriptor::TYPE_INT32:
+ case FieldDescriptor::TYPE_UINT32:
+ case FieldDescriptor::TYPE_SINT32:
+ case FieldDescriptor::TYPE_FIXED32:
+ case FieldDescriptor::TYPE_SFIXED32:
+ case FieldDescriptor::TYPE_ENUM:
+ type = "int";
+ break;
+ case FieldDescriptor::TYPE_INT64:
+ case FieldDescriptor::TYPE_UINT64:
+ case FieldDescriptor::TYPE_SINT64:
+ case FieldDescriptor::TYPE_FIXED64:
+ case FieldDescriptor::TYPE_SFIXED64:
+ type = "int|string";
+ break;
+ case FieldDescriptor::TYPE_DOUBLE:
+ case FieldDescriptor::TYPE_FLOAT:
+ type = "float";
+ break;
+ case FieldDescriptor::TYPE_BOOL:
+ type = "bool";
+ break;
+ case FieldDescriptor::TYPE_STRING:
+ case FieldDescriptor::TYPE_BYTES:
+ type = "string";
+ break;
+ case FieldDescriptor::TYPE_MESSAGE:
+ type = "\\" + FullClassName(field->message_type(), is_descriptor);
+ break;
+ case FieldDescriptor::TYPE_GROUP:
+ return "null";
+ default: assert(false); return "";
+ }
+ if (field->is_repeated()) {
+ // accommodate for edge case with multiple types.
+ size_t start_pos = type.find("|");
+ if (start_pos != std::string::npos) {
+ type.replace(start_pos, 1, "[]|");
+ }
+ type += "[]|\\Google\\Protobuf\\Internal\\RepeatedField";
+ }
+ return type;
+}
+
+std::string PhpGetterTypeName(const FieldDescriptor* field, bool is_descriptor) {
+ if (field->is_map()) {
+ return "\\Google\\Protobuf\\Internal\\MapField";
+ }
+ if (field->is_repeated()) {
+ return "\\Google\\Protobuf\\Internal\\RepeatedField";
+ }
+ switch (field->type()) {
+ case FieldDescriptor::TYPE_INT32:
+ case FieldDescriptor::TYPE_UINT32:
+ case FieldDescriptor::TYPE_SINT32:
+ case FieldDescriptor::TYPE_FIXED32:
+ case FieldDescriptor::TYPE_SFIXED32:
+ case FieldDescriptor::TYPE_ENUM: return "int";
+ case FieldDescriptor::TYPE_INT64:
+ case FieldDescriptor::TYPE_UINT64:
+ case FieldDescriptor::TYPE_SINT64:
+ case FieldDescriptor::TYPE_FIXED64:
+ case FieldDescriptor::TYPE_SFIXED64: return "int|string";
+ case FieldDescriptor::TYPE_DOUBLE:
+ case FieldDescriptor::TYPE_FLOAT: return "float";
+ case FieldDescriptor::TYPE_BOOL: return "bool";
+ case FieldDescriptor::TYPE_STRING:
+ case FieldDescriptor::TYPE_BYTES: return "string";
+ case FieldDescriptor::TYPE_MESSAGE:
+ return "\\" + FullClassName(field->message_type(), is_descriptor);
+ case FieldDescriptor::TYPE_GROUP: return "null";
+ default: assert(false); return "";
+ }
+}
+
std::string EnumOrMessageSuffix(
const FieldDescriptor* field, bool is_descriptor) {
if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
@@ -370,7 +551,7 @@ void Outdent(io::Printer* printer) {
void GenerateField(const FieldDescriptor* field, io::Printer* printer,
bool is_descriptor) {
if (field->is_repeated()) {
- GenerateFieldDocComment(printer, field);
+ GenerateFieldDocComment(printer, field, is_descriptor, kFieldProperty);
printer->Print(
"private $^name^;\n",
"name", field->name());
@@ -378,7 +559,7 @@ void GenerateField(const FieldDescriptor* field, io::Printer* printer,
// Oneof fields are handled by GenerateOneofField.
return;
} else {
- GenerateFieldDocComment(printer, field);
+ GenerateFieldDocComment(printer, field, is_descriptor, kFieldProperty);
printer->Print(
"private $^name^ = ^default^;\n",
"name", field->name(),
@@ -406,7 +587,7 @@ void GenerateFieldAccessor(const FieldDescriptor* field, bool is_descriptor,
// Generate getter.
if (oneof != NULL) {
- GenerateFieldDocComment(printer, field);
+ GenerateFieldDocComment(printer, field, is_descriptor, kFieldGetter);
printer->Print(
"public function get^camel_name^()\n"
"{\n"
@@ -415,7 +596,7 @@ void GenerateFieldAccessor(const FieldDescriptor* field, bool is_descriptor,
"camel_name", UnderscoresToCamelCase(field->name(), true),
"number", IntToString(field->number()));
} else {
- GenerateFieldDocComment(printer, field);
+ GenerateFieldDocComment(printer, field, is_descriptor, kFieldGetter);
printer->Print(
"public function get^camel_name^()\n"
"{\n"
@@ -426,45 +607,64 @@ void GenerateFieldAccessor(const FieldDescriptor* field, bool is_descriptor,
}
// Generate setter.
- GenerateFieldDocComment(printer, field);
+ GenerateFieldDocComment(printer, field, is_descriptor, kFieldSetter);
printer->Print(
- "public function set^camel_name^(^var^)\n"
+ "public function set^camel_name^($var)\n"
"{\n",
- "camel_name", UnderscoresToCamelCase(field->name(), true),
- "var", (field->is_repeated() ||
- field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) ?
- "&$var": "$var");
+ "camel_name", UnderscoresToCamelCase(field->name(), true));
Indent(printer);
// Type check.
if (field->is_map()) {
+ const Descriptor* map_entry = field->message_type();
+ const FieldDescriptor* key = map_entry->FindFieldByName("key");
+ const FieldDescriptor* value = map_entry->FindFieldByName("value");
+ printer->Print(
+ "$arr = GPBUtil::checkMapField($var, "
+ "\\Google\\Protobuf\\Internal\\GPBType::^key_type^, "
+ "\\Google\\Protobuf\\Internal\\GPBType::^value_type^",
+ "key_type", ToUpper(key->type_name()),
+ "value_type", ToUpper(value->type_name()));
+ if (value->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
+ printer->Print(
+ ", \\^class_name^);\n",
+ "class_name",
+ FullClassName(value->message_type(), is_descriptor) + "::class");
+ } else if (value->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) {
+ printer->Print(
+ ", \\^class_name^);\n",
+ "class_name",
+ FullClassName(value->enum_type(), is_descriptor) + "::class");
+ } else {
+ printer->Print(");\n");
+ }
} else if (field->is_repeated()) {
printer->Print(
- "GPBUtil::checkRepeatedField($var, "
+ "$arr = GPBUtil::checkRepeatedField($var, "
"\\Google\\Protobuf\\Internal\\GPBType::^type^",
"type", ToUpper(field->type_name()));
if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
printer->Print(
", \\^class_name^);\n",
"class_name",
- MessageName(field->message_type(), is_descriptor) + "::class");
+ FullClassName(field->message_type(), is_descriptor) + "::class");
} else if (field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) {
printer->Print(
- ", ^class_name^);\n",
+ ", \\^class_name^);\n",
"class_name",
- EnumName(field->enum_type(), is_descriptor) + "::class");
+ FullClassName(field->enum_type(), is_descriptor) + "::class");
} else {
printer->Print(");\n");
}
} else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
printer->Print(
"GPBUtil::checkMessage($var, \\^class_name^::class);\n",
- "class_name", MessageName(field->message_type(), is_descriptor));
+ "class_name", FullClassName(field->message_type(), is_descriptor));
} else if (field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) {
printer->Print(
"GPBUtil::checkEnum($var, \\^class_name^::class);\n",
- "class_name", EnumName(field->enum_type(), is_descriptor));
+ "class_name", FullClassName(field->enum_type(), is_descriptor));
} else if (field->cpp_type() == FieldDescriptor::CPPTYPE_STRING) {
printer->Print(
"GPBUtil::checkString($var, ^utf8^);\n",
@@ -480,6 +680,10 @@ void GenerateFieldAccessor(const FieldDescriptor* field, bool is_descriptor,
printer->Print(
"$this->writeOneof(^number^, $var);\n",
"number", IntToString(field->number()));
+ } else if (field->is_repeated()) {
+ printer->Print(
+ "$this->^name^ = $arr;\n",
+ "name", field->name());
} else {
printer->Print(
"$this->^name^ = $var;\n",
@@ -493,6 +697,8 @@ void GenerateFieldAccessor(const FieldDescriptor* field, bool is_descriptor,
"field_name", field->name());
}
+ printer->Print("\nreturn $this;\n");
+
Outdent(printer);
printer->Print(
@@ -522,13 +728,23 @@ void GenerateEnumToPool(const EnumDescriptor* en, io::Printer* printer) {
const EnumValueDescriptor* value = en->value(i);
printer->Print(
"->value(\"^name^\", ^number^)\n",
- "name", value->name(),
+ "name", ConstantNamePrefix(value->name()) + value->name(),
"number", IntToString(value->number()));
}
printer->Print("->finalizeToPool();\n\n");
Outdent(printer);
}
+void GenerateServiceMethod(const MethodDescriptor* method,
+ io::Printer* printer) {
+ printer->Print(
+ "public function ^camel_name^(\\^request_name^ $request);\n\n",
+ "camel_name", UnderscoresToCamelCase(method->name(), false),
+ "request_name", FullClassName(
+ method->input_type(), false)
+ );
+}
+
void GenerateMessageToPool(const string& name_prefix, const Descriptor* message,
io::Printer* printer) {
// Don't generate MapEntry messages -- we use the PHP extension's native
@@ -637,6 +853,12 @@ void GenerateAddFileToPool(const FileDescriptor* file, bool is_descriptor,
} else {
for (int i = 0; i < file->dependency_count(); i++) {
const std::string& name = file->dependency(i)->name();
+ // Currently, descriptor.proto is not ready for external usage. Skip to
+ // import it for now, so that its dependencies can still work as long as
+ // they don't use protos defined in descriptor.proto.
+ if (name == kDescriptorFile) {
+ continue;
+ }
std::string dependency_filename =
GeneratedMetadataFileName(name, is_descriptor);
printer->Print(
@@ -648,6 +870,26 @@ void GenerateAddFileToPool(const FileDescriptor* file, bool is_descriptor,
FileDescriptorSet files;
FileDescriptorProto* file_proto = files.add_file();
file->CopyTo(file_proto);
+
+ // Filter out descriptor.proto as it cannot be depended on for now.
+ RepeatedPtrField<string>* dependency = file_proto->mutable_dependency();
+ for (RepeatedPtrField<string>::iterator it = dependency->begin();
+ it != dependency->end(); ++it) {
+ if (*it != kDescriptorFile) {
+ dependency->erase(it);
+ break;
+ }
+ }
+
+ // Filter out all extensions, since we do not support extension yet.
+ file_proto->clear_extension();
+ RepeatedPtrField<DescriptorProto>* message_type =
+ file_proto->mutable_message_type();
+ for (RepeatedPtrField<DescriptorProto>::iterator it = message_type->begin();
+ it != message_type->end(); ++it) {
+ it->clear_extension();
+ }
+
string files_data;
files.SerializeToString(&files_data);
@@ -684,7 +926,7 @@ void GenerateUseDeclaration(bool is_descriptor, io::Printer* printer) {
"use Google\\Protobuf\\Internal\\GPBType;\n"
"use Google\\Protobuf\\Internal\\GPBWire;\n"
"use Google\\Protobuf\\Internal\\RepeatedField;\n"
- "use Google\\Protobuf\\Internal\\InputStream;\n\n"
+ "use Google\\Protobuf\\Internal\\InputStream;\n"
"use Google\\Protobuf\\Internal\\GPBUtil;\n\n");
}
}
@@ -757,12 +999,22 @@ void GenerateEnumFile(const FileDescriptor* file, const EnumDescriptor* en,
std::string fullname = FilenameToClassname(filename);
int lastindex = fullname.find_last_of("\\");
- GenerateEnumDocComment(&printer, en);
- if (lastindex != string::npos) {
+ if (file->options().has_php_namespace()) {
+ const string& php_namespace = file->options().php_namespace();
+ if (!php_namespace.empty()) {
+ printer.Print(
+ "namespace ^name^;\n\n",
+ "name", php_namespace);
+ }
+ } else if (!file->package().empty()) {
printer.Print(
"namespace ^name^;\n\n",
"name", fullname.substr(0, lastindex));
+ }
+ GenerateEnumDocComment(&printer, en, is_descriptor);
+
+ if (lastindex != string::npos) {
printer.Print(
"class ^name^\n"
"{\n",
@@ -779,7 +1031,7 @@ void GenerateEnumFile(const FileDescriptor* file, const EnumDescriptor* en,
const EnumValueDescriptor* value = en->value(i);
GenerateEnumValueDocComment(&printer, value);
printer.Print("const ^name^ = ^number^;\n",
- "name", value->name(),
+ "name", ConstantNamePrefix(value->name()) + value->name(),
"number", IntToString(value->number()));
}
@@ -806,7 +1058,14 @@ void GenerateMessageFile(const FileDescriptor* file, const Descriptor* message,
std::string fullname = FilenameToClassname(filename);
int lastindex = fullname.find_last_of("\\");
- if (!file->package().empty()) {
+ if (file->options().has_php_namespace()) {
+ const string& php_namespace = file->options().php_namespace();
+ if (!php_namespace.empty()) {
+ printer.Print(
+ "namespace ^name^;\n\n",
+ "name", php_namespace);
+ }
+ } else if (!file->package().empty()) {
printer.Print(
"namespace ^name^;\n\n",
"name", fullname.substr(0, lastindex));
@@ -814,7 +1073,7 @@ void GenerateMessageFile(const FileDescriptor* file, const Descriptor* message,
GenerateUseDeclaration(is_descriptor, &printer);
- GenerateMessageDocComment(&printer, message);
+ GenerateMessageDocComment(&printer, message, is_descriptor);
if (lastindex != string::npos) {
printer.Print(
"class ^name^ extends \\Google\\Protobuf\\Internal\\Message\n"
@@ -862,9 +1121,12 @@ void GenerateMessageFile(const FileDescriptor* file, const Descriptor* message,
for (int i = 0; i < message->oneof_decl_count(); i++) {
const OneofDescriptor* oneof = message->oneof_decl(i);
printer.Print(
+ "/**\n"
+ " * @return string\n"
+ " */\n"
"public function get^camel_name^()\n"
"{\n"
- " return $this->^name^;\n"
+ " return $this->whichOneof(\"^name^\");\n"
"}\n\n",
"camel_name", UnderscoresToCamelCase(oneof->name(), true), "name",
oneof->name());
@@ -884,6 +1146,58 @@ void GenerateMessageFile(const FileDescriptor* file, const Descriptor* message,
}
}
+void GenerateServiceFile(const FileDescriptor* file,
+ const ServiceDescriptor* service, bool is_descriptor,
+ GeneratorContext* generator_context) {
+ std::string filename = GeneratedServiceFileName(service, is_descriptor);
+ scoped_ptr<io::ZeroCopyOutputStream> output(
+ generator_context->Open(filename));
+ io::Printer printer(output.get(), '^');
+
+ GenerateHead(file, &printer);
+
+ std::string fullname = FilenameToClassname(filename);
+ int lastindex = fullname.find_last_of("\\");
+
+ if (file->options().has_php_namespace()) {
+ const string& php_namespace = file->options().php_namespace();
+ if (!php_namespace.empty()) {
+ printer.Print(
+ "namespace ^name^;\n\n",
+ "name", php_namespace);
+ }
+ } else if (!file->package().empty()) {
+ printer.Print(
+ "namespace ^name^;\n\n",
+ "name", fullname.substr(0, lastindex));
+ }
+
+ GenerateServiceDocComment(&printer, service);
+
+ if (lastindex != string::npos) {
+ printer.Print(
+ "interface ^name^\n"
+ "{\n",
+ "name", fullname.substr(lastindex + 1));
+ } else {
+ printer.Print(
+ "interface ^name^\n"
+ "{\n",
+ "name", fullname);
+ }
+
+ Indent(&printer);
+
+ for (int i = 0; i < service->method_count(); i++) {
+ const MethodDescriptor* method = service->method(i);
+ GenerateServiceMethodDocComment(&printer, method);
+ GenerateServiceMethod(method, &printer);
+ }
+
+ Outdent(&printer);
+ printer.Print("}\n\n");
+}
+
void GenerateFile(const FileDescriptor* file, bool is_descriptor,
GeneratorContext* generator_context) {
GenerateMetadataFile(file, is_descriptor, generator_context);
@@ -895,6 +1209,12 @@ void GenerateFile(const FileDescriptor* file, bool is_descriptor,
GenerateEnumFile(file, file->enum_type(i), is_descriptor,
generator_context);
}
+ if (file->options().php_generic_services()) {
+ for (int i = 0; i < file->service_count(); i++) {
+ GenerateServiceFile(file, file->service(i), is_descriptor,
+ generator_context);
+ }
+ }
}
static string EscapePhpdoc(const string& input) {
@@ -928,22 +1248,6 @@ static string EscapePhpdoc(const string& input) {
// does not have a corresponding @Deprecated annotation.
result.append("&#64;");
break;
- case '<':
- // Avoid interpretation as HTML.
- result.append("&lt;");
- break;
- case '>':
- // Avoid interpretation as HTML.
- result.append("&gt;");
- break;
- case '&':
- // Avoid interpretation as HTML.
- result.append("&amp;");
- break;
- case '\\':
- // Java interprets Unicode escape sequences anywhere!
- result.append("&#92;");
- break;
default:
result.push_back(c);
break;
@@ -962,7 +1266,7 @@ static void GenerateDocCommentBodyForLocation(
if (!comments.empty()) {
// TODO(teboring): Ideally we should parse the comment text as Markdown and
// write it back as HTML, but this requires a Markdown parser. For now
- // we just use <pre> to get fixed-width text formatting.
+ // we just use the proto comments unchanged.
// If the comment itself contains block comment start or end markers,
// HTML-escape them so that they don't accidentally close the doc comment.
@@ -973,7 +1277,6 @@ static void GenerateDocCommentBodyForLocation(
lines.pop_back();
}
- printer->Print(" * <pre>\n");
for (int i = 0; i < lines.size(); i++) {
// Most lines should start with a space. Watch out for lines that start
// with a /, since putting that right after the leading asterisk will
@@ -985,7 +1288,6 @@ static void GenerateDocCommentBodyForLocation(
}
}
printer->Print(
- " * </pre>\n"
" *\n");
}
}
@@ -1011,17 +1313,28 @@ static string FirstLineOf(const string& value) {
}
void GenerateMessageDocComment(io::Printer* printer,
- const Descriptor* message) {
+ const Descriptor* message, int is_descriptor) {
printer->Print("/**\n");
GenerateDocCommentBody(printer, message);
printer->Print(
+ " * Generated from protobuf message <code>^messagename^</code>\n"
+ " */\n",
+ "fullname", EscapePhpdoc(PhpName(message->full_name(), is_descriptor)),
+ "messagename", EscapePhpdoc(message->full_name()));
+}
+
+void GenerateServiceDocComment(io::Printer* printer,
+ const ServiceDescriptor* service) {
+ printer->Print("/**\n");
+ GenerateDocCommentBody(printer, service);
+ printer->Print(
" * Protobuf type <code>^fullname^</code>\n"
" */\n",
- "fullname", EscapePhpdoc(message->full_name()));
+ "fullname", EscapePhpdoc(service->full_name()));
}
-void GenerateFieldDocComment(io::Printer* printer,
- const FieldDescriptor* field) {
+void GenerateFieldDocComment(io::Printer* printer, const FieldDescriptor* field,
+ int is_descriptor, int function_type) {
// In theory we should have slightly different comments for setters, getters,
// etc., but in practice everyone already knows the difference between these
// so it's redundant information.
@@ -1033,18 +1346,27 @@ void GenerateFieldDocComment(io::Printer* printer,
printer->Print("/**\n");
GenerateDocCommentBody(printer, field);
printer->Print(
- " * <code>^def^</code>\n",
+ " * Generated from protobuf field <code>^def^</code>\n",
"def", EscapePhpdoc(FirstLineOf(field->DebugString())));
+ if (function_type == kFieldSetter) {
+ printer->Print(" * @param ^php_type^ $var\n",
+ "php_type", PhpSetterTypeName(field, is_descriptor));
+ printer->Print(" * @return $this\n");
+ } else if (function_type == kFieldGetter) {
+ printer->Print(" * @return ^php_type^\n",
+ "php_type", PhpGetterTypeName(field, is_descriptor));
+ }
printer->Print(" */\n");
}
-void GenerateEnumDocComment(io::Printer* printer, const EnumDescriptor* enum_) {
+void GenerateEnumDocComment(io::Printer* printer, const EnumDescriptor* enum_,
+ int is_descriptor) {
printer->Print("/**\n");
GenerateDocCommentBody(printer, enum_);
printer->Print(
" * Protobuf enum <code>^fullname^</code>\n"
" */\n",
- "fullname", EscapePhpdoc(enum_->full_name()));
+ "fullname", EscapePhpdoc(PhpName(enum_->full_name(), is_descriptor)));
}
void GenerateEnumValueDocComment(io::Printer* printer,
@@ -1052,11 +1374,28 @@ void GenerateEnumValueDocComment(io::Printer* printer,
printer->Print("/**\n");
GenerateDocCommentBody(printer, value);
printer->Print(
- " * <code>^def^</code>\n"
+ " * Generated from protobuf enum <code>^def^</code>\n"
" */\n",
"def", EscapePhpdoc(FirstLineOf(value->DebugString())));
}
+void GenerateServiceMethodDocComment(io::Printer* printer,
+ const MethodDescriptor* method) {
+ printer->Print("/**\n");
+ GenerateDocCommentBody(printer, method);
+ printer->Print(
+ " * Method <code>^method_name^</code>\n"
+ " *\n",
+ "method_name", EscapePhpdoc(UnderscoresToCamelCase(method->name(), false)));
+ printer->Print(
+ " * @param \\^input_type^ $request\n",
+ "input_type", EscapePhpdoc(FullClassName(method->input_type(), false)));
+ printer->Print(
+ " * @return \\^return_type^\n"
+ " */\n",
+ "return_type", EscapePhpdoc(FullClassName(method->output_type(), false)));
+}
+
bool Generator::Generate(const FileDescriptor* file, const string& parameter,
GeneratorContext* generator_context,
string* error) const {
diff --git a/src/google/protobuf/compiler/plugin.cc b/src/google/protobuf/compiler/plugin.cc
index 3848101d..7f975510 100644
--- a/src/google/protobuf/compiler/plugin.cc
+++ b/src/google/protobuf/compiler/plugin.cc
@@ -36,14 +36,7 @@
#include <set>
#ifdef _WIN32
-#include <io.h>
#include <fcntl.h>
-#ifndef STDIN_FILENO
-#define STDIN_FILENO 0
-#endif
-#ifndef STDOUT_FILENO
-#define STDOUT_FILENO 1
-#endif
#else
#include <unistd.h>
#endif
@@ -54,12 +47,19 @@
#include <google/protobuf/compiler/code_generator.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
+#include <google/protobuf/stubs/io_win32.h>
namespace google {
namespace protobuf {
namespace compiler {
+#if defined(_MSC_VER)
+// DO NOT include <io.h>, instead create functions in io_win32.{h,cc} and import
+// them like we do below.
+using google::protobuf::internal::win32::setmode;
+#endif
+
class GeneratorResponseContext : public GeneratorContext {
public:
GeneratorResponseContext(
@@ -127,6 +127,7 @@ bool GenerateCode(const CodeGeneratorRequest& request,
GeneratorResponseContext context(
request.compiler_version(), response, parsed_files);
+
string error;
bool succeeded = generator.GenerateAll(
parsed_files, request.parameter(), &context, &error);
@@ -150,8 +151,8 @@ int PluginMain(int argc, char* argv[], const CodeGenerator* generator) {
}
#ifdef _WIN32
- _setmode(STDIN_FILENO, _O_BINARY);
- _setmode(STDOUT_FILENO, _O_BINARY);
+ setmode(STDIN_FILENO, _O_BINARY);
+ setmode(STDOUT_FILENO, _O_BINARY);
#endif
CodeGeneratorRequest request;
diff --git a/src/google/protobuf/compiler/plugin.pb.cc b/src/google/protobuf/compiler/plugin.pb.cc
index bb78eff6..80c8c625 100644
--- a/src/google/protobuf/compiler/plugin.pb.cc
+++ b/src/google/protobuf/compiler/plugin.pb.cc
@@ -1,7 +1,6 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/compiler/plugin.proto
-#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include <google/protobuf/compiler/plugin.pb.h>
#include <algorithm>
@@ -15,97 +14,194 @@
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
+// This is a temporary google only hack
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+#include "third_party/protobuf/version.h"
+#endif
// @@protoc_insertion_point(includes)
-
namespace google {
namespace protobuf {
namespace compiler {
-class VersionDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<Version> {};
-VersionDefaultTypeInternal _Version_default_instance_;
-class CodeGeneratorRequestDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<CodeGeneratorRequest> {};
-CodeGeneratorRequestDefaultTypeInternal _CodeGeneratorRequest_default_instance_;
-class CodeGeneratorResponse_FileDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<CodeGeneratorResponse_File> {};
-CodeGeneratorResponse_FileDefaultTypeInternal _CodeGeneratorResponse_File_default_instance_;
-class CodeGeneratorResponseDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<CodeGeneratorResponse> {};
-CodeGeneratorResponseDefaultTypeInternal _CodeGeneratorResponse_default_instance_;
+class VersionDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<Version>
+ _instance;
+} _Version_default_instance_;
+class CodeGeneratorRequestDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<CodeGeneratorRequest>
+ _instance;
+} _CodeGeneratorRequest_default_instance_;
+class CodeGeneratorResponse_FileDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<CodeGeneratorResponse_File>
+ _instance;
+} _CodeGeneratorResponse_File_default_instance_;
+class CodeGeneratorResponseDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<CodeGeneratorResponse>
+ _instance;
+} _CodeGeneratorResponse_default_instance_;
+} // namespace compiler
+} // namespace protobuf
+} // namespace google
+namespace protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto {
+void InitDefaultsVersionImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
-namespace {
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ {
+ void* ptr = &::google::protobuf::compiler::_Version_default_instance_;
+ new (ptr) ::google::protobuf::compiler::Version();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::compiler::Version::InitAsDefaultInstance();
+}
-::google::protobuf::Metadata file_level_metadata[4];
+void InitDefaultsVersion() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsVersionImpl);
+}
-} // namespace
-
-
-const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fcompiler_2fplugin_2eproto() GOOGLE_ATTRIBUTE_COLD;
-const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fcompiler_2fplugin_2eproto() {
- static const ::google::protobuf::uint32 offsets[] = {
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Version, _has_bits_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Version, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Version, major_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Version, minor_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Version, patch_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Version, suffix_),
- 1,
- 2,
- 3,
- 0,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CodeGeneratorRequest, _has_bits_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CodeGeneratorRequest, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CodeGeneratorRequest, file_to_generate_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CodeGeneratorRequest, parameter_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CodeGeneratorRequest, proto_file_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CodeGeneratorRequest, compiler_version_),
- 2,
- 0,
- 3,
- 1,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CodeGeneratorResponse_File, _has_bits_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CodeGeneratorResponse_File, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CodeGeneratorResponse_File, name_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CodeGeneratorResponse_File, insertion_point_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CodeGeneratorResponse_File, content_),
- 0,
- 1,
- 2,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CodeGeneratorResponse, _has_bits_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CodeGeneratorResponse, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CodeGeneratorResponse, error_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CodeGeneratorResponse, file_),
- 0,
- 1,
- };
- return offsets;
+void InitDefaultsCodeGeneratorRequestImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorProto();
+ protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsVersion();
+ {
+ void* ptr = &::google::protobuf::compiler::_CodeGeneratorRequest_default_instance_;
+ new (ptr) ::google::protobuf::compiler::CodeGeneratorRequest();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::compiler::CodeGeneratorRequest::InitAsDefaultInstance();
}
-static const ::google::protobuf::internal::MigrationSchema schemas[] = {
- { 0, 8, sizeof(Version)},
- { 12, 20, sizeof(CodeGeneratorRequest)},
- { 24, 31, sizeof(CodeGeneratorResponse_File)},
- { 34, 40, sizeof(CodeGeneratorResponse)},
-};
+void InitDefaultsCodeGeneratorRequest() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsCodeGeneratorRequestImpl);
+}
+
+void InitDefaultsCodeGeneratorResponse_FileImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ {
+ void* ptr = &::google::protobuf::compiler::_CodeGeneratorResponse_File_default_instance_;
+ new (ptr) ::google::protobuf::compiler::CodeGeneratorResponse_File();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::compiler::CodeGeneratorResponse_File::InitAsDefaultInstance();
+}
+
+void InitDefaultsCodeGeneratorResponse_File() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsCodeGeneratorResponse_FileImpl);
+}
+
+void InitDefaultsCodeGeneratorResponseImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorResponse_File();
+ {
+ void* ptr = &::google::protobuf::compiler::_CodeGeneratorResponse_default_instance_;
+ new (ptr) ::google::protobuf::compiler::CodeGeneratorResponse();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::compiler::CodeGeneratorResponse::InitAsDefaultInstance();
+}
-static const ::google::protobuf::internal::DefaultInstanceData file_default_instances[] = {
- {reinterpret_cast<const ::google::protobuf::Message*>(&_Version_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_CodeGeneratorRequest_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_CodeGeneratorResponse_File_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_CodeGeneratorResponse_default_instance_), NULL},
+void InitDefaultsCodeGeneratorResponse() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsCodeGeneratorResponseImpl);
+}
+
+::google::protobuf::Metadata file_level_metadata[4];
+
+const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::Version, _has_bits_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::Version, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::Version, major_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::Version, minor_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::Version, patch_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::Version, suffix_),
+ 1,
+ 2,
+ 3,
+ 0,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorRequest, _has_bits_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorRequest, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorRequest, file_to_generate_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorRequest, parameter_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorRequest, proto_file_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorRequest, compiler_version_),
+ ~0u,
+ 0,
+ ~0u,
+ 1,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse_File, _has_bits_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse_File, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse_File, name_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse_File, insertion_point_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse_File, content_),
+ 0,
+ 1,
+ 2,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse, _has_bits_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse, error_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse, file_),
+ 0,
+ ~0u,
+};
+static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+ { 0, 9, sizeof(::google::protobuf::compiler::Version)},
+ { 13, 22, sizeof(::google::protobuf::compiler::CodeGeneratorRequest)},
+ { 26, 34, sizeof(::google::protobuf::compiler::CodeGeneratorResponse_File)},
+ { 37, 44, sizeof(::google::protobuf::compiler::CodeGeneratorResponse)},
};
-namespace {
+static ::google::protobuf::Message const * const file_default_instances[] = {
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::compiler::_Version_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::compiler::_CodeGeneratorRequest_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::compiler::_CodeGeneratorResponse_File_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::compiler::_CodeGeneratorResponse_default_instance_),
+};
void protobuf_AssignDescriptors() {
- protobuf_AddDesc_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
+ AddDescriptors();
::google::protobuf::MessageFactory* factory = NULL;
AssignDescriptors(
- "google/protobuf/compiler/plugin.proto", schemas, file_default_instances, protobuf_Offsets_google_2fprotobuf_2fcompiler_2fplugin_2eproto(), factory,
+ "google/protobuf/compiler/plugin.proto", schemas, file_default_instances, TableStruct::offsets, factory,
file_level_metadata, NULL, NULL);
}
@@ -114,45 +210,15 @@ void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);
}
-void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
+void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 4);
}
-} // namespace
-
-void protobuf_ShutdownFile_google_2fprotobuf_2fcompiler_2fplugin_2eproto() {
- _Version_default_instance_.Shutdown();
- delete file_level_metadata[0].reflection;
- _CodeGeneratorRequest_default_instance_.Shutdown();
- delete file_level_metadata[1].reflection;
- _CodeGeneratorResponse_File_default_instance_.Shutdown();
- delete file_level_metadata[2].reflection;
- _CodeGeneratorResponse_default_instance_.Shutdown();
- delete file_level_metadata[3].reflection;
-}
-
-void protobuf_InitDefaults_google_2fprotobuf_2fcompiler_2fplugin_2eproto_impl() {
- GOOGLE_PROTOBUF_VERIFY_VERSION;
-
- ::google::protobuf::protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
- ::google::protobuf::internal::InitProtobufDefaults();
- _Version_default_instance_.DefaultConstruct();
- _CodeGeneratorRequest_default_instance_.DefaultConstruct();
- _CodeGeneratorResponse_File_default_instance_.DefaultConstruct();
- _CodeGeneratorResponse_default_instance_.DefaultConstruct();
- _CodeGeneratorRequest_default_instance_.get_mutable()->compiler_version_ = const_cast< ::google::protobuf::compiler::Version*>(
- ::google::protobuf::compiler::Version::internal_default_instance());
-}
-
-void protobuf_InitDefaults_google_2fprotobuf_2fcompiler_2fplugin_2eproto() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &protobuf_InitDefaults_google_2fprotobuf_2fcompiler_2fplugin_2eproto_impl);
-}
-void protobuf_AddDesc_google_2fprotobuf_2fcompiler_2fplugin_2eproto_impl() {
- protobuf_InitDefaults_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
- static const char descriptor[] = {
+void AddDescriptorsImpl() {
+ InitDefaults();
+ static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n%google/protobuf/compiler/plugin.proto\022"
"\030google.protobuf.compiler\032 google/protob"
"uf/descriptor.proto\"F\n\007Version\022\r\n\005major\030"
@@ -166,31 +232,36 @@ void protobuf_AddDesc_google_2fprotobuf_2fcompiler_2fplugin_2eproto_impl() {
"\t\022B\n\004file\030\017 \003(\01324.google.protobuf.compil"
"er.CodeGeneratorResponse.File\032>\n\004File\022\014\n"
"\004name\030\001 \001(\t\022\027\n\017insertion_point\030\002 \001(\t\022\017\n\007"
- "content\030\017 \001(\tB7\n\034com.google.protobuf.com"
- "pilerB\014PluginProtosZ\tplugin_go"
+ "content\030\017 \001(\tBg\n\034com.google.protobuf.com"
+ "pilerB\014PluginProtosZ9github.com/golang/p"
+ "rotobuf/protoc-gen-go/plugin;plugin_go"
};
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
- descriptor, 590);
+ descriptor, 638);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"google/protobuf/compiler/plugin.proto", &protobuf_RegisterTypes);
- ::google::protobuf::protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
- ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_google_2fprotobuf_2fcompiler_2fplugin_2eproto);
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::AddDescriptors();
}
-GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AddDesc_google_2fprotobuf_2fcompiler_2fplugin_2eproto_once_);
-void protobuf_AddDesc_google_2fprotobuf_2fcompiler_2fplugin_2eproto() {
- ::google::protobuf::GoogleOnceInit(&protobuf_AddDesc_google_2fprotobuf_2fcompiler_2fplugin_2eproto_once_,
- &protobuf_AddDesc_google_2fprotobuf_2fcompiler_2fplugin_2eproto_impl);
+void AddDescriptors() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);
}
-// Force AddDescriptors() to be called at static initialization time.
-struct StaticDescriptorInitializer_google_2fprotobuf_2fcompiler_2fplugin_2eproto {
- StaticDescriptorInitializer_google_2fprotobuf_2fcompiler_2fplugin_2eproto() {
- protobuf_AddDesc_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
+// Force AddDescriptors() to be called at dynamic initialization time.
+struct StaticDescriptorInitializer {
+ StaticDescriptorInitializer() {
+ AddDescriptors();
}
-} static_descriptor_initializer_google_2fprotobuf_2fcompiler_2fplugin_2eproto_;
+} static_descriptor_initializer;
+} // namespace protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto
+namespace google {
+namespace protobuf {
+namespace compiler {
// ===================================================================
+void Version::InitAsDefaultInstance() {
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Version::kMajorFieldNumber;
const int Version::kMinorFieldNumber;
@@ -201,7 +272,7 @@ const int Version::kSuffixFieldNumber;
Version::Version()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
+ ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsVersion();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.compiler.Version)
@@ -217,16 +288,17 @@ Version::Version(const Version& from)
suffix_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.suffix_);
}
::memcpy(&major_, &from.major_,
- reinterpret_cast<char*>(&patch_) -
- reinterpret_cast<char*>(&major_) + sizeof(patch_));
+ static_cast<size_t>(reinterpret_cast<char*>(&patch_) -
+ reinterpret_cast<char*>(&major_)) + sizeof(patch_));
// @@protoc_insertion_point(copy_constructor:google.protobuf.compiler.Version)
}
void Version::SharedCtor() {
_cached_size_ = 0;
suffix_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- ::memset(&major_, 0, reinterpret_cast<char*>(&patch_) -
- reinterpret_cast<char*>(&major_) + sizeof(patch_));
+ ::memset(&major_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&patch_) -
+ reinterpret_cast<char*>(&major_)) + sizeof(patch_));
}
Version::~Version() {
@@ -244,12 +316,12 @@ void Version::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* Version::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[0].descriptor;
+ ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const Version& Version::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
+ ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsVersion();
return *internal_default_instance();
}
@@ -263,13 +335,19 @@ Version* Version::New(::google::protobuf::Arena* arena) const {
void Version::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.compiler.Version)
- if (has_suffix()) {
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
+ if (cached_has_bits & 0x00000001u) {
GOOGLE_DCHECK(!suffix_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
(*suffix_.UnsafeRawStringPointer())->clear();
}
- if (_has_bits_[0 / 32] & 14u) {
- ::memset(&major_, 0, reinterpret_cast<char*>(&patch_) -
- reinterpret_cast<char*>(&major_) + sizeof(patch_));
+ if (cached_has_bits & 14u) {
+ ::memset(&major_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&patch_) -
+ reinterpret_cast<char*>(&major_)) + sizeof(patch_));
}
_has_bits_.Clear();
_internal_metadata_.Clear();
@@ -287,7 +365,8 @@ bool Version::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional int32 major = 1;
case 1: {
- if (tag == 8u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
set_has_major();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
@@ -300,7 +379,8 @@ bool Version::MergePartialFromCodedStream(
// optional int32 minor = 2;
case 2: {
- if (tag == 16u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
set_has_minor();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
@@ -313,7 +393,8 @@ bool Version::MergePartialFromCodedStream(
// optional int32 patch = 3;
case 3: {
- if (tag == 24u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) {
set_has_patch();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
@@ -326,11 +407,12 @@ bool Version::MergePartialFromCodedStream(
// optional string suffix = 4;
case 4: {
- if (tag == 34u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_suffix()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->suffix().data(), this->suffix().length(),
+ this->suffix().data(), static_cast<int>(this->suffix().length()),
::google::protobuf::internal::WireFormat::PARSE,
"google.protobuf.compiler.Version.suffix");
} else {
@@ -341,13 +423,11 @@ bool Version::MergePartialFromCodedStream(
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
- input, tag, mutable_unknown_fields()));
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -364,25 +444,29 @@ failure:
void Version::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.compiler.Version)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional int32 major = 1;
- if (has_major()) {
+ if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->major(), output);
}
// optional int32 minor = 2;
- if (has_minor()) {
+ if (cached_has_bits & 0x00000004u) {
::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->minor(), output);
}
// optional int32 patch = 3;
- if (has_patch()) {
+ if (cached_has_bits & 0x00000008u) {
::google::protobuf::internal::WireFormatLite::WriteInt32(3, this->patch(), output);
}
// optional string suffix = 4;
- if (has_suffix()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->suffix().data(), this->suffix().length(),
+ this->suffix().data(), static_cast<int>(this->suffix().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.compiler.Version.suffix");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -391,7 +475,7 @@ void Version::SerializeWithCachedSizes(
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- unknown_fields(), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.compiler.Version)
}
@@ -400,25 +484,29 @@ void Version::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.compiler.Version)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional int32 major = 1;
- if (has_major()) {
+ if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->major(), target);
}
// optional int32 minor = 2;
- if (has_minor()) {
+ if (cached_has_bits & 0x00000004u) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->minor(), target);
}
// optional int32 patch = 3;
- if (has_patch()) {
+ if (cached_has_bits & 0x00000008u) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(3, this->patch(), target);
}
// optional string suffix = 4;
- if (has_suffix()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->suffix().data(), this->suffix().length(),
+ this->suffix().data(), static_cast<int>(this->suffix().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.compiler.Version.suffix");
target =
@@ -428,7 +516,7 @@ void Version::SerializeWithCachedSizes(
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- unknown_fields(), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.compiler.Version)
return target;
@@ -441,7 +529,7 @@ size_t Version::ByteSizeLong() const {
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- unknown_fields());
+ _internal_metadata_.unknown_fields());
}
if (_has_bits_[0 / 32] & 15u) {
// optional string suffix = 4;
@@ -499,20 +587,25 @@ void Version::MergeFrom(const Version& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.compiler.Version)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
- if (from._has_bits_[0 / 32] & 15u) {
- if (from.has_suffix()) {
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = from._has_bits_[0];
+ if (cached_has_bits & 15u) {
+ if (cached_has_bits & 0x00000001u) {
set_has_suffix();
suffix_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.suffix_);
}
- if (from.has_major()) {
- set_major(from.major());
+ if (cached_has_bits & 0x00000002u) {
+ major_ = from.major_;
}
- if (from.has_minor()) {
- set_minor(from.minor());
+ if (cached_has_bits & 0x00000004u) {
+ minor_ = from.minor_;
}
- if (from.has_patch()) {
- set_patch(from.patch());
+ if (cached_has_bits & 0x00000008u) {
+ patch_ = from.patch_;
}
+ _has_bits_[0] |= cached_has_bits;
}
}
@@ -539,153 +632,31 @@ void Version::Swap(Version* other) {
InternalSwap(other);
}
void Version::InternalSwap(Version* other) {
+ using std::swap;
suffix_.Swap(&other->suffix_);
- std::swap(major_, other->major_);
- std::swap(minor_, other->minor_);
- std::swap(patch_, other->patch_);
- std::swap(_has_bits_[0], other->_has_bits_[0]);
+ swap(major_, other->major_);
+ swap(minor_, other->minor_);
+ swap(patch_, other->patch_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- std::swap(_cached_size_, other->_cached_size_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Version::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[0];
-}
-
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// Version
-
-// optional int32 major = 1;
-bool Version::has_major() const {
- return (_has_bits_[0] & 0x00000002u) != 0;
-}
-void Version::set_has_major() {
- _has_bits_[0] |= 0x00000002u;
-}
-void Version::clear_has_major() {
- _has_bits_[0] &= ~0x00000002u;
-}
-void Version::clear_major() {
- major_ = 0;
- clear_has_major();
-}
-::google::protobuf::int32 Version::major() const {
- // @@protoc_insertion_point(field_get:google.protobuf.compiler.Version.major)
- return major_;
-}
-void Version::set_major(::google::protobuf::int32 value) {
- set_has_major();
- major_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.compiler.Version.major)
+ protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::file_level_metadata[kIndexInFileMessages];
}
-// optional int32 minor = 2;
-bool Version::has_minor() const {
- return (_has_bits_[0] & 0x00000004u) != 0;
-}
-void Version::set_has_minor() {
- _has_bits_[0] |= 0x00000004u;
-}
-void Version::clear_has_minor() {
- _has_bits_[0] &= ~0x00000004u;
-}
-void Version::clear_minor() {
- minor_ = 0;
- clear_has_minor();
-}
-::google::protobuf::int32 Version::minor() const {
- // @@protoc_insertion_point(field_get:google.protobuf.compiler.Version.minor)
- return minor_;
-}
-void Version::set_minor(::google::protobuf::int32 value) {
- set_has_minor();
- minor_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.compiler.Version.minor)
-}
-// optional int32 patch = 3;
-bool Version::has_patch() const {
- return (_has_bits_[0] & 0x00000008u) != 0;
-}
-void Version::set_has_patch() {
- _has_bits_[0] |= 0x00000008u;
-}
-void Version::clear_has_patch() {
- _has_bits_[0] &= ~0x00000008u;
-}
-void Version::clear_patch() {
- patch_ = 0;
- clear_has_patch();
-}
-::google::protobuf::int32 Version::patch() const {
- // @@protoc_insertion_point(field_get:google.protobuf.compiler.Version.patch)
- return patch_;
-}
-void Version::set_patch(::google::protobuf::int32 value) {
- set_has_patch();
- patch_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.compiler.Version.patch)
-}
+// ===================================================================
-// optional string suffix = 4;
-bool Version::has_suffix() const {
- return (_has_bits_[0] & 0x00000001u) != 0;
-}
-void Version::set_has_suffix() {
- _has_bits_[0] |= 0x00000001u;
-}
-void Version::clear_has_suffix() {
- _has_bits_[0] &= ~0x00000001u;
-}
-void Version::clear_suffix() {
- suffix_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_suffix();
-}
-const ::std::string& Version::suffix() const {
- // @@protoc_insertion_point(field_get:google.protobuf.compiler.Version.suffix)
- return suffix_.GetNoArena();
-}
-void Version::set_suffix(const ::std::string& value) {
- set_has_suffix();
- suffix_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.compiler.Version.suffix)
-}
-void Version::set_suffix(const char* value) {
- set_has_suffix();
- suffix_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.compiler.Version.suffix)
-}
-void Version::set_suffix(const char* value, size_t size) {
- set_has_suffix();
- suffix_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.compiler.Version.suffix)
-}
-::std::string* Version::mutable_suffix() {
- set_has_suffix();
- // @@protoc_insertion_point(field_mutable:google.protobuf.compiler.Version.suffix)
- return suffix_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* Version::release_suffix() {
- // @@protoc_insertion_point(field_release:google.protobuf.compiler.Version.suffix)
- clear_has_suffix();
- return suffix_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+void CodeGeneratorRequest::InitAsDefaultInstance() {
+ ::google::protobuf::compiler::_CodeGeneratorRequest_default_instance_._instance.get_mutable()->compiler_version_ = const_cast< ::google::protobuf::compiler::Version*>(
+ ::google::protobuf::compiler::Version::internal_default_instance());
}
-void Version::set_allocated_suffix(::std::string* suffix) {
- if (suffix != NULL) {
- set_has_suffix();
- } else {
- clear_has_suffix();
- }
- suffix_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), suffix);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.Version.suffix)
+void CodeGeneratorRequest::clear_proto_file() {
+ proto_file_.Clear();
}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
-
-// ===================================================================
-
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int CodeGeneratorRequest::kFileToGenerateFieldNumber;
const int CodeGeneratorRequest::kParameterFieldNumber;
@@ -696,7 +667,7 @@ const int CodeGeneratorRequest::kCompilerVersionFieldNumber;
CodeGeneratorRequest::CodeGeneratorRequest()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
+ ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorRequest();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.compiler.CodeGeneratorRequest)
@@ -734,9 +705,7 @@ CodeGeneratorRequest::~CodeGeneratorRequest() {
void CodeGeneratorRequest::SharedDtor() {
parameter_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- if (this != internal_default_instance()) {
- delete compiler_version_;
- }
+ if (this != internal_default_instance()) delete compiler_version_;
}
void CodeGeneratorRequest::SetCachedSize(int size) const {
@@ -745,12 +714,12 @@ void CodeGeneratorRequest::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* CodeGeneratorRequest::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[1].descriptor;
+ ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const CodeGeneratorRequest& CodeGeneratorRequest::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
+ ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorRequest();
return *internal_default_instance();
}
@@ -764,16 +733,21 @@ CodeGeneratorRequest* CodeGeneratorRequest::New(::google::protobuf::Arena* arena
void CodeGeneratorRequest::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.compiler.CodeGeneratorRequest)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
file_to_generate_.Clear();
proto_file_.Clear();
- if (_has_bits_[0 / 32] & 3u) {
- if (has_parameter()) {
+ cached_has_bits = _has_bits_[0];
+ if (cached_has_bits & 3u) {
+ if (cached_has_bits & 0x00000001u) {
GOOGLE_DCHECK(!parameter_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
(*parameter_.UnsafeRawStringPointer())->clear();
}
- if (has_compiler_version()) {
+ if (cached_has_bits & 0x00000002u) {
GOOGLE_DCHECK(compiler_version_ != NULL);
- compiler_version_->::google::protobuf::compiler::Version::Clear();
+ compiler_version_->Clear();
}
}
_has_bits_.Clear();
@@ -792,12 +766,13 @@ bool CodeGeneratorRequest::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated string file_to_generate = 1;
case 1: {
- if (tag == 10u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->add_file_to_generate()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->file_to_generate(this->file_to_generate_size() - 1).data(),
- this->file_to_generate(this->file_to_generate_size() - 1).length(),
+ static_cast<int>(this->file_to_generate(this->file_to_generate_size() - 1).length()),
::google::protobuf::internal::WireFormat::PARSE,
"google.protobuf.compiler.CodeGeneratorRequest.file_to_generate");
} else {
@@ -808,11 +783,12 @@ bool CodeGeneratorRequest::MergePartialFromCodedStream(
// optional string parameter = 2;
case 2: {
- if (tag == 18u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_parameter()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->parameter().data(), this->parameter().length(),
+ this->parameter().data(), static_cast<int>(this->parameter().length()),
::google::protobuf::internal::WireFormat::PARSE,
"google.protobuf.compiler.CodeGeneratorRequest.parameter");
} else {
@@ -823,8 +799,9 @@ bool CodeGeneratorRequest::MergePartialFromCodedStream(
// optional .google.protobuf.compiler.Version compiler_version = 3;
case 3: {
- if (tag == 26u) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_compiler_version()));
} else {
goto handle_unusual;
@@ -834,26 +811,22 @@ bool CodeGeneratorRequest::MergePartialFromCodedStream(
// repeated .google.protobuf.FileDescriptorProto proto_file = 15;
case 15: {
- if (tag == 122u) {
- DO_(input->IncrementRecursionDepth());
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
- input, add_proto_file()));
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(122u /* 122 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_proto_file()));
} else {
goto handle_unusual;
}
- input->UnsafeDecrementRecursionDepth();
break;
}
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
- input, tag, mutable_unknown_fields()));
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -870,20 +843,24 @@ failure:
void CodeGeneratorRequest::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.compiler.CodeGeneratorRequest)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// repeated string file_to_generate = 1;
- for (int i = 0; i < this->file_to_generate_size(); i++) {
+ for (int i = 0, n = this->file_to_generate_size(); i < n; i++) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->file_to_generate(i).data(), this->file_to_generate(i).length(),
+ this->file_to_generate(i).data(), static_cast<int>(this->file_to_generate(i).length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.compiler.CodeGeneratorRequest.file_to_generate");
::google::protobuf::internal::WireFormatLite::WriteString(
1, this->file_to_generate(i), output);
}
+ cached_has_bits = _has_bits_[0];
// optional string parameter = 2;
- if (has_parameter()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->parameter().data(), this->parameter().length(),
+ this->parameter().data(), static_cast<int>(this->parameter().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.compiler.CodeGeneratorRequest.parameter");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -891,20 +868,21 @@ void CodeGeneratorRequest::SerializeWithCachedSizes(
}
// optional .google.protobuf.compiler.Version compiler_version = 3;
- if (has_compiler_version()) {
+ if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
3, *this->compiler_version_, output);
}
// repeated .google.protobuf.FileDescriptorProto proto_file = 15;
- for (unsigned int i = 0, n = this->proto_file_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->proto_file_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 15, this->proto_file(i), output);
+ 15, this->proto_file(static_cast<int>(i)), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- unknown_fields(), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.compiler.CodeGeneratorRequest)
}
@@ -913,20 +891,24 @@ void CodeGeneratorRequest::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.compiler.CodeGeneratorRequest)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// repeated string file_to_generate = 1;
- for (int i = 0; i < this->file_to_generate_size(); i++) {
+ for (int i = 0, n = this->file_to_generate_size(); i < n; i++) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->file_to_generate(i).data(), this->file_to_generate(i).length(),
+ this->file_to_generate(i).data(), static_cast<int>(this->file_to_generate(i).length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.compiler.CodeGeneratorRequest.file_to_generate");
target = ::google::protobuf::internal::WireFormatLite::
WriteStringToArray(1, this->file_to_generate(i), target);
}
+ cached_has_bits = _has_bits_[0];
// optional string parameter = 2;
- if (has_parameter()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->parameter().data(), this->parameter().length(),
+ this->parameter().data(), static_cast<int>(this->parameter().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.compiler.CodeGeneratorRequest.parameter");
target =
@@ -935,22 +917,23 @@ void CodeGeneratorRequest::SerializeWithCachedSizes(
}
// optional .google.protobuf.compiler.Version compiler_version = 3;
- if (has_compiler_version()) {
+ if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 3, *this->compiler_version_, false, target);
+ InternalWriteMessageToArray(
+ 3, *this->compiler_version_, deterministic, target);
}
// repeated .google.protobuf.FileDescriptorProto proto_file = 15;
- for (unsigned int i = 0, n = this->proto_file_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->proto_file_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 15, this->proto_file(i), false, target);
+ InternalWriteMessageToArray(
+ 15, this->proto_file(static_cast<int>(i)), deterministic, target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- unknown_fields(), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.compiler.CodeGeneratorRequest)
return target;
@@ -963,24 +946,24 @@ size_t CodeGeneratorRequest::ByteSizeLong() const {
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- unknown_fields());
+ _internal_metadata_.unknown_fields());
}
// repeated string file_to_generate = 1;
total_size += 1 *
::google::protobuf::internal::FromIntSize(this->file_to_generate_size());
- for (int i = 0; i < this->file_to_generate_size(); i++) {
+ for (int i = 0, n = this->file_to_generate_size(); i < n; i++) {
total_size += ::google::protobuf::internal::WireFormatLite::StringSize(
this->file_to_generate(i));
}
// repeated .google.protobuf.FileDescriptorProto proto_file = 15;
{
- unsigned int count = this->proto_file_size();
+ unsigned int count = static_cast<unsigned int>(this->proto_file_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->proto_file(i));
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->proto_file(static_cast<int>(i)));
}
}
@@ -995,7 +978,7 @@ size_t CodeGeneratorRequest::ByteSizeLong() const {
// optional .google.protobuf.compiler.Version compiler_version = 3;
if (has_compiler_version()) {
total_size += 1 +
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
*this->compiler_version_);
}
@@ -1026,14 +1009,18 @@ void CodeGeneratorRequest::MergeFrom(const CodeGeneratorRequest& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.compiler.CodeGeneratorRequest)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
file_to_generate_.MergeFrom(from.file_to_generate_);
proto_file_.MergeFrom(from.proto_file_);
- if (from._has_bits_[0 / 32] & 3u) {
- if (from.has_parameter()) {
+ cached_has_bits = from._has_bits_[0];
+ if (cached_has_bits & 3u) {
+ if (cached_has_bits & 0x00000001u) {
set_has_parameter();
parameter_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.parameter_);
}
- if (from.has_compiler_version()) {
+ if (cached_has_bits & 0x00000002u) {
mutable_compiler_version()->::google::protobuf::compiler::Version::MergeFrom(from.compiler_version());
}
}
@@ -1063,211 +1050,26 @@ void CodeGeneratorRequest::Swap(CodeGeneratorRequest* other) {
InternalSwap(other);
}
void CodeGeneratorRequest::InternalSwap(CodeGeneratorRequest* other) {
- file_to_generate_.UnsafeArenaSwap(&other->file_to_generate_);
- proto_file_.UnsafeArenaSwap(&other->proto_file_);
+ using std::swap;
+ file_to_generate_.InternalSwap(&other->file_to_generate_);
+ proto_file_.InternalSwap(&other->proto_file_);
parameter_.Swap(&other->parameter_);
- std::swap(compiler_version_, other->compiler_version_);
- std::swap(_has_bits_[0], other->_has_bits_[0]);
+ swap(compiler_version_, other->compiler_version_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- std::swap(_cached_size_, other->_cached_size_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata CodeGeneratorRequest::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[1];
+ protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// CodeGeneratorRequest
-
-// repeated string file_to_generate = 1;
-int CodeGeneratorRequest::file_to_generate_size() const {
- return file_to_generate_.size();
-}
-void CodeGeneratorRequest::clear_file_to_generate() {
- file_to_generate_.Clear();
-}
-const ::std::string& CodeGeneratorRequest::file_to_generate(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate)
- return file_to_generate_.Get(index);
-}
-::std::string* CodeGeneratorRequest::mutable_file_to_generate(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate)
- return file_to_generate_.Mutable(index);
-}
-void CodeGeneratorRequest::set_file_to_generate(int index, const ::std::string& value) {
- // @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate)
- file_to_generate_.Mutable(index)->assign(value);
-}
-void CodeGeneratorRequest::set_file_to_generate(int index, const char* value) {
- file_to_generate_.Mutable(index)->assign(value);
- // @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate)
-}
-void CodeGeneratorRequest::set_file_to_generate(int index, const char* value, size_t size) {
- file_to_generate_.Mutable(index)->assign(
- reinterpret_cast<const char*>(value), size);
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate)
-}
-::std::string* CodeGeneratorRequest::add_file_to_generate() {
- // @@protoc_insertion_point(field_add_mutable:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate)
- return file_to_generate_.Add();
-}
-void CodeGeneratorRequest::add_file_to_generate(const ::std::string& value) {
- file_to_generate_.Add()->assign(value);
- // @@protoc_insertion_point(field_add:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate)
-}
-void CodeGeneratorRequest::add_file_to_generate(const char* value) {
- file_to_generate_.Add()->assign(value);
- // @@protoc_insertion_point(field_add_char:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate)
-}
-void CodeGeneratorRequest::add_file_to_generate(const char* value, size_t size) {
- file_to_generate_.Add()->assign(reinterpret_cast<const char*>(value), size);
- // @@protoc_insertion_point(field_add_pointer:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate)
-}
-const ::google::protobuf::RepeatedPtrField< ::std::string>&
-CodeGeneratorRequest::file_to_generate() const {
- // @@protoc_insertion_point(field_list:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate)
- return file_to_generate_;
-}
-::google::protobuf::RepeatedPtrField< ::std::string>*
-CodeGeneratorRequest::mutable_file_to_generate() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate)
- return &file_to_generate_;
-}
-
-// optional string parameter = 2;
-bool CodeGeneratorRequest::has_parameter() const {
- return (_has_bits_[0] & 0x00000001u) != 0;
-}
-void CodeGeneratorRequest::set_has_parameter() {
- _has_bits_[0] |= 0x00000001u;
-}
-void CodeGeneratorRequest::clear_has_parameter() {
- _has_bits_[0] &= ~0x00000001u;
-}
-void CodeGeneratorRequest::clear_parameter() {
- parameter_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_parameter();
-}
-const ::std::string& CodeGeneratorRequest::parameter() const {
- // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorRequest.parameter)
- return parameter_.GetNoArena();
-}
-void CodeGeneratorRequest::set_parameter(const ::std::string& value) {
- set_has_parameter();
- parameter_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorRequest.parameter)
-}
-void CodeGeneratorRequest::set_parameter(const char* value) {
- set_has_parameter();
- parameter_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorRequest.parameter)
-}
-void CodeGeneratorRequest::set_parameter(const char* value, size_t size) {
- set_has_parameter();
- parameter_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.compiler.CodeGeneratorRequest.parameter)
-}
-::std::string* CodeGeneratorRequest::mutable_parameter() {
- set_has_parameter();
- // @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorRequest.parameter)
- return parameter_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* CodeGeneratorRequest::release_parameter() {
- // @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorRequest.parameter)
- clear_has_parameter();
- return parameter_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void CodeGeneratorRequest::set_allocated_parameter(::std::string* parameter) {
- if (parameter != NULL) {
- set_has_parameter();
- } else {
- clear_has_parameter();
- }
- parameter_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), parameter);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorRequest.parameter)
-}
-
-// repeated .google.protobuf.FileDescriptorProto proto_file = 15;
-int CodeGeneratorRequest::proto_file_size() const {
- return proto_file_.size();
-}
-void CodeGeneratorRequest::clear_proto_file() {
- proto_file_.Clear();
-}
-const ::google::protobuf::FileDescriptorProto& CodeGeneratorRequest::proto_file(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorRequest.proto_file)
- return proto_file_.Get(index);
-}
-::google::protobuf::FileDescriptorProto* CodeGeneratorRequest::mutable_proto_file(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorRequest.proto_file)
- return proto_file_.Mutable(index);
-}
-::google::protobuf::FileDescriptorProto* CodeGeneratorRequest::add_proto_file() {
- // @@protoc_insertion_point(field_add:google.protobuf.compiler.CodeGeneratorRequest.proto_file)
- return proto_file_.Add();
-}
-::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto >*
-CodeGeneratorRequest::mutable_proto_file() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.compiler.CodeGeneratorRequest.proto_file)
- return &proto_file_;
-}
-const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto >&
-CodeGeneratorRequest::proto_file() const {
- // @@protoc_insertion_point(field_list:google.protobuf.compiler.CodeGeneratorRequest.proto_file)
- return proto_file_;
-}
-
-// optional .google.protobuf.compiler.Version compiler_version = 3;
-bool CodeGeneratorRequest::has_compiler_version() const {
- return (_has_bits_[0] & 0x00000002u) != 0;
-}
-void CodeGeneratorRequest::set_has_compiler_version() {
- _has_bits_[0] |= 0x00000002u;
-}
-void CodeGeneratorRequest::clear_has_compiler_version() {
- _has_bits_[0] &= ~0x00000002u;
-}
-void CodeGeneratorRequest::clear_compiler_version() {
- if (compiler_version_ != NULL) compiler_version_->::google::protobuf::compiler::Version::Clear();
- clear_has_compiler_version();
-}
-const ::google::protobuf::compiler::Version& CodeGeneratorRequest::compiler_version() const {
- // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorRequest.compiler_version)
- return compiler_version_ != NULL ? *compiler_version_
- : *::google::protobuf::compiler::Version::internal_default_instance();
-}
-::google::protobuf::compiler::Version* CodeGeneratorRequest::mutable_compiler_version() {
- set_has_compiler_version();
- if (compiler_version_ == NULL) {
- compiler_version_ = new ::google::protobuf::compiler::Version;
- }
- // @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorRequest.compiler_version)
- return compiler_version_;
-}
-::google::protobuf::compiler::Version* CodeGeneratorRequest::release_compiler_version() {
- // @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorRequest.compiler_version)
- clear_has_compiler_version();
- ::google::protobuf::compiler::Version* temp = compiler_version_;
- compiler_version_ = NULL;
- return temp;
-}
-void CodeGeneratorRequest::set_allocated_compiler_version(::google::protobuf::compiler::Version* compiler_version) {
- delete compiler_version_;
- compiler_version_ = compiler_version;
- if (compiler_version) {
- set_has_compiler_version();
- } else {
- clear_has_compiler_version();
- }
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorRequest.compiler_version)
-}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
+void CodeGeneratorResponse_File::InitAsDefaultInstance() {
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int CodeGeneratorResponse_File::kNameFieldNumber;
const int CodeGeneratorResponse_File::kInsertionPointFieldNumber;
@@ -1277,7 +1079,7 @@ const int CodeGeneratorResponse_File::kContentFieldNumber;
CodeGeneratorResponse_File::CodeGeneratorResponse_File()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
+ ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorResponse_File();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.compiler.CodeGeneratorResponse.File)
@@ -1327,12 +1129,12 @@ void CodeGeneratorResponse_File::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* CodeGeneratorResponse_File::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[2].descriptor;
+ ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const CodeGeneratorResponse_File& CodeGeneratorResponse_File::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
+ ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorResponse_File();
return *internal_default_instance();
}
@@ -1346,16 +1148,21 @@ CodeGeneratorResponse_File* CodeGeneratorResponse_File::New(::google::protobuf::
void CodeGeneratorResponse_File::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.compiler.CodeGeneratorResponse.File)
- if (_has_bits_[0 / 32] & 7u) {
- if (has_name()) {
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
+ if (cached_has_bits & 7u) {
+ if (cached_has_bits & 0x00000001u) {
GOOGLE_DCHECK(!name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
(*name_.UnsafeRawStringPointer())->clear();
}
- if (has_insertion_point()) {
+ if (cached_has_bits & 0x00000002u) {
GOOGLE_DCHECK(!insertion_point_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
(*insertion_point_.UnsafeRawStringPointer())->clear();
}
- if (has_content()) {
+ if (cached_has_bits & 0x00000004u) {
GOOGLE_DCHECK(!content_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
(*content_.UnsafeRawStringPointer())->clear();
}
@@ -1376,11 +1183,12 @@ bool CodeGeneratorResponse_File::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional string name = 1;
case 1: {
- if (tag == 10u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormat::PARSE,
"google.protobuf.compiler.CodeGeneratorResponse.File.name");
} else {
@@ -1391,11 +1199,12 @@ bool CodeGeneratorResponse_File::MergePartialFromCodedStream(
// optional string insertion_point = 2;
case 2: {
- if (tag == 18u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_insertion_point()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->insertion_point().data(), this->insertion_point().length(),
+ this->insertion_point().data(), static_cast<int>(this->insertion_point().length()),
::google::protobuf::internal::WireFormat::PARSE,
"google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point");
} else {
@@ -1406,11 +1215,12 @@ bool CodeGeneratorResponse_File::MergePartialFromCodedStream(
// optional string content = 15;
case 15: {
- if (tag == 122u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(122u /* 122 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_content()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->content().data(), this->content().length(),
+ this->content().data(), static_cast<int>(this->content().length()),
::google::protobuf::internal::WireFormat::PARSE,
"google.protobuf.compiler.CodeGeneratorResponse.File.content");
} else {
@@ -1421,13 +1231,11 @@ bool CodeGeneratorResponse_File::MergePartialFromCodedStream(
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
- input, tag, mutable_unknown_fields()));
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -1444,10 +1252,14 @@ failure:
void CodeGeneratorResponse_File::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.compiler.CodeGeneratorResponse.File)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional string name = 1;
- if (has_name()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.compiler.CodeGeneratorResponse.File.name");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -1455,9 +1267,9 @@ void CodeGeneratorResponse_File::SerializeWithCachedSizes(
}
// optional string insertion_point = 2;
- if (has_insertion_point()) {
+ if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->insertion_point().data(), this->insertion_point().length(),
+ this->insertion_point().data(), static_cast<int>(this->insertion_point().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -1465,9 +1277,9 @@ void CodeGeneratorResponse_File::SerializeWithCachedSizes(
}
// optional string content = 15;
- if (has_content()) {
+ if (cached_has_bits & 0x00000004u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->content().data(), this->content().length(),
+ this->content().data(), static_cast<int>(this->content().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.compiler.CodeGeneratorResponse.File.content");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -1476,7 +1288,7 @@ void CodeGeneratorResponse_File::SerializeWithCachedSizes(
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- unknown_fields(), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.compiler.CodeGeneratorResponse.File)
}
@@ -1485,10 +1297,14 @@ void CodeGeneratorResponse_File::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.compiler.CodeGeneratorResponse.File)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional string name = 1;
- if (has_name()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.compiler.CodeGeneratorResponse.File.name");
target =
@@ -1497,9 +1313,9 @@ void CodeGeneratorResponse_File::SerializeWithCachedSizes(
}
// optional string insertion_point = 2;
- if (has_insertion_point()) {
+ if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->insertion_point().data(), this->insertion_point().length(),
+ this->insertion_point().data(), static_cast<int>(this->insertion_point().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point");
target =
@@ -1508,9 +1324,9 @@ void CodeGeneratorResponse_File::SerializeWithCachedSizes(
}
// optional string content = 15;
- if (has_content()) {
+ if (cached_has_bits & 0x00000004u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->content().data(), this->content().length(),
+ this->content().data(), static_cast<int>(this->content().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.compiler.CodeGeneratorResponse.File.content");
target =
@@ -1520,7 +1336,7 @@ void CodeGeneratorResponse_File::SerializeWithCachedSizes(
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- unknown_fields(), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.compiler.CodeGeneratorResponse.File)
return target;
@@ -1533,7 +1349,7 @@ size_t CodeGeneratorResponse_File::ByteSizeLong() const {
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- unknown_fields());
+ _internal_metadata_.unknown_fields());
}
if (_has_bits_[0 / 32] & 7u) {
// optional string name = 1;
@@ -1584,16 +1400,20 @@ void CodeGeneratorResponse_File::MergeFrom(const CodeGeneratorResponse_File& fro
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.compiler.CodeGeneratorResponse.File)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
- if (from._has_bits_[0 / 32] & 7u) {
- if (from.has_name()) {
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = from._has_bits_[0];
+ if (cached_has_bits & 7u) {
+ if (cached_has_bits & 0x00000001u) {
set_has_name();
name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_);
}
- if (from.has_insertion_point()) {
+ if (cached_has_bits & 0x00000002u) {
set_has_insertion_point();
insertion_point_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.insertion_point_);
}
- if (from.has_content()) {
+ if (cached_has_bits & 0x00000004u) {
set_has_content();
content_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.content_);
}
@@ -1623,188 +1443,25 @@ void CodeGeneratorResponse_File::Swap(CodeGeneratorResponse_File* other) {
InternalSwap(other);
}
void CodeGeneratorResponse_File::InternalSwap(CodeGeneratorResponse_File* other) {
+ using std::swap;
name_.Swap(&other->name_);
insertion_point_.Swap(&other->insertion_point_);
content_.Swap(&other->content_);
- std::swap(_has_bits_[0], other->_has_bits_[0]);
+ swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- std::swap(_cached_size_, other->_cached_size_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata CodeGeneratorResponse_File::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[2];
-}
-
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// CodeGeneratorResponse_File
-
-// optional string name = 1;
-bool CodeGeneratorResponse_File::has_name() const {
- return (_has_bits_[0] & 0x00000001u) != 0;
-}
-void CodeGeneratorResponse_File::set_has_name() {
- _has_bits_[0] |= 0x00000001u;
-}
-void CodeGeneratorResponse_File::clear_has_name() {
- _has_bits_[0] &= ~0x00000001u;
-}
-void CodeGeneratorResponse_File::clear_name() {
- name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_name();
-}
-const ::std::string& CodeGeneratorResponse_File::name() const {
- // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorResponse.File.name)
- return name_.GetNoArena();
-}
-void CodeGeneratorResponse_File::set_name(const ::std::string& value) {
- set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorResponse.File.name)
-}
-void CodeGeneratorResponse_File::set_name(const char* value) {
- set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorResponse.File.name)
-}
-void CodeGeneratorResponse_File::set_name(const char* value, size_t size) {
- set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.compiler.CodeGeneratorResponse.File.name)
-}
-::std::string* CodeGeneratorResponse_File::mutable_name() {
- set_has_name();
- // @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorResponse.File.name)
- return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* CodeGeneratorResponse_File::release_name() {
- // @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorResponse.File.name)
- clear_has_name();
- return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void CodeGeneratorResponse_File::set_allocated_name(::std::string* name) {
- if (name != NULL) {
- set_has_name();
- } else {
- clear_has_name();
- }
- name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorResponse.File.name)
-}
-
-// optional string insertion_point = 2;
-bool CodeGeneratorResponse_File::has_insertion_point() const {
- return (_has_bits_[0] & 0x00000002u) != 0;
-}
-void CodeGeneratorResponse_File::set_has_insertion_point() {
- _has_bits_[0] |= 0x00000002u;
-}
-void CodeGeneratorResponse_File::clear_has_insertion_point() {
- _has_bits_[0] &= ~0x00000002u;
-}
-void CodeGeneratorResponse_File::clear_insertion_point() {
- insertion_point_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_insertion_point();
-}
-const ::std::string& CodeGeneratorResponse_File::insertion_point() const {
- // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point)
- return insertion_point_.GetNoArena();
-}
-void CodeGeneratorResponse_File::set_insertion_point(const ::std::string& value) {
- set_has_insertion_point();
- insertion_point_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point)
-}
-void CodeGeneratorResponse_File::set_insertion_point(const char* value) {
- set_has_insertion_point();
- insertion_point_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point)
-}
-void CodeGeneratorResponse_File::set_insertion_point(const char* value, size_t size) {
- set_has_insertion_point();
- insertion_point_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point)
-}
-::std::string* CodeGeneratorResponse_File::mutable_insertion_point() {
- set_has_insertion_point();
- // @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point)
- return insertion_point_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* CodeGeneratorResponse_File::release_insertion_point() {
- // @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point)
- clear_has_insertion_point();
- return insertion_point_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void CodeGeneratorResponse_File::set_allocated_insertion_point(::std::string* insertion_point) {
- if (insertion_point != NULL) {
- set_has_insertion_point();
- } else {
- clear_has_insertion_point();
- }
- insertion_point_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), insertion_point);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point)
-}
-
-// optional string content = 15;
-bool CodeGeneratorResponse_File::has_content() const {
- return (_has_bits_[0] & 0x00000004u) != 0;
-}
-void CodeGeneratorResponse_File::set_has_content() {
- _has_bits_[0] |= 0x00000004u;
-}
-void CodeGeneratorResponse_File::clear_has_content() {
- _has_bits_[0] &= ~0x00000004u;
-}
-void CodeGeneratorResponse_File::clear_content() {
- content_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_content();
-}
-const ::std::string& CodeGeneratorResponse_File::content() const {
- // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorResponse.File.content)
- return content_.GetNoArena();
-}
-void CodeGeneratorResponse_File::set_content(const ::std::string& value) {
- set_has_content();
- content_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorResponse.File.content)
-}
-void CodeGeneratorResponse_File::set_content(const char* value) {
- set_has_content();
- content_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorResponse.File.content)
-}
-void CodeGeneratorResponse_File::set_content(const char* value, size_t size) {
- set_has_content();
- content_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.compiler.CodeGeneratorResponse.File.content)
-}
-::std::string* CodeGeneratorResponse_File::mutable_content() {
- set_has_content();
- // @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorResponse.File.content)
- return content_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* CodeGeneratorResponse_File::release_content() {
- // @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorResponse.File.content)
- clear_has_content();
- return content_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void CodeGeneratorResponse_File::set_allocated_content(::std::string* content) {
- if (content != NULL) {
- set_has_content();
- } else {
- clear_has_content();
- }
- content_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), content);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorResponse.File.content)
+ protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
+void CodeGeneratorResponse::InitAsDefaultInstance() {
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int CodeGeneratorResponse::kErrorFieldNumber;
const int CodeGeneratorResponse::kFileFieldNumber;
@@ -1813,7 +1470,7 @@ const int CodeGeneratorResponse::kFileFieldNumber;
CodeGeneratorResponse::CodeGeneratorResponse()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
+ ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorResponse();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.compiler.CodeGeneratorResponse)
@@ -1852,12 +1509,12 @@ void CodeGeneratorResponse::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* CodeGeneratorResponse::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[3].descriptor;
+ ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const CodeGeneratorResponse& CodeGeneratorResponse::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
+ ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorResponse();
return *internal_default_instance();
}
@@ -1871,8 +1528,13 @@ CodeGeneratorResponse* CodeGeneratorResponse::New(::google::protobuf::Arena* are
void CodeGeneratorResponse::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.compiler.CodeGeneratorResponse)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
file_.Clear();
- if (has_error()) {
+ cached_has_bits = _has_bits_[0];
+ if (cached_has_bits & 0x00000001u) {
GOOGLE_DCHECK(!error_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
(*error_.UnsafeRawStringPointer())->clear();
}
@@ -1892,11 +1554,12 @@ bool CodeGeneratorResponse::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional string error = 1;
case 1: {
- if (tag == 10u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_error()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->error().data(), this->error().length(),
+ this->error().data(), static_cast<int>(this->error().length()),
::google::protobuf::internal::WireFormat::PARSE,
"google.protobuf.compiler.CodeGeneratorResponse.error");
} else {
@@ -1907,26 +1570,22 @@ bool CodeGeneratorResponse::MergePartialFromCodedStream(
// repeated .google.protobuf.compiler.CodeGeneratorResponse.File file = 15;
case 15: {
- if (tag == 122u) {
- DO_(input->IncrementRecursionDepth());
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
- input, add_file()));
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(122u /* 122 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_file()));
} else {
goto handle_unusual;
}
- input->UnsafeDecrementRecursionDepth();
break;
}
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
- input, tag, mutable_unknown_fields()));
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -1943,10 +1602,14 @@ failure:
void CodeGeneratorResponse::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.compiler.CodeGeneratorResponse)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional string error = 1;
- if (has_error()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->error().data(), this->error().length(),
+ this->error().data(), static_cast<int>(this->error().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.compiler.CodeGeneratorResponse.error");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -1954,14 +1617,15 @@ void CodeGeneratorResponse::SerializeWithCachedSizes(
}
// repeated .google.protobuf.compiler.CodeGeneratorResponse.File file = 15;
- for (unsigned int i = 0, n = this->file_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->file_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 15, this->file(i), output);
+ 15, this->file(static_cast<int>(i)), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- unknown_fields(), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.compiler.CodeGeneratorResponse)
}
@@ -1970,10 +1634,14 @@ void CodeGeneratorResponse::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.compiler.CodeGeneratorResponse)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional string error = 1;
- if (has_error()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->error().data(), this->error().length(),
+ this->error().data(), static_cast<int>(this->error().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.compiler.CodeGeneratorResponse.error");
target =
@@ -1982,15 +1650,16 @@ void CodeGeneratorResponse::SerializeWithCachedSizes(
}
// repeated .google.protobuf.compiler.CodeGeneratorResponse.File file = 15;
- for (unsigned int i = 0, n = this->file_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->file_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 15, this->file(i), false, target);
+ InternalWriteMessageToArray(
+ 15, this->file(static_cast<int>(i)), deterministic, target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- unknown_fields(), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.compiler.CodeGeneratorResponse)
return target;
@@ -2003,16 +1672,16 @@ size_t CodeGeneratorResponse::ByteSizeLong() const {
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- unknown_fields());
+ _internal_metadata_.unknown_fields());
}
// repeated .google.protobuf.compiler.CodeGeneratorResponse.File file = 15;
{
- unsigned int count = this->file_size();
+ unsigned int count = static_cast<unsigned int>(this->file_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->file(i));
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->file(static_cast<int>(i)));
}
}
@@ -2049,6 +1718,9 @@ void CodeGeneratorResponse::MergeFrom(const CodeGeneratorResponse& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.compiler.CodeGeneratorResponse)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
file_.MergeFrom(from.file_);
if (from.has_error()) {
set_has_error();
@@ -2079,109 +1751,21 @@ void CodeGeneratorResponse::Swap(CodeGeneratorResponse* other) {
InternalSwap(other);
}
void CodeGeneratorResponse::InternalSwap(CodeGeneratorResponse* other) {
- file_.UnsafeArenaSwap(&other->file_);
+ using std::swap;
+ file_.InternalSwap(&other->file_);
error_.Swap(&other->error_);
- std::swap(_has_bits_[0], other->_has_bits_[0]);
+ swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- std::swap(_cached_size_, other->_cached_size_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata CodeGeneratorResponse::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[3];
+ protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// CodeGeneratorResponse
-
-// optional string error = 1;
-bool CodeGeneratorResponse::has_error() const {
- return (_has_bits_[0] & 0x00000001u) != 0;
-}
-void CodeGeneratorResponse::set_has_error() {
- _has_bits_[0] |= 0x00000001u;
-}
-void CodeGeneratorResponse::clear_has_error() {
- _has_bits_[0] &= ~0x00000001u;
-}
-void CodeGeneratorResponse::clear_error() {
- error_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_error();
-}
-const ::std::string& CodeGeneratorResponse::error() const {
- // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorResponse.error)
- return error_.GetNoArena();
-}
-void CodeGeneratorResponse::set_error(const ::std::string& value) {
- set_has_error();
- error_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorResponse.error)
-}
-void CodeGeneratorResponse::set_error(const char* value) {
- set_has_error();
- error_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorResponse.error)
-}
-void CodeGeneratorResponse::set_error(const char* value, size_t size) {
- set_has_error();
- error_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.compiler.CodeGeneratorResponse.error)
-}
-::std::string* CodeGeneratorResponse::mutable_error() {
- set_has_error();
- // @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorResponse.error)
- return error_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* CodeGeneratorResponse::release_error() {
- // @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorResponse.error)
- clear_has_error();
- return error_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void CodeGeneratorResponse::set_allocated_error(::std::string* error) {
- if (error != NULL) {
- set_has_error();
- } else {
- clear_has_error();
- }
- error_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), error);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorResponse.error)
-}
-
-// repeated .google.protobuf.compiler.CodeGeneratorResponse.File file = 15;
-int CodeGeneratorResponse::file_size() const {
- return file_.size();
-}
-void CodeGeneratorResponse::clear_file() {
- file_.Clear();
-}
-const ::google::protobuf::compiler::CodeGeneratorResponse_File& CodeGeneratorResponse::file(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorResponse.file)
- return file_.Get(index);
-}
-::google::protobuf::compiler::CodeGeneratorResponse_File* CodeGeneratorResponse::mutable_file(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorResponse.file)
- return file_.Mutable(index);
-}
-::google::protobuf::compiler::CodeGeneratorResponse_File* CodeGeneratorResponse::add_file() {
- // @@protoc_insertion_point(field_add:google.protobuf.compiler.CodeGeneratorResponse.file)
- return file_.Add();
-}
-::google::protobuf::RepeatedPtrField< ::google::protobuf::compiler::CodeGeneratorResponse_File >*
-CodeGeneratorResponse::mutable_file() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.compiler.CodeGeneratorResponse.file)
- return &file_;
-}
-const ::google::protobuf::RepeatedPtrField< ::google::protobuf::compiler::CodeGeneratorResponse_File >&
-CodeGeneratorResponse::file() const {
- // @@protoc_insertion_point(field_list:google.protobuf.compiler.CodeGeneratorResponse.file)
- return file_;
-}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
-
} // namespace compiler
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/compiler/plugin.pb.h b/src/google/protobuf/compiler/plugin.pb.h
index 0948ab2d..8f92b6ae 100644
--- a/src/google/protobuf/compiler/plugin.pb.h
+++ b/src/google/protobuf/compiler/plugin.pb.h
@@ -8,19 +8,21 @@
#include <google/protobuf/stubs/common.h>
-#if GOOGLE_PROTOBUF_VERSION < 3001000
+#if GOOGLE_PROTOBUF_VERSION < 3004000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3001000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3004000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
+#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
+#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
@@ -29,83 +31,41 @@
#include <google/protobuf/unknown_field_set.h>
#include <google/protobuf/descriptor.pb.h>
// @@protoc_insertion_point(includes)
+#ifdef major
+#undef major
+#endif
+#ifdef minor
+#undef minor
+#endif
+
+namespace protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto {
+// Internal implementation detail -- do not use these members.
+struct LIBPROTOC_EXPORT TableStruct {
+ static const ::google::protobuf::internal::ParseTableField entries[];
+ static const ::google::protobuf::internal::AuxillaryParseTableField aux[];
+ static const ::google::protobuf::internal::ParseTable schema[4];
+ static const ::google::protobuf::internal::FieldMetadata field_metadata[];
+ static const ::google::protobuf::internal::SerializationTable serialization_table[];
+ static const ::google::protobuf::uint32 offsets[];
+};
+void LIBPROTOC_EXPORT AddDescriptors();
+void LIBPROTOC_EXPORT InitDefaultsVersionImpl();
+void LIBPROTOC_EXPORT InitDefaultsVersion();
+void LIBPROTOC_EXPORT InitDefaultsCodeGeneratorRequestImpl();
+void LIBPROTOC_EXPORT InitDefaultsCodeGeneratorRequest();
+void LIBPROTOC_EXPORT InitDefaultsCodeGeneratorResponse_FileImpl();
+void LIBPROTOC_EXPORT InitDefaultsCodeGeneratorResponse_File();
+void LIBPROTOC_EXPORT InitDefaultsCodeGeneratorResponseImpl();
+void LIBPROTOC_EXPORT InitDefaultsCodeGeneratorResponse();
+inline void LIBPROTOC_EXPORT InitDefaults() {
+ InitDefaultsVersion();
+ InitDefaultsCodeGeneratorRequest();
+ InitDefaultsCodeGeneratorResponse_File();
+ InitDefaultsCodeGeneratorResponse();
+}
+} // namespace protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto
namespace google {
namespace protobuf {
-class DescriptorProto;
-class DescriptorProtoDefaultTypeInternal;
-LIBPROTOC_EXPORT extern DescriptorProtoDefaultTypeInternal _DescriptorProto_default_instance_;
-class DescriptorProto_ExtensionRange;
-class DescriptorProto_ExtensionRangeDefaultTypeInternal;
-LIBPROTOC_EXPORT extern DescriptorProto_ExtensionRangeDefaultTypeInternal _DescriptorProto_ExtensionRange_default_instance_;
-class DescriptorProto_ReservedRange;
-class DescriptorProto_ReservedRangeDefaultTypeInternal;
-LIBPROTOC_EXPORT extern DescriptorProto_ReservedRangeDefaultTypeInternal _DescriptorProto_ReservedRange_default_instance_;
-class EnumDescriptorProto;
-class EnumDescriptorProtoDefaultTypeInternal;
-LIBPROTOC_EXPORT extern EnumDescriptorProtoDefaultTypeInternal _EnumDescriptorProto_default_instance_;
-class EnumOptions;
-class EnumOptionsDefaultTypeInternal;
-LIBPROTOC_EXPORT extern EnumOptionsDefaultTypeInternal _EnumOptions_default_instance_;
-class EnumValueDescriptorProto;
-class EnumValueDescriptorProtoDefaultTypeInternal;
-LIBPROTOC_EXPORT extern EnumValueDescriptorProtoDefaultTypeInternal _EnumValueDescriptorProto_default_instance_;
-class EnumValueOptions;
-class EnumValueOptionsDefaultTypeInternal;
-LIBPROTOC_EXPORT extern EnumValueOptionsDefaultTypeInternal _EnumValueOptions_default_instance_;
-class FieldDescriptorProto;
-class FieldDescriptorProtoDefaultTypeInternal;
-LIBPROTOC_EXPORT extern FieldDescriptorProtoDefaultTypeInternal _FieldDescriptorProto_default_instance_;
-class FieldOptions;
-class FieldOptionsDefaultTypeInternal;
-LIBPROTOC_EXPORT extern FieldOptionsDefaultTypeInternal _FieldOptions_default_instance_;
-class FileDescriptorProto;
-class FileDescriptorProtoDefaultTypeInternal;
-LIBPROTOC_EXPORT extern FileDescriptorProtoDefaultTypeInternal _FileDescriptorProto_default_instance_;
-class FileDescriptorSet;
-class FileDescriptorSetDefaultTypeInternal;
-LIBPROTOC_EXPORT extern FileDescriptorSetDefaultTypeInternal _FileDescriptorSet_default_instance_;
-class FileOptions;
-class FileOptionsDefaultTypeInternal;
-LIBPROTOC_EXPORT extern FileOptionsDefaultTypeInternal _FileOptions_default_instance_;
-class GeneratedCodeInfo;
-class GeneratedCodeInfoDefaultTypeInternal;
-LIBPROTOC_EXPORT extern GeneratedCodeInfoDefaultTypeInternal _GeneratedCodeInfo_default_instance_;
-class GeneratedCodeInfo_Annotation;
-class GeneratedCodeInfo_AnnotationDefaultTypeInternal;
-LIBPROTOC_EXPORT extern GeneratedCodeInfo_AnnotationDefaultTypeInternal _GeneratedCodeInfo_Annotation_default_instance_;
-class MessageOptions;
-class MessageOptionsDefaultTypeInternal;
-LIBPROTOC_EXPORT extern MessageOptionsDefaultTypeInternal _MessageOptions_default_instance_;
-class MethodDescriptorProto;
-class MethodDescriptorProtoDefaultTypeInternal;
-LIBPROTOC_EXPORT extern MethodDescriptorProtoDefaultTypeInternal _MethodDescriptorProto_default_instance_;
-class MethodOptions;
-class MethodOptionsDefaultTypeInternal;
-LIBPROTOC_EXPORT extern MethodOptionsDefaultTypeInternal _MethodOptions_default_instance_;
-class OneofDescriptorProto;
-class OneofDescriptorProtoDefaultTypeInternal;
-LIBPROTOC_EXPORT extern OneofDescriptorProtoDefaultTypeInternal _OneofDescriptorProto_default_instance_;
-class OneofOptions;
-class OneofOptionsDefaultTypeInternal;
-LIBPROTOC_EXPORT extern OneofOptionsDefaultTypeInternal _OneofOptions_default_instance_;
-class ServiceDescriptorProto;
-class ServiceDescriptorProtoDefaultTypeInternal;
-LIBPROTOC_EXPORT extern ServiceDescriptorProtoDefaultTypeInternal _ServiceDescriptorProto_default_instance_;
-class ServiceOptions;
-class ServiceOptionsDefaultTypeInternal;
-LIBPROTOC_EXPORT extern ServiceOptionsDefaultTypeInternal _ServiceOptions_default_instance_;
-class SourceCodeInfo;
-class SourceCodeInfoDefaultTypeInternal;
-LIBPROTOC_EXPORT extern SourceCodeInfoDefaultTypeInternal _SourceCodeInfo_default_instance_;
-class SourceCodeInfo_Location;
-class SourceCodeInfo_LocationDefaultTypeInternal;
-LIBPROTOC_EXPORT extern SourceCodeInfo_LocationDefaultTypeInternal _SourceCodeInfo_Location_default_instance_;
-class UninterpretedOption;
-class UninterpretedOptionDefaultTypeInternal;
-LIBPROTOC_EXPORT extern UninterpretedOptionDefaultTypeInternal _UninterpretedOption_default_instance_;
-class UninterpretedOption_NamePart;
-class UninterpretedOption_NamePartDefaultTypeInternal;
-LIBPROTOC_EXPORT extern UninterpretedOption_NamePartDefaultTypeInternal _UninterpretedOption_NamePart_default_instance_;
namespace compiler {
class CodeGeneratorRequest;
class CodeGeneratorRequestDefaultTypeInternal;
@@ -122,15 +82,10 @@ LIBPROTOC_EXPORT extern VersionDefaultTypeInternal _Version_default_instance_;
} // namespace compiler
} // namespace protobuf
} // namespace google
-
namespace google {
namespace protobuf {
namespace compiler {
-// Internal implementation detail -- do not call these.
-void LIBPROTOC_EXPORT protobuf_AddDesc_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
-void LIBPROTOC_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
-
// ===================================================================
class LIBPROTOC_EXPORT Version : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.compiler.Version) */ {
@@ -144,11 +99,24 @@ class LIBPROTOC_EXPORT Version : public ::google::protobuf::Message /* @@protoc_
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ Version(Version&& from) noexcept
+ : Version() {
+ *this = ::std::move(from);
+ }
+ inline Version& operator=(Version&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
-
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
@@ -156,12 +124,18 @@ class LIBPROTOC_EXPORT Version : public ::google::protobuf::Message /* @@protoc_
static const ::google::protobuf::Descriptor* descriptor();
static const Version& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const Version* internal_default_instance() {
return reinterpret_cast<const Version*>(
&_Version_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 0;
void Swap(Version* other);
+ friend void swap(Version& a, Version& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -182,10 +156,6 @@ class LIBPROTOC_EXPORT Version : public ::google::protobuf::Message /* @@protoc_
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
@@ -207,6 +177,21 @@ class LIBPROTOC_EXPORT Version : public ::google::protobuf::Message /* @@protoc_
// accessors -------------------------------------------------------
+ // optional string suffix = 4;
+ bool has_suffix() const;
+ void clear_suffix();
+ static const int kSuffixFieldNumber = 4;
+ const ::std::string& suffix() const;
+ void set_suffix(const ::std::string& value);
+ #if LANG_CXX11
+ void set_suffix(::std::string&& value);
+ #endif
+ void set_suffix(const char* value);
+ void set_suffix(const char* value, size_t size);
+ ::std::string* mutable_suffix();
+ ::std::string* release_suffix();
+ void set_allocated_suffix(::std::string* suffix);
+
// optional int32 major = 1;
bool has_major() const;
void clear_major();
@@ -228,18 +213,6 @@ class LIBPROTOC_EXPORT Version : public ::google::protobuf::Message /* @@protoc_
::google::protobuf::int32 patch() const;
void set_patch(::google::protobuf::int32 value);
- // optional string suffix = 4;
- bool has_suffix() const;
- void clear_suffix();
- static const int kSuffixFieldNumber = 4;
- const ::std::string& suffix() const;
- void set_suffix(const ::std::string& value);
- void set_suffix(const char* value);
- void set_suffix(const char* value, size_t size);
- ::std::string* mutable_suffix();
- ::std::string* release_suffix();
- void set_allocated_suffix(::std::string* suffix);
-
// @@protoc_insertion_point(class_scope:google.protobuf.compiler.Version)
private:
void set_has_major();
@@ -258,11 +231,8 @@ class LIBPROTOC_EXPORT Version : public ::google::protobuf::Message /* @@protoc_
::google::protobuf::int32 major_;
::google::protobuf::int32 minor_;
::google::protobuf::int32 patch_;
- friend void LIBPROTOC_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fcompiler_2fplugin_2eproto_impl();
- friend void LIBPROTOC_EXPORT protobuf_AddDesc_google_2fprotobuf_2fcompiler_2fplugin_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsVersionImpl();
};
// -------------------------------------------------------------------
@@ -277,11 +247,24 @@ class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ CodeGeneratorRequest(CodeGeneratorRequest&& from) noexcept
+ : CodeGeneratorRequest() {
+ *this = ::std::move(from);
+ }
+ inline CodeGeneratorRequest& operator=(CodeGeneratorRequest&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
-
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
@@ -289,12 +272,18 @@ class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message
static const ::google::protobuf::Descriptor* descriptor();
static const CodeGeneratorRequest& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const CodeGeneratorRequest* internal_default_instance() {
return reinterpret_cast<const CodeGeneratorRequest*>(
&_CodeGeneratorRequest_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 1;
void Swap(CodeGeneratorRequest* other);
+ friend void swap(CodeGeneratorRequest& a, CodeGeneratorRequest& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -315,10 +304,6 @@ class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
@@ -347,27 +332,21 @@ class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message
const ::std::string& file_to_generate(int index) const;
::std::string* mutable_file_to_generate(int index);
void set_file_to_generate(int index, const ::std::string& value);
+ #if LANG_CXX11
+ void set_file_to_generate(int index, ::std::string&& value);
+ #endif
void set_file_to_generate(int index, const char* value);
void set_file_to_generate(int index, const char* value, size_t size);
::std::string* add_file_to_generate();
void add_file_to_generate(const ::std::string& value);
+ #if LANG_CXX11
+ void add_file_to_generate(::std::string&& value);
+ #endif
void add_file_to_generate(const char* value);
void add_file_to_generate(const char* value, size_t size);
const ::google::protobuf::RepeatedPtrField< ::std::string>& file_to_generate() const;
::google::protobuf::RepeatedPtrField< ::std::string>* mutable_file_to_generate();
- // optional string parameter = 2;
- bool has_parameter() const;
- void clear_parameter();
- static const int kParameterFieldNumber = 2;
- const ::std::string& parameter() const;
- void set_parameter(const ::std::string& value);
- void set_parameter(const char* value);
- void set_parameter(const char* value, size_t size);
- ::std::string* mutable_parameter();
- ::std::string* release_parameter();
- void set_allocated_parameter(::std::string* parameter);
-
// repeated .google.protobuf.FileDescriptorProto proto_file = 15;
int proto_file_size() const;
void clear_proto_file();
@@ -380,13 +359,28 @@ class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto >&
proto_file() const;
+ // optional string parameter = 2;
+ bool has_parameter() const;
+ void clear_parameter();
+ static const int kParameterFieldNumber = 2;
+ const ::std::string& parameter() const;
+ void set_parameter(const ::std::string& value);
+ #if LANG_CXX11
+ void set_parameter(::std::string&& value);
+ #endif
+ void set_parameter(const char* value);
+ void set_parameter(const char* value, size_t size);
+ ::std::string* mutable_parameter();
+ ::std::string* release_parameter();
+ void set_allocated_parameter(::std::string* parameter);
+
// optional .google.protobuf.compiler.Version compiler_version = 3;
bool has_compiler_version() const;
void clear_compiler_version();
static const int kCompilerVersionFieldNumber = 3;
const ::google::protobuf::compiler::Version& compiler_version() const;
- ::google::protobuf::compiler::Version* mutable_compiler_version();
::google::protobuf::compiler::Version* release_compiler_version();
+ ::google::protobuf::compiler::Version* mutable_compiler_version();
void set_allocated_compiler_version(::google::protobuf::compiler::Version* compiler_version);
// @@protoc_insertion_point(class_scope:google.protobuf.compiler.CodeGeneratorRequest)
@@ -403,11 +397,8 @@ class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message
::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto > proto_file_;
::google::protobuf::internal::ArenaStringPtr parameter_;
::google::protobuf::compiler::Version* compiler_version_;
- friend void LIBPROTOC_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fcompiler_2fplugin_2eproto_impl();
- friend void LIBPROTOC_EXPORT protobuf_AddDesc_google_2fprotobuf_2fcompiler_2fplugin_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorRequestImpl();
};
// -------------------------------------------------------------------
@@ -422,11 +413,24 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::M
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ CodeGeneratorResponse_File(CodeGeneratorResponse_File&& from) noexcept
+ : CodeGeneratorResponse_File() {
+ *this = ::std::move(from);
+ }
+ inline CodeGeneratorResponse_File& operator=(CodeGeneratorResponse_File&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
-
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
@@ -434,12 +438,18 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::M
static const ::google::protobuf::Descriptor* descriptor();
static const CodeGeneratorResponse_File& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const CodeGeneratorResponse_File* internal_default_instance() {
return reinterpret_cast<const CodeGeneratorResponse_File*>(
&_CodeGeneratorResponse_File_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 2;
void Swap(CodeGeneratorResponse_File* other);
+ friend void swap(CodeGeneratorResponse_File& a, CodeGeneratorResponse_File& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -460,10 +470,6 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::M
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
@@ -491,6 +497,9 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::M
static const int kNameFieldNumber = 1;
const ::std::string& name() const;
void set_name(const ::std::string& value);
+ #if LANG_CXX11
+ void set_name(::std::string&& value);
+ #endif
void set_name(const char* value);
void set_name(const char* value, size_t size);
::std::string* mutable_name();
@@ -503,6 +512,9 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::M
static const int kInsertionPointFieldNumber = 2;
const ::std::string& insertion_point() const;
void set_insertion_point(const ::std::string& value);
+ #if LANG_CXX11
+ void set_insertion_point(::std::string&& value);
+ #endif
void set_insertion_point(const char* value);
void set_insertion_point(const char* value, size_t size);
::std::string* mutable_insertion_point();
@@ -515,6 +527,9 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::M
static const int kContentFieldNumber = 15;
const ::std::string& content() const;
void set_content(const ::std::string& value);
+ #if LANG_CXX11
+ void set_content(::std::string&& value);
+ #endif
void set_content(const char* value);
void set_content(const char* value, size_t size);
::std::string* mutable_content();
@@ -536,11 +551,8 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::M
::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::internal::ArenaStringPtr insertion_point_;
::google::protobuf::internal::ArenaStringPtr content_;
- friend void LIBPROTOC_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fcompiler_2fplugin_2eproto_impl();
- friend void LIBPROTOC_EXPORT protobuf_AddDesc_google_2fprotobuf_2fcompiler_2fplugin_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorResponse_FileImpl();
};
// -------------------------------------------------------------------
@@ -555,11 +567,24 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Messag
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ CodeGeneratorResponse(CodeGeneratorResponse&& from) noexcept
+ : CodeGeneratorResponse() {
+ *this = ::std::move(from);
+ }
+ inline CodeGeneratorResponse& operator=(CodeGeneratorResponse&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
-
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
@@ -567,12 +592,18 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Messag
static const ::google::protobuf::Descriptor* descriptor();
static const CodeGeneratorResponse& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const CodeGeneratorResponse* internal_default_instance() {
return reinterpret_cast<const CodeGeneratorResponse*>(
&_CodeGeneratorResponse_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 3;
void Swap(CodeGeneratorResponse* other);
+ friend void swap(CodeGeneratorResponse& a, CodeGeneratorResponse& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -593,10 +624,6 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Messag
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
@@ -620,18 +647,6 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Messag
// accessors -------------------------------------------------------
- // optional string error = 1;
- bool has_error() const;
- void clear_error();
- static const int kErrorFieldNumber = 1;
- const ::std::string& error() const;
- void set_error(const ::std::string& value);
- void set_error(const char* value);
- void set_error(const char* value, size_t size);
- ::std::string* mutable_error();
- ::std::string* release_error();
- void set_allocated_error(::std::string* error);
-
// repeated .google.protobuf.compiler.CodeGeneratorResponse.File file = 15;
int file_size() const;
void clear_file();
@@ -644,6 +659,21 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Messag
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::compiler::CodeGeneratorResponse_File >&
file() const;
+ // optional string error = 1;
+ bool has_error() const;
+ void clear_error();
+ static const int kErrorFieldNumber = 1;
+ const ::std::string& error() const;
+ void set_error(const ::std::string& value);
+ #if LANG_CXX11
+ void set_error(::std::string&& value);
+ #endif
+ void set_error(const char* value);
+ void set_error(const char* value, size_t size);
+ ::std::string* mutable_error();
+ ::std::string* release_error();
+ void set_allocated_error(::std::string* error);
+
// @@protoc_insertion_point(class_scope:google.protobuf.compiler.CodeGeneratorResponse)
private:
void set_has_error();
@@ -654,18 +684,18 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Messag
mutable int _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::compiler::CodeGeneratorResponse_File > file_;
::google::protobuf::internal::ArenaStringPtr error_;
- friend void LIBPROTOC_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fcompiler_2fplugin_2eproto_impl();
- friend void LIBPROTOC_EXPORT protobuf_AddDesc_google_2fprotobuf_2fcompiler_2fplugin_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorResponseImpl();
};
// ===================================================================
// ===================================================================
-#if !PROTOBUF_INLINE_NOT_IN_HEADERS
+#ifdef __GNUC__
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wstrict-aliasing"
+#endif // __GNUC__
// Version
// optional int32 major = 1;
@@ -763,7 +793,16 @@ inline void Version::set_suffix(const ::std::string& value) {
suffix_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.compiler.Version.suffix)
}
+#if LANG_CXX11
+inline void Version::set_suffix(::std::string&& value) {
+ set_has_suffix();
+ suffix_.SetNoArena(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.compiler.Version.suffix)
+}
+#endif
inline void Version::set_suffix(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
set_has_suffix();
suffix_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.compiler.Version.suffix)
@@ -817,7 +856,14 @@ inline void CodeGeneratorRequest::set_file_to_generate(int index, const ::std::s
// @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate)
file_to_generate_.Mutable(index)->assign(value);
}
+#if LANG_CXX11
+inline void CodeGeneratorRequest::set_file_to_generate(int index, ::std::string&& value) {
+ // @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate)
+ file_to_generate_.Mutable(index)->assign(std::move(value));
+}
+#endif
inline void CodeGeneratorRequest::set_file_to_generate(int index, const char* value) {
+ GOOGLE_DCHECK(value != NULL);
file_to_generate_.Mutable(index)->assign(value);
// @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate)
}
@@ -834,7 +880,14 @@ inline void CodeGeneratorRequest::add_file_to_generate(const ::std::string& valu
file_to_generate_.Add()->assign(value);
// @@protoc_insertion_point(field_add:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate)
}
+#if LANG_CXX11
+inline void CodeGeneratorRequest::add_file_to_generate(::std::string&& value) {
+ file_to_generate_.Add(std::move(value));
+ // @@protoc_insertion_point(field_add:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate)
+}
+#endif
inline void CodeGeneratorRequest::add_file_to_generate(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
file_to_generate_.Add()->assign(value);
// @@protoc_insertion_point(field_add_char:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate)
}
@@ -876,7 +929,16 @@ inline void CodeGeneratorRequest::set_parameter(const ::std::string& value) {
parameter_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorRequest.parameter)
}
+#if LANG_CXX11
+inline void CodeGeneratorRequest::set_parameter(::std::string&& value) {
+ set_has_parameter();
+ parameter_.SetNoArena(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.compiler.CodeGeneratorRequest.parameter)
+}
+#endif
inline void CodeGeneratorRequest::set_parameter(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
set_has_parameter();
parameter_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorRequest.parameter)
@@ -911,9 +973,6 @@ inline void CodeGeneratorRequest::set_allocated_parameter(::std::string* paramet
inline int CodeGeneratorRequest::proto_file_size() const {
return proto_file_.size();
}
-inline void CodeGeneratorRequest::clear_proto_file() {
- proto_file_.Clear();
-}
inline const ::google::protobuf::FileDescriptorProto& CodeGeneratorRequest::proto_file(int index) const {
// @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorRequest.proto_file)
return proto_file_.Get(index);
@@ -948,13 +1007,21 @@ inline void CodeGeneratorRequest::clear_has_compiler_version() {
_has_bits_[0] &= ~0x00000002u;
}
inline void CodeGeneratorRequest::clear_compiler_version() {
- if (compiler_version_ != NULL) compiler_version_->::google::protobuf::compiler::Version::Clear();
+ if (compiler_version_ != NULL) compiler_version_->Clear();
clear_has_compiler_version();
}
inline const ::google::protobuf::compiler::Version& CodeGeneratorRequest::compiler_version() const {
+ const ::google::protobuf::compiler::Version* p = compiler_version_;
// @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorRequest.compiler_version)
- return compiler_version_ != NULL ? *compiler_version_
- : *::google::protobuf::compiler::Version::internal_default_instance();
+ return p != NULL ? *p : *reinterpret_cast<const ::google::protobuf::compiler::Version*>(
+ &::google::protobuf::compiler::_Version_default_instance_);
+}
+inline ::google::protobuf::compiler::Version* CodeGeneratorRequest::release_compiler_version() {
+ // @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorRequest.compiler_version)
+ clear_has_compiler_version();
+ ::google::protobuf::compiler::Version* temp = compiler_version_;
+ compiler_version_ = NULL;
+ return temp;
}
inline ::google::protobuf::compiler::Version* CodeGeneratorRequest::mutable_compiler_version() {
set_has_compiler_version();
@@ -964,21 +1031,22 @@ inline ::google::protobuf::compiler::Version* CodeGeneratorRequest::mutable_comp
// @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorRequest.compiler_version)
return compiler_version_;
}
-inline ::google::protobuf::compiler::Version* CodeGeneratorRequest::release_compiler_version() {
- // @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorRequest.compiler_version)
- clear_has_compiler_version();
- ::google::protobuf::compiler::Version* temp = compiler_version_;
- compiler_version_ = NULL;
- return temp;
-}
inline void CodeGeneratorRequest::set_allocated_compiler_version(::google::protobuf::compiler::Version* compiler_version) {
- delete compiler_version_;
- compiler_version_ = compiler_version;
+ ::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
+ if (message_arena == NULL) {
+ delete compiler_version_;
+ }
if (compiler_version) {
+ ::google::protobuf::Arena* submessage_arena = NULL;
+ if (message_arena != submessage_arena) {
+ compiler_version = ::google::protobuf::internal::GetOwnedMessage(
+ message_arena, compiler_version, submessage_arena);
+ }
set_has_compiler_version();
} else {
clear_has_compiler_version();
}
+ compiler_version_ = compiler_version;
// @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorRequest.compiler_version)
}
@@ -1009,7 +1077,16 @@ inline void CodeGeneratorResponse_File::set_name(const ::std::string& value) {
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorResponse.File.name)
}
+#if LANG_CXX11
+inline void CodeGeneratorResponse_File::set_name(::std::string&& value) {
+ set_has_name();
+ name_.SetNoArena(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.compiler.CodeGeneratorResponse.File.name)
+}
+#endif
inline void CodeGeneratorResponse_File::set_name(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
set_has_name();
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorResponse.File.name)
@@ -1063,7 +1140,16 @@ inline void CodeGeneratorResponse_File::set_insertion_point(const ::std::string&
insertion_point_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point)
}
+#if LANG_CXX11
+inline void CodeGeneratorResponse_File::set_insertion_point(::std::string&& value) {
+ set_has_insertion_point();
+ insertion_point_.SetNoArena(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point)
+}
+#endif
inline void CodeGeneratorResponse_File::set_insertion_point(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
set_has_insertion_point();
insertion_point_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point)
@@ -1117,7 +1203,16 @@ inline void CodeGeneratorResponse_File::set_content(const ::std::string& value)
content_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorResponse.File.content)
}
+#if LANG_CXX11
+inline void CodeGeneratorResponse_File::set_content(::std::string&& value) {
+ set_has_content();
+ content_.SetNoArena(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.compiler.CodeGeneratorResponse.File.content)
+}
+#endif
inline void CodeGeneratorResponse_File::set_content(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
set_has_content();
content_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorResponse.File.content)
@@ -1175,7 +1270,16 @@ inline void CodeGeneratorResponse::set_error(const ::std::string& value) {
error_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorResponse.error)
}
+#if LANG_CXX11
+inline void CodeGeneratorResponse::set_error(::std::string&& value) {
+ set_has_error();
+ error_.SetNoArena(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.compiler.CodeGeneratorResponse.error)
+}
+#endif
inline void CodeGeneratorResponse::set_error(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
set_has_error();
error_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorResponse.error)
@@ -1236,7 +1340,9 @@ CodeGeneratorResponse::file() const {
return file_;
}
-#endif // !PROTOBUF_INLINE_NOT_IN_HEADERS
+#ifdef __GNUC__
+ #pragma GCC diagnostic pop
+#endif // __GNUC__
// -------------------------------------------------------------------
// -------------------------------------------------------------------
@@ -1246,7 +1352,6 @@ CodeGeneratorResponse::file() const {
// @@protoc_insertion_point(namespace_scope)
-
} // namespace compiler
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/compiler/plugin.proto b/src/google/protobuf/compiler/plugin.proto
index 6e4da2c1..5b557452 100644
--- a/src/google/protobuf/compiler/plugin.proto
+++ b/src/google/protobuf/compiler/plugin.proto
@@ -49,7 +49,7 @@ package google.protobuf.compiler;
option java_package = "com.google.protobuf.compiler";
option java_outer_classname = "PluginProtos";
-option go_package = "plugin_go";
+option go_package = "github.com/golang/protobuf/protoc-gen-go/plugin;plugin_go";
import "google/protobuf/descriptor.proto";
@@ -84,10 +84,14 @@ message CodeGeneratorRequest {
// the entire set into memory at once. However, as of this writing, this
// is not similarly optimized on protoc's end -- it will store all fields in
// memory at once before sending them to the plugin.
+ //
+ // Type names of fields and extensions in the FileDescriptorProto are always
+ // fully qualified.
repeated FileDescriptorProto proto_file = 15;
// The version number of protocol compiler.
optional Version compiler_version = 3;
+
}
// The plugin writes an encoded CodeGeneratorResponse to stdout.
diff --git a/src/google/protobuf/compiler/python/python_generator.cc b/src/google/protobuf/compiler/python/python_generator.cc
index f5769128..5ca6b4ee 100644
--- a/src/google/protobuf/compiler/python/python_generator.cc
+++ b/src/google/protobuf/compiler/python/python_generator.cc
@@ -63,11 +63,12 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/stringprintf.h>
#include <google/protobuf/io/printer.h>
-#include <google/protobuf/descriptor.h>
#include <google/protobuf/io/zero_copy_stream.h>
+#include <google/protobuf/descriptor.h>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/substitute.h>
+
namespace google {
namespace protobuf {
namespace compiler {
@@ -75,12 +76,21 @@ namespace python {
namespace {
+// Reimplemented here because we can't bring in
+// absl/strings/string_view_utils.h because it needs C++11.
+bool StrStartsWith(StringPiece sp, StringPiece x) {
+ return sp.size() >= x.size() && sp.substr(0, x.size()) == x;
+}
+bool StrEndsWith(StringPiece sp, StringPiece x) {
+ return sp.size() >= x.size() && sp.substr(sp.size() - x.size()) == x;
+}
+
// Returns a copy of |filename| with any trailing ".protodevel" or ".proto
// suffix stripped.
// TODO(robinson): Unify with copy in compiler/cpp/internal/helpers.cc.
string StripProto(const string& filename) {
- const char* suffix = HasSuffixString(filename, ".protodevel")
- ? ".protodevel" : ".proto";
+ const char* suffix =
+ StrEndsWith(filename, ".protodevel") ? ".protodevel" : ".proto";
return StripSuffixString(filename, suffix);
}
@@ -350,7 +360,9 @@ bool Generator::Generate(const FileDescriptor* file,
// can only be successfully parsed after we register corresponding
// extensions. Therefore we parse all options again here to recognize
// custom options that may be unknown when we define the descriptors.
+ // This does not apply to services because they are not used by extensions.
FixAllDescriptorOptions();
+ PrintServiceDescriptors();
if (HasGenericServices(file)) {
PrintServices();
}
@@ -445,8 +457,6 @@ void Generator::PrintFileDescriptor() const {
printer_->Outdent();
printer_->Print(")\n");
- printer_->Print("_sym_db.RegisterFileDescriptor($name$)\n", "name",
- kDescriptorKey);
printer_->Print("\n");
}
@@ -564,9 +574,16 @@ void Generator::PrintMessageDescriptors() const {
}
}
-void Generator::PrintServices() const {
+void Generator::PrintServiceDescriptors() const {
for (int i = 0; i < file_->service_count(); ++i) {
PrintServiceDescriptor(*file_->service(i));
+ AddServiceToFileDescriptor(*file_->service(i));
+ printer_->Print("\n");
+ }
+}
+
+void Generator::PrintServices() const {
+ for (int i = 0; i < file_->service_count(); ++i) {
PrintServiceClass(*file_->service(i));
PrintServiceStub(*file_->service(i));
printer_->Print("\n");
@@ -630,7 +647,10 @@ void Generator::PrintServiceDescriptor(
}
printer_->Outdent();
- printer_->Print("])\n\n");
+ printer_->Print("])\n");
+ printer_->Print("_sym_db.RegisterServiceDescriptor($name$)\n", "name",
+ service_name);
+ printer_->Print("\n");
}
@@ -889,6 +909,18 @@ void Generator::AddMessageToFileDescriptor(const Descriptor& descriptor) const {
printer_->Print(m, file_descriptor_template);
}
+void Generator::AddServiceToFileDescriptor(
+ const ServiceDescriptor& descriptor) const {
+ std::map<string, string> m;
+ m["descriptor_name"] = kDescriptorKey;
+ m["service_name"] = descriptor.name();
+ m["service_descriptor_name"] = ModuleLevelServiceDescriptorName(descriptor);
+ const char file_descriptor_template[] =
+ "$descriptor_name$.services_by_name['$service_name$'] = "
+ "$service_descriptor_name$\n";
+ printer_->Print(m, file_descriptor_template);
+}
+
void Generator::AddEnumToFileDescriptor(
const EnumDescriptor& descriptor) const {
std::map<string, string> m;
@@ -999,6 +1031,10 @@ void Generator::FixForeignFieldsInDescriptors() const {
for (int i = 0; i < file_->extension_count(); ++i) {
AddExtensionToFileDescriptor(*file_->extension(i));
}
+ // TODO(jieluo): Move this register to PrintFileDescriptor() when
+ // FieldDescriptor.file is added in generated file.
+ printer_->Print("_sym_db.RegisterFileDescriptor($name$)\n", "name",
+ kDescriptorKey);
printer_->Print("\n");
}
@@ -1115,7 +1151,7 @@ void Generator::PrintFieldDescriptor(
" has_default_value=$has_default_value$, default_value=$default_value$,\n"
" message_type=None, enum_type=None, containing_type=None,\n"
" is_extension=$is_extension$, extension_scope=None,\n"
- " options=$options$$json_name$)";
+ " options=$options$$json_name$, file=DESCRIPTOR)";
printer_->Print(m, field_descriptor_decl);
}
@@ -1380,8 +1416,17 @@ void Generator::FixOptionsForMessage(const Descriptor& descriptor) const {
void Generator::CopyPublicDependenciesAliases(
const string& copy_from, const FileDescriptor* file) const {
for (int i = 0; i < file->public_dependency_count(); ++i) {
+ string module_name = ModuleName(file->public_dependency(i)->name());
string module_alias = ModuleAlias(file->public_dependency(i)->name());
- printer_->Print("$alias$ = $copy_from$.$alias$\n", "alias", module_alias,
+ // There's no module alias in the dependent file if it was generated by
+ // an old protoc (less than 3.0.0-alpha-1). Use module name in this
+ // situation.
+ printer_->Print("try:\n"
+ " $alias$ = $copy_from$.$alias$\n"
+ "except AttributeError:\n"
+ " $alias$ = $copy_from$.$module$\n",
+ "alias", module_alias,
+ "module", module_name,
"copy_from", copy_from);
CopyPublicDependenciesAliases(copy_from, file->public_dependency(i));
}
diff --git a/src/google/protobuf/compiler/python/python_generator.h b/src/google/protobuf/compiler/python/python_generator.h
index 594260af..2b5a028b 100644
--- a/src/google/protobuf/compiler/python/python_generator.h
+++ b/src/google/protobuf/compiler/python/python_generator.h
@@ -112,6 +112,7 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator {
void AddMessageToFileDescriptor(const Descriptor& descriptor) const;
void AddEnumToFileDescriptor(const EnumDescriptor& descriptor) const;
void AddExtensionToFileDescriptor(const FieldDescriptor& descriptor) const;
+ void AddServiceToFileDescriptor(const ServiceDescriptor& descriptor) const;
string FieldReferencingExpression(const Descriptor* containing_type,
const FieldDescriptor& field,
const string& python_dict_name) const;
@@ -126,11 +127,12 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator {
void FixForeignFieldsInNestedExtensions(const Descriptor& descriptor) const;
void PrintServices() const;
+ void PrintServiceDescriptors() const;
void PrintServiceDescriptor(const ServiceDescriptor& descriptor) const;
void PrintServiceClass(const ServiceDescriptor& descriptor) const;
void PrintServiceStub(const ServiceDescriptor& descriptor) const;
void PrintDescriptorKeyAndModuleName(
- const ServiceDescriptor& descriptor) const ;
+ const ServiceDescriptor& descriptor) const;
void PrintEnumValueDescriptor(const EnumValueDescriptor& descriptor) const;
string OptionsValue(const string& class_name,
diff --git a/src/google/protobuf/compiler/subprocess.cc b/src/google/protobuf/compiler/subprocess.cc
index 933450fa..2e5a89ac 100644
--- a/src/google/protobuf/compiler/subprocess.cc
+++ b/src/google/protobuf/compiler/subprocess.cc
@@ -33,6 +33,7 @@
#include <google/protobuf/compiler/subprocess.h>
#include <algorithm>
+#include <cstring>
#include <iostream>
#ifndef _WIN32
@@ -47,11 +48,20 @@
#include <google/protobuf/message.h>
#include <google/protobuf/stubs/substitute.h>
-
namespace google {
namespace protobuf {
namespace compiler {
+namespace {
+char* portable_strdup(const char* s) {
+ char* ns = (char*) malloc(strlen(s) + 1);
+ if (ns != NULL) {
+ strcpy(ns, s);
+ }
+ return ns;
+}
+} // namespace
+
#ifdef _WIN32
static void CloseHandleOrDie(HANDLE handle) {
@@ -115,7 +125,7 @@ void Subprocess::Start(const string& program, SearchMode search_mode) {
}
// CreateProcess() mutates its second parameter. WTF?
- char* name_copy = strdup(program.c_str());
+ char* name_copy = portable_strdup(program.c_str());
// Create the process.
PROCESS_INFORMATION process_info;
@@ -299,7 +309,7 @@ void Subprocess::Start(const string& program, SearchMode search_mode) {
GOOGLE_CHECK(pipe(stdin_pipe) != -1);
GOOGLE_CHECK(pipe(stdout_pipe) != -1);
- char* argv[2] = { strdup(program.c_str()), NULL };
+ char* argv[2] = { portable_strdup(program.c_str()), NULL };
child_pid_ = fork();
if (child_pid_ == -1) {
@@ -347,7 +357,6 @@ void Subprocess::Start(const string& program, SearchMode search_mode) {
bool Subprocess::Communicate(const Message& input, Message* output,
string* error) {
-
GOOGLE_CHECK_NE(child_stdin_, -1) << "Must call Start() first.";
// The "sighandler_t" typedef is GNU-specific, so define our own.
diff --git a/src/google/protobuf/compiler/subprocess.h b/src/google/protobuf/compiler/subprocess.h
index 25138631..9d980b06 100644
--- a/src/google/protobuf/compiler/subprocess.h
+++ b/src/google/protobuf/compiler/subprocess.h
@@ -44,7 +44,6 @@
#include <string>
-
namespace google {
namespace protobuf {
diff --git a/src/google/protobuf/compiler/test_plugin.cc b/src/google/protobuf/compiler/test_plugin.cc
index 4830fd70..c676ce8c 100644
--- a/src/google/protobuf/compiler/test_plugin.cc
+++ b/src/google/protobuf/compiler/test_plugin.cc
@@ -37,7 +37,6 @@
#include <stdlib.h>
#include <google/protobuf/compiler/plugin.h>
#include <google/protobuf/compiler/mock_code_generator.h>
-#include <google/protobuf/stubs/strutil.h>
int main(int argc, char* argv[]) {
#ifdef _MSC_VER
diff --git a/src/google/protobuf/compiler/zip_output_unittest.sh b/src/google/protobuf/compiler/zip_output_unittest.sh
index 6fc7136d..f8597912 100755
--- a/src/google/protobuf/compiler/zip_output_unittest.sh
+++ b/src/google/protobuf/compiler/zip_output_unittest.sh
@@ -41,6 +41,8 @@ fail() {
TEST_TMPDIR=.
PROTOC=./protoc
+JAR=jar
+UNZIP=unzip
echo '
syntax = "proto2";
@@ -57,8 +59,9 @@ $PROTOC \
|| fail 'protoc failed.'
echo "Testing output to zip..."
-if unzip -h > /dev/null; then
- unzip -t $TEST_TMPDIR/testzip.zip > $TEST_TMPDIR/testzip.list || fail 'unzip failed.'
+if $UNZIP -h > /dev/null; then
+ $UNZIP -t $TEST_TMPDIR/testzip.zip > $TEST_TMPDIR/testzip.list \
+ || fail 'unzip failed.'
grep 'testing: testzip\.pb\.cc *OK$' $TEST_TMPDIR/testzip.list > /dev/null \
|| fail 'testzip.pb.cc not found in output zip.'
@@ -73,8 +76,14 @@ else
fi
echo "Testing output to jar..."
-if jar c $TEST_TMPDIR/testzip.proto > /dev/null; then
- jar tf $TEST_TMPDIR/testzip.jar > $TEST_TMPDIR/testzip.list || fail 'jar failed.'
+if $JAR c $TEST_TMPDIR/testzip.proto > /dev/null; then
+ $JAR tf $TEST_TMPDIR/testzip.jar > $TEST_TMPDIR/testzip.list \
+ || fail 'jar failed.'
+
+ # Check that -interface.jar timestamps are normalized:
+ if [[ "$(TZ=UTC $JAR tvf $TEST_TMPDIR/testzip.jar)" != *'Tue Jan 01 00:00:00 UTC 1980'* ]]; then
+ fail 'Zip did not contain normalized timestamps'
+ fi
grep '^test/jar/Foo\.java$' $TEST_TMPDIR/testzip.list > /dev/null \
|| fail 'Foo.java not found in output jar.'
diff --git a/src/google/protobuf/compiler/zip_writer.cc b/src/google/protobuf/compiler/zip_writer.cc
index 458cced2..1799af6a 100644
--- a/src/google/protobuf/compiler/zip_writer.cc
+++ b/src/google/protobuf/compiler/zip_writer.cc
@@ -70,6 +70,10 @@ namespace google {
namespace protobuf {
namespace compiler {
+// January 1, 1980 as a DOS date.
+// see https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx
+static const uint16 kDosEpoch = 1 << 5 | 1;
+
static const uint32 kCRC32Table[256] = {
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,
0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
@@ -154,7 +158,7 @@ bool ZipWriter::Write(const string& filename, const string& contents) {
WriteShort(&output, 0); // flags
WriteShort(&output, 0); // compression method: stored
WriteShort(&output, 0); // last modified time
- WriteShort(&output, 0); // last modified date
+ WriteShort(&output, kDosEpoch); // last modified date
output.WriteLittleEndian32(info.crc32); // crc-32
output.WriteLittleEndian32(info.size); // compressed size
output.WriteLittleEndian32(info.size); // uncompressed size
@@ -185,7 +189,7 @@ bool ZipWriter::WriteDirectory() {
WriteShort(&output, 0); // flags
WriteShort(&output, 0); // compression method: stored
WriteShort(&output, 0); // last modified time
- WriteShort(&output, 0); // last modified date
+ WriteShort(&output, kDosEpoch); // last modified date
output.WriteLittleEndian32(crc32); // crc-32
output.WriteLittleEndian32(size); // compressed size
output.WriteLittleEndian32(size); // uncompressed size
diff --git a/src/google/protobuf/descriptor.cc b/src/google/protobuf/descriptor.cc
index 7dfdb377..3f54b848 100644
--- a/src/google/protobuf/descriptor.cc
+++ b/src/google/protobuf/descriptor.cc
@@ -44,25 +44,26 @@
#include <algorithm>
#include <limits>
+#include <google/protobuf/stubs/common.h>
+#include <google/protobuf/stubs/logging.h>
+#include <google/protobuf/stubs/mutex.h>
+#include <google/protobuf/stubs/once.h>
+#include <google/protobuf/stubs/stringprintf.h>
+#include <google/protobuf/stubs/strutil.h>
+#include <google/protobuf/io/strtod.h>
+#include <google/protobuf/io/coded_stream.h>
+#include <google/protobuf/io/tokenizer.h>
+#include <google/protobuf/io/zero_copy_stream_impl.h>
+#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/descriptor_database.h>
-#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/dynamic_message.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/text_format.h>
#include <google/protobuf/unknown_field_set.h>
#include <google/protobuf/wire_format.h>
-#include <google/protobuf/io/strtod.h>
-#include <google/protobuf/io/coded_stream.h>
-#include <google/protobuf/io/tokenizer.h>
-#include <google/protobuf/io/zero_copy_stream_impl.h>
-#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/stubs/logging.h>
-#include <google/protobuf/stubs/mutex.h>
-#include <google/protobuf/stubs/once.h>
-#include <google/protobuf/stubs/stringprintf.h>
-#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/substitute.h>
+
#include <google/protobuf/stubs/map_util.h>
#include <google/protobuf/stubs/stl_util.h>
@@ -72,6 +73,79 @@ namespace google {
namespace protobuf {
+struct Symbol {
+ enum Type {
+ NULL_SYMBOL,
+ MESSAGE,
+ FIELD,
+ ONEOF,
+ ENUM,
+ ENUM_VALUE,
+ SERVICE,
+ METHOD,
+ PACKAGE
+ };
+ Type type;
+ union {
+ const Descriptor* descriptor;
+ const FieldDescriptor* field_descriptor;
+ const OneofDescriptor* oneof_descriptor;
+ const EnumDescriptor* enum_descriptor;
+ const EnumValueDescriptor* enum_value_descriptor;
+ const ServiceDescriptor* service_descriptor;
+ const MethodDescriptor* method_descriptor;
+ const FileDescriptor* package_file_descriptor;
+ };
+
+ inline Symbol() : type(NULL_SYMBOL) { descriptor = NULL; }
+ inline bool IsNull() const { return type == NULL_SYMBOL; }
+ inline bool IsType() const { return type == MESSAGE || type == ENUM; }
+ inline bool IsAggregate() const {
+ return type == MESSAGE || type == PACKAGE || type == ENUM ||
+ type == SERVICE;
+ }
+
+#define CONSTRUCTOR(TYPE, TYPE_CONSTANT, FIELD) \
+ inline explicit Symbol(const TYPE* value) { \
+ type = TYPE_CONSTANT; \
+ this->FIELD = value; \
+ }
+
+ CONSTRUCTOR(Descriptor, MESSAGE, descriptor)
+ CONSTRUCTOR(FieldDescriptor, FIELD, field_descriptor)
+ CONSTRUCTOR(OneofDescriptor, ONEOF, oneof_descriptor)
+ CONSTRUCTOR(EnumDescriptor, ENUM, enum_descriptor)
+ CONSTRUCTOR(EnumValueDescriptor, ENUM_VALUE, enum_value_descriptor)
+ CONSTRUCTOR(ServiceDescriptor, SERVICE, service_descriptor)
+ CONSTRUCTOR(MethodDescriptor, METHOD, method_descriptor)
+ CONSTRUCTOR(FileDescriptor, PACKAGE, package_file_descriptor)
+#undef CONSTRUCTOR
+
+ const FileDescriptor* GetFile() const {
+ switch (type) {
+ case NULL_SYMBOL:
+ return NULL;
+ case MESSAGE:
+ return descriptor->file();
+ case FIELD:
+ return field_descriptor->file();
+ case ONEOF:
+ return oneof_descriptor->containing_type()->file();
+ case ENUM:
+ return enum_descriptor->file();
+ case ENUM_VALUE:
+ return enum_value_descriptor->type()->file();
+ case SERVICE:
+ return service_descriptor->file();
+ case METHOD:
+ return method_descriptor->service()->file();
+ case PACKAGE:
+ return package_file_descriptor;
+ }
+ return NULL;
+ }
+};
+
const FieldDescriptor::CppType
FieldDescriptor::kTypeToCppTypeMap[MAX_TYPE + 1] = {
static_cast<CppType>(0), // 0 is reserved for errors
@@ -369,65 +443,6 @@ struct PointerStringPairHash {
};
-struct Symbol {
- enum Type {
- NULL_SYMBOL, MESSAGE, FIELD, ONEOF, ENUM, ENUM_VALUE, SERVICE, METHOD,
- PACKAGE
- };
- Type type;
- union {
- const Descriptor* descriptor;
- const FieldDescriptor* field_descriptor;
- const OneofDescriptor* oneof_descriptor;
- const EnumDescriptor* enum_descriptor;
- const EnumValueDescriptor* enum_value_descriptor;
- const ServiceDescriptor* service_descriptor;
- const MethodDescriptor* method_descriptor;
- const FileDescriptor* package_file_descriptor;
- };
-
- inline Symbol() : type(NULL_SYMBOL) { descriptor = NULL; }
- inline bool IsNull() const { return type == NULL_SYMBOL; }
- inline bool IsType() const {
- return type == MESSAGE || type == ENUM;
- }
- inline bool IsAggregate() const {
- return type == MESSAGE || type == PACKAGE
- || type == ENUM || type == SERVICE;
- }
-
-#define CONSTRUCTOR(TYPE, TYPE_CONSTANT, FIELD) \
- inline explicit Symbol(const TYPE* value) { \
- type = TYPE_CONSTANT; \
- this->FIELD = value; \
- }
-
- CONSTRUCTOR(Descriptor , MESSAGE , descriptor )
- CONSTRUCTOR(FieldDescriptor , FIELD , field_descriptor )
- CONSTRUCTOR(OneofDescriptor , ONEOF , oneof_descriptor )
- CONSTRUCTOR(EnumDescriptor , ENUM , enum_descriptor )
- CONSTRUCTOR(EnumValueDescriptor, ENUM_VALUE, enum_value_descriptor )
- CONSTRUCTOR(ServiceDescriptor , SERVICE , service_descriptor )
- CONSTRUCTOR(MethodDescriptor , METHOD , method_descriptor )
- CONSTRUCTOR(FileDescriptor , PACKAGE , package_file_descriptor)
-#undef CONSTRUCTOR
-
- const FileDescriptor* GetFile() const {
- switch (type) {
- case NULL_SYMBOL: return NULL;
- case MESSAGE : return descriptor ->file();
- case FIELD : return field_descriptor ->file();
- case ONEOF : return oneof_descriptor ->containing_type()->file();
- case ENUM : return enum_descriptor ->file();
- case ENUM_VALUE : return enum_value_descriptor->type()->file();
- case SERVICE : return service_descriptor ->file();
- case METHOD : return method_descriptor ->service()->file();
- case PACKAGE : return package_file_descriptor;
- }
- return NULL;
- }
-};
-
const Symbol kNullSymbol;
typedef hash_map<const char*, Symbol,
@@ -467,7 +482,7 @@ void InitAllowedProto3Extendee() {
allowed_proto3_extendees_ = new std::set<string>;
const char* kOptionNames[] = {
"FileOptions", "MessageOptions", "FieldOptions", "EnumOptions",
- "EnumValueOptions", "ServiceOptions", "MethodOptions"};
+ "EnumValueOptions", "ServiceOptions", "MethodOptions", "OneofOptions"};
for (int i = 0; i < GOOGLE_ARRAYSIZE(kOptionNames); ++i) {
// descriptor.proto has a different package name in opensource. We allow
// both so the opensource protocol compiler can also compile internal
@@ -578,7 +593,7 @@ class DescriptorPool::Tables {
// These return NULL if not found.
inline const FileDescriptor* FindFile(const string& key) const;
inline const FieldDescriptor* FindExtension(const Descriptor* extendee,
- int number);
+ int number) const;
inline void FindAllExtensions(const Descriptor* extendee,
std::vector<const FieldDescriptor*>* out) const;
@@ -610,6 +625,10 @@ class DescriptorPool::Tables {
// The string is initialized to the given value for convenience.
string* AllocateString(const string& value);
+ // Allocate a GoogleOnceDynamic which will be destroyed when the pool is
+ // destroyed.
+ GoogleOnceDynamic* AllocateOnceDynamic();
+
// Allocate a protocol message object. Some older versions of GCC have
// trouble understanding explicit template instantiations in some cases, so
// in those cases we have to pass a dummy pointer of the right type as the
@@ -622,6 +641,8 @@ class DescriptorPool::Tables {
private:
std::vector<string*> strings_; // All strings in the pool.
std::vector<Message*> messages_; // All messages in the pool.
+ std::vector<GoogleOnceDynamic*>
+ once_dynamics_; // All GoogleOnceDynamics in the pool.
std::vector<FileDescriptorTables*>
file_tables_; // All file tables in the pool.
std::vector<void*> allocations_; // All other memory allocated in the pool.
@@ -632,19 +653,20 @@ class DescriptorPool::Tables {
struct CheckPoint {
explicit CheckPoint(const Tables* tables)
- : strings_before_checkpoint(tables->strings_.size()),
- messages_before_checkpoint(tables->messages_.size()),
- file_tables_before_checkpoint(tables->file_tables_.size()),
- allocations_before_checkpoint(tables->allocations_.size()),
- pending_symbols_before_checkpoint(
- tables->symbols_after_checkpoint_.size()),
- pending_files_before_checkpoint(
- tables->files_after_checkpoint_.size()),
- pending_extensions_before_checkpoint(
- tables->extensions_after_checkpoint_.size()) {
- }
+ : strings_before_checkpoint(tables->strings_.size()),
+ messages_before_checkpoint(tables->messages_.size()),
+ once_dynamics_before_checkpoint(tables->once_dynamics_.size()),
+ file_tables_before_checkpoint(tables->file_tables_.size()),
+ allocations_before_checkpoint(tables->allocations_.size()),
+ pending_symbols_before_checkpoint(
+ tables->symbols_after_checkpoint_.size()),
+ pending_files_before_checkpoint(
+ tables->files_after_checkpoint_.size()),
+ pending_extensions_before_checkpoint(
+ tables->extensions_after_checkpoint_.size()) {}
int strings_before_checkpoint;
int messages_before_checkpoint;
+ int once_dynamics_before_checkpoint;
int file_tables_before_checkpoint;
int allocations_before_checkpoint;
int pending_symbols_before_checkpoint;
@@ -730,11 +752,27 @@ class FileDescriptorTables {
const SourceCodeInfo_Location* GetSourceLocation(
const std::vector<int>& path, const SourceCodeInfo* info) const;
+ // Must be called after BuildFileImpl(), even if the build failed and
+ // we are going to roll back to the last checkpoint.
+ void FinalizeTables();
+
private:
- SymbolsByParentMap symbols_by_parent_;
- FieldsByNameMap fields_by_lowercase_name_;
- FieldsByNameMap fields_by_camelcase_name_;
- FieldsByNumberMap fields_by_number_; // Not including extensions.
+ const void* FindParentForFieldsByMap(const FieldDescriptor* field) const;
+ static void FieldsByLowercaseNamesLazyInitStatic(
+ const FileDescriptorTables* tables);
+ void FieldsByLowercaseNamesLazyInitInternal() const;
+ static void FieldsByCamelcaseNamesLazyInitStatic(
+ const FileDescriptorTables* tables);
+ void FieldsByCamelcaseNamesLazyInitInternal() const;
+
+ SymbolsByParentMap symbols_by_parent_;
+ mutable FieldsByNameMap fields_by_lowercase_name_;
+ mutable FieldsByNameMap* fields_by_lowercase_name_tmp_;
+ mutable GoogleOnceDynamic fields_by_lowercase_name_once_;
+ mutable FieldsByNameMap fields_by_camelcase_name_;
+ mutable FieldsByNameMap* fields_by_camelcase_name_tmp_;
+ mutable GoogleOnceDynamic fields_by_camelcase_name_once_;
+ FieldsByNumberMap fields_by_number_; // Not including extensions.
EnumValuesByNumberMap enum_values_by_number_;
mutable EnumValuesByNumberMap unknown_enum_values_by_number_
GOOGLE_GUARDED_BY(unknown_enum_values_mu_);
@@ -767,17 +805,20 @@ DescriptorPool::Tables::~Tables() {
}
STLDeleteElements(&strings_);
STLDeleteElements(&file_tables_);
+ STLDeleteElements(&once_dynamics_);
}
FileDescriptorTables::FileDescriptorTables()
- // Initialize all the hash tables to start out with a small # of buckets
+ // Initialize all the hash tables to start out with a small # of buckets.
: symbols_by_parent_(3),
fields_by_lowercase_name_(3),
+ fields_by_lowercase_name_tmp_(new FieldsByNameMap()),
fields_by_camelcase_name_(3),
+ fields_by_camelcase_name_tmp_(new FieldsByNameMap()),
fields_by_number_(3),
enum_values_by_number_(3),
- unknown_enum_values_by_number_(3) {
-}
+ unknown_enum_values_by_number_(3),
+ locations_by_path_(3) {}
FileDescriptorTables::~FileDescriptorTables() {}
@@ -856,6 +897,9 @@ void DescriptorPool::Tables::RollbackToLastCheckpoint() {
messages_.begin() + checkpoint.messages_before_checkpoint,
messages_.end());
STLDeleteContainerPointers(
+ once_dynamics_.begin() + checkpoint.once_dynamics_before_checkpoint,
+ once_dynamics_.end());
+ STLDeleteContainerPointers(
file_tables_.begin() + checkpoint.file_tables_before_checkpoint,
file_tables_.end());
for (int i = checkpoint.allocations_before_checkpoint;
@@ -866,6 +910,7 @@ void DescriptorPool::Tables::RollbackToLastCheckpoint() {
strings_.resize(checkpoint.strings_before_checkpoint);
messages_.resize(checkpoint.messages_before_checkpoint);
+ once_dynamics_.resize(checkpoint.once_dynamics_before_checkpoint);
file_tables_.resize(checkpoint.file_tables_before_checkpoint);
allocations_.resize(checkpoint.allocations_before_checkpoint);
checkpoints_.pop_back();
@@ -933,14 +978,59 @@ inline const FieldDescriptor* FileDescriptorTables::FindFieldByNumber(
return FindPtrOrNull(fields_by_number_, std::make_pair(parent, number));
}
+const void* FileDescriptorTables::FindParentForFieldsByMap(
+ const FieldDescriptor* field) const {
+ if (field->is_extension()) {
+ if (field->extension_scope() == NULL) {
+ return field->file();
+ } else {
+ return field->extension_scope();
+ }
+ } else {
+ return field->containing_type();
+ }
+}
+
+void FileDescriptorTables::FieldsByLowercaseNamesLazyInitStatic(
+ const FileDescriptorTables* tables) {
+ tables->FieldsByLowercaseNamesLazyInitInternal();
+}
+
+void FileDescriptorTables::FieldsByLowercaseNamesLazyInitInternal() const {
+ for (FieldsByNumberMap::const_iterator it = fields_by_number_.begin();
+ it != fields_by_number_.end(); it++) {
+ PointerStringPair lowercase_key(FindParentForFieldsByMap(it->second),
+ it->second->lowercase_name().c_str());
+ InsertIfNotPresent(&fields_by_lowercase_name_, lowercase_key, it->second);
+ }
+}
+
inline const FieldDescriptor* FileDescriptorTables::FindFieldByLowercaseName(
const void* parent, const string& lowercase_name) const {
+ fields_by_lowercase_name_once_.Init(
+ &FileDescriptorTables::FieldsByLowercaseNamesLazyInitStatic, this);
return FindPtrOrNull(fields_by_lowercase_name_,
PointerStringPair(parent, lowercase_name.c_str()));
}
+void FileDescriptorTables::FieldsByCamelcaseNamesLazyInitStatic(
+ const FileDescriptorTables* tables) {
+ tables->FieldsByCamelcaseNamesLazyInitInternal();
+}
+
+void FileDescriptorTables::FieldsByCamelcaseNamesLazyInitInternal() const {
+ for (FieldsByNumberMap::const_iterator it = fields_by_number_.begin();
+ it != fields_by_number_.end(); it++) {
+ PointerStringPair camelcase_key(FindParentForFieldsByMap(it->second),
+ it->second->camelcase_name().c_str());
+ InsertIfNotPresent(&fields_by_camelcase_name_, camelcase_key, it->second);
+ }
+}
+
inline const FieldDescriptor* FileDescriptorTables::FindFieldByCamelcaseName(
const void* parent, const string& camelcase_name) const {
+ fields_by_camelcase_name_once_.Init(
+ &FileDescriptorTables::FieldsByCamelcaseNamesLazyInitStatic, this);
return FindPtrOrNull(fields_by_camelcase_name_,
PointerStringPair(parent, camelcase_name.c_str()));
}
@@ -1004,7 +1094,7 @@ FileDescriptorTables::FindEnumValueByNumberCreatingIfUnknown(
inline const FieldDescriptor* DescriptorPool::Tables::FindExtension(
- const Descriptor* extendee, int number) {
+ const Descriptor* extendee, int number) const {
return FindPtrOrNull(extensions_, std::make_pair(extendee, number));
}
@@ -1045,24 +1135,40 @@ bool DescriptorPool::Tables::AddFile(const FileDescriptor* file) {
}
}
+void FileDescriptorTables::FinalizeTables() {
+ // Clean up the temporary maps used by AddFieldByStylizedNames().
+ delete fields_by_lowercase_name_tmp_;
+ fields_by_lowercase_name_tmp_ = NULL;
+ delete fields_by_camelcase_name_tmp_;
+ fields_by_camelcase_name_tmp_ = NULL;
+}
+
void FileDescriptorTables::AddFieldByStylizedNames(
const FieldDescriptor* field) {
- const void* parent;
- if (field->is_extension()) {
- if (field->extension_scope() == NULL) {
- parent = field->file();
- } else {
- parent = field->extension_scope();
- }
- } else {
- parent = field->containing_type();
- }
+ const void* parent = FindParentForFieldsByMap(field);
+
+ // We want fields_by_{lower,camel}case_name_ to be lazily built, but
+ // cross-link order determines which entry will be present in the case of a
+ // conflict. So we use the temporary maps that get destroyed after
+ // BuildFileImpl() to detect the conflicts, and only store the conflicts in
+ // the map that will persist. We will then lazily populate the rest of the
+ // entries from fields_by_number_.
PointerStringPair lowercase_key(parent, field->lowercase_name().c_str());
- InsertIfNotPresent(&fields_by_lowercase_name_, lowercase_key, field);
+ if (!InsertIfNotPresent(fields_by_lowercase_name_tmp_, lowercase_key,
+ field)) {
+ InsertIfNotPresent(
+ &fields_by_lowercase_name_, lowercase_key,
+ FindPtrOrNull(*fields_by_lowercase_name_tmp_, lowercase_key));
+ }
PointerStringPair camelcase_key(parent, field->camelcase_name().c_str());
- InsertIfNotPresent(&fields_by_camelcase_name_, camelcase_key, field);
+ if (!InsertIfNotPresent(fields_by_camelcase_name_tmp_, camelcase_key,
+ field)) {
+ InsertIfNotPresent(
+ &fields_by_camelcase_name_, camelcase_key,
+ FindPtrOrNull(*fields_by_camelcase_name_tmp_, camelcase_key));
+ }
}
bool FileDescriptorTables::AddFieldByNumber(const FieldDescriptor* field) {
@@ -1104,6 +1210,12 @@ string* DescriptorPool::Tables::AllocateString(const string& value) {
return result;
}
+GoogleOnceDynamic* DescriptorPool::Tables::AllocateOnceDynamic() {
+ GoogleOnceDynamic* result = new GoogleOnceDynamic();
+ once_dynamics_.push_back(result);
+ return result;
+}
+
template<typename Type>
Type* DescriptorPool::Tables::AllocateMessage(Type* /* dummy */) {
Type* result = new Type;
@@ -1157,8 +1269,10 @@ DescriptorPool::DescriptorPool()
underlay_(NULL),
tables_(new Tables),
enforce_dependencies_(true),
+ lazily_build_dependencies_(false),
allow_unknown_(false),
- enforce_weak_(false) {}
+ enforce_weak_(false),
+ disallow_enforce_utf8_(false) {}
DescriptorPool::DescriptorPool(DescriptorDatabase* fallback_database,
ErrorCollector* error_collector)
@@ -1168,8 +1282,10 @@ DescriptorPool::DescriptorPool(DescriptorDatabase* fallback_database,
underlay_(NULL),
tables_(new Tables),
enforce_dependencies_(true),
+ lazily_build_dependencies_(false),
allow_unknown_(false),
- enforce_weak_(false) {
+ enforce_weak_(false),
+ disallow_enforce_utf8_(false) {
}
DescriptorPool::DescriptorPool(const DescriptorPool* underlay)
@@ -1179,8 +1295,10 @@ DescriptorPool::DescriptorPool(const DescriptorPool* underlay)
underlay_(underlay),
tables_(new Tables),
enforce_dependencies_(true),
+ lazily_build_dependencies_(false),
allow_unknown_(false),
- enforce_weak_(false) {}
+ enforce_weak_(false),
+ disallow_enforce_utf8_(false) {}
DescriptorPool::~DescriptorPool() {
if (mutex_ != NULL) delete mutex_;
@@ -1225,6 +1343,7 @@ void DeleteGeneratedPool() {
static void InitGeneratedPool() {
generated_database_ = new EncodedDescriptorDatabase;
generated_pool_ = new DescriptorPool(generated_database_);
+ generated_pool_->InternalSetLazilyBuildDependencies();
internal::OnShutdown(&DeleteGeneratedPool);
}
@@ -1379,6 +1498,15 @@ const MethodDescriptor* DescriptorPool::FindMethodByName(
const FieldDescriptor* DescriptorPool::FindExtensionByNumber(
const Descriptor* extendee, int number) const {
+ // A faster path to reduce lock contention in finding extensions, assuming
+ // most extensions will be cache hit.
+ if (mutex_ != NULL) {
+ ReaderMutexLock lock(mutex_);
+ const FieldDescriptor* result = tables_->FindExtension(extendee, number);
+ if (result != NULL) {
+ return result;
+ }
+ }
MutexLockMaybe lock(mutex_);
tables_->known_bad_symbols_.clear();
tables_->known_bad_files_.clear();
@@ -1681,6 +1809,18 @@ Descriptor::FindReservedRangeContainingNumber(int number) const {
return NULL;
}
+const EnumDescriptor::ReservedRange*
+EnumDescriptor::FindReservedRangeContainingNumber(int number) const {
+ // TODO(chrisn): Consider a non-linear search.
+ for (int i = 0; i < reserved_range_count(); i++) {
+ if (number >= reserved_range(i)->start &&
+ number <= reserved_range(i)->end) {
+ return reserved_range(i);
+ }
+ }
+ return NULL;
+}
+
// -------------------------------------------------------------------
bool DescriptorPool::TryFindFileInFallbackDatabase(const string& name) const {
@@ -1786,8 +1926,8 @@ bool DescriptorPool::TryFindExtensionInFallbackDatabase(
// ===================================================================
-bool FieldDescriptor::is_map() const {
- return type() == TYPE_MESSAGE && message_type()->options().map_entry();
+bool FieldDescriptor::is_map_message_type() const {
+ return message_type_->options().map_entry();
}
string FieldDescriptor::DefaultValueAsString(bool quote_string_type) const {
@@ -1914,6 +2054,10 @@ void Descriptor::CopyTo(DescriptorProto* proto) const {
DescriptorProto::ExtensionRange* range = proto->add_extension_range();
range->set_start(extension_range(i)->start);
range->set_end(extension_range(i)->end);
+ const ExtensionRangeOptions* options = extension_range(i)->options_;
+ if (options != &ExtensionRangeOptions::default_instance()) {
+ range->mutable_options()->CopyFrom(*options);
+ }
}
for (int i = 0; i < extension_count(); i++) {
extension(i)->CopyTo(proto->add_extension());
@@ -2019,6 +2163,14 @@ void EnumDescriptor::CopyTo(EnumDescriptorProto* proto) const {
for (int i = 0; i < value_count(); i++) {
value(i)->CopyTo(proto->add_value());
}
+ for (int i = 0; i < reserved_range_count(); i++) {
+ EnumDescriptorProto::EnumReservedRange* range = proto->add_reserved_range();
+ range->set_start(reserved_range(i)->start);
+ range->set_end(reserved_range(i)->end);
+ }
+ for (int i = 0; i < reserved_name_count(); i++) {
+ proto->add_reserved_name(reserved_name(i));
+ }
if (&options() != &EnumOptions::default_instance()) {
proto->mutable_options()->CopyFrom(options());
@@ -2651,6 +2803,30 @@ void EnumDescriptor::DebugString(int depth, string *contents,
for (int i = 0; i < value_count(); i++) {
value(i)->DebugString(depth, contents, debug_string_options);
}
+
+ if (reserved_range_count() > 0) {
+ strings::SubstituteAndAppend(contents, "$0 reserved ", prefix);
+ for (int i = 0; i < reserved_range_count(); i++) {
+ const EnumDescriptor::ReservedRange* range = reserved_range(i);
+ if (range->end == range->start) {
+ strings::SubstituteAndAppend(contents, "$0, ", range->start);
+ } else {
+ strings::SubstituteAndAppend(contents, "$0 to $1, ",
+ range->start, range->end);
+ }
+ }
+ contents->replace(contents->size() - 2, 2, ";\n");
+ }
+
+ if (reserved_name_count() > 0) {
+ strings::SubstituteAndAppend(contents, "$0 reserved ", prefix);
+ for (int i = 0; i < reserved_name_count(); i++) {
+ strings::SubstituteAndAppend(contents, "\"$0\", ",
+ CEscape(reserved_name(i)));
+ }
+ contents->replace(contents->size() - 2, 2, ";\n");
+ }
+
strings::SubstituteAndAppend(contents, "$0}\n", prefix);
comment_printer.AddPostComment(contents);
@@ -2950,7 +3126,7 @@ class DescriptorBuilder {
friend class OptionInterpreter;
// Non-recursive part of BuildFile functionality.
- const FileDescriptor* BuildFileImpl(const FileDescriptorProto& proto);
+ FileDescriptor* BuildFileImpl(const FileDescriptorProto& proto);
const DescriptorPool* pool_;
DescriptorPool::Tables* tables_; // for convenience
@@ -3023,15 +3199,16 @@ class DescriptorBuilder {
// - Search the pool's underlay if not found in tables_.
// - Insure that the resulting Symbol is from one of the file's declared
// dependencies.
- Symbol FindSymbol(const string& name);
+ Symbol FindSymbol(const string& name, bool build_it = true);
// Like FindSymbol() but does not require that the symbol is in one of the
// file's declared dependencies.
- Symbol FindSymbolNotEnforcingDeps(const string& name);
+ Symbol FindSymbolNotEnforcingDeps(const string& name, bool build_it = true);
// This implements the body of FindSymbolNotEnforcingDeps().
Symbol FindSymbolNotEnforcingDepsHelper(const DescriptorPool* pool,
- const string& name);
+ const string& name,
+ bool build_it = true);
// Like FindSymbol(), but looks up the name relative to some other symbol
// name. This first searches siblings of relative_to, then siblings of its
@@ -3047,31 +3224,21 @@ class DescriptorBuilder {
// that LookupSymbol may still return a non-type symbol in LOOKUP_TYPES mode,
// if it believes that's all it could refer to. The caller should always
// check that it receives the type of symbol it was expecting.
- enum PlaceholderType {
- PLACEHOLDER_MESSAGE,
- PLACEHOLDER_ENUM,
- PLACEHOLDER_EXTENDABLE_MESSAGE
- };
enum ResolveMode {
LOOKUP_ALL, LOOKUP_TYPES
};
Symbol LookupSymbol(const string& name, const string& relative_to,
- PlaceholderType placeholder_type = PLACEHOLDER_MESSAGE,
- ResolveMode resolve_mode = LOOKUP_ALL);
+ DescriptorPool::PlaceholderType placeholder_type =
+ DescriptorPool::PLACEHOLDER_MESSAGE,
+ ResolveMode resolve_mode = LOOKUP_ALL,
+ bool build_it = true);
// Like LookupSymbol() but will not return a placeholder even if
// AllowUnknownDependencies() has been used.
Symbol LookupSymbolNoPlaceholder(const string& name,
const string& relative_to,
- ResolveMode resolve_mode = LOOKUP_ALL);
-
- // Creates a placeholder type suitable for return from LookupSymbol(). May
- // return kNullSymbol if the name is not a valid type name.
- Symbol NewPlaceholder(const string& name, PlaceholderType placeholder_type);
-
- // Creates a placeholder file. Never returns NULL. This is used when an
- // import is not found and AllowUnknownDependencies() is enabled.
- FileDescriptor* NewPlaceholderFile(const string& name);
+ ResolveMode resolve_mode = LOOKUP_ALL,
+ bool build_it = true);
// Calls tables_->AddSymbol() and records an error if it fails. Returns
// true if successful or false if failed, though most callers can ignore
@@ -3093,10 +3260,6 @@ class DescriptorBuilder {
void ValidateSymbolName(const string& name, const string& full_name,
const Message& proto);
- // Like ValidateSymbolName(), but the name is allowed to contain periods and
- // an error is indicated by returning false (not recording the error).
- bool ValidateQualifiedName(const string& name);
-
// Used by BUILD_ARRAY macro (below) to avoid having to have the type
// specified as a macro parameter.
template <typename Type>
@@ -3147,6 +3310,9 @@ class DescriptorBuilder {
void BuildReservedRange(const DescriptorProto::ReservedRange& proto,
const Descriptor* parent,
Descriptor::ReservedRange* result);
+ void BuildReservedRange(const EnumDescriptorProto::EnumReservedRange& proto,
+ const EnumDescriptor* parent,
+ EnumDescriptor::ReservedRange* result);
void BuildOneof(const OneofDescriptorProto& proto,
Descriptor* parent,
OneofDescriptor* result);
@@ -3177,6 +3343,8 @@ class DescriptorBuilder {
void CrossLinkMessage(Descriptor* message, const DescriptorProto& proto);
void CrossLinkField(FieldDescriptor* field,
const FieldDescriptorProto& proto);
+ void CrossLinkExtensionRange(Descriptor::ExtensionRange* range,
+ const DescriptorProto::ExtensionRange& proto);
void CrossLinkEnum(EnumDescriptor* enum_type,
const EnumDescriptorProto& proto);
void CrossLinkEnumValue(EnumValueDescriptor* enum_value,
@@ -3356,6 +3524,8 @@ class DescriptorBuilder {
void DetectMapConflicts(const Descriptor* message,
const DescriptorProto& proto);
+ void ValidateJSType(FieldDescriptor* field,
+ const FieldDescriptorProto& proto);
};
const FileDescriptor* DescriptorPool::BuildFile(
@@ -3483,8 +3653,8 @@ void DescriptorBuilder::AddWarning(
bool DescriptorBuilder::IsInPackage(const FileDescriptor* file,
const string& package_name) {
return HasPrefixString(file->package(), package_name) &&
- (file->package().size() == package_name.size() ||
- file->package()[package_name.size()] == '.');
+ (file->package().size() == package_name.size() ||
+ file->package()[package_name.size()] == '.');
}
void DescriptorBuilder::RecordPublicDependencies(const FileDescriptor* file) {
@@ -3495,7 +3665,7 @@ void DescriptorBuilder::RecordPublicDependencies(const FileDescriptor* file) {
}
Symbol DescriptorBuilder::FindSymbolNotEnforcingDepsHelper(
- const DescriptorPool* pool, const string& name) {
+ const DescriptorPool* pool, const string& name, bool build_it) {
// If we are looking at an underlay, we must lock its mutex_, since we are
// accessing the underlay's tables_ directly.
MutexLockMaybe lock((pool == pool_) ? NULL : pool->mutex_);
@@ -3507,12 +3677,14 @@ Symbol DescriptorBuilder::FindSymbolNotEnforcingDepsHelper(
}
if (result.IsNull()) {
- // In theory, we shouldn't need to check fallback_database_ because the
- // symbol should be in one of its file's direct dependencies, and we have
- // already loaded those by the time we get here. But we check anyway so
- // that we can generate better error message when dependencies are missing
- // (i.e., "missing dependency" rather than "type is not defined").
- if (pool->TryFindSymbolInFallbackDatabase(name)) {
+ // With lazily_build_dependencies_, a symbol lookup at cross link time is
+ // not guaranteed to be successful. In most cases, build_it will be false,
+ // which intentionally prevents us from building an import until it's
+ // actually needed. In some cases, like registering an extension, we want
+ // to build the file containing the symbol, and build_it will be set.
+ // Also, build_it will be true when !lazily_build_dependencies_, to provide
+ // better error reporting of missing dependencies.
+ if (build_it && pool->TryFindSymbolInFallbackDatabase(name)) {
result = pool->tables_->FindSymbol(name);
}
}
@@ -3520,17 +3692,18 @@ Symbol DescriptorBuilder::FindSymbolNotEnforcingDepsHelper(
return result;
}
-Symbol DescriptorBuilder::FindSymbolNotEnforcingDeps(const string& name) {
- return FindSymbolNotEnforcingDepsHelper(pool_, name);
+Symbol DescriptorBuilder::FindSymbolNotEnforcingDeps(const string& name,
+ bool build_it) {
+ return FindSymbolNotEnforcingDepsHelper(pool_, name, build_it);
}
-Symbol DescriptorBuilder::FindSymbol(const string& name) {
- Symbol result = FindSymbolNotEnforcingDeps(name);
+Symbol DescriptorBuilder::FindSymbol(const string& name, bool build_it) {
+ Symbol result = FindSymbolNotEnforcingDeps(name, build_it);
if (result.IsNull()) return result;
if (!pool_->enforce_dependencies_) {
- // Hack for CompilerUpgrader.
+ // Hack for CompilerUpgrader, and also used for lazily_build_dependencies_
return result;
}
@@ -3564,14 +3737,16 @@ Symbol DescriptorBuilder::FindSymbol(const string& name) {
return kNullSymbol;
}
-Symbol DescriptorBuilder::LookupSymbolNoPlaceholder(
- const string& name, const string& relative_to, ResolveMode resolve_mode) {
+Symbol DescriptorBuilder::LookupSymbolNoPlaceholder(const string& name,
+ const string& relative_to,
+ ResolveMode resolve_mode,
+ bool build_it) {
possible_undeclared_dependency_ = NULL;
undefine_resolved_name_.clear();
- if (name.size() > 0 && name[0] == '.') {
+ if (!name.empty() && name[0] == '.') {
// Fully-qualified name.
- return FindSymbol(name.substr(1));
+ return FindSymbol(name.substr(1), build_it);
}
// If name is something like "Foo.Bar.baz", and symbols named "Foo" are
@@ -3599,7 +3774,7 @@ Symbol DescriptorBuilder::LookupSymbolNoPlaceholder(
// Chop off the last component of the scope.
string::size_type dot_pos = scope_to_try.find_last_of('.');
if (dot_pos == string::npos) {
- return FindSymbol(name);
+ return FindSymbol(name, build_it);
} else {
scope_to_try.erase(dot_pos);
}
@@ -3608,7 +3783,7 @@ Symbol DescriptorBuilder::LookupSymbolNoPlaceholder(
string::size_type old_size = scope_to_try.size();
scope_to_try.append(1, '.');
scope_to_try.append(first_part_of_name);
- Symbol result = FindSymbol(scope_to_try);
+ Symbol result = FindSymbol(scope_to_try, build_it);
if (!result.IsNull()) {
if (first_part_of_name.size() < name.size()) {
// name is a compound symbol, of which we only found the first part.
@@ -3616,7 +3791,7 @@ Symbol DescriptorBuilder::LookupSymbolNoPlaceholder(
if (result.IsAggregate()) {
scope_to_try.append(name, first_part_of_name.size(),
name.size() - first_part_of_name.size());
- result = FindSymbol(scope_to_try);
+ result = FindSymbol(scope_to_try, build_it);
if (result.IsNull()) {
undefine_resolved_name_ = scope_to_try;
}
@@ -3640,19 +3815,49 @@ Symbol DescriptorBuilder::LookupSymbolNoPlaceholder(
Symbol DescriptorBuilder::LookupSymbol(
const string& name, const string& relative_to,
- PlaceholderType placeholder_type, ResolveMode resolve_mode) {
- Symbol result = LookupSymbolNoPlaceholder(
- name, relative_to, resolve_mode);
+ DescriptorPool::PlaceholderType placeholder_type, ResolveMode resolve_mode,
+ bool build_it) {
+ Symbol result =
+ LookupSymbolNoPlaceholder(name, relative_to, resolve_mode, build_it);
if (result.IsNull() && pool_->allow_unknown_) {
// Not found, but AllowUnknownDependencies() is enabled. Return a
// placeholder instead.
- result = NewPlaceholder(name, placeholder_type);
+ result = pool_->NewPlaceholderWithMutexHeld(name, placeholder_type);
}
return result;
}
-Symbol DescriptorBuilder::NewPlaceholder(const string& name,
- PlaceholderType placeholder_type) {
+static bool ValidateQualifiedName(const string& name) {
+ bool last_was_period = false;
+
+ for (int i = 0; i < name.size(); i++) {
+ // I don't trust isalnum() due to locales. :(
+ if (('a' <= name[i] && name[i] <= 'z') ||
+ ('A' <= name[i] && name[i] <= 'Z') ||
+ ('0' <= name[i] && name[i] <= '9') || (name[i] == '_')) {
+ last_was_period = false;
+ } else if (name[i] == '.') {
+ if (last_was_period) return false;
+ last_was_period = true;
+ } else {
+ return false;
+ }
+ }
+
+ return !name.empty() && !last_was_period;
+}
+
+Symbol DescriptorPool::NewPlaceholder(const string& name,
+ PlaceholderType placeholder_type) const {
+ MutexLockMaybe lock(mutex_);
+ return NewPlaceholderWithMutexHeld(name, placeholder_type);
+}
+
+Symbol DescriptorPool::NewPlaceholderWithMutexHeld(
+ const string& name, PlaceholderType placeholder_type) const {
+ if (mutex_) {
+ mutex_->AssertHeld();
+ }
// Compute names.
const string* placeholder_full_name;
const string* placeholder_name;
@@ -3678,7 +3883,7 @@ Symbol DescriptorBuilder::NewPlaceholder(const string& name,
}
// Create the placeholders.
- FileDescriptor* placeholder_file = NewPlaceholderFile(
+ FileDescriptor* placeholder_file = NewPlaceholderFileWithMutexHeld(
*placeholder_full_name + ".placeholder.proto");
placeholder_file->package_ = placeholder_package;
@@ -3744,19 +3949,28 @@ Symbol DescriptorBuilder::NewPlaceholder(const string& name,
}
}
-FileDescriptor* DescriptorBuilder::NewPlaceholderFile(
- const string& name) {
+FileDescriptor* DescriptorPool::NewPlaceholderFile(const string& name) const {
+ MutexLockMaybe lock(mutex_);
+ return NewPlaceholderFileWithMutexHeld(name);
+}
+
+FileDescriptor* DescriptorPool::NewPlaceholderFileWithMutexHeld(
+ const string& name) const {
+ if (mutex_) {
+ mutex_->AssertHeld();
+ }
FileDescriptor* placeholder = tables_->Allocate<FileDescriptor>();
memset(placeholder, 0, sizeof(*placeholder));
placeholder->name_ = tables_->AllocateString(name);
placeholder->package_ = &internal::GetEmptyString();
- placeholder->pool_ = pool_;
+ placeholder->pool_ = this;
placeholder->options_ = &FileOptions::default_instance();
placeholder->tables_ = &FileDescriptorTables::GetEmptyInstance();
placeholder->source_code_info_ = &SourceCodeInfo::default_instance();
placeholder->is_placeholder_ = true;
placeholder->syntax_ = FileDescriptor::SYNTAX_PROTO2;
+ placeholder->finished_building_ = true;
// All other fields are zero or NULL.
return placeholder;
@@ -3850,27 +4064,6 @@ void DescriptorBuilder::ValidateSymbolName(
}
}
-bool DescriptorBuilder::ValidateQualifiedName(const string& name) {
- bool last_was_period = false;
-
- for (int i = 0; i < name.size(); i++) {
- // I don't trust isalnum() due to locales. :(
- if (('a' <= name[i] && name[i] <= 'z') ||
- ('A' <= name[i] && name[i] <= 'Z') ||
- ('0' <= name[i] && name[i] <= '9') ||
- (name[i] == '_')) {
- last_was_period = false;
- } else if (name[i] == '.') {
- if (last_was_period) return false;
- last_was_period = true;
- } else {
- return false;
- }
- }
-
- return !name.empty() && !last_was_period;
-}
-
// -------------------------------------------------------------------
// This generic implementation is good for all descriptors except
@@ -4014,33 +4207,47 @@ const FileDescriptor* DescriptorBuilder::BuildFile(
}
}
- // If we have a fallback_database_, attempt to load all dependencies now,
- // before checkpointing tables_. This avoids confusion with recursive
- // checkpoints.
- if (pool_->fallback_database_ != NULL) {
- tables_->pending_files_.push_back(proto.name());
- for (int i = 0; i < proto.dependency_size(); i++) {
- if (tables_->FindFile(proto.dependency(i)) == NULL &&
- (pool_->underlay_ == NULL ||
- pool_->underlay_->FindFileByName(proto.dependency(i)) == NULL)) {
- // We don't care what this returns since we'll find out below anyway.
- pool_->TryFindFileInFallbackDatabase(proto.dependency(i));
+ // If we have a fallback_database_, and we aren't doing lazy import building,
+ // attempt to load all dependencies now, before checkpointing tables_. This
+ // avoids confusion with recursive checkpoints.
+ if (!pool_->lazily_build_dependencies_) {
+ if (pool_->fallback_database_ != NULL) {
+ tables_->pending_files_.push_back(proto.name());
+ for (int i = 0; i < proto.dependency_size(); i++) {
+ if (tables_->FindFile(proto.dependency(i)) == NULL &&
+ (pool_->underlay_ == NULL ||
+ pool_->underlay_->FindFileByName(proto.dependency(i)) == NULL)) {
+ // We don't care what this returns since we'll find out below anyway.
+ pool_->TryFindFileInFallbackDatabase(proto.dependency(i));
+ }
}
+ tables_->pending_files_.pop_back();
}
- tables_->pending_files_.pop_back();
}
- return BuildFileImpl(proto);
-}
-const FileDescriptor* DescriptorBuilder::BuildFileImpl(
- const FileDescriptorProto& proto) {
// Checkpoint the tables so that we can roll back if something goes wrong.
tables_->AddCheckpoint();
+ FileDescriptor* result = BuildFileImpl(proto);
+
+ file_tables_->FinalizeTables();
+ if (result) {
+ tables_->ClearLastCheckpoint();
+ result->finished_building_ = true;
+ } else {
+ tables_->RollbackToLastCheckpoint();
+ }
+
+ return result;
+}
+
+FileDescriptor* DescriptorBuilder::BuildFileImpl(
+ const FileDescriptorProto& proto) {
FileDescriptor* result = tables_->Allocate<FileDescriptor>();
file_ = result;
result->is_placeholder_ = false;
+ result->finished_building_ = false;
if (proto.has_source_code_info()) {
SourceCodeInfo *info = tables_->AllocateMessage<SourceCodeInfo>();
info->CopyFrom(proto.source_code_info());
@@ -4087,7 +4294,6 @@ const FileDescriptor* DescriptorBuilder::BuildFileImpl(
"A file with this name is already in the pool.");
// Bail out early so that if this is actually the exact same file, we
// don't end up reporting that every single symbol is already defined.
- tables_->RollbackToLastCheckpoint();
return NULL;
}
if (!result->package().empty()) {
@@ -4098,7 +4304,19 @@ const FileDescriptor* DescriptorBuilder::BuildFileImpl(
std::set<string> seen_dependencies;
result->dependency_count_ = proto.dependency_size();
result->dependencies_ =
- tables_->AllocateArray<const FileDescriptor*>(proto.dependency_size());
+ tables_->AllocateArray<const FileDescriptor*>(proto.dependency_size());
+ if (pool_->lazily_build_dependencies_) {
+ result->dependencies_once_ = tables_->AllocateOnceDynamic();
+ result->dependencies_names_ =
+ tables_->AllocateArray<const string*>(proto.dependency_size());
+ if (proto.dependency_size() > 0) {
+ memset(result->dependencies_names_, 0,
+ sizeof(*result->dependencies_names_) * proto.dependency_size());
+ }
+ } else {
+ result->dependencies_once_ = NULL;
+ result->dependencies_names_ = NULL;
+ }
unused_dependency_.clear();
std::set<int> weak_deps;
for (int i = 0; i < proto.weak_dependency_size(); ++i) {
@@ -4114,12 +4332,22 @@ const FileDescriptor* DescriptorBuilder::BuildFileImpl(
dependency = pool_->underlay_->FindFileByName(proto.dependency(i));
}
+ if (dependency == result) {
+ // Recursive import. dependency/result is not fully initialized, and it's
+ // dangerous to try to do anything with it. The recursive import error
+ // will be detected and reported in DescriptorBuilder::BuildFile().
+ return NULL;
+ }
+
if (dependency == NULL) {
- if (pool_->allow_unknown_ ||
- (!pool_->enforce_weak_ && weak_deps.find(i) != weak_deps.end())) {
- dependency = NewPlaceholderFile(proto.dependency(i));
- } else {
- AddImportError(proto, i);
+ if (!pool_->lazily_build_dependencies_) {
+ if (pool_->allow_unknown_ ||
+ (!pool_->enforce_weak_ && weak_deps.find(i) != weak_deps.end())) {
+ dependency =
+ pool_->NewPlaceholderFileWithMutexHeld(proto.dependency(i));
+ } else {
+ AddImportError(proto, i);
+ }
}
} else {
// Add to unused_dependency_ to track unused imported files.
@@ -4133,6 +4361,10 @@ const FileDescriptor* DescriptorBuilder::BuildFileImpl(
}
result->dependencies_[i] = dependency;
+ if (pool_->lazily_build_dependencies_ && !dependency) {
+ result->dependencies_names_[i] =
+ tables_->AllocateString(proto.dependency(i));
+ }
}
// Check public dependencies.
@@ -4145,7 +4377,12 @@ const FileDescriptor* DescriptorBuilder::BuildFileImpl(
if (index >= 0 && index < proto.dependency_size()) {
result->public_dependencies_[public_dependency_count++] = index;
// Do not track unused imported files for public import.
- unused_dependency_.erase(result->dependency(index));
+ // Calling dependency(i) builds that file when doing lazy imports,
+ // need to avoid doing this. Unused dependency detection isn't done
+ // when building lazily, anyways.
+ if (!pool_->lazily_build_dependencies_) {
+ unused_dependency_.erase(result->dependency(index));
+ }
} else {
AddError(proto.name(), proto,
DescriptorPool::ErrorCollector::OTHER,
@@ -4156,8 +4393,13 @@ const FileDescriptor* DescriptorBuilder::BuildFileImpl(
// Build dependency set
dependencies_.clear();
- for (int i = 0; i < result->dependency_count(); i++) {
- RecordPublicDependencies(result->dependency(i));
+ // We don't/can't do proper dependency error checking when
+ // lazily_build_dependencies_, and calling dependency(i) will force
+ // a dependency to be built, which we don't want.
+ if (!pool_->lazily_build_dependencies_) {
+ for (int i = 0; i < result->dependency_count(); i++) {
+ RecordPublicDependencies(result->dependency(i));
+ }
}
// Check weak dependencies.
@@ -4207,8 +4449,9 @@ const FileDescriptor* DescriptorBuilder::BuildFileImpl(
options_to_interpret_.clear();
}
- // Validate options.
- if (!had_errors_) {
+ // Validate options. See comments at InternalSetLazilyBuildDependencies about
+ // error checking and lazy import building.
+ if (!had_errors_ && !pool_->lazily_build_dependencies_) {
ValidateFileOptions(result, proto);
}
@@ -4221,15 +4464,15 @@ const FileDescriptor* DescriptorBuilder::BuildFileImpl(
}
- if (!unused_dependency_.empty()) {
+ // Again, see comments at InternalSetLazilyBuildDependencies about error
+ // checking.
+ if (!unused_dependency_.empty() && !pool_->lazily_build_dependencies_) {
LogUnusedDependency(proto, result);
}
if (had_errors_) {
- tables_->RollbackToLastCheckpoint();
return NULL;
} else {
- tables_->ClearLastCheckpoint();
return result;
}
}
@@ -4439,6 +4682,10 @@ void DescriptorBuilder::BuildFieldOrExtension(const FieldDescriptorProto& proto,
result->extension_scope_ = NULL;
result->message_type_ = NULL;
result->enum_type_ = NULL;
+ result->type_name_ = NULL;
+ result->type_once_ = NULL;
+ result->default_value_enum_ = NULL;
+ result->default_value_enum_name_ = NULL;
result->has_default_value_ = proto.has_default_value();
if (proto.has_default_value() && result->is_repeated()) {
@@ -4681,6 +4928,13 @@ void DescriptorBuilder::BuildExtensionRange(
DescriptorPool::ErrorCollector::NUMBER,
"Extension range end number must be greater than start number.");
}
+
+ if (!proto.has_options()) {
+ result->options_ = NULL; // Will set to default_instance later.
+ } else {
+ AllocateOptionsImpl(parent->full_name(), parent->full_name(),
+ proto.options(), result);
+ }
}
void DescriptorBuilder::BuildReservedRange(
@@ -4696,6 +4950,19 @@ void DescriptorBuilder::BuildReservedRange(
}
}
+void DescriptorBuilder::BuildReservedRange(
+ const EnumDescriptorProto::EnumReservedRange& proto,
+ const EnumDescriptor* parent, EnumDescriptor::ReservedRange* result) {
+ result->start = proto.start();
+ result->end = proto.end();
+
+ if (result->start > result->end) {
+ AddError(parent->full_name(), proto,
+ DescriptorPool::ErrorCollector::NUMBER,
+ "Reserved range end number must be greater than start number.");
+ }
+}
+
void DescriptorBuilder::BuildOneof(const OneofDescriptorProto& proto,
Descriptor* parent,
OneofDescriptor* result) {
@@ -4817,6 +5084,17 @@ void DescriptorBuilder::BuildEnum(const EnumDescriptorProto& proto,
}
BUILD_ARRAY(proto, result, value, BuildEnumValue, result);
+ BUILD_ARRAY(proto, result, reserved_range, BuildReservedRange, result);
+
+ // Copy reserved names.
+ int reserved_name_count = proto.reserved_name_size();
+ result->reserved_name_count_ = reserved_name_count;
+ result->reserved_names_ =
+ tables_->AllocateArray<const string*>(reserved_name_count);
+ for (int i = 0; i < reserved_name_count; ++i) {
+ result->reserved_names_[i] =
+ tables_->AllocateString(proto.reserved_name(i));
+ }
CheckEnumValueUniqueness(proto, result);
@@ -4829,6 +5107,56 @@ void DescriptorBuilder::BuildEnum(const EnumDescriptorProto& proto,
AddSymbol(result->full_name(), parent, result->name(),
proto, Symbol(result));
+
+ for (int i = 0; i < proto.reserved_range_size(); i++) {
+ const EnumDescriptorProto_EnumReservedRange& range1 =
+ proto.reserved_range(i);
+ for (int j = i + 1; j < proto.reserved_range_size(); j++) {
+ const EnumDescriptorProto_EnumReservedRange& range2 =
+ proto.reserved_range(j);
+ if (range1.end() > range2.start() && range2.end() > range1.start()) {
+ AddError(result->full_name(), proto.reserved_range(i),
+ DescriptorPool::ErrorCollector::NUMBER,
+ strings::Substitute("Reserved range $0 to $1 overlaps with "
+ "already-defined range $2 to $3.",
+ range2.start(), range2.end() - 1,
+ range1.start(), range1.end() - 1));
+ }
+ }
+ }
+
+ hash_set<string> reserved_name_set;
+ for (int i = 0; i < proto.reserved_name_size(); i++) {
+ const string& name = proto.reserved_name(i);
+ if (reserved_name_set.find(name) == reserved_name_set.end()) {
+ reserved_name_set.insert(name);
+ } else {
+ AddError(name, proto, DescriptorPool::ErrorCollector::NAME,
+ strings::Substitute(
+ "Enum value \"$0\" is reserved multiple times.",
+ name));
+ }
+ }
+
+ for (int i = 0; i < result->value_count(); i++) {
+ const EnumValueDescriptor* value = result->value(i);
+ for (int j = 0; j < result->reserved_range_count(); j++) {
+ const EnumDescriptor::ReservedRange* range = result->reserved_range(j);
+ if (range->start <= value->number() && value->number() <= range->end) {
+ AddError(value->full_name(), proto.reserved_range(j),
+ DescriptorPool::ErrorCollector::NUMBER,
+ strings::Substitute(
+ "Enum value \"$0\" uses reserved number $1.",
+ value->name(), value->number()));
+ }
+ }
+ if (reserved_name_set.find(value->name()) != reserved_name_set.end()) {
+ AddError(value->full_name(), proto.value(i),
+ DescriptorPool::ErrorCollector::NAME,
+ strings::Substitute(
+ "Enum value \"$0\" is reserved.", value->name()));
+ }
+ }
}
void DescriptorBuilder::BuildEnumValue(const EnumValueDescriptorProto& proto,
@@ -4939,8 +5267,8 @@ void DescriptorBuilder::BuildMethod(const MethodDescriptorProto& proto,
ValidateSymbolName(proto.name(), *full_name, proto);
// These will be filled in when cross-linking.
- result->input_type_ = NULL;
- result->output_type_ = NULL;
+ result->input_type_.Init();
+ result->output_type_.Init();
// Copy options.
if (!proto.has_options()) {
@@ -5005,6 +5333,11 @@ void DescriptorBuilder::CrossLinkMessage(
CrossLinkField(&message->extensions_[i], proto.extension(i));
}
+ for (int i = 0; i < message->extension_range_count(); i++) {
+ CrossLinkExtensionRange(&message->extension_ranges_[i],
+ proto.extension_range(i));
+ }
+
// Set up field array for each oneof.
// First count the number of fields per oneof.
@@ -5067,15 +5400,27 @@ void DescriptorBuilder::CrossLinkMessage(
}
}
+void DescriptorBuilder::CrossLinkExtensionRange(
+ Descriptor::ExtensionRange* range,
+ const DescriptorProto::ExtensionRange& proto) {
+ if (range->options_ == NULL) {
+ range->options_ = &ExtensionRangeOptions::default_instance();
+ }
+}
+
void DescriptorBuilder::CrossLinkField(
FieldDescriptor* field, const FieldDescriptorProto& proto) {
if (field->options_ == NULL) {
field->options_ = &FieldOptions::default_instance();
}
+ // Add the field to the lowercase-name and camelcase-name tables.
+ file_tables_->AddFieldByStylizedNames(field);
+
if (proto.has_extendee()) {
- Symbol extendee = LookupSymbol(proto.extendee(), field->full_name(),
- PLACEHOLDER_EXTENDABLE_MESSAGE);
+ Symbol extendee =
+ LookupSymbol(proto.extendee(), field->full_name(),
+ DescriptorPool::PLACEHOLDER_EXTENDABLE_MESSAGE);
if (extendee.IsNull()) {
AddNotDefinedError(field->full_name(), proto,
DescriptorPool::ErrorCollector::EXTENDEE,
@@ -5120,21 +5465,56 @@ void DescriptorBuilder::CrossLinkField(
bool expecting_enum = (proto.type() == FieldDescriptorProto::TYPE_ENUM) ||
proto.has_default_value();
- Symbol type =
- LookupSymbol(proto.type_name(), field->full_name(),
- expecting_enum ? PLACEHOLDER_ENUM : PLACEHOLDER_MESSAGE,
- LOOKUP_TYPES);
+ // In case of weak fields we force building the dependency. We need to know
+ // if the type exist or not. If it doesnt exist we substitute Empty which
+ // should only be done if the type can't be found in the generated pool.
+ // TODO(gerbens) Ideally we should query the database directly to check
+ // if weak fields exist or not so that we don't need to force building
+ // weak dependencies. However the name lookup rules for symbols are
+ // somewhat complicated, so I defer it too another CL.
+ bool is_weak = !pool_->enforce_weak_ && proto.options().weak();
+ bool is_lazy = pool_->lazily_build_dependencies_ && !is_weak;
- // If the type is a weak type, we change the type to a google.protobuf.Empty field.
- if (type.IsNull() && !pool_->enforce_weak_ && proto.options().weak()) {
- type = FindSymbol(kNonLinkedWeakMessageReplacementName);
- }
+ Symbol type =
+ LookupSymbol(proto.type_name(), field->full_name(),
+ expecting_enum ? DescriptorPool::PLACEHOLDER_ENUM
+ : DescriptorPool::PLACEHOLDER_MESSAGE,
+ LOOKUP_TYPES, !is_lazy);
if (type.IsNull()) {
- AddNotDefinedError(field->full_name(), proto,
- DescriptorPool::ErrorCollector::TYPE,
- proto.type_name());
- return;
+ if (is_lazy) {
+ // Save the symbol names for later for lookup, and allocate the once
+ // object needed for the accessors.
+ string name = proto.type_name();
+ field->type_once_ = tables_->AllocateOnceDynamic();
+ field->type_name_ = tables_->AllocateString(name);
+ if (proto.has_default_value()) {
+ field->default_value_enum_name_ =
+ tables_->AllocateString(proto.default_value());
+ }
+ // AddFieldByNumber and AddExtension are done later in this function,
+ // and can/must be done if the field type was not found. The related
+ // error checking is not necessary when in lazily_build_dependencies_
+ // mode, and can't be done without building the type's descriptor,
+ // which we don't want to do.
+ file_tables_->AddFieldByNumber(field);
+ if (field->is_extension()) {
+ tables_->AddExtension(field);
+ }
+ return;
+ } else {
+ // If the type is a weak type, we change the type to a google.protobuf.Empty
+ // field.
+ if (is_weak) {
+ type = FindSymbol(kNonLinkedWeakMessageReplacementName);
+ }
+ if (type.IsNull()) {
+ AddNotDefinedError(field->full_name(), proto,
+ DescriptorPool::ErrorCollector::TYPE,
+ proto.type_name());
+ return;
+ }
+ }
}
if (!proto.has_type()) {
@@ -5230,7 +5610,10 @@ void DescriptorBuilder::CrossLinkField(
// Add the field to the fields-by-number table.
// Note: We have to do this *after* cross-linking because extensions do not
- // know their containing type until now.
+ // know their containing type until now. If we're in
+ // lazily_build_dependencies_ mode, we're guaranteed there's no errors, so no
+ // risk to calling containing_type() or other accessors that will build
+ // dependencies.
if (!file_tables_->AddFieldByNumber(field)) {
const FieldDescriptor* conflicting_field =
file_tables_->FindFieldByNumber(field->containing_type(),
@@ -5276,9 +5659,6 @@ void DescriptorBuilder::CrossLinkField(
}
}
}
-
- // Add the field to the lowercase-name and camelcase-name tables.
- file_tables_->AddFieldByStylizedNames(field);
}
void DescriptorBuilder::CrossLinkEnum(
@@ -5317,30 +5697,44 @@ void DescriptorBuilder::CrossLinkMethod(
method->options_ = &MethodOptions::default_instance();
}
- Symbol input_type = LookupSymbol(proto.input_type(), method->full_name());
+ Symbol input_type =
+ LookupSymbol(proto.input_type(), method->full_name(),
+ DescriptorPool::PLACEHOLDER_MESSAGE, LOOKUP_ALL,
+ !pool_->lazily_build_dependencies_);
if (input_type.IsNull()) {
- AddNotDefinedError(method->full_name(), proto,
- DescriptorPool::ErrorCollector::INPUT_TYPE,
- proto.input_type());
+ if (!pool_->lazily_build_dependencies_) {
+ AddNotDefinedError(method->full_name(), proto,
+ DescriptorPool::ErrorCollector::INPUT_TYPE,
+ proto.input_type());
+ } else {
+ method->input_type_.SetLazy(proto.input_type(), file_);
+ }
} else if (input_type.type != Symbol::MESSAGE) {
AddError(method->full_name(), proto,
DescriptorPool::ErrorCollector::INPUT_TYPE,
"\"" + proto.input_type() + "\" is not a message type.");
} else {
- method->input_type_ = input_type.descriptor;
+ method->input_type_.Set(input_type.descriptor);
}
- Symbol output_type = LookupSymbol(proto.output_type(), method->full_name());
+ Symbol output_type =
+ LookupSymbol(proto.output_type(), method->full_name(),
+ DescriptorPool::PLACEHOLDER_MESSAGE, LOOKUP_ALL,
+ !pool_->lazily_build_dependencies_);
if (output_type.IsNull()) {
- AddNotDefinedError(method->full_name(), proto,
- DescriptorPool::ErrorCollector::OUTPUT_TYPE,
- proto.output_type());
+ if (!pool_->lazily_build_dependencies_) {
+ AddNotDefinedError(method->full_name(), proto,
+ DescriptorPool::ErrorCollector::OUTPUT_TYPE,
+ proto.output_type());
+ } else {
+ method->output_type_.SetLazy(proto.output_type(), file_);
+ }
} else if (output_type.type != Symbol::MESSAGE) {
AddError(method->full_name(), proto,
DescriptorPool::ErrorCollector::OUTPUT_TYPE,
"\"" + proto.output_type() + "\" is not a message type.");
} else {
- method->output_type_ = output_type.descriptor;
+ method->output_type_.Set(output_type.descriptor);
}
}
@@ -5531,8 +5925,12 @@ void DescriptorBuilder::ValidateMessageOptions(Descriptor* message,
}
}
+
void DescriptorBuilder::ValidateFieldOptions(FieldDescriptor* field,
const FieldDescriptorProto& proto) {
+ if (pool_->lazily_build_dependencies_ && (!field || !field->message_type())) {
+ return;
+ }
// Only message type fields may be lazy.
if (field->options().lazy()) {
if (field->type() != FieldDescriptor::TYPE_MESSAGE) {
@@ -5591,6 +5989,8 @@ void DescriptorBuilder::ValidateFieldOptions(FieldDescriptor* field,
}
}
+ ValidateJSType(field, proto);
+
}
void DescriptorBuilder::ValidateEnumOptions(EnumDescriptor* enm,
@@ -5779,6 +6179,40 @@ void DescriptorBuilder::DetectMapConflicts(const Descriptor* message,
}
}
+void DescriptorBuilder::ValidateJSType(FieldDescriptor* field,
+ const FieldDescriptorProto& proto) {
+ FieldOptions::JSType jstype = field->options().jstype();
+ // The default is always acceptable.
+ if (jstype == FieldOptions::JS_NORMAL) {
+ return;
+ }
+
+ switch (field->type()) {
+ // Integral 64-bit types may be represented as JavaScript numbers or
+ // strings.
+ case FieldDescriptor::TYPE_UINT64:
+ case FieldDescriptor::TYPE_INT64:
+ case FieldDescriptor::TYPE_SINT64:
+ case FieldDescriptor::TYPE_FIXED64:
+ case FieldDescriptor::TYPE_SFIXED64:
+ if (jstype == FieldOptions::JS_STRING ||
+ jstype == FieldOptions::JS_NUMBER) {
+ return;
+ }
+ AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE,
+ "Illegal jstype for int64, uint64, sint64, fixed64 "
+ "or sfixed64 field: " +
+ FieldOptions_JSType_descriptor()->value(jstype)->name());
+ break;
+
+ // No other types permit a jstype option.
+ default:
+ AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE,
+ "jstype is only allowed on int64, uint64, sint64, fixed64 "
+ "or sfixed64 fields.");
+ break;
+ }
+}
#undef VALIDATE_OPTIONS_FROM_ARRAY
@@ -6520,6 +6954,7 @@ void DescriptorBuilder::LogUnusedDependency(const FileDescriptorProto& proto,
annotation_extensions.insert("google.protobuf.FieldOptions");
annotation_extensions.insert("google.protobuf.EnumOptions");
annotation_extensions.insert("google.protobuf.EnumValueOptions");
+ annotation_extensions.insert("google.protobuf.EnumValueOptions");
annotation_extensions.insert("google.protobuf.ServiceOptions");
annotation_extensions.insert("google.protobuf.MethodOptions");
annotation_extensions.insert("google.protobuf.StreamOptions");
@@ -6545,5 +6980,158 @@ void DescriptorBuilder::LogUnusedDependency(const FileDescriptorProto& proto,
}
}
+Symbol DescriptorPool::CrossLinkOnDemandHelper(const string& name,
+ bool expecting_enum) const {
+ string lookup_name = name;
+ if (!lookup_name.empty() && lookup_name[0] == '.') {
+ lookup_name = lookup_name.substr(1);
+ }
+ Symbol result = tables_->FindByNameHelper(this, lookup_name);
+ return result;
+}
+
+// Handle the lazy import building for a message field whose type wasn't built
+// at cross link time. If that was the case, we saved the name of the type to
+// be looked up when the accessor for the type was called. Set type_,
+// enum_type_, message_type_, and default_value_enum_ appropriately.
+void FieldDescriptor::InternalTypeOnceInit() const {
+ GOOGLE_CHECK(file()->finished_building_ == true);
+ if (type_name_) {
+ Symbol result = file()->pool()->CrossLinkOnDemandHelper(
+ *type_name_, type_ == FieldDescriptor::TYPE_ENUM);
+ if (result.type == Symbol::MESSAGE) {
+ type_ = FieldDescriptor::TYPE_MESSAGE;
+ message_type_ = result.descriptor;
+ } else if (result.type == Symbol::ENUM) {
+ type_ = FieldDescriptor::TYPE_ENUM;
+ enum_type_ = result.enum_descriptor;
+ }
+ }
+ if (enum_type_ && !default_value_enum_) {
+ if (default_value_enum_name_) {
+ // Have to build the full name now instead of at CrossLink time,
+ // because enum_type_ may not be known at the time.
+ string name = enum_type_->full_name();
+ // Enum values reside in the same scope as the enum type.
+ string::size_type last_dot = name.find_last_of('.');
+ if (last_dot != string::npos) {
+ name = name.substr(0, last_dot) + "." + *default_value_enum_name_;
+ } else {
+ name = *default_value_enum_name_;
+ }
+ Symbol result = file()->pool()->CrossLinkOnDemandHelper(name, true);
+ if (result.type == Symbol::ENUM_VALUE) {
+ default_value_enum_ = result.enum_value_descriptor;
+ }
+ }
+ if (!default_value_enum_) {
+ // We use the first defined value as the default
+ // if a default is not explicitly defined.
+ GOOGLE_CHECK(enum_type_->value_count());
+ default_value_enum_ = enum_type_->value(0);
+ }
+ }
+}
+
+void FieldDescriptor::TypeOnceInit(const FieldDescriptor* to_init) {
+ to_init->InternalTypeOnceInit();
+}
+
+// message_type(), enum_type(), default_value_enum(), and type()
+// all share the same GoogleOnceDynamic init path to do lazy
+// import building and cross linking of a field of a message.
+const Descriptor* FieldDescriptor::message_type() const {
+ if (type_once_) {
+ type_once_->Init(&FieldDescriptor::TypeOnceInit, this);
+ }
+ return message_type_;
+}
+
+const EnumDescriptor* FieldDescriptor::enum_type() const {
+ if (type_once_) {
+ type_once_->Init(&FieldDescriptor::TypeOnceInit, this);
+ }
+ return enum_type_;
+}
+
+const EnumValueDescriptor* FieldDescriptor::default_value_enum() const {
+ if (type_once_) {
+ type_once_->Init(&FieldDescriptor::TypeOnceInit, this);
+ }
+ return default_value_enum_;
+}
+
+void FileDescriptor::InternalDependenciesOnceInit() const {
+ GOOGLE_CHECK(finished_building_ == true);
+ for (int i = 0; i < dependency_count(); i++) {
+ if (dependencies_names_[i]) {
+ dependencies_[i] = pool_->FindFileByName(*dependencies_names_[i]);
+ }
+ }
+}
+
+void FileDescriptor::DependenciesOnceInit(const FileDescriptor* to_init) {
+ to_init->InternalDependenciesOnceInit();
+}
+
+const FileDescriptor* FileDescriptor::dependency(int index) const {
+ if (dependencies_once_) {
+ // Do once init for all indicies, as it's unlikely only a single index would
+ // be called, and saves on GoogleOnceDynamic allocations.
+ dependencies_once_->Init(&FileDescriptor::DependenciesOnceInit, this);
+ }
+ return dependencies_[index];
+}
+
+const Descriptor* MethodDescriptor::input_type() const {
+ return input_type_.Get();
+}
+
+const Descriptor* MethodDescriptor::output_type() const {
+ return output_type_.Get();
+}
+
+
+namespace internal {
+void LazyDescriptor::Set(const Descriptor* descriptor) {
+ GOOGLE_CHECK(!name_);
+ GOOGLE_CHECK(!once_);
+ GOOGLE_CHECK(!file_);
+ descriptor_ = descriptor;
+}
+
+void LazyDescriptor::SetLazy(const string& name, const FileDescriptor* file) {
+ // verify Init() has been called and Set hasn't been called yet.
+ GOOGLE_CHECK(!descriptor_);
+ GOOGLE_CHECK(!file_);
+ GOOGLE_CHECK(!name_);
+ GOOGLE_CHECK(!once_);
+ GOOGLE_CHECK(file && file->pool_);
+ GOOGLE_CHECK(file->pool_->lazily_build_dependencies_);
+ GOOGLE_CHECK(!file->finished_building_);
+ file_ = file;
+ name_ = file->pool_->tables_->AllocateString(name);
+ once_ = file->pool_->tables_->AllocateOnceDynamic();
+}
+
+void LazyDescriptor::Once() {
+ if (once_) {
+ once_->Init(&LazyDescriptor::OnceStatic, this);
+ }
+}
+
+void LazyDescriptor::OnceStatic(LazyDescriptor* lazy) { lazy->OnceInternal(); }
+
+void LazyDescriptor::OnceInternal() {
+ GOOGLE_CHECK(file_->finished_building_);
+ if (!descriptor_ && name_) {
+ Symbol result = file_->pool_->CrossLinkOnDemandHelper(*name_, false);
+ if (!result.IsNull() && result.type == Symbol::MESSAGE) {
+ descriptor_ = result.descriptor;
+ }
+ }
+}
+} // namespace internal
+
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/descriptor.h b/src/google/protobuf/descriptor.h
index cc099693..5f5159a8 100644
--- a/src/google/protobuf/descriptor.h
+++ b/src/google/protobuf/descriptor.h
@@ -63,6 +63,7 @@
#include <vector>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/mutex.h>
+#include <google/protobuf/stubs/once.h>
// TYPE_BOOL is defined in the MacOS's ConditionalMacros.h.
#ifdef TYPE_BOOL
@@ -98,6 +99,7 @@ class FieldOptions;
class OneofOptions;
class EnumOptions;
class EnumValueOptions;
+class ExtensionRangeOptions;
class ServiceOptions;
class MethodOptions;
class FileOptions;
@@ -110,6 +112,7 @@ class Message;
// Defined in descriptor.cc
class DescriptorBuilder;
class FileDescriptorTables;
+struct Symbol;
// Defined in unknown_field_set.h.
class UnknownField;
@@ -165,6 +168,55 @@ struct DebugStringOptions {
elide_oneof_body(false) {}
};
+// A class to handle the simplest cases of a lazily linked descriptor
+// for a message type that isn't built at the time of cross linking,
+// which is needed when a pool has lazily_build_dependencies_ set.
+// Must be instantiated as mutable in a descriptor.
+namespace internal {
+class LIBPROTOBUF_EXPORT LazyDescriptor {
+ public:
+ // Init function to be called at init time of a descriptor containing
+ // a LazyDescriptor.
+ void Init() {
+ descriptor_ = NULL;
+ name_ = NULL;
+ once_ = NULL;
+ file_ = NULL;
+ }
+
+ // Sets the value of the descriptor if it is known during the descriptor
+ // building process. Not thread safe, should only be called during the
+ // descriptor build process. Should not be called after SetLazy has been
+ // called.
+ void Set(const Descriptor* descriptor);
+
+ // Sets the information needed to lazily cross link the descriptor at a later
+ // time, SetLazy is not thread safe, should be called only once at descriptor
+ // build time if the symbol wasn't found and building of the file containing
+ // that type is delayed because lazily_build_dependencies_ is set on the pool.
+ // Should not be called after Set() has been called.
+ void SetLazy(const string& name, const FileDescriptor* file);
+
+ // Returns the current value of the descriptor, thread-safe. If SetLazy(...)
+ // has been called, will do a one-time cross link of the type specified,
+ // building the descriptor file that contains the type if necessary.
+ inline const Descriptor* Get() {
+ Once();
+ return descriptor_;
+ }
+
+ private:
+ static void OnceStatic(LazyDescriptor* lazy);
+ void OnceInternal();
+ void Once();
+
+ const Descriptor* descriptor_;
+ const string* name_;
+ GoogleOnceDynamic* once_;
+ const FileDescriptor* file_;
+};
+} // namespace internal
+
// Describes a type of protocol message, or a particular group within a
// message. To obtain the Descriptor for a given message object, call
// Message::GetDescriptor(). Generated message classes also have a
@@ -286,8 +338,12 @@ class LIBPROTOBUF_EXPORT Descriptor {
// A range of field numbers which are designated for third-party
// extensions.
struct ExtensionRange {
+ typedef ExtensionRangeOptions OptionsType;
+
int start; // inclusive
int end; // exclusive
+
+ const ExtensionRangeOptions* options_;
};
// The number of extension ranges in this message type.
@@ -389,27 +445,30 @@ class LIBPROTOBUF_EXPORT Descriptor {
const Descriptor* containing_type_;
const MessageOptions* options_;
- // True if this is a placeholder for an unknown type.
- bool is_placeholder_;
- // True if this is a placeholder and the type name wasn't fully-qualified.
- bool is_unqualified_placeholder_;
+ // These arrays are separated from their sizes to minimize padding on 64-bit.
+ FieldDescriptor* fields_;
+ OneofDescriptor* oneof_decls_;
+ Descriptor* nested_types_;
+ EnumDescriptor* enum_types_;
+ ExtensionRange* extension_ranges_;
+ FieldDescriptor* extensions_;
+ ReservedRange* reserved_ranges_;
+ const string** reserved_names_;
int field_count_;
- FieldDescriptor* fields_;
int oneof_decl_count_;
- OneofDescriptor* oneof_decls_;
int nested_type_count_;
- Descriptor* nested_types_;
int enum_type_count_;
- EnumDescriptor* enum_types_;
int extension_range_count_;
- ExtensionRange* extension_ranges_;
int extension_count_;
- FieldDescriptor* extensions_;
int reserved_range_count_;
- ReservedRange* reserved_ranges_;
int reserved_name_count_;
- const string** reserved_names_;
+
+ // True if this is a placeholder for an unknown type.
+ bool is_placeholder_;
+ // True if this is a placeholder and the type name wasn't fully-qualified.
+ bool is_unqualified_placeholder_;
+
// IMPORTANT: If you add a new field, make sure to search for all instances
// of Allocate<Descriptor>() and AllocateArray<Descriptor>() in descriptor.cc
// and update them to initialize the field.
@@ -417,6 +476,7 @@ class LIBPROTOBUF_EXPORT Descriptor {
// Must be constructed using DescriptorPool.
Descriptor() {}
friend class DescriptorBuilder;
+ friend class DescriptorPool;
friend class EnumDescriptor;
friend class FieldDescriptor;
friend class OneofDescriptor;
@@ -425,6 +485,7 @@ class LIBPROTOBUF_EXPORT Descriptor {
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Descriptor);
};
+
// Describes a single field of a message. To get the descriptor for a given
// field, first get the Descriptor for the message in which it is defined,
// then call Descriptor::FindFieldByName(). To get a FieldDescriptor for
@@ -680,33 +741,41 @@ class LIBPROTOBUF_EXPORT FieldDescriptor {
// to this descriptor from the file root.
void GetLocationPath(std::vector<int>* output) const;
+ // Returns true if this is a map message type.
+ bool is_map_message_type() const;
+
const string* name_;
const string* full_name_;
const string* lowercase_name_;
const string* camelcase_name_;
- // Whether the user has specified the json_name field option in the .proto
- // file.
- bool has_json_name_;
// If has_json_name_ is true, it's the value specified by the user.
// Otherwise, it has the same value as camelcase_name_.
const string* json_name_;
const FileDescriptor* file_;
- int number_;
- Type type_;
+ GoogleOnceDynamic* type_once_;
+ static void TypeOnceInit(const FieldDescriptor* to_init);
+ void InternalTypeOnceInit() const;
+ mutable Type type_;
Label label_;
+ bool has_default_value_;
+ // Whether the user has specified the json_name field option in the .proto
+ // file.
+ bool has_json_name_;
bool is_extension_;
+ int number_;
int index_in_oneof_;
const Descriptor* containing_type_;
const OneofDescriptor* containing_oneof_;
const Descriptor* extension_scope_;
- const Descriptor* message_type_;
- const EnumDescriptor* enum_type_;
+ mutable const Descriptor* message_type_;
+ mutable const EnumDescriptor* enum_type_;
const FieldOptions* options_;
+ const string* type_name_;
+ const string* default_value_enum_name_;
// IMPORTANT: If you add a new field, make sure to search for all instances
// of Allocate<FieldDescriptor>() and AllocateArray<FieldDescriptor>() in
// descriptor.cc and update them to initialize the field.
- bool has_default_value_;
union {
int32 default_value_int32_;
int64 default_value_int64_;
@@ -716,7 +785,7 @@ class LIBPROTOBUF_EXPORT FieldDescriptor {
double default_value_double_;
bool default_value_bool_;
- const EnumValueDescriptor* default_value_enum_;
+ mutable const EnumValueDescriptor* default_value_enum_;
const string* default_value_string_;
};
@@ -737,6 +806,7 @@ class LIBPROTOBUF_EXPORT FieldDescriptor {
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldDescriptor);
};
+
// Describes a oneof defined in a message type.
class LIBPROTOBUF_EXPORT OneofDescriptor {
public:
@@ -746,6 +816,8 @@ class LIBPROTOBUF_EXPORT OneofDescriptor {
// Index of this oneof within the message's oneof array.
int index() const;
+ // The .proto file in which this oneof was defined. Never NULL.
+ const FileDescriptor* file() const;
// The Descriptor for the message containing this oneof.
const Descriptor* containing_type() const;
@@ -855,12 +927,42 @@ class LIBPROTOBUF_EXPORT EnumDescriptor {
// See Descriptor::DebugStringWithOptions().
string DebugStringWithOptions(const DebugStringOptions& options) const;
-
// Returns true if this is a placeholder for an unknown enum. This will
// only be the case if this descriptor comes from a DescriptorPool
// with AllowUnknownDependencies() set.
bool is_placeholder() const;
+ // Reserved fields -------------------------------------------------
+
+ // A range of reserved field numbers.
+ struct ReservedRange {
+ int start; // inclusive
+ int end; // inclusive
+ };
+
+ // The number of reserved ranges in this message type.
+ int reserved_range_count() const;
+ // Gets an reserved range by index, where 0 <= index <
+ // reserved_range_count(). These are returned in the order they were defined
+ // in the .proto file.
+ const EnumDescriptor::ReservedRange* reserved_range(int index) const;
+
+ // Returns true if the number is in one of the reserved ranges.
+ bool IsReservedNumber(int number) const;
+
+ // Returns NULL if no reserved range contains the given number.
+ const EnumDescriptor::ReservedRange*
+ FindReservedRangeContainingNumber(int number) const;
+
+ // The number of reserved field names in this message type.
+ int reserved_name_count() const;
+
+ // Gets a reserved name by index, where 0 <= index < reserved_name_count().
+ const string& reserved_name(int index) const;
+
+ // Returns true if the field name is reserved.
+ bool IsReservedName(const string& name) const;
+
// Source Location ---------------------------------------------------
// Updates |*out_location| to the source location of the complete
@@ -907,6 +1009,12 @@ class LIBPROTOBUF_EXPORT EnumDescriptor {
int value_count_;
EnumValueDescriptor* values_;
+
+ int reserved_range_count_;
+ int reserved_name_count_;
+ EnumDescriptor::ReservedRange* reserved_ranges_;
+ const string** reserved_names_;
+
// IMPORTANT: If you add a new field, make sure to search for all instances
// of Allocate<EnumDescriptor>() and AllocateArray<EnumDescriptor>() in
// descriptor.cc and update them to initialize the field.
@@ -918,6 +1026,7 @@ class LIBPROTOBUF_EXPORT EnumDescriptor {
friend class FieldDescriptor;
friend class EnumValueDescriptor;
friend class FileDescriptor;
+ friend class DescriptorPool;
friend class internal::GeneratedMessageReflection;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumDescriptor);
};
@@ -940,6 +1049,8 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptor {
// with C++ scoping rules for enums.
const string& full_name() const;
+ // The .proto file in which this value was defined. Never NULL.
+ const FileDescriptor* file() const;
// The type of this value. Never NULL.
const EnumDescriptor* type() const;
@@ -994,6 +1105,7 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptor {
EnumValueDescriptor() {}
friend class DescriptorBuilder;
friend class EnumDescriptor;
+ friend class DescriptorPool;
friend class FileDescriptorTables;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumValueDescriptor);
};
@@ -1063,8 +1175,8 @@ class LIBPROTOBUF_EXPORT ServiceDescriptor {
const string* full_name_;
const FileDescriptor* file_;
const ServiceOptions* options_;
- int method_count_;
MethodDescriptor* methods_;
+ int method_count_;
// IMPORTANT: If you add a new field, make sure to search for all instances
// of Allocate<ServiceDescriptor>() and AllocateArray<ServiceDescriptor>() in
// descriptor.cc and update them to initialize the field.
@@ -1077,6 +1189,7 @@ class LIBPROTOBUF_EXPORT ServiceDescriptor {
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ServiceDescriptor);
};
+
// Describes an individual service method. To obtain a MethodDescriptor given
// a service, first get its ServiceDescriptor, then call
// ServiceDescriptor::FindMethodByName(). Use DescriptorPool to construct your
@@ -1090,6 +1203,8 @@ class LIBPROTOBUF_EXPORT MethodDescriptor {
// Index within the service's Descriptor.
int index() const;
+ // The .proto file in which this method was defined. Never NULL.
+ const FileDescriptor* file() const;
// Gets the service to which this method belongs. Never NULL.
const ServiceDescriptor* service() const;
@@ -1144,8 +1259,8 @@ class LIBPROTOBUF_EXPORT MethodDescriptor {
const string* name_;
const string* full_name_;
const ServiceDescriptor* service_;
- const Descriptor* input_type_;
- const Descriptor* output_type_;
+ mutable internal::LazyDescriptor input_type_;
+ mutable internal::LazyDescriptor output_type_;
const MethodOptions* options_;
bool client_streaming_;
bool server_streaming_;
@@ -1301,34 +1416,49 @@ class LIBPROTOBUF_EXPORT FileDescriptor {
const string* name_;
const string* package_;
const DescriptorPool* pool_;
+ GoogleOnceDynamic* dependencies_once_;
+ static void DependenciesOnceInit(const FileDescriptor* to_init);
+ void InternalDependenciesOnceInit() const;
+
+ // These are arranged to minimze padding on 64-bit.
int dependency_count_;
- const FileDescriptor** dependencies_;
int public_dependency_count_;
- int* public_dependencies_;
int weak_dependency_count_;
- int* weak_dependencies_;
int message_type_count_;
- Descriptor* message_types_;
int enum_type_count_;
- EnumDescriptor* enum_types_;
int service_count_;
- ServiceDescriptor* services_;
int extension_count_;
Syntax syntax_;
bool is_placeholder_;
+
+ // Indicates the FileDescriptor is completed building. Used to verify
+ // that type accessor functions that can possibly build a dependent file
+ // aren't called during the process of building the file.
+ bool finished_building_;
+
+ mutable const FileDescriptor** dependencies_;
+ const string** dependencies_names_;
+ int* public_dependencies_;
+ int* weak_dependencies_;
+ Descriptor* message_types_;
+ EnumDescriptor* enum_types_;
+ ServiceDescriptor* services_;
FieldDescriptor* extensions_;
const FileOptions* options_;
const FileDescriptorTables* tables_;
const SourceCodeInfo* source_code_info_;
+
// IMPORTANT: If you add a new field, make sure to search for all instances
// of Allocate<FileDescriptor>() and AllocateArray<FileDescriptor>() in
// descriptor.cc and update them to initialize the field.
FileDescriptor() {}
friend class DescriptorBuilder;
+ friend class DescriptorPool;
friend class Descriptor;
friend class FieldDescriptor;
+ friend class internal::LazyDescriptor;
friend class OneofDescriptor;
friend class EnumDescriptor;
friend class EnumValueDescriptor;
@@ -1337,6 +1467,7 @@ class LIBPROTOBUF_EXPORT FileDescriptor {
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FileDescriptor);
};
+
// ===================================================================
// Used to construct descriptors.
@@ -1559,6 +1690,9 @@ class LIBPROTOBUF_EXPORT DescriptorPool {
static void InternalAddGeneratedFile(
const void* encoded_file_descriptor, int size);
+ // Disallow [enforce_utf8 = false] in .proto files.
+ void DisallowEnforceUtf8() { disallow_enforce_utf8_ = true; }
+
// For internal use only: Gets a non-const pointer to the generated pool.
// This is called at static-initialization time only, so thread-safety is
@@ -1571,6 +1705,21 @@ class LIBPROTOBUF_EXPORT DescriptorPool {
// which it did not officially declare as dependencies.
void InternalDontEnforceDependencies();
+ // For internal use only: Enables lazy building of dependencies of a file.
+ // Delay the building of dependencies of a file descriptor until absolutely
+ // necessary, like when message_type() is called on a field that is defined
+ // in that dependency's file. This will cause functional issues if a proto
+ // or one of it's dependencies has errors. Should only be enabled for the
+ // generated_pool_ (because no descriptor build errors are guaranteed by
+ // the compilation generation process), testing, or if a lack of descriptor
+ // build errors can be guaranteed for a pool.
+ void InternalSetLazilyBuildDependencies() {
+ lazily_build_dependencies_ = true;
+ // This needs to be set when lazily building dependencies, as it breaks
+ // dependency checking.
+ InternalDontEnforceDependencies();
+ }
+
// For internal use only.
void internal_set_underlay(const DescriptorPool* underlay) {
underlay_ = underlay;
@@ -1589,10 +1738,13 @@ class LIBPROTOBUF_EXPORT DescriptorPool {
private:
friend class Descriptor;
+ friend class internal::LazyDescriptor;
friend class FieldDescriptor;
friend class EnumDescriptor;
friend class ServiceDescriptor;
+ friend class MethodDescriptor;
friend class FileDescriptor;
+ friend class StreamDescriptor;
friend class DescriptorBuilder;
friend class FileDescriptorTables;
@@ -1616,6 +1768,28 @@ class LIBPROTOBUF_EXPORT DescriptorPool {
const FileDescriptor* BuildFileFromDatabase(
const FileDescriptorProto& proto) const;
+ // Helper for when lazily_build_dependencies_ is set, can look up a symbol
+ // after the file's descriptor is built, and can build the file where that
+ // symbol is defined if necessary. Will create a placeholder if the type
+ // doesn't exist in the fallback database, or the file doesn't build
+ // successfully.
+ Symbol CrossLinkOnDemandHelper(const string& name, bool expecting_enum) const;
+
+ // Create a placeholder FileDescriptor of the specified name
+ FileDescriptor* NewPlaceholderFile(const string& name) const;
+ FileDescriptor* NewPlaceholderFileWithMutexHeld(const string& name) const;
+
+ enum PlaceholderType {
+ PLACEHOLDER_MESSAGE,
+ PLACEHOLDER_ENUM,
+ PLACEHOLDER_EXTENDABLE_MESSAGE
+ };
+ // Create a placeholder Descriptor of the specified name
+ Symbol NewPlaceholder(const string& name,
+ PlaceholderType placeholder_type) const;
+ Symbol NewPlaceholderWithMutexHeld(const string& name,
+ PlaceholderType placeholder_type) const;
+
// If fallback_database_ is NULL, this is NULL. Otherwise, this is a mutex
// which must be locked while accessing tables_.
Mutex* mutex_;
@@ -1631,13 +1805,16 @@ class LIBPROTOBUF_EXPORT DescriptorPool {
google::protobuf::scoped_ptr<Tables> tables_;
bool enforce_dependencies_;
+ bool lazily_build_dependencies_;
bool allow_unknown_;
bool enforce_weak_;
+ bool disallow_enforce_utf8_;
std::set<string> unused_import_track_files_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DescriptorPool);
};
+
// inline methods ====================================================
// These macros makes this repetitive code more readable.
@@ -1693,15 +1870,12 @@ PROTOBUF_DEFINE_STRING_ACCESSOR(FieldDescriptor, camelcase_name)
PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, file, const FileDescriptor*)
PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, number, int)
PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, is_extension, bool)
-PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, type, FieldDescriptor::Type)
PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, label, FieldDescriptor::Label)
PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, containing_type, const Descriptor*)
PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, containing_oneof,
const OneofDescriptor*)
PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, index_in_oneof, int)
PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, extension_scope, const Descriptor*)
-PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, message_type, const Descriptor*)
-PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, enum_type, const EnumDescriptor*)
PROTOBUF_DEFINE_OPTIONS_ACCESSOR(FieldDescriptor, FieldOptions)
PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, has_default_value, bool)
PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, has_json_name, bool)
@@ -1712,8 +1886,6 @@ PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_uint64, uint64)
PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_float , float )
PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_double, double)
PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_bool , bool )
-PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_enum,
- const EnumValueDescriptor*)
PROTOBUF_DEFINE_STRING_ACCESSOR(FieldDescriptor, default_value_string)
PROTOBUF_DEFINE_STRING_ACCESSOR(OneofDescriptor, name)
@@ -1731,6 +1903,10 @@ PROTOBUF_DEFINE_ARRAY_ACCESSOR(EnumDescriptor, value,
const EnumValueDescriptor*)
PROTOBUF_DEFINE_OPTIONS_ACCESSOR(EnumDescriptor, EnumOptions)
PROTOBUF_DEFINE_ACCESSOR(EnumDescriptor, is_placeholder, bool)
+PROTOBUF_DEFINE_ACCESSOR(EnumDescriptor, reserved_range_count, int)
+PROTOBUF_DEFINE_ARRAY_ACCESSOR(EnumDescriptor, reserved_range,
+ const EnumDescriptor::ReservedRange*)
+PROTOBUF_DEFINE_ACCESSOR(EnumDescriptor, reserved_name_count, int)
PROTOBUF_DEFINE_STRING_ACCESSOR(EnumValueDescriptor, name)
PROTOBUF_DEFINE_STRING_ACCESSOR(EnumValueDescriptor, full_name)
@@ -1749,8 +1925,6 @@ PROTOBUF_DEFINE_OPTIONS_ACCESSOR(ServiceDescriptor, ServiceOptions)
PROTOBUF_DEFINE_STRING_ACCESSOR(MethodDescriptor, name)
PROTOBUF_DEFINE_STRING_ACCESSOR(MethodDescriptor, full_name)
PROTOBUF_DEFINE_ACCESSOR(MethodDescriptor, service, const ServiceDescriptor*)
-PROTOBUF_DEFINE_ACCESSOR(MethodDescriptor, input_type, const Descriptor*)
-PROTOBUF_DEFINE_ACCESSOR(MethodDescriptor, output_type, const Descriptor*)
PROTOBUF_DEFINE_OPTIONS_ACCESSOR(MethodDescriptor, MethodOptions)
PROTOBUF_DEFINE_ACCESSOR(MethodDescriptor, client_streaming, bool)
PROTOBUF_DEFINE_ACCESSOR(MethodDescriptor, server_streaming, bool)
@@ -1804,6 +1978,32 @@ inline const string& Descriptor::reserved_name(int index) const {
return *reserved_names_[index];
}
+inline bool EnumDescriptor::IsReservedNumber(int number) const {
+ return FindReservedRangeContainingNumber(number) != NULL;
+}
+
+inline bool EnumDescriptor::IsReservedName(const string& name) const {
+ for (int i = 0; i < reserved_name_count(); i++) {
+ if (name == reserved_name(i)) {
+ return true;
+ }
+ }
+ return false;
+}
+
+// Can't use PROTOBUF_DEFINE_ARRAY_ACCESSOR because reserved_names_ is actually
+// an array of pointers rather than the usual array of objects.
+inline const string& EnumDescriptor::reserved_name(int index) const {
+ return *reserved_names_[index];
+}
+
+inline FieldDescriptor::Type FieldDescriptor::type() const {
+ if (type_once_) {
+ type_once_->Init(&FieldDescriptor::TypeOnceInit, this);
+ }
+ return type_;
+}
+
inline bool FieldDescriptor::is_required() const {
return label() == LABEL_REQUIRED;
}
@@ -1820,11 +2020,15 @@ inline bool FieldDescriptor::is_packable() const {
return is_repeated() && IsTypePackable(type());
}
+inline bool FieldDescriptor::is_map() const {
+ return type() == TYPE_MESSAGE && is_map_message_type();
+}
+
// To save space, index() is computed by looking at the descriptor's position
// in the parent's array of children.
inline int FieldDescriptor::index() const {
if (!is_extension_) {
- return static_cast<int>(this - containing_type_->fields_);
+ return static_cast<int>(this - containing_type()->fields_);
} else if (extension_scope_ != NULL) {
return static_cast<int>(this - extension_scope_->extensions_);
} else {
@@ -1840,6 +2044,10 @@ inline int Descriptor::index() const {
}
}
+inline const FileDescriptor* OneofDescriptor::file() const {
+ return containing_type()->file();
+}
+
inline int OneofDescriptor::index() const {
return static_cast<int>(this - containing_type_->oneof_decls_);
}
@@ -1852,6 +2060,10 @@ inline int EnumDescriptor::index() const {
}
}
+inline const FileDescriptor* EnumValueDescriptor::file() const {
+ return type()->file();
+}
+
inline int EnumValueDescriptor::index() const {
return static_cast<int>(this - type_->values_);
}
@@ -1860,20 +2072,24 @@ inline int ServiceDescriptor::index() const {
return static_cast<int>(this - file_->services_);
}
+inline const FileDescriptor* MethodDescriptor::file() const {
+ return service()->file();
+}
+
inline int MethodDescriptor::index() const {
return static_cast<int>(this - service_->methods_);
}
inline const char* FieldDescriptor::type_name() const {
- return kTypeToName[type_];
+ return kTypeToName[type()];
}
inline FieldDescriptor::CppType FieldDescriptor::cpp_type() const {
- return kTypeToCppTypeMap[type_];
+ return kTypeToCppTypeMap[type()];
}
inline const char* FieldDescriptor::cpp_type_name() const {
- return kCppTypeToName[kTypeToCppTypeMap[type_]];
+ return kCppTypeToName[kTypeToCppTypeMap[type()]];
}
inline FieldDescriptor::CppType FieldDescriptor::TypeToCppType(Type type) {
@@ -1895,18 +2111,14 @@ inline bool FieldDescriptor::IsTypePackable(Type field_type) {
field_type != FieldDescriptor::TYPE_BYTES);
}
-inline const FileDescriptor* FileDescriptor::dependency(int index) const {
- return dependencies_[index];
-}
-
inline const FileDescriptor* FileDescriptor::public_dependency(
int index) const {
- return dependencies_[public_dependencies_[index]];
+ return dependency(public_dependencies_[index]);
}
inline const FileDescriptor* FileDescriptor::weak_dependency(
int index) const {
- return dependencies_[weak_dependencies_[index]];
+ return dependency(weak_dependencies_[index]);
}
inline FileDescriptor::Syntax FileDescriptor::syntax() const {
diff --git a/src/google/protobuf/descriptor.pb.cc b/src/google/protobuf/descriptor.pb.cc
index 7c72a5a1..ab1b4992 100644
--- a/src/google/protobuf/descriptor.pb.cc
+++ b/src/google/protobuf/descriptor.pb.cc
@@ -1,7 +1,6 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/descriptor.proto
-#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include <google/protobuf/descriptor.pb.h>
#include <algorithm>
@@ -15,465 +14,1202 @@
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
+// This is a temporary google only hack
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+#include "third_party/protobuf/version.h"
+#endif
// @@protoc_insertion_point(includes)
-
namespace google {
namespace protobuf {
-class FileDescriptorSetDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<FileDescriptorSet> {};
-FileDescriptorSetDefaultTypeInternal _FileDescriptorSet_default_instance_;
-class FileDescriptorProtoDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<FileDescriptorProto> {};
-FileDescriptorProtoDefaultTypeInternal _FileDescriptorProto_default_instance_;
-class DescriptorProto_ExtensionRangeDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<DescriptorProto_ExtensionRange> {};
-DescriptorProto_ExtensionRangeDefaultTypeInternal _DescriptorProto_ExtensionRange_default_instance_;
-class DescriptorProto_ReservedRangeDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<DescriptorProto_ReservedRange> {};
-DescriptorProto_ReservedRangeDefaultTypeInternal _DescriptorProto_ReservedRange_default_instance_;
-class DescriptorProtoDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<DescriptorProto> {};
-DescriptorProtoDefaultTypeInternal _DescriptorProto_default_instance_;
-class FieldDescriptorProtoDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<FieldDescriptorProto> {};
-FieldDescriptorProtoDefaultTypeInternal _FieldDescriptorProto_default_instance_;
-class OneofDescriptorProtoDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<OneofDescriptorProto> {};
-OneofDescriptorProtoDefaultTypeInternal _OneofDescriptorProto_default_instance_;
-class EnumDescriptorProtoDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<EnumDescriptorProto> {};
-EnumDescriptorProtoDefaultTypeInternal _EnumDescriptorProto_default_instance_;
-class EnumValueDescriptorProtoDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<EnumValueDescriptorProto> {};
-EnumValueDescriptorProtoDefaultTypeInternal _EnumValueDescriptorProto_default_instance_;
-class ServiceDescriptorProtoDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<ServiceDescriptorProto> {};
-ServiceDescriptorProtoDefaultTypeInternal _ServiceDescriptorProto_default_instance_;
-class MethodDescriptorProtoDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<MethodDescriptorProto> {};
-MethodDescriptorProtoDefaultTypeInternal _MethodDescriptorProto_default_instance_;
-class FileOptionsDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<FileOptions> {};
-FileOptionsDefaultTypeInternal _FileOptions_default_instance_;
-class MessageOptionsDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<MessageOptions> {};
-MessageOptionsDefaultTypeInternal _MessageOptions_default_instance_;
-class FieldOptionsDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<FieldOptions> {};
-FieldOptionsDefaultTypeInternal _FieldOptions_default_instance_;
-class OneofOptionsDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<OneofOptions> {};
-OneofOptionsDefaultTypeInternal _OneofOptions_default_instance_;
-class EnumOptionsDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<EnumOptions> {};
-EnumOptionsDefaultTypeInternal _EnumOptions_default_instance_;
-class EnumValueOptionsDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<EnumValueOptions> {};
-EnumValueOptionsDefaultTypeInternal _EnumValueOptions_default_instance_;
-class ServiceOptionsDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<ServiceOptions> {};
-ServiceOptionsDefaultTypeInternal _ServiceOptions_default_instance_;
-class MethodOptionsDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<MethodOptions> {};
-MethodOptionsDefaultTypeInternal _MethodOptions_default_instance_;
-class UninterpretedOption_NamePartDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<UninterpretedOption_NamePart> {};
-UninterpretedOption_NamePartDefaultTypeInternal _UninterpretedOption_NamePart_default_instance_;
-class UninterpretedOptionDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<UninterpretedOption> {};
-UninterpretedOptionDefaultTypeInternal _UninterpretedOption_default_instance_;
-class SourceCodeInfo_LocationDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<SourceCodeInfo_Location> {};
-SourceCodeInfo_LocationDefaultTypeInternal _SourceCodeInfo_Location_default_instance_;
-class SourceCodeInfoDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<SourceCodeInfo> {};
-SourceCodeInfoDefaultTypeInternal _SourceCodeInfo_default_instance_;
-class GeneratedCodeInfo_AnnotationDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<GeneratedCodeInfo_Annotation> {};
-GeneratedCodeInfo_AnnotationDefaultTypeInternal _GeneratedCodeInfo_Annotation_default_instance_;
-class GeneratedCodeInfoDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<GeneratedCodeInfo> {};
-GeneratedCodeInfoDefaultTypeInternal _GeneratedCodeInfo_default_instance_;
-
-namespace {
-
-::google::protobuf::Metadata file_level_metadata[25];
+class FileDescriptorSetDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<FileDescriptorSet>
+ _instance;
+} _FileDescriptorSet_default_instance_;
+class FileDescriptorProtoDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<FileDescriptorProto>
+ _instance;
+} _FileDescriptorProto_default_instance_;
+class DescriptorProto_ExtensionRangeDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<DescriptorProto_ExtensionRange>
+ _instance;
+} _DescriptorProto_ExtensionRange_default_instance_;
+class DescriptorProto_ReservedRangeDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<DescriptorProto_ReservedRange>
+ _instance;
+} _DescriptorProto_ReservedRange_default_instance_;
+class DescriptorProtoDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<DescriptorProto>
+ _instance;
+} _DescriptorProto_default_instance_;
+class ExtensionRangeOptionsDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<ExtensionRangeOptions>
+ _instance;
+} _ExtensionRangeOptions_default_instance_;
+class FieldDescriptorProtoDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<FieldDescriptorProto>
+ _instance;
+} _FieldDescriptorProto_default_instance_;
+class OneofDescriptorProtoDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<OneofDescriptorProto>
+ _instance;
+} _OneofDescriptorProto_default_instance_;
+class EnumDescriptorProto_EnumReservedRangeDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<EnumDescriptorProto_EnumReservedRange>
+ _instance;
+} _EnumDescriptorProto_EnumReservedRange_default_instance_;
+class EnumDescriptorProtoDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<EnumDescriptorProto>
+ _instance;
+} _EnumDescriptorProto_default_instance_;
+class EnumValueDescriptorProtoDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<EnumValueDescriptorProto>
+ _instance;
+} _EnumValueDescriptorProto_default_instance_;
+class ServiceDescriptorProtoDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<ServiceDescriptorProto>
+ _instance;
+} _ServiceDescriptorProto_default_instance_;
+class MethodDescriptorProtoDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<MethodDescriptorProto>
+ _instance;
+} _MethodDescriptorProto_default_instance_;
+class FileOptionsDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<FileOptions>
+ _instance;
+} _FileOptions_default_instance_;
+class MessageOptionsDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<MessageOptions>
+ _instance;
+} _MessageOptions_default_instance_;
+class FieldOptionsDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<FieldOptions>
+ _instance;
+} _FieldOptions_default_instance_;
+class OneofOptionsDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<OneofOptions>
+ _instance;
+} _OneofOptions_default_instance_;
+class EnumOptionsDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<EnumOptions>
+ _instance;
+} _EnumOptions_default_instance_;
+class EnumValueOptionsDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<EnumValueOptions>
+ _instance;
+} _EnumValueOptions_default_instance_;
+class ServiceOptionsDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<ServiceOptions>
+ _instance;
+} _ServiceOptions_default_instance_;
+class MethodOptionsDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<MethodOptions>
+ _instance;
+} _MethodOptions_default_instance_;
+class UninterpretedOption_NamePartDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<UninterpretedOption_NamePart>
+ _instance;
+} _UninterpretedOption_NamePart_default_instance_;
+class UninterpretedOptionDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<UninterpretedOption>
+ _instance;
+} _UninterpretedOption_default_instance_;
+class SourceCodeInfo_LocationDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<SourceCodeInfo_Location>
+ _instance;
+} _SourceCodeInfo_Location_default_instance_;
+class SourceCodeInfoDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<SourceCodeInfo>
+ _instance;
+} _SourceCodeInfo_default_instance_;
+class GeneratedCodeInfo_AnnotationDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<GeneratedCodeInfo_Annotation>
+ _instance;
+} _GeneratedCodeInfo_Annotation_default_instance_;
+class GeneratedCodeInfoDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<GeneratedCodeInfo>
+ _instance;
+} _GeneratedCodeInfo_default_instance_;
+} // namespace protobuf
+} // namespace google
+namespace protobuf_google_2fprotobuf_2fdescriptor_2eproto {
+void InitDefaultsFileDescriptorSetImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorProto();
+ {
+ void* ptr = &::google::protobuf::_FileDescriptorSet_default_instance_;
+ new (ptr) ::google::protobuf::FileDescriptorSet();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::FileDescriptorSet::InitAsDefaultInstance();
+}
+
+void InitDefaultsFileDescriptorSet() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsFileDescriptorSetImpl);
+}
+
+void InitDefaultsFileDescriptorProtoImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto();
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto();
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceDescriptorProto();
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldDescriptorProto();
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileOptions();
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfo();
+ {
+ void* ptr = &::google::protobuf::_FileDescriptorProto_default_instance_;
+ new (ptr) ::google::protobuf::FileDescriptorProto();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::FileDescriptorProto::InitAsDefaultInstance();
+}
+
+void InitDefaultsFileDescriptorProto() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsFileDescriptorProtoImpl);
+}
+
+void InitDefaultsDescriptorProto_ExtensionRangeImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsExtensionRangeOptions();
+ {
+ void* ptr = &::google::protobuf::_DescriptorProto_ExtensionRange_default_instance_;
+ new (ptr) ::google::protobuf::DescriptorProto_ExtensionRange();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::DescriptorProto_ExtensionRange::InitAsDefaultInstance();
+}
+
+void InitDefaultsDescriptorProto_ExtensionRange() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsDescriptorProto_ExtensionRangeImpl);
+}
+
+void InitDefaultsDescriptorProto_ReservedRangeImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ {
+ void* ptr = &::google::protobuf::_DescriptorProto_ReservedRange_default_instance_;
+ new (ptr) ::google::protobuf::DescriptorProto_ReservedRange();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::DescriptorProto_ReservedRange::InitAsDefaultInstance();
+}
+
+void InitDefaultsDescriptorProto_ReservedRange() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsDescriptorProto_ReservedRangeImpl);
+}
+
+void InitDefaultsDescriptorProtoImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldDescriptorProto();
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto();
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ExtensionRange();
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofDescriptorProto();
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMessageOptions();
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ReservedRange();
+ {
+ void* ptr = &::google::protobuf::_DescriptorProto_default_instance_;
+ new (ptr) ::google::protobuf::DescriptorProto();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::DescriptorProto::InitAsDefaultInstance();
+}
+
+void InitDefaultsDescriptorProto() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsDescriptorProtoImpl);
+}
+
+void InitDefaultsExtensionRangeOptionsImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption();
+ {
+ void* ptr = &::google::protobuf::_ExtensionRangeOptions_default_instance_;
+ new (ptr) ::google::protobuf::ExtensionRangeOptions();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::ExtensionRangeOptions::InitAsDefaultInstance();
+}
+
+void InitDefaultsExtensionRangeOptions() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsExtensionRangeOptionsImpl);
+}
+
+void InitDefaultsFieldDescriptorProtoImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldOptions();
+ {
+ void* ptr = &::google::protobuf::_FieldDescriptorProto_default_instance_;
+ new (ptr) ::google::protobuf::FieldDescriptorProto();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::FieldDescriptorProto::InitAsDefaultInstance();
+}
+
+void InitDefaultsFieldDescriptorProto() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsFieldDescriptorProtoImpl);
+}
+
+void InitDefaultsOneofDescriptorProtoImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofOptions();
+ {
+ void* ptr = &::google::protobuf::_OneofDescriptorProto_default_instance_;
+ new (ptr) ::google::protobuf::OneofDescriptorProto();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::OneofDescriptorProto::InitAsDefaultInstance();
+}
+
+void InitDefaultsOneofDescriptorProto() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsOneofDescriptorProtoImpl);
+}
+
+void InitDefaultsEnumDescriptorProto_EnumReservedRangeImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ {
+ void* ptr = &::google::protobuf::_EnumDescriptorProto_EnumReservedRange_default_instance_;
+ new (ptr) ::google::protobuf::EnumDescriptorProto_EnumReservedRange();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::EnumDescriptorProto_EnumReservedRange::InitAsDefaultInstance();
+}
+
+void InitDefaultsEnumDescriptorProto_EnumReservedRange() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsEnumDescriptorProto_EnumReservedRangeImpl);
+}
+
+void InitDefaultsEnumDescriptorProtoImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueDescriptorProto();
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumOptions();
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto_EnumReservedRange();
+ {
+ void* ptr = &::google::protobuf::_EnumDescriptorProto_default_instance_;
+ new (ptr) ::google::protobuf::EnumDescriptorProto();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::EnumDescriptorProto::InitAsDefaultInstance();
+}
+
+void InitDefaultsEnumDescriptorProto() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsEnumDescriptorProtoImpl);
+}
+
+void InitDefaultsEnumValueDescriptorProtoImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueOptions();
+ {
+ void* ptr = &::google::protobuf::_EnumValueDescriptorProto_default_instance_;
+ new (ptr) ::google::protobuf::EnumValueDescriptorProto();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::EnumValueDescriptorProto::InitAsDefaultInstance();
+}
+
+void InitDefaultsEnumValueDescriptorProto() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsEnumValueDescriptorProtoImpl);
+}
+
+void InitDefaultsServiceDescriptorProtoImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodDescriptorProto();
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceOptions();
+ {
+ void* ptr = &::google::protobuf::_ServiceDescriptorProto_default_instance_;
+ new (ptr) ::google::protobuf::ServiceDescriptorProto();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::ServiceDescriptorProto::InitAsDefaultInstance();
+}
+
+void InitDefaultsServiceDescriptorProto() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsServiceDescriptorProtoImpl);
+}
+
+void InitDefaultsMethodDescriptorProtoImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodOptions();
+ {
+ void* ptr = &::google::protobuf::_MethodDescriptorProto_default_instance_;
+ new (ptr) ::google::protobuf::MethodDescriptorProto();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::MethodDescriptorProto::InitAsDefaultInstance();
+}
+
+void InitDefaultsMethodDescriptorProto() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsMethodDescriptorProtoImpl);
+}
+
+void InitDefaultsFileOptionsImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption();
+ {
+ void* ptr = &::google::protobuf::_FileOptions_default_instance_;
+ new (ptr) ::google::protobuf::FileOptions();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::FileOptions::InitAsDefaultInstance();
+}
+
+void InitDefaultsFileOptions() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsFileOptionsImpl);
+}
+
+void InitDefaultsMessageOptionsImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption();
+ {
+ void* ptr = &::google::protobuf::_MessageOptions_default_instance_;
+ new (ptr) ::google::protobuf::MessageOptions();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::MessageOptions::InitAsDefaultInstance();
+}
+
+void InitDefaultsMessageOptions() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsMessageOptionsImpl);
+}
+
+void InitDefaultsFieldOptionsImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption();
+ {
+ void* ptr = &::google::protobuf::_FieldOptions_default_instance_;
+ new (ptr) ::google::protobuf::FieldOptions();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::FieldOptions::InitAsDefaultInstance();
+}
+
+void InitDefaultsFieldOptions() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsFieldOptionsImpl);
+}
+
+void InitDefaultsOneofOptionsImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption();
+ {
+ void* ptr = &::google::protobuf::_OneofOptions_default_instance_;
+ new (ptr) ::google::protobuf::OneofOptions();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::OneofOptions::InitAsDefaultInstance();
+}
+
+void InitDefaultsOneofOptions() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsOneofOptionsImpl);
+}
+
+void InitDefaultsEnumOptionsImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption();
+ {
+ void* ptr = &::google::protobuf::_EnumOptions_default_instance_;
+ new (ptr) ::google::protobuf::EnumOptions();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::EnumOptions::InitAsDefaultInstance();
+}
+
+void InitDefaultsEnumOptions() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsEnumOptionsImpl);
+}
+
+void InitDefaultsEnumValueOptionsImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption();
+ {
+ void* ptr = &::google::protobuf::_EnumValueOptions_default_instance_;
+ new (ptr) ::google::protobuf::EnumValueOptions();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::EnumValueOptions::InitAsDefaultInstance();
+}
+
+void InitDefaultsEnumValueOptions() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsEnumValueOptionsImpl);
+}
+
+void InitDefaultsServiceOptionsImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption();
+ {
+ void* ptr = &::google::protobuf::_ServiceOptions_default_instance_;
+ new (ptr) ::google::protobuf::ServiceOptions();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::ServiceOptions::InitAsDefaultInstance();
+}
+
+void InitDefaultsServiceOptions() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsServiceOptionsImpl);
+}
+
+void InitDefaultsMethodOptionsImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption();
+ {
+ void* ptr = &::google::protobuf::_MethodOptions_default_instance_;
+ new (ptr) ::google::protobuf::MethodOptions();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::MethodOptions::InitAsDefaultInstance();
+}
+
+void InitDefaultsMethodOptions() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsMethodOptionsImpl);
+}
+
+void InitDefaultsUninterpretedOption_NamePartImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ {
+ void* ptr = &::google::protobuf::_UninterpretedOption_NamePart_default_instance_;
+ new (ptr) ::google::protobuf::UninterpretedOption_NamePart();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::UninterpretedOption_NamePart::InitAsDefaultInstance();
+}
+
+void InitDefaultsUninterpretedOption_NamePart() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsUninterpretedOption_NamePartImpl);
+}
+
+void InitDefaultsUninterpretedOptionImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption_NamePart();
+ {
+ void* ptr = &::google::protobuf::_UninterpretedOption_default_instance_;
+ new (ptr) ::google::protobuf::UninterpretedOption();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::UninterpretedOption::InitAsDefaultInstance();
+}
+
+void InitDefaultsUninterpretedOption() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsUninterpretedOptionImpl);
+}
+
+void InitDefaultsSourceCodeInfo_LocationImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ {
+ void* ptr = &::google::protobuf::_SourceCodeInfo_Location_default_instance_;
+ new (ptr) ::google::protobuf::SourceCodeInfo_Location();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::SourceCodeInfo_Location::InitAsDefaultInstance();
+}
+
+void InitDefaultsSourceCodeInfo_Location() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsSourceCodeInfo_LocationImpl);
+}
+
+void InitDefaultsSourceCodeInfoImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfo_Location();
+ {
+ void* ptr = &::google::protobuf::_SourceCodeInfo_default_instance_;
+ new (ptr) ::google::protobuf::SourceCodeInfo();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::SourceCodeInfo::InitAsDefaultInstance();
+}
+
+void InitDefaultsSourceCodeInfo() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsSourceCodeInfoImpl);
+}
+
+void InitDefaultsGeneratedCodeInfo_AnnotationImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ {
+ void* ptr = &::google::protobuf::_GeneratedCodeInfo_Annotation_default_instance_;
+ new (ptr) ::google::protobuf::GeneratedCodeInfo_Annotation();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::GeneratedCodeInfo_Annotation::InitAsDefaultInstance();
+}
+
+void InitDefaultsGeneratedCodeInfo_Annotation() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsGeneratedCodeInfo_AnnotationImpl);
+}
+
+void InitDefaultsGeneratedCodeInfoImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsGeneratedCodeInfo_Annotation();
+ {
+ void* ptr = &::google::protobuf::_GeneratedCodeInfo_default_instance_;
+ new (ptr) ::google::protobuf::GeneratedCodeInfo();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::GeneratedCodeInfo::InitAsDefaultInstance();
+}
+
+void InitDefaultsGeneratedCodeInfo() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsGeneratedCodeInfoImpl);
+}
+
+::google::protobuf::Metadata file_level_metadata[27];
const ::google::protobuf::EnumDescriptor* file_level_enum_descriptors[6];
-} // namespace
-
-
-const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fdescriptor_2eproto() GOOGLE_ATTRIBUTE_COLD;
-const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fdescriptor_2eproto() {
- static const ::google::protobuf::uint32 offsets[] = {
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorSet, _has_bits_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorSet, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorSet, file_),
- 0,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorProto, _has_bits_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorProto, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorProto, name_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorProto, package_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorProto, dependency_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorProto, public_dependency_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorProto, weak_dependency_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorProto, message_type_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorProto, enum_type_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorProto, service_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorProto, extension_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorProto, options_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorProto, source_code_info_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorProto, syntax_),
- 0,
- 1,
- 5,
- 6,
- 7,
- 8,
- 9,
- 10,
- 11,
- 3,
- 4,
- 2,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto_ExtensionRange, _has_bits_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto_ExtensionRange, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto_ExtensionRange, start_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto_ExtensionRange, end_),
- 0,
- 1,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto_ReservedRange, _has_bits_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto_ReservedRange, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto_ReservedRange, start_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto_ReservedRange, end_),
- 0,
- 1,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto, _has_bits_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto, name_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto, field_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto, extension_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto, nested_type_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto, enum_type_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto, extension_range_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto, oneof_decl_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto, options_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto, reserved_range_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto, reserved_name_),
- 0,
- 2,
- 3,
- 4,
- 5,
- 6,
- 7,
- 1,
- 8,
- 9,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldDescriptorProto, _has_bits_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldDescriptorProto, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldDescriptorProto, name_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldDescriptorProto, number_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldDescriptorProto, label_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldDescriptorProto, type_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldDescriptorProto, type_name_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldDescriptorProto, extendee_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldDescriptorProto, default_value_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldDescriptorProto, oneof_index_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldDescriptorProto, json_name_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldDescriptorProto, options_),
- 0,
- 6,
- 8,
- 9,
- 1,
- 2,
- 3,
- 7,
- 4,
- 5,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(OneofDescriptorProto, _has_bits_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(OneofDescriptorProto, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(OneofDescriptorProto, name_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(OneofDescriptorProto, options_),
- 0,
- 1,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumDescriptorProto, _has_bits_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumDescriptorProto, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumDescriptorProto, name_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumDescriptorProto, value_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumDescriptorProto, options_),
- 0,
- 2,
- 1,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumValueDescriptorProto, _has_bits_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumValueDescriptorProto, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumValueDescriptorProto, name_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumValueDescriptorProto, number_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumValueDescriptorProto, options_),
- 0,
- 2,
- 1,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServiceDescriptorProto, _has_bits_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServiceDescriptorProto, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServiceDescriptorProto, name_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServiceDescriptorProto, method_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServiceDescriptorProto, options_),
- 0,
- 2,
- 1,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MethodDescriptorProto, _has_bits_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MethodDescriptorProto, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MethodDescriptorProto, name_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MethodDescriptorProto, input_type_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MethodDescriptorProto, output_type_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MethodDescriptorProto, options_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MethodDescriptorProto, client_streaming_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MethodDescriptorProto, server_streaming_),
- 0,
- 1,
- 2,
- 3,
- 4,
- 5,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileOptions, _has_bits_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileOptions, _internal_metadata_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileOptions, _extensions_),
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileOptions, java_package_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileOptions, java_outer_classname_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileOptions, java_multiple_files_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileOptions, java_generate_equals_and_hash_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileOptions, java_string_check_utf8_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileOptions, optimize_for_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileOptions, go_package_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileOptions, cc_generic_services_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileOptions, java_generic_services_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileOptions, py_generic_services_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileOptions, deprecated_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileOptions, cc_enable_arenas_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileOptions, objc_class_prefix_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileOptions, csharp_namespace_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileOptions, swift_prefix_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileOptions, uninterpreted_option_),
- 0,
- 1,
- 6,
- 7,
- 8,
- 14,
- 2,
- 9,
- 10,
- 11,
- 12,
- 13,
- 3,
- 4,
- 5,
- 15,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MessageOptions, _has_bits_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MessageOptions, _internal_metadata_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MessageOptions, _extensions_),
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MessageOptions, message_set_wire_format_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MessageOptions, no_standard_descriptor_accessor_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MessageOptions, deprecated_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MessageOptions, map_entry_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MessageOptions, uninterpreted_option_),
- 0,
- 1,
- 2,
- 3,
- 4,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldOptions, _has_bits_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldOptions, _internal_metadata_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldOptions, _extensions_),
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldOptions, ctype_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldOptions, packed_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldOptions, jstype_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldOptions, lazy_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldOptions, deprecated_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldOptions, weak_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldOptions, uninterpreted_option_),
- 0,
- 2,
- 1,
- 3,
- 4,
- 5,
- 6,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(OneofOptions, _has_bits_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(OneofOptions, _internal_metadata_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(OneofOptions, _extensions_),
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(OneofOptions, uninterpreted_option_),
- 0,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumOptions, _has_bits_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumOptions, _internal_metadata_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumOptions, _extensions_),
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumOptions, allow_alias_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumOptions, deprecated_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumOptions, uninterpreted_option_),
- 0,
- 1,
- 2,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumValueOptions, _has_bits_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumValueOptions, _internal_metadata_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumValueOptions, _extensions_),
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumValueOptions, deprecated_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumValueOptions, uninterpreted_option_),
- 0,
- 1,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServiceOptions, _has_bits_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServiceOptions, _internal_metadata_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServiceOptions, _extensions_),
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServiceOptions, deprecated_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServiceOptions, uninterpreted_option_),
- 0,
- 1,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MethodOptions, _has_bits_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MethodOptions, _internal_metadata_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MethodOptions, _extensions_),
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MethodOptions, deprecated_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MethodOptions, idempotency_level_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MethodOptions, uninterpreted_option_),
- 0,
- 1,
- 2,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UninterpretedOption_NamePart, _has_bits_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UninterpretedOption_NamePart, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UninterpretedOption_NamePart, name_part_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UninterpretedOption_NamePart, is_extension_),
- 0,
- 1,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UninterpretedOption, _has_bits_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UninterpretedOption, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UninterpretedOption, name_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UninterpretedOption, identifier_value_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UninterpretedOption, positive_int_value_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UninterpretedOption, negative_int_value_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UninterpretedOption, double_value_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UninterpretedOption, string_value_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UninterpretedOption, aggregate_value_),
- 6,
- 0,
- 3,
- 4,
- 5,
- 1,
- 2,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SourceCodeInfo_Location, _has_bits_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SourceCodeInfo_Location, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SourceCodeInfo_Location, path_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SourceCodeInfo_Location, span_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SourceCodeInfo_Location, leading_comments_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SourceCodeInfo_Location, trailing_comments_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SourceCodeInfo_Location, leading_detached_comments_),
- 2,
- 3,
- 0,
- 1,
- 4,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SourceCodeInfo, _has_bits_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SourceCodeInfo, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SourceCodeInfo, location_),
- 0,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(GeneratedCodeInfo_Annotation, _has_bits_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(GeneratedCodeInfo_Annotation, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(GeneratedCodeInfo_Annotation, path_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(GeneratedCodeInfo_Annotation, source_file_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(GeneratedCodeInfo_Annotation, begin_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(GeneratedCodeInfo_Annotation, end_),
- 3,
- 0,
- 1,
- 2,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(GeneratedCodeInfo, _has_bits_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(GeneratedCodeInfo, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(GeneratedCodeInfo, annotation_),
- 0,
- };
- return offsets;
-}
-
-static const ::google::protobuf::internal::MigrationSchema schemas[] = {
- { 0, 5, sizeof(FileDescriptorSet)},
- { 6, 22, sizeof(FileDescriptorProto)},
- { 34, 40, sizeof(DescriptorProto_ExtensionRange)},
- { 42, 48, sizeof(DescriptorProto_ReservedRange)},
- { 50, 64, sizeof(DescriptorProto)},
- { 74, 88, sizeof(FieldDescriptorProto)},
- { 98, 104, sizeof(OneofDescriptorProto)},
- { 106, 113, sizeof(EnumDescriptorProto)},
- { 116, 123, sizeof(EnumValueDescriptorProto)},
- { 126, 133, sizeof(ServiceDescriptorProto)},
- { 136, 146, sizeof(MethodDescriptorProto)},
- { 152, 172, sizeof(FileOptions)},
- { 188, 197, sizeof(MessageOptions)},
- { 202, 213, sizeof(FieldOptions)},
- { 220, 225, sizeof(OneofOptions)},
- { 226, 233, sizeof(EnumOptions)},
- { 236, 242, sizeof(EnumValueOptions)},
- { 244, 250, sizeof(ServiceOptions)},
- { 252, 259, sizeof(MethodOptions)},
- { 262, 268, sizeof(UninterpretedOption_NamePart)},
- { 270, 281, sizeof(UninterpretedOption)},
- { 288, 297, sizeof(SourceCodeInfo_Location)},
- { 302, 307, sizeof(SourceCodeInfo)},
- { 308, 316, sizeof(GeneratedCodeInfo_Annotation)},
- { 320, 325, sizeof(GeneratedCodeInfo)},
+const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorSet, _has_bits_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorSet, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorSet, file_),
+ ~0u,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, _has_bits_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, name_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, package_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, dependency_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, public_dependency_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, weak_dependency_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, message_type_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, enum_type_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, service_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, extension_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, options_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, source_code_info_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, syntax_),
+ 0,
+ 1,
+ ~0u,
+ ~0u,
+ ~0u,
+ ~0u,
+ ~0u,
+ ~0u,
+ ~0u,
+ 3,
+ 4,
+ 2,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto_ExtensionRange, _has_bits_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto_ExtensionRange, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto_ExtensionRange, start_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto_ExtensionRange, end_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto_ExtensionRange, options_),
+ 1,
+ 2,
+ 0,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto_ReservedRange, _has_bits_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto_ReservedRange, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto_ReservedRange, start_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto_ReservedRange, end_),
+ 0,
+ 1,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto, _has_bits_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto, name_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto, field_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto, extension_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto, nested_type_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto, enum_type_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto, extension_range_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto, oneof_decl_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto, options_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto, reserved_range_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DescriptorProto, reserved_name_),
+ 0,
+ ~0u,
+ ~0u,
+ ~0u,
+ ~0u,
+ ~0u,
+ ~0u,
+ 1,
+ ~0u,
+ ~0u,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ExtensionRangeOptions, _has_bits_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ExtensionRangeOptions, _internal_metadata_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ExtensionRangeOptions, _extensions_),
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ExtensionRangeOptions, uninterpreted_option_),
+ ~0u,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, _has_bits_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, name_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, number_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, label_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, type_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, type_name_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, extendee_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, default_value_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, oneof_index_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, json_name_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, options_),
+ 0,
+ 6,
+ 8,
+ 9,
+ 2,
+ 1,
+ 3,
+ 7,
+ 4,
+ 5,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::OneofDescriptorProto, _has_bits_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::OneofDescriptorProto, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::OneofDescriptorProto, name_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::OneofDescriptorProto, options_),
+ 0,
+ 1,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto_EnumReservedRange, _has_bits_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto_EnumReservedRange, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto_EnumReservedRange, start_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto_EnumReservedRange, end_),
+ 0,
+ 1,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto, _has_bits_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto, name_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto, value_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto, options_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto, reserved_range_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto, reserved_name_),
+ 0,
+ ~0u,
+ 1,
+ ~0u,
+ ~0u,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumValueDescriptorProto, _has_bits_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumValueDescriptorProto, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumValueDescriptorProto, name_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumValueDescriptorProto, number_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumValueDescriptorProto, options_),
+ 0,
+ 2,
+ 1,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ServiceDescriptorProto, _has_bits_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ServiceDescriptorProto, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ServiceDescriptorProto, name_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ServiceDescriptorProto, method_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ServiceDescriptorProto, options_),
+ 0,
+ ~0u,
+ 1,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodDescriptorProto, _has_bits_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodDescriptorProto, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodDescriptorProto, name_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodDescriptorProto, input_type_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodDescriptorProto, output_type_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodDescriptorProto, options_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodDescriptorProto, client_streaming_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodDescriptorProto, server_streaming_),
+ 0,
+ 1,
+ 2,
+ 3,
+ 4,
+ 5,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, _has_bits_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, _internal_metadata_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, _extensions_),
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, java_package_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, java_outer_classname_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, java_multiple_files_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, java_generate_equals_and_hash_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, java_string_check_utf8_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, optimize_for_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, go_package_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, cc_generic_services_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, java_generic_services_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, py_generic_services_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, php_generic_services_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, deprecated_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, cc_enable_arenas_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, objc_class_prefix_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, csharp_namespace_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, swift_prefix_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, php_class_prefix_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, php_namespace_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, uninterpreted_option_),
+ 0,
+ 1,
+ 9,
+ 10,
+ 11,
+ 17,
+ 2,
+ 12,
+ 13,
+ 14,
+ 15,
+ 16,
+ 8,
+ 3,
+ 4,
+ 5,
+ 6,
+ 7,
+ ~0u,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MessageOptions, _has_bits_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MessageOptions, _internal_metadata_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MessageOptions, _extensions_),
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MessageOptions, message_set_wire_format_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MessageOptions, no_standard_descriptor_accessor_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MessageOptions, deprecated_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MessageOptions, map_entry_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MessageOptions, uninterpreted_option_),
+ 0,
+ 1,
+ 2,
+ 3,
+ ~0u,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldOptions, _has_bits_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldOptions, _internal_metadata_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldOptions, _extensions_),
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldOptions, ctype_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldOptions, packed_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldOptions, jstype_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldOptions, lazy_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldOptions, deprecated_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldOptions, weak_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldOptions, uninterpreted_option_),
+ 0,
+ 1,
+ 5,
+ 2,
+ 3,
+ 4,
+ ~0u,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::OneofOptions, _has_bits_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::OneofOptions, _internal_metadata_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::OneofOptions, _extensions_),
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::OneofOptions, uninterpreted_option_),
+ ~0u,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumOptions, _has_bits_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumOptions, _internal_metadata_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumOptions, _extensions_),
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumOptions, allow_alias_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumOptions, deprecated_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumOptions, uninterpreted_option_),
+ 0,
+ 1,
+ ~0u,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumValueOptions, _has_bits_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumValueOptions, _internal_metadata_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumValueOptions, _extensions_),
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumValueOptions, deprecated_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumValueOptions, uninterpreted_option_),
+ 0,
+ ~0u,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ServiceOptions, _has_bits_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ServiceOptions, _internal_metadata_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ServiceOptions, _extensions_),
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ServiceOptions, deprecated_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ServiceOptions, uninterpreted_option_),
+ 0,
+ ~0u,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodOptions, _has_bits_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodOptions, _internal_metadata_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodOptions, _extensions_),
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodOptions, deprecated_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodOptions, idempotency_level_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::MethodOptions, uninterpreted_option_),
+ 0,
+ 1,
+ ~0u,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UninterpretedOption_NamePart, _has_bits_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UninterpretedOption_NamePart, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UninterpretedOption_NamePart, name_part_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UninterpretedOption_NamePart, is_extension_),
+ 0,
+ 1,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UninterpretedOption, _has_bits_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UninterpretedOption, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UninterpretedOption, name_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UninterpretedOption, identifier_value_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UninterpretedOption, positive_int_value_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UninterpretedOption, negative_int_value_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UninterpretedOption, double_value_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UninterpretedOption, string_value_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UninterpretedOption, aggregate_value_),
+ ~0u,
+ 0,
+ 3,
+ 4,
+ 5,
+ 1,
+ 2,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::SourceCodeInfo_Location, _has_bits_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::SourceCodeInfo_Location, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::SourceCodeInfo_Location, path_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::SourceCodeInfo_Location, span_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::SourceCodeInfo_Location, leading_comments_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::SourceCodeInfo_Location, trailing_comments_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::SourceCodeInfo_Location, leading_detached_comments_),
+ ~0u,
+ ~0u,
+ 0,
+ 1,
+ ~0u,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::SourceCodeInfo, _has_bits_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::SourceCodeInfo, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::SourceCodeInfo, location_),
+ ~0u,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo_Annotation, _has_bits_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo_Annotation, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo_Annotation, path_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo_Annotation, source_file_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo_Annotation, begin_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo_Annotation, end_),
+ ~0u,
+ 0,
+ 1,
+ 2,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo, _has_bits_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo, annotation_),
+ ~0u,
};
-
-static const ::google::protobuf::internal::DefaultInstanceData file_default_instances[] = {
- {reinterpret_cast<const ::google::protobuf::Message*>(&_FileDescriptorSet_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_FileDescriptorProto_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_DescriptorProto_ExtensionRange_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_DescriptorProto_ReservedRange_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_DescriptorProto_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_FieldDescriptorProto_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_OneofDescriptorProto_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_EnumDescriptorProto_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_EnumValueDescriptorProto_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_ServiceDescriptorProto_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_MethodDescriptorProto_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_FileOptions_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_MessageOptions_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_FieldOptions_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_OneofOptions_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_EnumOptions_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_EnumValueOptions_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_ServiceOptions_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_MethodOptions_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_UninterpretedOption_NamePart_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_UninterpretedOption_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_SourceCodeInfo_Location_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_SourceCodeInfo_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_GeneratedCodeInfo_Annotation_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_GeneratedCodeInfo_default_instance_), NULL},
+static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+ { 0, 6, sizeof(::google::protobuf::FileDescriptorSet)},
+ { 7, 24, sizeof(::google::protobuf::FileDescriptorProto)},
+ { 36, 44, sizeof(::google::protobuf::DescriptorProto_ExtensionRange)},
+ { 47, 54, sizeof(::google::protobuf::DescriptorProto_ReservedRange)},
+ { 56, 71, sizeof(::google::protobuf::DescriptorProto)},
+ { 81, 87, sizeof(::google::protobuf::ExtensionRangeOptions)},
+ { 88, 103, sizeof(::google::protobuf::FieldDescriptorProto)},
+ { 113, 120, sizeof(::google::protobuf::OneofDescriptorProto)},
+ { 122, 129, sizeof(::google::protobuf::EnumDescriptorProto_EnumReservedRange)},
+ { 131, 141, sizeof(::google::protobuf::EnumDescriptorProto)},
+ { 146, 154, sizeof(::google::protobuf::EnumValueDescriptorProto)},
+ { 157, 165, sizeof(::google::protobuf::ServiceDescriptorProto)},
+ { 168, 179, sizeof(::google::protobuf::MethodDescriptorProto)},
+ { 185, 209, sizeof(::google::protobuf::FileOptions)},
+ { 228, 238, sizeof(::google::protobuf::MessageOptions)},
+ { 243, 255, sizeof(::google::protobuf::FieldOptions)},
+ { 262, 268, sizeof(::google::protobuf::OneofOptions)},
+ { 269, 277, sizeof(::google::protobuf::EnumOptions)},
+ { 280, 287, sizeof(::google::protobuf::EnumValueOptions)},
+ { 289, 296, sizeof(::google::protobuf::ServiceOptions)},
+ { 298, 306, sizeof(::google::protobuf::MethodOptions)},
+ { 309, 316, sizeof(::google::protobuf::UninterpretedOption_NamePart)},
+ { 318, 330, sizeof(::google::protobuf::UninterpretedOption)},
+ { 337, 347, sizeof(::google::protobuf::SourceCodeInfo_Location)},
+ { 352, 358, sizeof(::google::protobuf::SourceCodeInfo)},
+ { 359, 368, sizeof(::google::protobuf::GeneratedCodeInfo_Annotation)},
+ { 372, 378, sizeof(::google::protobuf::GeneratedCodeInfo)},
};
-namespace {
+static ::google::protobuf::Message const * const file_default_instances[] = {
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_FileDescriptorSet_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_FileDescriptorProto_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_DescriptorProto_ExtensionRange_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_DescriptorProto_ReservedRange_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_DescriptorProto_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_ExtensionRangeOptions_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_FieldDescriptorProto_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_OneofDescriptorProto_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_EnumDescriptorProto_EnumReservedRange_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_EnumDescriptorProto_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_EnumValueDescriptorProto_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_ServiceDescriptorProto_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_MethodDescriptorProto_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_FileOptions_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_MessageOptions_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_FieldOptions_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_OneofOptions_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_EnumOptions_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_EnumValueOptions_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_ServiceOptions_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_MethodOptions_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_UninterpretedOption_NamePart_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_UninterpretedOption_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_SourceCodeInfo_Location_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_SourceCodeInfo_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_GeneratedCodeInfo_Annotation_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_GeneratedCodeInfo_default_instance_),
+};
void protobuf_AssignDescriptors() {
- protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
+ AddDescriptors();
::google::protobuf::MessageFactory* factory = NULL;
AssignDescriptors(
- "google/protobuf/descriptor.proto", schemas, file_default_instances, protobuf_Offsets_google_2fprotobuf_2fdescriptor_2eproto(), factory,
+ "google/protobuf/descriptor.proto", schemas, file_default_instances, TableStruct::offsets, factory,
file_level_metadata, file_level_enum_descriptors, NULL);
}
@@ -482,123 +1218,15 @@ void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);
}
-void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
+void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
- ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 25);
-}
-
-} // namespace
-
-void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto() {
- _FileDescriptorSet_default_instance_.Shutdown();
- delete file_level_metadata[0].reflection;
- _FileDescriptorProto_default_instance_.Shutdown();
- delete file_level_metadata[1].reflection;
- _DescriptorProto_ExtensionRange_default_instance_.Shutdown();
- delete file_level_metadata[2].reflection;
- _DescriptorProto_ReservedRange_default_instance_.Shutdown();
- delete file_level_metadata[3].reflection;
- _DescriptorProto_default_instance_.Shutdown();
- delete file_level_metadata[4].reflection;
- _FieldDescriptorProto_default_instance_.Shutdown();
- delete file_level_metadata[5].reflection;
- _OneofDescriptorProto_default_instance_.Shutdown();
- delete file_level_metadata[6].reflection;
- _EnumDescriptorProto_default_instance_.Shutdown();
- delete file_level_metadata[7].reflection;
- _EnumValueDescriptorProto_default_instance_.Shutdown();
- delete file_level_metadata[8].reflection;
- _ServiceDescriptorProto_default_instance_.Shutdown();
- delete file_level_metadata[9].reflection;
- _MethodDescriptorProto_default_instance_.Shutdown();
- delete file_level_metadata[10].reflection;
- _FileOptions_default_instance_.Shutdown();
- delete file_level_metadata[11].reflection;
- _MessageOptions_default_instance_.Shutdown();
- delete file_level_metadata[12].reflection;
- _FieldOptions_default_instance_.Shutdown();
- delete file_level_metadata[13].reflection;
- _OneofOptions_default_instance_.Shutdown();
- delete file_level_metadata[14].reflection;
- _EnumOptions_default_instance_.Shutdown();
- delete file_level_metadata[15].reflection;
- _EnumValueOptions_default_instance_.Shutdown();
- delete file_level_metadata[16].reflection;
- _ServiceOptions_default_instance_.Shutdown();
- delete file_level_metadata[17].reflection;
- _MethodOptions_default_instance_.Shutdown();
- delete file_level_metadata[18].reflection;
- _UninterpretedOption_NamePart_default_instance_.Shutdown();
- delete file_level_metadata[19].reflection;
- _UninterpretedOption_default_instance_.Shutdown();
- delete file_level_metadata[20].reflection;
- _SourceCodeInfo_Location_default_instance_.Shutdown();
- delete file_level_metadata[21].reflection;
- _SourceCodeInfo_default_instance_.Shutdown();
- delete file_level_metadata[22].reflection;
- _GeneratedCodeInfo_Annotation_default_instance_.Shutdown();
- delete file_level_metadata[23].reflection;
- _GeneratedCodeInfo_default_instance_.Shutdown();
- delete file_level_metadata[24].reflection;
-}
-
-void protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl() {
- GOOGLE_PROTOBUF_VERIFY_VERSION;
-
- ::google::protobuf::internal::InitProtobufDefaults();
- _FileDescriptorSet_default_instance_.DefaultConstruct();
- _FileDescriptorProto_default_instance_.DefaultConstruct();
- _DescriptorProto_ExtensionRange_default_instance_.DefaultConstruct();
- _DescriptorProto_ReservedRange_default_instance_.DefaultConstruct();
- _DescriptorProto_default_instance_.DefaultConstruct();
- _FieldDescriptorProto_default_instance_.DefaultConstruct();
- _OneofDescriptorProto_default_instance_.DefaultConstruct();
- _EnumDescriptorProto_default_instance_.DefaultConstruct();
- _EnumValueDescriptorProto_default_instance_.DefaultConstruct();
- _ServiceDescriptorProto_default_instance_.DefaultConstruct();
- _MethodDescriptorProto_default_instance_.DefaultConstruct();
- _FileOptions_default_instance_.DefaultConstruct();
- _MessageOptions_default_instance_.DefaultConstruct();
- _FieldOptions_default_instance_.DefaultConstruct();
- _OneofOptions_default_instance_.DefaultConstruct();
- _EnumOptions_default_instance_.DefaultConstruct();
- _EnumValueOptions_default_instance_.DefaultConstruct();
- _ServiceOptions_default_instance_.DefaultConstruct();
- _MethodOptions_default_instance_.DefaultConstruct();
- _UninterpretedOption_NamePart_default_instance_.DefaultConstruct();
- _UninterpretedOption_default_instance_.DefaultConstruct();
- _SourceCodeInfo_Location_default_instance_.DefaultConstruct();
- _SourceCodeInfo_default_instance_.DefaultConstruct();
- _GeneratedCodeInfo_Annotation_default_instance_.DefaultConstruct();
- _GeneratedCodeInfo_default_instance_.DefaultConstruct();
- _FileDescriptorProto_default_instance_.get_mutable()->options_ = const_cast< ::google::protobuf::FileOptions*>(
- ::google::protobuf::FileOptions::internal_default_instance());
- _FileDescriptorProto_default_instance_.get_mutable()->source_code_info_ = const_cast< ::google::protobuf::SourceCodeInfo*>(
- ::google::protobuf::SourceCodeInfo::internal_default_instance());
- _DescriptorProto_default_instance_.get_mutable()->options_ = const_cast< ::google::protobuf::MessageOptions*>(
- ::google::protobuf::MessageOptions::internal_default_instance());
- _FieldDescriptorProto_default_instance_.get_mutable()->options_ = const_cast< ::google::protobuf::FieldOptions*>(
- ::google::protobuf::FieldOptions::internal_default_instance());
- _OneofDescriptorProto_default_instance_.get_mutable()->options_ = const_cast< ::google::protobuf::OneofOptions*>(
- ::google::protobuf::OneofOptions::internal_default_instance());
- _EnumDescriptorProto_default_instance_.get_mutable()->options_ = const_cast< ::google::protobuf::EnumOptions*>(
- ::google::protobuf::EnumOptions::internal_default_instance());
- _EnumValueDescriptorProto_default_instance_.get_mutable()->options_ = const_cast< ::google::protobuf::EnumValueOptions*>(
- ::google::protobuf::EnumValueOptions::internal_default_instance());
- _ServiceDescriptorProto_default_instance_.get_mutable()->options_ = const_cast< ::google::protobuf::ServiceOptions*>(
- ::google::protobuf::ServiceOptions::internal_default_instance());
- _MethodDescriptorProto_default_instance_.get_mutable()->options_ = const_cast< ::google::protobuf::MethodOptions*>(
- ::google::protobuf::MethodOptions::internal_default_instance());
+ ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 27);
}
-void protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl);
-}
-void protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl() {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
- static const char descriptor[] = {
+void AddDescriptorsImpl() {
+ InitDefaults();
+ static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n google/protobuf/descriptor.proto\022\017goog"
"le.protobuf\"G\n\021FileDescriptorSet\0222\n\004file"
"\030\001 \003(\0132$.google.protobuf.FileDescriptorP"
@@ -614,7 +1242,7 @@ void protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl() {
"\022-\n\007options\030\010 \001(\0132\034.google.protobuf.File"
"Options\0229\n\020source_code_info\030\t \001(\0132\037.goog"
"le.protobuf.SourceCodeInfo\022\016\n\006syntax\030\014 \001"
- "(\t\"\360\004\n\017DescriptorProto\022\014\n\004name\030\001 \001(\t\0224\n\005"
+ "(\t\"\251\005\n\017DescriptorProto\022\014\n\004name\030\001 \001(\t\0224\n\005"
"field\030\002 \003(\0132%.google.protobuf.FieldDescr"
"iptorProto\0228\n\textension\030\006 \003(\0132%.google.p"
"rotobuf.FieldDescriptorProto\0225\n\013nested_t"
@@ -627,139 +1255,151 @@ void protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl() {
"ions\030\007 \001(\0132\037.google.protobuf.MessageOpti"
"ons\022F\n\016reserved_range\030\t \003(\0132..google.pro"
"tobuf.DescriptorProto.ReservedRange\022\025\n\rr"
- "eserved_name\030\n \003(\t\032,\n\016ExtensionRange\022\r\n\005"
- "start\030\001 \001(\005\022\013\n\003end\030\002 \001(\005\032+\n\rReservedRang"
- "e\022\r\n\005start\030\001 \001(\005\022\013\n\003end\030\002 \001(\005\"\274\005\n\024FieldD"
- "escriptorProto\022\014\n\004name\030\001 \001(\t\022\016\n\006number\030\003"
- " \001(\005\022:\n\005label\030\004 \001(\0162+.google.protobuf.Fi"
- "eldDescriptorProto.Label\0228\n\004type\030\005 \001(\0162*"
- ".google.protobuf.FieldDescriptorProto.Ty"
- "pe\022\021\n\ttype_name\030\006 \001(\t\022\020\n\010extendee\030\002 \001(\t\022"
- "\025\n\rdefault_value\030\007 \001(\t\022\023\n\013oneof_index\030\t "
- "\001(\005\022\021\n\tjson_name\030\n \001(\t\022.\n\007options\030\010 \001(\0132"
- "\035.google.protobuf.FieldOptions\"\266\002\n\004Type\022"
- "\017\n\013TYPE_DOUBLE\020\001\022\016\n\nTYPE_FLOAT\020\002\022\016\n\nTYPE"
- "_INT64\020\003\022\017\n\013TYPE_UINT64\020\004\022\016\n\nTYPE_INT32\020"
- "\005\022\020\n\014TYPE_FIXED64\020\006\022\020\n\014TYPE_FIXED32\020\007\022\r\n"
- "\tTYPE_BOOL\020\010\022\017\n\013TYPE_STRING\020\t\022\016\n\nTYPE_GR"
- "OUP\020\n\022\020\n\014TYPE_MESSAGE\020\013\022\016\n\nTYPE_BYTES\020\014\022"
- "\017\n\013TYPE_UINT32\020\r\022\r\n\tTYPE_ENUM\020\016\022\021\n\rTYPE_"
- "SFIXED32\020\017\022\021\n\rTYPE_SFIXED64\020\020\022\017\n\013TYPE_SI"
- "NT32\020\021\022\017\n\013TYPE_SINT64\020\022\"C\n\005Label\022\022\n\016LABE"
- "L_OPTIONAL\020\001\022\022\n\016LABEL_REQUIRED\020\002\022\022\n\016LABE"
- "L_REPEATED\020\003\"T\n\024OneofDescriptorProto\022\014\n\004"
- "name\030\001 \001(\t\022.\n\007options\030\002 \001(\0132\035.google.pro"
- "tobuf.OneofOptions\"\214\001\n\023EnumDescriptorPro"
- "to\022\014\n\004name\030\001 \001(\t\0228\n\005value\030\002 \003(\0132).google"
- ".protobuf.EnumValueDescriptorProto\022-\n\007op"
- "tions\030\003 \001(\0132\034.google.protobuf.EnumOption"
- "s\"l\n\030EnumValueDescriptorProto\022\014\n\004name\030\001 "
- "\001(\t\022\016\n\006number\030\002 \001(\005\0222\n\007options\030\003 \001(\0132!.g"
- "oogle.protobuf.EnumValueOptions\"\220\001\n\026Serv"
- "iceDescriptorProto\022\014\n\004name\030\001 \001(\t\0226\n\006meth"
- "od\030\002 \003(\0132&.google.protobuf.MethodDescrip"
- "torProto\0220\n\007options\030\003 \001(\0132\037.google.proto"
- "buf.ServiceOptions\"\301\001\n\025MethodDescriptorP"
- "roto\022\014\n\004name\030\001 \001(\t\022\022\n\ninput_type\030\002 \001(\t\022\023"
- "\n\013output_type\030\003 \001(\t\022/\n\007options\030\004 \001(\0132\036.g"
- "oogle.protobuf.MethodOptions\022\037\n\020client_s"
- "treaming\030\005 \001(\010:\005false\022\037\n\020server_streamin"
- "g\030\006 \001(\010:\005false\"\232\005\n\013FileOptions\022\024\n\014java_p"
- "ackage\030\001 \001(\t\022\034\n\024java_outer_classname\030\010 \001"
- "(\t\022\"\n\023java_multiple_files\030\n \001(\010:\005false\022)"
- "\n\035java_generate_equals_and_hash\030\024 \001(\010B\002\030"
- "\001\022%\n\026java_string_check_utf8\030\033 \001(\010:\005false"
- "\022F\n\014optimize_for\030\t \001(\0162).google.protobuf"
- ".FileOptions.OptimizeMode:\005SPEED\022\022\n\ngo_p"
- "ackage\030\013 \001(\t\022\"\n\023cc_generic_services\030\020 \001("
- "\010:\005false\022$\n\025java_generic_services\030\021 \001(\010:"
- "\005false\022\"\n\023py_generic_services\030\022 \001(\010:\005fal"
- "se\022\031\n\ndeprecated\030\027 \001(\010:\005false\022\037\n\020cc_enab"
- "le_arenas\030\037 \001(\010:\005false\022\031\n\021objc_class_pre"
- "fix\030$ \001(\t\022\030\n\020csharp_namespace\030% \001(\t\022\024\n\014s"
- "wift_prefix\030\' \001(\t\022C\n\024uninterpreted_optio"
+ "eserved_name\030\n \003(\t\032e\n\016ExtensionRange\022\r\n\005"
+ "start\030\001 \001(\005\022\013\n\003end\030\002 \001(\005\0227\n\007options\030\003 \001("
+ "\0132&.google.protobuf.ExtensionRangeOption"
+ "s\032+\n\rReservedRange\022\r\n\005start\030\001 \001(\005\022\013\n\003end"
+ "\030\002 \001(\005\"g\n\025ExtensionRangeOptions\022C\n\024unint"
+ "erpreted_option\030\347\007 \003(\0132$.google.protobuf"
+ ".UninterpretedOption*\t\010\350\007\020\200\200\200\200\002\"\274\005\n\024Fiel"
+ "dDescriptorProto\022\014\n\004name\030\001 \001(\t\022\016\n\006number"
+ "\030\003 \001(\005\022:\n\005label\030\004 \001(\0162+.google.protobuf."
+ "FieldDescriptorProto.Label\0228\n\004type\030\005 \001(\016"
+ "2*.google.protobuf.FieldDescriptorProto."
+ "Type\022\021\n\ttype_name\030\006 \001(\t\022\020\n\010extendee\030\002 \001("
+ "\t\022\025\n\rdefault_value\030\007 \001(\t\022\023\n\013oneof_index\030"
+ "\t \001(\005\022\021\n\tjson_name\030\n \001(\t\022.\n\007options\030\010 \001("
+ "\0132\035.google.protobuf.FieldOptions\"\266\002\n\004Typ"
+ "e\022\017\n\013TYPE_DOUBLE\020\001\022\016\n\nTYPE_FLOAT\020\002\022\016\n\nTY"
+ "PE_INT64\020\003\022\017\n\013TYPE_UINT64\020\004\022\016\n\nTYPE_INT3"
+ "2\020\005\022\020\n\014TYPE_FIXED64\020\006\022\020\n\014TYPE_FIXED32\020\007\022"
+ "\r\n\tTYPE_BOOL\020\010\022\017\n\013TYPE_STRING\020\t\022\016\n\nTYPE_"
+ "GROUP\020\n\022\020\n\014TYPE_MESSAGE\020\013\022\016\n\nTYPE_BYTES\020"
+ "\014\022\017\n\013TYPE_UINT32\020\r\022\r\n\tTYPE_ENUM\020\016\022\021\n\rTYP"
+ "E_SFIXED32\020\017\022\021\n\rTYPE_SFIXED64\020\020\022\017\n\013TYPE_"
+ "SINT32\020\021\022\017\n\013TYPE_SINT64\020\022\"C\n\005Label\022\022\n\016LA"
+ "BEL_OPTIONAL\020\001\022\022\n\016LABEL_REQUIRED\020\002\022\022\n\016LA"
+ "BEL_REPEATED\020\003\"T\n\024OneofDescriptorProto\022\014"
+ "\n\004name\030\001 \001(\t\022.\n\007options\030\002 \001(\0132\035.google.p"
+ "rotobuf.OneofOptions\"\244\002\n\023EnumDescriptorP"
+ "roto\022\014\n\004name\030\001 \001(\t\0228\n\005value\030\002 \003(\0132).goog"
+ "le.protobuf.EnumValueDescriptorProto\022-\n\007"
+ "options\030\003 \001(\0132\034.google.protobuf.EnumOpti"
+ "ons\022N\n\016reserved_range\030\004 \003(\01326.google.pro"
+ "tobuf.EnumDescriptorProto.EnumReservedRa"
+ "nge\022\025\n\rreserved_name\030\005 \003(\t\032/\n\021EnumReserv"
+ "edRange\022\r\n\005start\030\001 \001(\005\022\013\n\003end\030\002 \001(\005\"l\n\030E"
+ "numValueDescriptorProto\022\014\n\004name\030\001 \001(\t\022\016\n"
+ "\006number\030\002 \001(\005\0222\n\007options\030\003 \001(\0132!.google."
+ "protobuf.EnumValueOptions\"\220\001\n\026ServiceDes"
+ "criptorProto\022\014\n\004name\030\001 \001(\t\0226\n\006method\030\002 \003"
+ "(\0132&.google.protobuf.MethodDescriptorPro"
+ "to\0220\n\007options\030\003 \001(\0132\037.google.protobuf.Se"
+ "rviceOptions\"\301\001\n\025MethodDescriptorProto\022\014"
+ "\n\004name\030\001 \001(\t\022\022\n\ninput_type\030\002 \001(\t\022\023\n\013outp"
+ "ut_type\030\003 \001(\t\022/\n\007options\030\004 \001(\0132\036.google."
+ "protobuf.MethodOptions\022\037\n\020client_streami"
+ "ng\030\005 \001(\010:\005false\022\037\n\020server_streaming\030\006 \001("
+ "\010:\005false\"\360\005\n\013FileOptions\022\024\n\014java_package"
+ "\030\001 \001(\t\022\034\n\024java_outer_classname\030\010 \001(\t\022\"\n\023"
+ "java_multiple_files\030\n \001(\010:\005false\022)\n\035java"
+ "_generate_equals_and_hash\030\024 \001(\010B\002\030\001\022%\n\026j"
+ "ava_string_check_utf8\030\033 \001(\010:\005false\022F\n\014op"
+ "timize_for\030\t \001(\0162).google.protobuf.FileO"
+ "ptions.OptimizeMode:\005SPEED\022\022\n\ngo_package"
+ "\030\013 \001(\t\022\"\n\023cc_generic_services\030\020 \001(\010:\005fal"
+ "se\022$\n\025java_generic_services\030\021 \001(\010:\005false"
+ "\022\"\n\023py_generic_services\030\022 \001(\010:\005false\022#\n\024"
+ "php_generic_services\030* \001(\010:\005false\022\031\n\ndep"
+ "recated\030\027 \001(\010:\005false\022\037\n\020cc_enable_arenas"
+ "\030\037 \001(\010:\005false\022\031\n\021objc_class_prefix\030$ \001(\t"
+ "\022\030\n\020csharp_namespace\030% \001(\t\022\024\n\014swift_pref"
+ "ix\030\' \001(\t\022\030\n\020php_class_prefix\030( \001(\t\022\025\n\rph"
+ "p_namespace\030) \001(\t\022C\n\024uninterpreted_optio"
"n\030\347\007 \003(\0132$.google.protobuf.Uninterpreted"
"Option\":\n\014OptimizeMode\022\t\n\005SPEED\020\001\022\r\n\tCOD"
"E_SIZE\020\002\022\020\n\014LITE_RUNTIME\020\003*\t\010\350\007\020\200\200\200\200\002J\004\010"
- "&\020\'\"\354\001\n\016MessageOptions\022&\n\027message_set_wi"
+ "&\020\'\"\362\001\n\016MessageOptions\022&\n\027message_set_wi"
"re_format\030\001 \001(\010:\005false\022.\n\037no_standard_de"
"scriptor_accessor\030\002 \001(\010:\005false\022\031\n\ndeprec"
"ated\030\003 \001(\010:\005false\022\021\n\tmap_entry\030\007 \001(\010\022C\n\024"
"uninterpreted_option\030\347\007 \003(\0132$.google.pro"
"tobuf.UninterpretedOption*\t\010\350\007\020\200\200\200\200\002J\004\010\010"
- "\020\t\"\236\003\n\014FieldOptions\022:\n\005ctype\030\001 \001(\0162#.goo"
- "gle.protobuf.FieldOptions.CType:\006STRING\022"
- "\016\n\006packed\030\002 \001(\010\022\?\n\006jstype\030\006 \001(\0162$.google"
- ".protobuf.FieldOptions.JSType:\tJS_NORMAL"
- "\022\023\n\004lazy\030\005 \001(\010:\005false\022\031\n\ndeprecated\030\003 \001("
- "\010:\005false\022\023\n\004weak\030\n \001(\010:\005false\022C\n\024uninter"
- "preted_option\030\347\007 \003(\0132$.google.protobuf.U"
- "ninterpretedOption\"/\n\005CType\022\n\n\006STRING\020\000\022"
- "\010\n\004CORD\020\001\022\020\n\014STRING_PIECE\020\002\"5\n\006JSType\022\r\n"
- "\tJS_NORMAL\020\000\022\r\n\tJS_STRING\020\001\022\r\n\tJS_NUMBER"
- "\020\002*\t\010\350\007\020\200\200\200\200\002J\004\010\004\020\005\"^\n\014OneofOptions\022C\n\024u"
+ "\020\tJ\004\010\t\020\n\"\236\003\n\014FieldOptions\022:\n\005ctype\030\001 \001(\016"
+ "2#.google.protobuf.FieldOptions.CType:\006S"
+ "TRING\022\016\n\006packed\030\002 \001(\010\022\?\n\006jstype\030\006 \001(\0162$."
+ "google.protobuf.FieldOptions.JSType:\tJS_"
+ "NORMAL\022\023\n\004lazy\030\005 \001(\010:\005false\022\031\n\ndeprecate"
+ "d\030\003 \001(\010:\005false\022\023\n\004weak\030\n \001(\010:\005false\022C\n\024u"
"ninterpreted_option\030\347\007 \003(\0132$.google.prot"
- "obuf.UninterpretedOption*\t\010\350\007\020\200\200\200\200\002\"\215\001\n\013"
- "EnumOptions\022\023\n\013allow_alias\030\002 \001(\010\022\031\n\ndepr"
- "ecated\030\003 \001(\010:\005false\022C\n\024uninterpreted_opt"
- "ion\030\347\007 \003(\0132$.google.protobuf.Uninterpret"
- "edOption*\t\010\350\007\020\200\200\200\200\002\"}\n\020EnumValueOptions\022"
- "\031\n\ndeprecated\030\001 \001(\010:\005false\022C\n\024uninterpre"
- "ted_option\030\347\007 \003(\0132$.google.protobuf.Unin"
- "terpretedOption*\t\010\350\007\020\200\200\200\200\002\"{\n\016ServiceOpt"
- "ions\022\031\n\ndeprecated\030! \001(\010:\005false\022C\n\024unint"
- "erpreted_option\030\347\007 \003(\0132$.google.protobuf"
- ".UninterpretedOption*\t\010\350\007\020\200\200\200\200\002\"\255\002\n\rMeth"
- "odOptions\022\031\n\ndeprecated\030! \001(\010:\005false\022_\n\021"
- "idempotency_level\030\" \001(\0162/.google.protobu"
- "f.MethodOptions.IdempotencyLevel:\023IDEMPO"
- "TENCY_UNKNOWN\022C\n\024uninterpreted_option\030\347\007"
- " \003(\0132$.google.protobuf.UninterpretedOpti"
- "on\"P\n\020IdempotencyLevel\022\027\n\023IDEMPOTENCY_UN"
- "KNOWN\020\000\022\023\n\017NO_SIDE_EFFECTS\020\001\022\016\n\nIDEMPOTE"
- "NT\020\002*\t\010\350\007\020\200\200\200\200\002\"\236\002\n\023UninterpretedOption\022"
- ";\n\004name\030\002 \003(\0132-.google.protobuf.Uninterp"
- "retedOption.NamePart\022\030\n\020identifier_value"
- "\030\003 \001(\t\022\032\n\022positive_int_value\030\004 \001(\004\022\032\n\022ne"
- "gative_int_value\030\005 \001(\003\022\024\n\014double_value\030\006"
- " \001(\001\022\024\n\014string_value\030\007 \001(\014\022\027\n\017aggregate_"
- "value\030\010 \001(\t\0323\n\010NamePart\022\021\n\tname_part\030\001 \002"
- "(\t\022\024\n\014is_extension\030\002 \002(\010\"\325\001\n\016SourceCodeI"
- "nfo\022:\n\010location\030\001 \003(\0132(.google.protobuf."
- "SourceCodeInfo.Location\032\206\001\n\010Location\022\020\n\004"
- "path\030\001 \003(\005B\002\020\001\022\020\n\004span\030\002 \003(\005B\002\020\001\022\030\n\020lead"
- "ing_comments\030\003 \001(\t\022\031\n\021trailing_comments\030"
- "\004 \001(\t\022!\n\031leading_detached_comments\030\006 \003(\t"
- "\"\247\001\n\021GeneratedCodeInfo\022A\n\nannotation\030\001 \003"
- "(\0132-.google.protobuf.GeneratedCodeInfo.A"
- "nnotation\032O\n\nAnnotation\022\020\n\004path\030\001 \003(\005B\002\020"
- "\001\022\023\n\013source_file\030\002 \001(\t\022\r\n\005begin\030\003 \001(\005\022\013\n"
- "\003end\030\004 \001(\005B\214\001\n\023com.google.protobufB\020Desc"
- "riptorProtosH\001Z>github.com/golang/protob"
- "uf/protoc-gen-go/descriptor;descriptor\242\002"
- "\003GPB\252\002\032Google.Protobuf.Reflection"
+ "obuf.UninterpretedOption\"/\n\005CType\022\n\n\006STR"
+ "ING\020\000\022\010\n\004CORD\020\001\022\020\n\014STRING_PIECE\020\002\"5\n\006JST"
+ "ype\022\r\n\tJS_NORMAL\020\000\022\r\n\tJS_STRING\020\001\022\r\n\tJS_"
+ "NUMBER\020\002*\t\010\350\007\020\200\200\200\200\002J\004\010\004\020\005\"^\n\014OneofOption"
+ "s\022C\n\024uninterpreted_option\030\347\007 \003(\0132$.googl"
+ "e.protobuf.UninterpretedOption*\t\010\350\007\020\200\200\200\200"
+ "\002\"\223\001\n\013EnumOptions\022\023\n\013allow_alias\030\002 \001(\010\022\031"
+ "\n\ndeprecated\030\003 \001(\010:\005false\022C\n\024uninterpret"
+ "ed_option\030\347\007 \003(\0132$.google.protobuf.Unint"
+ "erpretedOption*\t\010\350\007\020\200\200\200\200\002J\004\010\005\020\006\"}\n\020EnumV"
+ "alueOptions\022\031\n\ndeprecated\030\001 \001(\010:\005false\022C"
+ "\n\024uninterpreted_option\030\347\007 \003(\0132$.google.p"
+ "rotobuf.UninterpretedOption*\t\010\350\007\020\200\200\200\200\002\"{"
+ "\n\016ServiceOptions\022\031\n\ndeprecated\030! \001(\010:\005fa"
+ "lse\022C\n\024uninterpreted_option\030\347\007 \003(\0132$.goo"
+ "gle.protobuf.UninterpretedOption*\t\010\350\007\020\200\200"
+ "\200\200\002\"\255\002\n\rMethodOptions\022\031\n\ndeprecated\030! \001("
+ "\010:\005false\022_\n\021idempotency_level\030\" \001(\0162/.go"
+ "ogle.protobuf.MethodOptions.IdempotencyL"
+ "evel:\023IDEMPOTENCY_UNKNOWN\022C\n\024uninterpret"
+ "ed_option\030\347\007 \003(\0132$.google.protobuf.Unint"
+ "erpretedOption\"P\n\020IdempotencyLevel\022\027\n\023ID"
+ "EMPOTENCY_UNKNOWN\020\000\022\023\n\017NO_SIDE_EFFECTS\020\001"
+ "\022\016\n\nIDEMPOTENT\020\002*\t\010\350\007\020\200\200\200\200\002\"\236\002\n\023Uninterp"
+ "retedOption\022;\n\004name\030\002 \003(\0132-.google.proto"
+ "buf.UninterpretedOption.NamePart\022\030\n\020iden"
+ "tifier_value\030\003 \001(\t\022\032\n\022positive_int_value"
+ "\030\004 \001(\004\022\032\n\022negative_int_value\030\005 \001(\003\022\024\n\014do"
+ "uble_value\030\006 \001(\001\022\024\n\014string_value\030\007 \001(\014\022\027"
+ "\n\017aggregate_value\030\010 \001(\t\0323\n\010NamePart\022\021\n\tn"
+ "ame_part\030\001 \002(\t\022\024\n\014is_extension\030\002 \002(\010\"\325\001\n"
+ "\016SourceCodeInfo\022:\n\010location\030\001 \003(\0132(.goog"
+ "le.protobuf.SourceCodeInfo.Location\032\206\001\n\010"
+ "Location\022\020\n\004path\030\001 \003(\005B\002\020\001\022\020\n\004span\030\002 \003(\005"
+ "B\002\020\001\022\030\n\020leading_comments\030\003 \001(\t\022\031\n\021traili"
+ "ng_comments\030\004 \001(\t\022!\n\031leading_detached_co"
+ "mments\030\006 \003(\t\"\247\001\n\021GeneratedCodeInfo\022A\n\nan"
+ "notation\030\001 \003(\0132-.google.protobuf.Generat"
+ "edCodeInfo.Annotation\032O\n\nAnnotation\022\020\n\004p"
+ "ath\030\001 \003(\005B\002\020\001\022\023\n\013source_file\030\002 \001(\t\022\r\n\005be"
+ "gin\030\003 \001(\005\022\013\n\003end\030\004 \001(\005B\217\001\n\023com.google.pr"
+ "otobufB\020DescriptorProtosH\001Z>github.com/g"
+ "olang/protobuf/protoc-gen-go/descriptor;"
+ "descriptor\370\001\001\242\002\003GPB\252\002\032Google.Protobuf.Re"
+ "flection"
};
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
- descriptor, 5553);
+ descriptor, 5968);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"google/protobuf/descriptor.proto", &protobuf_RegisterTypes);
- ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto);
}
-GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_once_);
-void protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto() {
- ::google::protobuf::GoogleOnceInit(&protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_once_,
- &protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl);
+void AddDescriptors() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);
}
-// Force AddDescriptors() to be called at static initialization time.
-struct StaticDescriptorInitializer_google_2fprotobuf_2fdescriptor_2eproto {
- StaticDescriptorInitializer_google_2fprotobuf_2fdescriptor_2eproto() {
- protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
+// Force AddDescriptors() to be called at dynamic initialization time.
+struct StaticDescriptorInitializer {
+ StaticDescriptorInitializer() {
+ AddDescriptors();
}
-} static_descriptor_initializer_google_2fprotobuf_2fdescriptor_2eproto_;
+} static_descriptor_initializer;
+} // namespace protobuf_google_2fprotobuf_2fdescriptor_2eproto
+namespace google {
+namespace protobuf {
const ::google::protobuf::EnumDescriptor* FieldDescriptorProto_Type_descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_enum_descriptors[0];
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_enum_descriptors[0];
}
bool FieldDescriptorProto_Type_IsValid(int value) {
switch (value) {
@@ -811,8 +1451,8 @@ const FieldDescriptorProto_Type FieldDescriptorProto::Type_MAX;
const int FieldDescriptorProto::Type_ARRAYSIZE;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
const ::google::protobuf::EnumDescriptor* FieldDescriptorProto_Label_descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_enum_descriptors[1];
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_enum_descriptors[1];
}
bool FieldDescriptorProto_Label_IsValid(int value) {
switch (value) {
@@ -834,8 +1474,8 @@ const FieldDescriptorProto_Label FieldDescriptorProto::Label_MAX;
const int FieldDescriptorProto::Label_ARRAYSIZE;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
const ::google::protobuf::EnumDescriptor* FileOptions_OptimizeMode_descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_enum_descriptors[2];
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_enum_descriptors[2];
}
bool FileOptions_OptimizeMode_IsValid(int value) {
switch (value) {
@@ -857,8 +1497,8 @@ const FileOptions_OptimizeMode FileOptions::OptimizeMode_MAX;
const int FileOptions::OptimizeMode_ARRAYSIZE;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
const ::google::protobuf::EnumDescriptor* FieldOptions_CType_descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_enum_descriptors[3];
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_enum_descriptors[3];
}
bool FieldOptions_CType_IsValid(int value) {
switch (value) {
@@ -880,8 +1520,8 @@ const FieldOptions_CType FieldOptions::CType_MAX;
const int FieldOptions::CType_ARRAYSIZE;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
const ::google::protobuf::EnumDescriptor* FieldOptions_JSType_descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_enum_descriptors[4];
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_enum_descriptors[4];
}
bool FieldOptions_JSType_IsValid(int value) {
switch (value) {
@@ -903,8 +1543,8 @@ const FieldOptions_JSType FieldOptions::JSType_MAX;
const int FieldOptions::JSType_ARRAYSIZE;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
const ::google::protobuf::EnumDescriptor* MethodOptions_IdempotencyLevel_descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_enum_descriptors[5];
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_enum_descriptors[5];
}
bool MethodOptions_IdempotencyLevel_IsValid(int value) {
switch (value) {
@@ -928,6 +1568,8 @@ const int MethodOptions::IdempotencyLevel_ARRAYSIZE;
// ===================================================================
+void FileDescriptorSet::InitAsDefaultInstance() {
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int FileDescriptorSet::kFileFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
@@ -935,11 +1577,20 @@ const int FileDescriptorSet::kFileFieldNumber;
FileDescriptorSet::FileDescriptorSet()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorSet();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.FileDescriptorSet)
}
+FileDescriptorSet::FileDescriptorSet(::google::protobuf::Arena* arena)
+ : ::google::protobuf::Message(),
+ _internal_metadata_(arena),
+ file_(arena) {
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorSet();
+ SharedCtor();
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.FileDescriptorSet)
+}
FileDescriptorSet::FileDescriptorSet(const FileDescriptorSet& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
@@ -960,33 +1611,40 @@ FileDescriptorSet::~FileDescriptorSet() {
}
void FileDescriptorSet::SharedDtor() {
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
}
+void FileDescriptorSet::ArenaDtor(void* object) {
+ FileDescriptorSet* _this = reinterpret_cast< FileDescriptorSet* >(object);
+ (void)_this;
+}
+void FileDescriptorSet::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+}
void FileDescriptorSet::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* FileDescriptorSet::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[0].descriptor;
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const FileDescriptorSet& FileDescriptorSet::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorSet();
return *internal_default_instance();
}
FileDescriptorSet* FileDescriptorSet::New(::google::protobuf::Arena* arena) const {
- FileDescriptorSet* n = new FileDescriptorSet;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
+ return ::google::protobuf::Arena::CreateMessage<FileDescriptorSet>(arena);
}
void FileDescriptorSet::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.FileDescriptorSet)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
file_.Clear();
_has_bits_.Clear();
_internal_metadata_.Clear();
@@ -1004,26 +1662,22 @@ bool FileDescriptorSet::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated .google.protobuf.FileDescriptorProto file = 1;
case 1: {
- if (tag == 10u) {
- DO_(input->IncrementRecursionDepth());
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
- input, add_file()));
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_file()));
} else {
goto handle_unusual;
}
- input->UnsafeDecrementRecursionDepth();
break;
}
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
- input, tag, mutable_unknown_fields()));
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -1040,15 +1694,19 @@ failure:
void FileDescriptorSet::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.FileDescriptorSet)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// repeated .google.protobuf.FileDescriptorProto file = 1;
- for (unsigned int i = 0, n = this->file_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->file_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 1, this->file(i), output);
+ 1, this->file(static_cast<int>(i)), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- unknown_fields(), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.FileDescriptorSet)
}
@@ -1057,16 +1715,20 @@ void FileDescriptorSet::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.FileDescriptorSet)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// repeated .google.protobuf.FileDescriptorProto file = 1;
- for (unsigned int i = 0, n = this->file_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->file_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 1, this->file(i), false, target);
+ InternalWriteMessageToArray(
+ 1, this->file(static_cast<int>(i)), deterministic, target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- unknown_fields(), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.FileDescriptorSet)
return target;
@@ -1079,16 +1741,16 @@ size_t FileDescriptorSet::ByteSizeLong() const {
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- unknown_fields());
+ _internal_metadata_.unknown_fields());
}
// repeated .google.protobuf.FileDescriptorProto file = 1;
{
- unsigned int count = this->file_size();
+ unsigned int count = static_cast<unsigned int>(this->file_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->file(i));
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->file(static_cast<int>(i)));
}
}
@@ -1118,6 +1780,9 @@ void FileDescriptorSet::MergeFrom(const FileDescriptorSet& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.FileDescriptorSet)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
file_.MergeFrom(from.file_);
}
@@ -1142,57 +1807,79 @@ bool FileDescriptorSet::IsInitialized() const {
void FileDescriptorSet::Swap(FileDescriptorSet* other) {
if (other == this) return;
+ if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ InternalSwap(other);
+ } else {
+ FileDescriptorSet* temp = New(GetArenaNoVirtual());
+ temp->MergeFrom(*other);
+ other->CopyFrom(*this);
+ InternalSwap(temp);
+ if (GetArenaNoVirtual() == NULL) {
+ delete temp;
+ }
+ }
+}
+void FileDescriptorSet::UnsafeArenaSwap(FileDescriptorSet* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void FileDescriptorSet::InternalSwap(FileDescriptorSet* other) {
- file_.UnsafeArenaSwap(&other->file_);
- std::swap(_has_bits_[0], other->_has_bits_[0]);
+ using std::swap;
+ file_.InternalSwap(&other->file_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- std::swap(_cached_size_, other->_cached_size_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata FileDescriptorSet::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[0];
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// FileDescriptorSet
-// repeated .google.protobuf.FileDescriptorProto file = 1;
-int FileDescriptorSet::file_size() const {
- return file_.size();
-}
-void FileDescriptorSet::clear_file() {
- file_.Clear();
-}
-const ::google::protobuf::FileDescriptorProto& FileDescriptorSet::file(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorSet.file)
- return file_.Get(index);
+// ===================================================================
+
+void FileDescriptorProto::InitAsDefaultInstance() {
+ ::google::protobuf::_FileDescriptorProto_default_instance_._instance.get_mutable()->options_ = const_cast< ::google::protobuf::FileOptions*>(
+ ::google::protobuf::FileOptions::internal_default_instance());
+ ::google::protobuf::_FileDescriptorProto_default_instance_._instance.get_mutable()->source_code_info_ = const_cast< ::google::protobuf::SourceCodeInfo*>(
+ ::google::protobuf::SourceCodeInfo::internal_default_instance());
}
-::google::protobuf::FileDescriptorProto* FileDescriptorSet::mutable_file(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorSet.file)
- return file_.Mutable(index);
+void FileDescriptorProto::_slow_mutable_options() {
+ options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::FileOptions >(
+ GetArenaNoVirtual());
}
-::google::protobuf::FileDescriptorProto* FileDescriptorSet::add_file() {
- // @@protoc_insertion_point(field_add:google.protobuf.FileDescriptorSet.file)
- return file_.Add();
+void FileDescriptorProto::unsafe_arena_set_allocated_options(
+ ::google::protobuf::FileOptions* options) {
+ if (GetArenaNoVirtual() == NULL) {
+ delete options_;
+ }
+ options_ = options;
+ if (options) {
+ set_has_options();
+ } else {
+ clear_has_options();
+ }
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileDescriptorProto.options)
}
-::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto >*
-FileDescriptorSet::mutable_file() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.FileDescriptorSet.file)
- return &file_;
+void FileDescriptorProto::_slow_mutable_source_code_info() {
+ source_code_info_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::SourceCodeInfo >(
+ GetArenaNoVirtual());
}
-const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto >&
-FileDescriptorSet::file() const {
- // @@protoc_insertion_point(field_list:google.protobuf.FileDescriptorSet.file)
- return file_;
+void FileDescriptorProto::unsafe_arena_set_allocated_source_code_info(
+ ::google::protobuf::SourceCodeInfo* source_code_info) {
+ if (GetArenaNoVirtual() == NULL) {
+ delete source_code_info_;
+ }
+ source_code_info_ = source_code_info;
+ if (source_code_info) {
+ set_has_source_code_info();
+ } else {
+ clear_has_source_code_info();
+ }
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileDescriptorProto.source_code_info)
}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
-
-// ===================================================================
-
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int FileDescriptorProto::kNameFieldNumber;
const int FileDescriptorProto::kPackageFieldNumber;
@@ -1211,35 +1898,53 @@ const int FileDescriptorProto::kSyntaxFieldNumber;
FileDescriptorProto::FileDescriptorProto()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorProto();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.FileDescriptorProto)
}
+FileDescriptorProto::FileDescriptorProto(::google::protobuf::Arena* arena)
+ : ::google::protobuf::Message(),
+ _internal_metadata_(arena),
+ dependency_(arena),
+ message_type_(arena),
+ enum_type_(arena),
+ service_(arena),
+ extension_(arena),
+ public_dependency_(arena),
+ weak_dependency_(arena) {
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorProto();
+ SharedCtor();
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.FileDescriptorProto)
+}
FileDescriptorProto::FileDescriptorProto(const FileDescriptorProto& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
_cached_size_(0),
dependency_(from.dependency_),
- public_dependency_(from.public_dependency_),
- weak_dependency_(from.weak_dependency_),
message_type_(from.message_type_),
enum_type_(from.enum_type_),
service_(from.service_),
- extension_(from.extension_) {
+ extension_(from.extension_),
+ public_dependency_(from.public_dependency_),
+ weak_dependency_(from.weak_dependency_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_name()) {
- name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_);
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name(),
+ GetArenaNoVirtual());
}
package_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_package()) {
- package_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.package_);
+ package_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.package(),
+ GetArenaNoVirtual());
}
syntax_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_syntax()) {
- syntax_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.syntax_);
+ syntax_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.syntax(),
+ GetArenaNoVirtual());
}
if (from.has_options()) {
options_ = new ::google::protobuf::FileOptions(*from.options_);
@@ -1259,8 +1964,9 @@ void FileDescriptorProto::SharedCtor() {
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
package_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
syntax_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- ::memset(&options_, 0, reinterpret_cast<char*>(&source_code_info_) -
- reinterpret_cast<char*>(&options_) + sizeof(source_code_info_));
+ ::memset(&options_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&source_code_info_) -
+ reinterpret_cast<char*>(&options_)) + sizeof(source_code_info_));
}
FileDescriptorProto::~FileDescriptorProto() {
@@ -1269,69 +1975,73 @@ FileDescriptorProto::~FileDescriptorProto() {
}
void FileDescriptorProto::SharedDtor() {
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
package_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
syntax_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- if (this != internal_default_instance()) {
- delete options_;
- }
- if (this != internal_default_instance()) {
- delete source_code_info_;
- }
+ if (this != internal_default_instance()) delete options_;
+ if (this != internal_default_instance()) delete source_code_info_;
}
+void FileDescriptorProto::ArenaDtor(void* object) {
+ FileDescriptorProto* _this = reinterpret_cast< FileDescriptorProto* >(object);
+ (void)_this;
+}
+void FileDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+}
void FileDescriptorProto::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* FileDescriptorProto::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[1].descriptor;
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const FileDescriptorProto& FileDescriptorProto::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorProto();
return *internal_default_instance();
}
FileDescriptorProto* FileDescriptorProto::New(::google::protobuf::Arena* arena) const {
- FileDescriptorProto* n = new FileDescriptorProto;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
+ return ::google::protobuf::Arena::CreateMessage<FileDescriptorProto>(arena);
}
void FileDescriptorProto::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.FileDescriptorProto)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
dependency_.Clear();
- public_dependency_.Clear();
- weak_dependency_.Clear();
message_type_.Clear();
enum_type_.Clear();
service_.Clear();
extension_.Clear();
- if (_has_bits_[0 / 32] & 31u) {
- if (has_name()) {
+ public_dependency_.Clear();
+ weak_dependency_.Clear();
+ cached_has_bits = _has_bits_[0];
+ if (cached_has_bits & 31u) {
+ if (cached_has_bits & 0x00000001u) {
GOOGLE_DCHECK(!name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- (*name_.UnsafeRawStringPointer())->clear();
+ name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- if (has_package()) {
+ if (cached_has_bits & 0x00000002u) {
GOOGLE_DCHECK(!package_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- (*package_.UnsafeRawStringPointer())->clear();
+ package_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- if (has_syntax()) {
+ if (cached_has_bits & 0x00000004u) {
GOOGLE_DCHECK(!syntax_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- (*syntax_.UnsafeRawStringPointer())->clear();
+ syntax_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- if (has_options()) {
+ if (cached_has_bits & 0x00000008u) {
GOOGLE_DCHECK(options_ != NULL);
- options_->::google::protobuf::FileOptions::Clear();
+ options_->Clear();
}
- if (has_source_code_info()) {
+ if (cached_has_bits & 0x00000010u) {
GOOGLE_DCHECK(source_code_info_ != NULL);
- source_code_info_->::google::protobuf::SourceCodeInfo::Clear();
+ source_code_info_->Clear();
}
}
_has_bits_.Clear();
@@ -1350,11 +2060,12 @@ bool FileDescriptorProto::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional string name = 1;
case 1: {
- if (tag == 10u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormat::PARSE,
"google.protobuf.FileDescriptorProto.name");
} else {
@@ -1365,11 +2076,12 @@ bool FileDescriptorProto::MergePartialFromCodedStream(
// optional string package = 2;
case 2: {
- if (tag == 18u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_package()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->package().data(), this->package().length(),
+ this->package().data(), static_cast<int>(this->package().length()),
::google::protobuf::internal::WireFormat::PARSE,
"google.protobuf.FileDescriptorProto.package");
} else {
@@ -1380,12 +2092,13 @@ bool FileDescriptorProto::MergePartialFromCodedStream(
// repeated string dependency = 3;
case 3: {
- if (tag == 26u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->add_dependency()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->dependency(this->dependency_size() - 1).data(),
- this->dependency(this->dependency_size() - 1).length(),
+ static_cast<int>(this->dependency(this->dependency_size() - 1).length()),
::google::protobuf::internal::WireFormat::PARSE,
"google.protobuf.FileDescriptorProto.dependency");
} else {
@@ -1396,60 +2109,53 @@ bool FileDescriptorProto::MergePartialFromCodedStream(
// repeated .google.protobuf.DescriptorProto message_type = 4;
case 4: {
- if (tag == 34u) {
- DO_(input->IncrementRecursionDepth());
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
- input, add_message_type()));
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_message_type()));
} else {
goto handle_unusual;
}
- input->UnsafeDecrementRecursionDepth();
break;
}
// repeated .google.protobuf.EnumDescriptorProto enum_type = 5;
case 5: {
- if (tag == 42u) {
- DO_(input->IncrementRecursionDepth());
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
- input, add_enum_type()));
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(42u /* 42 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_enum_type()));
} else {
goto handle_unusual;
}
- input->UnsafeDecrementRecursionDepth();
break;
}
// repeated .google.protobuf.ServiceDescriptorProto service = 6;
case 6: {
- if (tag == 50u) {
- DO_(input->IncrementRecursionDepth());
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
- input, add_service()));
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(50u /* 50 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_service()));
} else {
goto handle_unusual;
}
- input->UnsafeDecrementRecursionDepth();
break;
}
// repeated .google.protobuf.FieldDescriptorProto extension = 7;
case 7: {
- if (tag == 58u) {
- DO_(input->IncrementRecursionDepth());
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
- input, add_extension()));
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(58u /* 58 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_extension()));
} else {
goto handle_unusual;
}
- input->UnsafeDecrementRecursionDepth();
break;
}
// optional .google.protobuf.FileOptions options = 8;
case 8: {
- if (tag == 66u) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(66u /* 66 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_options()));
} else {
goto handle_unusual;
@@ -1459,8 +2165,9 @@ bool FileDescriptorProto::MergePartialFromCodedStream(
// optional .google.protobuf.SourceCodeInfo source_code_info = 9;
case 9: {
- if (tag == 74u) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(74u /* 74 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_source_code_info()));
} else {
goto handle_unusual;
@@ -1470,11 +2177,14 @@ bool FileDescriptorProto::MergePartialFromCodedStream(
// repeated int32 public_dependency = 10;
case 10: {
- if (tag == 80u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(80u /* 80 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
1, 80u, input, this->mutable_public_dependency())));
- } else if (tag == 82u) {
+ } else if (
+ static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(82u /* 82 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitiveNoInline<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, this->mutable_public_dependency())));
@@ -1486,11 +2196,14 @@ bool FileDescriptorProto::MergePartialFromCodedStream(
// repeated int32 weak_dependency = 11;
case 11: {
- if (tag == 88u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(88u /* 88 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
1, 88u, input, this->mutable_weak_dependency())));
- } else if (tag == 90u) {
+ } else if (
+ static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(90u /* 90 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitiveNoInline<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, this->mutable_weak_dependency())));
@@ -1502,11 +2215,12 @@ bool FileDescriptorProto::MergePartialFromCodedStream(
// optional string syntax = 12;
case 12: {
- if (tag == 98u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(98u /* 98 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_syntax()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->syntax().data(), this->syntax().length(),
+ this->syntax().data(), static_cast<int>(this->syntax().length()),
::google::protobuf::internal::WireFormat::PARSE,
"google.protobuf.FileDescriptorProto.syntax");
} else {
@@ -1517,13 +2231,11 @@ bool FileDescriptorProto::MergePartialFromCodedStream(
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
- input, tag, mutable_unknown_fields()));
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -1540,10 +2252,14 @@ failure:
void FileDescriptorProto::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.FileDescriptorProto)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional string name = 1;
- if (has_name()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.FileDescriptorProto.name");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -1551,9 +2267,9 @@ void FileDescriptorProto::SerializeWithCachedSizes(
}
// optional string package = 2;
- if (has_package()) {
+ if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->package().data(), this->package().length(),
+ this->package().data(), static_cast<int>(this->package().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.FileDescriptorProto.package");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -1561,9 +2277,9 @@ void FileDescriptorProto::SerializeWithCachedSizes(
}
// repeated string dependency = 3;
- for (int i = 0; i < this->dependency_size(); i++) {
+ for (int i = 0, n = this->dependency_size(); i < n; i++) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->dependency(i).data(), this->dependency(i).length(),
+ this->dependency(i).data(), static_cast<int>(this->dependency(i).length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.FileDescriptorProto.dependency");
::google::protobuf::internal::WireFormatLite::WriteString(
@@ -1571,57 +2287,61 @@ void FileDescriptorProto::SerializeWithCachedSizes(
}
// repeated .google.protobuf.DescriptorProto message_type = 4;
- for (unsigned int i = 0, n = this->message_type_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->message_type_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 4, this->message_type(i), output);
+ 4, this->message_type(static_cast<int>(i)), output);
}
// repeated .google.protobuf.EnumDescriptorProto enum_type = 5;
- for (unsigned int i = 0, n = this->enum_type_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->enum_type_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 5, this->enum_type(i), output);
+ 5, this->enum_type(static_cast<int>(i)), output);
}
// repeated .google.protobuf.ServiceDescriptorProto service = 6;
- for (unsigned int i = 0, n = this->service_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->service_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 6, this->service(i), output);
+ 6, this->service(static_cast<int>(i)), output);
}
// repeated .google.protobuf.FieldDescriptorProto extension = 7;
- for (unsigned int i = 0, n = this->extension_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->extension_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 7, this->extension(i), output);
+ 7, this->extension(static_cast<int>(i)), output);
}
// optional .google.protobuf.FileOptions options = 8;
- if (has_options()) {
+ if (cached_has_bits & 0x00000008u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
8, *this->options_, output);
}
// optional .google.protobuf.SourceCodeInfo source_code_info = 9;
- if (has_source_code_info()) {
+ if (cached_has_bits & 0x00000010u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
9, *this->source_code_info_, output);
}
// repeated int32 public_dependency = 10;
- for (int i = 0; i < this->public_dependency_size(); i++) {
+ for (int i = 0, n = this->public_dependency_size(); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteInt32(
10, this->public_dependency(i), output);
}
// repeated int32 weak_dependency = 11;
- for (int i = 0; i < this->weak_dependency_size(); i++) {
+ for (int i = 0, n = this->weak_dependency_size(); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteInt32(
11, this->weak_dependency(i), output);
}
// optional string syntax = 12;
- if (has_syntax()) {
+ if (cached_has_bits & 0x00000004u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->syntax().data(), this->syntax().length(),
+ this->syntax().data(), static_cast<int>(this->syntax().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.FileDescriptorProto.syntax");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -1630,7 +2350,7 @@ void FileDescriptorProto::SerializeWithCachedSizes(
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- unknown_fields(), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.FileDescriptorProto)
}
@@ -1639,10 +2359,14 @@ void FileDescriptorProto::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.FileDescriptorProto)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional string name = 1;
- if (has_name()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.FileDescriptorProto.name");
target =
@@ -1651,9 +2375,9 @@ void FileDescriptorProto::SerializeWithCachedSizes(
}
// optional string package = 2;
- if (has_package()) {
+ if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->package().data(), this->package().length(),
+ this->package().data(), static_cast<int>(this->package().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.FileDescriptorProto.package");
target =
@@ -1662,9 +2386,9 @@ void FileDescriptorProto::SerializeWithCachedSizes(
}
// repeated string dependency = 3;
- for (int i = 0; i < this->dependency_size(); i++) {
+ for (int i = 0, n = this->dependency_size(); i < n; i++) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->dependency(i).data(), this->dependency(i).length(),
+ this->dependency(i).data(), static_cast<int>(this->dependency(i).length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.FileDescriptorProto.dependency");
target = ::google::protobuf::internal::WireFormatLite::
@@ -1672,63 +2396,63 @@ void FileDescriptorProto::SerializeWithCachedSizes(
}
// repeated .google.protobuf.DescriptorProto message_type = 4;
- for (unsigned int i = 0, n = this->message_type_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->message_type_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 4, this->message_type(i), false, target);
+ InternalWriteMessageToArray(
+ 4, this->message_type(static_cast<int>(i)), deterministic, target);
}
// repeated .google.protobuf.EnumDescriptorProto enum_type = 5;
- for (unsigned int i = 0, n = this->enum_type_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->enum_type_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 5, this->enum_type(i), false, target);
+ InternalWriteMessageToArray(
+ 5, this->enum_type(static_cast<int>(i)), deterministic, target);
}
// repeated .google.protobuf.ServiceDescriptorProto service = 6;
- for (unsigned int i = 0, n = this->service_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->service_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 6, this->service(i), false, target);
+ InternalWriteMessageToArray(
+ 6, this->service(static_cast<int>(i)), deterministic, target);
}
// repeated .google.protobuf.FieldDescriptorProto extension = 7;
- for (unsigned int i = 0, n = this->extension_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->extension_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 7, this->extension(i), false, target);
+ InternalWriteMessageToArray(
+ 7, this->extension(static_cast<int>(i)), deterministic, target);
}
// optional .google.protobuf.FileOptions options = 8;
- if (has_options()) {
+ if (cached_has_bits & 0x00000008u) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 8, *this->options_, false, target);
+ InternalWriteMessageToArray(
+ 8, *this->options_, deterministic, target);
}
// optional .google.protobuf.SourceCodeInfo source_code_info = 9;
- if (has_source_code_info()) {
+ if (cached_has_bits & 0x00000010u) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 9, *this->source_code_info_, false, target);
+ InternalWriteMessageToArray(
+ 9, *this->source_code_info_, deterministic, target);
}
// repeated int32 public_dependency = 10;
- for (int i = 0; i < this->public_dependency_size(); i++) {
- target = ::google::protobuf::internal::WireFormatLite::
- WriteInt32ToArray(10, this->public_dependency(i), target);
- }
+ target = ::google::protobuf::internal::WireFormatLite::
+ WriteInt32ToArray(10, this->public_dependency_, target);
// repeated int32 weak_dependency = 11;
- for (int i = 0; i < this->weak_dependency_size(); i++) {
- target = ::google::protobuf::internal::WireFormatLite::
- WriteInt32ToArray(11, this->weak_dependency(i), target);
- }
+ target = ::google::protobuf::internal::WireFormatLite::
+ WriteInt32ToArray(11, this->weak_dependency_, target);
// optional string syntax = 12;
- if (has_syntax()) {
+ if (cached_has_bits & 0x00000004u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->syntax().data(), this->syntax().length(),
+ this->syntax().data(), static_cast<int>(this->syntax().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.FileDescriptorProto.syntax");
target =
@@ -1738,7 +2462,7 @@ void FileDescriptorProto::SerializeWithCachedSizes(
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- unknown_fields(), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.FileDescriptorProto)
return target;
@@ -1751,86 +2475,78 @@ size_t FileDescriptorProto::ByteSizeLong() const {
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- unknown_fields());
+ _internal_metadata_.unknown_fields());
}
// repeated string dependency = 3;
total_size += 1 *
::google::protobuf::internal::FromIntSize(this->dependency_size());
- for (int i = 0; i < this->dependency_size(); i++) {
+ for (int i = 0, n = this->dependency_size(); i < n; i++) {
total_size += ::google::protobuf::internal::WireFormatLite::StringSize(
this->dependency(i));
}
- // repeated int32 public_dependency = 10;
- {
- size_t data_size = 0;
- unsigned int count = this->public_dependency_size();
- for (unsigned int i = 0; i < count; i++) {
- data_size += ::google::protobuf::internal::WireFormatLite::
- Int32Size(this->public_dependency(i));
- }
- total_size += 1 *
- ::google::protobuf::internal::FromIntSize(this->public_dependency_size());
- total_size += data_size;
- }
-
- // repeated int32 weak_dependency = 11;
- {
- size_t data_size = 0;
- unsigned int count = this->weak_dependency_size();
- for (unsigned int i = 0; i < count; i++) {
- data_size += ::google::protobuf::internal::WireFormatLite::
- Int32Size(this->weak_dependency(i));
- }
- total_size += 1 *
- ::google::protobuf::internal::FromIntSize(this->weak_dependency_size());
- total_size += data_size;
- }
-
// repeated .google.protobuf.DescriptorProto message_type = 4;
{
- unsigned int count = this->message_type_size();
+ unsigned int count = static_cast<unsigned int>(this->message_type_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->message_type(i));
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->message_type(static_cast<int>(i)));
}
}
// repeated .google.protobuf.EnumDescriptorProto enum_type = 5;
{
- unsigned int count = this->enum_type_size();
+ unsigned int count = static_cast<unsigned int>(this->enum_type_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->enum_type(i));
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->enum_type(static_cast<int>(i)));
}
}
// repeated .google.protobuf.ServiceDescriptorProto service = 6;
{
- unsigned int count = this->service_size();
+ unsigned int count = static_cast<unsigned int>(this->service_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->service(i));
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->service(static_cast<int>(i)));
}
}
// repeated .google.protobuf.FieldDescriptorProto extension = 7;
{
- unsigned int count = this->extension_size();
+ unsigned int count = static_cast<unsigned int>(this->extension_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->extension(i));
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->extension(static_cast<int>(i)));
}
}
+ // repeated int32 public_dependency = 10;
+ {
+ size_t data_size = ::google::protobuf::internal::WireFormatLite::
+ Int32Size(this->public_dependency_);
+ total_size += 1 *
+ ::google::protobuf::internal::FromIntSize(this->public_dependency_size());
+ total_size += data_size;
+ }
+
+ // repeated int32 weak_dependency = 11;
+ {
+ size_t data_size = ::google::protobuf::internal::WireFormatLite::
+ Int32Size(this->weak_dependency_);
+ total_size += 1 *
+ ::google::protobuf::internal::FromIntSize(this->weak_dependency_size());
+ total_size += data_size;
+ }
+
if (_has_bits_[0 / 32] & 31u) {
// optional string name = 1;
if (has_name()) {
@@ -1856,14 +2572,14 @@ size_t FileDescriptorProto::ByteSizeLong() const {
// optional .google.protobuf.FileOptions options = 8;
if (has_options()) {
total_size += 1 +
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
*this->options_);
}
// optional .google.protobuf.SourceCodeInfo source_code_info = 9;
if (has_source_code_info()) {
total_size += 1 +
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
*this->source_code_info_);
}
@@ -1894,30 +2610,31 @@ void FileDescriptorProto::MergeFrom(const FileDescriptorProto& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.FileDescriptorProto)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
dependency_.MergeFrom(from.dependency_);
- public_dependency_.MergeFrom(from.public_dependency_);
- weak_dependency_.MergeFrom(from.weak_dependency_);
message_type_.MergeFrom(from.message_type_);
enum_type_.MergeFrom(from.enum_type_);
service_.MergeFrom(from.service_);
extension_.MergeFrom(from.extension_);
- if (from._has_bits_[0 / 32] & 31u) {
- if (from.has_name()) {
- set_has_name();
- name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_);
+ public_dependency_.MergeFrom(from.public_dependency_);
+ weak_dependency_.MergeFrom(from.weak_dependency_);
+ cached_has_bits = from._has_bits_[0];
+ if (cached_has_bits & 31u) {
+ if (cached_has_bits & 0x00000001u) {
+ set_name(from.name());
}
- if (from.has_package()) {
- set_has_package();
- package_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.package_);
+ if (cached_has_bits & 0x00000002u) {
+ set_package(from.package());
}
- if (from.has_syntax()) {
- set_has_syntax();
- syntax_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.syntax_);
+ if (cached_has_bits & 0x00000004u) {
+ set_syntax(from.syntax());
}
- if (from.has_options()) {
+ if (cached_has_bits & 0x00000008u) {
mutable_options()->::google::protobuf::FileOptions::MergeFrom(from.options());
}
- if (from.has_source_code_info()) {
+ if (cached_has_bits & 0x00000010u) {
mutable_source_code_info()->::google::protobuf::SourceCodeInfo::MergeFrom(from.source_code_info());
}
}
@@ -1950,554 +2667,115 @@ bool FileDescriptorProto::IsInitialized() const {
void FileDescriptorProto::Swap(FileDescriptorProto* other) {
if (other == this) return;
+ if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ InternalSwap(other);
+ } else {
+ FileDescriptorProto* temp = New(GetArenaNoVirtual());
+ temp->MergeFrom(*other);
+ other->CopyFrom(*this);
+ InternalSwap(temp);
+ if (GetArenaNoVirtual() == NULL) {
+ delete temp;
+ }
+ }
+}
+void FileDescriptorProto::UnsafeArenaSwap(FileDescriptorProto* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void FileDescriptorProto::InternalSwap(FileDescriptorProto* other) {
- dependency_.UnsafeArenaSwap(&other->dependency_);
- public_dependency_.UnsafeArenaSwap(&other->public_dependency_);
- weak_dependency_.UnsafeArenaSwap(&other->weak_dependency_);
- message_type_.UnsafeArenaSwap(&other->message_type_);
- enum_type_.UnsafeArenaSwap(&other->enum_type_);
- service_.UnsafeArenaSwap(&other->service_);
- extension_.UnsafeArenaSwap(&other->extension_);
+ using std::swap;
+ dependency_.InternalSwap(&other->dependency_);
+ message_type_.InternalSwap(&other->message_type_);
+ enum_type_.InternalSwap(&other->enum_type_);
+ service_.InternalSwap(&other->service_);
+ extension_.InternalSwap(&other->extension_);
+ public_dependency_.InternalSwap(&other->public_dependency_);
+ weak_dependency_.InternalSwap(&other->weak_dependency_);
name_.Swap(&other->name_);
package_.Swap(&other->package_);
syntax_.Swap(&other->syntax_);
- std::swap(options_, other->options_);
- std::swap(source_code_info_, other->source_code_info_);
- std::swap(_has_bits_[0], other->_has_bits_[0]);
+ swap(options_, other->options_);
+ swap(source_code_info_, other->source_code_info_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- std::swap(_cached_size_, other->_cached_size_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata FileDescriptorProto::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[1];
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// FileDescriptorProto
-// optional string name = 1;
-bool FileDescriptorProto::has_name() const {
- return (_has_bits_[0] & 0x00000001u) != 0;
-}
-void FileDescriptorProto::set_has_name() {
- _has_bits_[0] |= 0x00000001u;
-}
-void FileDescriptorProto::clear_has_name() {
- _has_bits_[0] &= ~0x00000001u;
-}
-void FileDescriptorProto::clear_name() {
- name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_name();
-}
-const ::std::string& FileDescriptorProto::name() const {
- // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.name)
- return name_.GetNoArena();
-}
-void FileDescriptorProto::set_name(const ::std::string& value) {
- set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.FileDescriptorProto.name)
-}
-void FileDescriptorProto::set_name(const char* value) {
- set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.FileDescriptorProto.name)
-}
-void FileDescriptorProto::set_name(const char* value, size_t size) {
- set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.FileDescriptorProto.name)
-}
-::std::string* FileDescriptorProto::mutable_name() {
- set_has_name();
- // @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.name)
- return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* FileDescriptorProto::release_name() {
- // @@protoc_insertion_point(field_release:google.protobuf.FileDescriptorProto.name)
- clear_has_name();
- return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void FileDescriptorProto::set_allocated_name(::std::string* name) {
- if (name != NULL) {
- set_has_name();
- } else {
- clear_has_name();
- }
- name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileDescriptorProto.name)
-}
-
-// optional string package = 2;
-bool FileDescriptorProto::has_package() const {
- return (_has_bits_[0] & 0x00000002u) != 0;
-}
-void FileDescriptorProto::set_has_package() {
- _has_bits_[0] |= 0x00000002u;
-}
-void FileDescriptorProto::clear_has_package() {
- _has_bits_[0] &= ~0x00000002u;
-}
-void FileDescriptorProto::clear_package() {
- package_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_package();
-}
-const ::std::string& FileDescriptorProto::package() const {
- // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.package)
- return package_.GetNoArena();
-}
-void FileDescriptorProto::set_package(const ::std::string& value) {
- set_has_package();
- package_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.FileDescriptorProto.package)
-}
-void FileDescriptorProto::set_package(const char* value) {
- set_has_package();
- package_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.FileDescriptorProto.package)
-}
-void FileDescriptorProto::set_package(const char* value, size_t size) {
- set_has_package();
- package_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.FileDescriptorProto.package)
-}
-::std::string* FileDescriptorProto::mutable_package() {
- set_has_package();
- // @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.package)
- return package_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* FileDescriptorProto::release_package() {
- // @@protoc_insertion_point(field_release:google.protobuf.FileDescriptorProto.package)
- clear_has_package();
- return package_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void FileDescriptorProto::set_allocated_package(::std::string* package) {
- if (package != NULL) {
- set_has_package();
- } else {
- clear_has_package();
- }
- package_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), package);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileDescriptorProto.package)
-}
-
-// repeated string dependency = 3;
-int FileDescriptorProto::dependency_size() const {
- return dependency_.size();
-}
-void FileDescriptorProto::clear_dependency() {
- dependency_.Clear();
-}
-const ::std::string& FileDescriptorProto::dependency(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.dependency)
- return dependency_.Get(index);
-}
-::std::string* FileDescriptorProto::mutable_dependency(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.dependency)
- return dependency_.Mutable(index);
-}
-void FileDescriptorProto::set_dependency(int index, const ::std::string& value) {
- // @@protoc_insertion_point(field_set:google.protobuf.FileDescriptorProto.dependency)
- dependency_.Mutable(index)->assign(value);
-}
-void FileDescriptorProto::set_dependency(int index, const char* value) {
- dependency_.Mutable(index)->assign(value);
- // @@protoc_insertion_point(field_set_char:google.protobuf.FileDescriptorProto.dependency)
-}
-void FileDescriptorProto::set_dependency(int index, const char* value, size_t size) {
- dependency_.Mutable(index)->assign(
- reinterpret_cast<const char*>(value), size);
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.FileDescriptorProto.dependency)
-}
-::std::string* FileDescriptorProto::add_dependency() {
- // @@protoc_insertion_point(field_add_mutable:google.protobuf.FileDescriptorProto.dependency)
- return dependency_.Add();
-}
-void FileDescriptorProto::add_dependency(const ::std::string& value) {
- dependency_.Add()->assign(value);
- // @@protoc_insertion_point(field_add:google.protobuf.FileDescriptorProto.dependency)
-}
-void FileDescriptorProto::add_dependency(const char* value) {
- dependency_.Add()->assign(value);
- // @@protoc_insertion_point(field_add_char:google.protobuf.FileDescriptorProto.dependency)
-}
-void FileDescriptorProto::add_dependency(const char* value, size_t size) {
- dependency_.Add()->assign(reinterpret_cast<const char*>(value), size);
- // @@protoc_insertion_point(field_add_pointer:google.protobuf.FileDescriptorProto.dependency)
-}
-const ::google::protobuf::RepeatedPtrField< ::std::string>&
-FileDescriptorProto::dependency() const {
- // @@protoc_insertion_point(field_list:google.protobuf.FileDescriptorProto.dependency)
- return dependency_;
-}
-::google::protobuf::RepeatedPtrField< ::std::string>*
-FileDescriptorProto::mutable_dependency() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.FileDescriptorProto.dependency)
- return &dependency_;
-}
-
-// repeated int32 public_dependency = 10;
-int FileDescriptorProto::public_dependency_size() const {
- return public_dependency_.size();
-}
-void FileDescriptorProto::clear_public_dependency() {
- public_dependency_.Clear();
-}
-::google::protobuf::int32 FileDescriptorProto::public_dependency(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.public_dependency)
- return public_dependency_.Get(index);
-}
-void FileDescriptorProto::set_public_dependency(int index, ::google::protobuf::int32 value) {
- public_dependency_.Set(index, value);
- // @@protoc_insertion_point(field_set:google.protobuf.FileDescriptorProto.public_dependency)
-}
-void FileDescriptorProto::add_public_dependency(::google::protobuf::int32 value) {
- public_dependency_.Add(value);
- // @@protoc_insertion_point(field_add:google.protobuf.FileDescriptorProto.public_dependency)
-}
-const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >&
-FileDescriptorProto::public_dependency() const {
- // @@protoc_insertion_point(field_list:google.protobuf.FileDescriptorProto.public_dependency)
- return public_dependency_;
-}
-::google::protobuf::RepeatedField< ::google::protobuf::int32 >*
-FileDescriptorProto::mutable_public_dependency() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.FileDescriptorProto.public_dependency)
- return &public_dependency_;
-}
-
-// repeated int32 weak_dependency = 11;
-int FileDescriptorProto::weak_dependency_size() const {
- return weak_dependency_.size();
-}
-void FileDescriptorProto::clear_weak_dependency() {
- weak_dependency_.Clear();
-}
-::google::protobuf::int32 FileDescriptorProto::weak_dependency(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.weak_dependency)
- return weak_dependency_.Get(index);
-}
-void FileDescriptorProto::set_weak_dependency(int index, ::google::protobuf::int32 value) {
- weak_dependency_.Set(index, value);
- // @@protoc_insertion_point(field_set:google.protobuf.FileDescriptorProto.weak_dependency)
-}
-void FileDescriptorProto::add_weak_dependency(::google::protobuf::int32 value) {
- weak_dependency_.Add(value);
- // @@protoc_insertion_point(field_add:google.protobuf.FileDescriptorProto.weak_dependency)
-}
-const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >&
-FileDescriptorProto::weak_dependency() const {
- // @@protoc_insertion_point(field_list:google.protobuf.FileDescriptorProto.weak_dependency)
- return weak_dependency_;
-}
-::google::protobuf::RepeatedField< ::google::protobuf::int32 >*
-FileDescriptorProto::mutable_weak_dependency() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.FileDescriptorProto.weak_dependency)
- return &weak_dependency_;
-}
-
-// repeated .google.protobuf.DescriptorProto message_type = 4;
-int FileDescriptorProto::message_type_size() const {
- return message_type_.size();
-}
-void FileDescriptorProto::clear_message_type() {
- message_type_.Clear();
-}
-const ::google::protobuf::DescriptorProto& FileDescriptorProto::message_type(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.message_type)
- return message_type_.Get(index);
-}
-::google::protobuf::DescriptorProto* FileDescriptorProto::mutable_message_type(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.message_type)
- return message_type_.Mutable(index);
-}
-::google::protobuf::DescriptorProto* FileDescriptorProto::add_message_type() {
- // @@protoc_insertion_point(field_add:google.protobuf.FileDescriptorProto.message_type)
- return message_type_.Add();
-}
-::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto >*
-FileDescriptorProto::mutable_message_type() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.FileDescriptorProto.message_type)
- return &message_type_;
-}
-const ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto >&
-FileDescriptorProto::message_type() const {
- // @@protoc_insertion_point(field_list:google.protobuf.FileDescriptorProto.message_type)
- return message_type_;
-}
-
-// repeated .google.protobuf.EnumDescriptorProto enum_type = 5;
-int FileDescriptorProto::enum_type_size() const {
- return enum_type_.size();
-}
-void FileDescriptorProto::clear_enum_type() {
- enum_type_.Clear();
-}
-const ::google::protobuf::EnumDescriptorProto& FileDescriptorProto::enum_type(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.enum_type)
- return enum_type_.Get(index);
-}
-::google::protobuf::EnumDescriptorProto* FileDescriptorProto::mutable_enum_type(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.enum_type)
- return enum_type_.Mutable(index);
-}
-::google::protobuf::EnumDescriptorProto* FileDescriptorProto::add_enum_type() {
- // @@protoc_insertion_point(field_add:google.protobuf.FileDescriptorProto.enum_type)
- return enum_type_.Add();
-}
-::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto >*
-FileDescriptorProto::mutable_enum_type() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.FileDescriptorProto.enum_type)
- return &enum_type_;
-}
-const ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto >&
-FileDescriptorProto::enum_type() const {
- // @@protoc_insertion_point(field_list:google.protobuf.FileDescriptorProto.enum_type)
- return enum_type_;
-}
-
-// repeated .google.protobuf.ServiceDescriptorProto service = 6;
-int FileDescriptorProto::service_size() const {
- return service_.size();
-}
-void FileDescriptorProto::clear_service() {
- service_.Clear();
-}
-const ::google::protobuf::ServiceDescriptorProto& FileDescriptorProto::service(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.service)
- return service_.Get(index);
-}
-::google::protobuf::ServiceDescriptorProto* FileDescriptorProto::mutable_service(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.service)
- return service_.Mutable(index);
-}
-::google::protobuf::ServiceDescriptorProto* FileDescriptorProto::add_service() {
- // @@protoc_insertion_point(field_add:google.protobuf.FileDescriptorProto.service)
- return service_.Add();
-}
-::google::protobuf::RepeatedPtrField< ::google::protobuf::ServiceDescriptorProto >*
-FileDescriptorProto::mutable_service() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.FileDescriptorProto.service)
- return &service_;
-}
-const ::google::protobuf::RepeatedPtrField< ::google::protobuf::ServiceDescriptorProto >&
-FileDescriptorProto::service() const {
- // @@protoc_insertion_point(field_list:google.protobuf.FileDescriptorProto.service)
- return service_;
-}
-
-// repeated .google.protobuf.FieldDescriptorProto extension = 7;
-int FileDescriptorProto::extension_size() const {
- return extension_.size();
-}
-void FileDescriptorProto::clear_extension() {
- extension_.Clear();
-}
-const ::google::protobuf::FieldDescriptorProto& FileDescriptorProto::extension(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.extension)
- return extension_.Get(index);
-}
-::google::protobuf::FieldDescriptorProto* FileDescriptorProto::mutable_extension(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.extension)
- return extension_.Mutable(index);
-}
-::google::protobuf::FieldDescriptorProto* FileDescriptorProto::add_extension() {
- // @@protoc_insertion_point(field_add:google.protobuf.FileDescriptorProto.extension)
- return extension_.Add();
-}
-::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >*
-FileDescriptorProto::mutable_extension() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.FileDescriptorProto.extension)
- return &extension_;
-}
-const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >&
-FileDescriptorProto::extension() const {
- // @@protoc_insertion_point(field_list:google.protobuf.FileDescriptorProto.extension)
- return extension_;
-}
+// ===================================================================
-// optional .google.protobuf.FileOptions options = 8;
-bool FileDescriptorProto::has_options() const {
- return (_has_bits_[0] & 0x00000008u) != 0;
-}
-void FileDescriptorProto::set_has_options() {
- _has_bits_[0] |= 0x00000008u;
-}
-void FileDescriptorProto::clear_has_options() {
- _has_bits_[0] &= ~0x00000008u;
+void DescriptorProto_ExtensionRange::InitAsDefaultInstance() {
+ ::google::protobuf::_DescriptorProto_ExtensionRange_default_instance_._instance.get_mutable()->options_ = const_cast< ::google::protobuf::ExtensionRangeOptions*>(
+ ::google::protobuf::ExtensionRangeOptions::internal_default_instance());
}
-void FileDescriptorProto::clear_options() {
- if (options_ != NULL) options_->::google::protobuf::FileOptions::Clear();
- clear_has_options();
+void DescriptorProto_ExtensionRange::_slow_mutable_options() {
+ options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::ExtensionRangeOptions >(
+ GetArenaNoVirtual());
}
-const ::google::protobuf::FileOptions& FileDescriptorProto::options() const {
- // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.options)
- return options_ != NULL ? *options_
- : *::google::protobuf::FileOptions::internal_default_instance();
-}
-::google::protobuf::FileOptions* FileDescriptorProto::mutable_options() {
- set_has_options();
- if (options_ == NULL) {
- options_ = new ::google::protobuf::FileOptions;
+void DescriptorProto_ExtensionRange::unsafe_arena_set_allocated_options(
+ ::google::protobuf::ExtensionRangeOptions* options) {
+ if (GetArenaNoVirtual() == NULL) {
+ delete options_;
}
- // @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.options)
- return options_;
-}
-::google::protobuf::FileOptions* FileDescriptorProto::release_options() {
- // @@protoc_insertion_point(field_release:google.protobuf.FileDescriptorProto.options)
- clear_has_options();
- ::google::protobuf::FileOptions* temp = options_;
- options_ = NULL;
- return temp;
-}
-void FileDescriptorProto::set_allocated_options(::google::protobuf::FileOptions* options) {
- delete options_;
options_ = options;
if (options) {
set_has_options();
} else {
clear_has_options();
}
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileDescriptorProto.options)
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.DescriptorProto.ExtensionRange.options)
}
-
-// optional .google.protobuf.SourceCodeInfo source_code_info = 9;
-bool FileDescriptorProto::has_source_code_info() const {
- return (_has_bits_[0] & 0x00000010u) != 0;
-}
-void FileDescriptorProto::set_has_source_code_info() {
- _has_bits_[0] |= 0x00000010u;
-}
-void FileDescriptorProto::clear_has_source_code_info() {
- _has_bits_[0] &= ~0x00000010u;
-}
-void FileDescriptorProto::clear_source_code_info() {
- if (source_code_info_ != NULL) source_code_info_->::google::protobuf::SourceCodeInfo::Clear();
- clear_has_source_code_info();
-}
-const ::google::protobuf::SourceCodeInfo& FileDescriptorProto::source_code_info() const {
- // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.source_code_info)
- return source_code_info_ != NULL ? *source_code_info_
- : *::google::protobuf::SourceCodeInfo::internal_default_instance();
-}
-::google::protobuf::SourceCodeInfo* FileDescriptorProto::mutable_source_code_info() {
- set_has_source_code_info();
- if (source_code_info_ == NULL) {
- source_code_info_ = new ::google::protobuf::SourceCodeInfo;
- }
- // @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.source_code_info)
- return source_code_info_;
-}
-::google::protobuf::SourceCodeInfo* FileDescriptorProto::release_source_code_info() {
- // @@protoc_insertion_point(field_release:google.protobuf.FileDescriptorProto.source_code_info)
- clear_has_source_code_info();
- ::google::protobuf::SourceCodeInfo* temp = source_code_info_;
- source_code_info_ = NULL;
- return temp;
-}
-void FileDescriptorProto::set_allocated_source_code_info(::google::protobuf::SourceCodeInfo* source_code_info) {
- delete source_code_info_;
- source_code_info_ = source_code_info;
- if (source_code_info) {
- set_has_source_code_info();
- } else {
- clear_has_source_code_info();
- }
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileDescriptorProto.source_code_info)
-}
-
-// optional string syntax = 12;
-bool FileDescriptorProto::has_syntax() const {
- return (_has_bits_[0] & 0x00000004u) != 0;
-}
-void FileDescriptorProto::set_has_syntax() {
- _has_bits_[0] |= 0x00000004u;
-}
-void FileDescriptorProto::clear_has_syntax() {
- _has_bits_[0] &= ~0x00000004u;
-}
-void FileDescriptorProto::clear_syntax() {
- syntax_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_syntax();
-}
-const ::std::string& FileDescriptorProto::syntax() const {
- // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.syntax)
- return syntax_.GetNoArena();
-}
-void FileDescriptorProto::set_syntax(const ::std::string& value) {
- set_has_syntax();
- syntax_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.FileDescriptorProto.syntax)
-}
-void FileDescriptorProto::set_syntax(const char* value) {
- set_has_syntax();
- syntax_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.FileDescriptorProto.syntax)
-}
-void FileDescriptorProto::set_syntax(const char* value, size_t size) {
- set_has_syntax();
- syntax_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.FileDescriptorProto.syntax)
-}
-::std::string* FileDescriptorProto::mutable_syntax() {
- set_has_syntax();
- // @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.syntax)
- return syntax_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* FileDescriptorProto::release_syntax() {
- // @@protoc_insertion_point(field_release:google.protobuf.FileDescriptorProto.syntax)
- clear_has_syntax();
- return syntax_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void FileDescriptorProto::set_allocated_syntax(::std::string* syntax) {
- if (syntax != NULL) {
- set_has_syntax();
- } else {
- clear_has_syntax();
- }
- syntax_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), syntax);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileDescriptorProto.syntax)
-}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
-
-// ===================================================================
-
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int DescriptorProto_ExtensionRange::kStartFieldNumber;
const int DescriptorProto_ExtensionRange::kEndFieldNumber;
+const int DescriptorProto_ExtensionRange::kOptionsFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
DescriptorProto_ExtensionRange::DescriptorProto_ExtensionRange()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ExtensionRange();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.DescriptorProto.ExtensionRange)
}
+DescriptorProto_ExtensionRange::DescriptorProto_ExtensionRange(::google::protobuf::Arena* arena)
+ : ::google::protobuf::Message(),
+ _internal_metadata_(arena) {
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ExtensionRange();
+ SharedCtor();
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.DescriptorProto.ExtensionRange)
+}
DescriptorProto_ExtensionRange::DescriptorProto_ExtensionRange(const DescriptorProto_ExtensionRange& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
_cached_size_(0) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ if (from.has_options()) {
+ options_ = new ::google::protobuf::ExtensionRangeOptions(*from.options_);
+ } else {
+ options_ = NULL;
+ }
::memcpy(&start_, &from.start_,
- reinterpret_cast<char*>(&end_) -
- reinterpret_cast<char*>(&start_) + sizeof(end_));
+ static_cast<size_t>(reinterpret_cast<char*>(&end_) -
+ reinterpret_cast<char*>(&start_)) + sizeof(end_));
// @@protoc_insertion_point(copy_constructor:google.protobuf.DescriptorProto.ExtensionRange)
}
void DescriptorProto_ExtensionRange::SharedCtor() {
_cached_size_ = 0;
- ::memset(&start_, 0, reinterpret_cast<char*>(&end_) -
- reinterpret_cast<char*>(&start_) + sizeof(end_));
+ ::memset(&options_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&end_) -
+ reinterpret_cast<char*>(&options_)) + sizeof(end_));
}
DescriptorProto_ExtensionRange::~DescriptorProto_ExtensionRange() {
@@ -2506,36 +2784,50 @@ DescriptorProto_ExtensionRange::~DescriptorProto_ExtensionRange() {
}
void DescriptorProto_ExtensionRange::SharedDtor() {
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
+ if (this != internal_default_instance()) delete options_;
}
+void DescriptorProto_ExtensionRange::ArenaDtor(void* object) {
+ DescriptorProto_ExtensionRange* _this = reinterpret_cast< DescriptorProto_ExtensionRange* >(object);
+ (void)_this;
+}
+void DescriptorProto_ExtensionRange::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+}
void DescriptorProto_ExtensionRange::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* DescriptorProto_ExtensionRange::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[2].descriptor;
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const DescriptorProto_ExtensionRange& DescriptorProto_ExtensionRange::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ExtensionRange();
return *internal_default_instance();
}
DescriptorProto_ExtensionRange* DescriptorProto_ExtensionRange::New(::google::protobuf::Arena* arena) const {
- DescriptorProto_ExtensionRange* n = new DescriptorProto_ExtensionRange;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
+ return ::google::protobuf::Arena::CreateMessage<DescriptorProto_ExtensionRange>(arena);
}
void DescriptorProto_ExtensionRange::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.DescriptorProto.ExtensionRange)
- if (_has_bits_[0 / 32] & 3u) {
- ::memset(&start_, 0, reinterpret_cast<char*>(&end_) -
- reinterpret_cast<char*>(&start_) + sizeof(end_));
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
+ if (cached_has_bits & 0x00000001u) {
+ GOOGLE_DCHECK(options_ != NULL);
+ options_->Clear();
+ }
+ if (cached_has_bits & 6u) {
+ ::memset(&start_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&end_) -
+ reinterpret_cast<char*>(&start_)) + sizeof(end_));
}
_has_bits_.Clear();
_internal_metadata_.Clear();
@@ -2553,7 +2845,8 @@ bool DescriptorProto_ExtensionRange::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional int32 start = 1;
case 1: {
- if (tag == 8u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
set_has_start();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
@@ -2566,7 +2859,8 @@ bool DescriptorProto_ExtensionRange::MergePartialFromCodedStream(
// optional int32 end = 2;
case 2: {
- if (tag == 16u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
set_has_end();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
@@ -2577,15 +2871,25 @@ bool DescriptorProto_ExtensionRange::MergePartialFromCodedStream(
break;
}
+ // optional .google.protobuf.ExtensionRangeOptions options = 3;
+ case 3: {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
+ input, mutable_options()));
+ } else {
+ goto handle_unusual;
+ }
+ break;
+ }
+
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
- input, tag, mutable_unknown_fields()));
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -2602,19 +2906,29 @@ failure:
void DescriptorProto_ExtensionRange::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.DescriptorProto.ExtensionRange)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional int32 start = 1;
- if (has_start()) {
+ if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->start(), output);
}
// optional int32 end = 2;
- if (has_end()) {
+ if (cached_has_bits & 0x00000004u) {
::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->end(), output);
}
+ // optional .google.protobuf.ExtensionRangeOptions options = 3;
+ if (cached_has_bits & 0x00000001u) {
+ ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
+ 3, *this->options_, output);
+ }
+
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- unknown_fields(), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.DescriptorProto.ExtensionRange)
}
@@ -2623,19 +2937,30 @@ void DescriptorProto_ExtensionRange::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.DescriptorProto.ExtensionRange)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional int32 start = 1;
- if (has_start()) {
+ if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->start(), target);
}
// optional int32 end = 2;
- if (has_end()) {
+ if (cached_has_bits & 0x00000004u) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->end(), target);
}
+ // optional .google.protobuf.ExtensionRangeOptions options = 3;
+ if (cached_has_bits & 0x00000001u) {
+ target = ::google::protobuf::internal::WireFormatLite::
+ InternalWriteMessageToArray(
+ 3, *this->options_, deterministic, target);
+ }
+
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- unknown_fields(), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.DescriptorProto.ExtensionRange)
return target;
@@ -2648,9 +2973,16 @@ size_t DescriptorProto_ExtensionRange::ByteSizeLong() const {
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- unknown_fields());
+ _internal_metadata_.unknown_fields());
}
- if (_has_bits_[0 / 32] & 3u) {
+ if (_has_bits_[0 / 32] & 7u) {
+ // optional .google.protobuf.ExtensionRangeOptions options = 3;
+ if (has_options()) {
+ total_size += 1 +
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ *this->options_);
+ }
+
// optional int32 start = 1;
if (has_start()) {
total_size += 1 +
@@ -2692,13 +3024,21 @@ void DescriptorProto_ExtensionRange::MergeFrom(const DescriptorProto_ExtensionRa
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.DescriptorProto.ExtensionRange)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
- if (from._has_bits_[0 / 32] & 3u) {
- if (from.has_start()) {
- set_start(from.start());
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = from._has_bits_[0];
+ if (cached_has_bits & 7u) {
+ if (cached_has_bits & 0x00000001u) {
+ mutable_options()->::google::protobuf::ExtensionRangeOptions::MergeFrom(from.options());
}
- if (from.has_end()) {
- set_end(from.end());
+ if (cached_has_bits & 0x00000002u) {
+ start_ = from.start_;
}
+ if (cached_has_bits & 0x00000004u) {
+ end_ = from.end_;
+ }
+ _has_bits_[0] |= cached_has_bits;
}
}
@@ -2717,81 +3057,51 @@ void DescriptorProto_ExtensionRange::CopyFrom(const DescriptorProto_ExtensionRan
}
bool DescriptorProto_ExtensionRange::IsInitialized() const {
+ if (has_options()) {
+ if (!this->options_->IsInitialized()) return false;
+ }
return true;
}
void DescriptorProto_ExtensionRange::Swap(DescriptorProto_ExtensionRange* other) {
if (other == this) return;
+ if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ InternalSwap(other);
+ } else {
+ DescriptorProto_ExtensionRange* temp = New(GetArenaNoVirtual());
+ temp->MergeFrom(*other);
+ other->CopyFrom(*this);
+ InternalSwap(temp);
+ if (GetArenaNoVirtual() == NULL) {
+ delete temp;
+ }
+ }
+}
+void DescriptorProto_ExtensionRange::UnsafeArenaSwap(DescriptorProto_ExtensionRange* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void DescriptorProto_ExtensionRange::InternalSwap(DescriptorProto_ExtensionRange* other) {
- std::swap(start_, other->start_);
- std::swap(end_, other->end_);
- std::swap(_has_bits_[0], other->_has_bits_[0]);
+ using std::swap;
+ swap(options_, other->options_);
+ swap(start_, other->start_);
+ swap(end_, other->end_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- std::swap(_cached_size_, other->_cached_size_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata DescriptorProto_ExtensionRange::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[2];
-}
-
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// DescriptorProto_ExtensionRange
-
-// optional int32 start = 1;
-bool DescriptorProto_ExtensionRange::has_start() const {
- return (_has_bits_[0] & 0x00000001u) != 0;
-}
-void DescriptorProto_ExtensionRange::set_has_start() {
- _has_bits_[0] |= 0x00000001u;
-}
-void DescriptorProto_ExtensionRange::clear_has_start() {
- _has_bits_[0] &= ~0x00000001u;
-}
-void DescriptorProto_ExtensionRange::clear_start() {
- start_ = 0;
- clear_has_start();
-}
-::google::protobuf::int32 DescriptorProto_ExtensionRange::start() const {
- // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.ExtensionRange.start)
- return start_;
-}
-void DescriptorProto_ExtensionRange::set_start(::google::protobuf::int32 value) {
- set_has_start();
- start_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.DescriptorProto.ExtensionRange.start)
-}
-
-// optional int32 end = 2;
-bool DescriptorProto_ExtensionRange::has_end() const {
- return (_has_bits_[0] & 0x00000002u) != 0;
-}
-void DescriptorProto_ExtensionRange::set_has_end() {
- _has_bits_[0] |= 0x00000002u;
-}
-void DescriptorProto_ExtensionRange::clear_has_end() {
- _has_bits_[0] &= ~0x00000002u;
-}
-void DescriptorProto_ExtensionRange::clear_end() {
- end_ = 0;
- clear_has_end();
-}
-::google::protobuf::int32 DescriptorProto_ExtensionRange::end() const {
- // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.ExtensionRange.end)
- return end_;
-}
-void DescriptorProto_ExtensionRange::set_end(::google::protobuf::int32 value) {
- set_has_end();
- end_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.DescriptorProto.ExtensionRange.end)
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
+void DescriptorProto_ReservedRange::InitAsDefaultInstance() {
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int DescriptorProto_ReservedRange::kStartFieldNumber;
const int DescriptorProto_ReservedRange::kEndFieldNumber;
@@ -2800,11 +3110,19 @@ const int DescriptorProto_ReservedRange::kEndFieldNumber;
DescriptorProto_ReservedRange::DescriptorProto_ReservedRange()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ReservedRange();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.DescriptorProto.ReservedRange)
}
+DescriptorProto_ReservedRange::DescriptorProto_ReservedRange(::google::protobuf::Arena* arena)
+ : ::google::protobuf::Message(),
+ _internal_metadata_(arena) {
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ReservedRange();
+ SharedCtor();
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.DescriptorProto.ReservedRange)
+}
DescriptorProto_ReservedRange::DescriptorProto_ReservedRange(const DescriptorProto_ReservedRange& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
@@ -2812,15 +3130,16 @@ DescriptorProto_ReservedRange::DescriptorProto_ReservedRange(const DescriptorPro
_cached_size_(0) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
::memcpy(&start_, &from.start_,
- reinterpret_cast<char*>(&end_) -
- reinterpret_cast<char*>(&start_) + sizeof(end_));
+ static_cast<size_t>(reinterpret_cast<char*>(&end_) -
+ reinterpret_cast<char*>(&start_)) + sizeof(end_));
// @@protoc_insertion_point(copy_constructor:google.protobuf.DescriptorProto.ReservedRange)
}
void DescriptorProto_ReservedRange::SharedCtor() {
_cached_size_ = 0;
- ::memset(&start_, 0, reinterpret_cast<char*>(&end_) -
- reinterpret_cast<char*>(&start_) + sizeof(end_));
+ ::memset(&start_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&end_) -
+ reinterpret_cast<char*>(&start_)) + sizeof(end_));
}
DescriptorProto_ReservedRange::~DescriptorProto_ReservedRange() {
@@ -2829,36 +3148,45 @@ DescriptorProto_ReservedRange::~DescriptorProto_ReservedRange() {
}
void DescriptorProto_ReservedRange::SharedDtor() {
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
}
+void DescriptorProto_ReservedRange::ArenaDtor(void* object) {
+ DescriptorProto_ReservedRange* _this = reinterpret_cast< DescriptorProto_ReservedRange* >(object);
+ (void)_this;
+}
+void DescriptorProto_ReservedRange::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+}
void DescriptorProto_ReservedRange::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* DescriptorProto_ReservedRange::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[3].descriptor;
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const DescriptorProto_ReservedRange& DescriptorProto_ReservedRange::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ReservedRange();
return *internal_default_instance();
}
DescriptorProto_ReservedRange* DescriptorProto_ReservedRange::New(::google::protobuf::Arena* arena) const {
- DescriptorProto_ReservedRange* n = new DescriptorProto_ReservedRange;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
+ return ::google::protobuf::Arena::CreateMessage<DescriptorProto_ReservedRange>(arena);
}
void DescriptorProto_ReservedRange::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.DescriptorProto.ReservedRange)
- if (_has_bits_[0 / 32] & 3u) {
- ::memset(&start_, 0, reinterpret_cast<char*>(&end_) -
- reinterpret_cast<char*>(&start_) + sizeof(end_));
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
+ if (cached_has_bits & 3u) {
+ ::memset(&start_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&end_) -
+ reinterpret_cast<char*>(&start_)) + sizeof(end_));
}
_has_bits_.Clear();
_internal_metadata_.Clear();
@@ -2876,7 +3204,8 @@ bool DescriptorProto_ReservedRange::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional int32 start = 1;
case 1: {
- if (tag == 8u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
set_has_start();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
@@ -2889,7 +3218,8 @@ bool DescriptorProto_ReservedRange::MergePartialFromCodedStream(
// optional int32 end = 2;
case 2: {
- if (tag == 16u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
set_has_end();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
@@ -2902,13 +3232,11 @@ bool DescriptorProto_ReservedRange::MergePartialFromCodedStream(
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
- input, tag, mutable_unknown_fields()));
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -2925,19 +3253,23 @@ failure:
void DescriptorProto_ReservedRange::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.DescriptorProto.ReservedRange)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional int32 start = 1;
- if (has_start()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->start(), output);
}
// optional int32 end = 2;
- if (has_end()) {
+ if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->end(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- unknown_fields(), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.DescriptorProto.ReservedRange)
}
@@ -2946,19 +3278,23 @@ void DescriptorProto_ReservedRange::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.DescriptorProto.ReservedRange)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional int32 start = 1;
- if (has_start()) {
+ if (cached_has_bits & 0x00000001u) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->start(), target);
}
// optional int32 end = 2;
- if (has_end()) {
+ if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->end(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- unknown_fields(), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.DescriptorProto.ReservedRange)
return target;
@@ -2971,7 +3307,7 @@ size_t DescriptorProto_ReservedRange::ByteSizeLong() const {
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- unknown_fields());
+ _internal_metadata_.unknown_fields());
}
if (_has_bits_[0 / 32] & 3u) {
// optional int32 start = 1;
@@ -3015,13 +3351,18 @@ void DescriptorProto_ReservedRange::MergeFrom(const DescriptorProto_ReservedRang
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.DescriptorProto.ReservedRange)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
- if (from._has_bits_[0 / 32] & 3u) {
- if (from.has_start()) {
- set_start(from.start());
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = from._has_bits_[0];
+ if (cached_has_bits & 3u) {
+ if (cached_has_bits & 0x00000001u) {
+ start_ = from.start_;
}
- if (from.has_end()) {
- set_end(from.end());
+ if (cached_has_bits & 0x00000002u) {
+ end_ = from.end_;
}
+ _has_bits_[0] |= cached_has_bits;
}
}
@@ -3045,76 +3386,61 @@ bool DescriptorProto_ReservedRange::IsInitialized() const {
void DescriptorProto_ReservedRange::Swap(DescriptorProto_ReservedRange* other) {
if (other == this) return;
+ if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ InternalSwap(other);
+ } else {
+ DescriptorProto_ReservedRange* temp = New(GetArenaNoVirtual());
+ temp->MergeFrom(*other);
+ other->CopyFrom(*this);
+ InternalSwap(temp);
+ if (GetArenaNoVirtual() == NULL) {
+ delete temp;
+ }
+ }
+}
+void DescriptorProto_ReservedRange::UnsafeArenaSwap(DescriptorProto_ReservedRange* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void DescriptorProto_ReservedRange::InternalSwap(DescriptorProto_ReservedRange* other) {
- std::swap(start_, other->start_);
- std::swap(end_, other->end_);
- std::swap(_has_bits_[0], other->_has_bits_[0]);
+ using std::swap;
+ swap(start_, other->start_);
+ swap(end_, other->end_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- std::swap(_cached_size_, other->_cached_size_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata DescriptorProto_ReservedRange::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[3];
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// DescriptorProto_ReservedRange
-// optional int32 start = 1;
-bool DescriptorProto_ReservedRange::has_start() const {
- return (_has_bits_[0] & 0x00000001u) != 0;
-}
-void DescriptorProto_ReservedRange::set_has_start() {
- _has_bits_[0] |= 0x00000001u;
-}
-void DescriptorProto_ReservedRange::clear_has_start() {
- _has_bits_[0] &= ~0x00000001u;
-}
-void DescriptorProto_ReservedRange::clear_start() {
- start_ = 0;
- clear_has_start();
-}
-::google::protobuf::int32 DescriptorProto_ReservedRange::start() const {
- // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.ReservedRange.start)
- return start_;
-}
-void DescriptorProto_ReservedRange::set_start(::google::protobuf::int32 value) {
- set_has_start();
- start_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.DescriptorProto.ReservedRange.start)
-}
+// ===================================================================
-// optional int32 end = 2;
-bool DescriptorProto_ReservedRange::has_end() const {
- return (_has_bits_[0] & 0x00000002u) != 0;
-}
-void DescriptorProto_ReservedRange::set_has_end() {
- _has_bits_[0] |= 0x00000002u;
-}
-void DescriptorProto_ReservedRange::clear_has_end() {
- _has_bits_[0] &= ~0x00000002u;
-}
-void DescriptorProto_ReservedRange::clear_end() {
- end_ = 0;
- clear_has_end();
+void DescriptorProto::InitAsDefaultInstance() {
+ ::google::protobuf::_DescriptorProto_default_instance_._instance.get_mutable()->options_ = const_cast< ::google::protobuf::MessageOptions*>(
+ ::google::protobuf::MessageOptions::internal_default_instance());
}
-::google::protobuf::int32 DescriptorProto_ReservedRange::end() const {
- // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.ReservedRange.end)
- return end_;
+void DescriptorProto::_slow_mutable_options() {
+ options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::MessageOptions >(
+ GetArenaNoVirtual());
}
-void DescriptorProto_ReservedRange::set_end(::google::protobuf::int32 value) {
- set_has_end();
- end_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.DescriptorProto.ReservedRange.end)
+void DescriptorProto::unsafe_arena_set_allocated_options(
+ ::google::protobuf::MessageOptions* options) {
+ if (GetArenaNoVirtual() == NULL) {
+ delete options_;
+ }
+ options_ = options;
+ if (options) {
+ set_has_options();
+ } else {
+ clear_has_options();
+ }
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.DescriptorProto.options)
}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
-
-// ===================================================================
-
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int DescriptorProto::kNameFieldNumber;
const int DescriptorProto::kFieldFieldNumber;
@@ -3131,28 +3457,45 @@ const int DescriptorProto::kReservedNameFieldNumber;
DescriptorProto::DescriptorProto()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.DescriptorProto)
}
+DescriptorProto::DescriptorProto(::google::protobuf::Arena* arena)
+ : ::google::protobuf::Message(),
+ _internal_metadata_(arena),
+ field_(arena),
+ nested_type_(arena),
+ enum_type_(arena),
+ extension_range_(arena),
+ extension_(arena),
+ oneof_decl_(arena),
+ reserved_range_(arena),
+ reserved_name_(arena) {
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto();
+ SharedCtor();
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.DescriptorProto)
+}
DescriptorProto::DescriptorProto(const DescriptorProto& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
_cached_size_(0),
field_(from.field_),
- extension_(from.extension_),
nested_type_(from.nested_type_),
enum_type_(from.enum_type_),
extension_range_(from.extension_range_),
+ extension_(from.extension_),
oneof_decl_(from.oneof_decl_),
reserved_range_(from.reserved_range_),
reserved_name_(from.reserved_name_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_name()) {
- name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_);
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name(),
+ GetArenaNoVirtual());
}
if (from.has_options()) {
options_ = new ::google::protobuf::MessageOptions(*from.options_);
@@ -3174,53 +3517,59 @@ DescriptorProto::~DescriptorProto() {
}
void DescriptorProto::SharedDtor() {
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- if (this != internal_default_instance()) {
- delete options_;
- }
+ if (this != internal_default_instance()) delete options_;
}
+void DescriptorProto::ArenaDtor(void* object) {
+ DescriptorProto* _this = reinterpret_cast< DescriptorProto* >(object);
+ (void)_this;
+}
+void DescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+}
void DescriptorProto::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* DescriptorProto::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[4].descriptor;
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const DescriptorProto& DescriptorProto::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto();
return *internal_default_instance();
}
DescriptorProto* DescriptorProto::New(::google::protobuf::Arena* arena) const {
- DescriptorProto* n = new DescriptorProto;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
+ return ::google::protobuf::Arena::CreateMessage<DescriptorProto>(arena);
}
void DescriptorProto::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.DescriptorProto)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
field_.Clear();
- extension_.Clear();
nested_type_.Clear();
enum_type_.Clear();
extension_range_.Clear();
+ extension_.Clear();
oneof_decl_.Clear();
reserved_range_.Clear();
reserved_name_.Clear();
- if (_has_bits_[0 / 32] & 3u) {
- if (has_name()) {
+ cached_has_bits = _has_bits_[0];
+ if (cached_has_bits & 3u) {
+ if (cached_has_bits & 0x00000001u) {
GOOGLE_DCHECK(!name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- (*name_.UnsafeRawStringPointer())->clear();
+ name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- if (has_options()) {
+ if (cached_has_bits & 0x00000002u) {
GOOGLE_DCHECK(options_ != NULL);
- options_->::google::protobuf::MessageOptions::Clear();
+ options_->Clear();
}
}
_has_bits_.Clear();
@@ -3239,11 +3588,12 @@ bool DescriptorProto::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional string name = 1;
case 1: {
- if (tag == 10u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormat::PARSE,
"google.protobuf.DescriptorProto.name");
} else {
@@ -3254,73 +3604,64 @@ bool DescriptorProto::MergePartialFromCodedStream(
// repeated .google.protobuf.FieldDescriptorProto field = 2;
case 2: {
- if (tag == 18u) {
- DO_(input->IncrementRecursionDepth());
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
- input, add_field()));
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_field()));
} else {
goto handle_unusual;
}
- input->UnsafeDecrementRecursionDepth();
break;
}
// repeated .google.protobuf.DescriptorProto nested_type = 3;
case 3: {
- if (tag == 26u) {
- DO_(input->IncrementRecursionDepth());
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
- input, add_nested_type()));
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_nested_type()));
} else {
goto handle_unusual;
}
- input->UnsafeDecrementRecursionDepth();
break;
}
// repeated .google.protobuf.EnumDescriptorProto enum_type = 4;
case 4: {
- if (tag == 34u) {
- DO_(input->IncrementRecursionDepth());
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
- input, add_enum_type()));
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_enum_type()));
} else {
goto handle_unusual;
}
- input->UnsafeDecrementRecursionDepth();
break;
}
// repeated .google.protobuf.DescriptorProto.ExtensionRange extension_range = 5;
case 5: {
- if (tag == 42u) {
- DO_(input->IncrementRecursionDepth());
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
- input, add_extension_range()));
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(42u /* 42 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_extension_range()));
} else {
goto handle_unusual;
}
- input->UnsafeDecrementRecursionDepth();
break;
}
// repeated .google.protobuf.FieldDescriptorProto extension = 6;
case 6: {
- if (tag == 50u) {
- DO_(input->IncrementRecursionDepth());
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
- input, add_extension()));
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(50u /* 50 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_extension()));
} else {
goto handle_unusual;
}
- input->UnsafeDecrementRecursionDepth();
break;
}
// optional .google.protobuf.MessageOptions options = 7;
case 7: {
- if (tag == 58u) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(58u /* 58 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_options()));
} else {
goto handle_unusual;
@@ -3330,38 +3671,35 @@ bool DescriptorProto::MergePartialFromCodedStream(
// repeated .google.protobuf.OneofDescriptorProto oneof_decl = 8;
case 8: {
- if (tag == 66u) {
- DO_(input->IncrementRecursionDepth());
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
- input, add_oneof_decl()));
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(66u /* 66 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_oneof_decl()));
} else {
goto handle_unusual;
}
- input->UnsafeDecrementRecursionDepth();
break;
}
// repeated .google.protobuf.DescriptorProto.ReservedRange reserved_range = 9;
case 9: {
- if (tag == 74u) {
- DO_(input->IncrementRecursionDepth());
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
- input, add_reserved_range()));
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(74u /* 74 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_reserved_range()));
} else {
goto handle_unusual;
}
- input->UnsafeDecrementRecursionDepth();
break;
}
// repeated string reserved_name = 10;
case 10: {
- if (tag == 82u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(82u /* 82 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->add_reserved_name()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->reserved_name(this->reserved_name_size() - 1).data(),
- this->reserved_name(this->reserved_name_size() - 1).length(),
+ static_cast<int>(this->reserved_name(this->reserved_name_size() - 1).length()),
::google::protobuf::internal::WireFormat::PARSE,
"google.protobuf.DescriptorProto.reserved_name");
} else {
@@ -3372,13 +3710,11 @@ bool DescriptorProto::MergePartialFromCodedStream(
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
- input, tag, mutable_unknown_fields()));
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -3395,10 +3731,14 @@ failure:
void DescriptorProto::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.DescriptorProto)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional string name = 1;
- if (has_name()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.DescriptorProto.name");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -3406,57 +3746,64 @@ void DescriptorProto::SerializeWithCachedSizes(
}
// repeated .google.protobuf.FieldDescriptorProto field = 2;
- for (unsigned int i = 0, n = this->field_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->field_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 2, this->field(i), output);
+ 2, this->field(static_cast<int>(i)), output);
}
// repeated .google.protobuf.DescriptorProto nested_type = 3;
- for (unsigned int i = 0, n = this->nested_type_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->nested_type_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 3, this->nested_type(i), output);
+ 3, this->nested_type(static_cast<int>(i)), output);
}
// repeated .google.protobuf.EnumDescriptorProto enum_type = 4;
- for (unsigned int i = 0, n = this->enum_type_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->enum_type_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 4, this->enum_type(i), output);
+ 4, this->enum_type(static_cast<int>(i)), output);
}
// repeated .google.protobuf.DescriptorProto.ExtensionRange extension_range = 5;
- for (unsigned int i = 0, n = this->extension_range_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->extension_range_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 5, this->extension_range(i), output);
+ 5, this->extension_range(static_cast<int>(i)), output);
}
// repeated .google.protobuf.FieldDescriptorProto extension = 6;
- for (unsigned int i = 0, n = this->extension_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->extension_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 6, this->extension(i), output);
+ 6, this->extension(static_cast<int>(i)), output);
}
// optional .google.protobuf.MessageOptions options = 7;
- if (has_options()) {
+ if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
7, *this->options_, output);
}
// repeated .google.protobuf.OneofDescriptorProto oneof_decl = 8;
- for (unsigned int i = 0, n = this->oneof_decl_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->oneof_decl_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 8, this->oneof_decl(i), output);
+ 8, this->oneof_decl(static_cast<int>(i)), output);
}
// repeated .google.protobuf.DescriptorProto.ReservedRange reserved_range = 9;
- for (unsigned int i = 0, n = this->reserved_range_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->reserved_range_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 9, this->reserved_range(i), output);
+ 9, this->reserved_range(static_cast<int>(i)), output);
}
// repeated string reserved_name = 10;
- for (int i = 0; i < this->reserved_name_size(); i++) {
+ for (int i = 0, n = this->reserved_name_size(); i < n; i++) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->reserved_name(i).data(), this->reserved_name(i).length(),
+ this->reserved_name(i).data(), static_cast<int>(this->reserved_name(i).length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.DescriptorProto.reserved_name");
::google::protobuf::internal::WireFormatLite::WriteString(
@@ -3465,7 +3812,7 @@ void DescriptorProto::SerializeWithCachedSizes(
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- unknown_fields(), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.DescriptorProto)
}
@@ -3474,10 +3821,14 @@ void DescriptorProto::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.DescriptorProto)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional string name = 1;
- if (has_name()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.DescriptorProto.name");
target =
@@ -3486,65 +3837,72 @@ void DescriptorProto::SerializeWithCachedSizes(
}
// repeated .google.protobuf.FieldDescriptorProto field = 2;
- for (unsigned int i = 0, n = this->field_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->field_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 2, this->field(i), false, target);
+ InternalWriteMessageToArray(
+ 2, this->field(static_cast<int>(i)), deterministic, target);
}
// repeated .google.protobuf.DescriptorProto nested_type = 3;
- for (unsigned int i = 0, n = this->nested_type_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->nested_type_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 3, this->nested_type(i), false, target);
+ InternalWriteMessageToArray(
+ 3, this->nested_type(static_cast<int>(i)), deterministic, target);
}
// repeated .google.protobuf.EnumDescriptorProto enum_type = 4;
- for (unsigned int i = 0, n = this->enum_type_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->enum_type_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 4, this->enum_type(i), false, target);
+ InternalWriteMessageToArray(
+ 4, this->enum_type(static_cast<int>(i)), deterministic, target);
}
// repeated .google.protobuf.DescriptorProto.ExtensionRange extension_range = 5;
- for (unsigned int i = 0, n = this->extension_range_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->extension_range_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 5, this->extension_range(i), false, target);
+ InternalWriteMessageToArray(
+ 5, this->extension_range(static_cast<int>(i)), deterministic, target);
}
// repeated .google.protobuf.FieldDescriptorProto extension = 6;
- for (unsigned int i = 0, n = this->extension_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->extension_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 6, this->extension(i), false, target);
+ InternalWriteMessageToArray(
+ 6, this->extension(static_cast<int>(i)), deterministic, target);
}
// optional .google.protobuf.MessageOptions options = 7;
- if (has_options()) {
+ if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 7, *this->options_, false, target);
+ InternalWriteMessageToArray(
+ 7, *this->options_, deterministic, target);
}
// repeated .google.protobuf.OneofDescriptorProto oneof_decl = 8;
- for (unsigned int i = 0, n = this->oneof_decl_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->oneof_decl_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 8, this->oneof_decl(i), false, target);
+ InternalWriteMessageToArray(
+ 8, this->oneof_decl(static_cast<int>(i)), deterministic, target);
}
// repeated .google.protobuf.DescriptorProto.ReservedRange reserved_range = 9;
- for (unsigned int i = 0, n = this->reserved_range_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->reserved_range_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 9, this->reserved_range(i), false, target);
+ InternalWriteMessageToArray(
+ 9, this->reserved_range(static_cast<int>(i)), deterministic, target);
}
// repeated string reserved_name = 10;
- for (int i = 0; i < this->reserved_name_size(); i++) {
+ for (int i = 0, n = this->reserved_name_size(); i < n; i++) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->reserved_name(i).data(), this->reserved_name(i).length(),
+ this->reserved_name(i).data(), static_cast<int>(this->reserved_name(i).length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.DescriptorProto.reserved_name");
target = ::google::protobuf::internal::WireFormatLite::
@@ -3553,7 +3911,7 @@ void DescriptorProto::SerializeWithCachedSizes(
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- unknown_fields(), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.DescriptorProto)
return target;
@@ -3566,89 +3924,89 @@ size_t DescriptorProto::ByteSizeLong() const {
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- unknown_fields());
+ _internal_metadata_.unknown_fields());
}
// repeated .google.protobuf.FieldDescriptorProto field = 2;
{
- unsigned int count = this->field_size();
+ unsigned int count = static_cast<unsigned int>(this->field_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->field(i));
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->field(static_cast<int>(i)));
}
}
- // repeated .google.protobuf.FieldDescriptorProto extension = 6;
+ // repeated .google.protobuf.DescriptorProto nested_type = 3;
{
- unsigned int count = this->extension_size();
+ unsigned int count = static_cast<unsigned int>(this->nested_type_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->extension(i));
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->nested_type(static_cast<int>(i)));
}
}
- // repeated .google.protobuf.DescriptorProto nested_type = 3;
+ // repeated .google.protobuf.EnumDescriptorProto enum_type = 4;
{
- unsigned int count = this->nested_type_size();
+ unsigned int count = static_cast<unsigned int>(this->enum_type_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->nested_type(i));
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->enum_type(static_cast<int>(i)));
}
}
- // repeated .google.protobuf.EnumDescriptorProto enum_type = 4;
+ // repeated .google.protobuf.DescriptorProto.ExtensionRange extension_range = 5;
{
- unsigned int count = this->enum_type_size();
+ unsigned int count = static_cast<unsigned int>(this->extension_range_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->enum_type(i));
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->extension_range(static_cast<int>(i)));
}
}
- // repeated .google.protobuf.DescriptorProto.ExtensionRange extension_range = 5;
+ // repeated .google.protobuf.FieldDescriptorProto extension = 6;
{
- unsigned int count = this->extension_range_size();
+ unsigned int count = static_cast<unsigned int>(this->extension_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->extension_range(i));
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->extension(static_cast<int>(i)));
}
}
// repeated .google.protobuf.OneofDescriptorProto oneof_decl = 8;
{
- unsigned int count = this->oneof_decl_size();
+ unsigned int count = static_cast<unsigned int>(this->oneof_decl_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->oneof_decl(i));
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->oneof_decl(static_cast<int>(i)));
}
}
// repeated .google.protobuf.DescriptorProto.ReservedRange reserved_range = 9;
{
- unsigned int count = this->reserved_range_size();
+ unsigned int count = static_cast<unsigned int>(this->reserved_range_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->reserved_range(i));
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->reserved_range(static_cast<int>(i)));
}
}
// repeated string reserved_name = 10;
total_size += 1 *
::google::protobuf::internal::FromIntSize(this->reserved_name_size());
- for (int i = 0; i < this->reserved_name_size(); i++) {
+ for (int i = 0, n = this->reserved_name_size(); i < n; i++) {
total_size += ::google::protobuf::internal::WireFormatLite::StringSize(
this->reserved_name(i));
}
@@ -3664,7 +4022,7 @@ size_t DescriptorProto::ByteSizeLong() const {
// optional .google.protobuf.MessageOptions options = 7;
if (has_options()) {
total_size += 1 +
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
*this->options_);
}
@@ -3695,20 +4053,23 @@ void DescriptorProto::MergeFrom(const DescriptorProto& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.DescriptorProto)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
field_.MergeFrom(from.field_);
- extension_.MergeFrom(from.extension_);
nested_type_.MergeFrom(from.nested_type_);
enum_type_.MergeFrom(from.enum_type_);
extension_range_.MergeFrom(from.extension_range_);
+ extension_.MergeFrom(from.extension_);
oneof_decl_.MergeFrom(from.oneof_decl_);
reserved_range_.MergeFrom(from.reserved_range_);
reserved_name_.MergeFrom(from.reserved_name_);
- if (from._has_bits_[0 / 32] & 3u) {
- if (from.has_name()) {
- set_has_name();
- name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_);
+ cached_has_bits = from._has_bits_[0];
+ if (cached_has_bits & 3u) {
+ if (cached_has_bits & 0x00000001u) {
+ set_name(from.name());
}
- if (from.has_options()) {
+ if (cached_has_bits & 0x00000002u) {
mutable_options()->::google::protobuf::MessageOptions::MergeFrom(from.options());
}
}
@@ -3730,9 +4091,10 @@ void DescriptorProto::CopyFrom(const DescriptorProto& from) {
bool DescriptorProto::IsInitialized() const {
if (!::google::protobuf::internal::AllAreInitialized(this->field())) return false;
- if (!::google::protobuf::internal::AllAreInitialized(this->extension())) return false;
if (!::google::protobuf::internal::AllAreInitialized(this->nested_type())) return false;
if (!::google::protobuf::internal::AllAreInitialized(this->enum_type())) return false;
+ if (!::google::protobuf::internal::AllAreInitialized(this->extension_range())) return false;
+ if (!::google::protobuf::internal::AllAreInitialized(this->extension())) return false;
if (!::google::protobuf::internal::AllAreInitialized(this->oneof_decl())) return false;
if (has_options()) {
if (!this->options_->IsInitialized()) return false;
@@ -3742,400 +4104,366 @@ bool DescriptorProto::IsInitialized() const {
void DescriptorProto::Swap(DescriptorProto* other) {
if (other == this) return;
+ if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ InternalSwap(other);
+ } else {
+ DescriptorProto* temp = New(GetArenaNoVirtual());
+ temp->MergeFrom(*other);
+ other->CopyFrom(*this);
+ InternalSwap(temp);
+ if (GetArenaNoVirtual() == NULL) {
+ delete temp;
+ }
+ }
+}
+void DescriptorProto::UnsafeArenaSwap(DescriptorProto* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void DescriptorProto::InternalSwap(DescriptorProto* other) {
- field_.UnsafeArenaSwap(&other->field_);
- extension_.UnsafeArenaSwap(&other->extension_);
- nested_type_.UnsafeArenaSwap(&other->nested_type_);
- enum_type_.UnsafeArenaSwap(&other->enum_type_);
- extension_range_.UnsafeArenaSwap(&other->extension_range_);
- oneof_decl_.UnsafeArenaSwap(&other->oneof_decl_);
- reserved_range_.UnsafeArenaSwap(&other->reserved_range_);
- reserved_name_.UnsafeArenaSwap(&other->reserved_name_);
+ using std::swap;
+ field_.InternalSwap(&other->field_);
+ nested_type_.InternalSwap(&other->nested_type_);
+ enum_type_.InternalSwap(&other->enum_type_);
+ extension_range_.InternalSwap(&other->extension_range_);
+ extension_.InternalSwap(&other->extension_);
+ oneof_decl_.InternalSwap(&other->oneof_decl_);
+ reserved_range_.InternalSwap(&other->reserved_range_);
+ reserved_name_.InternalSwap(&other->reserved_name_);
name_.Swap(&other->name_);
- std::swap(options_, other->options_);
- std::swap(_has_bits_[0], other->_has_bits_[0]);
+ swap(options_, other->options_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- std::swap(_cached_size_, other->_cached_size_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata DescriptorProto::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[4];
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// DescriptorProto
-// optional string name = 1;
-bool DescriptorProto::has_name() const {
- return (_has_bits_[0] & 0x00000001u) != 0;
-}
-void DescriptorProto::set_has_name() {
- _has_bits_[0] |= 0x00000001u;
-}
-void DescriptorProto::clear_has_name() {
- _has_bits_[0] &= ~0x00000001u;
-}
-void DescriptorProto::clear_name() {
- name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_name();
-}
-const ::std::string& DescriptorProto::name() const {
- // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.name)
- return name_.GetNoArena();
-}
-void DescriptorProto::set_name(const ::std::string& value) {
- set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.DescriptorProto.name)
-}
-void DescriptorProto::set_name(const char* value) {
- set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.DescriptorProto.name)
-}
-void DescriptorProto::set_name(const char* value, size_t size) {
- set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.DescriptorProto.name)
-}
-::std::string* DescriptorProto::mutable_name() {
- set_has_name();
- // @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.name)
- return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* DescriptorProto::release_name() {
- // @@protoc_insertion_point(field_release:google.protobuf.DescriptorProto.name)
- clear_has_name();
- return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void DescriptorProto::set_allocated_name(::std::string* name) {
- if (name != NULL) {
- set_has_name();
- } else {
- clear_has_name();
- }
- name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.DescriptorProto.name)
-}
+// ===================================================================
-// repeated .google.protobuf.FieldDescriptorProto field = 2;
-int DescriptorProto::field_size() const {
- return field_.size();
-}
-void DescriptorProto::clear_field() {
- field_.Clear();
-}
-const ::google::protobuf::FieldDescriptorProto& DescriptorProto::field(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.field)
- return field_.Get(index);
-}
-::google::protobuf::FieldDescriptorProto* DescriptorProto::mutable_field(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.field)
- return field_.Mutable(index);
-}
-::google::protobuf::FieldDescriptorProto* DescriptorProto::add_field() {
- // @@protoc_insertion_point(field_add:google.protobuf.DescriptorProto.field)
- return field_.Add();
-}
-::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >*
-DescriptorProto::mutable_field() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.DescriptorProto.field)
- return &field_;
-}
-const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >&
-DescriptorProto::field() const {
- // @@protoc_insertion_point(field_list:google.protobuf.DescriptorProto.field)
- return field_;
+void ExtensionRangeOptions::InitAsDefaultInstance() {
}
+#if !defined(_MSC_VER) || _MSC_VER >= 1900
+const int ExtensionRangeOptions::kUninterpretedOptionFieldNumber;
+#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
-// repeated .google.protobuf.FieldDescriptorProto extension = 6;
-int DescriptorProto::extension_size() const {
- return extension_.size();
-}
-void DescriptorProto::clear_extension() {
- extension_.Clear();
-}
-const ::google::protobuf::FieldDescriptorProto& DescriptorProto::extension(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.extension)
- return extension_.Get(index);
-}
-::google::protobuf::FieldDescriptorProto* DescriptorProto::mutable_extension(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.extension)
- return extension_.Mutable(index);
-}
-::google::protobuf::FieldDescriptorProto* DescriptorProto::add_extension() {
- // @@protoc_insertion_point(field_add:google.protobuf.DescriptorProto.extension)
- return extension_.Add();
+ExtensionRangeOptions::ExtensionRangeOptions()
+ : ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsExtensionRangeOptions();
+ }
+ SharedCtor();
+ // @@protoc_insertion_point(constructor:google.protobuf.ExtensionRangeOptions)
}
-::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >*
-DescriptorProto::mutable_extension() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.DescriptorProto.extension)
- return &extension_;
+ExtensionRangeOptions::ExtensionRangeOptions(::google::protobuf::Arena* arena)
+ : ::google::protobuf::Message(),
+ _extensions_(arena),
+ _internal_metadata_(arena),
+ uninterpreted_option_(arena) {
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsExtensionRangeOptions();
+ SharedCtor();
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.ExtensionRangeOptions)
}
-const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >&
-DescriptorProto::extension() const {
- // @@protoc_insertion_point(field_list:google.protobuf.DescriptorProto.extension)
- return extension_;
+ExtensionRangeOptions::ExtensionRangeOptions(const ExtensionRangeOptions& from)
+ : ::google::protobuf::Message(),
+ _internal_metadata_(NULL),
+ _has_bits_(from._has_bits_),
+ _cached_size_(0),
+ uninterpreted_option_(from.uninterpreted_option_) {
+ _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _extensions_.MergeFrom(from._extensions_);
+ // @@protoc_insertion_point(copy_constructor:google.protobuf.ExtensionRangeOptions)
}
-// repeated .google.protobuf.DescriptorProto nested_type = 3;
-int DescriptorProto::nested_type_size() const {
- return nested_type_.size();
-}
-void DescriptorProto::clear_nested_type() {
- nested_type_.Clear();
-}
-const ::google::protobuf::DescriptorProto& DescriptorProto::nested_type(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.nested_type)
- return nested_type_.Get(index);
-}
-::google::protobuf::DescriptorProto* DescriptorProto::mutable_nested_type(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.nested_type)
- return nested_type_.Mutable(index);
-}
-::google::protobuf::DescriptorProto* DescriptorProto::add_nested_type() {
- // @@protoc_insertion_point(field_add:google.protobuf.DescriptorProto.nested_type)
- return nested_type_.Add();
-}
-::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto >*
-DescriptorProto::mutable_nested_type() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.DescriptorProto.nested_type)
- return &nested_type_;
-}
-const ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto >&
-DescriptorProto::nested_type() const {
- // @@protoc_insertion_point(field_list:google.protobuf.DescriptorProto.nested_type)
- return nested_type_;
+void ExtensionRangeOptions::SharedCtor() {
+ _cached_size_ = 0;
}
-// repeated .google.protobuf.EnumDescriptorProto enum_type = 4;
-int DescriptorProto::enum_type_size() const {
- return enum_type_.size();
+ExtensionRangeOptions::~ExtensionRangeOptions() {
+ // @@protoc_insertion_point(destructor:google.protobuf.ExtensionRangeOptions)
+ SharedDtor();
}
-void DescriptorProto::clear_enum_type() {
- enum_type_.Clear();
+
+void ExtensionRangeOptions::SharedDtor() {
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
}
-const ::google::protobuf::EnumDescriptorProto& DescriptorProto::enum_type(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.enum_type)
- return enum_type_.Get(index);
+
+void ExtensionRangeOptions::ArenaDtor(void* object) {
+ ExtensionRangeOptions* _this = reinterpret_cast< ExtensionRangeOptions* >(object);
+ (void)_this;
}
-::google::protobuf::EnumDescriptorProto* DescriptorProto::mutable_enum_type(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.enum_type)
- return enum_type_.Mutable(index);
+void ExtensionRangeOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
-::google::protobuf::EnumDescriptorProto* DescriptorProto::add_enum_type() {
- // @@protoc_insertion_point(field_add:google.protobuf.DescriptorProto.enum_type)
- return enum_type_.Add();
+void ExtensionRangeOptions::SetCachedSize(int size) const {
+ GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
+ _cached_size_ = size;
+ GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
-::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto >*
-DescriptorProto::mutable_enum_type() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.DescriptorProto.enum_type)
- return &enum_type_;
+const ::google::protobuf::Descriptor* ExtensionRangeOptions::descriptor() {
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
-const ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto >&
-DescriptorProto::enum_type() const {
- // @@protoc_insertion_point(field_list:google.protobuf.DescriptorProto.enum_type)
- return enum_type_;
+
+const ExtensionRangeOptions& ExtensionRangeOptions::default_instance() {
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsExtensionRangeOptions();
+ return *internal_default_instance();
}
-// repeated .google.protobuf.DescriptorProto.ExtensionRange extension_range = 5;
-int DescriptorProto::extension_range_size() const {
- return extension_range_.size();
+ExtensionRangeOptions* ExtensionRangeOptions::New(::google::protobuf::Arena* arena) const {
+ return ::google::protobuf::Arena::CreateMessage<ExtensionRangeOptions>(arena);
}
-void DescriptorProto::clear_extension_range() {
- extension_range_.Clear();
+
+void ExtensionRangeOptions::Clear() {
+// @@protoc_insertion_point(message_clear_start:google.protobuf.ExtensionRangeOptions)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
+ _extensions_.Clear();
+ uninterpreted_option_.Clear();
+ _has_bits_.Clear();
+ _internal_metadata_.Clear();
}
-const ::google::protobuf::DescriptorProto_ExtensionRange& DescriptorProto::extension_range(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.extension_range)
- return extension_range_.Get(index);
+
+bool ExtensionRangeOptions::MergePartialFromCodedStream(
+ ::google::protobuf::io::CodedInputStream* input) {
+#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+ ::google::protobuf::uint32 tag;
+ // @@protoc_insertion_point(parse_start:google.protobuf.ExtensionRangeOptions)
+ for (;;) {
+ ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u);
+ tag = p.first;
+ if (!p.second) goto handle_unusual;
+ switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
+ // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
+ case 999: {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(58u /* 7994 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_uninterpreted_option()));
+ } else {
+ goto handle_unusual;
+ }
+ break;
+ }
+
+ default: {
+ handle_unusual:
+ if (tag == 0) {
+ goto success;
+ }
+ if ((8000u <= tag)) {
+ DO_(_extensions_.ParseField(tag, input,
+ internal_default_instance(),
+ _internal_metadata_.mutable_unknown_fields()));
+ continue;
+ }
+ DO_(::google::protobuf::internal::WireFormat::SkipField(
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
+ break;
+ }
+ }
+ }
+success:
+ // @@protoc_insertion_point(parse_success:google.protobuf.ExtensionRangeOptions)
+ return true;
+failure:
+ // @@protoc_insertion_point(parse_failure:google.protobuf.ExtensionRangeOptions)
+ return false;
+#undef DO_
}
-::google::protobuf::DescriptorProto_ExtensionRange* DescriptorProto::mutable_extension_range(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.extension_range)
- return extension_range_.Mutable(index);
+
+void ExtensionRangeOptions::SerializeWithCachedSizes(
+ ::google::protobuf::io::CodedOutputStream* output) const {
+ // @@protoc_insertion_point(serialize_start:google.protobuf.ExtensionRangeOptions)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->uninterpreted_option_size()); i < n; i++) {
+ ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
+ 999, this->uninterpreted_option(static_cast<int>(i)), output);
+ }
+
+ // Extension range [1000, 536870912)
+ _extensions_.SerializeWithCachedSizes(
+ 1000, 536870912, output);
+
+ if (_internal_metadata_.have_unknown_fields()) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ _internal_metadata_.unknown_fields(), output);
+ }
+ // @@protoc_insertion_point(serialize_end:google.protobuf.ExtensionRangeOptions)
}
-::google::protobuf::DescriptorProto_ExtensionRange* DescriptorProto::add_extension_range() {
- // @@protoc_insertion_point(field_add:google.protobuf.DescriptorProto.extension_range)
- return extension_range_.Add();
+
+::google::protobuf::uint8* ExtensionRangeOptions::InternalSerializeWithCachedSizesToArray(
+ bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
+ // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.ExtensionRangeOptions)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->uninterpreted_option_size()); i < n; i++) {
+ target = ::google::protobuf::internal::WireFormatLite::
+ InternalWriteMessageToArray(
+ 999, this->uninterpreted_option(static_cast<int>(i)), deterministic, target);
+ }
+
+ // Extension range [1000, 536870912)
+ target = _extensions_.InternalSerializeWithCachedSizesToArray(
+ 1000, 536870912, deterministic, target);
+
+ if (_internal_metadata_.have_unknown_fields()) {
+ target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
+ _internal_metadata_.unknown_fields(), target);
+ }
+ // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.ExtensionRangeOptions)
+ return target;
}
-::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto_ExtensionRange >*
-DescriptorProto::mutable_extension_range() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.DescriptorProto.extension_range)
- return &extension_range_;
+
+size_t ExtensionRangeOptions::ByteSizeLong() const {
+// @@protoc_insertion_point(message_byte_size_start:google.protobuf.ExtensionRangeOptions)
+ size_t total_size = 0;
+
+ total_size += _extensions_.ByteSize();
+
+ if (_internal_metadata_.have_unknown_fields()) {
+ total_size +=
+ ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
+ _internal_metadata_.unknown_fields());
+ }
+ // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
+ {
+ unsigned int count = static_cast<unsigned int>(this->uninterpreted_option_size());
+ total_size += 2UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->uninterpreted_option(static_cast<int>(i)));
+ }
+ }
+
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
+ GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
+ _cached_size_ = cached_size;
+ GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ return total_size;
}
-const ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto_ExtensionRange >&
-DescriptorProto::extension_range() const {
- // @@protoc_insertion_point(field_list:google.protobuf.DescriptorProto.extension_range)
- return extension_range_;
+
+void ExtensionRangeOptions::MergeFrom(const ::google::protobuf::Message& from) {
+// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.ExtensionRangeOptions)
+ GOOGLE_DCHECK_NE(&from, this);
+ const ExtensionRangeOptions* source =
+ ::google::protobuf::internal::DynamicCastToGenerated<const ExtensionRangeOptions>(
+ &from);
+ if (source == NULL) {
+ // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.ExtensionRangeOptions)
+ ::google::protobuf::internal::ReflectionOps::Merge(from, this);
+ } else {
+ // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.ExtensionRangeOptions)
+ MergeFrom(*source);
+ }
}
-// repeated .google.protobuf.OneofDescriptorProto oneof_decl = 8;
-int DescriptorProto::oneof_decl_size() const {
- return oneof_decl_.size();
+void ExtensionRangeOptions::MergeFrom(const ExtensionRangeOptions& from) {
+// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.ExtensionRangeOptions)
+ GOOGLE_DCHECK_NE(&from, this);
+ _extensions_.MergeFrom(from._extensions_);
+ _internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ uninterpreted_option_.MergeFrom(from.uninterpreted_option_);
}
-void DescriptorProto::clear_oneof_decl() {
- oneof_decl_.Clear();
+
+void ExtensionRangeOptions::CopyFrom(const ::google::protobuf::Message& from) {
+// @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.ExtensionRangeOptions)
+ if (&from == this) return;
+ Clear();
+ MergeFrom(from);
}
-const ::google::protobuf::OneofDescriptorProto& DescriptorProto::oneof_decl(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.oneof_decl)
- return oneof_decl_.Get(index);
+
+void ExtensionRangeOptions::CopyFrom(const ExtensionRangeOptions& from) {
+// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.ExtensionRangeOptions)
+ if (&from == this) return;
+ Clear();
+ MergeFrom(from);
}
-::google::protobuf::OneofDescriptorProto* DescriptorProto::mutable_oneof_decl(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.oneof_decl)
- return oneof_decl_.Mutable(index);
+
+bool ExtensionRangeOptions::IsInitialized() const {
+ if (!_extensions_.IsInitialized()) {
+ return false;
+ }
+
+ if (!::google::protobuf::internal::AllAreInitialized(this->uninterpreted_option())) return false;
+ return true;
}
-::google::protobuf::OneofDescriptorProto* DescriptorProto::add_oneof_decl() {
- // @@protoc_insertion_point(field_add:google.protobuf.DescriptorProto.oneof_decl)
- return oneof_decl_.Add();
+
+void ExtensionRangeOptions::Swap(ExtensionRangeOptions* other) {
+ if (other == this) return;
+ if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ InternalSwap(other);
+ } else {
+ ExtensionRangeOptions* temp = New(GetArenaNoVirtual());
+ temp->MergeFrom(*other);
+ other->CopyFrom(*this);
+ InternalSwap(temp);
+ if (GetArenaNoVirtual() == NULL) {
+ delete temp;
+ }
+ }
}
-::google::protobuf::RepeatedPtrField< ::google::protobuf::OneofDescriptorProto >*
-DescriptorProto::mutable_oneof_decl() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.DescriptorProto.oneof_decl)
- return &oneof_decl_;
+void ExtensionRangeOptions::UnsafeArenaSwap(ExtensionRangeOptions* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ InternalSwap(other);
}
-const ::google::protobuf::RepeatedPtrField< ::google::protobuf::OneofDescriptorProto >&
-DescriptorProto::oneof_decl() const {
- // @@protoc_insertion_point(field_list:google.protobuf.DescriptorProto.oneof_decl)
- return oneof_decl_;
+void ExtensionRangeOptions::InternalSwap(ExtensionRangeOptions* other) {
+ using std::swap;
+ uninterpreted_option_.InternalSwap(&other->uninterpreted_option_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_cached_size_, other->_cached_size_);
+ _extensions_.Swap(&other->_extensions_);
}
-// optional .google.protobuf.MessageOptions options = 7;
-bool DescriptorProto::has_options() const {
- return (_has_bits_[0] & 0x00000002u) != 0;
+::google::protobuf::Metadata ExtensionRangeOptions::GetMetadata() const {
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
}
-void DescriptorProto::set_has_options() {
- _has_bits_[0] |= 0x00000002u;
-}
-void DescriptorProto::clear_has_options() {
- _has_bits_[0] &= ~0x00000002u;
-}
-void DescriptorProto::clear_options() {
- if (options_ != NULL) options_->::google::protobuf::MessageOptions::Clear();
- clear_has_options();
+
+
+// ===================================================================
+
+void FieldDescriptorProto::InitAsDefaultInstance() {
+ ::google::protobuf::_FieldDescriptorProto_default_instance_._instance.get_mutable()->options_ = const_cast< ::google::protobuf::FieldOptions*>(
+ ::google::protobuf::FieldOptions::internal_default_instance());
}
-const ::google::protobuf::MessageOptions& DescriptorProto::options() const {
- // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.options)
- return options_ != NULL ? *options_
- : *::google::protobuf::MessageOptions::internal_default_instance();
+void FieldDescriptorProto::_slow_mutable_options() {
+ options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::FieldOptions >(
+ GetArenaNoVirtual());
}
-::google::protobuf::MessageOptions* DescriptorProto::mutable_options() {
- set_has_options();
- if (options_ == NULL) {
- options_ = new ::google::protobuf::MessageOptions;
+void FieldDescriptorProto::unsafe_arena_set_allocated_options(
+ ::google::protobuf::FieldOptions* options) {
+ if (GetArenaNoVirtual() == NULL) {
+ delete options_;
}
- // @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.options)
- return options_;
-}
-::google::protobuf::MessageOptions* DescriptorProto::release_options() {
- // @@protoc_insertion_point(field_release:google.protobuf.DescriptorProto.options)
- clear_has_options();
- ::google::protobuf::MessageOptions* temp = options_;
- options_ = NULL;
- return temp;
-}
-void DescriptorProto::set_allocated_options(::google::protobuf::MessageOptions* options) {
- delete options_;
options_ = options;
if (options) {
set_has_options();
} else {
clear_has_options();
}
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.DescriptorProto.options)
-}
-
-// repeated .google.protobuf.DescriptorProto.ReservedRange reserved_range = 9;
-int DescriptorProto::reserved_range_size() const {
- return reserved_range_.size();
-}
-void DescriptorProto::clear_reserved_range() {
- reserved_range_.Clear();
-}
-const ::google::protobuf::DescriptorProto_ReservedRange& DescriptorProto::reserved_range(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.reserved_range)
- return reserved_range_.Get(index);
-}
-::google::protobuf::DescriptorProto_ReservedRange* DescriptorProto::mutable_reserved_range(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.reserved_range)
- return reserved_range_.Mutable(index);
-}
-::google::protobuf::DescriptorProto_ReservedRange* DescriptorProto::add_reserved_range() {
- // @@protoc_insertion_point(field_add:google.protobuf.DescriptorProto.reserved_range)
- return reserved_range_.Add();
-}
-::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto_ReservedRange >*
-DescriptorProto::mutable_reserved_range() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.DescriptorProto.reserved_range)
- return &reserved_range_;
-}
-const ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto_ReservedRange >&
-DescriptorProto::reserved_range() const {
- // @@protoc_insertion_point(field_list:google.protobuf.DescriptorProto.reserved_range)
- return reserved_range_;
-}
-
-// repeated string reserved_name = 10;
-int DescriptorProto::reserved_name_size() const {
- return reserved_name_.size();
-}
-void DescriptorProto::clear_reserved_name() {
- reserved_name_.Clear();
-}
-const ::std::string& DescriptorProto::reserved_name(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.reserved_name)
- return reserved_name_.Get(index);
-}
-::std::string* DescriptorProto::mutable_reserved_name(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.reserved_name)
- return reserved_name_.Mutable(index);
-}
-void DescriptorProto::set_reserved_name(int index, const ::std::string& value) {
- // @@protoc_insertion_point(field_set:google.protobuf.DescriptorProto.reserved_name)
- reserved_name_.Mutable(index)->assign(value);
-}
-void DescriptorProto::set_reserved_name(int index, const char* value) {
- reserved_name_.Mutable(index)->assign(value);
- // @@protoc_insertion_point(field_set_char:google.protobuf.DescriptorProto.reserved_name)
-}
-void DescriptorProto::set_reserved_name(int index, const char* value, size_t size) {
- reserved_name_.Mutable(index)->assign(
- reinterpret_cast<const char*>(value), size);
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.DescriptorProto.reserved_name)
-}
-::std::string* DescriptorProto::add_reserved_name() {
- // @@protoc_insertion_point(field_add_mutable:google.protobuf.DescriptorProto.reserved_name)
- return reserved_name_.Add();
-}
-void DescriptorProto::add_reserved_name(const ::std::string& value) {
- reserved_name_.Add()->assign(value);
- // @@protoc_insertion_point(field_add:google.protobuf.DescriptorProto.reserved_name)
-}
-void DescriptorProto::add_reserved_name(const char* value) {
- reserved_name_.Add()->assign(value);
- // @@protoc_insertion_point(field_add_char:google.protobuf.DescriptorProto.reserved_name)
-}
-void DescriptorProto::add_reserved_name(const char* value, size_t size) {
- reserved_name_.Add()->assign(reinterpret_cast<const char*>(value), size);
- // @@protoc_insertion_point(field_add_pointer:google.protobuf.DescriptorProto.reserved_name)
-}
-const ::google::protobuf::RepeatedPtrField< ::std::string>&
-DescriptorProto::reserved_name() const {
- // @@protoc_insertion_point(field_list:google.protobuf.DescriptorProto.reserved_name)
- return reserved_name_;
-}
-::google::protobuf::RepeatedPtrField< ::std::string>*
-DescriptorProto::mutable_reserved_name() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.DescriptorProto.reserved_name)
- return &reserved_name_;
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FieldDescriptorProto.options)
}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
-
-// ===================================================================
-
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int FieldDescriptorProto::kNameFieldNumber;
const int FieldDescriptorProto::kNumberFieldNumber;
@@ -4152,11 +4480,19 @@ const int FieldDescriptorProto::kOptionsFieldNumber;
FieldDescriptorProto::FieldDescriptorProto()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldDescriptorProto();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.FieldDescriptorProto)
}
+FieldDescriptorProto::FieldDescriptorProto(::google::protobuf::Arena* arena)
+ : ::google::protobuf::Message(),
+ _internal_metadata_(arena) {
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldDescriptorProto();
+ SharedCtor();
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.FieldDescriptorProto)
+}
FieldDescriptorProto::FieldDescriptorProto(const FieldDescriptorProto& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
@@ -4165,23 +4501,28 @@ FieldDescriptorProto::FieldDescriptorProto(const FieldDescriptorProto& from)
_internal_metadata_.MergeFrom(from._internal_metadata_);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_name()) {
- name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_);
- }
- type_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- if (from.has_type_name()) {
- type_name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.type_name_);
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name(),
+ GetArenaNoVirtual());
}
extendee_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_extendee()) {
- extendee_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.extendee_);
+ extendee_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.extendee(),
+ GetArenaNoVirtual());
+ }
+ type_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ if (from.has_type_name()) {
+ type_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.type_name(),
+ GetArenaNoVirtual());
}
default_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_default_value()) {
- default_value_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.default_value_);
+ default_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.default_value(),
+ GetArenaNoVirtual());
}
json_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_json_name()) {
- json_name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.json_name_);
+ json_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.json_name(),
+ GetArenaNoVirtual());
}
if (from.has_options()) {
options_ = new ::google::protobuf::FieldOptions(*from.options_);
@@ -4189,20 +4530,21 @@ FieldDescriptorProto::FieldDescriptorProto(const FieldDescriptorProto& from)
options_ = NULL;
}
::memcpy(&number_, &from.number_,
- reinterpret_cast<char*>(&type_) -
- reinterpret_cast<char*>(&number_) + sizeof(type_));
+ static_cast<size_t>(reinterpret_cast<char*>(&type_) -
+ reinterpret_cast<char*>(&number_)) + sizeof(type_));
// @@protoc_insertion_point(copy_constructor:google.protobuf.FieldDescriptorProto)
}
void FieldDescriptorProto::SharedCtor() {
_cached_size_ = 0;
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- type_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
extendee_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ type_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
default_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
json_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- ::memset(&options_, 0, reinterpret_cast<char*>(&oneof_index_) -
- reinterpret_cast<char*>(&options_) + sizeof(oneof_index_));
+ ::memset(&options_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&oneof_index_) -
+ reinterpret_cast<char*>(&options_)) + sizeof(oneof_index_));
label_ = 1;
type_ = 1;
}
@@ -4213,72 +4555,79 @@ FieldDescriptorProto::~FieldDescriptorProto() {
}
void FieldDescriptorProto::SharedDtor() {
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- type_name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
extendee_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ type_name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
default_value_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
json_name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- if (this != internal_default_instance()) {
- delete options_;
- }
+ if (this != internal_default_instance()) delete options_;
}
+void FieldDescriptorProto::ArenaDtor(void* object) {
+ FieldDescriptorProto* _this = reinterpret_cast< FieldDescriptorProto* >(object);
+ (void)_this;
+}
+void FieldDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+}
void FieldDescriptorProto::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* FieldDescriptorProto::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[5].descriptor;
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const FieldDescriptorProto& FieldDescriptorProto::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldDescriptorProto();
return *internal_default_instance();
}
FieldDescriptorProto* FieldDescriptorProto::New(::google::protobuf::Arena* arena) const {
- FieldDescriptorProto* n = new FieldDescriptorProto;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
+ return ::google::protobuf::Arena::CreateMessage<FieldDescriptorProto>(arena);
}
void FieldDescriptorProto::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.FieldDescriptorProto)
- if (_has_bits_[0 / 32] & 63u) {
- if (has_name()) {
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
+ if (cached_has_bits & 63u) {
+ if (cached_has_bits & 0x00000001u) {
GOOGLE_DCHECK(!name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- (*name_.UnsafeRawStringPointer())->clear();
+ name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- if (has_type_name()) {
- GOOGLE_DCHECK(!type_name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- (*type_name_.UnsafeRawStringPointer())->clear();
- }
- if (has_extendee()) {
+ if (cached_has_bits & 0x00000002u) {
GOOGLE_DCHECK(!extendee_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- (*extendee_.UnsafeRawStringPointer())->clear();
+ extendee_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- if (has_default_value()) {
+ if (cached_has_bits & 0x00000004u) {
+ GOOGLE_DCHECK(!type_name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
+ type_name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ }
+ if (cached_has_bits & 0x00000008u) {
GOOGLE_DCHECK(!default_value_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- (*default_value_.UnsafeRawStringPointer())->clear();
+ default_value_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- if (has_json_name()) {
+ if (cached_has_bits & 0x00000010u) {
GOOGLE_DCHECK(!json_name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- (*json_name_.UnsafeRawStringPointer())->clear();
+ json_name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- if (has_options()) {
+ if (cached_has_bits & 0x00000020u) {
GOOGLE_DCHECK(options_ != NULL);
- options_->::google::protobuf::FieldOptions::Clear();
+ options_->Clear();
}
}
- if (_has_bits_[0 / 32] & 192u) {
- ::memset(&number_, 0, reinterpret_cast<char*>(&oneof_index_) -
- reinterpret_cast<char*>(&number_) + sizeof(oneof_index_));
+ if (cached_has_bits & 192u) {
+ ::memset(&number_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&oneof_index_) -
+ reinterpret_cast<char*>(&number_)) + sizeof(oneof_index_));
}
- if (_has_bits_[8 / 32] & 768u) {
+ if (cached_has_bits & 768u) {
label_ = 1;
type_ = 1;
}
@@ -4298,11 +4647,12 @@ bool FieldDescriptorProto::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional string name = 1;
case 1: {
- if (tag == 10u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormat::PARSE,
"google.protobuf.FieldDescriptorProto.name");
} else {
@@ -4313,11 +4663,12 @@ bool FieldDescriptorProto::MergePartialFromCodedStream(
// optional string extendee = 2;
case 2: {
- if (tag == 18u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_extendee()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->extendee().data(), this->extendee().length(),
+ this->extendee().data(), static_cast<int>(this->extendee().length()),
::google::protobuf::internal::WireFormat::PARSE,
"google.protobuf.FieldDescriptorProto.extendee");
} else {
@@ -4328,7 +4679,8 @@ bool FieldDescriptorProto::MergePartialFromCodedStream(
// optional int32 number = 3;
case 3: {
- if (tag == 24u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) {
set_has_number();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
@@ -4341,7 +4693,8 @@ bool FieldDescriptorProto::MergePartialFromCodedStream(
// optional .google.protobuf.FieldDescriptorProto.Label label = 4;
case 4: {
- if (tag == 32u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(32u /* 32 & 0xFF */)) {
int value;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
@@ -4349,7 +4702,8 @@ bool FieldDescriptorProto::MergePartialFromCodedStream(
if (::google::protobuf::FieldDescriptorProto_Label_IsValid(value)) {
set_label(static_cast< ::google::protobuf::FieldDescriptorProto_Label >(value));
} else {
- mutable_unknown_fields()->AddVarint(4, value);
+ mutable_unknown_fields()->AddVarint(
+ 4, static_cast< ::google::protobuf::uint64>(value));
}
} else {
goto handle_unusual;
@@ -4359,7 +4713,8 @@ bool FieldDescriptorProto::MergePartialFromCodedStream(
// optional .google.protobuf.FieldDescriptorProto.Type type = 5;
case 5: {
- if (tag == 40u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) {
int value;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
@@ -4367,7 +4722,8 @@ bool FieldDescriptorProto::MergePartialFromCodedStream(
if (::google::protobuf::FieldDescriptorProto_Type_IsValid(value)) {
set_type(static_cast< ::google::protobuf::FieldDescriptorProto_Type >(value));
} else {
- mutable_unknown_fields()->AddVarint(5, value);
+ mutable_unknown_fields()->AddVarint(
+ 5, static_cast< ::google::protobuf::uint64>(value));
}
} else {
goto handle_unusual;
@@ -4377,11 +4733,12 @@ bool FieldDescriptorProto::MergePartialFromCodedStream(
// optional string type_name = 6;
case 6: {
- if (tag == 50u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(50u /* 50 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_type_name()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->type_name().data(), this->type_name().length(),
+ this->type_name().data(), static_cast<int>(this->type_name().length()),
::google::protobuf::internal::WireFormat::PARSE,
"google.protobuf.FieldDescriptorProto.type_name");
} else {
@@ -4392,11 +4749,12 @@ bool FieldDescriptorProto::MergePartialFromCodedStream(
// optional string default_value = 7;
case 7: {
- if (tag == 58u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(58u /* 58 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_default_value()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->default_value().data(), this->default_value().length(),
+ this->default_value().data(), static_cast<int>(this->default_value().length()),
::google::protobuf::internal::WireFormat::PARSE,
"google.protobuf.FieldDescriptorProto.default_value");
} else {
@@ -4407,8 +4765,9 @@ bool FieldDescriptorProto::MergePartialFromCodedStream(
// optional .google.protobuf.FieldOptions options = 8;
case 8: {
- if (tag == 66u) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(66u /* 66 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_options()));
} else {
goto handle_unusual;
@@ -4418,7 +4777,8 @@ bool FieldDescriptorProto::MergePartialFromCodedStream(
// optional int32 oneof_index = 9;
case 9: {
- if (tag == 72u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(72u /* 72 & 0xFF */)) {
set_has_oneof_index();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
@@ -4431,11 +4791,12 @@ bool FieldDescriptorProto::MergePartialFromCodedStream(
// optional string json_name = 10;
case 10: {
- if (tag == 82u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(82u /* 82 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_json_name()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->json_name().data(), this->json_name().length(),
+ this->json_name().data(), static_cast<int>(this->json_name().length()),
::google::protobuf::internal::WireFormat::PARSE,
"google.protobuf.FieldDescriptorProto.json_name");
} else {
@@ -4446,13 +4807,11 @@ bool FieldDescriptorProto::MergePartialFromCodedStream(
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
- input, tag, mutable_unknown_fields()));
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -4469,10 +4828,14 @@ failure:
void FieldDescriptorProto::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.FieldDescriptorProto)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional string name = 1;
- if (has_name()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.FieldDescriptorProto.name");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -4480,9 +4843,9 @@ void FieldDescriptorProto::SerializeWithCachedSizes(
}
// optional string extendee = 2;
- if (has_extendee()) {
+ if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->extendee().data(), this->extendee().length(),
+ this->extendee().data(), static_cast<int>(this->extendee().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.FieldDescriptorProto.extendee");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -4490,26 +4853,26 @@ void FieldDescriptorProto::SerializeWithCachedSizes(
}
// optional int32 number = 3;
- if (has_number()) {
+ if (cached_has_bits & 0x00000040u) {
::google::protobuf::internal::WireFormatLite::WriteInt32(3, this->number(), output);
}
// optional .google.protobuf.FieldDescriptorProto.Label label = 4;
- if (has_label()) {
+ if (cached_has_bits & 0x00000100u) {
::google::protobuf::internal::WireFormatLite::WriteEnum(
4, this->label(), output);
}
// optional .google.protobuf.FieldDescriptorProto.Type type = 5;
- if (has_type()) {
+ if (cached_has_bits & 0x00000200u) {
::google::protobuf::internal::WireFormatLite::WriteEnum(
5, this->type(), output);
}
// optional string type_name = 6;
- if (has_type_name()) {
+ if (cached_has_bits & 0x00000004u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->type_name().data(), this->type_name().length(),
+ this->type_name().data(), static_cast<int>(this->type_name().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.FieldDescriptorProto.type_name");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -4517,9 +4880,9 @@ void FieldDescriptorProto::SerializeWithCachedSizes(
}
// optional string default_value = 7;
- if (has_default_value()) {
+ if (cached_has_bits & 0x00000008u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->default_value().data(), this->default_value().length(),
+ this->default_value().data(), static_cast<int>(this->default_value().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.FieldDescriptorProto.default_value");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -4527,20 +4890,20 @@ void FieldDescriptorProto::SerializeWithCachedSizes(
}
// optional .google.protobuf.FieldOptions options = 8;
- if (has_options()) {
+ if (cached_has_bits & 0x00000020u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
8, *this->options_, output);
}
// optional int32 oneof_index = 9;
- if (has_oneof_index()) {
+ if (cached_has_bits & 0x00000080u) {
::google::protobuf::internal::WireFormatLite::WriteInt32(9, this->oneof_index(), output);
}
// optional string json_name = 10;
- if (has_json_name()) {
+ if (cached_has_bits & 0x00000010u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->json_name().data(), this->json_name().length(),
+ this->json_name().data(), static_cast<int>(this->json_name().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.FieldDescriptorProto.json_name");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -4549,7 +4912,7 @@ void FieldDescriptorProto::SerializeWithCachedSizes(
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- unknown_fields(), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.FieldDescriptorProto)
}
@@ -4558,10 +4921,14 @@ void FieldDescriptorProto::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.FieldDescriptorProto)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional string name = 1;
- if (has_name()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.FieldDescriptorProto.name");
target =
@@ -4570,9 +4937,9 @@ void FieldDescriptorProto::SerializeWithCachedSizes(
}
// optional string extendee = 2;
- if (has_extendee()) {
+ if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->extendee().data(), this->extendee().length(),
+ this->extendee().data(), static_cast<int>(this->extendee().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.FieldDescriptorProto.extendee");
target =
@@ -4581,26 +4948,26 @@ void FieldDescriptorProto::SerializeWithCachedSizes(
}
// optional int32 number = 3;
- if (has_number()) {
+ if (cached_has_bits & 0x00000040u) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(3, this->number(), target);
}
// optional .google.protobuf.FieldDescriptorProto.Label label = 4;
- if (has_label()) {
+ if (cached_has_bits & 0x00000100u) {
target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray(
4, this->label(), target);
}
// optional .google.protobuf.FieldDescriptorProto.Type type = 5;
- if (has_type()) {
+ if (cached_has_bits & 0x00000200u) {
target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray(
5, this->type(), target);
}
// optional string type_name = 6;
- if (has_type_name()) {
+ if (cached_has_bits & 0x00000004u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->type_name().data(), this->type_name().length(),
+ this->type_name().data(), static_cast<int>(this->type_name().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.FieldDescriptorProto.type_name");
target =
@@ -4609,9 +4976,9 @@ void FieldDescriptorProto::SerializeWithCachedSizes(
}
// optional string default_value = 7;
- if (has_default_value()) {
+ if (cached_has_bits & 0x00000008u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->default_value().data(), this->default_value().length(),
+ this->default_value().data(), static_cast<int>(this->default_value().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.FieldDescriptorProto.default_value");
target =
@@ -4620,21 +4987,21 @@ void FieldDescriptorProto::SerializeWithCachedSizes(
}
// optional .google.protobuf.FieldOptions options = 8;
- if (has_options()) {
+ if (cached_has_bits & 0x00000020u) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 8, *this->options_, false, target);
+ InternalWriteMessageToArray(
+ 8, *this->options_, deterministic, target);
}
// optional int32 oneof_index = 9;
- if (has_oneof_index()) {
+ if (cached_has_bits & 0x00000080u) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(9, this->oneof_index(), target);
}
// optional string json_name = 10;
- if (has_json_name()) {
+ if (cached_has_bits & 0x00000010u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->json_name().data(), this->json_name().length(),
+ this->json_name().data(), static_cast<int>(this->json_name().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.FieldDescriptorProto.json_name");
target =
@@ -4644,7 +5011,7 @@ void FieldDescriptorProto::SerializeWithCachedSizes(
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- unknown_fields(), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.FieldDescriptorProto)
return target;
@@ -4657,7 +5024,7 @@ size_t FieldDescriptorProto::ByteSizeLong() const {
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- unknown_fields());
+ _internal_metadata_.unknown_fields());
}
if (_has_bits_[0 / 32] & 255u) {
// optional string name = 1;
@@ -4667,18 +5034,18 @@ size_t FieldDescriptorProto::ByteSizeLong() const {
this->name());
}
- // optional string type_name = 6;
- if (has_type_name()) {
+ // optional string extendee = 2;
+ if (has_extendee()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
- this->type_name());
+ this->extendee());
}
- // optional string extendee = 2;
- if (has_extendee()) {
+ // optional string type_name = 6;
+ if (has_type_name()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
- this->extendee());
+ this->type_name());
}
// optional string default_value = 7;
@@ -4698,7 +5065,7 @@ size_t FieldDescriptorProto::ByteSizeLong() const {
// optional .google.protobuf.FieldOptions options = 8;
if (has_options()) {
total_size += 1 +
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
*this->options_);
}
@@ -4757,44 +5124,45 @@ void FieldDescriptorProto::MergeFrom(const FieldDescriptorProto& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.FieldDescriptorProto)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
- if (from._has_bits_[0 / 32] & 255u) {
- if (from.has_name()) {
- set_has_name();
- name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = from._has_bits_[0];
+ if (cached_has_bits & 255u) {
+ if (cached_has_bits & 0x00000001u) {
+ set_name(from.name());
}
- if (from.has_type_name()) {
- set_has_type_name();
- type_name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.type_name_);
+ if (cached_has_bits & 0x00000002u) {
+ set_extendee(from.extendee());
}
- if (from.has_extendee()) {
- set_has_extendee();
- extendee_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.extendee_);
+ if (cached_has_bits & 0x00000004u) {
+ set_type_name(from.type_name());
}
- if (from.has_default_value()) {
- set_has_default_value();
- default_value_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.default_value_);
+ if (cached_has_bits & 0x00000008u) {
+ set_default_value(from.default_value());
}
- if (from.has_json_name()) {
- set_has_json_name();
- json_name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.json_name_);
+ if (cached_has_bits & 0x00000010u) {
+ set_json_name(from.json_name());
}
- if (from.has_options()) {
+ if (cached_has_bits & 0x00000020u) {
mutable_options()->::google::protobuf::FieldOptions::MergeFrom(from.options());
}
- if (from.has_number()) {
- set_number(from.number());
+ if (cached_has_bits & 0x00000040u) {
+ number_ = from.number_;
}
- if (from.has_oneof_index()) {
- set_oneof_index(from.oneof_index());
+ if (cached_has_bits & 0x00000080u) {
+ oneof_index_ = from.oneof_index_;
}
+ _has_bits_[0] |= cached_has_bits;
}
- if (from._has_bits_[8 / 32] & 768u) {
- if (from.has_label()) {
- set_label(from.label());
+ if (cached_has_bits & 768u) {
+ if (cached_has_bits & 0x00000100u) {
+ label_ = from.label_;
}
- if (from.has_type()) {
- set_type(from.type());
+ if (cached_has_bits & 0x00000200u) {
+ type_ = from.type_;
}
+ _has_bits_[0] |= cached_has_bits;
}
}
@@ -4821,449 +5189,69 @@ bool FieldDescriptorProto::IsInitialized() const {
void FieldDescriptorProto::Swap(FieldDescriptorProto* other) {
if (other == this) return;
+ if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ InternalSwap(other);
+ } else {
+ FieldDescriptorProto* temp = New(GetArenaNoVirtual());
+ temp->MergeFrom(*other);
+ other->CopyFrom(*this);
+ InternalSwap(temp);
+ if (GetArenaNoVirtual() == NULL) {
+ delete temp;
+ }
+ }
+}
+void FieldDescriptorProto::UnsafeArenaSwap(FieldDescriptorProto* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void FieldDescriptorProto::InternalSwap(FieldDescriptorProto* other) {
+ using std::swap;
name_.Swap(&other->name_);
- type_name_.Swap(&other->type_name_);
extendee_.Swap(&other->extendee_);
+ type_name_.Swap(&other->type_name_);
default_value_.Swap(&other->default_value_);
json_name_.Swap(&other->json_name_);
- std::swap(options_, other->options_);
- std::swap(number_, other->number_);
- std::swap(oneof_index_, other->oneof_index_);
- std::swap(label_, other->label_);
- std::swap(type_, other->type_);
- std::swap(_has_bits_[0], other->_has_bits_[0]);
+ swap(options_, other->options_);
+ swap(number_, other->number_);
+ swap(oneof_index_, other->oneof_index_);
+ swap(label_, other->label_);
+ swap(type_, other->type_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- std::swap(_cached_size_, other->_cached_size_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata FieldDescriptorProto::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[5];
-}
-
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// FieldDescriptorProto
-
-// optional string name = 1;
-bool FieldDescriptorProto::has_name() const {
- return (_has_bits_[0] & 0x00000001u) != 0;
-}
-void FieldDescriptorProto::set_has_name() {
- _has_bits_[0] |= 0x00000001u;
-}
-void FieldDescriptorProto::clear_has_name() {
- _has_bits_[0] &= ~0x00000001u;
-}
-void FieldDescriptorProto::clear_name() {
- name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_name();
-}
-const ::std::string& FieldDescriptorProto::name() const {
- // @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.name)
- return name_.GetNoArena();
-}
-void FieldDescriptorProto::set_name(const ::std::string& value) {
- set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.name)
-}
-void FieldDescriptorProto::set_name(const char* value) {
- set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.FieldDescriptorProto.name)
-}
-void FieldDescriptorProto::set_name(const char* value, size_t size) {
- set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.FieldDescriptorProto.name)
-}
-::std::string* FieldDescriptorProto::mutable_name() {
- set_has_name();
- // @@protoc_insertion_point(field_mutable:google.protobuf.FieldDescriptorProto.name)
- return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* FieldDescriptorProto::release_name() {
- // @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.name)
- clear_has_name();
- return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void FieldDescriptorProto::set_allocated_name(::std::string* name) {
- if (name != NULL) {
- set_has_name();
- } else {
- clear_has_name();
- }
- name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.FieldDescriptorProto.name)
-}
-
-// optional int32 number = 3;
-bool FieldDescriptorProto::has_number() const {
- return (_has_bits_[0] & 0x00000040u) != 0;
-}
-void FieldDescriptorProto::set_has_number() {
- _has_bits_[0] |= 0x00000040u;
-}
-void FieldDescriptorProto::clear_has_number() {
- _has_bits_[0] &= ~0x00000040u;
-}
-void FieldDescriptorProto::clear_number() {
- number_ = 0;
- clear_has_number();
-}
-::google::protobuf::int32 FieldDescriptorProto::number() const {
- // @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.number)
- return number_;
-}
-void FieldDescriptorProto::set_number(::google::protobuf::int32 value) {
- set_has_number();
- number_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.number)
-}
-
-// optional .google.protobuf.FieldDescriptorProto.Label label = 4;
-bool FieldDescriptorProto::has_label() const {
- return (_has_bits_[0] & 0x00000100u) != 0;
-}
-void FieldDescriptorProto::set_has_label() {
- _has_bits_[0] |= 0x00000100u;
-}
-void FieldDescriptorProto::clear_has_label() {
- _has_bits_[0] &= ~0x00000100u;
-}
-void FieldDescriptorProto::clear_label() {
- label_ = 1;
- clear_has_label();
-}
-::google::protobuf::FieldDescriptorProto_Label FieldDescriptorProto::label() const {
- // @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.label)
- return static_cast< ::google::protobuf::FieldDescriptorProto_Label >(label_);
-}
-void FieldDescriptorProto::set_label(::google::protobuf::FieldDescriptorProto_Label value) {
- assert(::google::protobuf::FieldDescriptorProto_Label_IsValid(value));
- set_has_label();
- label_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.label)
-}
-
-// optional .google.protobuf.FieldDescriptorProto.Type type = 5;
-bool FieldDescriptorProto::has_type() const {
- return (_has_bits_[0] & 0x00000200u) != 0;
-}
-void FieldDescriptorProto::set_has_type() {
- _has_bits_[0] |= 0x00000200u;
-}
-void FieldDescriptorProto::clear_has_type() {
- _has_bits_[0] &= ~0x00000200u;
-}
-void FieldDescriptorProto::clear_type() {
- type_ = 1;
- clear_has_type();
-}
-::google::protobuf::FieldDescriptorProto_Type FieldDescriptorProto::type() const {
- // @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.type)
- return static_cast< ::google::protobuf::FieldDescriptorProto_Type >(type_);
-}
-void FieldDescriptorProto::set_type(::google::protobuf::FieldDescriptorProto_Type value) {
- assert(::google::protobuf::FieldDescriptorProto_Type_IsValid(value));
- set_has_type();
- type_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.type)
-}
-
-// optional string type_name = 6;
-bool FieldDescriptorProto::has_type_name() const {
- return (_has_bits_[0] & 0x00000002u) != 0;
-}
-void FieldDescriptorProto::set_has_type_name() {
- _has_bits_[0] |= 0x00000002u;
-}
-void FieldDescriptorProto::clear_has_type_name() {
- _has_bits_[0] &= ~0x00000002u;
-}
-void FieldDescriptorProto::clear_type_name() {
- type_name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_type_name();
-}
-const ::std::string& FieldDescriptorProto::type_name() const {
- // @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.type_name)
- return type_name_.GetNoArena();
-}
-void FieldDescriptorProto::set_type_name(const ::std::string& value) {
- set_has_type_name();
- type_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.type_name)
-}
-void FieldDescriptorProto::set_type_name(const char* value) {
- set_has_type_name();
- type_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.FieldDescriptorProto.type_name)
-}
-void FieldDescriptorProto::set_type_name(const char* value, size_t size) {
- set_has_type_name();
- type_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.FieldDescriptorProto.type_name)
-}
-::std::string* FieldDescriptorProto::mutable_type_name() {
- set_has_type_name();
- // @@protoc_insertion_point(field_mutable:google.protobuf.FieldDescriptorProto.type_name)
- return type_name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* FieldDescriptorProto::release_type_name() {
- // @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.type_name)
- clear_has_type_name();
- return type_name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void FieldDescriptorProto::set_allocated_type_name(::std::string* type_name) {
- if (type_name != NULL) {
- set_has_type_name();
- } else {
- clear_has_type_name();
- }
- type_name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), type_name);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.FieldDescriptorProto.type_name)
-}
-
-// optional string extendee = 2;
-bool FieldDescriptorProto::has_extendee() const {
- return (_has_bits_[0] & 0x00000004u) != 0;
-}
-void FieldDescriptorProto::set_has_extendee() {
- _has_bits_[0] |= 0x00000004u;
-}
-void FieldDescriptorProto::clear_has_extendee() {
- _has_bits_[0] &= ~0x00000004u;
-}
-void FieldDescriptorProto::clear_extendee() {
- extendee_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_extendee();
-}
-const ::std::string& FieldDescriptorProto::extendee() const {
- // @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.extendee)
- return extendee_.GetNoArena();
-}
-void FieldDescriptorProto::set_extendee(const ::std::string& value) {
- set_has_extendee();
- extendee_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.extendee)
-}
-void FieldDescriptorProto::set_extendee(const char* value) {
- set_has_extendee();
- extendee_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.FieldDescriptorProto.extendee)
-}
-void FieldDescriptorProto::set_extendee(const char* value, size_t size) {
- set_has_extendee();
- extendee_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.FieldDescriptorProto.extendee)
-}
-::std::string* FieldDescriptorProto::mutable_extendee() {
- set_has_extendee();
- // @@protoc_insertion_point(field_mutable:google.protobuf.FieldDescriptorProto.extendee)
- return extendee_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* FieldDescriptorProto::release_extendee() {
- // @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.extendee)
- clear_has_extendee();
- return extendee_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void FieldDescriptorProto::set_allocated_extendee(::std::string* extendee) {
- if (extendee != NULL) {
- set_has_extendee();
- } else {
- clear_has_extendee();
- }
- extendee_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), extendee);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.FieldDescriptorProto.extendee)
-}
-
-// optional string default_value = 7;
-bool FieldDescriptorProto::has_default_value() const {
- return (_has_bits_[0] & 0x00000008u) != 0;
-}
-void FieldDescriptorProto::set_has_default_value() {
- _has_bits_[0] |= 0x00000008u;
-}
-void FieldDescriptorProto::clear_has_default_value() {
- _has_bits_[0] &= ~0x00000008u;
-}
-void FieldDescriptorProto::clear_default_value() {
- default_value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_default_value();
-}
-const ::std::string& FieldDescriptorProto::default_value() const {
- // @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.default_value)
- return default_value_.GetNoArena();
-}
-void FieldDescriptorProto::set_default_value(const ::std::string& value) {
- set_has_default_value();
- default_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.default_value)
-}
-void FieldDescriptorProto::set_default_value(const char* value) {
- set_has_default_value();
- default_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.FieldDescriptorProto.default_value)
-}
-void FieldDescriptorProto::set_default_value(const char* value, size_t size) {
- set_has_default_value();
- default_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.FieldDescriptorProto.default_value)
-}
-::std::string* FieldDescriptorProto::mutable_default_value() {
- set_has_default_value();
- // @@protoc_insertion_point(field_mutable:google.protobuf.FieldDescriptorProto.default_value)
- return default_value_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* FieldDescriptorProto::release_default_value() {
- // @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.default_value)
- clear_has_default_value();
- return default_value_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void FieldDescriptorProto::set_allocated_default_value(::std::string* default_value) {
- if (default_value != NULL) {
- set_has_default_value();
- } else {
- clear_has_default_value();
- }
- default_value_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), default_value);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.FieldDescriptorProto.default_value)
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
}
-// optional int32 oneof_index = 9;
-bool FieldDescriptorProto::has_oneof_index() const {
- return (_has_bits_[0] & 0x00000080u) != 0;
-}
-void FieldDescriptorProto::set_has_oneof_index() {
- _has_bits_[0] |= 0x00000080u;
-}
-void FieldDescriptorProto::clear_has_oneof_index() {
- _has_bits_[0] &= ~0x00000080u;
-}
-void FieldDescriptorProto::clear_oneof_index() {
- oneof_index_ = 0;
- clear_has_oneof_index();
-}
-::google::protobuf::int32 FieldDescriptorProto::oneof_index() const {
- // @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.oneof_index)
- return oneof_index_;
-}
-void FieldDescriptorProto::set_oneof_index(::google::protobuf::int32 value) {
- set_has_oneof_index();
- oneof_index_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.oneof_index)
-}
-// optional string json_name = 10;
-bool FieldDescriptorProto::has_json_name() const {
- return (_has_bits_[0] & 0x00000010u) != 0;
-}
-void FieldDescriptorProto::set_has_json_name() {
- _has_bits_[0] |= 0x00000010u;
-}
-void FieldDescriptorProto::clear_has_json_name() {
- _has_bits_[0] &= ~0x00000010u;
-}
-void FieldDescriptorProto::clear_json_name() {
- json_name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_json_name();
-}
-const ::std::string& FieldDescriptorProto::json_name() const {
- // @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.json_name)
- return json_name_.GetNoArena();
-}
-void FieldDescriptorProto::set_json_name(const ::std::string& value) {
- set_has_json_name();
- json_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.json_name)
-}
-void FieldDescriptorProto::set_json_name(const char* value) {
- set_has_json_name();
- json_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.FieldDescriptorProto.json_name)
-}
-void FieldDescriptorProto::set_json_name(const char* value, size_t size) {
- set_has_json_name();
- json_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.FieldDescriptorProto.json_name)
-}
-::std::string* FieldDescriptorProto::mutable_json_name() {
- set_has_json_name();
- // @@protoc_insertion_point(field_mutable:google.protobuf.FieldDescriptorProto.json_name)
- return json_name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* FieldDescriptorProto::release_json_name() {
- // @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.json_name)
- clear_has_json_name();
- return json_name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void FieldDescriptorProto::set_allocated_json_name(::std::string* json_name) {
- if (json_name != NULL) {
- set_has_json_name();
- } else {
- clear_has_json_name();
- }
- json_name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), json_name);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.FieldDescriptorProto.json_name)
-}
+// ===================================================================
-// optional .google.protobuf.FieldOptions options = 8;
-bool FieldDescriptorProto::has_options() const {
- return (_has_bits_[0] & 0x00000020u) != 0;
-}
-void FieldDescriptorProto::set_has_options() {
- _has_bits_[0] |= 0x00000020u;
-}
-void FieldDescriptorProto::clear_has_options() {
- _has_bits_[0] &= ~0x00000020u;
-}
-void FieldDescriptorProto::clear_options() {
- if (options_ != NULL) options_->::google::protobuf::FieldOptions::Clear();
- clear_has_options();
+void OneofDescriptorProto::InitAsDefaultInstance() {
+ ::google::protobuf::_OneofDescriptorProto_default_instance_._instance.get_mutable()->options_ = const_cast< ::google::protobuf::OneofOptions*>(
+ ::google::protobuf::OneofOptions::internal_default_instance());
}
-const ::google::protobuf::FieldOptions& FieldDescriptorProto::options() const {
- // @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.options)
- return options_ != NULL ? *options_
- : *::google::protobuf::FieldOptions::internal_default_instance();
+void OneofDescriptorProto::_slow_mutable_options() {
+ options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::OneofOptions >(
+ GetArenaNoVirtual());
}
-::google::protobuf::FieldOptions* FieldDescriptorProto::mutable_options() {
- set_has_options();
- if (options_ == NULL) {
- options_ = new ::google::protobuf::FieldOptions;
+void OneofDescriptorProto::unsafe_arena_set_allocated_options(
+ ::google::protobuf::OneofOptions* options) {
+ if (GetArenaNoVirtual() == NULL) {
+ delete options_;
}
- // @@protoc_insertion_point(field_mutable:google.protobuf.FieldDescriptorProto.options)
- return options_;
-}
-::google::protobuf::FieldOptions* FieldDescriptorProto::release_options() {
- // @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.options)
- clear_has_options();
- ::google::protobuf::FieldOptions* temp = options_;
- options_ = NULL;
- return temp;
-}
-void FieldDescriptorProto::set_allocated_options(::google::protobuf::FieldOptions* options) {
- delete options_;
options_ = options;
if (options) {
set_has_options();
} else {
clear_has_options();
}
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.FieldDescriptorProto.options)
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.OneofDescriptorProto.options)
}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
-
-// ===================================================================
-
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int OneofDescriptorProto::kNameFieldNumber;
const int OneofDescriptorProto::kOptionsFieldNumber;
@@ -5272,11 +5260,19 @@ const int OneofDescriptorProto::kOptionsFieldNumber;
OneofDescriptorProto::OneofDescriptorProto()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofDescriptorProto();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.OneofDescriptorProto)
}
+OneofDescriptorProto::OneofDescriptorProto(::google::protobuf::Arena* arena)
+ : ::google::protobuf::Message(),
+ _internal_metadata_(arena) {
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofDescriptorProto();
+ SharedCtor();
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.OneofDescriptorProto)
+}
OneofDescriptorProto::OneofDescriptorProto(const OneofDescriptorProto& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
@@ -5285,7 +5281,8 @@ OneofDescriptorProto::OneofDescriptorProto(const OneofDescriptorProto& from)
_internal_metadata_.MergeFrom(from._internal_metadata_);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_name()) {
- name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_);
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name(),
+ GetArenaNoVirtual());
}
if (from.has_options()) {
options_ = new ::google::protobuf::OneofOptions(*from.options_);
@@ -5307,45 +5304,51 @@ OneofDescriptorProto::~OneofDescriptorProto() {
}
void OneofDescriptorProto::SharedDtor() {
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- if (this != internal_default_instance()) {
- delete options_;
- }
+ if (this != internal_default_instance()) delete options_;
}
+void OneofDescriptorProto::ArenaDtor(void* object) {
+ OneofDescriptorProto* _this = reinterpret_cast< OneofDescriptorProto* >(object);
+ (void)_this;
+}
+void OneofDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+}
void OneofDescriptorProto::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* OneofDescriptorProto::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[6].descriptor;
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const OneofDescriptorProto& OneofDescriptorProto::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofDescriptorProto();
return *internal_default_instance();
}
OneofDescriptorProto* OneofDescriptorProto::New(::google::protobuf::Arena* arena) const {
- OneofDescriptorProto* n = new OneofDescriptorProto;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
+ return ::google::protobuf::Arena::CreateMessage<OneofDescriptorProto>(arena);
}
void OneofDescriptorProto::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.OneofDescriptorProto)
- if (_has_bits_[0 / 32] & 3u) {
- if (has_name()) {
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
+ if (cached_has_bits & 3u) {
+ if (cached_has_bits & 0x00000001u) {
GOOGLE_DCHECK(!name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- (*name_.UnsafeRawStringPointer())->clear();
+ name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- if (has_options()) {
+ if (cached_has_bits & 0x00000002u) {
GOOGLE_DCHECK(options_ != NULL);
- options_->::google::protobuf::OneofOptions::Clear();
+ options_->Clear();
}
}
_has_bits_.Clear();
@@ -5364,11 +5367,12 @@ bool OneofDescriptorProto::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional string name = 1;
case 1: {
- if (tag == 10u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormat::PARSE,
"google.protobuf.OneofDescriptorProto.name");
} else {
@@ -5379,8 +5383,9 @@ bool OneofDescriptorProto::MergePartialFromCodedStream(
// optional .google.protobuf.OneofOptions options = 2;
case 2: {
- if (tag == 18u) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_options()));
} else {
goto handle_unusual;
@@ -5390,13 +5395,11 @@ bool OneofDescriptorProto::MergePartialFromCodedStream(
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
- input, tag, mutable_unknown_fields()));
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -5413,10 +5416,14 @@ failure:
void OneofDescriptorProto::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.OneofDescriptorProto)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional string name = 1;
- if (has_name()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.OneofDescriptorProto.name");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -5424,14 +5431,14 @@ void OneofDescriptorProto::SerializeWithCachedSizes(
}
// optional .google.protobuf.OneofOptions options = 2;
- if (has_options()) {
+ if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
2, *this->options_, output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- unknown_fields(), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.OneofDescriptorProto)
}
@@ -5440,10 +5447,14 @@ void OneofDescriptorProto::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.OneofDescriptorProto)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional string name = 1;
- if (has_name()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.OneofDescriptorProto.name");
target =
@@ -5452,15 +5463,15 @@ void OneofDescriptorProto::SerializeWithCachedSizes(
}
// optional .google.protobuf.OneofOptions options = 2;
- if (has_options()) {
+ if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 2, *this->options_, false, target);
+ InternalWriteMessageToArray(
+ 2, *this->options_, deterministic, target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- unknown_fields(), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.OneofDescriptorProto)
return target;
@@ -5473,7 +5484,7 @@ size_t OneofDescriptorProto::ByteSizeLong() const {
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- unknown_fields());
+ _internal_metadata_.unknown_fields());
}
if (_has_bits_[0 / 32] & 3u) {
// optional string name = 1;
@@ -5486,7 +5497,7 @@ size_t OneofDescriptorProto::ByteSizeLong() const {
// optional .google.protobuf.OneofOptions options = 2;
if (has_options()) {
total_size += 1 +
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
*this->options_);
}
@@ -5517,12 +5528,15 @@ void OneofDescriptorProto::MergeFrom(const OneofDescriptorProto& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.OneofDescriptorProto)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
- if (from._has_bits_[0 / 32] & 3u) {
- if (from.has_name()) {
- set_has_name();
- name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = from._has_bits_[0];
+ if (cached_has_bits & 3u) {
+ if (cached_has_bits & 0x00000001u) {
+ set_name(from.name());
}
- if (from.has_options()) {
+ if (cached_has_bits & 0x00000002u) {
mutable_options()->::google::protobuf::OneofOptions::MergeFrom(from.options());
}
}
@@ -5551,151 +5565,421 @@ bool OneofDescriptorProto::IsInitialized() const {
void OneofDescriptorProto::Swap(OneofDescriptorProto* other) {
if (other == this) return;
+ if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ InternalSwap(other);
+ } else {
+ OneofDescriptorProto* temp = New(GetArenaNoVirtual());
+ temp->MergeFrom(*other);
+ other->CopyFrom(*this);
+ InternalSwap(temp);
+ if (GetArenaNoVirtual() == NULL) {
+ delete temp;
+ }
+ }
+}
+void OneofDescriptorProto::UnsafeArenaSwap(OneofDescriptorProto* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void OneofDescriptorProto::InternalSwap(OneofDescriptorProto* other) {
+ using std::swap;
name_.Swap(&other->name_);
- std::swap(options_, other->options_);
- std::swap(_has_bits_[0], other->_has_bits_[0]);
+ swap(options_, other->options_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- std::swap(_cached_size_, other->_cached_size_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata OneofDescriptorProto::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[6];
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// OneofDescriptorProto
-// optional string name = 1;
-bool OneofDescriptorProto::has_name() const {
- return (_has_bits_[0] & 0x00000001u) != 0;
+// ===================================================================
+
+void EnumDescriptorProto_EnumReservedRange::InitAsDefaultInstance() {
}
-void OneofDescriptorProto::set_has_name() {
- _has_bits_[0] |= 0x00000001u;
+#if !defined(_MSC_VER) || _MSC_VER >= 1900
+const int EnumDescriptorProto_EnumReservedRange::kStartFieldNumber;
+const int EnumDescriptorProto_EnumReservedRange::kEndFieldNumber;
+#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
+
+EnumDescriptorProto_EnumReservedRange::EnumDescriptorProto_EnumReservedRange()
+ : ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto_EnumReservedRange();
+ }
+ SharedCtor();
+ // @@protoc_insertion_point(constructor:google.protobuf.EnumDescriptorProto.EnumReservedRange)
}
-void OneofDescriptorProto::clear_has_name() {
- _has_bits_[0] &= ~0x00000001u;
+EnumDescriptorProto_EnumReservedRange::EnumDescriptorProto_EnumReservedRange(::google::protobuf::Arena* arena)
+ : ::google::protobuf::Message(),
+ _internal_metadata_(arena) {
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto_EnumReservedRange();
+ SharedCtor();
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.EnumDescriptorProto.EnumReservedRange)
}
-void OneofDescriptorProto::clear_name() {
- name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_name();
+EnumDescriptorProto_EnumReservedRange::EnumDescriptorProto_EnumReservedRange(const EnumDescriptorProto_EnumReservedRange& from)
+ : ::google::protobuf::Message(),
+ _internal_metadata_(NULL),
+ _has_bits_(from._has_bits_),
+ _cached_size_(0) {
+ _internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::memcpy(&start_, &from.start_,
+ static_cast<size_t>(reinterpret_cast<char*>(&end_) -
+ reinterpret_cast<char*>(&start_)) + sizeof(end_));
+ // @@protoc_insertion_point(copy_constructor:google.protobuf.EnumDescriptorProto.EnumReservedRange)
}
-const ::std::string& OneofDescriptorProto::name() const {
- // @@protoc_insertion_point(field_get:google.protobuf.OneofDescriptorProto.name)
- return name_.GetNoArena();
+
+void EnumDescriptorProto_EnumReservedRange::SharedCtor() {
+ _cached_size_ = 0;
+ ::memset(&start_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&end_) -
+ reinterpret_cast<char*>(&start_)) + sizeof(end_));
}
-void OneofDescriptorProto::set_name(const ::std::string& value) {
- set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.OneofDescriptorProto.name)
+
+EnumDescriptorProto_EnumReservedRange::~EnumDescriptorProto_EnumReservedRange() {
+ // @@protoc_insertion_point(destructor:google.protobuf.EnumDescriptorProto.EnumReservedRange)
+ SharedDtor();
}
-void OneofDescriptorProto::set_name(const char* value) {
- set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.OneofDescriptorProto.name)
+
+void EnumDescriptorProto_EnumReservedRange::SharedDtor() {
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
}
-void OneofDescriptorProto::set_name(const char* value, size_t size) {
- set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.OneofDescriptorProto.name)
+
+void EnumDescriptorProto_EnumReservedRange::ArenaDtor(void* object) {
+ EnumDescriptorProto_EnumReservedRange* _this = reinterpret_cast< EnumDescriptorProto_EnumReservedRange* >(object);
+ (void)_this;
}
-::std::string* OneofDescriptorProto::mutable_name() {
- set_has_name();
- // @@protoc_insertion_point(field_mutable:google.protobuf.OneofDescriptorProto.name)
- return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+void EnumDescriptorProto_EnumReservedRange::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
-::std::string* OneofDescriptorProto::release_name() {
- // @@protoc_insertion_point(field_release:google.protobuf.OneofDescriptorProto.name)
- clear_has_name();
- return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+void EnumDescriptorProto_EnumReservedRange::SetCachedSize(int size) const {
+ GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
+ _cached_size_ = size;
+ GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
-void OneofDescriptorProto::set_allocated_name(::std::string* name) {
- if (name != NULL) {
- set_has_name();
- } else {
- clear_has_name();
+const ::google::protobuf::Descriptor* EnumDescriptorProto_EnumReservedRange::descriptor() {
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
+}
+
+const EnumDescriptorProto_EnumReservedRange& EnumDescriptorProto_EnumReservedRange::default_instance() {
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto_EnumReservedRange();
+ return *internal_default_instance();
+}
+
+EnumDescriptorProto_EnumReservedRange* EnumDescriptorProto_EnumReservedRange::New(::google::protobuf::Arena* arena) const {
+ return ::google::protobuf::Arena::CreateMessage<EnumDescriptorProto_EnumReservedRange>(arena);
+}
+
+void EnumDescriptorProto_EnumReservedRange::Clear() {
+// @@protoc_insertion_point(message_clear_start:google.protobuf.EnumDescriptorProto.EnumReservedRange)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
+ if (cached_has_bits & 3u) {
+ ::memset(&start_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&end_) -
+ reinterpret_cast<char*>(&start_)) + sizeof(end_));
}
- name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.OneofDescriptorProto.name)
+ _has_bits_.Clear();
+ _internal_metadata_.Clear();
}
-// optional .google.protobuf.OneofOptions options = 2;
-bool OneofDescriptorProto::has_options() const {
- return (_has_bits_[0] & 0x00000002u) != 0;
+bool EnumDescriptorProto_EnumReservedRange::MergePartialFromCodedStream(
+ ::google::protobuf::io::CodedInputStream* input) {
+#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+ ::google::protobuf::uint32 tag;
+ // @@protoc_insertion_point(parse_start:google.protobuf.EnumDescriptorProto.EnumReservedRange)
+ for (;;) {
+ ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
+ tag = p.first;
+ if (!p.second) goto handle_unusual;
+ switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
+ // optional int32 start = 1;
+ case 1: {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
+ set_has_start();
+ DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
+ ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
+ input, &start_)));
+ } else {
+ goto handle_unusual;
+ }
+ break;
+ }
+
+ // optional int32 end = 2;
+ case 2: {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
+ set_has_end();
+ DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
+ ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
+ input, &end_)));
+ } else {
+ goto handle_unusual;
+ }
+ break;
+ }
+
+ default: {
+ handle_unusual:
+ if (tag == 0) {
+ goto success;
+ }
+ DO_(::google::protobuf::internal::WireFormat::SkipField(
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
+ break;
+ }
+ }
+ }
+success:
+ // @@protoc_insertion_point(parse_success:google.protobuf.EnumDescriptorProto.EnumReservedRange)
+ return true;
+failure:
+ // @@protoc_insertion_point(parse_failure:google.protobuf.EnumDescriptorProto.EnumReservedRange)
+ return false;
+#undef DO_
}
-void OneofDescriptorProto::set_has_options() {
- _has_bits_[0] |= 0x00000002u;
+
+void EnumDescriptorProto_EnumReservedRange::SerializeWithCachedSizes(
+ ::google::protobuf::io::CodedOutputStream* output) const {
+ // @@protoc_insertion_point(serialize_start:google.protobuf.EnumDescriptorProto.EnumReservedRange)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
+ // optional int32 start = 1;
+ if (cached_has_bits & 0x00000001u) {
+ ::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->start(), output);
+ }
+
+ // optional int32 end = 2;
+ if (cached_has_bits & 0x00000002u) {
+ ::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->end(), output);
+ }
+
+ if (_internal_metadata_.have_unknown_fields()) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ _internal_metadata_.unknown_fields(), output);
+ }
+ // @@protoc_insertion_point(serialize_end:google.protobuf.EnumDescriptorProto.EnumReservedRange)
}
-void OneofDescriptorProto::clear_has_options() {
- _has_bits_[0] &= ~0x00000002u;
+
+::google::protobuf::uint8* EnumDescriptorProto_EnumReservedRange::InternalSerializeWithCachedSizesToArray(
+ bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
+ // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.EnumDescriptorProto.EnumReservedRange)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
+ // optional int32 start = 1;
+ if (cached_has_bits & 0x00000001u) {
+ target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->start(), target);
+ }
+
+ // optional int32 end = 2;
+ if (cached_has_bits & 0x00000002u) {
+ target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->end(), target);
+ }
+
+ if (_internal_metadata_.have_unknown_fields()) {
+ target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
+ _internal_metadata_.unknown_fields(), target);
+ }
+ // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.EnumDescriptorProto.EnumReservedRange)
+ return target;
}
-void OneofDescriptorProto::clear_options() {
- if (options_ != NULL) options_->::google::protobuf::OneofOptions::Clear();
- clear_has_options();
+
+size_t EnumDescriptorProto_EnumReservedRange::ByteSizeLong() const {
+// @@protoc_insertion_point(message_byte_size_start:google.protobuf.EnumDescriptorProto.EnumReservedRange)
+ size_t total_size = 0;
+
+ if (_internal_metadata_.have_unknown_fields()) {
+ total_size +=
+ ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
+ _internal_metadata_.unknown_fields());
+ }
+ if (_has_bits_[0 / 32] & 3u) {
+ // optional int32 start = 1;
+ if (has_start()) {
+ total_size += 1 +
+ ::google::protobuf::internal::WireFormatLite::Int32Size(
+ this->start());
+ }
+
+ // optional int32 end = 2;
+ if (has_end()) {
+ total_size += 1 +
+ ::google::protobuf::internal::WireFormatLite::Int32Size(
+ this->end());
+ }
+
+ }
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
+ GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
+ _cached_size_ = cached_size;
+ GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ return total_size;
}
-const ::google::protobuf::OneofOptions& OneofDescriptorProto::options() const {
- // @@protoc_insertion_point(field_get:google.protobuf.OneofDescriptorProto.options)
- return options_ != NULL ? *options_
- : *::google::protobuf::OneofOptions::internal_default_instance();
+
+void EnumDescriptorProto_EnumReservedRange::MergeFrom(const ::google::protobuf::Message& from) {
+// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.EnumDescriptorProto.EnumReservedRange)
+ GOOGLE_DCHECK_NE(&from, this);
+ const EnumDescriptorProto_EnumReservedRange* source =
+ ::google::protobuf::internal::DynamicCastToGenerated<const EnumDescriptorProto_EnumReservedRange>(
+ &from);
+ if (source == NULL) {
+ // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.EnumDescriptorProto.EnumReservedRange)
+ ::google::protobuf::internal::ReflectionOps::Merge(from, this);
+ } else {
+ // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.EnumDescriptorProto.EnumReservedRange)
+ MergeFrom(*source);
+ }
}
-::google::protobuf::OneofOptions* OneofDescriptorProto::mutable_options() {
- set_has_options();
- if (options_ == NULL) {
- options_ = new ::google::protobuf::OneofOptions;
+
+void EnumDescriptorProto_EnumReservedRange::MergeFrom(const EnumDescriptorProto_EnumReservedRange& from) {
+// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.EnumDescriptorProto.EnumReservedRange)
+ GOOGLE_DCHECK_NE(&from, this);
+ _internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = from._has_bits_[0];
+ if (cached_has_bits & 3u) {
+ if (cached_has_bits & 0x00000001u) {
+ start_ = from.start_;
+ }
+ if (cached_has_bits & 0x00000002u) {
+ end_ = from.end_;
+ }
+ _has_bits_[0] |= cached_has_bits;
}
- // @@protoc_insertion_point(field_mutable:google.protobuf.OneofDescriptorProto.options)
- return options_;
}
-::google::protobuf::OneofOptions* OneofDescriptorProto::release_options() {
- // @@protoc_insertion_point(field_release:google.protobuf.OneofDescriptorProto.options)
- clear_has_options();
- ::google::protobuf::OneofOptions* temp = options_;
- options_ = NULL;
- return temp;
+
+void EnumDescriptorProto_EnumReservedRange::CopyFrom(const ::google::protobuf::Message& from) {
+// @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.EnumDescriptorProto.EnumReservedRange)
+ if (&from == this) return;
+ Clear();
+ MergeFrom(from);
}
-void OneofDescriptorProto::set_allocated_options(::google::protobuf::OneofOptions* options) {
- delete options_;
- options_ = options;
- if (options) {
- set_has_options();
+
+void EnumDescriptorProto_EnumReservedRange::CopyFrom(const EnumDescriptorProto_EnumReservedRange& from) {
+// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.EnumDescriptorProto.EnumReservedRange)
+ if (&from == this) return;
+ Clear();
+ MergeFrom(from);
+}
+
+bool EnumDescriptorProto_EnumReservedRange::IsInitialized() const {
+ return true;
+}
+
+void EnumDescriptorProto_EnumReservedRange::Swap(EnumDescriptorProto_EnumReservedRange* other) {
+ if (other == this) return;
+ if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ InternalSwap(other);
} else {
- clear_has_options();
+ EnumDescriptorProto_EnumReservedRange* temp = New(GetArenaNoVirtual());
+ temp->MergeFrom(*other);
+ other->CopyFrom(*this);
+ InternalSwap(temp);
+ if (GetArenaNoVirtual() == NULL) {
+ delete temp;
+ }
}
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.OneofDescriptorProto.options)
+}
+void EnumDescriptorProto_EnumReservedRange::UnsafeArenaSwap(EnumDescriptorProto_EnumReservedRange* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ InternalSwap(other);
+}
+void EnumDescriptorProto_EnumReservedRange::InternalSwap(EnumDescriptorProto_EnumReservedRange* other) {
+ using std::swap;
+ swap(start_, other->start_);
+ swap(end_, other->end_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_cached_size_, other->_cached_size_);
+}
+
+::google::protobuf::Metadata EnumDescriptorProto_EnumReservedRange::GetMetadata() const {
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
+void EnumDescriptorProto::InitAsDefaultInstance() {
+ ::google::protobuf::_EnumDescriptorProto_default_instance_._instance.get_mutable()->options_ = const_cast< ::google::protobuf::EnumOptions*>(
+ ::google::protobuf::EnumOptions::internal_default_instance());
+}
+void EnumDescriptorProto::_slow_mutable_options() {
+ options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::EnumOptions >(
+ GetArenaNoVirtual());
+}
+void EnumDescriptorProto::unsafe_arena_set_allocated_options(
+ ::google::protobuf::EnumOptions* options) {
+ if (GetArenaNoVirtual() == NULL) {
+ delete options_;
+ }
+ options_ = options;
+ if (options) {
+ set_has_options();
+ } else {
+ clear_has_options();
+ }
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.EnumDescriptorProto.options)
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int EnumDescriptorProto::kNameFieldNumber;
const int EnumDescriptorProto::kValueFieldNumber;
const int EnumDescriptorProto::kOptionsFieldNumber;
+const int EnumDescriptorProto::kReservedRangeFieldNumber;
+const int EnumDescriptorProto::kReservedNameFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
EnumDescriptorProto::EnumDescriptorProto()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.EnumDescriptorProto)
}
+EnumDescriptorProto::EnumDescriptorProto(::google::protobuf::Arena* arena)
+ : ::google::protobuf::Message(),
+ _internal_metadata_(arena),
+ value_(arena),
+ reserved_range_(arena),
+ reserved_name_(arena) {
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto();
+ SharedCtor();
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.EnumDescriptorProto)
+}
EnumDescriptorProto::EnumDescriptorProto(const EnumDescriptorProto& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
_cached_size_(0),
- value_(from.value_) {
+ value_(from.value_),
+ reserved_range_(from.reserved_range_),
+ reserved_name_(from.reserved_name_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_name()) {
- name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_);
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name(),
+ GetArenaNoVirtual());
}
if (from.has_options()) {
options_ = new ::google::protobuf::EnumOptions(*from.options_);
@@ -5717,46 +6001,54 @@ EnumDescriptorProto::~EnumDescriptorProto() {
}
void EnumDescriptorProto::SharedDtor() {
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- if (this != internal_default_instance()) {
- delete options_;
- }
+ if (this != internal_default_instance()) delete options_;
}
+void EnumDescriptorProto::ArenaDtor(void* object) {
+ EnumDescriptorProto* _this = reinterpret_cast< EnumDescriptorProto* >(object);
+ (void)_this;
+}
+void EnumDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+}
void EnumDescriptorProto::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* EnumDescriptorProto::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[7].descriptor;
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const EnumDescriptorProto& EnumDescriptorProto::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto();
return *internal_default_instance();
}
EnumDescriptorProto* EnumDescriptorProto::New(::google::protobuf::Arena* arena) const {
- EnumDescriptorProto* n = new EnumDescriptorProto;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
+ return ::google::protobuf::Arena::CreateMessage<EnumDescriptorProto>(arena);
}
void EnumDescriptorProto::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.EnumDescriptorProto)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
value_.Clear();
- if (_has_bits_[0 / 32] & 3u) {
- if (has_name()) {
+ reserved_range_.Clear();
+ reserved_name_.Clear();
+ cached_has_bits = _has_bits_[0];
+ if (cached_has_bits & 3u) {
+ if (cached_has_bits & 0x00000001u) {
GOOGLE_DCHECK(!name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- (*name_.UnsafeRawStringPointer())->clear();
+ name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- if (has_options()) {
+ if (cached_has_bits & 0x00000002u) {
GOOGLE_DCHECK(options_ != NULL);
- options_->::google::protobuf::EnumOptions::Clear();
+ options_->Clear();
}
}
_has_bits_.Clear();
@@ -5775,11 +6067,12 @@ bool EnumDescriptorProto::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional string name = 1;
case 1: {
- if (tag == 10u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormat::PARSE,
"google.protobuf.EnumDescriptorProto.name");
} else {
@@ -5790,21 +6083,20 @@ bool EnumDescriptorProto::MergePartialFromCodedStream(
// repeated .google.protobuf.EnumValueDescriptorProto value = 2;
case 2: {
- if (tag == 18u) {
- DO_(input->IncrementRecursionDepth());
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
- input, add_value()));
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_value()));
} else {
goto handle_unusual;
}
- input->UnsafeDecrementRecursionDepth();
break;
}
// optional .google.protobuf.EnumOptions options = 3;
case 3: {
- if (tag == 26u) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_options()));
} else {
goto handle_unusual;
@@ -5812,15 +6104,41 @@ bool EnumDescriptorProto::MergePartialFromCodedStream(
break;
}
+ // repeated .google.protobuf.EnumDescriptorProto.EnumReservedRange reserved_range = 4;
+ case 4: {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_reserved_range()));
+ } else {
+ goto handle_unusual;
+ }
+ break;
+ }
+
+ // repeated string reserved_name = 5;
+ case 5: {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(42u /* 42 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadString(
+ input, this->add_reserved_name()));
+ ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
+ this->reserved_name(this->reserved_name_size() - 1).data(),
+ static_cast<int>(this->reserved_name(this->reserved_name_size() - 1).length()),
+ ::google::protobuf::internal::WireFormat::PARSE,
+ "google.protobuf.EnumDescriptorProto.reserved_name");
+ } else {
+ goto handle_unusual;
+ }
+ break;
+ }
+
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
- input, tag, mutable_unknown_fields()));
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -5837,10 +6155,14 @@ failure:
void EnumDescriptorProto::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.EnumDescriptorProto)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional string name = 1;
- if (has_name()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.EnumDescriptorProto.name");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -5848,20 +6170,38 @@ void EnumDescriptorProto::SerializeWithCachedSizes(
}
// repeated .google.protobuf.EnumValueDescriptorProto value = 2;
- for (unsigned int i = 0, n = this->value_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->value_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 2, this->value(i), output);
+ 2, this->value(static_cast<int>(i)), output);
}
// optional .google.protobuf.EnumOptions options = 3;
- if (has_options()) {
+ if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
3, *this->options_, output);
}
+ // repeated .google.protobuf.EnumDescriptorProto.EnumReservedRange reserved_range = 4;
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->reserved_range_size()); i < n; i++) {
+ ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
+ 4, this->reserved_range(static_cast<int>(i)), output);
+ }
+
+ // repeated string reserved_name = 5;
+ for (int i = 0, n = this->reserved_name_size(); i < n; i++) {
+ ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
+ this->reserved_name(i).data(), static_cast<int>(this->reserved_name(i).length()),
+ ::google::protobuf::internal::WireFormat::SERIALIZE,
+ "google.protobuf.EnumDescriptorProto.reserved_name");
+ ::google::protobuf::internal::WireFormatLite::WriteString(
+ 5, this->reserved_name(i), output);
+ }
+
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- unknown_fields(), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.EnumDescriptorProto)
}
@@ -5870,10 +6210,14 @@ void EnumDescriptorProto::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.EnumDescriptorProto)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional string name = 1;
- if (has_name()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.EnumDescriptorProto.name");
target =
@@ -5882,22 +6226,41 @@ void EnumDescriptorProto::SerializeWithCachedSizes(
}
// repeated .google.protobuf.EnumValueDescriptorProto value = 2;
- for (unsigned int i = 0, n = this->value_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->value_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 2, this->value(i), false, target);
+ InternalWriteMessageToArray(
+ 2, this->value(static_cast<int>(i)), deterministic, target);
}
// optional .google.protobuf.EnumOptions options = 3;
- if (has_options()) {
+ if (cached_has_bits & 0x00000002u) {
+ target = ::google::protobuf::internal::WireFormatLite::
+ InternalWriteMessageToArray(
+ 3, *this->options_, deterministic, target);
+ }
+
+ // repeated .google.protobuf.EnumDescriptorProto.EnumReservedRange reserved_range = 4;
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->reserved_range_size()); i < n; i++) {
+ target = ::google::protobuf::internal::WireFormatLite::
+ InternalWriteMessageToArray(
+ 4, this->reserved_range(static_cast<int>(i)), deterministic, target);
+ }
+
+ // repeated string reserved_name = 5;
+ for (int i = 0, n = this->reserved_name_size(); i < n; i++) {
+ ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
+ this->reserved_name(i).data(), static_cast<int>(this->reserved_name(i).length()),
+ ::google::protobuf::internal::WireFormat::SERIALIZE,
+ "google.protobuf.EnumDescriptorProto.reserved_name");
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 3, *this->options_, false, target);
+ WriteStringToArray(5, this->reserved_name(i), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- unknown_fields(), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.EnumDescriptorProto)
return target;
@@ -5910,19 +6273,38 @@ size_t EnumDescriptorProto::ByteSizeLong() const {
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- unknown_fields());
+ _internal_metadata_.unknown_fields());
}
// repeated .google.protobuf.EnumValueDescriptorProto value = 2;
{
- unsigned int count = this->value_size();
+ unsigned int count = static_cast<unsigned int>(this->value_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->value(i));
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->value(static_cast<int>(i)));
}
}
+ // repeated .google.protobuf.EnumDescriptorProto.EnumReservedRange reserved_range = 4;
+ {
+ unsigned int count = static_cast<unsigned int>(this->reserved_range_size());
+ total_size += 1UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->reserved_range(static_cast<int>(i)));
+ }
+ }
+
+ // repeated string reserved_name = 5;
+ total_size += 1 *
+ ::google::protobuf::internal::FromIntSize(this->reserved_name_size());
+ for (int i = 0, n = this->reserved_name_size(); i < n; i++) {
+ total_size += ::google::protobuf::internal::WireFormatLite::StringSize(
+ this->reserved_name(i));
+ }
+
if (_has_bits_[0 / 32] & 3u) {
// optional string name = 1;
if (has_name()) {
@@ -5934,7 +6316,7 @@ size_t EnumDescriptorProto::ByteSizeLong() const {
// optional .google.protobuf.EnumOptions options = 3;
if (has_options()) {
total_size += 1 +
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
*this->options_);
}
@@ -5965,13 +6347,18 @@ void EnumDescriptorProto::MergeFrom(const EnumDescriptorProto& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.EnumDescriptorProto)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
value_.MergeFrom(from.value_);
- if (from._has_bits_[0 / 32] & 3u) {
- if (from.has_name()) {
- set_has_name();
- name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_);
+ reserved_range_.MergeFrom(from.reserved_range_);
+ reserved_name_.MergeFrom(from.reserved_name_);
+ cached_has_bits = from._has_bits_[0];
+ if (cached_has_bits & 3u) {
+ if (cached_has_bits & 0x00000001u) {
+ set_name(from.name());
}
- if (from.has_options()) {
+ if (cached_has_bits & 0x00000002u) {
mutable_options()->::google::protobuf::EnumOptions::MergeFrom(from.options());
}
}
@@ -6001,158 +6388,64 @@ bool EnumDescriptorProto::IsInitialized() const {
void EnumDescriptorProto::Swap(EnumDescriptorProto* other) {
if (other == this) return;
+ if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ InternalSwap(other);
+ } else {
+ EnumDescriptorProto* temp = New(GetArenaNoVirtual());
+ temp->MergeFrom(*other);
+ other->CopyFrom(*this);
+ InternalSwap(temp);
+ if (GetArenaNoVirtual() == NULL) {
+ delete temp;
+ }
+ }
+}
+void EnumDescriptorProto::UnsafeArenaSwap(EnumDescriptorProto* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void EnumDescriptorProto::InternalSwap(EnumDescriptorProto* other) {
- value_.UnsafeArenaSwap(&other->value_);
+ using std::swap;
+ value_.InternalSwap(&other->value_);
+ reserved_range_.InternalSwap(&other->reserved_range_);
+ reserved_name_.InternalSwap(&other->reserved_name_);
name_.Swap(&other->name_);
- std::swap(options_, other->options_);
- std::swap(_has_bits_[0], other->_has_bits_[0]);
+ swap(options_, other->options_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- std::swap(_cached_size_, other->_cached_size_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata EnumDescriptorProto::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[7];
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// EnumDescriptorProto
-// optional string name = 1;
-bool EnumDescriptorProto::has_name() const {
- return (_has_bits_[0] & 0x00000001u) != 0;
-}
-void EnumDescriptorProto::set_has_name() {
- _has_bits_[0] |= 0x00000001u;
-}
-void EnumDescriptorProto::clear_has_name() {
- _has_bits_[0] &= ~0x00000001u;
-}
-void EnumDescriptorProto::clear_name() {
- name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_name();
-}
-const ::std::string& EnumDescriptorProto::name() const {
- // @@protoc_insertion_point(field_get:google.protobuf.EnumDescriptorProto.name)
- return name_.GetNoArena();
-}
-void EnumDescriptorProto::set_name(const ::std::string& value) {
- set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.EnumDescriptorProto.name)
-}
-void EnumDescriptorProto::set_name(const char* value) {
- set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.EnumDescriptorProto.name)
-}
-void EnumDescriptorProto::set_name(const char* value, size_t size) {
- set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.EnumDescriptorProto.name)
-}
-::std::string* EnumDescriptorProto::mutable_name() {
- set_has_name();
- // @@protoc_insertion_point(field_mutable:google.protobuf.EnumDescriptorProto.name)
- return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* EnumDescriptorProto::release_name() {
- // @@protoc_insertion_point(field_release:google.protobuf.EnumDescriptorProto.name)
- clear_has_name();
- return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void EnumDescriptorProto::set_allocated_name(::std::string* name) {
- if (name != NULL) {
- set_has_name();
- } else {
- clear_has_name();
- }
- name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.EnumDescriptorProto.name)
-}
-
-// repeated .google.protobuf.EnumValueDescriptorProto value = 2;
-int EnumDescriptorProto::value_size() const {
- return value_.size();
-}
-void EnumDescriptorProto::clear_value() {
- value_.Clear();
-}
-const ::google::protobuf::EnumValueDescriptorProto& EnumDescriptorProto::value(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.EnumDescriptorProto.value)
- return value_.Get(index);
-}
-::google::protobuf::EnumValueDescriptorProto* EnumDescriptorProto::mutable_value(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.EnumDescriptorProto.value)
- return value_.Mutable(index);
-}
-::google::protobuf::EnumValueDescriptorProto* EnumDescriptorProto::add_value() {
- // @@protoc_insertion_point(field_add:google.protobuf.EnumDescriptorProto.value)
- return value_.Add();
-}
-::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumValueDescriptorProto >*
-EnumDescriptorProto::mutable_value() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.EnumDescriptorProto.value)
- return &value_;
-}
-const ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumValueDescriptorProto >&
-EnumDescriptorProto::value() const {
- // @@protoc_insertion_point(field_list:google.protobuf.EnumDescriptorProto.value)
- return value_;
-}
+// ===================================================================
-// optional .google.protobuf.EnumOptions options = 3;
-bool EnumDescriptorProto::has_options() const {
- return (_has_bits_[0] & 0x00000002u) != 0;
-}
-void EnumDescriptorProto::set_has_options() {
- _has_bits_[0] |= 0x00000002u;
-}
-void EnumDescriptorProto::clear_has_options() {
- _has_bits_[0] &= ~0x00000002u;
-}
-void EnumDescriptorProto::clear_options() {
- if (options_ != NULL) options_->::google::protobuf::EnumOptions::Clear();
- clear_has_options();
+void EnumValueDescriptorProto::InitAsDefaultInstance() {
+ ::google::protobuf::_EnumValueDescriptorProto_default_instance_._instance.get_mutable()->options_ = const_cast< ::google::protobuf::EnumValueOptions*>(
+ ::google::protobuf::EnumValueOptions::internal_default_instance());
}
-const ::google::protobuf::EnumOptions& EnumDescriptorProto::options() const {
- // @@protoc_insertion_point(field_get:google.protobuf.EnumDescriptorProto.options)
- return options_ != NULL ? *options_
- : *::google::protobuf::EnumOptions::internal_default_instance();
+void EnumValueDescriptorProto::_slow_mutable_options() {
+ options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::EnumValueOptions >(
+ GetArenaNoVirtual());
}
-::google::protobuf::EnumOptions* EnumDescriptorProto::mutable_options() {
- set_has_options();
- if (options_ == NULL) {
- options_ = new ::google::protobuf::EnumOptions;
+void EnumValueDescriptorProto::unsafe_arena_set_allocated_options(
+ ::google::protobuf::EnumValueOptions* options) {
+ if (GetArenaNoVirtual() == NULL) {
+ delete options_;
}
- // @@protoc_insertion_point(field_mutable:google.protobuf.EnumDescriptorProto.options)
- return options_;
-}
-::google::protobuf::EnumOptions* EnumDescriptorProto::release_options() {
- // @@protoc_insertion_point(field_release:google.protobuf.EnumDescriptorProto.options)
- clear_has_options();
- ::google::protobuf::EnumOptions* temp = options_;
- options_ = NULL;
- return temp;
-}
-void EnumDescriptorProto::set_allocated_options(::google::protobuf::EnumOptions* options) {
- delete options_;
options_ = options;
if (options) {
set_has_options();
} else {
clear_has_options();
}
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.EnumDescriptorProto.options)
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.EnumValueDescriptorProto.options)
}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
-
-// ===================================================================
-
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int EnumValueDescriptorProto::kNameFieldNumber;
const int EnumValueDescriptorProto::kNumberFieldNumber;
@@ -6162,11 +6455,19 @@ const int EnumValueDescriptorProto::kOptionsFieldNumber;
EnumValueDescriptorProto::EnumValueDescriptorProto()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueDescriptorProto();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.EnumValueDescriptorProto)
}
+EnumValueDescriptorProto::EnumValueDescriptorProto(::google::protobuf::Arena* arena)
+ : ::google::protobuf::Message(),
+ _internal_metadata_(arena) {
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueDescriptorProto();
+ SharedCtor();
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.EnumValueDescriptorProto)
+}
EnumValueDescriptorProto::EnumValueDescriptorProto(const EnumValueDescriptorProto& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
@@ -6175,7 +6476,8 @@ EnumValueDescriptorProto::EnumValueDescriptorProto(const EnumValueDescriptorProt
_internal_metadata_.MergeFrom(from._internal_metadata_);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_name()) {
- name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_);
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name(),
+ GetArenaNoVirtual());
}
if (from.has_options()) {
options_ = new ::google::protobuf::EnumValueOptions(*from.options_);
@@ -6189,8 +6491,9 @@ EnumValueDescriptorProto::EnumValueDescriptorProto(const EnumValueDescriptorProt
void EnumValueDescriptorProto::SharedCtor() {
_cached_size_ = 0;
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- ::memset(&options_, 0, reinterpret_cast<char*>(&number_) -
- reinterpret_cast<char*>(&options_) + sizeof(number_));
+ ::memset(&options_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&number_) -
+ reinterpret_cast<char*>(&options_)) + sizeof(number_));
}
EnumValueDescriptorProto::~EnumValueDescriptorProto() {
@@ -6199,45 +6502,51 @@ EnumValueDescriptorProto::~EnumValueDescriptorProto() {
}
void EnumValueDescriptorProto::SharedDtor() {
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- if (this != internal_default_instance()) {
- delete options_;
- }
+ if (this != internal_default_instance()) delete options_;
}
+void EnumValueDescriptorProto::ArenaDtor(void* object) {
+ EnumValueDescriptorProto* _this = reinterpret_cast< EnumValueDescriptorProto* >(object);
+ (void)_this;
+}
+void EnumValueDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+}
void EnumValueDescriptorProto::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* EnumValueDescriptorProto::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[8].descriptor;
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const EnumValueDescriptorProto& EnumValueDescriptorProto::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueDescriptorProto();
return *internal_default_instance();
}
EnumValueDescriptorProto* EnumValueDescriptorProto::New(::google::protobuf::Arena* arena) const {
- EnumValueDescriptorProto* n = new EnumValueDescriptorProto;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
+ return ::google::protobuf::Arena::CreateMessage<EnumValueDescriptorProto>(arena);
}
void EnumValueDescriptorProto::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.EnumValueDescriptorProto)
- if (_has_bits_[0 / 32] & 3u) {
- if (has_name()) {
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
+ if (cached_has_bits & 3u) {
+ if (cached_has_bits & 0x00000001u) {
GOOGLE_DCHECK(!name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- (*name_.UnsafeRawStringPointer())->clear();
+ name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- if (has_options()) {
+ if (cached_has_bits & 0x00000002u) {
GOOGLE_DCHECK(options_ != NULL);
- options_->::google::protobuf::EnumValueOptions::Clear();
+ options_->Clear();
}
}
number_ = 0;
@@ -6257,11 +6566,12 @@ bool EnumValueDescriptorProto::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional string name = 1;
case 1: {
- if (tag == 10u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormat::PARSE,
"google.protobuf.EnumValueDescriptorProto.name");
} else {
@@ -6272,7 +6582,8 @@ bool EnumValueDescriptorProto::MergePartialFromCodedStream(
// optional int32 number = 2;
case 2: {
- if (tag == 16u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
set_has_number();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
@@ -6285,8 +6596,9 @@ bool EnumValueDescriptorProto::MergePartialFromCodedStream(
// optional .google.protobuf.EnumValueOptions options = 3;
case 3: {
- if (tag == 26u) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_options()));
} else {
goto handle_unusual;
@@ -6296,13 +6608,11 @@ bool EnumValueDescriptorProto::MergePartialFromCodedStream(
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
- input, tag, mutable_unknown_fields()));
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -6319,10 +6629,14 @@ failure:
void EnumValueDescriptorProto::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.EnumValueDescriptorProto)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional string name = 1;
- if (has_name()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.EnumValueDescriptorProto.name");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -6330,19 +6644,19 @@ void EnumValueDescriptorProto::SerializeWithCachedSizes(
}
// optional int32 number = 2;
- if (has_number()) {
+ if (cached_has_bits & 0x00000004u) {
::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->number(), output);
}
// optional .google.protobuf.EnumValueOptions options = 3;
- if (has_options()) {
+ if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
3, *this->options_, output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- unknown_fields(), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.EnumValueDescriptorProto)
}
@@ -6351,10 +6665,14 @@ void EnumValueDescriptorProto::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.EnumValueDescriptorProto)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional string name = 1;
- if (has_name()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.EnumValueDescriptorProto.name");
target =
@@ -6363,20 +6681,20 @@ void EnumValueDescriptorProto::SerializeWithCachedSizes(
}
// optional int32 number = 2;
- if (has_number()) {
+ if (cached_has_bits & 0x00000004u) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->number(), target);
}
// optional .google.protobuf.EnumValueOptions options = 3;
- if (has_options()) {
+ if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 3, *this->options_, false, target);
+ InternalWriteMessageToArray(
+ 3, *this->options_, deterministic, target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- unknown_fields(), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.EnumValueDescriptorProto)
return target;
@@ -6389,7 +6707,7 @@ size_t EnumValueDescriptorProto::ByteSizeLong() const {
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- unknown_fields());
+ _internal_metadata_.unknown_fields());
}
if (_has_bits_[0 / 32] & 7u) {
// optional string name = 1;
@@ -6402,7 +6720,7 @@ size_t EnumValueDescriptorProto::ByteSizeLong() const {
// optional .google.protobuf.EnumValueOptions options = 3;
if (has_options()) {
total_size += 1 +
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
*this->options_);
}
@@ -6440,17 +6758,21 @@ void EnumValueDescriptorProto::MergeFrom(const EnumValueDescriptorProto& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.EnumValueDescriptorProto)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
- if (from._has_bits_[0 / 32] & 7u) {
- if (from.has_name()) {
- set_has_name();
- name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = from._has_bits_[0];
+ if (cached_has_bits & 7u) {
+ if (cached_has_bits & 0x00000001u) {
+ set_name(from.name());
}
- if (from.has_options()) {
+ if (cached_has_bits & 0x00000002u) {
mutable_options()->::google::protobuf::EnumValueOptions::MergeFrom(from.options());
}
- if (from.has_number()) {
- set_number(from.number());
+ if (cached_has_bits & 0x00000004u) {
+ number_ = from.number_;
}
+ _has_bits_[0] |= cached_has_bits;
}
}
@@ -6477,152 +6799,62 @@ bool EnumValueDescriptorProto::IsInitialized() const {
void EnumValueDescriptorProto::Swap(EnumValueDescriptorProto* other) {
if (other == this) return;
+ if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ InternalSwap(other);
+ } else {
+ EnumValueDescriptorProto* temp = New(GetArenaNoVirtual());
+ temp->MergeFrom(*other);
+ other->CopyFrom(*this);
+ InternalSwap(temp);
+ if (GetArenaNoVirtual() == NULL) {
+ delete temp;
+ }
+ }
+}
+void EnumValueDescriptorProto::UnsafeArenaSwap(EnumValueDescriptorProto* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void EnumValueDescriptorProto::InternalSwap(EnumValueDescriptorProto* other) {
+ using std::swap;
name_.Swap(&other->name_);
- std::swap(options_, other->options_);
- std::swap(number_, other->number_);
- std::swap(_has_bits_[0], other->_has_bits_[0]);
+ swap(options_, other->options_);
+ swap(number_, other->number_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- std::swap(_cached_size_, other->_cached_size_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata EnumValueDescriptorProto::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[8];
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// EnumValueDescriptorProto
-// optional string name = 1;
-bool EnumValueDescriptorProto::has_name() const {
- return (_has_bits_[0] & 0x00000001u) != 0;
-}
-void EnumValueDescriptorProto::set_has_name() {
- _has_bits_[0] |= 0x00000001u;
-}
-void EnumValueDescriptorProto::clear_has_name() {
- _has_bits_[0] &= ~0x00000001u;
-}
-void EnumValueDescriptorProto::clear_name() {
- name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_name();
-}
-const ::std::string& EnumValueDescriptorProto::name() const {
- // @@protoc_insertion_point(field_get:google.protobuf.EnumValueDescriptorProto.name)
- return name_.GetNoArena();
-}
-void EnumValueDescriptorProto::set_name(const ::std::string& value) {
- set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.EnumValueDescriptorProto.name)
-}
-void EnumValueDescriptorProto::set_name(const char* value) {
- set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.EnumValueDescriptorProto.name)
-}
-void EnumValueDescriptorProto::set_name(const char* value, size_t size) {
- set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.EnumValueDescriptorProto.name)
-}
-::std::string* EnumValueDescriptorProto::mutable_name() {
- set_has_name();
- // @@protoc_insertion_point(field_mutable:google.protobuf.EnumValueDescriptorProto.name)
- return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* EnumValueDescriptorProto::release_name() {
- // @@protoc_insertion_point(field_release:google.protobuf.EnumValueDescriptorProto.name)
- clear_has_name();
- return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void EnumValueDescriptorProto::set_allocated_name(::std::string* name) {
- if (name != NULL) {
- set_has_name();
- } else {
- clear_has_name();
- }
- name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.EnumValueDescriptorProto.name)
-}
-
-// optional int32 number = 2;
-bool EnumValueDescriptorProto::has_number() const {
- return (_has_bits_[0] & 0x00000004u) != 0;
-}
-void EnumValueDescriptorProto::set_has_number() {
- _has_bits_[0] |= 0x00000004u;
-}
-void EnumValueDescriptorProto::clear_has_number() {
- _has_bits_[0] &= ~0x00000004u;
-}
-void EnumValueDescriptorProto::clear_number() {
- number_ = 0;
- clear_has_number();
-}
-::google::protobuf::int32 EnumValueDescriptorProto::number() const {
- // @@protoc_insertion_point(field_get:google.protobuf.EnumValueDescriptorProto.number)
- return number_;
-}
-void EnumValueDescriptorProto::set_number(::google::protobuf::int32 value) {
- set_has_number();
- number_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.EnumValueDescriptorProto.number)
-}
+// ===================================================================
-// optional .google.protobuf.EnumValueOptions options = 3;
-bool EnumValueDescriptorProto::has_options() const {
- return (_has_bits_[0] & 0x00000002u) != 0;
-}
-void EnumValueDescriptorProto::set_has_options() {
- _has_bits_[0] |= 0x00000002u;
-}
-void EnumValueDescriptorProto::clear_has_options() {
- _has_bits_[0] &= ~0x00000002u;
-}
-void EnumValueDescriptorProto::clear_options() {
- if (options_ != NULL) options_->::google::protobuf::EnumValueOptions::Clear();
- clear_has_options();
+void ServiceDescriptorProto::InitAsDefaultInstance() {
+ ::google::protobuf::_ServiceDescriptorProto_default_instance_._instance.get_mutable()->options_ = const_cast< ::google::protobuf::ServiceOptions*>(
+ ::google::protobuf::ServiceOptions::internal_default_instance());
}
-const ::google::protobuf::EnumValueOptions& EnumValueDescriptorProto::options() const {
- // @@protoc_insertion_point(field_get:google.protobuf.EnumValueDescriptorProto.options)
- return options_ != NULL ? *options_
- : *::google::protobuf::EnumValueOptions::internal_default_instance();
+void ServiceDescriptorProto::_slow_mutable_options() {
+ options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::ServiceOptions >(
+ GetArenaNoVirtual());
}
-::google::protobuf::EnumValueOptions* EnumValueDescriptorProto::mutable_options() {
- set_has_options();
- if (options_ == NULL) {
- options_ = new ::google::protobuf::EnumValueOptions;
+void ServiceDescriptorProto::unsafe_arena_set_allocated_options(
+ ::google::protobuf::ServiceOptions* options) {
+ if (GetArenaNoVirtual() == NULL) {
+ delete options_;
}
- // @@protoc_insertion_point(field_mutable:google.protobuf.EnumValueDescriptorProto.options)
- return options_;
-}
-::google::protobuf::EnumValueOptions* EnumValueDescriptorProto::release_options() {
- // @@protoc_insertion_point(field_release:google.protobuf.EnumValueDescriptorProto.options)
- clear_has_options();
- ::google::protobuf::EnumValueOptions* temp = options_;
- options_ = NULL;
- return temp;
-}
-void EnumValueDescriptorProto::set_allocated_options(::google::protobuf::EnumValueOptions* options) {
- delete options_;
options_ = options;
if (options) {
set_has_options();
} else {
clear_has_options();
}
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.EnumValueDescriptorProto.options)
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.ServiceDescriptorProto.options)
}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
-
-// ===================================================================
-
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int ServiceDescriptorProto::kNameFieldNumber;
const int ServiceDescriptorProto::kMethodFieldNumber;
@@ -6632,11 +6864,20 @@ const int ServiceDescriptorProto::kOptionsFieldNumber;
ServiceDescriptorProto::ServiceDescriptorProto()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceDescriptorProto();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.ServiceDescriptorProto)
}
+ServiceDescriptorProto::ServiceDescriptorProto(::google::protobuf::Arena* arena)
+ : ::google::protobuf::Message(),
+ _internal_metadata_(arena),
+ method_(arena) {
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceDescriptorProto();
+ SharedCtor();
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.ServiceDescriptorProto)
+}
ServiceDescriptorProto::ServiceDescriptorProto(const ServiceDescriptorProto& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
@@ -6646,7 +6887,8 @@ ServiceDescriptorProto::ServiceDescriptorProto(const ServiceDescriptorProto& fro
_internal_metadata_.MergeFrom(from._internal_metadata_);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_name()) {
- name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_);
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name(),
+ GetArenaNoVirtual());
}
if (from.has_options()) {
options_ = new ::google::protobuf::ServiceOptions(*from.options_);
@@ -6668,46 +6910,52 @@ ServiceDescriptorProto::~ServiceDescriptorProto() {
}
void ServiceDescriptorProto::SharedDtor() {
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- if (this != internal_default_instance()) {
- delete options_;
- }
+ if (this != internal_default_instance()) delete options_;
}
+void ServiceDescriptorProto::ArenaDtor(void* object) {
+ ServiceDescriptorProto* _this = reinterpret_cast< ServiceDescriptorProto* >(object);
+ (void)_this;
+}
+void ServiceDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+}
void ServiceDescriptorProto::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* ServiceDescriptorProto::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[9].descriptor;
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const ServiceDescriptorProto& ServiceDescriptorProto::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceDescriptorProto();
return *internal_default_instance();
}
ServiceDescriptorProto* ServiceDescriptorProto::New(::google::protobuf::Arena* arena) const {
- ServiceDescriptorProto* n = new ServiceDescriptorProto;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
+ return ::google::protobuf::Arena::CreateMessage<ServiceDescriptorProto>(arena);
}
void ServiceDescriptorProto::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.ServiceDescriptorProto)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
method_.Clear();
- if (_has_bits_[0 / 32] & 3u) {
- if (has_name()) {
+ cached_has_bits = _has_bits_[0];
+ if (cached_has_bits & 3u) {
+ if (cached_has_bits & 0x00000001u) {
GOOGLE_DCHECK(!name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- (*name_.UnsafeRawStringPointer())->clear();
+ name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- if (has_options()) {
+ if (cached_has_bits & 0x00000002u) {
GOOGLE_DCHECK(options_ != NULL);
- options_->::google::protobuf::ServiceOptions::Clear();
+ options_->Clear();
}
}
_has_bits_.Clear();
@@ -6726,11 +6974,12 @@ bool ServiceDescriptorProto::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional string name = 1;
case 1: {
- if (tag == 10u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormat::PARSE,
"google.protobuf.ServiceDescriptorProto.name");
} else {
@@ -6741,21 +6990,20 @@ bool ServiceDescriptorProto::MergePartialFromCodedStream(
// repeated .google.protobuf.MethodDescriptorProto method = 2;
case 2: {
- if (tag == 18u) {
- DO_(input->IncrementRecursionDepth());
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
- input, add_method()));
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_method()));
} else {
goto handle_unusual;
}
- input->UnsafeDecrementRecursionDepth();
break;
}
// optional .google.protobuf.ServiceOptions options = 3;
case 3: {
- if (tag == 26u) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_options()));
} else {
goto handle_unusual;
@@ -6765,13 +7013,11 @@ bool ServiceDescriptorProto::MergePartialFromCodedStream(
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
- input, tag, mutable_unknown_fields()));
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -6788,10 +7034,14 @@ failure:
void ServiceDescriptorProto::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.ServiceDescriptorProto)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional string name = 1;
- if (has_name()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.ServiceDescriptorProto.name");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -6799,20 +7049,21 @@ void ServiceDescriptorProto::SerializeWithCachedSizes(
}
// repeated .google.protobuf.MethodDescriptorProto method = 2;
- for (unsigned int i = 0, n = this->method_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->method_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 2, this->method(i), output);
+ 2, this->method(static_cast<int>(i)), output);
}
// optional .google.protobuf.ServiceOptions options = 3;
- if (has_options()) {
+ if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
3, *this->options_, output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- unknown_fields(), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.ServiceDescriptorProto)
}
@@ -6821,10 +7072,14 @@ void ServiceDescriptorProto::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.ServiceDescriptorProto)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional string name = 1;
- if (has_name()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.ServiceDescriptorProto.name");
target =
@@ -6833,22 +7088,23 @@ void ServiceDescriptorProto::SerializeWithCachedSizes(
}
// repeated .google.protobuf.MethodDescriptorProto method = 2;
- for (unsigned int i = 0, n = this->method_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->method_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 2, this->method(i), false, target);
+ InternalWriteMessageToArray(
+ 2, this->method(static_cast<int>(i)), deterministic, target);
}
// optional .google.protobuf.ServiceOptions options = 3;
- if (has_options()) {
+ if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 3, *this->options_, false, target);
+ InternalWriteMessageToArray(
+ 3, *this->options_, deterministic, target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- unknown_fields(), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.ServiceDescriptorProto)
return target;
@@ -6861,16 +7117,16 @@ size_t ServiceDescriptorProto::ByteSizeLong() const {
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- unknown_fields());
+ _internal_metadata_.unknown_fields());
}
// repeated .google.protobuf.MethodDescriptorProto method = 2;
{
- unsigned int count = this->method_size();
+ unsigned int count = static_cast<unsigned int>(this->method_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->method(i));
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->method(static_cast<int>(i)));
}
}
@@ -6885,7 +7141,7 @@ size_t ServiceDescriptorProto::ByteSizeLong() const {
// optional .google.protobuf.ServiceOptions options = 3;
if (has_options()) {
total_size += 1 +
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
*this->options_);
}
@@ -6916,13 +7172,16 @@ void ServiceDescriptorProto::MergeFrom(const ServiceDescriptorProto& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.ServiceDescriptorProto)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
method_.MergeFrom(from.method_);
- if (from._has_bits_[0 / 32] & 3u) {
- if (from.has_name()) {
- set_has_name();
- name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_);
+ cached_has_bits = from._has_bits_[0];
+ if (cached_has_bits & 3u) {
+ if (cached_has_bits & 0x00000001u) {
+ set_name(from.name());
}
- if (from.has_options()) {
+ if (cached_has_bits & 0x00000002u) {
mutable_options()->::google::protobuf::ServiceOptions::MergeFrom(from.options());
}
}
@@ -6952,158 +7211,62 @@ bool ServiceDescriptorProto::IsInitialized() const {
void ServiceDescriptorProto::Swap(ServiceDescriptorProto* other) {
if (other == this) return;
+ if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ InternalSwap(other);
+ } else {
+ ServiceDescriptorProto* temp = New(GetArenaNoVirtual());
+ temp->MergeFrom(*other);
+ other->CopyFrom(*this);
+ InternalSwap(temp);
+ if (GetArenaNoVirtual() == NULL) {
+ delete temp;
+ }
+ }
+}
+void ServiceDescriptorProto::UnsafeArenaSwap(ServiceDescriptorProto* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void ServiceDescriptorProto::InternalSwap(ServiceDescriptorProto* other) {
- method_.UnsafeArenaSwap(&other->method_);
+ using std::swap;
+ method_.InternalSwap(&other->method_);
name_.Swap(&other->name_);
- std::swap(options_, other->options_);
- std::swap(_has_bits_[0], other->_has_bits_[0]);
+ swap(options_, other->options_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- std::swap(_cached_size_, other->_cached_size_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata ServiceDescriptorProto::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[9];
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// ServiceDescriptorProto
-
-// optional string name = 1;
-bool ServiceDescriptorProto::has_name() const {
- return (_has_bits_[0] & 0x00000001u) != 0;
-}
-void ServiceDescriptorProto::set_has_name() {
- _has_bits_[0] |= 0x00000001u;
-}
-void ServiceDescriptorProto::clear_has_name() {
- _has_bits_[0] &= ~0x00000001u;
-}
-void ServiceDescriptorProto::clear_name() {
- name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_name();
-}
-const ::std::string& ServiceDescriptorProto::name() const {
- // @@protoc_insertion_point(field_get:google.protobuf.ServiceDescriptorProto.name)
- return name_.GetNoArena();
-}
-void ServiceDescriptorProto::set_name(const ::std::string& value) {
- set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.ServiceDescriptorProto.name)
-}
-void ServiceDescriptorProto::set_name(const char* value) {
- set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.ServiceDescriptorProto.name)
-}
-void ServiceDescriptorProto::set_name(const char* value, size_t size) {
- set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.ServiceDescriptorProto.name)
-}
-::std::string* ServiceDescriptorProto::mutable_name() {
- set_has_name();
- // @@protoc_insertion_point(field_mutable:google.protobuf.ServiceDescriptorProto.name)
- return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* ServiceDescriptorProto::release_name() {
- // @@protoc_insertion_point(field_release:google.protobuf.ServiceDescriptorProto.name)
- clear_has_name();
- return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void ServiceDescriptorProto::set_allocated_name(::std::string* name) {
- if (name != NULL) {
- set_has_name();
- } else {
- clear_has_name();
- }
- name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.ServiceDescriptorProto.name)
-}
-// repeated .google.protobuf.MethodDescriptorProto method = 2;
-int ServiceDescriptorProto::method_size() const {
- return method_.size();
-}
-void ServiceDescriptorProto::clear_method() {
- method_.Clear();
-}
-const ::google::protobuf::MethodDescriptorProto& ServiceDescriptorProto::method(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.ServiceDescriptorProto.method)
- return method_.Get(index);
-}
-::google::protobuf::MethodDescriptorProto* ServiceDescriptorProto::mutable_method(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.ServiceDescriptorProto.method)
- return method_.Mutable(index);
-}
-::google::protobuf::MethodDescriptorProto* ServiceDescriptorProto::add_method() {
- // @@protoc_insertion_point(field_add:google.protobuf.ServiceDescriptorProto.method)
- return method_.Add();
-}
-::google::protobuf::RepeatedPtrField< ::google::protobuf::MethodDescriptorProto >*
-ServiceDescriptorProto::mutable_method() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.ServiceDescriptorProto.method)
- return &method_;
-}
-const ::google::protobuf::RepeatedPtrField< ::google::protobuf::MethodDescriptorProto >&
-ServiceDescriptorProto::method() const {
- // @@protoc_insertion_point(field_list:google.protobuf.ServiceDescriptorProto.method)
- return method_;
-}
+// ===================================================================
-// optional .google.protobuf.ServiceOptions options = 3;
-bool ServiceDescriptorProto::has_options() const {
- return (_has_bits_[0] & 0x00000002u) != 0;
-}
-void ServiceDescriptorProto::set_has_options() {
- _has_bits_[0] |= 0x00000002u;
-}
-void ServiceDescriptorProto::clear_has_options() {
- _has_bits_[0] &= ~0x00000002u;
-}
-void ServiceDescriptorProto::clear_options() {
- if (options_ != NULL) options_->::google::protobuf::ServiceOptions::Clear();
- clear_has_options();
+void MethodDescriptorProto::InitAsDefaultInstance() {
+ ::google::protobuf::_MethodDescriptorProto_default_instance_._instance.get_mutable()->options_ = const_cast< ::google::protobuf::MethodOptions*>(
+ ::google::protobuf::MethodOptions::internal_default_instance());
}
-const ::google::protobuf::ServiceOptions& ServiceDescriptorProto::options() const {
- // @@protoc_insertion_point(field_get:google.protobuf.ServiceDescriptorProto.options)
- return options_ != NULL ? *options_
- : *::google::protobuf::ServiceOptions::internal_default_instance();
+void MethodDescriptorProto::_slow_mutable_options() {
+ options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::MethodOptions >(
+ GetArenaNoVirtual());
}
-::google::protobuf::ServiceOptions* ServiceDescriptorProto::mutable_options() {
- set_has_options();
- if (options_ == NULL) {
- options_ = new ::google::protobuf::ServiceOptions;
+void MethodDescriptorProto::unsafe_arena_set_allocated_options(
+ ::google::protobuf::MethodOptions* options) {
+ if (GetArenaNoVirtual() == NULL) {
+ delete options_;
}
- // @@protoc_insertion_point(field_mutable:google.protobuf.ServiceDescriptorProto.options)
- return options_;
-}
-::google::protobuf::ServiceOptions* ServiceDescriptorProto::release_options() {
- // @@protoc_insertion_point(field_release:google.protobuf.ServiceDescriptorProto.options)
- clear_has_options();
- ::google::protobuf::ServiceOptions* temp = options_;
- options_ = NULL;
- return temp;
-}
-void ServiceDescriptorProto::set_allocated_options(::google::protobuf::ServiceOptions* options) {
- delete options_;
options_ = options;
if (options) {
set_has_options();
} else {
clear_has_options();
}
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.ServiceDescriptorProto.options)
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.MethodDescriptorProto.options)
}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
-
-// ===================================================================
-
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int MethodDescriptorProto::kNameFieldNumber;
const int MethodDescriptorProto::kInputTypeFieldNumber;
@@ -7116,11 +7279,19 @@ const int MethodDescriptorProto::kServerStreamingFieldNumber;
MethodDescriptorProto::MethodDescriptorProto()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodDescriptorProto();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.MethodDescriptorProto)
}
+MethodDescriptorProto::MethodDescriptorProto(::google::protobuf::Arena* arena)
+ : ::google::protobuf::Message(),
+ _internal_metadata_(arena) {
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodDescriptorProto();
+ SharedCtor();
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.MethodDescriptorProto)
+}
MethodDescriptorProto::MethodDescriptorProto(const MethodDescriptorProto& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
@@ -7129,15 +7300,18 @@ MethodDescriptorProto::MethodDescriptorProto(const MethodDescriptorProto& from)
_internal_metadata_.MergeFrom(from._internal_metadata_);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_name()) {
- name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_);
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name(),
+ GetArenaNoVirtual());
}
input_type_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_input_type()) {
- input_type_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.input_type_);
+ input_type_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.input_type(),
+ GetArenaNoVirtual());
}
output_type_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_output_type()) {
- output_type_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.output_type_);
+ output_type_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.output_type(),
+ GetArenaNoVirtual());
}
if (from.has_options()) {
options_ = new ::google::protobuf::MethodOptions(*from.options_);
@@ -7145,8 +7319,8 @@ MethodDescriptorProto::MethodDescriptorProto(const MethodDescriptorProto& from)
options_ = NULL;
}
::memcpy(&client_streaming_, &from.client_streaming_,
- reinterpret_cast<char*>(&server_streaming_) -
- reinterpret_cast<char*>(&client_streaming_) + sizeof(server_streaming_));
+ static_cast<size_t>(reinterpret_cast<char*>(&server_streaming_) -
+ reinterpret_cast<char*>(&client_streaming_)) + sizeof(server_streaming_));
// @@protoc_insertion_point(copy_constructor:google.protobuf.MethodDescriptorProto)
}
@@ -7155,8 +7329,9 @@ void MethodDescriptorProto::SharedCtor() {
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
input_type_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
output_type_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- ::memset(&options_, 0, reinterpret_cast<char*>(&server_streaming_) -
- reinterpret_cast<char*>(&options_) + sizeof(server_streaming_));
+ ::memset(&options_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&server_streaming_) -
+ reinterpret_cast<char*>(&options_)) + sizeof(server_streaming_));
}
MethodDescriptorProto::~MethodDescriptorProto() {
@@ -7165,61 +7340,66 @@ MethodDescriptorProto::~MethodDescriptorProto() {
}
void MethodDescriptorProto::SharedDtor() {
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
input_type_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
output_type_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- if (this != internal_default_instance()) {
- delete options_;
- }
+ if (this != internal_default_instance()) delete options_;
}
+void MethodDescriptorProto::ArenaDtor(void* object) {
+ MethodDescriptorProto* _this = reinterpret_cast< MethodDescriptorProto* >(object);
+ (void)_this;
+}
+void MethodDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+}
void MethodDescriptorProto::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* MethodDescriptorProto::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[10].descriptor;
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const MethodDescriptorProto& MethodDescriptorProto::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodDescriptorProto();
return *internal_default_instance();
}
MethodDescriptorProto* MethodDescriptorProto::New(::google::protobuf::Arena* arena) const {
- MethodDescriptorProto* n = new MethodDescriptorProto;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
+ return ::google::protobuf::Arena::CreateMessage<MethodDescriptorProto>(arena);
}
void MethodDescriptorProto::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.MethodDescriptorProto)
- if (_has_bits_[0 / 32] & 15u) {
- if (has_name()) {
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
+ if (cached_has_bits & 15u) {
+ if (cached_has_bits & 0x00000001u) {
GOOGLE_DCHECK(!name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- (*name_.UnsafeRawStringPointer())->clear();
+ name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- if (has_input_type()) {
+ if (cached_has_bits & 0x00000002u) {
GOOGLE_DCHECK(!input_type_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- (*input_type_.UnsafeRawStringPointer())->clear();
+ input_type_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- if (has_output_type()) {
+ if (cached_has_bits & 0x00000004u) {
GOOGLE_DCHECK(!output_type_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- (*output_type_.UnsafeRawStringPointer())->clear();
+ output_type_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- if (has_options()) {
+ if (cached_has_bits & 0x00000008u) {
GOOGLE_DCHECK(options_ != NULL);
- options_->::google::protobuf::MethodOptions::Clear();
+ options_->Clear();
}
}
- if (_has_bits_[0 / 32] & 48u) {
- ::memset(&client_streaming_, 0, reinterpret_cast<char*>(&server_streaming_) -
- reinterpret_cast<char*>(&client_streaming_) + sizeof(server_streaming_));
- }
+ ::memset(&client_streaming_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&server_streaming_) -
+ reinterpret_cast<char*>(&client_streaming_)) + sizeof(server_streaming_));
_has_bits_.Clear();
_internal_metadata_.Clear();
}
@@ -7236,11 +7416,12 @@ bool MethodDescriptorProto::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional string name = 1;
case 1: {
- if (tag == 10u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormat::PARSE,
"google.protobuf.MethodDescriptorProto.name");
} else {
@@ -7251,11 +7432,12 @@ bool MethodDescriptorProto::MergePartialFromCodedStream(
// optional string input_type = 2;
case 2: {
- if (tag == 18u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_input_type()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->input_type().data(), this->input_type().length(),
+ this->input_type().data(), static_cast<int>(this->input_type().length()),
::google::protobuf::internal::WireFormat::PARSE,
"google.protobuf.MethodDescriptorProto.input_type");
} else {
@@ -7266,11 +7448,12 @@ bool MethodDescriptorProto::MergePartialFromCodedStream(
// optional string output_type = 3;
case 3: {
- if (tag == 26u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_output_type()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->output_type().data(), this->output_type().length(),
+ this->output_type().data(), static_cast<int>(this->output_type().length()),
::google::protobuf::internal::WireFormat::PARSE,
"google.protobuf.MethodDescriptorProto.output_type");
} else {
@@ -7281,8 +7464,9 @@ bool MethodDescriptorProto::MergePartialFromCodedStream(
// optional .google.protobuf.MethodOptions options = 4;
case 4: {
- if (tag == 34u) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_options()));
} else {
goto handle_unusual;
@@ -7292,7 +7476,8 @@ bool MethodDescriptorProto::MergePartialFromCodedStream(
// optional bool client_streaming = 5 [default = false];
case 5: {
- if (tag == 40u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) {
set_has_client_streaming();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
@@ -7305,7 +7490,8 @@ bool MethodDescriptorProto::MergePartialFromCodedStream(
// optional bool server_streaming = 6 [default = false];
case 6: {
- if (tag == 48u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(48u /* 48 & 0xFF */)) {
set_has_server_streaming();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
@@ -7318,13 +7504,11 @@ bool MethodDescriptorProto::MergePartialFromCodedStream(
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
- input, tag, mutable_unknown_fields()));
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -7341,10 +7525,14 @@ failure:
void MethodDescriptorProto::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.MethodDescriptorProto)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional string name = 1;
- if (has_name()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.MethodDescriptorProto.name");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -7352,9 +7540,9 @@ void MethodDescriptorProto::SerializeWithCachedSizes(
}
// optional string input_type = 2;
- if (has_input_type()) {
+ if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->input_type().data(), this->input_type().length(),
+ this->input_type().data(), static_cast<int>(this->input_type().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.MethodDescriptorProto.input_type");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -7362,9 +7550,9 @@ void MethodDescriptorProto::SerializeWithCachedSizes(
}
// optional string output_type = 3;
- if (has_output_type()) {
+ if (cached_has_bits & 0x00000004u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->output_type().data(), this->output_type().length(),
+ this->output_type().data(), static_cast<int>(this->output_type().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.MethodDescriptorProto.output_type");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -7372,24 +7560,24 @@ void MethodDescriptorProto::SerializeWithCachedSizes(
}
// optional .google.protobuf.MethodOptions options = 4;
- if (has_options()) {
+ if (cached_has_bits & 0x00000008u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
4, *this->options_, output);
}
// optional bool client_streaming = 5 [default = false];
- if (has_client_streaming()) {
+ if (cached_has_bits & 0x00000010u) {
::google::protobuf::internal::WireFormatLite::WriteBool(5, this->client_streaming(), output);
}
// optional bool server_streaming = 6 [default = false];
- if (has_server_streaming()) {
+ if (cached_has_bits & 0x00000020u) {
::google::protobuf::internal::WireFormatLite::WriteBool(6, this->server_streaming(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- unknown_fields(), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.MethodDescriptorProto)
}
@@ -7398,10 +7586,14 @@ void MethodDescriptorProto::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.MethodDescriptorProto)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional string name = 1;
- if (has_name()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.MethodDescriptorProto.name");
target =
@@ -7410,9 +7602,9 @@ void MethodDescriptorProto::SerializeWithCachedSizes(
}
// optional string input_type = 2;
- if (has_input_type()) {
+ if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->input_type().data(), this->input_type().length(),
+ this->input_type().data(), static_cast<int>(this->input_type().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.MethodDescriptorProto.input_type");
target =
@@ -7421,9 +7613,9 @@ void MethodDescriptorProto::SerializeWithCachedSizes(
}
// optional string output_type = 3;
- if (has_output_type()) {
+ if (cached_has_bits & 0x00000004u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->output_type().data(), this->output_type().length(),
+ this->output_type().data(), static_cast<int>(this->output_type().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.MethodDescriptorProto.output_type");
target =
@@ -7432,25 +7624,25 @@ void MethodDescriptorProto::SerializeWithCachedSizes(
}
// optional .google.protobuf.MethodOptions options = 4;
- if (has_options()) {
+ if (cached_has_bits & 0x00000008u) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 4, *this->options_, false, target);
+ InternalWriteMessageToArray(
+ 4, *this->options_, deterministic, target);
}
// optional bool client_streaming = 5 [default = false];
- if (has_client_streaming()) {
+ if (cached_has_bits & 0x00000010u) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(5, this->client_streaming(), target);
}
// optional bool server_streaming = 6 [default = false];
- if (has_server_streaming()) {
+ if (cached_has_bits & 0x00000020u) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(6, this->server_streaming(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- unknown_fields(), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.MethodDescriptorProto)
return target;
@@ -7463,7 +7655,7 @@ size_t MethodDescriptorProto::ByteSizeLong() const {
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- unknown_fields());
+ _internal_metadata_.unknown_fields());
}
if (_has_bits_[0 / 32] & 63u) {
// optional string name = 1;
@@ -7490,7 +7682,7 @@ size_t MethodDescriptorProto::ByteSizeLong() const {
// optional .google.protobuf.MethodOptions options = 4;
if (has_options()) {
total_size += 1 +
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
*this->options_);
}
@@ -7531,28 +7723,30 @@ void MethodDescriptorProto::MergeFrom(const MethodDescriptorProto& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.MethodDescriptorProto)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
- if (from._has_bits_[0 / 32] & 63u) {
- if (from.has_name()) {
- set_has_name();
- name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = from._has_bits_[0];
+ if (cached_has_bits & 63u) {
+ if (cached_has_bits & 0x00000001u) {
+ set_name(from.name());
}
- if (from.has_input_type()) {
- set_has_input_type();
- input_type_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.input_type_);
+ if (cached_has_bits & 0x00000002u) {
+ set_input_type(from.input_type());
}
- if (from.has_output_type()) {
- set_has_output_type();
- output_type_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.output_type_);
+ if (cached_has_bits & 0x00000004u) {
+ set_output_type(from.output_type());
}
- if (from.has_options()) {
+ if (cached_has_bits & 0x00000008u) {
mutable_options()->::google::protobuf::MethodOptions::MergeFrom(from.options());
}
- if (from.has_client_streaming()) {
- set_client_streaming(from.client_streaming());
+ if (cached_has_bits & 0x00000010u) {
+ client_streaming_ = from.client_streaming_;
}
- if (from.has_server_streaming()) {
- set_server_streaming(from.server_streaming());
+ if (cached_has_bits & 0x00000020u) {
+ server_streaming_ = from.server_streaming_;
}
+ _has_bits_[0] |= cached_has_bits;
}
}
@@ -7579,287 +7773,46 @@ bool MethodDescriptorProto::IsInitialized() const {
void MethodDescriptorProto::Swap(MethodDescriptorProto* other) {
if (other == this) return;
+ if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ InternalSwap(other);
+ } else {
+ MethodDescriptorProto* temp = New(GetArenaNoVirtual());
+ temp->MergeFrom(*other);
+ other->CopyFrom(*this);
+ InternalSwap(temp);
+ if (GetArenaNoVirtual() == NULL) {
+ delete temp;
+ }
+ }
+}
+void MethodDescriptorProto::UnsafeArenaSwap(MethodDescriptorProto* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void MethodDescriptorProto::InternalSwap(MethodDescriptorProto* other) {
+ using std::swap;
name_.Swap(&other->name_);
input_type_.Swap(&other->input_type_);
output_type_.Swap(&other->output_type_);
- std::swap(options_, other->options_);
- std::swap(client_streaming_, other->client_streaming_);
- std::swap(server_streaming_, other->server_streaming_);
- std::swap(_has_bits_[0], other->_has_bits_[0]);
+ swap(options_, other->options_);
+ swap(client_streaming_, other->client_streaming_);
+ swap(server_streaming_, other->server_streaming_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- std::swap(_cached_size_, other->_cached_size_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata MethodDescriptorProto::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[10];
-}
-
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// MethodDescriptorProto
-
-// optional string name = 1;
-bool MethodDescriptorProto::has_name() const {
- return (_has_bits_[0] & 0x00000001u) != 0;
-}
-void MethodDescriptorProto::set_has_name() {
- _has_bits_[0] |= 0x00000001u;
-}
-void MethodDescriptorProto::clear_has_name() {
- _has_bits_[0] &= ~0x00000001u;
-}
-void MethodDescriptorProto::clear_name() {
- name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_name();
-}
-const ::std::string& MethodDescriptorProto::name() const {
- // @@protoc_insertion_point(field_get:google.protobuf.MethodDescriptorProto.name)
- return name_.GetNoArena();
-}
-void MethodDescriptorProto::set_name(const ::std::string& value) {
- set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.MethodDescriptorProto.name)
-}
-void MethodDescriptorProto::set_name(const char* value) {
- set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.MethodDescriptorProto.name)
-}
-void MethodDescriptorProto::set_name(const char* value, size_t size) {
- set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.MethodDescriptorProto.name)
-}
-::std::string* MethodDescriptorProto::mutable_name() {
- set_has_name();
- // @@protoc_insertion_point(field_mutable:google.protobuf.MethodDescriptorProto.name)
- return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* MethodDescriptorProto::release_name() {
- // @@protoc_insertion_point(field_release:google.protobuf.MethodDescriptorProto.name)
- clear_has_name();
- return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void MethodDescriptorProto::set_allocated_name(::std::string* name) {
- if (name != NULL) {
- set_has_name();
- } else {
- clear_has_name();
- }
- name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.MethodDescriptorProto.name)
-}
-
-// optional string input_type = 2;
-bool MethodDescriptorProto::has_input_type() const {
- return (_has_bits_[0] & 0x00000002u) != 0;
-}
-void MethodDescriptorProto::set_has_input_type() {
- _has_bits_[0] |= 0x00000002u;
-}
-void MethodDescriptorProto::clear_has_input_type() {
- _has_bits_[0] &= ~0x00000002u;
-}
-void MethodDescriptorProto::clear_input_type() {
- input_type_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_input_type();
-}
-const ::std::string& MethodDescriptorProto::input_type() const {
- // @@protoc_insertion_point(field_get:google.protobuf.MethodDescriptorProto.input_type)
- return input_type_.GetNoArena();
-}
-void MethodDescriptorProto::set_input_type(const ::std::string& value) {
- set_has_input_type();
- input_type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.MethodDescriptorProto.input_type)
-}
-void MethodDescriptorProto::set_input_type(const char* value) {
- set_has_input_type();
- input_type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.MethodDescriptorProto.input_type)
-}
-void MethodDescriptorProto::set_input_type(const char* value, size_t size) {
- set_has_input_type();
- input_type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.MethodDescriptorProto.input_type)
-}
-::std::string* MethodDescriptorProto::mutable_input_type() {
- set_has_input_type();
- // @@protoc_insertion_point(field_mutable:google.protobuf.MethodDescriptorProto.input_type)
- return input_type_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* MethodDescriptorProto::release_input_type() {
- // @@protoc_insertion_point(field_release:google.protobuf.MethodDescriptorProto.input_type)
- clear_has_input_type();
- return input_type_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void MethodDescriptorProto::set_allocated_input_type(::std::string* input_type) {
- if (input_type != NULL) {
- set_has_input_type();
- } else {
- clear_has_input_type();
- }
- input_type_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), input_type);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.MethodDescriptorProto.input_type)
-}
-
-// optional string output_type = 3;
-bool MethodDescriptorProto::has_output_type() const {
- return (_has_bits_[0] & 0x00000004u) != 0;
-}
-void MethodDescriptorProto::set_has_output_type() {
- _has_bits_[0] |= 0x00000004u;
-}
-void MethodDescriptorProto::clear_has_output_type() {
- _has_bits_[0] &= ~0x00000004u;
-}
-void MethodDescriptorProto::clear_output_type() {
- output_type_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_output_type();
-}
-const ::std::string& MethodDescriptorProto::output_type() const {
- // @@protoc_insertion_point(field_get:google.protobuf.MethodDescriptorProto.output_type)
- return output_type_.GetNoArena();
-}
-void MethodDescriptorProto::set_output_type(const ::std::string& value) {
- set_has_output_type();
- output_type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.MethodDescriptorProto.output_type)
-}
-void MethodDescriptorProto::set_output_type(const char* value) {
- set_has_output_type();
- output_type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.MethodDescriptorProto.output_type)
-}
-void MethodDescriptorProto::set_output_type(const char* value, size_t size) {
- set_has_output_type();
- output_type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.MethodDescriptorProto.output_type)
-}
-::std::string* MethodDescriptorProto::mutable_output_type() {
- set_has_output_type();
- // @@protoc_insertion_point(field_mutable:google.protobuf.MethodDescriptorProto.output_type)
- return output_type_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* MethodDescriptorProto::release_output_type() {
- // @@protoc_insertion_point(field_release:google.protobuf.MethodDescriptorProto.output_type)
- clear_has_output_type();
- return output_type_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void MethodDescriptorProto::set_allocated_output_type(::std::string* output_type) {
- if (output_type != NULL) {
- set_has_output_type();
- } else {
- clear_has_output_type();
- }
- output_type_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), output_type);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.MethodDescriptorProto.output_type)
-}
-
-// optional .google.protobuf.MethodOptions options = 4;
-bool MethodDescriptorProto::has_options() const {
- return (_has_bits_[0] & 0x00000008u) != 0;
-}
-void MethodDescriptorProto::set_has_options() {
- _has_bits_[0] |= 0x00000008u;
-}
-void MethodDescriptorProto::clear_has_options() {
- _has_bits_[0] &= ~0x00000008u;
-}
-void MethodDescriptorProto::clear_options() {
- if (options_ != NULL) options_->::google::protobuf::MethodOptions::Clear();
- clear_has_options();
-}
-const ::google::protobuf::MethodOptions& MethodDescriptorProto::options() const {
- // @@protoc_insertion_point(field_get:google.protobuf.MethodDescriptorProto.options)
- return options_ != NULL ? *options_
- : *::google::protobuf::MethodOptions::internal_default_instance();
-}
-::google::protobuf::MethodOptions* MethodDescriptorProto::mutable_options() {
- set_has_options();
- if (options_ == NULL) {
- options_ = new ::google::protobuf::MethodOptions;
- }
- // @@protoc_insertion_point(field_mutable:google.protobuf.MethodDescriptorProto.options)
- return options_;
-}
-::google::protobuf::MethodOptions* MethodDescriptorProto::release_options() {
- // @@protoc_insertion_point(field_release:google.protobuf.MethodDescriptorProto.options)
- clear_has_options();
- ::google::protobuf::MethodOptions* temp = options_;
- options_ = NULL;
- return temp;
-}
-void MethodDescriptorProto::set_allocated_options(::google::protobuf::MethodOptions* options) {
- delete options_;
- options_ = options;
- if (options) {
- set_has_options();
- } else {
- clear_has_options();
- }
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.MethodDescriptorProto.options)
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
}
-// optional bool client_streaming = 5 [default = false];
-bool MethodDescriptorProto::has_client_streaming() const {
- return (_has_bits_[0] & 0x00000010u) != 0;
-}
-void MethodDescriptorProto::set_has_client_streaming() {
- _has_bits_[0] |= 0x00000010u;
-}
-void MethodDescriptorProto::clear_has_client_streaming() {
- _has_bits_[0] &= ~0x00000010u;
-}
-void MethodDescriptorProto::clear_client_streaming() {
- client_streaming_ = false;
- clear_has_client_streaming();
-}
-bool MethodDescriptorProto::client_streaming() const {
- // @@protoc_insertion_point(field_get:google.protobuf.MethodDescriptorProto.client_streaming)
- return client_streaming_;
-}
-void MethodDescriptorProto::set_client_streaming(bool value) {
- set_has_client_streaming();
- client_streaming_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.MethodDescriptorProto.client_streaming)
-}
-
-// optional bool server_streaming = 6 [default = false];
-bool MethodDescriptorProto::has_server_streaming() const {
- return (_has_bits_[0] & 0x00000020u) != 0;
-}
-void MethodDescriptorProto::set_has_server_streaming() {
- _has_bits_[0] |= 0x00000020u;
-}
-void MethodDescriptorProto::clear_has_server_streaming() {
- _has_bits_[0] &= ~0x00000020u;
-}
-void MethodDescriptorProto::clear_server_streaming() {
- server_streaming_ = false;
- clear_has_server_streaming();
-}
-bool MethodDescriptorProto::server_streaming() const {
- // @@protoc_insertion_point(field_get:google.protobuf.MethodDescriptorProto.server_streaming)
- return server_streaming_;
-}
-void MethodDescriptorProto::set_server_streaming(bool value) {
- set_has_server_streaming();
- server_streaming_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.MethodDescriptorProto.server_streaming)
-}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
+void FileOptions::InitAsDefaultInstance() {
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int FileOptions::kJavaPackageFieldNumber;
const int FileOptions::kJavaOuterClassnameFieldNumber;
@@ -7871,22 +7824,35 @@ const int FileOptions::kGoPackageFieldNumber;
const int FileOptions::kCcGenericServicesFieldNumber;
const int FileOptions::kJavaGenericServicesFieldNumber;
const int FileOptions::kPyGenericServicesFieldNumber;
+const int FileOptions::kPhpGenericServicesFieldNumber;
const int FileOptions::kDeprecatedFieldNumber;
const int FileOptions::kCcEnableArenasFieldNumber;
const int FileOptions::kObjcClassPrefixFieldNumber;
const int FileOptions::kCsharpNamespaceFieldNumber;
const int FileOptions::kSwiftPrefixFieldNumber;
+const int FileOptions::kPhpClassPrefixFieldNumber;
+const int FileOptions::kPhpNamespaceFieldNumber;
const int FileOptions::kUninterpretedOptionFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
FileOptions::FileOptions()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileOptions();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.FileOptions)
}
+FileOptions::FileOptions(::google::protobuf::Arena* arena)
+ : ::google::protobuf::Message(),
+ _extensions_(arena),
+ _internal_metadata_(arena),
+ uninterpreted_option_(arena) {
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileOptions();
+ SharedCtor();
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.FileOptions)
+}
FileOptions::FileOptions(const FileOptions& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
@@ -7897,31 +7863,47 @@ FileOptions::FileOptions(const FileOptions& from)
_extensions_.MergeFrom(from._extensions_);
java_package_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_java_package()) {
- java_package_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.java_package_);
+ java_package_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.java_package(),
+ GetArenaNoVirtual());
}
java_outer_classname_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_java_outer_classname()) {
- java_outer_classname_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.java_outer_classname_);
+ java_outer_classname_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.java_outer_classname(),
+ GetArenaNoVirtual());
}
go_package_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_go_package()) {
- go_package_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.go_package_);
+ go_package_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.go_package(),
+ GetArenaNoVirtual());
}
objc_class_prefix_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_objc_class_prefix()) {
- objc_class_prefix_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.objc_class_prefix_);
+ objc_class_prefix_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.objc_class_prefix(),
+ GetArenaNoVirtual());
}
csharp_namespace_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_csharp_namespace()) {
- csharp_namespace_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.csharp_namespace_);
+ csharp_namespace_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.csharp_namespace(),
+ GetArenaNoVirtual());
}
swift_prefix_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_swift_prefix()) {
- swift_prefix_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.swift_prefix_);
- }
- ::memcpy(&java_multiple_files_, &from.java_multiple_files_,
- reinterpret_cast<char*>(&optimize_for_) -
- reinterpret_cast<char*>(&java_multiple_files_) + sizeof(optimize_for_));
+ swift_prefix_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.swift_prefix(),
+ GetArenaNoVirtual());
+ }
+ php_class_prefix_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ if (from.has_php_class_prefix()) {
+ php_class_prefix_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.php_class_prefix(),
+ GetArenaNoVirtual());
+ }
+ php_namespace_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ if (from.has_php_namespace()) {
+ php_namespace_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.php_namespace(),
+ GetArenaNoVirtual());
+ }
+ ::memcpy(&cc_enable_arenas_, &from.cc_enable_arenas_,
+ static_cast<size_t>(reinterpret_cast<char*>(&optimize_for_) -
+ reinterpret_cast<char*>(&cc_enable_arenas_)) + sizeof(optimize_for_));
// @@protoc_insertion_point(copy_constructor:google.protobuf.FileOptions)
}
@@ -7933,8 +7915,11 @@ void FileOptions::SharedCtor() {
objc_class_prefix_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
csharp_namespace_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
swift_prefix_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- ::memset(&java_multiple_files_, 0, reinterpret_cast<char*>(&cc_enable_arenas_) -
- reinterpret_cast<char*>(&java_multiple_files_) + sizeof(cc_enable_arenas_));
+ php_class_prefix_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ php_namespace_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ ::memset(&cc_enable_arenas_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&deprecated_) -
+ reinterpret_cast<char*>(&cc_enable_arenas_)) + sizeof(deprecated_));
optimize_for_ = 1;
}
@@ -7944,74 +7929,92 @@ FileOptions::~FileOptions() {
}
void FileOptions::SharedDtor() {
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
java_package_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
java_outer_classname_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
go_package_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
objc_class_prefix_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
csharp_namespace_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
swift_prefix_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ php_class_prefix_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ php_namespace_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
+void FileOptions::ArenaDtor(void* object) {
+ FileOptions* _this = reinterpret_cast< FileOptions* >(object);
+ (void)_this;
+}
+void FileOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+}
void FileOptions::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* FileOptions::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[11].descriptor;
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const FileOptions& FileOptions::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileOptions();
return *internal_default_instance();
}
FileOptions* FileOptions::New(::google::protobuf::Arena* arena) const {
- FileOptions* n = new FileOptions;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
+ return ::google::protobuf::Arena::CreateMessage<FileOptions>(arena);
}
void FileOptions::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.FileOptions)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
_extensions_.Clear();
uninterpreted_option_.Clear();
- if (_has_bits_[0 / 32] & 63u) {
- if (has_java_package()) {
+ cached_has_bits = _has_bits_[0];
+ if (cached_has_bits & 255u) {
+ if (cached_has_bits & 0x00000001u) {
GOOGLE_DCHECK(!java_package_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- (*java_package_.UnsafeRawStringPointer())->clear();
+ java_package_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- if (has_java_outer_classname()) {
+ if (cached_has_bits & 0x00000002u) {
GOOGLE_DCHECK(!java_outer_classname_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- (*java_outer_classname_.UnsafeRawStringPointer())->clear();
+ java_outer_classname_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- if (has_go_package()) {
+ if (cached_has_bits & 0x00000004u) {
GOOGLE_DCHECK(!go_package_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- (*go_package_.UnsafeRawStringPointer())->clear();
+ go_package_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- if (has_objc_class_prefix()) {
+ if (cached_has_bits & 0x00000008u) {
GOOGLE_DCHECK(!objc_class_prefix_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- (*objc_class_prefix_.UnsafeRawStringPointer())->clear();
+ objc_class_prefix_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- if (has_csharp_namespace()) {
+ if (cached_has_bits & 0x00000010u) {
GOOGLE_DCHECK(!csharp_namespace_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- (*csharp_namespace_.UnsafeRawStringPointer())->clear();
+ csharp_namespace_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- if (has_swift_prefix()) {
+ if (cached_has_bits & 0x00000020u) {
GOOGLE_DCHECK(!swift_prefix_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- (*swift_prefix_.UnsafeRawStringPointer())->clear();
+ swift_prefix_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ }
+ if (cached_has_bits & 0x00000040u) {
+ GOOGLE_DCHECK(!php_class_prefix_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
+ php_class_prefix_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ }
+ if (cached_has_bits & 0x00000080u) {
+ GOOGLE_DCHECK(!php_namespace_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
+ php_namespace_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
}
- if (_has_bits_[0 / 32] & 192u) {
- ::memset(&java_multiple_files_, 0, reinterpret_cast<char*>(&java_generate_equals_and_hash_) -
- reinterpret_cast<char*>(&java_multiple_files_) + sizeof(java_generate_equals_and_hash_));
+ if (cached_has_bits & 65280u) {
+ ::memset(&cc_enable_arenas_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&php_generic_services_) -
+ reinterpret_cast<char*>(&cc_enable_arenas_)) + sizeof(php_generic_services_));
}
- if (_has_bits_[8 / 32] & 32512u) {
- ::memset(&java_string_check_utf8_, 0, reinterpret_cast<char*>(&cc_enable_arenas_) -
- reinterpret_cast<char*>(&java_string_check_utf8_) + sizeof(cc_enable_arenas_));
+ if (cached_has_bits & 196608u) {
+ deprecated_ = false;
optimize_for_ = 1;
}
_has_bits_.Clear();
@@ -8030,11 +8033,12 @@ bool FileOptions::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional string java_package = 1;
case 1: {
- if (tag == 10u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_java_package()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->java_package().data(), this->java_package().length(),
+ this->java_package().data(), static_cast<int>(this->java_package().length()),
::google::protobuf::internal::WireFormat::PARSE,
"google.protobuf.FileOptions.java_package");
} else {
@@ -8045,11 +8049,12 @@ bool FileOptions::MergePartialFromCodedStream(
// optional string java_outer_classname = 8;
case 8: {
- if (tag == 66u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(66u /* 66 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_java_outer_classname()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->java_outer_classname().data(), this->java_outer_classname().length(),
+ this->java_outer_classname().data(), static_cast<int>(this->java_outer_classname().length()),
::google::protobuf::internal::WireFormat::PARSE,
"google.protobuf.FileOptions.java_outer_classname");
} else {
@@ -8060,7 +8065,8 @@ bool FileOptions::MergePartialFromCodedStream(
// optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED];
case 9: {
- if (tag == 72u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(72u /* 72 & 0xFF */)) {
int value;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
@@ -8068,7 +8074,8 @@ bool FileOptions::MergePartialFromCodedStream(
if (::google::protobuf::FileOptions_OptimizeMode_IsValid(value)) {
set_optimize_for(static_cast< ::google::protobuf::FileOptions_OptimizeMode >(value));
} else {
- mutable_unknown_fields()->AddVarint(9, value);
+ mutable_unknown_fields()->AddVarint(
+ 9, static_cast< ::google::protobuf::uint64>(value));
}
} else {
goto handle_unusual;
@@ -8078,7 +8085,8 @@ bool FileOptions::MergePartialFromCodedStream(
// optional bool java_multiple_files = 10 [default = false];
case 10: {
- if (tag == 80u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(80u /* 80 & 0xFF */)) {
set_has_java_multiple_files();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
@@ -8091,11 +8099,12 @@ bool FileOptions::MergePartialFromCodedStream(
// optional string go_package = 11;
case 11: {
- if (tag == 90u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(90u /* 90 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_go_package()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->go_package().data(), this->go_package().length(),
+ this->go_package().data(), static_cast<int>(this->go_package().length()),
::google::protobuf::internal::WireFormat::PARSE,
"google.protobuf.FileOptions.go_package");
} else {
@@ -8106,7 +8115,8 @@ bool FileOptions::MergePartialFromCodedStream(
// optional bool cc_generic_services = 16 [default = false];
case 16: {
- if (tag == 128u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(128u /* 128 & 0xFF */)) {
set_has_cc_generic_services();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
@@ -8119,7 +8129,8 @@ bool FileOptions::MergePartialFromCodedStream(
// optional bool java_generic_services = 17 [default = false];
case 17: {
- if (tag == 136u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(136u /* 136 & 0xFF */)) {
set_has_java_generic_services();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
@@ -8132,7 +8143,8 @@ bool FileOptions::MergePartialFromCodedStream(
// optional bool py_generic_services = 18 [default = false];
case 18: {
- if (tag == 144u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(144u /* 144 & 0xFF */)) {
set_has_py_generic_services();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
@@ -8145,7 +8157,8 @@ bool FileOptions::MergePartialFromCodedStream(
// optional bool java_generate_equals_and_hash = 20 [deprecated = true];
case 20: {
- if (tag == 160u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(160u /* 160 & 0xFF */)) {
set_has_java_generate_equals_and_hash();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
@@ -8158,7 +8171,8 @@ bool FileOptions::MergePartialFromCodedStream(
// optional bool deprecated = 23 [default = false];
case 23: {
- if (tag == 184u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(184u /* 184 & 0xFF */)) {
set_has_deprecated();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
@@ -8171,7 +8185,8 @@ bool FileOptions::MergePartialFromCodedStream(
// optional bool java_string_check_utf8 = 27 [default = false];
case 27: {
- if (tag == 216u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(216u /* 216 & 0xFF */)) {
set_has_java_string_check_utf8();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
@@ -8184,7 +8199,8 @@ bool FileOptions::MergePartialFromCodedStream(
// optional bool cc_enable_arenas = 31 [default = false];
case 31: {
- if (tag == 248u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(248u /* 248 & 0xFF */)) {
set_has_cc_enable_arenas();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
@@ -8197,11 +8213,12 @@ bool FileOptions::MergePartialFromCodedStream(
// optional string objc_class_prefix = 36;
case 36: {
- if (tag == 290u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(34u /* 290 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_objc_class_prefix()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->objc_class_prefix().data(), this->objc_class_prefix().length(),
+ this->objc_class_prefix().data(), static_cast<int>(this->objc_class_prefix().length()),
::google::protobuf::internal::WireFormat::PARSE,
"google.protobuf.FileOptions.objc_class_prefix");
} else {
@@ -8212,11 +8229,12 @@ bool FileOptions::MergePartialFromCodedStream(
// optional string csharp_namespace = 37;
case 37: {
- if (tag == 298u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(42u /* 298 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_csharp_namespace()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->csharp_namespace().data(), this->csharp_namespace().length(),
+ this->csharp_namespace().data(), static_cast<int>(this->csharp_namespace().length()),
::google::protobuf::internal::WireFormat::PARSE,
"google.protobuf.FileOptions.csharp_namespace");
} else {
@@ -8227,11 +8245,12 @@ bool FileOptions::MergePartialFromCodedStream(
// optional string swift_prefix = 39;
case 39: {
- if (tag == 314u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(58u /* 314 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_swift_prefix()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->swift_prefix().data(), this->swift_prefix().length(),
+ this->swift_prefix().data(), static_cast<int>(this->swift_prefix().length()),
::google::protobuf::internal::WireFormat::PARSE,
"google.protobuf.FileOptions.swift_prefix");
} else {
@@ -8240,33 +8259,76 @@ bool FileOptions::MergePartialFromCodedStream(
break;
}
+ // optional string php_class_prefix = 40;
+ case 40: {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(66u /* 322 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadString(
+ input, this->mutable_php_class_prefix()));
+ ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
+ this->php_class_prefix().data(), static_cast<int>(this->php_class_prefix().length()),
+ ::google::protobuf::internal::WireFormat::PARSE,
+ "google.protobuf.FileOptions.php_class_prefix");
+ } else {
+ goto handle_unusual;
+ }
+ break;
+ }
+
+ // optional string php_namespace = 41;
+ case 41: {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(74u /* 330 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadString(
+ input, this->mutable_php_namespace()));
+ ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
+ this->php_namespace().data(), static_cast<int>(this->php_namespace().length()),
+ ::google::protobuf::internal::WireFormat::PARSE,
+ "google.protobuf.FileOptions.php_namespace");
+ } else {
+ goto handle_unusual;
+ }
+ break;
+ }
+
+ // optional bool php_generic_services = 42 [default = false];
+ case 42: {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(80u /* 336 & 0xFF */)) {
+ set_has_php_generic_services();
+ DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
+ bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
+ input, &php_generic_services_)));
+ } else {
+ goto handle_unusual;
+ }
+ break;
+ }
+
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
case 999: {
- if (tag == 7994u) {
- DO_(input->IncrementRecursionDepth());
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
- input, add_uninterpreted_option()));
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(58u /* 7994 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_uninterpreted_option()));
} else {
goto handle_unusual;
}
- input->UnsafeDecrementRecursionDepth();
break;
}
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
if ((8000u <= tag)) {
- DO_(_extensions_.ParseField(tag, input, internal_default_instance(),
- mutable_unknown_fields()));
+ DO_(_extensions_.ParseField(tag, input,
+ internal_default_instance(),
+ _internal_metadata_.mutable_unknown_fields()));
continue;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
- input, tag, mutable_unknown_fields()));
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -8283,10 +8345,14 @@ failure:
void FileOptions::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.FileOptions)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional string java_package = 1;
- if (has_java_package()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->java_package().data(), this->java_package().length(),
+ this->java_package().data(), static_cast<int>(this->java_package().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.FileOptions.java_package");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -8294,9 +8360,9 @@ void FileOptions::SerializeWithCachedSizes(
}
// optional string java_outer_classname = 8;
- if (has_java_outer_classname()) {
+ if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->java_outer_classname().data(), this->java_outer_classname().length(),
+ this->java_outer_classname().data(), static_cast<int>(this->java_outer_classname().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.FileOptions.java_outer_classname");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -8304,20 +8370,20 @@ void FileOptions::SerializeWithCachedSizes(
}
// optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED];
- if (has_optimize_for()) {
+ if (cached_has_bits & 0x00020000u) {
::google::protobuf::internal::WireFormatLite::WriteEnum(
9, this->optimize_for(), output);
}
// optional bool java_multiple_files = 10 [default = false];
- if (has_java_multiple_files()) {
+ if (cached_has_bits & 0x00000200u) {
::google::protobuf::internal::WireFormatLite::WriteBool(10, this->java_multiple_files(), output);
}
// optional string go_package = 11;
- if (has_go_package()) {
+ if (cached_has_bits & 0x00000004u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->go_package().data(), this->go_package().length(),
+ this->go_package().data(), static_cast<int>(this->go_package().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.FileOptions.go_package");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -8325,44 +8391,44 @@ void FileOptions::SerializeWithCachedSizes(
}
// optional bool cc_generic_services = 16 [default = false];
- if (has_cc_generic_services()) {
+ if (cached_has_bits & 0x00001000u) {
::google::protobuf::internal::WireFormatLite::WriteBool(16, this->cc_generic_services(), output);
}
// optional bool java_generic_services = 17 [default = false];
- if (has_java_generic_services()) {
+ if (cached_has_bits & 0x00002000u) {
::google::protobuf::internal::WireFormatLite::WriteBool(17, this->java_generic_services(), output);
}
// optional bool py_generic_services = 18 [default = false];
- if (has_py_generic_services()) {
+ if (cached_has_bits & 0x00004000u) {
::google::protobuf::internal::WireFormatLite::WriteBool(18, this->py_generic_services(), output);
}
// optional bool java_generate_equals_and_hash = 20 [deprecated = true];
- if (has_java_generate_equals_and_hash()) {
+ if (cached_has_bits & 0x00000400u) {
::google::protobuf::internal::WireFormatLite::WriteBool(20, this->java_generate_equals_and_hash(), output);
}
// optional bool deprecated = 23 [default = false];
- if (has_deprecated()) {
+ if (cached_has_bits & 0x00010000u) {
::google::protobuf::internal::WireFormatLite::WriteBool(23, this->deprecated(), output);
}
// optional bool java_string_check_utf8 = 27 [default = false];
- if (has_java_string_check_utf8()) {
+ if (cached_has_bits & 0x00000800u) {
::google::protobuf::internal::WireFormatLite::WriteBool(27, this->java_string_check_utf8(), output);
}
// optional bool cc_enable_arenas = 31 [default = false];
- if (has_cc_enable_arenas()) {
+ if (cached_has_bits & 0x00000100u) {
::google::protobuf::internal::WireFormatLite::WriteBool(31, this->cc_enable_arenas(), output);
}
// optional string objc_class_prefix = 36;
- if (has_objc_class_prefix()) {
+ if (cached_has_bits & 0x00000008u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->objc_class_prefix().data(), this->objc_class_prefix().length(),
+ this->objc_class_prefix().data(), static_cast<int>(this->objc_class_prefix().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.FileOptions.objc_class_prefix");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -8370,9 +8436,9 @@ void FileOptions::SerializeWithCachedSizes(
}
// optional string csharp_namespace = 37;
- if (has_csharp_namespace()) {
+ if (cached_has_bits & 0x00000010u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->csharp_namespace().data(), this->csharp_namespace().length(),
+ this->csharp_namespace().data(), static_cast<int>(this->csharp_namespace().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.FileOptions.csharp_namespace");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -8380,19 +8446,45 @@ void FileOptions::SerializeWithCachedSizes(
}
// optional string swift_prefix = 39;
- if (has_swift_prefix()) {
+ if (cached_has_bits & 0x00000020u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->swift_prefix().data(), this->swift_prefix().length(),
+ this->swift_prefix().data(), static_cast<int>(this->swift_prefix().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.FileOptions.swift_prefix");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
39, this->swift_prefix(), output);
}
+ // optional string php_class_prefix = 40;
+ if (cached_has_bits & 0x00000040u) {
+ ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
+ this->php_class_prefix().data(), static_cast<int>(this->php_class_prefix().length()),
+ ::google::protobuf::internal::WireFormat::SERIALIZE,
+ "google.protobuf.FileOptions.php_class_prefix");
+ ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
+ 40, this->php_class_prefix(), output);
+ }
+
+ // optional string php_namespace = 41;
+ if (cached_has_bits & 0x00000080u) {
+ ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
+ this->php_namespace().data(), static_cast<int>(this->php_namespace().length()),
+ ::google::protobuf::internal::WireFormat::SERIALIZE,
+ "google.protobuf.FileOptions.php_namespace");
+ ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
+ 41, this->php_namespace(), output);
+ }
+
+ // optional bool php_generic_services = 42 [default = false];
+ if (cached_has_bits & 0x00008000u) {
+ ::google::protobuf::internal::WireFormatLite::WriteBool(42, this->php_generic_services(), output);
+ }
+
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
- for (unsigned int i = 0, n = this->uninterpreted_option_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->uninterpreted_option_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 999, this->uninterpreted_option(i), output);
+ 999, this->uninterpreted_option(static_cast<int>(i)), output);
}
// Extension range [1000, 536870912)
@@ -8401,7 +8493,7 @@ void FileOptions::SerializeWithCachedSizes(
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- unknown_fields(), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.FileOptions)
}
@@ -8410,10 +8502,14 @@ void FileOptions::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.FileOptions)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional string java_package = 1;
- if (has_java_package()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->java_package().data(), this->java_package().length(),
+ this->java_package().data(), static_cast<int>(this->java_package().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.FileOptions.java_package");
target =
@@ -8422,9 +8518,9 @@ void FileOptions::SerializeWithCachedSizes(
}
// optional string java_outer_classname = 8;
- if (has_java_outer_classname()) {
+ if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->java_outer_classname().data(), this->java_outer_classname().length(),
+ this->java_outer_classname().data(), static_cast<int>(this->java_outer_classname().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.FileOptions.java_outer_classname");
target =
@@ -8433,20 +8529,20 @@ void FileOptions::SerializeWithCachedSizes(
}
// optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED];
- if (has_optimize_for()) {
+ if (cached_has_bits & 0x00020000u) {
target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray(
9, this->optimize_for(), target);
}
// optional bool java_multiple_files = 10 [default = false];
- if (has_java_multiple_files()) {
+ if (cached_has_bits & 0x00000200u) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(10, this->java_multiple_files(), target);
}
// optional string go_package = 11;
- if (has_go_package()) {
+ if (cached_has_bits & 0x00000004u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->go_package().data(), this->go_package().length(),
+ this->go_package().data(), static_cast<int>(this->go_package().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.FileOptions.go_package");
target =
@@ -8455,44 +8551,44 @@ void FileOptions::SerializeWithCachedSizes(
}
// optional bool cc_generic_services = 16 [default = false];
- if (has_cc_generic_services()) {
+ if (cached_has_bits & 0x00001000u) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(16, this->cc_generic_services(), target);
}
// optional bool java_generic_services = 17 [default = false];
- if (has_java_generic_services()) {
+ if (cached_has_bits & 0x00002000u) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(17, this->java_generic_services(), target);
}
// optional bool py_generic_services = 18 [default = false];
- if (has_py_generic_services()) {
+ if (cached_has_bits & 0x00004000u) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(18, this->py_generic_services(), target);
}
// optional bool java_generate_equals_and_hash = 20 [deprecated = true];
- if (has_java_generate_equals_and_hash()) {
+ if (cached_has_bits & 0x00000400u) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(20, this->java_generate_equals_and_hash(), target);
}
// optional bool deprecated = 23 [default = false];
- if (has_deprecated()) {
+ if (cached_has_bits & 0x00010000u) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(23, this->deprecated(), target);
}
// optional bool java_string_check_utf8 = 27 [default = false];
- if (has_java_string_check_utf8()) {
+ if (cached_has_bits & 0x00000800u) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(27, this->java_string_check_utf8(), target);
}
// optional bool cc_enable_arenas = 31 [default = false];
- if (has_cc_enable_arenas()) {
+ if (cached_has_bits & 0x00000100u) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(31, this->cc_enable_arenas(), target);
}
// optional string objc_class_prefix = 36;
- if (has_objc_class_prefix()) {
+ if (cached_has_bits & 0x00000008u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->objc_class_prefix().data(), this->objc_class_prefix().length(),
+ this->objc_class_prefix().data(), static_cast<int>(this->objc_class_prefix().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.FileOptions.objc_class_prefix");
target =
@@ -8501,9 +8597,9 @@ void FileOptions::SerializeWithCachedSizes(
}
// optional string csharp_namespace = 37;
- if (has_csharp_namespace()) {
+ if (cached_has_bits & 0x00000010u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->csharp_namespace().data(), this->csharp_namespace().length(),
+ this->csharp_namespace().data(), static_cast<int>(this->csharp_namespace().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.FileOptions.csharp_namespace");
target =
@@ -8512,9 +8608,9 @@ void FileOptions::SerializeWithCachedSizes(
}
// optional string swift_prefix = 39;
- if (has_swift_prefix()) {
+ if (cached_has_bits & 0x00000020u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->swift_prefix().data(), this->swift_prefix().length(),
+ this->swift_prefix().data(), static_cast<int>(this->swift_prefix().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.FileOptions.swift_prefix");
target =
@@ -8522,20 +8618,48 @@ void FileOptions::SerializeWithCachedSizes(
39, this->swift_prefix(), target);
}
+ // optional string php_class_prefix = 40;
+ if (cached_has_bits & 0x00000040u) {
+ ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
+ this->php_class_prefix().data(), static_cast<int>(this->php_class_prefix().length()),
+ ::google::protobuf::internal::WireFormat::SERIALIZE,
+ "google.protobuf.FileOptions.php_class_prefix");
+ target =
+ ::google::protobuf::internal::WireFormatLite::WriteStringToArray(
+ 40, this->php_class_prefix(), target);
+ }
+
+ // optional string php_namespace = 41;
+ if (cached_has_bits & 0x00000080u) {
+ ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
+ this->php_namespace().data(), static_cast<int>(this->php_namespace().length()),
+ ::google::protobuf::internal::WireFormat::SERIALIZE,
+ "google.protobuf.FileOptions.php_namespace");
+ target =
+ ::google::protobuf::internal::WireFormatLite::WriteStringToArray(
+ 41, this->php_namespace(), target);
+ }
+
+ // optional bool php_generic_services = 42 [default = false];
+ if (cached_has_bits & 0x00008000u) {
+ target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(42, this->php_generic_services(), target);
+ }
+
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
- for (unsigned int i = 0, n = this->uninterpreted_option_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->uninterpreted_option_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 999, this->uninterpreted_option(i), false, target);
+ InternalWriteMessageToArray(
+ 999, this->uninterpreted_option(static_cast<int>(i)), deterministic, target);
}
// Extension range [1000, 536870912)
target = _extensions_.InternalSerializeWithCachedSizesToArray(
- 1000, 536870912, false, target);
+ 1000, 536870912, deterministic, target);
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- unknown_fields(), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.FileOptions)
return target;
@@ -8550,16 +8674,16 @@ size_t FileOptions::ByteSizeLong() const {
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- unknown_fields());
+ _internal_metadata_.unknown_fields());
}
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
{
- unsigned int count = this->uninterpreted_option_size();
+ unsigned int count = static_cast<unsigned int>(this->uninterpreted_option_size());
total_size += 2UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->uninterpreted_option(i));
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->uninterpreted_option(static_cast<int>(i)));
}
}
@@ -8606,6 +8730,27 @@ size_t FileOptions::ByteSizeLong() const {
this->swift_prefix());
}
+ // optional string php_class_prefix = 40;
+ if (has_php_class_prefix()) {
+ total_size += 2 +
+ ::google::protobuf::internal::WireFormatLite::StringSize(
+ this->php_class_prefix());
+ }
+
+ // optional string php_namespace = 41;
+ if (has_php_namespace()) {
+ total_size += 2 +
+ ::google::protobuf::internal::WireFormatLite::StringSize(
+ this->php_namespace());
+ }
+
+ }
+ if (_has_bits_[8 / 32] & 65280u) {
+ // optional bool cc_enable_arenas = 31 [default = false];
+ if (has_cc_enable_arenas()) {
+ total_size += 2 + 1;
+ }
+
// optional bool java_multiple_files = 10 [default = false];
if (has_java_multiple_files()) {
total_size += 1 + 1;
@@ -8616,8 +8761,6 @@ size_t FileOptions::ByteSizeLong() const {
total_size += 2 + 1;
}
- }
- if (_has_bits_[8 / 32] & 32512u) {
// optional bool java_string_check_utf8 = 27 [default = false];
if (has_java_string_check_utf8()) {
total_size += 2 + 1;
@@ -8638,13 +8781,15 @@ size_t FileOptions::ByteSizeLong() const {
total_size += 2 + 1;
}
- // optional bool deprecated = 23 [default = false];
- if (has_deprecated()) {
+ // optional bool php_generic_services = 42 [default = false];
+ if (has_php_generic_services()) {
total_size += 2 + 1;
}
- // optional bool cc_enable_arenas = 31 [default = false];
- if (has_cc_enable_arenas()) {
+ }
+ if (_has_bits_[16 / 32] & 196608u) {
+ // optional bool deprecated = 23 [default = false];
+ if (has_deprecated()) {
total_size += 2 + 1;
}
@@ -8682,61 +8827,72 @@ void FileOptions::MergeFrom(const FileOptions& from) {
GOOGLE_DCHECK_NE(&from, this);
_extensions_.MergeFrom(from._extensions_);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
uninterpreted_option_.MergeFrom(from.uninterpreted_option_);
- if (from._has_bits_[0 / 32] & 255u) {
- if (from.has_java_package()) {
- set_has_java_package();
- java_package_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.java_package_);
+ cached_has_bits = from._has_bits_[0];
+ if (cached_has_bits & 255u) {
+ if (cached_has_bits & 0x00000001u) {
+ set_java_package(from.java_package());
}
- if (from.has_java_outer_classname()) {
- set_has_java_outer_classname();
- java_outer_classname_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.java_outer_classname_);
+ if (cached_has_bits & 0x00000002u) {
+ set_java_outer_classname(from.java_outer_classname());
}
- if (from.has_go_package()) {
- set_has_go_package();
- go_package_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.go_package_);
+ if (cached_has_bits & 0x00000004u) {
+ set_go_package(from.go_package());
}
- if (from.has_objc_class_prefix()) {
- set_has_objc_class_prefix();
- objc_class_prefix_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.objc_class_prefix_);
+ if (cached_has_bits & 0x00000008u) {
+ set_objc_class_prefix(from.objc_class_prefix());
}
- if (from.has_csharp_namespace()) {
- set_has_csharp_namespace();
- csharp_namespace_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.csharp_namespace_);
+ if (cached_has_bits & 0x00000010u) {
+ set_csharp_namespace(from.csharp_namespace());
}
- if (from.has_swift_prefix()) {
- set_has_swift_prefix();
- swift_prefix_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.swift_prefix_);
+ if (cached_has_bits & 0x00000020u) {
+ set_swift_prefix(from.swift_prefix());
}
- if (from.has_java_multiple_files()) {
- set_java_multiple_files(from.java_multiple_files());
+ if (cached_has_bits & 0x00000040u) {
+ set_php_class_prefix(from.php_class_prefix());
}
- if (from.has_java_generate_equals_and_hash()) {
- set_java_generate_equals_and_hash(from.java_generate_equals_and_hash());
+ if (cached_has_bits & 0x00000080u) {
+ set_php_namespace(from.php_namespace());
}
}
- if (from._has_bits_[8 / 32] & 32512u) {
- if (from.has_java_string_check_utf8()) {
- set_java_string_check_utf8(from.java_string_check_utf8());
+ if (cached_has_bits & 65280u) {
+ if (cached_has_bits & 0x00000100u) {
+ cc_enable_arenas_ = from.cc_enable_arenas_;
+ }
+ if (cached_has_bits & 0x00000200u) {
+ java_multiple_files_ = from.java_multiple_files_;
}
- if (from.has_cc_generic_services()) {
- set_cc_generic_services(from.cc_generic_services());
+ if (cached_has_bits & 0x00000400u) {
+ java_generate_equals_and_hash_ = from.java_generate_equals_and_hash_;
}
- if (from.has_java_generic_services()) {
- set_java_generic_services(from.java_generic_services());
+ if (cached_has_bits & 0x00000800u) {
+ java_string_check_utf8_ = from.java_string_check_utf8_;
}
- if (from.has_py_generic_services()) {
- set_py_generic_services(from.py_generic_services());
+ if (cached_has_bits & 0x00001000u) {
+ cc_generic_services_ = from.cc_generic_services_;
}
- if (from.has_deprecated()) {
- set_deprecated(from.deprecated());
+ if (cached_has_bits & 0x00002000u) {
+ java_generic_services_ = from.java_generic_services_;
}
- if (from.has_cc_enable_arenas()) {
- set_cc_enable_arenas(from.cc_enable_arenas());
+ if (cached_has_bits & 0x00004000u) {
+ py_generic_services_ = from.py_generic_services_;
}
- if (from.has_optimize_for()) {
- set_optimize_for(from.optimize_for());
+ if (cached_has_bits & 0x00008000u) {
+ php_generic_services_ = from.php_generic_services_;
}
+ _has_bits_[0] |= cached_has_bits;
+ }
+ if (cached_has_bits & 196608u) {
+ if (cached_has_bits & 0x00010000u) {
+ deprecated_ = from.deprecated_;
+ }
+ if (cached_has_bits & 0x00020000u) {
+ optimize_for_ = from.optimize_for_;
+ }
+ _has_bits_[0] |= cached_has_bits;
}
}
@@ -8765,614 +8921,60 @@ bool FileOptions::IsInitialized() const {
void FileOptions::Swap(FileOptions* other) {
if (other == this) return;
+ if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ InternalSwap(other);
+ } else {
+ FileOptions* temp = New(GetArenaNoVirtual());
+ temp->MergeFrom(*other);
+ other->CopyFrom(*this);
+ InternalSwap(temp);
+ if (GetArenaNoVirtual() == NULL) {
+ delete temp;
+ }
+ }
+}
+void FileOptions::UnsafeArenaSwap(FileOptions* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void FileOptions::InternalSwap(FileOptions* other) {
- uninterpreted_option_.UnsafeArenaSwap(&other->uninterpreted_option_);
+ using std::swap;
+ uninterpreted_option_.InternalSwap(&other->uninterpreted_option_);
java_package_.Swap(&other->java_package_);
java_outer_classname_.Swap(&other->java_outer_classname_);
go_package_.Swap(&other->go_package_);
objc_class_prefix_.Swap(&other->objc_class_prefix_);
csharp_namespace_.Swap(&other->csharp_namespace_);
swift_prefix_.Swap(&other->swift_prefix_);
- std::swap(java_multiple_files_, other->java_multiple_files_);
- std::swap(java_generate_equals_and_hash_, other->java_generate_equals_and_hash_);
- std::swap(java_string_check_utf8_, other->java_string_check_utf8_);
- std::swap(cc_generic_services_, other->cc_generic_services_);
- std::swap(java_generic_services_, other->java_generic_services_);
- std::swap(py_generic_services_, other->py_generic_services_);
- std::swap(deprecated_, other->deprecated_);
- std::swap(cc_enable_arenas_, other->cc_enable_arenas_);
- std::swap(optimize_for_, other->optimize_for_);
- std::swap(_has_bits_[0], other->_has_bits_[0]);
+ php_class_prefix_.Swap(&other->php_class_prefix_);
+ php_namespace_.Swap(&other->php_namespace_);
+ swap(cc_enable_arenas_, other->cc_enable_arenas_);
+ swap(java_multiple_files_, other->java_multiple_files_);
+ swap(java_generate_equals_and_hash_, other->java_generate_equals_and_hash_);
+ swap(java_string_check_utf8_, other->java_string_check_utf8_);
+ swap(cc_generic_services_, other->cc_generic_services_);
+ swap(java_generic_services_, other->java_generic_services_);
+ swap(py_generic_services_, other->py_generic_services_);
+ swap(php_generic_services_, other->php_generic_services_);
+ swap(deprecated_, other->deprecated_);
+ swap(optimize_for_, other->optimize_for_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- std::swap(_cached_size_, other->_cached_size_);
+ swap(_cached_size_, other->_cached_size_);
_extensions_.Swap(&other->_extensions_);
}
::google::protobuf::Metadata FileOptions::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[11];
-}
-
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// FileOptions
-
-// optional string java_package = 1;
-bool FileOptions::has_java_package() const {
- return (_has_bits_[0] & 0x00000001u) != 0;
-}
-void FileOptions::set_has_java_package() {
- _has_bits_[0] |= 0x00000001u;
-}
-void FileOptions::clear_has_java_package() {
- _has_bits_[0] &= ~0x00000001u;
-}
-void FileOptions::clear_java_package() {
- java_package_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_java_package();
-}
-const ::std::string& FileOptions::java_package() const {
- // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.java_package)
- return java_package_.GetNoArena();
-}
-void FileOptions::set_java_package(const ::std::string& value) {
- set_has_java_package();
- java_package_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.java_package)
-}
-void FileOptions::set_java_package(const char* value) {
- set_has_java_package();
- java_package_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.java_package)
-}
-void FileOptions::set_java_package(const char* value, size_t size) {
- set_has_java_package();
- java_package_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.java_package)
-}
-::std::string* FileOptions::mutable_java_package() {
- set_has_java_package();
- // @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.java_package)
- return java_package_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* FileOptions::release_java_package() {
- // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.java_package)
- clear_has_java_package();
- return java_package_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void FileOptions::set_allocated_java_package(::std::string* java_package) {
- if (java_package != NULL) {
- set_has_java_package();
- } else {
- clear_has_java_package();
- }
- java_package_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), java_package);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.java_package)
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
}
-// optional string java_outer_classname = 8;
-bool FileOptions::has_java_outer_classname() const {
- return (_has_bits_[0] & 0x00000002u) != 0;
-}
-void FileOptions::set_has_java_outer_classname() {
- _has_bits_[0] |= 0x00000002u;
-}
-void FileOptions::clear_has_java_outer_classname() {
- _has_bits_[0] &= ~0x00000002u;
-}
-void FileOptions::clear_java_outer_classname() {
- java_outer_classname_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_java_outer_classname();
-}
-const ::std::string& FileOptions::java_outer_classname() const {
- // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.java_outer_classname)
- return java_outer_classname_.GetNoArena();
-}
-void FileOptions::set_java_outer_classname(const ::std::string& value) {
- set_has_java_outer_classname();
- java_outer_classname_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.java_outer_classname)
-}
-void FileOptions::set_java_outer_classname(const char* value) {
- set_has_java_outer_classname();
- java_outer_classname_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.java_outer_classname)
-}
-void FileOptions::set_java_outer_classname(const char* value, size_t size) {
- set_has_java_outer_classname();
- java_outer_classname_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.java_outer_classname)
-}
-::std::string* FileOptions::mutable_java_outer_classname() {
- set_has_java_outer_classname();
- // @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.java_outer_classname)
- return java_outer_classname_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* FileOptions::release_java_outer_classname() {
- // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.java_outer_classname)
- clear_has_java_outer_classname();
- return java_outer_classname_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void FileOptions::set_allocated_java_outer_classname(::std::string* java_outer_classname) {
- if (java_outer_classname != NULL) {
- set_has_java_outer_classname();
- } else {
- clear_has_java_outer_classname();
- }
- java_outer_classname_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), java_outer_classname);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.java_outer_classname)
-}
-
-// optional bool java_multiple_files = 10 [default = false];
-bool FileOptions::has_java_multiple_files() const {
- return (_has_bits_[0] & 0x00000040u) != 0;
-}
-void FileOptions::set_has_java_multiple_files() {
- _has_bits_[0] |= 0x00000040u;
-}
-void FileOptions::clear_has_java_multiple_files() {
- _has_bits_[0] &= ~0x00000040u;
-}
-void FileOptions::clear_java_multiple_files() {
- java_multiple_files_ = false;
- clear_has_java_multiple_files();
-}
-bool FileOptions::java_multiple_files() const {
- // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.java_multiple_files)
- return java_multiple_files_;
-}
-void FileOptions::set_java_multiple_files(bool value) {
- set_has_java_multiple_files();
- java_multiple_files_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.java_multiple_files)
-}
-
-// optional bool java_generate_equals_and_hash = 20 [deprecated = true];
-bool FileOptions::has_java_generate_equals_and_hash() const {
- return (_has_bits_[0] & 0x00000080u) != 0;
-}
-void FileOptions::set_has_java_generate_equals_and_hash() {
- _has_bits_[0] |= 0x00000080u;
-}
-void FileOptions::clear_has_java_generate_equals_and_hash() {
- _has_bits_[0] &= ~0x00000080u;
-}
-void FileOptions::clear_java_generate_equals_and_hash() {
- java_generate_equals_and_hash_ = false;
- clear_has_java_generate_equals_and_hash();
-}
-bool FileOptions::java_generate_equals_and_hash() const {
- // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.java_generate_equals_and_hash)
- return java_generate_equals_and_hash_;
-}
-void FileOptions::set_java_generate_equals_and_hash(bool value) {
- set_has_java_generate_equals_and_hash();
- java_generate_equals_and_hash_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.java_generate_equals_and_hash)
-}
-
-// optional bool java_string_check_utf8 = 27 [default = false];
-bool FileOptions::has_java_string_check_utf8() const {
- return (_has_bits_[0] & 0x00000100u) != 0;
-}
-void FileOptions::set_has_java_string_check_utf8() {
- _has_bits_[0] |= 0x00000100u;
-}
-void FileOptions::clear_has_java_string_check_utf8() {
- _has_bits_[0] &= ~0x00000100u;
-}
-void FileOptions::clear_java_string_check_utf8() {
- java_string_check_utf8_ = false;
- clear_has_java_string_check_utf8();
-}
-bool FileOptions::java_string_check_utf8() const {
- // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.java_string_check_utf8)
- return java_string_check_utf8_;
-}
-void FileOptions::set_java_string_check_utf8(bool value) {
- set_has_java_string_check_utf8();
- java_string_check_utf8_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.java_string_check_utf8)
-}
-
-// optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED];
-bool FileOptions::has_optimize_for() const {
- return (_has_bits_[0] & 0x00004000u) != 0;
-}
-void FileOptions::set_has_optimize_for() {
- _has_bits_[0] |= 0x00004000u;
-}
-void FileOptions::clear_has_optimize_for() {
- _has_bits_[0] &= ~0x00004000u;
-}
-void FileOptions::clear_optimize_for() {
- optimize_for_ = 1;
- clear_has_optimize_for();
-}
-::google::protobuf::FileOptions_OptimizeMode FileOptions::optimize_for() const {
- // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.optimize_for)
- return static_cast< ::google::protobuf::FileOptions_OptimizeMode >(optimize_for_);
-}
-void FileOptions::set_optimize_for(::google::protobuf::FileOptions_OptimizeMode value) {
- assert(::google::protobuf::FileOptions_OptimizeMode_IsValid(value));
- set_has_optimize_for();
- optimize_for_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.optimize_for)
-}
-
-// optional string go_package = 11;
-bool FileOptions::has_go_package() const {
- return (_has_bits_[0] & 0x00000004u) != 0;
-}
-void FileOptions::set_has_go_package() {
- _has_bits_[0] |= 0x00000004u;
-}
-void FileOptions::clear_has_go_package() {
- _has_bits_[0] &= ~0x00000004u;
-}
-void FileOptions::clear_go_package() {
- go_package_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_go_package();
-}
-const ::std::string& FileOptions::go_package() const {
- // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.go_package)
- return go_package_.GetNoArena();
-}
-void FileOptions::set_go_package(const ::std::string& value) {
- set_has_go_package();
- go_package_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.go_package)
-}
-void FileOptions::set_go_package(const char* value) {
- set_has_go_package();
- go_package_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.go_package)
-}
-void FileOptions::set_go_package(const char* value, size_t size) {
- set_has_go_package();
- go_package_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.go_package)
-}
-::std::string* FileOptions::mutable_go_package() {
- set_has_go_package();
- // @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.go_package)
- return go_package_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* FileOptions::release_go_package() {
- // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.go_package)
- clear_has_go_package();
- return go_package_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void FileOptions::set_allocated_go_package(::std::string* go_package) {
- if (go_package != NULL) {
- set_has_go_package();
- } else {
- clear_has_go_package();
- }
- go_package_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), go_package);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.go_package)
-}
-
-// optional bool cc_generic_services = 16 [default = false];
-bool FileOptions::has_cc_generic_services() const {
- return (_has_bits_[0] & 0x00000200u) != 0;
-}
-void FileOptions::set_has_cc_generic_services() {
- _has_bits_[0] |= 0x00000200u;
-}
-void FileOptions::clear_has_cc_generic_services() {
- _has_bits_[0] &= ~0x00000200u;
-}
-void FileOptions::clear_cc_generic_services() {
- cc_generic_services_ = false;
- clear_has_cc_generic_services();
-}
-bool FileOptions::cc_generic_services() const {
- // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.cc_generic_services)
- return cc_generic_services_;
-}
-void FileOptions::set_cc_generic_services(bool value) {
- set_has_cc_generic_services();
- cc_generic_services_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.cc_generic_services)
-}
-
-// optional bool java_generic_services = 17 [default = false];
-bool FileOptions::has_java_generic_services() const {
- return (_has_bits_[0] & 0x00000400u) != 0;
-}
-void FileOptions::set_has_java_generic_services() {
- _has_bits_[0] |= 0x00000400u;
-}
-void FileOptions::clear_has_java_generic_services() {
- _has_bits_[0] &= ~0x00000400u;
-}
-void FileOptions::clear_java_generic_services() {
- java_generic_services_ = false;
- clear_has_java_generic_services();
-}
-bool FileOptions::java_generic_services() const {
- // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.java_generic_services)
- return java_generic_services_;
-}
-void FileOptions::set_java_generic_services(bool value) {
- set_has_java_generic_services();
- java_generic_services_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.java_generic_services)
-}
-
-// optional bool py_generic_services = 18 [default = false];
-bool FileOptions::has_py_generic_services() const {
- return (_has_bits_[0] & 0x00000800u) != 0;
-}
-void FileOptions::set_has_py_generic_services() {
- _has_bits_[0] |= 0x00000800u;
-}
-void FileOptions::clear_has_py_generic_services() {
- _has_bits_[0] &= ~0x00000800u;
-}
-void FileOptions::clear_py_generic_services() {
- py_generic_services_ = false;
- clear_has_py_generic_services();
-}
-bool FileOptions::py_generic_services() const {
- // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.py_generic_services)
- return py_generic_services_;
-}
-void FileOptions::set_py_generic_services(bool value) {
- set_has_py_generic_services();
- py_generic_services_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.py_generic_services)
-}
-
-// optional bool deprecated = 23 [default = false];
-bool FileOptions::has_deprecated() const {
- return (_has_bits_[0] & 0x00001000u) != 0;
-}
-void FileOptions::set_has_deprecated() {
- _has_bits_[0] |= 0x00001000u;
-}
-void FileOptions::clear_has_deprecated() {
- _has_bits_[0] &= ~0x00001000u;
-}
-void FileOptions::clear_deprecated() {
- deprecated_ = false;
- clear_has_deprecated();
-}
-bool FileOptions::deprecated() const {
- // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.deprecated)
- return deprecated_;
-}
-void FileOptions::set_deprecated(bool value) {
- set_has_deprecated();
- deprecated_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.deprecated)
-}
-
-// optional bool cc_enable_arenas = 31 [default = false];
-bool FileOptions::has_cc_enable_arenas() const {
- return (_has_bits_[0] & 0x00002000u) != 0;
-}
-void FileOptions::set_has_cc_enable_arenas() {
- _has_bits_[0] |= 0x00002000u;
-}
-void FileOptions::clear_has_cc_enable_arenas() {
- _has_bits_[0] &= ~0x00002000u;
-}
-void FileOptions::clear_cc_enable_arenas() {
- cc_enable_arenas_ = false;
- clear_has_cc_enable_arenas();
-}
-bool FileOptions::cc_enable_arenas() const {
- // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.cc_enable_arenas)
- return cc_enable_arenas_;
-}
-void FileOptions::set_cc_enable_arenas(bool value) {
- set_has_cc_enable_arenas();
- cc_enable_arenas_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.cc_enable_arenas)
-}
-
-// optional string objc_class_prefix = 36;
-bool FileOptions::has_objc_class_prefix() const {
- return (_has_bits_[0] & 0x00000008u) != 0;
-}
-void FileOptions::set_has_objc_class_prefix() {
- _has_bits_[0] |= 0x00000008u;
-}
-void FileOptions::clear_has_objc_class_prefix() {
- _has_bits_[0] &= ~0x00000008u;
-}
-void FileOptions::clear_objc_class_prefix() {
- objc_class_prefix_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_objc_class_prefix();
-}
-const ::std::string& FileOptions::objc_class_prefix() const {
- // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.objc_class_prefix)
- return objc_class_prefix_.GetNoArena();
-}
-void FileOptions::set_objc_class_prefix(const ::std::string& value) {
- set_has_objc_class_prefix();
- objc_class_prefix_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.objc_class_prefix)
-}
-void FileOptions::set_objc_class_prefix(const char* value) {
- set_has_objc_class_prefix();
- objc_class_prefix_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.objc_class_prefix)
-}
-void FileOptions::set_objc_class_prefix(const char* value, size_t size) {
- set_has_objc_class_prefix();
- objc_class_prefix_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.objc_class_prefix)
-}
-::std::string* FileOptions::mutable_objc_class_prefix() {
- set_has_objc_class_prefix();
- // @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.objc_class_prefix)
- return objc_class_prefix_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* FileOptions::release_objc_class_prefix() {
- // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.objc_class_prefix)
- clear_has_objc_class_prefix();
- return objc_class_prefix_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void FileOptions::set_allocated_objc_class_prefix(::std::string* objc_class_prefix) {
- if (objc_class_prefix != NULL) {
- set_has_objc_class_prefix();
- } else {
- clear_has_objc_class_prefix();
- }
- objc_class_prefix_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), objc_class_prefix);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.objc_class_prefix)
-}
-
-// optional string csharp_namespace = 37;
-bool FileOptions::has_csharp_namespace() const {
- return (_has_bits_[0] & 0x00000010u) != 0;
-}
-void FileOptions::set_has_csharp_namespace() {
- _has_bits_[0] |= 0x00000010u;
-}
-void FileOptions::clear_has_csharp_namespace() {
- _has_bits_[0] &= ~0x00000010u;
-}
-void FileOptions::clear_csharp_namespace() {
- csharp_namespace_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_csharp_namespace();
-}
-const ::std::string& FileOptions::csharp_namespace() const {
- // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.csharp_namespace)
- return csharp_namespace_.GetNoArena();
-}
-void FileOptions::set_csharp_namespace(const ::std::string& value) {
- set_has_csharp_namespace();
- csharp_namespace_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.csharp_namespace)
-}
-void FileOptions::set_csharp_namespace(const char* value) {
- set_has_csharp_namespace();
- csharp_namespace_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.csharp_namespace)
-}
-void FileOptions::set_csharp_namespace(const char* value, size_t size) {
- set_has_csharp_namespace();
- csharp_namespace_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.csharp_namespace)
-}
-::std::string* FileOptions::mutable_csharp_namespace() {
- set_has_csharp_namespace();
- // @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.csharp_namespace)
- return csharp_namespace_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* FileOptions::release_csharp_namespace() {
- // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.csharp_namespace)
- clear_has_csharp_namespace();
- return csharp_namespace_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void FileOptions::set_allocated_csharp_namespace(::std::string* csharp_namespace) {
- if (csharp_namespace != NULL) {
- set_has_csharp_namespace();
- } else {
- clear_has_csharp_namespace();
- }
- csharp_namespace_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), csharp_namespace);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.csharp_namespace)
-}
-
-// optional string swift_prefix = 39;
-bool FileOptions::has_swift_prefix() const {
- return (_has_bits_[0] & 0x00000020u) != 0;
-}
-void FileOptions::set_has_swift_prefix() {
- _has_bits_[0] |= 0x00000020u;
-}
-void FileOptions::clear_has_swift_prefix() {
- _has_bits_[0] &= ~0x00000020u;
-}
-void FileOptions::clear_swift_prefix() {
- swift_prefix_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_swift_prefix();
-}
-const ::std::string& FileOptions::swift_prefix() const {
- // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.swift_prefix)
- return swift_prefix_.GetNoArena();
-}
-void FileOptions::set_swift_prefix(const ::std::string& value) {
- set_has_swift_prefix();
- swift_prefix_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.swift_prefix)
-}
-void FileOptions::set_swift_prefix(const char* value) {
- set_has_swift_prefix();
- swift_prefix_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.swift_prefix)
-}
-void FileOptions::set_swift_prefix(const char* value, size_t size) {
- set_has_swift_prefix();
- swift_prefix_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.swift_prefix)
-}
-::std::string* FileOptions::mutable_swift_prefix() {
- set_has_swift_prefix();
- // @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.swift_prefix)
- return swift_prefix_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* FileOptions::release_swift_prefix() {
- // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.swift_prefix)
- clear_has_swift_prefix();
- return swift_prefix_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void FileOptions::set_allocated_swift_prefix(::std::string* swift_prefix) {
- if (swift_prefix != NULL) {
- set_has_swift_prefix();
- } else {
- clear_has_swift_prefix();
- }
- swift_prefix_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), swift_prefix);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.swift_prefix)
-}
-
-// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
-int FileOptions::uninterpreted_option_size() const {
- return uninterpreted_option_.size();
-}
-void FileOptions::clear_uninterpreted_option() {
- uninterpreted_option_.Clear();
-}
-const ::google::protobuf::UninterpretedOption& FileOptions::uninterpreted_option(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.uninterpreted_option)
- return uninterpreted_option_.Get(index);
-}
-::google::protobuf::UninterpretedOption* FileOptions::mutable_uninterpreted_option(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.uninterpreted_option)
- return uninterpreted_option_.Mutable(index);
-}
-::google::protobuf::UninterpretedOption* FileOptions::add_uninterpreted_option() {
- // @@protoc_insertion_point(field_add:google.protobuf.FileOptions.uninterpreted_option)
- return uninterpreted_option_.Add();
-}
-::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >*
-FileOptions::mutable_uninterpreted_option() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.FileOptions.uninterpreted_option)
- return &uninterpreted_option_;
-}
-const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
-FileOptions::uninterpreted_option() const {
- // @@protoc_insertion_point(field_list:google.protobuf.FileOptions.uninterpreted_option)
- return uninterpreted_option_;
-}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
+void MessageOptions::InitAsDefaultInstance() {
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int MessageOptions::kMessageSetWireFormatFieldNumber;
const int MessageOptions::kNoStandardDescriptorAccessorFieldNumber;
@@ -9384,11 +8986,21 @@ const int MessageOptions::kUninterpretedOptionFieldNumber;
MessageOptions::MessageOptions()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMessageOptions();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.MessageOptions)
}
+MessageOptions::MessageOptions(::google::protobuf::Arena* arena)
+ : ::google::protobuf::Message(),
+ _extensions_(arena),
+ _internal_metadata_(arena),
+ uninterpreted_option_(arena) {
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMessageOptions();
+ SharedCtor();
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.MessageOptions)
+}
MessageOptions::MessageOptions(const MessageOptions& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
@@ -9398,15 +9010,16 @@ MessageOptions::MessageOptions(const MessageOptions& from)
_internal_metadata_.MergeFrom(from._internal_metadata_);
_extensions_.MergeFrom(from._extensions_);
::memcpy(&message_set_wire_format_, &from.message_set_wire_format_,
- reinterpret_cast<char*>(&map_entry_) -
- reinterpret_cast<char*>(&message_set_wire_format_) + sizeof(map_entry_));
+ static_cast<size_t>(reinterpret_cast<char*>(&map_entry_) -
+ reinterpret_cast<char*>(&message_set_wire_format_)) + sizeof(map_entry_));
// @@protoc_insertion_point(copy_constructor:google.protobuf.MessageOptions)
}
void MessageOptions::SharedCtor() {
_cached_size_ = 0;
- ::memset(&message_set_wire_format_, 0, reinterpret_cast<char*>(&map_entry_) -
- reinterpret_cast<char*>(&message_set_wire_format_) + sizeof(map_entry_));
+ ::memset(&message_set_wire_format_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&map_entry_) -
+ reinterpret_cast<char*>(&message_set_wire_format_)) + sizeof(map_entry_));
}
MessageOptions::~MessageOptions() {
@@ -9415,39 +9028,45 @@ MessageOptions::~MessageOptions() {
}
void MessageOptions::SharedDtor() {
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
}
+void MessageOptions::ArenaDtor(void* object) {
+ MessageOptions* _this = reinterpret_cast< MessageOptions* >(object);
+ (void)_this;
+}
+void MessageOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+}
void MessageOptions::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* MessageOptions::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[12].descriptor;
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const MessageOptions& MessageOptions::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMessageOptions();
return *internal_default_instance();
}
MessageOptions* MessageOptions::New(::google::protobuf::Arena* arena) const {
- MessageOptions* n = new MessageOptions;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
+ return ::google::protobuf::Arena::CreateMessage<MessageOptions>(arena);
}
void MessageOptions::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.MessageOptions)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
_extensions_.Clear();
uninterpreted_option_.Clear();
- if (_has_bits_[0 / 32] & 15u) {
- ::memset(&message_set_wire_format_, 0, reinterpret_cast<char*>(&map_entry_) -
- reinterpret_cast<char*>(&message_set_wire_format_) + sizeof(map_entry_));
- }
+ ::memset(&message_set_wire_format_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&map_entry_) -
+ reinterpret_cast<char*>(&message_set_wire_format_)) + sizeof(map_entry_));
_has_bits_.Clear();
_internal_metadata_.Clear();
}
@@ -9464,7 +9083,8 @@ bool MessageOptions::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional bool message_set_wire_format = 1 [default = false];
case 1: {
- if (tag == 8u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
set_has_message_set_wire_format();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
@@ -9477,7 +9097,8 @@ bool MessageOptions::MergePartialFromCodedStream(
// optional bool no_standard_descriptor_accessor = 2 [default = false];
case 2: {
- if (tag == 16u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
set_has_no_standard_descriptor_accessor();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
@@ -9490,7 +9111,8 @@ bool MessageOptions::MergePartialFromCodedStream(
// optional bool deprecated = 3 [default = false];
case 3: {
- if (tag == 24u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) {
set_has_deprecated();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
@@ -9503,7 +9125,8 @@ bool MessageOptions::MergePartialFromCodedStream(
// optional bool map_entry = 7;
case 7: {
- if (tag == 56u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(56u /* 56 & 0xFF */)) {
set_has_map_entry();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
@@ -9516,31 +9139,28 @@ bool MessageOptions::MergePartialFromCodedStream(
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
case 999: {
- if (tag == 7994u) {
- DO_(input->IncrementRecursionDepth());
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
- input, add_uninterpreted_option()));
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(58u /* 7994 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_uninterpreted_option()));
} else {
goto handle_unusual;
}
- input->UnsafeDecrementRecursionDepth();
break;
}
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
if ((8000u <= tag)) {
- DO_(_extensions_.ParseField(tag, input, internal_default_instance(),
- mutable_unknown_fields()));
+ DO_(_extensions_.ParseField(tag, input,
+ internal_default_instance(),
+ _internal_metadata_.mutable_unknown_fields()));
continue;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
- input, tag, mutable_unknown_fields()));
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -9557,30 +9177,35 @@ failure:
void MessageOptions::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.MessageOptions)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional bool message_set_wire_format = 1 [default = false];
- if (has_message_set_wire_format()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormatLite::WriteBool(1, this->message_set_wire_format(), output);
}
// optional bool no_standard_descriptor_accessor = 2 [default = false];
- if (has_no_standard_descriptor_accessor()) {
+ if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteBool(2, this->no_standard_descriptor_accessor(), output);
}
// optional bool deprecated = 3 [default = false];
- if (has_deprecated()) {
+ if (cached_has_bits & 0x00000004u) {
::google::protobuf::internal::WireFormatLite::WriteBool(3, this->deprecated(), output);
}
// optional bool map_entry = 7;
- if (has_map_entry()) {
+ if (cached_has_bits & 0x00000008u) {
::google::protobuf::internal::WireFormatLite::WriteBool(7, this->map_entry(), output);
}
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
- for (unsigned int i = 0, n = this->uninterpreted_option_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->uninterpreted_option_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 999, this->uninterpreted_option(i), output);
+ 999, this->uninterpreted_option(static_cast<int>(i)), output);
}
// Extension range [1000, 536870912)
@@ -9589,7 +9214,7 @@ void MessageOptions::SerializeWithCachedSizes(
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- unknown_fields(), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.MessageOptions)
}
@@ -9598,40 +9223,45 @@ void MessageOptions::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.MessageOptions)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional bool message_set_wire_format = 1 [default = false];
- if (has_message_set_wire_format()) {
+ if (cached_has_bits & 0x00000001u) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(1, this->message_set_wire_format(), target);
}
// optional bool no_standard_descriptor_accessor = 2 [default = false];
- if (has_no_standard_descriptor_accessor()) {
+ if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(2, this->no_standard_descriptor_accessor(), target);
}
// optional bool deprecated = 3 [default = false];
- if (has_deprecated()) {
+ if (cached_has_bits & 0x00000004u) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(3, this->deprecated(), target);
}
// optional bool map_entry = 7;
- if (has_map_entry()) {
+ if (cached_has_bits & 0x00000008u) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(7, this->map_entry(), target);
}
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
- for (unsigned int i = 0, n = this->uninterpreted_option_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->uninterpreted_option_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 999, this->uninterpreted_option(i), false, target);
+ InternalWriteMessageToArray(
+ 999, this->uninterpreted_option(static_cast<int>(i)), deterministic, target);
}
// Extension range [1000, 536870912)
target = _extensions_.InternalSerializeWithCachedSizesToArray(
- 1000, 536870912, false, target);
+ 1000, 536870912, deterministic, target);
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- unknown_fields(), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.MessageOptions)
return target;
@@ -9646,16 +9276,16 @@ size_t MessageOptions::ByteSizeLong() const {
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- unknown_fields());
+ _internal_metadata_.unknown_fields());
}
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
{
- unsigned int count = this->uninterpreted_option_size();
+ unsigned int count = static_cast<unsigned int>(this->uninterpreted_option_size());
total_size += 2UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->uninterpreted_option(i));
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->uninterpreted_option(static_cast<int>(i)));
}
}
@@ -9708,20 +9338,25 @@ void MessageOptions::MergeFrom(const MessageOptions& from) {
GOOGLE_DCHECK_NE(&from, this);
_extensions_.MergeFrom(from._extensions_);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
uninterpreted_option_.MergeFrom(from.uninterpreted_option_);
- if (from._has_bits_[0 / 32] & 15u) {
- if (from.has_message_set_wire_format()) {
- set_message_set_wire_format(from.message_set_wire_format());
+ cached_has_bits = from._has_bits_[0];
+ if (cached_has_bits & 15u) {
+ if (cached_has_bits & 0x00000001u) {
+ message_set_wire_format_ = from.message_set_wire_format_;
}
- if (from.has_no_standard_descriptor_accessor()) {
- set_no_standard_descriptor_accessor(from.no_standard_descriptor_accessor());
+ if (cached_has_bits & 0x00000002u) {
+ no_standard_descriptor_accessor_ = from.no_standard_descriptor_accessor_;
}
- if (from.has_deprecated()) {
- set_deprecated(from.deprecated());
+ if (cached_has_bits & 0x00000004u) {
+ deprecated_ = from.deprecated_;
}
- if (from.has_map_entry()) {
- set_map_entry(from.map_entry());
+ if (cached_has_bits & 0x00000008u) {
+ map_entry_ = from.map_entry_;
}
+ _has_bits_[0] |= cached_has_bits;
}
}
@@ -9750,158 +9385,46 @@ bool MessageOptions::IsInitialized() const {
void MessageOptions::Swap(MessageOptions* other) {
if (other == this) return;
+ if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ InternalSwap(other);
+ } else {
+ MessageOptions* temp = New(GetArenaNoVirtual());
+ temp->MergeFrom(*other);
+ other->CopyFrom(*this);
+ InternalSwap(temp);
+ if (GetArenaNoVirtual() == NULL) {
+ delete temp;
+ }
+ }
+}
+void MessageOptions::UnsafeArenaSwap(MessageOptions* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void MessageOptions::InternalSwap(MessageOptions* other) {
- uninterpreted_option_.UnsafeArenaSwap(&other->uninterpreted_option_);
- std::swap(message_set_wire_format_, other->message_set_wire_format_);
- std::swap(no_standard_descriptor_accessor_, other->no_standard_descriptor_accessor_);
- std::swap(deprecated_, other->deprecated_);
- std::swap(map_entry_, other->map_entry_);
- std::swap(_has_bits_[0], other->_has_bits_[0]);
+ using std::swap;
+ uninterpreted_option_.InternalSwap(&other->uninterpreted_option_);
+ swap(message_set_wire_format_, other->message_set_wire_format_);
+ swap(no_standard_descriptor_accessor_, other->no_standard_descriptor_accessor_);
+ swap(deprecated_, other->deprecated_);
+ swap(map_entry_, other->map_entry_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- std::swap(_cached_size_, other->_cached_size_);
+ swap(_cached_size_, other->_cached_size_);
_extensions_.Swap(&other->_extensions_);
}
::google::protobuf::Metadata MessageOptions::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[12];
-}
-
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// MessageOptions
-
-// optional bool message_set_wire_format = 1 [default = false];
-bool MessageOptions::has_message_set_wire_format() const {
- return (_has_bits_[0] & 0x00000001u) != 0;
-}
-void MessageOptions::set_has_message_set_wire_format() {
- _has_bits_[0] |= 0x00000001u;
-}
-void MessageOptions::clear_has_message_set_wire_format() {
- _has_bits_[0] &= ~0x00000001u;
-}
-void MessageOptions::clear_message_set_wire_format() {
- message_set_wire_format_ = false;
- clear_has_message_set_wire_format();
-}
-bool MessageOptions::message_set_wire_format() const {
- // @@protoc_insertion_point(field_get:google.protobuf.MessageOptions.message_set_wire_format)
- return message_set_wire_format_;
-}
-void MessageOptions::set_message_set_wire_format(bool value) {
- set_has_message_set_wire_format();
- message_set_wire_format_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.MessageOptions.message_set_wire_format)
-}
-
-// optional bool no_standard_descriptor_accessor = 2 [default = false];
-bool MessageOptions::has_no_standard_descriptor_accessor() const {
- return (_has_bits_[0] & 0x00000002u) != 0;
-}
-void MessageOptions::set_has_no_standard_descriptor_accessor() {
- _has_bits_[0] |= 0x00000002u;
-}
-void MessageOptions::clear_has_no_standard_descriptor_accessor() {
- _has_bits_[0] &= ~0x00000002u;
-}
-void MessageOptions::clear_no_standard_descriptor_accessor() {
- no_standard_descriptor_accessor_ = false;
- clear_has_no_standard_descriptor_accessor();
-}
-bool MessageOptions::no_standard_descriptor_accessor() const {
- // @@protoc_insertion_point(field_get:google.protobuf.MessageOptions.no_standard_descriptor_accessor)
- return no_standard_descriptor_accessor_;
-}
-void MessageOptions::set_no_standard_descriptor_accessor(bool value) {
- set_has_no_standard_descriptor_accessor();
- no_standard_descriptor_accessor_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.MessageOptions.no_standard_descriptor_accessor)
-}
-
-// optional bool deprecated = 3 [default = false];
-bool MessageOptions::has_deprecated() const {
- return (_has_bits_[0] & 0x00000004u) != 0;
-}
-void MessageOptions::set_has_deprecated() {
- _has_bits_[0] |= 0x00000004u;
-}
-void MessageOptions::clear_has_deprecated() {
- _has_bits_[0] &= ~0x00000004u;
-}
-void MessageOptions::clear_deprecated() {
- deprecated_ = false;
- clear_has_deprecated();
-}
-bool MessageOptions::deprecated() const {
- // @@protoc_insertion_point(field_get:google.protobuf.MessageOptions.deprecated)
- return deprecated_;
-}
-void MessageOptions::set_deprecated(bool value) {
- set_has_deprecated();
- deprecated_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.MessageOptions.deprecated)
-}
-
-// optional bool map_entry = 7;
-bool MessageOptions::has_map_entry() const {
- return (_has_bits_[0] & 0x00000008u) != 0;
-}
-void MessageOptions::set_has_map_entry() {
- _has_bits_[0] |= 0x00000008u;
-}
-void MessageOptions::clear_has_map_entry() {
- _has_bits_[0] &= ~0x00000008u;
-}
-void MessageOptions::clear_map_entry() {
- map_entry_ = false;
- clear_has_map_entry();
-}
-bool MessageOptions::map_entry() const {
- // @@protoc_insertion_point(field_get:google.protobuf.MessageOptions.map_entry)
- return map_entry_;
-}
-void MessageOptions::set_map_entry(bool value) {
- set_has_map_entry();
- map_entry_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.MessageOptions.map_entry)
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
}
-// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
-int MessageOptions::uninterpreted_option_size() const {
- return uninterpreted_option_.size();
-}
-void MessageOptions::clear_uninterpreted_option() {
- uninterpreted_option_.Clear();
-}
-const ::google::protobuf::UninterpretedOption& MessageOptions::uninterpreted_option(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.MessageOptions.uninterpreted_option)
- return uninterpreted_option_.Get(index);
-}
-::google::protobuf::UninterpretedOption* MessageOptions::mutable_uninterpreted_option(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.MessageOptions.uninterpreted_option)
- return uninterpreted_option_.Mutable(index);
-}
-::google::protobuf::UninterpretedOption* MessageOptions::add_uninterpreted_option() {
- // @@protoc_insertion_point(field_add:google.protobuf.MessageOptions.uninterpreted_option)
- return uninterpreted_option_.Add();
-}
-::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >*
-MessageOptions::mutable_uninterpreted_option() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.MessageOptions.uninterpreted_option)
- return &uninterpreted_option_;
-}
-const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
-MessageOptions::uninterpreted_option() const {
- // @@protoc_insertion_point(field_list:google.protobuf.MessageOptions.uninterpreted_option)
- return uninterpreted_option_;
-}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
+void FieldOptions::InitAsDefaultInstance() {
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int FieldOptions::kCtypeFieldNumber;
const int FieldOptions::kPackedFieldNumber;
@@ -9915,11 +9438,21 @@ const int FieldOptions::kUninterpretedOptionFieldNumber;
FieldOptions::FieldOptions()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldOptions();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.FieldOptions)
}
+FieldOptions::FieldOptions(::google::protobuf::Arena* arena)
+ : ::google::protobuf::Message(),
+ _extensions_(arena),
+ _internal_metadata_(arena),
+ uninterpreted_option_(arena) {
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldOptions();
+ SharedCtor();
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.FieldOptions)
+}
FieldOptions::FieldOptions(const FieldOptions& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
@@ -9929,15 +9462,16 @@ FieldOptions::FieldOptions(const FieldOptions& from)
_internal_metadata_.MergeFrom(from._internal_metadata_);
_extensions_.MergeFrom(from._extensions_);
::memcpy(&ctype_, &from.ctype_,
- reinterpret_cast<char*>(&weak_) -
- reinterpret_cast<char*>(&ctype_) + sizeof(weak_));
+ static_cast<size_t>(reinterpret_cast<char*>(&jstype_) -
+ reinterpret_cast<char*>(&ctype_)) + sizeof(jstype_));
// @@protoc_insertion_point(copy_constructor:google.protobuf.FieldOptions)
}
void FieldOptions::SharedCtor() {
_cached_size_ = 0;
- ::memset(&ctype_, 0, reinterpret_cast<char*>(&weak_) -
- reinterpret_cast<char*>(&ctype_) + sizeof(weak_));
+ ::memset(&ctype_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&jstype_) -
+ reinterpret_cast<char*>(&ctype_)) + sizeof(jstype_));
}
FieldOptions::~FieldOptions() {
@@ -9946,38 +9480,47 @@ FieldOptions::~FieldOptions() {
}
void FieldOptions::SharedDtor() {
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
}
+void FieldOptions::ArenaDtor(void* object) {
+ FieldOptions* _this = reinterpret_cast< FieldOptions* >(object);
+ (void)_this;
+}
+void FieldOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+}
void FieldOptions::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* FieldOptions::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[13].descriptor;
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const FieldOptions& FieldOptions::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldOptions();
return *internal_default_instance();
}
FieldOptions* FieldOptions::New(::google::protobuf::Arena* arena) const {
- FieldOptions* n = new FieldOptions;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
+ return ::google::protobuf::Arena::CreateMessage<FieldOptions>(arena);
}
void FieldOptions::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.FieldOptions)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
_extensions_.Clear();
uninterpreted_option_.Clear();
- if (_has_bits_[0 / 32] & 63u) {
- ::memset(&ctype_, 0, reinterpret_cast<char*>(&weak_) -
- reinterpret_cast<char*>(&ctype_) + sizeof(weak_));
+ cached_has_bits = _has_bits_[0];
+ if (cached_has_bits & 63u) {
+ ::memset(&ctype_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&jstype_) -
+ reinterpret_cast<char*>(&ctype_)) + sizeof(jstype_));
}
_has_bits_.Clear();
_internal_metadata_.Clear();
@@ -9995,7 +9538,8 @@ bool FieldOptions::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional .google.protobuf.FieldOptions.CType ctype = 1 [default = STRING];
case 1: {
- if (tag == 8u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
int value;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
@@ -10003,7 +9547,8 @@ bool FieldOptions::MergePartialFromCodedStream(
if (::google::protobuf::FieldOptions_CType_IsValid(value)) {
set_ctype(static_cast< ::google::protobuf::FieldOptions_CType >(value));
} else {
- mutable_unknown_fields()->AddVarint(1, value);
+ mutable_unknown_fields()->AddVarint(
+ 1, static_cast< ::google::protobuf::uint64>(value));
}
} else {
goto handle_unusual;
@@ -10013,7 +9558,8 @@ bool FieldOptions::MergePartialFromCodedStream(
// optional bool packed = 2;
case 2: {
- if (tag == 16u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
set_has_packed();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
@@ -10026,7 +9572,8 @@ bool FieldOptions::MergePartialFromCodedStream(
// optional bool deprecated = 3 [default = false];
case 3: {
- if (tag == 24u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) {
set_has_deprecated();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
@@ -10039,7 +9586,8 @@ bool FieldOptions::MergePartialFromCodedStream(
// optional bool lazy = 5 [default = false];
case 5: {
- if (tag == 40u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) {
set_has_lazy();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
@@ -10052,7 +9600,8 @@ bool FieldOptions::MergePartialFromCodedStream(
// optional .google.protobuf.FieldOptions.JSType jstype = 6 [default = JS_NORMAL];
case 6: {
- if (tag == 48u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(48u /* 48 & 0xFF */)) {
int value;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
@@ -10060,7 +9609,8 @@ bool FieldOptions::MergePartialFromCodedStream(
if (::google::protobuf::FieldOptions_JSType_IsValid(value)) {
set_jstype(static_cast< ::google::protobuf::FieldOptions_JSType >(value));
} else {
- mutable_unknown_fields()->AddVarint(6, value);
+ mutable_unknown_fields()->AddVarint(
+ 6, static_cast< ::google::protobuf::uint64>(value));
}
} else {
goto handle_unusual;
@@ -10070,7 +9620,8 @@ bool FieldOptions::MergePartialFromCodedStream(
// optional bool weak = 10 [default = false];
case 10: {
- if (tag == 80u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(80u /* 80 & 0xFF */)) {
set_has_weak();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
@@ -10083,31 +9634,28 @@ bool FieldOptions::MergePartialFromCodedStream(
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
case 999: {
- if (tag == 7994u) {
- DO_(input->IncrementRecursionDepth());
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
- input, add_uninterpreted_option()));
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(58u /* 7994 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_uninterpreted_option()));
} else {
goto handle_unusual;
}
- input->UnsafeDecrementRecursionDepth();
break;
}
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
if ((8000u <= tag)) {
- DO_(_extensions_.ParseField(tag, input, internal_default_instance(),
- mutable_unknown_fields()));
+ DO_(_extensions_.ParseField(tag, input,
+ internal_default_instance(),
+ _internal_metadata_.mutable_unknown_fields()));
continue;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
- input, tag, mutable_unknown_fields()));
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -10124,42 +9672,47 @@ failure:
void FieldOptions::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.FieldOptions)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional .google.protobuf.FieldOptions.CType ctype = 1 [default = STRING];
- if (has_ctype()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormatLite::WriteEnum(
1, this->ctype(), output);
}
// optional bool packed = 2;
- if (has_packed()) {
+ if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteBool(2, this->packed(), output);
}
// optional bool deprecated = 3 [default = false];
- if (has_deprecated()) {
+ if (cached_has_bits & 0x00000008u) {
::google::protobuf::internal::WireFormatLite::WriteBool(3, this->deprecated(), output);
}
// optional bool lazy = 5 [default = false];
- if (has_lazy()) {
+ if (cached_has_bits & 0x00000004u) {
::google::protobuf::internal::WireFormatLite::WriteBool(5, this->lazy(), output);
}
// optional .google.protobuf.FieldOptions.JSType jstype = 6 [default = JS_NORMAL];
- if (has_jstype()) {
+ if (cached_has_bits & 0x00000020u) {
::google::protobuf::internal::WireFormatLite::WriteEnum(
6, this->jstype(), output);
}
// optional bool weak = 10 [default = false];
- if (has_weak()) {
+ if (cached_has_bits & 0x00000010u) {
::google::protobuf::internal::WireFormatLite::WriteBool(10, this->weak(), output);
}
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
- for (unsigned int i = 0, n = this->uninterpreted_option_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->uninterpreted_option_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 999, this->uninterpreted_option(i), output);
+ 999, this->uninterpreted_option(static_cast<int>(i)), output);
}
// Extension range [1000, 536870912)
@@ -10168,7 +9721,7 @@ void FieldOptions::SerializeWithCachedSizes(
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- unknown_fields(), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.FieldOptions)
}
@@ -10177,52 +9730,57 @@ void FieldOptions::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.FieldOptions)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional .google.protobuf.FieldOptions.CType ctype = 1 [default = STRING];
- if (has_ctype()) {
+ if (cached_has_bits & 0x00000001u) {
target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray(
1, this->ctype(), target);
}
// optional bool packed = 2;
- if (has_packed()) {
+ if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(2, this->packed(), target);
}
// optional bool deprecated = 3 [default = false];
- if (has_deprecated()) {
+ if (cached_has_bits & 0x00000008u) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(3, this->deprecated(), target);
}
// optional bool lazy = 5 [default = false];
- if (has_lazy()) {
+ if (cached_has_bits & 0x00000004u) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(5, this->lazy(), target);
}
// optional .google.protobuf.FieldOptions.JSType jstype = 6 [default = JS_NORMAL];
- if (has_jstype()) {
+ if (cached_has_bits & 0x00000020u) {
target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray(
6, this->jstype(), target);
}
// optional bool weak = 10 [default = false];
- if (has_weak()) {
+ if (cached_has_bits & 0x00000010u) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(10, this->weak(), target);
}
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
- for (unsigned int i = 0, n = this->uninterpreted_option_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->uninterpreted_option_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 999, this->uninterpreted_option(i), false, target);
+ InternalWriteMessageToArray(
+ 999, this->uninterpreted_option(static_cast<int>(i)), deterministic, target);
}
// Extension range [1000, 536870912)
target = _extensions_.InternalSerializeWithCachedSizesToArray(
- 1000, 536870912, false, target);
+ 1000, 536870912, deterministic, target);
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- unknown_fields(), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.FieldOptions)
return target;
@@ -10237,16 +9795,16 @@ size_t FieldOptions::ByteSizeLong() const {
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- unknown_fields());
+ _internal_metadata_.unknown_fields());
}
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
{
- unsigned int count = this->uninterpreted_option_size();
+ unsigned int count = static_cast<unsigned int>(this->uninterpreted_option_size());
total_size += 2UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->uninterpreted_option(i));
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->uninterpreted_option(static_cast<int>(i)));
}
}
@@ -10257,12 +9815,6 @@ size_t FieldOptions::ByteSizeLong() const {
::google::protobuf::internal::WireFormatLite::EnumSize(this->ctype());
}
- // optional .google.protobuf.FieldOptions.JSType jstype = 6 [default = JS_NORMAL];
- if (has_jstype()) {
- total_size += 1 +
- ::google::protobuf::internal::WireFormatLite::EnumSize(this->jstype());
- }
-
// optional bool packed = 2;
if (has_packed()) {
total_size += 1 + 1;
@@ -10283,6 +9835,12 @@ size_t FieldOptions::ByteSizeLong() const {
total_size += 1 + 1;
}
+ // optional .google.protobuf.FieldOptions.JSType jstype = 6 [default = JS_NORMAL];
+ if (has_jstype()) {
+ total_size += 1 +
+ ::google::protobuf::internal::WireFormatLite::EnumSize(this->jstype());
+ }
+
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
@@ -10311,26 +9869,31 @@ void FieldOptions::MergeFrom(const FieldOptions& from) {
GOOGLE_DCHECK_NE(&from, this);
_extensions_.MergeFrom(from._extensions_);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
uninterpreted_option_.MergeFrom(from.uninterpreted_option_);
- if (from._has_bits_[0 / 32] & 63u) {
- if (from.has_ctype()) {
- set_ctype(from.ctype());
+ cached_has_bits = from._has_bits_[0];
+ if (cached_has_bits & 63u) {
+ if (cached_has_bits & 0x00000001u) {
+ ctype_ = from.ctype_;
}
- if (from.has_jstype()) {
- set_jstype(from.jstype());
+ if (cached_has_bits & 0x00000002u) {
+ packed_ = from.packed_;
}
- if (from.has_packed()) {
- set_packed(from.packed());
+ if (cached_has_bits & 0x00000004u) {
+ lazy_ = from.lazy_;
}
- if (from.has_lazy()) {
- set_lazy(from.lazy());
+ if (cached_has_bits & 0x00000008u) {
+ deprecated_ = from.deprecated_;
}
- if (from.has_deprecated()) {
- set_deprecated(from.deprecated());
+ if (cached_has_bits & 0x00000010u) {
+ weak_ = from.weak_;
}
- if (from.has_weak()) {
- set_weak(from.weak());
+ if (cached_has_bits & 0x00000020u) {
+ jstype_ = from.jstype_;
}
+ _has_bits_[0] |= cached_has_bits;
}
}
@@ -10359,210 +9922,48 @@ bool FieldOptions::IsInitialized() const {
void FieldOptions::Swap(FieldOptions* other) {
if (other == this) return;
+ if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ InternalSwap(other);
+ } else {
+ FieldOptions* temp = New(GetArenaNoVirtual());
+ temp->MergeFrom(*other);
+ other->CopyFrom(*this);
+ InternalSwap(temp);
+ if (GetArenaNoVirtual() == NULL) {
+ delete temp;
+ }
+ }
+}
+void FieldOptions::UnsafeArenaSwap(FieldOptions* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void FieldOptions::InternalSwap(FieldOptions* other) {
- uninterpreted_option_.UnsafeArenaSwap(&other->uninterpreted_option_);
- std::swap(ctype_, other->ctype_);
- std::swap(jstype_, other->jstype_);
- std::swap(packed_, other->packed_);
- std::swap(lazy_, other->lazy_);
- std::swap(deprecated_, other->deprecated_);
- std::swap(weak_, other->weak_);
- std::swap(_has_bits_[0], other->_has_bits_[0]);
+ using std::swap;
+ uninterpreted_option_.InternalSwap(&other->uninterpreted_option_);
+ swap(ctype_, other->ctype_);
+ swap(packed_, other->packed_);
+ swap(lazy_, other->lazy_);
+ swap(deprecated_, other->deprecated_);
+ swap(weak_, other->weak_);
+ swap(jstype_, other->jstype_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- std::swap(_cached_size_, other->_cached_size_);
+ swap(_cached_size_, other->_cached_size_);
_extensions_.Swap(&other->_extensions_);
}
::google::protobuf::Metadata FieldOptions::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[13];
-}
-
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// FieldOptions
-
-// optional .google.protobuf.FieldOptions.CType ctype = 1 [default = STRING];
-bool FieldOptions::has_ctype() const {
- return (_has_bits_[0] & 0x00000001u) != 0;
-}
-void FieldOptions::set_has_ctype() {
- _has_bits_[0] |= 0x00000001u;
-}
-void FieldOptions::clear_has_ctype() {
- _has_bits_[0] &= ~0x00000001u;
-}
-void FieldOptions::clear_ctype() {
- ctype_ = 0;
- clear_has_ctype();
-}
-::google::protobuf::FieldOptions_CType FieldOptions::ctype() const {
- // @@protoc_insertion_point(field_get:google.protobuf.FieldOptions.ctype)
- return static_cast< ::google::protobuf::FieldOptions_CType >(ctype_);
-}
-void FieldOptions::set_ctype(::google::protobuf::FieldOptions_CType value) {
- assert(::google::protobuf::FieldOptions_CType_IsValid(value));
- set_has_ctype();
- ctype_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.FieldOptions.ctype)
-}
-
-// optional bool packed = 2;
-bool FieldOptions::has_packed() const {
- return (_has_bits_[0] & 0x00000004u) != 0;
-}
-void FieldOptions::set_has_packed() {
- _has_bits_[0] |= 0x00000004u;
-}
-void FieldOptions::clear_has_packed() {
- _has_bits_[0] &= ~0x00000004u;
-}
-void FieldOptions::clear_packed() {
- packed_ = false;
- clear_has_packed();
-}
-bool FieldOptions::packed() const {
- // @@protoc_insertion_point(field_get:google.protobuf.FieldOptions.packed)
- return packed_;
-}
-void FieldOptions::set_packed(bool value) {
- set_has_packed();
- packed_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.FieldOptions.packed)
-}
-
-// optional .google.protobuf.FieldOptions.JSType jstype = 6 [default = JS_NORMAL];
-bool FieldOptions::has_jstype() const {
- return (_has_bits_[0] & 0x00000002u) != 0;
-}
-void FieldOptions::set_has_jstype() {
- _has_bits_[0] |= 0x00000002u;
-}
-void FieldOptions::clear_has_jstype() {
- _has_bits_[0] &= ~0x00000002u;
-}
-void FieldOptions::clear_jstype() {
- jstype_ = 0;
- clear_has_jstype();
-}
-::google::protobuf::FieldOptions_JSType FieldOptions::jstype() const {
- // @@protoc_insertion_point(field_get:google.protobuf.FieldOptions.jstype)
- return static_cast< ::google::protobuf::FieldOptions_JSType >(jstype_);
-}
-void FieldOptions::set_jstype(::google::protobuf::FieldOptions_JSType value) {
- assert(::google::protobuf::FieldOptions_JSType_IsValid(value));
- set_has_jstype();
- jstype_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.FieldOptions.jstype)
-}
-
-// optional bool lazy = 5 [default = false];
-bool FieldOptions::has_lazy() const {
- return (_has_bits_[0] & 0x00000008u) != 0;
-}
-void FieldOptions::set_has_lazy() {
- _has_bits_[0] |= 0x00000008u;
-}
-void FieldOptions::clear_has_lazy() {
- _has_bits_[0] &= ~0x00000008u;
-}
-void FieldOptions::clear_lazy() {
- lazy_ = false;
- clear_has_lazy();
-}
-bool FieldOptions::lazy() const {
- // @@protoc_insertion_point(field_get:google.protobuf.FieldOptions.lazy)
- return lazy_;
-}
-void FieldOptions::set_lazy(bool value) {
- set_has_lazy();
- lazy_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.FieldOptions.lazy)
-}
-
-// optional bool deprecated = 3 [default = false];
-bool FieldOptions::has_deprecated() const {
- return (_has_bits_[0] & 0x00000010u) != 0;
-}
-void FieldOptions::set_has_deprecated() {
- _has_bits_[0] |= 0x00000010u;
-}
-void FieldOptions::clear_has_deprecated() {
- _has_bits_[0] &= ~0x00000010u;
-}
-void FieldOptions::clear_deprecated() {
- deprecated_ = false;
- clear_has_deprecated();
-}
-bool FieldOptions::deprecated() const {
- // @@protoc_insertion_point(field_get:google.protobuf.FieldOptions.deprecated)
- return deprecated_;
-}
-void FieldOptions::set_deprecated(bool value) {
- set_has_deprecated();
- deprecated_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.FieldOptions.deprecated)
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
}
-// optional bool weak = 10 [default = false];
-bool FieldOptions::has_weak() const {
- return (_has_bits_[0] & 0x00000020u) != 0;
-}
-void FieldOptions::set_has_weak() {
- _has_bits_[0] |= 0x00000020u;
-}
-void FieldOptions::clear_has_weak() {
- _has_bits_[0] &= ~0x00000020u;
-}
-void FieldOptions::clear_weak() {
- weak_ = false;
- clear_has_weak();
-}
-bool FieldOptions::weak() const {
- // @@protoc_insertion_point(field_get:google.protobuf.FieldOptions.weak)
- return weak_;
-}
-void FieldOptions::set_weak(bool value) {
- set_has_weak();
- weak_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.FieldOptions.weak)
-}
-
-// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
-int FieldOptions::uninterpreted_option_size() const {
- return uninterpreted_option_.size();
-}
-void FieldOptions::clear_uninterpreted_option() {
- uninterpreted_option_.Clear();
-}
-const ::google::protobuf::UninterpretedOption& FieldOptions::uninterpreted_option(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.FieldOptions.uninterpreted_option)
- return uninterpreted_option_.Get(index);
-}
-::google::protobuf::UninterpretedOption* FieldOptions::mutable_uninterpreted_option(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.FieldOptions.uninterpreted_option)
- return uninterpreted_option_.Mutable(index);
-}
-::google::protobuf::UninterpretedOption* FieldOptions::add_uninterpreted_option() {
- // @@protoc_insertion_point(field_add:google.protobuf.FieldOptions.uninterpreted_option)
- return uninterpreted_option_.Add();
-}
-::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >*
-FieldOptions::mutable_uninterpreted_option() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.FieldOptions.uninterpreted_option)
- return &uninterpreted_option_;
-}
-const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
-FieldOptions::uninterpreted_option() const {
- // @@protoc_insertion_point(field_list:google.protobuf.FieldOptions.uninterpreted_option)
- return uninterpreted_option_;
-}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
+void OneofOptions::InitAsDefaultInstance() {
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int OneofOptions::kUninterpretedOptionFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
@@ -10570,11 +9971,21 @@ const int OneofOptions::kUninterpretedOptionFieldNumber;
OneofOptions::OneofOptions()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofOptions();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.OneofOptions)
}
+OneofOptions::OneofOptions(::google::protobuf::Arena* arena)
+ : ::google::protobuf::Message(),
+ _extensions_(arena),
+ _internal_metadata_(arena),
+ uninterpreted_option_(arena) {
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofOptions();
+ SharedCtor();
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.OneofOptions)
+}
OneofOptions::OneofOptions(const OneofOptions& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
@@ -10596,33 +10007,40 @@ OneofOptions::~OneofOptions() {
}
void OneofOptions::SharedDtor() {
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
}
+void OneofOptions::ArenaDtor(void* object) {
+ OneofOptions* _this = reinterpret_cast< OneofOptions* >(object);
+ (void)_this;
+}
+void OneofOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+}
void OneofOptions::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* OneofOptions::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[14].descriptor;
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const OneofOptions& OneofOptions::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofOptions();
return *internal_default_instance();
}
OneofOptions* OneofOptions::New(::google::protobuf::Arena* arena) const {
- OneofOptions* n = new OneofOptions;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
+ return ::google::protobuf::Arena::CreateMessage<OneofOptions>(arena);
}
void OneofOptions::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.OneofOptions)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
_extensions_.Clear();
uninterpreted_option_.Clear();
_has_bits_.Clear();
@@ -10641,31 +10059,28 @@ bool OneofOptions::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
case 999: {
- if (tag == 7994u) {
- DO_(input->IncrementRecursionDepth());
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
- input, add_uninterpreted_option()));
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(58u /* 7994 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_uninterpreted_option()));
} else {
goto handle_unusual;
}
- input->UnsafeDecrementRecursionDepth();
break;
}
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
if ((8000u <= tag)) {
- DO_(_extensions_.ParseField(tag, input, internal_default_instance(),
- mutable_unknown_fields()));
+ DO_(_extensions_.ParseField(tag, input,
+ internal_default_instance(),
+ _internal_metadata_.mutable_unknown_fields()));
continue;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
- input, tag, mutable_unknown_fields()));
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -10682,10 +10097,14 @@ failure:
void OneofOptions::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.OneofOptions)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
- for (unsigned int i = 0, n = this->uninterpreted_option_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->uninterpreted_option_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 999, this->uninterpreted_option(i), output);
+ 999, this->uninterpreted_option(static_cast<int>(i)), output);
}
// Extension range [1000, 536870912)
@@ -10694,7 +10113,7 @@ void OneofOptions::SerializeWithCachedSizes(
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- unknown_fields(), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.OneofOptions)
}
@@ -10703,20 +10122,24 @@ void OneofOptions::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.OneofOptions)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
- for (unsigned int i = 0, n = this->uninterpreted_option_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->uninterpreted_option_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 999, this->uninterpreted_option(i), false, target);
+ InternalWriteMessageToArray(
+ 999, this->uninterpreted_option(static_cast<int>(i)), deterministic, target);
}
// Extension range [1000, 536870912)
target = _extensions_.InternalSerializeWithCachedSizesToArray(
- 1000, 536870912, false, target);
+ 1000, 536870912, deterministic, target);
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- unknown_fields(), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.OneofOptions)
return target;
@@ -10731,16 +10154,16 @@ size_t OneofOptions::ByteSizeLong() const {
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- unknown_fields());
+ _internal_metadata_.unknown_fields());
}
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
{
- unsigned int count = this->uninterpreted_option_size();
+ unsigned int count = static_cast<unsigned int>(this->uninterpreted_option_size());
total_size += 2UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->uninterpreted_option(i));
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->uninterpreted_option(static_cast<int>(i)));
}
}
@@ -10771,6 +10194,9 @@ void OneofOptions::MergeFrom(const OneofOptions& from) {
GOOGLE_DCHECK_NE(&from, this);
_extensions_.MergeFrom(from._extensions_);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
uninterpreted_option_.MergeFrom(from.uninterpreted_option_);
}
@@ -10799,58 +10225,42 @@ bool OneofOptions::IsInitialized() const {
void OneofOptions::Swap(OneofOptions* other) {
if (other == this) return;
+ if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ InternalSwap(other);
+ } else {
+ OneofOptions* temp = New(GetArenaNoVirtual());
+ temp->MergeFrom(*other);
+ other->CopyFrom(*this);
+ InternalSwap(temp);
+ if (GetArenaNoVirtual() == NULL) {
+ delete temp;
+ }
+ }
+}
+void OneofOptions::UnsafeArenaSwap(OneofOptions* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void OneofOptions::InternalSwap(OneofOptions* other) {
- uninterpreted_option_.UnsafeArenaSwap(&other->uninterpreted_option_);
- std::swap(_has_bits_[0], other->_has_bits_[0]);
+ using std::swap;
+ uninterpreted_option_.InternalSwap(&other->uninterpreted_option_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- std::swap(_cached_size_, other->_cached_size_);
+ swap(_cached_size_, other->_cached_size_);
_extensions_.Swap(&other->_extensions_);
}
::google::protobuf::Metadata OneofOptions::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[14];
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// OneofOptions
-
-// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
-int OneofOptions::uninterpreted_option_size() const {
- return uninterpreted_option_.size();
-}
-void OneofOptions::clear_uninterpreted_option() {
- uninterpreted_option_.Clear();
-}
-const ::google::protobuf::UninterpretedOption& OneofOptions::uninterpreted_option(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.OneofOptions.uninterpreted_option)
- return uninterpreted_option_.Get(index);
-}
-::google::protobuf::UninterpretedOption* OneofOptions::mutable_uninterpreted_option(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.OneofOptions.uninterpreted_option)
- return uninterpreted_option_.Mutable(index);
-}
-::google::protobuf::UninterpretedOption* OneofOptions::add_uninterpreted_option() {
- // @@protoc_insertion_point(field_add:google.protobuf.OneofOptions.uninterpreted_option)
- return uninterpreted_option_.Add();
-}
-::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >*
-OneofOptions::mutable_uninterpreted_option() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.OneofOptions.uninterpreted_option)
- return &uninterpreted_option_;
-}
-const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
-OneofOptions::uninterpreted_option() const {
- // @@protoc_insertion_point(field_list:google.protobuf.OneofOptions.uninterpreted_option)
- return uninterpreted_option_;
-}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
+void EnumOptions::InitAsDefaultInstance() {
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int EnumOptions::kAllowAliasFieldNumber;
const int EnumOptions::kDeprecatedFieldNumber;
@@ -10860,11 +10270,21 @@ const int EnumOptions::kUninterpretedOptionFieldNumber;
EnumOptions::EnumOptions()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumOptions();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.EnumOptions)
}
+EnumOptions::EnumOptions(::google::protobuf::Arena* arena)
+ : ::google::protobuf::Message(),
+ _extensions_(arena),
+ _internal_metadata_(arena),
+ uninterpreted_option_(arena) {
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumOptions();
+ SharedCtor();
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.EnumOptions)
+}
EnumOptions::EnumOptions(const EnumOptions& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
@@ -10874,15 +10294,16 @@ EnumOptions::EnumOptions(const EnumOptions& from)
_internal_metadata_.MergeFrom(from._internal_metadata_);
_extensions_.MergeFrom(from._extensions_);
::memcpy(&allow_alias_, &from.allow_alias_,
- reinterpret_cast<char*>(&deprecated_) -
- reinterpret_cast<char*>(&allow_alias_) + sizeof(deprecated_));
+ static_cast<size_t>(reinterpret_cast<char*>(&deprecated_) -
+ reinterpret_cast<char*>(&allow_alias_)) + sizeof(deprecated_));
// @@protoc_insertion_point(copy_constructor:google.protobuf.EnumOptions)
}
void EnumOptions::SharedCtor() {
_cached_size_ = 0;
- ::memset(&allow_alias_, 0, reinterpret_cast<char*>(&deprecated_) -
- reinterpret_cast<char*>(&allow_alias_) + sizeof(deprecated_));
+ ::memset(&allow_alias_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&deprecated_) -
+ reinterpret_cast<char*>(&allow_alias_)) + sizeof(deprecated_));
}
EnumOptions::~EnumOptions() {
@@ -10891,39 +10312,45 @@ EnumOptions::~EnumOptions() {
}
void EnumOptions::SharedDtor() {
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
}
+void EnumOptions::ArenaDtor(void* object) {
+ EnumOptions* _this = reinterpret_cast< EnumOptions* >(object);
+ (void)_this;
+}
+void EnumOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+}
void EnumOptions::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* EnumOptions::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[15].descriptor;
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const EnumOptions& EnumOptions::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumOptions();
return *internal_default_instance();
}
EnumOptions* EnumOptions::New(::google::protobuf::Arena* arena) const {
- EnumOptions* n = new EnumOptions;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
+ return ::google::protobuf::Arena::CreateMessage<EnumOptions>(arena);
}
void EnumOptions::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.EnumOptions)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
_extensions_.Clear();
uninterpreted_option_.Clear();
- if (_has_bits_[0 / 32] & 3u) {
- ::memset(&allow_alias_, 0, reinterpret_cast<char*>(&deprecated_) -
- reinterpret_cast<char*>(&allow_alias_) + sizeof(deprecated_));
- }
+ ::memset(&allow_alias_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&deprecated_) -
+ reinterpret_cast<char*>(&allow_alias_)) + sizeof(deprecated_));
_has_bits_.Clear();
_internal_metadata_.Clear();
}
@@ -10940,7 +10367,8 @@ bool EnumOptions::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional bool allow_alias = 2;
case 2: {
- if (tag == 16u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
set_has_allow_alias();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
@@ -10953,7 +10381,8 @@ bool EnumOptions::MergePartialFromCodedStream(
// optional bool deprecated = 3 [default = false];
case 3: {
- if (tag == 24u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) {
set_has_deprecated();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
@@ -10966,31 +10395,28 @@ bool EnumOptions::MergePartialFromCodedStream(
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
case 999: {
- if (tag == 7994u) {
- DO_(input->IncrementRecursionDepth());
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
- input, add_uninterpreted_option()));
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(58u /* 7994 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_uninterpreted_option()));
} else {
goto handle_unusual;
}
- input->UnsafeDecrementRecursionDepth();
break;
}
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
if ((8000u <= tag)) {
- DO_(_extensions_.ParseField(tag, input, internal_default_instance(),
- mutable_unknown_fields()));
+ DO_(_extensions_.ParseField(tag, input,
+ internal_default_instance(),
+ _internal_metadata_.mutable_unknown_fields()));
continue;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
- input, tag, mutable_unknown_fields()));
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -11007,20 +10433,25 @@ failure:
void EnumOptions::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.EnumOptions)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional bool allow_alias = 2;
- if (has_allow_alias()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormatLite::WriteBool(2, this->allow_alias(), output);
}
// optional bool deprecated = 3 [default = false];
- if (has_deprecated()) {
+ if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteBool(3, this->deprecated(), output);
}
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
- for (unsigned int i = 0, n = this->uninterpreted_option_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->uninterpreted_option_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 999, this->uninterpreted_option(i), output);
+ 999, this->uninterpreted_option(static_cast<int>(i)), output);
}
// Extension range [1000, 536870912)
@@ -11029,7 +10460,7 @@ void EnumOptions::SerializeWithCachedSizes(
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- unknown_fields(), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.EnumOptions)
}
@@ -11038,30 +10469,35 @@ void EnumOptions::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.EnumOptions)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional bool allow_alias = 2;
- if (has_allow_alias()) {
+ if (cached_has_bits & 0x00000001u) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(2, this->allow_alias(), target);
}
// optional bool deprecated = 3 [default = false];
- if (has_deprecated()) {
+ if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(3, this->deprecated(), target);
}
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
- for (unsigned int i = 0, n = this->uninterpreted_option_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->uninterpreted_option_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 999, this->uninterpreted_option(i), false, target);
+ InternalWriteMessageToArray(
+ 999, this->uninterpreted_option(static_cast<int>(i)), deterministic, target);
}
// Extension range [1000, 536870912)
target = _extensions_.InternalSerializeWithCachedSizesToArray(
- 1000, 536870912, false, target);
+ 1000, 536870912, deterministic, target);
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- unknown_fields(), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.EnumOptions)
return target;
@@ -11076,16 +10512,16 @@ size_t EnumOptions::ByteSizeLong() const {
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- unknown_fields());
+ _internal_metadata_.unknown_fields());
}
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
{
- unsigned int count = this->uninterpreted_option_size();
+ unsigned int count = static_cast<unsigned int>(this->uninterpreted_option_size());
total_size += 2UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->uninterpreted_option(i));
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->uninterpreted_option(static_cast<int>(i)));
}
}
@@ -11128,14 +10564,19 @@ void EnumOptions::MergeFrom(const EnumOptions& from) {
GOOGLE_DCHECK_NE(&from, this);
_extensions_.MergeFrom(from._extensions_);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
uninterpreted_option_.MergeFrom(from.uninterpreted_option_);
- if (from._has_bits_[0 / 32] & 3u) {
- if (from.has_allow_alias()) {
- set_allow_alias(from.allow_alias());
+ cached_has_bits = from._has_bits_[0];
+ if (cached_has_bits & 3u) {
+ if (cached_has_bits & 0x00000001u) {
+ allow_alias_ = from.allow_alias_;
}
- if (from.has_deprecated()) {
- set_deprecated(from.deprecated());
+ if (cached_has_bits & 0x00000002u) {
+ deprecated_ = from.deprecated_;
}
+ _has_bits_[0] |= cached_has_bits;
}
}
@@ -11164,108 +10605,44 @@ bool EnumOptions::IsInitialized() const {
void EnumOptions::Swap(EnumOptions* other) {
if (other == this) return;
+ if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ InternalSwap(other);
+ } else {
+ EnumOptions* temp = New(GetArenaNoVirtual());
+ temp->MergeFrom(*other);
+ other->CopyFrom(*this);
+ InternalSwap(temp);
+ if (GetArenaNoVirtual() == NULL) {
+ delete temp;
+ }
+ }
+}
+void EnumOptions::UnsafeArenaSwap(EnumOptions* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void EnumOptions::InternalSwap(EnumOptions* other) {
- uninterpreted_option_.UnsafeArenaSwap(&other->uninterpreted_option_);
- std::swap(allow_alias_, other->allow_alias_);
- std::swap(deprecated_, other->deprecated_);
- std::swap(_has_bits_[0], other->_has_bits_[0]);
+ using std::swap;
+ uninterpreted_option_.InternalSwap(&other->uninterpreted_option_);
+ swap(allow_alias_, other->allow_alias_);
+ swap(deprecated_, other->deprecated_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- std::swap(_cached_size_, other->_cached_size_);
+ swap(_cached_size_, other->_cached_size_);
_extensions_.Swap(&other->_extensions_);
}
::google::protobuf::Metadata EnumOptions::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[15];
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// EnumOptions
-
-// optional bool allow_alias = 2;
-bool EnumOptions::has_allow_alias() const {
- return (_has_bits_[0] & 0x00000001u) != 0;
-}
-void EnumOptions::set_has_allow_alias() {
- _has_bits_[0] |= 0x00000001u;
-}
-void EnumOptions::clear_has_allow_alias() {
- _has_bits_[0] &= ~0x00000001u;
-}
-void EnumOptions::clear_allow_alias() {
- allow_alias_ = false;
- clear_has_allow_alias();
-}
-bool EnumOptions::allow_alias() const {
- // @@protoc_insertion_point(field_get:google.protobuf.EnumOptions.allow_alias)
- return allow_alias_;
-}
-void EnumOptions::set_allow_alias(bool value) {
- set_has_allow_alias();
- allow_alias_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.EnumOptions.allow_alias)
-}
-
-// optional bool deprecated = 3 [default = false];
-bool EnumOptions::has_deprecated() const {
- return (_has_bits_[0] & 0x00000002u) != 0;
-}
-void EnumOptions::set_has_deprecated() {
- _has_bits_[0] |= 0x00000002u;
-}
-void EnumOptions::clear_has_deprecated() {
- _has_bits_[0] &= ~0x00000002u;
-}
-void EnumOptions::clear_deprecated() {
- deprecated_ = false;
- clear_has_deprecated();
-}
-bool EnumOptions::deprecated() const {
- // @@protoc_insertion_point(field_get:google.protobuf.EnumOptions.deprecated)
- return deprecated_;
-}
-void EnumOptions::set_deprecated(bool value) {
- set_has_deprecated();
- deprecated_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.EnumOptions.deprecated)
-}
-
-// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
-int EnumOptions::uninterpreted_option_size() const {
- return uninterpreted_option_.size();
-}
-void EnumOptions::clear_uninterpreted_option() {
- uninterpreted_option_.Clear();
-}
-const ::google::protobuf::UninterpretedOption& EnumOptions::uninterpreted_option(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.EnumOptions.uninterpreted_option)
- return uninterpreted_option_.Get(index);
-}
-::google::protobuf::UninterpretedOption* EnumOptions::mutable_uninterpreted_option(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.EnumOptions.uninterpreted_option)
- return uninterpreted_option_.Mutable(index);
-}
-::google::protobuf::UninterpretedOption* EnumOptions::add_uninterpreted_option() {
- // @@protoc_insertion_point(field_add:google.protobuf.EnumOptions.uninterpreted_option)
- return uninterpreted_option_.Add();
-}
-::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >*
-EnumOptions::mutable_uninterpreted_option() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.EnumOptions.uninterpreted_option)
- return &uninterpreted_option_;
-}
-const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
-EnumOptions::uninterpreted_option() const {
- // @@protoc_insertion_point(field_list:google.protobuf.EnumOptions.uninterpreted_option)
- return uninterpreted_option_;
-}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
+void EnumValueOptions::InitAsDefaultInstance() {
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int EnumValueOptions::kDeprecatedFieldNumber;
const int EnumValueOptions::kUninterpretedOptionFieldNumber;
@@ -11274,11 +10651,21 @@ const int EnumValueOptions::kUninterpretedOptionFieldNumber;
EnumValueOptions::EnumValueOptions()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueOptions();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.EnumValueOptions)
}
+EnumValueOptions::EnumValueOptions(::google::protobuf::Arena* arena)
+ : ::google::protobuf::Message(),
+ _extensions_(arena),
+ _internal_metadata_(arena),
+ uninterpreted_option_(arena) {
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueOptions();
+ SharedCtor();
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.EnumValueOptions)
+}
EnumValueOptions::EnumValueOptions(const EnumValueOptions& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
@@ -11302,33 +10689,40 @@ EnumValueOptions::~EnumValueOptions() {
}
void EnumValueOptions::SharedDtor() {
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
}
+void EnumValueOptions::ArenaDtor(void* object) {
+ EnumValueOptions* _this = reinterpret_cast< EnumValueOptions* >(object);
+ (void)_this;
+}
+void EnumValueOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+}
void EnumValueOptions::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* EnumValueOptions::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[16].descriptor;
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const EnumValueOptions& EnumValueOptions::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueOptions();
return *internal_default_instance();
}
EnumValueOptions* EnumValueOptions::New(::google::protobuf::Arena* arena) const {
- EnumValueOptions* n = new EnumValueOptions;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
+ return ::google::protobuf::Arena::CreateMessage<EnumValueOptions>(arena);
}
void EnumValueOptions::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.EnumValueOptions)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
_extensions_.Clear();
uninterpreted_option_.Clear();
deprecated_ = false;
@@ -11348,7 +10742,8 @@ bool EnumValueOptions::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional bool deprecated = 1 [default = false];
case 1: {
- if (tag == 8u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
set_has_deprecated();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
@@ -11361,31 +10756,28 @@ bool EnumValueOptions::MergePartialFromCodedStream(
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
case 999: {
- if (tag == 7994u) {
- DO_(input->IncrementRecursionDepth());
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
- input, add_uninterpreted_option()));
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(58u /* 7994 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_uninterpreted_option()));
} else {
goto handle_unusual;
}
- input->UnsafeDecrementRecursionDepth();
break;
}
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
if ((8000u <= tag)) {
- DO_(_extensions_.ParseField(tag, input, internal_default_instance(),
- mutable_unknown_fields()));
+ DO_(_extensions_.ParseField(tag, input,
+ internal_default_instance(),
+ _internal_metadata_.mutable_unknown_fields()));
continue;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
- input, tag, mutable_unknown_fields()));
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -11402,15 +10794,20 @@ failure:
void EnumValueOptions::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.EnumValueOptions)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional bool deprecated = 1 [default = false];
- if (has_deprecated()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormatLite::WriteBool(1, this->deprecated(), output);
}
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
- for (unsigned int i = 0, n = this->uninterpreted_option_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->uninterpreted_option_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 999, this->uninterpreted_option(i), output);
+ 999, this->uninterpreted_option(static_cast<int>(i)), output);
}
// Extension range [1000, 536870912)
@@ -11419,7 +10816,7 @@ void EnumValueOptions::SerializeWithCachedSizes(
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- unknown_fields(), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.EnumValueOptions)
}
@@ -11428,25 +10825,30 @@ void EnumValueOptions::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.EnumValueOptions)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional bool deprecated = 1 [default = false];
- if (has_deprecated()) {
+ if (cached_has_bits & 0x00000001u) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(1, this->deprecated(), target);
}
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
- for (unsigned int i = 0, n = this->uninterpreted_option_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->uninterpreted_option_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 999, this->uninterpreted_option(i), false, target);
+ InternalWriteMessageToArray(
+ 999, this->uninterpreted_option(static_cast<int>(i)), deterministic, target);
}
// Extension range [1000, 536870912)
target = _extensions_.InternalSerializeWithCachedSizesToArray(
- 1000, 536870912, false, target);
+ 1000, 536870912, deterministic, target);
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- unknown_fields(), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.EnumValueOptions)
return target;
@@ -11461,16 +10863,16 @@ size_t EnumValueOptions::ByteSizeLong() const {
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- unknown_fields());
+ _internal_metadata_.unknown_fields());
}
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
{
- unsigned int count = this->uninterpreted_option_size();
+ unsigned int count = static_cast<unsigned int>(this->uninterpreted_option_size());
total_size += 2UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->uninterpreted_option(i));
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->uninterpreted_option(static_cast<int>(i)));
}
}
@@ -11506,6 +10908,9 @@ void EnumValueOptions::MergeFrom(const EnumValueOptions& from) {
GOOGLE_DCHECK_NE(&from, this);
_extensions_.MergeFrom(from._extensions_);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
uninterpreted_option_.MergeFrom(from.uninterpreted_option_);
if (from.has_deprecated()) {
set_deprecated(from.deprecated());
@@ -11537,83 +10942,43 @@ bool EnumValueOptions::IsInitialized() const {
void EnumValueOptions::Swap(EnumValueOptions* other) {
if (other == this) return;
+ if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ InternalSwap(other);
+ } else {
+ EnumValueOptions* temp = New(GetArenaNoVirtual());
+ temp->MergeFrom(*other);
+ other->CopyFrom(*this);
+ InternalSwap(temp);
+ if (GetArenaNoVirtual() == NULL) {
+ delete temp;
+ }
+ }
+}
+void EnumValueOptions::UnsafeArenaSwap(EnumValueOptions* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void EnumValueOptions::InternalSwap(EnumValueOptions* other) {
- uninterpreted_option_.UnsafeArenaSwap(&other->uninterpreted_option_);
- std::swap(deprecated_, other->deprecated_);
- std::swap(_has_bits_[0], other->_has_bits_[0]);
+ using std::swap;
+ uninterpreted_option_.InternalSwap(&other->uninterpreted_option_);
+ swap(deprecated_, other->deprecated_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- std::swap(_cached_size_, other->_cached_size_);
+ swap(_cached_size_, other->_cached_size_);
_extensions_.Swap(&other->_extensions_);
}
::google::protobuf::Metadata EnumValueOptions::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[16];
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// EnumValueOptions
-
-// optional bool deprecated = 1 [default = false];
-bool EnumValueOptions::has_deprecated() const {
- return (_has_bits_[0] & 0x00000001u) != 0;
-}
-void EnumValueOptions::set_has_deprecated() {
- _has_bits_[0] |= 0x00000001u;
-}
-void EnumValueOptions::clear_has_deprecated() {
- _has_bits_[0] &= ~0x00000001u;
-}
-void EnumValueOptions::clear_deprecated() {
- deprecated_ = false;
- clear_has_deprecated();
-}
-bool EnumValueOptions::deprecated() const {
- // @@protoc_insertion_point(field_get:google.protobuf.EnumValueOptions.deprecated)
- return deprecated_;
-}
-void EnumValueOptions::set_deprecated(bool value) {
- set_has_deprecated();
- deprecated_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.EnumValueOptions.deprecated)
-}
-
-// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
-int EnumValueOptions::uninterpreted_option_size() const {
- return uninterpreted_option_.size();
-}
-void EnumValueOptions::clear_uninterpreted_option() {
- uninterpreted_option_.Clear();
-}
-const ::google::protobuf::UninterpretedOption& EnumValueOptions::uninterpreted_option(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.EnumValueOptions.uninterpreted_option)
- return uninterpreted_option_.Get(index);
-}
-::google::protobuf::UninterpretedOption* EnumValueOptions::mutable_uninterpreted_option(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.EnumValueOptions.uninterpreted_option)
- return uninterpreted_option_.Mutable(index);
-}
-::google::protobuf::UninterpretedOption* EnumValueOptions::add_uninterpreted_option() {
- // @@protoc_insertion_point(field_add:google.protobuf.EnumValueOptions.uninterpreted_option)
- return uninterpreted_option_.Add();
-}
-::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >*
-EnumValueOptions::mutable_uninterpreted_option() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.EnumValueOptions.uninterpreted_option)
- return &uninterpreted_option_;
-}
-const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
-EnumValueOptions::uninterpreted_option() const {
- // @@protoc_insertion_point(field_list:google.protobuf.EnumValueOptions.uninterpreted_option)
- return uninterpreted_option_;
-}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
+void ServiceOptions::InitAsDefaultInstance() {
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int ServiceOptions::kDeprecatedFieldNumber;
const int ServiceOptions::kUninterpretedOptionFieldNumber;
@@ -11622,11 +10987,21 @@ const int ServiceOptions::kUninterpretedOptionFieldNumber;
ServiceOptions::ServiceOptions()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceOptions();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.ServiceOptions)
}
+ServiceOptions::ServiceOptions(::google::protobuf::Arena* arena)
+ : ::google::protobuf::Message(),
+ _extensions_(arena),
+ _internal_metadata_(arena),
+ uninterpreted_option_(arena) {
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceOptions();
+ SharedCtor();
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.ServiceOptions)
+}
ServiceOptions::ServiceOptions(const ServiceOptions& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
@@ -11650,33 +11025,40 @@ ServiceOptions::~ServiceOptions() {
}
void ServiceOptions::SharedDtor() {
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
}
+void ServiceOptions::ArenaDtor(void* object) {
+ ServiceOptions* _this = reinterpret_cast< ServiceOptions* >(object);
+ (void)_this;
+}
+void ServiceOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+}
void ServiceOptions::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* ServiceOptions::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[17].descriptor;
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const ServiceOptions& ServiceOptions::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceOptions();
return *internal_default_instance();
}
ServiceOptions* ServiceOptions::New(::google::protobuf::Arena* arena) const {
- ServiceOptions* n = new ServiceOptions;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
+ return ::google::protobuf::Arena::CreateMessage<ServiceOptions>(arena);
}
void ServiceOptions::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.ServiceOptions)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
_extensions_.Clear();
uninterpreted_option_.Clear();
deprecated_ = false;
@@ -11696,7 +11078,8 @@ bool ServiceOptions::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional bool deprecated = 33 [default = false];
case 33: {
- if (tag == 264u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(8u /* 264 & 0xFF */)) {
set_has_deprecated();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
@@ -11709,31 +11092,28 @@ bool ServiceOptions::MergePartialFromCodedStream(
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
case 999: {
- if (tag == 7994u) {
- DO_(input->IncrementRecursionDepth());
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
- input, add_uninterpreted_option()));
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(58u /* 7994 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_uninterpreted_option()));
} else {
goto handle_unusual;
}
- input->UnsafeDecrementRecursionDepth();
break;
}
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
if ((8000u <= tag)) {
- DO_(_extensions_.ParseField(tag, input, internal_default_instance(),
- mutable_unknown_fields()));
+ DO_(_extensions_.ParseField(tag, input,
+ internal_default_instance(),
+ _internal_metadata_.mutable_unknown_fields()));
continue;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
- input, tag, mutable_unknown_fields()));
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -11750,15 +11130,20 @@ failure:
void ServiceOptions::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.ServiceOptions)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional bool deprecated = 33 [default = false];
- if (has_deprecated()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormatLite::WriteBool(33, this->deprecated(), output);
}
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
- for (unsigned int i = 0, n = this->uninterpreted_option_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->uninterpreted_option_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 999, this->uninterpreted_option(i), output);
+ 999, this->uninterpreted_option(static_cast<int>(i)), output);
}
// Extension range [1000, 536870912)
@@ -11767,7 +11152,7 @@ void ServiceOptions::SerializeWithCachedSizes(
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- unknown_fields(), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.ServiceOptions)
}
@@ -11776,25 +11161,30 @@ void ServiceOptions::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.ServiceOptions)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional bool deprecated = 33 [default = false];
- if (has_deprecated()) {
+ if (cached_has_bits & 0x00000001u) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(33, this->deprecated(), target);
}
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
- for (unsigned int i = 0, n = this->uninterpreted_option_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->uninterpreted_option_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 999, this->uninterpreted_option(i), false, target);
+ InternalWriteMessageToArray(
+ 999, this->uninterpreted_option(static_cast<int>(i)), deterministic, target);
}
// Extension range [1000, 536870912)
target = _extensions_.InternalSerializeWithCachedSizesToArray(
- 1000, 536870912, false, target);
+ 1000, 536870912, deterministic, target);
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- unknown_fields(), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.ServiceOptions)
return target;
@@ -11809,16 +11199,16 @@ size_t ServiceOptions::ByteSizeLong() const {
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- unknown_fields());
+ _internal_metadata_.unknown_fields());
}
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
{
- unsigned int count = this->uninterpreted_option_size();
+ unsigned int count = static_cast<unsigned int>(this->uninterpreted_option_size());
total_size += 2UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->uninterpreted_option(i));
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->uninterpreted_option(static_cast<int>(i)));
}
}
@@ -11854,6 +11244,9 @@ void ServiceOptions::MergeFrom(const ServiceOptions& from) {
GOOGLE_DCHECK_NE(&from, this);
_extensions_.MergeFrom(from._extensions_);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
uninterpreted_option_.MergeFrom(from.uninterpreted_option_);
if (from.has_deprecated()) {
set_deprecated(from.deprecated());
@@ -11885,83 +11278,43 @@ bool ServiceOptions::IsInitialized() const {
void ServiceOptions::Swap(ServiceOptions* other) {
if (other == this) return;
+ if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ InternalSwap(other);
+ } else {
+ ServiceOptions* temp = New(GetArenaNoVirtual());
+ temp->MergeFrom(*other);
+ other->CopyFrom(*this);
+ InternalSwap(temp);
+ if (GetArenaNoVirtual() == NULL) {
+ delete temp;
+ }
+ }
+}
+void ServiceOptions::UnsafeArenaSwap(ServiceOptions* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void ServiceOptions::InternalSwap(ServiceOptions* other) {
- uninterpreted_option_.UnsafeArenaSwap(&other->uninterpreted_option_);
- std::swap(deprecated_, other->deprecated_);
- std::swap(_has_bits_[0], other->_has_bits_[0]);
+ using std::swap;
+ uninterpreted_option_.InternalSwap(&other->uninterpreted_option_);
+ swap(deprecated_, other->deprecated_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- std::swap(_cached_size_, other->_cached_size_);
+ swap(_cached_size_, other->_cached_size_);
_extensions_.Swap(&other->_extensions_);
}
::google::protobuf::Metadata ServiceOptions::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[17];
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// ServiceOptions
-
-// optional bool deprecated = 33 [default = false];
-bool ServiceOptions::has_deprecated() const {
- return (_has_bits_[0] & 0x00000001u) != 0;
-}
-void ServiceOptions::set_has_deprecated() {
- _has_bits_[0] |= 0x00000001u;
-}
-void ServiceOptions::clear_has_deprecated() {
- _has_bits_[0] &= ~0x00000001u;
-}
-void ServiceOptions::clear_deprecated() {
- deprecated_ = false;
- clear_has_deprecated();
-}
-bool ServiceOptions::deprecated() const {
- // @@protoc_insertion_point(field_get:google.protobuf.ServiceOptions.deprecated)
- return deprecated_;
-}
-void ServiceOptions::set_deprecated(bool value) {
- set_has_deprecated();
- deprecated_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.ServiceOptions.deprecated)
-}
-
-// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
-int ServiceOptions::uninterpreted_option_size() const {
- return uninterpreted_option_.size();
-}
-void ServiceOptions::clear_uninterpreted_option() {
- uninterpreted_option_.Clear();
-}
-const ::google::protobuf::UninterpretedOption& ServiceOptions::uninterpreted_option(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.ServiceOptions.uninterpreted_option)
- return uninterpreted_option_.Get(index);
-}
-::google::protobuf::UninterpretedOption* ServiceOptions::mutable_uninterpreted_option(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.ServiceOptions.uninterpreted_option)
- return uninterpreted_option_.Mutable(index);
-}
-::google::protobuf::UninterpretedOption* ServiceOptions::add_uninterpreted_option() {
- // @@protoc_insertion_point(field_add:google.protobuf.ServiceOptions.uninterpreted_option)
- return uninterpreted_option_.Add();
-}
-::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >*
-ServiceOptions::mutable_uninterpreted_option() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.ServiceOptions.uninterpreted_option)
- return &uninterpreted_option_;
-}
-const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
-ServiceOptions::uninterpreted_option() const {
- // @@protoc_insertion_point(field_list:google.protobuf.ServiceOptions.uninterpreted_option)
- return uninterpreted_option_;
-}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
+void MethodOptions::InitAsDefaultInstance() {
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int MethodOptions::kDeprecatedFieldNumber;
const int MethodOptions::kIdempotencyLevelFieldNumber;
@@ -11971,11 +11324,21 @@ const int MethodOptions::kUninterpretedOptionFieldNumber;
MethodOptions::MethodOptions()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodOptions();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.MethodOptions)
}
+MethodOptions::MethodOptions(::google::protobuf::Arena* arena)
+ : ::google::protobuf::Message(),
+ _extensions_(arena),
+ _internal_metadata_(arena),
+ uninterpreted_option_(arena) {
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodOptions();
+ SharedCtor();
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.MethodOptions)
+}
MethodOptions::MethodOptions(const MethodOptions& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
@@ -11985,15 +11348,16 @@ MethodOptions::MethodOptions(const MethodOptions& from)
_internal_metadata_.MergeFrom(from._internal_metadata_);
_extensions_.MergeFrom(from._extensions_);
::memcpy(&deprecated_, &from.deprecated_,
- reinterpret_cast<char*>(&idempotency_level_) -
- reinterpret_cast<char*>(&deprecated_) + sizeof(idempotency_level_));
+ static_cast<size_t>(reinterpret_cast<char*>(&idempotency_level_) -
+ reinterpret_cast<char*>(&deprecated_)) + sizeof(idempotency_level_));
// @@protoc_insertion_point(copy_constructor:google.protobuf.MethodOptions)
}
void MethodOptions::SharedCtor() {
_cached_size_ = 0;
- ::memset(&deprecated_, 0, reinterpret_cast<char*>(&idempotency_level_) -
- reinterpret_cast<char*>(&deprecated_) + sizeof(idempotency_level_));
+ ::memset(&deprecated_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&idempotency_level_) -
+ reinterpret_cast<char*>(&deprecated_)) + sizeof(idempotency_level_));
}
MethodOptions::~MethodOptions() {
@@ -12002,38 +11366,47 @@ MethodOptions::~MethodOptions() {
}
void MethodOptions::SharedDtor() {
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
}
+void MethodOptions::ArenaDtor(void* object) {
+ MethodOptions* _this = reinterpret_cast< MethodOptions* >(object);
+ (void)_this;
+}
+void MethodOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+}
void MethodOptions::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* MethodOptions::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[18].descriptor;
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const MethodOptions& MethodOptions::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodOptions();
return *internal_default_instance();
}
MethodOptions* MethodOptions::New(::google::protobuf::Arena* arena) const {
- MethodOptions* n = new MethodOptions;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
+ return ::google::protobuf::Arena::CreateMessage<MethodOptions>(arena);
}
void MethodOptions::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.MethodOptions)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
_extensions_.Clear();
uninterpreted_option_.Clear();
- if (_has_bits_[0 / 32] & 3u) {
- ::memset(&deprecated_, 0, reinterpret_cast<char*>(&idempotency_level_) -
- reinterpret_cast<char*>(&deprecated_) + sizeof(idempotency_level_));
+ cached_has_bits = _has_bits_[0];
+ if (cached_has_bits & 3u) {
+ ::memset(&deprecated_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&idempotency_level_) -
+ reinterpret_cast<char*>(&deprecated_)) + sizeof(idempotency_level_));
}
_has_bits_.Clear();
_internal_metadata_.Clear();
@@ -12051,7 +11424,8 @@ bool MethodOptions::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional bool deprecated = 33 [default = false];
case 33: {
- if (tag == 264u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(8u /* 264 & 0xFF */)) {
set_has_deprecated();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
@@ -12064,7 +11438,8 @@ bool MethodOptions::MergePartialFromCodedStream(
// optional .google.protobuf.MethodOptions.IdempotencyLevel idempotency_level = 34 [default = IDEMPOTENCY_UNKNOWN];
case 34: {
- if (tag == 272u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(16u /* 272 & 0xFF */)) {
int value;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
@@ -12072,7 +11447,8 @@ bool MethodOptions::MergePartialFromCodedStream(
if (::google::protobuf::MethodOptions_IdempotencyLevel_IsValid(value)) {
set_idempotency_level(static_cast< ::google::protobuf::MethodOptions_IdempotencyLevel >(value));
} else {
- mutable_unknown_fields()->AddVarint(34, value);
+ mutable_unknown_fields()->AddVarint(
+ 34, static_cast< ::google::protobuf::uint64>(value));
}
} else {
goto handle_unusual;
@@ -12082,31 +11458,28 @@ bool MethodOptions::MergePartialFromCodedStream(
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
case 999: {
- if (tag == 7994u) {
- DO_(input->IncrementRecursionDepth());
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
- input, add_uninterpreted_option()));
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(58u /* 7994 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_uninterpreted_option()));
} else {
goto handle_unusual;
}
- input->UnsafeDecrementRecursionDepth();
break;
}
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
if ((8000u <= tag)) {
- DO_(_extensions_.ParseField(tag, input, internal_default_instance(),
- mutable_unknown_fields()));
+ DO_(_extensions_.ParseField(tag, input,
+ internal_default_instance(),
+ _internal_metadata_.mutable_unknown_fields()));
continue;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
- input, tag, mutable_unknown_fields()));
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -12123,21 +11496,26 @@ failure:
void MethodOptions::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.MethodOptions)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional bool deprecated = 33 [default = false];
- if (has_deprecated()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormatLite::WriteBool(33, this->deprecated(), output);
}
// optional .google.protobuf.MethodOptions.IdempotencyLevel idempotency_level = 34 [default = IDEMPOTENCY_UNKNOWN];
- if (has_idempotency_level()) {
+ if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteEnum(
34, this->idempotency_level(), output);
}
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
- for (unsigned int i = 0, n = this->uninterpreted_option_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->uninterpreted_option_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 999, this->uninterpreted_option(i), output);
+ 999, this->uninterpreted_option(static_cast<int>(i)), output);
}
// Extension range [1000, 536870912)
@@ -12146,7 +11524,7 @@ void MethodOptions::SerializeWithCachedSizes(
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- unknown_fields(), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.MethodOptions)
}
@@ -12155,31 +11533,36 @@ void MethodOptions::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.MethodOptions)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// optional bool deprecated = 33 [default = false];
- if (has_deprecated()) {
+ if (cached_has_bits & 0x00000001u) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(33, this->deprecated(), target);
}
// optional .google.protobuf.MethodOptions.IdempotencyLevel idempotency_level = 34 [default = IDEMPOTENCY_UNKNOWN];
- if (has_idempotency_level()) {
+ if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray(
34, this->idempotency_level(), target);
}
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
- for (unsigned int i = 0, n = this->uninterpreted_option_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->uninterpreted_option_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 999, this->uninterpreted_option(i), false, target);
+ InternalWriteMessageToArray(
+ 999, this->uninterpreted_option(static_cast<int>(i)), deterministic, target);
}
// Extension range [1000, 536870912)
target = _extensions_.InternalSerializeWithCachedSizesToArray(
- 1000, 536870912, false, target);
+ 1000, 536870912, deterministic, target);
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- unknown_fields(), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.MethodOptions)
return target;
@@ -12194,16 +11577,16 @@ size_t MethodOptions::ByteSizeLong() const {
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- unknown_fields());
+ _internal_metadata_.unknown_fields());
}
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
{
- unsigned int count = this->uninterpreted_option_size();
+ unsigned int count = static_cast<unsigned int>(this->uninterpreted_option_size());
total_size += 2UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->uninterpreted_option(i));
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->uninterpreted_option(static_cast<int>(i)));
}
}
@@ -12247,14 +11630,19 @@ void MethodOptions::MergeFrom(const MethodOptions& from) {
GOOGLE_DCHECK_NE(&from, this);
_extensions_.MergeFrom(from._extensions_);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
uninterpreted_option_.MergeFrom(from.uninterpreted_option_);
- if (from._has_bits_[0 / 32] & 3u) {
- if (from.has_deprecated()) {
- set_deprecated(from.deprecated());
+ cached_has_bits = from._has_bits_[0];
+ if (cached_has_bits & 3u) {
+ if (cached_has_bits & 0x00000001u) {
+ deprecated_ = from.deprecated_;
}
- if (from.has_idempotency_level()) {
- set_idempotency_level(from.idempotency_level());
+ if (cached_has_bits & 0x00000002u) {
+ idempotency_level_ = from.idempotency_level_;
}
+ _has_bits_[0] |= cached_has_bits;
}
}
@@ -12283,109 +11671,44 @@ bool MethodOptions::IsInitialized() const {
void MethodOptions::Swap(MethodOptions* other) {
if (other == this) return;
+ if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ InternalSwap(other);
+ } else {
+ MethodOptions* temp = New(GetArenaNoVirtual());
+ temp->MergeFrom(*other);
+ other->CopyFrom(*this);
+ InternalSwap(temp);
+ if (GetArenaNoVirtual() == NULL) {
+ delete temp;
+ }
+ }
+}
+void MethodOptions::UnsafeArenaSwap(MethodOptions* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void MethodOptions::InternalSwap(MethodOptions* other) {
- uninterpreted_option_.UnsafeArenaSwap(&other->uninterpreted_option_);
- std::swap(deprecated_, other->deprecated_);
- std::swap(idempotency_level_, other->idempotency_level_);
- std::swap(_has_bits_[0], other->_has_bits_[0]);
+ using std::swap;
+ uninterpreted_option_.InternalSwap(&other->uninterpreted_option_);
+ swap(deprecated_, other->deprecated_);
+ swap(idempotency_level_, other->idempotency_level_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- std::swap(_cached_size_, other->_cached_size_);
+ swap(_cached_size_, other->_cached_size_);
_extensions_.Swap(&other->_extensions_);
}
::google::protobuf::Metadata MethodOptions::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[18];
-}
-
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// MethodOptions
-
-// optional bool deprecated = 33 [default = false];
-bool MethodOptions::has_deprecated() const {
- return (_has_bits_[0] & 0x00000001u) != 0;
-}
-void MethodOptions::set_has_deprecated() {
- _has_bits_[0] |= 0x00000001u;
-}
-void MethodOptions::clear_has_deprecated() {
- _has_bits_[0] &= ~0x00000001u;
-}
-void MethodOptions::clear_deprecated() {
- deprecated_ = false;
- clear_has_deprecated();
-}
-bool MethodOptions::deprecated() const {
- // @@protoc_insertion_point(field_get:google.protobuf.MethodOptions.deprecated)
- return deprecated_;
-}
-void MethodOptions::set_deprecated(bool value) {
- set_has_deprecated();
- deprecated_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.MethodOptions.deprecated)
-}
-
-// optional .google.protobuf.MethodOptions.IdempotencyLevel idempotency_level = 34 [default = IDEMPOTENCY_UNKNOWN];
-bool MethodOptions::has_idempotency_level() const {
- return (_has_bits_[0] & 0x00000002u) != 0;
-}
-void MethodOptions::set_has_idempotency_level() {
- _has_bits_[0] |= 0x00000002u;
-}
-void MethodOptions::clear_has_idempotency_level() {
- _has_bits_[0] &= ~0x00000002u;
-}
-void MethodOptions::clear_idempotency_level() {
- idempotency_level_ = 0;
- clear_has_idempotency_level();
-}
-::google::protobuf::MethodOptions_IdempotencyLevel MethodOptions::idempotency_level() const {
- // @@protoc_insertion_point(field_get:google.protobuf.MethodOptions.idempotency_level)
- return static_cast< ::google::protobuf::MethodOptions_IdempotencyLevel >(idempotency_level_);
-}
-void MethodOptions::set_idempotency_level(::google::protobuf::MethodOptions_IdempotencyLevel value) {
- assert(::google::protobuf::MethodOptions_IdempotencyLevel_IsValid(value));
- set_has_idempotency_level();
- idempotency_level_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.MethodOptions.idempotency_level)
-}
-
-// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
-int MethodOptions::uninterpreted_option_size() const {
- return uninterpreted_option_.size();
-}
-void MethodOptions::clear_uninterpreted_option() {
- uninterpreted_option_.Clear();
-}
-const ::google::protobuf::UninterpretedOption& MethodOptions::uninterpreted_option(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.MethodOptions.uninterpreted_option)
- return uninterpreted_option_.Get(index);
-}
-::google::protobuf::UninterpretedOption* MethodOptions::mutable_uninterpreted_option(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.MethodOptions.uninterpreted_option)
- return uninterpreted_option_.Mutable(index);
-}
-::google::protobuf::UninterpretedOption* MethodOptions::add_uninterpreted_option() {
- // @@protoc_insertion_point(field_add:google.protobuf.MethodOptions.uninterpreted_option)
- return uninterpreted_option_.Add();
-}
-::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >*
-MethodOptions::mutable_uninterpreted_option() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.MethodOptions.uninterpreted_option)
- return &uninterpreted_option_;
-}
-const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
-MethodOptions::uninterpreted_option() const {
- // @@protoc_insertion_point(field_list:google.protobuf.MethodOptions.uninterpreted_option)
- return uninterpreted_option_;
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
+void UninterpretedOption_NamePart::InitAsDefaultInstance() {
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int UninterpretedOption_NamePart::kNamePartFieldNumber;
const int UninterpretedOption_NamePart::kIsExtensionFieldNumber;
@@ -12394,11 +11717,19 @@ const int UninterpretedOption_NamePart::kIsExtensionFieldNumber;
UninterpretedOption_NamePart::UninterpretedOption_NamePart()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption_NamePart();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.UninterpretedOption.NamePart)
}
+UninterpretedOption_NamePart::UninterpretedOption_NamePart(::google::protobuf::Arena* arena)
+ : ::google::protobuf::Message(),
+ _internal_metadata_(arena) {
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption_NamePart();
+ SharedCtor();
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.UninterpretedOption.NamePart)
+}
UninterpretedOption_NamePart::UninterpretedOption_NamePart(const UninterpretedOption_NamePart& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
@@ -12407,7 +11738,8 @@ UninterpretedOption_NamePart::UninterpretedOption_NamePart(const UninterpretedOp
_internal_metadata_.MergeFrom(from._internal_metadata_);
name_part_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_name_part()) {
- name_part_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_part_);
+ name_part_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_part(),
+ GetArenaNoVirtual());
}
is_extension_ = from.is_extension_;
// @@protoc_insertion_point(copy_constructor:google.protobuf.UninterpretedOption.NamePart)
@@ -12425,37 +11757,45 @@ UninterpretedOption_NamePart::~UninterpretedOption_NamePart() {
}
void UninterpretedOption_NamePart::SharedDtor() {
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
name_part_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
+void UninterpretedOption_NamePart::ArenaDtor(void* object) {
+ UninterpretedOption_NamePart* _this = reinterpret_cast< UninterpretedOption_NamePart* >(object);
+ (void)_this;
+}
+void UninterpretedOption_NamePart::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+}
void UninterpretedOption_NamePart::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* UninterpretedOption_NamePart::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[19].descriptor;
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const UninterpretedOption_NamePart& UninterpretedOption_NamePart::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption_NamePart();
return *internal_default_instance();
}
UninterpretedOption_NamePart* UninterpretedOption_NamePart::New(::google::protobuf::Arena* arena) const {
- UninterpretedOption_NamePart* n = new UninterpretedOption_NamePart;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
+ return ::google::protobuf::Arena::CreateMessage<UninterpretedOption_NamePart>(arena);
}
void UninterpretedOption_NamePart::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.UninterpretedOption.NamePart)
- if (has_name_part()) {
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
+ if (cached_has_bits & 0x00000001u) {
GOOGLE_DCHECK(!name_part_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- (*name_part_.UnsafeRawStringPointer())->clear();
+ name_part_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
is_extension_ = false;
_has_bits_.Clear();
@@ -12474,11 +11814,12 @@ bool UninterpretedOption_NamePart::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// required string name_part = 1;
case 1: {
- if (tag == 10u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name_part()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->name_part().data(), this->name_part().length(),
+ this->name_part().data(), static_cast<int>(this->name_part().length()),
::google::protobuf::internal::WireFormat::PARSE,
"google.protobuf.UninterpretedOption.NamePart.name_part");
} else {
@@ -12489,7 +11830,8 @@ bool UninterpretedOption_NamePart::MergePartialFromCodedStream(
// required bool is_extension = 2;
case 2: {
- if (tag == 16u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
set_has_is_extension();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
@@ -12502,13 +11844,11 @@ bool UninterpretedOption_NamePart::MergePartialFromCodedStream(
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
- input, tag, mutable_unknown_fields()));
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -12525,10 +11865,14 @@ failure:
void UninterpretedOption_NamePart::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.UninterpretedOption.NamePart)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// required string name_part = 1;
- if (has_name_part()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->name_part().data(), this->name_part().length(),
+ this->name_part().data(), static_cast<int>(this->name_part().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.UninterpretedOption.NamePart.name_part");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -12536,13 +11880,13 @@ void UninterpretedOption_NamePart::SerializeWithCachedSizes(
}
// required bool is_extension = 2;
- if (has_is_extension()) {
+ if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteBool(2, this->is_extension(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- unknown_fields(), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.UninterpretedOption.NamePart)
}
@@ -12551,10 +11895,14 @@ void UninterpretedOption_NamePart::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.UninterpretedOption.NamePart)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = _has_bits_[0];
// required string name_part = 1;
- if (has_name_part()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->name_part().data(), this->name_part().length(),
+ this->name_part().data(), static_cast<int>(this->name_part().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.UninterpretedOption.NamePart.name_part");
target =
@@ -12563,13 +11911,13 @@ void UninterpretedOption_NamePart::SerializeWithCachedSizes(
}
// required bool is_extension = 2;
- if (has_is_extension()) {
+ if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(2, this->is_extension(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- unknown_fields(), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.UninterpretedOption.NamePart)
return target;
@@ -12600,7 +11948,7 @@ size_t UninterpretedOption_NamePart::ByteSizeLong() const {
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- unknown_fields());
+ _internal_metadata_.unknown_fields());
}
if (((_has_bits_[0] & 0x00000003) ^ 0x00000003) == 0) { // All required fields are present.
// required string name_part = 1;
@@ -12640,14 +11988,18 @@ void UninterpretedOption_NamePart::MergeFrom(const UninterpretedOption_NamePart&
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.UninterpretedOption.NamePart)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
- if (from._has_bits_[0 / 32] & 3u) {
- if (from.has_name_part()) {
- set_has_name_part();
- name_part_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_part_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ cached_has_bits = from._has_bits_[0];
+ if (cached_has_bits & 3u) {
+ if (cached_has_bits & 0x00000001u) {
+ set_name_part(from.name_part());
}
- if (from.has_is_extension()) {
- set_is_extension(from.is_extension());
+ if (cached_has_bits & 0x00000002u) {
+ is_extension_ = from.is_extension_;
}
+ _has_bits_[0] |= cached_has_bits;
}
}
@@ -12672,106 +12024,42 @@ bool UninterpretedOption_NamePart::IsInitialized() const {
void UninterpretedOption_NamePart::Swap(UninterpretedOption_NamePart* other) {
if (other == this) return;
+ if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ InternalSwap(other);
+ } else {
+ UninterpretedOption_NamePart* temp = New(GetArenaNoVirtual());
+ temp->MergeFrom(*other);
+ other->CopyFrom(*this);
+ InternalSwap(temp);
+ if (GetArenaNoVirtual() == NULL) {
+ delete temp;
+ }
+ }
+}
+void UninterpretedOption_NamePart::UnsafeArenaSwap(UninterpretedOption_NamePart* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void UninterpretedOption_NamePart::InternalSwap(UninterpretedOption_NamePart* other) {
+ using std::swap;
name_part_.Swap(&other->name_part_);
- std::swap(is_extension_, other->is_extension_);
- std::swap(_has_bits_[0], other->_has_bits_[0]);
+ swap(is_extension_, other->is_extension_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- std::swap(_cached_size_, other->_cached_size_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata UninterpretedOption_NamePart::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[19];
-}
-
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// UninterpretedOption_NamePart
-
-// required string name_part = 1;
-bool UninterpretedOption_NamePart::has_name_part() const {
- return (_has_bits_[0] & 0x00000001u) != 0;
-}
-void UninterpretedOption_NamePart::set_has_name_part() {
- _has_bits_[0] |= 0x00000001u;
-}
-void UninterpretedOption_NamePart::clear_has_name_part() {
- _has_bits_[0] &= ~0x00000001u;
-}
-void UninterpretedOption_NamePart::clear_name_part() {
- name_part_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_name_part();
-}
-const ::std::string& UninterpretedOption_NamePart::name_part() const {
- // @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.NamePart.name_part)
- return name_part_.GetNoArena();
-}
-void UninterpretedOption_NamePart::set_name_part(const ::std::string& value) {
- set_has_name_part();
- name_part_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.UninterpretedOption.NamePart.name_part)
-}
-void UninterpretedOption_NamePart::set_name_part(const char* value) {
- set_has_name_part();
- name_part_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.UninterpretedOption.NamePart.name_part)
-}
-void UninterpretedOption_NamePart::set_name_part(const char* value, size_t size) {
- set_has_name_part();
- name_part_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.UninterpretedOption.NamePart.name_part)
-}
-::std::string* UninterpretedOption_NamePart::mutable_name_part() {
- set_has_name_part();
- // @@protoc_insertion_point(field_mutable:google.protobuf.UninterpretedOption.NamePart.name_part)
- return name_part_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* UninterpretedOption_NamePart::release_name_part() {
- // @@protoc_insertion_point(field_release:google.protobuf.UninterpretedOption.NamePart.name_part)
- clear_has_name_part();
- return name_part_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void UninterpretedOption_NamePart::set_allocated_name_part(::std::string* name_part) {
- if (name_part != NULL) {
- set_has_name_part();
- } else {
- clear_has_name_part();
- }
- name_part_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name_part);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.UninterpretedOption.NamePart.name_part)
-}
-
-// required bool is_extension = 2;
-bool UninterpretedOption_NamePart::has_is_extension() const {
- return (_has_bits_[0] & 0x00000002u) != 0;
-}
-void UninterpretedOption_NamePart::set_has_is_extension() {
- _has_bits_[0] |= 0x00000002u;
-}
-void UninterpretedOption_NamePart::clear_has_is_extension() {
- _has_bits_[0] &= ~0x00000002u;
-}
-void UninterpretedOption_NamePart::clear_is_extension() {
- is_extension_ = false;
- clear_has_is_extension();
-}
-bool UninterpretedOption_NamePart::is_extension() const {
- // @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.NamePart.is_extension)
- return is_extension_;
-}
-void UninterpretedOption_NamePart::set_is_extension(bool value) {
- set_has_is_extension();
- is_extension_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.UninterpretedOption.NamePart.is_extension)
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
+void UninterpretedOption::InitAsDefaultInstance() {
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int UninterpretedOption::kNameFieldNumber;
const int UninterpretedOption::kIdentifierValueFieldNumber;
@@ -12785,11 +12073,20 @@ const int UninterpretedOption::kAggregateValueFieldNumber;
UninterpretedOption::UninterpretedOption()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.UninterpretedOption)
}
+UninterpretedOption::UninterpretedOption(::google::protobuf::Arena* arena)
+ : ::google::protobuf::Message(),
+ _internal_metadata_(arena),
+ name_(arena) {
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption();
+ SharedCtor();
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.UninterpretedOption)
+}
UninterpretedOption::UninterpretedOption(const UninterpretedOption& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
@@ -12799,19 +12096,22 @@ UninterpretedOption::UninterpretedOption(const UninterpretedOption& from)
_internal_metadata_.MergeFrom(from._internal_metadata_);
identifier_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_identifier_value()) {
- identifier_value_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.identifier_value_);
+ identifier_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.identifier_value(),
+ GetArenaNoVirtual());
}
string_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_string_value()) {
- string_value_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.string_value_);
+ string_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.string_value(),
+ GetArenaNoVirtual());
}
aggregate_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_aggregate_value()) {
- aggregate_value_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.aggregate_value_);
+ aggregate_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.aggregate_value(),
+ GetArenaNoVirtual());
}
::memcpy(&positive_int_value_, &from.positive_int_value_,
- reinterpret_cast<char*>(&double_value_) -
- reinterpret_cast<char*>(&positive_int_value_) + sizeof(double_value_));
+ static_cast<size_t>(reinterpret_cast<char*>(&double_value_) -
+ reinterpret_cast<char*>(&positive_int_value_)) + sizeof(double_value_));
// @@protoc_insertion_point(copy_constructor:google.protobuf.UninterpretedOption)
}
@@ -12820,8 +12120,9 @@ void UninterpretedOption::SharedCtor() {
identifier_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
string_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
aggregate_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- ::memset(&positive_int_value_, 0, reinterpret_cast<char*>(&double_value_) -
- reinterpret_cast<char*>(&positive_int_value_) + sizeof(double_value_));
+ ::memset(&positive_int_value_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&double_value_) -
+ reinterpret_cast<char*>(&positive_int_value_)) + sizeof(double_value_));
}
UninterpretedOption::~UninterpretedOption() {
@@ -12830,54 +12131,63 @@ UninterpretedOption::~UninterpretedOption() {
}
void UninterpretedOption::SharedDtor() {
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
identifier_value_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
string_value_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
aggregate_value_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
+void UninterpretedOption::ArenaDtor(void* object) {
+ UninterpretedOption* _this = reinterpret_cast< UninterpretedOption* >(object);
+ (void)_this;
+}
+void UninterpretedOption::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+}
void UninterpretedOption::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* UninterpretedOption::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[20].descriptor;
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const UninterpretedOption& UninterpretedOption::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption();
return *internal_default_instance();
}
UninterpretedOption* UninterpretedOption::New(::google::protobuf::Arena* arena) const {
- UninterpretedOption* n = new UninterpretedOption;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
+ return ::google::protobuf::Arena::CreateMessage<UninterpretedOption>(arena);
}
void UninterpretedOption::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.UninterpretedOption)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
name_.Clear();
- if (_has_bits_[0 / 32] & 7u) {
- if (has_identifier_value()) {
+ cached_has_bits = _has_bits_[0];
+ if (cached_has_bits & 7u) {
+ if (cached_has_bits & 0x00000001u) {
GOOGLE_DCHECK(!identifier_value_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- (*identifier_value_.UnsafeRawStringPointer())->clear();
+ identifier_value_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- if (has_string_value()) {
+ if (cached_has_bits & 0x00000002u) {
GOOGLE_DCHECK(!string_value_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- (*string_value_.UnsafeRawStringPointer())->clear();
+ string_value_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- if (has_aggregate_value()) {
+ if (cached_has_bits & 0x00000004u) {
GOOGLE_DCHECK(!aggregate_value_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- (*aggregate_value_.UnsafeRawStringPointer())->clear();
+ aggregate_value_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
}
- if (_has_bits_[0 / 32] & 56u) {
- ::memset(&positive_int_value_, 0, reinterpret_cast<char*>(&double_value_) -
- reinterpret_cast<char*>(&positive_int_value_) + sizeof(double_value_));
+ if (cached_has_bits & 56u) {
+ ::memset(&positive_int_value_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&double_value_) -
+ reinterpret_cast<char*>(&positive_int_value_)) + sizeof(double_value_));
}
_has_bits_.Clear();
_internal_metadata_.Clear();
@@ -12895,24 +12205,23 @@ bool UninterpretedOption::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated .google.protobuf.UninterpretedOption.NamePart name = 2;
case 2: {
- if (tag == 18u) {
- DO_(input->IncrementRecursionDepth());
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
- input, add_name()));
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_name()));
} else {
goto handle_unusual;
}
- input->UnsafeDecrementRecursionDepth();
break;
}
// optional string identifier_value = 3;
case 3: {
- if (tag == 26u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_identifier_value()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->identifier_value().data(), this->identifier_value().length(),
+ this->identifier_value().data(), static_cast<int>(this->identifier_value().length()),
::google::protobuf::internal::WireFormat::PARSE,
"google.protobuf.UninterpretedOption.identifier_value");
} else {
@@ -12923,7 +12232,8 @@ bool UninterpretedOption::MergePartialFromCodedStream(
// optional uint64 positive_int_value = 4;
case 4: {
- if (tag == 32u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(32u /* 32 & 0xFF */)) {
set_has_positive_int_value();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_UINT64>(
@@ -12936,7 +12246,8 @@ bool UninterpretedOption::MergePartialFromCodedStream(
// optional int64 negative_int_value = 5;
case 5: {
- if (tag == 40u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) {
set_has_negative_int_value();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>(
@@ -12949,7 +12260,8 @@ bool UninterpretedOption::MergePartialFromCodedStream(
// optional double double_value = 6;
case 6: {
- if (tag == 49u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(49u /* 49 & 0xFF */)) {
set_has_double_value();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
@@ -12962,7 +12274,8 @@ bool UninterpretedOption::MergePartialFromCodedStream(
// optional bytes string_value = 7;
case 7: {
- if (tag == 58u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(58u /* 58 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadBytes(
input, this->mutable_string_value()));
} else {
@@ -12973,11 +12286,12 @@ bool UninterpretedOption::MergePartialFromCodedStream(
// optional string aggregate_value = 8;
case 8: {
- if (tag == 66u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(66u /* 66 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_aggregate_value()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->aggregate_value().data(), this->aggregate_value().length(),
+ this->aggregate_value().data(), static_cast<int>(this->aggregate_value().length()),
::google::protobuf::internal::WireFormat::PARSE,
"google.protobuf.UninterpretedOption.aggregate_value");
} else {
@@ -12988,13 +12302,11 @@ bool UninterpretedOption::MergePartialFromCodedStream(
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
- input, tag, mutable_unknown_fields()));
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -13011,16 +12323,21 @@ failure:
void UninterpretedOption::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.UninterpretedOption)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// repeated .google.protobuf.UninterpretedOption.NamePart name = 2;
- for (unsigned int i = 0, n = this->name_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->name_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 2, this->name(i), output);
+ 2, this->name(static_cast<int>(i)), output);
}
+ cached_has_bits = _has_bits_[0];
// optional string identifier_value = 3;
- if (has_identifier_value()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->identifier_value().data(), this->identifier_value().length(),
+ this->identifier_value().data(), static_cast<int>(this->identifier_value().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.UninterpretedOption.identifier_value");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -13028,30 +12345,30 @@ void UninterpretedOption::SerializeWithCachedSizes(
}
// optional uint64 positive_int_value = 4;
- if (has_positive_int_value()) {
+ if (cached_has_bits & 0x00000008u) {
::google::protobuf::internal::WireFormatLite::WriteUInt64(4, this->positive_int_value(), output);
}
// optional int64 negative_int_value = 5;
- if (has_negative_int_value()) {
+ if (cached_has_bits & 0x00000010u) {
::google::protobuf::internal::WireFormatLite::WriteInt64(5, this->negative_int_value(), output);
}
// optional double double_value = 6;
- if (has_double_value()) {
+ if (cached_has_bits & 0x00000020u) {
::google::protobuf::internal::WireFormatLite::WriteDouble(6, this->double_value(), output);
}
// optional bytes string_value = 7;
- if (has_string_value()) {
+ if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased(
7, this->string_value(), output);
}
// optional string aggregate_value = 8;
- if (has_aggregate_value()) {
+ if (cached_has_bits & 0x00000004u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->aggregate_value().data(), this->aggregate_value().length(),
+ this->aggregate_value().data(), static_cast<int>(this->aggregate_value().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.UninterpretedOption.aggregate_value");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -13060,7 +12377,7 @@ void UninterpretedOption::SerializeWithCachedSizes(
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- unknown_fields(), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.UninterpretedOption)
}
@@ -13069,17 +12386,22 @@ void UninterpretedOption::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.UninterpretedOption)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// repeated .google.protobuf.UninterpretedOption.NamePart name = 2;
- for (unsigned int i = 0, n = this->name_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->name_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 2, this->name(i), false, target);
+ InternalWriteMessageToArray(
+ 2, this->name(static_cast<int>(i)), deterministic, target);
}
+ cached_has_bits = _has_bits_[0];
// optional string identifier_value = 3;
- if (has_identifier_value()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->identifier_value().data(), this->identifier_value().length(),
+ this->identifier_value().data(), static_cast<int>(this->identifier_value().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.UninterpretedOption.identifier_value");
target =
@@ -13088,31 +12410,31 @@ void UninterpretedOption::SerializeWithCachedSizes(
}
// optional uint64 positive_int_value = 4;
- if (has_positive_int_value()) {
+ if (cached_has_bits & 0x00000008u) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt64ToArray(4, this->positive_int_value(), target);
}
// optional int64 negative_int_value = 5;
- if (has_negative_int_value()) {
+ if (cached_has_bits & 0x00000010u) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(5, this->negative_int_value(), target);
}
// optional double double_value = 6;
- if (has_double_value()) {
+ if (cached_has_bits & 0x00000020u) {
target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(6, this->double_value(), target);
}
// optional bytes string_value = 7;
- if (has_string_value()) {
+ if (cached_has_bits & 0x00000002u) {
target =
::google::protobuf::internal::WireFormatLite::WriteBytesToArray(
7, this->string_value(), target);
}
// optional string aggregate_value = 8;
- if (has_aggregate_value()) {
+ if (cached_has_bits & 0x00000004u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->aggregate_value().data(), this->aggregate_value().length(),
+ this->aggregate_value().data(), static_cast<int>(this->aggregate_value().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.UninterpretedOption.aggregate_value");
target =
@@ -13122,7 +12444,7 @@ void UninterpretedOption::SerializeWithCachedSizes(
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- unknown_fields(), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.UninterpretedOption)
return target;
@@ -13135,16 +12457,16 @@ size_t UninterpretedOption::ByteSizeLong() const {
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- unknown_fields());
+ _internal_metadata_.unknown_fields());
}
// repeated .google.protobuf.UninterpretedOption.NamePart name = 2;
{
- unsigned int count = this->name_size();
+ unsigned int count = static_cast<unsigned int>(this->name_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->name(i));
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->name(static_cast<int>(i)));
}
}
@@ -13216,29 +12538,31 @@ void UninterpretedOption::MergeFrom(const UninterpretedOption& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.UninterpretedOption)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
name_.MergeFrom(from.name_);
- if (from._has_bits_[0 / 32] & 63u) {
- if (from.has_identifier_value()) {
- set_has_identifier_value();
- identifier_value_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.identifier_value_);
+ cached_has_bits = from._has_bits_[0];
+ if (cached_has_bits & 63u) {
+ if (cached_has_bits & 0x00000001u) {
+ set_identifier_value(from.identifier_value());
}
- if (from.has_string_value()) {
- set_has_string_value();
- string_value_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.string_value_);
+ if (cached_has_bits & 0x00000002u) {
+ set_string_value(from.string_value());
}
- if (from.has_aggregate_value()) {
- set_has_aggregate_value();
- aggregate_value_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.aggregate_value_);
+ if (cached_has_bits & 0x00000004u) {
+ set_aggregate_value(from.aggregate_value());
}
- if (from.has_positive_int_value()) {
- set_positive_int_value(from.positive_int_value());
+ if (cached_has_bits & 0x00000008u) {
+ positive_int_value_ = from.positive_int_value_;
}
- if (from.has_negative_int_value()) {
- set_negative_int_value(from.negative_int_value());
+ if (cached_has_bits & 0x00000010u) {
+ negative_int_value_ = from.negative_int_value_;
}
- if (from.has_double_value()) {
- set_double_value(from.double_value());
+ if (cached_has_bits & 0x00000020u) {
+ double_value_ = from.double_value_;
}
+ _has_bits_[0] |= cached_has_bits;
}
}
@@ -13263,297 +12587,47 @@ bool UninterpretedOption::IsInitialized() const {
void UninterpretedOption::Swap(UninterpretedOption* other) {
if (other == this) return;
+ if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ InternalSwap(other);
+ } else {
+ UninterpretedOption* temp = New(GetArenaNoVirtual());
+ temp->MergeFrom(*other);
+ other->CopyFrom(*this);
+ InternalSwap(temp);
+ if (GetArenaNoVirtual() == NULL) {
+ delete temp;
+ }
+ }
+}
+void UninterpretedOption::UnsafeArenaSwap(UninterpretedOption* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void UninterpretedOption::InternalSwap(UninterpretedOption* other) {
- name_.UnsafeArenaSwap(&other->name_);
+ using std::swap;
+ name_.InternalSwap(&other->name_);
identifier_value_.Swap(&other->identifier_value_);
string_value_.Swap(&other->string_value_);
aggregate_value_.Swap(&other->aggregate_value_);
- std::swap(positive_int_value_, other->positive_int_value_);
- std::swap(negative_int_value_, other->negative_int_value_);
- std::swap(double_value_, other->double_value_);
- std::swap(_has_bits_[0], other->_has_bits_[0]);
+ swap(positive_int_value_, other->positive_int_value_);
+ swap(negative_int_value_, other->negative_int_value_);
+ swap(double_value_, other->double_value_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- std::swap(_cached_size_, other->_cached_size_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata UninterpretedOption::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[20];
-}
-
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// UninterpretedOption
-
-// repeated .google.protobuf.UninterpretedOption.NamePart name = 2;
-int UninterpretedOption::name_size() const {
- return name_.size();
-}
-void UninterpretedOption::clear_name() {
- name_.Clear();
-}
-const ::google::protobuf::UninterpretedOption_NamePart& UninterpretedOption::name(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.name)
- return name_.Get(index);
-}
-::google::protobuf::UninterpretedOption_NamePart* UninterpretedOption::mutable_name(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.UninterpretedOption.name)
- return name_.Mutable(index);
-}
-::google::protobuf::UninterpretedOption_NamePart* UninterpretedOption::add_name() {
- // @@protoc_insertion_point(field_add:google.protobuf.UninterpretedOption.name)
- return name_.Add();
-}
-::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption_NamePart >*
-UninterpretedOption::mutable_name() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.UninterpretedOption.name)
- return &name_;
-}
-const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption_NamePart >&
-UninterpretedOption::name() const {
- // @@protoc_insertion_point(field_list:google.protobuf.UninterpretedOption.name)
- return name_;
-}
-
-// optional string identifier_value = 3;
-bool UninterpretedOption::has_identifier_value() const {
- return (_has_bits_[0] & 0x00000001u) != 0;
-}
-void UninterpretedOption::set_has_identifier_value() {
- _has_bits_[0] |= 0x00000001u;
-}
-void UninterpretedOption::clear_has_identifier_value() {
- _has_bits_[0] &= ~0x00000001u;
-}
-void UninterpretedOption::clear_identifier_value() {
- identifier_value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_identifier_value();
-}
-const ::std::string& UninterpretedOption::identifier_value() const {
- // @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.identifier_value)
- return identifier_value_.GetNoArena();
-}
-void UninterpretedOption::set_identifier_value(const ::std::string& value) {
- set_has_identifier_value();
- identifier_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.UninterpretedOption.identifier_value)
-}
-void UninterpretedOption::set_identifier_value(const char* value) {
- set_has_identifier_value();
- identifier_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.UninterpretedOption.identifier_value)
-}
-void UninterpretedOption::set_identifier_value(const char* value, size_t size) {
- set_has_identifier_value();
- identifier_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.UninterpretedOption.identifier_value)
-}
-::std::string* UninterpretedOption::mutable_identifier_value() {
- set_has_identifier_value();
- // @@protoc_insertion_point(field_mutable:google.protobuf.UninterpretedOption.identifier_value)
- return identifier_value_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* UninterpretedOption::release_identifier_value() {
- // @@protoc_insertion_point(field_release:google.protobuf.UninterpretedOption.identifier_value)
- clear_has_identifier_value();
- return identifier_value_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void UninterpretedOption::set_allocated_identifier_value(::std::string* identifier_value) {
- if (identifier_value != NULL) {
- set_has_identifier_value();
- } else {
- clear_has_identifier_value();
- }
- identifier_value_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), identifier_value);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.UninterpretedOption.identifier_value)
-}
-
-// optional uint64 positive_int_value = 4;
-bool UninterpretedOption::has_positive_int_value() const {
- return (_has_bits_[0] & 0x00000008u) != 0;
-}
-void UninterpretedOption::set_has_positive_int_value() {
- _has_bits_[0] |= 0x00000008u;
-}
-void UninterpretedOption::clear_has_positive_int_value() {
- _has_bits_[0] &= ~0x00000008u;
-}
-void UninterpretedOption::clear_positive_int_value() {
- positive_int_value_ = GOOGLE_ULONGLONG(0);
- clear_has_positive_int_value();
-}
-::google::protobuf::uint64 UninterpretedOption::positive_int_value() const {
- // @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.positive_int_value)
- return positive_int_value_;
-}
-void UninterpretedOption::set_positive_int_value(::google::protobuf::uint64 value) {
- set_has_positive_int_value();
- positive_int_value_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.UninterpretedOption.positive_int_value)
-}
-
-// optional int64 negative_int_value = 5;
-bool UninterpretedOption::has_negative_int_value() const {
- return (_has_bits_[0] & 0x00000010u) != 0;
-}
-void UninterpretedOption::set_has_negative_int_value() {
- _has_bits_[0] |= 0x00000010u;
-}
-void UninterpretedOption::clear_has_negative_int_value() {
- _has_bits_[0] &= ~0x00000010u;
-}
-void UninterpretedOption::clear_negative_int_value() {
- negative_int_value_ = GOOGLE_LONGLONG(0);
- clear_has_negative_int_value();
-}
-::google::protobuf::int64 UninterpretedOption::negative_int_value() const {
- // @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.negative_int_value)
- return negative_int_value_;
-}
-void UninterpretedOption::set_negative_int_value(::google::protobuf::int64 value) {
- set_has_negative_int_value();
- negative_int_value_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.UninterpretedOption.negative_int_value)
-}
-
-// optional double double_value = 6;
-bool UninterpretedOption::has_double_value() const {
- return (_has_bits_[0] & 0x00000020u) != 0;
-}
-void UninterpretedOption::set_has_double_value() {
- _has_bits_[0] |= 0x00000020u;
-}
-void UninterpretedOption::clear_has_double_value() {
- _has_bits_[0] &= ~0x00000020u;
-}
-void UninterpretedOption::clear_double_value() {
- double_value_ = 0;
- clear_has_double_value();
-}
-double UninterpretedOption::double_value() const {
- // @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.double_value)
- return double_value_;
-}
-void UninterpretedOption::set_double_value(double value) {
- set_has_double_value();
- double_value_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.UninterpretedOption.double_value)
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
}
-// optional bytes string_value = 7;
-bool UninterpretedOption::has_string_value() const {
- return (_has_bits_[0] & 0x00000002u) != 0;
-}
-void UninterpretedOption::set_has_string_value() {
- _has_bits_[0] |= 0x00000002u;
-}
-void UninterpretedOption::clear_has_string_value() {
- _has_bits_[0] &= ~0x00000002u;
-}
-void UninterpretedOption::clear_string_value() {
- string_value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_string_value();
-}
-const ::std::string& UninterpretedOption::string_value() const {
- // @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.string_value)
- return string_value_.GetNoArena();
-}
-void UninterpretedOption::set_string_value(const ::std::string& value) {
- set_has_string_value();
- string_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.UninterpretedOption.string_value)
-}
-void UninterpretedOption::set_string_value(const char* value) {
- set_has_string_value();
- string_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.UninterpretedOption.string_value)
-}
-void UninterpretedOption::set_string_value(const void* value, size_t size) {
- set_has_string_value();
- string_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.UninterpretedOption.string_value)
-}
-::std::string* UninterpretedOption::mutable_string_value() {
- set_has_string_value();
- // @@protoc_insertion_point(field_mutable:google.protobuf.UninterpretedOption.string_value)
- return string_value_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* UninterpretedOption::release_string_value() {
- // @@protoc_insertion_point(field_release:google.protobuf.UninterpretedOption.string_value)
- clear_has_string_value();
- return string_value_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void UninterpretedOption::set_allocated_string_value(::std::string* string_value) {
- if (string_value != NULL) {
- set_has_string_value();
- } else {
- clear_has_string_value();
- }
- string_value_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), string_value);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.UninterpretedOption.string_value)
-}
-
-// optional string aggregate_value = 8;
-bool UninterpretedOption::has_aggregate_value() const {
- return (_has_bits_[0] & 0x00000004u) != 0;
-}
-void UninterpretedOption::set_has_aggregate_value() {
- _has_bits_[0] |= 0x00000004u;
-}
-void UninterpretedOption::clear_has_aggregate_value() {
- _has_bits_[0] &= ~0x00000004u;
-}
-void UninterpretedOption::clear_aggregate_value() {
- aggregate_value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_aggregate_value();
-}
-const ::std::string& UninterpretedOption::aggregate_value() const {
- // @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.aggregate_value)
- return aggregate_value_.GetNoArena();
-}
-void UninterpretedOption::set_aggregate_value(const ::std::string& value) {
- set_has_aggregate_value();
- aggregate_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.UninterpretedOption.aggregate_value)
-}
-void UninterpretedOption::set_aggregate_value(const char* value) {
- set_has_aggregate_value();
- aggregate_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.UninterpretedOption.aggregate_value)
-}
-void UninterpretedOption::set_aggregate_value(const char* value, size_t size) {
- set_has_aggregate_value();
- aggregate_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.UninterpretedOption.aggregate_value)
-}
-::std::string* UninterpretedOption::mutable_aggregate_value() {
- set_has_aggregate_value();
- // @@protoc_insertion_point(field_mutable:google.protobuf.UninterpretedOption.aggregate_value)
- return aggregate_value_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* UninterpretedOption::release_aggregate_value() {
- // @@protoc_insertion_point(field_release:google.protobuf.UninterpretedOption.aggregate_value)
- clear_has_aggregate_value();
- return aggregate_value_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void UninterpretedOption::set_allocated_aggregate_value(::std::string* aggregate_value) {
- if (aggregate_value != NULL) {
- set_has_aggregate_value();
- } else {
- clear_has_aggregate_value();
- }
- aggregate_value_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), aggregate_value);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.UninterpretedOption.aggregate_value)
-}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
+void SourceCodeInfo_Location::InitAsDefaultInstance() {
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int SourceCodeInfo_Location::kPathFieldNumber;
const int SourceCodeInfo_Location::kSpanFieldNumber;
@@ -13565,11 +12639,22 @@ const int SourceCodeInfo_Location::kLeadingDetachedCommentsFieldNumber;
SourceCodeInfo_Location::SourceCodeInfo_Location()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfo_Location();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.SourceCodeInfo.Location)
}
+SourceCodeInfo_Location::SourceCodeInfo_Location(::google::protobuf::Arena* arena)
+ : ::google::protobuf::Message(),
+ _internal_metadata_(arena),
+ path_(arena),
+ span_(arena),
+ leading_detached_comments_(arena) {
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfo_Location();
+ SharedCtor();
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.SourceCodeInfo.Location)
+}
SourceCodeInfo_Location::SourceCodeInfo_Location(const SourceCodeInfo_Location& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
@@ -13581,11 +12666,13 @@ SourceCodeInfo_Location::SourceCodeInfo_Location(const SourceCodeInfo_Location&
_internal_metadata_.MergeFrom(from._internal_metadata_);
leading_comments_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_leading_comments()) {
- leading_comments_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.leading_comments_);
+ leading_comments_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.leading_comments(),
+ GetArenaNoVirtual());
}
trailing_comments_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_trailing_comments()) {
- trailing_comments_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.trailing_comments_);
+ trailing_comments_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.trailing_comments(),
+ GetArenaNoVirtual());
}
// @@protoc_insertion_point(copy_constructor:google.protobuf.SourceCodeInfo.Location)
}
@@ -13602,46 +12689,54 @@ SourceCodeInfo_Location::~SourceCodeInfo_Location() {
}
void SourceCodeInfo_Location::SharedDtor() {
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
leading_comments_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
trailing_comments_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
+void SourceCodeInfo_Location::ArenaDtor(void* object) {
+ SourceCodeInfo_Location* _this = reinterpret_cast< SourceCodeInfo_Location* >(object);
+ (void)_this;
+}
+void SourceCodeInfo_Location::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+}
void SourceCodeInfo_Location::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* SourceCodeInfo_Location::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[21].descriptor;
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const SourceCodeInfo_Location& SourceCodeInfo_Location::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfo_Location();
return *internal_default_instance();
}
SourceCodeInfo_Location* SourceCodeInfo_Location::New(::google::protobuf::Arena* arena) const {
- SourceCodeInfo_Location* n = new SourceCodeInfo_Location;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
+ return ::google::protobuf::Arena::CreateMessage<SourceCodeInfo_Location>(arena);
}
void SourceCodeInfo_Location::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.SourceCodeInfo.Location)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
path_.Clear();
span_.Clear();
leading_detached_comments_.Clear();
- if (_has_bits_[0 / 32] & 3u) {
- if (has_leading_comments()) {
+ cached_has_bits = _has_bits_[0];
+ if (cached_has_bits & 3u) {
+ if (cached_has_bits & 0x00000001u) {
GOOGLE_DCHECK(!leading_comments_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- (*leading_comments_.UnsafeRawStringPointer())->clear();
+ leading_comments_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- if (has_trailing_comments()) {
+ if (cached_has_bits & 0x00000002u) {
GOOGLE_DCHECK(!trailing_comments_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- (*trailing_comments_.UnsafeRawStringPointer())->clear();
+ trailing_comments_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
}
_has_bits_.Clear();
@@ -13660,11 +12755,14 @@ bool SourceCodeInfo_Location::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated int32 path = 1 [packed = true];
case 1: {
- if (tag == 10u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, this->mutable_path())));
- } else if (tag == 8u) {
+ } else if (
+ static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
1, 10u, input, this->mutable_path())));
@@ -13676,11 +12774,14 @@ bool SourceCodeInfo_Location::MergePartialFromCodedStream(
// repeated int32 span = 2 [packed = true];
case 2: {
- if (tag == 18u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, this->mutable_span())));
- } else if (tag == 16u) {
+ } else if (
+ static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
1, 18u, input, this->mutable_span())));
@@ -13692,11 +12793,12 @@ bool SourceCodeInfo_Location::MergePartialFromCodedStream(
// optional string leading_comments = 3;
case 3: {
- if (tag == 26u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_leading_comments()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->leading_comments().data(), this->leading_comments().length(),
+ this->leading_comments().data(), static_cast<int>(this->leading_comments().length()),
::google::protobuf::internal::WireFormat::PARSE,
"google.protobuf.SourceCodeInfo.Location.leading_comments");
} else {
@@ -13707,11 +12809,12 @@ bool SourceCodeInfo_Location::MergePartialFromCodedStream(
// optional string trailing_comments = 4;
case 4: {
- if (tag == 34u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_trailing_comments()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->trailing_comments().data(), this->trailing_comments().length(),
+ this->trailing_comments().data(), static_cast<int>(this->trailing_comments().length()),
::google::protobuf::internal::WireFormat::PARSE,
"google.protobuf.SourceCodeInfo.Location.trailing_comments");
} else {
@@ -13722,12 +12825,13 @@ bool SourceCodeInfo_Location::MergePartialFromCodedStream(
// repeated string leading_detached_comments = 6;
case 6: {
- if (tag == 50u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(50u /* 50 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->add_leading_detached_comments()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->leading_detached_comments(this->leading_detached_comments_size() - 1).data(),
- this->leading_detached_comments(this->leading_detached_comments_size() - 1).length(),
+ static_cast<int>(this->leading_detached_comments(this->leading_detached_comments_size() - 1).length()),
::google::protobuf::internal::WireFormat::PARSE,
"google.protobuf.SourceCodeInfo.Location.leading_detached_comments");
} else {
@@ -13738,13 +12842,11 @@ bool SourceCodeInfo_Location::MergePartialFromCodedStream(
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
- input, tag, mutable_unknown_fields()));
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -13761,12 +12863,16 @@ failure:
void SourceCodeInfo_Location::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.SourceCodeInfo.Location)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// repeated int32 path = 1 [packed = true];
if (this->path_size() > 0) {
::google::protobuf::internal::WireFormatLite::WriteTag(1, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output);
- output->WriteVarint32(_path_cached_byte_size_);
+ output->WriteVarint32(static_cast< ::google::protobuf::uint32>(
+ _path_cached_byte_size_));
}
- for (int i = 0; i < this->path_size(); i++) {
+ for (int i = 0, n = this->path_size(); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteInt32NoTag(
this->path(i), output);
}
@@ -13774,17 +12880,19 @@ void SourceCodeInfo_Location::SerializeWithCachedSizes(
// repeated int32 span = 2 [packed = true];
if (this->span_size() > 0) {
::google::protobuf::internal::WireFormatLite::WriteTag(2, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output);
- output->WriteVarint32(_span_cached_byte_size_);
+ output->WriteVarint32(static_cast< ::google::protobuf::uint32>(
+ _span_cached_byte_size_));
}
- for (int i = 0; i < this->span_size(); i++) {
+ for (int i = 0, n = this->span_size(); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteInt32NoTag(
this->span(i), output);
}
+ cached_has_bits = _has_bits_[0];
// optional string leading_comments = 3;
- if (has_leading_comments()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->leading_comments().data(), this->leading_comments().length(),
+ this->leading_comments().data(), static_cast<int>(this->leading_comments().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.SourceCodeInfo.Location.leading_comments");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -13792,9 +12900,9 @@ void SourceCodeInfo_Location::SerializeWithCachedSizes(
}
// optional string trailing_comments = 4;
- if (has_trailing_comments()) {
+ if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->trailing_comments().data(), this->trailing_comments().length(),
+ this->trailing_comments().data(), static_cast<int>(this->trailing_comments().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.SourceCodeInfo.Location.trailing_comments");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -13802,9 +12910,9 @@ void SourceCodeInfo_Location::SerializeWithCachedSizes(
}
// repeated string leading_detached_comments = 6;
- for (int i = 0; i < this->leading_detached_comments_size(); i++) {
+ for (int i = 0, n = this->leading_detached_comments_size(); i < n; i++) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->leading_detached_comments(i).data(), this->leading_detached_comments(i).length(),
+ this->leading_detached_comments(i).data(), static_cast<int>(this->leading_detached_comments(i).length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.SourceCodeInfo.Location.leading_detached_comments");
::google::protobuf::internal::WireFormatLite::WriteString(
@@ -13813,7 +12921,7 @@ void SourceCodeInfo_Location::SerializeWithCachedSizes(
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- unknown_fields(), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.SourceCodeInfo.Location)
}
@@ -13822,6 +12930,9 @@ void SourceCodeInfo_Location::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.SourceCodeInfo.Location)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// repeated int32 path = 1 [packed = true];
if (this->path_size() > 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray(
@@ -13829,11 +12940,10 @@ void SourceCodeInfo_Location::SerializeWithCachedSizes(
::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,
target);
target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray(
- _path_cached_byte_size_, target);
- }
- for (int i = 0; i < this->path_size(); i++) {
+ static_cast< ::google::protobuf::int32>(
+ _path_cached_byte_size_), target);
target = ::google::protobuf::internal::WireFormatLite::
- WriteInt32NoTagToArray(this->path(i), target);
+ WriteInt32NoTagToArray(this->path_, target);
}
// repeated int32 span = 2 [packed = true];
@@ -13843,17 +12953,17 @@ void SourceCodeInfo_Location::SerializeWithCachedSizes(
::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,
target);
target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray(
- _span_cached_byte_size_, target);
- }
- for (int i = 0; i < this->span_size(); i++) {
+ static_cast< ::google::protobuf::int32>(
+ _span_cached_byte_size_), target);
target = ::google::protobuf::internal::WireFormatLite::
- WriteInt32NoTagToArray(this->span(i), target);
+ WriteInt32NoTagToArray(this->span_, target);
}
+ cached_has_bits = _has_bits_[0];
// optional string leading_comments = 3;
- if (has_leading_comments()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->leading_comments().data(), this->leading_comments().length(),
+ this->leading_comments().data(), static_cast<int>(this->leading_comments().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.SourceCodeInfo.Location.leading_comments");
target =
@@ -13862,9 +12972,9 @@ void SourceCodeInfo_Location::SerializeWithCachedSizes(
}
// optional string trailing_comments = 4;
- if (has_trailing_comments()) {
+ if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->trailing_comments().data(), this->trailing_comments().length(),
+ this->trailing_comments().data(), static_cast<int>(this->trailing_comments().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.SourceCodeInfo.Location.trailing_comments");
target =
@@ -13873,9 +12983,9 @@ void SourceCodeInfo_Location::SerializeWithCachedSizes(
}
// repeated string leading_detached_comments = 6;
- for (int i = 0; i < this->leading_detached_comments_size(); i++) {
+ for (int i = 0, n = this->leading_detached_comments_size(); i < n; i++) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->leading_detached_comments(i).data(), this->leading_detached_comments(i).length(),
+ this->leading_detached_comments(i).data(), static_cast<int>(this->leading_detached_comments(i).length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.SourceCodeInfo.Location.leading_detached_comments");
target = ::google::protobuf::internal::WireFormatLite::
@@ -13884,7 +12994,7 @@ void SourceCodeInfo_Location::SerializeWithCachedSizes(
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- unknown_fields(), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.SourceCodeInfo.Location)
return target;
@@ -13897,19 +13007,16 @@ size_t SourceCodeInfo_Location::ByteSizeLong() const {
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- unknown_fields());
+ _internal_metadata_.unknown_fields());
}
// repeated int32 path = 1 [packed = true];
{
- size_t data_size = 0;
- unsigned int count = this->path_size();
- for (unsigned int i = 0; i < count; i++) {
- data_size += ::google::protobuf::internal::WireFormatLite::
- Int32Size(this->path(i));
- }
+ size_t data_size = ::google::protobuf::internal::WireFormatLite::
+ Int32Size(this->path_);
if (data_size > 0) {
total_size += 1 +
- ::google::protobuf::internal::WireFormatLite::Int32Size(data_size);
+ ::google::protobuf::internal::WireFormatLite::Int32Size(
+ static_cast< ::google::protobuf::int32>(data_size));
}
int cached_size = ::google::protobuf::internal::ToCachedSize(data_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
@@ -13920,15 +13027,12 @@ size_t SourceCodeInfo_Location::ByteSizeLong() const {
// repeated int32 span = 2 [packed = true];
{
- size_t data_size = 0;
- unsigned int count = this->span_size();
- for (unsigned int i = 0; i < count; i++) {
- data_size += ::google::protobuf::internal::WireFormatLite::
- Int32Size(this->span(i));
- }
+ size_t data_size = ::google::protobuf::internal::WireFormatLite::
+ Int32Size(this->span_);
if (data_size > 0) {
total_size += 1 +
- ::google::protobuf::internal::WireFormatLite::Int32Size(data_size);
+ ::google::protobuf::internal::WireFormatLite::Int32Size(
+ static_cast< ::google::protobuf::int32>(data_size));
}
int cached_size = ::google::protobuf::internal::ToCachedSize(data_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
@@ -13940,7 +13044,7 @@ size_t SourceCodeInfo_Location::ByteSizeLong() const {
// repeated string leading_detached_comments = 6;
total_size += 1 *
::google::protobuf::internal::FromIntSize(this->leading_detached_comments_size());
- for (int i = 0; i < this->leading_detached_comments_size(); i++) {
+ for (int i = 0, n = this->leading_detached_comments_size(); i < n; i++) {
total_size += ::google::protobuf::internal::WireFormatLite::StringSize(
this->leading_detached_comments(i));
}
@@ -13987,17 +13091,19 @@ void SourceCodeInfo_Location::MergeFrom(const SourceCodeInfo_Location& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.SourceCodeInfo.Location)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
path_.MergeFrom(from.path_);
span_.MergeFrom(from.span_);
leading_detached_comments_.MergeFrom(from.leading_detached_comments_);
- if (from._has_bits_[0 / 32] & 3u) {
- if (from.has_leading_comments()) {
- set_has_leading_comments();
- leading_comments_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.leading_comments_);
+ cached_has_bits = from._has_bits_[0];
+ if (cached_has_bits & 3u) {
+ if (cached_has_bits & 0x00000001u) {
+ set_leading_comments(from.leading_comments());
}
- if (from.has_trailing_comments()) {
- set_has_trailing_comments();
- trailing_comments_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.trailing_comments_);
+ if (cached_has_bits & 0x00000002u) {
+ set_trailing_comments(from.trailing_comments());
}
}
}
@@ -14022,254 +13128,45 @@ bool SourceCodeInfo_Location::IsInitialized() const {
void SourceCodeInfo_Location::Swap(SourceCodeInfo_Location* other) {
if (other == this) return;
+ if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ InternalSwap(other);
+ } else {
+ SourceCodeInfo_Location* temp = New(GetArenaNoVirtual());
+ temp->MergeFrom(*other);
+ other->CopyFrom(*this);
+ InternalSwap(temp);
+ if (GetArenaNoVirtual() == NULL) {
+ delete temp;
+ }
+ }
+}
+void SourceCodeInfo_Location::UnsafeArenaSwap(SourceCodeInfo_Location* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void SourceCodeInfo_Location::InternalSwap(SourceCodeInfo_Location* other) {
- path_.UnsafeArenaSwap(&other->path_);
- span_.UnsafeArenaSwap(&other->span_);
- leading_detached_comments_.UnsafeArenaSwap(&other->leading_detached_comments_);
+ using std::swap;
+ path_.InternalSwap(&other->path_);
+ span_.InternalSwap(&other->span_);
+ leading_detached_comments_.InternalSwap(&other->leading_detached_comments_);
leading_comments_.Swap(&other->leading_comments_);
trailing_comments_.Swap(&other->trailing_comments_);
- std::swap(_has_bits_[0], other->_has_bits_[0]);
+ swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- std::swap(_cached_size_, other->_cached_size_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata SourceCodeInfo_Location::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[21];
-}
-
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// SourceCodeInfo_Location
-
-// repeated int32 path = 1 [packed = true];
-int SourceCodeInfo_Location::path_size() const {
- return path_.size();
-}
-void SourceCodeInfo_Location::clear_path() {
- path_.Clear();
-}
-::google::protobuf::int32 SourceCodeInfo_Location::path(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.SourceCodeInfo.Location.path)
- return path_.Get(index);
-}
-void SourceCodeInfo_Location::set_path(int index, ::google::protobuf::int32 value) {
- path_.Set(index, value);
- // @@protoc_insertion_point(field_set:google.protobuf.SourceCodeInfo.Location.path)
-}
-void SourceCodeInfo_Location::add_path(::google::protobuf::int32 value) {
- path_.Add(value);
- // @@protoc_insertion_point(field_add:google.protobuf.SourceCodeInfo.Location.path)
-}
-const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >&
-SourceCodeInfo_Location::path() const {
- // @@protoc_insertion_point(field_list:google.protobuf.SourceCodeInfo.Location.path)
- return path_;
-}
-::google::protobuf::RepeatedField< ::google::protobuf::int32 >*
-SourceCodeInfo_Location::mutable_path() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.SourceCodeInfo.Location.path)
- return &path_;
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
}
-// repeated int32 span = 2 [packed = true];
-int SourceCodeInfo_Location::span_size() const {
- return span_.size();
-}
-void SourceCodeInfo_Location::clear_span() {
- span_.Clear();
-}
-::google::protobuf::int32 SourceCodeInfo_Location::span(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.SourceCodeInfo.Location.span)
- return span_.Get(index);
-}
-void SourceCodeInfo_Location::set_span(int index, ::google::protobuf::int32 value) {
- span_.Set(index, value);
- // @@protoc_insertion_point(field_set:google.protobuf.SourceCodeInfo.Location.span)
-}
-void SourceCodeInfo_Location::add_span(::google::protobuf::int32 value) {
- span_.Add(value);
- // @@protoc_insertion_point(field_add:google.protobuf.SourceCodeInfo.Location.span)
-}
-const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >&
-SourceCodeInfo_Location::span() const {
- // @@protoc_insertion_point(field_list:google.protobuf.SourceCodeInfo.Location.span)
- return span_;
-}
-::google::protobuf::RepeatedField< ::google::protobuf::int32 >*
-SourceCodeInfo_Location::mutable_span() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.SourceCodeInfo.Location.span)
- return &span_;
-}
-
-// optional string leading_comments = 3;
-bool SourceCodeInfo_Location::has_leading_comments() const {
- return (_has_bits_[0] & 0x00000001u) != 0;
-}
-void SourceCodeInfo_Location::set_has_leading_comments() {
- _has_bits_[0] |= 0x00000001u;
-}
-void SourceCodeInfo_Location::clear_has_leading_comments() {
- _has_bits_[0] &= ~0x00000001u;
-}
-void SourceCodeInfo_Location::clear_leading_comments() {
- leading_comments_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_leading_comments();
-}
-const ::std::string& SourceCodeInfo_Location::leading_comments() const {
- // @@protoc_insertion_point(field_get:google.protobuf.SourceCodeInfo.Location.leading_comments)
- return leading_comments_.GetNoArena();
-}
-void SourceCodeInfo_Location::set_leading_comments(const ::std::string& value) {
- set_has_leading_comments();
- leading_comments_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.SourceCodeInfo.Location.leading_comments)
-}
-void SourceCodeInfo_Location::set_leading_comments(const char* value) {
- set_has_leading_comments();
- leading_comments_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.SourceCodeInfo.Location.leading_comments)
-}
-void SourceCodeInfo_Location::set_leading_comments(const char* value, size_t size) {
- set_has_leading_comments();
- leading_comments_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.SourceCodeInfo.Location.leading_comments)
-}
-::std::string* SourceCodeInfo_Location::mutable_leading_comments() {
- set_has_leading_comments();
- // @@protoc_insertion_point(field_mutable:google.protobuf.SourceCodeInfo.Location.leading_comments)
- return leading_comments_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* SourceCodeInfo_Location::release_leading_comments() {
- // @@protoc_insertion_point(field_release:google.protobuf.SourceCodeInfo.Location.leading_comments)
- clear_has_leading_comments();
- return leading_comments_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void SourceCodeInfo_Location::set_allocated_leading_comments(::std::string* leading_comments) {
- if (leading_comments != NULL) {
- set_has_leading_comments();
- } else {
- clear_has_leading_comments();
- }
- leading_comments_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), leading_comments);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.SourceCodeInfo.Location.leading_comments)
-}
-
-// optional string trailing_comments = 4;
-bool SourceCodeInfo_Location::has_trailing_comments() const {
- return (_has_bits_[0] & 0x00000002u) != 0;
-}
-void SourceCodeInfo_Location::set_has_trailing_comments() {
- _has_bits_[0] |= 0x00000002u;
-}
-void SourceCodeInfo_Location::clear_has_trailing_comments() {
- _has_bits_[0] &= ~0x00000002u;
-}
-void SourceCodeInfo_Location::clear_trailing_comments() {
- trailing_comments_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_trailing_comments();
-}
-const ::std::string& SourceCodeInfo_Location::trailing_comments() const {
- // @@protoc_insertion_point(field_get:google.protobuf.SourceCodeInfo.Location.trailing_comments)
- return trailing_comments_.GetNoArena();
-}
-void SourceCodeInfo_Location::set_trailing_comments(const ::std::string& value) {
- set_has_trailing_comments();
- trailing_comments_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.SourceCodeInfo.Location.trailing_comments)
-}
-void SourceCodeInfo_Location::set_trailing_comments(const char* value) {
- set_has_trailing_comments();
- trailing_comments_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.SourceCodeInfo.Location.trailing_comments)
-}
-void SourceCodeInfo_Location::set_trailing_comments(const char* value, size_t size) {
- set_has_trailing_comments();
- trailing_comments_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.SourceCodeInfo.Location.trailing_comments)
-}
-::std::string* SourceCodeInfo_Location::mutable_trailing_comments() {
- set_has_trailing_comments();
- // @@protoc_insertion_point(field_mutable:google.protobuf.SourceCodeInfo.Location.trailing_comments)
- return trailing_comments_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* SourceCodeInfo_Location::release_trailing_comments() {
- // @@protoc_insertion_point(field_release:google.protobuf.SourceCodeInfo.Location.trailing_comments)
- clear_has_trailing_comments();
- return trailing_comments_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void SourceCodeInfo_Location::set_allocated_trailing_comments(::std::string* trailing_comments) {
- if (trailing_comments != NULL) {
- set_has_trailing_comments();
- } else {
- clear_has_trailing_comments();
- }
- trailing_comments_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), trailing_comments);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.SourceCodeInfo.Location.trailing_comments)
-}
-
-// repeated string leading_detached_comments = 6;
-int SourceCodeInfo_Location::leading_detached_comments_size() const {
- return leading_detached_comments_.size();
-}
-void SourceCodeInfo_Location::clear_leading_detached_comments() {
- leading_detached_comments_.Clear();
-}
-const ::std::string& SourceCodeInfo_Location::leading_detached_comments(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.SourceCodeInfo.Location.leading_detached_comments)
- return leading_detached_comments_.Get(index);
-}
-::std::string* SourceCodeInfo_Location::mutable_leading_detached_comments(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.SourceCodeInfo.Location.leading_detached_comments)
- return leading_detached_comments_.Mutable(index);
-}
-void SourceCodeInfo_Location::set_leading_detached_comments(int index, const ::std::string& value) {
- // @@protoc_insertion_point(field_set:google.protobuf.SourceCodeInfo.Location.leading_detached_comments)
- leading_detached_comments_.Mutable(index)->assign(value);
-}
-void SourceCodeInfo_Location::set_leading_detached_comments(int index, const char* value) {
- leading_detached_comments_.Mutable(index)->assign(value);
- // @@protoc_insertion_point(field_set_char:google.protobuf.SourceCodeInfo.Location.leading_detached_comments)
-}
-void SourceCodeInfo_Location::set_leading_detached_comments(int index, const char* value, size_t size) {
- leading_detached_comments_.Mutable(index)->assign(
- reinterpret_cast<const char*>(value), size);
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.SourceCodeInfo.Location.leading_detached_comments)
-}
-::std::string* SourceCodeInfo_Location::add_leading_detached_comments() {
- // @@protoc_insertion_point(field_add_mutable:google.protobuf.SourceCodeInfo.Location.leading_detached_comments)
- return leading_detached_comments_.Add();
-}
-void SourceCodeInfo_Location::add_leading_detached_comments(const ::std::string& value) {
- leading_detached_comments_.Add()->assign(value);
- // @@protoc_insertion_point(field_add:google.protobuf.SourceCodeInfo.Location.leading_detached_comments)
-}
-void SourceCodeInfo_Location::add_leading_detached_comments(const char* value) {
- leading_detached_comments_.Add()->assign(value);
- // @@protoc_insertion_point(field_add_char:google.protobuf.SourceCodeInfo.Location.leading_detached_comments)
-}
-void SourceCodeInfo_Location::add_leading_detached_comments(const char* value, size_t size) {
- leading_detached_comments_.Add()->assign(reinterpret_cast<const char*>(value), size);
- // @@protoc_insertion_point(field_add_pointer:google.protobuf.SourceCodeInfo.Location.leading_detached_comments)
-}
-const ::google::protobuf::RepeatedPtrField< ::std::string>&
-SourceCodeInfo_Location::leading_detached_comments() const {
- // @@protoc_insertion_point(field_list:google.protobuf.SourceCodeInfo.Location.leading_detached_comments)
- return leading_detached_comments_;
-}
-::google::protobuf::RepeatedPtrField< ::std::string>*
-SourceCodeInfo_Location::mutable_leading_detached_comments() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.SourceCodeInfo.Location.leading_detached_comments)
- return &leading_detached_comments_;
-}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
+void SourceCodeInfo::InitAsDefaultInstance() {
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int SourceCodeInfo::kLocationFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
@@ -14277,11 +13174,20 @@ const int SourceCodeInfo::kLocationFieldNumber;
SourceCodeInfo::SourceCodeInfo()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfo();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.SourceCodeInfo)
}
+SourceCodeInfo::SourceCodeInfo(::google::protobuf::Arena* arena)
+ : ::google::protobuf::Message(),
+ _internal_metadata_(arena),
+ location_(arena) {
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfo();
+ SharedCtor();
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.SourceCodeInfo)
+}
SourceCodeInfo::SourceCodeInfo(const SourceCodeInfo& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
@@ -14302,33 +13208,40 @@ SourceCodeInfo::~SourceCodeInfo() {
}
void SourceCodeInfo::SharedDtor() {
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
}
+void SourceCodeInfo::ArenaDtor(void* object) {
+ SourceCodeInfo* _this = reinterpret_cast< SourceCodeInfo* >(object);
+ (void)_this;
+}
+void SourceCodeInfo::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+}
void SourceCodeInfo::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* SourceCodeInfo::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[22].descriptor;
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const SourceCodeInfo& SourceCodeInfo::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfo();
return *internal_default_instance();
}
SourceCodeInfo* SourceCodeInfo::New(::google::protobuf::Arena* arena) const {
- SourceCodeInfo* n = new SourceCodeInfo;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
+ return ::google::protobuf::Arena::CreateMessage<SourceCodeInfo>(arena);
}
void SourceCodeInfo::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.SourceCodeInfo)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
location_.Clear();
_has_bits_.Clear();
_internal_metadata_.Clear();
@@ -14346,26 +13259,22 @@ bool SourceCodeInfo::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated .google.protobuf.SourceCodeInfo.Location location = 1;
case 1: {
- if (tag == 10u) {
- DO_(input->IncrementRecursionDepth());
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
- input, add_location()));
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_location()));
} else {
goto handle_unusual;
}
- input->UnsafeDecrementRecursionDepth();
break;
}
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
- input, tag, mutable_unknown_fields()));
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -14382,15 +13291,19 @@ failure:
void SourceCodeInfo::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.SourceCodeInfo)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// repeated .google.protobuf.SourceCodeInfo.Location location = 1;
- for (unsigned int i = 0, n = this->location_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->location_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 1, this->location(i), output);
+ 1, this->location(static_cast<int>(i)), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- unknown_fields(), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.SourceCodeInfo)
}
@@ -14399,16 +13312,20 @@ void SourceCodeInfo::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.SourceCodeInfo)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// repeated .google.protobuf.SourceCodeInfo.Location location = 1;
- for (unsigned int i = 0, n = this->location_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->location_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 1, this->location(i), false, target);
+ InternalWriteMessageToArray(
+ 1, this->location(static_cast<int>(i)), deterministic, target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- unknown_fields(), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.SourceCodeInfo)
return target;
@@ -14421,16 +13338,16 @@ size_t SourceCodeInfo::ByteSizeLong() const {
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- unknown_fields());
+ _internal_metadata_.unknown_fields());
}
// repeated .google.protobuf.SourceCodeInfo.Location location = 1;
{
- unsigned int count = this->location_size();
+ unsigned int count = static_cast<unsigned int>(this->location_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->location(i));
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->location(static_cast<int>(i)));
}
}
@@ -14460,6 +13377,9 @@ void SourceCodeInfo::MergeFrom(const SourceCodeInfo& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.SourceCodeInfo)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
location_.MergeFrom(from.location_);
}
@@ -14483,57 +13403,41 @@ bool SourceCodeInfo::IsInitialized() const {
void SourceCodeInfo::Swap(SourceCodeInfo* other) {
if (other == this) return;
+ if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ InternalSwap(other);
+ } else {
+ SourceCodeInfo* temp = New(GetArenaNoVirtual());
+ temp->MergeFrom(*other);
+ other->CopyFrom(*this);
+ InternalSwap(temp);
+ if (GetArenaNoVirtual() == NULL) {
+ delete temp;
+ }
+ }
+}
+void SourceCodeInfo::UnsafeArenaSwap(SourceCodeInfo* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void SourceCodeInfo::InternalSwap(SourceCodeInfo* other) {
- location_.UnsafeArenaSwap(&other->location_);
- std::swap(_has_bits_[0], other->_has_bits_[0]);
+ using std::swap;
+ location_.InternalSwap(&other->location_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- std::swap(_cached_size_, other->_cached_size_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata SourceCodeInfo::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[22];
-}
-
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// SourceCodeInfo
-
-// repeated .google.protobuf.SourceCodeInfo.Location location = 1;
-int SourceCodeInfo::location_size() const {
- return location_.size();
-}
-void SourceCodeInfo::clear_location() {
- location_.Clear();
-}
-const ::google::protobuf::SourceCodeInfo_Location& SourceCodeInfo::location(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.SourceCodeInfo.location)
- return location_.Get(index);
-}
-::google::protobuf::SourceCodeInfo_Location* SourceCodeInfo::mutable_location(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.SourceCodeInfo.location)
- return location_.Mutable(index);
-}
-::google::protobuf::SourceCodeInfo_Location* SourceCodeInfo::add_location() {
- // @@protoc_insertion_point(field_add:google.protobuf.SourceCodeInfo.location)
- return location_.Add();
-}
-::google::protobuf::RepeatedPtrField< ::google::protobuf::SourceCodeInfo_Location >*
-SourceCodeInfo::mutable_location() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.SourceCodeInfo.location)
- return &location_;
-}
-const ::google::protobuf::RepeatedPtrField< ::google::protobuf::SourceCodeInfo_Location >&
-SourceCodeInfo::location() const {
- // @@protoc_insertion_point(field_list:google.protobuf.SourceCodeInfo.location)
- return location_;
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
+void GeneratedCodeInfo_Annotation::InitAsDefaultInstance() {
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int GeneratedCodeInfo_Annotation::kPathFieldNumber;
const int GeneratedCodeInfo_Annotation::kSourceFileFieldNumber;
@@ -14544,11 +13448,20 @@ const int GeneratedCodeInfo_Annotation::kEndFieldNumber;
GeneratedCodeInfo_Annotation::GeneratedCodeInfo_Annotation()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsGeneratedCodeInfo_Annotation();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.GeneratedCodeInfo.Annotation)
}
+GeneratedCodeInfo_Annotation::GeneratedCodeInfo_Annotation(::google::protobuf::Arena* arena)
+ : ::google::protobuf::Message(),
+ _internal_metadata_(arena),
+ path_(arena) {
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsGeneratedCodeInfo_Annotation();
+ SharedCtor();
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.GeneratedCodeInfo.Annotation)
+}
GeneratedCodeInfo_Annotation::GeneratedCodeInfo_Annotation(const GeneratedCodeInfo_Annotation& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
@@ -14558,19 +13471,21 @@ GeneratedCodeInfo_Annotation::GeneratedCodeInfo_Annotation(const GeneratedCodeIn
_internal_metadata_.MergeFrom(from._internal_metadata_);
source_file_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_source_file()) {
- source_file_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.source_file_);
+ source_file_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.source_file(),
+ GetArenaNoVirtual());
}
::memcpy(&begin_, &from.begin_,
- reinterpret_cast<char*>(&end_) -
- reinterpret_cast<char*>(&begin_) + sizeof(end_));
+ static_cast<size_t>(reinterpret_cast<char*>(&end_) -
+ reinterpret_cast<char*>(&begin_)) + sizeof(end_));
// @@protoc_insertion_point(copy_constructor:google.protobuf.GeneratedCodeInfo.Annotation)
}
void GeneratedCodeInfo_Annotation::SharedCtor() {
_cached_size_ = 0;
source_file_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- ::memset(&begin_, 0, reinterpret_cast<char*>(&end_) -
- reinterpret_cast<char*>(&begin_) + sizeof(end_));
+ ::memset(&begin_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&end_) -
+ reinterpret_cast<char*>(&begin_)) + sizeof(end_));
}
GeneratedCodeInfo_Annotation::~GeneratedCodeInfo_Annotation() {
@@ -14579,42 +13494,51 @@ GeneratedCodeInfo_Annotation::~GeneratedCodeInfo_Annotation() {
}
void GeneratedCodeInfo_Annotation::SharedDtor() {
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
source_file_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
+void GeneratedCodeInfo_Annotation::ArenaDtor(void* object) {
+ GeneratedCodeInfo_Annotation* _this = reinterpret_cast< GeneratedCodeInfo_Annotation* >(object);
+ (void)_this;
+}
+void GeneratedCodeInfo_Annotation::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+}
void GeneratedCodeInfo_Annotation::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* GeneratedCodeInfo_Annotation::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[23].descriptor;
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const GeneratedCodeInfo_Annotation& GeneratedCodeInfo_Annotation::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsGeneratedCodeInfo_Annotation();
return *internal_default_instance();
}
GeneratedCodeInfo_Annotation* GeneratedCodeInfo_Annotation::New(::google::protobuf::Arena* arena) const {
- GeneratedCodeInfo_Annotation* n = new GeneratedCodeInfo_Annotation;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
+ return ::google::protobuf::Arena::CreateMessage<GeneratedCodeInfo_Annotation>(arena);
}
void GeneratedCodeInfo_Annotation::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.GeneratedCodeInfo.Annotation)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
path_.Clear();
- if (has_source_file()) {
+ cached_has_bits = _has_bits_[0];
+ if (cached_has_bits & 0x00000001u) {
GOOGLE_DCHECK(!source_file_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
- (*source_file_.UnsafeRawStringPointer())->clear();
+ source_file_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- if (_has_bits_[0 / 32] & 6u) {
- ::memset(&begin_, 0, reinterpret_cast<char*>(&end_) -
- reinterpret_cast<char*>(&begin_) + sizeof(end_));
+ if (cached_has_bits & 6u) {
+ ::memset(&begin_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&end_) -
+ reinterpret_cast<char*>(&begin_)) + sizeof(end_));
}
_has_bits_.Clear();
_internal_metadata_.Clear();
@@ -14632,11 +13556,14 @@ bool GeneratedCodeInfo_Annotation::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated int32 path = 1 [packed = true];
case 1: {
- if (tag == 10u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, this->mutable_path())));
- } else if (tag == 8u) {
+ } else if (
+ static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
1, 10u, input, this->mutable_path())));
@@ -14648,11 +13575,12 @@ bool GeneratedCodeInfo_Annotation::MergePartialFromCodedStream(
// optional string source_file = 2;
case 2: {
- if (tag == 18u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_source_file()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->source_file().data(), this->source_file().length(),
+ this->source_file().data(), static_cast<int>(this->source_file().length()),
::google::protobuf::internal::WireFormat::PARSE,
"google.protobuf.GeneratedCodeInfo.Annotation.source_file");
} else {
@@ -14663,7 +13591,8 @@ bool GeneratedCodeInfo_Annotation::MergePartialFromCodedStream(
// optional int32 begin = 3;
case 3: {
- if (tag == 24u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) {
set_has_begin();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
@@ -14676,7 +13605,8 @@ bool GeneratedCodeInfo_Annotation::MergePartialFromCodedStream(
// optional int32 end = 4;
case 4: {
- if (tag == 32u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(32u /* 32 & 0xFF */)) {
set_has_end();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
@@ -14689,13 +13619,11 @@ bool GeneratedCodeInfo_Annotation::MergePartialFromCodedStream(
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
- input, tag, mutable_unknown_fields()));
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -14712,20 +13640,25 @@ failure:
void GeneratedCodeInfo_Annotation::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.GeneratedCodeInfo.Annotation)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// repeated int32 path = 1 [packed = true];
if (this->path_size() > 0) {
::google::protobuf::internal::WireFormatLite::WriteTag(1, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output);
- output->WriteVarint32(_path_cached_byte_size_);
+ output->WriteVarint32(static_cast< ::google::protobuf::uint32>(
+ _path_cached_byte_size_));
}
- for (int i = 0; i < this->path_size(); i++) {
+ for (int i = 0, n = this->path_size(); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteInt32NoTag(
this->path(i), output);
}
+ cached_has_bits = _has_bits_[0];
// optional string source_file = 2;
- if (has_source_file()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->source_file().data(), this->source_file().length(),
+ this->source_file().data(), static_cast<int>(this->source_file().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.GeneratedCodeInfo.Annotation.source_file");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -14733,18 +13666,18 @@ void GeneratedCodeInfo_Annotation::SerializeWithCachedSizes(
}
// optional int32 begin = 3;
- if (has_begin()) {
+ if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteInt32(3, this->begin(), output);
}
// optional int32 end = 4;
- if (has_end()) {
+ if (cached_has_bits & 0x00000004u) {
::google::protobuf::internal::WireFormatLite::WriteInt32(4, this->end(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- unknown_fields(), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.GeneratedCodeInfo.Annotation)
}
@@ -14753,6 +13686,9 @@ void GeneratedCodeInfo_Annotation::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.GeneratedCodeInfo.Annotation)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// repeated int32 path = 1 [packed = true];
if (this->path_size() > 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray(
@@ -14760,17 +13696,17 @@ void GeneratedCodeInfo_Annotation::SerializeWithCachedSizes(
::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,
target);
target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray(
- _path_cached_byte_size_, target);
- }
- for (int i = 0; i < this->path_size(); i++) {
+ static_cast< ::google::protobuf::int32>(
+ _path_cached_byte_size_), target);
target = ::google::protobuf::internal::WireFormatLite::
- WriteInt32NoTagToArray(this->path(i), target);
+ WriteInt32NoTagToArray(this->path_, target);
}
+ cached_has_bits = _has_bits_[0];
// optional string source_file = 2;
- if (has_source_file()) {
+ if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
- this->source_file().data(), this->source_file().length(),
+ this->source_file().data(), static_cast<int>(this->source_file().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"google.protobuf.GeneratedCodeInfo.Annotation.source_file");
target =
@@ -14779,18 +13715,18 @@ void GeneratedCodeInfo_Annotation::SerializeWithCachedSizes(
}
// optional int32 begin = 3;
- if (has_begin()) {
+ if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(3, this->begin(), target);
}
// optional int32 end = 4;
- if (has_end()) {
+ if (cached_has_bits & 0x00000004u) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(4, this->end(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- unknown_fields(), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.GeneratedCodeInfo.Annotation)
return target;
@@ -14803,19 +13739,16 @@ size_t GeneratedCodeInfo_Annotation::ByteSizeLong() const {
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- unknown_fields());
+ _internal_metadata_.unknown_fields());
}
// repeated int32 path = 1 [packed = true];
{
- size_t data_size = 0;
- unsigned int count = this->path_size();
- for (unsigned int i = 0; i < count; i++) {
- data_size += ::google::protobuf::internal::WireFormatLite::
- Int32Size(this->path(i));
- }
+ size_t data_size = ::google::protobuf::internal::WireFormatLite::
+ Int32Size(this->path_);
if (data_size > 0) {
total_size += 1 +
- ::google::protobuf::internal::WireFormatLite::Int32Size(data_size);
+ ::google::protobuf::internal::WireFormatLite::Int32Size(
+ static_cast< ::google::protobuf::int32>(data_size));
}
int cached_size = ::google::protobuf::internal::ToCachedSize(data_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
@@ -14873,18 +13806,22 @@ void GeneratedCodeInfo_Annotation::MergeFrom(const GeneratedCodeInfo_Annotation&
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.GeneratedCodeInfo.Annotation)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
path_.MergeFrom(from.path_);
- if (from._has_bits_[0 / 32] & 7u) {
- if (from.has_source_file()) {
- set_has_source_file();
- source_file_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.source_file_);
+ cached_has_bits = from._has_bits_[0];
+ if (cached_has_bits & 7u) {
+ if (cached_has_bits & 0x00000001u) {
+ set_source_file(from.source_file());
}
- if (from.has_begin()) {
- set_begin(from.begin());
+ if (cached_has_bits & 0x00000002u) {
+ begin_ = from.begin_;
}
- if (from.has_end()) {
- set_end(from.end());
+ if (cached_has_bits & 0x00000004u) {
+ end_ = from.end_;
}
+ _has_bits_[0] |= cached_has_bits;
}
}
@@ -14908,162 +13845,44 @@ bool GeneratedCodeInfo_Annotation::IsInitialized() const {
void GeneratedCodeInfo_Annotation::Swap(GeneratedCodeInfo_Annotation* other) {
if (other == this) return;
+ if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ InternalSwap(other);
+ } else {
+ GeneratedCodeInfo_Annotation* temp = New(GetArenaNoVirtual());
+ temp->MergeFrom(*other);
+ other->CopyFrom(*this);
+ InternalSwap(temp);
+ if (GetArenaNoVirtual() == NULL) {
+ delete temp;
+ }
+ }
+}
+void GeneratedCodeInfo_Annotation::UnsafeArenaSwap(GeneratedCodeInfo_Annotation* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void GeneratedCodeInfo_Annotation::InternalSwap(GeneratedCodeInfo_Annotation* other) {
- path_.UnsafeArenaSwap(&other->path_);
+ using std::swap;
+ path_.InternalSwap(&other->path_);
source_file_.Swap(&other->source_file_);
- std::swap(begin_, other->begin_);
- std::swap(end_, other->end_);
- std::swap(_has_bits_[0], other->_has_bits_[0]);
+ swap(begin_, other->begin_);
+ swap(end_, other->end_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- std::swap(_cached_size_, other->_cached_size_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata GeneratedCodeInfo_Annotation::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[23];
-}
-
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// GeneratedCodeInfo_Annotation
-
-// repeated int32 path = 1 [packed = true];
-int GeneratedCodeInfo_Annotation::path_size() const {
- return path_.size();
-}
-void GeneratedCodeInfo_Annotation::clear_path() {
- path_.Clear();
-}
-::google::protobuf::int32 GeneratedCodeInfo_Annotation::path(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.GeneratedCodeInfo.Annotation.path)
- return path_.Get(index);
-}
-void GeneratedCodeInfo_Annotation::set_path(int index, ::google::protobuf::int32 value) {
- path_.Set(index, value);
- // @@protoc_insertion_point(field_set:google.protobuf.GeneratedCodeInfo.Annotation.path)
-}
-void GeneratedCodeInfo_Annotation::add_path(::google::protobuf::int32 value) {
- path_.Add(value);
- // @@protoc_insertion_point(field_add:google.protobuf.GeneratedCodeInfo.Annotation.path)
-}
-const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >&
-GeneratedCodeInfo_Annotation::path() const {
- // @@protoc_insertion_point(field_list:google.protobuf.GeneratedCodeInfo.Annotation.path)
- return path_;
-}
-::google::protobuf::RepeatedField< ::google::protobuf::int32 >*
-GeneratedCodeInfo_Annotation::mutable_path() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.GeneratedCodeInfo.Annotation.path)
- return &path_;
-}
-
-// optional string source_file = 2;
-bool GeneratedCodeInfo_Annotation::has_source_file() const {
- return (_has_bits_[0] & 0x00000001u) != 0;
-}
-void GeneratedCodeInfo_Annotation::set_has_source_file() {
- _has_bits_[0] |= 0x00000001u;
-}
-void GeneratedCodeInfo_Annotation::clear_has_source_file() {
- _has_bits_[0] &= ~0x00000001u;
-}
-void GeneratedCodeInfo_Annotation::clear_source_file() {
- source_file_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_source_file();
-}
-const ::std::string& GeneratedCodeInfo_Annotation::source_file() const {
- // @@protoc_insertion_point(field_get:google.protobuf.GeneratedCodeInfo.Annotation.source_file)
- return source_file_.GetNoArena();
-}
-void GeneratedCodeInfo_Annotation::set_source_file(const ::std::string& value) {
- set_has_source_file();
- source_file_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.GeneratedCodeInfo.Annotation.source_file)
-}
-void GeneratedCodeInfo_Annotation::set_source_file(const char* value) {
- set_has_source_file();
- source_file_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.GeneratedCodeInfo.Annotation.source_file)
-}
-void GeneratedCodeInfo_Annotation::set_source_file(const char* value, size_t size) {
- set_has_source_file();
- source_file_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.GeneratedCodeInfo.Annotation.source_file)
-}
-::std::string* GeneratedCodeInfo_Annotation::mutable_source_file() {
- set_has_source_file();
- // @@protoc_insertion_point(field_mutable:google.protobuf.GeneratedCodeInfo.Annotation.source_file)
- return source_file_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* GeneratedCodeInfo_Annotation::release_source_file() {
- // @@protoc_insertion_point(field_release:google.protobuf.GeneratedCodeInfo.Annotation.source_file)
- clear_has_source_file();
- return source_file_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void GeneratedCodeInfo_Annotation::set_allocated_source_file(::std::string* source_file) {
- if (source_file != NULL) {
- set_has_source_file();
- } else {
- clear_has_source_file();
- }
- source_file_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), source_file);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.GeneratedCodeInfo.Annotation.source_file)
-}
-
-// optional int32 begin = 3;
-bool GeneratedCodeInfo_Annotation::has_begin() const {
- return (_has_bits_[0] & 0x00000002u) != 0;
-}
-void GeneratedCodeInfo_Annotation::set_has_begin() {
- _has_bits_[0] |= 0x00000002u;
-}
-void GeneratedCodeInfo_Annotation::clear_has_begin() {
- _has_bits_[0] &= ~0x00000002u;
-}
-void GeneratedCodeInfo_Annotation::clear_begin() {
- begin_ = 0;
- clear_has_begin();
-}
-::google::protobuf::int32 GeneratedCodeInfo_Annotation::begin() const {
- // @@protoc_insertion_point(field_get:google.protobuf.GeneratedCodeInfo.Annotation.begin)
- return begin_;
-}
-void GeneratedCodeInfo_Annotation::set_begin(::google::protobuf::int32 value) {
- set_has_begin();
- begin_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.GeneratedCodeInfo.Annotation.begin)
-}
-
-// optional int32 end = 4;
-bool GeneratedCodeInfo_Annotation::has_end() const {
- return (_has_bits_[0] & 0x00000004u) != 0;
-}
-void GeneratedCodeInfo_Annotation::set_has_end() {
- _has_bits_[0] |= 0x00000004u;
-}
-void GeneratedCodeInfo_Annotation::clear_has_end() {
- _has_bits_[0] &= ~0x00000004u;
-}
-void GeneratedCodeInfo_Annotation::clear_end() {
- end_ = 0;
- clear_has_end();
-}
-::google::protobuf::int32 GeneratedCodeInfo_Annotation::end() const {
- // @@protoc_insertion_point(field_get:google.protobuf.GeneratedCodeInfo.Annotation.end)
- return end_;
-}
-void GeneratedCodeInfo_Annotation::set_end(::google::protobuf::int32 value) {
- set_has_end();
- end_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.GeneratedCodeInfo.Annotation.end)
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
+void GeneratedCodeInfo::InitAsDefaultInstance() {
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int GeneratedCodeInfo::kAnnotationFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
@@ -15071,11 +13890,20 @@ const int GeneratedCodeInfo::kAnnotationFieldNumber;
GeneratedCodeInfo::GeneratedCodeInfo()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsGeneratedCodeInfo();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.GeneratedCodeInfo)
}
+GeneratedCodeInfo::GeneratedCodeInfo(::google::protobuf::Arena* arena)
+ : ::google::protobuf::Message(),
+ _internal_metadata_(arena),
+ annotation_(arena) {
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsGeneratedCodeInfo();
+ SharedCtor();
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.GeneratedCodeInfo)
+}
GeneratedCodeInfo::GeneratedCodeInfo(const GeneratedCodeInfo& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
@@ -15096,33 +13924,40 @@ GeneratedCodeInfo::~GeneratedCodeInfo() {
}
void GeneratedCodeInfo::SharedDtor() {
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
}
+void GeneratedCodeInfo::ArenaDtor(void* object) {
+ GeneratedCodeInfo* _this = reinterpret_cast< GeneratedCodeInfo* >(object);
+ (void)_this;
+}
+void GeneratedCodeInfo::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+}
void GeneratedCodeInfo::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* GeneratedCodeInfo::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[24].descriptor;
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const GeneratedCodeInfo& GeneratedCodeInfo::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsGeneratedCodeInfo();
return *internal_default_instance();
}
GeneratedCodeInfo* GeneratedCodeInfo::New(::google::protobuf::Arena* arena) const {
- GeneratedCodeInfo* n = new GeneratedCodeInfo;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
+ return ::google::protobuf::Arena::CreateMessage<GeneratedCodeInfo>(arena);
}
void GeneratedCodeInfo::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.GeneratedCodeInfo)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
annotation_.Clear();
_has_bits_.Clear();
_internal_metadata_.Clear();
@@ -15140,26 +13975,22 @@ bool GeneratedCodeInfo::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated .google.protobuf.GeneratedCodeInfo.Annotation annotation = 1;
case 1: {
- if (tag == 10u) {
- DO_(input->IncrementRecursionDepth());
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
- input, add_annotation()));
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_annotation()));
} else {
goto handle_unusual;
}
- input->UnsafeDecrementRecursionDepth();
break;
}
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
- input, tag, mutable_unknown_fields()));
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -15176,15 +14007,19 @@ failure:
void GeneratedCodeInfo::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.GeneratedCodeInfo)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// repeated .google.protobuf.GeneratedCodeInfo.Annotation annotation = 1;
- for (unsigned int i = 0, n = this->annotation_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->annotation_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 1, this->annotation(i), output);
+ 1, this->annotation(static_cast<int>(i)), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- unknown_fields(), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.GeneratedCodeInfo)
}
@@ -15193,16 +14028,20 @@ void GeneratedCodeInfo::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.GeneratedCodeInfo)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// repeated .google.protobuf.GeneratedCodeInfo.Annotation annotation = 1;
- for (unsigned int i = 0, n = this->annotation_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->annotation_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 1, this->annotation(i), false, target);
+ InternalWriteMessageToArray(
+ 1, this->annotation(static_cast<int>(i)), deterministic, target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- unknown_fields(), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.GeneratedCodeInfo)
return target;
@@ -15215,16 +14054,16 @@ size_t GeneratedCodeInfo::ByteSizeLong() const {
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- unknown_fields());
+ _internal_metadata_.unknown_fields());
}
// repeated .google.protobuf.GeneratedCodeInfo.Annotation annotation = 1;
{
- unsigned int count = this->annotation_size();
+ unsigned int count = static_cast<unsigned int>(this->annotation_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->annotation(i));
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->annotation(static_cast<int>(i)));
}
}
@@ -15254,6 +14093,9 @@ void GeneratedCodeInfo::MergeFrom(const GeneratedCodeInfo& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.GeneratedCodeInfo)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
annotation_.MergeFrom(from.annotation_);
}
@@ -15277,57 +14119,38 @@ bool GeneratedCodeInfo::IsInitialized() const {
void GeneratedCodeInfo::Swap(GeneratedCodeInfo* other) {
if (other == this) return;
+ if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ InternalSwap(other);
+ } else {
+ GeneratedCodeInfo* temp = New(GetArenaNoVirtual());
+ temp->MergeFrom(*other);
+ other->CopyFrom(*this);
+ InternalSwap(temp);
+ if (GetArenaNoVirtual() == NULL) {
+ delete temp;
+ }
+ }
+}
+void GeneratedCodeInfo::UnsafeArenaSwap(GeneratedCodeInfo* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void GeneratedCodeInfo::InternalSwap(GeneratedCodeInfo* other) {
- annotation_.UnsafeArenaSwap(&other->annotation_);
- std::swap(_has_bits_[0], other->_has_bits_[0]);
+ using std::swap;
+ annotation_.InternalSwap(&other->annotation_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
- std::swap(_cached_size_, other->_cached_size_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata GeneratedCodeInfo::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[24];
-}
-
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// GeneratedCodeInfo
-
-// repeated .google.protobuf.GeneratedCodeInfo.Annotation annotation = 1;
-int GeneratedCodeInfo::annotation_size() const {
- return annotation_.size();
-}
-void GeneratedCodeInfo::clear_annotation() {
- annotation_.Clear();
-}
-const ::google::protobuf::GeneratedCodeInfo_Annotation& GeneratedCodeInfo::annotation(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.GeneratedCodeInfo.annotation)
- return annotation_.Get(index);
-}
-::google::protobuf::GeneratedCodeInfo_Annotation* GeneratedCodeInfo::mutable_annotation(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.GeneratedCodeInfo.annotation)
- return annotation_.Mutable(index);
-}
-::google::protobuf::GeneratedCodeInfo_Annotation* GeneratedCodeInfo::add_annotation() {
- // @@protoc_insertion_point(field_add:google.protobuf.GeneratedCodeInfo.annotation)
- return annotation_.Add();
-}
-::google::protobuf::RepeatedPtrField< ::google::protobuf::GeneratedCodeInfo_Annotation >*
-GeneratedCodeInfo::mutable_annotation() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.GeneratedCodeInfo.annotation)
- return &annotation_;
-}
-const ::google::protobuf::RepeatedPtrField< ::google::protobuf::GeneratedCodeInfo_Annotation >&
-GeneratedCodeInfo::annotation() const {
- // @@protoc_insertion_point(field_list:google.protobuf.GeneratedCodeInfo.annotation)
- return annotation_;
+ protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
-
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/descriptor.pb.h b/src/google/protobuf/descriptor.pb.h
index 8459b138..ee3ad7d7 100644
--- a/src/google/protobuf/descriptor.pb.h
+++ b/src/google/protobuf/descriptor.pb.h
@@ -8,19 +8,21 @@
#include <google/protobuf/stubs/common.h>
-#if GOOGLE_PROTOBUF_VERSION < 3001000
+#if GOOGLE_PROTOBUF_VERSION < 3004000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3001000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3004000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
+#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
+#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
@@ -29,6 +31,102 @@
#include <google/protobuf/generated_enum_reflection.h>
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
+
+namespace protobuf_google_2fprotobuf_2fdescriptor_2eproto {
+// Internal implementation detail -- do not use these members.
+struct LIBPROTOBUF_EXPORT TableStruct {
+ static const ::google::protobuf::internal::ParseTableField entries[];
+ static const ::google::protobuf::internal::AuxillaryParseTableField aux[];
+ static const ::google::protobuf::internal::ParseTable schema[27];
+ static const ::google::protobuf::internal::FieldMetadata field_metadata[];
+ static const ::google::protobuf::internal::SerializationTable serialization_table[];
+ static const ::google::protobuf::uint32 offsets[];
+};
+void LIBPROTOBUF_EXPORT AddDescriptors();
+void LIBPROTOBUF_EXPORT InitDefaultsFileDescriptorSetImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsFileDescriptorSet();
+void LIBPROTOBUF_EXPORT InitDefaultsFileDescriptorProtoImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsFileDescriptorProto();
+void LIBPROTOBUF_EXPORT InitDefaultsDescriptorProto_ExtensionRangeImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsDescriptorProto_ExtensionRange();
+void LIBPROTOBUF_EXPORT InitDefaultsDescriptorProto_ReservedRangeImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsDescriptorProto_ReservedRange();
+void LIBPROTOBUF_EXPORT InitDefaultsDescriptorProtoImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsDescriptorProto();
+void LIBPROTOBUF_EXPORT InitDefaultsExtensionRangeOptionsImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsExtensionRangeOptions();
+void LIBPROTOBUF_EXPORT InitDefaultsFieldDescriptorProtoImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsFieldDescriptorProto();
+void LIBPROTOBUF_EXPORT InitDefaultsOneofDescriptorProtoImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsOneofDescriptorProto();
+void LIBPROTOBUF_EXPORT InitDefaultsEnumDescriptorProto_EnumReservedRangeImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsEnumDescriptorProto_EnumReservedRange();
+void LIBPROTOBUF_EXPORT InitDefaultsEnumDescriptorProtoImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsEnumDescriptorProto();
+void LIBPROTOBUF_EXPORT InitDefaultsEnumValueDescriptorProtoImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsEnumValueDescriptorProto();
+void LIBPROTOBUF_EXPORT InitDefaultsServiceDescriptorProtoImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsServiceDescriptorProto();
+void LIBPROTOBUF_EXPORT InitDefaultsMethodDescriptorProtoImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsMethodDescriptorProto();
+void LIBPROTOBUF_EXPORT InitDefaultsFileOptionsImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsFileOptions();
+void LIBPROTOBUF_EXPORT InitDefaultsMessageOptionsImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsMessageOptions();
+void LIBPROTOBUF_EXPORT InitDefaultsFieldOptionsImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsFieldOptions();
+void LIBPROTOBUF_EXPORT InitDefaultsOneofOptionsImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsOneofOptions();
+void LIBPROTOBUF_EXPORT InitDefaultsEnumOptionsImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsEnumOptions();
+void LIBPROTOBUF_EXPORT InitDefaultsEnumValueOptionsImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsEnumValueOptions();
+void LIBPROTOBUF_EXPORT InitDefaultsServiceOptionsImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsServiceOptions();
+void LIBPROTOBUF_EXPORT InitDefaultsMethodOptionsImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsMethodOptions();
+void LIBPROTOBUF_EXPORT InitDefaultsUninterpretedOption_NamePartImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsUninterpretedOption_NamePart();
+void LIBPROTOBUF_EXPORT InitDefaultsUninterpretedOptionImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsUninterpretedOption();
+void LIBPROTOBUF_EXPORT InitDefaultsSourceCodeInfo_LocationImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsSourceCodeInfo_Location();
+void LIBPROTOBUF_EXPORT InitDefaultsSourceCodeInfoImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsSourceCodeInfo();
+void LIBPROTOBUF_EXPORT InitDefaultsGeneratedCodeInfo_AnnotationImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsGeneratedCodeInfo_Annotation();
+void LIBPROTOBUF_EXPORT InitDefaultsGeneratedCodeInfoImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsGeneratedCodeInfo();
+inline void LIBPROTOBUF_EXPORT InitDefaults() {
+ InitDefaultsFileDescriptorSet();
+ InitDefaultsFileDescriptorProto();
+ InitDefaultsDescriptorProto_ExtensionRange();
+ InitDefaultsDescriptorProto_ReservedRange();
+ InitDefaultsDescriptorProto();
+ InitDefaultsExtensionRangeOptions();
+ InitDefaultsFieldDescriptorProto();
+ InitDefaultsOneofDescriptorProto();
+ InitDefaultsEnumDescriptorProto_EnumReservedRange();
+ InitDefaultsEnumDescriptorProto();
+ InitDefaultsEnumValueDescriptorProto();
+ InitDefaultsServiceDescriptorProto();
+ InitDefaultsMethodDescriptorProto();
+ InitDefaultsFileOptions();
+ InitDefaultsMessageOptions();
+ InitDefaultsFieldOptions();
+ InitDefaultsOneofOptions();
+ InitDefaultsEnumOptions();
+ InitDefaultsEnumValueOptions();
+ InitDefaultsServiceOptions();
+ InitDefaultsMethodOptions();
+ InitDefaultsUninterpretedOption_NamePart();
+ InitDefaultsUninterpretedOption();
+ InitDefaultsSourceCodeInfo_Location();
+ InitDefaultsSourceCodeInfo();
+ InitDefaultsGeneratedCodeInfo_Annotation();
+ InitDefaultsGeneratedCodeInfo();
+}
+} // namespace protobuf_google_2fprotobuf_2fdescriptor_2eproto
namespace google {
namespace protobuf {
class DescriptorProto;
@@ -43,6 +141,9 @@ LIBPROTOBUF_EXPORT extern DescriptorProto_ReservedRangeDefaultTypeInternal _Desc
class EnumDescriptorProto;
class EnumDescriptorProtoDefaultTypeInternal;
LIBPROTOBUF_EXPORT extern EnumDescriptorProtoDefaultTypeInternal _EnumDescriptorProto_default_instance_;
+class EnumDescriptorProto_EnumReservedRange;
+class EnumDescriptorProto_EnumReservedRangeDefaultTypeInternal;
+LIBPROTOBUF_EXPORT extern EnumDescriptorProto_EnumReservedRangeDefaultTypeInternal _EnumDescriptorProto_EnumReservedRange_default_instance_;
class EnumOptions;
class EnumOptionsDefaultTypeInternal;
LIBPROTOBUF_EXPORT extern EnumOptionsDefaultTypeInternal _EnumOptions_default_instance_;
@@ -52,6 +153,9 @@ LIBPROTOBUF_EXPORT extern EnumValueDescriptorProtoDefaultTypeInternal _EnumValue
class EnumValueOptions;
class EnumValueOptionsDefaultTypeInternal;
LIBPROTOBUF_EXPORT extern EnumValueOptionsDefaultTypeInternal _EnumValueOptions_default_instance_;
+class ExtensionRangeOptions;
+class ExtensionRangeOptionsDefaultTypeInternal;
+LIBPROTOBUF_EXPORT extern ExtensionRangeOptionsDefaultTypeInternal _ExtensionRangeOptions_default_instance_;
class FieldDescriptorProto;
class FieldDescriptorProtoDefaultTypeInternal;
LIBPROTOBUF_EXPORT extern FieldDescriptorProtoDefaultTypeInternal _FieldDescriptorProto_default_instance_;
@@ -108,14 +212,9 @@ class UninterpretedOption_NamePartDefaultTypeInternal;
LIBPROTOBUF_EXPORT extern UninterpretedOption_NamePartDefaultTypeInternal _UninterpretedOption_NamePart_default_instance_;
} // namespace protobuf
} // namespace google
-
namespace google {
namespace protobuf {
-// Internal implementation detail -- do not call these.
-void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
-void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
-
enum FieldDescriptorProto_Type {
FieldDescriptorProto_Type_TYPE_DOUBLE = 1,
FieldDescriptorProto_Type_TYPE_FLOAT = 2,
@@ -264,24 +363,50 @@ class LIBPROTOBUF_EXPORT FileDescriptorSet : public ::google::protobuf::Message
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ FileDescriptorSet(FileDescriptorSet&& from) noexcept
+ : FileDescriptorSet() {
+ *this = ::std::move(from);
+ }
+ inline FileDescriptorSet& operator=(FileDescriptorSet&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
-
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
+ inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ return GetArenaNoVirtual();
+ }
+ inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ return MaybeArenaPtr();
+ }
static const ::google::protobuf::Descriptor* descriptor();
static const FileDescriptorSet& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const FileDescriptorSet* internal_default_instance() {
return reinterpret_cast<const FileDescriptorSet*>(
&_FileDescriptorSet_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 0;
+ void UnsafeArenaSwap(FileDescriptorSet* other);
void Swap(FileDescriptorSet* other);
+ friend void swap(FileDescriptorSet& a, FileDescriptorSet& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -302,22 +427,23 @@ class LIBPROTOBUF_EXPORT FileDescriptorSet : public ::google::protobuf::Message
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const PROTOBUF_FINAL;
void InternalSwap(FileDescriptorSet* other);
+ protected:
+ explicit FileDescriptorSet(::google::protobuf::Arena* arena);
+ private:
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
- return NULL;
+ return _internal_metadata_.arena();
}
inline void* MaybeArenaPtr() const {
- return NULL;
+ return _internal_metadata_.raw_arena_ptr();
}
public:
@@ -343,14 +469,14 @@ class LIBPROTOBUF_EXPORT FileDescriptorSet : public ::google::protobuf::Message
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto > file_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fdescriptor_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorSetImpl();
};
// -------------------------------------------------------------------
@@ -365,24 +491,50 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ FileDescriptorProto(FileDescriptorProto&& from) noexcept
+ : FileDescriptorProto() {
+ *this = ::std::move(from);
+ }
+ inline FileDescriptorProto& operator=(FileDescriptorProto&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
-
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
+ inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ return GetArenaNoVirtual();
+ }
+ inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ return MaybeArenaPtr();
+ }
static const ::google::protobuf::Descriptor* descriptor();
static const FileDescriptorProto& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const FileDescriptorProto* internal_default_instance() {
return reinterpret_cast<const FileDescriptorProto*>(
&_FileDescriptorProto_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 1;
+ void UnsafeArenaSwap(FileDescriptorProto* other);
void Swap(FileDescriptorProto* other);
+ friend void swap(FileDescriptorProto& a, FileDescriptorProto& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -403,22 +555,23 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const PROTOBUF_FINAL;
void InternalSwap(FileDescriptorProto* other);
+ protected:
+ explicit FileDescriptorProto(::google::protobuf::Arena* arena);
+ private:
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
- return NULL;
+ return _internal_metadata_.arena();
}
inline void* MaybeArenaPtr() const {
- return NULL;
+ return _internal_metadata_.raw_arena_ptr();
}
public:
@@ -428,30 +581,6 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag
// accessors -------------------------------------------------------
- // optional string name = 1;
- bool has_name() const;
- void clear_name();
- static const int kNameFieldNumber = 1;
- const ::std::string& name() const;
- void set_name(const ::std::string& value);
- void set_name(const char* value);
- void set_name(const char* value, size_t size);
- ::std::string* mutable_name();
- ::std::string* release_name();
- void set_allocated_name(::std::string* name);
-
- // optional string package = 2;
- bool has_package() const;
- void clear_package();
- static const int kPackageFieldNumber = 2;
- const ::std::string& package() const;
- void set_package(const ::std::string& value);
- void set_package(const char* value);
- void set_package(const char* value, size_t size);
- ::std::string* mutable_package();
- ::std::string* release_package();
- void set_allocated_package(::std::string* package);
-
// repeated string dependency = 3;
int dependency_size() const;
void clear_dependency();
@@ -459,39 +588,21 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag
const ::std::string& dependency(int index) const;
::std::string* mutable_dependency(int index);
void set_dependency(int index, const ::std::string& value);
+ #if LANG_CXX11
+ void set_dependency(int index, ::std::string&& value);
+ #endif
void set_dependency(int index, const char* value);
void set_dependency(int index, const char* value, size_t size);
::std::string* add_dependency();
void add_dependency(const ::std::string& value);
+ #if LANG_CXX11
+ void add_dependency(::std::string&& value);
+ #endif
void add_dependency(const char* value);
void add_dependency(const char* value, size_t size);
const ::google::protobuf::RepeatedPtrField< ::std::string>& dependency() const;
::google::protobuf::RepeatedPtrField< ::std::string>* mutable_dependency();
- // repeated int32 public_dependency = 10;
- int public_dependency_size() const;
- void clear_public_dependency();
- static const int kPublicDependencyFieldNumber = 10;
- ::google::protobuf::int32 public_dependency(int index) const;
- void set_public_dependency(int index, ::google::protobuf::int32 value);
- void add_public_dependency(::google::protobuf::int32 value);
- const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >&
- public_dependency() const;
- ::google::protobuf::RepeatedField< ::google::protobuf::int32 >*
- mutable_public_dependency();
-
- // repeated int32 weak_dependency = 11;
- int weak_dependency_size() const;
- void clear_weak_dependency();
- static const int kWeakDependencyFieldNumber = 11;
- ::google::protobuf::int32 weak_dependency(int index) const;
- void set_weak_dependency(int index, ::google::protobuf::int32 value);
- void add_weak_dependency(::google::protobuf::int32 value);
- const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >&
- weak_dependency() const;
- ::google::protobuf::RepeatedField< ::google::protobuf::int32 >*
- mutable_weak_dependency();
-
// repeated .google.protobuf.DescriptorProto message_type = 4;
int message_type_size() const;
void clear_message_type();
@@ -540,35 +651,131 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >&
extension() const;
+ // repeated int32 public_dependency = 10;
+ int public_dependency_size() const;
+ void clear_public_dependency();
+ static const int kPublicDependencyFieldNumber = 10;
+ ::google::protobuf::int32 public_dependency(int index) const;
+ void set_public_dependency(int index, ::google::protobuf::int32 value);
+ void add_public_dependency(::google::protobuf::int32 value);
+ const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >&
+ public_dependency() const;
+ ::google::protobuf::RepeatedField< ::google::protobuf::int32 >*
+ mutable_public_dependency();
+
+ // repeated int32 weak_dependency = 11;
+ int weak_dependency_size() const;
+ void clear_weak_dependency();
+ static const int kWeakDependencyFieldNumber = 11;
+ ::google::protobuf::int32 weak_dependency(int index) const;
+ void set_weak_dependency(int index, ::google::protobuf::int32 value);
+ void add_weak_dependency(::google::protobuf::int32 value);
+ const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >&
+ weak_dependency() const;
+ ::google::protobuf::RepeatedField< ::google::protobuf::int32 >*
+ mutable_weak_dependency();
+
+ // optional string name = 1;
+ bool has_name() const;
+ void clear_name();
+ static const int kNameFieldNumber = 1;
+ const ::std::string& name() const;
+ void set_name(const ::std::string& value);
+ #if LANG_CXX11
+ void set_name(::std::string&& value);
+ #endif
+ void set_name(const char* value);
+ void set_name(const char* value, size_t size);
+ ::std::string* mutable_name();
+ ::std::string* release_name();
+ void set_allocated_name(::std::string* name);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ ::std::string* unsafe_arena_release_name();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_name(
+ ::std::string* name);
+
+ // optional string package = 2;
+ bool has_package() const;
+ void clear_package();
+ static const int kPackageFieldNumber = 2;
+ const ::std::string& package() const;
+ void set_package(const ::std::string& value);
+ #if LANG_CXX11
+ void set_package(::std::string&& value);
+ #endif
+ void set_package(const char* value);
+ void set_package(const char* value, size_t size);
+ ::std::string* mutable_package();
+ ::std::string* release_package();
+ void set_allocated_package(::std::string* package);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ ::std::string* unsafe_arena_release_package();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_package(
+ ::std::string* package);
+
+ // optional string syntax = 12;
+ bool has_syntax() const;
+ void clear_syntax();
+ static const int kSyntaxFieldNumber = 12;
+ const ::std::string& syntax() const;
+ void set_syntax(const ::std::string& value);
+ #if LANG_CXX11
+ void set_syntax(::std::string&& value);
+ #endif
+ void set_syntax(const char* value);
+ void set_syntax(const char* value, size_t size);
+ ::std::string* mutable_syntax();
+ ::std::string* release_syntax();
+ void set_allocated_syntax(::std::string* syntax);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ ::std::string* unsafe_arena_release_syntax();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_syntax(
+ ::std::string* syntax);
+
// optional .google.protobuf.FileOptions options = 8;
bool has_options() const;
void clear_options();
static const int kOptionsFieldNumber = 8;
+ private:
+ void _slow_mutable_options();
+ public:
const ::google::protobuf::FileOptions& options() const;
- ::google::protobuf::FileOptions* mutable_options();
::google::protobuf::FileOptions* release_options();
+ ::google::protobuf::FileOptions* mutable_options();
void set_allocated_options(::google::protobuf::FileOptions* options);
+ void unsafe_arena_set_allocated_options(
+ ::google::protobuf::FileOptions* options);
+ ::google::protobuf::FileOptions* unsafe_arena_release_options();
// optional .google.protobuf.SourceCodeInfo source_code_info = 9;
bool has_source_code_info() const;
void clear_source_code_info();
static const int kSourceCodeInfoFieldNumber = 9;
+ private:
+ void _slow_mutable_source_code_info();
+ public:
const ::google::protobuf::SourceCodeInfo& source_code_info() const;
- ::google::protobuf::SourceCodeInfo* mutable_source_code_info();
::google::protobuf::SourceCodeInfo* release_source_code_info();
+ ::google::protobuf::SourceCodeInfo* mutable_source_code_info();
void set_allocated_source_code_info(::google::protobuf::SourceCodeInfo* source_code_info);
-
- // optional string syntax = 12;
- bool has_syntax() const;
- void clear_syntax();
- static const int kSyntaxFieldNumber = 12;
- const ::std::string& syntax() const;
- void set_syntax(const ::std::string& value);
- void set_syntax(const char* value);
- void set_syntax(const char* value, size_t size);
- ::std::string* mutable_syntax();
- ::std::string* release_syntax();
- void set_allocated_syntax(::std::string* syntax);
+ void unsafe_arena_set_allocated_source_code_info(
+ ::google::protobuf::SourceCodeInfo* source_code_info);
+ ::google::protobuf::SourceCodeInfo* unsafe_arena_release_source_code_info();
// @@protoc_insertion_point(class_scope:google.protobuf.FileDescriptorProto)
private:
@@ -584,25 +791,25 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag
void clear_has_syntax();
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::RepeatedPtrField< ::std::string> dependency_;
- ::google::protobuf::RepeatedField< ::google::protobuf::int32 > public_dependency_;
- ::google::protobuf::RepeatedField< ::google::protobuf::int32 > weak_dependency_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto > message_type_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto > enum_type_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::ServiceDescriptorProto > service_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto > extension_;
+ ::google::protobuf::RepeatedField< ::google::protobuf::int32 > public_dependency_;
+ ::google::protobuf::RepeatedField< ::google::protobuf::int32 > weak_dependency_;
::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::internal::ArenaStringPtr package_;
::google::protobuf::internal::ArenaStringPtr syntax_;
::google::protobuf::FileOptions* options_;
::google::protobuf::SourceCodeInfo* source_code_info_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fdescriptor_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorProtoImpl();
};
// -------------------------------------------------------------------
@@ -617,24 +824,50 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::proto
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ DescriptorProto_ExtensionRange(DescriptorProto_ExtensionRange&& from) noexcept
+ : DescriptorProto_ExtensionRange() {
+ *this = ::std::move(from);
+ }
+ inline DescriptorProto_ExtensionRange& operator=(DescriptorProto_ExtensionRange&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
-
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
+ inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ return GetArenaNoVirtual();
+ }
+ inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ return MaybeArenaPtr();
+ }
static const ::google::protobuf::Descriptor* descriptor();
static const DescriptorProto_ExtensionRange& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const DescriptorProto_ExtensionRange* internal_default_instance() {
return reinterpret_cast<const DescriptorProto_ExtensionRange*>(
&_DescriptorProto_ExtensionRange_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 2;
+ void UnsafeArenaSwap(DescriptorProto_ExtensionRange* other);
void Swap(DescriptorProto_ExtensionRange* other);
+ friend void swap(DescriptorProto_ExtensionRange& a, DescriptorProto_ExtensionRange& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -655,22 +888,23 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::proto
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const PROTOBUF_FINAL;
void InternalSwap(DescriptorProto_ExtensionRange* other);
+ protected:
+ explicit DescriptorProto_ExtensionRange(::google::protobuf::Arena* arena);
+ private:
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
- return NULL;
+ return _internal_metadata_.arena();
}
inline void* MaybeArenaPtr() const {
- return NULL;
+ return _internal_metadata_.raw_arena_ptr();
}
public:
@@ -680,6 +914,21 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::proto
// accessors -------------------------------------------------------
+ // optional .google.protobuf.ExtensionRangeOptions options = 3;
+ bool has_options() const;
+ void clear_options();
+ static const int kOptionsFieldNumber = 3;
+ private:
+ void _slow_mutable_options();
+ public:
+ const ::google::protobuf::ExtensionRangeOptions& options() const;
+ ::google::protobuf::ExtensionRangeOptions* release_options();
+ ::google::protobuf::ExtensionRangeOptions* mutable_options();
+ void set_allocated_options(::google::protobuf::ExtensionRangeOptions* options);
+ void unsafe_arena_set_allocated_options(
+ ::google::protobuf::ExtensionRangeOptions* options);
+ ::google::protobuf::ExtensionRangeOptions* unsafe_arena_release_options();
+
// optional int32 start = 1;
bool has_start() const;
void clear_start();
@@ -700,17 +949,20 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::proto
void clear_has_start();
void set_has_end();
void clear_has_end();
+ void set_has_options();
+ void clear_has_options();
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
+ ::google::protobuf::ExtensionRangeOptions* options_;
::google::protobuf::int32 start_;
::google::protobuf::int32 end_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fdescriptor_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ExtensionRangeImpl();
};
// -------------------------------------------------------------------
@@ -725,24 +977,50 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ReservedRange : public ::google::protob
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ DescriptorProto_ReservedRange(DescriptorProto_ReservedRange&& from) noexcept
+ : DescriptorProto_ReservedRange() {
+ *this = ::std::move(from);
+ }
+ inline DescriptorProto_ReservedRange& operator=(DescriptorProto_ReservedRange&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
-
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
+ inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ return GetArenaNoVirtual();
+ }
+ inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ return MaybeArenaPtr();
+ }
static const ::google::protobuf::Descriptor* descriptor();
static const DescriptorProto_ReservedRange& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const DescriptorProto_ReservedRange* internal_default_instance() {
return reinterpret_cast<const DescriptorProto_ReservedRange*>(
&_DescriptorProto_ReservedRange_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 3;
+ void UnsafeArenaSwap(DescriptorProto_ReservedRange* other);
void Swap(DescriptorProto_ReservedRange* other);
+ friend void swap(DescriptorProto_ReservedRange& a, DescriptorProto_ReservedRange& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -763,22 +1041,23 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ReservedRange : public ::google::protob
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const PROTOBUF_FINAL;
void InternalSwap(DescriptorProto_ReservedRange* other);
+ protected:
+ explicit DescriptorProto_ReservedRange(::google::protobuf::Arena* arena);
+ private:
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
- return NULL;
+ return _internal_metadata_.arena();
}
inline void* MaybeArenaPtr() const {
- return NULL;
+ return _internal_metadata_.raw_arena_ptr();
}
public:
@@ -810,15 +1089,15 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ReservedRange : public ::google::protob
void clear_has_end();
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::int32 start_;
::google::protobuf::int32 end_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fdescriptor_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ReservedRangeImpl();
};
// -------------------------------------------------------------------
@@ -833,24 +1112,50 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /*
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ DescriptorProto(DescriptorProto&& from) noexcept
+ : DescriptorProto() {
+ *this = ::std::move(from);
+ }
+ inline DescriptorProto& operator=(DescriptorProto&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
-
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
+ inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ return GetArenaNoVirtual();
+ }
+ inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ return MaybeArenaPtr();
+ }
static const ::google::protobuf::Descriptor* descriptor();
static const DescriptorProto& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const DescriptorProto* internal_default_instance() {
return reinterpret_cast<const DescriptorProto*>(
&_DescriptorProto_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 4;
+ void UnsafeArenaSwap(DescriptorProto* other);
void Swap(DescriptorProto* other);
+ friend void swap(DescriptorProto& a, DescriptorProto& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -871,22 +1176,23 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /*
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const PROTOBUF_FINAL;
void InternalSwap(DescriptorProto* other);
+ protected:
+ explicit DescriptorProto(::google::protobuf::Arena* arena);
+ private:
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
- return NULL;
+ return _internal_metadata_.arena();
}
inline void* MaybeArenaPtr() const {
- return NULL;
+ return _internal_metadata_.raw_arena_ptr();
}
public:
@@ -899,18 +1205,6 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /*
// accessors -------------------------------------------------------
- // optional string name = 1;
- bool has_name() const;
- void clear_name();
- static const int kNameFieldNumber = 1;
- const ::std::string& name() const;
- void set_name(const ::std::string& value);
- void set_name(const char* value);
- void set_name(const char* value, size_t size);
- ::std::string* mutable_name();
- ::std::string* release_name();
- void set_allocated_name(::std::string* name);
-
// repeated .google.protobuf.FieldDescriptorProto field = 2;
int field_size() const;
void clear_field();
@@ -923,18 +1217,6 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /*
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >&
field() const;
- // repeated .google.protobuf.FieldDescriptorProto extension = 6;
- int extension_size() const;
- void clear_extension();
- static const int kExtensionFieldNumber = 6;
- const ::google::protobuf::FieldDescriptorProto& extension(int index) const;
- ::google::protobuf::FieldDescriptorProto* mutable_extension(int index);
- ::google::protobuf::FieldDescriptorProto* add_extension();
- ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >*
- mutable_extension();
- const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >&
- extension() const;
-
// repeated .google.protobuf.DescriptorProto nested_type = 3;
int nested_type_size() const;
void clear_nested_type();
@@ -971,6 +1253,18 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /*
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto_ExtensionRange >&
extension_range() const;
+ // repeated .google.protobuf.FieldDescriptorProto extension = 6;
+ int extension_size() const;
+ void clear_extension();
+ static const int kExtensionFieldNumber = 6;
+ const ::google::protobuf::FieldDescriptorProto& extension(int index) const;
+ ::google::protobuf::FieldDescriptorProto* mutable_extension(int index);
+ ::google::protobuf::FieldDescriptorProto* add_extension();
+ ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >*
+ mutable_extension();
+ const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >&
+ extension() const;
+
// repeated .google.protobuf.OneofDescriptorProto oneof_decl = 8;
int oneof_decl_size() const;
void clear_oneof_decl();
@@ -983,15 +1277,6 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /*
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::OneofDescriptorProto >&
oneof_decl() const;
- // optional .google.protobuf.MessageOptions options = 7;
- bool has_options() const;
- void clear_options();
- static const int kOptionsFieldNumber = 7;
- const ::google::protobuf::MessageOptions& options() const;
- ::google::protobuf::MessageOptions* mutable_options();
- ::google::protobuf::MessageOptions* release_options();
- void set_allocated_options(::google::protobuf::MessageOptions* options);
-
// repeated .google.protobuf.DescriptorProto.ReservedRange reserved_range = 9;
int reserved_range_size() const;
void clear_reserved_range();
@@ -1011,15 +1296,60 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /*
const ::std::string& reserved_name(int index) const;
::std::string* mutable_reserved_name(int index);
void set_reserved_name(int index, const ::std::string& value);
+ #if LANG_CXX11
+ void set_reserved_name(int index, ::std::string&& value);
+ #endif
void set_reserved_name(int index, const char* value);
void set_reserved_name(int index, const char* value, size_t size);
::std::string* add_reserved_name();
void add_reserved_name(const ::std::string& value);
+ #if LANG_CXX11
+ void add_reserved_name(::std::string&& value);
+ #endif
void add_reserved_name(const char* value);
void add_reserved_name(const char* value, size_t size);
const ::google::protobuf::RepeatedPtrField< ::std::string>& reserved_name() const;
::google::protobuf::RepeatedPtrField< ::std::string>* mutable_reserved_name();
+ // optional string name = 1;
+ bool has_name() const;
+ void clear_name();
+ static const int kNameFieldNumber = 1;
+ const ::std::string& name() const;
+ void set_name(const ::std::string& value);
+ #if LANG_CXX11
+ void set_name(::std::string&& value);
+ #endif
+ void set_name(const char* value);
+ void set_name(const char* value, size_t size);
+ ::std::string* mutable_name();
+ ::std::string* release_name();
+ void set_allocated_name(::std::string* name);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ ::std::string* unsafe_arena_release_name();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_name(
+ ::std::string* name);
+
+ // optional .google.protobuf.MessageOptions options = 7;
+ bool has_options() const;
+ void clear_options();
+ static const int kOptionsFieldNumber = 7;
+ private:
+ void _slow_mutable_options();
+ public:
+ const ::google::protobuf::MessageOptions& options() const;
+ ::google::protobuf::MessageOptions* release_options();
+ ::google::protobuf::MessageOptions* mutable_options();
+ void set_allocated_options(::google::protobuf::MessageOptions* options);
+ void unsafe_arena_set_allocated_options(
+ ::google::protobuf::MessageOptions* options);
+ ::google::protobuf::MessageOptions* unsafe_arena_release_options();
+
// @@protoc_insertion_point(class_scope:google.protobuf.DescriptorProto)
private:
void set_has_name();
@@ -1028,23 +1358,154 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /*
void clear_has_options();
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto > field_;
- ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto > extension_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto > nested_type_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto > enum_type_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto_ExtensionRange > extension_range_;
+ ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto > extension_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::OneofDescriptorProto > oneof_decl_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto_ReservedRange > reserved_range_;
::google::protobuf::RepeatedPtrField< ::std::string> reserved_name_;
::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::MessageOptions* options_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fdescriptor_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
+ friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProtoImpl();
+};
+// -------------------------------------------------------------------
+
+class LIBPROTOBUF_EXPORT ExtensionRangeOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.ExtensionRangeOptions) */ {
+ public:
+ ExtensionRangeOptions();
+ virtual ~ExtensionRangeOptions();
+ ExtensionRangeOptions(const ExtensionRangeOptions& from);
+
+ inline ExtensionRangeOptions& operator=(const ExtensionRangeOptions& from) {
+ CopyFrom(from);
+ return *this;
+ }
+ #if LANG_CXX11
+ ExtensionRangeOptions(ExtensionRangeOptions&& from) noexcept
+ : ExtensionRangeOptions() {
+ *this = ::std::move(from);
+ }
+
+ inline ExtensionRangeOptions& operator=(ExtensionRangeOptions&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
+ inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
+ return _internal_metadata_.unknown_fields();
+ }
+ inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
+ return _internal_metadata_.mutable_unknown_fields();
+ }
+
+ inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ return GetArenaNoVirtual();
+ }
+ inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ return MaybeArenaPtr();
+ }
+ static const ::google::protobuf::Descriptor* descriptor();
+ static const ExtensionRangeOptions& default_instance();
+
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
+ static inline const ExtensionRangeOptions* internal_default_instance() {
+ return reinterpret_cast<const ExtensionRangeOptions*>(
+ &_ExtensionRangeOptions_default_instance_);
+ }
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 5;
+
+ void UnsafeArenaSwap(ExtensionRangeOptions* other);
+ void Swap(ExtensionRangeOptions* other);
+ friend void swap(ExtensionRangeOptions& a, ExtensionRangeOptions& b) {
+ a.Swap(&b);
+ }
+
+ // implements Message ----------------------------------------------
+
+ inline ExtensionRangeOptions* New() const PROTOBUF_FINAL { return New(NULL); }
+
+ ExtensionRangeOptions* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const ExtensionRangeOptions& from);
+ void MergeFrom(const ExtensionRangeOptions& from);
+ void Clear() PROTOBUF_FINAL;
+ bool IsInitialized() const PROTOBUF_FINAL;
+
+ size_t ByteSizeLong() const PROTOBUF_FINAL;
+ bool MergePartialFromCodedStream(
+ ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ void SerializeWithCachedSizes(
+ ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
+ bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
+ int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ private:
+ void SharedCtor();
+ void SharedDtor();
+ void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void InternalSwap(ExtensionRangeOptions* other);
+ protected:
+ explicit ExtensionRangeOptions(::google::protobuf::Arena* arena);
+ private:
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
+ private:
+ inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
+ return _internal_metadata_.arena();
+ }
+ inline void* MaybeArenaPtr() const {
+ return _internal_metadata_.raw_arena_ptr();
+ }
+ public:
+
+ ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+
+ // nested types ----------------------------------------------------
+
+ // accessors -------------------------------------------------------
+
+ // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
+ int uninterpreted_option_size() const;
+ void clear_uninterpreted_option();
+ static const int kUninterpretedOptionFieldNumber = 999;
+ const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const;
+ ::google::protobuf::UninterpretedOption* mutable_uninterpreted_option(int index);
+ ::google::protobuf::UninterpretedOption* add_uninterpreted_option();
+ ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >*
+ mutable_uninterpreted_option();
+ const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
+ uninterpreted_option() const;
+
+ GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(ExtensionRangeOptions)
+ // @@protoc_insertion_point(class_scope:google.protobuf.ExtensionRangeOptions)
+ private:
+
+ ::google::protobuf::internal::ExtensionSet _extensions_;
+
+ ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
+ ::google::protobuf::internal::HasBits<1> _has_bits_;
+ mutable int _cached_size_;
+ ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_;
+ friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsExtensionRangeOptionsImpl();
};
// -------------------------------------------------------------------
@@ -1059,24 +1520,50 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ FieldDescriptorProto(FieldDescriptorProto&& from) noexcept
+ : FieldDescriptorProto() {
+ *this = ::std::move(from);
+ }
+ inline FieldDescriptorProto& operator=(FieldDescriptorProto&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
-
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
+ inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ return GetArenaNoVirtual();
+ }
+ inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ return MaybeArenaPtr();
+ }
static const ::google::protobuf::Descriptor* descriptor();
static const FieldDescriptorProto& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const FieldDescriptorProto* internal_default_instance() {
return reinterpret_cast<const FieldDescriptorProto*>(
&_FieldDescriptorProto_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 6;
+ void UnsafeArenaSwap(FieldDescriptorProto* other);
void Swap(FieldDescriptorProto* other);
+ friend void swap(FieldDescriptorProto& a, FieldDescriptorProto& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -1097,22 +1584,23 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const PROTOBUF_FINAL;
void InternalSwap(FieldDescriptorProto* other);
+ protected:
+ explicit FieldDescriptorProto(::google::protobuf::Arena* arena);
+ private:
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
- return NULL;
+ return _internal_metadata_.arena();
}
inline void* MaybeArenaPtr() const {
- return NULL;
+ return _internal_metadata_.raw_arena_ptr();
}
public:
@@ -1214,32 +1702,47 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa
static const int kNameFieldNumber = 1;
const ::std::string& name() const;
void set_name(const ::std::string& value);
+ #if LANG_CXX11
+ void set_name(::std::string&& value);
+ #endif
void set_name(const char* value);
void set_name(const char* value, size_t size);
::std::string* mutable_name();
::std::string* release_name();
void set_allocated_name(::std::string* name);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ ::std::string* unsafe_arena_release_name();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_name(
+ ::std::string* name);
- // optional int32 number = 3;
- bool has_number() const;
- void clear_number();
- static const int kNumberFieldNumber = 3;
- ::google::protobuf::int32 number() const;
- void set_number(::google::protobuf::int32 value);
-
- // optional .google.protobuf.FieldDescriptorProto.Label label = 4;
- bool has_label() const;
- void clear_label();
- static const int kLabelFieldNumber = 4;
- ::google::protobuf::FieldDescriptorProto_Label label() const;
- void set_label(::google::protobuf::FieldDescriptorProto_Label value);
-
- // optional .google.protobuf.FieldDescriptorProto.Type type = 5;
- bool has_type() const;
- void clear_type();
- static const int kTypeFieldNumber = 5;
- ::google::protobuf::FieldDescriptorProto_Type type() const;
- void set_type(::google::protobuf::FieldDescriptorProto_Type value);
+ // optional string extendee = 2;
+ bool has_extendee() const;
+ void clear_extendee();
+ static const int kExtendeeFieldNumber = 2;
+ const ::std::string& extendee() const;
+ void set_extendee(const ::std::string& value);
+ #if LANG_CXX11
+ void set_extendee(::std::string&& value);
+ #endif
+ void set_extendee(const char* value);
+ void set_extendee(const char* value, size_t size);
+ ::std::string* mutable_extendee();
+ ::std::string* release_extendee();
+ void set_allocated_extendee(::std::string* extendee);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ ::std::string* unsafe_arena_release_extendee();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_extendee(
+ ::std::string* extendee);
// optional string type_name = 6;
bool has_type_name() const;
@@ -1247,23 +1750,23 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa
static const int kTypeNameFieldNumber = 6;
const ::std::string& type_name() const;
void set_type_name(const ::std::string& value);
+ #if LANG_CXX11
+ void set_type_name(::std::string&& value);
+ #endif
void set_type_name(const char* value);
void set_type_name(const char* value, size_t size);
::std::string* mutable_type_name();
::std::string* release_type_name();
void set_allocated_type_name(::std::string* type_name);
-
- // optional string extendee = 2;
- bool has_extendee() const;
- void clear_extendee();
- static const int kExtendeeFieldNumber = 2;
- const ::std::string& extendee() const;
- void set_extendee(const ::std::string& value);
- void set_extendee(const char* value);
- void set_extendee(const char* value, size_t size);
- ::std::string* mutable_extendee();
- ::std::string* release_extendee();
- void set_allocated_extendee(::std::string* extendee);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ ::std::string* unsafe_arena_release_type_name();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_type_name(
+ ::std::string* type_name);
// optional string default_value = 7;
bool has_default_value() const;
@@ -1271,18 +1774,23 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa
static const int kDefaultValueFieldNumber = 7;
const ::std::string& default_value() const;
void set_default_value(const ::std::string& value);
+ #if LANG_CXX11
+ void set_default_value(::std::string&& value);
+ #endif
void set_default_value(const char* value);
void set_default_value(const char* value, size_t size);
::std::string* mutable_default_value();
::std::string* release_default_value();
void set_allocated_default_value(::std::string* default_value);
-
- // optional int32 oneof_index = 9;
- bool has_oneof_index() const;
- void clear_oneof_index();
- static const int kOneofIndexFieldNumber = 9;
- ::google::protobuf::int32 oneof_index() const;
- void set_oneof_index(::google::protobuf::int32 value);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ ::std::string* unsafe_arena_release_default_value();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_default_value(
+ ::std::string* default_value);
// optional string json_name = 10;
bool has_json_name() const;
@@ -1290,20 +1798,66 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa
static const int kJsonNameFieldNumber = 10;
const ::std::string& json_name() const;
void set_json_name(const ::std::string& value);
+ #if LANG_CXX11
+ void set_json_name(::std::string&& value);
+ #endif
void set_json_name(const char* value);
void set_json_name(const char* value, size_t size);
::std::string* mutable_json_name();
::std::string* release_json_name();
void set_allocated_json_name(::std::string* json_name);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ ::std::string* unsafe_arena_release_json_name();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_json_name(
+ ::std::string* json_name);
// optional .google.protobuf.FieldOptions options = 8;
bool has_options() const;
void clear_options();
static const int kOptionsFieldNumber = 8;
+ private:
+ void _slow_mutable_options();
+ public:
const ::google::protobuf::FieldOptions& options() const;
- ::google::protobuf::FieldOptions* mutable_options();
::google::protobuf::FieldOptions* release_options();
+ ::google::protobuf::FieldOptions* mutable_options();
void set_allocated_options(::google::protobuf::FieldOptions* options);
+ void unsafe_arena_set_allocated_options(
+ ::google::protobuf::FieldOptions* options);
+ ::google::protobuf::FieldOptions* unsafe_arena_release_options();
+
+ // optional int32 number = 3;
+ bool has_number() const;
+ void clear_number();
+ static const int kNumberFieldNumber = 3;
+ ::google::protobuf::int32 number() const;
+ void set_number(::google::protobuf::int32 value);
+
+ // optional int32 oneof_index = 9;
+ bool has_oneof_index() const;
+ void clear_oneof_index();
+ static const int kOneofIndexFieldNumber = 9;
+ ::google::protobuf::int32 oneof_index() const;
+ void set_oneof_index(::google::protobuf::int32 value);
+
+ // optional .google.protobuf.FieldDescriptorProto.Label label = 4;
+ bool has_label() const;
+ void clear_label();
+ static const int kLabelFieldNumber = 4;
+ ::google::protobuf::FieldDescriptorProto_Label label() const;
+ void set_label(::google::protobuf::FieldDescriptorProto_Label value);
+
+ // optional .google.protobuf.FieldDescriptorProto.Type type = 5;
+ bool has_type() const;
+ void clear_type();
+ static const int kTypeFieldNumber = 5;
+ ::google::protobuf::FieldDescriptorProto_Type type() const;
+ void set_type(::google::protobuf::FieldDescriptorProto_Type value);
// @@protoc_insertion_point(class_scope:google.protobuf.FieldDescriptorProto)
private:
@@ -1329,11 +1883,14 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa
void clear_has_options();
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::internal::ArenaStringPtr name_;
- ::google::protobuf::internal::ArenaStringPtr type_name_;
::google::protobuf::internal::ArenaStringPtr extendee_;
+ ::google::protobuf::internal::ArenaStringPtr type_name_;
::google::protobuf::internal::ArenaStringPtr default_value_;
::google::protobuf::internal::ArenaStringPtr json_name_;
::google::protobuf::FieldOptions* options_;
@@ -1341,11 +1898,8 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa
::google::protobuf::int32 oneof_index_;
int label_;
int type_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fdescriptor_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldDescriptorProtoImpl();
};
// -------------------------------------------------------------------
@@ -1360,24 +1914,50 @@ class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Messa
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ OneofDescriptorProto(OneofDescriptorProto&& from) noexcept
+ : OneofDescriptorProto() {
+ *this = ::std::move(from);
+ }
+ inline OneofDescriptorProto& operator=(OneofDescriptorProto&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
-
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
+ inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ return GetArenaNoVirtual();
+ }
+ inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ return MaybeArenaPtr();
+ }
static const ::google::protobuf::Descriptor* descriptor();
static const OneofDescriptorProto& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const OneofDescriptorProto* internal_default_instance() {
return reinterpret_cast<const OneofDescriptorProto*>(
&_OneofDescriptorProto_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 7;
+ void UnsafeArenaSwap(OneofDescriptorProto* other);
void Swap(OneofDescriptorProto* other);
+ friend void swap(OneofDescriptorProto& a, OneofDescriptorProto& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -1398,22 +1978,23 @@ class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Messa
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const PROTOBUF_FINAL;
void InternalSwap(OneofDescriptorProto* other);
+ protected:
+ explicit OneofDescriptorProto(::google::protobuf::Arena* arena);
+ private:
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
- return NULL;
+ return _internal_metadata_.arena();
}
inline void* MaybeArenaPtr() const {
- return NULL;
+ return _internal_metadata_.raw_arena_ptr();
}
public:
@@ -1429,20 +2010,38 @@ class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Messa
static const int kNameFieldNumber = 1;
const ::std::string& name() const;
void set_name(const ::std::string& value);
+ #if LANG_CXX11
+ void set_name(::std::string&& value);
+ #endif
void set_name(const char* value);
void set_name(const char* value, size_t size);
::std::string* mutable_name();
::std::string* release_name();
void set_allocated_name(::std::string* name);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ ::std::string* unsafe_arena_release_name();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_name(
+ ::std::string* name);
// optional .google.protobuf.OneofOptions options = 2;
bool has_options() const;
void clear_options();
static const int kOptionsFieldNumber = 2;
+ private:
+ void _slow_mutable_options();
+ public:
const ::google::protobuf::OneofOptions& options() const;
- ::google::protobuf::OneofOptions* mutable_options();
::google::protobuf::OneofOptions* release_options();
+ ::google::protobuf::OneofOptions* mutable_options();
void set_allocated_options(::google::protobuf::OneofOptions* options);
+ void unsafe_arena_set_allocated_options(
+ ::google::protobuf::OneofOptions* options);
+ ::google::protobuf::OneofOptions* unsafe_arena_release_options();
// @@protoc_insertion_point(class_scope:google.protobuf.OneofDescriptorProto)
private:
@@ -1452,15 +2051,150 @@ class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Messa
void clear_has_options();
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::OneofOptions* options_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fdescriptor_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
+ friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofDescriptorProtoImpl();
+};
+// -------------------------------------------------------------------
+
+class LIBPROTOBUF_EXPORT EnumDescriptorProto_EnumReservedRange : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumDescriptorProto.EnumReservedRange) */ {
+ public:
+ EnumDescriptorProto_EnumReservedRange();
+ virtual ~EnumDescriptorProto_EnumReservedRange();
+
+ EnumDescriptorProto_EnumReservedRange(const EnumDescriptorProto_EnumReservedRange& from);
+
+ inline EnumDescriptorProto_EnumReservedRange& operator=(const EnumDescriptorProto_EnumReservedRange& from) {
+ CopyFrom(from);
+ return *this;
+ }
+ #if LANG_CXX11
+ EnumDescriptorProto_EnumReservedRange(EnumDescriptorProto_EnumReservedRange&& from) noexcept
+ : EnumDescriptorProto_EnumReservedRange() {
+ *this = ::std::move(from);
+ }
+
+ inline EnumDescriptorProto_EnumReservedRange& operator=(EnumDescriptorProto_EnumReservedRange&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
+ inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
+ return _internal_metadata_.unknown_fields();
+ }
+ inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
+ return _internal_metadata_.mutable_unknown_fields();
+ }
+
+ inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ return GetArenaNoVirtual();
+ }
+ inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ return MaybeArenaPtr();
+ }
+ static const ::google::protobuf::Descriptor* descriptor();
+ static const EnumDescriptorProto_EnumReservedRange& default_instance();
+
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
+ static inline const EnumDescriptorProto_EnumReservedRange* internal_default_instance() {
+ return reinterpret_cast<const EnumDescriptorProto_EnumReservedRange*>(
+ &_EnumDescriptorProto_EnumReservedRange_default_instance_);
+ }
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 8;
+
+ void UnsafeArenaSwap(EnumDescriptorProto_EnumReservedRange* other);
+ void Swap(EnumDescriptorProto_EnumReservedRange* other);
+ friend void swap(EnumDescriptorProto_EnumReservedRange& a, EnumDescriptorProto_EnumReservedRange& b) {
+ a.Swap(&b);
+ }
+
+ // implements Message ----------------------------------------------
+
+ inline EnumDescriptorProto_EnumReservedRange* New() const PROTOBUF_FINAL { return New(NULL); }
+
+ EnumDescriptorProto_EnumReservedRange* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
+ void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
+ void CopyFrom(const EnumDescriptorProto_EnumReservedRange& from);
+ void MergeFrom(const EnumDescriptorProto_EnumReservedRange& from);
+ void Clear() PROTOBUF_FINAL;
+ bool IsInitialized() const PROTOBUF_FINAL;
+
+ size_t ByteSizeLong() const PROTOBUF_FINAL;
+ bool MergePartialFromCodedStream(
+ ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
+ void SerializeWithCachedSizes(
+ ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
+ ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
+ bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
+ int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
+ private:
+ void SharedCtor();
+ void SharedDtor();
+ void SetCachedSize(int size) const PROTOBUF_FINAL;
+ void InternalSwap(EnumDescriptorProto_EnumReservedRange* other);
+ protected:
+ explicit EnumDescriptorProto_EnumReservedRange(::google::protobuf::Arena* arena);
+ private:
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
+ private:
+ inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
+ return _internal_metadata_.arena();
+ }
+ inline void* MaybeArenaPtr() const {
+ return _internal_metadata_.raw_arena_ptr();
+ }
+ public:
+
+ ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
+
+ // nested types ----------------------------------------------------
+
+ // accessors -------------------------------------------------------
+
+ // optional int32 start = 1;
+ bool has_start() const;
+ void clear_start();
+ static const int kStartFieldNumber = 1;
+ ::google::protobuf::int32 start() const;
+ void set_start(::google::protobuf::int32 value);
+
+ // optional int32 end = 2;
+ bool has_end() const;
+ void clear_end();
+ static const int kEndFieldNumber = 2;
+ ::google::protobuf::int32 end() const;
+ void set_end(::google::protobuf::int32 value);
+
+ // @@protoc_insertion_point(class_scope:google.protobuf.EnumDescriptorProto.EnumReservedRange)
+ private:
+ void set_has_start();
+ void clear_has_start();
+ void set_has_end();
+ void clear_has_end();
+ ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
+ ::google::protobuf::internal::HasBits<1> _has_bits_;
+ mutable int _cached_size_;
+ ::google::protobuf::int32 start_;
+ ::google::protobuf::int32 end_;
+ friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto_EnumReservedRangeImpl();
};
// -------------------------------------------------------------------
@@ -1475,24 +2209,50 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ EnumDescriptorProto(EnumDescriptorProto&& from) noexcept
+ : EnumDescriptorProto() {
+ *this = ::std::move(from);
+ }
+ inline EnumDescriptorProto& operator=(EnumDescriptorProto&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
-
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
+ inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ return GetArenaNoVirtual();
+ }
+ inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ return MaybeArenaPtr();
+ }
static const ::google::protobuf::Descriptor* descriptor();
static const EnumDescriptorProto& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const EnumDescriptorProto* internal_default_instance() {
return reinterpret_cast<const EnumDescriptorProto*>(
&_EnumDescriptorProto_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 9;
+ void UnsafeArenaSwap(EnumDescriptorProto* other);
void Swap(EnumDescriptorProto* other);
+ friend void swap(EnumDescriptorProto& a, EnumDescriptorProto& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -1513,22 +2273,23 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const PROTOBUF_FINAL;
void InternalSwap(EnumDescriptorProto* other);
+ protected:
+ explicit EnumDescriptorProto(::google::protobuf::Arena* arena);
+ private:
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
- return NULL;
+ return _internal_metadata_.arena();
}
inline void* MaybeArenaPtr() const {
- return NULL;
+ return _internal_metadata_.raw_arena_ptr();
}
public:
@@ -1536,19 +2297,9 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag
// nested types ----------------------------------------------------
- // accessors -------------------------------------------------------
+ typedef EnumDescriptorProto_EnumReservedRange EnumReservedRange;
- // optional string name = 1;
- bool has_name() const;
- void clear_name();
- static const int kNameFieldNumber = 1;
- const ::std::string& name() const;
- void set_name(const ::std::string& value);
- void set_name(const char* value);
- void set_name(const char* value, size_t size);
- ::std::string* mutable_name();
- ::std::string* release_name();
- void set_allocated_name(::std::string* name);
+ // accessors -------------------------------------------------------
// repeated .google.protobuf.EnumValueDescriptorProto value = 2;
int value_size() const;
@@ -1562,14 +2313,78 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumValueDescriptorProto >&
value() const;
+ // repeated .google.protobuf.EnumDescriptorProto.EnumReservedRange reserved_range = 4;
+ int reserved_range_size() const;
+ void clear_reserved_range();
+ static const int kReservedRangeFieldNumber = 4;
+ const ::google::protobuf::EnumDescriptorProto_EnumReservedRange& reserved_range(int index) const;
+ ::google::protobuf::EnumDescriptorProto_EnumReservedRange* mutable_reserved_range(int index);
+ ::google::protobuf::EnumDescriptorProto_EnumReservedRange* add_reserved_range();
+ ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto_EnumReservedRange >*
+ mutable_reserved_range();
+ const ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto_EnumReservedRange >&
+ reserved_range() const;
+
+ // repeated string reserved_name = 5;
+ int reserved_name_size() const;
+ void clear_reserved_name();
+ static const int kReservedNameFieldNumber = 5;
+ const ::std::string& reserved_name(int index) const;
+ ::std::string* mutable_reserved_name(int index);
+ void set_reserved_name(int index, const ::std::string& value);
+ #if LANG_CXX11
+ void set_reserved_name(int index, ::std::string&& value);
+ #endif
+ void set_reserved_name(int index, const char* value);
+ void set_reserved_name(int index, const char* value, size_t size);
+ ::std::string* add_reserved_name();
+ void add_reserved_name(const ::std::string& value);
+ #if LANG_CXX11
+ void add_reserved_name(::std::string&& value);
+ #endif
+ void add_reserved_name(const char* value);
+ void add_reserved_name(const char* value, size_t size);
+ const ::google::protobuf::RepeatedPtrField< ::std::string>& reserved_name() const;
+ ::google::protobuf::RepeatedPtrField< ::std::string>* mutable_reserved_name();
+
+ // optional string name = 1;
+ bool has_name() const;
+ void clear_name();
+ static const int kNameFieldNumber = 1;
+ const ::std::string& name() const;
+ void set_name(const ::std::string& value);
+ #if LANG_CXX11
+ void set_name(::std::string&& value);
+ #endif
+ void set_name(const char* value);
+ void set_name(const char* value, size_t size);
+ ::std::string* mutable_name();
+ ::std::string* release_name();
+ void set_allocated_name(::std::string* name);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ ::std::string* unsafe_arena_release_name();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_name(
+ ::std::string* name);
+
// optional .google.protobuf.EnumOptions options = 3;
bool has_options() const;
void clear_options();
static const int kOptionsFieldNumber = 3;
+ private:
+ void _slow_mutable_options();
+ public:
const ::google::protobuf::EnumOptions& options() const;
- ::google::protobuf::EnumOptions* mutable_options();
::google::protobuf::EnumOptions* release_options();
+ ::google::protobuf::EnumOptions* mutable_options();
void set_allocated_options(::google::protobuf::EnumOptions* options);
+ void unsafe_arena_set_allocated_options(
+ ::google::protobuf::EnumOptions* options);
+ ::google::protobuf::EnumOptions* unsafe_arena_release_options();
// @@protoc_insertion_point(class_scope:google.protobuf.EnumDescriptorProto)
private:
@@ -1579,16 +2394,18 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag
void clear_has_options();
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumValueDescriptorProto > value_;
+ ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto_EnumReservedRange > reserved_range_;
+ ::google::protobuf::RepeatedPtrField< ::std::string> reserved_name_;
::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::EnumOptions* options_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fdescriptor_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProtoImpl();
};
// -------------------------------------------------------------------
@@ -1603,24 +2420,50 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::M
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ EnumValueDescriptorProto(EnumValueDescriptorProto&& from) noexcept
+ : EnumValueDescriptorProto() {
+ *this = ::std::move(from);
+ }
+ inline EnumValueDescriptorProto& operator=(EnumValueDescriptorProto&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
-
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
+ inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ return GetArenaNoVirtual();
+ }
+ inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ return MaybeArenaPtr();
+ }
static const ::google::protobuf::Descriptor* descriptor();
static const EnumValueDescriptorProto& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const EnumValueDescriptorProto* internal_default_instance() {
return reinterpret_cast<const EnumValueDescriptorProto*>(
&_EnumValueDescriptorProto_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 10;
+ void UnsafeArenaSwap(EnumValueDescriptorProto* other);
void Swap(EnumValueDescriptorProto* other);
+ friend void swap(EnumValueDescriptorProto& a, EnumValueDescriptorProto& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -1641,22 +2484,23 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::M
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const PROTOBUF_FINAL;
void InternalSwap(EnumValueDescriptorProto* other);
+ protected:
+ explicit EnumValueDescriptorProto(::google::protobuf::Arena* arena);
+ private:
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
- return NULL;
+ return _internal_metadata_.arena();
}
inline void* MaybeArenaPtr() const {
- return NULL;
+ return _internal_metadata_.raw_arena_ptr();
}
public:
@@ -1672,27 +2516,45 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::M
static const int kNameFieldNumber = 1;
const ::std::string& name() const;
void set_name(const ::std::string& value);
+ #if LANG_CXX11
+ void set_name(::std::string&& value);
+ #endif
void set_name(const char* value);
void set_name(const char* value, size_t size);
::std::string* mutable_name();
::std::string* release_name();
void set_allocated_name(::std::string* name);
-
- // optional int32 number = 2;
- bool has_number() const;
- void clear_number();
- static const int kNumberFieldNumber = 2;
- ::google::protobuf::int32 number() const;
- void set_number(::google::protobuf::int32 value);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ ::std::string* unsafe_arena_release_name();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_name(
+ ::std::string* name);
// optional .google.protobuf.EnumValueOptions options = 3;
bool has_options() const;
void clear_options();
static const int kOptionsFieldNumber = 3;
+ private:
+ void _slow_mutable_options();
+ public:
const ::google::protobuf::EnumValueOptions& options() const;
- ::google::protobuf::EnumValueOptions* mutable_options();
::google::protobuf::EnumValueOptions* release_options();
+ ::google::protobuf::EnumValueOptions* mutable_options();
void set_allocated_options(::google::protobuf::EnumValueOptions* options);
+ void unsafe_arena_set_allocated_options(
+ ::google::protobuf::EnumValueOptions* options);
+ ::google::protobuf::EnumValueOptions* unsafe_arena_release_options();
+
+ // optional int32 number = 2;
+ bool has_number() const;
+ void clear_number();
+ static const int kNumberFieldNumber = 2;
+ ::google::protobuf::int32 number() const;
+ void set_number(::google::protobuf::int32 value);
// @@protoc_insertion_point(class_scope:google.protobuf.EnumValueDescriptorProto)
private:
@@ -1704,16 +2566,16 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::M
void clear_has_options();
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::EnumValueOptions* options_;
::google::protobuf::int32 number_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fdescriptor_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueDescriptorProtoImpl();
};
// -------------------------------------------------------------------
@@ -1728,24 +2590,50 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ ServiceDescriptorProto(ServiceDescriptorProto&& from) noexcept
+ : ServiceDescriptorProto() {
+ *this = ::std::move(from);
+ }
+ inline ServiceDescriptorProto& operator=(ServiceDescriptorProto&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
-
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
+ inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ return GetArenaNoVirtual();
+ }
+ inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ return MaybeArenaPtr();
+ }
static const ::google::protobuf::Descriptor* descriptor();
static const ServiceDescriptorProto& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const ServiceDescriptorProto* internal_default_instance() {
return reinterpret_cast<const ServiceDescriptorProto*>(
&_ServiceDescriptorProto_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 11;
+ void UnsafeArenaSwap(ServiceDescriptorProto* other);
void Swap(ServiceDescriptorProto* other);
+ friend void swap(ServiceDescriptorProto& a, ServiceDescriptorProto& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -1766,22 +2654,23 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const PROTOBUF_FINAL;
void InternalSwap(ServiceDescriptorProto* other);
+ protected:
+ explicit ServiceDescriptorProto(::google::protobuf::Arena* arena);
+ private:
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
- return NULL;
+ return _internal_metadata_.arena();
}
inline void* MaybeArenaPtr() const {
- return NULL;
+ return _internal_metadata_.raw_arena_ptr();
}
public:
@@ -1791,18 +2680,6 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes
// accessors -------------------------------------------------------
- // optional string name = 1;
- bool has_name() const;
- void clear_name();
- static const int kNameFieldNumber = 1;
- const ::std::string& name() const;
- void set_name(const ::std::string& value);
- void set_name(const char* value);
- void set_name(const char* value, size_t size);
- ::std::string* mutable_name();
- ::std::string* release_name();
- void set_allocated_name(::std::string* name);
-
// repeated .google.protobuf.MethodDescriptorProto method = 2;
int method_size() const;
void clear_method();
@@ -1815,14 +2692,44 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::MethodDescriptorProto >&
method() const;
+ // optional string name = 1;
+ bool has_name() const;
+ void clear_name();
+ static const int kNameFieldNumber = 1;
+ const ::std::string& name() const;
+ void set_name(const ::std::string& value);
+ #if LANG_CXX11
+ void set_name(::std::string&& value);
+ #endif
+ void set_name(const char* value);
+ void set_name(const char* value, size_t size);
+ ::std::string* mutable_name();
+ ::std::string* release_name();
+ void set_allocated_name(::std::string* name);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ ::std::string* unsafe_arena_release_name();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_name(
+ ::std::string* name);
+
// optional .google.protobuf.ServiceOptions options = 3;
bool has_options() const;
void clear_options();
static const int kOptionsFieldNumber = 3;
+ private:
+ void _slow_mutable_options();
+ public:
const ::google::protobuf::ServiceOptions& options() const;
- ::google::protobuf::ServiceOptions* mutable_options();
::google::protobuf::ServiceOptions* release_options();
+ ::google::protobuf::ServiceOptions* mutable_options();
void set_allocated_options(::google::protobuf::ServiceOptions* options);
+ void unsafe_arena_set_allocated_options(
+ ::google::protobuf::ServiceOptions* options);
+ ::google::protobuf::ServiceOptions* unsafe_arena_release_options();
// @@protoc_insertion_point(class_scope:google.protobuf.ServiceDescriptorProto)
private:
@@ -1832,16 +2739,16 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes
void clear_has_options();
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::MethodDescriptorProto > method_;
::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::ServiceOptions* options_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fdescriptor_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceDescriptorProtoImpl();
};
// -------------------------------------------------------------------
@@ -1856,24 +2763,50 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ MethodDescriptorProto(MethodDescriptorProto&& from) noexcept
+ : MethodDescriptorProto() {
+ *this = ::std::move(from);
+ }
+ inline MethodDescriptorProto& operator=(MethodDescriptorProto&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
-
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
+ inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ return GetArenaNoVirtual();
+ }
+ inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ return MaybeArenaPtr();
+ }
static const ::google::protobuf::Descriptor* descriptor();
static const MethodDescriptorProto& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const MethodDescriptorProto* internal_default_instance() {
return reinterpret_cast<const MethodDescriptorProto*>(
&_MethodDescriptorProto_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 12;
+ void UnsafeArenaSwap(MethodDescriptorProto* other);
void Swap(MethodDescriptorProto* other);
+ friend void swap(MethodDescriptorProto& a, MethodDescriptorProto& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -1894,22 +2827,23 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const PROTOBUF_FINAL;
void InternalSwap(MethodDescriptorProto* other);
+ protected:
+ explicit MethodDescriptorProto(::google::protobuf::Arena* arena);
+ private:
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
- return NULL;
+ return _internal_metadata_.arena();
}
inline void* MaybeArenaPtr() const {
- return NULL;
+ return _internal_metadata_.raw_arena_ptr();
}
public:
@@ -1925,11 +2859,23 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess
static const int kNameFieldNumber = 1;
const ::std::string& name() const;
void set_name(const ::std::string& value);
+ #if LANG_CXX11
+ void set_name(::std::string&& value);
+ #endif
void set_name(const char* value);
void set_name(const char* value, size_t size);
::std::string* mutable_name();
::std::string* release_name();
void set_allocated_name(::std::string* name);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ ::std::string* unsafe_arena_release_name();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_name(
+ ::std::string* name);
// optional string input_type = 2;
bool has_input_type() const;
@@ -1937,11 +2883,23 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess
static const int kInputTypeFieldNumber = 2;
const ::std::string& input_type() const;
void set_input_type(const ::std::string& value);
+ #if LANG_CXX11
+ void set_input_type(::std::string&& value);
+ #endif
void set_input_type(const char* value);
void set_input_type(const char* value, size_t size);
::std::string* mutable_input_type();
::std::string* release_input_type();
void set_allocated_input_type(::std::string* input_type);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ ::std::string* unsafe_arena_release_input_type();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_input_type(
+ ::std::string* input_type);
// optional string output_type = 3;
bool has_output_type() const;
@@ -1949,20 +2907,38 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess
static const int kOutputTypeFieldNumber = 3;
const ::std::string& output_type() const;
void set_output_type(const ::std::string& value);
+ #if LANG_CXX11
+ void set_output_type(::std::string&& value);
+ #endif
void set_output_type(const char* value);
void set_output_type(const char* value, size_t size);
::std::string* mutable_output_type();
::std::string* release_output_type();
void set_allocated_output_type(::std::string* output_type);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ ::std::string* unsafe_arena_release_output_type();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_output_type(
+ ::std::string* output_type);
// optional .google.protobuf.MethodOptions options = 4;
bool has_options() const;
void clear_options();
static const int kOptionsFieldNumber = 4;
+ private:
+ void _slow_mutable_options();
+ public:
const ::google::protobuf::MethodOptions& options() const;
- ::google::protobuf::MethodOptions* mutable_options();
::google::protobuf::MethodOptions* release_options();
+ ::google::protobuf::MethodOptions* mutable_options();
void set_allocated_options(::google::protobuf::MethodOptions* options);
+ void unsafe_arena_set_allocated_options(
+ ::google::protobuf::MethodOptions* options);
+ ::google::protobuf::MethodOptions* unsafe_arena_release_options();
// optional bool client_streaming = 5 [default = false];
bool has_client_streaming() const;
@@ -1994,6 +2970,9 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess
void clear_has_server_streaming();
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::internal::ArenaStringPtr name_;
@@ -2002,11 +2981,8 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess
::google::protobuf::MethodOptions* options_;
bool client_streaming_;
bool server_streaming_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fdescriptor_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodDescriptorProtoImpl();
};
// -------------------------------------------------------------------
@@ -2021,24 +2997,50 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ FileOptions(FileOptions&& from) noexcept
+ : FileOptions() {
+ *this = ::std::move(from);
+ }
+ inline FileOptions& operator=(FileOptions&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
-
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
+ inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ return GetArenaNoVirtual();
+ }
+ inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ return MaybeArenaPtr();
+ }
static const ::google::protobuf::Descriptor* descriptor();
static const FileOptions& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const FileOptions* internal_default_instance() {
return reinterpret_cast<const FileOptions*>(
&_FileOptions_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 13;
+ void UnsafeArenaSwap(FileOptions* other);
void Swap(FileOptions* other);
+ friend void swap(FileOptions& a, FileOptions& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -2059,22 +3061,23 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const PROTOBUF_FINAL;
void InternalSwap(FileOptions* other);
+ protected:
+ explicit FileOptions(::google::protobuf::Arena* arena);
+ private:
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
- return NULL;
+ return _internal_metadata_.arena();
}
inline void* MaybeArenaPtr() const {
- return NULL;
+ return _internal_metadata_.raw_arena_ptr();
}
public:
@@ -2112,17 +3115,41 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
// accessors -------------------------------------------------------
+ // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
+ int uninterpreted_option_size() const;
+ void clear_uninterpreted_option();
+ static const int kUninterpretedOptionFieldNumber = 999;
+ const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const;
+ ::google::protobuf::UninterpretedOption* mutable_uninterpreted_option(int index);
+ ::google::protobuf::UninterpretedOption* add_uninterpreted_option();
+ ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >*
+ mutable_uninterpreted_option();
+ const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
+ uninterpreted_option() const;
+
// optional string java_package = 1;
bool has_java_package() const;
void clear_java_package();
static const int kJavaPackageFieldNumber = 1;
const ::std::string& java_package() const;
void set_java_package(const ::std::string& value);
+ #if LANG_CXX11
+ void set_java_package(::std::string&& value);
+ #endif
void set_java_package(const char* value);
void set_java_package(const char* value, size_t size);
::std::string* mutable_java_package();
::std::string* release_java_package();
void set_allocated_java_package(::std::string* java_package);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ ::std::string* unsafe_arena_release_java_package();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_java_package(
+ ::std::string* java_package);
// optional string java_outer_classname = 8;
bool has_java_outer_classname() const;
@@ -2130,11 +3157,174 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
static const int kJavaOuterClassnameFieldNumber = 8;
const ::std::string& java_outer_classname() const;
void set_java_outer_classname(const ::std::string& value);
+ #if LANG_CXX11
+ void set_java_outer_classname(::std::string&& value);
+ #endif
void set_java_outer_classname(const char* value);
void set_java_outer_classname(const char* value, size_t size);
::std::string* mutable_java_outer_classname();
::std::string* release_java_outer_classname();
void set_allocated_java_outer_classname(::std::string* java_outer_classname);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ ::std::string* unsafe_arena_release_java_outer_classname();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_java_outer_classname(
+ ::std::string* java_outer_classname);
+
+ // optional string go_package = 11;
+ bool has_go_package() const;
+ void clear_go_package();
+ static const int kGoPackageFieldNumber = 11;
+ const ::std::string& go_package() const;
+ void set_go_package(const ::std::string& value);
+ #if LANG_CXX11
+ void set_go_package(::std::string&& value);
+ #endif
+ void set_go_package(const char* value);
+ void set_go_package(const char* value, size_t size);
+ ::std::string* mutable_go_package();
+ ::std::string* release_go_package();
+ void set_allocated_go_package(::std::string* go_package);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ ::std::string* unsafe_arena_release_go_package();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_go_package(
+ ::std::string* go_package);
+
+ // optional string objc_class_prefix = 36;
+ bool has_objc_class_prefix() const;
+ void clear_objc_class_prefix();
+ static const int kObjcClassPrefixFieldNumber = 36;
+ const ::std::string& objc_class_prefix() const;
+ void set_objc_class_prefix(const ::std::string& value);
+ #if LANG_CXX11
+ void set_objc_class_prefix(::std::string&& value);
+ #endif
+ void set_objc_class_prefix(const char* value);
+ void set_objc_class_prefix(const char* value, size_t size);
+ ::std::string* mutable_objc_class_prefix();
+ ::std::string* release_objc_class_prefix();
+ void set_allocated_objc_class_prefix(::std::string* objc_class_prefix);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ ::std::string* unsafe_arena_release_objc_class_prefix();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_objc_class_prefix(
+ ::std::string* objc_class_prefix);
+
+ // optional string csharp_namespace = 37;
+ bool has_csharp_namespace() const;
+ void clear_csharp_namespace();
+ static const int kCsharpNamespaceFieldNumber = 37;
+ const ::std::string& csharp_namespace() const;
+ void set_csharp_namespace(const ::std::string& value);
+ #if LANG_CXX11
+ void set_csharp_namespace(::std::string&& value);
+ #endif
+ void set_csharp_namespace(const char* value);
+ void set_csharp_namespace(const char* value, size_t size);
+ ::std::string* mutable_csharp_namespace();
+ ::std::string* release_csharp_namespace();
+ void set_allocated_csharp_namespace(::std::string* csharp_namespace);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ ::std::string* unsafe_arena_release_csharp_namespace();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_csharp_namespace(
+ ::std::string* csharp_namespace);
+
+ // optional string swift_prefix = 39;
+ bool has_swift_prefix() const;
+ void clear_swift_prefix();
+ static const int kSwiftPrefixFieldNumber = 39;
+ const ::std::string& swift_prefix() const;
+ void set_swift_prefix(const ::std::string& value);
+ #if LANG_CXX11
+ void set_swift_prefix(::std::string&& value);
+ #endif
+ void set_swift_prefix(const char* value);
+ void set_swift_prefix(const char* value, size_t size);
+ ::std::string* mutable_swift_prefix();
+ ::std::string* release_swift_prefix();
+ void set_allocated_swift_prefix(::std::string* swift_prefix);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ ::std::string* unsafe_arena_release_swift_prefix();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_swift_prefix(
+ ::std::string* swift_prefix);
+
+ // optional string php_class_prefix = 40;
+ bool has_php_class_prefix() const;
+ void clear_php_class_prefix();
+ static const int kPhpClassPrefixFieldNumber = 40;
+ const ::std::string& php_class_prefix() const;
+ void set_php_class_prefix(const ::std::string& value);
+ #if LANG_CXX11
+ void set_php_class_prefix(::std::string&& value);
+ #endif
+ void set_php_class_prefix(const char* value);
+ void set_php_class_prefix(const char* value, size_t size);
+ ::std::string* mutable_php_class_prefix();
+ ::std::string* release_php_class_prefix();
+ void set_allocated_php_class_prefix(::std::string* php_class_prefix);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ ::std::string* unsafe_arena_release_php_class_prefix();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_php_class_prefix(
+ ::std::string* php_class_prefix);
+
+ // optional string php_namespace = 41;
+ bool has_php_namespace() const;
+ void clear_php_namespace();
+ static const int kPhpNamespaceFieldNumber = 41;
+ const ::std::string& php_namespace() const;
+ void set_php_namespace(const ::std::string& value);
+ #if LANG_CXX11
+ void set_php_namespace(::std::string&& value);
+ #endif
+ void set_php_namespace(const char* value);
+ void set_php_namespace(const char* value, size_t size);
+ ::std::string* mutable_php_namespace();
+ ::std::string* release_php_namespace();
+ void set_allocated_php_namespace(::std::string* php_namespace);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ ::std::string* unsafe_arena_release_php_namespace();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_php_namespace(
+ ::std::string* php_namespace);
+
+ // optional bool cc_enable_arenas = 31 [default = false];
+ bool has_cc_enable_arenas() const;
+ void clear_cc_enable_arenas();
+ static const int kCcEnableArenasFieldNumber = 31;
+ bool cc_enable_arenas() const;
+ void set_cc_enable_arenas(bool value);
// optional bool java_multiple_files = 10 [default = false];
bool has_java_multiple_files() const;
@@ -2157,25 +3347,6 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
bool java_string_check_utf8() const;
void set_java_string_check_utf8(bool value);
- // optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED];
- bool has_optimize_for() const;
- void clear_optimize_for();
- static const int kOptimizeForFieldNumber = 9;
- ::google::protobuf::FileOptions_OptimizeMode optimize_for() const;
- void set_optimize_for(::google::protobuf::FileOptions_OptimizeMode value);
-
- // optional string go_package = 11;
- bool has_go_package() const;
- void clear_go_package();
- static const int kGoPackageFieldNumber = 11;
- const ::std::string& go_package() const;
- void set_go_package(const ::std::string& value);
- void set_go_package(const char* value);
- void set_go_package(const char* value, size_t size);
- ::std::string* mutable_go_package();
- ::std::string* release_go_package();
- void set_allocated_go_package(::std::string* go_package);
-
// optional bool cc_generic_services = 16 [default = false];
bool has_cc_generic_services() const;
void clear_cc_generic_services();
@@ -2197,6 +3368,13 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
bool py_generic_services() const;
void set_py_generic_services(bool value);
+ // optional bool php_generic_services = 42 [default = false];
+ bool has_php_generic_services() const;
+ void clear_php_generic_services();
+ static const int kPhpGenericServicesFieldNumber = 42;
+ bool php_generic_services() const;
+ void set_php_generic_services(bool value);
+
// optional bool deprecated = 23 [default = false];
bool has_deprecated() const;
void clear_deprecated();
@@ -2204,60 +3382,12 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
bool deprecated() const;
void set_deprecated(bool value);
- // optional bool cc_enable_arenas = 31 [default = false];
- bool has_cc_enable_arenas() const;
- void clear_cc_enable_arenas();
- static const int kCcEnableArenasFieldNumber = 31;
- bool cc_enable_arenas() const;
- void set_cc_enable_arenas(bool value);
-
- // optional string objc_class_prefix = 36;
- bool has_objc_class_prefix() const;
- void clear_objc_class_prefix();
- static const int kObjcClassPrefixFieldNumber = 36;
- const ::std::string& objc_class_prefix() const;
- void set_objc_class_prefix(const ::std::string& value);
- void set_objc_class_prefix(const char* value);
- void set_objc_class_prefix(const char* value, size_t size);
- ::std::string* mutable_objc_class_prefix();
- ::std::string* release_objc_class_prefix();
- void set_allocated_objc_class_prefix(::std::string* objc_class_prefix);
-
- // optional string csharp_namespace = 37;
- bool has_csharp_namespace() const;
- void clear_csharp_namespace();
- static const int kCsharpNamespaceFieldNumber = 37;
- const ::std::string& csharp_namespace() const;
- void set_csharp_namespace(const ::std::string& value);
- void set_csharp_namespace(const char* value);
- void set_csharp_namespace(const char* value, size_t size);
- ::std::string* mutable_csharp_namespace();
- ::std::string* release_csharp_namespace();
- void set_allocated_csharp_namespace(::std::string* csharp_namespace);
-
- // optional string swift_prefix = 39;
- bool has_swift_prefix() const;
- void clear_swift_prefix();
- static const int kSwiftPrefixFieldNumber = 39;
- const ::std::string& swift_prefix() const;
- void set_swift_prefix(const ::std::string& value);
- void set_swift_prefix(const char* value);
- void set_swift_prefix(const char* value, size_t size);
- ::std::string* mutable_swift_prefix();
- ::std::string* release_swift_prefix();
- void set_allocated_swift_prefix(::std::string* swift_prefix);
-
- // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
- int uninterpreted_option_size() const;
- void clear_uninterpreted_option();
- static const int kUninterpretedOptionFieldNumber = 999;
- const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const;
- ::google::protobuf::UninterpretedOption* mutable_uninterpreted_option(int index);
- ::google::protobuf::UninterpretedOption* add_uninterpreted_option();
- ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >*
- mutable_uninterpreted_option();
- const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
- uninterpreted_option() const;
+ // optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED];
+ bool has_optimize_for() const;
+ void clear_optimize_for();
+ static const int kOptimizeForFieldNumber = 9;
+ ::google::protobuf::FileOptions_OptimizeMode optimize_for() const;
+ void set_optimize_for(::google::protobuf::FileOptions_OptimizeMode value);
GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(FileOptions)
// @@protoc_insertion_point(class_scope:google.protobuf.FileOptions)
@@ -2282,6 +3412,8 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
void clear_has_java_generic_services();
void set_has_py_generic_services();
void clear_has_py_generic_services();
+ void set_has_php_generic_services();
+ void clear_has_php_generic_services();
void set_has_deprecated();
void clear_has_deprecated();
void set_has_cc_enable_arenas();
@@ -2292,10 +3424,17 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
void clear_has_csharp_namespace();
void set_has_swift_prefix();
void clear_has_swift_prefix();
+ void set_has_php_class_prefix();
+ void clear_has_php_class_prefix();
+ void set_has_php_namespace();
+ void clear_has_php_namespace();
::google::protobuf::internal::ExtensionSet _extensions_;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_;
@@ -2305,20 +3444,20 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
::google::protobuf::internal::ArenaStringPtr objc_class_prefix_;
::google::protobuf::internal::ArenaStringPtr csharp_namespace_;
::google::protobuf::internal::ArenaStringPtr swift_prefix_;
+ ::google::protobuf::internal::ArenaStringPtr php_class_prefix_;
+ ::google::protobuf::internal::ArenaStringPtr php_namespace_;
+ bool cc_enable_arenas_;
bool java_multiple_files_;
bool java_generate_equals_and_hash_;
bool java_string_check_utf8_;
bool cc_generic_services_;
bool java_generic_services_;
bool py_generic_services_;
+ bool php_generic_services_;
bool deprecated_;
- bool cc_enable_arenas_;
int optimize_for_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fdescriptor_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileOptionsImpl();
};
// -------------------------------------------------------------------
@@ -2333,24 +3472,50 @@ class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /*
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ MessageOptions(MessageOptions&& from) noexcept
+ : MessageOptions() {
+ *this = ::std::move(from);
+ }
+ inline MessageOptions& operator=(MessageOptions&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
-
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
+ inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ return GetArenaNoVirtual();
+ }
+ inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ return MaybeArenaPtr();
+ }
static const ::google::protobuf::Descriptor* descriptor();
static const MessageOptions& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const MessageOptions* internal_default_instance() {
return reinterpret_cast<const MessageOptions*>(
&_MessageOptions_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 14;
+ void UnsafeArenaSwap(MessageOptions* other);
void Swap(MessageOptions* other);
+ friend void swap(MessageOptions& a, MessageOptions& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -2371,22 +3536,23 @@ class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /*
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const PROTOBUF_FINAL;
void InternalSwap(MessageOptions* other);
+ protected:
+ explicit MessageOptions(::google::protobuf::Arena* arena);
+ private:
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
- return NULL;
+ return _internal_metadata_.arena();
}
inline void* MaybeArenaPtr() const {
- return NULL;
+ return _internal_metadata_.raw_arena_ptr();
}
public:
@@ -2396,6 +3562,18 @@ class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /*
// accessors -------------------------------------------------------
+ // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
+ int uninterpreted_option_size() const;
+ void clear_uninterpreted_option();
+ static const int kUninterpretedOptionFieldNumber = 999;
+ const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const;
+ ::google::protobuf::UninterpretedOption* mutable_uninterpreted_option(int index);
+ ::google::protobuf::UninterpretedOption* add_uninterpreted_option();
+ ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >*
+ mutable_uninterpreted_option();
+ const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
+ uninterpreted_option() const;
+
// optional bool message_set_wire_format = 1 [default = false];
bool has_message_set_wire_format() const;
void clear_message_set_wire_format();
@@ -2424,18 +3602,6 @@ class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /*
bool map_entry() const;
void set_map_entry(bool value);
- // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
- int uninterpreted_option_size() const;
- void clear_uninterpreted_option();
- static const int kUninterpretedOptionFieldNumber = 999;
- const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const;
- ::google::protobuf::UninterpretedOption* mutable_uninterpreted_option(int index);
- ::google::protobuf::UninterpretedOption* add_uninterpreted_option();
- ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >*
- mutable_uninterpreted_option();
- const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
- uninterpreted_option() const;
-
GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(MessageOptions)
// @@protoc_insertion_point(class_scope:google.protobuf.MessageOptions)
private:
@@ -2451,6 +3617,9 @@ class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /*
::google::protobuf::internal::ExtensionSet _extensions_;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_;
@@ -2458,11 +3627,8 @@ class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /*
bool no_standard_descriptor_accessor_;
bool deprecated_;
bool map_entry_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fdescriptor_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMessageOptionsImpl();
};
// -------------------------------------------------------------------
@@ -2477,24 +3643,50 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ FieldOptions(FieldOptions&& from) noexcept
+ : FieldOptions() {
+ *this = ::std::move(from);
+ }
+ inline FieldOptions& operator=(FieldOptions&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
-
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
+ inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ return GetArenaNoVirtual();
+ }
+ inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ return MaybeArenaPtr();
+ }
static const ::google::protobuf::Descriptor* descriptor();
static const FieldOptions& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const FieldOptions* internal_default_instance() {
return reinterpret_cast<const FieldOptions*>(
&_FieldOptions_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 15;
+ void UnsafeArenaSwap(FieldOptions* other);
void Swap(FieldOptions* other);
+ friend void swap(FieldOptions& a, FieldOptions& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -2515,22 +3707,23 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const PROTOBUF_FINAL;
void InternalSwap(FieldOptions* other);
+ protected:
+ explicit FieldOptions(::google::protobuf::Arena* arena);
+ private:
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
- return NULL;
+ return _internal_metadata_.arena();
}
inline void* MaybeArenaPtr() const {
- return NULL;
+ return _internal_metadata_.raw_arena_ptr();
}
public:
@@ -2596,6 +3789,18 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@
// accessors -------------------------------------------------------
+ // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
+ int uninterpreted_option_size() const;
+ void clear_uninterpreted_option();
+ static const int kUninterpretedOptionFieldNumber = 999;
+ const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const;
+ ::google::protobuf::UninterpretedOption* mutable_uninterpreted_option(int index);
+ ::google::protobuf::UninterpretedOption* add_uninterpreted_option();
+ ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >*
+ mutable_uninterpreted_option();
+ const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
+ uninterpreted_option() const;
+
// optional .google.protobuf.FieldOptions.CType ctype = 1 [default = STRING];
bool has_ctype() const;
void clear_ctype();
@@ -2610,13 +3815,6 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@
bool packed() const;
void set_packed(bool value);
- // optional .google.protobuf.FieldOptions.JSType jstype = 6 [default = JS_NORMAL];
- bool has_jstype() const;
- void clear_jstype();
- static const int kJstypeFieldNumber = 6;
- ::google::protobuf::FieldOptions_JSType jstype() const;
- void set_jstype(::google::protobuf::FieldOptions_JSType value);
-
// optional bool lazy = 5 [default = false];
bool has_lazy() const;
void clear_lazy();
@@ -2638,17 +3836,12 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@
bool weak() const;
void set_weak(bool value);
- // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
- int uninterpreted_option_size() const;
- void clear_uninterpreted_option();
- static const int kUninterpretedOptionFieldNumber = 999;
- const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const;
- ::google::protobuf::UninterpretedOption* mutable_uninterpreted_option(int index);
- ::google::protobuf::UninterpretedOption* add_uninterpreted_option();
- ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >*
- mutable_uninterpreted_option();
- const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
- uninterpreted_option() const;
+ // optional .google.protobuf.FieldOptions.JSType jstype = 6 [default = JS_NORMAL];
+ bool has_jstype() const;
+ void clear_jstype();
+ static const int kJstypeFieldNumber = 6;
+ ::google::protobuf::FieldOptions_JSType jstype() const;
+ void set_jstype(::google::protobuf::FieldOptions_JSType value);
GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(FieldOptions)
// @@protoc_insertion_point(class_scope:google.protobuf.FieldOptions)
@@ -2669,20 +3862,20 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@
::google::protobuf::internal::ExtensionSet _extensions_;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_;
int ctype_;
- int jstype_;
bool packed_;
bool lazy_;
bool deprecated_;
bool weak_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fdescriptor_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
-
+ int jstype_;
+ friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldOptionsImpl();
};
// -------------------------------------------------------------------
@@ -2697,24 +3890,50 @@ class LIBPROTOBUF_EXPORT OneofOptions : public ::google::protobuf::Message /* @@
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ OneofOptions(OneofOptions&& from) noexcept
+ : OneofOptions() {
+ *this = ::std::move(from);
+ }
+ inline OneofOptions& operator=(OneofOptions&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
-
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
+ inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ return GetArenaNoVirtual();
+ }
+ inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ return MaybeArenaPtr();
+ }
static const ::google::protobuf::Descriptor* descriptor();
static const OneofOptions& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const OneofOptions* internal_default_instance() {
return reinterpret_cast<const OneofOptions*>(
&_OneofOptions_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 16;
+ void UnsafeArenaSwap(OneofOptions* other);
void Swap(OneofOptions* other);
+ friend void swap(OneofOptions& a, OneofOptions& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -2735,22 +3954,23 @@ class LIBPROTOBUF_EXPORT OneofOptions : public ::google::protobuf::Message /* @@
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const PROTOBUF_FINAL;
void InternalSwap(OneofOptions* other);
+ protected:
+ explicit OneofOptions(::google::protobuf::Arena* arena);
+ private:
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
- return NULL;
+ return _internal_metadata_.arena();
}
inline void* MaybeArenaPtr() const {
- return NULL;
+ return _internal_metadata_.raw_arena_ptr();
}
public:
@@ -2779,14 +3999,14 @@ class LIBPROTOBUF_EXPORT OneofOptions : public ::google::protobuf::Message /* @@
::google::protobuf::internal::ExtensionSet _extensions_;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fdescriptor_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofOptionsImpl();
};
// -------------------------------------------------------------------
@@ -2801,24 +4021,50 @@ class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@p
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ EnumOptions(EnumOptions&& from) noexcept
+ : EnumOptions() {
+ *this = ::std::move(from);
+ }
+ inline EnumOptions& operator=(EnumOptions&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
-
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
+ inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ return GetArenaNoVirtual();
+ }
+ inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ return MaybeArenaPtr();
+ }
static const ::google::protobuf::Descriptor* descriptor();
static const EnumOptions& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const EnumOptions* internal_default_instance() {
return reinterpret_cast<const EnumOptions*>(
&_EnumOptions_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 17;
+ void UnsafeArenaSwap(EnumOptions* other);
void Swap(EnumOptions* other);
+ friend void swap(EnumOptions& a, EnumOptions& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -2839,22 +4085,23 @@ class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@p
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const PROTOBUF_FINAL;
void InternalSwap(EnumOptions* other);
+ protected:
+ explicit EnumOptions(::google::protobuf::Arena* arena);
+ private:
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
- return NULL;
+ return _internal_metadata_.arena();
}
inline void* MaybeArenaPtr() const {
- return NULL;
+ return _internal_metadata_.raw_arena_ptr();
}
public:
@@ -2864,6 +4111,18 @@ class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@p
// accessors -------------------------------------------------------
+ // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
+ int uninterpreted_option_size() const;
+ void clear_uninterpreted_option();
+ static const int kUninterpretedOptionFieldNumber = 999;
+ const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const;
+ ::google::protobuf::UninterpretedOption* mutable_uninterpreted_option(int index);
+ ::google::protobuf::UninterpretedOption* add_uninterpreted_option();
+ ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >*
+ mutable_uninterpreted_option();
+ const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
+ uninterpreted_option() const;
+
// optional bool allow_alias = 2;
bool has_allow_alias() const;
void clear_allow_alias();
@@ -2878,18 +4137,6 @@ class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@p
bool deprecated() const;
void set_deprecated(bool value);
- // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
- int uninterpreted_option_size() const;
- void clear_uninterpreted_option();
- static const int kUninterpretedOptionFieldNumber = 999;
- const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const;
- ::google::protobuf::UninterpretedOption* mutable_uninterpreted_option(int index);
- ::google::protobuf::UninterpretedOption* add_uninterpreted_option();
- ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >*
- mutable_uninterpreted_option();
- const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
- uninterpreted_option() const;
-
GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(EnumOptions)
// @@protoc_insertion_point(class_scope:google.protobuf.EnumOptions)
private:
@@ -2901,16 +4148,16 @@ class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@p
::google::protobuf::internal::ExtensionSet _extensions_;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_;
bool allow_alias_;
bool deprecated_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fdescriptor_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumOptionsImpl();
};
// -------------------------------------------------------------------
@@ -2925,24 +4172,50 @@ class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message /
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ EnumValueOptions(EnumValueOptions&& from) noexcept
+ : EnumValueOptions() {
+ *this = ::std::move(from);
+ }
+ inline EnumValueOptions& operator=(EnumValueOptions&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
-
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
+ inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ return GetArenaNoVirtual();
+ }
+ inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ return MaybeArenaPtr();
+ }
static const ::google::protobuf::Descriptor* descriptor();
static const EnumValueOptions& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const EnumValueOptions* internal_default_instance() {
return reinterpret_cast<const EnumValueOptions*>(
&_EnumValueOptions_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 18;
+ void UnsafeArenaSwap(EnumValueOptions* other);
void Swap(EnumValueOptions* other);
+ friend void swap(EnumValueOptions& a, EnumValueOptions& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -2963,22 +4236,23 @@ class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message /
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const PROTOBUF_FINAL;
void InternalSwap(EnumValueOptions* other);
+ protected:
+ explicit EnumValueOptions(::google::protobuf::Arena* arena);
+ private:
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
- return NULL;
+ return _internal_metadata_.arena();
}
inline void* MaybeArenaPtr() const {
- return NULL;
+ return _internal_metadata_.raw_arena_ptr();
}
public:
@@ -2988,13 +4262,6 @@ class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message /
// accessors -------------------------------------------------------
- // optional bool deprecated = 1 [default = false];
- bool has_deprecated() const;
- void clear_deprecated();
- static const int kDeprecatedFieldNumber = 1;
- bool deprecated() const;
- void set_deprecated(bool value);
-
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
int uninterpreted_option_size() const;
void clear_uninterpreted_option();
@@ -3007,6 +4274,13 @@ class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message /
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
uninterpreted_option() const;
+ // optional bool deprecated = 1 [default = false];
+ bool has_deprecated() const;
+ void clear_deprecated();
+ static const int kDeprecatedFieldNumber = 1;
+ bool deprecated() const;
+ void set_deprecated(bool value);
+
GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(EnumValueOptions)
// @@protoc_insertion_point(class_scope:google.protobuf.EnumValueOptions)
private:
@@ -3016,15 +4290,15 @@ class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message /
::google::protobuf::internal::ExtensionSet _extensions_;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_;
bool deprecated_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fdescriptor_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueOptionsImpl();
};
// -------------------------------------------------------------------
@@ -3039,24 +4313,50 @@ class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /*
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ ServiceOptions(ServiceOptions&& from) noexcept
+ : ServiceOptions() {
+ *this = ::std::move(from);
+ }
+ inline ServiceOptions& operator=(ServiceOptions&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
-
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
+ inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ return GetArenaNoVirtual();
+ }
+ inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ return MaybeArenaPtr();
+ }
static const ::google::protobuf::Descriptor* descriptor();
static const ServiceOptions& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const ServiceOptions* internal_default_instance() {
return reinterpret_cast<const ServiceOptions*>(
&_ServiceOptions_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 19;
+ void UnsafeArenaSwap(ServiceOptions* other);
void Swap(ServiceOptions* other);
+ friend void swap(ServiceOptions& a, ServiceOptions& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -3077,22 +4377,23 @@ class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /*
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const PROTOBUF_FINAL;
void InternalSwap(ServiceOptions* other);
+ protected:
+ explicit ServiceOptions(::google::protobuf::Arena* arena);
+ private:
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
- return NULL;
+ return _internal_metadata_.arena();
}
inline void* MaybeArenaPtr() const {
- return NULL;
+ return _internal_metadata_.raw_arena_ptr();
}
public:
@@ -3102,13 +4403,6 @@ class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /*
// accessors -------------------------------------------------------
- // optional bool deprecated = 33 [default = false];
- bool has_deprecated() const;
- void clear_deprecated();
- static const int kDeprecatedFieldNumber = 33;
- bool deprecated() const;
- void set_deprecated(bool value);
-
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
int uninterpreted_option_size() const;
void clear_uninterpreted_option();
@@ -3121,6 +4415,13 @@ class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /*
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
uninterpreted_option() const;
+ // optional bool deprecated = 33 [default = false];
+ bool has_deprecated() const;
+ void clear_deprecated();
+ static const int kDeprecatedFieldNumber = 33;
+ bool deprecated() const;
+ void set_deprecated(bool value);
+
GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(ServiceOptions)
// @@protoc_insertion_point(class_scope:google.protobuf.ServiceOptions)
private:
@@ -3130,15 +4431,15 @@ class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /*
::google::protobuf::internal::ExtensionSet _extensions_;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_;
bool deprecated_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fdescriptor_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceOptionsImpl();
};
// -------------------------------------------------------------------
@@ -3153,24 +4454,50 @@ class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ MethodOptions(MethodOptions&& from) noexcept
+ : MethodOptions() {
+ *this = ::std::move(from);
+ }
+ inline MethodOptions& operator=(MethodOptions&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
-
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
+ inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ return GetArenaNoVirtual();
+ }
+ inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ return MaybeArenaPtr();
+ }
static const ::google::protobuf::Descriptor* descriptor();
static const MethodOptions& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const MethodOptions* internal_default_instance() {
return reinterpret_cast<const MethodOptions*>(
&_MethodOptions_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 20;
+ void UnsafeArenaSwap(MethodOptions* other);
void Swap(MethodOptions* other);
+ friend void swap(MethodOptions& a, MethodOptions& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -3191,22 +4518,23 @@ class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const PROTOBUF_FINAL;
void InternalSwap(MethodOptions* other);
+ protected:
+ explicit MethodOptions(::google::protobuf::Arena* arena);
+ private:
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
- return NULL;
+ return _internal_metadata_.arena();
}
inline void* MaybeArenaPtr() const {
- return NULL;
+ return _internal_metadata_.raw_arena_ptr();
}
public:
@@ -3244,6 +4572,18 @@ class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @
// accessors -------------------------------------------------------
+ // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
+ int uninterpreted_option_size() const;
+ void clear_uninterpreted_option();
+ static const int kUninterpretedOptionFieldNumber = 999;
+ const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const;
+ ::google::protobuf::UninterpretedOption* mutable_uninterpreted_option(int index);
+ ::google::protobuf::UninterpretedOption* add_uninterpreted_option();
+ ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >*
+ mutable_uninterpreted_option();
+ const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
+ uninterpreted_option() const;
+
// optional bool deprecated = 33 [default = false];
bool has_deprecated() const;
void clear_deprecated();
@@ -3258,18 +4598,6 @@ class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @
::google::protobuf::MethodOptions_IdempotencyLevel idempotency_level() const;
void set_idempotency_level(::google::protobuf::MethodOptions_IdempotencyLevel value);
- // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
- int uninterpreted_option_size() const;
- void clear_uninterpreted_option();
- static const int kUninterpretedOptionFieldNumber = 999;
- const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const;
- ::google::protobuf::UninterpretedOption* mutable_uninterpreted_option(int index);
- ::google::protobuf::UninterpretedOption* add_uninterpreted_option();
- ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >*
- mutable_uninterpreted_option();
- const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
- uninterpreted_option() const;
-
GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(MethodOptions)
// @@protoc_insertion_point(class_scope:google.protobuf.MethodOptions)
private:
@@ -3281,16 +4609,16 @@ class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @
::google::protobuf::internal::ExtensionSet _extensions_;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_;
bool deprecated_;
int idempotency_level_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fdescriptor_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodOptionsImpl();
};
// -------------------------------------------------------------------
@@ -3305,24 +4633,50 @@ class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobu
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ UninterpretedOption_NamePart(UninterpretedOption_NamePart&& from) noexcept
+ : UninterpretedOption_NamePart() {
+ *this = ::std::move(from);
+ }
+ inline UninterpretedOption_NamePart& operator=(UninterpretedOption_NamePart&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
-
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
+ inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ return GetArenaNoVirtual();
+ }
+ inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ return MaybeArenaPtr();
+ }
static const ::google::protobuf::Descriptor* descriptor();
static const UninterpretedOption_NamePart& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const UninterpretedOption_NamePart* internal_default_instance() {
return reinterpret_cast<const UninterpretedOption_NamePart*>(
&_UninterpretedOption_NamePart_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 21;
+ void UnsafeArenaSwap(UninterpretedOption_NamePart* other);
void Swap(UninterpretedOption_NamePart* other);
+ friend void swap(UninterpretedOption_NamePart& a, UninterpretedOption_NamePart& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -3343,22 +4697,23 @@ class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobu
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const PROTOBUF_FINAL;
void InternalSwap(UninterpretedOption_NamePart* other);
+ protected:
+ explicit UninterpretedOption_NamePart(::google::protobuf::Arena* arena);
+ private:
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
- return NULL;
+ return _internal_metadata_.arena();
}
inline void* MaybeArenaPtr() const {
- return NULL;
+ return _internal_metadata_.raw_arena_ptr();
}
public:
@@ -3374,11 +4729,23 @@ class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobu
static const int kNamePartFieldNumber = 1;
const ::std::string& name_part() const;
void set_name_part(const ::std::string& value);
+ #if LANG_CXX11
+ void set_name_part(::std::string&& value);
+ #endif
void set_name_part(const char* value);
void set_name_part(const char* value, size_t size);
::std::string* mutable_name_part();
::std::string* release_name_part();
void set_allocated_name_part(::std::string* name_part);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ ::std::string* unsafe_arena_release_name_part();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_name_part(
+ ::std::string* name_part);
// required bool is_extension = 2;
bool has_is_extension() const;
@@ -3398,15 +4765,15 @@ class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobu
size_t RequiredFieldsByteSizeFallback() const;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::internal::ArenaStringPtr name_part_;
bool is_extension_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fdescriptor_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption_NamePartImpl();
};
// -------------------------------------------------------------------
@@ -3421,24 +4788,50 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ UninterpretedOption(UninterpretedOption&& from) noexcept
+ : UninterpretedOption() {
+ *this = ::std::move(from);
+ }
+ inline UninterpretedOption& operator=(UninterpretedOption&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
-
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
+ inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ return GetArenaNoVirtual();
+ }
+ inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ return MaybeArenaPtr();
+ }
static const ::google::protobuf::Descriptor* descriptor();
static const UninterpretedOption& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const UninterpretedOption* internal_default_instance() {
return reinterpret_cast<const UninterpretedOption*>(
&_UninterpretedOption_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 22;
+ void UnsafeArenaSwap(UninterpretedOption* other);
void Swap(UninterpretedOption* other);
+ friend void swap(UninterpretedOption& a, UninterpretedOption& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -3459,22 +4852,23 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const PROTOBUF_FINAL;
void InternalSwap(UninterpretedOption* other);
+ protected:
+ explicit UninterpretedOption(::google::protobuf::Arena* arena);
+ private:
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
- return NULL;
+ return _internal_metadata_.arena();
}
inline void* MaybeArenaPtr() const {
- return NULL;
+ return _internal_metadata_.raw_arena_ptr();
}
public:
@@ -3504,32 +4898,23 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag
static const int kIdentifierValueFieldNumber = 3;
const ::std::string& identifier_value() const;
void set_identifier_value(const ::std::string& value);
+ #if LANG_CXX11
+ void set_identifier_value(::std::string&& value);
+ #endif
void set_identifier_value(const char* value);
void set_identifier_value(const char* value, size_t size);
::std::string* mutable_identifier_value();
::std::string* release_identifier_value();
void set_allocated_identifier_value(::std::string* identifier_value);
-
- // optional uint64 positive_int_value = 4;
- bool has_positive_int_value() const;
- void clear_positive_int_value();
- static const int kPositiveIntValueFieldNumber = 4;
- ::google::protobuf::uint64 positive_int_value() const;
- void set_positive_int_value(::google::protobuf::uint64 value);
-
- // optional int64 negative_int_value = 5;
- bool has_negative_int_value() const;
- void clear_negative_int_value();
- static const int kNegativeIntValueFieldNumber = 5;
- ::google::protobuf::int64 negative_int_value() const;
- void set_negative_int_value(::google::protobuf::int64 value);
-
- // optional double double_value = 6;
- bool has_double_value() const;
- void clear_double_value();
- static const int kDoubleValueFieldNumber = 6;
- double double_value() const;
- void set_double_value(double value);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ ::std::string* unsafe_arena_release_identifier_value();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_identifier_value(
+ ::std::string* identifier_value);
// optional bytes string_value = 7;
bool has_string_value() const;
@@ -3537,11 +4922,23 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag
static const int kStringValueFieldNumber = 7;
const ::std::string& string_value() const;
void set_string_value(const ::std::string& value);
+ #if LANG_CXX11
+ void set_string_value(::std::string&& value);
+ #endif
void set_string_value(const char* value);
void set_string_value(const void* value, size_t size);
::std::string* mutable_string_value();
::std::string* release_string_value();
void set_allocated_string_value(::std::string* string_value);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ ::std::string* unsafe_arena_release_string_value();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_string_value(
+ ::std::string* string_value);
// optional string aggregate_value = 8;
bool has_aggregate_value() const;
@@ -3549,11 +4946,44 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag
static const int kAggregateValueFieldNumber = 8;
const ::std::string& aggregate_value() const;
void set_aggregate_value(const ::std::string& value);
+ #if LANG_CXX11
+ void set_aggregate_value(::std::string&& value);
+ #endif
void set_aggregate_value(const char* value);
void set_aggregate_value(const char* value, size_t size);
::std::string* mutable_aggregate_value();
::std::string* release_aggregate_value();
void set_allocated_aggregate_value(::std::string* aggregate_value);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ ::std::string* unsafe_arena_release_aggregate_value();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_aggregate_value(
+ ::std::string* aggregate_value);
+
+ // optional uint64 positive_int_value = 4;
+ bool has_positive_int_value() const;
+ void clear_positive_int_value();
+ static const int kPositiveIntValueFieldNumber = 4;
+ ::google::protobuf::uint64 positive_int_value() const;
+ void set_positive_int_value(::google::protobuf::uint64 value);
+
+ // optional int64 negative_int_value = 5;
+ bool has_negative_int_value() const;
+ void clear_negative_int_value();
+ static const int kNegativeIntValueFieldNumber = 5;
+ ::google::protobuf::int64 negative_int_value() const;
+ void set_negative_int_value(::google::protobuf::int64 value);
+
+ // optional double double_value = 6;
+ bool has_double_value() const;
+ void clear_double_value();
+ static const int kDoubleValueFieldNumber = 6;
+ double double_value() const;
+ void set_double_value(double value);
// @@protoc_insertion_point(class_scope:google.protobuf.UninterpretedOption)
private:
@@ -3571,6 +5001,9 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag
void clear_has_aggregate_value();
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption_NamePart > name_;
@@ -3580,11 +5013,8 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag
::google::protobuf::uint64 positive_int_value_;
::google::protobuf::int64 negative_int_value_;
double double_value_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fdescriptor_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOptionImpl();
};
// -------------------------------------------------------------------
@@ -3599,24 +5029,50 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ SourceCodeInfo_Location(SourceCodeInfo_Location&& from) noexcept
+ : SourceCodeInfo_Location() {
+ *this = ::std::move(from);
+ }
+ inline SourceCodeInfo_Location& operator=(SourceCodeInfo_Location&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
-
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
+ inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ return GetArenaNoVirtual();
+ }
+ inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ return MaybeArenaPtr();
+ }
static const ::google::protobuf::Descriptor* descriptor();
static const SourceCodeInfo_Location& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const SourceCodeInfo_Location* internal_default_instance() {
return reinterpret_cast<const SourceCodeInfo_Location*>(
&_SourceCodeInfo_Location_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 23;
+ void UnsafeArenaSwap(SourceCodeInfo_Location* other);
void Swap(SourceCodeInfo_Location* other);
+ friend void swap(SourceCodeInfo_Location& a, SourceCodeInfo_Location& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -3637,22 +5093,23 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const PROTOBUF_FINAL;
void InternalSwap(SourceCodeInfo_Location* other);
+ protected:
+ explicit SourceCodeInfo_Location(::google::protobuf::Arena* arena);
+ private:
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
- return NULL;
+ return _internal_metadata_.arena();
}
inline void* MaybeArenaPtr() const {
- return NULL;
+ return _internal_metadata_.raw_arena_ptr();
}
public:
@@ -3686,17 +5143,51 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me
::google::protobuf::RepeatedField< ::google::protobuf::int32 >*
mutable_span();
+ // repeated string leading_detached_comments = 6;
+ int leading_detached_comments_size() const;
+ void clear_leading_detached_comments();
+ static const int kLeadingDetachedCommentsFieldNumber = 6;
+ const ::std::string& leading_detached_comments(int index) const;
+ ::std::string* mutable_leading_detached_comments(int index);
+ void set_leading_detached_comments(int index, const ::std::string& value);
+ #if LANG_CXX11
+ void set_leading_detached_comments(int index, ::std::string&& value);
+ #endif
+ void set_leading_detached_comments(int index, const char* value);
+ void set_leading_detached_comments(int index, const char* value, size_t size);
+ ::std::string* add_leading_detached_comments();
+ void add_leading_detached_comments(const ::std::string& value);
+ #if LANG_CXX11
+ void add_leading_detached_comments(::std::string&& value);
+ #endif
+ void add_leading_detached_comments(const char* value);
+ void add_leading_detached_comments(const char* value, size_t size);
+ const ::google::protobuf::RepeatedPtrField< ::std::string>& leading_detached_comments() const;
+ ::google::protobuf::RepeatedPtrField< ::std::string>* mutable_leading_detached_comments();
+
// optional string leading_comments = 3;
bool has_leading_comments() const;
void clear_leading_comments();
static const int kLeadingCommentsFieldNumber = 3;
const ::std::string& leading_comments() const;
void set_leading_comments(const ::std::string& value);
+ #if LANG_CXX11
+ void set_leading_comments(::std::string&& value);
+ #endif
void set_leading_comments(const char* value);
void set_leading_comments(const char* value, size_t size);
::std::string* mutable_leading_comments();
::std::string* release_leading_comments();
void set_allocated_leading_comments(::std::string* leading_comments);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ ::std::string* unsafe_arena_release_leading_comments();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_leading_comments(
+ ::std::string* leading_comments);
// optional string trailing_comments = 4;
bool has_trailing_comments() const;
@@ -3704,27 +5195,23 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me
static const int kTrailingCommentsFieldNumber = 4;
const ::std::string& trailing_comments() const;
void set_trailing_comments(const ::std::string& value);
+ #if LANG_CXX11
+ void set_trailing_comments(::std::string&& value);
+ #endif
void set_trailing_comments(const char* value);
void set_trailing_comments(const char* value, size_t size);
::std::string* mutable_trailing_comments();
::std::string* release_trailing_comments();
void set_allocated_trailing_comments(::std::string* trailing_comments);
-
- // repeated string leading_detached_comments = 6;
- int leading_detached_comments_size() const;
- void clear_leading_detached_comments();
- static const int kLeadingDetachedCommentsFieldNumber = 6;
- const ::std::string& leading_detached_comments(int index) const;
- ::std::string* mutable_leading_detached_comments(int index);
- void set_leading_detached_comments(int index, const ::std::string& value);
- void set_leading_detached_comments(int index, const char* value);
- void set_leading_detached_comments(int index, const char* value, size_t size);
- ::std::string* add_leading_detached_comments();
- void add_leading_detached_comments(const ::std::string& value);
- void add_leading_detached_comments(const char* value);
- void add_leading_detached_comments(const char* value, size_t size);
- const ::google::protobuf::RepeatedPtrField< ::std::string>& leading_detached_comments() const;
- ::google::protobuf::RepeatedPtrField< ::std::string>* mutable_leading_detached_comments();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ ::std::string* unsafe_arena_release_trailing_comments();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_trailing_comments(
+ ::std::string* trailing_comments);
// @@protoc_insertion_point(class_scope:google.protobuf.SourceCodeInfo.Location)
private:
@@ -3734,6 +5221,9 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me
void clear_has_trailing_comments();
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::RepeatedField< ::google::protobuf::int32 > path_;
@@ -3743,11 +5233,8 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me
::google::protobuf::RepeatedPtrField< ::std::string> leading_detached_comments_;
::google::protobuf::internal::ArenaStringPtr leading_comments_;
::google::protobuf::internal::ArenaStringPtr trailing_comments_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fdescriptor_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfo_LocationImpl();
};
// -------------------------------------------------------------------
@@ -3762,24 +5249,50 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo : public ::google::protobuf::Message /*
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ SourceCodeInfo(SourceCodeInfo&& from) noexcept
+ : SourceCodeInfo() {
+ *this = ::std::move(from);
+ }
+ inline SourceCodeInfo& operator=(SourceCodeInfo&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
-
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
+ inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ return GetArenaNoVirtual();
+ }
+ inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ return MaybeArenaPtr();
+ }
static const ::google::protobuf::Descriptor* descriptor();
static const SourceCodeInfo& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const SourceCodeInfo* internal_default_instance() {
return reinterpret_cast<const SourceCodeInfo*>(
&_SourceCodeInfo_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 24;
+ void UnsafeArenaSwap(SourceCodeInfo* other);
void Swap(SourceCodeInfo* other);
+ friend void swap(SourceCodeInfo& a, SourceCodeInfo& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -3800,22 +5313,23 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo : public ::google::protobuf::Message /*
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const PROTOBUF_FINAL;
void InternalSwap(SourceCodeInfo* other);
+ protected:
+ explicit SourceCodeInfo(::google::protobuf::Arena* arena);
+ private:
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
- return NULL;
+ return _internal_metadata_.arena();
}
inline void* MaybeArenaPtr() const {
- return NULL;
+ return _internal_metadata_.raw_arena_ptr();
}
public:
@@ -3843,14 +5357,14 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo : public ::google::protobuf::Message /*
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::SourceCodeInfo_Location > location_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fdescriptor_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfoImpl();
};
// -------------------------------------------------------------------
@@ -3865,24 +5379,50 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobu
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ GeneratedCodeInfo_Annotation(GeneratedCodeInfo_Annotation&& from) noexcept
+ : GeneratedCodeInfo_Annotation() {
+ *this = ::std::move(from);
+ }
+ inline GeneratedCodeInfo_Annotation& operator=(GeneratedCodeInfo_Annotation&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
-
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
+ inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ return GetArenaNoVirtual();
+ }
+ inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ return MaybeArenaPtr();
+ }
static const ::google::protobuf::Descriptor* descriptor();
static const GeneratedCodeInfo_Annotation& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const GeneratedCodeInfo_Annotation* internal_default_instance() {
return reinterpret_cast<const GeneratedCodeInfo_Annotation*>(
&_GeneratedCodeInfo_Annotation_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 25;
+ void UnsafeArenaSwap(GeneratedCodeInfo_Annotation* other);
void Swap(GeneratedCodeInfo_Annotation* other);
+ friend void swap(GeneratedCodeInfo_Annotation& a, GeneratedCodeInfo_Annotation& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -3903,22 +5443,23 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobu
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const PROTOBUF_FINAL;
void InternalSwap(GeneratedCodeInfo_Annotation* other);
+ protected:
+ explicit GeneratedCodeInfo_Annotation(::google::protobuf::Arena* arena);
+ private:
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
- return NULL;
+ return _internal_metadata_.arena();
}
inline void* MaybeArenaPtr() const {
- return NULL;
+ return _internal_metadata_.raw_arena_ptr();
}
public:
@@ -3946,11 +5487,23 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobu
static const int kSourceFileFieldNumber = 2;
const ::std::string& source_file() const;
void set_source_file(const ::std::string& value);
+ #if LANG_CXX11
+ void set_source_file(::std::string&& value);
+ #endif
void set_source_file(const char* value);
void set_source_file(const char* value, size_t size);
::std::string* mutable_source_file();
::std::string* release_source_file();
void set_allocated_source_file(::std::string* source_file);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ ::std::string* unsafe_arena_release_source_file();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_source_file(
+ ::std::string* source_file);
// optional int32 begin = 3;
bool has_begin() const;
@@ -3976,6 +5529,9 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobu
void clear_has_end();
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::RepeatedField< ::google::protobuf::int32 > path_;
@@ -3983,11 +5539,8 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobu
::google::protobuf::internal::ArenaStringPtr source_file_;
::google::protobuf::int32 begin_;
::google::protobuf::int32 end_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fdescriptor_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsGeneratedCodeInfo_AnnotationImpl();
};
// -------------------------------------------------------------------
@@ -4002,24 +5555,50 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo : public ::google::protobuf::Message
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ GeneratedCodeInfo(GeneratedCodeInfo&& from) noexcept
+ : GeneratedCodeInfo() {
+ *this = ::std::move(from);
+ }
+ inline GeneratedCodeInfo& operator=(GeneratedCodeInfo&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
-
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
+ inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
+ return GetArenaNoVirtual();
+ }
+ inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
+ return MaybeArenaPtr();
+ }
static const ::google::protobuf::Descriptor* descriptor();
static const GeneratedCodeInfo& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const GeneratedCodeInfo* internal_default_instance() {
return reinterpret_cast<const GeneratedCodeInfo*>(
&_GeneratedCodeInfo_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 26;
+ void UnsafeArenaSwap(GeneratedCodeInfo* other);
void Swap(GeneratedCodeInfo* other);
+ friend void swap(GeneratedCodeInfo& a, GeneratedCodeInfo& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -4040,22 +5619,23 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo : public ::google::protobuf::Message
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const PROTOBUF_FINAL;
void InternalSwap(GeneratedCodeInfo* other);
+ protected:
+ explicit GeneratedCodeInfo(::google::protobuf::Arena* arena);
+ private:
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
- return NULL;
+ return _internal_metadata_.arena();
}
inline void* MaybeArenaPtr() const {
- return NULL;
+ return _internal_metadata_.raw_arena_ptr();
}
public:
@@ -4083,21 +5663,24 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo : public ::google::protobuf::Message
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::GeneratedCodeInfo_Annotation > annotation_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fdescriptor_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsGeneratedCodeInfoImpl();
};
// ===================================================================
// ===================================================================
-#if !PROTOBUF_INLINE_NOT_IN_HEADERS
+#ifdef __GNUC__
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wstrict-aliasing"
+#endif // __GNUC__
// FileDescriptorSet
// repeated .google.protobuf.FileDescriptorProto file = 1;
@@ -4145,38 +5728,49 @@ inline void FileDescriptorProto::clear_has_name() {
_has_bits_[0] &= ~0x00000001u;
}
inline void FileDescriptorProto::clear_name() {
- name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
clear_has_name();
}
inline const ::std::string& FileDescriptorProto::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.name)
- return name_.GetNoArena();
+ return name_.Get();
}
inline void FileDescriptorProto::set_name(const ::std::string& value) {
set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.FileDescriptorProto.name)
}
+#if LANG_CXX11
+inline void FileDescriptorProto::set_name(::std::string&& value) {
+ set_has_name();
+ name_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileDescriptorProto.name)
+}
+#endif
inline void FileDescriptorProto::set_name(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.FileDescriptorProto.name)
}
-inline void FileDescriptorProto::set_name(const char* value, size_t size) {
+inline void FileDescriptorProto::set_name(const char* value,
+ size_t size) {
set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FileDescriptorProto.name)
}
inline ::std::string* FileDescriptorProto::mutable_name() {
set_has_name();
// @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.name)
- return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* FileDescriptorProto::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.FileDescriptorProto.name)
clear_has_name();
- return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FileDescriptorProto::set_allocated_name(::std::string* name) {
if (name != NULL) {
@@ -4184,9 +5778,29 @@ inline void FileDescriptorProto::set_allocated_name(::std::string* name) {
} else {
clear_has_name();
}
- name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name);
+ name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FileDescriptorProto.name)
}
+inline ::std::string* FileDescriptorProto::unsafe_arena_release_name() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileDescriptorProto.name)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ clear_has_name();
+ return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
+inline void FileDescriptorProto::unsafe_arena_set_allocated_name(
+ ::std::string* name) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (name != NULL) {
+ set_has_name();
+ } else {
+ clear_has_name();
+ }
+ name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ name, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileDescriptorProto.name)
+}
// optional string package = 2;
inline bool FileDescriptorProto::has_package() const {
@@ -4199,38 +5813,49 @@ inline void FileDescriptorProto::clear_has_package() {
_has_bits_[0] &= ~0x00000002u;
}
inline void FileDescriptorProto::clear_package() {
- package_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ package_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
clear_has_package();
}
inline const ::std::string& FileDescriptorProto::package() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.package)
- return package_.GetNoArena();
+ return package_.Get();
}
inline void FileDescriptorProto::set_package(const ::std::string& value) {
set_has_package();
- package_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ package_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.FileDescriptorProto.package)
}
+#if LANG_CXX11
+inline void FileDescriptorProto::set_package(::std::string&& value) {
+ set_has_package();
+ package_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileDescriptorProto.package)
+}
+#endif
inline void FileDescriptorProto::set_package(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
set_has_package();
- package_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ package_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.FileDescriptorProto.package)
}
-inline void FileDescriptorProto::set_package(const char* value, size_t size) {
+inline void FileDescriptorProto::set_package(const char* value,
+ size_t size) {
set_has_package();
- package_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ package_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FileDescriptorProto.package)
}
inline ::std::string* FileDescriptorProto::mutable_package() {
set_has_package();
// @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.package)
- return package_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return package_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* FileDescriptorProto::release_package() {
// @@protoc_insertion_point(field_release:google.protobuf.FileDescriptorProto.package)
clear_has_package();
- return package_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return package_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FileDescriptorProto::set_allocated_package(::std::string* package) {
if (package != NULL) {
@@ -4238,9 +5863,29 @@ inline void FileDescriptorProto::set_allocated_package(::std::string* package) {
} else {
clear_has_package();
}
- package_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), package);
+ package_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), package,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FileDescriptorProto.package)
}
+inline ::std::string* FileDescriptorProto::unsafe_arena_release_package() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileDescriptorProto.package)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ clear_has_package();
+ return package_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
+inline void FileDescriptorProto::unsafe_arena_set_allocated_package(
+ ::std::string* package) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (package != NULL) {
+ set_has_package();
+ } else {
+ clear_has_package();
+ }
+ package_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ package, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileDescriptorProto.package)
+}
// repeated string dependency = 3;
inline int FileDescriptorProto::dependency_size() const {
@@ -4261,7 +5906,14 @@ inline void FileDescriptorProto::set_dependency(int index, const ::std::string&
// @@protoc_insertion_point(field_set:google.protobuf.FileDescriptorProto.dependency)
dependency_.Mutable(index)->assign(value);
}
+#if LANG_CXX11
+inline void FileDescriptorProto::set_dependency(int index, ::std::string&& value) {
+ // @@protoc_insertion_point(field_set:google.protobuf.FileDescriptorProto.dependency)
+ dependency_.Mutable(index)->assign(std::move(value));
+}
+#endif
inline void FileDescriptorProto::set_dependency(int index, const char* value) {
+ GOOGLE_DCHECK(value != NULL);
dependency_.Mutable(index)->assign(value);
// @@protoc_insertion_point(field_set_char:google.protobuf.FileDescriptorProto.dependency)
}
@@ -4278,7 +5930,14 @@ inline void FileDescriptorProto::add_dependency(const ::std::string& value) {
dependency_.Add()->assign(value);
// @@protoc_insertion_point(field_add:google.protobuf.FileDescriptorProto.dependency)
}
+#if LANG_CXX11
+inline void FileDescriptorProto::add_dependency(::std::string&& value) {
+ dependency_.Add(std::move(value));
+ // @@protoc_insertion_point(field_add:google.protobuf.FileDescriptorProto.dependency)
+}
+#endif
inline void FileDescriptorProto::add_dependency(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
dependency_.Add()->assign(value);
// @@protoc_insertion_point(field_add_char:google.protobuf.FileDescriptorProto.dependency)
}
@@ -4488,37 +6147,57 @@ inline void FileDescriptorProto::clear_has_options() {
_has_bits_[0] &= ~0x00000008u;
}
inline void FileDescriptorProto::clear_options() {
- if (options_ != NULL) options_->::google::protobuf::FileOptions::Clear();
+ if (options_ != NULL) options_->Clear();
clear_has_options();
}
inline const ::google::protobuf::FileOptions& FileDescriptorProto::options() const {
+ const ::google::protobuf::FileOptions* p = options_;
// @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.options)
- return options_ != NULL ? *options_
- : *::google::protobuf::FileOptions::internal_default_instance();
-}
-inline ::google::protobuf::FileOptions* FileDescriptorProto::mutable_options() {
- set_has_options();
- if (options_ == NULL) {
- options_ = new ::google::protobuf::FileOptions;
- }
- // @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.options)
- return options_;
+ return p != NULL ? *p : *reinterpret_cast<const ::google::protobuf::FileOptions*>(
+ &::google::protobuf::_FileOptions_default_instance_);
}
inline ::google::protobuf::FileOptions* FileDescriptorProto::release_options() {
// @@protoc_insertion_point(field_release:google.protobuf.FileDescriptorProto.options)
clear_has_options();
::google::protobuf::FileOptions* temp = options_;
+ if (GetArenaNoVirtual() != NULL) {
+ temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL);
+ }
options_ = NULL;
return temp;
}
+inline ::google::protobuf::FileOptions* FileDescriptorProto::unsafe_arena_release_options() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileDescriptorProto.options)
+ clear_has_options();
+ ::google::protobuf::FileOptions* temp = options_;
+ options_ = NULL;
+ return temp;
+}
+inline ::google::protobuf::FileOptions* FileDescriptorProto::mutable_options() {
+ set_has_options();
+ if (options_ == NULL) {
+ _slow_mutable_options();
+ }
+ // @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.options)
+ return options_;
+}
inline void FileDescriptorProto::set_allocated_options(::google::protobuf::FileOptions* options) {
- delete options_;
- options_ = options;
+ ::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
+ if (message_arena == NULL) {
+ delete options_;
+ }
if (options) {
+ ::google::protobuf::Arena* submessage_arena =
+ ::google::protobuf::Arena::GetArena(options);
+ if (message_arena != submessage_arena) {
+ options = ::google::protobuf::internal::GetOwnedMessage(
+ message_arena, options, submessage_arena);
+ }
set_has_options();
} else {
clear_has_options();
}
+ options_ = options;
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FileDescriptorProto.options)
}
@@ -4533,37 +6212,57 @@ inline void FileDescriptorProto::clear_has_source_code_info() {
_has_bits_[0] &= ~0x00000010u;
}
inline void FileDescriptorProto::clear_source_code_info() {
- if (source_code_info_ != NULL) source_code_info_->::google::protobuf::SourceCodeInfo::Clear();
+ if (source_code_info_ != NULL) source_code_info_->Clear();
clear_has_source_code_info();
}
inline const ::google::protobuf::SourceCodeInfo& FileDescriptorProto::source_code_info() const {
+ const ::google::protobuf::SourceCodeInfo* p = source_code_info_;
// @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.source_code_info)
- return source_code_info_ != NULL ? *source_code_info_
- : *::google::protobuf::SourceCodeInfo::internal_default_instance();
-}
-inline ::google::protobuf::SourceCodeInfo* FileDescriptorProto::mutable_source_code_info() {
- set_has_source_code_info();
- if (source_code_info_ == NULL) {
- source_code_info_ = new ::google::protobuf::SourceCodeInfo;
- }
- // @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.source_code_info)
- return source_code_info_;
+ return p != NULL ? *p : *reinterpret_cast<const ::google::protobuf::SourceCodeInfo*>(
+ &::google::protobuf::_SourceCodeInfo_default_instance_);
}
inline ::google::protobuf::SourceCodeInfo* FileDescriptorProto::release_source_code_info() {
// @@protoc_insertion_point(field_release:google.protobuf.FileDescriptorProto.source_code_info)
clear_has_source_code_info();
::google::protobuf::SourceCodeInfo* temp = source_code_info_;
+ if (GetArenaNoVirtual() != NULL) {
+ temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL);
+ }
source_code_info_ = NULL;
return temp;
}
+inline ::google::protobuf::SourceCodeInfo* FileDescriptorProto::unsafe_arena_release_source_code_info() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileDescriptorProto.source_code_info)
+ clear_has_source_code_info();
+ ::google::protobuf::SourceCodeInfo* temp = source_code_info_;
+ source_code_info_ = NULL;
+ return temp;
+}
+inline ::google::protobuf::SourceCodeInfo* FileDescriptorProto::mutable_source_code_info() {
+ set_has_source_code_info();
+ if (source_code_info_ == NULL) {
+ _slow_mutable_source_code_info();
+ }
+ // @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.source_code_info)
+ return source_code_info_;
+}
inline void FileDescriptorProto::set_allocated_source_code_info(::google::protobuf::SourceCodeInfo* source_code_info) {
- delete source_code_info_;
- source_code_info_ = source_code_info;
+ ::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
+ if (message_arena == NULL) {
+ delete source_code_info_;
+ }
if (source_code_info) {
+ ::google::protobuf::Arena* submessage_arena =
+ ::google::protobuf::Arena::GetArena(source_code_info);
+ if (message_arena != submessage_arena) {
+ source_code_info = ::google::protobuf::internal::GetOwnedMessage(
+ message_arena, source_code_info, submessage_arena);
+ }
set_has_source_code_info();
} else {
clear_has_source_code_info();
}
+ source_code_info_ = source_code_info;
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FileDescriptorProto.source_code_info)
}
@@ -4578,38 +6277,49 @@ inline void FileDescriptorProto::clear_has_syntax() {
_has_bits_[0] &= ~0x00000004u;
}
inline void FileDescriptorProto::clear_syntax() {
- syntax_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ syntax_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
clear_has_syntax();
}
inline const ::std::string& FileDescriptorProto::syntax() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.syntax)
- return syntax_.GetNoArena();
+ return syntax_.Get();
}
inline void FileDescriptorProto::set_syntax(const ::std::string& value) {
set_has_syntax();
- syntax_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ syntax_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.FileDescriptorProto.syntax)
}
+#if LANG_CXX11
+inline void FileDescriptorProto::set_syntax(::std::string&& value) {
+ set_has_syntax();
+ syntax_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileDescriptorProto.syntax)
+}
+#endif
inline void FileDescriptorProto::set_syntax(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
set_has_syntax();
- syntax_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ syntax_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.FileDescriptorProto.syntax)
}
-inline void FileDescriptorProto::set_syntax(const char* value, size_t size) {
+inline void FileDescriptorProto::set_syntax(const char* value,
+ size_t size) {
set_has_syntax();
- syntax_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ syntax_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FileDescriptorProto.syntax)
}
inline ::std::string* FileDescriptorProto::mutable_syntax() {
set_has_syntax();
// @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.syntax)
- return syntax_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return syntax_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* FileDescriptorProto::release_syntax() {
// @@protoc_insertion_point(field_release:google.protobuf.FileDescriptorProto.syntax)
clear_has_syntax();
- return syntax_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return syntax_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FileDescriptorProto::set_allocated_syntax(::std::string* syntax) {
if (syntax != NULL) {
@@ -4617,9 +6327,29 @@ inline void FileDescriptorProto::set_allocated_syntax(::std::string* syntax) {
} else {
clear_has_syntax();
}
- syntax_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), syntax);
+ syntax_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), syntax,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FileDescriptorProto.syntax)
}
+inline ::std::string* FileDescriptorProto::unsafe_arena_release_syntax() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileDescriptorProto.syntax)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ clear_has_syntax();
+ return syntax_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
+inline void FileDescriptorProto::unsafe_arena_set_allocated_syntax(
+ ::std::string* syntax) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (syntax != NULL) {
+ set_has_syntax();
+ } else {
+ clear_has_syntax();
+ }
+ syntax_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ syntax, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileDescriptorProto.syntax)
+}
// -------------------------------------------------------------------
@@ -4627,13 +6357,13 @@ inline void FileDescriptorProto::set_allocated_syntax(::std::string* syntax) {
// optional int32 start = 1;
inline bool DescriptorProto_ExtensionRange::has_start() const {
- return (_has_bits_[0] & 0x00000001u) != 0;
+ return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void DescriptorProto_ExtensionRange::set_has_start() {
- _has_bits_[0] |= 0x00000001u;
+ _has_bits_[0] |= 0x00000002u;
}
inline void DescriptorProto_ExtensionRange::clear_has_start() {
- _has_bits_[0] &= ~0x00000001u;
+ _has_bits_[0] &= ~0x00000002u;
}
inline void DescriptorProto_ExtensionRange::clear_start() {
start_ = 0;
@@ -4651,13 +6381,13 @@ inline void DescriptorProto_ExtensionRange::set_start(::google::protobuf::int32
// optional int32 end = 2;
inline bool DescriptorProto_ExtensionRange::has_end() const {
- return (_has_bits_[0] & 0x00000002u) != 0;
+ return (_has_bits_[0] & 0x00000004u) != 0;
}
inline void DescriptorProto_ExtensionRange::set_has_end() {
- _has_bits_[0] |= 0x00000002u;
+ _has_bits_[0] |= 0x00000004u;
}
inline void DescriptorProto_ExtensionRange::clear_has_end() {
- _has_bits_[0] &= ~0x00000002u;
+ _has_bits_[0] &= ~0x00000004u;
}
inline void DescriptorProto_ExtensionRange::clear_end() {
end_ = 0;
@@ -4673,6 +6403,71 @@ inline void DescriptorProto_ExtensionRange::set_end(::google::protobuf::int32 va
// @@protoc_insertion_point(field_set:google.protobuf.DescriptorProto.ExtensionRange.end)
}
+// optional .google.protobuf.ExtensionRangeOptions options = 3;
+inline bool DescriptorProto_ExtensionRange::has_options() const {
+ return (_has_bits_[0] & 0x00000001u) != 0;
+}
+inline void DescriptorProto_ExtensionRange::set_has_options() {
+ _has_bits_[0] |= 0x00000001u;
+}
+inline void DescriptorProto_ExtensionRange::clear_has_options() {
+ _has_bits_[0] &= ~0x00000001u;
+}
+inline void DescriptorProto_ExtensionRange::clear_options() {
+ if (options_ != NULL) options_->Clear();
+ clear_has_options();
+}
+inline const ::google::protobuf::ExtensionRangeOptions& DescriptorProto_ExtensionRange::options() const {
+ const ::google::protobuf::ExtensionRangeOptions* p = options_;
+ // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.ExtensionRange.options)
+ return p != NULL ? *p : *reinterpret_cast<const ::google::protobuf::ExtensionRangeOptions*>(
+ &::google::protobuf::_ExtensionRangeOptions_default_instance_);
+}
+inline ::google::protobuf::ExtensionRangeOptions* DescriptorProto_ExtensionRange::release_options() {
+ // @@protoc_insertion_point(field_release:google.protobuf.DescriptorProto.ExtensionRange.options)
+ clear_has_options();
+ ::google::protobuf::ExtensionRangeOptions* temp = options_;
+ if (GetArenaNoVirtual() != NULL) {
+ temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL);
+ }
+ options_ = NULL;
+ return temp;
+}
+inline ::google::protobuf::ExtensionRangeOptions* DescriptorProto_ExtensionRange::unsafe_arena_release_options() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.DescriptorProto.ExtensionRange.options)
+ clear_has_options();
+ ::google::protobuf::ExtensionRangeOptions* temp = options_;
+ options_ = NULL;
+ return temp;
+}
+inline ::google::protobuf::ExtensionRangeOptions* DescriptorProto_ExtensionRange::mutable_options() {
+ set_has_options();
+ if (options_ == NULL) {
+ _slow_mutable_options();
+ }
+ // @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.ExtensionRange.options)
+ return options_;
+}
+inline void DescriptorProto_ExtensionRange::set_allocated_options(::google::protobuf::ExtensionRangeOptions* options) {
+ ::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
+ if (message_arena == NULL) {
+ delete options_;
+ }
+ if (options) {
+ ::google::protobuf::Arena* submessage_arena =
+ ::google::protobuf::Arena::GetArena(options);
+ if (message_arena != submessage_arena) {
+ options = ::google::protobuf::internal::GetOwnedMessage(
+ message_arena, options, submessage_arena);
+ }
+ set_has_options();
+ } else {
+ clear_has_options();
+ }
+ options_ = options;
+ // @@protoc_insertion_point(field_set_allocated:google.protobuf.DescriptorProto.ExtensionRange.options)
+}
+
// -------------------------------------------------------------------
// DescriptorProto_ReservedRange
@@ -4740,38 +6535,49 @@ inline void DescriptorProto::clear_has_name() {
_has_bits_[0] &= ~0x00000001u;
}
inline void DescriptorProto::clear_name() {
- name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
clear_has_name();
}
inline const ::std::string& DescriptorProto::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.name)
- return name_.GetNoArena();
+ return name_.Get();
}
inline void DescriptorProto::set_name(const ::std::string& value) {
set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.DescriptorProto.name)
}
+#if LANG_CXX11
+inline void DescriptorProto::set_name(::std::string&& value) {
+ set_has_name();
+ name_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.DescriptorProto.name)
+}
+#endif
inline void DescriptorProto::set_name(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.DescriptorProto.name)
}
-inline void DescriptorProto::set_name(const char* value, size_t size) {
+inline void DescriptorProto::set_name(const char* value,
+ size_t size) {
set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.DescriptorProto.name)
}
inline ::std::string* DescriptorProto::mutable_name() {
set_has_name();
// @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.name)
- return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* DescriptorProto::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.DescriptorProto.name)
clear_has_name();
- return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void DescriptorProto::set_allocated_name(::std::string* name) {
if (name != NULL) {
@@ -4779,9 +6585,29 @@ inline void DescriptorProto::set_allocated_name(::std::string* name) {
} else {
clear_has_name();
}
- name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name);
+ name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.DescriptorProto.name)
}
+inline ::std::string* DescriptorProto::unsafe_arena_release_name() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.DescriptorProto.name)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ clear_has_name();
+ return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
+inline void DescriptorProto::unsafe_arena_set_allocated_name(
+ ::std::string* name) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (name != NULL) {
+ set_has_name();
+ } else {
+ clear_has_name();
+ }
+ name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ name, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.DescriptorProto.name)
+}
// repeated .google.protobuf.FieldDescriptorProto field = 2;
inline int DescriptorProto::field_size() const {
@@ -4974,37 +6800,57 @@ inline void DescriptorProto::clear_has_options() {
_has_bits_[0] &= ~0x00000002u;
}
inline void DescriptorProto::clear_options() {
- if (options_ != NULL) options_->::google::protobuf::MessageOptions::Clear();
+ if (options_ != NULL) options_->Clear();
clear_has_options();
}
inline const ::google::protobuf::MessageOptions& DescriptorProto::options() const {
+ const ::google::protobuf::MessageOptions* p = options_;
// @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.options)
- return options_ != NULL ? *options_
- : *::google::protobuf::MessageOptions::internal_default_instance();
-}
-inline ::google::protobuf::MessageOptions* DescriptorProto::mutable_options() {
- set_has_options();
- if (options_ == NULL) {
- options_ = new ::google::protobuf::MessageOptions;
- }
- // @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.options)
- return options_;
+ return p != NULL ? *p : *reinterpret_cast<const ::google::protobuf::MessageOptions*>(
+ &::google::protobuf::_MessageOptions_default_instance_);
}
inline ::google::protobuf::MessageOptions* DescriptorProto::release_options() {
// @@protoc_insertion_point(field_release:google.protobuf.DescriptorProto.options)
clear_has_options();
::google::protobuf::MessageOptions* temp = options_;
+ if (GetArenaNoVirtual() != NULL) {
+ temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL);
+ }
+ options_ = NULL;
+ return temp;
+}
+inline ::google::protobuf::MessageOptions* DescriptorProto::unsafe_arena_release_options() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.DescriptorProto.options)
+ clear_has_options();
+ ::google::protobuf::MessageOptions* temp = options_;
options_ = NULL;
return temp;
}
+inline ::google::protobuf::MessageOptions* DescriptorProto::mutable_options() {
+ set_has_options();
+ if (options_ == NULL) {
+ _slow_mutable_options();
+ }
+ // @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.options)
+ return options_;
+}
inline void DescriptorProto::set_allocated_options(::google::protobuf::MessageOptions* options) {
- delete options_;
- options_ = options;
+ ::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
+ if (message_arena == NULL) {
+ delete options_;
+ }
if (options) {
+ ::google::protobuf::Arena* submessage_arena =
+ ::google::protobuf::Arena::GetArena(options);
+ if (message_arena != submessage_arena) {
+ options = ::google::protobuf::internal::GetOwnedMessage(
+ message_arena, options, submessage_arena);
+ }
set_has_options();
} else {
clear_has_options();
}
+ options_ = options;
// @@protoc_insertion_point(field_set_allocated:google.protobuf.DescriptorProto.options)
}
@@ -5057,7 +6903,14 @@ inline void DescriptorProto::set_reserved_name(int index, const ::std::string& v
// @@protoc_insertion_point(field_set:google.protobuf.DescriptorProto.reserved_name)
reserved_name_.Mutable(index)->assign(value);
}
+#if LANG_CXX11
+inline void DescriptorProto::set_reserved_name(int index, ::std::string&& value) {
+ // @@protoc_insertion_point(field_set:google.protobuf.DescriptorProto.reserved_name)
+ reserved_name_.Mutable(index)->assign(std::move(value));
+}
+#endif
inline void DescriptorProto::set_reserved_name(int index, const char* value) {
+ GOOGLE_DCHECK(value != NULL);
reserved_name_.Mutable(index)->assign(value);
// @@protoc_insertion_point(field_set_char:google.protobuf.DescriptorProto.reserved_name)
}
@@ -5074,7 +6927,14 @@ inline void DescriptorProto::add_reserved_name(const ::std::string& value) {
reserved_name_.Add()->assign(value);
// @@protoc_insertion_point(field_add:google.protobuf.DescriptorProto.reserved_name)
}
+#if LANG_CXX11
+inline void DescriptorProto::add_reserved_name(::std::string&& value) {
+ reserved_name_.Add(std::move(value));
+ // @@protoc_insertion_point(field_add:google.protobuf.DescriptorProto.reserved_name)
+}
+#endif
inline void DescriptorProto::add_reserved_name(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
reserved_name_.Add()->assign(value);
// @@protoc_insertion_point(field_add_char:google.protobuf.DescriptorProto.reserved_name)
}
@@ -5095,6 +6955,40 @@ DescriptorProto::mutable_reserved_name() {
// -------------------------------------------------------------------
+// ExtensionRangeOptions
+
+// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
+inline int ExtensionRangeOptions::uninterpreted_option_size() const {
+ return uninterpreted_option_.size();
+}
+inline void ExtensionRangeOptions::clear_uninterpreted_option() {
+ uninterpreted_option_.Clear();
+}
+inline const ::google::protobuf::UninterpretedOption& ExtensionRangeOptions::uninterpreted_option(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.ExtensionRangeOptions.uninterpreted_option)
+ return uninterpreted_option_.Get(index);
+}
+inline ::google::protobuf::UninterpretedOption* ExtensionRangeOptions::mutable_uninterpreted_option(int index) {
+ // @@protoc_insertion_point(field_mutable:google.protobuf.ExtensionRangeOptions.uninterpreted_option)
+ return uninterpreted_option_.Mutable(index);
+}
+inline ::google::protobuf::UninterpretedOption* ExtensionRangeOptions::add_uninterpreted_option() {
+ // @@protoc_insertion_point(field_add:google.protobuf.ExtensionRangeOptions.uninterpreted_option)
+ return uninterpreted_option_.Add();
+}
+inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >*
+ExtensionRangeOptions::mutable_uninterpreted_option() {
+ // @@protoc_insertion_point(field_mutable_list:google.protobuf.ExtensionRangeOptions.uninterpreted_option)
+ return &uninterpreted_option_;
+}
+inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >&
+ExtensionRangeOptions::uninterpreted_option() const {
+ // @@protoc_insertion_point(field_list:google.protobuf.ExtensionRangeOptions.uninterpreted_option)
+ return uninterpreted_option_;
+}
+
+// -------------------------------------------------------------------
+
// FieldDescriptorProto
// optional string name = 1;
@@ -5108,38 +7002,49 @@ inline void FieldDescriptorProto::clear_has_name() {
_has_bits_[0] &= ~0x00000001u;
}
inline void FieldDescriptorProto::clear_name() {
- name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
clear_has_name();
}
inline const ::std::string& FieldDescriptorProto::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.name)
- return name_.GetNoArena();
+ return name_.Get();
}
inline void FieldDescriptorProto::set_name(const ::std::string& value) {
set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.name)
}
+#if LANG_CXX11
+inline void FieldDescriptorProto::set_name(::std::string&& value) {
+ set_has_name();
+ name_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.FieldDescriptorProto.name)
+}
+#endif
inline void FieldDescriptorProto::set_name(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.FieldDescriptorProto.name)
}
-inline void FieldDescriptorProto::set_name(const char* value, size_t size) {
+inline void FieldDescriptorProto::set_name(const char* value,
+ size_t size) {
set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FieldDescriptorProto.name)
}
inline ::std::string* FieldDescriptorProto::mutable_name() {
set_has_name();
// @@protoc_insertion_point(field_mutable:google.protobuf.FieldDescriptorProto.name)
- return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* FieldDescriptorProto::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.name)
clear_has_name();
- return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FieldDescriptorProto::set_allocated_name(::std::string* name) {
if (name != NULL) {
@@ -5147,9 +7052,29 @@ inline void FieldDescriptorProto::set_allocated_name(::std::string* name) {
} else {
clear_has_name();
}
- name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name);
+ name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FieldDescriptorProto.name)
}
+inline ::std::string* FieldDescriptorProto::unsafe_arena_release_name() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FieldDescriptorProto.name)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ clear_has_name();
+ return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
+inline void FieldDescriptorProto::unsafe_arena_set_allocated_name(
+ ::std::string* name) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (name != NULL) {
+ set_has_name();
+ } else {
+ clear_has_name();
+ }
+ name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ name, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FieldDescriptorProto.name)
+}
// optional int32 number = 3;
inline bool FieldDescriptorProto::has_number() const {
@@ -5227,47 +7152,58 @@ inline void FieldDescriptorProto::set_type(::google::protobuf::FieldDescriptorPr
// optional string type_name = 6;
inline bool FieldDescriptorProto::has_type_name() const {
- return (_has_bits_[0] & 0x00000002u) != 0;
+ return (_has_bits_[0] & 0x00000004u) != 0;
}
inline void FieldDescriptorProto::set_has_type_name() {
- _has_bits_[0] |= 0x00000002u;
+ _has_bits_[0] |= 0x00000004u;
}
inline void FieldDescriptorProto::clear_has_type_name() {
- _has_bits_[0] &= ~0x00000002u;
+ _has_bits_[0] &= ~0x00000004u;
}
inline void FieldDescriptorProto::clear_type_name() {
- type_name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ type_name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
clear_has_type_name();
}
inline const ::std::string& FieldDescriptorProto::type_name() const {
// @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.type_name)
- return type_name_.GetNoArena();
+ return type_name_.Get();
}
inline void FieldDescriptorProto::set_type_name(const ::std::string& value) {
set_has_type_name();
- type_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ type_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.type_name)
}
+#if LANG_CXX11
+inline void FieldDescriptorProto::set_type_name(::std::string&& value) {
+ set_has_type_name();
+ type_name_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.FieldDescriptorProto.type_name)
+}
+#endif
inline void FieldDescriptorProto::set_type_name(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
set_has_type_name();
- type_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ type_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.FieldDescriptorProto.type_name)
}
-inline void FieldDescriptorProto::set_type_name(const char* value, size_t size) {
+inline void FieldDescriptorProto::set_type_name(const char* value,
+ size_t size) {
set_has_type_name();
- type_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ type_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FieldDescriptorProto.type_name)
}
inline ::std::string* FieldDescriptorProto::mutable_type_name() {
set_has_type_name();
// @@protoc_insertion_point(field_mutable:google.protobuf.FieldDescriptorProto.type_name)
- return type_name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return type_name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* FieldDescriptorProto::release_type_name() {
// @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.type_name)
clear_has_type_name();
- return type_name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return type_name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FieldDescriptorProto::set_allocated_type_name(::std::string* type_name) {
if (type_name != NULL) {
@@ -5275,53 +7211,84 @@ inline void FieldDescriptorProto::set_allocated_type_name(::std::string* type_na
} else {
clear_has_type_name();
}
- type_name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), type_name);
+ type_name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), type_name,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FieldDescriptorProto.type_name)
}
+inline ::std::string* FieldDescriptorProto::unsafe_arena_release_type_name() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FieldDescriptorProto.type_name)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ clear_has_type_name();
+ return type_name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
+inline void FieldDescriptorProto::unsafe_arena_set_allocated_type_name(
+ ::std::string* type_name) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (type_name != NULL) {
+ set_has_type_name();
+ } else {
+ clear_has_type_name();
+ }
+ type_name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ type_name, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FieldDescriptorProto.type_name)
+}
// optional string extendee = 2;
inline bool FieldDescriptorProto::has_extendee() const {
- return (_has_bits_[0] & 0x00000004u) != 0;
+ return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void FieldDescriptorProto::set_has_extendee() {
- _has_bits_[0] |= 0x00000004u;
+ _has_bits_[0] |= 0x00000002u;
}
inline void FieldDescriptorProto::clear_has_extendee() {
- _has_bits_[0] &= ~0x00000004u;
+ _has_bits_[0] &= ~0x00000002u;
}
inline void FieldDescriptorProto::clear_extendee() {
- extendee_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ extendee_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
clear_has_extendee();
}
inline const ::std::string& FieldDescriptorProto::extendee() const {
// @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.extendee)
- return extendee_.GetNoArena();
+ return extendee_.Get();
}
inline void FieldDescriptorProto::set_extendee(const ::std::string& value) {
set_has_extendee();
- extendee_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ extendee_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.extendee)
}
+#if LANG_CXX11
+inline void FieldDescriptorProto::set_extendee(::std::string&& value) {
+ set_has_extendee();
+ extendee_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.FieldDescriptorProto.extendee)
+}
+#endif
inline void FieldDescriptorProto::set_extendee(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
set_has_extendee();
- extendee_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ extendee_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.FieldDescriptorProto.extendee)
}
-inline void FieldDescriptorProto::set_extendee(const char* value, size_t size) {
+inline void FieldDescriptorProto::set_extendee(const char* value,
+ size_t size) {
set_has_extendee();
- extendee_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ extendee_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FieldDescriptorProto.extendee)
}
inline ::std::string* FieldDescriptorProto::mutable_extendee() {
set_has_extendee();
// @@protoc_insertion_point(field_mutable:google.protobuf.FieldDescriptorProto.extendee)
- return extendee_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return extendee_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* FieldDescriptorProto::release_extendee() {
// @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.extendee)
clear_has_extendee();
- return extendee_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return extendee_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FieldDescriptorProto::set_allocated_extendee(::std::string* extendee) {
if (extendee != NULL) {
@@ -5329,9 +7296,29 @@ inline void FieldDescriptorProto::set_allocated_extendee(::std::string* extendee
} else {
clear_has_extendee();
}
- extendee_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), extendee);
+ extendee_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), extendee,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FieldDescriptorProto.extendee)
}
+inline ::std::string* FieldDescriptorProto::unsafe_arena_release_extendee() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FieldDescriptorProto.extendee)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ clear_has_extendee();
+ return extendee_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
+inline void FieldDescriptorProto::unsafe_arena_set_allocated_extendee(
+ ::std::string* extendee) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (extendee != NULL) {
+ set_has_extendee();
+ } else {
+ clear_has_extendee();
+ }
+ extendee_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ extendee, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FieldDescriptorProto.extendee)
+}
// optional string default_value = 7;
inline bool FieldDescriptorProto::has_default_value() const {
@@ -5344,38 +7331,49 @@ inline void FieldDescriptorProto::clear_has_default_value() {
_has_bits_[0] &= ~0x00000008u;
}
inline void FieldDescriptorProto::clear_default_value() {
- default_value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ default_value_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
clear_has_default_value();
}
inline const ::std::string& FieldDescriptorProto::default_value() const {
// @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.default_value)
- return default_value_.GetNoArena();
+ return default_value_.Get();
}
inline void FieldDescriptorProto::set_default_value(const ::std::string& value) {
set_has_default_value();
- default_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ default_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.default_value)
}
+#if LANG_CXX11
+inline void FieldDescriptorProto::set_default_value(::std::string&& value) {
+ set_has_default_value();
+ default_value_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.FieldDescriptorProto.default_value)
+}
+#endif
inline void FieldDescriptorProto::set_default_value(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
set_has_default_value();
- default_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ default_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.FieldDescriptorProto.default_value)
}
-inline void FieldDescriptorProto::set_default_value(const char* value, size_t size) {
+inline void FieldDescriptorProto::set_default_value(const char* value,
+ size_t size) {
set_has_default_value();
- default_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ default_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FieldDescriptorProto.default_value)
}
inline ::std::string* FieldDescriptorProto::mutable_default_value() {
set_has_default_value();
// @@protoc_insertion_point(field_mutable:google.protobuf.FieldDescriptorProto.default_value)
- return default_value_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return default_value_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* FieldDescriptorProto::release_default_value() {
// @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.default_value)
clear_has_default_value();
- return default_value_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return default_value_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FieldDescriptorProto::set_allocated_default_value(::std::string* default_value) {
if (default_value != NULL) {
@@ -5383,9 +7381,29 @@ inline void FieldDescriptorProto::set_allocated_default_value(::std::string* def
} else {
clear_has_default_value();
}
- default_value_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), default_value);
+ default_value_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), default_value,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FieldDescriptorProto.default_value)
}
+inline ::std::string* FieldDescriptorProto::unsafe_arena_release_default_value() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FieldDescriptorProto.default_value)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ clear_has_default_value();
+ return default_value_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
+inline void FieldDescriptorProto::unsafe_arena_set_allocated_default_value(
+ ::std::string* default_value) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (default_value != NULL) {
+ set_has_default_value();
+ } else {
+ clear_has_default_value();
+ }
+ default_value_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ default_value, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FieldDescriptorProto.default_value)
+}
// optional int32 oneof_index = 9;
inline bool FieldDescriptorProto::has_oneof_index() const {
@@ -5422,38 +7440,49 @@ inline void FieldDescriptorProto::clear_has_json_name() {
_has_bits_[0] &= ~0x00000010u;
}
inline void FieldDescriptorProto::clear_json_name() {
- json_name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ json_name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
clear_has_json_name();
}
inline const ::std::string& FieldDescriptorProto::json_name() const {
// @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.json_name)
- return json_name_.GetNoArena();
+ return json_name_.Get();
}
inline void FieldDescriptorProto::set_json_name(const ::std::string& value) {
set_has_json_name();
- json_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ json_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.json_name)
}
+#if LANG_CXX11
+inline void FieldDescriptorProto::set_json_name(::std::string&& value) {
+ set_has_json_name();
+ json_name_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.FieldDescriptorProto.json_name)
+}
+#endif
inline void FieldDescriptorProto::set_json_name(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
set_has_json_name();
- json_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ json_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.FieldDescriptorProto.json_name)
}
-inline void FieldDescriptorProto::set_json_name(const char* value, size_t size) {
+inline void FieldDescriptorProto::set_json_name(const char* value,
+ size_t size) {
set_has_json_name();
- json_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ json_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FieldDescriptorProto.json_name)
}
inline ::std::string* FieldDescriptorProto::mutable_json_name() {
set_has_json_name();
// @@protoc_insertion_point(field_mutable:google.protobuf.FieldDescriptorProto.json_name)
- return json_name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return json_name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* FieldDescriptorProto::release_json_name() {
// @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.json_name)
clear_has_json_name();
- return json_name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return json_name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FieldDescriptorProto::set_allocated_json_name(::std::string* json_name) {
if (json_name != NULL) {
@@ -5461,9 +7490,29 @@ inline void FieldDescriptorProto::set_allocated_json_name(::std::string* json_na
} else {
clear_has_json_name();
}
- json_name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), json_name);
+ json_name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), json_name,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FieldDescriptorProto.json_name)
}
+inline ::std::string* FieldDescriptorProto::unsafe_arena_release_json_name() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FieldDescriptorProto.json_name)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ clear_has_json_name();
+ return json_name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
+inline void FieldDescriptorProto::unsafe_arena_set_allocated_json_name(
+ ::std::string* json_name) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (json_name != NULL) {
+ set_has_json_name();
+ } else {
+ clear_has_json_name();
+ }
+ json_name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ json_name, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FieldDescriptorProto.json_name)
+}
// optional .google.protobuf.FieldOptions options = 8;
inline bool FieldDescriptorProto::has_options() const {
@@ -5476,37 +7525,57 @@ inline void FieldDescriptorProto::clear_has_options() {
_has_bits_[0] &= ~0x00000020u;
}
inline void FieldDescriptorProto::clear_options() {
- if (options_ != NULL) options_->::google::protobuf::FieldOptions::Clear();
+ if (options_ != NULL) options_->Clear();
clear_has_options();
}
inline const ::google::protobuf::FieldOptions& FieldDescriptorProto::options() const {
+ const ::google::protobuf::FieldOptions* p = options_;
// @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.options)
- return options_ != NULL ? *options_
- : *::google::protobuf::FieldOptions::internal_default_instance();
-}
-inline ::google::protobuf::FieldOptions* FieldDescriptorProto::mutable_options() {
- set_has_options();
- if (options_ == NULL) {
- options_ = new ::google::protobuf::FieldOptions;
- }
- // @@protoc_insertion_point(field_mutable:google.protobuf.FieldDescriptorProto.options)
- return options_;
+ return p != NULL ? *p : *reinterpret_cast<const ::google::protobuf::FieldOptions*>(
+ &::google::protobuf::_FieldOptions_default_instance_);
}
inline ::google::protobuf::FieldOptions* FieldDescriptorProto::release_options() {
// @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.options)
clear_has_options();
::google::protobuf::FieldOptions* temp = options_;
+ if (GetArenaNoVirtual() != NULL) {
+ temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL);
+ }
+ options_ = NULL;
+ return temp;
+}
+inline ::google::protobuf::FieldOptions* FieldDescriptorProto::unsafe_arena_release_options() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FieldDescriptorProto.options)
+ clear_has_options();
+ ::google::protobuf::FieldOptions* temp = options_;
options_ = NULL;
return temp;
}
+inline ::google::protobuf::FieldOptions* FieldDescriptorProto::mutable_options() {
+ set_has_options();
+ if (options_ == NULL) {
+ _slow_mutable_options();
+ }
+ // @@protoc_insertion_point(field_mutable:google.protobuf.FieldDescriptorProto.options)
+ return options_;
+}
inline void FieldDescriptorProto::set_allocated_options(::google::protobuf::FieldOptions* options) {
- delete options_;
- options_ = options;
+ ::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
+ if (message_arena == NULL) {
+ delete options_;
+ }
if (options) {
+ ::google::protobuf::Arena* submessage_arena =
+ ::google::protobuf::Arena::GetArena(options);
+ if (message_arena != submessage_arena) {
+ options = ::google::protobuf::internal::GetOwnedMessage(
+ message_arena, options, submessage_arena);
+ }
set_has_options();
} else {
clear_has_options();
}
+ options_ = options;
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FieldDescriptorProto.options)
}
@@ -5525,38 +7594,49 @@ inline void OneofDescriptorProto::clear_has_name() {
_has_bits_[0] &= ~0x00000001u;
}
inline void OneofDescriptorProto::clear_name() {
- name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
clear_has_name();
}
inline const ::std::string& OneofDescriptorProto::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.OneofDescriptorProto.name)
- return name_.GetNoArena();
+ return name_.Get();
}
inline void OneofDescriptorProto::set_name(const ::std::string& value) {
set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.OneofDescriptorProto.name)
}
+#if LANG_CXX11
+inline void OneofDescriptorProto::set_name(::std::string&& value) {
+ set_has_name();
+ name_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.OneofDescriptorProto.name)
+}
+#endif
inline void OneofDescriptorProto::set_name(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.OneofDescriptorProto.name)
}
-inline void OneofDescriptorProto::set_name(const char* value, size_t size) {
+inline void OneofDescriptorProto::set_name(const char* value,
+ size_t size) {
set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.OneofDescriptorProto.name)
}
inline ::std::string* OneofDescriptorProto::mutable_name() {
set_has_name();
// @@protoc_insertion_point(field_mutable:google.protobuf.OneofDescriptorProto.name)
- return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* OneofDescriptorProto::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.OneofDescriptorProto.name)
clear_has_name();
- return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void OneofDescriptorProto::set_allocated_name(::std::string* name) {
if (name != NULL) {
@@ -5564,9 +7644,29 @@ inline void OneofDescriptorProto::set_allocated_name(::std::string* name) {
} else {
clear_has_name();
}
- name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name);
+ name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.OneofDescriptorProto.name)
}
+inline ::std::string* OneofDescriptorProto::unsafe_arena_release_name() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.OneofDescriptorProto.name)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ clear_has_name();
+ return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
+inline void OneofDescriptorProto::unsafe_arena_set_allocated_name(
+ ::std::string* name) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (name != NULL) {
+ set_has_name();
+ } else {
+ clear_has_name();
+ }
+ name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ name, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.OneofDescriptorProto.name)
+}
// optional .google.protobuf.OneofOptions options = 2;
inline bool OneofDescriptorProto::has_options() const {
@@ -5579,42 +7679,114 @@ inline void OneofDescriptorProto::clear_has_options() {
_has_bits_[0] &= ~0x00000002u;
}
inline void OneofDescriptorProto::clear_options() {
- if (options_ != NULL) options_->::google::protobuf::OneofOptions::Clear();
+ if (options_ != NULL) options_->Clear();
clear_has_options();
}
inline const ::google::protobuf::OneofOptions& OneofDescriptorProto::options() const {
+ const ::google::protobuf::OneofOptions* p = options_;
// @@protoc_insertion_point(field_get:google.protobuf.OneofDescriptorProto.options)
- return options_ != NULL ? *options_
- : *::google::protobuf::OneofOptions::internal_default_instance();
-}
-inline ::google::protobuf::OneofOptions* OneofDescriptorProto::mutable_options() {
- set_has_options();
- if (options_ == NULL) {
- options_ = new ::google::protobuf::OneofOptions;
- }
- // @@protoc_insertion_point(field_mutable:google.protobuf.OneofDescriptorProto.options)
- return options_;
+ return p != NULL ? *p : *reinterpret_cast<const ::google::protobuf::OneofOptions*>(
+ &::google::protobuf::_OneofOptions_default_instance_);
}
inline ::google::protobuf::OneofOptions* OneofDescriptorProto::release_options() {
// @@protoc_insertion_point(field_release:google.protobuf.OneofDescriptorProto.options)
clear_has_options();
::google::protobuf::OneofOptions* temp = options_;
+ if (GetArenaNoVirtual() != NULL) {
+ temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL);
+ }
+ options_ = NULL;
+ return temp;
+}
+inline ::google::protobuf::OneofOptions* OneofDescriptorProto::unsafe_arena_release_options() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.OneofDescriptorProto.options)
+ clear_has_options();
+ ::google::protobuf::OneofOptions* temp = options_;
options_ = NULL;
return temp;
}
+inline ::google::protobuf::OneofOptions* OneofDescriptorProto::mutable_options() {
+ set_has_options();
+ if (options_ == NULL) {
+ _slow_mutable_options();
+ }
+ // @@protoc_insertion_point(field_mutable:google.protobuf.OneofDescriptorProto.options)
+ return options_;
+}
inline void OneofDescriptorProto::set_allocated_options(::google::protobuf::OneofOptions* options) {
- delete options_;
- options_ = options;
+ ::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
+ if (message_arena == NULL) {
+ delete options_;
+ }
if (options) {
+ ::google::protobuf::Arena* submessage_arena =
+ ::google::protobuf::Arena::GetArena(options);
+ if (message_arena != submessage_arena) {
+ options = ::google::protobuf::internal::GetOwnedMessage(
+ message_arena, options, submessage_arena);
+ }
set_has_options();
} else {
clear_has_options();
}
+ options_ = options;
// @@protoc_insertion_point(field_set_allocated:google.protobuf.OneofDescriptorProto.options)
}
// -------------------------------------------------------------------
+// EnumDescriptorProto_EnumReservedRange
+
+// optional int32 start = 1;
+inline bool EnumDescriptorProto_EnumReservedRange::has_start() const {
+ return (_has_bits_[0] & 0x00000001u) != 0;
+}
+inline void EnumDescriptorProto_EnumReservedRange::set_has_start() {
+ _has_bits_[0] |= 0x00000001u;
+}
+inline void EnumDescriptorProto_EnumReservedRange::clear_has_start() {
+ _has_bits_[0] &= ~0x00000001u;
+}
+inline void EnumDescriptorProto_EnumReservedRange::clear_start() {
+ start_ = 0;
+ clear_has_start();
+}
+inline ::google::protobuf::int32 EnumDescriptorProto_EnumReservedRange::start() const {
+ // @@protoc_insertion_point(field_get:google.protobuf.EnumDescriptorProto.EnumReservedRange.start)
+ return start_;
+}
+inline void EnumDescriptorProto_EnumReservedRange::set_start(::google::protobuf::int32 value) {
+ set_has_start();
+ start_ = value;
+ // @@protoc_insertion_point(field_set:google.protobuf.EnumDescriptorProto.EnumReservedRange.start)
+}
+
+// optional int32 end = 2;
+inline bool EnumDescriptorProto_EnumReservedRange::has_end() const {
+ return (_has_bits_[0] & 0x00000002u) != 0;
+}
+inline void EnumDescriptorProto_EnumReservedRange::set_has_end() {
+ _has_bits_[0] |= 0x00000002u;
+}
+inline void EnumDescriptorProto_EnumReservedRange::clear_has_end() {
+ _has_bits_[0] &= ~0x00000002u;
+}
+inline void EnumDescriptorProto_EnumReservedRange::clear_end() {
+ end_ = 0;
+ clear_has_end();
+}
+inline ::google::protobuf::int32 EnumDescriptorProto_EnumReservedRange::end() const {
+ // @@protoc_insertion_point(field_get:google.protobuf.EnumDescriptorProto.EnumReservedRange.end)
+ return end_;
+}
+inline void EnumDescriptorProto_EnumReservedRange::set_end(::google::protobuf::int32 value) {
+ set_has_end();
+ end_ = value;
+ // @@protoc_insertion_point(field_set:google.protobuf.EnumDescriptorProto.EnumReservedRange.end)
+}
+
+// -------------------------------------------------------------------
+
// EnumDescriptorProto
// optional string name = 1;
@@ -5628,38 +7800,49 @@ inline void EnumDescriptorProto::clear_has_name() {
_has_bits_[0] &= ~0x00000001u;
}
inline void EnumDescriptorProto::clear_name() {
- name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
clear_has_name();
}
inline const ::std::string& EnumDescriptorProto::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.EnumDescriptorProto.name)
- return name_.GetNoArena();
+ return name_.Get();
}
inline void EnumDescriptorProto::set_name(const ::std::string& value) {
set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.EnumDescriptorProto.name)
}
+#if LANG_CXX11
+inline void EnumDescriptorProto::set_name(::std::string&& value) {
+ set_has_name();
+ name_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.EnumDescriptorProto.name)
+}
+#endif
inline void EnumDescriptorProto::set_name(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.EnumDescriptorProto.name)
}
-inline void EnumDescriptorProto::set_name(const char* value, size_t size) {
+inline void EnumDescriptorProto::set_name(const char* value,
+ size_t size) {
set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.EnumDescriptorProto.name)
}
inline ::std::string* EnumDescriptorProto::mutable_name() {
set_has_name();
// @@protoc_insertion_point(field_mutable:google.protobuf.EnumDescriptorProto.name)
- return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* EnumDescriptorProto::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.EnumDescriptorProto.name)
clear_has_name();
- return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void EnumDescriptorProto::set_allocated_name(::std::string* name) {
if (name != NULL) {
@@ -5667,9 +7850,29 @@ inline void EnumDescriptorProto::set_allocated_name(::std::string* name) {
} else {
clear_has_name();
}
- name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name);
+ name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.EnumDescriptorProto.name)
}
+inline ::std::string* EnumDescriptorProto::unsafe_arena_release_name() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.EnumDescriptorProto.name)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ clear_has_name();
+ return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
+inline void EnumDescriptorProto::unsafe_arena_set_allocated_name(
+ ::std::string* name) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (name != NULL) {
+ set_has_name();
+ } else {
+ clear_has_name();
+ }
+ name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ name, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.EnumDescriptorProto.name)
+}
// repeated .google.protobuf.EnumValueDescriptorProto value = 2;
inline int EnumDescriptorProto::value_size() const {
@@ -5712,40 +7915,159 @@ inline void EnumDescriptorProto::clear_has_options() {
_has_bits_[0] &= ~0x00000002u;
}
inline void EnumDescriptorProto::clear_options() {
- if (options_ != NULL) options_->::google::protobuf::EnumOptions::Clear();
+ if (options_ != NULL) options_->Clear();
clear_has_options();
}
inline const ::google::protobuf::EnumOptions& EnumDescriptorProto::options() const {
+ const ::google::protobuf::EnumOptions* p = options_;
// @@protoc_insertion_point(field_get:google.protobuf.EnumDescriptorProto.options)
- return options_ != NULL ? *options_
- : *::google::protobuf::EnumOptions::internal_default_instance();
-}
-inline ::google::protobuf::EnumOptions* EnumDescriptorProto::mutable_options() {
- set_has_options();
- if (options_ == NULL) {
- options_ = new ::google::protobuf::EnumOptions;
- }
- // @@protoc_insertion_point(field_mutable:google.protobuf.EnumDescriptorProto.options)
- return options_;
+ return p != NULL ? *p : *reinterpret_cast<const ::google::protobuf::EnumOptions*>(
+ &::google::protobuf::_EnumOptions_default_instance_);
}
inline ::google::protobuf::EnumOptions* EnumDescriptorProto::release_options() {
// @@protoc_insertion_point(field_release:google.protobuf.EnumDescriptorProto.options)
clear_has_options();
::google::protobuf::EnumOptions* temp = options_;
+ if (GetArenaNoVirtual() != NULL) {
+ temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL);
+ }
+ options_ = NULL;
+ return temp;
+}
+inline ::google::protobuf::EnumOptions* EnumDescriptorProto::unsafe_arena_release_options() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.EnumDescriptorProto.options)
+ clear_has_options();
+ ::google::protobuf::EnumOptions* temp = options_;
options_ = NULL;
return temp;
}
+inline ::google::protobuf::EnumOptions* EnumDescriptorProto::mutable_options() {
+ set_has_options();
+ if (options_ == NULL) {
+ _slow_mutable_options();
+ }
+ // @@protoc_insertion_point(field_mutable:google.protobuf.EnumDescriptorProto.options)
+ return options_;
+}
inline void EnumDescriptorProto::set_allocated_options(::google::protobuf::EnumOptions* options) {
- delete options_;
- options_ = options;
+ ::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
+ if (message_arena == NULL) {
+ delete options_;
+ }
if (options) {
+ ::google::protobuf::Arena* submessage_arena =
+ ::google::protobuf::Arena::GetArena(options);
+ if (message_arena != submessage_arena) {
+ options = ::google::protobuf::internal::GetOwnedMessage(
+ message_arena, options, submessage_arena);
+ }
set_has_options();
} else {
clear_has_options();
}
+ options_ = options;
// @@protoc_insertion_point(field_set_allocated:google.protobuf.EnumDescriptorProto.options)
}
+// repeated .google.protobuf.EnumDescriptorProto.EnumReservedRange reserved_range = 4;
+inline int EnumDescriptorProto::reserved_range_size() const {
+ return reserved_range_.size();
+}
+inline void EnumDescriptorProto::clear_reserved_range() {
+ reserved_range_.Clear();
+}
+inline const ::google::protobuf::EnumDescriptorProto_EnumReservedRange& EnumDescriptorProto::reserved_range(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.EnumDescriptorProto.reserved_range)
+ return reserved_range_.Get(index);
+}
+inline ::google::protobuf::EnumDescriptorProto_EnumReservedRange* EnumDescriptorProto::mutable_reserved_range(int index) {
+ // @@protoc_insertion_point(field_mutable:google.protobuf.EnumDescriptorProto.reserved_range)
+ return reserved_range_.Mutable(index);
+}
+inline ::google::protobuf::EnumDescriptorProto_EnumReservedRange* EnumDescriptorProto::add_reserved_range() {
+ // @@protoc_insertion_point(field_add:google.protobuf.EnumDescriptorProto.reserved_range)
+ return reserved_range_.Add();
+}
+inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto_EnumReservedRange >*
+EnumDescriptorProto::mutable_reserved_range() {
+ // @@protoc_insertion_point(field_mutable_list:google.protobuf.EnumDescriptorProto.reserved_range)
+ return &reserved_range_;
+}
+inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto_EnumReservedRange >&
+EnumDescriptorProto::reserved_range() const {
+ // @@protoc_insertion_point(field_list:google.protobuf.EnumDescriptorProto.reserved_range)
+ return reserved_range_;
+}
+
+// repeated string reserved_name = 5;
+inline int EnumDescriptorProto::reserved_name_size() const {
+ return reserved_name_.size();
+}
+inline void EnumDescriptorProto::clear_reserved_name() {
+ reserved_name_.Clear();
+}
+inline const ::std::string& EnumDescriptorProto::reserved_name(int index) const {
+ // @@protoc_insertion_point(field_get:google.protobuf.EnumDescriptorProto.reserved_name)
+ return reserved_name_.Get(index);
+}
+inline ::std::string* EnumDescriptorProto::mutable_reserved_name(int index) {
+ // @@protoc_insertion_point(field_mutable:google.protobuf.EnumDescriptorProto.reserved_name)
+ return reserved_name_.Mutable(index);
+}
+inline void EnumDescriptorProto::set_reserved_name(int index, const ::std::string& value) {
+ // @@protoc_insertion_point(field_set:google.protobuf.EnumDescriptorProto.reserved_name)
+ reserved_name_.Mutable(index)->assign(value);
+}
+#if LANG_CXX11
+inline void EnumDescriptorProto::set_reserved_name(int index, ::std::string&& value) {
+ // @@protoc_insertion_point(field_set:google.protobuf.EnumDescriptorProto.reserved_name)
+ reserved_name_.Mutable(index)->assign(std::move(value));
+}
+#endif
+inline void EnumDescriptorProto::set_reserved_name(int index, const char* value) {
+ GOOGLE_DCHECK(value != NULL);
+ reserved_name_.Mutable(index)->assign(value);
+ // @@protoc_insertion_point(field_set_char:google.protobuf.EnumDescriptorProto.reserved_name)
+}
+inline void EnumDescriptorProto::set_reserved_name(int index, const char* value, size_t size) {
+ reserved_name_.Mutable(index)->assign(
+ reinterpret_cast<const char*>(value), size);
+ // @@protoc_insertion_point(field_set_pointer:google.protobuf.EnumDescriptorProto.reserved_name)
+}
+inline ::std::string* EnumDescriptorProto::add_reserved_name() {
+ // @@protoc_insertion_point(field_add_mutable:google.protobuf.EnumDescriptorProto.reserved_name)
+ return reserved_name_.Add();
+}
+inline void EnumDescriptorProto::add_reserved_name(const ::std::string& value) {
+ reserved_name_.Add()->assign(value);
+ // @@protoc_insertion_point(field_add:google.protobuf.EnumDescriptorProto.reserved_name)
+}
+#if LANG_CXX11
+inline void EnumDescriptorProto::add_reserved_name(::std::string&& value) {
+ reserved_name_.Add(std::move(value));
+ // @@protoc_insertion_point(field_add:google.protobuf.EnumDescriptorProto.reserved_name)
+}
+#endif
+inline void EnumDescriptorProto::add_reserved_name(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
+ reserved_name_.Add()->assign(value);
+ // @@protoc_insertion_point(field_add_char:google.protobuf.EnumDescriptorProto.reserved_name)
+}
+inline void EnumDescriptorProto::add_reserved_name(const char* value, size_t size) {
+ reserved_name_.Add()->assign(reinterpret_cast<const char*>(value), size);
+ // @@protoc_insertion_point(field_add_pointer:google.protobuf.EnumDescriptorProto.reserved_name)
+}
+inline const ::google::protobuf::RepeatedPtrField< ::std::string>&
+EnumDescriptorProto::reserved_name() const {
+ // @@protoc_insertion_point(field_list:google.protobuf.EnumDescriptorProto.reserved_name)
+ return reserved_name_;
+}
+inline ::google::protobuf::RepeatedPtrField< ::std::string>*
+EnumDescriptorProto::mutable_reserved_name() {
+ // @@protoc_insertion_point(field_mutable_list:google.protobuf.EnumDescriptorProto.reserved_name)
+ return &reserved_name_;
+}
+
// -------------------------------------------------------------------
// EnumValueDescriptorProto
@@ -5761,38 +8083,49 @@ inline void EnumValueDescriptorProto::clear_has_name() {
_has_bits_[0] &= ~0x00000001u;
}
inline void EnumValueDescriptorProto::clear_name() {
- name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
clear_has_name();
}
inline const ::std::string& EnumValueDescriptorProto::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.EnumValueDescriptorProto.name)
- return name_.GetNoArena();
+ return name_.Get();
}
inline void EnumValueDescriptorProto::set_name(const ::std::string& value) {
set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.EnumValueDescriptorProto.name)
}
+#if LANG_CXX11
+inline void EnumValueDescriptorProto::set_name(::std::string&& value) {
+ set_has_name();
+ name_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.EnumValueDescriptorProto.name)
+}
+#endif
inline void EnumValueDescriptorProto::set_name(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.EnumValueDescriptorProto.name)
}
-inline void EnumValueDescriptorProto::set_name(const char* value, size_t size) {
+inline void EnumValueDescriptorProto::set_name(const char* value,
+ size_t size) {
set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.EnumValueDescriptorProto.name)
}
inline ::std::string* EnumValueDescriptorProto::mutable_name() {
set_has_name();
// @@protoc_insertion_point(field_mutable:google.protobuf.EnumValueDescriptorProto.name)
- return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* EnumValueDescriptorProto::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.EnumValueDescriptorProto.name)
clear_has_name();
- return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void EnumValueDescriptorProto::set_allocated_name(::std::string* name) {
if (name != NULL) {
@@ -5800,9 +8133,29 @@ inline void EnumValueDescriptorProto::set_allocated_name(::std::string* name) {
} else {
clear_has_name();
}
- name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name);
+ name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.EnumValueDescriptorProto.name)
}
+inline ::std::string* EnumValueDescriptorProto::unsafe_arena_release_name() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.EnumValueDescriptorProto.name)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ clear_has_name();
+ return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
+inline void EnumValueDescriptorProto::unsafe_arena_set_allocated_name(
+ ::std::string* name) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (name != NULL) {
+ set_has_name();
+ } else {
+ clear_has_name();
+ }
+ name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ name, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.EnumValueDescriptorProto.name)
+}
// optional int32 number = 2;
inline bool EnumValueDescriptorProto::has_number() const {
@@ -5839,37 +8192,57 @@ inline void EnumValueDescriptorProto::clear_has_options() {
_has_bits_[0] &= ~0x00000002u;
}
inline void EnumValueDescriptorProto::clear_options() {
- if (options_ != NULL) options_->::google::protobuf::EnumValueOptions::Clear();
+ if (options_ != NULL) options_->Clear();
clear_has_options();
}
inline const ::google::protobuf::EnumValueOptions& EnumValueDescriptorProto::options() const {
+ const ::google::protobuf::EnumValueOptions* p = options_;
// @@protoc_insertion_point(field_get:google.protobuf.EnumValueDescriptorProto.options)
- return options_ != NULL ? *options_
- : *::google::protobuf::EnumValueOptions::internal_default_instance();
-}
-inline ::google::protobuf::EnumValueOptions* EnumValueDescriptorProto::mutable_options() {
- set_has_options();
- if (options_ == NULL) {
- options_ = new ::google::protobuf::EnumValueOptions;
- }
- // @@protoc_insertion_point(field_mutable:google.protobuf.EnumValueDescriptorProto.options)
- return options_;
+ return p != NULL ? *p : *reinterpret_cast<const ::google::protobuf::EnumValueOptions*>(
+ &::google::protobuf::_EnumValueOptions_default_instance_);
}
inline ::google::protobuf::EnumValueOptions* EnumValueDescriptorProto::release_options() {
// @@protoc_insertion_point(field_release:google.protobuf.EnumValueDescriptorProto.options)
clear_has_options();
::google::protobuf::EnumValueOptions* temp = options_;
+ if (GetArenaNoVirtual() != NULL) {
+ temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL);
+ }
options_ = NULL;
return temp;
}
+inline ::google::protobuf::EnumValueOptions* EnumValueDescriptorProto::unsafe_arena_release_options() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.EnumValueDescriptorProto.options)
+ clear_has_options();
+ ::google::protobuf::EnumValueOptions* temp = options_;
+ options_ = NULL;
+ return temp;
+}
+inline ::google::protobuf::EnumValueOptions* EnumValueDescriptorProto::mutable_options() {
+ set_has_options();
+ if (options_ == NULL) {
+ _slow_mutable_options();
+ }
+ // @@protoc_insertion_point(field_mutable:google.protobuf.EnumValueDescriptorProto.options)
+ return options_;
+}
inline void EnumValueDescriptorProto::set_allocated_options(::google::protobuf::EnumValueOptions* options) {
- delete options_;
- options_ = options;
+ ::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
+ if (message_arena == NULL) {
+ delete options_;
+ }
if (options) {
+ ::google::protobuf::Arena* submessage_arena =
+ ::google::protobuf::Arena::GetArena(options);
+ if (message_arena != submessage_arena) {
+ options = ::google::protobuf::internal::GetOwnedMessage(
+ message_arena, options, submessage_arena);
+ }
set_has_options();
} else {
clear_has_options();
}
+ options_ = options;
// @@protoc_insertion_point(field_set_allocated:google.protobuf.EnumValueDescriptorProto.options)
}
@@ -5888,38 +8261,49 @@ inline void ServiceDescriptorProto::clear_has_name() {
_has_bits_[0] &= ~0x00000001u;
}
inline void ServiceDescriptorProto::clear_name() {
- name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
clear_has_name();
}
inline const ::std::string& ServiceDescriptorProto::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.ServiceDescriptorProto.name)
- return name_.GetNoArena();
+ return name_.Get();
}
inline void ServiceDescriptorProto::set_name(const ::std::string& value) {
set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.ServiceDescriptorProto.name)
}
+#if LANG_CXX11
+inline void ServiceDescriptorProto::set_name(::std::string&& value) {
+ set_has_name();
+ name_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.ServiceDescriptorProto.name)
+}
+#endif
inline void ServiceDescriptorProto::set_name(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.ServiceDescriptorProto.name)
}
-inline void ServiceDescriptorProto::set_name(const char* value, size_t size) {
+inline void ServiceDescriptorProto::set_name(const char* value,
+ size_t size) {
set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.ServiceDescriptorProto.name)
}
inline ::std::string* ServiceDescriptorProto::mutable_name() {
set_has_name();
// @@protoc_insertion_point(field_mutable:google.protobuf.ServiceDescriptorProto.name)
- return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* ServiceDescriptorProto::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.ServiceDescriptorProto.name)
clear_has_name();
- return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void ServiceDescriptorProto::set_allocated_name(::std::string* name) {
if (name != NULL) {
@@ -5927,9 +8311,29 @@ inline void ServiceDescriptorProto::set_allocated_name(::std::string* name) {
} else {
clear_has_name();
}
- name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name);
+ name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.ServiceDescriptorProto.name)
}
+inline ::std::string* ServiceDescriptorProto::unsafe_arena_release_name() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.ServiceDescriptorProto.name)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ clear_has_name();
+ return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
+inline void ServiceDescriptorProto::unsafe_arena_set_allocated_name(
+ ::std::string* name) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (name != NULL) {
+ set_has_name();
+ } else {
+ clear_has_name();
+ }
+ name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ name, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.ServiceDescriptorProto.name)
+}
// repeated .google.protobuf.MethodDescriptorProto method = 2;
inline int ServiceDescriptorProto::method_size() const {
@@ -5972,37 +8376,57 @@ inline void ServiceDescriptorProto::clear_has_options() {
_has_bits_[0] &= ~0x00000002u;
}
inline void ServiceDescriptorProto::clear_options() {
- if (options_ != NULL) options_->::google::protobuf::ServiceOptions::Clear();
+ if (options_ != NULL) options_->Clear();
clear_has_options();
}
inline const ::google::protobuf::ServiceOptions& ServiceDescriptorProto::options() const {
+ const ::google::protobuf::ServiceOptions* p = options_;
// @@protoc_insertion_point(field_get:google.protobuf.ServiceDescriptorProto.options)
- return options_ != NULL ? *options_
- : *::google::protobuf::ServiceOptions::internal_default_instance();
-}
-inline ::google::protobuf::ServiceOptions* ServiceDescriptorProto::mutable_options() {
- set_has_options();
- if (options_ == NULL) {
- options_ = new ::google::protobuf::ServiceOptions;
- }
- // @@protoc_insertion_point(field_mutable:google.protobuf.ServiceDescriptorProto.options)
- return options_;
+ return p != NULL ? *p : *reinterpret_cast<const ::google::protobuf::ServiceOptions*>(
+ &::google::protobuf::_ServiceOptions_default_instance_);
}
inline ::google::protobuf::ServiceOptions* ServiceDescriptorProto::release_options() {
// @@protoc_insertion_point(field_release:google.protobuf.ServiceDescriptorProto.options)
clear_has_options();
::google::protobuf::ServiceOptions* temp = options_;
+ if (GetArenaNoVirtual() != NULL) {
+ temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL);
+ }
+ options_ = NULL;
+ return temp;
+}
+inline ::google::protobuf::ServiceOptions* ServiceDescriptorProto::unsafe_arena_release_options() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.ServiceDescriptorProto.options)
+ clear_has_options();
+ ::google::protobuf::ServiceOptions* temp = options_;
options_ = NULL;
return temp;
}
+inline ::google::protobuf::ServiceOptions* ServiceDescriptorProto::mutable_options() {
+ set_has_options();
+ if (options_ == NULL) {
+ _slow_mutable_options();
+ }
+ // @@protoc_insertion_point(field_mutable:google.protobuf.ServiceDescriptorProto.options)
+ return options_;
+}
inline void ServiceDescriptorProto::set_allocated_options(::google::protobuf::ServiceOptions* options) {
- delete options_;
- options_ = options;
+ ::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
+ if (message_arena == NULL) {
+ delete options_;
+ }
if (options) {
+ ::google::protobuf::Arena* submessage_arena =
+ ::google::protobuf::Arena::GetArena(options);
+ if (message_arena != submessage_arena) {
+ options = ::google::protobuf::internal::GetOwnedMessage(
+ message_arena, options, submessage_arena);
+ }
set_has_options();
} else {
clear_has_options();
}
+ options_ = options;
// @@protoc_insertion_point(field_set_allocated:google.protobuf.ServiceDescriptorProto.options)
}
@@ -6021,38 +8445,49 @@ inline void MethodDescriptorProto::clear_has_name() {
_has_bits_[0] &= ~0x00000001u;
}
inline void MethodDescriptorProto::clear_name() {
- name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
clear_has_name();
}
inline const ::std::string& MethodDescriptorProto::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.MethodDescriptorProto.name)
- return name_.GetNoArena();
+ return name_.Get();
}
inline void MethodDescriptorProto::set_name(const ::std::string& value) {
set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.MethodDescriptorProto.name)
}
+#if LANG_CXX11
+inline void MethodDescriptorProto::set_name(::std::string&& value) {
+ set_has_name();
+ name_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.MethodDescriptorProto.name)
+}
+#endif
inline void MethodDescriptorProto::set_name(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.MethodDescriptorProto.name)
}
-inline void MethodDescriptorProto::set_name(const char* value, size_t size) {
+inline void MethodDescriptorProto::set_name(const char* value,
+ size_t size) {
set_has_name();
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.MethodDescriptorProto.name)
}
inline ::std::string* MethodDescriptorProto::mutable_name() {
set_has_name();
// @@protoc_insertion_point(field_mutable:google.protobuf.MethodDescriptorProto.name)
- return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* MethodDescriptorProto::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.MethodDescriptorProto.name)
clear_has_name();
- return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void MethodDescriptorProto::set_allocated_name(::std::string* name) {
if (name != NULL) {
@@ -6060,9 +8495,29 @@ inline void MethodDescriptorProto::set_allocated_name(::std::string* name) {
} else {
clear_has_name();
}
- name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name);
+ name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.MethodDescriptorProto.name)
}
+inline ::std::string* MethodDescriptorProto::unsafe_arena_release_name() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.MethodDescriptorProto.name)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ clear_has_name();
+ return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
+inline void MethodDescriptorProto::unsafe_arena_set_allocated_name(
+ ::std::string* name) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (name != NULL) {
+ set_has_name();
+ } else {
+ clear_has_name();
+ }
+ name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ name, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.MethodDescriptorProto.name)
+}
// optional string input_type = 2;
inline bool MethodDescriptorProto::has_input_type() const {
@@ -6075,38 +8530,49 @@ inline void MethodDescriptorProto::clear_has_input_type() {
_has_bits_[0] &= ~0x00000002u;
}
inline void MethodDescriptorProto::clear_input_type() {
- input_type_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ input_type_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
clear_has_input_type();
}
inline const ::std::string& MethodDescriptorProto::input_type() const {
// @@protoc_insertion_point(field_get:google.protobuf.MethodDescriptorProto.input_type)
- return input_type_.GetNoArena();
+ return input_type_.Get();
}
inline void MethodDescriptorProto::set_input_type(const ::std::string& value) {
set_has_input_type();
- input_type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ input_type_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.MethodDescriptorProto.input_type)
}
+#if LANG_CXX11
+inline void MethodDescriptorProto::set_input_type(::std::string&& value) {
+ set_has_input_type();
+ input_type_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.MethodDescriptorProto.input_type)
+}
+#endif
inline void MethodDescriptorProto::set_input_type(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
set_has_input_type();
- input_type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ input_type_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.MethodDescriptorProto.input_type)
}
-inline void MethodDescriptorProto::set_input_type(const char* value, size_t size) {
+inline void MethodDescriptorProto::set_input_type(const char* value,
+ size_t size) {
set_has_input_type();
- input_type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ input_type_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.MethodDescriptorProto.input_type)
}
inline ::std::string* MethodDescriptorProto::mutable_input_type() {
set_has_input_type();
// @@protoc_insertion_point(field_mutable:google.protobuf.MethodDescriptorProto.input_type)
- return input_type_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return input_type_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* MethodDescriptorProto::release_input_type() {
// @@protoc_insertion_point(field_release:google.protobuf.MethodDescriptorProto.input_type)
clear_has_input_type();
- return input_type_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return input_type_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void MethodDescriptorProto::set_allocated_input_type(::std::string* input_type) {
if (input_type != NULL) {
@@ -6114,9 +8580,29 @@ inline void MethodDescriptorProto::set_allocated_input_type(::std::string* input
} else {
clear_has_input_type();
}
- input_type_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), input_type);
+ input_type_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), input_type,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.MethodDescriptorProto.input_type)
}
+inline ::std::string* MethodDescriptorProto::unsafe_arena_release_input_type() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.MethodDescriptorProto.input_type)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ clear_has_input_type();
+ return input_type_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
+inline void MethodDescriptorProto::unsafe_arena_set_allocated_input_type(
+ ::std::string* input_type) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (input_type != NULL) {
+ set_has_input_type();
+ } else {
+ clear_has_input_type();
+ }
+ input_type_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ input_type, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.MethodDescriptorProto.input_type)
+}
// optional string output_type = 3;
inline bool MethodDescriptorProto::has_output_type() const {
@@ -6129,38 +8615,49 @@ inline void MethodDescriptorProto::clear_has_output_type() {
_has_bits_[0] &= ~0x00000004u;
}
inline void MethodDescriptorProto::clear_output_type() {
- output_type_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ output_type_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
clear_has_output_type();
}
inline const ::std::string& MethodDescriptorProto::output_type() const {
// @@protoc_insertion_point(field_get:google.protobuf.MethodDescriptorProto.output_type)
- return output_type_.GetNoArena();
+ return output_type_.Get();
}
inline void MethodDescriptorProto::set_output_type(const ::std::string& value) {
set_has_output_type();
- output_type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ output_type_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.MethodDescriptorProto.output_type)
}
+#if LANG_CXX11
+inline void MethodDescriptorProto::set_output_type(::std::string&& value) {
+ set_has_output_type();
+ output_type_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.MethodDescriptorProto.output_type)
+}
+#endif
inline void MethodDescriptorProto::set_output_type(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
set_has_output_type();
- output_type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ output_type_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.MethodDescriptorProto.output_type)
}
-inline void MethodDescriptorProto::set_output_type(const char* value, size_t size) {
+inline void MethodDescriptorProto::set_output_type(const char* value,
+ size_t size) {
set_has_output_type();
- output_type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ output_type_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.MethodDescriptorProto.output_type)
}
inline ::std::string* MethodDescriptorProto::mutable_output_type() {
set_has_output_type();
// @@protoc_insertion_point(field_mutable:google.protobuf.MethodDescriptorProto.output_type)
- return output_type_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return output_type_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* MethodDescriptorProto::release_output_type() {
// @@protoc_insertion_point(field_release:google.protobuf.MethodDescriptorProto.output_type)
clear_has_output_type();
- return output_type_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return output_type_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void MethodDescriptorProto::set_allocated_output_type(::std::string* output_type) {
if (output_type != NULL) {
@@ -6168,9 +8665,29 @@ inline void MethodDescriptorProto::set_allocated_output_type(::std::string* outp
} else {
clear_has_output_type();
}
- output_type_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), output_type);
+ output_type_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), output_type,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.MethodDescriptorProto.output_type)
}
+inline ::std::string* MethodDescriptorProto::unsafe_arena_release_output_type() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.MethodDescriptorProto.output_type)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ clear_has_output_type();
+ return output_type_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
+inline void MethodDescriptorProto::unsafe_arena_set_allocated_output_type(
+ ::std::string* output_type) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (output_type != NULL) {
+ set_has_output_type();
+ } else {
+ clear_has_output_type();
+ }
+ output_type_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ output_type, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.MethodDescriptorProto.output_type)
+}
// optional .google.protobuf.MethodOptions options = 4;
inline bool MethodDescriptorProto::has_options() const {
@@ -6183,37 +8700,57 @@ inline void MethodDescriptorProto::clear_has_options() {
_has_bits_[0] &= ~0x00000008u;
}
inline void MethodDescriptorProto::clear_options() {
- if (options_ != NULL) options_->::google::protobuf::MethodOptions::Clear();
+ if (options_ != NULL) options_->Clear();
clear_has_options();
}
inline const ::google::protobuf::MethodOptions& MethodDescriptorProto::options() const {
+ const ::google::protobuf::MethodOptions* p = options_;
// @@protoc_insertion_point(field_get:google.protobuf.MethodDescriptorProto.options)
- return options_ != NULL ? *options_
- : *::google::protobuf::MethodOptions::internal_default_instance();
-}
-inline ::google::protobuf::MethodOptions* MethodDescriptorProto::mutable_options() {
- set_has_options();
- if (options_ == NULL) {
- options_ = new ::google::protobuf::MethodOptions;
- }
- // @@protoc_insertion_point(field_mutable:google.protobuf.MethodDescriptorProto.options)
- return options_;
+ return p != NULL ? *p : *reinterpret_cast<const ::google::protobuf::MethodOptions*>(
+ &::google::protobuf::_MethodOptions_default_instance_);
}
inline ::google::protobuf::MethodOptions* MethodDescriptorProto::release_options() {
// @@protoc_insertion_point(field_release:google.protobuf.MethodDescriptorProto.options)
clear_has_options();
::google::protobuf::MethodOptions* temp = options_;
+ if (GetArenaNoVirtual() != NULL) {
+ temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL);
+ }
+ options_ = NULL;
+ return temp;
+}
+inline ::google::protobuf::MethodOptions* MethodDescriptorProto::unsafe_arena_release_options() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.MethodDescriptorProto.options)
+ clear_has_options();
+ ::google::protobuf::MethodOptions* temp = options_;
options_ = NULL;
return temp;
}
+inline ::google::protobuf::MethodOptions* MethodDescriptorProto::mutable_options() {
+ set_has_options();
+ if (options_ == NULL) {
+ _slow_mutable_options();
+ }
+ // @@protoc_insertion_point(field_mutable:google.protobuf.MethodDescriptorProto.options)
+ return options_;
+}
inline void MethodDescriptorProto::set_allocated_options(::google::protobuf::MethodOptions* options) {
- delete options_;
- options_ = options;
+ ::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
+ if (message_arena == NULL) {
+ delete options_;
+ }
if (options) {
+ ::google::protobuf::Arena* submessage_arena =
+ ::google::protobuf::Arena::GetArena(options);
+ if (message_arena != submessage_arena) {
+ options = ::google::protobuf::internal::GetOwnedMessage(
+ message_arena, options, submessage_arena);
+ }
set_has_options();
} else {
clear_has_options();
}
+ options_ = options;
// @@protoc_insertion_point(field_set_allocated:google.protobuf.MethodDescriptorProto.options)
}
@@ -6280,38 +8817,49 @@ inline void FileOptions::clear_has_java_package() {
_has_bits_[0] &= ~0x00000001u;
}
inline void FileOptions::clear_java_package() {
- java_package_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ java_package_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
clear_has_java_package();
}
inline const ::std::string& FileOptions::java_package() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileOptions.java_package)
- return java_package_.GetNoArena();
+ return java_package_.Get();
}
inline void FileOptions::set_java_package(const ::std::string& value) {
set_has_java_package();
- java_package_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ java_package_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.FileOptions.java_package)
}
+#if LANG_CXX11
+inline void FileOptions::set_java_package(::std::string&& value) {
+ set_has_java_package();
+ java_package_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.java_package)
+}
+#endif
inline void FileOptions::set_java_package(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
set_has_java_package();
- java_package_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ java_package_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.java_package)
}
-inline void FileOptions::set_java_package(const char* value, size_t size) {
+inline void FileOptions::set_java_package(const char* value,
+ size_t size) {
set_has_java_package();
- java_package_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ java_package_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.java_package)
}
inline ::std::string* FileOptions::mutable_java_package() {
set_has_java_package();
// @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.java_package)
- return java_package_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return java_package_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* FileOptions::release_java_package() {
// @@protoc_insertion_point(field_release:google.protobuf.FileOptions.java_package)
clear_has_java_package();
- return java_package_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return java_package_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FileOptions::set_allocated_java_package(::std::string* java_package) {
if (java_package != NULL) {
@@ -6319,9 +8867,29 @@ inline void FileOptions::set_allocated_java_package(::std::string* java_package)
} else {
clear_has_java_package();
}
- java_package_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), java_package);
+ java_package_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), java_package,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.java_package)
}
+inline ::std::string* FileOptions::unsafe_arena_release_java_package() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileOptions.java_package)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ clear_has_java_package();
+ return java_package_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
+inline void FileOptions::unsafe_arena_set_allocated_java_package(
+ ::std::string* java_package) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (java_package != NULL) {
+ set_has_java_package();
+ } else {
+ clear_has_java_package();
+ }
+ java_package_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ java_package, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileOptions.java_package)
+}
// optional string java_outer_classname = 8;
inline bool FileOptions::has_java_outer_classname() const {
@@ -6334,38 +8902,49 @@ inline void FileOptions::clear_has_java_outer_classname() {
_has_bits_[0] &= ~0x00000002u;
}
inline void FileOptions::clear_java_outer_classname() {
- java_outer_classname_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ java_outer_classname_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
clear_has_java_outer_classname();
}
inline const ::std::string& FileOptions::java_outer_classname() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileOptions.java_outer_classname)
- return java_outer_classname_.GetNoArena();
+ return java_outer_classname_.Get();
}
inline void FileOptions::set_java_outer_classname(const ::std::string& value) {
set_has_java_outer_classname();
- java_outer_classname_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ java_outer_classname_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.FileOptions.java_outer_classname)
}
+#if LANG_CXX11
+inline void FileOptions::set_java_outer_classname(::std::string&& value) {
+ set_has_java_outer_classname();
+ java_outer_classname_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.java_outer_classname)
+}
+#endif
inline void FileOptions::set_java_outer_classname(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
set_has_java_outer_classname();
- java_outer_classname_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ java_outer_classname_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.java_outer_classname)
}
-inline void FileOptions::set_java_outer_classname(const char* value, size_t size) {
+inline void FileOptions::set_java_outer_classname(const char* value,
+ size_t size) {
set_has_java_outer_classname();
- java_outer_classname_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ java_outer_classname_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.java_outer_classname)
}
inline ::std::string* FileOptions::mutable_java_outer_classname() {
set_has_java_outer_classname();
// @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.java_outer_classname)
- return java_outer_classname_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return java_outer_classname_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* FileOptions::release_java_outer_classname() {
// @@protoc_insertion_point(field_release:google.protobuf.FileOptions.java_outer_classname)
clear_has_java_outer_classname();
- return java_outer_classname_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return java_outer_classname_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FileOptions::set_allocated_java_outer_classname(::std::string* java_outer_classname) {
if (java_outer_classname != NULL) {
@@ -6373,19 +8952,39 @@ inline void FileOptions::set_allocated_java_outer_classname(::std::string* java_
} else {
clear_has_java_outer_classname();
}
- java_outer_classname_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), java_outer_classname);
+ java_outer_classname_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), java_outer_classname,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.java_outer_classname)
}
+inline ::std::string* FileOptions::unsafe_arena_release_java_outer_classname() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileOptions.java_outer_classname)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ clear_has_java_outer_classname();
+ return java_outer_classname_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
+inline void FileOptions::unsafe_arena_set_allocated_java_outer_classname(
+ ::std::string* java_outer_classname) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (java_outer_classname != NULL) {
+ set_has_java_outer_classname();
+ } else {
+ clear_has_java_outer_classname();
+ }
+ java_outer_classname_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ java_outer_classname, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileOptions.java_outer_classname)
+}
// optional bool java_multiple_files = 10 [default = false];
inline bool FileOptions::has_java_multiple_files() const {
- return (_has_bits_[0] & 0x00000040u) != 0;
+ return (_has_bits_[0] & 0x00000200u) != 0;
}
inline void FileOptions::set_has_java_multiple_files() {
- _has_bits_[0] |= 0x00000040u;
+ _has_bits_[0] |= 0x00000200u;
}
inline void FileOptions::clear_has_java_multiple_files() {
- _has_bits_[0] &= ~0x00000040u;
+ _has_bits_[0] &= ~0x00000200u;
}
inline void FileOptions::clear_java_multiple_files() {
java_multiple_files_ = false;
@@ -6403,13 +9002,13 @@ inline void FileOptions::set_java_multiple_files(bool value) {
// optional bool java_generate_equals_and_hash = 20 [deprecated = true];
inline bool FileOptions::has_java_generate_equals_and_hash() const {
- return (_has_bits_[0] & 0x00000080u) != 0;
+ return (_has_bits_[0] & 0x00000400u) != 0;
}
inline void FileOptions::set_has_java_generate_equals_and_hash() {
- _has_bits_[0] |= 0x00000080u;
+ _has_bits_[0] |= 0x00000400u;
}
inline void FileOptions::clear_has_java_generate_equals_and_hash() {
- _has_bits_[0] &= ~0x00000080u;
+ _has_bits_[0] &= ~0x00000400u;
}
inline void FileOptions::clear_java_generate_equals_and_hash() {
java_generate_equals_and_hash_ = false;
@@ -6427,13 +9026,13 @@ inline void FileOptions::set_java_generate_equals_and_hash(bool value) {
// optional bool java_string_check_utf8 = 27 [default = false];
inline bool FileOptions::has_java_string_check_utf8() const {
- return (_has_bits_[0] & 0x00000100u) != 0;
+ return (_has_bits_[0] & 0x00000800u) != 0;
}
inline void FileOptions::set_has_java_string_check_utf8() {
- _has_bits_[0] |= 0x00000100u;
+ _has_bits_[0] |= 0x00000800u;
}
inline void FileOptions::clear_has_java_string_check_utf8() {
- _has_bits_[0] &= ~0x00000100u;
+ _has_bits_[0] &= ~0x00000800u;
}
inline void FileOptions::clear_java_string_check_utf8() {
java_string_check_utf8_ = false;
@@ -6451,13 +9050,13 @@ inline void FileOptions::set_java_string_check_utf8(bool value) {
// optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED];
inline bool FileOptions::has_optimize_for() const {
- return (_has_bits_[0] & 0x00004000u) != 0;
+ return (_has_bits_[0] & 0x00020000u) != 0;
}
inline void FileOptions::set_has_optimize_for() {
- _has_bits_[0] |= 0x00004000u;
+ _has_bits_[0] |= 0x00020000u;
}
inline void FileOptions::clear_has_optimize_for() {
- _has_bits_[0] &= ~0x00004000u;
+ _has_bits_[0] &= ~0x00020000u;
}
inline void FileOptions::clear_optimize_for() {
optimize_for_ = 1;
@@ -6485,38 +9084,49 @@ inline void FileOptions::clear_has_go_package() {
_has_bits_[0] &= ~0x00000004u;
}
inline void FileOptions::clear_go_package() {
- go_package_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ go_package_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
clear_has_go_package();
}
inline const ::std::string& FileOptions::go_package() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileOptions.go_package)
- return go_package_.GetNoArena();
+ return go_package_.Get();
}
inline void FileOptions::set_go_package(const ::std::string& value) {
set_has_go_package();
- go_package_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ go_package_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.FileOptions.go_package)
}
+#if LANG_CXX11
+inline void FileOptions::set_go_package(::std::string&& value) {
+ set_has_go_package();
+ go_package_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.go_package)
+}
+#endif
inline void FileOptions::set_go_package(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
set_has_go_package();
- go_package_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ go_package_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.go_package)
}
-inline void FileOptions::set_go_package(const char* value, size_t size) {
+inline void FileOptions::set_go_package(const char* value,
+ size_t size) {
set_has_go_package();
- go_package_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ go_package_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.go_package)
}
inline ::std::string* FileOptions::mutable_go_package() {
set_has_go_package();
// @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.go_package)
- return go_package_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return go_package_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* FileOptions::release_go_package() {
// @@protoc_insertion_point(field_release:google.protobuf.FileOptions.go_package)
clear_has_go_package();
- return go_package_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return go_package_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FileOptions::set_allocated_go_package(::std::string* go_package) {
if (go_package != NULL) {
@@ -6524,19 +9134,39 @@ inline void FileOptions::set_allocated_go_package(::std::string* go_package) {
} else {
clear_has_go_package();
}
- go_package_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), go_package);
+ go_package_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), go_package,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.go_package)
}
+inline ::std::string* FileOptions::unsafe_arena_release_go_package() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileOptions.go_package)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ clear_has_go_package();
+ return go_package_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
+inline void FileOptions::unsafe_arena_set_allocated_go_package(
+ ::std::string* go_package) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (go_package != NULL) {
+ set_has_go_package();
+ } else {
+ clear_has_go_package();
+ }
+ go_package_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ go_package, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileOptions.go_package)
+}
// optional bool cc_generic_services = 16 [default = false];
inline bool FileOptions::has_cc_generic_services() const {
- return (_has_bits_[0] & 0x00000200u) != 0;
+ return (_has_bits_[0] & 0x00001000u) != 0;
}
inline void FileOptions::set_has_cc_generic_services() {
- _has_bits_[0] |= 0x00000200u;
+ _has_bits_[0] |= 0x00001000u;
}
inline void FileOptions::clear_has_cc_generic_services() {
- _has_bits_[0] &= ~0x00000200u;
+ _has_bits_[0] &= ~0x00001000u;
}
inline void FileOptions::clear_cc_generic_services() {
cc_generic_services_ = false;
@@ -6554,13 +9184,13 @@ inline void FileOptions::set_cc_generic_services(bool value) {
// optional bool java_generic_services = 17 [default = false];
inline bool FileOptions::has_java_generic_services() const {
- return (_has_bits_[0] & 0x00000400u) != 0;
+ return (_has_bits_[0] & 0x00002000u) != 0;
}
inline void FileOptions::set_has_java_generic_services() {
- _has_bits_[0] |= 0x00000400u;
+ _has_bits_[0] |= 0x00002000u;
}
inline void FileOptions::clear_has_java_generic_services() {
- _has_bits_[0] &= ~0x00000400u;
+ _has_bits_[0] &= ~0x00002000u;
}
inline void FileOptions::clear_java_generic_services() {
java_generic_services_ = false;
@@ -6578,13 +9208,13 @@ inline void FileOptions::set_java_generic_services(bool value) {
// optional bool py_generic_services = 18 [default = false];
inline bool FileOptions::has_py_generic_services() const {
- return (_has_bits_[0] & 0x00000800u) != 0;
+ return (_has_bits_[0] & 0x00004000u) != 0;
}
inline void FileOptions::set_has_py_generic_services() {
- _has_bits_[0] |= 0x00000800u;
+ _has_bits_[0] |= 0x00004000u;
}
inline void FileOptions::clear_has_py_generic_services() {
- _has_bits_[0] &= ~0x00000800u;
+ _has_bits_[0] &= ~0x00004000u;
}
inline void FileOptions::clear_py_generic_services() {
py_generic_services_ = false;
@@ -6600,15 +9230,39 @@ inline void FileOptions::set_py_generic_services(bool value) {
// @@protoc_insertion_point(field_set:google.protobuf.FileOptions.py_generic_services)
}
+// optional bool php_generic_services = 42 [default = false];
+inline bool FileOptions::has_php_generic_services() const {
+ return (_has_bits_[0] & 0x00008000u) != 0;
+}
+inline void FileOptions::set_has_php_generic_services() {
+ _has_bits_[0] |= 0x00008000u;
+}
+inline void FileOptions::clear_has_php_generic_services() {
+ _has_bits_[0] &= ~0x00008000u;
+}
+inline void FileOptions::clear_php_generic_services() {
+ php_generic_services_ = false;
+ clear_has_php_generic_services();
+}
+inline bool FileOptions::php_generic_services() const {
+ // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.php_generic_services)
+ return php_generic_services_;
+}
+inline void FileOptions::set_php_generic_services(bool value) {
+ set_has_php_generic_services();
+ php_generic_services_ = value;
+ // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.php_generic_services)
+}
+
// optional bool deprecated = 23 [default = false];
inline bool FileOptions::has_deprecated() const {
- return (_has_bits_[0] & 0x00001000u) != 0;
+ return (_has_bits_[0] & 0x00010000u) != 0;
}
inline void FileOptions::set_has_deprecated() {
- _has_bits_[0] |= 0x00001000u;
+ _has_bits_[0] |= 0x00010000u;
}
inline void FileOptions::clear_has_deprecated() {
- _has_bits_[0] &= ~0x00001000u;
+ _has_bits_[0] &= ~0x00010000u;
}
inline void FileOptions::clear_deprecated() {
deprecated_ = false;
@@ -6626,13 +9280,13 @@ inline void FileOptions::set_deprecated(bool value) {
// optional bool cc_enable_arenas = 31 [default = false];
inline bool FileOptions::has_cc_enable_arenas() const {
- return (_has_bits_[0] & 0x00002000u) != 0;
+ return (_has_bits_[0] & 0x00000100u) != 0;
}
inline void FileOptions::set_has_cc_enable_arenas() {
- _has_bits_[0] |= 0x00002000u;
+ _has_bits_[0] |= 0x00000100u;
}
inline void FileOptions::clear_has_cc_enable_arenas() {
- _has_bits_[0] &= ~0x00002000u;
+ _has_bits_[0] &= ~0x00000100u;
}
inline void FileOptions::clear_cc_enable_arenas() {
cc_enable_arenas_ = false;
@@ -6659,38 +9313,49 @@ inline void FileOptions::clear_has_objc_class_prefix() {
_has_bits_[0] &= ~0x00000008u;
}
inline void FileOptions::clear_objc_class_prefix() {
- objc_class_prefix_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ objc_class_prefix_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
clear_has_objc_class_prefix();
}
inline const ::std::string& FileOptions::objc_class_prefix() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileOptions.objc_class_prefix)
- return objc_class_prefix_.GetNoArena();
+ return objc_class_prefix_.Get();
}
inline void FileOptions::set_objc_class_prefix(const ::std::string& value) {
set_has_objc_class_prefix();
- objc_class_prefix_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ objc_class_prefix_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.FileOptions.objc_class_prefix)
}
+#if LANG_CXX11
+inline void FileOptions::set_objc_class_prefix(::std::string&& value) {
+ set_has_objc_class_prefix();
+ objc_class_prefix_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.objc_class_prefix)
+}
+#endif
inline void FileOptions::set_objc_class_prefix(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
set_has_objc_class_prefix();
- objc_class_prefix_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ objc_class_prefix_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.objc_class_prefix)
}
-inline void FileOptions::set_objc_class_prefix(const char* value, size_t size) {
+inline void FileOptions::set_objc_class_prefix(const char* value,
+ size_t size) {
set_has_objc_class_prefix();
- objc_class_prefix_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ objc_class_prefix_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.objc_class_prefix)
}
inline ::std::string* FileOptions::mutable_objc_class_prefix() {
set_has_objc_class_prefix();
// @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.objc_class_prefix)
- return objc_class_prefix_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return objc_class_prefix_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* FileOptions::release_objc_class_prefix() {
// @@protoc_insertion_point(field_release:google.protobuf.FileOptions.objc_class_prefix)
clear_has_objc_class_prefix();
- return objc_class_prefix_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return objc_class_prefix_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FileOptions::set_allocated_objc_class_prefix(::std::string* objc_class_prefix) {
if (objc_class_prefix != NULL) {
@@ -6698,9 +9363,29 @@ inline void FileOptions::set_allocated_objc_class_prefix(::std::string* objc_cla
} else {
clear_has_objc_class_prefix();
}
- objc_class_prefix_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), objc_class_prefix);
+ objc_class_prefix_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), objc_class_prefix,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.objc_class_prefix)
}
+inline ::std::string* FileOptions::unsafe_arena_release_objc_class_prefix() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileOptions.objc_class_prefix)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ clear_has_objc_class_prefix();
+ return objc_class_prefix_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
+inline void FileOptions::unsafe_arena_set_allocated_objc_class_prefix(
+ ::std::string* objc_class_prefix) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (objc_class_prefix != NULL) {
+ set_has_objc_class_prefix();
+ } else {
+ clear_has_objc_class_prefix();
+ }
+ objc_class_prefix_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ objc_class_prefix, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileOptions.objc_class_prefix)
+}
// optional string csharp_namespace = 37;
inline bool FileOptions::has_csharp_namespace() const {
@@ -6713,38 +9398,49 @@ inline void FileOptions::clear_has_csharp_namespace() {
_has_bits_[0] &= ~0x00000010u;
}
inline void FileOptions::clear_csharp_namespace() {
- csharp_namespace_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ csharp_namespace_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
clear_has_csharp_namespace();
}
inline const ::std::string& FileOptions::csharp_namespace() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileOptions.csharp_namespace)
- return csharp_namespace_.GetNoArena();
+ return csharp_namespace_.Get();
}
inline void FileOptions::set_csharp_namespace(const ::std::string& value) {
set_has_csharp_namespace();
- csharp_namespace_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ csharp_namespace_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.FileOptions.csharp_namespace)
}
+#if LANG_CXX11
+inline void FileOptions::set_csharp_namespace(::std::string&& value) {
+ set_has_csharp_namespace();
+ csharp_namespace_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.csharp_namespace)
+}
+#endif
inline void FileOptions::set_csharp_namespace(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
set_has_csharp_namespace();
- csharp_namespace_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ csharp_namespace_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.csharp_namespace)
}
-inline void FileOptions::set_csharp_namespace(const char* value, size_t size) {
+inline void FileOptions::set_csharp_namespace(const char* value,
+ size_t size) {
set_has_csharp_namespace();
- csharp_namespace_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ csharp_namespace_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.csharp_namespace)
}
inline ::std::string* FileOptions::mutable_csharp_namespace() {
set_has_csharp_namespace();
// @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.csharp_namespace)
- return csharp_namespace_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return csharp_namespace_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* FileOptions::release_csharp_namespace() {
// @@protoc_insertion_point(field_release:google.protobuf.FileOptions.csharp_namespace)
clear_has_csharp_namespace();
- return csharp_namespace_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return csharp_namespace_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FileOptions::set_allocated_csharp_namespace(::std::string* csharp_namespace) {
if (csharp_namespace != NULL) {
@@ -6752,9 +9448,29 @@ inline void FileOptions::set_allocated_csharp_namespace(::std::string* csharp_na
} else {
clear_has_csharp_namespace();
}
- csharp_namespace_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), csharp_namespace);
+ csharp_namespace_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), csharp_namespace,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.csharp_namespace)
}
+inline ::std::string* FileOptions::unsafe_arena_release_csharp_namespace() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileOptions.csharp_namespace)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ clear_has_csharp_namespace();
+ return csharp_namespace_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
+inline void FileOptions::unsafe_arena_set_allocated_csharp_namespace(
+ ::std::string* csharp_namespace) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (csharp_namespace != NULL) {
+ set_has_csharp_namespace();
+ } else {
+ clear_has_csharp_namespace();
+ }
+ csharp_namespace_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ csharp_namespace, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileOptions.csharp_namespace)
+}
// optional string swift_prefix = 39;
inline bool FileOptions::has_swift_prefix() const {
@@ -6767,38 +9483,49 @@ inline void FileOptions::clear_has_swift_prefix() {
_has_bits_[0] &= ~0x00000020u;
}
inline void FileOptions::clear_swift_prefix() {
- swift_prefix_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ swift_prefix_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
clear_has_swift_prefix();
}
inline const ::std::string& FileOptions::swift_prefix() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileOptions.swift_prefix)
- return swift_prefix_.GetNoArena();
+ return swift_prefix_.Get();
}
inline void FileOptions::set_swift_prefix(const ::std::string& value) {
set_has_swift_prefix();
- swift_prefix_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ swift_prefix_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.FileOptions.swift_prefix)
}
+#if LANG_CXX11
+inline void FileOptions::set_swift_prefix(::std::string&& value) {
+ set_has_swift_prefix();
+ swift_prefix_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.swift_prefix)
+}
+#endif
inline void FileOptions::set_swift_prefix(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
set_has_swift_prefix();
- swift_prefix_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ swift_prefix_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.swift_prefix)
}
-inline void FileOptions::set_swift_prefix(const char* value, size_t size) {
+inline void FileOptions::set_swift_prefix(const char* value,
+ size_t size) {
set_has_swift_prefix();
- swift_prefix_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ swift_prefix_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.swift_prefix)
}
inline ::std::string* FileOptions::mutable_swift_prefix() {
set_has_swift_prefix();
// @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.swift_prefix)
- return swift_prefix_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return swift_prefix_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* FileOptions::release_swift_prefix() {
// @@protoc_insertion_point(field_release:google.protobuf.FileOptions.swift_prefix)
clear_has_swift_prefix();
- return swift_prefix_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return swift_prefix_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FileOptions::set_allocated_swift_prefix(::std::string* swift_prefix) {
if (swift_prefix != NULL) {
@@ -6806,9 +9533,199 @@ inline void FileOptions::set_allocated_swift_prefix(::std::string* swift_prefix)
} else {
clear_has_swift_prefix();
}
- swift_prefix_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), swift_prefix);
+ swift_prefix_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), swift_prefix,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.swift_prefix)
}
+inline ::std::string* FileOptions::unsafe_arena_release_swift_prefix() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileOptions.swift_prefix)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ clear_has_swift_prefix();
+ return swift_prefix_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
+inline void FileOptions::unsafe_arena_set_allocated_swift_prefix(
+ ::std::string* swift_prefix) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (swift_prefix != NULL) {
+ set_has_swift_prefix();
+ } else {
+ clear_has_swift_prefix();
+ }
+ swift_prefix_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ swift_prefix, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileOptions.swift_prefix)
+}
+
+// optional string php_class_prefix = 40;
+inline bool FileOptions::has_php_class_prefix() const {
+ return (_has_bits_[0] & 0x00000040u) != 0;
+}
+inline void FileOptions::set_has_php_class_prefix() {
+ _has_bits_[0] |= 0x00000040u;
+}
+inline void FileOptions::clear_has_php_class_prefix() {
+ _has_bits_[0] &= ~0x00000040u;
+}
+inline void FileOptions::clear_php_class_prefix() {
+ php_class_prefix_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ clear_has_php_class_prefix();
+}
+inline const ::std::string& FileOptions::php_class_prefix() const {
+ // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.php_class_prefix)
+ return php_class_prefix_.Get();
+}
+inline void FileOptions::set_php_class_prefix(const ::std::string& value) {
+ set_has_php_class_prefix();
+ php_class_prefix_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.php_class_prefix)
+}
+#if LANG_CXX11
+inline void FileOptions::set_php_class_prefix(::std::string&& value) {
+ set_has_php_class_prefix();
+ php_class_prefix_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.php_class_prefix)
+}
+#endif
+inline void FileOptions::set_php_class_prefix(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
+ set_has_php_class_prefix();
+ php_class_prefix_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.php_class_prefix)
+}
+inline void FileOptions::set_php_class_prefix(const char* value,
+ size_t size) {
+ set_has_php_class_prefix();
+ php_class_prefix_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.php_class_prefix)
+}
+inline ::std::string* FileOptions::mutable_php_class_prefix() {
+ set_has_php_class_prefix();
+ // @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.php_class_prefix)
+ return php_class_prefix_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+}
+inline ::std::string* FileOptions::release_php_class_prefix() {
+ // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.php_class_prefix)
+ clear_has_php_class_prefix();
+ return php_class_prefix_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+}
+inline void FileOptions::set_allocated_php_class_prefix(::std::string* php_class_prefix) {
+ if (php_class_prefix != NULL) {
+ set_has_php_class_prefix();
+ } else {
+ clear_has_php_class_prefix();
+ }
+ php_class_prefix_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), php_class_prefix,
+ GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.php_class_prefix)
+}
+inline ::std::string* FileOptions::unsafe_arena_release_php_class_prefix() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileOptions.php_class_prefix)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ clear_has_php_class_prefix();
+ return php_class_prefix_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
+inline void FileOptions::unsafe_arena_set_allocated_php_class_prefix(
+ ::std::string* php_class_prefix) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (php_class_prefix != NULL) {
+ set_has_php_class_prefix();
+ } else {
+ clear_has_php_class_prefix();
+ }
+ php_class_prefix_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ php_class_prefix, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileOptions.php_class_prefix)
+}
+
+// optional string php_namespace = 41;
+inline bool FileOptions::has_php_namespace() const {
+ return (_has_bits_[0] & 0x00000080u) != 0;
+}
+inline void FileOptions::set_has_php_namespace() {
+ _has_bits_[0] |= 0x00000080u;
+}
+inline void FileOptions::clear_has_php_namespace() {
+ _has_bits_[0] &= ~0x00000080u;
+}
+inline void FileOptions::clear_php_namespace() {
+ php_namespace_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ clear_has_php_namespace();
+}
+inline const ::std::string& FileOptions::php_namespace() const {
+ // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.php_namespace)
+ return php_namespace_.Get();
+}
+inline void FileOptions::set_php_namespace(const ::std::string& value) {
+ set_has_php_namespace();
+ php_namespace_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.php_namespace)
+}
+#if LANG_CXX11
+inline void FileOptions::set_php_namespace(::std::string&& value) {
+ set_has_php_namespace();
+ php_namespace_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.php_namespace)
+}
+#endif
+inline void FileOptions::set_php_namespace(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
+ set_has_php_namespace();
+ php_namespace_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.php_namespace)
+}
+inline void FileOptions::set_php_namespace(const char* value,
+ size_t size) {
+ set_has_php_namespace();
+ php_namespace_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.php_namespace)
+}
+inline ::std::string* FileOptions::mutable_php_namespace() {
+ set_has_php_namespace();
+ // @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.php_namespace)
+ return php_namespace_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+}
+inline ::std::string* FileOptions::release_php_namespace() {
+ // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.php_namespace)
+ clear_has_php_namespace();
+ return php_namespace_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+}
+inline void FileOptions::set_allocated_php_namespace(::std::string* php_namespace) {
+ if (php_namespace != NULL) {
+ set_has_php_namespace();
+ } else {
+ clear_has_php_namespace();
+ }
+ php_namespace_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), php_namespace,
+ GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.php_namespace)
+}
+inline ::std::string* FileOptions::unsafe_arena_release_php_namespace() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileOptions.php_namespace)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ clear_has_php_namespace();
+ return php_namespace_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
+inline void FileOptions::unsafe_arena_set_allocated_php_namespace(
+ ::std::string* php_namespace) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (php_namespace != NULL) {
+ set_has_php_namespace();
+ } else {
+ clear_has_php_namespace();
+ }
+ php_namespace_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ php_namespace, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileOptions.php_namespace)
+}
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
inline int FileOptions::uninterpreted_option_size() const {
@@ -7001,13 +9918,13 @@ inline void FieldOptions::set_ctype(::google::protobuf::FieldOptions_CType value
// optional bool packed = 2;
inline bool FieldOptions::has_packed() const {
- return (_has_bits_[0] & 0x00000004u) != 0;
+ return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void FieldOptions::set_has_packed() {
- _has_bits_[0] |= 0x00000004u;
+ _has_bits_[0] |= 0x00000002u;
}
inline void FieldOptions::clear_has_packed() {
- _has_bits_[0] &= ~0x00000004u;
+ _has_bits_[0] &= ~0x00000002u;
}
inline void FieldOptions::clear_packed() {
packed_ = false;
@@ -7025,13 +9942,13 @@ inline void FieldOptions::set_packed(bool value) {
// optional .google.protobuf.FieldOptions.JSType jstype = 6 [default = JS_NORMAL];
inline bool FieldOptions::has_jstype() const {
- return (_has_bits_[0] & 0x00000002u) != 0;
+ return (_has_bits_[0] & 0x00000020u) != 0;
}
inline void FieldOptions::set_has_jstype() {
- _has_bits_[0] |= 0x00000002u;
+ _has_bits_[0] |= 0x00000020u;
}
inline void FieldOptions::clear_has_jstype() {
- _has_bits_[0] &= ~0x00000002u;
+ _has_bits_[0] &= ~0x00000020u;
}
inline void FieldOptions::clear_jstype() {
jstype_ = 0;
@@ -7050,13 +9967,13 @@ inline void FieldOptions::set_jstype(::google::protobuf::FieldOptions_JSType val
// optional bool lazy = 5 [default = false];
inline bool FieldOptions::has_lazy() const {
- return (_has_bits_[0] & 0x00000008u) != 0;
+ return (_has_bits_[0] & 0x00000004u) != 0;
}
inline void FieldOptions::set_has_lazy() {
- _has_bits_[0] |= 0x00000008u;
+ _has_bits_[0] |= 0x00000004u;
}
inline void FieldOptions::clear_has_lazy() {
- _has_bits_[0] &= ~0x00000008u;
+ _has_bits_[0] &= ~0x00000004u;
}
inline void FieldOptions::clear_lazy() {
lazy_ = false;
@@ -7074,13 +9991,13 @@ inline void FieldOptions::set_lazy(bool value) {
// optional bool deprecated = 3 [default = false];
inline bool FieldOptions::has_deprecated() const {
- return (_has_bits_[0] & 0x00000010u) != 0;
+ return (_has_bits_[0] & 0x00000008u) != 0;
}
inline void FieldOptions::set_has_deprecated() {
- _has_bits_[0] |= 0x00000010u;
+ _has_bits_[0] |= 0x00000008u;
}
inline void FieldOptions::clear_has_deprecated() {
- _has_bits_[0] &= ~0x00000010u;
+ _has_bits_[0] &= ~0x00000008u;
}
inline void FieldOptions::clear_deprecated() {
deprecated_ = false;
@@ -7098,13 +10015,13 @@ inline void FieldOptions::set_deprecated(bool value) {
// optional bool weak = 10 [default = false];
inline bool FieldOptions::has_weak() const {
- return (_has_bits_[0] & 0x00000020u) != 0;
+ return (_has_bits_[0] & 0x00000010u) != 0;
}
inline void FieldOptions::set_has_weak() {
- _has_bits_[0] |= 0x00000020u;
+ _has_bits_[0] |= 0x00000010u;
}
inline void FieldOptions::clear_has_weak() {
- _has_bits_[0] &= ~0x00000020u;
+ _has_bits_[0] &= ~0x00000010u;
}
inline void FieldOptions::clear_weak() {
weak_ = false;
@@ -7480,38 +10397,49 @@ inline void UninterpretedOption_NamePart::clear_has_name_part() {
_has_bits_[0] &= ~0x00000001u;
}
inline void UninterpretedOption_NamePart::clear_name_part() {
- name_part_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ name_part_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
clear_has_name_part();
}
inline const ::std::string& UninterpretedOption_NamePart::name_part() const {
// @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.NamePart.name_part)
- return name_part_.GetNoArena();
+ return name_part_.Get();
}
inline void UninterpretedOption_NamePart::set_name_part(const ::std::string& value) {
set_has_name_part();
- name_part_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ name_part_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.UninterpretedOption.NamePart.name_part)
}
+#if LANG_CXX11
+inline void UninterpretedOption_NamePart::set_name_part(::std::string&& value) {
+ set_has_name_part();
+ name_part_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.UninterpretedOption.NamePart.name_part)
+}
+#endif
inline void UninterpretedOption_NamePart::set_name_part(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
set_has_name_part();
- name_part_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ name_part_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.UninterpretedOption.NamePart.name_part)
}
-inline void UninterpretedOption_NamePart::set_name_part(const char* value, size_t size) {
+inline void UninterpretedOption_NamePart::set_name_part(const char* value,
+ size_t size) {
set_has_name_part();
- name_part_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ name_part_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.UninterpretedOption.NamePart.name_part)
}
inline ::std::string* UninterpretedOption_NamePart::mutable_name_part() {
set_has_name_part();
// @@protoc_insertion_point(field_mutable:google.protobuf.UninterpretedOption.NamePart.name_part)
- return name_part_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_part_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* UninterpretedOption_NamePart::release_name_part() {
// @@protoc_insertion_point(field_release:google.protobuf.UninterpretedOption.NamePart.name_part)
clear_has_name_part();
- return name_part_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_part_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void UninterpretedOption_NamePart::set_allocated_name_part(::std::string* name_part) {
if (name_part != NULL) {
@@ -7519,9 +10447,29 @@ inline void UninterpretedOption_NamePart::set_allocated_name_part(::std::string*
} else {
clear_has_name_part();
}
- name_part_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name_part);
+ name_part_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name_part,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.UninterpretedOption.NamePart.name_part)
}
+inline ::std::string* UninterpretedOption_NamePart::unsafe_arena_release_name_part() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.UninterpretedOption.NamePart.name_part)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ clear_has_name_part();
+ return name_part_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
+inline void UninterpretedOption_NamePart::unsafe_arena_set_allocated_name_part(
+ ::std::string* name_part) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (name_part != NULL) {
+ set_has_name_part();
+ } else {
+ clear_has_name_part();
+ }
+ name_part_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ name_part, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.UninterpretedOption.NamePart.name_part)
+}
// required bool is_extension = 2;
inline bool UninterpretedOption_NamePart::has_is_extension() const {
@@ -7592,38 +10540,49 @@ inline void UninterpretedOption::clear_has_identifier_value() {
_has_bits_[0] &= ~0x00000001u;
}
inline void UninterpretedOption::clear_identifier_value() {
- identifier_value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ identifier_value_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
clear_has_identifier_value();
}
inline const ::std::string& UninterpretedOption::identifier_value() const {
// @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.identifier_value)
- return identifier_value_.GetNoArena();
+ return identifier_value_.Get();
}
inline void UninterpretedOption::set_identifier_value(const ::std::string& value) {
set_has_identifier_value();
- identifier_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ identifier_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.UninterpretedOption.identifier_value)
}
+#if LANG_CXX11
+inline void UninterpretedOption::set_identifier_value(::std::string&& value) {
+ set_has_identifier_value();
+ identifier_value_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.UninterpretedOption.identifier_value)
+}
+#endif
inline void UninterpretedOption::set_identifier_value(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
set_has_identifier_value();
- identifier_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ identifier_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.UninterpretedOption.identifier_value)
}
-inline void UninterpretedOption::set_identifier_value(const char* value, size_t size) {
+inline void UninterpretedOption::set_identifier_value(const char* value,
+ size_t size) {
set_has_identifier_value();
- identifier_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ identifier_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.UninterpretedOption.identifier_value)
}
inline ::std::string* UninterpretedOption::mutable_identifier_value() {
set_has_identifier_value();
// @@protoc_insertion_point(field_mutable:google.protobuf.UninterpretedOption.identifier_value)
- return identifier_value_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return identifier_value_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* UninterpretedOption::release_identifier_value() {
// @@protoc_insertion_point(field_release:google.protobuf.UninterpretedOption.identifier_value)
clear_has_identifier_value();
- return identifier_value_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return identifier_value_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void UninterpretedOption::set_allocated_identifier_value(::std::string* identifier_value) {
if (identifier_value != NULL) {
@@ -7631,9 +10590,29 @@ inline void UninterpretedOption::set_allocated_identifier_value(::std::string* i
} else {
clear_has_identifier_value();
}
- identifier_value_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), identifier_value);
+ identifier_value_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), identifier_value,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.UninterpretedOption.identifier_value)
}
+inline ::std::string* UninterpretedOption::unsafe_arena_release_identifier_value() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.UninterpretedOption.identifier_value)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ clear_has_identifier_value();
+ return identifier_value_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
+inline void UninterpretedOption::unsafe_arena_set_allocated_identifier_value(
+ ::std::string* identifier_value) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (identifier_value != NULL) {
+ set_has_identifier_value();
+ } else {
+ clear_has_identifier_value();
+ }
+ identifier_value_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ identifier_value, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.UninterpretedOption.identifier_value)
+}
// optional uint64 positive_int_value = 4;
inline bool UninterpretedOption::has_positive_int_value() const {
@@ -7718,38 +10697,49 @@ inline void UninterpretedOption::clear_has_string_value() {
_has_bits_[0] &= ~0x00000002u;
}
inline void UninterpretedOption::clear_string_value() {
- string_value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ string_value_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
clear_has_string_value();
}
inline const ::std::string& UninterpretedOption::string_value() const {
// @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.string_value)
- return string_value_.GetNoArena();
+ return string_value_.Get();
}
inline void UninterpretedOption::set_string_value(const ::std::string& value) {
set_has_string_value();
- string_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ string_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.UninterpretedOption.string_value)
}
+#if LANG_CXX11
+inline void UninterpretedOption::set_string_value(::std::string&& value) {
+ set_has_string_value();
+ string_value_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.UninterpretedOption.string_value)
+}
+#endif
inline void UninterpretedOption::set_string_value(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
set_has_string_value();
- string_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ string_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.UninterpretedOption.string_value)
}
-inline void UninterpretedOption::set_string_value(const void* value, size_t size) {
+inline void UninterpretedOption::set_string_value(const void* value,
+ size_t size) {
set_has_string_value();
- string_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ string_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.UninterpretedOption.string_value)
}
inline ::std::string* UninterpretedOption::mutable_string_value() {
set_has_string_value();
// @@protoc_insertion_point(field_mutable:google.protobuf.UninterpretedOption.string_value)
- return string_value_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return string_value_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* UninterpretedOption::release_string_value() {
// @@protoc_insertion_point(field_release:google.protobuf.UninterpretedOption.string_value)
clear_has_string_value();
- return string_value_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return string_value_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void UninterpretedOption::set_allocated_string_value(::std::string* string_value) {
if (string_value != NULL) {
@@ -7757,9 +10747,29 @@ inline void UninterpretedOption::set_allocated_string_value(::std::string* strin
} else {
clear_has_string_value();
}
- string_value_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), string_value);
+ string_value_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), string_value,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.UninterpretedOption.string_value)
}
+inline ::std::string* UninterpretedOption::unsafe_arena_release_string_value() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.UninterpretedOption.string_value)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ clear_has_string_value();
+ return string_value_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
+inline void UninterpretedOption::unsafe_arena_set_allocated_string_value(
+ ::std::string* string_value) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (string_value != NULL) {
+ set_has_string_value();
+ } else {
+ clear_has_string_value();
+ }
+ string_value_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ string_value, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.UninterpretedOption.string_value)
+}
// optional string aggregate_value = 8;
inline bool UninterpretedOption::has_aggregate_value() const {
@@ -7772,38 +10782,49 @@ inline void UninterpretedOption::clear_has_aggregate_value() {
_has_bits_[0] &= ~0x00000004u;
}
inline void UninterpretedOption::clear_aggregate_value() {
- aggregate_value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ aggregate_value_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
clear_has_aggregate_value();
}
inline const ::std::string& UninterpretedOption::aggregate_value() const {
// @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.aggregate_value)
- return aggregate_value_.GetNoArena();
+ return aggregate_value_.Get();
}
inline void UninterpretedOption::set_aggregate_value(const ::std::string& value) {
set_has_aggregate_value();
- aggregate_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ aggregate_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.UninterpretedOption.aggregate_value)
}
+#if LANG_CXX11
+inline void UninterpretedOption::set_aggregate_value(::std::string&& value) {
+ set_has_aggregate_value();
+ aggregate_value_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.UninterpretedOption.aggregate_value)
+}
+#endif
inline void UninterpretedOption::set_aggregate_value(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
set_has_aggregate_value();
- aggregate_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ aggregate_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.UninterpretedOption.aggregate_value)
}
-inline void UninterpretedOption::set_aggregate_value(const char* value, size_t size) {
+inline void UninterpretedOption::set_aggregate_value(const char* value,
+ size_t size) {
set_has_aggregate_value();
- aggregate_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ aggregate_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.UninterpretedOption.aggregate_value)
}
inline ::std::string* UninterpretedOption::mutable_aggregate_value() {
set_has_aggregate_value();
// @@protoc_insertion_point(field_mutable:google.protobuf.UninterpretedOption.aggregate_value)
- return aggregate_value_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return aggregate_value_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* UninterpretedOption::release_aggregate_value() {
// @@protoc_insertion_point(field_release:google.protobuf.UninterpretedOption.aggregate_value)
clear_has_aggregate_value();
- return aggregate_value_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return aggregate_value_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void UninterpretedOption::set_allocated_aggregate_value(::std::string* aggregate_value) {
if (aggregate_value != NULL) {
@@ -7811,9 +10832,29 @@ inline void UninterpretedOption::set_allocated_aggregate_value(::std::string* ag
} else {
clear_has_aggregate_value();
}
- aggregate_value_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), aggregate_value);
+ aggregate_value_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), aggregate_value,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.UninterpretedOption.aggregate_value)
}
+inline ::std::string* UninterpretedOption::unsafe_arena_release_aggregate_value() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.UninterpretedOption.aggregate_value)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ clear_has_aggregate_value();
+ return aggregate_value_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
+inline void UninterpretedOption::unsafe_arena_set_allocated_aggregate_value(
+ ::std::string* aggregate_value) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (aggregate_value != NULL) {
+ set_has_aggregate_value();
+ } else {
+ clear_has_aggregate_value();
+ }
+ aggregate_value_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ aggregate_value, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.UninterpretedOption.aggregate_value)
+}
// -------------------------------------------------------------------
@@ -7890,38 +10931,49 @@ inline void SourceCodeInfo_Location::clear_has_leading_comments() {
_has_bits_[0] &= ~0x00000001u;
}
inline void SourceCodeInfo_Location::clear_leading_comments() {
- leading_comments_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ leading_comments_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
clear_has_leading_comments();
}
inline const ::std::string& SourceCodeInfo_Location::leading_comments() const {
// @@protoc_insertion_point(field_get:google.protobuf.SourceCodeInfo.Location.leading_comments)
- return leading_comments_.GetNoArena();
+ return leading_comments_.Get();
}
inline void SourceCodeInfo_Location::set_leading_comments(const ::std::string& value) {
set_has_leading_comments();
- leading_comments_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ leading_comments_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.SourceCodeInfo.Location.leading_comments)
}
+#if LANG_CXX11
+inline void SourceCodeInfo_Location::set_leading_comments(::std::string&& value) {
+ set_has_leading_comments();
+ leading_comments_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.SourceCodeInfo.Location.leading_comments)
+}
+#endif
inline void SourceCodeInfo_Location::set_leading_comments(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
set_has_leading_comments();
- leading_comments_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ leading_comments_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.SourceCodeInfo.Location.leading_comments)
}
-inline void SourceCodeInfo_Location::set_leading_comments(const char* value, size_t size) {
+inline void SourceCodeInfo_Location::set_leading_comments(const char* value,
+ size_t size) {
set_has_leading_comments();
- leading_comments_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ leading_comments_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.SourceCodeInfo.Location.leading_comments)
}
inline ::std::string* SourceCodeInfo_Location::mutable_leading_comments() {
set_has_leading_comments();
// @@protoc_insertion_point(field_mutable:google.protobuf.SourceCodeInfo.Location.leading_comments)
- return leading_comments_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return leading_comments_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* SourceCodeInfo_Location::release_leading_comments() {
// @@protoc_insertion_point(field_release:google.protobuf.SourceCodeInfo.Location.leading_comments)
clear_has_leading_comments();
- return leading_comments_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return leading_comments_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void SourceCodeInfo_Location::set_allocated_leading_comments(::std::string* leading_comments) {
if (leading_comments != NULL) {
@@ -7929,9 +10981,29 @@ inline void SourceCodeInfo_Location::set_allocated_leading_comments(::std::strin
} else {
clear_has_leading_comments();
}
- leading_comments_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), leading_comments);
+ leading_comments_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), leading_comments,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.SourceCodeInfo.Location.leading_comments)
}
+inline ::std::string* SourceCodeInfo_Location::unsafe_arena_release_leading_comments() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.SourceCodeInfo.Location.leading_comments)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ clear_has_leading_comments();
+ return leading_comments_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
+inline void SourceCodeInfo_Location::unsafe_arena_set_allocated_leading_comments(
+ ::std::string* leading_comments) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (leading_comments != NULL) {
+ set_has_leading_comments();
+ } else {
+ clear_has_leading_comments();
+ }
+ leading_comments_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ leading_comments, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.SourceCodeInfo.Location.leading_comments)
+}
// optional string trailing_comments = 4;
inline bool SourceCodeInfo_Location::has_trailing_comments() const {
@@ -7944,38 +11016,49 @@ inline void SourceCodeInfo_Location::clear_has_trailing_comments() {
_has_bits_[0] &= ~0x00000002u;
}
inline void SourceCodeInfo_Location::clear_trailing_comments() {
- trailing_comments_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ trailing_comments_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
clear_has_trailing_comments();
}
inline const ::std::string& SourceCodeInfo_Location::trailing_comments() const {
// @@protoc_insertion_point(field_get:google.protobuf.SourceCodeInfo.Location.trailing_comments)
- return trailing_comments_.GetNoArena();
+ return trailing_comments_.Get();
}
inline void SourceCodeInfo_Location::set_trailing_comments(const ::std::string& value) {
set_has_trailing_comments();
- trailing_comments_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ trailing_comments_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.SourceCodeInfo.Location.trailing_comments)
}
+#if LANG_CXX11
+inline void SourceCodeInfo_Location::set_trailing_comments(::std::string&& value) {
+ set_has_trailing_comments();
+ trailing_comments_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.SourceCodeInfo.Location.trailing_comments)
+}
+#endif
inline void SourceCodeInfo_Location::set_trailing_comments(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
set_has_trailing_comments();
- trailing_comments_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ trailing_comments_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.SourceCodeInfo.Location.trailing_comments)
}
-inline void SourceCodeInfo_Location::set_trailing_comments(const char* value, size_t size) {
+inline void SourceCodeInfo_Location::set_trailing_comments(const char* value,
+ size_t size) {
set_has_trailing_comments();
- trailing_comments_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ trailing_comments_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.SourceCodeInfo.Location.trailing_comments)
}
inline ::std::string* SourceCodeInfo_Location::mutable_trailing_comments() {
set_has_trailing_comments();
// @@protoc_insertion_point(field_mutable:google.protobuf.SourceCodeInfo.Location.trailing_comments)
- return trailing_comments_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return trailing_comments_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* SourceCodeInfo_Location::release_trailing_comments() {
// @@protoc_insertion_point(field_release:google.protobuf.SourceCodeInfo.Location.trailing_comments)
clear_has_trailing_comments();
- return trailing_comments_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return trailing_comments_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void SourceCodeInfo_Location::set_allocated_trailing_comments(::std::string* trailing_comments) {
if (trailing_comments != NULL) {
@@ -7983,9 +11066,29 @@ inline void SourceCodeInfo_Location::set_allocated_trailing_comments(::std::stri
} else {
clear_has_trailing_comments();
}
- trailing_comments_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), trailing_comments);
+ trailing_comments_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), trailing_comments,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.SourceCodeInfo.Location.trailing_comments)
}
+inline ::std::string* SourceCodeInfo_Location::unsafe_arena_release_trailing_comments() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.SourceCodeInfo.Location.trailing_comments)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ clear_has_trailing_comments();
+ return trailing_comments_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
+inline void SourceCodeInfo_Location::unsafe_arena_set_allocated_trailing_comments(
+ ::std::string* trailing_comments) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (trailing_comments != NULL) {
+ set_has_trailing_comments();
+ } else {
+ clear_has_trailing_comments();
+ }
+ trailing_comments_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ trailing_comments, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.SourceCodeInfo.Location.trailing_comments)
+}
// repeated string leading_detached_comments = 6;
inline int SourceCodeInfo_Location::leading_detached_comments_size() const {
@@ -8006,7 +11109,14 @@ inline void SourceCodeInfo_Location::set_leading_detached_comments(int index, co
// @@protoc_insertion_point(field_set:google.protobuf.SourceCodeInfo.Location.leading_detached_comments)
leading_detached_comments_.Mutable(index)->assign(value);
}
+#if LANG_CXX11
+inline void SourceCodeInfo_Location::set_leading_detached_comments(int index, ::std::string&& value) {
+ // @@protoc_insertion_point(field_set:google.protobuf.SourceCodeInfo.Location.leading_detached_comments)
+ leading_detached_comments_.Mutable(index)->assign(std::move(value));
+}
+#endif
inline void SourceCodeInfo_Location::set_leading_detached_comments(int index, const char* value) {
+ GOOGLE_DCHECK(value != NULL);
leading_detached_comments_.Mutable(index)->assign(value);
// @@protoc_insertion_point(field_set_char:google.protobuf.SourceCodeInfo.Location.leading_detached_comments)
}
@@ -8023,7 +11133,14 @@ inline void SourceCodeInfo_Location::add_leading_detached_comments(const ::std::
leading_detached_comments_.Add()->assign(value);
// @@protoc_insertion_point(field_add:google.protobuf.SourceCodeInfo.Location.leading_detached_comments)
}
+#if LANG_CXX11
+inline void SourceCodeInfo_Location::add_leading_detached_comments(::std::string&& value) {
+ leading_detached_comments_.Add(std::move(value));
+ // @@protoc_insertion_point(field_add:google.protobuf.SourceCodeInfo.Location.leading_detached_comments)
+}
+#endif
inline void SourceCodeInfo_Location::add_leading_detached_comments(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
leading_detached_comments_.Add()->assign(value);
// @@protoc_insertion_point(field_add_char:google.protobuf.SourceCodeInfo.Location.leading_detached_comments)
}
@@ -8121,38 +11238,49 @@ inline void GeneratedCodeInfo_Annotation::clear_has_source_file() {
_has_bits_[0] &= ~0x00000001u;
}
inline void GeneratedCodeInfo_Annotation::clear_source_file() {
- source_file_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ source_file_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
clear_has_source_file();
}
inline const ::std::string& GeneratedCodeInfo_Annotation::source_file() const {
// @@protoc_insertion_point(field_get:google.protobuf.GeneratedCodeInfo.Annotation.source_file)
- return source_file_.GetNoArena();
+ return source_file_.Get();
}
inline void GeneratedCodeInfo_Annotation::set_source_file(const ::std::string& value) {
set_has_source_file();
- source_file_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ source_file_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.GeneratedCodeInfo.Annotation.source_file)
}
+#if LANG_CXX11
+inline void GeneratedCodeInfo_Annotation::set_source_file(::std::string&& value) {
+ set_has_source_file();
+ source_file_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.GeneratedCodeInfo.Annotation.source_file)
+}
+#endif
inline void GeneratedCodeInfo_Annotation::set_source_file(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
set_has_source_file();
- source_file_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ source_file_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.GeneratedCodeInfo.Annotation.source_file)
}
-inline void GeneratedCodeInfo_Annotation::set_source_file(const char* value, size_t size) {
+inline void GeneratedCodeInfo_Annotation::set_source_file(const char* value,
+ size_t size) {
set_has_source_file();
- source_file_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ source_file_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.GeneratedCodeInfo.Annotation.source_file)
}
inline ::std::string* GeneratedCodeInfo_Annotation::mutable_source_file() {
set_has_source_file();
// @@protoc_insertion_point(field_mutable:google.protobuf.GeneratedCodeInfo.Annotation.source_file)
- return source_file_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return source_file_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* GeneratedCodeInfo_Annotation::release_source_file() {
// @@protoc_insertion_point(field_release:google.protobuf.GeneratedCodeInfo.Annotation.source_file)
clear_has_source_file();
- return source_file_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return source_file_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void GeneratedCodeInfo_Annotation::set_allocated_source_file(::std::string* source_file) {
if (source_file != NULL) {
@@ -8160,9 +11288,29 @@ inline void GeneratedCodeInfo_Annotation::set_allocated_source_file(::std::strin
} else {
clear_has_source_file();
}
- source_file_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), source_file);
+ source_file_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), source_file,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.GeneratedCodeInfo.Annotation.source_file)
}
+inline ::std::string* GeneratedCodeInfo_Annotation::unsafe_arena_release_source_file() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.GeneratedCodeInfo.Annotation.source_file)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ clear_has_source_file();
+ return source_file_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
+inline void GeneratedCodeInfo_Annotation::unsafe_arena_set_allocated_source_file(
+ ::std::string* source_file) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (source_file != NULL) {
+ set_has_source_file();
+ } else {
+ clear_has_source_file();
+ }
+ source_file_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ source_file, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.GeneratedCodeInfo.Annotation.source_file)
+}
// optional int32 begin = 3;
inline bool GeneratedCodeInfo_Annotation::has_begin() const {
@@ -8246,7 +11394,9 @@ GeneratedCodeInfo::annotation() const {
return annotation_;
}
-#endif // !PROTOBUF_INLINE_NOT_IN_HEADERS
+#ifdef __GNUC__
+ #pragma GCC diagnostic pop
+#endif // __GNUC__
// -------------------------------------------------------------------
// -------------------------------------------------------------------
@@ -8295,14 +11445,16 @@ GeneratedCodeInfo::annotation() const {
// -------------------------------------------------------------------
+// -------------------------------------------------------------------
+
+// -------------------------------------------------------------------
-// @@protoc_insertion_point(namespace_scope)
+// @@protoc_insertion_point(namespace_scope)
} // namespace protobuf
} // namespace google
-#ifndef SWIG
namespace google {
namespace protobuf {
@@ -8339,7 +11491,6 @@ inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::MethodOption
} // namespace protobuf
} // namespace google
-#endif // SWIG
// @@protoc_insertion_point(global_scope)
diff --git a/src/google/protobuf/descriptor.proto b/src/google/protobuf/descriptor.proto
index 03aba076..8697a50d 100644
--- a/src/google/protobuf/descriptor.proto
+++ b/src/google/protobuf/descriptor.proto
@@ -45,6 +45,7 @@ option java_package = "com.google.protobuf";
option java_outer_classname = "DescriptorProtos";
option csharp_namespace = "Google.Protobuf.Reflection";
option objc_class_prefix = "GPB";
+option cc_enable_arenas = true;
// descriptor.proto must be optimized for speed because reflection-based
// algorithms don't work during bootstrapping.
@@ -101,6 +102,8 @@ message DescriptorProto {
message ExtensionRange {
optional int32 start = 1;
optional int32 end = 2;
+
+ optional ExtensionRangeOptions options = 3;
}
repeated ExtensionRange extension_range = 5;
@@ -121,6 +124,14 @@ message DescriptorProto {
repeated string reserved_name = 10;
}
+message ExtensionRangeOptions {
+ // The parser stores options it doesn't recognize here. See above.
+ repeated UninterpretedOption uninterpreted_option = 999;
+
+ // Clients can define custom options in extensions of this message. See above.
+ extensions 1000 to max;
+}
+
// Describes a field within a message.
message FieldDescriptorProto {
enum Type {
@@ -139,7 +150,11 @@ message FieldDescriptorProto {
TYPE_FIXED32 = 7;
TYPE_BOOL = 8;
TYPE_STRING = 9;
- TYPE_GROUP = 10; // Tag-delimited aggregate.
+ // Tag-delimited aggregate.
+ // Group type is deprecated and not supported in proto3. However, Proto3
+ // implementations should still be able to parse the group wire format and
+ // treat group fields as unknown fields.
+ TYPE_GROUP = 10;
TYPE_MESSAGE = 11; // Length-delimited aggregate.
// New in version 2.
@@ -211,6 +226,26 @@ message EnumDescriptorProto {
repeated EnumValueDescriptorProto value = 2;
optional EnumOptions options = 3;
+
+ // Range of reserved numeric values. Reserved values may not be used by
+ // entries in the same enum. Reserved ranges may not overlap.
+ //
+ // Note that this is distinct from DescriptorProto.ReservedRange in that it
+ // is inclusive such that it can appropriately represent the entire int32
+ // domain.
+ message EnumReservedRange {
+ optional int32 start = 1; // Inclusive.
+ optional int32 end = 2; // Inclusive.
+ }
+
+ // Range of reserved numeric values. Reserved numeric values may not be used
+ // by enum values in the same enum declaration. Reserved ranges may not
+ // overlap.
+ repeated EnumReservedRange reserved_range = 4;
+
+ // Reserved enum value names, which may not be reused. A given name may only
+ // be reserved once.
+ repeated string reserved_name = 5;
}
// Describes a value within an enum.
@@ -347,6 +382,7 @@ message FileOptions {
optional bool cc_generic_services = 16 [default=false];
optional bool java_generic_services = 17 [default=false];
optional bool py_generic_services = 18 [default=false];
+ optional bool php_generic_services = 42 [default=false];
// Is this file deprecated?
// Depending on the target platform, this can emit Deprecated annotations
@@ -372,10 +408,21 @@ message FileOptions {
// to prefix the types/symbols defined.
optional string swift_prefix = 39;
- // The parser stores options it doesn't recognize here. See above.
+ // Sets the php class prefix which is prepended to all php generated classes
+ // from this .proto. Default is empty.
+ optional string php_class_prefix = 40;
+
+ // Use this option to change the namespace of php generated classes. Default
+ // is empty. When this option is empty, the package name will be used for
+ // determining the namespace.
+ optional string php_namespace = 41;
+
+ // The parser stores options it doesn't recognize here.
+ // See the documentation for the "Options" section above.
repeated UninterpretedOption uninterpreted_option = 999;
- // Clients can define custom options in extensions of this message. See above.
+ // Clients can define custom options in extensions of this message.
+ // See the documentation for the "Options" section above.
extensions 1000 to max;
reserved 38;
@@ -437,7 +484,7 @@ message MessageOptions {
optional bool map_entry = 7;
reserved 8; // javalite_serializable
-
+ reserved 9; // javanano_as_lite
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
@@ -469,13 +516,15 @@ message FieldOptions {
// The jstype option determines the JavaScript type used for values of the
// field. The option is permitted only for 64 bit integral and fixed types
- // (int64, uint64, sint64, fixed64, sfixed64). By default these types are
- // represented as JavaScript strings. This avoids loss of precision that can
- // happen when a large value is converted to a floating point JavaScript
- // numbers. Specifying JS_NUMBER for the jstype causes the generated
- // JavaScript code to use the JavaScript "number" type instead of strings.
- // This option is an enum to permit additional types to be added,
- // e.g. goog.math.Integer.
+ // (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING
+ // is represented as JavaScript string, which avoids loss of precision that
+ // can happen when a large value is converted to a floating point JavaScript.
+ // Specifying JS_NUMBER for the jstype causes the generated JavaScript code to
+ // use the JavaScript "number" type. The behavior of the default option
+ // JS_NORMAL is implementation dependent.
+ //
+ // This option is an enum to permit additional types to be added, e.g.
+ // goog.math.Integer.
optional JSType jstype = 6 [default = JS_NORMAL];
enum JSType {
// Use the default type.
@@ -557,6 +606,7 @@ message EnumOptions {
// is a formalization for deprecating enums.
optional bool deprecated = 3 [default=false];
+ reserved 5; // javanano_as_lite
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
diff --git a/src/google/protobuf/descriptor_database.cc b/src/google/protobuf/descriptor_database.cc
index 57ae960f..ba85ef13 100644
--- a/src/google/protobuf/descriptor_database.cc
+++ b/src/google/protobuf/descriptor_database.cc
@@ -39,8 +39,9 @@
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/stubs/strutil.h>
-#include <google/protobuf/stubs/stl_util.h>
+
#include <google/protobuf/stubs/map_util.h>
+#include <google/protobuf/stubs/stl_util.h>
namespace google {
namespace protobuf {
@@ -199,7 +200,7 @@ template <typename Value>
bool SimpleDescriptorDatabase::DescriptorIndex<Value>::FindAllExtensionNumbers(
const string& containing_type,
std::vector<int>* output) {
- typename std::map<pair<string, int>, Value>::const_iterator it =
+ typename std::map<std::pair<string, int>, Value>::const_iterator it =
by_extension_.lower_bound(std::make_pair(containing_type, 0));
bool success = false;
@@ -213,7 +214,7 @@ bool SimpleDescriptorDatabase::DescriptorIndex<Value>::FindAllExtensionNumbers(
}
template <typename Value>
-typename map<string, Value>::iterator
+typename std::map<string, Value>::iterator
SimpleDescriptorDatabase::DescriptorIndex<Value>::FindLastLessOrEqual(
const string& name) {
// Find the last key in the map which sorts less than or equal to the
@@ -230,7 +231,7 @@ bool SimpleDescriptorDatabase::DescriptorIndex<Value>::IsSubSymbol(
const string& sub_symbol, const string& super_symbol) {
return sub_symbol == super_symbol ||
(HasPrefixString(super_symbol, sub_symbol) &&
- super_symbol[sub_symbol.size()] == '.');
+ super_symbol[sub_symbol.size()] == '.');
}
template <typename Value>
diff --git a/src/google/protobuf/descriptor_database.h b/src/google/protobuf/descriptor_database.h
index be97a6d8..28f8af7a 100644
--- a/src/google/protobuf/descriptor_database.h
+++ b/src/google/protobuf/descriptor_database.h
@@ -102,6 +102,18 @@ class LIBPROTOBUF_EXPORT DescriptorDatabase {
}
+ // Finds the file names and appends them to the output in an
+ // undefined order. This method is best-effort: it's not guaranteed that the
+ // database will find all files. Returns true if the database supports
+ // searching all file names, otherwise returns false and leaves output
+ // unchanged.
+ //
+ // This method has a default implementation that always returns
+ // false.
+ virtual bool FindAllFileNames(std::vector<string>* output) {
+ return false;
+ }
+
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DescriptorDatabase);
};
diff --git a/src/google/protobuf/descriptor_database_unittest.cc b/src/google/protobuf/descriptor_database_unittest.cc
index 05d67656..9d710886 100644
--- a/src/google/protobuf/descriptor_database_unittest.cc
+++ b/src/google/protobuf/descriptor_database_unittest.cc
@@ -44,7 +44,6 @@
#include <google/protobuf/descriptor.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/text_format.h>
-#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
@@ -248,6 +247,10 @@ TEST_P(DescriptorDatabaseTest, FindFileContainingSymbol) {
FileDescriptorProto file;
EXPECT_TRUE(database_->FindFileContainingSymbol("Foo.qux", &file));
EXPECT_EQ("foo.proto", file.name());
+ // Non-existent field under a valid top level symbol can also be
+ // found.
+ EXPECT_TRUE(database_->FindFileContainingSymbol("Foo.none_field.none",
+ &file));
}
{
diff --git a/src/google/protobuf/descriptor_unittest.cc b/src/google/protobuf/descriptor_unittest.cc
index 7ec75156..6cca0ada 100644
--- a/src/google/protobuf/descriptor_unittest.cc
+++ b/src/google/protobuf/descriptor_unittest.cc
@@ -34,6 +34,7 @@
//
// This file makes extensive use of RFC 3092. :)
+#include <limits>
#include <memory>
#ifndef _SHARED_PTR_H
#include <google/protobuf/stubs/shared_ptr.h>
@@ -44,6 +45,7 @@
#include <google/protobuf/compiler/parser.h>
#include <google/protobuf/unittest.pb.h>
#include <google/protobuf/unittest_custom_options.pb.h>
+#include <google/protobuf/unittest_lazy_dependencies.pb.h>
#include <google/protobuf/unittest_proto3_arena.pb.h>
#include <google/protobuf/io/tokenizer.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
@@ -52,7 +54,6 @@
#include <google/protobuf/descriptor_database.h>
#include <google/protobuf/dynamic_message.h>
#include <google/protobuf/text_format.h>
-#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/substitute.h>
#include <google/protobuf/stubs/common.h>
@@ -62,6 +63,7 @@
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
+
namespace google {
namespace protobuf {
@@ -157,6 +159,14 @@ DescriptorProto::ReservedRange* AddReservedRange(DescriptorProto* parent,
return result;
}
+EnumDescriptorProto::EnumReservedRange* AddReservedRange(
+ EnumDescriptorProto* parent, int start, int end) {
+ EnumDescriptorProto::EnumReservedRange* result = parent->add_reserved_range();
+ result->set_start(start);
+ result->set_end(end);
+ return result;
+}
+
EnumValueDescriptorProto* AddEnumValue(EnumDescriptorProto* enum_proto,
const string& name, int number) {
EnumValueDescriptorProto* result = enum_proto->add_value();
@@ -501,7 +511,7 @@ void ExtractDebugString(
for (int i = 0; i < file->dependency_count(); ++i) {
ExtractDebugString(file->dependency(i), visited, debug_strings);
}
- debug_strings->push_back(make_pair(file->name(), file->DebugString()));
+ debug_strings->push_back(std::make_pair(file->name(), file->DebugString()));
}
class SimpleErrorCollector : public google::protobuf::io::ErrorCollector {
@@ -2047,6 +2057,137 @@ TEST_F(ReservedDescriptorTest, IsReservedName) {
// ===================================================================
+// Test reserved enum fields.
+class ReservedEnumDescriptorTest : public testing::Test {
+ protected:
+ virtual void SetUp() {
+ // Build descriptors for the following definitions:
+ //
+ // enum Foo {
+ // BAR = 1;
+ // reserved 2, 9 to 11, 15;
+ // reserved "foo", "bar";
+ // }
+
+ FileDescriptorProto foo_file;
+ foo_file.set_name("foo.proto");
+
+ EnumDescriptorProto* foo = AddEnum(&foo_file, "Foo");
+ EnumDescriptorProto* edge1 = AddEnum(&foo_file, "Edge1");
+ EnumDescriptorProto* edge2 = AddEnum(&foo_file, "Edge2");
+
+ AddEnumValue(foo, "BAR", 4);
+ AddReservedRange(foo, -5, -3);
+ AddReservedRange(foo, -2, 1);
+ AddReservedRange(foo, 2, 3);
+ AddReservedRange(foo, 9, 12);
+ AddReservedRange(foo, 15, 16);
+
+ foo->add_reserved_name("foo");
+ foo->add_reserved_name("bar");
+
+ // Some additional edge cases that cover most or all of the range of enum
+ // values
+
+ // Note: We use INT_MAX as the maximum reserved range upper bound,
+ // inclusive.
+ AddEnumValue(edge1, "EDGE1", 1);
+ AddReservedRange(edge1, 10, INT_MAX);
+ AddEnumValue(edge2, "EDGE2", 15);
+ AddReservedRange(edge2, INT_MIN, 10);
+
+ // Build the descriptors and get the pointers.
+ foo_file_ = pool_.BuildFile(foo_file);
+ ASSERT_TRUE(foo_file_ != NULL);
+
+ ASSERT_EQ(3, foo_file_->enum_type_count());
+ foo_ = foo_file_->enum_type(0);
+ edge1_ = foo_file_->enum_type(1);
+ edge2_ = foo_file_->enum_type(2);
+ }
+
+ DescriptorPool pool_;
+ const FileDescriptor* foo_file_;
+ const EnumDescriptor* foo_;
+ const EnumDescriptor* edge1_;
+ const EnumDescriptor* edge2_;
+};
+
+TEST_F(ReservedEnumDescriptorTest, ReservedRanges) {
+ ASSERT_EQ(5, foo_->reserved_range_count());
+
+ EXPECT_EQ(-5, foo_->reserved_range(0)->start);
+ EXPECT_EQ(-3, foo_->reserved_range(0)->end);
+
+ EXPECT_EQ(-2, foo_->reserved_range(1)->start);
+ EXPECT_EQ(1, foo_->reserved_range(1)->end);
+
+ EXPECT_EQ(2, foo_->reserved_range(2)->start);
+ EXPECT_EQ(3, foo_->reserved_range(2)->end);
+
+ EXPECT_EQ(9, foo_->reserved_range(3)->start);
+ EXPECT_EQ(12, foo_->reserved_range(3)->end);
+
+ EXPECT_EQ(15, foo_->reserved_range(4)->start);
+ EXPECT_EQ(16, foo_->reserved_range(4)->end);
+
+ ASSERT_EQ(1, edge1_->reserved_range_count());
+ EXPECT_EQ(10, edge1_->reserved_range(0)->start);
+ EXPECT_EQ(INT_MAX, edge1_->reserved_range(0)->end);
+
+ ASSERT_EQ(1, edge2_->reserved_range_count());
+ EXPECT_EQ(INT_MIN, edge2_->reserved_range(0)->start);
+ EXPECT_EQ(10, edge2_->reserved_range(0)->end);
+}
+
+TEST_F(ReservedEnumDescriptorTest, IsReservedNumber) {
+ EXPECT_TRUE(foo_->IsReservedNumber(-5));
+ EXPECT_TRUE(foo_->IsReservedNumber(-4));
+ EXPECT_TRUE(foo_->IsReservedNumber(-3));
+ EXPECT_TRUE(foo_->IsReservedNumber(-2));
+ EXPECT_TRUE(foo_->IsReservedNumber(-1));
+ EXPECT_TRUE(foo_->IsReservedNumber(0));
+ EXPECT_TRUE(foo_->IsReservedNumber(1));
+ EXPECT_TRUE (foo_->IsReservedNumber(2));
+ EXPECT_TRUE(foo_->IsReservedNumber(3));
+ EXPECT_FALSE(foo_->IsReservedNumber(8));
+ EXPECT_TRUE (foo_->IsReservedNumber(9));
+ EXPECT_TRUE (foo_->IsReservedNumber(10));
+ EXPECT_TRUE (foo_->IsReservedNumber(11));
+ EXPECT_TRUE(foo_->IsReservedNumber(12));
+ EXPECT_FALSE(foo_->IsReservedNumber(13));
+ EXPECT_FALSE(foo_->IsReservedNumber(13));
+ EXPECT_FALSE(foo_->IsReservedNumber(14));
+ EXPECT_TRUE (foo_->IsReservedNumber(15));
+ EXPECT_TRUE(foo_->IsReservedNumber(16));
+ EXPECT_FALSE(foo_->IsReservedNumber(17));
+
+ EXPECT_FALSE(edge1_->IsReservedNumber(9));
+ EXPECT_TRUE(edge1_->IsReservedNumber(10));
+ EXPECT_TRUE(edge1_->IsReservedNumber(INT_MAX - 1));
+ EXPECT_TRUE(edge1_->IsReservedNumber(INT_MAX));
+
+ EXPECT_TRUE(edge2_->IsReservedNumber(INT_MIN));
+ EXPECT_TRUE(edge2_->IsReservedNumber(9));
+ EXPECT_TRUE(edge2_->IsReservedNumber(10));
+ EXPECT_FALSE(edge2_->IsReservedNumber(11));
+}
+
+TEST_F(ReservedEnumDescriptorTest, ReservedNames) {
+ ASSERT_EQ(2, foo_->reserved_name_count());
+
+ EXPECT_EQ("foo", foo_->reserved_name(0));
+ EXPECT_EQ("bar", foo_->reserved_name(1));
+}
+
+TEST_F(ReservedEnumDescriptorTest, IsReservedName) {
+ EXPECT_TRUE (foo_->IsReservedName("foo"));
+ EXPECT_TRUE (foo_->IsReservedName("bar"));
+ EXPECT_FALSE(foo_->IsReservedName("baz"));
+}
+
+// ===================================================================
+
class MiscTest : public testing::Test {
protected:
// Function which makes a field descriptor of the given type.
@@ -3774,6 +3915,138 @@ TEST_F(ValidationErrorTest, ReservedFieldsDebugString) {
file->DebugString());
}
+TEST_F(ValidationErrorTest, EnumReservedFieldError) {
+ BuildFileWithErrors(
+ "name: \"foo.proto\" "
+ "enum_type {"
+ " name: \"Foo\""
+ " value { name:\"BAR\" number:15 }"
+ " reserved_range { start: 10 end: 20 }"
+ "}",
+
+ "foo.proto: BAR: NUMBER: Enum value \"BAR\" uses reserved number 15.\n");
+}
+
+TEST_F(ValidationErrorTest, EnumNegativeReservedFieldError) {
+ BuildFileWithErrors(
+ "name: \"foo.proto\" "
+ "enum_type {"
+ " name: \"Foo\""
+ " value { name:\"BAR\" number:-15 }"
+ " reserved_range { start: -20 end: -10 }"
+ "}",
+
+ "foo.proto: BAR: NUMBER: Enum value \"BAR\" uses reserved number -15.\n");
+}
+
+TEST_F(ValidationErrorTest, EnumReservedRangeOverlap) {
+ BuildFileWithErrors(
+ "name: \"foo.proto\" "
+ "enum_type {"
+ " name: \"Foo\""
+ " value { name:\"BAR\" number:0 }"
+ " reserved_range { start: 10 end: 20 }"
+ " reserved_range { start: 5 end: 15 }"
+ "}",
+
+ "foo.proto: Foo: NUMBER: Reserved range 5 to 14"
+ " overlaps with already-defined range 10 to 19.\n");
+}
+
+TEST_F(ValidationErrorTest, EnumNegativeReservedRangeOverlap) {
+ BuildFileWithErrors(
+ "name: \"foo.proto\" "
+ "enum_type {"
+ " name: \"Foo\""
+ " value { name:\"BAR\" number:0 }"
+ " reserved_range { start: -20 end: -10 }"
+ " reserved_range { start: -15 end: -5 }"
+ "}",
+
+ "foo.proto: Foo: NUMBER: Reserved range -15 to -6"
+ " overlaps with already-defined range -20 to -11.\n");
+}
+
+TEST_F(ValidationErrorTest, EnumMixedReservedRangeOverlap) {
+ BuildFileWithErrors(
+ "name: \"foo.proto\" "
+ "enum_type {"
+ " name: \"Foo\""
+ " value { name:\"BAR\" number:20 }"
+ " reserved_range { start: -20 end: 10 }"
+ " reserved_range { start: -15 end: 5 }"
+ "}",
+
+ "foo.proto: Foo: NUMBER: Reserved range -15 to 4"
+ " overlaps with already-defined range -20 to 9.\n");
+}
+
+TEST_F(ValidationErrorTest, EnumReservedRangeStartGreaterThanEnd) {
+ BuildFileWithErrors(
+ "name: \"foo.proto\" "
+ "enum_type {"
+ " name: \"Foo\""
+ " value { name:\"BAR\" number:20 }"
+ " reserved_range { start: 11 end: 10 }"
+ "}",
+
+ "foo.proto: Foo: NUMBER: Reserved range end number must be greater"
+ " than start number.\n");
+}
+
+TEST_F(ValidationErrorTest, EnumReservedNameError) {
+ BuildFileWithErrors(
+ "name: \"foo.proto\" "
+ "enum_type {"
+ " name: \"Foo\""
+ " value { name:\"FOO\" number:15 }"
+ " value { name:\"BAR\" number:15 }"
+ " reserved_name: \"FOO\""
+ " reserved_name: \"BAR\""
+ "}",
+
+ "foo.proto: FOO: NAME: Enum value \"FOO\" is reserved.\n"
+ "foo.proto: BAR: NAME: Enum value \"BAR\" is reserved.\n");
+}
+
+TEST_F(ValidationErrorTest, EnumReservedNameRedundant) {
+ BuildFileWithErrors(
+ "name: \"foo.proto\" "
+ "enum_type {"
+ " name: \"Foo\""
+ " value { name:\"FOO\" number:15 }"
+ " reserved_name: \"foo\""
+ " reserved_name: \"foo\""
+ "}",
+
+ "foo.proto: foo: NAME: Enum value \"foo\" is reserved multiple times.\n");
+}
+
+TEST_F(ValidationErrorTest, EnumReservedFieldsDebugString) {
+ const FileDescriptor* file = BuildFile(
+ "name: \"foo.proto\" "
+ "enum_type {"
+ " name: \"Foo\""
+ " value { name:\"FOO\" number:3 }"
+ " reserved_name: \"foo\""
+ " reserved_name: \"bar\""
+ " reserved_range { start: -6 end: -6 }"
+ " reserved_range { start: -5 end: -4 }"
+ " reserved_range { start: -1 end: 1 }"
+ " reserved_range { start: 5 end: 5 }"
+ " reserved_range { start: 10 end: 19 }"
+ "}");
+
+ ASSERT_EQ(
+ "syntax = \"proto2\";\n\n"
+ "enum Foo {\n"
+ " FOO = 3;\n"
+ " reserved -6, -5 to -4, -1 to 1, 5, 10 to 19;\n"
+ " reserved \"foo\", \"bar\";\n"
+ "}\n\n",
+ file->DebugString());
+}
+
TEST_F(ValidationErrorTest, InvalidDefaults) {
BuildFileWithErrors(
"name: \"foo.proto\" "
@@ -6066,6 +6339,7 @@ TEST_F(ValidationErrorTest, ValidateProto3JsonName) {
"conflicts with field \"ab\". This is not allowed in proto3.\n");
}
+
// ===================================================================
// DescriptorDatabase
@@ -6824,6 +7098,360 @@ TEST_F(CopySourceCodeInfoToTest, CopySourceCodeInfoTo) {
// ===================================================================
+class LazilyBuildDependenciesTest : public testing::Test {
+ public:
+ LazilyBuildDependenciesTest() : pool_(&db_, NULL) {
+ pool_.InternalSetLazilyBuildDependencies();
+ }
+
+ void ParseProtoAndAddToDb(const char* proto) {
+ FileDescriptorProto tmp;
+ ASSERT_TRUE(TextFormat::ParseFromString(proto, &tmp));
+ db_.Add(tmp);
+ }
+
+ void ParseProtoAndAddToDb(const string& proto) {
+ FileDescriptorProto tmp;
+ ASSERT_TRUE(TextFormat::ParseFromString(proto, &tmp));
+ db_.Add(tmp);
+ }
+
+ void AddSimpleMessageProtoFileToDb(const char* file_name,
+ const char* message_name) {
+ ParseProtoAndAddToDb("name: '" + string(file_name) +
+ ".proto' "
+ "package: \"protobuf_unittest\" "
+ "message_type { "
+ " name:'" +
+ string(message_name) +
+ "' "
+ " field { name:'a' number:1 "
+ " label:LABEL_OPTIONAL "
+ " type_name:'int32' } "
+ "}");
+ }
+
+ void AddSimpleEnumProtoFileToDb(const char* file_name, const char* enum_name,
+ const char* enum_value_name) {
+ ParseProtoAndAddToDb("name: '" + string(file_name) +
+ ".proto' "
+ "package: 'protobuf_unittest' "
+ "enum_type { "
+ " name:'" +
+ string(enum_name) +
+ "' "
+ " value { name:'" +
+ string(enum_value_name) +
+ "' number:1 } "
+ "}");
+ }
+
+ protected:
+ SimpleDescriptorDatabase db_;
+ DescriptorPool pool_;
+};
+
+TEST_F(LazilyBuildDependenciesTest, Message) {
+ ParseProtoAndAddToDb(
+ "name: 'foo.proto' "
+ "package: 'protobuf_unittest' "
+ "dependency: 'bar.proto' "
+ "message_type { "
+ " name:'Foo' "
+ " field { name:'bar' number:1 label:LABEL_OPTIONAL "
+ "type_name:'.protobuf_unittest.Bar' } "
+ "}");
+ AddSimpleMessageProtoFileToDb("bar", "Bar");
+
+ // Verify neither has been built yet.
+ EXPECT_FALSE(pool_.InternalIsFileLoaded("foo.proto"));
+ EXPECT_FALSE(pool_.InternalIsFileLoaded("bar.proto"));
+
+ const FileDescriptor* file = pool_.FindFileByName("foo.proto");
+
+ // Verify only foo gets built when asking for foo.proto
+ EXPECT_TRUE(file != NULL);
+ EXPECT_TRUE(pool_.InternalIsFileLoaded("foo.proto"));
+ EXPECT_FALSE(pool_.InternalIsFileLoaded("bar.proto"));
+
+ // Verify calling FindFieldBy* works when the type of the field was
+ // not built at cross link time. Verify this doesn't build the file
+ // the field's type is defined in, as well.
+ const Descriptor* desc = file->FindMessageTypeByName("Foo");
+ const FieldDescriptor* field = desc->FindFieldByName("bar");
+ EXPECT_TRUE(field != NULL);
+ EXPECT_EQ(field, desc->FindFieldByNumber(1));
+ EXPECT_EQ(field, desc->FindFieldByLowercaseName("bar"));
+ EXPECT_EQ(field, desc->FindFieldByCamelcaseName("bar"));
+ EXPECT_FALSE(pool_.InternalIsFileLoaded("bar.proto"));
+
+ // Finally, verify that if we call message_type() on the field, we will
+ // buid the file where the message is defined, and get a valid descriptor
+ EXPECT_TRUE(field->message_type() != NULL);
+ EXPECT_TRUE(pool_.InternalIsFileLoaded("bar.proto"));
+}
+
+TEST_F(LazilyBuildDependenciesTest, Enum) {
+ ParseProtoAndAddToDb(
+ "name: 'foo.proto' "
+ "package: 'protobuf_unittest' "
+ "dependency: 'enum1.proto' "
+ "dependency: 'enum2.proto' "
+ "message_type { "
+ " name:'Lazy' "
+ " field { name:'enum1' number:1 label:LABEL_OPTIONAL "
+ "type_name:'.protobuf_unittest.Enum1' } "
+ " field { name:'enum2' number:1 label:LABEL_OPTIONAL "
+ "type_name:'.protobuf_unittest.Enum2' } "
+ "}");
+ AddSimpleEnumProtoFileToDb("enum1", "Enum1", "ENUM1");
+ AddSimpleEnumProtoFileToDb("enum2", "Enum2", "ENUM2");
+
+ const FileDescriptor* file = pool_.FindFileByName("foo.proto");
+
+ // Verify calling enum_type() on a field whose definition is not
+ // yet built will build the file and return a descriptor.
+ EXPECT_FALSE(pool_.InternalIsFileLoaded("enum1.proto"));
+ const Descriptor* desc = file->FindMessageTypeByName("Lazy");
+ EXPECT_TRUE(desc != NULL);
+ const FieldDescriptor* field = desc->FindFieldByName("enum1");
+ EXPECT_TRUE(field != NULL);
+ EXPECT_TRUE(field->enum_type() != NULL);
+ EXPECT_TRUE(pool_.InternalIsFileLoaded("enum1.proto"));
+
+ // Verify calling default_value_enum() on a field whose definition is not
+ // yet built will build the file and return a descriptor to the value.
+ EXPECT_FALSE(pool_.InternalIsFileLoaded("enum2.proto"));
+ field = desc->FindFieldByName("enum2");
+ EXPECT_TRUE(field != NULL);
+ EXPECT_TRUE(field->default_value_enum() != NULL);
+ EXPECT_TRUE(pool_.InternalIsFileLoaded("enum2.proto"));
+}
+
+TEST_F(LazilyBuildDependenciesTest, Type) {
+ ParseProtoAndAddToDb(
+ "name: 'foo.proto' "
+ "package: 'protobuf_unittest' "
+ "dependency: 'message1.proto' "
+ "dependency: 'message2.proto' "
+ "dependency: 'enum1.proto' "
+ "dependency: 'enum2.proto' "
+ "message_type { "
+ " name:'Lazy' "
+ " field { name:'message1' number:1 label:LABEL_OPTIONAL "
+ "type_name:'.protobuf_unittest.Message1' } "
+ " field { name:'message2' number:1 label:LABEL_OPTIONAL "
+ "type_name:'.protobuf_unittest.Message2' } "
+ " field { name:'enum1' number:1 label:LABEL_OPTIONAL "
+ "type_name:'.protobuf_unittest.Enum1' } "
+ " field { name:'enum2' number:1 label:LABEL_OPTIONAL "
+ "type_name:'.protobuf_unittest.Enum2' } "
+ "}");
+ AddSimpleMessageProtoFileToDb("message1", "Message1");
+ AddSimpleMessageProtoFileToDb("message2", "Message2");
+ AddSimpleEnumProtoFileToDb("enum1", "Enum1", "ENUM1");
+ AddSimpleEnumProtoFileToDb("enum2", "Enum2", "ENUM2");
+
+ const FileDescriptor* file = pool_.FindFileByName("foo.proto");
+
+ // Verify calling type() on a field that is a message type will
+ // build the type defined in another file.
+ EXPECT_FALSE(pool_.InternalIsFileLoaded("message1.proto"));
+ const Descriptor* desc = file->FindMessageTypeByName("Lazy");
+ EXPECT_TRUE(desc != NULL);
+ const FieldDescriptor* field = desc->FindFieldByName("message1");
+ EXPECT_TRUE(field != NULL);
+ EXPECT_EQ(field->type(), FieldDescriptor::TYPE_MESSAGE);
+ EXPECT_TRUE(pool_.InternalIsFileLoaded("message1.proto"));
+
+ // Verify calling cpp_type() on a field that is a message type will
+ // build the type defined in another file.
+ EXPECT_FALSE(pool_.InternalIsFileLoaded("message2.proto"));
+ field = desc->FindFieldByName("message2");
+ EXPECT_TRUE(field != NULL);
+ EXPECT_EQ(field->cpp_type(), FieldDescriptor::CPPTYPE_MESSAGE);
+ EXPECT_TRUE(pool_.InternalIsFileLoaded("message2.proto"));
+
+ // Verify calling type() on a field that is an enum type will
+ // build the type defined in another file.
+ EXPECT_FALSE(pool_.InternalIsFileLoaded("enum1.proto"));
+ field = desc->FindFieldByName("enum1");
+ EXPECT_TRUE(field != NULL);
+ EXPECT_EQ(field->type(), FieldDescriptor::TYPE_ENUM);
+ EXPECT_TRUE(pool_.InternalIsFileLoaded("enum1.proto"));
+
+ // Verify calling cpp_type() on a field that is an enum type will
+ // build the type defined in another file.
+ EXPECT_FALSE(pool_.InternalIsFileLoaded("enum2.proto"));
+ field = desc->FindFieldByName("enum2");
+ EXPECT_TRUE(field != NULL);
+ EXPECT_EQ(field->cpp_type(), FieldDescriptor::CPPTYPE_ENUM);
+ EXPECT_TRUE(pool_.InternalIsFileLoaded("enum2.proto"));
+}
+
+TEST_F(LazilyBuildDependenciesTest, Extension) {
+ ParseProtoAndAddToDb(
+ "name: 'foo.proto' "
+ "package: 'protobuf_unittest' "
+ "dependency: 'bar.proto' "
+ "dependency: 'baz.proto' "
+ "extension { extendee: '.protobuf_unittest.Bar' name:'bar' number:11"
+ " label:LABEL_OPTIONAL type_name:'.protobuf_unittest.Baz' }");
+ ParseProtoAndAddToDb(
+ "name: 'bar.proto' "
+ "package: 'protobuf_unittest' "
+ "message_type { "
+ " name:'Bar' "
+ " extension_range { start: 10 end: 20 }"
+ "}");
+ AddSimpleMessageProtoFileToDb("baz", "Baz");
+
+ // Verify none have been built yet.
+ EXPECT_FALSE(pool_.InternalIsFileLoaded("foo.proto"));
+ EXPECT_FALSE(pool_.InternalIsFileLoaded("bar.proto"));
+ EXPECT_FALSE(pool_.InternalIsFileLoaded("baz.proto"));
+
+ const FileDescriptor* file = pool_.FindFileByName("foo.proto");
+
+ // Verify foo.bar gets loaded, and bar.proto gets loaded
+ // to register the extension. baz.proto should not get loaded.
+ EXPECT_TRUE(file != NULL);
+ EXPECT_TRUE(pool_.InternalIsFileLoaded("foo.proto"));
+ EXPECT_TRUE(pool_.InternalIsFileLoaded("bar.proto"));
+ EXPECT_FALSE(pool_.InternalIsFileLoaded("baz.proto"));
+}
+
+TEST_F(LazilyBuildDependenciesTest, Service) {
+ ParseProtoAndAddToDb(
+ "name: 'foo.proto' "
+ "package: 'protobuf_unittest' "
+ "dependency: 'message1.proto' "
+ "dependency: 'message2.proto' "
+ "dependency: 'message3.proto' "
+ "dependency: 'message4.proto' "
+ "service {"
+ " name: 'LazyService'"
+ " method { name: 'A' input_type: '.protobuf_unittest.Message1' "
+ " output_type: '.protobuf_unittest.Message2' }"
+ "}");
+ AddSimpleMessageProtoFileToDb("message1", "Message1");
+ AddSimpleMessageProtoFileToDb("message2", "Message2");
+ AddSimpleMessageProtoFileToDb("message3", "Message3");
+ AddSimpleMessageProtoFileToDb("message4", "Message4");
+
+ const FileDescriptor* file = pool_.FindFileByName("foo.proto");
+
+ // Verify calling FindServiceByName or FindMethodByName doesn't build the
+ // files defining the input and output type, and input_type() and
+ // output_type() does indeed build the appropriate files.
+ const ServiceDescriptor* service = file->FindServiceByName("LazyService");
+ EXPECT_TRUE(service != NULL);
+ const MethodDescriptor* method = service->FindMethodByName("A");
+ EXPECT_FALSE(pool_.InternalIsFileLoaded("message1.proto"));
+ EXPECT_FALSE(pool_.InternalIsFileLoaded("message2.proto"));
+ EXPECT_TRUE(method != NULL);
+ EXPECT_TRUE(method->input_type() != NULL);
+ EXPECT_TRUE(pool_.InternalIsFileLoaded("message1.proto"));
+ EXPECT_FALSE(pool_.InternalIsFileLoaded("message2.proto"));
+ EXPECT_TRUE(method->output_type() != NULL);
+ EXPECT_TRUE(pool_.InternalIsFileLoaded("message2.proto"));
+}
+
+
+TEST_F(LazilyBuildDependenciesTest, GeneratedFile) {
+ // Most testing is done with custom pools with lazy dependencies forced on,
+ // do some sanity checking that lazy imports is on by default for the
+ // generated pool, and do custom options testing with generated to
+ // be able to use the GetExtension ids for the custom options.
+
+ // Verify none of the files are loaded yet.
+ EXPECT_FALSE(DescriptorPool::generated_pool()->InternalIsFileLoaded(
+ "google/protobuf/unittest_lazy_dependencies.proto"));
+ EXPECT_FALSE(DescriptorPool::generated_pool()->InternalIsFileLoaded(
+ "google/protobuf/unittest_lazy_dependencies_custom_option.proto"));
+ EXPECT_FALSE(DescriptorPool::generated_pool()->InternalIsFileLoaded(
+ "google/protobuf/unittest_lazy_dependencies_enum.proto"));
+
+ // Verify calling autogenerated function to get a descriptor in the base
+ // file will build that file but none of it's imports. This verifies that
+ // lazily_build_dependencies_ is set on the generated pool, and also that
+ // the generated function "descriptor()" doesn't somehow subvert the laziness
+ // by manually loading the dependencies or something.
+ EXPECT_TRUE(protobuf_unittest::lazy_imports::ImportedMessage::descriptor() !=
+ NULL);
+ EXPECT_TRUE(DescriptorPool::generated_pool()->InternalIsFileLoaded(
+ "google/protobuf/unittest_lazy_dependencies.proto"));
+ EXPECT_FALSE(DescriptorPool::generated_pool()->InternalIsFileLoaded(
+ "google/protobuf/unittest_lazy_dependencies_custom_option.proto"));
+ EXPECT_FALSE(DescriptorPool::generated_pool()->InternalIsFileLoaded(
+ "google/protobuf/unittest_lazy_dependencies_enum.proto"));
+
+ // Verify custom options work when defined in an import that isn't loaded,
+ // and that a non-default value of a custom option doesn't load the file
+ // where that enum is defined.
+ const google::protobuf::MessageOptions& options =
+ protobuf_unittest::lazy_imports::MessageCustomOption::descriptor()
+ ->options();
+ protobuf_unittest::lazy_imports::LazyEnum custom_option_value =
+ options.GetExtension(protobuf_unittest::lazy_imports::lazy_enum_option);
+
+ EXPECT_FALSE(DescriptorPool::generated_pool()->InternalIsFileLoaded(
+ "google/protobuf/unittest_lazy_dependencies_custom_option.proto"));
+ EXPECT_FALSE(DescriptorPool::generated_pool()->InternalIsFileLoaded(
+ "google/protobuf/unittest_lazy_dependencies_enum.proto"));
+ EXPECT_EQ(custom_option_value, protobuf_unittest::lazy_imports::LAZY_ENUM_1);
+
+ const google::protobuf::MessageOptions& options2 =
+ protobuf_unittest::lazy_imports::MessageCustomOption2::descriptor()
+ ->options();
+ custom_option_value =
+ options2.GetExtension(protobuf_unittest::lazy_imports::lazy_enum_option);
+
+ EXPECT_FALSE(DescriptorPool::generated_pool()->InternalIsFileLoaded(
+ "google/protobuf/unittest_lazy_dependencies_custom_option.proto"));
+ EXPECT_FALSE(DescriptorPool::generated_pool()->InternalIsFileLoaded(
+ "google/protobuf/unittest_lazy_dependencies_enum.proto"));
+ EXPECT_EQ(custom_option_value, protobuf_unittest::lazy_imports::LAZY_ENUM_0);
+}
+
+TEST_F(LazilyBuildDependenciesTest, Dependency) {
+ ParseProtoAndAddToDb(
+ "name: 'foo.proto' "
+ "package: 'protobuf_unittest' "
+ "dependency: 'bar.proto' "
+ "message_type { "
+ " name:'Foo' "
+ " field { name:'bar' number:1 label:LABEL_OPTIONAL "
+ "type_name:'.protobuf_unittest.Bar' } "
+ "}");
+ ParseProtoAndAddToDb(
+ "name: 'bar.proto' "
+ "package: 'protobuf_unittest' "
+ "dependency: 'baz.proto' "
+ "message_type { "
+ " name:'Bar' "
+ " field { name:'baz' number:1 label:LABEL_OPTIONAL "
+ "type_name:'.protobuf_unittest.Baz' } "
+ "}");
+ AddSimpleMessageProtoFileToDb("baz", "Baz");
+
+ const FileDescriptor* foo_file = pool_.FindFileByName("foo.proto");
+ EXPECT_TRUE(foo_file != NULL);
+ // As expected, requesting foo.proto shouldn't build it's dependencies
+ EXPECT_TRUE(pool_.InternalIsFileLoaded("foo.proto"));
+ EXPECT_FALSE(pool_.InternalIsFileLoaded("bar.proto"));
+ EXPECT_FALSE(pool_.InternalIsFileLoaded("baz.proto"));
+
+ // Verify calling dependency(N) will build the dependency, but
+ // not that file's dependencies.
+ const FileDescriptor* bar_file = foo_file->dependency(0);
+ EXPECT_TRUE(bar_file != NULL);
+ EXPECT_TRUE(pool_.InternalIsFileLoaded("bar.proto"));
+ EXPECT_FALSE(pool_.InternalIsFileLoaded("baz.proto"));
+}
+
+// ===================================================================
+
} // namespace descriptor_unittest
} // namespace protobuf
diff --git a/src/google/protobuf/drop_unknown_fields_test.cc b/src/google/protobuf/drop_unknown_fields_test.cc
index 6f16dc53..f2f2f749 100644
--- a/src/google/protobuf/drop_unknown_fields_test.cc
+++ b/src/google/protobuf/drop_unknown_fields_test.cc
@@ -35,6 +35,7 @@
#include <google/protobuf/unittest_drop_unknown_fields.pb.h>
#include <google/protobuf/dynamic_message.h>
+#include <google/protobuf/message_lite.h>
#include <gtest/gtest.h>
namespace google {
@@ -43,7 +44,8 @@ using unittest_drop_unknown_fields::FooWithExtraFields;
namespace protobuf {
-TEST(DropUnknownFieldsTest, GeneratedMessage) {
+TEST(DropUnknownFieldsTest, GeneratedMessageDefaultDrop) {
+ ::google::protobuf::internal::SetProto3PreserveUnknownsDefault(false);
FooWithExtraFields foo_with_extra_fields;
foo_with_extra_fields.set_int32_value(1);
foo_with_extra_fields.set_enum_value(FooWithExtraFields::QUX);
@@ -54,8 +56,6 @@ TEST(DropUnknownFieldsTest, GeneratedMessage) {
EXPECT_EQ(1, foo.int32_value());
EXPECT_EQ(static_cast<int>(FooWithExtraFields::QUX),
static_cast<int>(foo.enum_value()));
- // We don't generate unknown field accessors but the UnknownFieldSet is
- // still exposed through reflection API.
EXPECT_TRUE(foo.GetReflection()->GetUnknownFields(foo).empty());
ASSERT_TRUE(foo_with_extra_fields.ParseFromString(foo.SerializeAsString()));
@@ -65,7 +65,29 @@ TEST(DropUnknownFieldsTest, GeneratedMessage) {
EXPECT_EQ(0, foo_with_extra_fields.extra_int32_value());
}
-TEST(DropUnknownFieldsTest, DynamicMessage) {
+TEST(DropUnknownFieldsTest, GeneratedMessageDefaultPreserve) {
+ ::google::protobuf::internal::SetProto3PreserveUnknownsDefault(true);
+ FooWithExtraFields foo_with_extra_fields;
+ foo_with_extra_fields.set_int32_value(1);
+ foo_with_extra_fields.set_enum_value(FooWithExtraFields::QUX);
+ foo_with_extra_fields.set_extra_int32_value(2);
+
+ Foo foo;
+ ASSERT_TRUE(foo.ParseFromString(foo_with_extra_fields.SerializeAsString()));
+ EXPECT_EQ(1, foo.int32_value());
+ EXPECT_EQ(static_cast<int>(FooWithExtraFields::QUX),
+ static_cast<int>(foo.enum_value()));
+ EXPECT_FALSE(foo.GetReflection()->GetUnknownFields(foo).empty());
+
+ ASSERT_TRUE(foo_with_extra_fields.ParseFromString(foo.SerializeAsString()));
+ EXPECT_EQ(1, foo_with_extra_fields.int32_value());
+ EXPECT_EQ(FooWithExtraFields::QUX, foo_with_extra_fields.enum_value());
+ // The "extra_int32_value" field should not be lost.
+ EXPECT_EQ(2, foo_with_extra_fields.extra_int32_value());
+}
+
+TEST(DropUnknownFieldsTest, DynamicMessageDefaultDrop) {
+ internal::SetProto3PreserveUnknownsDefault(false);
FooWithExtraFields foo_with_extra_fields;
foo_with_extra_fields.set_int32_value(1);
foo_with_extra_fields.set_enum_value(FooWithExtraFields::QUX);
@@ -84,5 +106,25 @@ TEST(DropUnknownFieldsTest, DynamicMessage) {
EXPECT_EQ(0, foo_with_extra_fields.extra_int32_value());
}
+TEST(DropUnknownFieldsTest, DynamicMessageDefaultPreserve) {
+ internal::SetProto3PreserveUnknownsDefault(true);
+ FooWithExtraFields foo_with_extra_fields;
+ foo_with_extra_fields.set_int32_value(1);
+ foo_with_extra_fields.set_enum_value(FooWithExtraFields::QUX);
+ foo_with_extra_fields.set_extra_int32_value(2);
+
+ google::protobuf::DynamicMessageFactory factory;
+ google::protobuf::scoped_ptr<google::protobuf::Message> foo(
+ factory.GetPrototype(Foo::descriptor())->New());
+ ASSERT_TRUE(foo->ParseFromString(foo_with_extra_fields.SerializeAsString()));
+ EXPECT_FALSE(foo->GetReflection()->GetUnknownFields(*foo).empty());
+
+ ASSERT_TRUE(foo_with_extra_fields.ParseFromString(foo->SerializeAsString()));
+ EXPECT_EQ(1, foo_with_extra_fields.int32_value());
+ EXPECT_EQ(FooWithExtraFields::QUX, foo_with_extra_fields.enum_value());
+ // The "extra_int32_value" field should not be lost.
+ EXPECT_EQ(2, foo_with_extra_fields.extra_int32_value());
+}
+
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/duration.pb.cc b/src/google/protobuf/duration.pb.cc
index 12135b80..0a8aad48 100644
--- a/src/google/protobuf/duration.pb.cc
+++ b/src/google/protobuf/duration.pb.cc
@@ -1,7 +1,6 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/duration.proto
-#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include <google/protobuf/duration.pb.h>
#include <algorithm>
@@ -15,48 +14,66 @@
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
+// This is a temporary google only hack
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+#include "third_party/protobuf/version.h"
+#endif
// @@protoc_insertion_point(includes)
-
namespace google {
namespace protobuf {
-class DurationDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<Duration> {};
-DurationDefaultTypeInternal _Duration_default_instance_;
-
-namespace {
-
-::google::protobuf::Metadata file_level_metadata[1];
-
-} // namespace
+class DurationDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<Duration>
+ _instance;
+} _Duration_default_instance_;
+} // namespace protobuf
+} // namespace google
+namespace protobuf_google_2fprotobuf_2fduration_2eproto {
+void InitDefaultsDurationImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ {
+ void* ptr = &::google::protobuf::_Duration_default_instance_;
+ new (ptr) ::google::protobuf::Duration();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::Duration::InitAsDefaultInstance();
+}
-const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fduration_2eproto() GOOGLE_ATTRIBUTE_COLD;
-const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fduration_2eproto() {
- static const ::google::protobuf::uint32 offsets[] = {
- ~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Duration, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Duration, seconds_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Duration, nanos_),
- };
- return offsets;
+void InitDefaultsDuration() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsDurationImpl);
}
-static const ::google::protobuf::internal::MigrationSchema schemas[] = {
- { 0, -1, sizeof(Duration)},
-};
+::google::protobuf::Metadata file_level_metadata[1];
-static const ::google::protobuf::internal::DefaultInstanceData file_default_instances[] = {
- {reinterpret_cast<const ::google::protobuf::Message*>(&_Duration_default_instance_), NULL},
+const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+ ~0u, // no _has_bits_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Duration, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Duration, seconds_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Duration, nanos_),
+};
+static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+ { 0, -1, sizeof(::google::protobuf::Duration)},
};
-namespace {
+static ::google::protobuf::Message const * const file_default_instances[] = {
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_Duration_default_instance_),
+};
void protobuf_AssignDescriptors() {
- protobuf_AddDesc_google_2fprotobuf_2fduration_2eproto();
+ AddDescriptors();
::google::protobuf::MessageFactory* factory = NULL;
AssignDescriptors(
- "google/protobuf/duration.proto", schemas, file_default_instances, protobuf_Offsets_google_2fprotobuf_2fduration_2eproto(), factory,
+ "google/protobuf/duration.proto", schemas, file_default_instances, TableStruct::offsets, factory,
file_level_metadata, NULL, NULL);
}
@@ -65,33 +82,15 @@ void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);
}
-void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
+void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 1);
}
-} // namespace
-
-void protobuf_ShutdownFile_google_2fprotobuf_2fduration_2eproto() {
- _Duration_default_instance_.Shutdown();
- delete file_level_metadata[0].reflection;
-}
-
-void protobuf_InitDefaults_google_2fprotobuf_2fduration_2eproto_impl() {
- GOOGLE_PROTOBUF_VERIFY_VERSION;
-
- ::google::protobuf::internal::InitProtobufDefaults();
- _Duration_default_instance_.DefaultConstruct();
-}
-
-void protobuf_InitDefaults_google_2fprotobuf_2fduration_2eproto() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &protobuf_InitDefaults_google_2fprotobuf_2fduration_2eproto_impl);
-}
-void protobuf_AddDesc_google_2fprotobuf_2fduration_2eproto_impl() {
- protobuf_InitDefaults_google_2fprotobuf_2fduration_2eproto();
- static const char descriptor[] = {
+void AddDescriptorsImpl() {
+ InitDefaults();
+ static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n\036google/protobuf/duration.proto\022\017google"
".protobuf\"*\n\010Duration\022\017\n\007seconds\030\001 \001(\003\022\r"
"\n\005nanos\030\002 \001(\005B|\n\023com.google.protobufB\rDu"
@@ -103,23 +102,26 @@ void protobuf_AddDesc_google_2fprotobuf_2fduration_2eproto_impl() {
descriptor, 227);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"google/protobuf/duration.proto", &protobuf_RegisterTypes);
- ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_google_2fprotobuf_2fduration_2eproto);
}
-GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AddDesc_google_2fprotobuf_2fduration_2eproto_once_);
-void protobuf_AddDesc_google_2fprotobuf_2fduration_2eproto() {
- ::google::protobuf::GoogleOnceInit(&protobuf_AddDesc_google_2fprotobuf_2fduration_2eproto_once_,
- &protobuf_AddDesc_google_2fprotobuf_2fduration_2eproto_impl);
+void AddDescriptors() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);
}
-// Force AddDescriptors() to be called at static initialization time.
-struct StaticDescriptorInitializer_google_2fprotobuf_2fduration_2eproto {
- StaticDescriptorInitializer_google_2fprotobuf_2fduration_2eproto() {
- protobuf_AddDesc_google_2fprotobuf_2fduration_2eproto();
+// Force AddDescriptors() to be called at dynamic initialization time.
+struct StaticDescriptorInitializer {
+ StaticDescriptorInitializer() {
+ AddDescriptors();
}
-} static_descriptor_initializer_google_2fprotobuf_2fduration_2eproto_;
+} static_descriptor_initializer;
+} // namespace protobuf_google_2fprotobuf_2fduration_2eproto
+namespace google {
+namespace protobuf {
// ===================================================================
+void Duration::InitAsDefaultInstance() {
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Duration::kSecondsFieldNumber;
const int Duration::kNanosFieldNumber;
@@ -128,7 +130,7 @@ const int Duration::kNanosFieldNumber;
Duration::Duration()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fduration_2eproto();
+ ::protobuf_google_2fprotobuf_2fduration_2eproto::InitDefaultsDuration();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Duration)
@@ -136,9 +138,7 @@ Duration::Duration()
Duration::Duration(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
-#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
- protobuf_InitDefaults_google_2fprotobuf_2fduration_2eproto();
-#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ ::protobuf_google_2fprotobuf_2fduration_2eproto::InitDefaultsDuration();
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Duration)
@@ -149,14 +149,15 @@ Duration::Duration(const Duration& from)
_cached_size_(0) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
::memcpy(&seconds_, &from.seconds_,
- reinterpret_cast<char*>(&nanos_) -
- reinterpret_cast<char*>(&seconds_) + sizeof(nanos_));
+ static_cast<size_t>(reinterpret_cast<char*>(&nanos_) -
+ reinterpret_cast<char*>(&seconds_)) + sizeof(nanos_));
// @@protoc_insertion_point(copy_constructor:google.protobuf.Duration)
}
void Duration::SharedCtor() {
- ::memset(&seconds_, 0, reinterpret_cast<char*>(&nanos_) -
- reinterpret_cast<char*>(&seconds_) + sizeof(nanos_));
+ ::memset(&seconds_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&nanos_) -
+ reinterpret_cast<char*>(&seconds_)) + sizeof(nanos_));
_cached_size_ = 0;
}
@@ -166,11 +167,7 @@ Duration::~Duration() {
}
void Duration::SharedDtor() {
- ::google::protobuf::Arena* arena = GetArenaNoVirtual();
- if (arena != NULL) {
- return;
- }
-
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
}
void Duration::ArenaDtor(void* object) {
@@ -185,12 +182,12 @@ void Duration::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* Duration::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[0].descriptor;
+ ::protobuf_google_2fprotobuf_2fduration_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fduration_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const Duration& Duration::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fduration_2eproto();
+ ::protobuf_google_2fprotobuf_2fduration_2eproto::InitDefaultsDuration();
return *internal_default_instance();
}
@@ -200,8 +197,14 @@ Duration* Duration::New(::google::protobuf::Arena* arena) const {
void Duration::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Duration)
- ::memset(&seconds_, 0, reinterpret_cast<char*>(&nanos_) -
- reinterpret_cast<char*>(&seconds_) + sizeof(nanos_));
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
+ ::memset(&seconds_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&nanos_) -
+ reinterpret_cast<char*>(&seconds_)) + sizeof(nanos_));
+ _internal_metadata_.Clear();
}
bool Duration::MergePartialFromCodedStream(
@@ -216,7 +219,8 @@ bool Duration::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// int64 seconds = 1;
case 1: {
- if (tag == 8u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>(
@@ -229,7 +233,8 @@ bool Duration::MergePartialFromCodedStream(
// int32 nanos = 2;
case 2: {
- if (tag == 16u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
@@ -242,12 +247,11 @@ bool Duration::MergePartialFromCodedStream(
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
- DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
+ DO_(::google::protobuf::internal::WireFormat::SkipField(
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -264,6 +268,9 @@ failure:
void Duration::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.Duration)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// int64 seconds = 1;
if (this->seconds() != 0) {
::google::protobuf::internal::WireFormatLite::WriteInt64(1, this->seconds(), output);
@@ -274,6 +281,10 @@ void Duration::SerializeWithCachedSizes(
::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->nanos(), output);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ }
// @@protoc_insertion_point(serialize_end:google.protobuf.Duration)
}
@@ -281,6 +292,9 @@ void Duration::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Duration)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// int64 seconds = 1;
if (this->seconds() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(1, this->seconds(), target);
@@ -291,6 +305,10 @@ void Duration::SerializeWithCachedSizes(
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->nanos(), target);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ }
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Duration)
return target;
}
@@ -299,6 +317,11 @@ size_t Duration::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.Duration)
size_t total_size = 0;
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ total_size +=
+ ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ }
// int64 seconds = 1;
if (this->seconds() != 0) {
total_size += 1 +
@@ -339,6 +362,9 @@ void Duration::MergeFrom(const Duration& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Duration)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
if (from.seconds() != 0) {
set_seconds(from.seconds());
}
@@ -385,51 +411,20 @@ void Duration::UnsafeArenaSwap(Duration* other) {
InternalSwap(other);
}
void Duration::InternalSwap(Duration* other) {
- std::swap(seconds_, other->seconds_);
- std::swap(nanos_, other->nanos_);
- std::swap(_cached_size_, other->_cached_size_);
+ using std::swap;
+ swap(seconds_, other->seconds_);
+ swap(nanos_, other->nanos_);
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Duration::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[0];
+ protobuf_google_2fprotobuf_2fduration_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fduration_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// Duration
-
-// int64 seconds = 1;
-void Duration::clear_seconds() {
- seconds_ = GOOGLE_LONGLONG(0);
-}
-::google::protobuf::int64 Duration::seconds() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Duration.seconds)
- return seconds_;
-}
-void Duration::set_seconds(::google::protobuf::int64 value) {
-
- seconds_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.Duration.seconds)
-}
-
-// int32 nanos = 2;
-void Duration::clear_nanos() {
- nanos_ = 0;
-}
-::google::protobuf::int32 Duration::nanos() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Duration.nanos)
- return nanos_;
-}
-void Duration::set_nanos(::google::protobuf::int32 value) {
-
- nanos_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.Duration.nanos)
-}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
-
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/duration.pb.h b/src/google/protobuf/duration.pb.h
index f8e67cc5..0489df43 100644
--- a/src/google/protobuf/duration.pb.h
+++ b/src/google/protobuf/duration.pb.h
@@ -8,19 +8,21 @@
#include <google/protobuf/stubs/common.h>
-#if GOOGLE_PROTOBUF_VERSION < 3001000
+#if GOOGLE_PROTOBUF_VERSION < 3004000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3001000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3004000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
+#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
+#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
@@ -28,6 +30,24 @@
#include <google/protobuf/extension_set.h> // IWYU pragma: export
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
+
+namespace protobuf_google_2fprotobuf_2fduration_2eproto {
+// Internal implementation detail -- do not use these members.
+struct LIBPROTOBUF_EXPORT TableStruct {
+ static const ::google::protobuf::internal::ParseTableField entries[];
+ static const ::google::protobuf::internal::AuxillaryParseTableField aux[];
+ static const ::google::protobuf::internal::ParseTable schema[1];
+ static const ::google::protobuf::internal::FieldMetadata field_metadata[];
+ static const ::google::protobuf::internal::SerializationTable serialization_table[];
+ static const ::google::protobuf::uint32 offsets[];
+};
+void LIBPROTOBUF_EXPORT AddDescriptors();
+void LIBPROTOBUF_EXPORT InitDefaultsDurationImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsDuration();
+inline void LIBPROTOBUF_EXPORT InitDefaults() {
+ InitDefaultsDuration();
+}
+} // namespace protobuf_google_2fprotobuf_2fduration_2eproto
namespace google {
namespace protobuf {
class Duration;
@@ -35,14 +55,9 @@ class DurationDefaultTypeInternal;
LIBPROTOBUF_EXPORT extern DurationDefaultTypeInternal _Duration_default_instance_;
} // namespace protobuf
} // namespace google
-
namespace google {
namespace protobuf {
-// Internal implementation detail -- do not call these.
-void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fduration_2eproto();
-void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fduration_2eproto();
-
// ===================================================================
class LIBPROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Duration) */ {
@@ -56,7 +71,21 @@ class LIBPROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@prot
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ Duration(Duration&& from) noexcept
+ : Duration() {
+ *this = ::std::move(from);
+ }
+ inline Duration& operator=(Duration&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
return GetArenaNoVirtual();
}
@@ -66,13 +95,19 @@ class LIBPROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@prot
static const ::google::protobuf::Descriptor* descriptor();
static const Duration& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const Duration* internal_default_instance() {
return reinterpret_cast<const Duration*>(
&_Duration_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 0;
void UnsafeArenaSwap(Duration* other);
void Swap(Duration* other);
+ friend void swap(Duration& a, Duration& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -93,10 +128,6 @@ class LIBPROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@prot
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
@@ -139,24 +170,24 @@ class LIBPROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@prot
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- friend class ::google::protobuf::Arena;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::int64 seconds_;
::google::protobuf::int32 nanos_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fduration_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fduration_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fduration_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fduration_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fduration_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fduration_2eproto::InitDefaultsDurationImpl();
};
// ===================================================================
// ===================================================================
-#if !PROTOBUF_INLINE_NOT_IN_HEADERS
+#ifdef __GNUC__
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wstrict-aliasing"
+#endif // __GNUC__
// Duration
// int64 seconds = 1;
@@ -187,11 +218,12 @@ inline void Duration::set_nanos(::google::protobuf::int32 value) {
// @@protoc_insertion_point(field_set:google.protobuf.Duration.nanos)
}
-#endif // !PROTOBUF_INLINE_NOT_IN_HEADERS
+#ifdef __GNUC__
+ #pragma GCC diagnostic pop
+#endif // __GNUC__
// @@protoc_insertion_point(namespace_scope)
-
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/duration.proto b/src/google/protobuf/duration.proto
index 7f461f40..975fce41 100644
--- a/src/google/protobuf/duration.proto
+++ b/src/google/protobuf/duration.proto
@@ -47,6 +47,8 @@ option objc_class_prefix = "GPB";
// two Timestamp values is a Duration and it can be added or subtracted
// from a Timestamp. Range is approximately +-10,000 years.
//
+// # Examples
+//
// Example 1: Compute Duration from two Timestamps in pseudo code.
//
// Timestamp start = ...;
@@ -87,11 +89,22 @@ option objc_class_prefix = "GPB";
// duration = Duration()
// duration.FromTimedelta(td)
//
+// # JSON Mapping
+//
+// In JSON format, the Duration type is encoded as a string rather than an
+// object, where the string ends in the suffix "s" (indicating seconds) and
+// is preceded by the number of seconds, with nanoseconds expressed as
+// fractional seconds. For example, 3 seconds with 0 nanoseconds should be
+// encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should
+// be expressed in JSON format as "3.000000001s", and 3 seconds and 1
+// microsecond should be expressed in JSON format as "3.000001s".
+//
//
message Duration {
// Signed seconds of the span of time. Must be from -315,576,000,000
- // to +315,576,000,000 inclusive.
+ // to +315,576,000,000 inclusive. Note: these bounds are computed from:
+ // 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years
int64 seconds = 1;
// Signed fractions of a second at nanosecond resolution of the span
diff --git a/src/google/protobuf/dynamic_message.cc b/src/google/protobuf/dynamic_message.cc
index d686e01e..cdd43243 100644
--- a/src/google/protobuf/dynamic_message.cc
+++ b/src/google/protobuf/dynamic_message.cc
@@ -77,13 +77,14 @@
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/arenastring.h>
+#include <google/protobuf/extension_set.h>
+#include <google/protobuf/map_field.h>
#include <google/protobuf/map_field_inl.h>
+#include <google/protobuf/map_type_handler.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/repeated_field.h>
-#include <google/protobuf/map_type_handler.h>
-#include <google/protobuf/extension_set.h>
#include <google/protobuf/wire_format.h>
-#include <google/protobuf/map_field.h>
+
namespace google {
namespace protobuf {
@@ -239,17 +240,20 @@ class DynamicMessage : public Message {
// looking back at this field. This would assume details about the
// implementation of scoped_ptr.
const DynamicMessage* prototype;
- void* default_oneof_instance;
+ int weak_field_map_offset; // The offset for the weak_field_map;
- TypeInfo() : prototype(NULL), default_oneof_instance(NULL) {}
+ TypeInfo() : prototype(NULL) {}
~TypeInfo() {
delete prototype;
- operator delete(default_oneof_instance);
}
};
DynamicMessage(const TypeInfo* type_info);
+
+ // This should only be used by GetPrototypeNoLock() to avoid dead lock.
+ DynamicMessage(const TypeInfo* type_info, bool lock_factory);
+
~DynamicMessage();
// Called on the prototype after construction to initialize message fields.
@@ -280,7 +284,8 @@ class DynamicMessage : public Message {
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DynamicMessage);
DynamicMessage(const TypeInfo* type_info, ::google::protobuf::Arena* arena);
- void SharedCtor();
+
+ void SharedCtor(bool lock_factory);
inline bool is_prototype() const {
return type_info_->prototype == this ||
@@ -304,17 +309,22 @@ class DynamicMessage : public Message {
DynamicMessage::DynamicMessage(const TypeInfo* type_info)
: type_info_(type_info),
cached_byte_size_(0) {
- SharedCtor();
+ SharedCtor(true);
}
DynamicMessage::DynamicMessage(const TypeInfo* type_info,
::google::protobuf::Arena* arena)
: type_info_(type_info),
cached_byte_size_(0) {
- SharedCtor();
+ SharedCtor(true);
+}
+
+DynamicMessage::DynamicMessage(const TypeInfo* type_info, bool lock_factory)
+ : type_info_(type_info), cached_byte_size_(0) {
+ SharedCtor(lock_factory);
}
-void DynamicMessage::SharedCtor() {
+void DynamicMessage::SharedCtor(bool lock_factory) {
// We need to call constructors for various fields manually and set
// default values where appropriate. We use placement new to call
// constructors. If you haven't heard of placement new, I suggest Googling
@@ -325,7 +335,6 @@ void DynamicMessage::SharedCtor() {
// constructor.)
const Descriptor* descriptor = type_info_->type;
-
// Initialize oneof cases.
for (int i = 0 ; i < descriptor->oneof_decl_count(); ++i) {
new (OffsetToPointer(type_info_->oneof_case_offset + sizeof(uint32) * i))
@@ -338,7 +347,6 @@ void DynamicMessage::SharedCtor() {
if (type_info_->extensions_offset != -1) {
new (OffsetToPointer(type_info_->extensions_offset)) ExtensionSet;
}
-
for (int i = 0; i < descriptor->field_count(); i++) {
const FieldDescriptor* field = descriptor->field(i);
void* field_ptr = OffsetToPointer(type_info_->offsets[i]);
@@ -400,8 +408,17 @@ void DynamicMessage::SharedCtor() {
new(field_ptr) Message*(NULL);
} else {
if (IsMapFieldInApi(field)) {
- new (field_ptr) DynamicMapField(
- type_info_->factory->GetPrototypeNoLock(field->message_type()));
+ // We need to lock in most cases to avoid data racing. Only not lock
+ // when the constructor is called inside GetPrototype(), in which
+ // case we have already locked the factory.
+ if (lock_factory) {
+ new (field_ptr) DynamicMapField(
+ type_info_->factory->GetPrototype(field->message_type()));
+ } else {
+ new (field_ptr)
+ DynamicMapField(type_info_->factory->GetPrototypeNoLock(
+ field->message_type()));
+ }
} else {
new (field_ptr) RepeatedPtrField<Message>();
}
@@ -448,8 +465,8 @@ DynamicMessage::~DynamicMessage() {
case FieldOptions::STRING: {
const ::std::string* default_value =
&(reinterpret_cast<const ArenaStringPtr*>(
- reinterpret_cast<uint8*>(
- type_info_->default_oneof_instance) +
+ reinterpret_cast<const uint8*>(
+ type_info_->prototype) +
type_info_->offsets[i])
->Get());
reinterpret_cast<ArenaStringPtr*>(field_ptr)->Destroy(
@@ -539,11 +556,6 @@ void DynamicMessage::CrossLinkPrototypes() {
for (int i = 0; i < descriptor->field_count(); i++) {
const FieldDescriptor* field = descriptor->field(i);
void* field_ptr = OffsetToPointer(type_info_->offsets[i]);
- if (field->containing_oneof()) {
- field_ptr = reinterpret_cast<uint8*>(
- type_info_->default_oneof_instance) + type_info_->offsets[i];
- }
-
if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE &&
!field->is_repeated()) {
// For fields with message types, we need to cross-link with the
@@ -614,7 +626,7 @@ DynamicMessageFactory::~DynamicMessageFactory() {
iter != prototypes_->map_.end(); ++iter) {
DeleteDefaultOneofInstance(iter->second->type,
iter->second->offsets.get(),
- iter->second->default_oneof_instance);
+ iter->second->prototype);
delete iter->second;
}
}
@@ -700,6 +712,7 @@ const Message* DynamicMessageFactory::GetPrototypeNoLock(
// All the fields.
//
// TODO(b/31226269): Optimize the order of fields to minimize padding.
+ int num_weak_fields = 0;
for (int i = 0; i < type->field_count(); i++) {
// Make sure field is aligned to avoid bus errors.
// Oneof fields do not use any space.
@@ -723,48 +736,50 @@ const Message* DynamicMessageFactory::GetPrototypeNoLock(
type_info->internal_metadata_offset = size;
size += sizeof(InternalMetadataWithArena);
+ type_info->weak_field_map_offset = -1;
+
// Align the final size to make sure no clever allocators think that
// alignment is not necessary.
- size = AlignOffset(size);
type_info->size = size;
- // Allocate the prototype.
- void* base = operator new(size);
- memset(base, 0, size);
- // The prototype in type_info has to be set before creating the prototype
- // instance on memory. e.g., message Foo { map<int32, Foo> a = 1; }. When
- // creating prototype for Foo, prototype of the map entry will also be
- // created, which needs the address of the prototype of Foo (the value in
- // map). To break the cyclic dependency, we have to assgin the address of
- // prototype into type_info first.
- type_info->prototype = static_cast<DynamicMessage*>(base);
- DynamicMessage* prototype = new(base) DynamicMessage(type_info);
// Construct the reflection object.
- void* default_oneof_instance = NULL;
- int oneof_case_offset = -1;
-
if (type->oneof_decl_count() > 0) {
// Compute the size of default oneof instance and offsets of default
// oneof fields.
- int oneof_size = 0;
for (int i = 0; i < type->oneof_decl_count(); i++) {
for (int j = 0; j < type->oneof_decl(i)->field_count(); j++) {
const FieldDescriptor* field = type->oneof_decl(i)->field(j);
int field_size = OneofFieldSpaceUsed(field);
- oneof_size = AlignTo(oneof_size, std::min(kSafeAlignment, field_size));
- offsets[field->index()] = oneof_size;
- oneof_size += field_size;
+ size = AlignTo(size, std::min(kSafeAlignment, field_size));
+ offsets[field->index()] = size;
+ size += field_size;
}
}
+ }
+ size = AlignOffset(size);
+ // Allocate the prototype + oneof fields.
+ void* base = operator new(size);
+ memset(base, 0, size);
+
+ // The prototype in type_info has to be set before creating the prototype
+ // instance on memory. e.g., message Foo { map<int32, Foo> a = 1; }. When
+ // creating prototype for Foo, prototype of the map entry will also be
+ // created, which needs the address of the prototype of Foo (the value in
+ // map). To break the cyclic dependency, we have to assgin the address of
+ // prototype into type_info first.
+ type_info->prototype = static_cast<DynamicMessage*>(base);
+
+ // We have already locked the factory so we should not lock in the constructor
+ // of dynamic message to avoid dead lock.
+ DynamicMessage* prototype = new (base) DynamicMessage(type_info, false);
+
+ if (type->oneof_decl_count() > 0 || num_weak_fields > 0) {
// Construct default oneof instance.
- type_info->default_oneof_instance = ::operator new(oneof_size);
ConstructDefaultOneofInstance(type_info->type,
type_info->offsets.get(),
- type_info->default_oneof_instance);
- default_oneof_instance = type_info->default_oneof_instance;
- oneof_case_offset = type_info->oneof_case_offset;
+ prototype);
}
internal::ReflectionSchema schema = {
@@ -774,9 +789,9 @@ const Message* DynamicMessageFactory::GetPrototypeNoLock(
type_info->has_bits_offset,
type_info->internal_metadata_offset,
type_info->extensions_offset,
- default_oneof_instance,
- oneof_case_offset,
- type_info->size};
+ type_info->oneof_case_offset,
+ type_info->size,
+ type_info->weak_field_map_offset};
type_info->reflection.reset(new GeneratedMessageReflection(
type_info->type, schema, type_info->pool, this));
@@ -790,12 +805,12 @@ const Message* DynamicMessageFactory::GetPrototypeNoLock(
void DynamicMessageFactory::ConstructDefaultOneofInstance(
const Descriptor* type,
const uint32 offsets[],
- void* default_oneof_instance) {
+ void* default_oneof_or_weak_instance) {
for (int i = 0; i < type->oneof_decl_count(); i++) {
for (int j = 0; j < type->oneof_decl(i)->field_count(); j++) {
const FieldDescriptor* field = type->oneof_decl(i)->field(j);
void* field_ptr = reinterpret_cast<uint8*>(
- default_oneof_instance) + offsets[field->index()];
+ default_oneof_or_weak_instance) + offsets[field->index()];
switch (field->cpp_type()) {
#define HANDLE_TYPE(CPPTYPE, TYPE) \
case FieldDescriptor::CPPTYPE_##CPPTYPE: \
@@ -836,7 +851,7 @@ void DynamicMessageFactory::ConstructDefaultOneofInstance(
void DynamicMessageFactory::DeleteDefaultOneofInstance(
const Descriptor* type,
const uint32 offsets[],
- void* default_oneof_instance) {
+ const void* default_oneof_instance) {
for (int i = 0; i < type->oneof_decl_count(); i++) {
for (int j = 0; j < type->oneof_decl(i)->field_count(); j++) {
const FieldDescriptor* field = type->oneof_decl(i)->field(j);
diff --git a/src/google/protobuf/dynamic_message.h b/src/google/protobuf/dynamic_message.h
index 7ff80f26..e29b148d 100644
--- a/src/google/protobuf/dynamic_message.h
+++ b/src/google/protobuf/dynamic_message.h
@@ -38,12 +38,15 @@
#ifndef GOOGLE_PROTOBUF_DYNAMIC_MESSAGE_H__
#define GOOGLE_PROTOBUF_DYNAMIC_MESSAGE_H__
+#include <algorithm>
#include <memory>
#ifndef _SHARED_PTR_H
#include <google/protobuf/stubs/shared_ptr.h>
#endif
+#include <vector>
#include <google/protobuf/message.h>
+#include <google/protobuf/repeated_field.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/mutex.h>
@@ -141,11 +144,92 @@ class LIBPROTOBUF_EXPORT DynamicMessageFactory : public MessageFactory {
// Delete default oneof instance. Called by ~DynamicMessageFactory.
static void DeleteDefaultOneofInstance(const Descriptor* type,
const uint32 offsets[],
- void* default_oneof_instance);
+ const void* default_oneof_instance);
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DynamicMessageFactory);
};
+// Helper for computing a sorted list of map entries via reflection.
+class LIBPROTOBUF_EXPORT DynamicMapSorter {
+ public:
+ static std::vector<const Message*> Sort(const Message& message,
+ int map_size,
+ const Reflection* reflection,
+ const FieldDescriptor* field) {
+ std::vector<const Message*> result(static_cast<size_t>(map_size));
+ const RepeatedPtrField<Message>& map_field =
+ reflection->GetRepeatedPtrField<Message>(message, field);
+ size_t i = 0;
+ for (RepeatedPtrField<Message>::const_pointer_iterator it =
+ map_field.pointer_begin(); it != map_field.pointer_end(); ) {
+ result[i++] = *it++;
+ }
+ GOOGLE_DCHECK_EQ(result.size(), i);
+ MapEntryMessageComparator comparator(field->message_type());
+ std::stable_sort(result.begin(), result.end(), comparator);
+ // Complain if the keys aren't in ascending order.
+#ifndef NDEBUG
+ for (size_t j = 1; j < static_cast<size_t>(map_size); j++) {
+ if (!comparator(result[j - 1], result[j])) {
+ GOOGLE_LOG(ERROR) << (comparator(result[j], result[j - 1]) ?
+ "internal error in map key sorting" :
+ "map keys are not unique");
+ }
+ }
+#endif
+ return result;
+ }
+
+ private:
+ class LIBPROTOBUF_EXPORT MapEntryMessageComparator {
+ public:
+ explicit MapEntryMessageComparator(const Descriptor* descriptor)
+ : field_(descriptor->field(0)) {}
+
+ bool operator()(const Message* a, const Message* b) {
+ const Reflection* reflection = a->GetReflection();
+ switch (field_->cpp_type()) {
+ case FieldDescriptor::CPPTYPE_BOOL: {
+ bool first = reflection->GetBool(*a, field_);
+ bool second = reflection->GetBool(*b, field_);
+ return first < second;
+ }
+ case FieldDescriptor::CPPTYPE_INT32: {
+ int32 first = reflection->GetInt32(*a, field_);
+ int32 second = reflection->GetInt32(*b, field_);
+ return first < second;
+ }
+ case FieldDescriptor::CPPTYPE_INT64: {
+ int64 first = reflection->GetInt64(*a, field_);
+ int64 second = reflection->GetInt64(*b, field_);
+ return first < second;
+ }
+ case FieldDescriptor::CPPTYPE_UINT32: {
+ uint32 first = reflection->GetUInt32(*a, field_);
+ uint32 second = reflection->GetUInt32(*b, field_);
+ return first < second;
+ }
+ case FieldDescriptor::CPPTYPE_UINT64: {
+ uint64 first = reflection->GetUInt64(*a, field_);
+ uint64 second = reflection->GetUInt64(*b, field_);
+ return first < second;
+ }
+ case FieldDescriptor::CPPTYPE_STRING: {
+ string first = reflection->GetString(*a, field_);
+ string second = reflection->GetString(*b, field_);
+ return first < second;
+ }
+ default:
+ GOOGLE_LOG(DFATAL) << "Invalid key for map field.";
+ return true;
+ }
+ }
+
+ private:
+ const FieldDescriptor* field_;
+ };
+};
+
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/empty.pb.cc b/src/google/protobuf/empty.pb.cc
index 19f4aefe..caa019e8 100644
--- a/src/google/protobuf/empty.pb.cc
+++ b/src/google/protobuf/empty.pb.cc
@@ -1,7 +1,6 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/empty.proto
-#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include <google/protobuf/empty.pb.h>
#include <algorithm>
@@ -15,46 +14,64 @@
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
+// This is a temporary google only hack
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+#include "third_party/protobuf/version.h"
+#endif
// @@protoc_insertion_point(includes)
-
namespace google {
namespace protobuf {
-class EmptyDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<Empty> {};
-EmptyDefaultTypeInternal _Empty_default_instance_;
-
-namespace {
-
-::google::protobuf::Metadata file_level_metadata[1];
-
-} // namespace
+class EmptyDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<Empty>
+ _instance;
+} _Empty_default_instance_;
+} // namespace protobuf
+} // namespace google
+namespace protobuf_google_2fprotobuf_2fempty_2eproto {
+void InitDefaultsEmptyImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ {
+ void* ptr = &::google::protobuf::_Empty_default_instance_;
+ new (ptr) ::google::protobuf::Empty();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::Empty::InitAsDefaultInstance();
+}
-const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fempty_2eproto() GOOGLE_ATTRIBUTE_COLD;
-const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fempty_2eproto() {
- static const ::google::protobuf::uint32 offsets[] = {
- ~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Empty, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- };
- return offsets;
+void InitDefaultsEmpty() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsEmptyImpl);
}
-static const ::google::protobuf::internal::MigrationSchema schemas[] = {
- { 0, -1, sizeof(Empty)},
-};
+::google::protobuf::Metadata file_level_metadata[1];
-static const ::google::protobuf::internal::DefaultInstanceData file_default_instances[] = {
- {reinterpret_cast<const ::google::protobuf::Message*>(&_Empty_default_instance_), NULL},
+const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+ ~0u, // no _has_bits_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Empty, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+};
+static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+ { 0, -1, sizeof(::google::protobuf::Empty)},
};
-namespace {
+static ::google::protobuf::Message const * const file_default_instances[] = {
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_Empty_default_instance_),
+};
void protobuf_AssignDescriptors() {
- protobuf_AddDesc_google_2fprotobuf_2fempty_2eproto();
+ AddDescriptors();
::google::protobuf::MessageFactory* factory = NULL;
AssignDescriptors(
- "google/protobuf/empty.proto", schemas, file_default_instances, protobuf_Offsets_google_2fprotobuf_2fempty_2eproto(), factory,
+ "google/protobuf/empty.proto", schemas, file_default_instances, TableStruct::offsets, factory,
file_level_metadata, NULL, NULL);
}
@@ -63,33 +80,15 @@ void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);
}
-void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
+void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 1);
}
-} // namespace
-
-void protobuf_ShutdownFile_google_2fprotobuf_2fempty_2eproto() {
- _Empty_default_instance_.Shutdown();
- delete file_level_metadata[0].reflection;
-}
-
-void protobuf_InitDefaults_google_2fprotobuf_2fempty_2eproto_impl() {
- GOOGLE_PROTOBUF_VERIFY_VERSION;
-
- ::google::protobuf::internal::InitProtobufDefaults();
- _Empty_default_instance_.DefaultConstruct();
-}
-
-void protobuf_InitDefaults_google_2fprotobuf_2fempty_2eproto() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &protobuf_InitDefaults_google_2fprotobuf_2fempty_2eproto_impl);
-}
-void protobuf_AddDesc_google_2fprotobuf_2fempty_2eproto_impl() {
- protobuf_InitDefaults_google_2fprotobuf_2fempty_2eproto();
- static const char descriptor[] = {
+void AddDescriptorsImpl() {
+ InitDefaults();
+ static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n\033google/protobuf/empty.proto\022\017google.pr"
"otobuf\"\007\n\005EmptyBv\n\023com.google.protobufB\n"
"EmptyProtoP\001Z\'github.com/golang/protobuf"
@@ -100,30 +99,33 @@ void protobuf_AddDesc_google_2fprotobuf_2fempty_2eproto_impl() {
descriptor, 183);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"google/protobuf/empty.proto", &protobuf_RegisterTypes);
- ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_google_2fprotobuf_2fempty_2eproto);
}
-GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AddDesc_google_2fprotobuf_2fempty_2eproto_once_);
-void protobuf_AddDesc_google_2fprotobuf_2fempty_2eproto() {
- ::google::protobuf::GoogleOnceInit(&protobuf_AddDesc_google_2fprotobuf_2fempty_2eproto_once_,
- &protobuf_AddDesc_google_2fprotobuf_2fempty_2eproto_impl);
+void AddDescriptors() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);
}
-// Force AddDescriptors() to be called at static initialization time.
-struct StaticDescriptorInitializer_google_2fprotobuf_2fempty_2eproto {
- StaticDescriptorInitializer_google_2fprotobuf_2fempty_2eproto() {
- protobuf_AddDesc_google_2fprotobuf_2fempty_2eproto();
+// Force AddDescriptors() to be called at dynamic initialization time.
+struct StaticDescriptorInitializer {
+ StaticDescriptorInitializer() {
+ AddDescriptors();
}
-} static_descriptor_initializer_google_2fprotobuf_2fempty_2eproto_;
+} static_descriptor_initializer;
+} // namespace protobuf_google_2fprotobuf_2fempty_2eproto
+namespace google {
+namespace protobuf {
// ===================================================================
+void Empty::InitAsDefaultInstance() {
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
Empty::Empty()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fempty_2eproto();
+ ::protobuf_google_2fprotobuf_2fempty_2eproto::InitDefaultsEmpty();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Empty)
@@ -131,9 +133,7 @@ Empty::Empty()
Empty::Empty(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
-#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
- protobuf_InitDefaults_google_2fprotobuf_2fempty_2eproto();
-#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ ::protobuf_google_2fprotobuf_2fempty_2eproto::InitDefaultsEmpty();
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Empty)
@@ -156,11 +156,7 @@ Empty::~Empty() {
}
void Empty::SharedDtor() {
- ::google::protobuf::Arena* arena = GetArenaNoVirtual();
- if (arena != NULL) {
- return;
- }
-
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
}
void Empty::ArenaDtor(void* object) {
@@ -175,12 +171,12 @@ void Empty::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* Empty::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[0].descriptor;
+ ::protobuf_google_2fprotobuf_2fempty_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fempty_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const Empty& Empty::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fempty_2eproto();
+ ::protobuf_google_2fprotobuf_2fempty_2eproto::InitDefaultsEmpty();
return *internal_default_instance();
}
@@ -190,6 +186,11 @@ Empty* Empty::New(::google::protobuf::Arena* arena) const {
void Empty::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Empty)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
+ _internal_metadata_.Clear();
}
bool Empty::MergePartialFromCodedStream(
@@ -202,12 +203,11 @@ bool Empty::MergePartialFromCodedStream(
tag = p.first;
if (!p.second) goto handle_unusual;
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
- DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
+ DO_(::google::protobuf::internal::WireFormat::SkipField(
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
}
success:
// @@protoc_insertion_point(parse_success:google.protobuf.Empty)
@@ -221,6 +221,13 @@ failure:
void Empty::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.Empty)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ }
// @@protoc_insertion_point(serialize_end:google.protobuf.Empty)
}
@@ -228,6 +235,13 @@ void Empty::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Empty)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ }
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Empty)
return target;
}
@@ -236,6 +250,11 @@ size_t Empty::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.Empty)
size_t total_size = 0;
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ total_size +=
+ ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ }
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
@@ -262,6 +281,9 @@ void Empty::MergeFrom(const Empty& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Empty)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
}
void Empty::CopyFrom(const ::google::protobuf::Message& from) {
@@ -302,21 +324,18 @@ void Empty::UnsafeArenaSwap(Empty* other) {
InternalSwap(other);
}
void Empty::InternalSwap(Empty* other) {
- std::swap(_cached_size_, other->_cached_size_);
+ using std::swap;
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Empty::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[0];
+ protobuf_google_2fprotobuf_2fempty_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fempty_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// Empty
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
-
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/empty.pb.h b/src/google/protobuf/empty.pb.h
index 4a84bb4f..1d7c5887 100644
--- a/src/google/protobuf/empty.pb.h
+++ b/src/google/protobuf/empty.pb.h
@@ -8,19 +8,21 @@
#include <google/protobuf/stubs/common.h>
-#if GOOGLE_PROTOBUF_VERSION < 3001000
+#if GOOGLE_PROTOBUF_VERSION < 3004000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3001000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3004000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
+#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
+#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
@@ -28,6 +30,24 @@
#include <google/protobuf/extension_set.h> // IWYU pragma: export
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
+
+namespace protobuf_google_2fprotobuf_2fempty_2eproto {
+// Internal implementation detail -- do not use these members.
+struct LIBPROTOBUF_EXPORT TableStruct {
+ static const ::google::protobuf::internal::ParseTableField entries[];
+ static const ::google::protobuf::internal::AuxillaryParseTableField aux[];
+ static const ::google::protobuf::internal::ParseTable schema[1];
+ static const ::google::protobuf::internal::FieldMetadata field_metadata[];
+ static const ::google::protobuf::internal::SerializationTable serialization_table[];
+ static const ::google::protobuf::uint32 offsets[];
+};
+void LIBPROTOBUF_EXPORT AddDescriptors();
+void LIBPROTOBUF_EXPORT InitDefaultsEmptyImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsEmpty();
+inline void LIBPROTOBUF_EXPORT InitDefaults() {
+ InitDefaultsEmpty();
+}
+} // namespace protobuf_google_2fprotobuf_2fempty_2eproto
namespace google {
namespace protobuf {
class Empty;
@@ -35,14 +55,9 @@ class EmptyDefaultTypeInternal;
LIBPROTOBUF_EXPORT extern EmptyDefaultTypeInternal _Empty_default_instance_;
} // namespace protobuf
} // namespace google
-
namespace google {
namespace protobuf {
-// Internal implementation detail -- do not call these.
-void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fempty_2eproto();
-void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fempty_2eproto();
-
// ===================================================================
class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Empty) */ {
@@ -56,7 +71,21 @@ class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ Empty(Empty&& from) noexcept
+ : Empty() {
+ *this = ::std::move(from);
+ }
+ inline Empty& operator=(Empty&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
return GetArenaNoVirtual();
}
@@ -66,13 +95,19 @@ class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_
static const ::google::protobuf::Descriptor* descriptor();
static const Empty& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const Empty* internal_default_instance() {
return reinterpret_cast<const Empty*>(
&_Empty_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 0;
void UnsafeArenaSwap(Empty* other);
void Swap(Empty* other);
+ friend void swap(Empty& a, Empty& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -93,10 +128,6 @@ class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
@@ -127,29 +158,30 @@ class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- friend class ::google::protobuf::Arena;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fempty_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fempty_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fempty_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fempty_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fempty_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fempty_2eproto::InitDefaultsEmptyImpl();
};
// ===================================================================
// ===================================================================
-#if !PROTOBUF_INLINE_NOT_IN_HEADERS
+#ifdef __GNUC__
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wstrict-aliasing"
+#endif // __GNUC__
// Empty
-#endif // !PROTOBUF_INLINE_NOT_IN_HEADERS
+#ifdef __GNUC__
+ #pragma GCC diagnostic pop
+#endif // __GNUC__
// @@protoc_insertion_point(namespace_scope)
-
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/extension_set.cc b/src/google/protobuf/extension_set.cc
index 955c079b..cf6b6fb4 100644
--- a/src/google/protobuf/extension_set.cc
+++ b/src/google/protobuf/extension_set.cc
@@ -221,7 +221,7 @@ int ExtensionSet::NumExtensions() const {
int ExtensionSet::ExtensionSize(int number) const {
ExtensionMap::const_iterator iter = extensions_.find(number);
- if (iter == extensions_.end()) return false;
+ if (iter == extensions_.end()) return 0;
return iter->second.GetSize();
}
diff --git a/src/google/protobuf/extension_set.h b/src/google/protobuf/extension_set.h
index f5aa8de9..0a5d98f2 100644
--- a/src/google/protobuf/extension_set.h
+++ b/src/google/protobuf/extension_set.h
@@ -416,7 +416,8 @@ class LIBPROTOBUF_EXPORT ExtensionSet {
uint8* target) const;
// For backward-compatibility, versions of two of the above methods that
- // are never forced to serialize deterministically.
+ // serialize deterministically iff SetDefaultSerializationDeterministic()
+ // has been called.
uint8* SerializeWithCachedSizesToArray(int start_field_number,
int end_field_number,
uint8* target) const;
@@ -435,6 +436,13 @@ class LIBPROTOBUF_EXPORT ExtensionSet {
// be linked in). It's up to the protocol compiler to avoid calling this on
// such ExtensionSets (easy enough since lite messages don't implement
// SpaceUsed()).
+ size_t SpaceUsedExcludingSelfLong() const;
+
+ // This method just calls SpaceUsedExcludingSelfLong() but it can not be
+ // inlined because the definition of SpaceUsedExcludingSelfLong() is not
+ // included in lite runtime and when an inline method refers to it MSVC
+ // will complain about unresolved symbols when building the lite runtime
+ // as .dll.
int SpaceUsedExcludingSelf() const;
private:
@@ -457,7 +465,7 @@ class LIBPROTOBUF_EXPORT ExtensionSet {
virtual bool IsInitialized() const = 0;
virtual int ByteSize() const = 0;
- virtual int SpaceUsed() const = 0;
+ virtual size_t SpaceUsedLong() const = 0;
virtual void MergeFrom(const LazyMessageExtension& other) = 0;
virtual void Clear() = 0;
@@ -556,7 +564,7 @@ class LIBPROTOBUF_EXPORT ExtensionSet {
void Clear();
int GetSize() const;
void Free();
- int SpaceUsedExcludingSelf() const;
+ size_t SpaceUsedExcludingSelfLong() const;
};
typedef std::map<int, Extension> ExtensionMap;
@@ -620,7 +628,7 @@ class LIBPROTOBUF_EXPORT ExtensionSet {
// class.
// Defined in extension_set_heavy.cc.
- static inline int RepeatedMessage_SpaceUsedExcludingSelf(
+ static inline size_t RepeatedMessage_SpaceUsedExcludingSelfLong(
RepeatedPtrFieldBase* field);
// The Extension struct is small enough to be passed by value, so we use it
@@ -689,6 +697,10 @@ inline void ExtensionSet::AddString(int number, FieldType type,
// ExtensionSet* set);
// static inline void Add(int number, ConstType value, ExtensionSet* set);
// static inline MutableType Add(int number, ExtensionSet* set);
+// This is used by the ExtensionIdentifier constructor to register
+// the extension at dynamic initialization.
+// template <typename ExtendeeT>
+// static void Register(int number, FieldType type, bool is_packed);
// };
//
// Not all of these methods make sense for all field types. For example, the
@@ -720,6 +732,11 @@ class PrimitiveTypeTraits {
ConstType default_value);
static inline void Set(int number, FieldType field_type,
ConstType value, ExtensionSet* set);
+ template <typename ExtendeeT>
+ static void Register(int number, FieldType type, bool is_packed) {
+ ExtensionSet::RegisterExtension(&ExtendeeT::default_instance(), number,
+ type, false, is_packed);
+ }
};
template <typename Type>
@@ -743,6 +760,11 @@ class RepeatedPrimitiveTypeTraits {
bool is_packed, ExtensionSet* set);
static const RepeatedFieldType* GetDefaultRepeatedField();
+ template <typename ExtendeeT>
+ static void Register(int number, FieldType type, bool is_packed) {
+ ExtensionSet::RegisterExtension(&ExtendeeT::default_instance(), number,
+ type, true, is_packed);
+ }
};
LIBPROTOBUF_EXPORT extern ProtobufOnceType repeated_primitive_generic_type_traits_once_init_;
@@ -840,6 +862,11 @@ class LIBPROTOBUF_EXPORT StringTypeTraits {
ExtensionSet* set) {
return set->MutableString(number, field_type, NULL);
}
+ template <typename ExtendeeT>
+ static void Register(int number, FieldType type, bool is_packed) {
+ ExtensionSet::RegisterExtension(&ExtendeeT::default_instance(), number,
+ type, false, is_packed);
+ }
};
LIBPROTOBUF_EXPORT extern ProtobufOnceType repeated_string_type_traits_once_init_;
@@ -892,6 +919,12 @@ class LIBPROTOBUF_EXPORT RepeatedStringTypeTraits {
return default_repeated_field_;
}
+ template <typename ExtendeeT>
+ static void Register(int number, FieldType type, bool is_packed) {
+ ExtensionSet::RegisterExtension(&ExtendeeT::default_instance(), number,
+ type, true, is_packed);
+ }
+
private:
static void InitializeDefaultRepeatedFields();
static void DestroyDefaultRepeatedFields();
@@ -919,6 +952,11 @@ class EnumTypeTraits {
GOOGLE_DCHECK(IsValid(value));
set->SetEnum(number, field_type, value, NULL);
}
+ template <typename ExtendeeT>
+ static void Register(int number, FieldType type, bool is_packed) {
+ ExtensionSet::RegisterEnumExtension(&ExtendeeT::default_instance(), number,
+ type, false, is_packed, IsValid);
+ }
};
template <typename Type, bool IsValid(int)>
@@ -972,6 +1010,11 @@ class RepeatedEnumTypeTraits {
return reinterpret_cast<const RepeatedField<Type>*>(
RepeatedPrimitiveTypeTraits<int32>::GetDefaultRepeatedField());
}
+ template <typename ExtendeeT>
+ static void Register(int number, FieldType type, bool is_packed) {
+ ExtensionSet::RegisterEnumExtension(&ExtendeeT::default_instance(), number,
+ type, true, is_packed, IsValid);
+ }
};
// -------------------------------------------------------------------
@@ -1017,6 +1060,12 @@ class MessageTypeTraits {
return static_cast<Type*>(set->UnsafeArenaReleaseMessage(
number, Type::default_instance()));
}
+ template <typename ExtendeeT>
+ static void Register(int number, FieldType type, bool is_packed) {
+ ExtensionSet::RegisterMessageExtension(&ExtendeeT::default_instance(),
+ number, type, false, is_packed,
+ &Type::default_instance());
+ }
};
// forward declaration
@@ -1062,6 +1111,12 @@ class RepeatedMessageTypeTraits {
}
static const RepeatedFieldType* GetDefaultRepeatedField();
+ template <typename ExtendeeT>
+ static void Register(int number, FieldType type, bool is_packed) {
+ ExtensionSet::RegisterMessageExtension(&ExtendeeT::default_instance(),
+ number, type, true, is_packed,
+ &Type::default_instance());
+ }
};
LIBPROTOBUF_EXPORT extern ProtobufOnceType repeated_message_generic_type_traits_once_init_;
@@ -1100,7 +1155,7 @@ template<typename Type> inline
// parameter, and thus make an instance of ExtensionIdentifier have no
// actual contents. However, if we did that, then using at extension
// identifier would not necessarily cause the compiler to output any sort
-// of reference to any simple defined in the extension's .pb.o file. Some
+// of reference to any symbol defined in the extension's .pb.o file. Some
// linkers will actually drop object files that are not explicitly referenced,
// but that would be bad because it would cause this extension to not be
// registered at static initialization, and therefore using it would crash.
@@ -1113,12 +1168,18 @@ class ExtensionIdentifier {
typedef ExtendeeType Extendee;
ExtensionIdentifier(int number, typename TypeTraits::ConstType default_value)
- : number_(number), default_value_(default_value) {}
+ : number_(number), default_value_(default_value) {
+ Register(number);
+ }
inline int number() const { return number_; }
typename TypeTraits::ConstType default_value() const {
return default_value_;
}
+ static void Register(int number) {
+ TypeTraits::template Register<ExtendeeType>(number, field_type, is_packed);
+ }
+
private:
const int number_;
typename TypeTraits::ConstType default_value_;
diff --git a/src/google/protobuf/extension_set_heavy.cc b/src/google/protobuf/extension_set_heavy.cc
index 2c37ade9..fad31340 100644
--- a/src/google/protobuf/extension_set_heavy.cc
+++ b/src/google/protobuf/extension_set_heavy.cc
@@ -35,11 +35,14 @@
// Contains methods defined in extension_set.h which cannot be part of the
// lite library because they use descriptors or reflection.
+#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
+#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h>
+#include <google/protobuf/unknown_field_set.h>
#include <google/protobuf/wire_format.h>
#include <google/protobuf/wire_format_lite_inl.h>
@@ -340,31 +343,35 @@ bool ExtensionSet::ParseMessageSet(io::CodedInputStream* input,
}
int ExtensionSet::SpaceUsedExcludingSelf() const {
- int total_size =
+ return internal::FromIntSize(SpaceUsedExcludingSelfLong());
+}
+
+size_t ExtensionSet::SpaceUsedExcludingSelfLong() const {
+ size_t total_size =
extensions_.size() * sizeof(ExtensionMap::value_type);
for (ExtensionMap::const_iterator iter = extensions_.begin(),
end = extensions_.end();
iter != end;
++iter) {
- total_size += iter->second.SpaceUsedExcludingSelf();
+ total_size += iter->second.SpaceUsedExcludingSelfLong();
}
return total_size;
}
-inline int ExtensionSet::RepeatedMessage_SpaceUsedExcludingSelf(
+inline size_t ExtensionSet::RepeatedMessage_SpaceUsedExcludingSelfLong(
RepeatedPtrFieldBase* field) {
- return field->SpaceUsedExcludingSelf<GenericTypeHandler<Message> >();
+ return field->SpaceUsedExcludingSelfLong<GenericTypeHandler<Message> >();
}
-int ExtensionSet::Extension::SpaceUsedExcludingSelf() const {
- int total_size = 0;
+size_t ExtensionSet::Extension::SpaceUsedExcludingSelfLong() const {
+ size_t total_size = 0;
if (is_repeated) {
switch (cpp_type(type)) {
-#define HANDLE_TYPE(UPPERCASE, LOWERCASE) \
- case FieldDescriptor::CPPTYPE_##UPPERCASE: \
- total_size += sizeof(*repeated_##LOWERCASE##_value) + \
- repeated_##LOWERCASE##_value->SpaceUsedExcludingSelf();\
- break
+#define HANDLE_TYPE(UPPERCASE, LOWERCASE) \
+ case FieldDescriptor::CPPTYPE_##UPPERCASE: \
+ total_size += sizeof(*repeated_##LOWERCASE##_value) + \
+ repeated_##LOWERCASE##_value->SpaceUsedExcludingSelfLong(); \
+ break
HANDLE_TYPE( INT32, int32);
HANDLE_TYPE( INT64, int64);
@@ -379,24 +386,25 @@ int ExtensionSet::Extension::SpaceUsedExcludingSelf() const {
case FieldDescriptor::CPPTYPE_MESSAGE:
// repeated_message_value is actually a RepeatedPtrField<MessageLite>,
- // but MessageLite has no SpaceUsed(), so we must directly call
- // RepeatedPtrFieldBase::SpaceUsedExcludingSelf() with a different type
- // handler.
- total_size += sizeof(*repeated_message_value) +
- RepeatedMessage_SpaceUsedExcludingSelf(repeated_message_value);
+ // but MessageLite has no SpaceUsedLong(), so we must directly call
+ // RepeatedPtrFieldBase::SpaceUsedExcludingSelfLong() with a different
+ // type handler.
+ total_size +=
+ sizeof(*repeated_message_value) +
+ RepeatedMessage_SpaceUsedExcludingSelfLong(repeated_message_value);
break;
}
} else {
switch (cpp_type(type)) {
case FieldDescriptor::CPPTYPE_STRING:
total_size += sizeof(*string_value) +
- StringSpaceUsedExcludingSelf(*string_value);
+ StringSpaceUsedExcludingSelfLong(*string_value);
break;
case FieldDescriptor::CPPTYPE_MESSAGE:
if (is_lazy) {
- total_size += lazymessage_value->SpaceUsed();
+ total_size += lazymessage_value->SpaceUsedLong();
} else {
- total_size += down_cast<Message*>(message_value)->SpaceUsed();
+ total_size += down_cast<Message*>(message_value)->SpaceUsedLong();
}
break;
default:
@@ -413,12 +421,16 @@ uint8* ExtensionSet::SerializeWithCachedSizesToArray(int start_field_number,
int end_field_number,
uint8* target) const {
return InternalSerializeWithCachedSizesToArray(
- start_field_number, end_field_number, false, target);
+ start_field_number, end_field_number,
+ google::protobuf::io::CodedOutputStream::IsDefaultSerializationDeterministic(),
+ target);
}
uint8* ExtensionSet::SerializeMessageSetWithCachedSizesToArray(
uint8* target) const {
- return InternalSerializeMessageSetWithCachedSizesToArray(false, target);
+ return InternalSerializeMessageSetWithCachedSizesToArray(
+ google::protobuf::io::CodedOutputStream::IsDefaultSerializationDeterministic(),
+ target);
}
uint8* ExtensionSet::InternalSerializeWithCachedSizesToArray(
@@ -479,10 +491,10 @@ uint8* ExtensionSet::Extension::InternalSerializeFieldWithCachedSizesToArray(
HANDLE_TYPE( ENUM, Enum, enum);
#undef HANDLE_TYPE
- case WireFormatLite::TYPE_STRING:
- case WireFormatLite::TYPE_BYTES:
- case WireFormatLite::TYPE_GROUP:
- case WireFormatLite::TYPE_MESSAGE:
+ case FieldDescriptor::TYPE_STRING:
+ case FieldDescriptor::TYPE_BYTES:
+ case FieldDescriptor::TYPE_GROUP:
+ case FieldDescriptor::TYPE_MESSAGE:
GOOGLE_LOG(FATAL) << "Non-primitive types can't be packed.";
break;
}
@@ -587,11 +599,12 @@ ExtensionSet::Extension::InternalSerializeMessageSetItemWithCachedSizesToArray(
WireFormatLite::kMessageSetTypeIdNumber, number, target);
// Write message.
if (is_lazy) {
- target = lazymessage_value->WriteMessageToArray(
- WireFormatLite::kMessageSetMessageNumber, target);
+ target = lazymessage_value->InternalWriteMessageToArray(
+ WireFormatLite::kMessageSetMessageNumber, deterministic, target);
} else {
- target = WireFormatLite::WriteMessageToArray(
- WireFormatLite::kMessageSetMessageNumber, *message_value, target);
+ target = WireFormatLite::InternalWriteMessageToArray(
+ WireFormatLite::kMessageSetMessageNumber, *message_value, deterministic,
+ target);
}
// End group.
target = io::CodedOutputStream::WriteTagToArray(
diff --git a/src/google/protobuf/extension_set_unittest.cc b/src/google/protobuf/extension_set_unittest.cc
index d6b823c0..3e71b253 100644
--- a/src/google/protobuf/extension_set_unittest.cc
+++ b/src/google/protobuf/extension_set_unittest.cc
@@ -32,6 +32,8 @@
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
+
+#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/unittest.pb.h>
#include <google/protobuf/unittest_mset.pb.h>
@@ -46,7 +48,6 @@
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
#include <google/protobuf/stubs/stl_util.h>
diff --git a/src/google/protobuf/field_mask.pb.cc b/src/google/protobuf/field_mask.pb.cc
index b7925b88..c55a697a 100644
--- a/src/google/protobuf/field_mask.pb.cc
+++ b/src/google/protobuf/field_mask.pb.cc
@@ -1,7 +1,6 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/field_mask.proto
-#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include <google/protobuf/field_mask.pb.h>
#include <algorithm>
@@ -15,47 +14,65 @@
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
+// This is a temporary google only hack
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+#include "third_party/protobuf/version.h"
+#endif
// @@protoc_insertion_point(includes)
-
namespace google {
namespace protobuf {
-class FieldMaskDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<FieldMask> {};
-FieldMaskDefaultTypeInternal _FieldMask_default_instance_;
-
-namespace {
-
-::google::protobuf::Metadata file_level_metadata[1];
-
-} // namespace
+class FieldMaskDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<FieldMask>
+ _instance;
+} _FieldMask_default_instance_;
+} // namespace protobuf
+} // namespace google
+namespace protobuf_google_2fprotobuf_2ffield_5fmask_2eproto {
+void InitDefaultsFieldMaskImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ {
+ void* ptr = &::google::protobuf::_FieldMask_default_instance_;
+ new (ptr) ::google::protobuf::FieldMask();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::FieldMask::InitAsDefaultInstance();
+}
-const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2ffield_5fmask_2eproto() GOOGLE_ATTRIBUTE_COLD;
-const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2ffield_5fmask_2eproto() {
- static const ::google::protobuf::uint32 offsets[] = {
- ~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldMask, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldMask, paths_),
- };
- return offsets;
+void InitDefaultsFieldMask() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsFieldMaskImpl);
}
-static const ::google::protobuf::internal::MigrationSchema schemas[] = {
- { 0, -1, sizeof(FieldMask)},
-};
+::google::protobuf::Metadata file_level_metadata[1];
-static const ::google::protobuf::internal::DefaultInstanceData file_default_instances[] = {
- {reinterpret_cast<const ::google::protobuf::Message*>(&_FieldMask_default_instance_), NULL},
+const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+ ~0u, // no _has_bits_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldMask, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldMask, paths_),
+};
+static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+ { 0, -1, sizeof(::google::protobuf::FieldMask)},
};
-namespace {
+static ::google::protobuf::Message const * const file_default_instances[] = {
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_FieldMask_default_instance_),
+};
void protobuf_AssignDescriptors() {
- protobuf_AddDesc_google_2fprotobuf_2ffield_5fmask_2eproto();
+ AddDescriptors();
::google::protobuf::MessageFactory* factory = NULL;
AssignDescriptors(
- "google/protobuf/field_mask.proto", schemas, file_default_instances, protobuf_Offsets_google_2fprotobuf_2ffield_5fmask_2eproto(), factory,
+ "google/protobuf/field_mask.proto", schemas, file_default_instances, TableStruct::offsets, factory,
file_level_metadata, NULL, NULL);
}
@@ -64,33 +81,15 @@ void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);
}
-void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
+void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 1);
}
-} // namespace
-
-void protobuf_ShutdownFile_google_2fprotobuf_2ffield_5fmask_2eproto() {
- _FieldMask_default_instance_.Shutdown();
- delete file_level_metadata[0].reflection;
-}
-
-void protobuf_InitDefaults_google_2fprotobuf_2ffield_5fmask_2eproto_impl() {
- GOOGLE_PROTOBUF_VERIFY_VERSION;
-
- ::google::protobuf::internal::InitProtobufDefaults();
- _FieldMask_default_instance_.DefaultConstruct();
-}
-
-void protobuf_InitDefaults_google_2fprotobuf_2ffield_5fmask_2eproto() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &protobuf_InitDefaults_google_2fprotobuf_2ffield_5fmask_2eproto_impl);
-}
-void protobuf_AddDesc_google_2fprotobuf_2ffield_5fmask_2eproto_impl() {
- protobuf_InitDefaults_google_2fprotobuf_2ffield_5fmask_2eproto();
- static const char descriptor[] = {
+void AddDescriptorsImpl() {
+ InitDefaults();
+ static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n google/protobuf/field_mask.proto\022\017goog"
"le.protobuf\"\032\n\tFieldMask\022\r\n\005paths\030\001 \003(\tB"
"\211\001\n\023com.google.protobufB\016FieldMaskProtoP"
@@ -102,23 +101,26 @@ void protobuf_AddDesc_google_2fprotobuf_2ffield_5fmask_2eproto_impl() {
descriptor, 227);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"google/protobuf/field_mask.proto", &protobuf_RegisterTypes);
- ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_google_2fprotobuf_2ffield_5fmask_2eproto);
}
-GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AddDesc_google_2fprotobuf_2ffield_5fmask_2eproto_once_);
-void protobuf_AddDesc_google_2fprotobuf_2ffield_5fmask_2eproto() {
- ::google::protobuf::GoogleOnceInit(&protobuf_AddDesc_google_2fprotobuf_2ffield_5fmask_2eproto_once_,
- &protobuf_AddDesc_google_2fprotobuf_2ffield_5fmask_2eproto_impl);
+void AddDescriptors() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);
}
-// Force AddDescriptors() to be called at static initialization time.
-struct StaticDescriptorInitializer_google_2fprotobuf_2ffield_5fmask_2eproto {
- StaticDescriptorInitializer_google_2fprotobuf_2ffield_5fmask_2eproto() {
- protobuf_AddDesc_google_2fprotobuf_2ffield_5fmask_2eproto();
+// Force AddDescriptors() to be called at dynamic initialization time.
+struct StaticDescriptorInitializer {
+ StaticDescriptorInitializer() {
+ AddDescriptors();
}
-} static_descriptor_initializer_google_2fprotobuf_2ffield_5fmask_2eproto_;
+} static_descriptor_initializer;
+} // namespace protobuf_google_2fprotobuf_2ffield_5fmask_2eproto
+namespace google {
+namespace protobuf {
// ===================================================================
+void FieldMask::InitAsDefaultInstance() {
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int FieldMask::kPathsFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
@@ -126,7 +128,7 @@ const int FieldMask::kPathsFieldNumber;
FieldMask::FieldMask()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2ffield_5fmask_2eproto();
+ ::protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::InitDefaultsFieldMask();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.FieldMask)
@@ -158,12 +160,12 @@ void FieldMask::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* FieldMask::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[0].descriptor;
+ ::protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const FieldMask& FieldMask::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2ffield_5fmask_2eproto();
+ ::protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::InitDefaultsFieldMask();
return *internal_default_instance();
}
@@ -177,7 +179,12 @@ FieldMask* FieldMask::New(::google::protobuf::Arena* arena) const {
void FieldMask::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.FieldMask)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
paths_.Clear();
+ _internal_metadata_.Clear();
}
bool FieldMask::MergePartialFromCodedStream(
@@ -192,12 +199,13 @@ bool FieldMask::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated string paths = 1;
case 1: {
- if (tag == 10u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->add_paths()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->paths(this->paths_size() - 1).data(),
- this->paths(this->paths_size() - 1).length(),
+ static_cast<int>(this->paths(this->paths_size() - 1).length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.protobuf.FieldMask.paths"));
} else {
@@ -208,12 +216,11 @@ bool FieldMask::MergePartialFromCodedStream(
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
- DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
+ DO_(::google::protobuf::internal::WireFormat::SkipField(
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -230,16 +237,23 @@ failure:
void FieldMask::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.FieldMask)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// repeated string paths = 1;
- for (int i = 0; i < this->paths_size(); i++) {
+ for (int i = 0, n = this->paths_size(); i < n; i++) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->paths(i).data(), this->paths(i).length(),
+ this->paths(i).data(), static_cast<int>(this->paths(i).length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.FieldMask.paths");
::google::protobuf::internal::WireFormatLite::WriteString(
1, this->paths(i), output);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ }
// @@protoc_insertion_point(serialize_end:google.protobuf.FieldMask)
}
@@ -247,16 +261,23 @@ void FieldMask::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.FieldMask)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// repeated string paths = 1;
- for (int i = 0; i < this->paths_size(); i++) {
+ for (int i = 0, n = this->paths_size(); i < n; i++) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->paths(i).data(), this->paths(i).length(),
+ this->paths(i).data(), static_cast<int>(this->paths(i).length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.FieldMask.paths");
target = ::google::protobuf::internal::WireFormatLite::
WriteStringToArray(1, this->paths(i), target);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ }
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.FieldMask)
return target;
}
@@ -265,10 +286,15 @@ size_t FieldMask::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.FieldMask)
size_t total_size = 0;
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ total_size +=
+ ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ }
// repeated string paths = 1;
total_size += 1 *
::google::protobuf::internal::FromIntSize(this->paths_size());
- for (int i = 0; i < this->paths_size(); i++) {
+ for (int i = 0, n = this->paths_size(); i < n; i++) {
total_size += ::google::protobuf::internal::WireFormatLite::StringSize(
this->paths(i));
}
@@ -299,6 +325,9 @@ void FieldMask::MergeFrom(const FieldMask& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.FieldMask)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
paths_.MergeFrom(from.paths_);
}
@@ -325,77 +354,19 @@ void FieldMask::Swap(FieldMask* other) {
InternalSwap(other);
}
void FieldMask::InternalSwap(FieldMask* other) {
- paths_.UnsafeArenaSwap(&other->paths_);
- std::swap(_cached_size_, other->_cached_size_);
+ using std::swap;
+ paths_.InternalSwap(&other->paths_);
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata FieldMask::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[0];
-}
-
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// FieldMask
-
-// repeated string paths = 1;
-int FieldMask::paths_size() const {
- return paths_.size();
-}
-void FieldMask::clear_paths() {
- paths_.Clear();
-}
-const ::std::string& FieldMask::paths(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.FieldMask.paths)
- return paths_.Get(index);
-}
-::std::string* FieldMask::mutable_paths(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.FieldMask.paths)
- return paths_.Mutable(index);
-}
-void FieldMask::set_paths(int index, const ::std::string& value) {
- // @@protoc_insertion_point(field_set:google.protobuf.FieldMask.paths)
- paths_.Mutable(index)->assign(value);
-}
-void FieldMask::set_paths(int index, const char* value) {
- paths_.Mutable(index)->assign(value);
- // @@protoc_insertion_point(field_set_char:google.protobuf.FieldMask.paths)
-}
-void FieldMask::set_paths(int index, const char* value, size_t size) {
- paths_.Mutable(index)->assign(
- reinterpret_cast<const char*>(value), size);
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.FieldMask.paths)
-}
-::std::string* FieldMask::add_paths() {
- // @@protoc_insertion_point(field_add_mutable:google.protobuf.FieldMask.paths)
- return paths_.Add();
-}
-void FieldMask::add_paths(const ::std::string& value) {
- paths_.Add()->assign(value);
- // @@protoc_insertion_point(field_add:google.protobuf.FieldMask.paths)
-}
-void FieldMask::add_paths(const char* value) {
- paths_.Add()->assign(value);
- // @@protoc_insertion_point(field_add_char:google.protobuf.FieldMask.paths)
-}
-void FieldMask::add_paths(const char* value, size_t size) {
- paths_.Add()->assign(reinterpret_cast<const char*>(value), size);
- // @@protoc_insertion_point(field_add_pointer:google.protobuf.FieldMask.paths)
-}
-const ::google::protobuf::RepeatedPtrField< ::std::string>&
-FieldMask::paths() const {
- // @@protoc_insertion_point(field_list:google.protobuf.FieldMask.paths)
- return paths_;
-}
-::google::protobuf::RepeatedPtrField< ::std::string>*
-FieldMask::mutable_paths() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.FieldMask.paths)
- return &paths_;
+ protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
-
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/field_mask.pb.h b/src/google/protobuf/field_mask.pb.h
index d7600c1b..3275dc54 100644
--- a/src/google/protobuf/field_mask.pb.h
+++ b/src/google/protobuf/field_mask.pb.h
@@ -8,19 +8,21 @@
#include <google/protobuf/stubs/common.h>
-#if GOOGLE_PROTOBUF_VERSION < 3001000
+#if GOOGLE_PROTOBUF_VERSION < 3004000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3001000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3004000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
+#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
+#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
@@ -28,6 +30,24 @@
#include <google/protobuf/extension_set.h> // IWYU pragma: export
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
+
+namespace protobuf_google_2fprotobuf_2ffield_5fmask_2eproto {
+// Internal implementation detail -- do not use these members.
+struct LIBPROTOBUF_EXPORT TableStruct {
+ static const ::google::protobuf::internal::ParseTableField entries[];
+ static const ::google::protobuf::internal::AuxillaryParseTableField aux[];
+ static const ::google::protobuf::internal::ParseTable schema[1];
+ static const ::google::protobuf::internal::FieldMetadata field_metadata[];
+ static const ::google::protobuf::internal::SerializationTable serialization_table[];
+ static const ::google::protobuf::uint32 offsets[];
+};
+void LIBPROTOBUF_EXPORT AddDescriptors();
+void LIBPROTOBUF_EXPORT InitDefaultsFieldMaskImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsFieldMask();
+inline void LIBPROTOBUF_EXPORT InitDefaults() {
+ InitDefaultsFieldMask();
+}
+} // namespace protobuf_google_2fprotobuf_2ffield_5fmask_2eproto
namespace google {
namespace protobuf {
class FieldMask;
@@ -35,14 +55,9 @@ class FieldMaskDefaultTypeInternal;
LIBPROTOBUF_EXPORT extern FieldMaskDefaultTypeInternal _FieldMask_default_instance_;
} // namespace protobuf
} // namespace google
-
namespace google {
namespace protobuf {
-// Internal implementation detail -- do not call these.
-void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2ffield_5fmask_2eproto();
-void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2ffield_5fmask_2eproto();
-
// ===================================================================
class LIBPROTOBUF_EXPORT FieldMask : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FieldMask) */ {
@@ -56,16 +71,36 @@ class LIBPROTOBUF_EXPORT FieldMask : public ::google::protobuf::Message /* @@pro
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ FieldMask(FieldMask&& from) noexcept
+ : FieldMask() {
+ *this = ::std::move(from);
+ }
+ inline FieldMask& operator=(FieldMask&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
static const ::google::protobuf::Descriptor* descriptor();
static const FieldMask& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const FieldMask* internal_default_instance() {
return reinterpret_cast<const FieldMask*>(
&_FieldMask_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 0;
void Swap(FieldMask* other);
+ friend void swap(FieldMask& a, FieldMask& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -86,10 +121,6 @@ class LIBPROTOBUF_EXPORT FieldMask : public ::google::protobuf::Message /* @@pro
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
@@ -118,10 +149,16 @@ class LIBPROTOBUF_EXPORT FieldMask : public ::google::protobuf::Message /* @@pro
const ::std::string& paths(int index) const;
::std::string* mutable_paths(int index);
void set_paths(int index, const ::std::string& value);
+ #if LANG_CXX11
+ void set_paths(int index, ::std::string&& value);
+ #endif
void set_paths(int index, const char* value);
void set_paths(int index, const char* value, size_t size);
::std::string* add_paths();
void add_paths(const ::std::string& value);
+ #if LANG_CXX11
+ void add_paths(::std::string&& value);
+ #endif
void add_paths(const char* value);
void add_paths(const char* value, size_t size);
const ::google::protobuf::RepeatedPtrField< ::std::string>& paths() const;
@@ -133,18 +170,18 @@ class LIBPROTOBUF_EXPORT FieldMask : public ::google::protobuf::Message /* @@pro
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
::google::protobuf::RepeatedPtrField< ::std::string> paths_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2ffield_5fmask_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2ffield_5fmask_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2ffield_5fmask_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2ffield_5fmask_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::InitDefaultsFieldMaskImpl();
};
// ===================================================================
// ===================================================================
-#if !PROTOBUF_INLINE_NOT_IN_HEADERS
+#ifdef __GNUC__
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wstrict-aliasing"
+#endif // __GNUC__
// FieldMask
// repeated string paths = 1;
@@ -166,7 +203,14 @@ inline void FieldMask::set_paths(int index, const ::std::string& value) {
// @@protoc_insertion_point(field_set:google.protobuf.FieldMask.paths)
paths_.Mutable(index)->assign(value);
}
+#if LANG_CXX11
+inline void FieldMask::set_paths(int index, ::std::string&& value) {
+ // @@protoc_insertion_point(field_set:google.protobuf.FieldMask.paths)
+ paths_.Mutable(index)->assign(std::move(value));
+}
+#endif
inline void FieldMask::set_paths(int index, const char* value) {
+ GOOGLE_DCHECK(value != NULL);
paths_.Mutable(index)->assign(value);
// @@protoc_insertion_point(field_set_char:google.protobuf.FieldMask.paths)
}
@@ -183,7 +227,14 @@ inline void FieldMask::add_paths(const ::std::string& value) {
paths_.Add()->assign(value);
// @@protoc_insertion_point(field_add:google.protobuf.FieldMask.paths)
}
+#if LANG_CXX11
+inline void FieldMask::add_paths(::std::string&& value) {
+ paths_.Add(std::move(value));
+ // @@protoc_insertion_point(field_add:google.protobuf.FieldMask.paths)
+}
+#endif
inline void FieldMask::add_paths(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
paths_.Add()->assign(value);
// @@protoc_insertion_point(field_add_char:google.protobuf.FieldMask.paths)
}
@@ -202,11 +253,12 @@ FieldMask::mutable_paths() {
return &paths_;
}
-#endif // !PROTOBUF_INLINE_NOT_IN_HEADERS
+#ifdef __GNUC__
+ #pragma GCC diagnostic pop
+#endif // __GNUC__
// @@protoc_insertion_point(namespace_scope)
-
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/field_mask.proto b/src/google/protobuf/field_mask.proto
index c68d247c..eb96ba00 100644
--- a/src/google/protobuf/field_mask.proto
+++ b/src/google/protobuf/field_mask.proto
@@ -240,6 +240,12 @@ option go_package = "google.golang.org/genproto/protobuf/field_mask;field_mask";
//
// Note that oneof type names ("test_oneof" in this case) cannot be used in
// paths.
+//
+// ## Field Mask Verification
+//
+// The implementation of the all the API methods, which have any FieldMask type
+// field in the request, should verify the included field paths, and return
+// `INVALID_ARGUMENT` error if any path is duplicated or unmappable.
message FieldMask {
// The set of field mask paths.
repeated string paths = 1;
diff --git a/src/google/protobuf/generated_message_reflection.cc b/src/google/protobuf/generated_message_reflection.cc
index 08742232..f0f207ea 100644
--- a/src/google/protobuf/generated_message_reflection.cc
+++ b/src/google/protobuf/generated_message_reflection.cc
@@ -44,7 +44,7 @@
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/map_field.h>
#include <google/protobuf/repeated_field.h>
-// #include "google/protobuf/bridge/compatibility_mode_support.h"
+#include <google/protobuf/wire_format.h>
#define GOOGLE_PROTOBUF_HAS_ONEOF
@@ -73,12 +73,6 @@ const string& NameOfEnum(const EnumDescriptor* descriptor, int value) {
return (d == NULL ? GetEmptyString() : d->name());
}
-namespace {
-inline bool SupportsArenas(const Descriptor* descriptor) {
- return descriptor->file()->options().cc_enable_arenas();
-}
-} // anonymous namespace
-
// ===================================================================
// Helpers for reporting usage errors (e.g. trying to use GetInt32() on
// a string field).
@@ -197,47 +191,20 @@ GeneratedMessageReflection::GeneratedMessageReflection(
descriptor_pool_((pool == NULL) ? DescriptorPool::generated_pool()
: pool),
message_factory_(factory),
- // TODO(haberman) remove this when upb is using our table driven.
- default_instance_(schema_.default_instance_),
- default_oneof_instance_(schema_.default_oneof_instance_),
- offsets_(schema_.offsets_),
- has_bits_indices_(schema_.has_bit_indices_),
- has_bits_offset_(schema_.has_bits_offset_),
- oneof_case_offset_(schema_.oneof_case_offset_),
- unknown_fields_offset_(-1),
- extensions_offset_(schema_.extensions_offset_),
- arena_offset_(schema_.metadata_offset_),
- object_size_(schema_.object_size_) {
+ last_non_weak_field_index_(-1) {
+ last_non_weak_field_index_ = descriptor_->field_count() - 1;
}
GeneratedMessageReflection::~GeneratedMessageReflection() {}
-namespace {
-UnknownFieldSet* empty_unknown_field_set_ = NULL;
-GOOGLE_PROTOBUF_DECLARE_ONCE(empty_unknown_field_set_once_);
-
-void DeleteEmptyUnknownFieldSet() {
- delete empty_unknown_field_set_;
- empty_unknown_field_set_ = NULL;
-}
-
-void InitEmptyUnknownFieldSet() {
- empty_unknown_field_set_ = new UnknownFieldSet;
- internal::OnShutdown(&DeleteEmptyUnknownFieldSet);
-}
-
-const UnknownFieldSet& GetEmptyUnknownFieldSet() {
- ::google::protobuf::GoogleOnceInit(&empty_unknown_field_set_once_, &InitEmptyUnknownFieldSet);
- return *empty_unknown_field_set_;
-}
-} // namespace
-
const UnknownFieldSet& GeneratedMessageReflection::GetUnknownFields(
const Message& message) const {
- if (descriptor_->file()->syntax() == FileDescriptor::SYNTAX_PROTO3) {
+ if (descriptor_->file()->syntax() == FileDescriptor::SYNTAX_PROTO3 &&
+ !GetProto3PreserveUnknownsDefault()) {
// We have to ensure that any mutations made to the return value of
- // MutableUnknownFields() are not reflected here.
- return GetEmptyUnknownFieldSet();
+ // MutableUnknownFields() are not reflected here when Proto3 defaults to
+ // discard unknowns.
+ return *UnknownFieldSet::default_instance();
} else {
return GetInternalMetadataWithArena(message).unknown_fields();
}
@@ -248,28 +215,25 @@ UnknownFieldSet* GeneratedMessageReflection::MutableUnknownFields(
return MutableInternalMetadataWithArena(message)->mutable_unknown_fields();
}
-int GeneratedMessageReflection::SpaceUsed(const Message& message) const {
+size_t GeneratedMessageReflection::SpaceUsedLong(const Message& message) const {
// object_size_ already includes the in-memory representation of each field
// in the message, so we only need to account for additional memory used by
// the fields.
- int total_size = schema_.GetObjectSize();
+ size_t total_size = schema_.GetObjectSize();
- total_size += GetUnknownFields(message).SpaceUsedExcludingSelf();
+ total_size += GetUnknownFields(message).SpaceUsedExcludingSelfLong();
if (schema_.HasExtensionSet()) {
- total_size += GetExtensionSet(message).SpaceUsedExcludingSelf();
+ total_size += GetExtensionSet(message).SpaceUsedExcludingSelfLong();
}
-
- const int field_count = descriptor_->field_count();
- for (int i = 0; i < field_count; i++) {
+ for (int i = 0; i <= last_non_weak_field_index_; i++) {
const FieldDescriptor* field = descriptor_->field(i);
-
if (field->is_repeated()) {
switch (field->cpp_type()) {
#define HANDLE_TYPE(UPPERCASE, LOWERCASE) \
case FieldDescriptor::CPPTYPE_##UPPERCASE : \
total_size += GetRaw<RepeatedField<LOWERCASE> >(message, field) \
- .SpaceUsedExcludingSelf(); \
+ .SpaceUsedExcludingSelfLong(); \
break
HANDLE_TYPE( INT32, int32);
@@ -287,21 +251,21 @@ int GeneratedMessageReflection::SpaceUsed(const Message& message) const {
default: // TODO(kenton): Support other string reps.
case FieldOptions::STRING:
total_size += GetRaw<RepeatedPtrField<string> >(message, field)
- .SpaceUsedExcludingSelf();
+ .SpaceUsedExcludingSelfLong();
break;
}
break;
case FieldDescriptor::CPPTYPE_MESSAGE:
if (IsMapFieldInApi(field)) {
- total_size +=
- GetRaw<MapFieldBase>(message, field).SpaceUsedExcludingSelf();
+ total_size += GetRaw<MapFieldBase>(message, field)
+ .SpaceUsedExcludingSelfLong();
} else {
// We don't know which subclass of RepeatedPtrFieldBase the type is,
// so we use RepeatedPtrFieldBase directly.
total_size +=
GetRaw<RepeatedPtrFieldBase>(message, field)
- .SpaceUsedExcludingSelf<GenericTypeHandler<Message> >();
+ .SpaceUsedExcludingSelfLong<GenericTypeHandler<Message> >();
}
break;
@@ -337,7 +301,8 @@ int GeneratedMessageReflection::SpaceUsed(const Message& message) const {
if (ptr != default_ptr) {
// string fields are represented by just a pointer, so also
// include sizeof(string) as well.
- total_size += sizeof(*ptr) + StringSpaceUsedExcludingSelf(*ptr);
+ total_size +=
+ sizeof(*ptr) + StringSpaceUsedExcludingSelfLong(*ptr);
}
break;
}
@@ -352,14 +317,13 @@ int GeneratedMessageReflection::SpaceUsed(const Message& message) const {
} else {
const Message* sub_message = GetRaw<const Message*>(message, field);
if (sub_message != NULL) {
- total_size += sub_message->SpaceUsed();
+ total_size += sub_message->SpaceUsedLong();
}
}
break;
}
}
}
-
return total_size;
}
@@ -643,21 +607,28 @@ void GeneratedMessageReflection::Swap(
if (schema_.HasHasbits()) {
uint32* has_bits1 = MutableHasBits(message1);
uint32* has_bits2 = MutableHasBits(message2);
- int has_bits_size = (descriptor_->field_count() + 31) / 32;
+
+ int fields_with_has_bits = 0;
+ for (int i = 0; i < descriptor_->field_count(); i++) {
+ const FieldDescriptor* field = descriptor_->field(i);
+ if (field->is_repeated() || field->containing_oneof()) {
+ continue;
+ }
+ fields_with_has_bits++;
+ }
+
+ int has_bits_size = (fields_with_has_bits + 31) / 32;
for (int i = 0; i < has_bits_size; i++) {
std::swap(has_bits1[i], has_bits2[i]);
}
}
- const int field_count = descriptor_->field_count();
- for (int i = 0; i < field_count; i++) {
+ for (int i = 0; i <= last_non_weak_field_index_; i++) {
const FieldDescriptor* field = descriptor_->field(i);
- if (!field->containing_oneof()) {
- SwapField(message1, message2, field);
- }
+ if (field->containing_oneof()) continue;
+ SwapField(message1, message2, field);
}
-
const int oneof_decl_count = descriptor_->oneof_decl_count();
for (int i = 0; i < oneof_decl_count; i++) {
SwapOneofField(message1, message2, descriptor_->oneof_decl(i));
@@ -711,8 +682,11 @@ void GeneratedMessageReflection::SwapFields(
swapped_oneof.insert(oneof_index);
SwapOneofField(message1, message2, field->containing_oneof());
} else {
- // Swap has bit.
- SwapBit(message1, message2, field);
+ // Swap has bit for non-repeated fields. We have already checked for
+ // oneof already.
+ if (!field->is_repeated()) {
+ SwapBit(message1, message2, field);
+ }
// Swap field.
SwapField(message1, message2, field);
}
@@ -786,7 +760,6 @@ void GeneratedMessageReflection::ClearField(
ClearOneofField(message, field);
return;
}
-
if (HasBit(*message, field)) {
ClearBit(message, field);
@@ -1006,6 +979,7 @@ struct FieldNumberSorter {
inline bool IsIndexInHasBitSet(
const uint32* has_bit_set, uint32 has_bit_index) {
+ GOOGLE_DCHECK_NE(has_bit_index, ~0u);
return ((has_bit_set[has_bit_index / 32] >> (has_bit_index % 32)) &
static_cast<uint32>(1)) != 0;
}
@@ -1028,11 +1002,9 @@ void GeneratedMessageReflection::ListFields(
schema_.HasHasbits() ? GetHasBits(message) : NULL;
const uint32* const has_bits_indices = schema_.has_bit_indices_;
const uint32* const oneof_case_array =
- &GetConstRefAtOffset<uint32>(message, schema_.oneof_case_offset_);
-
- const int field_count = descriptor_->field_count();
- output->reserve(field_count);
- for (int i = 0; i < field_count; i++) {
+ GetConstPointerAtOffset<uint32>(&message, schema_.oneof_case_offset_);
+ output->reserve(descriptor_->field_count());
+ for (int i = 0; i <= last_non_weak_field_index_; i++) {
const FieldDescriptor* field = descriptor_->field(i);
if (field->is_repeated()) {
if (FieldSize(message, field) > 0) {
@@ -1055,7 +1027,6 @@ void GeneratedMessageReflection::ListFields(
}
}
}
-
if (schema_.HasExtensionSet()) {
GetExtensionSet(message).AppendToList(descriptor_, descriptor_pool_,
output);
@@ -1461,8 +1432,7 @@ const Message& GeneratedMessageReflection::GetMessage(
GetExtensionSet(message).GetMessage(
field->number(), field->message_type(), factory));
} else {
- const Message* result;
- result = GetRaw<const Message*>(message, field);
+ const Message* result = GetRaw<const Message*>(message, field);
if (result == NULL) {
result = DefaultRaw<const Message*>(field);
}
@@ -1482,6 +1452,7 @@ Message* GeneratedMessageReflection::MutableMessage(
MutableExtensionSet(message)->MutableMessage(field, factory));
} else {
Message* result;
+
Message** result_holder = MutableRaw<Message*>(message, field);
if (field->containing_oneof()) {
@@ -1511,7 +1482,7 @@ void GeneratedMessageReflection::UnsafeArenaSetAllocatedMessage(
USAGE_CHECK_ALL(SetAllocatedMessage, SINGULAR, MESSAGE);
if (field->is_extension()) {
- MutableExtensionSet(message)->SetAllocatedMessage(
+ MutableExtensionSet(message)->UnsafeArenaSetAllocatedMessage(
field->number(), field->type(), field, sub_message);
} else {
if (field->containing_oneof()) {
@@ -1579,7 +1550,9 @@ Message* GeneratedMessageReflection::UnsafeArenaReleaseMessage(
MutableExtensionSet(message)->UnsafeArenaReleaseMessage(field,
factory));
} else {
- ClearBit(message, field);
+ if (!(field->is_repeated() || field->containing_oneof())) {
+ ClearBit(message, field);
+ }
if (field->containing_oneof()) {
if (HasOneofField(*message, field)) {
*MutableOneofCase(message, field->containing_oneof()) = 0;
@@ -1977,6 +1950,7 @@ inline const Type& GeneratedMessageReflection::DefaultRaw(
// Simple accessors for manipulating has_bits_.
inline bool GeneratedMessageReflection::HasBit(
const Message& message, const FieldDescriptor* field) const {
+ GOOGLE_DCHECK(!field->options().weak());
if (schema_.HasHasbits()) {
return IsIndexInHasBitSet(GetHasBits(message), schema_.HasBitIndex(field));
}
@@ -2032,6 +2006,7 @@ inline bool GeneratedMessageReflection::HasBit(
inline void GeneratedMessageReflection::SetBit(
Message* message, const FieldDescriptor* field) const {
+ GOOGLE_DCHECK(!field->options().weak());
if (!schema_.HasHasbits()) {
return;
}
@@ -2042,6 +2017,7 @@ inline void GeneratedMessageReflection::SetBit(
inline void GeneratedMessageReflection::ClearBit(
Message* message, const FieldDescriptor* field) const {
+ GOOGLE_DCHECK(!field->options().weak());
if (!schema_.HasHasbits()) {
return;
}
@@ -2052,6 +2028,7 @@ inline void GeneratedMessageReflection::ClearBit(
inline void GeneratedMessageReflection::SwapBit(
Message* message1, Message* message2, const FieldDescriptor* field) const {
+ GOOGLE_DCHECK(!field->options().weak());
if (!schema_.HasHasbits()) {
return;
}
@@ -2233,29 +2210,23 @@ namespace {
// Helper function to transform migration schema into reflection schema.
ReflectionSchema MigrationToReflectionSchema(
- const DefaultInstanceData* default_instance_data, const uint32* offsets,
+ const Message* const* default_instance, const uint32* offsets,
MigrationSchema migration_schema) {
ReflectionSchema result;
- result.default_instance_ = default_instance_data->default_instance;
- // First 5 offsets are offsets to the special fields. The following offsets
+ result.default_instance_ = *default_instance;
+ // First 6 offsets are offsets to the special fields. The following offsets
// are the proto fields.
- result.offsets_ = offsets + migration_schema.offsets_index + 4;
+ result.offsets_ = offsets + migration_schema.offsets_index + 5;
result.has_bit_indices_ = offsets + migration_schema.has_bit_indices_index;
result.has_bits_offset_ = offsets[migration_schema.offsets_index + 0];
result.metadata_offset_ = offsets[migration_schema.offsets_index + 1];
result.extensions_offset_ = offsets[migration_schema.offsets_index + 2];
- result.default_oneof_instance_ = default_instance_data->default_oneof_instance;
result.oneof_case_offset_ = offsets[migration_schema.offsets_index + 3];
result.object_size_ = migration_schema.object_size;
+ result.weak_field_map_offset_ = offsets[migration_schema.offsets_index + 4];
return result;
}
-ReflectionSchema MigrationToReflectionSchema(
- const DefaultInstanceData* default_instance_data, const uint32* offsets,
- ReflectionSchema schema) {
- return schema;
-}
-
template<typename Schema>
class AssignDescriptorsHelper {
public:
@@ -2263,7 +2234,7 @@ class AssignDescriptorsHelper {
Metadata* file_level_metadata,
const EnumDescriptor** file_level_enum_descriptors,
const Schema* schemas,
- const DefaultInstanceData* default_instance_data,
+ const Message* const* default_instance_data,
const uint32* offsets)
: factory_(factory),
file_level_metadata_(file_level_metadata),
@@ -2279,17 +2250,16 @@ class AssignDescriptorsHelper {
file_level_metadata_->descriptor = descriptor;
- if (!descriptor->options().map_entry()) {
- // Only set reflection for non map types.
- file_level_metadata_->reflection = new GeneratedMessageReflection(
- descriptor, MigrationToReflectionSchema(default_instance_data_++,
- offsets_, *schemas_),
- ::google::protobuf::DescriptorPool::generated_pool(), factory_);
- for (int i = 0; i < descriptor->enum_type_count(); i++) {
- AssignEnumDescriptor(descriptor->enum_type(i));
- }
- schemas_++;
+ file_level_metadata_->reflection = new GeneratedMessageReflection(
+ descriptor,
+ MigrationToReflectionSchema(default_instance_data_, offsets_,
+ *schemas_),
+ ::google::protobuf::DescriptorPool::generated_pool(), factory_);
+ for (int i = 0; i < descriptor->enum_type_count(); i++) {
+ AssignEnumDescriptor(descriptor->enum_type(i));
}
+ schemas_++;
+ default_instance_data_++;
file_level_metadata_++;
}
@@ -2298,51 +2268,57 @@ class AssignDescriptorsHelper {
file_level_enum_descriptors_++;
}
+ const Metadata* GetCurrentMetadataPtr() const { return file_level_metadata_; }
+
private:
MessageFactory* factory_;
Metadata* file_level_metadata_;
const EnumDescriptor** file_level_enum_descriptors_;
const Schema* schemas_;
- const DefaultInstanceData* default_instance_data_;
+ const Message* const * default_instance_data_;
const uint32* offsets_;
};
-} // namespace
-
-void AssignDescriptors(
- const string& filename, const MigrationSchema* schemas,
- const DefaultInstanceData* default_instance_data, const uint32* offsets,
- MessageFactory* factory,
- // update the following descriptor arrays.
- Metadata* file_level_metadata,
- const EnumDescriptor** file_level_enum_descriptors,
- const ServiceDescriptor** file_level_service_descriptors) {
- const ::google::protobuf::FileDescriptor* file =
- ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName(filename);
- GOOGLE_CHECK(file != NULL);
-
- if (!factory) factory = MessageFactory::generated_factory();
-
- AssignDescriptorsHelper<MigrationSchema> helper(factory, file_level_metadata,
- file_level_enum_descriptors, schemas,
- default_instance_data, offsets);
-
- for (int i = 0; i < file->message_type_count(); i++) {
- helper.AssignMessageDescriptor(file->message_type(i));
+// We have the routines that assign descriptors and build reflection
+// automatically delete the allocated reflection. MetadataOwner owns
+// all the allocated reflection instances.
+struct MetadataOwner {
+ void AddArray(const Metadata* begin, const Metadata* end) {
+ MutexLock lock(&mu_);
+ metadata_arrays_.push_back(std::make_pair(begin, end));
}
- for (int i = 0; i < file->enum_type_count(); i++) {
- helper.AssignEnumDescriptor(file->enum_type(i));
+ static MetadataOwner* Instance() {
+ static MetadataOwner* res = new MetadataOwner;
+ return res;
}
- if (file->options().cc_generic_services()) {
- for (int i = 0; i < file->service_count(); i++) {
- file_level_service_descriptors[i] = file->service(i);
+
+ private:
+ // Use the constructor to register the shutdown code. Because c++ makes sure
+ // this called only once.
+ MetadataOwner() { OnShutdown(&DeleteMetadata); }
+ ~MetadataOwner() {
+ for (int i = 0; i < metadata_arrays_.size(); i++) {
+ for (const Metadata* m = metadata_arrays_[i].first;
+ m < metadata_arrays_[i].second; m++) {
+ delete m->reflection;
+ }
}
}
-}
+
+ static void DeleteMetadata() {
+ delete Instance();
+ }
+
+ Mutex mu_;
+ std::vector<std::pair<const Metadata*, const Metadata*> > metadata_arrays_;
+};
+
+} // namespace
void AssignDescriptors(
- const string& filename, const ReflectionSchema* schemas,
+ const string& filename, const MigrationSchema* schemas,
+ const Message* const* default_instances_, const uint32* offsets,
MessageFactory* factory,
// update the following descriptor arrays.
Metadata* file_level_metadata,
@@ -2354,9 +2330,9 @@ void AssignDescriptors(
if (!factory) factory = MessageFactory::generated_factory();
- AssignDescriptorsHelper<ReflectionSchema> helper(factory, file_level_metadata,
+ AssignDescriptorsHelper<MigrationSchema> helper(factory, file_level_metadata,
file_level_enum_descriptors, schemas,
- NULL, NULL);
+ default_instances_, offsets);
for (int i = 0; i < file->message_type_count(); i++) {
helper.AssignMessageDescriptor(file->message_type(i));
@@ -2370,6 +2346,8 @@ void AssignDescriptors(
file_level_service_descriptors[i] = file->service(i);
}
}
+ MetadataOwner::Instance()->AddArray(
+ file_level_metadata, helper.GetCurrentMetadataPtr());
}
void RegisterAllTypesInternal(const Metadata* file_level_metadata, int size) {
@@ -2390,6 +2368,18 @@ void RegisterAllTypes(const Metadata* file_level_metadata, int size) {
RegisterAllTypesInternal(file_level_metadata, size);
}
+void UnknownFieldSetSerializer(const uint8* base, uint32 offset, uint32 tag,
+ uint32 has_offset,
+ ::google::protobuf::io::CodedOutputStream* output) {
+ const void* ptr = base + offset;
+ const InternalMetadataWithArena* metadata =
+ static_cast<const InternalMetadataWithArena*>(ptr);
+ if (metadata->have_unknown_fields()) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ metadata->unknown_fields(), output);
+ }
+}
+
} // namespace internal
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/generated_message_reflection.h b/src/google/protobuf/generated_message_reflection.h
index 2633ab62..02ecba61 100644
--- a/src/google/protobuf/generated_message_reflection.h
+++ b/src/google/protobuf/generated_message_reflection.h
@@ -45,7 +45,6 @@
// TODO(jasonh): Remove this once the compiler change to directly include this
// is released to components.
#include <google/protobuf/generated_enum_reflection.h>
-#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/message.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/unknown_field_set.h>
@@ -62,7 +61,15 @@ namespace protobuf {
class DescriptorPool;
class MapKey;
class MapValueRef;
-}
+} // namespace protobuf
+
+
+namespace protobuf {
+namespace flat {
+class MetadataBuilder;
+} // namespace flat
+} // namespace protobuf
+
namespace protobuf {
namespace internal {
@@ -73,6 +80,7 @@ class GeneratedMessageReflection;
// Defined in other files.
class ExtensionSet; // extension_set.h
+class WeakFieldMap; // weak_field_map.h
// This struct describes the internal layout of the message, hence this is
// used to act on the message reflectively.
@@ -83,17 +91,17 @@ class ExtensionSet; // extension_set.h
// embedded message fields *must* have non-NULL pointers
// in the default instance.)
// offsets: An array of ints giving the byte offsets.
-// For each oneof field, the offset is relative to the
-// default_oneof_instance. These can be computed at compile
-// time using the
-// PROTO2_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET() macro.
-// For each none oneof field, the offset is related to
-// the start of the message object. These can be computed
-// at compile time using the
+// For each oneof or weak field, the offset is relative to the
+// default_instance. These can be computed at compile time
+// using the
+// GOOGLE_PROTOBUF_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET()
+// macro. For each none oneof field, the offset is related to
+// the start of the message object. These can be computed at
+// compile time using the
// GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET() macro.
// Besides offsets for all fields, this array also contains
-// offsets for oneof unions. The offset of the i-th oneof
-// union is offsets[descriptor->field_count() + i].
+// offsets for oneof unions. The offset of the i-th oneof union
+// is offsets[descriptor->field_count() + i].
// has_bit_indices: Mapping from field indexes to their index in the has
// bit array.
// has_bits_offset: Offset in the message of an array of uint32s of size
@@ -107,11 +115,6 @@ class ExtensionSet; // extension_set.h
// extensions_offset: Offset in the message of the ExtensionSet for the
// message, or -1 if the message type has no extension
// ranges.
-// default_oneof_instance: The default instance of the oneofs. It is a
-// struct holding the default value of all oneof fields
-// for this message. It is only used to obtain pointers
-// to default instances of oneof fields, which Get
-// methods will return if the field is not set.
// oneof_case_offset: Offset in the message of an array of uint32s of
// size descriptor->oneof_decl_count(). Each uint32
// indicates what field is set for each oneof.
@@ -119,10 +122,13 @@ class ExtensionSet; // extension_set.h
// by sizeof().
// arena_offset: If a message doesn't have a unknown_field_set that stores
// the arena, it must have a direct pointer to the arena.
+// weak_field_map_offset: If the message proto has weak fields, this is the
+// offset of _weak_field_map_ in the generated proto. Otherwise
+// -1.
struct ReflectionSchema {
public:
// Size of a google::protobuf::Message object of this type.
- uint32 GetObjectSize() const { return object_size_; }
+ uint32 GetObjectSize() const { return static_cast<uint32>(object_size_); }
// Offset of a non-oneof field. Getting a field offset is slightly more
// efficient when we know statically that it is not a oneof field.
@@ -134,8 +140,9 @@ struct ReflectionSchema {
// Offset of any field.
uint32 GetFieldOffset(const FieldDescriptor* field) const {
if (field->containing_oneof()) {
- size_t offset = field->containing_type()->field_count() +
- field->containing_oneof()->index();
+ size_t offset =
+ static_cast<size_t>(field->containing_type()->field_count() +
+ field->containing_oneof()->index());
return offsets_[offset];
} else {
return GetFieldOffsetNonOneof(field);
@@ -143,7 +150,9 @@ struct ReflectionSchema {
}
uint32 GetOneofCaseOffset(const OneofDescriptor* oneof_descriptor) const {
- return oneof_case_offset_ + (oneof_descriptor->index() * sizeof(uint32));
+ return static_cast<uint32>(oneof_case_offset_) +
+ static_cast<uint32>(
+ static_cast<size_t>(oneof_descriptor->index()) * sizeof(uint32));
}
bool HasHasbits() const { return has_bits_offset_ != -1; }
@@ -157,15 +166,15 @@ struct ReflectionSchema {
// Byte offset of the hasbits array.
uint32 HasBitsOffset() const {
GOOGLE_DCHECK(HasHasbits());
- return has_bits_offset_;
+ return static_cast<uint32>(has_bits_offset_);
}
- // The offset of the InternalMetadataWithArenaOffset member.
- // For Lite this will actually be an InternalMetadataWithArenaOffsetLite.
+ // The offset of the InternalMetadataWithArena member.
+ // For Lite this will actually be an InternalMetadataWithArenaLite.
// The schema doesn't contain enough information to distinguish between
// these two cases.
uint32 GetMetadataOffset() const {
- return metadata_offset_;
+ return static_cast<uint32>(metadata_offset_);
}
// Whether this message has an ExtensionSet.
@@ -174,9 +183,13 @@ struct ReflectionSchema {
// The offset of the ExtensionSet in this message.
uint32 GetExtensionSetOffset() const {
GOOGLE_DCHECK(HasExtensionSet());
- return extensions_offset_;
+ return static_cast<uint32>(extensions_offset_);
}
+ // The off set of WeakFieldMap when the message contains weak fields.
+ // The default is 0 for now.
+ int GetWeakFieldMapOffset() const { return weak_field_map_offset_; }
+
bool IsDefaultInstance(const Message& message) const {
return &message == default_instance_;
}
@@ -184,13 +197,13 @@ struct ReflectionSchema {
// Returns a pointer to the default value for this field. The size and type
// of the underlying data depends on the field's type.
const void *GetFieldDefault(const FieldDescriptor* field) const {
- return field->containing_oneof()
- ? reinterpret_cast<const uint8*>(default_oneof_instance_) +
- offsets_[field->index()]
- : reinterpret_cast<const uint8*>(default_instance_) +
+ return reinterpret_cast<const uint8*>(default_instance_) +
offsets_[field->index()];
}
+
+ bool HasWeakFields() const { return weak_field_map_offset_ > 0; }
+
// These members are intended to be private, but we cannot actually make them
// private because this prevents us from using aggregate initialization of
// them, ie.
@@ -203,9 +216,9 @@ struct ReflectionSchema {
int has_bits_offset_;
int metadata_offset_;
int extensions_offset_;
- const void* default_oneof_instance_;
int oneof_case_offset_;
int object_size_;
+ int weak_field_map_offset_;
};
// Structs that the code generator emits directly to describe a message.
@@ -214,11 +227,6 @@ struct ReflectionSchema {
//
// EXPERIMENTAL: these are changing rapidly, and may completely disappear
// or merge with ReflectionSchema.
-struct DefaultInstanceData {
- const Message* default_instance;
- const void* default_oneof_instance;
-};
-
struct MigrationSchema {
int32 offsets_index;
int32 has_bit_indices_index;
@@ -271,7 +279,7 @@ class LIBPROTOBUF_EXPORT GeneratedMessageReflection PROTOBUF_FINAL : public Refl
const UnknownFieldSet& GetUnknownFields(const Message& message) const;
UnknownFieldSet* MutableUnknownFields(Message* message) const;
- int SpaceUsed(const Message& message) const;
+ size_t SpaceUsedLong(const Message& message) const;
bool HasField(const Message& message, const FieldDescriptor* field) const;
int FieldSize(const Message& message, const FieldDescriptor* field) const;
@@ -489,7 +497,7 @@ class LIBPROTOBUF_EXPORT GeneratedMessageReflection PROTOBUF_FINAL : public Refl
const Descriptor* message_type) const;
private:
- friend class GeneratedMessage;
+ friend class google::protobuf::flat::MetadataBuilder;
friend class upb::google_opensource::GMR_Handlers;
const Descriptor* const descriptor_;
@@ -497,20 +505,10 @@ class LIBPROTOBUF_EXPORT GeneratedMessageReflection PROTOBUF_FINAL : public Refl
const DescriptorPool* const descriptor_pool_;
MessageFactory* const message_factory_;
- // To parse directly into a proto2 generated class, the class GMR_Handlers
- // needs access to member offsets and hasbits.
- // upb still needs these.
- // TODO(haberman) clean this up.
- const Message* const default_instance_;
- const void* const default_oneof_instance_;
- const uint32* const offsets_;
- const uint32* const has_bits_indices_;
- const int has_bits_offset_;
- const int oneof_case_offset_;
- const int unknown_fields_offset_;
- const int extensions_offset_;
- const int arena_offset_;
- const int object_size_;
+ // Last non weak field index. This is an optimization when most weak fields
+ // are at the end of the containing message. If a message proto doesn't
+ // contain weak fields, then this field equals descriptor_->field_count().
+ int last_non_weak_field_index_;
template <class T>
const T& GetRawNonOneof(const Message& message,
@@ -637,40 +635,6 @@ class LIBPROTOBUF_EXPORT GeneratedMessageReflection PROTOBUF_FINAL : public Refl
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(GeneratedMessageReflection);
};
-// Returns the offset of the given field within the given aggregate type.
-// This is equivalent to the ANSI C offsetof() macro. However, according
-// to the C++ standard, offsetof() only works on POD types, and GCC
-// enforces this requirement with a warning. In practice, this rule is
-// unnecessarily strict; there is probably no compiler or platform on
-// which the offsets of the direct fields of a class are non-constant.
-// Fields inherited from superclasses *can* have non-constant offsets,
-// but that's not what this macro will be used for.
-#if defined(__clang__)
-// For Clang we use __builtin_offsetof() and suppress the warning,
-// to avoid Control Flow Integrity and UBSan vptr sanitizers from
-// crashing while trying to validate the invalid reinterpet_casts.
-#define GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TYPE, FIELD) \
- _Pragma("clang diagnostic push") \
- _Pragma("clang diagnostic ignored \"-Winvalid-offsetof\"") \
- __builtin_offsetof(TYPE, FIELD) \
- _Pragma("clang diagnostic pop")
-#else
-// Note that we calculate relative to the pointer value 16 here since if we
-// just use zero, GCC complains about dereferencing a NULL pointer. We
-// choose 16 rather than some other number just in case the compiler would
-// be confused by an unaligned pointer.
-#define GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TYPE, FIELD) \
- static_cast< ::google::protobuf::uint32>( \
- reinterpret_cast<const char*>( \
- &reinterpret_cast<const TYPE*>(16)->FIELD) - \
- reinterpret_cast<const char*>(16))
-#endif
-
-#define PROTO2_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET(ONEOF, FIELD) \
- static_cast< ::google::protobuf::uint32>( \
- reinterpret_cast<const char*>(&(ONEOF->FIELD)) \
- - reinterpret_cast<const char*>(ONEOF))
-
// There are some places in proto2 where dynamic_cast would be useful as an
// optimization. For example, take Message::MergeFrom(const Message& other).
// For a given generated message FooMessage, we generate these two methods:
@@ -697,6 +661,8 @@ class LIBPROTOBUF_EXPORT GeneratedMessageReflection PROTOBUF_FINAL : public Refl
template<typename To, typename From>
inline To dynamic_cast_if_available(From from) {
#if defined(GOOGLE_PROTOBUF_NO_RTTI) || (defined(_MSC_VER)&&!defined(_CPPRTTI))
+ // Avoid the compiler warning about unused variables.
+ (void)from;
return NULL;
#else
return dynamic_cast<To>(from);
@@ -741,15 +707,7 @@ T* DynamicCastToGenerated(Message* from) {
LIBPROTOBUF_EXPORT void AssignDescriptors(
const string& filename, const MigrationSchema* schemas,
- const DefaultInstanceData* default_instance_data, const uint32* offsets,
- MessageFactory* factory,
- // update the following descriptor arrays.
- Metadata* file_level_metadata,
- const EnumDescriptor** file_level_enum_descriptors,
- const ServiceDescriptor** file_level_service_descriptors);
-
-LIBPROTOBUF_EXPORT void AssignDescriptors(
- const string& filename, const ReflectionSchema* schemas,
+ const Message* const* default_instances_, const uint32* offsets,
MessageFactory* factory,
// update the following descriptor arrays.
Metadata* file_level_metadata,
@@ -758,6 +716,11 @@ LIBPROTOBUF_EXPORT void AssignDescriptors(
LIBPROTOBUF_EXPORT void RegisterAllTypes(const Metadata* file_level_metadata, int size);
+// These cannot be in lite so we put them in the reflection.
+LIBPROTOBUF_EXPORT void UnknownFieldSetSerializer(const uint8* base, uint32 offset, uint32 tag,
+ uint32 has_offset,
+ ::google::protobuf::io::CodedOutputStream* output);
+
} // namespace internal
} // namespace protobuf
diff --git a/src/google/protobuf/generated_message_reflection_unittest.cc b/src/google/protobuf/generated_message_reflection_unittest.cc
index e2c6cdc0..242cc4a1 100644
--- a/src/google/protobuf/generated_message_reflection_unittest.cc
+++ b/src/google/protobuf/generated_message_reflection_unittest.cc
@@ -48,9 +48,10 @@
#include <google/protobuf/stubs/shared_ptr.h>
#endif
-#include <google/protobuf/descriptor.h>
#include <google/protobuf/test_util.h>
#include <google/protobuf/unittest.pb.h>
+#include <google/protobuf/arena.h>
+#include <google/protobuf/descriptor.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
@@ -519,6 +520,41 @@ TEST(GeneratedMessageReflectionTest, SetAllocatedMessageTest) {
&to_message, TestUtil::ReflectionTester::IS_NULL);
}
+TEST(GeneratedMessageReflectionTest, SetAllocatedMessageOnArenaTest) {
+ unittest::TestAllTypes from_message1;
+ unittest::TestAllTypes from_message2;
+ ::google::protobuf::Arena arena;
+ unittest::TestAllTypes* to_message =
+ ::google::protobuf::Arena::CreateMessage<unittest::TestAllTypes>(&arena);
+ TestUtil::ReflectionTester reflection_tester(
+ unittest::TestAllTypes::descriptor());
+ reflection_tester.SetAllFieldsViaReflection(&from_message1);
+ reflection_tester.SetAllFieldsViaReflection(&from_message2);
+
+ // Before moving fields, we expect the nested messages to be NULL.
+ reflection_tester.ExpectMessagesReleasedViaReflection(
+ to_message, TestUtil::ReflectionTester::IS_NULL);
+
+ // After fields are moved we should get non-NULL releases.
+ reflection_tester.SetAllocatedOptionalMessageFieldsToMessageViaReflection(
+ &from_message1, to_message);
+ reflection_tester.ExpectMessagesReleasedViaReflection(
+ to_message, TestUtil::ReflectionTester::NOT_NULL);
+
+ // Another move to make sure that we can SetAllocated several times.
+ reflection_tester.SetAllocatedOptionalMessageFieldsToMessageViaReflection(
+ &from_message2, to_message);
+ reflection_tester.ExpectMessagesReleasedViaReflection(
+ to_message, TestUtil::ReflectionTester::NOT_NULL);
+
+ // After SetAllocatedOptionalMessageFieldsToNullViaReflection() we expect the
+ // releases to be NULL again.
+ reflection_tester.SetAllocatedOptionalMessageFieldsToNullViaReflection(
+ to_message);
+ reflection_tester.ExpectMessagesReleasedViaReflection(
+ to_message, TestUtil::ReflectionTester::IS_NULL);
+}
+
TEST(GeneratedMessageReflectionTest, SetAllocatedExtensionMessageTest) {
unittest::TestAllExtensions from_message1;
unittest::TestAllExtensions from_message2;
@@ -552,6 +588,41 @@ TEST(GeneratedMessageReflectionTest, SetAllocatedExtensionMessageTest) {
&to_message, TestUtil::ReflectionTester::IS_NULL);
}
+TEST(GeneratedMessageReflectionTest, SetAllocatedExtensionMessageOnArenaTest) {
+ ::google::protobuf::Arena arena;
+ unittest::TestAllExtensions* to_message =
+ ::google::protobuf::Arena::CreateMessage<unittest::TestAllExtensions>(&arena);
+ unittest::TestAllExtensions from_message1;
+ unittest::TestAllExtensions from_message2;
+ TestUtil::ReflectionTester reflection_tester(
+ unittest::TestAllExtensions::descriptor());
+ reflection_tester.SetAllFieldsViaReflection(&from_message1);
+ reflection_tester.SetAllFieldsViaReflection(&from_message2);
+
+ // Before moving fields, we expect the nested messages to be NULL.
+ reflection_tester.ExpectMessagesReleasedViaReflection(
+ to_message, TestUtil::ReflectionTester::IS_NULL);
+
+ // After fields are moved we should get non-NULL releases.
+ reflection_tester.SetAllocatedOptionalMessageFieldsToMessageViaReflection(
+ &from_message1, to_message);
+ reflection_tester.ExpectMessagesReleasedViaReflection(
+ to_message, TestUtil::ReflectionTester::NOT_NULL);
+
+ // Another move to make sure that we can SetAllocated several times.
+ reflection_tester.SetAllocatedOptionalMessageFieldsToMessageViaReflection(
+ &from_message2, to_message);
+ reflection_tester.ExpectMessagesReleasedViaReflection(
+ to_message, TestUtil::ReflectionTester::NOT_NULL);
+
+ // After SetAllocatedOptionalMessageFieldsToNullViaReflection() we expect the
+ // releases to be NULL again.
+ reflection_tester.SetAllocatedOptionalMessageFieldsToNullViaReflection(
+ to_message);
+ reflection_tester.ExpectMessagesReleasedViaReflection(
+ to_message, TestUtil::ReflectionTester::IS_NULL);
+}
+
TEST(GeneratedMessageReflectionTest, AddRepeatedMessage) {
unittest::TestAllTypes message;
@@ -723,6 +794,59 @@ TEST(GeneratedMessageReflectionTest, SetAllocatedOneofMessageTest) {
delete released;
}
+TEST(GeneratedMessageReflectionTest, SetAllocatedOneofMessageOnArenaTest) {
+ unittest::TestOneof2 from_message1;
+ unittest::TestOneof2 from_message2;
+ ::google::protobuf::Arena arena;
+ unittest::TestOneof2* to_message =
+ ::google::protobuf::Arena::CreateMessage<unittest::TestOneof2>(&arena);
+ const Descriptor* descriptor = unittest::TestOneof2::descriptor();
+ const Reflection* reflection = to_message->GetReflection();
+
+ Message* released = reflection->ReleaseMessage(
+ to_message, descriptor->FindFieldByName("foo_lazy_message"));
+ EXPECT_TRUE(released == NULL);
+ released = reflection->ReleaseMessage(
+ to_message, descriptor->FindFieldByName("foo_message"));
+ EXPECT_TRUE(released == NULL);
+
+ TestUtil::ReflectionTester::SetOneofViaReflection(&from_message1);
+ TestUtil::ReflectionTester::ExpectOneofSetViaReflection(from_message1);
+
+ TestUtil::ReflectionTester::
+ SetAllocatedOptionalMessageFieldsToMessageViaReflection(
+ &from_message1, to_message);
+ const Message& sub_message = reflection->GetMessage(
+ *to_message, descriptor->FindFieldByName("foo_lazy_message"));
+ released = reflection->ReleaseMessage(
+ to_message, descriptor->FindFieldByName("foo_lazy_message"));
+ EXPECT_TRUE(released != NULL);
+ // Since sub_message is arena allocated, releasing it results in copying it
+ // into new heap-allocated memory.
+ EXPECT_NE(&sub_message, released);
+ delete released;
+
+ TestUtil::ReflectionTester::SetOneofViaReflection(&from_message2);
+
+ reflection->MutableMessage(
+ &from_message2, descriptor->FindFieldByName("foo_message"));
+
+ TestUtil::ReflectionTester::
+ SetAllocatedOptionalMessageFieldsToMessageViaReflection(
+ &from_message2, to_message);
+
+ const Message& sub_message2 = reflection->GetMessage(
+ *to_message, descriptor->FindFieldByName("foo_message"));
+ released = reflection->ReleaseMessage(
+ to_message, descriptor->FindFieldByName("foo_message"));
+ EXPECT_TRUE(released != NULL);
+ // Since sub_message2 is arena allocated, releasing it results in copying it
+ // into new heap-allocated memory.
+ EXPECT_NE(&sub_message2, released);
+ delete released;
+}
+
+
TEST(GeneratedMessageReflectionTest, ReleaseMessageTest) {
unittest::TestAllTypes message;
TestUtil::ReflectionTester reflection_tester(
diff --git a/src/google/protobuf/generated_message_table_driven.cc b/src/google/protobuf/generated_message_table_driven.cc
new file mode 100644
index 00000000..29af1ef6
--- /dev/null
+++ b/src/google/protobuf/generated_message_table_driven.cc
@@ -0,0 +1,103 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#include <google/protobuf/generated_message_table_driven.h>
+
+#include <google/protobuf/stubs/type_traits.h>
+
+#include <google/protobuf/generated_message_table_driven_lite.h>
+#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
+#include <google/protobuf/metadata.h>
+#include <google/protobuf/repeated_field.h>
+#include <google/protobuf/wire_format.h>
+#include <google/protobuf/wire_format_lite.h>
+#include <google/protobuf/wire_format_lite_inl.h>
+
+namespace google {
+namespace protobuf {
+namespace internal {
+
+namespace {
+
+UnknownFieldSet* MutableUnknownFields(MessageLite* msg, int64 arena_offset) {
+ return Raw<InternalMetadataWithArena>(msg, arena_offset)
+ ->mutable_unknown_fields();
+}
+
+struct UnknownFieldHandler {
+ static bool Skip(MessageLite* msg, const ParseTable& table,
+ io::CodedInputStream* input,
+ int tag) {
+ GOOGLE_DCHECK(table.unknown_field_set);
+
+ return WireFormat::SkipField(input, tag,
+ MutableUnknownFields(msg, table.arena_offset));
+ }
+
+ static void Varint(MessageLite* msg, const ParseTable& table,
+ int tag, int value) {
+ GOOGLE_DCHECK(table.unknown_field_set);
+
+ MutableUnknownFields(msg, table.arena_offset)->AddVarint(
+ WireFormatLite::GetTagFieldNumber(tag), value);
+ }
+
+ static bool ParseExtension(
+ MessageLite* msg, const ParseTable& table,
+ io::CodedInputStream* input, int tag) {
+ ExtensionSet* extensions = GetExtensionSet(msg, table.extension_offset);
+ if (extensions == NULL) {
+ return false;
+ }
+
+ const Message* prototype = down_cast<const Message*>(
+ table.default_instance());
+
+ GOOGLE_DCHECK(prototype != NULL);
+ GOOGLE_DCHECK(table.unknown_field_set);
+ UnknownFieldSet* unknown_fields =
+ MutableUnknownFields(msg, table.arena_offset);
+
+ return extensions->ParseField(tag, input, prototype, unknown_fields);
+ }
+};
+
+} // namespace
+
+bool MergePartialFromCodedStream(
+ MessageLite* msg, const ParseTable& table, io::CodedInputStream* input) {
+ return MergePartialFromCodedStreamImpl<UnknownFieldHandler,
+ InternalMetadataWithArena>(msg, table,
+ input);
+}
+
+} // namespace internal
+} // namespace protobuf
+} // namespace google
diff --git a/src/google/protobuf/generated_message_table_driven.h b/src/google/protobuf/generated_message_table_driven.h
new file mode 100644
index 00000000..6f3fe666
--- /dev/null
+++ b/src/google/protobuf/generated_message_table_driven.h
@@ -0,0 +1,219 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#ifndef GOOGLE_PROTOBUF_GENERATED_MESSAGE_TABLE_DRIVEN_H__
+#define GOOGLE_PROTOBUF_GENERATED_MESSAGE_TABLE_DRIVEN_H__
+
+#include <google/protobuf/map.h>
+#include <google/protobuf/map_entry_lite.h>
+#include <google/protobuf/map_field_lite.h>
+#include <google/protobuf/message_lite.h>
+#include <google/protobuf/wire_format_lite.h>
+#include <google/protobuf/wire_format_lite_inl.h>
+
+#if LANG_CXX11
+#define PROTOBUF_CONSTEXPR constexpr
+
+// We require C++11 and Clang to use constexpr for variables, as GCC 4.8
+// requires constexpr to be consistent between declarations of variables
+// unnecessarily (see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58541).
+// VS 2017 Update 3 also supports this usage of constexpr.
+#if defined(__clang__) || (defined(_MSC_VER) && _MSC_VER >= 1911)
+#define PROTOBUF_CONSTEXPR_VAR constexpr
+#else // !__clang__
+#define PROTOBUF_CONSTEXPR_VAR
+#endif // !_clang
+
+#else
+#define PROTOBUF_CONSTEXPR
+#define PROTOBUF_CONSTEXPR_VAR
+#endif
+
+namespace google {
+namespace protobuf {
+namespace internal {
+
+// Processing-type masks.
+static PROTOBUF_CONSTEXPR const unsigned char kOneofMask = 0x40;
+static PROTOBUF_CONSTEXPR const unsigned char kRepeatedMask = 0x20;
+// Mask for the raw type: either a WireFormatLite::FieldType or one of the
+// ProcessingTypes below, without the oneof or repeated flag.
+static PROTOBUF_CONSTEXPR const unsigned char kTypeMask = 0x1f;
+
+// Wire type masks.
+static PROTOBUF_CONSTEXPR const unsigned char kNotPackedMask = 0x10;
+static PROTOBUF_CONSTEXPR const unsigned char kInvalidMask = 0x20;
+
+enum ProcessingTypes {
+ TYPE_STRING_CORD = 19,
+ TYPE_STRING_STRING_PIECE = 20,
+ TYPE_BYTES_CORD = 21,
+ TYPE_BYTES_STRING_PIECE = 22,
+ TYPE_MAP = 23,
+};
+
+#if LANG_CXX11
+static_assert(TYPE_MAP < kRepeatedMask, "Invalid enum");
+#endif
+
+// TODO(ckennelly): Add a static assertion to ensure that these masks do not
+// conflict with wiretypes.
+
+// ParseTableField is kept small to help simplify instructions for computing
+// offsets, as we will always need this information to parse a field.
+// Additional data, needed for some types, is stored in
+// AuxillaryParseTableField.
+struct ParseTableField {
+ uint32 offset;
+ // The presence_index ordinarily represents a has_bit index, but for fields
+ // inside a oneof it represents the index in _oneof_case_.
+ uint32 presence_index;
+ unsigned char normal_wiretype;
+ unsigned char packed_wiretype;
+
+ // processing_type is given by:
+ // (FieldDescriptor->type() << 1) | FieldDescriptor->is_packed()
+ unsigned char processing_type;
+
+ unsigned char tag_size;
+};
+
+struct ParseTable;
+
+union AuxillaryParseTableField {
+ typedef bool (*EnumValidator)(int);
+
+ // Enums
+ struct enum_aux {
+ EnumValidator validator;
+ };
+ enum_aux enums;
+ // Group, messages
+ struct message_aux {
+ // ExplicitlyInitialized<T> -> T requires a reinterpret_cast, which prevents
+ // the tables from being constructed as a constexpr. We use void to avoid
+ // the cast.
+ const void* default_message_void;
+ const MessageLite* default_message() const {
+ return static_cast<const MessageLite*>(default_message_void);
+ }
+ const ParseTable* parse_table;
+ };
+ message_aux messages;
+ // Strings
+ struct string_aux {
+ const void* default_ptr;
+ const char* field_name;
+ };
+ string_aux strings;
+
+ struct map_aux {
+ bool (*parse_map)(io::CodedInputStream*, void*);
+ };
+ map_aux maps;
+
+#if LANG_CXX11
+ AuxillaryParseTableField() = default;
+#else
+ AuxillaryParseTableField() { }
+#endif
+ PROTOBUF_CONSTEXPR AuxillaryParseTableField(
+ AuxillaryParseTableField::enum_aux e) : enums(e) {}
+ PROTOBUF_CONSTEXPR AuxillaryParseTableField(
+ AuxillaryParseTableField::message_aux m) : messages(m) {}
+ PROTOBUF_CONSTEXPR AuxillaryParseTableField(
+ AuxillaryParseTableField::string_aux s) : strings(s) {}
+ PROTOBUF_CONSTEXPR AuxillaryParseTableField(
+ AuxillaryParseTableField::map_aux m)
+ : maps(m) {}
+};
+
+struct ParseTable {
+ const ParseTableField* fields;
+ const AuxillaryParseTableField* aux;
+ int max_field_number;
+ // TODO(ckennelly): Do something with this padding.
+
+ // TODO(ckennelly): Vet these for sign extension.
+ int64 has_bits_offset;
+ int64 oneof_case_offset;
+ int64 extension_offset;
+ int64 arena_offset;
+
+ // ExplicitlyInitialized<T> -> T requires a reinterpret_cast, which prevents
+ // the tables from being constructed as a constexpr. We use void to avoid
+ // the cast.
+ const void* default_instance_void;
+ const MessageLite* default_instance() const {
+ return static_cast<const MessageLite*>(default_instance_void);
+ }
+
+ bool unknown_field_set;
+};
+
+// TODO(jhen): Remove the __NVCC__ check when we get a version of nvcc that
+// supports these checks.
+#if LANG_CXX11 && !defined(__NVCC__)
+static_assert(sizeof(ParseTableField) <= 16, "ParseTableField is too large");
+// The tables must be composed of POD components to ensure link-time
+// initialization.
+static_assert(std::is_pod<ParseTableField>::value, "");
+static_assert(std::is_pod<AuxillaryParseTableField>::value, "");
+static_assert(std::is_pod<AuxillaryParseTableField::enum_aux>::value, "");
+static_assert(std::is_pod<AuxillaryParseTableField::message_aux>::value, "");
+static_assert(std::is_pod<AuxillaryParseTableField::string_aux>::value, "");
+static_assert(std::is_pod<ParseTable>::value, "");
+#endif
+
+// TODO(ckennelly): Consolidate these implementations into a single one, using
+// dynamic dispatch to the appropriate unknown field handler.
+bool MergePartialFromCodedStream(MessageLite* msg, const ParseTable& table,
+ io::CodedInputStream* input);
+bool MergePartialFromCodedStreamLite(MessageLite* msg, const ParseTable& table,
+ io::CodedInputStream* input);
+
+template <typename Entry>
+bool ParseMap(io::CodedInputStream* input, void* map_field) {
+ typedef typename MapEntryToMapField<Entry>::MapFieldType MapFieldType;
+ typedef google::protobuf::Map<typename Entry::EntryKeyType,
+ typename Entry::EntryValueType>
+ MapType;
+ typedef typename Entry::template Parser<MapFieldType, MapType> ParserType;
+
+ ParserType parser(static_cast<MapFieldType*>(map_field));
+ return ::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(input,
+ &parser);
+}
+
+} // namespace internal
+} // namespace protobuf
+
+} // namespace google
+#endif // GOOGLE_PROTOBUF_GENERATED_MESSAGE_TABLE_DRIVEN_H__
diff --git a/src/google/protobuf/generated_message_table_driven_lite.cc b/src/google/protobuf/generated_message_table_driven_lite.cc
new file mode 100644
index 00000000..90a50505
--- /dev/null
+++ b/src/google/protobuf/generated_message_table_driven_lite.cc
@@ -0,0 +1,109 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#include <google/protobuf/generated_message_table_driven_lite.h>
+
+#include <google/protobuf/stubs/type_traits.h>
+
+#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
+#include <google/protobuf/metadata_lite.h>
+#include <google/protobuf/repeated_field.h>
+#include <google/protobuf/wire_format_lite.h>
+#include <google/protobuf/wire_format_lite_inl.h>
+
+namespace google {
+namespace protobuf {
+namespace internal {
+
+namespace {
+
+string* MutableUnknownFields(MessageLite* msg, int64 arena_offset) {
+ return Raw<InternalMetadataWithArenaLite>(msg, arena_offset)
+ ->mutable_unknown_fields();
+}
+
+struct UnknownFieldHandlerLite {
+ static bool Skip(MessageLite* msg, const ParseTable& table,
+ io::CodedInputStream* input,
+ int tag) {
+ GOOGLE_DCHECK(!table.unknown_field_set);
+ ::google::protobuf::io::StringOutputStream unknown_fields_string(
+ MutableUnknownFields(msg, table.arena_offset));
+ ::google::protobuf::io::CodedOutputStream unknown_fields_stream(
+ &unknown_fields_string, false);
+
+ return ::google::protobuf::internal::WireFormatLite::SkipField(
+ input, tag, &unknown_fields_stream);
+ }
+
+ static void Varint(MessageLite* msg, const ParseTable& table,
+ int tag, int value) {
+ GOOGLE_DCHECK(!table.unknown_field_set);
+
+ ::google::protobuf::io::StringOutputStream unknown_fields_string(
+ MutableUnknownFields(msg, table.arena_offset));
+ ::google::protobuf::io::CodedOutputStream unknown_fields_stream(
+ &unknown_fields_string, false);
+ unknown_fields_stream.WriteVarint32(tag);
+ unknown_fields_stream.WriteVarint32(value);
+ }
+
+ static bool ParseExtension(
+ MessageLite* msg, const ParseTable& table,
+ io::CodedInputStream* input, int tag) {
+ ExtensionSet* extensions = GetExtensionSet(msg, table.extension_offset);
+ if (extensions == NULL) {
+ return false;
+ }
+
+ const MessageLite* prototype = table.default_instance();
+
+ GOOGLE_DCHECK(!table.unknown_field_set);
+ ::google::protobuf::io::StringOutputStream unknown_fields_string(
+ MutableUnknownFields(msg, table.arena_offset));
+ ::google::protobuf::io::CodedOutputStream unknown_fields_stream(
+ &unknown_fields_string, false);
+ return extensions->ParseField(
+ tag, input, prototype, &unknown_fields_stream);
+ }
+};
+
+} // namespace
+
+bool MergePartialFromCodedStreamLite(
+ MessageLite* msg, const ParseTable& table, io::CodedInputStream* input) {
+ return MergePartialFromCodedStreamImpl<UnknownFieldHandlerLite,
+ InternalMetadataWithArenaLite>(
+ msg, table, input);
+}
+
+} // namespace internal
+} // namespace protobuf
+} // namespace google
diff --git a/src/google/protobuf/generated_message_table_driven_lite.h b/src/google/protobuf/generated_message_table_driven_lite.h
new file mode 100644
index 00000000..20b4da21
--- /dev/null
+++ b/src/google/protobuf/generated_message_table_driven_lite.h
@@ -0,0 +1,823 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#ifndef GOOGLE_PROTOBUF_GENERATED_MESSAGE_TABLE_DRIVEN_LITE_H__
+#define GOOGLE_PROTOBUF_GENERATED_MESSAGE_TABLE_DRIVEN_LITE_H__
+
+#include <google/protobuf/generated_message_table_driven.h>
+
+#include <google/protobuf/stubs/type_traits.h>
+
+#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
+#include <google/protobuf/extension_set.h>
+#include <google/protobuf/metadata_lite.h>
+#include <google/protobuf/repeated_field.h>
+#include <google/protobuf/wire_format_lite.h>
+#include <google/protobuf/wire_format_lite_inl.h>
+
+
+namespace google {
+namespace protobuf {
+namespace internal {
+
+
+enum StringType {
+ StringType_STRING = 0,
+ StringType_CORD = 1,
+ StringType_STRING_PIECE = 2
+};
+
+// Logically a superset of StringType, consisting of all field types that
+// require special initialization.
+enum ProcessingType {
+ ProcessingType_STRING = 0,
+ ProcessingType_CORD = 1,
+ ProcessingType_STRING_PIECE = 2,
+ ProcessingType_MESSAGE = 3
+};
+
+enum Cardinality {
+ Cardinality_SINGULAR = 0,
+ Cardinality_REPEATED = 1,
+ Cardinality_ONEOF = 3
+};
+
+template <typename Type>
+inline Type* Raw(MessageLite* msg, int64 offset) {
+ return reinterpret_cast<Type*>(reinterpret_cast<uint8*>(msg) + offset);
+}
+
+template <typename Type>
+inline const Type* Raw(const MessageLite* msg, int64 offset) {
+ return reinterpret_cast<const Type*>(reinterpret_cast<const uint8*>(msg) +
+ offset);
+}
+
+template <typename InternalMetadata>
+inline Arena* GetArena(MessageLite* msg, int64 arena_offset) {
+ if (GOOGLE_PREDICT_FALSE(arena_offset == -1)) {
+ return NULL;
+ }
+
+ return Raw<InternalMetadata>(msg, arena_offset)->arena();
+}
+
+inline ExtensionSet* GetExtensionSet(MessageLite* msg, int64 extension_offset) {
+ if (extension_offset == -1) {
+ return NULL;
+ }
+
+ return Raw<ExtensionSet>(msg, extension_offset);
+}
+
+template <typename Type>
+inline Type* AddField(MessageLite* msg, int64 offset) {
+#if LANG_CXX11
+ static_assert(has_trivial_copy<Type>::value,
+ "Do not assign");
+#endif
+
+ google::protobuf::RepeatedField<Type>* repeated =
+ Raw<google::protobuf::RepeatedField<Type> >(msg, offset);
+ return repeated->Add();
+}
+
+template <>
+inline string* AddField<string>(MessageLite* msg, int64 offset) {
+ google::protobuf::RepeatedPtrField<string>* repeated =
+ Raw<google::protobuf::RepeatedPtrField<string> >(msg, offset);
+ return repeated->Add();
+}
+
+
+template <typename Type>
+inline void AddField(MessageLite* msg, int64 offset, Type value) {
+#if LANG_CXX11
+ static_assert(has_trivial_copy<Type>::value,
+ "Do not assign");
+#endif
+ *AddField<Type>(msg, offset) = value;
+}
+
+inline void SetBit(uint32* has_bits, uint32 has_bit_index) {
+ GOOGLE_DCHECK(has_bits != NULL);
+
+ uint32 mask = static_cast<uint32>(1u) << (has_bit_index % 32);
+ has_bits[has_bit_index / 32u] |= mask;
+}
+
+template <typename Type>
+inline Type* MutableField(MessageLite* msg, uint32* has_bits,
+ uint32 has_bit_index, int64 offset) {
+ SetBit(has_bits, has_bit_index);
+ return Raw<Type>(msg, offset);
+}
+
+template <typename Type>
+inline void SetField(MessageLite* msg, uint32* has_bits, uint32 has_bit_index,
+ int64 offset, Type value) {
+#if LANG_CXX11
+ static_assert(has_trivial_copy<Type>::value,
+ "Do not assign");
+#endif
+ *MutableField<Type>(msg, has_bits, has_bit_index, offset) = value;
+}
+
+template <typename Type>
+inline void SetOneofField(MessageLite* msg, uint32* oneof_case,
+ uint32 oneof_case_index, int64 offset,
+ int field_number, Type value) {
+ oneof_case[oneof_case_index] = field_number;
+ *Raw<Type>(msg, offset) = value;
+}
+
+// Clears a oneof field. The field argument should correspond to the particular
+// field that is currently set in the oneof.
+inline void ClearOneofField(const ParseTableField& field, Arena* arena,
+ MessageLite* msg) {
+ switch (field.processing_type & kTypeMask) {
+ case WireFormatLite::TYPE_MESSAGE:
+ if (arena == NULL) {
+ delete *Raw<MessageLite*>(msg, field.offset);
+ }
+ break;
+
+ case WireFormatLite::TYPE_STRING:
+ case WireFormatLite::TYPE_BYTES:
+ Raw<ArenaStringPtr>(msg, field.offset)
+ ->Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena);
+ break;
+
+ default:
+ // No cleanup needed.
+ break;
+ }
+}
+
+// Clears and reinitializes a oneof field as necessary, in preparation for
+// parsing a new value with type field_type and field number field_number.
+//
+// Note: the oneof_case argument should point directly to the _oneof_case_
+// element corresponding to this particular oneof, not to the beginning of the
+// _oneof_case_ array.
+template <ProcessingType field_type>
+inline void ResetOneofField(const ParseTable& table, int field_number,
+ Arena* arena, MessageLite* msg, uint32* oneof_case,
+ int64 offset, const void* default_ptr) {
+ if (*oneof_case == field_number) {
+ // The oneof is already set to the right type, so there is no need to clear
+ // it.
+ return;
+ }
+
+ if (*oneof_case != 0) {
+ ClearOneofField(table.fields[*oneof_case], arena, msg);
+ }
+ *oneof_case = field_number;
+
+ switch (field_type) {
+ case ProcessingType_STRING:
+ Raw<ArenaStringPtr>(msg, offset)
+ ->UnsafeSetDefault(static_cast<const string*>(default_ptr));
+ break;
+ case ProcessingType_MESSAGE:
+ MessageLite** submessage = Raw<MessageLite*>(msg, offset);
+ const MessageLite* prototype =
+ table.aux[field_number].messages.default_message();
+ *submessage = prototype->New(arena);
+ break;
+ }
+}
+
+template <Cardinality cardinality, bool validate, StringType ctype>
+static inline bool HandleString(io::CodedInputStream* input, MessageLite* msg,
+ Arena* arena, uint32* has_bits,
+ uint32 has_bit_index, int64 offset,
+ const void* default_ptr,
+ const char* field_name) {
+#ifdef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
+ const char* sdata;
+ size_t size;
+#endif
+
+ string* value;
+ switch (cardinality) {
+ case Cardinality_SINGULAR:
+ // TODO(ckennelly): Is this optimal?
+ value =
+ MutableField<ArenaStringPtr>(msg, has_bits, has_bit_index, offset)
+ ->Mutable(static_cast<const string*>(default_ptr), arena);
+ break;
+ case Cardinality_REPEATED:
+ value = AddField<string>(msg, offset);
+ break;
+ case Cardinality_ONEOF:
+ value = Raw<ArenaStringPtr>(msg, offset)
+ ->Mutable(static_cast<const string*>(default_ptr), arena);
+ break;
+ }
+ GOOGLE_DCHECK(value != NULL);
+
+ if (GOOGLE_PREDICT_FALSE(!WireFormatLite::ReadString(input, value))) {
+ return false;
+ }
+
+#ifdef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
+ sdata = value->data();
+ size = value->size();
+#endif
+
+#ifdef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
+ if (validate) {
+ WireFormatLite::VerifyUtf8String(sdata, size, WireFormatLite::PARSE,
+ field_name);
+ }
+#endif
+
+ return true;
+}
+
+template <typename UnknownFieldHandler, typename InternalMetadata,
+ Cardinality cardinality>
+inline bool HandleEnum(const ParseTable& table, io::CodedInputStream* input,
+ MessageLite* msg, uint32* presence,
+ uint32 presence_index, int64 offset, uint32 tag,
+ int field_number) {
+ int value;
+ if (GOOGLE_PREDICT_FALSE(
+ (!WireFormatLite::ReadPrimitive<int, WireFormatLite::TYPE_ENUM>(
+ input, &value)))) {
+ return false;
+ }
+
+ AuxillaryParseTableField::EnumValidator validator =
+ table.aux[field_number].enums.validator;
+ if (validator(value)) {
+ switch (cardinality) {
+ case Cardinality_SINGULAR:
+ SetField(msg, presence, presence_index, offset, value);
+ break;
+ case Cardinality_REPEATED:
+ AddField(msg, offset, value);
+ break;
+ case Cardinality_ONEOF:
+ ClearOneofField(table.fields[presence[presence_index]],
+ GetArena<InternalMetadata>(msg, table.arena_offset),
+ msg);
+ SetOneofField(msg, presence, presence_index, offset, field_number,
+ value);
+ break;
+ }
+ } else {
+ UnknownFieldHandler::Varint(msg, table, tag, value);
+ }
+
+ return true;
+}
+
+// RepeatedMessageTypeHandler allows us to operate on RepeatedPtrField fields
+// without instantiating the specific template.
+class RepeatedMessageTypeHandler {
+ public:
+ typedef MessageLite Type;
+ static Arena* GetArena(Type* t) { return t->GetArena(); }
+ static void* GetMaybeArenaPointer(Type* t) {
+ return t->GetMaybeArenaPointer();
+ }
+ static inline Type* NewFromPrototype(const Type* prototype,
+ Arena* arena = NULL) {
+ return prototype->New(arena);
+ }
+ static void Delete(Type* t, Arena* arena = NULL) {
+ if (arena == NULL) {
+ delete t;
+ }
+ }
+};
+
+inline bool ReadGroup(int field_number, io::CodedInputStream* input,
+ MessageLite* value) {
+ if (GOOGLE_PREDICT_FALSE(!input->IncrementRecursionDepth())) {
+ return false;
+ }
+
+ if (GOOGLE_PREDICT_FALSE(!value->MergePartialFromCodedStream(input))) {
+ return false;
+ }
+
+ input->DecrementRecursionDepth();
+ // Make sure the last thing read was an end tag for this group.
+ if (GOOGLE_PREDICT_FALSE(!input->LastTagWas(WireFormatLite::MakeTag(
+ field_number, WireFormatLite::WIRETYPE_END_GROUP)))) {
+ return false;
+ }
+
+ return true;
+}
+
+inline bool ReadMessage(io::CodedInputStream* input, MessageLite* value) {
+ int length;
+ if (GOOGLE_PREDICT_FALSE(!input->ReadVarintSizeAsInt(&length))) {
+ return false;
+ }
+
+ std::pair<io::CodedInputStream::Limit, int> p =
+ input->IncrementRecursionDepthAndPushLimit(length);
+ if (GOOGLE_PREDICT_FALSE(p.second < 0 ||
+ !value->MergePartialFromCodedStream(input))) {
+ return false;
+ }
+
+ // Make sure that parsing stopped when the limit was hit, not at an endgroup
+ // tag.
+ return input->DecrementRecursionDepthAndPopLimit(p.first);
+}
+
+class MergePartialFromCodedStreamHelper {
+ public:
+ static MessageLite* Add(RepeatedPtrFieldBase* field,
+ const MessageLite* prototype) {
+ return field->Add<RepeatedMessageTypeHandler>(
+ const_cast<MessageLite*>(prototype));
+ }
+};
+
+template <typename UnknownFieldHandler, typename InternalMetadata>
+bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
+ io::CodedInputStream* input) {
+ // We require that has_bits are present, as to avoid having to check for them
+ // for every field.
+ //
+ // TODO(ckennelly): Make this a compile-time parameter with templates.
+ GOOGLE_DCHECK_GE(table.has_bits_offset, 0);
+ uint32* has_bits = Raw<uint32>(msg, table.has_bits_offset);
+ GOOGLE_DCHECK(has_bits != NULL);
+
+ while (true) {
+ uint32 tag = input->ReadTag();
+
+ const WireFormatLite::WireType wire_type =
+ WireFormatLite::GetTagWireType(tag);
+ const int field_number = WireFormatLite::GetTagFieldNumber(tag);
+
+ if (field_number > table.max_field_number) {
+ // check for possible extensions
+ if (UnknownFieldHandler::ParseExtension(msg, table, input, tag)) {
+ // successfully parsed
+ continue;
+ }
+
+ if (GOOGLE_PREDICT_FALSE(!UnknownFieldHandler::Skip(msg, table, input, tag))) {
+ return false;
+ }
+
+ continue;
+ }
+
+ // We implicitly verify that data points to a valid field as we check the
+ // wire types. Entries in table.fields[i] that do not correspond to valid
+ // field numbers have their normal_wiretype and packed_wiretype fields set
+ // with the kInvalidMask value. As wire_type cannot take on that value, we
+ // will never match.
+ const ParseTableField* data = table.fields + field_number;
+
+ // TODO(ckennelly): Avoid sign extension
+ const int64 presence_index = data->presence_index;
+ const int64 offset = data->offset;
+ const unsigned char processing_type = data->processing_type;
+
+ if (data->normal_wiretype == static_cast<unsigned char>(wire_type)) {
+ // TODO(ckennelly): Use a computed goto on GCC/LLVM or otherwise eliminate
+ // the bounds check on processing_type.
+
+ switch (processing_type) {
+#define HANDLE_TYPE(TYPE, CPPTYPE) \
+ case (WireFormatLite::TYPE_##TYPE): { \
+ CPPTYPE value; \
+ if (GOOGLE_PREDICT_FALSE( \
+ (!WireFormatLite::ReadPrimitive< \
+ CPPTYPE, WireFormatLite::TYPE_##TYPE>(input, &value)))) { \
+ return false; \
+ } \
+ SetField(msg, has_bits, presence_index, offset, value); \
+ break; \
+ } \
+ case (WireFormatLite::TYPE_##TYPE) | kRepeatedMask: { \
+ google::protobuf::RepeatedField<CPPTYPE>* values = \
+ Raw<google::protobuf::RepeatedField<CPPTYPE> >(msg, offset); \
+ if (GOOGLE_PREDICT_FALSE((!WireFormatLite::ReadRepeatedPrimitive< \
+ CPPTYPE, WireFormatLite::TYPE_##TYPE>( \
+ data->tag_size, tag, input, values)))) { \
+ return false; \
+ } \
+ break; \
+ } \
+ case (WireFormatLite::TYPE_##TYPE) | kOneofMask: { \
+ uint32* oneof_case = Raw<uint32>(msg, table.oneof_case_offset); \
+ CPPTYPE value; \
+ if (GOOGLE_PREDICT_FALSE( \
+ (!WireFormatLite::ReadPrimitive< \
+ CPPTYPE, WireFormatLite::TYPE_##TYPE>(input, &value)))) { \
+ return false; \
+ } \
+ ClearOneofField(table.fields[oneof_case[presence_index]], \
+ GetArena<InternalMetadata>(msg, table.arena_offset), msg); \
+ SetOneofField(msg, oneof_case, presence_index, offset, field_number, \
+ value); \
+ break; \
+ }
+
+ HANDLE_TYPE(INT32, int32)
+ HANDLE_TYPE(INT64, int64)
+ HANDLE_TYPE(SINT32, int32)
+ HANDLE_TYPE(SINT64, int64)
+ HANDLE_TYPE(UINT32, uint32)
+ HANDLE_TYPE(UINT64, uint64)
+
+ HANDLE_TYPE(FIXED32, uint32)
+ HANDLE_TYPE(FIXED64, uint64)
+ HANDLE_TYPE(SFIXED32, int32)
+ HANDLE_TYPE(SFIXED64, int64)
+
+ HANDLE_TYPE(FLOAT, float)
+ HANDLE_TYPE(DOUBLE, double)
+
+ HANDLE_TYPE(BOOL, bool)
+#undef HANDLE_TYPE
+ case WireFormatLite::TYPE_BYTES:
+#ifndef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
+ case WireFormatLite::TYPE_STRING:
+#endif
+ {
+ Arena* const arena =
+ GetArena<InternalMetadata>(msg, table.arena_offset);
+ const void* default_ptr = table.aux[field_number].strings.default_ptr;
+
+ if (GOOGLE_PREDICT_FALSE((
+ !HandleString<Cardinality_SINGULAR, false, StringType_STRING>(
+ input, msg, arena, has_bits, presence_index, offset,
+ default_ptr, NULL)))) {
+ return false;
+ }
+ break;
+ }
+ case WireFormatLite::TYPE_BYTES | kOneofMask:
+#ifndef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
+ case WireFormatLite::TYPE_STRING | kOneofMask:
+#endif
+ {
+ Arena* const arena =
+ GetArena<InternalMetadata>(msg, table.arena_offset);
+ uint32* oneof_case = Raw<uint32>(msg, table.oneof_case_offset);
+ const void* default_ptr = table.aux[field_number].strings.default_ptr;
+
+ ResetOneofField<ProcessingType_STRING>(
+ table, field_number, arena, msg, oneof_case + presence_index,
+ offset, default_ptr);
+
+ if (GOOGLE_PREDICT_FALSE(
+ (!HandleString<Cardinality_ONEOF, false, StringType_STRING>(
+ input, msg, arena, has_bits, presence_index, offset,
+ default_ptr, NULL)))) {
+ return false;
+ }
+ break;
+ }
+ case (WireFormatLite::TYPE_BYTES) | kRepeatedMask:
+#ifndef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
+ case (WireFormatLite::TYPE_STRING) | kRepeatedMask:
+#endif
+ {
+ Arena* const arena =
+ GetArena<InternalMetadata>(msg, table.arena_offset);
+ const void* default_ptr =
+ table.aux[field_number].strings.default_ptr;
+
+ if (GOOGLE_PREDICT_FALSE((
+ !HandleString<Cardinality_REPEATED, false, StringType_STRING>(
+ input, msg, arena, has_bits, presence_index, offset,
+ default_ptr, NULL)))) {
+ return false;
+ }
+ break;
+ }
+#ifdef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
+ case (WireFormatLite::TYPE_STRING): {
+ Arena* const arena =
+ GetArena<InternalMetadata>(msg, table.arena_offset);
+ const void* default_ptr = table.aux[field_number].strings.default_ptr;
+ const char* field_name = table.aux[field_number].strings.field_name;
+
+ if (GOOGLE_PREDICT_FALSE(
+ (!HandleString<Cardinality_SINGULAR, true, StringType_STRING>(
+ input, msg, arena, has_bits, presence_index, offset,
+ default_ptr, field_name)))) {
+ return false;
+ }
+ break;
+ }
+ case (WireFormatLite::TYPE_STRING) | kRepeatedMask: {
+ Arena* const arena =
+ GetArena<InternalMetadata>(msg, table.arena_offset);
+ const void* default_ptr = table.aux[field_number].strings.default_ptr;
+ const char* field_name = table.aux[field_number].strings.field_name;
+
+ if (GOOGLE_PREDICT_FALSE(
+ (!HandleString<Cardinality_REPEATED, true, StringType_STRING>(
+ input, msg, arena, has_bits, presence_index, offset,
+ default_ptr, field_name)))) {
+ return false;
+ }
+ break;
+ }
+ case (WireFormatLite::TYPE_STRING) | kOneofMask: {
+ Arena* const arena =
+ GetArena<InternalMetadata>(msg, table.arena_offset);
+ uint32* oneof_case = Raw<uint32>(msg, table.oneof_case_offset);
+ const void* default_ptr = table.aux[field_number].strings.default_ptr;
+ const char* field_name = table.aux[field_number].strings.field_name;
+
+ ResetOneofField<ProcessingType_STRING>(
+ table, field_number, arena, msg, oneof_case + presence_index,
+ offset, default_ptr);
+
+ if (GOOGLE_PREDICT_FALSE(
+ (!HandleString<Cardinality_ONEOF, true, StringType_STRING>(
+ input, msg, arena, has_bits, presence_index, offset,
+ default_ptr, field_name)))) {
+ return false;
+ }
+ break;
+ }
+#endif
+ case WireFormatLite::TYPE_ENUM: {
+ if (GOOGLE_PREDICT_FALSE((!HandleEnum<UnknownFieldHandler, InternalMetadata,
+ Cardinality_SINGULAR>(
+ table, input, msg, has_bits, presence_index, offset, tag,
+ field_number)))) {
+ return false;
+ }
+ break;
+ }
+ case WireFormatLite::TYPE_ENUM | kRepeatedMask: {
+ if (GOOGLE_PREDICT_FALSE((!HandleEnum<UnknownFieldHandler, InternalMetadata,
+ Cardinality_REPEATED>(
+ table, input, msg, has_bits, presence_index, offset, tag,
+ field_number)))) {
+ return false;
+ }
+ break;
+ }
+ case WireFormatLite::TYPE_ENUM | kOneofMask: {
+ uint32* oneof_case = Raw<uint32>(msg, table.oneof_case_offset);
+ if (GOOGLE_PREDICT_FALSE((!HandleEnum<UnknownFieldHandler, InternalMetadata,
+ Cardinality_ONEOF>(
+ table, input, msg, oneof_case, presence_index, offset, tag,
+ field_number)))) {
+ return false;
+ }
+ break;
+ }
+ case WireFormatLite::TYPE_GROUP: {
+ MessageLite** submsg_holder =
+ MutableField<MessageLite*>(msg, has_bits, presence_index, offset);
+ MessageLite* submsg = *submsg_holder;
+
+ if (submsg == NULL) {
+ Arena* const arena =
+ GetArena<InternalMetadata>(msg, table.arena_offset);
+ const MessageLite* prototype =
+ table.aux[field_number].messages.default_message();
+ submsg = prototype->New(arena);
+ *submsg_holder = submsg;
+ }
+
+ if (GOOGLE_PREDICT_FALSE(!WireFormatLite::ReadGroup(
+ field_number, input, submsg))) {
+ return false;
+ }
+
+ break;
+ }
+ case WireFormatLite::TYPE_GROUP | kRepeatedMask: {
+ RepeatedPtrFieldBase* field = Raw<RepeatedPtrFieldBase>(msg, offset);
+ const MessageLite* prototype =
+ table.aux[field_number].messages.default_message();
+ GOOGLE_DCHECK(prototype != NULL);
+
+ MessageLite* submsg =
+ MergePartialFromCodedStreamHelper::Add(field, prototype);
+
+ if (GOOGLE_PREDICT_FALSE(!WireFormatLite::ReadGroup(
+ field_number, input, submsg))) {
+ return false;
+ }
+
+ break;
+ }
+ case WireFormatLite::TYPE_MESSAGE: {
+ MessageLite** submsg_holder =
+ MutableField<MessageLite*>(msg, has_bits, presence_index, offset);
+ MessageLite* submsg = *submsg_holder;
+
+ if (submsg == NULL) {
+ Arena* const arena =
+ GetArena<InternalMetadata>(msg, table.arena_offset);
+ const MessageLite* prototype =
+ table.aux[field_number].messages.default_message();
+ submsg = prototype->New(arena);
+ *submsg_holder = submsg;
+ }
+
+ if (GOOGLE_PREDICT_FALSE(!WireFormatLite::ReadMessage(input, submsg))) {
+ return false;
+ }
+
+ break;
+ }
+ // TODO(ckennelly): Adapt ReadMessageNoVirtualNoRecursionDepth and
+ // manage input->IncrementRecursionDepth() here.
+ case WireFormatLite::TYPE_MESSAGE | kRepeatedMask: {
+ RepeatedPtrFieldBase* field = Raw<RepeatedPtrFieldBase>(msg, offset);
+ const MessageLite* prototype =
+ table.aux[field_number].messages.default_message();
+ GOOGLE_DCHECK(prototype != NULL);
+
+ MessageLite* submsg =
+ MergePartialFromCodedStreamHelper::Add(field, prototype);
+
+ if (GOOGLE_PREDICT_FALSE(!WireFormatLite::ReadMessage(input, submsg))) {
+ return false;
+ }
+
+ break;
+ }
+ case WireFormatLite::TYPE_MESSAGE | kOneofMask: {
+ Arena* const arena =
+ GetArena<InternalMetadata>(msg, table.arena_offset);
+ uint32* oneof_case = Raw<uint32>(msg, table.oneof_case_offset);
+ MessageLite** submsg_holder = Raw<MessageLite*>(msg, offset);
+ ResetOneofField<ProcessingType_MESSAGE>(
+ table, field_number, arena, msg, oneof_case + presence_index,
+ offset, NULL);
+ MessageLite* submsg = *submsg_holder;
+
+ if (GOOGLE_PREDICT_FALSE(!WireFormatLite::ReadMessage(input, submsg))) {
+ return false;
+ }
+
+ break;
+ }
+ case TYPE_MAP: {
+ if (GOOGLE_PREDICT_FALSE(!(*table.aux[field_number].maps.parse_map)(
+ input, Raw<void>(msg, offset)))) {
+ return false;
+ }
+ break;
+ }
+ case 0: {
+ // Done.
+ return true;
+ }
+ default:
+ break;
+ }
+ } else if (data->packed_wiretype == static_cast<unsigned char>(wire_type)) {
+ // Non-packable fields have their packed_wiretype masked with
+ // kNotPackedMask, which is impossible to match here.
+ GOOGLE_DCHECK(processing_type & kRepeatedMask);
+ GOOGLE_DCHECK_NE(processing_type, kRepeatedMask);
+ GOOGLE_DCHECK_EQ(0, processing_type & kOneofMask);
+
+
+
+ // TODO(ckennelly): Use a computed goto on GCC/LLVM.
+ //
+ // Mask out kRepeatedMask bit, allowing the jump table to be smaller.
+ switch (static_cast<WireFormatLite::FieldType>(
+ processing_type ^ kRepeatedMask)) {
+#define HANDLE_PACKED_TYPE(TYPE, CPPTYPE, CPPTYPE_METHOD) \
+ case WireFormatLite::TYPE_##TYPE: { \
+ google::protobuf::RepeatedField<CPPTYPE>* values = \
+ Raw<google::protobuf::RepeatedField<CPPTYPE> >(msg, offset); \
+ if (GOOGLE_PREDICT_FALSE( \
+ (!WireFormatLite::ReadPackedPrimitive< \
+ CPPTYPE, WireFormatLite::TYPE_##TYPE>(input, values)))) { \
+ return false; \
+ } \
+ break; \
+ }
+
+ HANDLE_PACKED_TYPE(INT32, int32, Int32)
+ HANDLE_PACKED_TYPE(INT64, int64, Int64)
+ HANDLE_PACKED_TYPE(SINT32, int32, Int32)
+ HANDLE_PACKED_TYPE(SINT64, int64, Int64)
+ HANDLE_PACKED_TYPE(UINT32, uint32, UInt32)
+ HANDLE_PACKED_TYPE(UINT64, uint64, UInt64)
+
+ HANDLE_PACKED_TYPE(FIXED32, uint32, UInt32)
+ HANDLE_PACKED_TYPE(FIXED64, uint64, UInt64)
+ HANDLE_PACKED_TYPE(SFIXED32, int32, Int32)
+ HANDLE_PACKED_TYPE(SFIXED64, int64, Int64)
+
+ HANDLE_PACKED_TYPE(FLOAT, float, Float)
+ HANDLE_PACKED_TYPE(DOUBLE, double, Double)
+
+ HANDLE_PACKED_TYPE(BOOL, bool, Bool)
+#undef HANDLE_PACKED_TYPE
+ case WireFormatLite::TYPE_ENUM: {
+ // To avoid unnecessarily calling MutableUnknownFields (which mutates
+ // InternalMetadataWithArena) when all inputs in the repeated series
+ // are valid, we implement our own parser rather than call
+ // WireFormat::ReadPackedEnumPreserveUnknowns.
+ uint32 length;
+ if (GOOGLE_PREDICT_FALSE(!input->ReadVarint32(&length))) {
+ return false;
+ }
+
+ AuxillaryParseTableField::EnumValidator validator =
+ table.aux[field_number].enums.validator;
+ google::protobuf::RepeatedField<int>* values =
+ Raw<google::protobuf::RepeatedField<int> >(msg, offset);
+
+ io::CodedInputStream::Limit limit = input->PushLimit(length);
+ while (input->BytesUntilLimit() > 0) {
+ int value;
+ if (GOOGLE_PREDICT_FALSE(
+ (!google::protobuf::internal::WireFormatLite::ReadPrimitive<
+ int, WireFormatLite::TYPE_ENUM>(input, &value)))) {
+ return false;
+ }
+
+ if (validator(value)) {
+ values->Add(value);
+ } else {
+ // TODO(ckennelly): Consider caching here.
+ UnknownFieldHandler::Varint(msg, table, tag, value);
+ }
+ }
+ input->PopLimit(limit);
+
+ break;
+ }
+ case WireFormatLite::TYPE_STRING:
+ case WireFormatLite::TYPE_GROUP:
+ case WireFormatLite::TYPE_MESSAGE:
+ case WireFormatLite::TYPE_BYTES:
+ GOOGLE_DCHECK(false);
+ return false;
+ default:
+ break;
+ }
+ } else {
+ if (wire_type == WireFormatLite::WIRETYPE_END_GROUP) {
+ // Must be the end of the message.
+ return true;
+ }
+
+ // check for possible extensions
+ if (UnknownFieldHandler::ParseExtension(msg, table, input, tag)) {
+ // successfully parsed
+ continue;
+ }
+
+ // process unknown field.
+ if (GOOGLE_PREDICT_FALSE(!UnknownFieldHandler::Skip(msg, table, input, tag))) {
+ return false;
+ }
+ }
+ }
+}
+
+} // namespace internal
+} // namespace protobuf
+
+} // namespace google
+#endif // GOOGLE_PROTOBUF_GENERATED_MESSAGE_TABLE_DRIVEN_LITE_H__
diff --git a/src/google/protobuf/generated_message_util.cc b/src/google/protobuf/generated_message_util.cc
index b4d2c9c1..15d84222 100644
--- a/src/google/protobuf/generated_message_util.cc
+++ b/src/google/protobuf/generated_message_util.cc
@@ -35,12 +35,25 @@
#include <google/protobuf/generated_message_util.h>
#include <limits>
+#include <vector>
+#include <google/protobuf/io/coded_stream_inl.h>
+#include <google/protobuf/io/coded_stream.h>
+#include <google/protobuf/arenastring.h>
+#include <google/protobuf/extension_set.h>
+#include <google/protobuf/message_lite.h>
+#include <google/protobuf/metadata_lite.h>
+#include <google/protobuf/stubs/port.h>
+#include <google/protobuf/repeated_field.h>
+#include <google/protobuf/wire_format_lite.h>
+#include <google/protobuf/wire_format_lite_inl.h>
namespace google {
+
namespace protobuf {
namespace internal {
+
double Infinity() {
return std::numeric_limits<double>::infinity();
}
@@ -51,14 +64,14 @@ double NaN() {
ExplicitlyConstructed< ::std::string> fixed_address_empty_string;
GOOGLE_PROTOBUF_DECLARE_ONCE(empty_string_once_init_);
-void DeleteEmptyString() { fixed_address_empty_string.Shutdown(); }
+void DeleteEmptyString() { fixed_address_empty_string.Destruct(); }
void InitEmptyString() {
fixed_address_empty_string.DefaultConstruct();
OnShutdown(&DeleteEmptyString);
}
-int StringSpaceUsedExcludingSelf(const string& str) {
+size_t StringSpaceUsedExcludingSelfLong(const string& str) {
const void* start = &str;
const void* end = &str + 1;
if (start <= str.data() && str.data() < end) {
@@ -75,6 +88,643 @@ void InitProtobufDefaults() {
GetEmptyString();
}
+template <typename T>
+const T& Get(const void* ptr) {
+ return *static_cast<const T*>(ptr);
+}
+
+// PrimitiveTypeHelper is a wrapper around the interface of WireFormatLite.
+// WireFormatLite has a very inconvenient interface with respect to template
+// meta-programming. This class wraps the different named functions into
+// a single Serialize / SerializeToArray interface.
+template <int type>
+struct PrimitiveTypeHelper;
+
+template <>
+struct PrimitiveTypeHelper<WireFormatLite::TYPE_BOOL> {
+ typedef bool Type;
+ static void Serialize(const void* ptr,
+ ::google::protobuf::io::CodedOutputStream* output) {
+ WireFormatLite::WriteBoolNoTag(Get<bool>(ptr), output);
+ }
+ static uint8* SerializeToArray(const void* ptr, uint8* buffer) {
+ return WireFormatLite::WriteBoolNoTagToArray(Get<Type>(ptr), buffer);
+ }
+};
+
+template <>
+struct PrimitiveTypeHelper<WireFormatLite::TYPE_INT32> {
+ typedef int32 Type;
+ static void Serialize(const void* ptr,
+ ::google::protobuf::io::CodedOutputStream* output) {
+ WireFormatLite::WriteInt32NoTag(Get<int32>(ptr), output);
+ }
+ static uint8* SerializeToArray(const void* ptr, uint8* buffer) {
+ return WireFormatLite::WriteInt32NoTagToArray(Get<Type>(ptr), buffer);
+ }
+};
+
+template <>
+struct PrimitiveTypeHelper<WireFormatLite::TYPE_SINT32> {
+ typedef int32 Type;
+ static void Serialize(const void* ptr,
+ ::google::protobuf::io::CodedOutputStream* output) {
+ WireFormatLite::WriteSInt32NoTag(Get<int32>(ptr), output);
+ }
+ static uint8* SerializeToArray(const void* ptr, uint8* buffer) {
+ return WireFormatLite::WriteSInt32NoTagToArray(Get<Type>(ptr), buffer);
+ }
+};
+
+template <>
+struct PrimitiveTypeHelper<WireFormatLite::TYPE_UINT32> {
+ typedef uint32 Type;
+ static void Serialize(const void* ptr,
+ ::google::protobuf::io::CodedOutputStream* output) {
+ WireFormatLite::WriteUInt32NoTag(Get<uint32>(ptr), output);
+ }
+ static uint8* SerializeToArray(const void* ptr, uint8* buffer) {
+ return WireFormatLite::WriteUInt32NoTagToArray(Get<Type>(ptr), buffer);
+ }
+};
+template <>
+struct PrimitiveTypeHelper<WireFormatLite::TYPE_INT64> {
+ typedef int64 Type;
+ static void Serialize(const void* ptr,
+ ::google::protobuf::io::CodedOutputStream* output) {
+ WireFormatLite::WriteInt64NoTag(Get<int64>(ptr), output);
+ }
+ static uint8* SerializeToArray(const void* ptr, uint8* buffer) {
+ return WireFormatLite::WriteInt64NoTagToArray(Get<Type>(ptr), buffer);
+ }
+};
+
+template <>
+struct PrimitiveTypeHelper<WireFormatLite::TYPE_SINT64> {
+ typedef int64 Type;
+ static void Serialize(const void* ptr,
+ ::google::protobuf::io::CodedOutputStream* output) {
+ WireFormatLite::WriteSInt64NoTag(Get<int64>(ptr), output);
+ }
+ static uint8* SerializeToArray(const void* ptr, uint8* buffer) {
+ return WireFormatLite::WriteSInt64NoTagToArray(Get<Type>(ptr), buffer);
+ }
+};
+template <>
+struct PrimitiveTypeHelper<WireFormatLite::TYPE_UINT64> {
+ typedef uint64 Type;
+ static void Serialize(const void* ptr,
+ ::google::protobuf::io::CodedOutputStream* output) {
+ WireFormatLite::WriteUInt64NoTag(Get<uint64>(ptr), output);
+ }
+ static uint8* SerializeToArray(const void* ptr, uint8* buffer) {
+ return WireFormatLite::WriteUInt64NoTagToArray(Get<Type>(ptr), buffer);
+ }
+};
+
+template <>
+struct PrimitiveTypeHelper<WireFormatLite::TYPE_FIXED32> {
+ typedef uint32 Type;
+ static void Serialize(const void* ptr,
+ ::google::protobuf::io::CodedOutputStream* output) {
+ WireFormatLite::WriteFixed32NoTag(Get<uint32>(ptr), output);
+ }
+ static uint8* SerializeToArray(const void* ptr, uint8* buffer) {
+ return WireFormatLite::WriteFixed32NoTagToArray(Get<Type>(ptr), buffer);
+ }
+};
+
+template <>
+struct PrimitiveTypeHelper<WireFormatLite::TYPE_FIXED64> {
+ typedef uint64 Type;
+ static void Serialize(const void* ptr,
+ ::google::protobuf::io::CodedOutputStream* output) {
+ WireFormatLite::WriteFixed64NoTag(Get<uint64>(ptr), output);
+ }
+ static uint8* SerializeToArray(const void* ptr, uint8* buffer) {
+ return WireFormatLite::WriteFixed64NoTagToArray(Get<Type>(ptr), buffer);
+ }
+};
+
+template <>
+struct PrimitiveTypeHelper<WireFormatLite::TYPE_ENUM>
+ : PrimitiveTypeHelper<WireFormatLite::TYPE_INT32> {};
+
+template <>
+struct PrimitiveTypeHelper<WireFormatLite::TYPE_SFIXED32>
+ : PrimitiveTypeHelper<WireFormatLite::TYPE_FIXED32> {
+ typedef int32 Type;
+};
+template <>
+struct PrimitiveTypeHelper<WireFormatLite::TYPE_SFIXED64>
+ : PrimitiveTypeHelper<WireFormatLite::TYPE_FIXED64> {
+ typedef int64 Type;
+};
+template <>
+struct PrimitiveTypeHelper<WireFormatLite::TYPE_FLOAT>
+ : PrimitiveTypeHelper<WireFormatLite::TYPE_FIXED32> {
+ typedef float Type;
+};
+template <>
+struct PrimitiveTypeHelper<WireFormatLite::TYPE_DOUBLE>
+ : PrimitiveTypeHelper<WireFormatLite::TYPE_FIXED64> {
+ typedef double Type;
+};
+
+template <>
+struct PrimitiveTypeHelper<WireFormatLite::TYPE_STRING> {
+ typedef string Type;
+ static void Serialize(const void* ptr,
+ ::google::protobuf::io::CodedOutputStream* output) {
+ const Type& value = *static_cast<const Type*>(ptr);
+ output->WriteVarint32(value.size());
+ output->WriteRawMaybeAliased(value.data(), value.size());
+ }
+ static uint8* SerializeToArray(const void* ptr, uint8* buffer) {
+ const Type& value = *static_cast<const Type*>(ptr);
+ return io::CodedOutputStream::WriteStringWithSizeToArray(value, buffer);
+ }
+};
+
+template <>
+struct PrimitiveTypeHelper<WireFormatLite::TYPE_BYTES>
+ : PrimitiveTypeHelper<WireFormatLite::TYPE_STRING> {};
+
+
+// We want to serialize to both CodedOutputStream and directly into byte arrays
+// without duplicating the code. In fact we might want extra output channels in
+// the future.
+template <typename O, int type>
+struct OutputHelper;
+
+template <int type, typename O>
+void SerializeTo(const void* ptr, O* output) {
+ OutputHelper<O, type>::Serialize(ptr, output);
+}
+
+template <typename O>
+void WriteTagTo(uint32 tag, O* output) {
+ SerializeTo<WireFormatLite::TYPE_UINT32>(&tag, output);
+}
+
+template <typename O>
+void WriteLengthTo(uint32 length, O* output) {
+ SerializeTo<WireFormatLite::TYPE_UINT32>(&length, output);
+}
+
+// Specialization for coded output stream
+template <int type>
+struct OutputHelper< ::google::protobuf::io::CodedOutputStream, type> {
+ static void Serialize(const void* ptr,
+ ::google::protobuf::io::CodedOutputStream* output) {
+ PrimitiveTypeHelper<type>::Serialize(ptr, output);
+ }
+};
+
+// Specialization for writing into a plain array
+struct ArrayOutput {
+ uint8* ptr;
+ bool is_deterministic;
+};
+
+template <int type>
+struct OutputHelper<ArrayOutput, type> {
+ static void Serialize(const void* ptr, ArrayOutput* output) {
+ output->ptr = PrimitiveTypeHelper<type>::SerializeToArray(ptr, output->ptr);
+ }
+};
+
+void SerializeMessageNoTable(const MessageLite* msg,
+ ::google::protobuf::io::CodedOutputStream* output) {
+ msg->SerializeWithCachedSizes(output);
+}
+
+void SerializeMessageNoTable(const MessageLite* msg, ArrayOutput* output) {
+ output->ptr = msg->InternalSerializeWithCachedSizesToArray(
+ output->is_deterministic, output->ptr);
+}
+
+// Helper to branch to fast path if possible
+void SerializeMessageDispatch(const ::google::protobuf::MessageLite& msg,
+ const FieldMetadata* field_table, int num_fields,
+ int32 cached_size,
+ ::google::protobuf::io::CodedOutputStream* output) {
+ const uint8* base = reinterpret_cast<const uint8*>(&msg);
+ // Try the fast path
+ uint8* ptr = output->GetDirectBufferForNBytesAndAdvance(cached_size);
+ if (ptr) {
+ // We use virtual dispatch to enable dedicated generated code for the
+ // fast path.
+ msg.InternalSerializeWithCachedSizesToArray(
+ output->IsSerializationDeterministic(), ptr);
+ return;
+ }
+ SerializeInternal(base, field_table, num_fields, output);
+}
+
+// Helper to branch to fast path if possible
+void SerializeMessageDispatch(const ::google::protobuf::MessageLite& msg,
+ const FieldMetadata* field_table, int num_fields,
+ int32 cached_size, ArrayOutput* output) {
+ const uint8* base = reinterpret_cast<const uint8*>(&msg);
+ output->ptr = SerializeInternalToArray(base, field_table, num_fields,
+ output->is_deterministic, output->ptr);
+}
+
+// Serializing messages is special as it's not a primitive type and needs an
+// explicit overload for each output type.
+template <typename O>
+void SerializeMessageTo(const MessageLite* msg, const void* table_ptr,
+ O* output) {
+ const SerializationTable* table =
+ static_cast<const SerializationTable*>(table_ptr);
+ if (!table) {
+ // Proto1
+ WriteLengthTo(msg->GetCachedSize(), output);
+ SerializeMessageNoTable(msg, output);
+ return;
+ }
+ const FieldMetadata* field_table = table->field_table;
+ const uint8* base = reinterpret_cast<const uint8*>(msg);
+ int cached_size = *reinterpret_cast<const int32*>(base + field_table->offset);
+ WriteLengthTo(cached_size, output);
+ int num_fields = table->num_fields - 1;
+ SerializeMessageDispatch(*msg, field_table + 1, num_fields, cached_size,
+ output);
+}
+
+// Almost the same as above only it doesn't output the length field.
+template <typename O>
+void SerializeGroupTo(const MessageLite* msg, const void* table_ptr,
+ O* output) {
+ const SerializationTable* table =
+ static_cast<const SerializationTable*>(table_ptr);
+ if (!table) {
+ // Proto1
+ SerializeMessageNoTable(msg, output);
+ return;
+ }
+ const FieldMetadata* field_table = table->field_table;
+ const uint8* base = reinterpret_cast<const uint8*>(msg);
+ int cached_size = *reinterpret_cast<const int32*>(base + field_table->offset);
+ int num_fields = table->num_fields - 1;
+ SerializeMessageDispatch(*msg, field_table + 1, num_fields, cached_size,
+ output);
+}
+
+template <int type>
+struct SingularFieldHelper {
+ template <typename O>
+ static void Serialize(const void* field, const FieldMetadata& md, O* output) {
+ WriteTagTo(md.tag, output);
+ SerializeTo<type>(field, output);
+ }
+};
+
+template <>
+struct SingularFieldHelper<WireFormatLite::TYPE_STRING> {
+ template <typename O>
+ static void Serialize(const void* field, const FieldMetadata& md, O* output) {
+ WriteTagTo(md.tag, output);
+ SerializeTo<WireFormatLite::TYPE_STRING>(&Get<ArenaStringPtr>(field).Get(),
+ output);
+ }
+};
+
+template <>
+struct SingularFieldHelper<WireFormatLite::TYPE_BYTES>
+ : SingularFieldHelper<WireFormatLite::TYPE_STRING> {};
+
+template <>
+struct SingularFieldHelper<WireFormatLite::TYPE_GROUP> {
+ template <typename O>
+ static void Serialize(const void* field, const FieldMetadata& md, O* output) {
+ WriteTagTo(md.tag, output);
+ SerializeGroupTo(Get<const MessageLite*>(field),
+ static_cast<const SerializationTable*>(md.ptr), output);
+ WriteTagTo(md.tag + 1, output);
+ }
+};
+
+template <>
+struct SingularFieldHelper<WireFormatLite::TYPE_MESSAGE> {
+ template <typename O>
+ static void Serialize(const void* field, const FieldMetadata& md, O* output) {
+ WriteTagTo(md.tag, output);
+ SerializeMessageTo(Get<const MessageLite*>(field),
+ static_cast<const SerializationTable*>(md.ptr), output);
+ }
+};
+
+template <int type>
+struct RepeatedFieldHelper {
+ template <typename O>
+ static void Serialize(const void* field, const FieldMetadata& md, O* output) {
+ typedef typename PrimitiveTypeHelper<type>::Type T;
+ const RepeatedField<T>& array = Get<RepeatedField<T> >(field);
+ for (int i = 0; i < array.size(); i++) {
+ WriteTagTo(md.tag, output);
+ SerializeTo<type>(&array[i], output);
+ }
+ }
+};
+
+// We need to use a helper class to get access to the private members
+class AccessorHelper {
+ public:
+ static int Size(const RepeatedPtrFieldBase& x) { return x.size(); }
+ static void const* Get(const RepeatedPtrFieldBase& x, int idx) {
+ return x.raw_data()[idx];
+ }
+};
+
+template <>
+struct RepeatedFieldHelper<WireFormatLite::TYPE_STRING> {
+ template <typename O>
+ static void Serialize(const void* field, const FieldMetadata& md, O* output) {
+ const internal::RepeatedPtrFieldBase& array =
+ Get<internal::RepeatedPtrFieldBase>(field);
+ for (int i = 0; i < AccessorHelper::Size(array); i++) {
+ WriteTagTo(md.tag, output);
+ SerializeTo<WireFormatLite::TYPE_STRING>(AccessorHelper::Get(array, i),
+ output);
+ }
+ }
+};
+
+template <>
+struct RepeatedFieldHelper<WireFormatLite::TYPE_BYTES>
+ : RepeatedFieldHelper<WireFormatLite::TYPE_STRING> {};
+
+template <>
+struct RepeatedFieldHelper<WireFormatLite::TYPE_GROUP> {
+ template <typename O>
+ static void Serialize(const void* field, const FieldMetadata& md, O* output) {
+ const internal::RepeatedPtrFieldBase& array =
+ Get<internal::RepeatedPtrFieldBase>(field);
+ for (int i = 0; i < AccessorHelper::Size(array); i++) {
+ WriteTagTo(md.tag, output);
+ SerializeGroupTo(
+ static_cast<const MessageLite*>(AccessorHelper::Get(array, i)),
+ static_cast<const SerializationTable*>(md.ptr), output);
+ WriteTagTo(md.tag + 1, output);
+ }
+ }
+};
+
+template <>
+struct RepeatedFieldHelper<WireFormatLite::TYPE_MESSAGE> {
+ template <typename O>
+ static void Serialize(const void* field, const FieldMetadata& md, O* output) {
+ const internal::RepeatedPtrFieldBase& array =
+ Get<internal::RepeatedPtrFieldBase>(field);
+ for (int i = 0; i < AccessorHelper::Size(array); i++) {
+ WriteTagTo(md.tag, output);
+ SerializeMessageTo(
+ static_cast<const MessageLite*>(AccessorHelper::Get(array, i)), md.ptr,
+ output);
+ }
+ }
+};
+
+
+template <int type>
+struct PackedFieldHelper {
+ template <typename O>
+ static void Serialize(const void* field, const FieldMetadata& md, O* output) {
+ typedef typename PrimitiveTypeHelper<type>::Type T;
+ const RepeatedField<T>& array = Get<RepeatedField<T> >(field);
+ if (array.empty()) return;
+ WriteTagTo(md.tag, output);
+ int cached_size =
+ Get<int>(static_cast<const uint8*>(field) + sizeof(RepeatedField<T>));
+ WriteLengthTo(cached_size, output);
+ for (int i = 0; i < array.size(); i++) {
+ SerializeTo<type>(&array[i], output);
+ }
+ }
+};
+
+template <>
+struct PackedFieldHelper<WireFormatLite::TYPE_STRING> {
+ template <typename O>
+ static void Serialize(const void* field, const FieldMetadata& md, O* output) {
+ GOOGLE_LOG(FATAL) << "Not implemented field number " << md.tag << " with type "
+ << md.type;
+ }
+};
+
+template <>
+struct PackedFieldHelper<WireFormatLite::TYPE_BYTES>
+ : PackedFieldHelper<WireFormatLite::TYPE_STRING> {};
+template <>
+struct PackedFieldHelper<WireFormatLite::TYPE_GROUP>
+ : PackedFieldHelper<WireFormatLite::TYPE_STRING> {};
+template <>
+struct PackedFieldHelper<WireFormatLite::TYPE_MESSAGE>
+ : PackedFieldHelper<WireFormatLite::TYPE_STRING> {};
+
+template <int type>
+struct OneOfFieldHelper {
+ template <typename O>
+ static void Serialize(const void* field, const FieldMetadata& md, O* output) {
+ SingularFieldHelper<type>::Serialize(field, md, output);
+ }
+};
+
+
+void SerializeNotImplemented(int field) {
+ GOOGLE_LOG(FATAL) << "Not implemented field number " << field;
+}
+
+// When switching to c++11 we should make these constexpr functions
+#define SERIALIZE_TABLE_OP(type, type_class) \
+ ((type - 1) + static_cast<int>(type_class) * FieldMetadata::kNumTypes)
+
+int FieldMetadata::CalculateType(int type,
+ FieldMetadata::FieldTypeClass type_class) {
+ return SERIALIZE_TABLE_OP(type, type_class);
+}
+
+template <int type>
+bool IsNull(const void* ptr) {
+ return *static_cast<const typename PrimitiveTypeHelper<type>::Type*>(ptr) ==
+ 0;
+}
+
+template <>
+bool IsNull<WireFormatLite::TYPE_STRING>(const void* ptr) {
+ return static_cast<const ArenaStringPtr*>(ptr)->Get().size() == 0;
+}
+
+template <>
+bool IsNull<WireFormatLite::TYPE_BYTES>(const void* ptr) {
+ return static_cast<const ArenaStringPtr*>(ptr)->Get().size() == 0;
+}
+
+template <>
+bool IsNull<WireFormatLite::TYPE_GROUP>(const void* ptr) {
+ return Get<const MessageLite*>(ptr) == NULL;
+}
+
+template <>
+bool IsNull<WireFormatLite::TYPE_MESSAGE>(const void* ptr) {
+ return Get<const MessageLite*>(ptr) == NULL;
+}
+
+
+#define SERIALIZERS_FOR_TYPE(type) \
+ case SERIALIZE_TABLE_OP(type, FieldMetadata::kPresence): \
+ if (!IsPresent(base, field_metadata.has_offset)) continue; \
+ SingularFieldHelper<type>::Serialize(ptr, field_metadata, output); \
+ break; \
+ case SERIALIZE_TABLE_OP(type, FieldMetadata::kNoPresence): \
+ if (IsNull<type>(ptr)) continue; \
+ SingularFieldHelper<type>::Serialize(ptr, field_metadata, output); \
+ break; \
+ case SERIALIZE_TABLE_OP(type, FieldMetadata::kRepeated): \
+ RepeatedFieldHelper<type>::Serialize(ptr, field_metadata, output); \
+ break; \
+ case SERIALIZE_TABLE_OP(type, FieldMetadata::kPacked): \
+ PackedFieldHelper<type>::Serialize(ptr, field_metadata, output); \
+ break; \
+ case SERIALIZE_TABLE_OP(type, FieldMetadata::kOneOf): \
+ if (!IsOneofPresent(base, field_metadata.has_offset, field_metadata.tag)) \
+ continue; \
+ OneOfFieldHelper<type>::Serialize(ptr, field_metadata, output); \
+ break
+
+void SerializeInternal(const uint8* base,
+ const FieldMetadata* field_metadata_table,
+ int32 num_fields,
+ ::google::protobuf::io::CodedOutputStream* output) {
+ for (int i = 0; i < num_fields; i++) {
+ const FieldMetadata& field_metadata = field_metadata_table[i];
+ const uint8* ptr = base + field_metadata.offset;
+ switch (field_metadata.type) {
+ SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_DOUBLE);
+ SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_FLOAT);
+ SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_INT64);
+ SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_UINT64);
+ SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_INT32);
+ SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_FIXED64);
+ SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_FIXED32);
+ SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_BOOL);
+ SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_STRING);
+ SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_GROUP);
+ SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_MESSAGE);
+ SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_BYTES);
+ SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_UINT32);
+ SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_ENUM);
+ SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_SFIXED32);
+ SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_SFIXED64);
+ SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_SINT32);
+ SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_SINT64);
+
+ // Special cases
+ case FieldMetadata::kSpecial:
+ reinterpret_cast<SpecialSerializer>(
+ const_cast<void*>(field_metadata.ptr))(
+ base, field_metadata.offset, field_metadata.tag,
+ field_metadata.has_offset, output);
+ break;
+ default:
+ // __builtin_unreachable()
+ SerializeNotImplemented(field_metadata.type);
+ }
+ }
+}
+
+uint8* SerializeInternalToArray(const uint8* base,
+ const FieldMetadata* field_metadata_table,
+ int32 num_fields, bool is_deterministic,
+ uint8* buffer) {
+ ArrayOutput array_output = {buffer, is_deterministic};
+ ArrayOutput* output = &array_output;
+ for (int i = 0; i < num_fields; i++) {
+ const FieldMetadata& field_metadata = field_metadata_table[i];
+ const uint8* ptr = base + field_metadata.offset;
+ switch (field_metadata.type) {
+ SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_DOUBLE);
+ SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_FLOAT);
+ SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_INT64);
+ SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_UINT64);
+ SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_INT32);
+ SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_FIXED64);
+ SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_FIXED32);
+ SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_BOOL);
+ SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_STRING);
+ SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_GROUP);
+ SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_MESSAGE);
+ SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_BYTES);
+ SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_UINT32);
+ SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_ENUM);
+ SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_SFIXED32);
+ SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_SFIXED64);
+ SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_SINT32);
+ SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_SINT64);
+ // Special cases
+ case FieldMetadata::kSpecial: {
+ io::ArrayOutputStream array_stream(array_output.ptr, INT_MAX);
+ io::CodedOutputStream output(&array_stream);
+ output.SetSerializationDeterministic(is_deterministic);
+ reinterpret_cast<SpecialSerializer>(
+ const_cast<void*>(field_metadata.ptr))(
+ base, field_metadata.offset, field_metadata.tag,
+ field_metadata.has_offset, &output);
+ array_output.ptr += output.ByteCount();
+ } break;
+ default:
+ // __builtin_unreachable()
+ SerializeNotImplemented(field_metadata.type);
+ }
+ }
+ return array_output.ptr;
+}
+#undef SERIALIZERS_FOR_TYPE
+
+void ExtensionSerializer(const uint8* ptr, uint32 offset, uint32 tag,
+ uint32 has_offset,
+ ::google::protobuf::io::CodedOutputStream* output) {
+ reinterpret_cast<const ExtensionSet*>(ptr + offset)
+ ->SerializeWithCachedSizes(tag, has_offset, output);
+}
+
+void UnknownFieldSerializerLite(const uint8* ptr, uint32 offset, uint32 tag,
+ uint32 has_offset,
+ ::google::protobuf::io::CodedOutputStream* output) {
+ output->WriteString(
+ reinterpret_cast<const InternalMetadataWithArenaLite*>(ptr + offset)
+ ->unknown_fields());
+}
+
+MessageLite* DuplicateIfNonNullInternal(MessageLite* message, Arena* arena) {
+ if (message) {
+ MessageLite* ret = message->New(arena);
+ ret->CheckTypeAndMergeFrom(*message);
+ return ret;
+ } else {
+ return NULL;
+ }
+}
+
+// Returns a message owned by this Arena. This may require Own()ing or
+// duplicating the message.
+MessageLite* GetOwnedMessageInternal(Arena* message_arena,
+ MessageLite* submessage,
+ Arena* submessage_arena) {
+ GOOGLE_DCHECK(submessage->GetArena() == submessage_arena);
+ GOOGLE_DCHECK(message_arena != submessage_arena);
+ if (message_arena != NULL && submessage_arena == NULL) {
+ message_arena->Own(submessage);
+ return submessage;
+ } else {
+ MessageLite* ret = submessage->New(message_arena);
+ ret->CheckTypeAndMergeFrom(*submessage);
+ return ret;
+ }
+}
+
} // namespace internal
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/generated_message_util.h b/src/google/protobuf/generated_message_util.h
index 14101832..8ebfc13b 100644
--- a/src/google/protobuf/generated_message_util.h
+++ b/src/google/protobuf/generated_message_util.h
@@ -39,25 +39,24 @@
#define GOOGLE_PROTOBUF_GENERATED_MESSAGE_UTIL_H__
#include <assert.h>
+#include <climits>
#include <string>
+#include <vector>
+#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/once.h>
#include <google/protobuf/has_bits.h>
-
-#ifndef PROTOBUF_FINAL
-#if LANG_CXX11
-#define PROTOBUF_FINAL final
-#else
-#define PROTOBUF_FINAL
-#endif
-#endif // !PROTOBUF_FINAL
+#include <google/protobuf/map_entry_lite.h>
+#include <google/protobuf/message_lite.h>
+#include <google/protobuf/wire_format_lite.h>
namespace google {
namespace protobuf {
class Arena;
+
namespace io { class CodedInputStream; }
namespace internal {
@@ -75,103 +74,243 @@ namespace internal {
#define GOOGLE_PROTOBUF_DEPRECATED_ATTR
+// Returns the offset of the given field within the given aggregate type.
+// This is equivalent to the ANSI C offsetof() macro. However, according
+// to the C++ standard, offsetof() only works on POD types, and GCC
+// enforces this requirement with a warning. In practice, this rule is
+// unnecessarily strict; there is probably no compiler or platform on
+// which the offsets of the direct fields of a class are non-constant.
+// Fields inherited from superclasses *can* have non-constant offsets,
+// but that's not what this macro will be used for.
+#if defined(__clang__)
+// For Clang we use __builtin_offsetof() and suppress the warning,
+// to avoid Control Flow Integrity and UBSan vptr sanitizers from
+// crashing while trying to validate the invalid reinterpet_casts.
+#define GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TYPE, FIELD) \
+ _Pragma("clang diagnostic push") \
+ _Pragma("clang diagnostic ignored \"-Winvalid-offsetof\"") \
+ __builtin_offsetof(TYPE, FIELD) \
+ _Pragma("clang diagnostic pop")
+#else
+// Note that we calculate relative to the pointer value 16 here since if we
+// just use zero, GCC complains about dereferencing a NULL pointer. We
+// choose 16 rather than some other number just in case the compiler would
+// be confused by an unaligned pointer.
+#define GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TYPE, FIELD) \
+ static_cast< ::google::protobuf::uint32>( \
+ reinterpret_cast<const char*>( \
+ &reinterpret_cast<const TYPE*>(16)->FIELD) - \
+ reinterpret_cast<const char*>(16))
+#endif
+
// Constants for special floating point values.
LIBPROTOBUF_EXPORT double Infinity();
LIBPROTOBUF_EXPORT double NaN();
-// This type is used to define a global variable, without it's constructor
-// and destructor run on start and end of the program lifetime. This circumvents
-// the initial construction order fiasco, while keeping the address of the
-// empty string a compile time constant.
-template <typename T>
-class ExplicitlyConstructed {
- public:
- void DefaultConstruct() {
- new (&union_) T();
- init_ = true;
- }
- bool IsInitialized() { return init_; }
- void Shutdown() {
- if (init_) {
- init_ = false;
- get_mutable()->~T();
- }
+// True if IsInitialized() is true for all elements of t. Type is expected
+// to be a RepeatedPtrField<some message type>. It's useful to have this
+// helper here to keep the protobuf compiler from ever having to emit loops in
+// IsInitialized() methods. We want the C++ compiler to inline this or not
+// as it sees fit.
+template <class Type> bool AllAreInitialized(const Type& t) {
+ for (int i = t.size(); --i >= 0; ) {
+ if (!t.Get(i).IsInitialized()) return false;
}
+ return true;
+}
-#if LANG_CXX11
- constexpr
-#endif
- const T&
- get() const {
- return reinterpret_cast<const T&>(union_);
- }
- T* get_mutable() { return reinterpret_cast<T*>(&union_); }
-
- private:
- // Prefer c++14 aligned_storage, but for compatibility this will do.
- union AlignedUnion {
- char space[sizeof(T)];
- int64 align_to_int64;
- void* align_to_ptr;
- } union_;
- bool init_; // false by linker
+LIBPROTOBUF_EXPORT void InitProtobufDefaults();
+
+struct LIBPROTOBUF_EXPORT FieldMetadata {
+ uint32 offset; // offset of this field in the struct
+ uint32 tag; // field * 8 + wire_type
+ // byte offset * 8 + bit_offset;
+ // if the high bit is set then this is the byte offset of the oneof_case
+ // for this field.
+ uint32 has_offset;
+ uint32 type; // the type of this field.
+ const void* ptr; // auxiliary data
+
+ // From the serializer point of view each fundamental type can occur in
+ // 4 different ways. For simplicity we treat all combinations as a cartesion
+ // product although not all combinations are allowed.
+ enum FieldTypeClass {
+ kPresence,
+ kNoPresence,
+ kRepeated,
+ kPacked,
+ kOneOf,
+ kNumTypeClasses // must be last enum
+ };
+ // C++ protobuf has 20 fundamental types, were we added Cord and StringPiece
+ // and also distinquish the same types if they have different wire format.
+ enum {
+ kCordType = 19,
+ kStringPieceType = 20,
+ kNumTypes = 20,
+ kSpecial = kNumTypes * kNumTypeClasses,
+ };
+
+ static int CalculateType(int fundamental_type, FieldTypeClass type_class);
};
-// TODO(jieluo): Change to template. We have tried to use template,
-// but it causes net/rpc/python:rpcutil_test fail (the empty string will
-// init twice). It may related to swig. Change to template after we
-// found the solution.
+inline bool IsPresent(const void* base, uint32 hasbit) {
+ const uint32* has_bits_array = static_cast<const uint32*>(base);
+ return has_bits_array[hasbit / 32] & (1u << (hasbit & 31));
+}
-// Default empty string object. Don't use this directly. Instead, call
-// GetEmptyString() to get the reference.
-LIBPROTOBUF_EXPORT extern ExplicitlyConstructed< ::std::string> fixed_address_empty_string;
-LIBPROTOBUF_EXPORT extern ProtobufOnceType empty_string_once_init_;
-LIBPROTOBUF_EXPORT void InitEmptyString();
+inline bool IsOneofPresent(const void* base, uint32 offset, uint32 tag) {
+ const uint32* oneof =
+ reinterpret_cast<const uint32*>(static_cast<const uint8*>(base) + offset);
+ return *oneof == tag >> 3;
+}
+typedef void (*SpecialSerializer)(const uint8* base, uint32 offset, uint32 tag,
+ uint32 has_offset,
+ ::google::protobuf::io::CodedOutputStream* output);
+
+LIBPROTOBUF_EXPORT void ExtensionSerializer(const uint8* base, uint32 offset, uint32 tag,
+ uint32 has_offset,
+ ::google::protobuf::io::CodedOutputStream* output);
+LIBPROTOBUF_EXPORT void UnknownFieldSerializerLite(const uint8* base, uint32 offset, uint32 tag,
+ uint32 has_offset,
+ ::google::protobuf::io::CodedOutputStream* output);
+
+struct SerializationTable {
+ int num_fields;
+ const FieldMetadata* field_table;
+};
-LIBPROTOBUF_EXPORT inline const ::std::string& GetEmptyStringAlreadyInited() {
- return fixed_address_empty_string.get();
+LIBPROTOBUF_EXPORT void SerializeInternal(const uint8* base, const FieldMetadata* table,
+ int num_fields, ::google::protobuf::io::CodedOutputStream* output);
+
+inline void TableSerialize(const ::google::protobuf::MessageLite& msg,
+ const SerializationTable* table,
+ ::google::protobuf::io::CodedOutputStream* output) {
+ const FieldMetadata* field_table = table->field_table;
+ int num_fields = table->num_fields - 1;
+ const uint8* base = reinterpret_cast<const uint8*>(&msg);
+ // TODO(gerbens) This skips the first test if we could use the fast
+ // array serialization path, we should make this
+ // int cached_size =
+ // *reinterpret_cast<const int32*>(base + field_table->offset);
+ // SerializeWithCachedSize(msg, field_table + 1, num_fields, cached_size, ...)
+ // But we keep conformance with the old way for now.
+ SerializeInternal(base, field_table + 1, num_fields, output);
}
-LIBPROTOBUF_EXPORT inline const ::std::string& GetEmptyString() {
- ::google::protobuf::GoogleOnceInit(&empty_string_once_init_, &InitEmptyString);
- return GetEmptyStringAlreadyInited();
+uint8* SerializeInternalToArray(const uint8* base, const FieldMetadata* table,
+ int num_fields, bool is_deterministic,
+ uint8* buffer);
+
+inline uint8* TableSerializeToArray(const ::google::protobuf::MessageLite& msg,
+ const SerializationTable* table,
+ bool is_deterministic, uint8* buffer) {
+ const uint8* base = reinterpret_cast<const uint8*>(&msg);
+ const FieldMetadata* field_table = table->field_table + 1;
+ int num_fields = table->num_fields - 1;
+ return SerializeInternalToArray(base, field_table, num_fields,
+ is_deterministic, buffer);
}
-LIBPROTOBUF_EXPORT int StringSpaceUsedExcludingSelf(const string& str);
+template <typename T>
+struct CompareHelper {
+ bool operator()(const T& a, const T& b) { return a < b; }
+};
+template <>
+struct CompareHelper<ArenaStringPtr> {
+ bool operator()(const ArenaStringPtr& a, const ArenaStringPtr& b) {
+ return a.Get() < b.Get();
+ }
+};
-// True if IsInitialized() is true for all elements of t. Type is expected
-// to be a RepeatedPtrField<some message type>. It's useful to have this
-// helper here to keep the protobuf compiler from ever having to emit loops in
-// IsInitialized() methods. We want the C++ compiler to inline this or not
-// as it sees fit.
-template <class Type> bool AllAreInitialized(const Type& t) {
- for (int i = t.size(); --i >= 0; ) {
- if (!t.Get(i).IsInitialized()) return false;
+struct CompareMapKey {
+ template <typename T>
+ bool operator()(const MapEntryHelper<T>& a, const MapEntryHelper<T>& b) {
+ return Compare(a.key_, b.key_);
+ }
+ template <typename T>
+ bool Compare(const T& a, const T& b) {
+ return CompareHelper<T>()(a, b);
+ }
+};
+
+template <typename MapFieldType, const SerializationTable* table>
+void MapFieldSerializer(const uint8* base, uint32 offset, uint32 tag,
+ uint32 has_offset,
+ ::google::protobuf::io::CodedOutputStream* output) {
+ typedef MapEntryHelper<typename MapFieldType::EntryTypeTrait> Entry;
+ typedef typename MapFieldType::MapType::const_iterator Iter;
+
+ const MapFieldType& map_field =
+ *reinterpret_cast<const MapFieldType*>(base + offset);
+ const SerializationTable* t =
+ table +
+ has_offset; // has_offset is overloaded for maps to mean table offset
+ if (!output->IsSerializationDeterministic()) {
+ for (Iter it = map_field.GetMap().begin(); it != map_field.GetMap().end();
+ ++it) {
+ Entry map_entry(*it);
+ output->WriteVarint32(tag);
+ output->WriteVarint32(map_entry._cached_size_);
+ SerializeInternal(reinterpret_cast<const uint8*>(&map_entry),
+ t->field_table, t->num_fields, output);
+ }
+ } else {
+ std::vector<Entry> v;
+ for (Iter it = map_field.GetMap().begin(); it != map_field.GetMap().end();
+ ++it) {
+ v.push_back(Entry(*it));
+ }
+ std::sort(v.begin(), v.end(), CompareMapKey());
+ for (int i = 0; i < v.size(); i++) {
+ output->WriteVarint32(tag);
+ output->WriteVarint32(v[i]._cached_size_);
+ SerializeInternal(reinterpret_cast<const uint8*>(&v[i]), t->field_table,
+ t->num_fields, output);
+ }
}
- return true;
}
-LIBPROTOBUF_EXPORT void InitProtobufDefaults();
+LIBPROTOBUF_EXPORT MessageLite* DuplicateIfNonNullInternal(MessageLite* message, Arena* arena);
+LIBPROTOBUF_EXPORT MessageLite* GetOwnedMessageInternal(Arena* message_arena,
+ MessageLite* submessage,
+ Arena* submessage_arena);
-// We compute sizes as size_t but cache them as int. This function converts a
-// computed size to a cached size. Since we don't proceed with serialization if
-// the total size was > INT_MAX, it is not important what this function returns
-// for inputs > INT_MAX.
-inline int ToCachedSize(size_t size) {
- return static_cast<int>(size);
+template <typename T>
+T* DuplicateIfNonNull(T* message, Arena* arena) {
+ // The casts must be reinterpret_cast<> because T might be a forward-declared
+ // type that the compiler doesn't know is related to MessageLite.
+ return reinterpret_cast<T*>(DuplicateIfNonNullInternal(
+ reinterpret_cast<MessageLite*>(message), arena));
}
-// We mainly calculate sizes in terms of size_t, but some functions that compute
-// sizes return "int". These int sizes are expected to always be positive.
-// This function is more efficient than casting an int to size_t directly on
-// 64-bit platforms because it avoids making the compiler emit a sign extending
-// instruction, which we don't want and don't want to pay for.
-inline size_t FromIntSize(int size) {
- // Convert to unsigned before widening so sign extension is not necessary.
- return static_cast<unsigned int>(size);
+template <typename T>
+T* GetOwnedMessage(Arena* message_arena, T* submessage,
+ Arena* submessage_arena) {
+ // The casts must be reinterpret_cast<> because T might be a forward-declared
+ // type that the compiler doesn't know is related to MessageLite.
+ return reinterpret_cast<T*>(GetOwnedMessageInternal(
+ message_arena, reinterpret_cast<MessageLite*>(submessage),
+ submessage_arena));
+}
+
+// Returns a message owned by this Arena. This may require Own()ing or
+// duplicating the message.
+template <typename T>
+T* GetOwnedMessage(T* message, Arena* arena) {
+ GOOGLE_DCHECK(message);
+ Arena* message_arena = google::protobuf::Arena::GetArena(message);
+ if (message_arena == arena) {
+ return message;
+ } else if (arena != NULL && message_arena == NULL) {
+ arena->Own(message);
+ return message;
+ } else {
+ return DuplicateIfNonNull(message, arena);
+ }
}
} // namespace internal
diff --git a/src/google/protobuf/has_bits.h b/src/google/protobuf/has_bits.h
index 133bc02a..e3a0149a 100644
--- a/src/google/protobuf/has_bits.h
+++ b/src/google/protobuf/has_bits.h
@@ -32,6 +32,7 @@
#define GOOGLE_PROTOBUF_HAS_BITS_H__
#include <google/protobuf/stubs/common.h>
+#include <google/protobuf/stubs/port.h>
namespace google {
namespace protobuf {
@@ -40,17 +41,18 @@ namespace internal {
template<size_t doublewords>
class HasBits {
public:
- HasBits() GOOGLE_ATTRIBUTE_ALWAYS_INLINE { Clear(); }
+ HasBits() GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { Clear(); }
- void Clear() GOOGLE_ATTRIBUTE_ALWAYS_INLINE {
+ void Clear() GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE {
memset(has_bits_, 0, sizeof(has_bits_));
}
- ::google::protobuf::uint32& operator[](int index) GOOGLE_ATTRIBUTE_ALWAYS_INLINE {
+ ::google::protobuf::uint32& operator[](int index) GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE {
return has_bits_[index];
}
- const ::google::protobuf::uint32& operator[](int index) const GOOGLE_ATTRIBUTE_ALWAYS_INLINE {
+ const ::google::protobuf::uint32& operator[](int index) const
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE {
return has_bits_[index];
}
@@ -61,10 +63,41 @@ class HasBits {
bool operator!=(const HasBits<doublewords>& rhs) const {
return !(*this == rhs);
}
+
+ bool empty() const;
+
private:
::google::protobuf::uint32 has_bits_[doublewords];
};
+template <>
+inline bool HasBits<1>::empty() const {
+ return !has_bits_[0];
+}
+
+template <>
+inline bool HasBits<2>::empty() const {
+ return !(has_bits_[0] | has_bits_[1]);
+}
+
+template <>
+inline bool HasBits<3>::empty() const {
+ return !(has_bits_[0] | has_bits_[1] | has_bits_[2]);
+}
+
+template <>
+inline bool HasBits<4>::empty() const {
+ return !(has_bits_[0] | has_bits_[1] | has_bits_[2] | has_bits_[3]);
+}
+
+template <size_t doublewords>
+inline bool HasBits<doublewords>::empty() const {
+ for (size_t i = 0; i < doublewords; ++i) {
+ if (has_bits_[i]) return false;
+ }
+ return true;
+}
+
} // namespace internal
} // namespace protobuf
diff --git a/src/google/protobuf/implicit_weak_message.cc b/src/google/protobuf/implicit_weak_message.cc
new file mode 100644
index 00000000..0dd126be
--- /dev/null
+++ b/src/google/protobuf/implicit_weak_message.cc
@@ -0,0 +1,51 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#include <google/protobuf/implicit_weak_message.h>
+
+#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
+#include <google/protobuf/wire_format_lite.h>
+
+namespace google {
+namespace protobuf {
+namespace internal {
+
+::google::protobuf::internal::ExplicitlyConstructed<ImplicitWeakMessage>
+ implicit_weak_message_default_instance;
+
+bool ImplicitWeakMessage::MergePartialFromCodedStream(io::CodedInputStream* input) {
+ io::StringOutputStream string_stream(&data_);
+ io::CodedOutputStream coded_stream(&string_stream, false);
+ return WireFormatLite::SkipMessage(input, &coded_stream);
+}
+
+} // namespace internal
+} // namespace protobuf
+} // namespace google
diff --git a/src/google/protobuf/implicit_weak_message.h b/src/google/protobuf/implicit_weak_message.h
new file mode 100644
index 00000000..12cc7db9
--- /dev/null
+++ b/src/google/protobuf/implicit_weak_message.h
@@ -0,0 +1,89 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#ifndef GOOGLE_PROTOBUF_IMPLICIT_WEAK_MESSAGE_H__
+#define GOOGLE_PROTOBUF_IMPLICIT_WEAK_MESSAGE_H__
+
+#include <google/protobuf/io/coded_stream.h>
+#include <google/protobuf/arena.h>
+#include <google/protobuf/message_lite.h>
+
+namespace google {
+namespace protobuf {
+namespace internal {
+
+class LIBPROTOBUF_EXPORT ImplicitWeakMessage : public MessageLite {
+ public:
+ ImplicitWeakMessage() : arena_(NULL) {}
+ explicit ImplicitWeakMessage(Arena* arena) : arena_(arena) {}
+
+ string GetTypeName() const { return ""; }
+
+ MessageLite* New() const { return new ImplicitWeakMessage; }
+ MessageLite* New(Arena* arena) const {
+ return Arena::CreateMessage<ImplicitWeakMessage>(arena);
+ }
+
+ Arena* GetArena() const { return arena_; }
+
+ void Clear() { data_.clear(); }
+
+ bool IsInitialized() const { return true; }
+
+ void CheckTypeAndMergeFrom(const MessageLite& other) {
+ data_.append(static_cast<const ImplicitWeakMessage&>(other).data_);
+ }
+
+ bool MergePartialFromCodedStream(io::CodedInputStream* input);
+
+ size_t ByteSizeLong() const { return data_.size(); }
+
+ void SerializeWithCachedSizes(io::CodedOutputStream* output) const {
+ output->WriteString(data_);
+ }
+
+ int GetCachedSize() const { return data_.size(); }
+
+ typedef void InternalArenaConstructable_;
+
+ private:
+ Arena* const arena_;
+ string data_;
+ GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImplicitWeakMessage);
+};
+
+extern ::google::protobuf::internal::ExplicitlyConstructed<ImplicitWeakMessage>
+ implicit_weak_message_default_instance;
+
+} // namespace internal
+} // namespace protobuf
+
+} // namespace google
+#endif // GOOGLE_PROTOBUF_IMPLICIT_WEAK_MESSAGE_H__
diff --git a/src/google/protobuf/io/coded_stream.cc b/src/google/protobuf/io/coded_stream.cc
index 93748ee3..79cff2c7 100644
--- a/src/google/protobuf/io/coded_stream.cc
+++ b/src/google/protobuf/io/coded_stream.cc
@@ -76,10 +76,6 @@ CodedInputStream::~CodedInputStream() {
if (input_ != NULL) {
BackUpInputToCurrentPosition();
}
-
- if (total_bytes_warning_threshold_ == -2) {
- GOOGLE_LOG(WARNING) << "The total number of bytes read was " << total_bytes_read_;
- }
}
// Static.
@@ -123,21 +119,15 @@ CodedInputStream::Limit CodedInputStream::PushLimit(int byte_limit) {
Limit old_limit = current_limit_;
// security: byte_limit is possibly evil, so check for negative values
- // and overflow.
- if (byte_limit >= 0 &&
- byte_limit <= INT_MAX - current_position) {
+ // and overflow. Also check that the new requested limit is before the
+ // previous limit; otherwise we continue to enforce the previous limit.
+ if GOOGLE_PREDICT_TRUE(byte_limit >= 0 &&
+ byte_limit <= INT_MAX - current_position &&
+ byte_limit < current_limit_ - current_position) {
current_limit_ = current_position + byte_limit;
- } else {
- // Negative or overflow.
- current_limit_ = INT_MAX;
+ RecomputeBufferLimits();
}
- // We need to enforce all limits, not just the new one, so if the previous
- // limit was before the new requested limit, we continue to enforce the
- // previous limit.
- current_limit_ = std::min(current_limit_, old_limit);
-
- RecomputeBufferLimits();
return old_limit;
}
@@ -185,16 +175,12 @@ int CodedInputStream::BytesUntilLimit() const {
void CodedInputStream::SetTotalBytesLimit(
int total_bytes_limit, int warning_threshold) {
+ (void) warning_threshold;
+
// Make sure the limit isn't already past, since this could confuse other
// code.
int current_position = CurrentPosition();
total_bytes_limit_ = std::max(current_position, total_bytes_limit);
- if (warning_threshold >= 0) {
- total_bytes_warning_threshold_ = warning_threshold;
- } else {
- // warning_threshold is negative
- total_bytes_warning_threshold_ = -1;
- }
RecomputeBufferLimits();
}
@@ -211,17 +197,7 @@ void CodedInputStream::PrintTotalBytesLimitError() {
"in google/protobuf/io/coded_stream.h.";
}
-bool CodedInputStream::Skip(int count) {
- if (count < 0) return false; // security: count is often user-supplied
-
- const int original_buffer_size = BufferSize();
-
- if (count <= original_buffer_size) {
- // Just skipping within the current buffer. Easy.
- Advance(count);
- return true;
- }
-
+bool CodedInputStream::SkipFallback(int count, int original_buffer_size) {
if (buffer_size_after_limit_ > 0) {
// We hit a limit inside this buffer. Advance to the limit and fail.
Advance(original_buffer_size);
@@ -339,7 +315,8 @@ namespace {
// The first part of the pair is true iff the read was successful. The second
// part is buffer + (number of bytes read). This function is always inlined,
// so returning a pair is costless.
-GOOGLE_ATTRIBUTE_ALWAYS_INLINE ::std::pair<bool, const uint8*> ReadVarint32FromArray(
+GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+::std::pair<bool, const uint8*> ReadVarint32FromArray(
uint32 first_byte, const uint8* buffer,
uint32* value);
inline ::std::pair<bool, const uint8*> ReadVarint32FromArray(
@@ -376,8 +353,8 @@ inline ::std::pair<bool, const uint8*> ReadVarint32FromArray(
return std::make_pair(true, ptr);
}
-GOOGLE_ATTRIBUTE_ALWAYS_INLINE::std::pair<bool, const uint8*> ReadVarint64FromArray(
- const uint8* buffer, uint64* value);
+GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE::std::pair<bool, const uint8*>
+ReadVarint64FromArray(const uint8* buffer, uint64* value);
inline ::std::pair<bool, const uint8*> ReadVarint64FromArray(
const uint8* buffer, uint64* value) {
const uint8* ptr = buffer;
@@ -605,20 +582,6 @@ bool CodedInputStream::Refresh() {
return false;
}
- if (total_bytes_warning_threshold_ >= 0 &&
- total_bytes_read_ >= total_bytes_warning_threshold_) {
- GOOGLE_LOG(INFO) << "Reading dangerously large protocol message. If the "
- "message turns out to be larger than "
- << total_bytes_limit_ << " bytes, parsing will be halted "
- "for security reasons. To increase the limit (or to "
- "disable these warnings), see "
- "CodedInputStream::SetTotalBytesLimit() in "
- "google/protobuf/io/coded_stream.h.";
-
- // Don't warn again for this stream, and print total size at the end.
- total_bytes_warning_threshold_ = -2;
- }
-
const void* void_buffer;
int buffer_size;
if (NextNonEmpty(input_, &void_buffer, &buffer_size)) {
@@ -655,7 +618,7 @@ bool CodedInputStream::Refresh() {
// CodedOutputStream =================================================
-bool CodedOutputStream::default_serialization_deterministic_ = false;
+google::protobuf::internal::AtomicWord CodedOutputStream::default_serialization_deterministic_ = 0;
CodedOutputStream::CodedOutputStream(ZeroCopyOutputStream* output)
: output_(output),
@@ -816,25 +779,6 @@ bool CodedOutputStream::Refresh() {
}
}
-size_t CodedOutputStream::VarintSize32Fallback(uint32 value) {
- // This computes floor(log2(value)) / 7 + 1
- // Use an explicit multiplication to implement the divide of
- // a number in the 1..31 range.
- GOOGLE_DCHECK_NE(0, value); // This is enforced by our caller.
-
- uint32 log2value = Bits::Log2FloorNonZero(value);
- return static_cast<size_t>((log2value * 9 + 73) / 64);
-}
-
-size_t CodedOutputStream::VarintSize64(uint64 value) {
- // This computes value == 0 ? 1 : floor(log2(value)) / 7 + 1
- // Use an explicit multiplication to implement the divide of
- // a number in the 1..63 range.
- // Explicit OR 0x1 to avoid calling clz(0), which is undefined.
- uint32 log2value = Bits::Log2FloorNonZero64(value | 0x1);
- return static_cast<size_t>((log2value * 9 + 73) / 64);
-}
-
uint8* CodedOutputStream::WriteStringWithSizeToArray(const string& str,
uint8* target) {
GOOGLE_DCHECK_LE(str.size(), kuint32max);
diff --git a/src/google/protobuf/io/coded_stream.h b/src/google/protobuf/io/coded_stream.h
index dc42e2fe..02d87ea4 100644
--- a/src/google/protobuf/io/coded_stream.h
+++ b/src/google/protobuf/io/coded_stream.h
@@ -131,7 +131,10 @@
#define PROTOBUF_LITTLE_ENDIAN 1
#endif
#endif
+#include <google/protobuf/stubs/atomicops.h>
#include <google/protobuf/stubs/common.h>
+#include <google/protobuf/stubs/port.h>
+#include <google/protobuf/stubs/port.h>
namespace google {
@@ -140,6 +143,8 @@ namespace protobuf {
class DescriptorPool;
class MessageFactory;
+namespace internal { void MapTestForceDeterministic(); }
+
namespace io {
// Defined in this file.
@@ -180,7 +185,7 @@ class LIBPROTOBUF_EXPORT CodedInputStream {
// Skips a number of bytes. Returns false if an underlying read error
// occurs.
- bool Skip(int count);
+ inline bool Skip(int count);
// Sets *data to point directly at the unread part of the CodedInputStream's
// underlying buffer, and *size to the size of that buffer, but does not
@@ -193,28 +198,23 @@ class LIBPROTOBUF_EXPORT CodedInputStream {
// Like GetDirectBufferPointer, but this method is inlined, and does not
// attempt to Refresh() if the buffer is currently empty.
- GOOGLE_ATTRIBUTE_ALWAYS_INLINE void GetDirectBufferPointerInline(const void** data,
- int* size);
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+ void GetDirectBufferPointerInline(const void** data, int* size);
// Read raw bytes, copying them into the given buffer.
bool ReadRaw(void* buffer, int size);
// Like the above, with inlined optimizations. This should only be used
// by the protobuf implementation.
- GOOGLE_ATTRIBUTE_ALWAYS_INLINE bool InternalReadRawInline(void* buffer, int size);
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+ bool InternalReadRawInline(void* buffer, int size);
// Like ReadRaw, but reads into a string.
- //
- // Implementation Note: ReadString() grows the string gradually as it
- // reads in the data, rather than allocating the entire requested size
- // upfront. This prevents denial-of-service attacks in which a client
- // could claim that a string is going to be MAX_INT bytes long in order to
- // crash the server because it can't allocate this much space at once.
bool ReadString(string* buffer, int size);
// Like the above, with inlined optimizations. This should only be used
// by the protobuf implementation.
- GOOGLE_ATTRIBUTE_ALWAYS_INLINE bool InternalReadStringInline(string* buffer,
- int size);
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+ bool InternalReadStringInline(string* buffer, int size);
// Read a 32-bit little-endian integer.
@@ -257,8 +257,11 @@ class LIBPROTOBUF_EXPORT CodedInputStream {
// Always inline because this is only called in one place per parse loop
// but it is called for every iteration of said loop, so it should be fast.
// GCC doesn't want to inline this by default.
- GOOGLE_ATTRIBUTE_ALWAYS_INLINE uint32 ReadTag();
- GOOGLE_ATTRIBUTE_ALWAYS_INLINE uint32 ReadTagNoLastTag();
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE uint32 ReadTag() {
+ return last_tag_ = ReadTagNoLastTag();
+ }
+
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE uint32 ReadTagNoLastTag();
// This usually a faster alternative to ReadTag() when cutoff is a manifest
@@ -269,10 +272,15 @@ class LIBPROTOBUF_EXPORT CodedInputStream {
// above cutoff or is 0. (There's intentional wiggle room when tag is 0,
// because that can arise in several ways, and for best performance we want
// to avoid an extra "is tag == 0?" check here.)
- GOOGLE_ATTRIBUTE_ALWAYS_INLINE std::pair<uint32, bool> ReadTagWithCutoff(
- uint32 cutoff);
- GOOGLE_ATTRIBUTE_ALWAYS_INLINE std::pair<uint32, bool> ReadTagWithCutoffNoLastTag(
- uint32 cutoff);
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+ std::pair<uint32, bool> ReadTagWithCutoff(uint32 cutoff) {
+ std::pair<uint32, bool> result = ReadTagWithCutoffNoLastTag(cutoff);
+ last_tag_ = result.first;
+ return result;
+ }
+
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+ std::pair<uint32, bool> ReadTagWithCutoffNoLastTag(uint32 cutoff);
// Usually returns true if calling ReadVarint32() now would produce the given
// value. Will always return false if ReadVarint32() would not return the
@@ -281,7 +289,7 @@ class LIBPROTOBUF_EXPORT CodedInputStream {
// parameter.
// Always inline because this collapses to a small number of instructions
// when given a constant parameter, but GCC doesn't want to inline by default.
- GOOGLE_ATTRIBUTE_ALWAYS_INLINE bool ExpectTag(uint32 expected);
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE bool ExpectTag(uint32 expected);
// Like above, except this reads from the specified buffer. The caller is
// responsible for ensuring that the buffer is large enough to read a varint
@@ -290,9 +298,8 @@ class LIBPROTOBUF_EXPORT CodedInputStream {
//
// Returns a pointer beyond the expected tag if it was found, or NULL if it
// was not.
- GOOGLE_ATTRIBUTE_ALWAYS_INLINE static const uint8* ExpectTagFromArray(
- const uint8* buffer,
- uint32 expected);
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+ static const uint8* ExpectTagFromArray(const uint8* buffer, uint32 expected);
// Usually returns true if no more bytes can be read. Always returns false
// if more bytes can be read. If ExpectAtEnd() returns true, a subsequent
@@ -312,6 +319,7 @@ class LIBPROTOBUF_EXPORT CodedInputStream {
// tag to make sure it had the right number, so it calls LastTagWas() on
// return from the embedded parser to check.
bool LastTagWas(uint32 expected);
+ void SetLastTag(uint32 tag) { last_tag_ = tag; }
// When parsing message (but NOT a group), this method must be called
// immediately after MergeFromCodedStream() returns (if it returns true)
@@ -369,11 +377,10 @@ class LIBPROTOBUF_EXPORT CodedInputStream {
// maximum message length should be limited to the shortest length that
// will not harm usability. The theoretical shortest message that could
// cause integer overflows is 512MB. The default limit is 64MB. Apps
- // should set shorter limits if possible. If warning_threshold is not -1,
- // a warning will be printed to stderr after warning_threshold bytes are
- // read. For backwards compatibility all negative values get squashed to -1,
- // as other negative values might have special internal meanings.
- // An error will always be printed to stderr if the limit is reached.
+ // should set shorter limits if possible. For backwards compatibility all
+ // negative values get squashed to -1, as other negative values might have
+ // special internal meanings. An error will always be printed to stderr if
+ // the limit is reached.
//
// This is unrelated to PushLimit()/PopLimit().
//
@@ -389,9 +396,9 @@ class LIBPROTOBUF_EXPORT CodedInputStream {
// Message::ParseFromString(). In this case, you will need to change
// your code to instead construct some sort of ZeroCopyInputStream
// (e.g. an ArrayInputStream), construct a CodedInputStream around
- // that, then call Message::ParseFromCodedStream() instead. Then
- // you can adjust the limit. Yes, it's more work, but you're doing
- // something unusual.
+ // that, then you can adjust the limit. Then call
+ // Message::ParseFromCodedStream() instead. Yes, it's more work, but
+ // you're doing something unusual.
void SetTotalBytesLimit(int total_bytes_limit, int warning_threshold);
// The Total Bytes Limit minus the Current Position, or -1 if there
@@ -566,12 +573,6 @@ class LIBPROTOBUF_EXPORT CodedInputStream {
// current_limit_. Set using SetTotalBytesLimit().
int total_bytes_limit_;
- // If positive/0: Limit for bytes read after which a warning due to size
- // should be logged.
- // If -1: Printing of warning disabled. Can be set by client.
- // If -2: Internal: Limit has been reached, print full size when destructing.
- int total_bytes_warning_threshold_;
-
// Current recursion budget, controlled by IncrementRecursionDepth() and
// similar. Starts at recursion_limit_ and goes down: if this reaches
// -1 we are over budget.
@@ -579,12 +580,17 @@ class LIBPROTOBUF_EXPORT CodedInputStream {
// Recursion depth limit, set by SetRecursionLimit().
int recursion_limit_;
+ bool disable_strict_correctness_enforcement_;
+
// See SetExtensionRegistry().
const DescriptorPool* extension_pool_;
MessageFactory* extension_factory_;
// Private member functions.
+ // Fallback when Skip() goes past the end of the current buffer.
+ bool SkipFallback(int count, int original_buffer_size);
+
// Advance the buffer by a given number of bytes.
void Advance(int amount);
@@ -622,12 +628,6 @@ class LIBPROTOBUF_EXPORT CodedInputStream {
bool ReadLittleEndian32Fallback(uint32* value);
bool ReadLittleEndian64Fallback(uint64* value);
- template<bool update_last_tag>
- GOOGLE_ATTRIBUTE_ALWAYS_INLINE uint32 ReadTagImplementation();
- template<bool update_last_tag>
- GOOGLE_ATTRIBUTE_ALWAYS_INLINE
- std::pair<uint32, bool> ReadTagWithCutoffImplementation(uint32 cutoff);
-
// Fallback/slow methods for reading tags. These do not update last_tag_,
// but will set legitimate_message_end_ if we are at the end of the input
// stream.
@@ -640,8 +640,6 @@ class LIBPROTOBUF_EXPORT CodedInputStream {
static const int kDefaultTotalBytesLimit = INT_MAX;
- static const int kDefaultTotalBytesWarningThreshold = 32 << 20; // 32MB
-
static int default_recursion_limit_; // 100 by default.
};
@@ -796,8 +794,8 @@ class LIBPROTOBUF_EXPORT CodedOutputStream {
// but GCC by default doesn't want to inline this.
void WriteTag(uint32 value);
// Like WriteTag() but writing directly to the target array.
- GOOGLE_ATTRIBUTE_ALWAYS_INLINE static uint8* WriteTagToArray(uint32 value,
- uint8* target);
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+ static uint8* WriteTagToArray(uint32 value, uint8* target);
// Returns the number of bytes needed to encode the given value as a varint.
static size_t VarintSize32(uint32 value);
@@ -864,7 +862,11 @@ class LIBPROTOBUF_EXPORT CodedOutputStream {
bool IsSerializationDeterministic() const {
return serialization_deterministic_is_overridden_ ?
serialization_deterministic_override_ :
- default_serialization_deterministic_;
+ IsDefaultSerializationDeterministic();
+ }
+
+ static bool IsDefaultSerializationDeterministic() {
+ return google::protobuf::internal::NoBarrier_Load(&default_serialization_deterministic_);
}
private:
@@ -879,7 +881,9 @@ class LIBPROTOBUF_EXPORT CodedOutputStream {
// See SetSerializationDeterministic() regarding these three fields.
bool serialization_deterministic_is_overridden_;
bool serialization_deterministic_override_;
- static bool default_serialization_deterministic_;
+ // Conceptually, default_serialization_deterministic_ is an atomic bool.
+ // TODO(haberman): replace with std::atomic<bool> when we move to C++11.
+ static google::protobuf::internal::AtomicWord default_serialization_deterministic_;
// Advance the buffer by a given number of bytes.
void Advance(int amount);
@@ -897,11 +901,16 @@ class LIBPROTOBUF_EXPORT CodedOutputStream {
void WriteVarint32SlowPath(uint32 value);
void WriteVarint64SlowPath(uint64 value);
- static size_t VarintSize32Fallback(uint32 value);
-
// See above. Other projects may use "friend" to allow them to call this.
+ // After SetDefaultSerializationDeterministic() completes, all protocol
+ // buffer serializations will be deterministic by default. Thread safe.
+ // However, the meaning of "after" is subtle here: to be safe, each thread
+ // that wants deterministic serialization by default needs to call
+ // SetDefaultSerializationDeterministic() or ensure on its own that another
+ // thread has done so.
+ friend void ::google::protobuf::internal::MapTestForceDeterministic();
static void SetDefaultSerializationDeterministic() {
- default_serialization_deterministic_ = true;
+ google::protobuf::internal::NoBarrier_Store(&default_serialization_deterministic_, 1);
}
};
@@ -988,8 +997,7 @@ inline const uint8* CodedInputStream::ReadLittleEndian64FromArray(
inline bool CodedInputStream::ReadLittleEndian32(uint32* value) {
#if defined(PROTOBUF_LITTLE_ENDIAN)
if (GOOGLE_PREDICT_TRUE(BufferSize() >= static_cast<int>(sizeof(*value)))) {
- memcpy(value, buffer_, sizeof(*value));
- Advance(sizeof(*value));
+ buffer_ = ReadLittleEndian32FromArray(buffer_, value);
return true;
} else {
return ReadLittleEndian32Fallback(value);
@@ -1002,8 +1010,7 @@ inline bool CodedInputStream::ReadLittleEndian32(uint32* value) {
inline bool CodedInputStream::ReadLittleEndian64(uint64* value) {
#if defined(PROTOBUF_LITTLE_ENDIAN)
if (GOOGLE_PREDICT_TRUE(BufferSize() >= static_cast<int>(sizeof(*value)))) {
- memcpy(value, buffer_, sizeof(*value));
- Advance(sizeof(*value));
+ buffer_ = ReadLittleEndian64FromArray(buffer_, value);
return true;
} else {
return ReadLittleEndian64Fallback(value);
@@ -1013,48 +1020,21 @@ inline bool CodedInputStream::ReadLittleEndian64(uint64* value) {
#endif
}
-inline uint32 CodedInputStream::ReadTag() {
- return ReadTagImplementation<true>();
-}
-
inline uint32 CodedInputStream::ReadTagNoLastTag() {
- return ReadTagImplementation<false>();
-}
-
-template<bool update_last_tag>
-inline uint32 CodedInputStream::ReadTagImplementation() {
uint32 v = 0;
if (GOOGLE_PREDICT_TRUE(buffer_ < buffer_end_)) {
v = *buffer_;
if (v < 0x80) {
- if (update_last_tag) {
- last_tag_ = v;
- }
Advance(1);
return v;
}
}
v = ReadTagFallback(v);
- if (update_last_tag) {
- last_tag_ = v;
- }
return v;
}
-inline std::pair<uint32, bool> CodedInputStream::ReadTagWithCutoff(
- uint32 cutoff) {
- return ReadTagWithCutoffImplementation<true>(cutoff);
-}
-
inline std::pair<uint32, bool> CodedInputStream::ReadTagWithCutoffNoLastTag(
uint32 cutoff) {
- return ReadTagWithCutoffImplementation<false>(cutoff);
-}
-
-template<bool update_last_tag>
-inline std::pair<uint32, bool>
-CodedInputStream::ReadTagWithCutoffImplementation(
- uint32 cutoff) {
// In performance-sensitive code we can expect cutoff to be a compile-time
// constant, and things like "cutoff >= kMax1ByteVarint" to be evaluated at
// compile time.
@@ -1067,9 +1047,6 @@ CodedInputStream::ReadTagWithCutoffImplementation(
if (static_cast<int8>(buffer_[0]) > 0) {
const uint32 kMax1ByteVarint = 0x7f;
uint32 tag = buffer_[0];
- if (update_last_tag) {
- last_tag_ = tag;
- }
Advance(1);
return std::make_pair(tag, cutoff >= kMax1ByteVarint || tag <= cutoff);
}
@@ -1081,9 +1058,6 @@ CodedInputStream::ReadTagWithCutoffImplementation(
GOOGLE_PREDICT_TRUE((buffer_[0] & ~buffer_[1]) >= 0x80)) {
const uint32 kMax2ByteVarint = (0x7f << 7) + 0x7f;
uint32 tag = (1u << 7) * buffer_[1] + (buffer_[0] - 0x80);
- if (update_last_tag) {
- last_tag_ = tag;
- }
Advance(2);
// It might make sense to test for tag == 0 now, but it is so rare that
// that we don't bother. A varint-encoded 0 should be one byte unless
@@ -1097,9 +1071,6 @@ CodedInputStream::ReadTagWithCutoffImplementation(
}
// Slow path
const uint32 tag = ReadTagFallback(first_byte_or_zero);
- if (update_last_tag) {
- last_tag_ = tag;
- }
return std::make_pair(tag, static_cast<uint32>(tag - 1) < cutoff);
}
@@ -1284,11 +1255,23 @@ inline uint8* CodedOutputStream::WriteTagToArray(
}
inline size_t CodedOutputStream::VarintSize32(uint32 value) {
- if (value < (1 << 7)) {
- return 1;
- } else {
- return VarintSize32Fallback(value);
- }
+ // This computes value == 0 ? 1 : floor(log2(value)) / 7 + 1
+ // Use an explicit multiplication to implement the divide of
+ // a number in the 1..31 range.
+ // Explicit OR 0x1 to avoid calling Bits::Log2FloorNonZero(0), which is
+ // undefined.
+ uint32 log2value = Bits::Log2FloorNonZero(value | 0x1);
+ return static_cast<size_t>((log2value * 9 + 73) / 64);
+}
+
+inline size_t CodedOutputStream::VarintSize64(uint64 value) {
+ // This computes value == 0 ? 1 : floor(log2(value)) / 7 + 1
+ // Use an explicit multiplication to implement the divide of
+ // a number in the 1..63 range.
+ // Explicit OR 0x1 to avoid calling Bits::Log2FloorNonZero(0), which is
+ // undefined.
+ uint32 log2value = Bits::Log2FloorNonZero64(value | 0x1);
+ return static_cast<size_t>((log2value * 9 + 73) / 64);
}
inline size_t CodedOutputStream::VarintSize32SignExtended(int32 value) {
@@ -1379,9 +1362,9 @@ inline CodedInputStream::CodedInputStream(ZeroCopyInputStream* input)
current_limit_(kint32max),
buffer_size_after_limit_(0),
total_bytes_limit_(kDefaultTotalBytesLimit),
- total_bytes_warning_threshold_(kDefaultTotalBytesWarningThreshold),
recursion_budget_(default_recursion_limit_),
recursion_limit_(default_recursion_limit_),
+ disable_strict_correctness_enforcement_(true),
extension_pool_(NULL),
extension_factory_(NULL) {
// Eagerly Refresh() so buffer space is immediately available.
@@ -1400,9 +1383,9 @@ inline CodedInputStream::CodedInputStream(const uint8* buffer, int size)
current_limit_(size),
buffer_size_after_limit_(0),
total_bytes_limit_(kDefaultTotalBytesLimit),
- total_bytes_warning_threshold_(kDefaultTotalBytesWarningThreshold),
recursion_budget_(default_recursion_limit_),
recursion_limit_(default_recursion_limit_),
+ disable_strict_correctness_enforcement_(true),
extension_pool_(NULL),
extension_factory_(NULL) {
// Note that setting current_limit_ == size is important to prevent some
@@ -1413,11 +1396,25 @@ inline bool CodedInputStream::IsFlat() const {
return input_ == NULL;
}
+inline bool CodedInputStream::Skip(int count) {
+ if (count < 0) return false; // security: count is often user-supplied
+
+ const int original_buffer_size = BufferSize();
+
+ if (count <= original_buffer_size) {
+ // Just skipping within the current buffer. Easy.
+ Advance(count);
+ return true;
+ }
+
+ return SkipFallback(count, original_buffer_size);
+}
+
} // namespace io
} // namespace protobuf
-#if _MSC_VER >= 1300 && !defined(__INTEL_COMPILER)
+#if defined(_MSC_VER) && _MSC_VER >= 1300 && !defined(__INTEL_COMPILER)
#pragma runtime_checks("c", restore)
#endif // _MSC_VER && !defined(__INTEL_COMPILER)
diff --git a/src/google/protobuf/io/coded_stream_unittest.cc b/src/google/protobuf/io/coded_stream_unittest.cc
index 31574d5b..96f91ae9 100644
--- a/src/google/protobuf/io/coded_stream_unittest.cc
+++ b/src/google/protobuf/io/coded_stream_unittest.cc
@@ -63,6 +63,7 @@ namespace protobuf {
namespace io {
namespace {
+
// ===================================================================
// Data-Driven Test Infrastructure
@@ -1296,35 +1297,6 @@ void CodedStreamTest::SetupTotalBytesLimitWarningTest(
*out_warnings = scoped_log.GetMessages(WARNING);
}
-TEST_F(CodedStreamTest, TotalBytesLimitWarning) {
- std::vector<string> errors;
- std::vector<string> warnings;
- SetupTotalBytesLimitWarningTest(10240, 1024, &errors, &warnings);
-
- EXPECT_EQ(0, errors.size());
-
- EXPECT_EQ(1, warnings.size());
- EXPECT_PRED_FORMAT2(testing::IsSubstring,
- "The total number of bytes read was 2048",
- warnings[0]);
-}
-
-TEST_F(CodedStreamTest, TotalBytesLimitWarningDisabled) {
- std::vector<string> errors;
- std::vector<string> warnings;
-
- // Test with -1
- SetupTotalBytesLimitWarningTest(10240, -1, &errors, &warnings);
- EXPECT_EQ(0, errors.size());
- EXPECT_EQ(0, warnings.size());
-
- // Test again with -2, expecting the same result
- SetupTotalBytesLimitWarningTest(10240, -2, &errors, &warnings);
- EXPECT_EQ(0, errors.size());
- EXPECT_EQ(0, warnings.size());
-}
-
-
TEST_F(CodedStreamTest, RecursionLimit) {
ArrayInputStream input(buffer_, sizeof(buffer_));
CodedInputStream coded_input(&input);
@@ -1425,9 +1397,6 @@ TEST_F(CodedStreamTest, InputOver2G) {
EXPECT_EQ(0, errors.size());
}
-// ===================================================================
-
-
} // namespace
} // namespace io
} // namespace protobuf
diff --git a/src/google/protobuf/io/printer.cc b/src/google/protobuf/io/printer.cc
index 99e895f5..8493268d 100644
--- a/src/google/protobuf/io/printer.cc
+++ b/src/google/protobuf/io/printer.cc
@@ -111,6 +111,7 @@ void Printer::Print(const std::map<string, string>& variables,
int size = strlen(text);
int pos = 0; // The number of bytes we've written so far.
substitutions_.clear();
+ line_start_variables_.clear();
for (int i = 0; i < size; i++) {
if (text[i] == '\n') {
@@ -122,6 +123,7 @@ void Printer::Print(const std::map<string, string>& variables,
// Setting this true will cause the next WriteRaw() to insert an indent
// first.
at_start_of_line_ = true;
+ line_start_variables_.clear();
} else if (text[i] == variable_delimiter_) {
// Saw the start of a variable name.
@@ -148,12 +150,15 @@ void Printer::Print(const std::map<string, string>& variables,
if (iter == variables.end()) {
GOOGLE_LOG(DFATAL) << " Undefined variable: " << varname;
} else {
- size_t begin = offset_;
+ if (at_start_of_line_ && iter->second.empty()) {
+ line_start_variables_.push_back(varname);
+ }
WriteRaw(iter->second.data(), iter->second.size());
std::pair<std::map<string, std::pair<size_t, size_t> >::iterator,
bool>
- inserted = substitutions_.insert(
- std::make_pair(varname, std::make_pair(begin, offset_)));
+ inserted = substitutions_.insert(std::make_pair(
+ varname,
+ std::make_pair(offset_ - iter->second.size(), offset_)));
if (!inserted.second) {
// This variable was used multiple times. Make its span have
// negative length so we can detect it if it gets used in an
@@ -319,10 +324,29 @@ void Printer::WriteRaw(const char* data, int size) {
if (at_start_of_line_ && (size > 0) && (data[0] != '\n')) {
// Insert an indent.
at_start_of_line_ = false;
- WriteRaw(indent_.data(), indent_.size());
+ CopyToBuffer(indent_.data(), indent_.size());
if (failed_) return;
+ // Fix up empty variables (e.g., "{") that should be annotated as
+ // coming after the indent.
+ for (std::vector<string>::iterator i = line_start_variables_.begin();
+ i != line_start_variables_.end(); ++i) {
+ substitutions_[*i].first += indent_.size();
+ substitutions_[*i].second += indent_.size();
+ }
}
+ // If we're going to write any data, clear line_start_variables_, since
+ // we've either updated them in the block above or they no longer refer to
+ // the current line.
+ line_start_variables_.clear();
+
+ CopyToBuffer(data, size);
+}
+
+void Printer::CopyToBuffer(const char* data, int size) {
+ if (failed_) return;
+ if (size == 0) return;
+
while (size > buffer_size_) {
// Data exceeds space in the buffer. Copy what we can and request a
// new buffer.
diff --git a/src/google/protobuf/io/printer.h b/src/google/protobuf/io/printer.h
index e666445b..d11745ce 100644
--- a/src/google/protobuf/io/printer.h
+++ b/src/google/protobuf/io/printer.h
@@ -157,7 +157,7 @@ class AnnotationProtoCollector : public AnnotationCollector {
// vars["function"] = "call";
// vars["mark"] = "";
// printer.Print(vars, "$function$($foo$,$foo$)$mark$");
-// printer.Annotate("function", "rmark", call_);
+// printer.Annotate("function", "mark", call_);
//
// This code associates the span covering "call(bar,bar)" in the output with the
// call_ descriptor.
@@ -311,6 +311,9 @@ class LIBPROTOBUF_EXPORT Printer {
void Annotate(const char* begin_varname, const char* end_varname,
const string& file_path, const std::vector<int>& path);
+ // Copy size worth of bytes from data to buffer_.
+ void CopyToBuffer(const char* data, int size);
+
const char variable_delimiter_;
ZeroCopyOutputStream* const output_;
@@ -334,6 +337,11 @@ class LIBPROTOBUF_EXPORT Printer {
// length of the substituted string).
std::map<string, std::pair<size_t, size_t> > substitutions_;
+ // Keeps track of the keys in substitutions_ that need to be updated when
+ // indents are inserted. These are keys that refer to the beginning of the
+ // current line.
+ std::vector<string> line_start_variables_;
+
// Returns true and sets range to the substitution range in the output for
// varname if varname was used once in the last call to Print. If varname
// was not used, or if it was used multiple times, returns false (and
diff --git a/src/google/protobuf/io/printer_unittest.cc b/src/google/protobuf/io/printer_unittest.cc
index 0435228a..d0a0ebee 100644
--- a/src/google/protobuf/io/printer_unittest.cc
+++ b/src/google/protobuf/io/printer_unittest.cc
@@ -360,6 +360,83 @@ TEST(Printer, AnnotateDespiteUnrelatedMultipleUses) {
EXPECT_EQ(7, bar->end());
}
+TEST(Printer, AnnotateIndent) {
+ char buffer[8192];
+ ArrayOutputStream output(buffer, sizeof(buffer));
+ GeneratedCodeInfo info;
+ AnnotationProtoCollector<GeneratedCodeInfo> info_collector(&info);
+ {
+ Printer printer(&output, '$', &info_collector);
+ printer.Print("0\n");
+ printer.Indent();
+ printer.Print("$foo$", "foo", "4");
+ std::vector<int> path;
+ path.push_back(44);
+ MockDescriptor descriptor("path", path);
+ printer.Annotate("foo", &descriptor);
+ printer.Print(",\n");
+ printer.Print("$bar$", "bar", "9");
+ path[0] = 99;
+ MockDescriptor descriptor_two("path", path);
+ printer.Annotate("bar", &descriptor_two);
+ printer.Print("\n${$$D$$}$\n", "{", "", "}", "", "D", "d");
+ path[0] = 1313;
+ MockDescriptor descriptor_three("path", path);
+ printer.Annotate("{", "}", &descriptor_three);
+ printer.Outdent();
+ printer.Print("\n");
+ }
+ buffer[output.ByteCount()] = '\0';
+ EXPECT_STREQ("0\n 4,\n 9\n d\n\n", buffer);
+ ASSERT_EQ(3, info.annotation_size());
+ const GeneratedCodeInfo::Annotation* foo = &info.annotation(0);
+ ASSERT_EQ(1, foo->path_size());
+ EXPECT_EQ(44, foo->path(0));
+ EXPECT_EQ("path", foo->source_file());
+ EXPECT_EQ(4, foo->begin());
+ EXPECT_EQ(5, foo->end());
+ const GeneratedCodeInfo::Annotation* bar = &info.annotation(1);
+ ASSERT_EQ(1, bar->path_size());
+ EXPECT_EQ(99, bar->path(0));
+ EXPECT_EQ("path", bar->source_file());
+ EXPECT_EQ(9, bar->begin());
+ EXPECT_EQ(10, bar->end());
+ const GeneratedCodeInfo::Annotation* braces = &info.annotation(2);
+ ASSERT_EQ(1, braces->path_size());
+ EXPECT_EQ(1313, braces->path(0));
+ EXPECT_EQ("path", braces->source_file());
+ EXPECT_EQ(13, braces->begin());
+ EXPECT_EQ(14, braces->end());
+}
+
+TEST(Printer, AnnotateIndentNewline) {
+ char buffer[8192];
+ ArrayOutputStream output(buffer, sizeof(buffer));
+ GeneratedCodeInfo info;
+ AnnotationProtoCollector<GeneratedCodeInfo> info_collector(&info);
+ {
+ Printer printer(&output, '$', &info_collector);
+ printer.Indent();
+ printer.Print("$A$$N$$B$C\n", "A", "", "N", "\nz", "B", "");
+ std::vector<int> path;
+ path.push_back(0);
+ MockDescriptor descriptor("path", path);
+ printer.Annotate("A", "B", &descriptor);
+ printer.Outdent();
+ printer.Print("\n");
+ }
+ buffer[output.ByteCount()] = '\0';
+ EXPECT_STREQ("\nz C\n\n", buffer);
+ ASSERT_EQ(1, info.annotation_size());
+ const GeneratedCodeInfo::Annotation* ab = &info.annotation(0);
+ ASSERT_EQ(1, ab->path_size());
+ EXPECT_EQ(0, ab->path(0));
+ EXPECT_EQ("path", ab->source_file());
+ EXPECT_EQ(0, ab->begin());
+ EXPECT_EQ(4, ab->end());
+}
+
+
TEST(Printer, Indenting) {
char buffer[8192];
diff --git a/src/google/protobuf/io/tokenizer_unittest.cc b/src/google/protobuf/io/tokenizer_unittest.cc
index a2c19522..e55288e2 100644
--- a/src/google/protobuf/io/tokenizer_unittest.cc
+++ b/src/google/protobuf/io/tokenizer_unittest.cc
@@ -199,8 +199,8 @@ struct SimpleTokenCase {
Tokenizer::TokenType type;
};
-inline ostream& operator<<(ostream& out,
- const SimpleTokenCase& test_case) {
+inline std::ostream& operator<<(std::ostream& out,
+ const SimpleTokenCase& test_case) {
return out << CEscape(test_case.input);
}
@@ -333,15 +333,15 @@ struct MultiTokenCase {
// needed.
};
-inline ostream& operator<<(ostream& out,
- const MultiTokenCase& test_case) {
+inline std::ostream& operator<<(std::ostream& out,
+ const MultiTokenCase& test_case) {
return out << CEscape(test_case.input);
}
MultiTokenCase kMultiTokenCases[] = {
// Test empty input.
{ "", {
- { Tokenizer::TYPE_END , "" , 0, 0 },
+ { Tokenizer::TYPE_END , "" , 0, 0, 0 },
}},
// Test all token types at the same time.
@@ -520,8 +520,8 @@ struct DocCommentCase {
const char* next_leading_comments;
};
-inline ostream& operator<<(ostream& out,
- const DocCommentCase& test_case) {
+inline std::ostream& operator<<(std::ostream& out,
+ const DocCommentCase& test_case) {
return out << CEscape(test_case.input);
}
@@ -860,8 +860,7 @@ struct ErrorCase {
const char* errors;
};
-inline ostream& operator<<(ostream& out,
- const ErrorCase& test_case) {
+inline std::ostream& operator<<(std::ostream& out, const ErrorCase& test_case) {
return out << CEscape(test_case.input);
}
diff --git a/src/google/protobuf/io/zero_copy_stream.cc b/src/google/protobuf/io/zero_copy_stream.cc
index 186de001..f81555e5 100644
--- a/src/google/protobuf/io/zero_copy_stream.cc
+++ b/src/google/protobuf/io/zero_copy_stream.cc
@@ -41,9 +41,6 @@ namespace google {
namespace protobuf {
namespace io {
-ZeroCopyInputStream::~ZeroCopyInputStream() {}
-ZeroCopyOutputStream::~ZeroCopyOutputStream() {}
-
bool ZeroCopyOutputStream::WriteAliasedRaw(const void* /* data */,
int /* size */) {
diff --git a/src/google/protobuf/io/zero_copy_stream.h b/src/google/protobuf/io/zero_copy_stream.h
index 52650fc6..62ace7ae 100644
--- a/src/google/protobuf/io/zero_copy_stream.h
+++ b/src/google/protobuf/io/zero_copy_stream.h
@@ -123,8 +123,8 @@ class ZeroCopyOutputStream;
// copying.
class LIBPROTOBUF_EXPORT ZeroCopyInputStream {
public:
- inline ZeroCopyInputStream() {}
- virtual ~ZeroCopyInputStream();
+ ZeroCopyInputStream() {}
+ virtual ~ZeroCopyInputStream() {}
// Obtains a chunk of data from the stream.
//
@@ -180,8 +180,8 @@ class LIBPROTOBUF_EXPORT ZeroCopyInputStream {
// copying.
class LIBPROTOBUF_EXPORT ZeroCopyOutputStream {
public:
- inline ZeroCopyOutputStream() {}
- virtual ~ZeroCopyOutputStream();
+ ZeroCopyOutputStream() {}
+ virtual ~ZeroCopyOutputStream() {}
// Obtains a buffer into which data can be written. Any data written
// into this buffer will eventually (maybe instantly, maybe later on)
diff --git a/src/google/protobuf/io/zero_copy_stream_impl.cc b/src/google/protobuf/io/zero_copy_stream_impl.cc
index 7ec2b5da..83dec3e6 100644
--- a/src/google/protobuf/io/zero_copy_stream_impl.cc
+++ b/src/google/protobuf/io/zero_copy_stream_impl.cc
@@ -32,9 +32,7 @@
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
-#ifdef _MSC_VER
-#include <io.h>
-#else
+#ifndef _MSC_VER
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
@@ -43,11 +41,11 @@
#include <errno.h>
#include <iostream>
#include <algorithm>
-
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/stl_util.h>
+#include <google/protobuf/stubs/io_win32.h>
namespace google {
@@ -60,6 +58,16 @@ namespace io {
#define lseek(fd, offset, origin) ((off_t)-1)
#endif
+#ifdef _MSC_VER
+// DO NOT include <io.h>, instead create functions in io_win32.{h,cc} and import
+// them like we do below.
+using google::protobuf::internal::win32::access;
+using google::protobuf::internal::win32::close;
+using google::protobuf::internal::win32::open;
+using google::protobuf::internal::win32::read;
+using google::protobuf::internal::win32::write;
+#endif
+
namespace {
// EINTR sucks.
@@ -81,8 +89,6 @@ FileInputStream::FileInputStream(int file_descriptor, int block_size)
impl_(&copying_input_, block_size) {
}
-FileInputStream::~FileInputStream() {}
-
bool FileInputStream::Close() {
return copying_input_.Close();
}
@@ -270,12 +276,8 @@ bool FileOutputStream::CopyingFileOutputStream::Write(
// ===================================================================
-IstreamInputStream::IstreamInputStream(istream* input, int block_size)
- : copying_input_(input),
- impl_(&copying_input_, block_size) {
-}
-
-IstreamInputStream::~IstreamInputStream() {}
+IstreamInputStream::IstreamInputStream(std::istream* input, int block_size)
+ : copying_input_(input), impl_(&copying_input_, block_size) {}
bool IstreamInputStream::Next(const void** data, int* size) {
return impl_.Next(data, size);
@@ -294,9 +296,8 @@ int64 IstreamInputStream::ByteCount() const {
}
IstreamInputStream::CopyingIstreamInputStream::CopyingIstreamInputStream(
- istream* input)
- : input_(input) {
-}
+ std::istream* input)
+ : input_(input) {}
IstreamInputStream::CopyingIstreamInputStream::~CopyingIstreamInputStream() {}
@@ -312,10 +313,8 @@ int IstreamInputStream::CopyingIstreamInputStream::Read(
// ===================================================================
-OstreamOutputStream::OstreamOutputStream(ostream* output, int block_size)
- : copying_output_(output),
- impl_(&copying_output_, block_size) {
-}
+OstreamOutputStream::OstreamOutputStream(std::ostream* output, int block_size)
+ : copying_output_(output), impl_(&copying_output_, block_size) {}
OstreamOutputStream::~OstreamOutputStream() {
impl_.Flush();
@@ -334,9 +333,8 @@ int64 OstreamOutputStream::ByteCount() const {
}
OstreamOutputStream::CopyingOstreamOutputStream::CopyingOstreamOutputStream(
- ostream* output)
- : output_(output) {
-}
+ std::ostream* output)
+ : output_(output) {}
OstreamOutputStream::CopyingOstreamOutputStream::~CopyingOstreamOutputStream() {
}
@@ -354,9 +352,6 @@ ConcatenatingInputStream::ConcatenatingInputStream(
: streams_(streams), stream_count_(count), bytes_retired_(0) {
}
-ConcatenatingInputStream::~ConcatenatingInputStream() {
-}
-
bool ConcatenatingInputStream::Next(const void** data, int* size) {
while (stream_count_ > 0) {
if (streams_[0]->Next(data, size)) return true;
diff --git a/src/google/protobuf/io/zero_copy_stream_impl.h b/src/google/protobuf/io/zero_copy_stream_impl.h
index 3365790e..ea978bfb 100644
--- a/src/google/protobuf/io/zero_copy_stream_impl.h
+++ b/src/google/protobuf/io/zero_copy_stream_impl.h
@@ -67,7 +67,6 @@ class LIBPROTOBUF_EXPORT FileInputStream : public ZeroCopyInputStream {
// should be read and returned with each call to Next(). Otherwise,
// a reasonable default is used.
explicit FileInputStream(int file_descriptor, int block_size = -1);
- ~FileInputStream();
// Flushes any buffers and closes the underlying file. Returns false if
// an error occurs during the process; use GetErrno() to examine the error.
@@ -219,7 +218,6 @@ class LIBPROTOBUF_EXPORT IstreamInputStream : public ZeroCopyInputStream {
// should be read and returned with each call to Next(). Otherwise,
// a reasonable default is used.
explicit IstreamInputStream(std::istream* stream, int block_size = -1);
- ~IstreamInputStream();
// implements ZeroCopyInputStream ----------------------------------
bool Next(const void** data, int* size);
@@ -306,7 +304,6 @@ class LIBPROTOBUF_EXPORT ConcatenatingInputStream : public ZeroCopyInputStream {
// All streams passed in as well as the array itself must remain valid
// until the ConcatenatingInputStream is destroyed.
ConcatenatingInputStream(ZeroCopyInputStream* const streams[], int count);
- ~ConcatenatingInputStream();
// implements ZeroCopyInputStream ----------------------------------
bool Next(const void** data, int* size);
diff --git a/src/google/protobuf/io/zero_copy_stream_impl_lite.cc b/src/google/protobuf/io/zero_copy_stream_impl_lite.cc
index e6ca88c2..66ad49bc 100644
--- a/src/google/protobuf/io/zero_copy_stream_impl_lite.cc
+++ b/src/google/protobuf/io/zero_copy_stream_impl_lite.cc
@@ -64,9 +64,6 @@ ArrayInputStream::ArrayInputStream(const void* data, int size,
last_returned_size_(0) {
}
-ArrayInputStream::~ArrayInputStream() {
-}
-
bool ArrayInputStream::Next(const void** data, int* size) {
if (position_ < size_) {
last_returned_size_ = std::min(block_size_, size_ - position_);
@@ -117,9 +114,6 @@ ArrayOutputStream::ArrayOutputStream(void* data, int size, int block_size)
last_returned_size_(0) {
}
-ArrayOutputStream::~ArrayOutputStream() {
-}
-
bool ArrayOutputStream::Next(void** data, int* size) {
if (position_ < size_) {
last_returned_size_ = std::min(block_size_, size_ - position_);
@@ -153,9 +147,6 @@ StringOutputStream::StringOutputStream(string* target)
: target_(target) {
}
-StringOutputStream::~StringOutputStream() {
-}
-
bool StringOutputStream::Next(void** data, int* size) {
GOOGLE_CHECK(target_ != NULL);
int old_size = target_->size();
@@ -205,32 +196,6 @@ void StringOutputStream::SetString(string* target) {
// ===================================================================
-LazyStringOutputStream::LazyStringOutputStream(
- ResultCallback<string*>* callback)
- : StringOutputStream(NULL),
- callback_(GOOGLE_CHECK_NOTNULL(callback)),
- string_is_set_(false) {
-}
-
-LazyStringOutputStream::~LazyStringOutputStream() {
-}
-
-bool LazyStringOutputStream::Next(void** data, int* size) {
- if (!string_is_set_) {
- SetString(callback_->Run());
- string_is_set_ = true;
- }
- return StringOutputStream::Next(data, size);
-}
-
-int64 LazyStringOutputStream::ByteCount() const {
- return string_is_set_ ? StringOutputStream::ByteCount() : 0;
-}
-
-// ===================================================================
-
-CopyingInputStream::~CopyingInputStream() {}
-
int CopyingInputStream::Skip(int count) {
char junk[4096];
int skipped = 0;
@@ -350,8 +315,6 @@ void CopyingInputStreamAdaptor::FreeBuffer() {
// ===================================================================
-CopyingOutputStream::~CopyingOutputStream() {}
-
CopyingOutputStreamAdaptor::CopyingOutputStreamAdaptor(
CopyingOutputStream* copying_stream, int block_size)
: copying_stream_(copying_stream),
diff --git a/src/google/protobuf/io/zero_copy_stream_impl_lite.h b/src/google/protobuf/io/zero_copy_stream_impl_lite.h
index e4d6a024..ab0fd5ac 100644
--- a/src/google/protobuf/io/zero_copy_stream_impl_lite.h
+++ b/src/google/protobuf/io/zero_copy_stream_impl_lite.h
@@ -73,7 +73,6 @@ class LIBPROTOBUF_EXPORT ArrayInputStream : public ZeroCopyInputStream {
// useful for testing; in production you would probably never want to set
// it.
ArrayInputStream(const void* data, int size, int block_size = -1);
- ~ArrayInputStream();
// implements ZeroCopyInputStream ----------------------------------
bool Next(const void** data, int* size);
@@ -107,7 +106,6 @@ class LIBPROTOBUF_EXPORT ArrayOutputStream : public ZeroCopyOutputStream {
// useful for testing; in production you would probably never want to set
// it.
ArrayOutputStream(void* data, int size, int block_size = -1);
- ~ArrayOutputStream();
// implements ZeroCopyOutputStream ---------------------------------
bool Next(void** data, int* size);
@@ -141,7 +139,6 @@ class LIBPROTOBUF_EXPORT StringOutputStream : public ZeroCopyOutputStream {
// the first call to Next() will return at least n bytes of buffer
// space.
explicit StringOutputStream(string* target);
- ~StringOutputStream();
// implements ZeroCopyOutputStream ---------------------------------
bool Next(void** data, int* size);
@@ -159,27 +156,6 @@ class LIBPROTOBUF_EXPORT StringOutputStream : public ZeroCopyOutputStream {
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(StringOutputStream);
};
-// LazyStringOutputStream is a StringOutputStream with lazy acquisition of
-// the output string from a callback. The string is owned externally, and not
-// deleted in the stream destructor.
-class LIBPROTOBUF_EXPORT LazyStringOutputStream : public StringOutputStream {
- public:
- // Callback should be permanent (non-self-deleting). Ownership is transferred
- // to the LazyStringOutputStream.
- explicit LazyStringOutputStream(ResultCallback<string*>* callback);
- ~LazyStringOutputStream();
-
- // implements ZeroCopyOutputStream, overriding StringOutputStream -----------
- bool Next(void** data, int* size);
- int64 ByteCount() const;
-
- private:
- const google::protobuf::scoped_ptr<ResultCallback<string*> > callback_;
- bool string_is_set_;
-
- GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(LazyStringOutputStream);
-};
-
// Note: There is no StringInputStream. Instead, just create an
// ArrayInputStream as follows:
// ArrayInputStream input(str.data(), str.size());
@@ -199,7 +175,7 @@ class LIBPROTOBUF_EXPORT LazyStringOutputStream : public StringOutputStream {
// in large blocks.
class LIBPROTOBUF_EXPORT CopyingInputStream {
public:
- virtual ~CopyingInputStream();
+ virtual ~CopyingInputStream() {}
// Reads up to "size" bytes into the given buffer. Returns the number of
// bytes read. Read() waits until at least one byte is available, or
@@ -293,7 +269,7 @@ class LIBPROTOBUF_EXPORT CopyingInputStreamAdaptor : public ZeroCopyInputStream
// in large blocks.
class LIBPROTOBUF_EXPORT CopyingOutputStream {
public:
- virtual ~CopyingOutputStream();
+ virtual ~CopyingOutputStream() {}
// Writes "size" bytes from the given buffer to the output. Returns true
// if successful, false on a write error.
@@ -399,7 +375,7 @@ inline std::pair<char*, bool> as_string_data(string* s) {
#ifdef LANG_CXX11
return std::make_pair(p, true);
#else
- return make_pair(p, p != NULL);
+ return std::make_pair(p, p != NULL);
#endif
}
diff --git a/src/google/protobuf/io/zero_copy_stream_unittest.cc b/src/google/protobuf/io/zero_copy_stream_unittest.cc
index a9db8872..dfc383a3 100644
--- a/src/google/protobuf/io/zero_copy_stream_unittest.cc
+++ b/src/google/protobuf/io/zero_copy_stream_unittest.cc
@@ -47,9 +47,7 @@
// implementations.
-#ifdef _MSC_VER
-#include <io.h>
-#else
+#ifndef _MSC_VER
#include <unistd.h>
#endif
#include <stdlib.h>
@@ -76,6 +74,7 @@
#include <google/protobuf/testing/googletest.h>
#include <google/protobuf/testing/file.h>
#include <gtest/gtest.h>
+#include <google/protobuf/stubs/io_win32.h>
namespace google {
namespace protobuf {
@@ -86,6 +85,15 @@ namespace {
#define pipe(fds) _pipe(fds, 4096, O_BINARY)
#endif
+#ifdef _MSC_VER
+// DO NOT include <io.h>, instead create functions in io_win32.{h,cc} and import
+// them like we do below.
+using google::protobuf::internal::win32::access;
+using google::protobuf::internal::win32::mkdir;
+using google::protobuf::internal::win32::open;
+using google::protobuf::internal::win32::close;
+#endif
+
#ifndef O_BINARY
#ifdef _O_BINARY
#define O_BINARY _O_BINARY
@@ -882,7 +890,7 @@ TEST_F(IoTest, IostreamIo) {
for (int i = 0; i < kBlockSizeCount; i++) {
for (int j = 0; j < kBlockSizeCount; j++) {
{
- stringstream stream;
+ std::stringstream stream;
{
OstreamOutputStream output(&stream, kBlockSizes[i]);
@@ -898,7 +906,7 @@ TEST_F(IoTest, IostreamIo) {
}
{
- stringstream stream;
+ std::stringstream stream;
{
OstreamOutputStream output(&stream, kBlockSizes[i]);
diff --git a/src/google/protobuf/lite_arena_unittest.cc b/src/google/protobuf/lite_arena_unittest.cc
index f0bee880..dadaffb6 100644
--- a/src/google/protobuf/lite_arena_unittest.cc
+++ b/src/google/protobuf/lite_arena_unittest.cc
@@ -37,13 +37,22 @@ namespace google {
namespace protobuf {
namespace {
-TEST(LiteArenaTest, MapNoHeapAllocation) {
- // Allocate a large initial block to avoid mallocs during hooked test.
- std::vector<char> arena_block(128 * 1024);
- google::protobuf::ArenaOptions options;
- options.initial_block = &arena_block[0];
- options.initial_block_size = arena_block.size();
- google::protobuf::Arena arena(options);
+class LiteArenaTest : public testing::Test {
+ protected:
+ LiteArenaTest() {
+ ArenaOptions options;
+ options.start_block_size = 128 * 1024;
+ options.max_block_size = 128 * 1024;
+ arena_.reset(new Arena(options));
+ // Trigger the allocation of the first arena block, so that further use of
+ // the arena will not require any heap allocations.
+ google::protobuf::Arena::CreateArray<char>(arena_.get(), 1);
+ }
+
+ google::protobuf::scoped_ptr<Arena> arena_;
+};
+
+TEST_F(LiteArenaTest, MapNoHeapAllocation) {
string data;
data.reserve(128 * 1024);
@@ -53,22 +62,21 @@ TEST(LiteArenaTest, MapNoHeapAllocation) {
// google::protobuf::internal::NoHeapChecker no_heap;
protobuf_unittest::TestArenaMapLite* from =
- google::protobuf::Arena::CreateMessage<protobuf_unittest::TestArenaMapLite>(&arena);
+ Arena::CreateMessage<protobuf_unittest::TestArenaMapLite>(arena_.get());
google::protobuf::MapLiteTestUtil::SetArenaMapFields(from);
from->SerializeToString(&data);
protobuf_unittest::TestArenaMapLite* to =
- google::protobuf::Arena::CreateMessage<protobuf_unittest::TestArenaMapLite>(&arena);
+ Arena::CreateMessage<protobuf_unittest::TestArenaMapLite>(arena_.get());
to->ParseFromString(data);
google::protobuf::MapLiteTestUtil::ExpectArenaMapFieldsSet(*to);
}
}
-TEST(LiteArenaTest, UnknownFieldMemLeak) {
- google::protobuf::Arena arena;
+TEST_F(LiteArenaTest, UnknownFieldMemLeak) {
protobuf_unittest::ForeignMessageArenaLite* message =
google::protobuf::Arena::CreateMessage<protobuf_unittest::ForeignMessageArenaLite>(
- &arena);
+ arena_.get());
string data = "\012\000";
int original_capacity = data.capacity();
while (data.capacity() <= original_capacity) {
diff --git a/src/google/protobuf/lite_unittest.cc b/src/google/protobuf/lite_unittest.cc
index 3ca3fbaf..d6693963 100644
--- a/src/google/protobuf/lite_unittest.cc
+++ b/src/google/protobuf/lite_unittest.cc
@@ -36,24 +36,26 @@
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/arena_test_util.h>
-#include <google/protobuf/map_lite_unittest.pb.h>
#include <google/protobuf/map_lite_test_util.h>
+#include <google/protobuf/map_lite_unittest.pb.h>
#include <google/protobuf/test_util_lite.h>
#include <google/protobuf/unittest_lite.pb.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
#include <google/protobuf/wire_format_lite.h>
#include <google/protobuf/wire_format_lite_inl.h>
+#include <gtest/gtest.h>
+
#include <google/protobuf/stubs/strutil.h>
-using namespace std;
+using std::string;
namespace {
// Helper methods to test parsing merge behavior.
void ExpectMessageMerged(const google::protobuf::unittest::TestAllTypesLite& message) {
- GOOGLE_CHECK(message.optional_int32() == 3);
- GOOGLE_CHECK(message.optional_int64() == 2);
- GOOGLE_CHECK(message.optional_string() == "hello");
+ EXPECT_EQ(message.optional_int32(), 3);
+ EXPECT_EQ(message.optional_int64(), 2);
+ EXPECT_EQ(message.optional_string(), "hello");
}
void AssignParsingMergeMessages(
@@ -89,14 +91,8 @@ void SetSomeTypesInEmptyMessageUnknownFields(
} // namespace
-#define EXPECT_TRUE GOOGLE_CHECK
-#define ASSERT_TRUE GOOGLE_CHECK
-#define EXPECT_FALSE(COND) GOOGLE_CHECK(!(COND))
-#define EXPECT_EQ GOOGLE_CHECK_EQ
-#define ASSERT_EQ GOOGLE_CHECK_EQ
-
-int main(int argc, char* argv[]) {
- string data, data2, packed_data;
+TEST(Lite, AllLite1) {
+ string data;
{
protobuf_unittest::TestAllTypesLite message, message2, message3;
@@ -113,7 +109,10 @@ int main(int argc, char* argv[]) {
message.Clear();
google::protobuf::TestUtilLite::ExpectClear(message);
}
+}
+TEST(Lite, AllLite2) {
+ string data;
{
protobuf_unittest::TestAllExtensionsLite message, message2, message3;
google::protobuf::TestUtilLite::ExpectExtensionsClear(message);
@@ -129,6 +128,10 @@ int main(int argc, char* argv[]) {
message.Clear();
google::protobuf::TestUtilLite::ExpectExtensionsClear(message);
}
+}
+
+TEST(Lite, AllLite3) {
+ string data, packed_data;
{
protobuf_unittest::TestPackedTypesLite message, message2, message3;
@@ -152,7 +155,7 @@ int main(int argc, char* argv[]) {
google::protobuf::TestUtilLite::SetPackedExtensions(&message);
message2.CopyFrom(message);
string packed_extensions_data = message.SerializeAsString();
- GOOGLE_CHECK(packed_extensions_data == packed_data);
+ EXPECT_EQ(packed_extensions_data, packed_data);
message3.ParseFromString(packed_extensions_data);
google::protobuf::TestUtilLite::ExpectPackedExtensionsSet(message);
google::protobuf::TestUtilLite::ExpectPackedExtensionsSet(message2);
@@ -162,6 +165,10 @@ int main(int argc, char* argv[]) {
message.Clear();
google::protobuf::TestUtilLite::ExpectPackedExtensionsClear(message);
}
+}
+
+TEST(Lite, AllLite5) {
+ string data;
{
// Test that if an optional or required message/group field appears multiple
@@ -209,11 +216,16 @@ int main(int argc, char* argv[]) {
google::protobuf::unittest::TestParsingMergeLite::optional_ext));
// Repeated fields should not be merged.
- GOOGLE_CHECK(parsing_merge.repeated_all_types_size() == 3);
- GOOGLE_CHECK(parsing_merge.repeatedgroup_size() == 3);
- GOOGLE_CHECK(parsing_merge.ExtensionSize(
- google::protobuf::unittest::TestParsingMergeLite::repeated_ext) == 3);
+ EXPECT_EQ(parsing_merge.repeated_all_types_size(), 3);
+ EXPECT_EQ(parsing_merge.repeatedgroup_size(), 3);
+ EXPECT_EQ(parsing_merge.ExtensionSize(
+ google::protobuf::unittest::TestParsingMergeLite::repeated_ext),
+ 3);
}
+}
+
+TEST(Lite, AllLite6) {
+ string data;
// Test unknown fields support for lite messages.
{
@@ -231,6 +243,10 @@ int main(int argc, char* argv[]) {
message.Clear();
google::protobuf::TestUtilLite::ExpectClear(message);
}
+}
+
+TEST(Lite, AllLite7) {
+ string data;
{
protobuf_unittest::TestAllExtensionsLite message, message2;
@@ -247,6 +263,10 @@ int main(int argc, char* argv[]) {
message.Clear();
google::protobuf::TestUtilLite::ExpectExtensionsClear(message);
}
+}
+
+TEST(Lite, AllLite8) {
+ string data;
{
protobuf_unittest::TestPackedTypesLite message, message2;
@@ -263,6 +283,10 @@ int main(int argc, char* argv[]) {
message.Clear();
google::protobuf::TestUtilLite::ExpectPackedClear(message);
}
+}
+
+TEST(Lite, AllLite9) {
+ string data;
{
protobuf_unittest::TestPackedExtensionsLite message, message2;
@@ -279,6 +303,10 @@ int main(int argc, char* argv[]) {
message.Clear();
google::protobuf::TestUtilLite::ExpectPackedExtensionsClear(message);
}
+}
+
+TEST(Lite, AllLite10) {
+ string data;
{
// Test Unknown fields swap
@@ -286,11 +314,15 @@ int main(int argc, char* argv[]) {
SetAllTypesInEmptyMessageUnknownFields(&empty_message);
SetSomeTypesInEmptyMessageUnknownFields(&empty_message2);
data = empty_message.SerializeAsString();
- data2 = empty_message2.SerializeAsString();
+ string data2 = empty_message2.SerializeAsString();
empty_message.Swap(&empty_message2);
- GOOGLE_CHECK_EQ(data, empty_message2.SerializeAsString());
- GOOGLE_CHECK_EQ(data2, empty_message.SerializeAsString());
+ EXPECT_EQ(data, empty_message2.SerializeAsString());
+ EXPECT_EQ(data2, empty_message.SerializeAsString());
}
+}
+
+TEST(Lite, AllLite11) {
+ string data;
{
// Test unknown fields swap with self
@@ -298,8 +330,12 @@ int main(int argc, char* argv[]) {
SetAllTypesInEmptyMessageUnknownFields(&empty_message);
data = empty_message.SerializeAsString();
empty_message.Swap(&empty_message);
- GOOGLE_CHECK_EQ(data, empty_message.SerializeAsString());
+ EXPECT_EQ(data, empty_message.SerializeAsString());
}
+}
+
+TEST(Lite, AllLite12) {
+ string data;
{
// Test MergeFrom with unknown fields
@@ -324,8 +360,12 @@ int main(int argc, char* argv[]) {
// We do not compare the serialized output of a normal message and a lite
// message because the order of fields do not match. We convert lite message
// back into normal message, then compare.
- GOOGLE_CHECK_EQ(message.SerializeAsString(), message2.SerializeAsString());
+ EXPECT_EQ(message.SerializeAsString(), message2.SerializeAsString());
}
+}
+
+TEST(Lite, AllLite13) {
+ string data;
{
// Test unknown enum value
@@ -345,18 +385,26 @@ int main(int argc, char* argv[]) {
}
message.ParseFromString(buffer);
data = message.SerializeAsString();
- GOOGLE_CHECK_EQ(data, buffer);
+ EXPECT_EQ(data, buffer);
}
+}
+
+TEST(Lite, AllLite14) {
+ string data;
{
// Test Clear with unknown fields
protobuf_unittest::TestEmptyMessageLite empty_message;
SetAllTypesInEmptyMessageUnknownFields(&empty_message);
empty_message.Clear();
- GOOGLE_CHECK_EQ(0, empty_message.unknown_fields().size());
+ EXPECT_EQ(0, empty_message.unknown_fields().size());
}
+}
+
+// Tests for map lite =============================================
- // Tests for map lite =============================================
+TEST(Lite, AllLite15) {
+ string data;
{
// Accessors
@@ -368,6 +416,10 @@ int main(int argc, char* argv[]) {
google::protobuf::MapLiteTestUtil::ModifyMapFields(&message);
google::protobuf::MapLiteTestUtil::ExpectMapFieldsModified(message);
}
+}
+
+TEST(Lite, AllLite16) {
+ string data;
{
// SetMapFieldsInitialized
@@ -376,6 +428,10 @@ int main(int argc, char* argv[]) {
google::protobuf::MapLiteTestUtil::SetMapFieldsInitialized(&message);
google::protobuf::MapLiteTestUtil::ExpectMapFieldsSetInitialized(message);
}
+}
+
+TEST(Lite, AllLite17) {
+ string data;
{
// Clear
@@ -385,6 +441,10 @@ int main(int argc, char* argv[]) {
message.Clear();
google::protobuf::MapLiteTestUtil::ExpectClear(message);
}
+}
+
+TEST(Lite, AllLite18) {
+ string data;
{
// ClearMessageMap
@@ -394,6 +454,10 @@ int main(int argc, char* argv[]) {
google::protobuf::TestUtilLite::ExpectClear(
(*message.mutable_map_int32_message())[0]);
}
+}
+
+TEST(Lite, AllLite19) {
+ string data;
{
// CopyFrom
@@ -407,6 +471,10 @@ int main(int argc, char* argv[]) {
message2.CopyFrom(message2);
google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message2);
}
+}
+
+TEST(Lite, AllLite20) {
+ string data;
{
// CopyFromMessageMap
@@ -421,6 +489,10 @@ int main(int argc, char* argv[]) {
EXPECT_EQ(1, message1.map_int32_message().at(0).repeated_int32_size());
EXPECT_EQ(101, message1.map_int32_message().at(0).repeated_int32(0));
}
+}
+
+TEST(Lite, AllLite21) {
+ string data;
{
// SwapWithEmpty
@@ -434,6 +506,10 @@ int main(int argc, char* argv[]) {
google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message2);
google::protobuf::MapLiteTestUtil::ExpectClear(message1);
}
+}
+
+TEST(Lite, AllLite22) {
+ string data;
{
// SwapWithSelf
@@ -445,6 +521,10 @@ int main(int argc, char* argv[]) {
message.Swap(&message);
google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message);
}
+}
+
+TEST(Lite, AllLite23) {
+ string data;
{
// SwapWithOther
@@ -458,6 +538,10 @@ int main(int argc, char* argv[]) {
google::protobuf::MapLiteTestUtil::ExpectMapFieldsModified(message1);
google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message2);
}
+}
+
+TEST(Lite, AllLite24) {
+ string data;
{
// CopyConstructor
@@ -467,6 +551,10 @@ int main(int argc, char* argv[]) {
protobuf_unittest::TestMapLite message2(message1);
google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message2);
}
+}
+
+TEST(Lite, AllLite25) {
+ string data;
{
// CopyAssignmentOperator
@@ -481,6 +569,10 @@ int main(int argc, char* argv[]) {
message2.operator=(message2);
google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message2);
}
+}
+
+TEST(Lite, AllLite26) {
+ string data;
{
// NonEmptyMergeFrom
@@ -499,6 +591,10 @@ int main(int argc, char* argv[]) {
message1.MergeFrom(message2);
google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message1);
}
+}
+
+TEST(Lite, AllLite27) {
+ string data;
{
// MergeFromMessageMap
@@ -513,6 +609,10 @@ int main(int argc, char* argv[]) {
EXPECT_EQ(1, message1.map_int32_message().at(0).repeated_int32_size());
EXPECT_EQ(101, message1.map_int32_message().at(0).repeated_int32(0));
}
+}
+
+TEST(Lite, AllLite28) {
+ string data;
{
// Test the generated SerializeWithCachedSizesToArray()
@@ -527,6 +627,10 @@ int main(int argc, char* argv[]) {
EXPECT_TRUE(message2.ParseFromString(data));
google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message2);
}
+}
+
+TEST(Lite, AllLite29) {
+ string data;
{
// Test the generated SerializeWithCachedSizes()
@@ -547,8 +651,12 @@ int main(int argc, char* argv[]) {
EXPECT_TRUE(message2.ParseFromString(data));
google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message2);
}
+}
+TEST(Lite, AllLite32) {
+ string data;
+
{
// Proto2UnknownEnum
protobuf_unittest::TestEnumMapPlusExtraLite from;
@@ -578,6 +686,10 @@ int main(int argc, char* argv[]) {
EXPECT_EQ(protobuf_unittest::E_PROTO2_MAP_ENUM_EXTRA_LITE,
from.unknown_map_field().at(0));
}
+}
+
+TEST(Lite, AllLite33) {
+ string data;
{
// StandardWireFormat
@@ -588,6 +700,10 @@ int main(int argc, char* argv[]) {
EXPECT_EQ(1, message.map_int32_int32().size());
EXPECT_EQ(1, message.map_int32_int32().at(1));
}
+}
+
+TEST(Lite, AllLite34) {
+ string data;
{
// UnorderedWireFormat
@@ -600,6 +716,10 @@ int main(int argc, char* argv[]) {
EXPECT_EQ(1, message.map_int32_int32().size());
EXPECT_EQ(1, message.map_int32_int32().at(2));
}
+}
+
+TEST(Lite, AllLite35) {
+ string data;
{
// DuplicatedKeyWireFormat
@@ -612,6 +732,10 @@ int main(int argc, char* argv[]) {
EXPECT_EQ(1, message.map_int32_int32().size());
EXPECT_EQ(1, message.map_int32_int32().at(2));
}
+}
+
+TEST(Lite, AllLite36) {
+ string data;
{
// DuplicatedValueWireFormat
@@ -624,6 +748,10 @@ int main(int argc, char* argv[]) {
EXPECT_EQ(1, message.map_int32_int32().size());
EXPECT_EQ(2, message.map_int32_int32().at(1));
}
+}
+
+TEST(Lite, AllLite37) {
+ string data;
{
// MissedKeyWireFormat
@@ -636,6 +764,10 @@ int main(int argc, char* argv[]) {
EXPECT_EQ(1, message.map_int32_int32().size());
EXPECT_EQ(1, message.map_int32_int32().at(0));
}
+}
+
+TEST(Lite, AllLite38) {
+ string data;
{
// MissedValueWireFormat
@@ -648,6 +780,10 @@ int main(int argc, char* argv[]) {
EXPECT_EQ(1, message.map_int32_int32().size());
EXPECT_EQ(0, message.map_int32_int32().at(1));
}
+}
+
+TEST(Lite, AllLite39) {
+ string data;
{
// UnknownFieldWireFormat
@@ -660,6 +796,10 @@ int main(int argc, char* argv[]) {
EXPECT_EQ(1, message.map_int32_int32().size());
EXPECT_EQ(3, message.map_int32_int32().at(2));
}
+}
+
+TEST(Lite, AllLite40) {
+ string data;
{
// CorruptedWireFormat
@@ -670,6 +810,10 @@ int main(int argc, char* argv[]) {
EXPECT_FALSE(message.ParseFromString(data));
}
+}
+
+TEST(Lite, AllLite41) {
+ string data;
{
// IsInitialized
@@ -685,6 +829,10 @@ int main(int argc, char* argv[]) {
(*map_message.mutable_map_field())[0].set_c(0);
EXPECT_TRUE(map_message.IsInitialized());
}
+}
+
+TEST(Lite, AllLite42) {
+ string data;
{
// Check that adding more values to enum does not corrupt message
@@ -712,7 +860,146 @@ int main(int argc, char* argv[]) {
EXPECT_EQ(v2_message.int_field(), same_v2_message.int_field());
EXPECT_EQ(v2_message.enum_field(), same_v2_message.enum_field());
}
+}
+
+// Test that when parsing a oneof, we can successfully clear whatever already
+// happened to be stored in the oneof.
+TEST(Lite, AllLite43) {
+ protobuf_unittest::TestOneofParsingLite message1;
+
+ message1.set_oneof_int32(17);
+ string serialized;
+ EXPECT_TRUE(message1.SerializeToString(&serialized));
+
+ // Submessage
+ {
+ protobuf_unittest::TestOneofParsingLite message2;
+ message2.mutable_oneof_submessage();
+ google::protobuf::io::CodedInputStream input_stream(
+ reinterpret_cast<const ::google::protobuf::uint8*>(serialized.data()), serialized.size());
+ EXPECT_TRUE(message2.MergeFromCodedStream(&input_stream));
+ EXPECT_EQ(17, message2.oneof_int32());
+ }
+
+ // String
+ {
+ protobuf_unittest::TestOneofParsingLite message2;
+ message2.set_oneof_string("string");
+ google::protobuf::io::CodedInputStream input_stream(
+ reinterpret_cast<const ::google::protobuf::uint8*>(serialized.data()), serialized.size());
+ EXPECT_TRUE(message2.MergeFromCodedStream(&input_stream));
+ EXPECT_EQ(17, message2.oneof_int32());
+ }
+
+ // Bytes
+ {
+ protobuf_unittest::TestOneofParsingLite message2;
+ message2.set_oneof_bytes("bytes");
+ google::protobuf::io::CodedInputStream input_stream(
+ reinterpret_cast<const ::google::protobuf::uint8*>(serialized.data()), serialized.size());
+ EXPECT_TRUE(message2.MergeFromCodedStream(&input_stream));
+ EXPECT_EQ(17, message2.oneof_int32());
+ }
+}
+
+// Verify that we can successfully parse fields of various types within oneof
+// fields. We also verify that we can parse the same data twice into the same
+// message.
+TEST(Lite, AllLite44) {
+ // Int32
+ {
+ protobuf_unittest::TestOneofParsingLite original;
+ original.set_oneof_int32(17);
+ string serialized;
+ EXPECT_TRUE(original.SerializeToString(&serialized));
+ protobuf_unittest::TestOneofParsingLite parsed;
+ for (int i = 0; i < 2; ++i) {
+ google::protobuf::io::CodedInputStream input_stream(
+ reinterpret_cast<const ::google::protobuf::uint8*>(serialized.data()),
+ serialized.size());
+ EXPECT_TRUE(parsed.MergeFromCodedStream(&input_stream));
+ EXPECT_EQ(17, parsed.oneof_int32());
+ }
+ }
+
+ // Submessage
+ {
+ protobuf_unittest::TestOneofParsingLite original;
+ original.mutable_oneof_submessage()->set_optional_int32(5);
+ string serialized;
+ EXPECT_TRUE(original.SerializeToString(&serialized));
+ protobuf_unittest::TestOneofParsingLite parsed;
+ for (int i = 0; i < 2; ++i) {
+ google::protobuf::io::CodedInputStream input_stream(
+ reinterpret_cast<const ::google::protobuf::uint8*>(serialized.data()),
+ serialized.size());
+ EXPECT_TRUE(parsed.MergeFromCodedStream(&input_stream));
+ EXPECT_EQ(5, parsed.oneof_submessage().optional_int32());
+ }
+ }
+
+ // String
+ {
+ protobuf_unittest::TestOneofParsingLite original;
+ original.set_oneof_string("string");
+ string serialized;
+ EXPECT_TRUE(original.SerializeToString(&serialized));
+ protobuf_unittest::TestOneofParsingLite parsed;
+ for (int i = 0; i < 2; ++i) {
+ google::protobuf::io::CodedInputStream input_stream(
+ reinterpret_cast<const ::google::protobuf::uint8*>(serialized.data()),
+ serialized.size());
+ EXPECT_TRUE(parsed.MergeFromCodedStream(&input_stream));
+ EXPECT_EQ("string", parsed.oneof_string());
+ }
+ }
+
+ // Bytes
+ {
+ protobuf_unittest::TestOneofParsingLite original;
+ original.set_oneof_bytes("bytes");
+ string serialized;
+ EXPECT_TRUE(original.SerializeToString(&serialized));
+ protobuf_unittest::TestOneofParsingLite parsed;
+ for (int i = 0; i < 2; ++i) {
+ google::protobuf::io::CodedInputStream input_stream(
+ reinterpret_cast<const ::google::protobuf::uint8*>(serialized.data()),
+ serialized.size());
+ EXPECT_TRUE(parsed.MergeFromCodedStream(&input_stream));
+ EXPECT_EQ("bytes", parsed.oneof_bytes());
+ }
+ }
+
+ // Enum
+ {
+ protobuf_unittest::TestOneofParsingLite original;
+ original.set_oneof_enum(protobuf_unittest::V2_SECOND);
+ string serialized;
+ EXPECT_TRUE(original.SerializeToString(&serialized));
+ protobuf_unittest::TestOneofParsingLite parsed;
+ for (int i = 0; i < 2; ++i) {
+ google::protobuf::io::CodedInputStream input_stream(
+ reinterpret_cast<const ::google::protobuf::uint8*>(serialized.data()),
+ serialized.size());
+ EXPECT_TRUE(parsed.MergeFromCodedStream(&input_stream));
+ EXPECT_EQ(protobuf_unittest::V2_SECOND, parsed.oneof_enum());
+ }
+ }
std::cout << "PASS" << std::endl;
- return 0;
+}
+
+TEST(Lite, AllLite45) {
+ // Test unknown fields are not discarded upon parsing.
+ string data = "\20\1"; // varint 1 with field number 2
+
+ protobuf_unittest::ForeignMessageLite a;
+ EXPECT_TRUE(a.ParseFromString(data));
+ google::protobuf::io::CodedInputStream input_stream(
+ reinterpret_cast<const ::google::protobuf::uint8*>(data.data()), data.size());
+ EXPECT_TRUE(a.MergePartialFromCodedStream(&input_stream));
+
+ string serialized = a.SerializeAsString();
+ EXPECT_EQ(serialized.substr(0, 2), data);
+ EXPECT_EQ(serialized.substr(2), data);
}
diff --git a/src/google/protobuf/map.h b/src/google/protobuf/map.h
index 47ced29f..7d9cc5c5 100644
--- a/src/google/protobuf/map.h
+++ b/src/google/protobuf/map.h
@@ -37,7 +37,6 @@
#ifndef GOOGLE_PROTOBUF_MAP_H__
#define GOOGLE_PROTOBUF_MAP_H__
-#include <google/protobuf/stubs/hash.h>
#include <iterator>
#include <limits> // To support Visual Studio 2008
#include <set>
@@ -47,11 +46,7 @@
#include <google/protobuf/arena.h>
#include <google/protobuf/generated_enum_util.h>
#include <google/protobuf/map_type_handler.h>
-#include <google/protobuf/message.h>
-#include <google/protobuf/descriptor.h>
-#if __cpp_exceptions && LANG_CXX11
-#include <random>
-#endif
+#include <google/protobuf/stubs/hash.h>
namespace google {
namespace protobuf {
@@ -64,16 +59,14 @@ class MapIterator;
template <typename Enum> struct is_proto_enum;
namespace internal {
-template <typename Key, typename T,
+template <typename Derived, typename Key, typename T,
WireFormatLite::FieldType key_wire_type,
- WireFormatLite::FieldType value_wire_type,
- int default_enum_value>
+ WireFormatLite::FieldType value_wire_type, int default_enum_value>
class MapFieldLite;
-template <typename Key, typename T,
+template <typename Derived, typename Key, typename T,
WireFormatLite::FieldType key_wire_type,
- WireFormatLite::FieldType value_wire_type,
- int default_enum_value>
+ WireFormatLite::FieldType value_wire_type, int default_enum_value>
class MapField;
template <typename Key, typename T>
@@ -84,389 +77,6 @@ class DynamicMapField;
class GeneratedMessageReflection;
} // namespace internal
-#define TYPE_CHECK(EXPECTEDTYPE, METHOD) \
- if (type() != EXPECTEDTYPE) { \
- GOOGLE_LOG(FATAL) \
- << "Protocol Buffer map usage error:\n" \
- << METHOD << " type does not match\n" \
- << " Expected : " \
- << FieldDescriptor::CppTypeName(EXPECTEDTYPE) << "\n" \
- << " Actual : " \
- << FieldDescriptor::CppTypeName(type()); \
- }
-
-// MapKey is an union type for representing any possible
-// map key.
-class LIBPROTOBUF_EXPORT MapKey {
- public:
- MapKey() : type_(0) {
- }
- MapKey(const MapKey& other) : type_(0) {
- CopyFrom(other);
- }
-
- ~MapKey() {
- if (type_ == FieldDescriptor::CPPTYPE_STRING) {
- delete val_.string_value_;
- }
- }
-
- FieldDescriptor::CppType type() const {
- if (type_ == 0) {
- GOOGLE_LOG(FATAL)
- << "Protocol Buffer map usage error:\n"
- << "MapKey::type MapKey is not initialized. "
- << "Call set methods to initialize MapKey.";
- }
- return (FieldDescriptor::CppType)type_;
- }
-
- void SetInt64Value(int64 value) {
- SetType(FieldDescriptor::CPPTYPE_INT64);
- val_.int64_value_ = value;
- }
- void SetUInt64Value(uint64 value) {
- SetType(FieldDescriptor::CPPTYPE_UINT64);
- val_.uint64_value_ = value;
- }
- void SetInt32Value(int32 value) {
- SetType(FieldDescriptor::CPPTYPE_INT32);
- val_.int32_value_ = value;
- }
- void SetUInt32Value(uint32 value) {
- SetType(FieldDescriptor::CPPTYPE_UINT32);
- val_.uint32_value_ = value;
- }
- void SetBoolValue(bool value) {
- SetType(FieldDescriptor::CPPTYPE_BOOL);
- val_.bool_value_ = value;
- }
- void SetStringValue(const string& val) {
- SetType(FieldDescriptor::CPPTYPE_STRING);
- *val_.string_value_ = val;
- }
-
- int64 GetInt64Value() const {
- TYPE_CHECK(FieldDescriptor::CPPTYPE_INT64,
- "MapKey::GetInt64Value");
- return val_.int64_value_;
- }
- uint64 GetUInt64Value() const {
- TYPE_CHECK(FieldDescriptor::CPPTYPE_UINT64,
- "MapKey::GetUInt64Value");
- return val_.uint64_value_;
- }
- int32 GetInt32Value() const {
- TYPE_CHECK(FieldDescriptor::CPPTYPE_INT32,
- "MapKey::GetInt32Value");
- return val_.int32_value_;
- }
- uint32 GetUInt32Value() const {
- TYPE_CHECK(FieldDescriptor::CPPTYPE_UINT32,
- "MapKey::GetUInt32Value");
- return val_.uint32_value_;
- }
- bool GetBoolValue() const {
- TYPE_CHECK(FieldDescriptor::CPPTYPE_BOOL,
- "MapKey::GetBoolValue");
- return val_.bool_value_;
- }
- const string& GetStringValue() const {
- TYPE_CHECK(FieldDescriptor::CPPTYPE_STRING,
- "MapKey::GetStringValue");
- return *val_.string_value_;
- }
-
- bool operator<(const MapKey& other) const {
- if (type_ != other.type_) {
- // We could define a total order that handles this case, but
- // there currently no need. So, for now, fail.
- GOOGLE_LOG(FATAL) << "Unsupported: type mismatch";
- }
- switch (type()) {
- case FieldDescriptor::CPPTYPE_DOUBLE:
- case FieldDescriptor::CPPTYPE_FLOAT:
- case FieldDescriptor::CPPTYPE_ENUM:
- case FieldDescriptor::CPPTYPE_MESSAGE:
- GOOGLE_LOG(FATAL) << "Unsupported";
- return false;
- case FieldDescriptor::CPPTYPE_STRING:
- return *val_.string_value_ < *other.val_.string_value_;
- case FieldDescriptor::CPPTYPE_INT64:
- return val_.int64_value_ < other.val_.int64_value_;
- case FieldDescriptor::CPPTYPE_INT32:
- return val_.int32_value_ < other.val_.int32_value_;
- case FieldDescriptor::CPPTYPE_UINT64:
- return val_.uint64_value_ < other.val_.uint64_value_;
- case FieldDescriptor::CPPTYPE_UINT32:
- return val_.uint32_value_ < other.val_.uint32_value_;
- case FieldDescriptor::CPPTYPE_BOOL:
- return val_.bool_value_ < other.val_.bool_value_;
- }
- return false;
- }
-
- bool operator==(const MapKey& other) const {
- if (type_ != other.type_) {
- // To be consistent with operator<, we don't allow this either.
- GOOGLE_LOG(FATAL) << "Unsupported: type mismatch";
- }
- switch (type()) {
- case FieldDescriptor::CPPTYPE_DOUBLE:
- case FieldDescriptor::CPPTYPE_FLOAT:
- case FieldDescriptor::CPPTYPE_ENUM:
- case FieldDescriptor::CPPTYPE_MESSAGE:
- GOOGLE_LOG(FATAL) << "Unsupported";
- break;
- case FieldDescriptor::CPPTYPE_STRING:
- return *val_.string_value_ == *other.val_.string_value_;
- case FieldDescriptor::CPPTYPE_INT64:
- return val_.int64_value_ == other.val_.int64_value_;
- case FieldDescriptor::CPPTYPE_INT32:
- return val_.int32_value_ == other.val_.int32_value_;
- case FieldDescriptor::CPPTYPE_UINT64:
- return val_.uint64_value_ == other.val_.uint64_value_;
- case FieldDescriptor::CPPTYPE_UINT32:
- return val_.uint32_value_ == other.val_.uint32_value_;
- case FieldDescriptor::CPPTYPE_BOOL:
- return val_.bool_value_ == other.val_.bool_value_;
- }
- GOOGLE_LOG(FATAL) << "Can't get here.";
- return false;
- }
-
- void CopyFrom(const MapKey& other) {
- SetType(other.type());
- switch (type_) {
- case FieldDescriptor::CPPTYPE_DOUBLE:
- case FieldDescriptor::CPPTYPE_FLOAT:
- case FieldDescriptor::CPPTYPE_ENUM:
- case FieldDescriptor::CPPTYPE_MESSAGE:
- GOOGLE_LOG(FATAL) << "Unsupported";
- break;
- case FieldDescriptor::CPPTYPE_STRING:
- *val_.string_value_ = *other.val_.string_value_;
- break;
- case FieldDescriptor::CPPTYPE_INT64:
- val_.int64_value_ = other.val_.int64_value_;
- break;
- case FieldDescriptor::CPPTYPE_INT32:
- val_.int32_value_ = other.val_.int32_value_;
- break;
- case FieldDescriptor::CPPTYPE_UINT64:
- val_.uint64_value_ = other.val_.uint64_value_;
- break;
- case FieldDescriptor::CPPTYPE_UINT32:
- val_.uint32_value_ = other.val_.uint32_value_;
- break;
- case FieldDescriptor::CPPTYPE_BOOL:
- val_.bool_value_ = other.val_.bool_value_;
- break;
- }
- }
-
- private:
- template <typename K, typename V>
- friend class internal::TypeDefinedMapFieldBase;
- friend class MapIterator;
- friend class internal::DynamicMapField;
-
- union KeyValue {
- KeyValue() {}
- string* string_value_;
- int64 int64_value_;
- int32 int32_value_;
- uint64 uint64_value_;
- uint32 uint32_value_;
- bool bool_value_;
- } val_;
-
- void SetType(FieldDescriptor::CppType type) {
- if (type_ == type) return;
- if (type_ == FieldDescriptor::CPPTYPE_STRING) {
- delete val_.string_value_;
- }
- type_ = type;
- if (type_ == FieldDescriptor::CPPTYPE_STRING) {
- val_.string_value_ = new string;
- }
- }
-
- // type_ is 0 or a valid FieldDescriptor::CppType.
- int type_;
-};
-
-// MapValueRef points to a map value.
-class LIBPROTOBUF_EXPORT MapValueRef {
- public:
- MapValueRef() : data_(NULL), type_(0) {}
-
- void SetInt64Value(int64 value) {
- TYPE_CHECK(FieldDescriptor::CPPTYPE_INT64,
- "MapValueRef::SetInt64Value");
- *reinterpret_cast<int64*>(data_) = value;
- }
- void SetUInt64Value(uint64 value) {
- TYPE_CHECK(FieldDescriptor::CPPTYPE_UINT64,
- "MapValueRef::SetUInt64Value");
- *reinterpret_cast<uint64*>(data_) = value;
- }
- void SetInt32Value(int32 value) {
- TYPE_CHECK(FieldDescriptor::CPPTYPE_INT32,
- "MapValueRef::SetInt32Value");
- *reinterpret_cast<int32*>(data_) = value;
- }
- void SetUInt32Value(uint32 value) {
- TYPE_CHECK(FieldDescriptor::CPPTYPE_UINT32,
- "MapValueRef::SetUInt32Value");
- *reinterpret_cast<uint32*>(data_) = value;
- }
- void SetBoolValue(bool value) {
- TYPE_CHECK(FieldDescriptor::CPPTYPE_BOOL,
- "MapValueRef::SetBoolValue");
- *reinterpret_cast<bool*>(data_) = value;
- }
- // TODO(jieluo) - Checks that enum is member.
- void SetEnumValue(int value) {
- TYPE_CHECK(FieldDescriptor::CPPTYPE_ENUM,
- "MapValueRef::SetEnumValue");
- *reinterpret_cast<int*>(data_) = value;
- }
- void SetStringValue(const string& value) {
- TYPE_CHECK(FieldDescriptor::CPPTYPE_STRING,
- "MapValueRef::SetStringValue");
- *reinterpret_cast<string*>(data_) = value;
- }
- void SetFloatValue(float value) {
- TYPE_CHECK(FieldDescriptor::CPPTYPE_FLOAT,
- "MapValueRef::SetFloatValue");
- *reinterpret_cast<float*>(data_) = value;
- }
- void SetDoubleValue(double value) {
- TYPE_CHECK(FieldDescriptor::CPPTYPE_DOUBLE,
- "MapValueRef::SetDoubleValue");
- *reinterpret_cast<double*>(data_) = value;
- }
-
- int64 GetInt64Value() const {
- TYPE_CHECK(FieldDescriptor::CPPTYPE_INT64,
- "MapValueRef::GetInt64Value");
- return *reinterpret_cast<int64*>(data_);
- }
- uint64 GetUInt64Value() const {
- TYPE_CHECK(FieldDescriptor::CPPTYPE_UINT64,
- "MapValueRef::GetUInt64Value");
- return *reinterpret_cast<uint64*>(data_);
- }
- int32 GetInt32Value() const {
- TYPE_CHECK(FieldDescriptor::CPPTYPE_INT32,
- "MapValueRef::GetInt32Value");
- return *reinterpret_cast<int32*>(data_);
- }
- uint32 GetUInt32Value() const {
- TYPE_CHECK(FieldDescriptor::CPPTYPE_UINT32,
- "MapValueRef::GetUInt32Value");
- return *reinterpret_cast<uint32*>(data_);
- }
- bool GetBoolValue() const {
- TYPE_CHECK(FieldDescriptor::CPPTYPE_BOOL,
- "MapValueRef::GetBoolValue");
- return *reinterpret_cast<bool*>(data_);
- }
- int GetEnumValue() const {
- TYPE_CHECK(FieldDescriptor::CPPTYPE_ENUM,
- "MapValueRef::GetEnumValue");
- return *reinterpret_cast<int*>(data_);
- }
- const string& GetStringValue() const {
- TYPE_CHECK(FieldDescriptor::CPPTYPE_STRING,
- "MapValueRef::GetStringValue");
- return *reinterpret_cast<string*>(data_);
- }
- float GetFloatValue() const {
- TYPE_CHECK(FieldDescriptor::CPPTYPE_FLOAT,
- "MapValueRef::GetFloatValue");
- return *reinterpret_cast<float*>(data_);
- }
- double GetDoubleValue() const {
- TYPE_CHECK(FieldDescriptor::CPPTYPE_DOUBLE,
- "MapValueRef::GetDoubleValue");
- return *reinterpret_cast<double*>(data_);
- }
-
- const Message& GetMessageValue() const {
- TYPE_CHECK(FieldDescriptor::CPPTYPE_MESSAGE,
- "MapValueRef::GetMessageValue");
- return *reinterpret_cast<Message*>(data_);
- }
-
- Message* MutableMessageValue() {
- TYPE_CHECK(FieldDescriptor::CPPTYPE_MESSAGE,
- "MapValueRef::MutableMessageValue");
- return reinterpret_cast<Message*>(data_);
- }
-
- private:
- template <typename K, typename V,
- internal::WireFormatLite::FieldType key_wire_type,
- internal::WireFormatLite::FieldType value_wire_type,
- int default_enum_value>
- friend class internal::MapField;
- template <typename K, typename V>
- friend class internal::TypeDefinedMapFieldBase;
- friend class MapIterator;
- friend class internal::GeneratedMessageReflection;
- friend class internal::DynamicMapField;
-
- void SetType(FieldDescriptor::CppType type) {
- type_ = type;
- }
-
- FieldDescriptor::CppType type() const {
- if (type_ == 0 || data_ == NULL) {
- GOOGLE_LOG(FATAL)
- << "Protocol Buffer map usage error:\n"
- << "MapValueRef::type MapValueRef is not initialized.";
- }
- return (FieldDescriptor::CppType)type_;
- }
- void SetValue(const void* val) {
- data_ = const_cast<void*>(val);
- }
- void CopyFrom(const MapValueRef& other) {
- type_ = other.type_;
- data_ = other.data_;
- }
- // Only used in DynamicMapField
- void DeleteData() {
- switch (type_) {
-#define HANDLE_TYPE(CPPTYPE, TYPE) \
- case google::protobuf::FieldDescriptor::CPPTYPE_##CPPTYPE: { \
- delete reinterpret_cast<TYPE*>(data_); \
- break; \
- }
- HANDLE_TYPE(INT32, int32);
- HANDLE_TYPE(INT64, int64);
- HANDLE_TYPE(UINT32, uint32);
- HANDLE_TYPE(UINT64, uint64);
- HANDLE_TYPE(DOUBLE, double);
- HANDLE_TYPE(FLOAT, float);
- HANDLE_TYPE(BOOL, bool);
- HANDLE_TYPE(STRING, string);
- HANDLE_TYPE(ENUM, int32);
- HANDLE_TYPE(MESSAGE, Message);
-#undef HANDLE_TYPE
- }
- }
- // data_ point to a map value. MapValueRef does not
- // own this value.
- void* data_;
- // type_ is 0 or a valid FieldDescriptor::CppType.
- int type_;
-};
-
-#undef TYPE_CHECK
-
// This is the class for google::protobuf::Map's internal value_type. Instead of using
// std::pair as value_type, we use this class which provides us more control of
// its process of construction and destruction.
@@ -523,30 +133,38 @@ class Map {
typedef size_t size_type;
typedef hash<Key> hasher;
- explicit Map(bool old_style = false)
- : arena_(NULL),
- default_enum_value_(0),
- old_style_(old_style) {
- Init();
- }
- explicit Map(Arena* arena, bool old_style = false)
- : arena_(arena),
- default_enum_value_(0),
- old_style_(old_style) {
- Init();
- }
+ Map() : arena_(NULL), default_enum_value_(0) { Init(); }
+ explicit Map(Arena* arena) : arena_(arena), default_enum_value_(0) { Init(); }
+
Map(const Map& other)
- : arena_(NULL),
- default_enum_value_(other.default_enum_value_),
- old_style_(other.old_style_) {
+ : arena_(NULL), default_enum_value_(other.default_enum_value_) {
Init();
insert(other.begin(), other.end());
}
+
+#if LANG_CXX11
+ Map(Map&& other) noexcept : Map() {
+ if (other.arena_) {
+ *this = other;
+ } else {
+ swap(other);
+ }
+ }
+ Map& operator=(Map&& other) noexcept {
+ if (this != &other) {
+ if (arena_ != other.arena_) {
+ *this = other;
+ } else {
+ swap(other);
+ }
+ }
+ return *this;
+ }
+#endif
+
template <class InputIt>
- Map(const InputIt& first, const InputIt& last, bool old_style = false)
- : arena_(NULL),
- default_enum_value_(0),
- old_style_(old_style) {
+ Map(const InputIt& first, const InputIt& last)
+ : arena_(NULL), default_enum_value_(0) {
Init();
insert(first, last);
}
@@ -554,22 +172,13 @@ class Map {
~Map() {
clear();
if (arena_ == NULL) {
- if (old_style_)
- delete deprecated_elements_;
- else
- delete elements_;
+ delete elements_;
}
}
private:
void Init() {
- if (old_style_)
- deprecated_elements_ = Arena::Create<DeprecatedInnerMap>(
- arena_, 0, hasher(), std::equal_to<Key>(),
- MapAllocator<std::pair<const Key, MapPair<Key, T>*> >(arena_));
- else
- elements_ =
- Arena::Create<InnerMap>(arena_, 0, hasher(), Allocator(arena_));
+ elements_ = Arena::Create<InnerMap>(arena_, 0u, hasher(), Allocator(arena_));
}
// re-implement std::allocator to use arena allocator for memory allocation.
@@ -592,7 +201,7 @@ class Map {
MapAllocator(const MapAllocator<X>& allocator)
: arena_(allocator.arena()) {}
- pointer allocate(size_type n, const_pointer hint = 0) {
+ pointer allocate(size_type n, const void* /* hint */ = 0) {
// If arena is not given, malloc needs to be called which doesn't
// construct element object.
if (arena_ == NULL) {
@@ -608,6 +217,7 @@ class Map {
#if defined(__GXX_DELETE_WITH_SIZE__) || defined(__cpp_sized_deallocation)
::operator delete(p, n * sizeof(value_type));
#else
+ (void)n;
::operator delete(p);
#endif
}
@@ -678,7 +288,7 @@ class Map {
const Key& key() const { return k_; }
Key& key() { return k_; }
- value_type* const value() const { return v_; }
+ value_type* value() const { return v_; }
value_type*& value() { return v_; }
private:
@@ -764,14 +374,13 @@ class Map {
};
typedef typename Allocator::template rebind<Key*>::other KeyPtrAllocator;
typedef std::set<Key*, KeyCompare, KeyPtrAllocator> Tree;
+ typedef typename Tree::iterator TreeIterator;
// iterator and const_iterator are instantiations of iterator_base.
template <typename KeyValueType>
- class iterator_base {
- public:
+ struct iterator_base {
typedef KeyValueType& reference;
typedef KeyValueType* pointer;
- typedef typename Tree::iterator TreeIterator;
// Invariants:
// node_ is always correct. This is handy because the most common
@@ -780,7 +389,7 @@ class Map {
// are updated to be correct also, but those fields can become stale
// if the underlying map is modified. When those fields are needed they
// are rechecked, and updated if necessary.
- iterator_base() : node_(NULL) {}
+ iterator_base() : node_(NULL), m_(NULL), bucket_index_(0) {}
explicit iterator_base(const InnerMap* m) : m_(m) {
SearchFrom(m->index_of_first_non_null_);
@@ -791,22 +400,15 @@ class Map {
// can convert to const_iterator" is OK but the reverse direction is not.
template <typename U>
explicit iterator_base(const iterator_base<U>& it)
- : node_(it.node_),
- m_(it.m_),
- bucket_index_(it.bucket_index_),
- tree_it_(it.tree_it_) {}
+ : node_(it.node_), m_(it.m_), bucket_index_(it.bucket_index_) {}
iterator_base(Node* n, const InnerMap* m, size_type index)
- : node_(n),
- m_(m),
- bucket_index_(index) {}
+ : node_(n), m_(m), bucket_index_(index) {}
iterator_base(TreeIterator tree_it, const InnerMap* m, size_type index)
- : node_(NodePtrFromKeyPtr(*tree_it)),
- m_(m),
- bucket_index_(index),
- tree_it_(tree_it) {
- // Invariant: iterators that use tree_it_ have an even bucket_index_.
+ : node_(NodePtrFromKeyPtr(*tree_it)), m_(m), bucket_index_(index) {
+ // Invariant: iterators that use buckets with trees have an even
+ // bucket_index_.
GOOGLE_DCHECK_EQ(bucket_index_ % 2, 0);
}
@@ -824,8 +426,7 @@ class Map {
} else if (m_->TableEntryIsTree(bucket_index_)) {
Tree* tree = static_cast<Tree*>(m_->table_[bucket_index_]);
GOOGLE_DCHECK(!tree->empty());
- tree_it_ = tree->begin();
- node_ = NodePtrFromKeyPtr(*tree_it_);
+ node_ = NodePtrFromKeyPtr(*tree->begin());
break;
}
}
@@ -843,16 +444,17 @@ class Map {
iterator_base& operator++() {
if (node_->next == NULL) {
- const bool is_list = revalidate_if_necessary();
+ TreeIterator tree_it;
+ const bool is_list = revalidate_if_necessary(&tree_it);
if (is_list) {
SearchFrom(bucket_index_ + 1);
} else {
GOOGLE_DCHECK_EQ(bucket_index_ & 1, 0);
Tree* tree = static_cast<Tree*>(m_->table_[bucket_index_]);
- if (++tree_it_ == tree->end()) {
+ if (++tree_it == tree->end()) {
SearchFrom(bucket_index_ + 2);
} else {
- node_ = NodePtrFromKeyPtr(*tree_it_);
+ node_ = NodePtrFromKeyPtr(*tree_it);
}
}
} else {
@@ -869,8 +471,9 @@ class Map {
// Assumes node_ and m_ are correct and non-NULL, but other fields may be
// stale. Fix them as needed. Then return true iff node_ points to a
- // Node in a list.
- bool revalidate_if_necessary() {
+ // Node in a list. If false is returned then *it is modified to be
+ // a valid iterator for node_.
+ bool revalidate_if_necessary(TreeIterator* it) {
GOOGLE_DCHECK(node_ != NULL && m_ != NULL);
// Force bucket_index_ to be in range.
bucket_index_ &= (m_->num_buckets_ - 1);
@@ -891,16 +494,14 @@ class Map {
// not. Revalidate just to be sure. This case is rare enough that we
// don't worry about potential optimizations, such as having a custom
// find-like method that compares Node* instead of const Key&.
- iterator_base i(m_->find(*KeyPtrFromNodePtr(node_)));
+ iterator_base i(m_->find(*KeyPtrFromNodePtr(node_), it));
bucket_index_ = i.bucket_index_;
- tree_it_ = i.tree_it_;
return m_->TableEntryIsList(bucket_index_);
}
Node* node_;
const InnerMap* m_;
size_type bucket_index_;
- TreeIterator tree_it_;
};
public:
@@ -952,7 +553,7 @@ class Map {
bool empty() const { return size() == 0; }
iterator find(const Key& k) { return iterator(FindHelper(k).first); }
- const_iterator find(const Key& k) const { return FindHelper(k).first; }
+ const_iterator find(const Key& k) const { return find(k, NULL); }
// In traditional C++ style, this performs "insert if not present."
std::pair<iterator, bool> insert(const KeyValuePair& kv) {
@@ -999,7 +600,8 @@ class Map {
void erase(iterator it) {
GOOGLE_DCHECK_EQ(it.m_, this);
- const bool is_list = it.revalidate_if_necessary();
+ typename Tree::iterator tree_it;
+ const bool is_list = it.revalidate_if_necessary(&tree_it);
size_type b = it.bucket_index_;
Node* const item = it.node_;
if (is_list) {
@@ -1010,7 +612,7 @@ class Map {
} else {
GOOGLE_DCHECK(TableEntryIsTree(b));
Tree* tree = static_cast<Tree*>(table_[b]);
- tree->erase(it.tree_it_);
+ tree->erase(*tree_it);
if (tree->empty()) {
// Force b to be the minimum of b and b ^ 1. This is important
// only because we want index_of_first_non_null_ to be correct.
@@ -1030,7 +632,14 @@ class Map {
}
private:
+ const_iterator find(const Key& k, TreeIterator* it) const {
+ return FindHelper(k, it).first;
+ }
std::pair<const_iterator, size_type> FindHelper(const Key& k) const {
+ return FindHelper(k, NULL);
+ }
+ std::pair<const_iterator, size_type> FindHelper(const Key& k,
+ TreeIterator* it) const {
size_type b = BucketNumber(k);
if (TableEntryIsNonEmptyList(b)) {
Node* node = static_cast<Node*>(table_[b]);
@@ -1048,6 +657,7 @@ class Map {
Key* key = const_cast<Key*>(&k);
typename Tree::iterator tree_it = tree->find(key);
if (tree_it != tree->end()) {
+ if (it != NULL) *it = tree_it;
return std::make_pair(const_iterator(tree_it, this, b), b);
}
}
@@ -1273,14 +883,7 @@ class Map {
size_type BucketNumber(const Key& k) const {
// We inherit from hasher, so one-arg operator() provides a hash function.
size_type h = (*const_cast<InnerMap*>(this))(k);
- // To help prevent people from making assumptions about the hash function,
- // we use the seed differently depending on NDEBUG. The default hash
- // function, the seeding, etc., are all likely to change in the future.
-#ifndef NDEBUG
- return (h * (seed_ | 1)) & (num_buckets_ - 1);
-#else
return (h + seed_) & (num_buckets_ - 1);
-#endif
}
bool IsMatch(const Key& k0, const Key& k1) const {
@@ -1290,7 +893,9 @@ class Map {
// Return a power of two no less than max(kMinTableSize, n).
// Assumes either n < kMinTableSize or n is a power of two.
size_type TableSize(size_type n) {
- return n < kMinTableSize ? kMinTableSize : n;
+ return n < static_cast<size_type>(kMinTableSize)
+ ? static_cast<size_type>(kMinTableSize)
+ : n;
}
// Use alloc_ to allocate an array of n objects of type U.
@@ -1328,16 +933,6 @@ class Map {
// Return a randomish value.
size_type Seed() const {
- // random_device can throw, so avoid it unless we are compiling with
- // exceptions enabled.
-#if __cpp_exceptions && LANG_CXX11
- try {
- std::random_device rd;
- std::knuth_b knuth(rd());
- std::uniform_int_distribution<size_type> u;
- return u(knuth);
- } catch (...) { }
-#endif
size_type s = static_cast<size_type>(reinterpret_cast<uintptr_t>(this));
#if defined(__x86_64__) && defined(__GNUC__)
uint32 hi, lo;
@@ -1356,72 +951,34 @@ class Map {
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(InnerMap);
}; // end of class InnerMap
- typedef hash_map<Key, value_type*, hash<Key>, std::equal_to<Key>,
- MapAllocator<std::pair<const Key, MapPair<Key, T>*> > >
- DeprecatedInnerMap;
-
public:
// Iterators
- class iterator_base {
- public:
- // We support "old style" and "new style" iterators for now. This is
- // temporary. Also, for "iterator()" we have an unknown category.
- // TODO(gpike): get rid of this.
- enum IteratorStyle { kUnknown, kOld, kNew };
- explicit iterator_base(IteratorStyle style) : iterator_style_(style) {}
-
- bool OldStyle() const {
- GOOGLE_DCHECK_NE(iterator_style_, kUnknown);
- return iterator_style_ == kOld;
- }
- bool UnknownStyle() const {
- return iterator_style_ == kUnknown;
- }
- bool SameStyle(const iterator_base& other) const {
- return iterator_style_ == other.iterator_style_;
- }
-
- private:
- IteratorStyle iterator_style_;
- };
-
- class const_iterator
- : private iterator_base,
- public std::iterator<std::forward_iterator_tag, value_type, ptrdiff_t,
- const value_type*, const value_type&> {
+ class const_iterator {
typedef typename InnerMap::const_iterator InnerIt;
- typedef typename DeprecatedInnerMap::const_iterator DeprecatedInnerIt;
public:
- const_iterator() : iterator_base(iterator_base::kUnknown) {}
- explicit const_iterator(const DeprecatedInnerIt& dit)
- : iterator_base(iterator_base::kOld), dit_(dit) {}
- explicit const_iterator(const InnerIt& it)
- : iterator_base(iterator_base::kNew), it_(it) {}
+ typedef std::forward_iterator_tag iterator_category;
+ typedef typename Map::value_type value_type;
+ typedef ptrdiff_t difference_type;
+ typedef const value_type* pointer;
+ typedef const value_type& reference;
- const_iterator(const const_iterator& other)
- : iterator_base(other), it_(other.it_), dit_(other.dit_) {}
+ const_iterator() {}
+ explicit const_iterator(const InnerIt& it) : it_(it) {}
const_reference operator*() const {
- return this->OldStyle() ? *dit_->second : *it_->value();
+ return *it_->value();
}
const_pointer operator->() const { return &(operator*()); }
const_iterator& operator++() {
- if (this->OldStyle())
- ++dit_;
- else
- ++it_;
+ ++it_;
return *this;
}
- const_iterator operator++(int) {
- return this->OldStyle() ? const_iterator(dit_++) : const_iterator(it_++);
- }
+ const_iterator operator++(int) { return const_iterator(it_++); }
friend bool operator==(const const_iterator& a, const const_iterator& b) {
- if (!a.SameStyle(b)) return false;
- if (a.UnknownStyle()) return true;
- return a.OldStyle() ? (a.dit_ == b.dit_) : (a.it_ == b.it_);
+ return a.it_ == b.it_;
}
friend bool operator!=(const const_iterator& a, const const_iterator& b) {
return !(a == b);
@@ -1429,48 +986,37 @@ class Map {
private:
InnerIt it_;
- DeprecatedInnerIt dit_;
};
- class iterator : private iterator_base,
- public std::iterator<std::forward_iterator_tag, value_type> {
+ class iterator {
typedef typename InnerMap::iterator InnerIt;
- typedef typename DeprecatedInnerMap::iterator DeprecatedInnerIt;
public:
- iterator() : iterator_base(iterator_base::kUnknown) {}
- explicit iterator(const DeprecatedInnerIt& dit)
- : iterator_base(iterator_base::kOld), dit_(dit) {}
- explicit iterator(const InnerIt& it)
- : iterator_base(iterator_base::kNew), it_(it) {}
+ typedef std::forward_iterator_tag iterator_category;
+ typedef typename Map::value_type value_type;
+ typedef ptrdiff_t difference_type;
+ typedef value_type* pointer;
+ typedef value_type& reference;
- reference operator*() const {
- return this->OldStyle() ? *dit_->second : *it_->value();
- }
+ iterator() {}
+ explicit iterator(const InnerIt& it) : it_(it) {}
+
+ reference operator*() const { return *it_->value(); }
pointer operator->() const { return &(operator*()); }
iterator& operator++() {
- if (this->OldStyle())
- ++dit_;
- else
- ++it_;
+ ++it_;
return *this;
}
- iterator operator++(int) {
- return this->OldStyle() ? iterator(dit_++) : iterator(it_++);
- }
+ iterator operator++(int) { return iterator(it_++); }
// Allow implicit conversion to const_iterator.
operator const_iterator() const {
- return this->OldStyle() ?
- const_iterator(typename DeprecatedInnerMap::const_iterator(dit_)) :
- const_iterator(typename InnerMap::const_iterator(it_));
+ return const_iterator(typename InnerMap::const_iterator(it_));
}
friend bool operator==(const iterator& a, const iterator& b) {
- if (!a.SameStyle(b)) return false;
- if (a.UnknownStyle()) return true;
- return a.OldStyle() ? a.dit_ == b.dit_ : a.it_ == b.it_;
+ return a.it_ == b.it_;
}
friend bool operator!=(const iterator& a, const iterator& b) {
return !(a == b);
@@ -1480,38 +1026,26 @@ class Map {
friend class Map;
InnerIt it_;
- DeprecatedInnerIt dit_;
};
- iterator begin() {
- return old_style_ ? iterator(deprecated_elements_->begin())
- : iterator(elements_->begin());
- }
- iterator end() {
- return old_style_ ? iterator(deprecated_elements_->end())
- : iterator(elements_->end());
- }
+ iterator begin() { return iterator(elements_->begin()); }
+ iterator end() { return iterator(elements_->end()); }
const_iterator begin() const {
- return old_style_ ? const_iterator(deprecated_elements_->begin())
- : const_iterator(iterator(elements_->begin()));
+ return const_iterator(iterator(elements_->begin()));
}
const_iterator end() const {
- return old_style_ ? const_iterator(deprecated_elements_->end())
- : const_iterator(iterator(elements_->end()));
+ return const_iterator(iterator(elements_->end()));
}
const_iterator cbegin() const { return begin(); }
const_iterator cend() const { return end(); }
// Capacity
- size_type size() const {
- return old_style_ ? deprecated_elements_->size() : elements_->size();
- }
+ size_type size() const { return elements_->size(); }
bool empty() const { return size() == 0; }
// Element access
T& operator[](const key_type& key) {
- value_type** value =
- old_style_ ? &(*deprecated_elements_)[key] : &(*elements_)[key];
+ value_type** value = &(*elements_)[key];
if (*value == NULL) {
*value = CreateValueTypeInternal(key);
internal::MapValueInitializer<google::protobuf::is_proto_enum<T>::value,
@@ -1522,28 +1056,25 @@ class Map {
}
const T& at(const key_type& key) const {
const_iterator it = find(key);
- GOOGLE_CHECK(it != end());
+ GOOGLE_CHECK(it != end()) << "key not found: " << key;
return it->second;
}
T& at(const key_type& key) {
iterator it = find(key);
- GOOGLE_CHECK(it != end());
+ GOOGLE_CHECK(it != end()) << "key not found: " << key;
return it->second;
}
// Lookup
size_type count(const key_type& key) const {
- if (find(key) != end()) assert(key == find(key)->first);
- return find(key) == end() ? 0 : 1;
+ const_iterator it = find(key);
+ GOOGLE_DCHECK(it == end() || key == it->first);
+ return it == end() ? 0 : 1;
}
const_iterator find(const key_type& key) const {
- return old_style_ ? const_iterator(deprecated_elements_->find(key))
- : const_iterator(iterator(elements_->find(key)));
- }
- iterator find(const key_type& key) {
- return old_style_ ? iterator(deprecated_elements_->find(key))
- : iterator(elements_->find(key));
+ return const_iterator(iterator(elements_->find(key)));
}
+ iterator find(const key_type& key) { return iterator(elements_->find(key)); }
std::pair<const_iterator, const_iterator> equal_range(
const key_type& key) const {
const_iterator it = find(key);
@@ -1566,23 +1097,12 @@ class Map {
// insert
std::pair<iterator, bool> insert(const value_type& value) {
- if (old_style_) {
- iterator it = find(value.first);
- if (it != end()) {
- return std::pair<iterator, bool>(it, false);
- } else {
- return std::pair<iterator, bool>(
- iterator(deprecated_elements_->insert(std::pair<Key, value_type*>(
- value.first, CreateValueTypeInternal(value))).first), true);
- }
- } else {
- std::pair<typename InnerMap::iterator, bool> p =
- elements_->insert(value.first);
- if (p.second) {
- p.first->value() = CreateValueTypeInternal(value);
- }
- return std::pair<iterator, bool>(iterator(p.first), p.second);
+ std::pair<typename InnerMap::iterator, bool> p =
+ elements_->insert(value.first);
+ if (p.second) {
+ p.first->value() = CreateValueTypeInternal(value);
}
+ return std::pair<iterator, bool>(iterator(p.first), p.second);
}
template <class InputIt>
void insert(InputIt first, InputIt last) {
@@ -1607,10 +1127,7 @@ class Map {
iterator erase(iterator pos) {
if (arena_ == NULL) delete pos.operator->();
iterator i = pos++;
- if (old_style_)
- deprecated_elements_->erase(i.dit_);
- else
- elements_->erase(i.it_);
+ elements_->erase(i.it_);
return pos;
}
void erase(iterator first, iterator last) {
@@ -1630,13 +1147,9 @@ class Map {
}
void swap(Map& other) {
- if (arena_ == other.arena_ && old_style_ == other.old_style_) {
+ if (arena_ == other.arena_) {
std::swap(default_enum_value_, other.default_enum_value_);
- if (old_style_) {
- std::swap(deprecated_elements_, other.deprecated_elements_);
- } else {
- std::swap(elements_, other.elements_);
- }
+ std::swap(elements_, other.elements_);
} else {
// TODO(zuguang): optimize this. The temporary copy can be allocated
// in the same arena as the other message, and the "other = copy" can
@@ -1649,10 +1162,7 @@ class Map {
// Access to hasher. Currently this returns a copy, but it may
// be modified to return a const reference in the future.
- hasher hash_function() const {
- return old_style_ ? deprecated_elements_->hash_function()
- : elements_->hash_function();
- }
+ hasher hash_function() const { return elements_->hash_function(); }
private:
// Set default enum value only for proto2 map field whose value is enum type.
@@ -1689,19 +1199,12 @@ class Map {
Arena* arena_;
int default_enum_value_;
- // The following is a tagged union because we support two map styles
- // for now.
- // TODO(gpike): get rid of the old style.
- const bool old_style_;
- union {
- InnerMap* elements_;
- DeprecatedInnerMap* deprecated_elements_;
- };
+ InnerMap* elements_;
friend class ::google::protobuf::Arena;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
- template <typename K, typename V,
+ template <typename Derived, typename K, typename V,
internal::WireFormatLite::FieldType key_wire_type,
internal::WireFormatLite::FieldType value_wire_type,
int default_enum_value>
@@ -1709,42 +1212,6 @@ class Map {
};
} // namespace protobuf
-} // namespace google
-
-GOOGLE_PROTOBUF_HASH_NAMESPACE_DECLARATION_START
-template<>
-struct hash<google::protobuf::MapKey> {
- size_t
- operator()(const google::protobuf::MapKey& map_key) const {
- switch (map_key.type()) {
- case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE:
- case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT:
- case google::protobuf::FieldDescriptor::CPPTYPE_ENUM:
- case google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE:
- GOOGLE_LOG(FATAL) << "Unsupported";
- break;
- case google::protobuf::FieldDescriptor::CPPTYPE_STRING:
- return hash<string>()(map_key.GetStringValue());
- case google::protobuf::FieldDescriptor::CPPTYPE_INT64:
- return hash< ::google::protobuf::int64>()(map_key.GetInt64Value());
- case google::protobuf::FieldDescriptor::CPPTYPE_INT32:
- return hash< ::google::protobuf::int32>()(map_key.GetInt32Value());
- case google::protobuf::FieldDescriptor::CPPTYPE_UINT64:
- return hash< ::google::protobuf::uint64>()(map_key.GetUInt64Value());
- case google::protobuf::FieldDescriptor::CPPTYPE_UINT32:
- return hash< ::google::protobuf::uint32>()(map_key.GetUInt32Value());
- case google::protobuf::FieldDescriptor::CPPTYPE_BOOL:
- return hash<bool>()(map_key.GetBoolValue());
- }
- GOOGLE_LOG(FATAL) << "Can't get here.";
- return 0;
- }
- bool
- operator()(const google::protobuf::MapKey& map_key1,
- const google::protobuf::MapKey& map_key2) const {
- return map_key1 < map_key2;
- }
-};
-GOOGLE_PROTOBUF_HASH_NAMESPACE_DECLARATION_END
+} // namespace google
#endif // GOOGLE_PROTOBUF_MAP_H__
diff --git a/src/google/protobuf/map_entry.h b/src/google/protobuf/map_entry.h
index 07c24c02..801def97 100644
--- a/src/google/protobuf/map_entry.h
+++ b/src/google/protobuf/map_entry.h
@@ -43,10 +43,9 @@ namespace google {
namespace protobuf {
class Arena;
namespace internal {
-template <typename Key, typename Value,
+template <typename Derived, typename Key, typename Value,
WireFormatLite::FieldType kKeyFieldType,
- WireFormatLite::FieldType kValueFieldType,
- int default_enum_value>
+ WireFormatLite::FieldType kValueFieldType, int default_enum_value>
class MapField;
}
}
@@ -54,30 +53,6 @@ class MapField;
namespace protobuf {
namespace internal {
-// Register all MapEntry default instances so we can delete them in
-// ShutdownProtobufLibrary().
-void LIBPROTOBUF_EXPORT RegisterMapEntryDefaultInstance(
- MessageLite* default_instance);
-
-// This is the common base class for MapEntry. It is used by MapFieldBase in
-// reflection api, in which the static type of key and value is unknown.
-class LIBPROTOBUF_EXPORT MapEntryBase : public Message {
- public:
- ::google::protobuf::Metadata GetMetadata() const {
- ::google::protobuf::Metadata metadata;
- metadata.descriptor = descriptor_;
- metadata.reflection = reflection_;
- return metadata;
- }
-
- protected:
- MapEntryBase() : descriptor_(NULL), reflection_(NULL) { }
- virtual ~MapEntryBase() {}
-
- const Descriptor* descriptor_;
- const Reflection* reflection_;
-};
-
// MapEntry is the returned google::protobuf::Message when calling AddMessage of
// google::protobuf::Reflection. In order to let it work with generated message
// reflection, its in-memory type is the same as generated message with the same
@@ -105,213 +80,58 @@ class LIBPROTOBUF_EXPORT MapEntryBase : public Message {
// while we need to explicitly specify the cpp type if proto type is
// TYPE_MESSAGE to infer the in-memory type. Moreover, default_enum_value is
// used to initialize enum field in proto2.
-template <typename Key, typename Value,
+template <typename Derived, typename Key, typename Value,
WireFormatLite::FieldType kKeyFieldType,
- WireFormatLite::FieldType kValueFieldType,
- int default_enum_value>
-class MapEntry : public MapEntryBase {
- // Provide utilities to parse/serialize key/value. Provide utilities to
- // manipulate internal stored type.
- typedef MapTypeHandler<kKeyFieldType, Key> KeyTypeHandler;
- typedef MapTypeHandler<kValueFieldType, Value> ValueTypeHandler;
-
- // Enum type cannot be used for MapTypeHandler::Read. Define a type
- // which will replace Enum with int.
- typedef typename KeyTypeHandler::MapEntryAccessorType KeyMapEntryAccessorType;
- typedef typename ValueTypeHandler::MapEntryAccessorType
- ValueMapEntryAccessorType;
-
- // Abbreviation for MapEntry
- typedef typename google::protobuf::internal::MapEntry<
- Key, Value, kKeyFieldType, kValueFieldType, default_enum_value> EntryType;
-
- // Abbreviation for MapEntryLite
- typedef typename google::protobuf::internal::MapEntryLite<
- Key, Value, kKeyFieldType, kValueFieldType, default_enum_value>
- EntryLiteType;
-
+ WireFormatLite::FieldType kValueFieldType, int default_enum_value>
+class MapEntry
+ : public MapEntryImpl<Derived, Message, Key, Value, kKeyFieldType,
+ kValueFieldType, default_enum_value> {
public:
- ~MapEntry() {
- if (this == default_instance_) {
- delete reflection_;
- }
- }
-
- // accessors ======================================================
-
- virtual inline const KeyMapEntryAccessorType& key() const {
- return entry_lite_.key();
- }
- inline KeyMapEntryAccessorType* mutable_key() {
- return entry_lite_.mutable_key();
- }
- virtual inline const ValueMapEntryAccessorType& value() const {
- return entry_lite_.value();
- }
- inline ValueMapEntryAccessorType* mutable_value() {
- return entry_lite_.mutable_value();
- }
-
- // implements Message =============================================
-
- bool MergePartialFromCodedStream(::google::protobuf::io::CodedInputStream* input) {
- return entry_lite_.MergePartialFromCodedStream(input);
- }
-
- size_t ByteSizeLong() const {
- return entry_lite_.ByteSizeLong();
- }
-
- void SerializeWithCachedSizes(::google::protobuf::io::CodedOutputStream* output) const {
- entry_lite_.SerializeWithCachedSizes(output);
- }
-
- ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(bool deterministic,
- ::google::protobuf::uint8* output) const {
- return entry_lite_.InternalSerializeWithCachedSizesToArray(deterministic,
- output);
- }
-
- int GetCachedSize() const {
- return entry_lite_.GetCachedSize();
- }
-
- bool IsInitialized() const {
- return entry_lite_.IsInitialized();
- }
-
- Message* New() const {
- MapEntry* entry = new MapEntry;
- entry->descriptor_ = descriptor_;
- entry->reflection_ = reflection_;
- entry->set_default_instance(default_instance_);
- return entry;
- }
-
- Message* New(Arena* arena) const {
- MapEntry* entry = Arena::CreateMessage<MapEntry>(arena);
- entry->descriptor_ = descriptor_;
- entry->reflection_ = reflection_;
- entry->set_default_instance(default_instance_);
- return entry;
- }
-
- int SpaceUsed() const {
- int size = sizeof(MapEntry);
- size += entry_lite_.SpaceUsed();
- return size;
- }
-
- void CopyFrom(const ::google::protobuf::Message& from) {
- Clear();
- MergeFrom(from);
- }
-
- void MergeFrom(const ::google::protobuf::Message& from) {
- GOOGLE_CHECK_NE(&from, this);
- const MapEntry* source = dynamic_cast_if_available<const MapEntry*>(&from);
- if (source == NULL) {
- ReflectionOps::Merge(from, this);
- } else {
- MergeFrom(*source);
- }
- }
-
- void CopyFrom(const MapEntry& from) {
- Clear();
- MergeFrom(from);
- }
-
- void MergeFrom(const MapEntry& from) {
- entry_lite_.MergeFrom(from.entry_lite_);
- }
-
- void Clear() {
- entry_lite_.Clear();
- }
-
- void InitAsDefaultInstance() {
- entry_lite_.InitAsDefaultInstance();
- }
-
- Arena* GetArena() const {
- return entry_lite_.GetArena();
- }
-
- // Create default MapEntry instance for given descriptor. Descriptor has to be
- // given when creating default MapEntry instance because different map field
- // may have the same type and MapEntry class. The given descriptor is needed
- // to distinguish instances of the same MapEntry class.
- static MapEntry* CreateDefaultInstance(const Descriptor* descriptor) {
- MapEntry* entry = new MapEntry;
- ReflectionSchema schema = {
- entry,
- offsets_,
- has_bits_,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MapEntry, entry_lite_._has_bits_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MapEntry, _internal_metadata_),
- -1,
- NULL,
- -1,
- sizeof(MapEntry)};
- const Reflection* reflection = new GeneratedMessageReflection(
- descriptor, schema, DescriptorPool::generated_pool(),
- MessageFactory::generated_factory());
- entry->descriptor_ = descriptor;
- entry->reflection_ = reflection;
- entry->set_default_instance(entry);
- entry->InitAsDefaultInstance();
- RegisterMapEntryDefaultInstance(entry);
- return entry;
- }
-
- private:
- MapEntry()
- : _internal_metadata_(NULL), default_instance_(NULL), entry_lite_() {}
-
+ MapEntry() : _internal_metadata_(NULL) {}
explicit MapEntry(Arena* arena)
- : _internal_metadata_(arena),
- default_instance_(NULL),
- entry_lite_(arena) {}
-
- inline Arena* GetArenaNoVirtual() const {
- return entry_lite_.GetArenaNoVirtual();
- }
-
- void set_default_instance(MapEntry* default_instance) {
- default_instance_ = default_instance;
- entry_lite_.set_default_instance(&default_instance->entry_lite_);
- }
+ : MapEntryImpl<Derived, Message, Key, Value, kKeyFieldType,
+ kValueFieldType, default_enum_value>(arena),
+ _internal_metadata_(arena) {}
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
- static uint32 offsets_[2];
- static uint32 has_bits_[2];
InternalMetadataWithArena _internal_metadata_;
- MapEntry* default_instance_;
- EntryLiteType entry_lite_;
+ private:
friend class ::google::protobuf::Arena;
- typedef void InternalArenaConstructable_;
- typedef void DestructorSkippable_;
- template <typename K, typename V, WireFormatLite::FieldType k_wire_type,
- WireFormatLite::FieldType, int default_enum>
+ template <typename C, typename K, typename V,
+ WireFormatLite::FieldType k_wire_type, WireFormatLite::FieldType,
+ int default_enum>
friend class internal::MapField;
friend class internal::GeneratedMessageReflection;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapEntry);
};
-template <typename Key, typename Value, WireFormatLite::FieldType kKeyFieldType,
+// Specialization for the full runtime
+template <typename Derived, typename Key, typename Value,
+ WireFormatLite::FieldType kKeyFieldType,
WireFormatLite::FieldType kValueFieldType, int default_enum_value>
-uint32 MapEntry<Key, Value, kKeyFieldType, kValueFieldType,
- default_enum_value>::offsets_[2] = {
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MapEntry, entry_lite_.key_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MapEntry, entry_lite_.value_),
+struct MapEntryHelper<MapEntry<Derived, Key, Value, kKeyFieldType,
+ kValueFieldType, default_enum_value> >
+ : MapEntryHelper<MapEntryLite<Derived, Key, Value, kKeyFieldType,
+ kValueFieldType, default_enum_value> > {
+ explicit MapEntryHelper(const MapPair<Key, Value>& map_pair)
+ : MapEntryHelper<MapEntryLite<Derived, Key, Value, kKeyFieldType,
+ kValueFieldType, default_enum_value> >(
+ map_pair) {}
};
-template <typename Key, typename Value, WireFormatLite::FieldType kKeyFieldType,
- WireFormatLite::FieldType kValueFieldType, int default_enum_value>
-uint32 MapEntry<Key, Value, kKeyFieldType, kValueFieldType,
- default_enum_value>::has_bits_[2] = {0, 1};
+template <typename Derived, typename K, typename V,
+ WireFormatLite::FieldType key, WireFormatLite::FieldType value,
+ int default_enum>
+struct DeconstructMapEntry<MapEntry<Derived, K, V, key, value, default_enum> > {
+ typedef K Key;
+ typedef V Value;
+ static const WireFormatLite::FieldType kKeyFieldType = key;
+ static const WireFormatLite::FieldType kValueFieldType = value;
+ static const int default_enum_value = default_enum;
+};
} // namespace internal
} // namespace protobuf
diff --git a/src/google/protobuf/map_entry_lite.h b/src/google/protobuf/map_entry_lite.h
index bb1d7e06..7c477c56 100644
--- a/src/google/protobuf/map_entry_lite.h
+++ b/src/google/protobuf/map_entry_lite.h
@@ -32,22 +32,23 @@
#define GOOGLE_PROTOBUF_MAP_ENTRY_LITE_H__
#include <assert.h>
+
+#include <google/protobuf/arena.h>
+#include <google/protobuf/map.h>
#include <google/protobuf/map_type_handler.h>
+#include <google/protobuf/stubs/port.h>
#include <google/protobuf/wire_format_lite_inl.h>
namespace google {
namespace protobuf {
-class Arena;
namespace internal {
-template <typename Key, typename Value,
+template <typename Derived, typename Key, typename Value,
WireFormatLite::FieldType kKeyFieldType,
- WireFormatLite::FieldType kValueFieldType,
- int default_enum_value>
+ WireFormatLite::FieldType kValueFieldType, int default_enum_value>
class MapEntry;
-template <typename Key, typename Value,
+template <typename Derived, typename Key, typename Value,
WireFormatLite::FieldType kKeyFieldType,
- WireFormatLite::FieldType kValueFieldType,
- int default_enum_value>
+ WireFormatLite::FieldType kValueFieldType, int default_enum_value>
class MapFieldLite;
} // namespace internal
} // namespace protobuf
@@ -87,13 +88,14 @@ struct MoveHelper<false, false, true, T> { // strings and similar
}
};
-// MapEntryLite is used to implement parsing and serialization of map for lite
-// runtime.
-template <typename Key, typename Value,
+// MapEntryImpl is used to implement parsing and serialization of map entries.
+// It uses Curious Recursive Template Pattern (CRTP) to provide the type of
+// the eventual code to the template code.
+template <typename Derived, typename Base, typename Key, typename Value,
WireFormatLite::FieldType kKeyFieldType,
- WireFormatLite::FieldType kValueFieldType,
- int default_enum_value>
-class MapEntryLite : public MessageLite {
+ WireFormatLite::FieldType kValueFieldType, int default_enum_value>
+class MapEntryImpl : public Base {
+ protected:
// Provide utilities to parse/serialize key/value. Provide utilities to
// manipulate internal stored type.
typedef MapTypeHandler<kKeyFieldType, Key> KeyTypeHandler;
@@ -122,12 +124,33 @@ class MapEntryLite : public MessageLite {
static const size_t kTagSize = 1;
public:
- ~MapEntryLite() {
- if (this != default_instance_) {
- if (GetArenaNoVirtual() != NULL) return;
- KeyTypeHandler::DeleteNoArena(key_);
- ValueTypeHandler::DeleteNoArena(value_);
- }
+ // Work-around for a compiler bug (see repeated_field.h).
+ typedef void MapEntryHasMergeTypeTrait;
+ typedef Derived EntryType;
+ typedef Key EntryKeyType;
+ typedef Value EntryValueType;
+ static const WireFormatLite::FieldType kEntryKeyFieldType = kKeyFieldType;
+ static const WireFormatLite::FieldType kEntryValueFieldType = kValueFieldType;
+ static const int kEntryDefaultEnumValue = default_enum_value;
+
+ MapEntryImpl() : arena_(NULL) {
+ KeyTypeHandler::Initialize(&key_, NULL);
+ ValueTypeHandler::InitializeMaybeByDefaultEnum(&value_, default_enum_value,
+ NULL);
+ _has_bits_[0] = 0;
+ }
+
+ explicit MapEntryImpl(Arena* arena) : arena_(arena) {
+ KeyTypeHandler::Initialize(&key_, arena);
+ ValueTypeHandler::InitializeMaybeByDefaultEnum(&value_, default_enum_value,
+ arena);
+ _has_bits_[0] = 0;
+ }
+
+ ~MapEntryImpl() {
+ if (GetArenaNoVirtual() != NULL) return;
+ KeyTypeHandler::DeleteNoArena(key_);
+ ValueTypeHandler::DeleteNoArena(value_);
}
// accessors ======================================================
@@ -136,9 +159,8 @@ class MapEntryLite : public MessageLite {
return KeyTypeHandler::GetExternalReference(key_);
}
virtual inline const ValueMapEntryAccessorType& value() const {
- GOOGLE_CHECK(default_instance_ != NULL);
- return ValueTypeHandler::DefaultIfNotInitialized(value_,
- default_instance_->value_);
+ return ValueTypeHandler::DefaultIfNotInitialized(
+ value_, Derived::internal_default_instance()->value_);
}
inline KeyMapEntryAccessorType* mutable_key() {
set_has_key();
@@ -151,12 +173,12 @@ class MapEntryLite : public MessageLite {
// implements MessageLite =========================================
- // MapEntryLite is for implementation only and this function isn't called
+ // MapEntryImpl is for implementation only and this function isn't called
// anywhere. Just provide a fake implementation here for MessageLite.
string GetTypeName() const { return ""; }
void CheckTypeAndMergeFrom(const MessageLite& other) {
- MergeFrom(*::google::protobuf::down_cast<const MapEntryLite*>(&other));
+ MergeFromInternal(*::google::protobuf::down_cast<const Derived*>(&other));
}
bool MergePartialFromCodedStream(::google::protobuf::io::CodedInputStream* input) {
@@ -203,8 +225,10 @@ class MapEntryLite : public MessageLite {
size_t ByteSizeLong() const {
size_t size = 0;
- size += has_key() ? kTagSize + KeyTypeHandler::ByteSize(key()) : 0;
- size += has_value() ? kTagSize + ValueTypeHandler::ByteSize(value()) : 0;
+ size += has_key() ?
+ kTagSize + static_cast<size_t>(KeyTypeHandler::ByteSize(key())) : 0;
+ size += has_value() ?
+ kTagSize + static_cast<size_t>(ValueTypeHandler::ByteSize(value())) : 0;
return size;
}
@@ -221,44 +245,43 @@ class MapEntryLite : public MessageLite {
deterministic, output);
return output;
}
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
+
+ // Don't override SerializeWithCachedSizesToArray. Use MessageLite's.
int GetCachedSize() const {
int size = 0;
size += has_key()
- ? kTagSize + KeyTypeHandler::GetCachedSize(key())
+ ? static_cast<int>(kTagSize) + KeyTypeHandler::GetCachedSize(key())
: 0;
size += has_value()
- ? kTagSize + ValueTypeHandler::GetCachedSize(
- value())
+ ? static_cast<int>(kTagSize) + ValueTypeHandler::GetCachedSize(value())
: 0;
return size;
}
bool IsInitialized() const { return ValueTypeHandler::IsInitialized(value_); }
- MessageLite* New() const {
- MapEntryLite* entry = new MapEntryLite;
- entry->default_instance_ = default_instance_;
+ Base* New() const {
+ Derived* entry = new Derived;
return entry;
}
- MessageLite* New(Arena* arena) const {
- MapEntryLite* entry = Arena::CreateMessage<MapEntryLite>(arena);
- entry->default_instance_ = default_instance_;
+ Base* New(Arena* arena) const {
+ Derived* entry = Arena::CreateMessage<Derived>(arena);
return entry;
}
- int SpaceUsed() const {
- int size = sizeof(MapEntryLite);
- size += KeyTypeHandler::SpaceUsedInMapEntry(key_);
- size += ValueTypeHandler::SpaceUsedInMapEntry(value_);
+ size_t SpaceUsedLong() const {
+ size_t size = sizeof(Derived);
+ size += KeyTypeHandler::SpaceUsedInMapEntryLong(key_);
+ size += ValueTypeHandler::SpaceUsedInMapEntryLong(value_);
return size;
}
- void MergeFrom(const MapEntryLite& from) {
+ protected:
+ // We can't declare this function directly here as it would hide the other
+ // overload (const Message&).
+ void MergeFromInternal(const MapEntryImpl& from) {
if (from._has_bits_[0]) {
if (from.has_key()) {
KeyTypeHandler::EnsureMutable(&key_, GetArenaNoVirtual());
@@ -273,6 +296,7 @@ class MapEntryLite : public MessageLite {
}
}
+ public:
void Clear() {
KeyTypeHandler::Clear(&key_, GetArenaNoVirtual());
ValueTypeHandler::ClearMaybeByDefaultEnum(
@@ -281,33 +305,28 @@ class MapEntryLite : public MessageLite {
clear_has_value();
}
- void InitAsDefaultInstance() {
- KeyTypeHandler::AssignDefaultValue(&key_);
- ValueTypeHandler::AssignDefaultValue(&value_);
+ static void InitAsDefaultInstance() {
+ Derived* d = const_cast<Derived*>(Derived::internal_default_instance());
+ KeyTypeHandler::AssignDefaultValue(&d->key_);
+ ValueTypeHandler::AssignDefaultValue(&d->value_);
}
Arena* GetArena() const {
return GetArenaNoVirtual();
}
- // Create a MapEntryLite for given key and value from google::protobuf::Map in
+ // Create a MapEntryImpl for given key and value from google::protobuf::Map in
// serialization. This function is only called when value is enum. Enum is
// treated differently because its type in MapEntry is int and its type in
// google::protobuf::Map is enum. We cannot create a reference to int from an enum.
- static MapEntryLite* EnumWrap(const Key& key, const Value value,
- Arena* arena) {
- return Arena::CreateMessage<MapEnumEntryWrapper<
- Key, Value, kKeyFieldType, kValueFieldType, default_enum_value> >(
- arena, key, value);
+ static Derived* EnumWrap(const Key& key, const Value value, Arena* arena) {
+ return Arena::CreateMessage<MapEnumEntryWrapper>(arena, key, value);
}
// Like above, but for all the other types. This avoids value copy to create
- // MapEntryLite from google::protobuf::Map in serialization.
- static MapEntryLite* Wrap(const Key& key, const Value& value, Arena* arena) {
- return Arena::CreateMessage<MapEntryWrapper<Key, Value, kKeyFieldType,
- kValueFieldType,
- default_enum_value> >(
- arena, key, value);
+ // MapEntryImpl from google::protobuf::Map in serialization.
+ static Derived* Wrap(const Key& key, const Value& value, Arena* arena) {
+ return Arena::CreateMessage<MapEntryWrapper>(arena, key, value);
}
// Parsing using MergePartialFromCodedStream, above, is not as
@@ -367,7 +386,7 @@ class MapEntryLite : public MessageLite {
const Value& value() const { return *value_ptr_; }
private:
- void UseKeyAndValueFromEntry() GOOGLE_ATTRIBUTE_COLD {
+ void UseKeyAndValueFromEntry() GOOGLE_PROTOBUF_ATTRIBUTE_COLD {
// Update key_ in case we need it later (because key() is called).
// This is potentially inefficient, especially if the key is
// expensive to copy (e.g., a long string), but this is a cold
@@ -385,7 +404,7 @@ class MapEntryLite : public MessageLite {
// into map_, we are not at the end of the input. This is unusual, but
// allowed by the spec.
bool ReadBeyondKeyValuePair(::google::protobuf::io::CodedInputStream* input)
- GOOGLE_ATTRIBUTE_COLD {
+ GOOGLE_PROTOBUF_ATTRIBUTE_COLD {
typedef MoveHelper<KeyTypeHandler::kIsEnum,
KeyTypeHandler::kIsMessage,
KeyTypeHandler::kWireType ==
@@ -412,7 +431,7 @@ class MapEntryLite : public MessageLite {
Value* value_ptr_;
// On the fast path entry_ is not used. And, when entry_ is used, it's set
// to mf_->NewEntry(), so in the arena case we must call entry_.release.
- google::protobuf::scoped_ptr<MapEntryLite> entry_;
+ google::protobuf::scoped_ptr<MapEntryImpl> entry_;
};
protected:
@@ -434,21 +453,17 @@ class MapEntryLite : public MessageLite {
// involves copy of key and value to construct a MapEntry. In order to avoid
// this copy in constructing a MapEntry, we need the following class which
// only takes references of given key and value.
- template <typename K, typename V, WireFormatLite::FieldType k_wire_type,
- WireFormatLite::FieldType v_wire_type, int default_enum>
- class MapEntryWrapper
- : public MapEntryLite<K, V, k_wire_type, v_wire_type, default_enum> {
- typedef MapEntryLite<K, V, k_wire_type, v_wire_type, default_enum> Base;
- typedef typename Base::KeyMapEntryAccessorType KeyMapEntryAccessorType;
- typedef typename Base::ValueMapEntryAccessorType ValueMapEntryAccessorType;
+ class MapEntryWrapper : public Derived {
+ typedef Derived BaseClass;
+ typedef typename BaseClass::KeyMapEntryAccessorType KeyMapEntryAccessorType;
+ typedef
+ typename BaseClass::ValueMapEntryAccessorType ValueMapEntryAccessorType;
public:
- MapEntryWrapper(Arena* arena, const K& key, const V& value)
- : MapEntryLite<K, V, k_wire_type, v_wire_type, default_enum>(arena),
- key_(key),
- value_(value) {
- Base::set_has_key();
- Base::set_has_value();
+ MapEntryWrapper(Arena* arena, const Key& key, const Value& value)
+ : Derived(arena), key_(key), value_(value) {
+ BaseClass::set_has_key();
+ BaseClass::set_has_value();
}
inline const KeyMapEntryAccessorType& key() const { return key_; }
inline const ValueMapEntryAccessorType& value() const { return value_; }
@@ -468,21 +483,17 @@ class MapEntryLite : public MessageLite {
// initialize a reference to int with a reference to enum, compiler will
// generate a temporary int from enum and initialize the reference to int with
// the temporary.
- template <typename K, typename V, WireFormatLite::FieldType k_wire_type,
- WireFormatLite::FieldType v_wire_type, int default_enum>
- class MapEnumEntryWrapper
- : public MapEntryLite<K, V, k_wire_type, v_wire_type, default_enum> {
- typedef MapEntryLite<K, V, k_wire_type, v_wire_type, default_enum> Base;
- typedef typename Base::KeyMapEntryAccessorType KeyMapEntryAccessorType;
- typedef typename Base::ValueMapEntryAccessorType ValueMapEntryAccessorType;
+ class MapEnumEntryWrapper : public Derived {
+ typedef Derived BaseClass;
+ typedef typename BaseClass::KeyMapEntryAccessorType KeyMapEntryAccessorType;
+ typedef
+ typename BaseClass::ValueMapEntryAccessorType ValueMapEntryAccessorType;
public:
- MapEnumEntryWrapper(Arena* arena, const K& key, const V& value)
- : MapEntryLite<K, V, k_wire_type, v_wire_type, default_enum>(arena),
- key_(key),
- value_(value) {
- Base::set_has_key();
- Base::set_has_value();
+ MapEnumEntryWrapper(Arena* arena, const Key& key, const Value& value)
+ : Derived(arena), key_(key), value_(value) {
+ BaseClass::set_has_key();
+ BaseClass::set_has_value();
}
inline const KeyMapEntryAccessorType& key() const { return key_; }
inline const ValueMapEntryAccessorType& value() const { return value_; }
@@ -495,48 +506,62 @@ class MapEntryLite : public MessageLite {
typedef void DestructorSkippable_;
};
- MapEntryLite() : default_instance_(NULL), arena_(NULL) {
- KeyTypeHandler::Initialize(&key_, NULL);
- ValueTypeHandler::InitializeMaybeByDefaultEnum(
- &value_, default_enum_value, NULL);
- _has_bits_[0] = 0;
- }
-
- explicit MapEntryLite(Arena* arena)
- : default_instance_(NULL), arena_(arena) {
- KeyTypeHandler::Initialize(&key_, arena);
- ValueTypeHandler::InitializeMaybeByDefaultEnum(
- &value_, default_enum_value, arena);
- _has_bits_[0] = 0;
- }
-
inline Arena* GetArenaNoVirtual() const {
return arena_;
}
- void set_default_instance(MapEntryLite* default_instance) {
- default_instance_ = default_instance;
- }
-
- MapEntryLite* default_instance_;
-
+ public: // Needed for constructing tables
KeyOnMemory key_;
ValueOnMemory value_;
Arena* arena_;
uint32 _has_bits_[1];
+ private:
friend class ::google::protobuf::Arena;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
- template <typename K, typename V, WireFormatLite::FieldType,
+ template <typename C, typename K, typename V, WireFormatLite::FieldType,
WireFormatLite::FieldType, int>
friend class internal::MapEntry;
- template <typename K, typename V, WireFormatLite::FieldType,
+ template <typename C, typename K, typename V, WireFormatLite::FieldType,
WireFormatLite::FieldType, int>
friend class internal::MapFieldLite;
+ GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapEntryImpl);
+};
+
+template <typename T, typename Key, typename Value,
+ WireFormatLite::FieldType kKeyFieldType,
+ WireFormatLite::FieldType kValueFieldType, int default_enum_value>
+class MapEntryLite
+ : public MapEntryImpl<T, MessageLite, Key, Value, kKeyFieldType,
+ kValueFieldType, default_enum_value> {
+ public:
+ typedef MapEntryImpl<T, MessageLite, Key, Value, kKeyFieldType,
+ kValueFieldType, default_enum_value>
+ SuperType;
+ MapEntryLite() {}
+ explicit MapEntryLite(Arena* arena) : SuperType(arena) {}
+ void MergeFrom(const MapEntryLite& other) { MergeFromInternal(other); }
+
+ private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapEntryLite);
};
+// The completely unprincipled and unwieldy use of template parameters in
+// the map code necessitates wrappers to make the code a little bit more
+// manageable.
+template <typename Derived>
+struct DeconstructMapEntry;
+
+template <typename T, typename K, typename V, WireFormatLite::FieldType key,
+ WireFormatLite::FieldType value, int default_enum>
+struct DeconstructMapEntry<MapEntryLite<T, K, V, key, value, default_enum> > {
+ typedef K Key;
+ typedef V Value;
+ static const WireFormatLite::FieldType kKeyFieldType = key;
+ static const WireFormatLite::FieldType kValueFieldType = value;
+ static const int default_enum_value = default_enum;
+};
// Helpers for deterministic serialization =============================
@@ -564,6 +589,76 @@ template <typename T> struct CompareByDerefFirst {
}
};
+// Helper for table driven serialization
+
+template <WireFormatLite::FieldType FieldType>
+struct FromHelper {
+ template <typename T>
+ static const T& From(const T& x) {
+ return x;
+ }
+};
+
+template <>
+struct FromHelper<WireFormatLite::TYPE_STRING> {
+ static ArenaStringPtr From(const string& x) {
+ ArenaStringPtr res;
+ *res.UnsafeRawStringPointer() = const_cast<string*>(&x);
+ return res;
+ }
+};
+template <>
+struct FromHelper<WireFormatLite::TYPE_BYTES> {
+ static ArenaStringPtr From(const string& x) {
+ ArenaStringPtr res;
+ *res.UnsafeRawStringPointer() = const_cast<string*>(&x);
+ return res;
+ }
+};
+template <>
+struct FromHelper<WireFormatLite::TYPE_MESSAGE> {
+ template <typename T>
+ static T* From(const T& x) {
+ return const_cast<T*>(&x);
+ }
+};
+
+template <typename MapEntryType>
+struct MapEntryHelper;
+
+template <typename T, typename Key, typename Value,
+ WireFormatLite::FieldType kKeyFieldType,
+ WireFormatLite::FieldType kValueFieldType, int default_enum_value>
+struct MapEntryHelper<MapEntryLite<T, Key, Value, kKeyFieldType,
+ kValueFieldType, default_enum_value> > {
+ // Provide utilities to parse/serialize key/value. Provide utilities to
+ // manipulate internal stored type.
+ typedef MapTypeHandler<kKeyFieldType, Key> KeyTypeHandler;
+ typedef MapTypeHandler<kValueFieldType, Value> ValueTypeHandler;
+
+ // Define internal memory layout. Strings and messages are stored as
+ // pointers, while other types are stored as values.
+ typedef typename KeyTypeHandler::TypeOnMemory KeyOnMemory;
+ typedef typename ValueTypeHandler::TypeOnMemory ValueOnMemory;
+
+ explicit MapEntryHelper(const MapPair<Key, Value>& map_pair)
+ : _has_bits_(3),
+ _cached_size_(2 + KeyTypeHandler::GetCachedSize(map_pair.first) +
+ ValueTypeHandler::GetCachedSize(map_pair.second)),
+ key_(FromHelper<kKeyFieldType>::From(map_pair.first)),
+ value_(FromHelper<kValueFieldType>::From(map_pair.second)) {}
+
+ // Purposely not folowing the style guide naming. These are the names
+ // the proto compiler would generate given the map entry descriptor.
+ // The proto compiler generates the offsets in this struct as if this was
+ // a regular message. This way the table driven code barely notices it's
+ // dealing with a map field.
+ uint32 _has_bits_; // NOLINT
+ uint32 _cached_size_; // NOLINT
+ KeyOnMemory key_; // NOLINT
+ ValueOnMemory value_; // NOLINT
+};
+
} // namespace internal
} // namespace protobuf
diff --git a/src/google/protobuf/map_field.cc b/src/google/protobuf/map_field.cc
index 49f91818..64dcc990 100644
--- a/src/google/protobuf/map_field.cc
+++ b/src/google/protobuf/map_field.cc
@@ -37,31 +37,6 @@ namespace google {
namespace protobuf {
namespace internal {
-ProtobufOnceType map_entry_default_instances_once_;
-Mutex* map_entry_default_instances_mutex_;
-vector<MessageLite*>* map_entry_default_instances_;
-
-void DeleteMapEntryDefaultInstances() {
- for (int i = 0; i < map_entry_default_instances_->size(); ++i) {
- delete map_entry_default_instances_->at(i);
- }
- delete map_entry_default_instances_mutex_;
- delete map_entry_default_instances_;
-}
-
-void InitMapEntryDefaultInstances() {
- map_entry_default_instances_mutex_ = new Mutex();
- map_entry_default_instances_ = new vector<MessageLite*>();
- OnShutdown(&DeleteMapEntryDefaultInstances);
-}
-
-void RegisterMapEntryDefaultInstance(MessageLite* default_instance) {
- ::google::protobuf::GoogleOnceInit(&map_entry_default_instances_once_,
- &InitMapEntryDefaultInstances);
- MutexLock lock(map_entry_default_instances_mutex_);
- map_entry_default_instances_->push_back(default_instance);
-}
-
MapFieldBase::~MapFieldBase() {
if (repeated_field_ != NULL && arena_ == NULL) delete repeated_field_;
}
@@ -77,25 +52,26 @@ RepeatedPtrFieldBase* MapFieldBase::MutableRepeatedField() {
return repeated_field_;
}
-int MapFieldBase::SpaceUsedExcludingSelf() const {
+size_t MapFieldBase::SpaceUsedExcludingSelfLong() const {
mutex_.Lock();
- int size = SpaceUsedExcludingSelfNoLock();
+ size_t size = SpaceUsedExcludingSelfNoLock();
mutex_.Unlock();
return size;
}
-int MapFieldBase::SpaceUsedExcludingSelfNoLock() const {
+size_t MapFieldBase::SpaceUsedExcludingSelfNoLock() const {
if (repeated_field_ != NULL) {
- return repeated_field_->SpaceUsedExcludingSelf();
+ return repeated_field_->SpaceUsedExcludingSelfLong();
} else {
return 0;
}
}
-void MapFieldBase::InitMetadataOnce() const {
- GOOGLE_CHECK(entry_descriptor_ != NULL);
- GOOGLE_CHECK(assign_descriptor_callback_ != NULL);
- (*assign_descriptor_callback_)();
+bool MapFieldBase::IsMapValid() const {
+ // "Acquire" insures the operation after SyncRepeatedFieldWithMap won't get
+ // executed before state_ is checked.
+ Atomic32 state = google::protobuf::internal::Acquire_Load(&state_);
+ return state != STATE_MODIFIED_REPEATED;
}
void MapFieldBase::SetMapDirty() { state_ = STATE_MODIFIED_MAP; }
@@ -390,6 +366,13 @@ void DynamicMapField::SyncMapWithRepeatedFieldNoLock() const {
GOOGLE_LOG(FATAL) << "Can't get here.";
break;
}
+
+ // Remove existing map value with same key.
+ Map<MapKey, MapValueRef>::iterator iter = map->find(map_key);
+ if (iter != map->end()) {
+ iter->second.DeleteData();
+ }
+
MapValueRef& map_val = (*map)[map_key];
map_val.SetType(val_des->cpp_type());
switch (val_des->cpp_type()) {
@@ -421,13 +404,13 @@ void DynamicMapField::SyncMapWithRepeatedFieldNoLock() const {
}
}
-int DynamicMapField::SpaceUsedExcludingSelfNoLock() const {
- int size = 0;
+size_t DynamicMapField::SpaceUsedExcludingSelfNoLock() const {
+ size_t size = 0;
if (MapFieldBase::repeated_field_ != NULL) {
- size += MapFieldBase::repeated_field_->SpaceUsedExcludingSelf();
+ size += MapFieldBase::repeated_field_->SpaceUsedExcludingSelfLong();
}
size += sizeof(map_);
- int map_size = map_.size();
+ size_t map_size = map_.size();
if (map_size) {
Map<MapKey, MapValueRef>::const_iterator it = map_.begin();
size += sizeof(it->first) * map_size;
@@ -456,7 +439,7 @@ int DynamicMapField::SpaceUsedExcludingSelfNoLock() const {
case google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE: {
while (it != map_.end()) {
const Message& message = it->second.GetMessageValue();
- size += message.GetReflection()->SpaceUsed(message);
+ size += message.GetReflection()->SpaceUsedLong(message);
++it;
}
break;
diff --git a/src/google/protobuf/map_field.h b/src/google/protobuf/map_field.h
index d6af8532..6c75a6da 100644
--- a/src/google/protobuf/map_field.h
+++ b/src/google/protobuf/map_field.h
@@ -36,6 +36,7 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/arena.h>
+#include <google/protobuf/descriptor.h>
#include <google/protobuf/map_entry.h>
#include <google/protobuf/map_field_lite.h>
#include <google/protobuf/map_type_handler.h>
@@ -62,14 +63,10 @@ class LIBPROTOBUF_EXPORT MapFieldBase {
MapFieldBase()
: arena_(NULL),
repeated_field_(NULL),
- entry_descriptor_(NULL),
- assign_descriptor_callback_(NULL),
state_(STATE_MODIFIED_MAP) {}
explicit MapFieldBase(Arena* arena)
: arena_(arena),
repeated_field_(NULL),
- entry_descriptor_(NULL),
- assign_descriptor_callback_(NULL),
state_(STATE_MODIFIED_MAP) {
// Mutex's destructor needs to be called explicitly to release resources
// acquired in its constructor.
@@ -89,6 +86,8 @@ class LIBPROTOBUF_EXPORT MapFieldBase {
virtual bool ContainsMapKey(const MapKey& map_key) const = 0;
virtual bool InsertOrLookupMapValue(
const MapKey& map_key, MapValueRef* val) = 0;
+ // Insures operations after won't get executed before calling this.
+ bool IsMapValid() const;
virtual bool DeleteMapValue(const MapKey& map_key) = 0;
virtual bool EqualIterator(const MapIterator& a,
const MapIterator& b) const = 0;
@@ -99,11 +98,15 @@ class LIBPROTOBUF_EXPORT MapFieldBase {
// Returns the number of bytes used by the repeated field, excluding
// sizeof(*this)
- int SpaceUsedExcludingSelf() const;
+ size_t SpaceUsedExcludingSelfLong() const;
+
+ int SpaceUsedExcludingSelf() const {
+ return internal::ToIntSize(SpaceUsedExcludingSelfLong());
+ }
protected:
// Gets the size of space used by map field.
- virtual int SpaceUsedExcludingSelfNoLock() const;
+ virtual size_t SpaceUsedExcludingSelfNoLock() const;
// Synchronizes the content in Map to RepeatedPtrField if there is any change
// to Map after last synchronization.
@@ -124,9 +127,6 @@ class LIBPROTOBUF_EXPORT MapFieldBase {
// Provides derived class the access to repeated field.
void* MutableRepeatedPtrField() const;
- // Creates descriptor for only one time.
- void InitMetadataOnce() const;
-
enum State {
STATE_MODIFIED_MAP = 0, // map has newly added data that has not been
// synchronized to repeated field
@@ -137,13 +137,6 @@ class LIBPROTOBUF_EXPORT MapFieldBase {
Arena* arena_;
mutable RepeatedPtrField<Message>* repeated_field_;
- // MapEntry can only be created from MapField. To create MapEntry, MapField
- // needs to know its descriptor, because MapEntry is not generated class which
- // cannot initialize its own descriptor by calling generated
- // descriptor-assign-function. Thus, we need to register a callback to
- // initialize MapEntry's descriptor.
- const Descriptor** entry_descriptor_;
- void (*assign_descriptor_callback_)();
mutable Mutex mutex_; // The thread to synchronize map and repeated field
// needs to get lock first;
@@ -177,6 +170,7 @@ class LIBPROTOBUF_EXPORT MapFieldBase {
// IncreaseIterator() is called by operator++() of MapIterator only.
// It implements the ++ operator of MapIterator.
virtual void IncreaseIterator(MapIterator* map_iter) const = 0;
+ GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapFieldBase);
};
// This class provides common Map Reflection implementations for generated
@@ -206,32 +200,31 @@ class TypeDefinedMapFieldBase : public MapFieldBase {
void IncreaseIterator(MapIterator* map_iter) const;
virtual void SetMapIteratorValue(MapIterator* map_iter) const = 0;
+ GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(TypeDefinedMapFieldBase);
};
// This class provides access to map field using generated api. It is used for
// internal generated message implentation only. Users should never use this
// directly.
-template <typename Key, typename T,
+template <typename Derived, typename Key, typename T,
WireFormatLite::FieldType kKeyFieldType,
- WireFormatLite::FieldType kValueFieldType,
- int default_enum_value = 0>
-class MapField : public TypeDefinedMapFieldBase<Key, T>,
- public MapFieldLite<Key, T, kKeyFieldType, kValueFieldType,
- default_enum_value> {
+ WireFormatLite::FieldType kValueFieldType, int default_enum_value = 0>
+class MapField : public TypeDefinedMapFieldBase<Key, T> {
// Provide utilities to parse/serialize key/value. Provide utilities to
// manipulate internal stored type.
typedef MapTypeHandler<kKeyFieldType, Key> KeyTypeHandler;
typedef MapTypeHandler<kValueFieldType, T> ValueTypeHandler;
// Define message type for internal repeated field.
- typedef MapEntry<Key, T, kKeyFieldType, kValueFieldType, default_enum_value>
- EntryType;
- typedef MapEntryLite<Key, T, kKeyFieldType, kValueFieldType,
- default_enum_value> EntryLiteType;
+ typedef Derived EntryType;
+ typedef MapEntryLite<Derived, Key, T, kKeyFieldType, kValueFieldType,
+ default_enum_value>
+ EntryLiteType;
// Define abbreviation for parent MapFieldLite
- typedef MapFieldLite<Key, T, kKeyFieldType, kValueFieldType,
- default_enum_value> MapFieldLiteType;
+ typedef MapFieldLite<Derived, Key, T, kKeyFieldType, kValueFieldType,
+ default_enum_value>
+ MapFieldLiteType;
// Enum needs to be handled differently from other types because it has
// different exposed type in google::protobuf::Map's api and repeated field's api. For
@@ -241,58 +234,76 @@ class MapField : public TypeDefinedMapFieldBase<Key, T>,
typedef typename MapIf<kIsValueEnum, T, const T&>::type CastValueType;
public:
- MapField();
- explicit MapField(Arena* arena);
- // MapField doesn't own the default_entry, which means default_entry must
- // outlive the lifetime of MapField.
- MapField(const Message* default_entry);
- // For tests only.
- MapField(Arena* arena, const Message* default_entry);
- ~MapField();
+ typedef typename Derived::SuperType EntryTypeTrait;
+ typedef Map<Key, T> MapType;
+
+ MapField() {}
+ explicit MapField(Arena* arena)
+ : TypeDefinedMapFieldBase<Key, T>(arena), impl_(arena) {}
// Implement MapFieldBase
bool ContainsMapKey(const MapKey& map_key) const;
bool InsertOrLookupMapValue(const MapKey& map_key, MapValueRef* val);
bool DeleteMapValue(const MapKey& map_key);
- // Accessors
- const Map<Key, T>& GetMap() const;
- Map<Key, T>* MutableMap();
+ const Map<Key, T>& GetMap() const {
+ MapFieldBase::SyncMapWithRepeatedField();
+ return impl_.GetMap();
+ }
+
+ Map<Key, T>* MutableMap() {
+ MapFieldBase::SyncMapWithRepeatedField();
+ Map<Key, T>* result = impl_.MutableMap();
+ MapFieldBase::SetMapDirty();
+ return result;
+ }
// Convenient methods for generated message implementation.
int size() const;
void Clear();
- void MergeFrom(const MapFieldLiteType& other);
- void Swap(MapFieldLiteType* other);
-
- // Allocates metadata only if this MapField is part of a generated message.
- void SetEntryDescriptor(const Descriptor** descriptor);
- void SetAssignDescriptorCallback(void (*callback)());
+ void MergeFrom(const MapField& other);
+ void Swap(MapField* other);
+
+ // Used in the implementation of parsing. Caller should take the ownership iff
+ // arena_ is NULL.
+ EntryType* NewEntry() const { return impl_.NewEntry(); }
+ // Used in the implementation of serializing enum value type. Caller should
+ // take the ownership iff arena_ is NULL.
+ EntryType* NewEnumEntryWrapper(const Key& key, const T t) const {
+ return impl_.NewEnumEntryWrapper(key, t);
+ }
+ // Used in the implementation of serializing other value types. Caller should
+ // take the ownership iff arena_ is NULL.
+ EntryType* NewEntryWrapper(const Key& key, const T& t) const {
+ return impl_.NewEntryWrapper(key, t);
+ }
private:
+ MapFieldLiteType impl_;
+
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
- // MapField needs MapEntry's default instance to create new MapEntry.
- void InitDefaultEntryOnce() const;
-
- // Manually set default entry instance. For test only.
- void SetDefaultEntryOnce(const EntryType* default_entry) const;
-
- // Convenient methods to get internal google::protobuf::Map
- const Map<Key, T>& GetInternalMap() const;
- Map<Key, T>* MutableInternalMap();
-
// Implements MapFieldBase
void SyncRepeatedFieldWithMapNoLock() const;
void SyncMapWithRepeatedFieldNoLock() const;
- int SpaceUsedExcludingSelfNoLock() const;
+ size_t SpaceUsedExcludingSelfNoLock() const;
void SetMapIteratorValue(MapIterator* map_iter) const;
- mutable const EntryType* default_entry_;
-
friend class ::google::protobuf::Arena;
+ friend class MapFieldStateTest; // For testing, it needs raw access to impl_
+ GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapField);
+};
+
+template <typename T, typename Key, typename Value,
+ WireFormatLite::FieldType kKeyFieldType,
+ WireFormatLite::FieldType kValueFieldType, int default_enum_value>
+struct MapEntryToMapField<MapEntry<T, Key, Value, kKeyFieldType,
+ kValueFieldType, default_enum_value> > {
+ typedef MapField<T, Key, Value, kKeyFieldType, kValueFieldType,
+ default_enum_value>
+ MapFieldType;
};
class LIBPROTOBUF_EXPORT DynamicMapField: public TypeDefinedMapFieldBase<MapKey, MapValueRef> {
@@ -318,12 +329,401 @@ class LIBPROTOBUF_EXPORT DynamicMapField: public TypeDefinedMapFieldBase<MapKey,
// Implements MapFieldBase
void SyncRepeatedFieldWithMapNoLock() const;
void SyncMapWithRepeatedFieldNoLock() const;
- int SpaceUsedExcludingSelfNoLock() const;
+ size_t SpaceUsedExcludingSelfNoLock() const;
void SetMapIteratorValue(MapIterator* map_iter) const;
+ GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DynamicMapField);
};
} // namespace internal
+#define TYPE_CHECK(EXPECTEDTYPE, METHOD) \
+ if (type() != EXPECTEDTYPE) { \
+ GOOGLE_LOG(FATAL) \
+ << "Protocol Buffer map usage error:\n" \
+ << METHOD << " type does not match\n" \
+ << " Expected : " \
+ << FieldDescriptor::CppTypeName(EXPECTEDTYPE) << "\n" \
+ << " Actual : " \
+ << FieldDescriptor::CppTypeName(type()); \
+ }
+
+// MapKey is an union type for representing any possible
+// map key.
+class LIBPROTOBUF_EXPORT MapKey {
+ public:
+ MapKey() : type_(0) {
+ }
+ MapKey(const MapKey& other) : type_(0) {
+ CopyFrom(other);
+ }
+ MapKey& operator=(const MapKey& other) {
+ CopyFrom(other);
+ return *this;
+ }
+
+ ~MapKey() {
+ if (type_ == FieldDescriptor::CPPTYPE_STRING) {
+ delete val_.string_value_;
+ }
+ }
+
+ FieldDescriptor::CppType type() const {
+ if (type_ == 0) {
+ GOOGLE_LOG(FATAL)
+ << "Protocol Buffer map usage error:\n"
+ << "MapKey::type MapKey is not initialized. "
+ << "Call set methods to initialize MapKey.";
+ }
+ return (FieldDescriptor::CppType)type_;
+ }
+
+ void SetInt64Value(int64 value) {
+ SetType(FieldDescriptor::CPPTYPE_INT64);
+ val_.int64_value_ = value;
+ }
+ void SetUInt64Value(uint64 value) {
+ SetType(FieldDescriptor::CPPTYPE_UINT64);
+ val_.uint64_value_ = value;
+ }
+ void SetInt32Value(int32 value) {
+ SetType(FieldDescriptor::CPPTYPE_INT32);
+ val_.int32_value_ = value;
+ }
+ void SetUInt32Value(uint32 value) {
+ SetType(FieldDescriptor::CPPTYPE_UINT32);
+ val_.uint32_value_ = value;
+ }
+ void SetBoolValue(bool value) {
+ SetType(FieldDescriptor::CPPTYPE_BOOL);
+ val_.bool_value_ = value;
+ }
+ void SetStringValue(const string& val) {
+ SetType(FieldDescriptor::CPPTYPE_STRING);
+ *val_.string_value_ = val;
+ }
+
+ int64 GetInt64Value() const {
+ TYPE_CHECK(FieldDescriptor::CPPTYPE_INT64,
+ "MapKey::GetInt64Value");
+ return val_.int64_value_;
+ }
+ uint64 GetUInt64Value() const {
+ TYPE_CHECK(FieldDescriptor::CPPTYPE_UINT64,
+ "MapKey::GetUInt64Value");
+ return val_.uint64_value_;
+ }
+ int32 GetInt32Value() const {
+ TYPE_CHECK(FieldDescriptor::CPPTYPE_INT32,
+ "MapKey::GetInt32Value");
+ return val_.int32_value_;
+ }
+ uint32 GetUInt32Value() const {
+ TYPE_CHECK(FieldDescriptor::CPPTYPE_UINT32,
+ "MapKey::GetUInt32Value");
+ return val_.uint32_value_;
+ }
+ bool GetBoolValue() const {
+ TYPE_CHECK(FieldDescriptor::CPPTYPE_BOOL,
+ "MapKey::GetBoolValue");
+ return val_.bool_value_;
+ }
+ const string& GetStringValue() const {
+ TYPE_CHECK(FieldDescriptor::CPPTYPE_STRING,
+ "MapKey::GetStringValue");
+ return *val_.string_value_;
+ }
+
+ bool operator<(const MapKey& other) const {
+ if (type_ != other.type_) {
+ // We could define a total order that handles this case, but
+ // there currently no need. So, for now, fail.
+ GOOGLE_LOG(FATAL) << "Unsupported: type mismatch";
+ }
+ switch (type()) {
+ case FieldDescriptor::CPPTYPE_DOUBLE:
+ case FieldDescriptor::CPPTYPE_FLOAT:
+ case FieldDescriptor::CPPTYPE_ENUM:
+ case FieldDescriptor::CPPTYPE_MESSAGE:
+ GOOGLE_LOG(FATAL) << "Unsupported";
+ return false;
+ case FieldDescriptor::CPPTYPE_STRING:
+ return *val_.string_value_ < *other.val_.string_value_;
+ case FieldDescriptor::CPPTYPE_INT64:
+ return val_.int64_value_ < other.val_.int64_value_;
+ case FieldDescriptor::CPPTYPE_INT32:
+ return val_.int32_value_ < other.val_.int32_value_;
+ case FieldDescriptor::CPPTYPE_UINT64:
+ return val_.uint64_value_ < other.val_.uint64_value_;
+ case FieldDescriptor::CPPTYPE_UINT32:
+ return val_.uint32_value_ < other.val_.uint32_value_;
+ case FieldDescriptor::CPPTYPE_BOOL:
+ return val_.bool_value_ < other.val_.bool_value_;
+ }
+ return false;
+ }
+
+ bool operator==(const MapKey& other) const {
+ if (type_ != other.type_) {
+ // To be consistent with operator<, we don't allow this either.
+ GOOGLE_LOG(FATAL) << "Unsupported: type mismatch";
+ }
+ switch (type()) {
+ case FieldDescriptor::CPPTYPE_DOUBLE:
+ case FieldDescriptor::CPPTYPE_FLOAT:
+ case FieldDescriptor::CPPTYPE_ENUM:
+ case FieldDescriptor::CPPTYPE_MESSAGE:
+ GOOGLE_LOG(FATAL) << "Unsupported";
+ break;
+ case FieldDescriptor::CPPTYPE_STRING:
+ return *val_.string_value_ == *other.val_.string_value_;
+ case FieldDescriptor::CPPTYPE_INT64:
+ return val_.int64_value_ == other.val_.int64_value_;
+ case FieldDescriptor::CPPTYPE_INT32:
+ return val_.int32_value_ == other.val_.int32_value_;
+ case FieldDescriptor::CPPTYPE_UINT64:
+ return val_.uint64_value_ == other.val_.uint64_value_;
+ case FieldDescriptor::CPPTYPE_UINT32:
+ return val_.uint32_value_ == other.val_.uint32_value_;
+ case FieldDescriptor::CPPTYPE_BOOL:
+ return val_.bool_value_ == other.val_.bool_value_;
+ }
+ GOOGLE_LOG(FATAL) << "Can't get here.";
+ return false;
+ }
+
+ void CopyFrom(const MapKey& other) {
+ SetType(other.type());
+ switch (type_) {
+ case FieldDescriptor::CPPTYPE_DOUBLE:
+ case FieldDescriptor::CPPTYPE_FLOAT:
+ case FieldDescriptor::CPPTYPE_ENUM:
+ case FieldDescriptor::CPPTYPE_MESSAGE:
+ GOOGLE_LOG(FATAL) << "Unsupported";
+ break;
+ case FieldDescriptor::CPPTYPE_STRING:
+ *val_.string_value_ = *other.val_.string_value_;
+ break;
+ case FieldDescriptor::CPPTYPE_INT64:
+ val_.int64_value_ = other.val_.int64_value_;
+ break;
+ case FieldDescriptor::CPPTYPE_INT32:
+ val_.int32_value_ = other.val_.int32_value_;
+ break;
+ case FieldDescriptor::CPPTYPE_UINT64:
+ val_.uint64_value_ = other.val_.uint64_value_;
+ break;
+ case FieldDescriptor::CPPTYPE_UINT32:
+ val_.uint32_value_ = other.val_.uint32_value_;
+ break;
+ case FieldDescriptor::CPPTYPE_BOOL:
+ val_.bool_value_ = other.val_.bool_value_;
+ break;
+ }
+ }
+
+ private:
+ template <typename K, typename V>
+ friend class internal::TypeDefinedMapFieldBase;
+ friend class MapIterator;
+ friend class internal::DynamicMapField;
+
+ union KeyValue {
+ KeyValue() {}
+ string* string_value_;
+ int64 int64_value_;
+ int32 int32_value_;
+ uint64 uint64_value_;
+ uint32 uint32_value_;
+ bool bool_value_;
+ } val_;
+
+ void SetType(FieldDescriptor::CppType type) {
+ if (type_ == type) return;
+ if (type_ == FieldDescriptor::CPPTYPE_STRING) {
+ delete val_.string_value_;
+ }
+ type_ = type;
+ if (type_ == FieldDescriptor::CPPTYPE_STRING) {
+ val_.string_value_ = new string;
+ }
+ }
+
+ // type_ is 0 or a valid FieldDescriptor::CppType.
+ int type_;
+};
+
+// MapValueRef points to a map value.
+class LIBPROTOBUF_EXPORT MapValueRef {
+ public:
+ MapValueRef() : data_(NULL), type_(0) {}
+
+ void SetInt64Value(int64 value) {
+ TYPE_CHECK(FieldDescriptor::CPPTYPE_INT64,
+ "MapValueRef::SetInt64Value");
+ *reinterpret_cast<int64*>(data_) = value;
+ }
+ void SetUInt64Value(uint64 value) {
+ TYPE_CHECK(FieldDescriptor::CPPTYPE_UINT64,
+ "MapValueRef::SetUInt64Value");
+ *reinterpret_cast<uint64*>(data_) = value;
+ }
+ void SetInt32Value(int32 value) {
+ TYPE_CHECK(FieldDescriptor::CPPTYPE_INT32,
+ "MapValueRef::SetInt32Value");
+ *reinterpret_cast<int32*>(data_) = value;
+ }
+ void SetUInt32Value(uint32 value) {
+ TYPE_CHECK(FieldDescriptor::CPPTYPE_UINT32,
+ "MapValueRef::SetUInt32Value");
+ *reinterpret_cast<uint32*>(data_) = value;
+ }
+ void SetBoolValue(bool value) {
+ TYPE_CHECK(FieldDescriptor::CPPTYPE_BOOL,
+ "MapValueRef::SetBoolValue");
+ *reinterpret_cast<bool*>(data_) = value;
+ }
+ // TODO(jieluo) - Checks that enum is member.
+ void SetEnumValue(int value) {
+ TYPE_CHECK(FieldDescriptor::CPPTYPE_ENUM,
+ "MapValueRef::SetEnumValue");
+ *reinterpret_cast<int*>(data_) = value;
+ }
+ void SetStringValue(const string& value) {
+ TYPE_CHECK(FieldDescriptor::CPPTYPE_STRING,
+ "MapValueRef::SetStringValue");
+ *reinterpret_cast<string*>(data_) = value;
+ }
+ void SetFloatValue(float value) {
+ TYPE_CHECK(FieldDescriptor::CPPTYPE_FLOAT,
+ "MapValueRef::SetFloatValue");
+ *reinterpret_cast<float*>(data_) = value;
+ }
+ void SetDoubleValue(double value) {
+ TYPE_CHECK(FieldDescriptor::CPPTYPE_DOUBLE,
+ "MapValueRef::SetDoubleValue");
+ *reinterpret_cast<double*>(data_) = value;
+ }
+
+ int64 GetInt64Value() const {
+ TYPE_CHECK(FieldDescriptor::CPPTYPE_INT64,
+ "MapValueRef::GetInt64Value");
+ return *reinterpret_cast<int64*>(data_);
+ }
+ uint64 GetUInt64Value() const {
+ TYPE_CHECK(FieldDescriptor::CPPTYPE_UINT64,
+ "MapValueRef::GetUInt64Value");
+ return *reinterpret_cast<uint64*>(data_);
+ }
+ int32 GetInt32Value() const {
+ TYPE_CHECK(FieldDescriptor::CPPTYPE_INT32,
+ "MapValueRef::GetInt32Value");
+ return *reinterpret_cast<int32*>(data_);
+ }
+ uint32 GetUInt32Value() const {
+ TYPE_CHECK(FieldDescriptor::CPPTYPE_UINT32,
+ "MapValueRef::GetUInt32Value");
+ return *reinterpret_cast<uint32*>(data_);
+ }
+ bool GetBoolValue() const {
+ TYPE_CHECK(FieldDescriptor::CPPTYPE_BOOL,
+ "MapValueRef::GetBoolValue");
+ return *reinterpret_cast<bool*>(data_);
+ }
+ int GetEnumValue() const {
+ TYPE_CHECK(FieldDescriptor::CPPTYPE_ENUM,
+ "MapValueRef::GetEnumValue");
+ return *reinterpret_cast<int*>(data_);
+ }
+ const string& GetStringValue() const {
+ TYPE_CHECK(FieldDescriptor::CPPTYPE_STRING,
+ "MapValueRef::GetStringValue");
+ return *reinterpret_cast<string*>(data_);
+ }
+ float GetFloatValue() const {
+ TYPE_CHECK(FieldDescriptor::CPPTYPE_FLOAT,
+ "MapValueRef::GetFloatValue");
+ return *reinterpret_cast<float*>(data_);
+ }
+ double GetDoubleValue() const {
+ TYPE_CHECK(FieldDescriptor::CPPTYPE_DOUBLE,
+ "MapValueRef::GetDoubleValue");
+ return *reinterpret_cast<double*>(data_);
+ }
+
+ const Message& GetMessageValue() const {
+ TYPE_CHECK(FieldDescriptor::CPPTYPE_MESSAGE,
+ "MapValueRef::GetMessageValue");
+ return *reinterpret_cast<Message*>(data_);
+ }
+
+ Message* MutableMessageValue() {
+ TYPE_CHECK(FieldDescriptor::CPPTYPE_MESSAGE,
+ "MapValueRef::MutableMessageValue");
+ return reinterpret_cast<Message*>(data_);
+ }
+
+ private:
+ template <typename Derived, typename K, typename V,
+ internal::WireFormatLite::FieldType key_wire_type,
+ internal::WireFormatLite::FieldType value_wire_type,
+ int default_enum_value>
+ friend class internal::MapField;
+ template <typename K, typename V>
+ friend class internal::TypeDefinedMapFieldBase;
+ friend class MapIterator;
+ friend class internal::GeneratedMessageReflection;
+ friend class internal::DynamicMapField;
+
+ void SetType(FieldDescriptor::CppType type) {
+ type_ = type;
+ }
+
+ FieldDescriptor::CppType type() const {
+ if (type_ == 0 || data_ == NULL) {
+ GOOGLE_LOG(FATAL)
+ << "Protocol Buffer map usage error:\n"
+ << "MapValueRef::type MapValueRef is not initialized.";
+ }
+ return (FieldDescriptor::CppType)type_;
+ }
+ void SetValue(const void* val) {
+ data_ = const_cast<void*>(val);
+ }
+ void CopyFrom(const MapValueRef& other) {
+ type_ = other.type_;
+ data_ = other.data_;
+ }
+ // Only used in DynamicMapField
+ void DeleteData() {
+ switch (type_) {
+#define HANDLE_TYPE(CPPTYPE, TYPE) \
+ case google::protobuf::FieldDescriptor::CPPTYPE_##CPPTYPE: { \
+ delete reinterpret_cast<TYPE*>(data_); \
+ break; \
+ }
+ HANDLE_TYPE(INT32, int32);
+ HANDLE_TYPE(INT64, int64);
+ HANDLE_TYPE(UINT32, uint32);
+ HANDLE_TYPE(UINT64, uint64);
+ HANDLE_TYPE(DOUBLE, double);
+ HANDLE_TYPE(FLOAT, float);
+ HANDLE_TYPE(BOOL, bool);
+ HANDLE_TYPE(STRING, string);
+ HANDLE_TYPE(ENUM, int32);
+ HANDLE_TYPE(MESSAGE, Message);
+#undef HANDLE_TYPE
+ }
+ }
+ // data_ point to a map value. MapValueRef does not
+ // own this value.
+ void* data_;
+ // type_ is 0 or a valid FieldDescriptor::CppType.
+ int type_;
+ GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapValueRef);
+};
+
+#undef TYPE_CHECK
+
class LIBPROTOBUF_EXPORT MapIterator {
public:
MapIterator(Message* message, const FieldDescriptor* field) {
@@ -341,6 +741,11 @@ class LIBPROTOBUF_EXPORT MapIterator {
~MapIterator() {
map_->DeleteIterator(this);
}
+ MapIterator& operator=(const MapIterator& other) {
+ map_ = other.map_;
+ map_->CopyIterator(this, other);
+ return *this;
+ }
friend bool operator==(const MapIterator& a, const MapIterator& b) {
return a.map_->EqualIterator(a, b);
}
@@ -373,7 +778,7 @@ class LIBPROTOBUF_EXPORT MapIterator {
template <typename Key, typename T>
friend class internal::TypeDefinedMapFieldBase;
friend class internal::DynamicMapField;
- template <typename Key, typename T,
+ template <typename Derived, typename Key, typename T,
internal::WireFormatLite::FieldType kKeyFieldType,
internal::WireFormatLite::FieldType kValueFieldType,
int default_enum_value>
@@ -392,6 +797,42 @@ class LIBPROTOBUF_EXPORT MapIterator {
};
} // namespace protobuf
-
} // namespace google
+
+GOOGLE_PROTOBUF_HASH_NAMESPACE_DECLARATION_START
+template<>
+struct hash<google::protobuf::MapKey> {
+ size_t
+ operator()(const google::protobuf::MapKey& map_key) const {
+ switch (map_key.type()) {
+ case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE:
+ case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT:
+ case google::protobuf::FieldDescriptor::CPPTYPE_ENUM:
+ case google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE:
+ GOOGLE_LOG(FATAL) << "Unsupported";
+ break;
+ case google::protobuf::FieldDescriptor::CPPTYPE_STRING:
+ return hash<string>()(map_key.GetStringValue());
+ case google::protobuf::FieldDescriptor::CPPTYPE_INT64:
+ return hash< ::google::protobuf::int64>()(map_key.GetInt64Value());
+ case google::protobuf::FieldDescriptor::CPPTYPE_INT32:
+ return hash< ::google::protobuf::int32>()(map_key.GetInt32Value());
+ case google::protobuf::FieldDescriptor::CPPTYPE_UINT64:
+ return hash< ::google::protobuf::uint64>()(map_key.GetUInt64Value());
+ case google::protobuf::FieldDescriptor::CPPTYPE_UINT32:
+ return hash< ::google::protobuf::uint32>()(map_key.GetUInt32Value());
+ case google::protobuf::FieldDescriptor::CPPTYPE_BOOL:
+ return hash<bool>()(map_key.GetBoolValue());
+ }
+ GOOGLE_LOG(FATAL) << "Can't get here.";
+ return 0;
+ }
+ bool
+ operator()(const google::protobuf::MapKey& map_key1,
+ const google::protobuf::MapKey& map_key2) const {
+ return map_key1 < map_key2;
+ }
+};
+GOOGLE_PROTOBUF_HASH_NAMESPACE_DECLARATION_END
+
#endif // GOOGLE_PROTOBUF_MAP_FIELD_H__
diff --git a/src/google/protobuf/map_field_inl.h b/src/google/protobuf/map_field_inl.h
index 01c9b89a..e317b5ed 100644
--- a/src/google/protobuf/map_field_inl.h
+++ b/src/google/protobuf/map_field_inl.h
@@ -162,81 +162,32 @@ void TypeDefinedMapFieldBase<Key, T>::CopyIterator(
// ----------------------------------------------------------------------
-template <typename Key, typename T,
+template <typename Derived, typename Key, typename T,
WireFormatLite::FieldType kKeyFieldType,
- WireFormatLite::FieldType kValueFieldType,
- int default_enum_value>
-MapField<Key, T, kKeyFieldType, kValueFieldType, default_enum_value>::MapField()
- : default_entry_(NULL) {}
-
-template <typename Key, typename T,
- WireFormatLite::FieldType kKeyFieldType,
- WireFormatLite::FieldType kValueFieldType,
- int default_enum_value>
-MapField<Key, T, kKeyFieldType, kValueFieldType, default_enum_value>::MapField(
- Arena* arena)
- : TypeDefinedMapFieldBase<Key, T>(arena),
- MapFieldLite<Key, T, kKeyFieldType, kValueFieldType, default_enum_value>(
- arena),
- default_entry_(NULL) {}
-
-template <typename Key, typename T,
- WireFormatLite::FieldType kKeyFieldType,
- WireFormatLite::FieldType kValueFieldType,
- int default_enum_value>
-MapField<Key, T, kKeyFieldType, kValueFieldType, default_enum_value>::MapField(
- const Message* default_entry)
- : default_entry_(down_cast<const EntryType*>(default_entry)) {}
-
-template <typename Key, typename T,
- WireFormatLite::FieldType kKeyFieldType,
- WireFormatLite::FieldType kValueFieldType,
- int default_enum_value>
-MapField<Key, T, kKeyFieldType, kValueFieldType, default_enum_value>::MapField(
- Arena* arena, const Message* default_entry)
- : TypeDefinedMapFieldBase<Key, T>(arena),
- MapFieldLite<Key, T, kKeyFieldType, kValueFieldType, default_enum_value>(
- arena),
- default_entry_(down_cast<const EntryType*>(default_entry)) {}
-
-template <typename Key, typename T,
- WireFormatLite::FieldType kKeyFieldType,
- WireFormatLite::FieldType kValueFieldType,
- int default_enum_value>
-MapField<Key, T, kKeyFieldType, kValueFieldType,
- default_enum_value>::~MapField() {}
-
-template <typename Key, typename T,
- WireFormatLite::FieldType kKeyFieldType,
- WireFormatLite::FieldType kValueFieldType,
- int default_enum_value>
-int
-MapField<Key, T, kKeyFieldType, kValueFieldType,
- default_enum_value>::size() const {
+ WireFormatLite::FieldType kValueFieldType, int default_enum_value>
+int MapField<Derived, Key, T, kKeyFieldType, kValueFieldType,
+ default_enum_value>::size() const {
MapFieldBase::SyncMapWithRepeatedField();
- return MapFieldLiteType::GetInternalMap().size();
+ return static_cast<int>(impl_.GetMap().size());
}
-template <typename Key, typename T,
+template <typename Derived, typename Key, typename T,
WireFormatLite::FieldType kKeyFieldType,
- WireFormatLite::FieldType kValueFieldType,
- int default_enum_value>
-void
-MapField<Key, T, kKeyFieldType, kValueFieldType,
- default_enum_value>::Clear() {
+ WireFormatLite::FieldType kValueFieldType, int default_enum_value>
+void MapField<Derived, Key, T, kKeyFieldType, kValueFieldType,
+ default_enum_value>::Clear() {
MapFieldBase::SyncMapWithRepeatedField();
- MapFieldLiteType::MutableInternalMap()->clear();
+ impl_.MutableMap()->clear();
MapFieldBase::SetMapDirty();
}
-template <typename Key, typename T,
+template <typename Derived, typename Key, typename T,
WireFormatLite::FieldType kKeyFieldType,
- WireFormatLite::FieldType kValueFieldType,
- int default_enum_value>
-void MapField<Key, T, kKeyFieldType, kValueFieldType,
- default_enum_value>::SetMapIteratorValue(
- MapIterator* map_iter) const {
- const Map<Key, T>& map = GetMap();
+ WireFormatLite::FieldType kValueFieldType, int default_enum_value>
+void MapField<Derived, Key, T, kKeyFieldType, kValueFieldType,
+ default_enum_value>::SetMapIteratorValue(MapIterator* map_iter)
+ const {
+ const Map<Key, T>& map = impl_.GetMap();
typename Map<Key, T>::const_iterator iter =
TypeDefinedMapFieldBase<Key, T>::InternalGetIterator(map_iter);
if (iter == map.end()) return;
@@ -244,27 +195,23 @@ void MapField<Key, T, kKeyFieldType, kValueFieldType,
map_iter->value_.SetValue(&iter->second);
}
-template <typename Key, typename T,
+template <typename Derived, typename Key, typename T,
WireFormatLite::FieldType kKeyFieldType,
- WireFormatLite::FieldType kValueFieldType,
- int default_enum_value>
-bool MapField<Key, T, kKeyFieldType, kValueFieldType,
- default_enum_value>::ContainsMapKey(
- const MapKey& map_key) const {
- const Map<Key, T>& map = GetMap();
+ WireFormatLite::FieldType kValueFieldType, int default_enum_value>
+bool MapField<Derived, Key, T, kKeyFieldType, kValueFieldType,
+ default_enum_value>::ContainsMapKey(const MapKey& map_key) const {
+ const Map<Key, T>& map = impl_.GetMap();
const Key& key = UnwrapMapKey<Key>(map_key);
typename Map<Key, T>::const_iterator iter = map.find(key);
return iter != map.end();
}
-template <typename Key, typename T,
+template <typename Derived, typename Key, typename T,
WireFormatLite::FieldType kKeyFieldType,
- WireFormatLite::FieldType kValueFieldType,
- int default_enum_value>
-bool MapField<Key, T, kKeyFieldType, kValueFieldType,
- default_enum_value>::InsertOrLookupMapValue(
- const MapKey& map_key,
- MapValueRef* val) {
+ WireFormatLite::FieldType kValueFieldType, int default_enum_value>
+bool MapField<Derived, Key, T, kKeyFieldType, kValueFieldType,
+ default_enum_value>::InsertOrLookupMapValue(const MapKey& map_key,
+ MapValueRef* val) {
// Always use mutable map because users may change the map value by
// MapValueRef.
Map<Key, T>* map = MutableMap();
@@ -280,158 +227,83 @@ bool MapField<Key, T, kKeyFieldType, kValueFieldType,
return false;
}
-template <typename Key, typename T,
+template <typename Derived, typename Key, typename T,
WireFormatLite::FieldType kKeyFieldType,
- WireFormatLite::FieldType kValueFieldType,
- int default_enum_value>
-bool MapField<Key, T, kKeyFieldType, kValueFieldType,
- default_enum_value>::DeleteMapValue(
- const MapKey& map_key) {
+ WireFormatLite::FieldType kValueFieldType, int default_enum_value>
+bool MapField<Derived, Key, T, kKeyFieldType, kValueFieldType,
+ default_enum_value>::DeleteMapValue(const MapKey& map_key) {
const Key& key = UnwrapMapKey<Key>(map_key);
return MutableMap()->erase(key);
}
-template <typename Key, typename T,
- WireFormatLite::FieldType kKeyFieldType,
- WireFormatLite::FieldType kValueFieldType,
- int default_enum_value>
-const Map<Key, T>&
-MapField<Key, T, kKeyFieldType, kValueFieldType,
- default_enum_value>::GetMap() const {
- MapFieldBase::SyncMapWithRepeatedField();
- return MapFieldLiteType::GetInternalMap();
-}
-
-template <typename Key, typename T,
- WireFormatLite::FieldType kKeyFieldType,
- WireFormatLite::FieldType kValueFieldType,
- int default_enum_value>
-Map<Key, T>*
-MapField<Key, T, kKeyFieldType, kValueFieldType,
- default_enum_value>::MutableMap() {
- MapFieldBase::SyncMapWithRepeatedField();
- Map<Key, T>* result = MapFieldLiteType::MutableInternalMap();
- MapFieldBase::SetMapDirty();
- return result;
-}
-
-template <typename Key, typename T,
+template <typename Derived, typename Key, typename T,
WireFormatLite::FieldType kKeyFieldType,
- WireFormatLite::FieldType kValueFieldType,
- int default_enum_value>
-void
-MapField<Key, T, kKeyFieldType, kValueFieldType,
- default_enum_value>::MergeFrom(
- const MapFieldLiteType& other) {
- const MapField& down_other = down_cast<const MapField&>(other);
+ WireFormatLite::FieldType kValueFieldType, int default_enum_value>
+void MapField<Derived, Key, T, kKeyFieldType, kValueFieldType,
+ default_enum_value>::MergeFrom(const MapField& other) {
MapFieldBase::SyncMapWithRepeatedField();
- down_other.SyncMapWithRepeatedField();
- MapFieldLiteType::MergeFrom(other);
+ other.SyncMapWithRepeatedField();
+ impl_.MergeFrom(other.impl_);
MapFieldBase::SetMapDirty();
}
-template <typename Key, typename T,
- WireFormatLite::FieldType kKeyFieldType,
- WireFormatLite::FieldType kValueFieldType,
- int default_enum_value>
-void
-MapField<Key, T, kKeyFieldType, kValueFieldType,
- default_enum_value>::Swap(
- MapFieldLiteType* other) {
- MapField* down_other = down_cast<MapField*>(other);
- std::swap(MapFieldBase::repeated_field_, down_other->repeated_field_);
- MapFieldLiteType::Swap(other);
- std::swap(MapFieldBase::state_, down_other->state_);
-}
-
-template <typename Key, typename T,
- WireFormatLite::FieldType kKeyFieldType,
- WireFormatLite::FieldType kValueFieldType,
- int default_enum_value>
-void
-MapField<Key, T, kKeyFieldType, kValueFieldType,
- default_enum_value>::SetEntryDescriptor(
- const Descriptor** descriptor) {
- MapFieldBase::entry_descriptor_ = descriptor;
-}
-
-template <typename Key, typename T,
- WireFormatLite::FieldType kKeyFieldType,
- WireFormatLite::FieldType kValueFieldType,
- int default_enum_value>
-void
-MapField<Key, T, kKeyFieldType, kValueFieldType,
- default_enum_value>::SetAssignDescriptorCallback(void (*callback)()) {
- MapFieldBase::assign_descriptor_callback_ = callback;
-}
-
-template <typename Key, typename T,
+template <typename Derived, typename Key, typename T,
WireFormatLite::FieldType kKeyFieldType,
- WireFormatLite::FieldType kValueFieldType,
- int default_enum_value>
-const Map<Key, T>&
-MapField<Key, T, kKeyFieldType, kValueFieldType,
- default_enum_value>::GetInternalMap() const {
- return MapFieldLiteType::GetInternalMap();
+ WireFormatLite::FieldType kValueFieldType, int default_enum_value>
+void MapField<Derived, Key, T, kKeyFieldType, kValueFieldType,
+ default_enum_value>::Swap(MapField* other) {
+ std::swap(this->MapFieldBase::repeated_field_, other->repeated_field_);
+ impl_.Swap(&other->impl_);
+ std::swap(this->MapFieldBase::state_, other->state_);
}
-template <typename Key, typename T,
+template <typename Derived, typename Key, typename T,
WireFormatLite::FieldType kKeyFieldType,
- WireFormatLite::FieldType kValueFieldType,
- int default_enum_value>
-Map<Key, T>*
-MapField<Key, T, kKeyFieldType, kValueFieldType,
- default_enum_value>::MutableInternalMap() {
- return MapFieldLiteType::MutableInternalMap();
-}
-
-template <typename Key, typename T,
- WireFormatLite::FieldType kKeyFieldType,
- WireFormatLite::FieldType kValueFieldType,
- int default_enum_value>
-void
-MapField<Key, T, kKeyFieldType, kValueFieldType,
- default_enum_value>::SyncRepeatedFieldWithMapNoLock() const {
- if (MapFieldBase::repeated_field_ == NULL) {
- if (MapFieldBase::arena_ == NULL) {
- MapFieldBase::repeated_field_ = new RepeatedPtrField<Message>();
+ WireFormatLite::FieldType kValueFieldType, int default_enum_value>
+void MapField<Derived, Key, T, kKeyFieldType, kValueFieldType,
+ default_enum_value>::SyncRepeatedFieldWithMapNoLock() const {
+ if (this->MapFieldBase::repeated_field_ == NULL) {
+ if (this->MapFieldBase::arena_ == NULL) {
+ this->MapFieldBase::repeated_field_ = new RepeatedPtrField<Message>();
} else {
- MapFieldBase::repeated_field_ =
+ this->MapFieldBase::repeated_field_ =
Arena::CreateMessage<RepeatedPtrField<Message> >(
- MapFieldBase::arena_);
+ this->MapFieldBase::arena_);
}
}
- const Map<Key, T>& map = GetInternalMap();
+ const Map<Key, T>& map = impl_.GetMap();
RepeatedPtrField<EntryType>* repeated_field =
reinterpret_cast<RepeatedPtrField<EntryType>*>(
- MapFieldBase::repeated_field_);
+ this->MapFieldBase::repeated_field_);
repeated_field->Clear();
+ // The only way we can get at this point is through reflection and the
+ // only way we can get the reflection object is by having called GetReflection
+ // on the encompassing field. So that type must have existed and hence we
+ // know that this MapEntry default_type has also already been constructed.
+ // So it's safe to just call internal_default_instance().
+ const Message* default_entry = Derived::internal_default_instance();
for (typename Map<Key, T>::const_iterator it = map.begin();
it != map.end(); ++it) {
- InitDefaultEntryOnce();
- GOOGLE_CHECK(default_entry_ != NULL);
EntryType* new_entry =
- down_cast<EntryType*>(default_entry_->New(MapFieldBase::arena_));
+ down_cast<EntryType*>(default_entry->New(this->MapFieldBase::arena_));
repeated_field->AddAllocated(new_entry);
(*new_entry->mutable_key()) = it->first;
(*new_entry->mutable_value()) = it->second;
}
}
-template <typename Key, typename T,
+template <typename Derived, typename Key, typename T,
WireFormatLite::FieldType kKeyFieldType,
- WireFormatLite::FieldType kValueFieldType,
- int default_enum_value>
-void
-MapField<Key, T, kKeyFieldType, kValueFieldType,
- default_enum_value>::SyncMapWithRepeatedFieldNoLock() const {
- Map<Key, T>* map = const_cast<MapField*>(this)->MutableInternalMap();
+ WireFormatLite::FieldType kValueFieldType, int default_enum_value>
+void MapField<Derived, Key, T, kKeyFieldType, kValueFieldType,
+ default_enum_value>::SyncMapWithRepeatedFieldNoLock() const {
+ Map<Key, T>* map = const_cast<MapField*>(this)->impl_.MutableMap();
RepeatedPtrField<EntryType>* repeated_field =
reinterpret_cast<RepeatedPtrField<EntryType>*>(
- MapFieldBase::repeated_field_);
- GOOGLE_CHECK(MapFieldBase::repeated_field_ != NULL);
+ this->MapFieldBase::repeated_field_);
+ GOOGLE_CHECK(this->MapFieldBase::repeated_field_ != NULL);
map->clear();
for (typename RepeatedPtrField<EntryType>::iterator it =
repeated_field->begin(); it != repeated_field->end(); ++it) {
@@ -444,44 +316,24 @@ MapField<Key, T, kKeyFieldType, kValueFieldType,
}
}
-template <typename Key, typename T,
+template <typename Derived, typename Key, typename T,
WireFormatLite::FieldType kKeyFieldType,
- WireFormatLite::FieldType kValueFieldType,
- int default_enum_value>
-int
-MapField<Key, T, kKeyFieldType, kValueFieldType,
- default_enum_value>::SpaceUsedExcludingSelfNoLock() const {
- int size = 0;
- if (MapFieldBase::repeated_field_ != NULL) {
- size += MapFieldBase::repeated_field_->SpaceUsedExcludingSelf();
+ WireFormatLite::FieldType kValueFieldType, int default_enum_value>
+size_t MapField<Derived, Key, T, kKeyFieldType, kValueFieldType,
+ default_enum_value>::SpaceUsedExcludingSelfNoLock() const {
+ size_t size = 0;
+ if (this->MapFieldBase::repeated_field_ != NULL) {
+ size += this->MapFieldBase::repeated_field_->SpaceUsedExcludingSelfLong();
}
- Map<Key, T>* map = const_cast<MapField*>(this)->MutableInternalMap();
+ Map<Key, T>* map = const_cast<MapField*>(this)->impl_.MutableMap();
size += sizeof(*map);
- for (typename Map<Key, T>::iterator it = map->begin();
- it != map->end(); ++it) {
- size += KeyTypeHandler::SpaceUsedInMap(it->first);
- size += ValueTypeHandler::SpaceUsedInMap(it->second);
+ for (typename Map<Key, T>::iterator it = map->begin(); it != map->end();
+ ++it) {
+ size += KeyTypeHandler::SpaceUsedInMapLong(it->first);
+ size += ValueTypeHandler::SpaceUsedInMapLong(it->second);
}
return size;
}
-
-template <typename Key, typename T,
- WireFormatLite::FieldType kKeyFieldType,
- WireFormatLite::FieldType kValueFieldType,
- int default_enum_value>
-void
-MapField<Key, T, kKeyFieldType, kValueFieldType,
- default_enum_value>::InitDefaultEntryOnce()
- const {
- if (default_entry_ == NULL) {
- MapFieldBase::InitMetadataOnce();
- GOOGLE_CHECK(*MapFieldBase::entry_descriptor_ != NULL);
- default_entry_ = down_cast<const EntryType*>(
- MessageFactory::generated_factory()->GetPrototype(
- *MapFieldBase::entry_descriptor_));
- }
-}
-
} // namespace internal
} // namespace protobuf
diff --git a/src/google/protobuf/map_field_lite.h b/src/google/protobuf/map_field_lite.h
index cb0a4a45..f648b430 100644
--- a/src/google/protobuf/map_field_lite.h
+++ b/src/google/protobuf/map_field_lite.h
@@ -33,6 +33,7 @@
#include <google/protobuf/map.h>
#include <google/protobuf/map_entry_lite.h>
+#include <google/protobuf/wire_format_lite.h>
namespace google {
namespace protobuf {
@@ -41,224 +42,72 @@ namespace internal {
// This class provides access to map field using generated api. It is used for
// internal generated message implentation only. Users should never use this
// directly.
-template <typename Key, typename T,
+template <typename Derived, typename Key, typename T,
WireFormatLite::FieldType key_wire_type,
- WireFormatLite::FieldType value_wire_type,
- int default_enum_value = 0>
+ WireFormatLite::FieldType value_wire_type, int default_enum_value = 0>
class MapFieldLite {
// Define message type for internal repeated field.
- typedef MapEntryLite<Key, T, key_wire_type, value_wire_type,
- default_enum_value> EntryType;
+ typedef Derived EntryType;
public:
- MapFieldLite();
- explicit MapFieldLite(Arena* arena);
- virtual ~MapFieldLite();
+ typedef Map<Key, T> MapType;
+ typedef EntryType EntryTypeTrait;
+
+ MapFieldLite() : arena_(NULL) { SetDefaultEnumValue(); }
+
+ explicit MapFieldLite(Arena* arena) : arena_(arena), map_(arena) {
+ SetDefaultEnumValue();
+ }
// Accessors
- virtual const Map<Key, T>& GetMap() const;
- virtual Map<Key, T>* MutableMap();
+ const Map<Key, T>& GetMap() const { return map_; }
+ Map<Key, T>* MutableMap() { return &map_; }
// Convenient methods for generated message implementation.
- virtual int size() const;
- virtual void Clear();
- virtual void MergeFrom(const MapFieldLite& other);
- virtual void Swap(MapFieldLite* other);
+ int size() const { return static_cast<int>(map_.size()); }
+ void Clear() { return map_.clear(); }
+ void MergeFrom(const MapFieldLite& other) {
+ for (typename Map<Key, T>::const_iterator it = other.map_.begin();
+ it != other.map_.end(); ++it) {
+ map_[it->first] = it->second;
+ }
+ }
+ void Swap(MapFieldLite* other) { map_.swap(other->map_); }
// Set default enum value only for proto2 map field whose value is enum type.
- void SetDefaultEnumValue();
+ void SetDefaultEnumValue() {
+ MutableMap()->SetDefaultEnumValue(default_enum_value);
+ }
// Used in the implementation of parsing. Caller should take the ownership iff
// arena_ is NULL.
- EntryType* NewEntry() const;
+ EntryType* NewEntry() const {
+ if (arena_ == NULL) {
+ return new EntryType();
+ } else {
+ return Arena::CreateMessage<EntryType>(arena_);
+ }
+ }
// Used in the implementation of serializing enum value type. Caller should
// take the ownership iff arena_ is NULL.
- EntryType* NewEnumEntryWrapper(const Key& key, const T t) const;
+ EntryType* NewEnumEntryWrapper(const Key& key, const T t) const {
+ return EntryType::EnumWrap(key, t, arena_);
+ }
// Used in the implementation of serializing other value types. Caller should
// take the ownership iff arena_ is NULL.
- EntryType* NewEntryWrapper(const Key& key, const T& t) const;
-
- protected:
- // Convenient methods to get internal google::protobuf::Map
- virtual const Map<Key, T>& GetInternalMap() const;
- virtual Map<Key, T>* MutableInternalMap();
+ EntryType* NewEntryWrapper(const Key& key, const T& t) const {
+ return EntryType::Wrap(key, t, arena_);
+ }
private:
typedef void DestructorSkippable_;
Arena* arena_;
- Map<Key, T>* map_;
+ Map<Key, T> map_;
friend class ::google::protobuf::Arena;
};
-template <typename Key, typename T,
- WireFormatLite::FieldType key_wire_type,
- WireFormatLite::FieldType value_wire_type,
- int default_enum_value>
-MapFieldLite<Key, T, key_wire_type, value_wire_type,
- default_enum_value>::MapFieldLite()
- : arena_(NULL) {
- map_ = new Map<Key, T>;
- SetDefaultEnumValue();
-}
-
-template <typename Key, typename T,
- WireFormatLite::FieldType key_wire_type,
- WireFormatLite::FieldType value_wire_type,
- int default_enum_value>
-MapFieldLite<Key, T, key_wire_type, value_wire_type,
- default_enum_value>::MapFieldLite(Arena* arena)
- : arena_(arena) {
- map_ = Arena::CreateMessage<Map<Key, T> >(arena);
- SetDefaultEnumValue();
-}
-
-template <typename Key, typename T,
- WireFormatLite::FieldType key_wire_type,
- WireFormatLite::FieldType value_wire_type,
- int default_enum_value>
-MapFieldLite<Key, T, key_wire_type, value_wire_type,
- default_enum_value>::~MapFieldLite() {
- delete map_;
-}
-
-template <typename Key, typename T,
- WireFormatLite::FieldType key_wire_type,
- WireFormatLite::FieldType value_wire_type,
- int default_enum_value>
-const Map<Key, T>&
-MapFieldLite<Key, T, key_wire_type, value_wire_type,
- default_enum_value>::GetMap() const {
- return *map_;
-}
-
-template <typename Key, typename T,
- WireFormatLite::FieldType key_wire_type,
- WireFormatLite::FieldType value_wire_type,
- int default_enum_value>
-Map<Key, T>*
-MapFieldLite<Key, T, key_wire_type, value_wire_type,
- default_enum_value>::MutableMap() {
- return map_;
-}
-
-template <typename Key, typename T,
- WireFormatLite::FieldType key_wire_type,
- WireFormatLite::FieldType value_wire_type,
- int default_enum_value>
-int
-MapFieldLite<Key, T, key_wire_type, value_wire_type,
- default_enum_value>::size() const {
- return map_->size();
-}
-
-template <typename Key, typename T,
- WireFormatLite::FieldType key_wire_type,
- WireFormatLite::FieldType value_wire_type,
- int default_enum_value>
-void
-MapFieldLite<Key, T, key_wire_type, value_wire_type,
- default_enum_value>::Clear() {
- map_->clear();
-}
-
-template <typename Key, typename T,
- WireFormatLite::FieldType key_wire_type,
- WireFormatLite::FieldType value_wire_type,
- int default_enum_value>
-void
-MapFieldLite<Key, T, key_wire_type, value_wire_type,
- default_enum_value>::MergeFrom(
- const MapFieldLite& other) {
- for (typename Map<Key, T>::const_iterator it = other.map_->begin();
- it != other.map_->end(); ++it) {
- (*map_)[it->first] = it->second;
- }
-}
-
-template <typename Key, typename T,
- WireFormatLite::FieldType key_wire_type,
- WireFormatLite::FieldType value_wire_type,
- int default_enum_value>
-void
-MapFieldLite<Key, T, key_wire_type, value_wire_type,
- default_enum_value>::Swap(
- MapFieldLite* other) {
- std::swap(map_, other->map_);
-}
-
-template <typename Key, typename T,
- WireFormatLite::FieldType key_wire_type,
- WireFormatLite::FieldType value_wire_type,
- int default_enum_value>
-void
-MapFieldLite<Key, T, key_wire_type, value_wire_type,
- default_enum_value>::SetDefaultEnumValue() {
- MutableInternalMap()->SetDefaultEnumValue(default_enum_value);
-}
-
-template <typename Key, typename T,
- WireFormatLite::FieldType key_wire_type,
- WireFormatLite::FieldType value_wire_type,
- int default_enum_value>
-const Map<Key, T>&
-MapFieldLite<Key, T, key_wire_type, value_wire_type,
- default_enum_value>::GetInternalMap() const {
- return *map_;
-}
-
-template <typename Key, typename T,
- WireFormatLite::FieldType key_wire_type,
- WireFormatLite::FieldType value_wire_type,
- int default_enum_value>
-Map<Key, T>*
-MapFieldLite<Key, T, key_wire_type, value_wire_type,
- default_enum_value>::MutableInternalMap() {
- return map_;
-}
-
-#define EntryType \
- MapEntryLite<Key, T, key_wire_type, value_wire_type, default_enum_value>
-
-template <typename Key, typename T,
- WireFormatLite::FieldType key_wire_type,
- WireFormatLite::FieldType value_wire_type,
- int default_enum_value>
-EntryType*
-MapFieldLite<Key, T, key_wire_type, value_wire_type,
- default_enum_value>::NewEntry() const {
- if (arena_ == NULL) {
- return new EntryType();
- } else {
- return Arena::CreateMessage<EntryType>(arena_);
- }
-}
-
-template <typename Key, typename T,
- WireFormatLite::FieldType key_wire_type,
- WireFormatLite::FieldType value_wire_type,
- int default_enum_value>
-EntryType*
-MapFieldLite<Key, T, key_wire_type, value_wire_type,
- default_enum_value>::NewEnumEntryWrapper(const Key& key,
- const T t) const {
- return EntryType::EnumWrap(key, t, arena_);
-}
-
-template <typename Key, typename T,
- WireFormatLite::FieldType key_wire_type,
- WireFormatLite::FieldType value_wire_type,
- int default_enum_value>
-EntryType*
-MapFieldLite<Key, T, key_wire_type, value_wire_type,
- default_enum_value>::NewEntryWrapper(const Key& key,
- const T& t) const {
- return EntryType::Wrap(key, t, arena_);
-}
-
-#undef EntryType
-
// True if IsInitialized() is true for value field in all elements of t. T is
// expected to be message. It's useful to have this helper here to keep the
// protobuf compiler from ever having to emit loops in IsInitialized() methods.
@@ -272,6 +121,21 @@ bool AllAreInitialized(const Map<Key, T>& t) {
return true;
}
+template <typename MEntry>
+struct MapEntryToMapField : MapEntryToMapField<typename MEntry::SuperType> {};
+
+template <typename T, typename Key, typename Value,
+ WireFormatLite::FieldType kKeyFieldType,
+ WireFormatLite::FieldType kValueFieldType, int default_enum_value>
+struct MapEntryToMapField<MapEntryLite<T, Key, Value, kKeyFieldType,
+ kValueFieldType, default_enum_value> > {
+ typedef MapFieldLite<MapEntryLite<T, Key, Value, kKeyFieldType,
+ kValueFieldType, default_enum_value>,
+ Key, Value, kKeyFieldType, kValueFieldType,
+ default_enum_value>
+ MapFieldType;
+};
+
} // namespace internal
} // namespace protobuf
diff --git a/src/google/protobuf/map_field_test.cc b/src/google/protobuf/map_field_test.cc
index dd5061c4..4e0e751c 100644
--- a/src/google/protobuf/map_field_test.cc
+++ b/src/google/protobuf/map_field_test.cc
@@ -101,8 +101,10 @@ class MapFieldBaseStub : public MapFieldBase {
class MapFieldBasePrimitiveTest : public ::testing::Test {
protected:
- typedef MapField<int32, int32, WireFormatLite::TYPE_INT32,
- WireFormatLite::TYPE_INT32, false> MapFieldType;
+ typedef unittest::TestMap_MapInt32Int32Entry_DoNotUse EntryType;
+ typedef MapField<EntryType, int32, int32, WireFormatLite::TYPE_INT32,
+ WireFormatLite::TYPE_INT32, false>
+ MapFieldType;
MapFieldBasePrimitiveTest() {
// Get descriptors
@@ -113,9 +115,7 @@ class MapFieldBasePrimitiveTest : public ::testing::Test {
value_descriptor_ = map_descriptor_->FindFieldByName("value");
// Build map field
- default_entry_ =
- MessageFactory::generated_factory()->GetPrototype(map_descriptor_);
- map_field_.reset(new MapFieldType(default_entry_));
+ map_field_.reset(new MapFieldType);
map_field_base_ = map_field_.get();
map_ = map_field_->MutableMap();
initial_value_map_[0] = 100;
@@ -130,7 +130,6 @@ class MapFieldBasePrimitiveTest : public ::testing::Test {
const Descriptor* map_descriptor_;
const FieldDescriptor* key_descriptor_;
const FieldDescriptor* value_descriptor_;
- const Message* default_entry_;
std::map<int32, int32> initial_value_map_; // copy of initial values inserted
};
@@ -177,8 +176,7 @@ TEST_F(MapFieldBasePrimitiveTest, Arena) {
// repeated fields are allocated from arenas.
// NoHeapChecker no_heap;
- MapFieldType* map_field =
- Arena::CreateMessage<MapFieldType>(&arena, default_entry_);
+ MapFieldType* map_field = Arena::CreateMessage<MapFieldType>(&arena);
// Set content in map
(*map_field->MutableMap())[100] = 101;
@@ -208,19 +206,13 @@ class MapFieldStateTest
: public testing::TestWithParam<State> {
public:
protected:
- typedef MapField<int32, int32, WireFormatLite::TYPE_INT32,
- WireFormatLite::TYPE_INT32, false> MapFieldType;
- typedef MapFieldLite<int32, int32, WireFormatLite::TYPE_INT32,
- WireFormatLite::TYPE_INT32, false> MapFieldLiteType;
+ typedef unittest::TestMap_MapInt32Int32Entry_DoNotUse EntryType;
+ typedef MapField<EntryType, int32, int32, WireFormatLite::TYPE_INT32,
+ WireFormatLite::TYPE_INT32, false>
+ MapFieldType;
MapFieldStateTest() : state_(GetParam()) {
// Build map field
- const Descriptor* map_descriptor =
- unittest::TestMap::descriptor()
- ->FindFieldByName("map_int32_int32")
- ->message_type();
- default_entry_ =
- MessageFactory::generated_factory()->GetPrototype(map_descriptor);
- map_field_.reset(new MapFieldType(default_entry_));
+ map_field_.reset(new MapFieldType());
map_field_base_ = map_field_.get();
Expect(map_field_.get(), MAP_DIRTY, 0, 0, true);
@@ -257,8 +249,8 @@ class MapFieldStateTest
MakeMapDirty(map_field);
MapFieldBase* map_field_base = map_field;
map_field_base->MutableRepeatedField();
- Map<int32, int32>* map = implicit_cast<MapFieldLiteType*>(map_field)
- ->MapFieldLiteType::MutableMap();
+ // We use MutableMap on impl_ because we don't want to disturb the syncing
+ Map<int32, int32>* map = map_field->impl_.MutableMap();
map->clear();
Expect(map_field, REPEATED_DIRTY, 0, 1, false);
@@ -270,8 +262,8 @@ class MapFieldStateTest
MapFieldBaseStub* stub =
reinterpret_cast<MapFieldBaseStub*>(map_field_base);
- Map<int32, int32>* map = implicit_cast<MapFieldLiteType*>(map_field)
- ->MapFieldLiteType::MutableMap();
+ // We use MutableMap on impl_ because we don't want to disturb the syncing
+ Map<int32, int32>* map = map_field->impl_.MutableMap();
RepeatedPtrField<Message>* repeated_field = stub->InternalRepeatedField();
switch (state) {
@@ -302,7 +294,6 @@ class MapFieldStateTest
google::protobuf::scoped_ptr<MapFieldType> map_field_;
MapFieldBase* map_field_base_;
State state_;
- const Message* default_entry_;
};
INSTANTIATE_TEST_CASE_P(MapFieldStateTestInstance, MapFieldStateTest,
@@ -327,7 +318,7 @@ TEST_P(MapFieldStateTest, MutableMap) {
}
TEST_P(MapFieldStateTest, MergeFromClean) {
- MapFieldType other(default_entry_);
+ MapFieldType other;
AddOneStillClean(&other);
map_field_->MergeFrom(other);
@@ -342,7 +333,7 @@ TEST_P(MapFieldStateTest, MergeFromClean) {
}
TEST_P(MapFieldStateTest, MergeFromMapDirty) {
- MapFieldType other(default_entry_);
+ MapFieldType other;
MakeMapDirty(&other);
map_field_->MergeFrom(other);
@@ -357,7 +348,7 @@ TEST_P(MapFieldStateTest, MergeFromMapDirty) {
}
TEST_P(MapFieldStateTest, MergeFromRepeatedDirty) {
- MapFieldType other(default_entry_);
+ MapFieldType other;
MakeRepeatedDirty(&other);
map_field_->MergeFrom(other);
@@ -372,7 +363,7 @@ TEST_P(MapFieldStateTest, MergeFromRepeatedDirty) {
}
TEST_P(MapFieldStateTest, SwapClean) {
- MapFieldType other(default_entry_);
+ MapFieldType other;
AddOneStillClean(&other);
map_field_->Swap(&other);
@@ -395,7 +386,7 @@ TEST_P(MapFieldStateTest, SwapClean) {
}
TEST_P(MapFieldStateTest, SwapMapDirty) {
- MapFieldType other(default_entry_);
+ MapFieldType other;
MakeMapDirty(&other);
map_field_->Swap(&other);
@@ -418,7 +409,7 @@ TEST_P(MapFieldStateTest, SwapMapDirty) {
}
TEST_P(MapFieldStateTest, SwapRepeatedDirty) {
- MapFieldType other(default_entry_);
+ MapFieldType other;
MakeRepeatedDirty(&other);
map_field_->Swap(&other);
diff --git a/src/google/protobuf/map_proto2_unittest.proto b/src/google/protobuf/map_proto2_unittest.proto
index e9360a5a..20d58f90 100644
--- a/src/google/protobuf/map_proto2_unittest.proto
+++ b/src/google/protobuf/map_proto2_unittest.proto
@@ -84,3 +84,8 @@ message TestMaps {
map<bool, TestIntIntMap> m_bool = 11;
map<string, TestIntIntMap> m_string = 12;
}
+
+// Test maps in submessages.
+message TestSubmessageMaps {
+ optional TestMaps m = 1;
+}
diff --git a/src/google/protobuf/map_test.cc b/src/google/protobuf/map_test.cc
index d0a34d01..080c71a7 100644
--- a/src/google/protobuf/map_test.cc
+++ b/src/google/protobuf/map_test.cc
@@ -54,10 +54,13 @@
#include <google/protobuf/testing/file.h>
#include <google/protobuf/arena_test_util.h>
#include <google/protobuf/map_proto2_unittest.pb.h>
-#include <google/protobuf/map_unittest.pb.h>
#include <google/protobuf/map_test_util.h>
+#include <google/protobuf/map_unittest.pb.h>
#include <google/protobuf/test_util.h>
#include <google/protobuf/unittest.pb.h>
+#include <google/protobuf/io/coded_stream.h>
+#include <google/protobuf/io/tokenizer.h>
+#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/descriptor_database.h>
@@ -70,12 +73,8 @@
#include <google/protobuf/text_format.h>
#include <google/protobuf/wire_format.h>
#include <google/protobuf/wire_format_lite_inl.h>
-#include <google/protobuf/io/coded_stream.h>
-#include <google/protobuf/io/tokenizer.h>
-#include <google/protobuf/io/zero_copy_stream_impl.h>
-#include <google/protobuf/util/time_util.h>
#include <google/protobuf/util/message_differencer.h>
-#include <google/protobuf/stubs/strutil.h>
+#include <google/protobuf/util/time_util.h>
#include <google/protobuf/stubs/substitute.h>
#include <gmock/gmock.h>
#include <google/protobuf/testing/googletest.h>
@@ -91,19 +90,21 @@ using google::protobuf::unittest::TestRecursiveMapMessage;
namespace protobuf {
namespace internal {
+void MapTestForceDeterministic() {
+ ::google::protobuf::io::CodedOutputStream::SetDefaultSerializationDeterministic();
+}
+
// Map API Test =====================================================
-// Parameterized tests on whether to use old style maps.
-class MapImplTest : public testing::TestWithParam<bool> {
+class MapImplTest : public ::testing::Test {
protected:
MapImplTest()
- : map_ptr_(new Map<int32, int32>(GetParam())),
+ : map_ptr_(new Map<int32, int32>()),
map_(*map_ptr_),
const_map_(*map_ptr_) {
EXPECT_TRUE(map_.empty());
EXPECT_EQ(0, map_.size());
}
- ~MapImplTest() {}
void ExpectSingleElement(int32 key, int32 value) {
EXPECT_FALSE(map_.empty());
@@ -129,7 +130,7 @@ class MapImplTest : public testing::TestWithParam<bool> {
EXPECT_EQ(value, map_.at(key));
Map<int32, int32>::iterator it = map_.find(key);
- // interator dereferenceable
+ // iterator dereferenceable
EXPECT_EQ(key, (*it).first);
EXPECT_EQ(value, (*it).second);
EXPECT_EQ(key, it->first);
@@ -157,7 +158,7 @@ class MapImplTest : public testing::TestWithParam<bool> {
EXPECT_EQ(value, const_map_.at(key));
Map<int32, int32>::const_iterator const_it = const_map_.find(key);
- // interator dereferenceable
+ // iterator dereferenceable
EXPECT_EQ(key, (*const_it).first);
EXPECT_EQ(value, (*const_it).second);
EXPECT_EQ(key, const_it->first);
@@ -174,7 +175,7 @@ class MapImplTest : public testing::TestWithParam<bool> {
const Map<int32, int32>& const_map_;
};
-TEST_P(MapImplTest, OperatorBracket) {
+TEST_F(MapImplTest, OperatorBracket) {
int32 key = 0;
int32 value1 = 100;
int32 value2 = 101;
@@ -188,7 +189,7 @@ TEST_P(MapImplTest, OperatorBracket) {
ExpectSingleElement(key, value2);
}
-TEST_P(MapImplTest, OperatorBracketNonExist) {
+TEST_F(MapImplTest, OperatorBracketNonExist) {
int32 key = 0;
int32 default_value = 0;
@@ -196,7 +197,7 @@ TEST_P(MapImplTest, OperatorBracketNonExist) {
ExpectSingleElement(key, default_value);
}
-TEST_P(MapImplTest, MutableAt) {
+TEST_F(MapImplTest, MutableAt) {
int32 key = 0;
int32 value1 = 100;
int32 value2 = 101;
@@ -210,15 +211,15 @@ TEST_P(MapImplTest, MutableAt) {
#ifdef PROTOBUF_HAS_DEATH_TEST
-TEST_P(MapImplTest, MutableAtNonExistDeathTest) {
+TEST_F(MapImplTest, MutableAtNonExistDeathTest) {
EXPECT_DEATH(map_.at(0), "");
}
-TEST_P(MapImplTest, ImmutableAtNonExistDeathTest) {
+TEST_F(MapImplTest, ImmutableAtNonExistDeathTest) {
EXPECT_DEATH(const_map_.at(0), "");
}
-TEST_P(MapImplTest, UsageErrors) {
+TEST_F(MapImplTest, UsageErrors) {
MapKey key;
key.SetInt64Value(1);
EXPECT_DEATH(key.GetUInt64Value(),
@@ -235,23 +236,30 @@ TEST_P(MapImplTest, UsageErrors) {
#endif // PROTOBUF_HAS_DEATH_TEST
-TEST_P(MapImplTest, CountNonExist) {
+TEST_F(MapImplTest, MapKeyAssignment) {
+ MapKey from, to;
+ from.SetStringValue("abc");
+ to = from;
+ EXPECT_EQ("abc", to.GetStringValue());
+}
+
+TEST_F(MapImplTest, CountNonExist) {
EXPECT_EQ(0, map_.count(0));
}
-TEST_P(MapImplTest, MutableFindNonExist) {
+TEST_F(MapImplTest, MutableFindNonExist) {
EXPECT_TRUE(map_.end() == map_.find(0));
}
-TEST_P(MapImplTest, ImmutableFindNonExist) {
+TEST_F(MapImplTest, ImmutableFindNonExist) {
EXPECT_TRUE(const_map_.end() == const_map_.find(0));
}
-TEST_P(MapImplTest, ConstEnd) {
+TEST_F(MapImplTest, ConstEnd) {
EXPECT_TRUE(const_map_.end() == const_map_.cend());
}
-TEST_P(MapImplTest, GetReferenceFromIterator) {
+TEST_F(MapImplTest, GetReferenceFromIterator) {
for (int i = 0; i < 10; i++) {
map_[i] = i;
}
@@ -274,7 +282,7 @@ TEST_P(MapImplTest, GetReferenceFromIterator) {
}
}
-TEST_P(MapImplTest, IteratorBasic) {
+TEST_F(MapImplTest, IteratorBasic) {
map_[0] = 0;
// Default constructible (per forward iterator requirements).
@@ -316,10 +324,9 @@ static int k2 = 1321555333;
// A naive begin() implementation will cause begin() to get slower and slower
// if one erases elements at the "front" of the hash map, and we'd like to
// avoid that, as std::unordered_map does.
-TEST_P(MapImplTest, BeginIsFast) {
- // Disable this test for both new and old implementations.
- if (/*GetParam()*/true) return;
- Map<int32, int32> map(false); // This test uses new-style maps only.
+TEST_F(MapImplTest, BeginIsFast) {
+ if (true) return; // TODO(gpike): make this less flaky and re-enable it.
+ Map<int32, int32> map;
const int kTestSize = 250000;
// Create a random-looking map of size n. Use non-negative integer keys.
uint32 frog = 123983;
@@ -367,7 +374,7 @@ TEST_P(MapImplTest, BeginIsFast) {
// Try to create kTestSize keys that will land in just a few buckets, and
// time the insertions, to get a rough estimate of whether an O(n^2) worst case
// was triggered. This test is a hacky, but probably better than nothing.
-TEST_P(MapImplTest, HashFlood) {
+TEST_F(MapImplTest, HashFlood) {
const int kTestSize = 1024; // must be a power of 2
std::set<int> s;
for (int i = 0; s.size() < kTestSize; i++) {
@@ -400,6 +407,22 @@ TEST_P(MapImplTest, HashFlood) {
EXPECT_LE(x1, x0 * 20);
}
+TEST_F(MapImplTest, CopyIteratorStressTest) {
+ std::vector<Map<int32, int32>::iterator> v;
+ const int kIters = 1e5;
+ for (uint32 i = 0; i < kIters; i++) {
+ int32 key = (3 + i * (5 + i * (-8 + i * (62 + i)))) & 0x77777777;
+ map_[key] = i;
+ v.push_back(map_.find(key));
+ }
+ for (std::vector<Map<int32, int32>::iterator>::const_iterator it = v.begin();
+ it != v.end(); it++) {
+ Map<int32, int32>::iterator i = *it;
+ ASSERT_EQ(i->first, (*it)->first);
+ ASSERT_EQ(i->second, (*it)->second);
+ }
+}
+
template <typename T, typename U>
static void TestValidityForAllKeysExcept(int key_to_avoid,
const T& check_map,
@@ -464,11 +487,11 @@ static void TestOldVersusNewIterator(int skip, Map<int, int>* m) {
}
// Create and test an n-element Map, with emphasis on iterator correctness.
-static void StressTestIterators(int n, bool test_old_style_proto2_maps) {
+static void StressTestIterators(int n) {
GOOGLE_LOG(INFO) << "StressTestIterators " << n;
GOOGLE_CHECK_GT(n, 0);
// Create a random-looking map of size n. Use non-negative integer keys.
- Map<int, int> m(test_old_style_proto2_maps);
+ Map<int, int> m;
uint32 frog = 123987 + n;
int last_key = 0;
int counter = 0;
@@ -526,10 +549,7 @@ static void StressTestIterators(int n, bool test_old_style_proto2_maps) {
}
}
-TEST_P(MapImplTest, IteratorInvalidation) {
- // As multiple underlying hash_map implementations do not follow the
- // validation requirement, the test is disabled for old-style maps.
- if (GetParam()) return;
+TEST_F(MapImplTest, IteratorInvalidation) {
// Create a set of pseudo-random sizes to test.
#ifndef NDEBUG
const int kMaxSizeToTest = 100 * 1000;
@@ -538,7 +558,7 @@ TEST_P(MapImplTest, IteratorInvalidation) {
#endif
std::set<int> s;
int n = kMaxSizeToTest;
- int frog = k1 + n;
+ unsigned int frog = k1 + n;
while (n > 1 && s.size() < 25) {
s.insert(n);
n = static_cast<int>(n * 100 / (101.0 + (frog & 63)));
@@ -551,15 +571,12 @@ TEST_P(MapImplTest, IteratorInvalidation) {
s.insert(3);
// Now, the real work.
for (std::set<int>::iterator i = s.begin(); i != s.end(); ++i) {
- StressTestIterators(*i, GetParam());
+ StressTestIterators(*i);
}
}
// Test that erase() revalidates iterators.
-TEST_P(MapImplTest, EraseRevalidates) {
- // As multiple underlying hash_map implementations do not follow the
- // validation requirement, the test is disabled for old-style maps.
- if (GetParam()) return;
+TEST_F(MapImplTest, EraseRevalidates) {
map_[3] = map_[13] = map_[20] = 0;
const int initial_size = map_.size();
EXPECT_EQ(3, initial_size);
@@ -591,7 +608,7 @@ bool IsConstHelper(const T& /*t*/) {
return true;
}
-TEST_P(MapImplTest, IteratorConstness) {
+TEST_F(MapImplTest, IteratorConstness) {
map_[0] = 0;
EXPECT_TRUE(IsConstHelper(*map_.cbegin()));
EXPECT_TRUE(IsConstHelper(*const_map_.begin()));
@@ -604,14 +621,14 @@ bool IsForwardIteratorHelper(T /*t*/) {
return false;
}
-TEST_P(MapImplTest, IteratorCategory) {
+TEST_F(MapImplTest, IteratorCategory) {
EXPECT_TRUE(IsForwardIteratorHelper(
std::iterator_traits<Map<int, int>::iterator>::iterator_category()));
EXPECT_TRUE(IsForwardIteratorHelper(std::iterator_traits<
Map<int, int>::const_iterator>::iterator_category()));
}
-TEST_P(MapImplTest, InsertSingle) {
+TEST_F(MapImplTest, InsertSingle) {
int32 key = 0;
int32 value1 = 100;
int32 value2 = 101;
@@ -636,7 +653,7 @@ TEST_P(MapImplTest, InsertSingle) {
EXPECT_FALSE(result2.second);
}
-TEST_P(MapImplTest, InsertByIterator) {
+TEST_F(MapImplTest, InsertByIterator) {
int32 key1 = 0;
int32 key2 = 1;
int32 value1a = 100;
@@ -659,7 +676,7 @@ TEST_P(MapImplTest, InsertByIterator) {
ExpectElements(map1);
}
-TEST_P(MapImplTest, EraseSingleByKey) {
+TEST_F(MapImplTest, EraseSingleByKey) {
int32 key = 0;
int32 value = 100;
@@ -677,7 +694,7 @@ TEST_P(MapImplTest, EraseSingleByKey) {
EXPECT_EQ(0, map_.erase(key));
}
-TEST_P(MapImplTest, EraseMutipleByKey) {
+TEST_F(MapImplTest, EraseMutipleByKey) {
// erase in one specific order to trigger corner cases
for (int i = 0; i < 5; i++) {
map_[i] = i;
@@ -704,7 +721,7 @@ TEST_P(MapImplTest, EraseMutipleByKey) {
EXPECT_TRUE(map_.end() == map_.find(2));
}
-TEST_P(MapImplTest, EraseSingleByIterator) {
+TEST_F(MapImplTest, EraseSingleByIterator) {
int32 key = 0;
int32 value = 100;
@@ -719,7 +736,7 @@ TEST_P(MapImplTest, EraseSingleByIterator) {
EXPECT_TRUE(map_.begin() == map_.end());
}
-TEST_P(MapImplTest, ValidIteratorAfterErase) {
+TEST_F(MapImplTest, ValidIteratorAfterErase) {
for (int i = 0; i < 10; i++) {
map_[i] = i;
}
@@ -739,7 +756,7 @@ TEST_P(MapImplTest, ValidIteratorAfterErase) {
EXPECT_EQ(5, map_.size());
}
-TEST_P(MapImplTest, EraseByIterator) {
+TEST_F(MapImplTest, EraseByIterator) {
int32 key1 = 0;
int32 key2 = 1;
int32 value1 = 100;
@@ -760,7 +777,7 @@ TEST_P(MapImplTest, EraseByIterator) {
EXPECT_TRUE(map_.begin() == map_.end());
}
-TEST_P(MapImplTest, Clear) {
+TEST_F(MapImplTest, Clear) {
int32 key = 0;
int32 value = 100;
@@ -794,16 +811,16 @@ static void CopyConstructorHelper(Arena* arena, Map<int32, int32>* m) {
EXPECT_EQ(value2, other.at(key2));
}
-TEST_P(MapImplTest, CopyConstructorWithArena) {
+TEST_F(MapImplTest, CopyConstructorWithArena) {
Arena a;
CopyConstructorHelper(&a, &map_);
}
-TEST_P(MapImplTest, CopyConstructorWithoutArena) {
+TEST_F(MapImplTest, CopyConstructorWithoutArena) {
CopyConstructorHelper(NULL, &map_);
}
-TEST_P(MapImplTest, IterConstructor) {
+TEST_F(MapImplTest, IterConstructor) {
int32 key1 = 0;
int32 key2 = 1;
int32 value1 = 100;
@@ -813,15 +830,14 @@ TEST_P(MapImplTest, IterConstructor) {
map[key1] = value1;
map[key2] = value2;
- Map<int32, int32> new_map(map.begin(), map.end(),
- GetParam());
+ Map<int32, int32> new_map(map.begin(), map.end());
EXPECT_EQ(2, new_map.size());
EXPECT_EQ(value1, new_map.at(key1));
EXPECT_EQ(value2, new_map.at(key2));
}
-TEST_P(MapImplTest, Assigner) {
+TEST_F(MapImplTest, Assigner) {
int32 key1 = 0;
int32 key2 = 1;
int32 value1 = 100;
@@ -833,7 +849,7 @@ TEST_P(MapImplTest, Assigner) {
map_.insert(map.begin(), map.end());
- Map<int32, int32> other(GetParam());
+ Map<int32, int32> other;
int32 key_other = 123;
int32 value_other = 321;
other[key_other] = value_other;
@@ -851,16 +867,9 @@ TEST_P(MapImplTest, Assigner) {
EXPECT_EQ(2, other.size());
EXPECT_EQ(value1, other.at(key1));
EXPECT_EQ(value2, other.at(key2));
-
- // Try assignment to a map with a different choice of "style."
- Map<int32, int32> m(!GetParam());
- m = other;
- EXPECT_EQ(2, m.size());
- EXPECT_EQ(value1, m.at(key1));
- EXPECT_EQ(value2, m.at(key2));
}
-TEST_P(MapImplTest, Rehash) {
+TEST_F(MapImplTest, Rehash) {
const int test_size = 50;
std::map<int32, int32> reference_map;
for (int i = 0; i < test_size; i++) {
@@ -877,7 +886,7 @@ TEST_P(MapImplTest, Rehash) {
EXPECT_TRUE(map_.empty());
}
-TEST_P(MapImplTest, EqualRange) {
+TEST_F(MapImplTest, EqualRange) {
int key = 100, key_missing = 101;
map_[key] = 100;
@@ -901,14 +910,14 @@ TEST_P(MapImplTest, EqualRange) {
EXPECT_TRUE(const_map_.end() == const_range.second);
}
-TEST_P(MapImplTest, ConvertToStdMap) {
+TEST_F(MapImplTest, ConvertToStdMap) {
map_[100] = 101;
std::map<int32, int32> std_map(map_.begin(), map_.end());
EXPECT_EQ(1, std_map.size());
EXPECT_EQ(101, std_map[100]);
}
-TEST_P(MapImplTest, ConvertToStdVectorOfPairs) {
+TEST_F(MapImplTest, ConvertToStdVectorOfPairs) {
map_[100] = 101;
std::vector<std::pair<int32, int32> > std_vec(map_.begin(), map_.end());
EXPECT_EQ(1, std_vec.size());
@@ -916,21 +925,8 @@ TEST_P(MapImplTest, ConvertToStdVectorOfPairs) {
EXPECT_EQ(101, std_vec[0].second);
}
-TEST_P(MapImplTest, SwapSameStyle) {
- Map<int32, int32> another(GetParam()); // same old_style_ value
- map_[9398] = 41999;
- another[9398] = 41999;
- another[8070] = 42056;
- another.swap(map_);
- EXPECT_THAT(another, testing::UnorderedElementsAre(
- testing::Pair(9398, 41999)));
- EXPECT_THAT(map_, testing::UnorderedElementsAre(
- testing::Pair(8070, 42056),
- testing::Pair(9398, 41999)));
-}
-
-TEST_P(MapImplTest, SwapDifferentStyle) {
- Map<int32, int32> another(!GetParam()); // different old_style_ value
+TEST_F(MapImplTest, SwapBasic) {
+ Map<int32, int32> another;
map_[9398] = 41999;
another[9398] = 41999;
another[8070] = 42056;
@@ -942,10 +938,10 @@ TEST_P(MapImplTest, SwapDifferentStyle) {
testing::Pair(9398, 41999)));
}
-TEST_P(MapImplTest, SwapArena) {
+TEST_F(MapImplTest, SwapArena) {
Arena arena1, arena2;
- Map<int32, int32> m1(&arena1, false);
- Map<int32, int32> m2(&arena2, false);
+ Map<int32, int32> m1(&arena1);
+ Map<int32, int32> m2(&arena2);
map_[9398] = 41999;
m1[9398] = 41999;
m1[8070] = 42056;
@@ -965,7 +961,16 @@ TEST_P(MapImplTest, SwapArena) {
testing::Pair(9398, 41999)));
}
-INSTANTIATE_TEST_CASE_P(BoolSequence, MapImplTest, testing::Bool());
+TEST_F(MapImplTest, CopyAssignMapIterator) {
+ TestMap message;
+ MapReflectionTester reflection_tester(
+ unittest::TestMap::descriptor());
+ reflection_tester.SetMapFieldsViaMapReflection(&message);
+ MapIterator it1 = reflection_tester.MapBegin(&message, "map_int32_int32");
+ MapIterator it2 = reflection_tester.MapEnd(&message, "map_int32_int32");
+ it2 = it1;
+ EXPECT_EQ(it1.GetKey().GetInt32Value(), it2.GetKey().GetInt32Value());
+}
// Map Field Reflection Test ========================================
@@ -988,6 +993,11 @@ static int Int(const string& value) {
class MapFieldReflectionTest : public testing::Test {
protected:
typedef FieldDescriptor FD;
+
+ int MapSize(const Reflection* reflection, const FieldDescriptor* field,
+ const Message& message) {
+ return reflection->MapSize(message, field);
+ }
};
TEST_F(MapFieldReflectionTest, RegularFields) {
@@ -1795,6 +1805,50 @@ TEST_F(MapFieldReflectionTest, RepeatedFieldRefMergeFromAndSwap) {
// TODO(teboring): add test for duplicated key
}
+TEST_F(MapFieldReflectionTest, MapSizeWithDuplicatedKey) {
+ // Dynamic Message
+ {
+ DynamicMessageFactory factory;
+ google::protobuf::scoped_ptr<Message> message(
+ factory.GetPrototype(unittest::TestMap::descriptor())->New());
+ const Reflection* reflection = message->GetReflection();
+ const FieldDescriptor* field =
+ unittest::TestMap::descriptor()->FindFieldByName("map_int32_int32");
+
+ Message* entry1 = reflection->AddMessage(message.get(), field);
+ Message* entry2 = reflection->AddMessage(message.get(), field);
+
+ const Reflection* entry_reflection = entry1->GetReflection();
+ const FieldDescriptor* key_field =
+ entry1->GetDescriptor()->FindFieldByName("key");
+ entry_reflection->SetInt32(entry1, key_field, 1);
+ entry_reflection->SetInt32(entry2, key_field, 1);
+
+ EXPECT_EQ(2, reflection->FieldSize(*message, field));
+ EXPECT_EQ(1, MapSize(reflection, field, *message));
+ }
+
+ // Generated Message
+ {
+ unittest::TestMap message;
+ const Reflection* reflection = message.GetReflection();
+ const FieldDescriptor* field =
+ message.GetDescriptor()->FindFieldByName("map_int32_int32");
+
+ Message* entry1 = reflection->AddMessage(&message, field);
+ Message* entry2 = reflection->AddMessage(&message, field);
+
+ const Reflection* entry_reflection = entry1->GetReflection();
+ const FieldDescriptor* key_field =
+ entry1->GetDescriptor()->FindFieldByName("key");
+ entry_reflection->SetInt32(entry1, key_field, 1);
+ entry_reflection->SetInt32(entry2, key_field, 1);
+
+ EXPECT_EQ(2, reflection->FieldSize(message, field));
+ EXPECT_EQ(1, MapSize(reflection, field, message));
+ }
+}
+
// Generated Message Test ===========================================
TEST(GeneratedMapFieldTest, Accessors) {
@@ -2702,6 +2756,69 @@ TEST_F(MapFieldInDynamicMessageTest, RecursiveMap) {
ASSERT_TRUE(to->ParseFromString(data));
}
+TEST_F(MapFieldInDynamicMessageTest, MapValueReferernceValidAfterSerialize) {
+ google::protobuf::scoped_ptr<Message> message(map_prototype_->New());
+ MapReflectionTester reflection_tester(map_descriptor_);
+ reflection_tester.SetMapFieldsViaMapReflection(message.get());
+
+ // Get value reference before serialization, so that we know the value is from
+ // map.
+ MapKey map_key;
+ MapValueRef map_val;
+ map_key.SetInt32Value(0);
+ reflection_tester.GetMapValueViaMapReflection(
+ message.get(), "map_int32_foreign_message", map_key, &map_val);
+ Message* submsg = map_val.MutableMessageValue();
+
+ // In previous implementation, calling SerializeToString will cause syncing
+ // from map to repeated field, which will invalidate the submsg we previously
+ // got.
+ string data;
+ message->SerializeToString(&data);
+
+ const Reflection* submsg_reflection = submsg->GetReflection();
+ const Descriptor* submsg_desc = submsg->GetDescriptor();
+ const FieldDescriptor* submsg_field = submsg_desc->FindFieldByName("c");
+ submsg_reflection->SetInt32(submsg, submsg_field, 128);
+
+ message->SerializeToString(&data);
+ TestMap to;
+ to.ParseFromString(data);
+ EXPECT_EQ(128, to.map_int32_foreign_message().at(0).c());
+}
+
+TEST_F(MapFieldInDynamicMessageTest, MapEntryReferernceValidAfterSerialize) {
+ google::protobuf::scoped_ptr<Message> message(map_prototype_->New());
+ MapReflectionTester reflection_tester(map_descriptor_);
+ reflection_tester.SetMapFieldsViaReflection(message.get());
+
+ // Get map entry before serialization, so that we know the it is from
+ // repeated field.
+ Message* map_entry = reflection_tester.GetMapEntryViaReflection(
+ message.get(), "map_int32_foreign_message", 0);
+ const Reflection* map_entry_reflection = map_entry->GetReflection();
+ const Descriptor* map_entry_desc = map_entry->GetDescriptor();
+ const FieldDescriptor* value_field = map_entry_desc->FindFieldByName("value");
+ Message* submsg =
+ map_entry_reflection->MutableMessage(map_entry, value_field);
+
+ // In previous implementation, calling SerializeToString will cause syncing
+ // from repeated field to map, which will invalidate the map_entry we
+ // previously got.
+ string data;
+ message->SerializeToString(&data);
+
+ const Reflection* submsg_reflection = submsg->GetReflection();
+ const Descriptor* submsg_desc = submsg->GetDescriptor();
+ const FieldDescriptor* submsg_field = submsg_desc->FindFieldByName("c");
+ submsg_reflection->SetInt32(submsg, submsg_field, 128);
+
+ message->SerializeToString(&data);
+ TestMap to;
+ to.ParseFromString(data);
+ EXPECT_EQ(128, to.map_int32_foreign_message().at(0).c());
+}
+
// ReflectionOps Test ===============================================
TEST(ReflectionOpsForMapFieldTest, MapSanityCheck) {
@@ -2764,6 +2881,20 @@ TEST(ReflectionOpsForMapFieldTest, MapDiscardUnknownFields) {
GetUnknownFields(message).field_count());
}
+TEST(ReflectionOpsForMapFieldTest, IsInitialized) {
+ unittest::TestRequiredMessageMap map_message;
+
+ // Add an uninitialized message.
+ (*map_message.mutable_map_field())[0];
+ EXPECT_FALSE(ReflectionOps::IsInitialized(map_message));
+
+ // Initialize uninitialized message
+ (*map_message.mutable_map_field())[0].set_a(0);
+ (*map_message.mutable_map_field())[0].set_b(0);
+ (*map_message.mutable_map_field())[0].set_c(0);
+ EXPECT_TRUE(ReflectionOps::IsInitialized(map_message));
+}
+
// Wire Format Test =================================================
TEST(WireFormatForMapFieldTest, ParseMap) {
@@ -2824,6 +2955,33 @@ TEST(WireFormatForMapFieldTest, SerializeMap) {
EXPECT_TRUE(dynamic_data == generated_data);
}
+TEST(WireFormatForMapFieldTest, SerializeMapDynamicMessage) {
+ DynamicMessageFactory factory;
+ google::protobuf::scoped_ptr<Message> dynamic_message;
+ dynamic_message.reset(
+ factory.GetPrototype(unittest::TestMap::descriptor())->New());
+ MapReflectionTester reflection_tester(
+ unittest::TestMap::descriptor());
+ reflection_tester.SetMapFieldsViaReflection(dynamic_message.get());
+ reflection_tester.ExpectMapFieldsSetViaReflection(*dynamic_message);
+
+ unittest::TestMap generated_message;
+ MapTestUtil::SetMapFields(&generated_message);
+ MapTestUtil::ExpectMapFieldsSet(generated_message);
+
+ string generated_data;
+ string dynamic_data;
+
+ // Serialize.
+ generated_message.SerializeToString(&generated_data);
+ dynamic_message->SerializeToString(&dynamic_data);
+
+ // Because map serialization doesn't guarantee order, we just compare
+ // serialized size here. This is enough to tell dynamic message doesn't miss
+ // anything in serialization.
+ EXPECT_TRUE(dynamic_data.size() == generated_data.size());
+}
+
TEST(WireFormatForMapFieldTest, MapParseHelpers) {
string data;
@@ -2844,7 +3002,7 @@ TEST(WireFormatForMapFieldTest, MapParseHelpers) {
{
// Test ParseFromIstream.
protobuf_unittest::TestMap message;
- stringstream stream(data);
+ std::stringstream stream(data);
EXPECT_TRUE(message.ParseFromIstream(&stream));
EXPECT_TRUE(stream.eof());
MapTestUtil::ExpectMapFieldsSet(message);
@@ -2976,6 +3134,27 @@ TEST(MapSerializationTest, Deterministic) {
TestDeterministicSerialization(t, "golden_message_maps");
}
+TEST(MapSerializationTest, DeterministicSubmessage) {
+ protobuf_unittest::TestSubmessageMaps p;
+ protobuf_unittest::TestMaps t;
+ const string filename = "golden_message_maps";
+ string golden;
+ GOOGLE_CHECK_OK(File::GetContents(
+ TestSourceDir() + "/google/protobuf/testdata/" + filename,
+ &golden, true));
+ t.ParseFromString(golden);
+ *(p.mutable_m()) = t;
+ std::vector<string> v;
+ // Use multiple attempts to increase the chance of a failure if something is
+ // buggy. For example, each separate copy of a map might use a different
+ // randomly-chosen hash function.
+ const int kAttempts = 10;
+ for (int i = 0; i < kAttempts; i++) {
+ protobuf_unittest::TestSubmessageMaps q(p);
+ ASSERT_EQ(DeterministicSerialization(q), DeterministicSerialization(p));
+ }
+}
+
// Text Format Test =================================================
TEST(TextFormatMapTest, SerializeAndParse) {
@@ -3054,7 +3233,7 @@ TEST(ArenaTest, ParsingAndSerializingNoHeapAllocation) {
}
// Use text format parsing and serializing to test reflection api.
-TEST(ArenaTest, RelfectionInTextFormat) {
+TEST(ArenaTest, ReflectionInTextFormat) {
Arena arena;
string data;
@@ -3104,6 +3283,44 @@ TEST(ArenaTest, IsInitialized) {
EXPECT_EQ(0, (*message->mutable_map_int32_int32())[0]);
}
+#if LANG_CXX11
+TEST(MoveTest, MoveConstructorWorks) {
+ Map<int32, TestAllTypes> original_map;
+ original_map[42].mutable_optional_nested_message()->set_bb(42);
+ original_map[43].mutable_optional_nested_message()->set_bb(43);
+ const auto* nested_msg42_ptr = &original_map[42].optional_nested_message();
+ const auto* nested_msg43_ptr = &original_map[43].optional_nested_message();
+
+ Map<int32, TestAllTypes> moved_to_map(std::move(original_map));
+ EXPECT_TRUE(original_map.empty());
+ EXPECT_EQ(2, moved_to_map.size());
+ EXPECT_EQ(42, moved_to_map[42].optional_nested_message().bb());
+ EXPECT_EQ(43, moved_to_map[43].optional_nested_message().bb());
+ // This test takes advantage of the fact that pointers are swapped, so there
+ // should be pointer stability.
+ EXPECT_EQ(nested_msg42_ptr, &moved_to_map[42].optional_nested_message());
+ EXPECT_EQ(nested_msg43_ptr, &moved_to_map[43].optional_nested_message());
+}
+
+TEST(MoveTest, MoveAssignmentWorks) {
+ Map<int32, TestAllTypes> original_map;
+ original_map[42].mutable_optional_nested_message()->set_bb(42);
+ original_map[43].mutable_optional_nested_message()->set_bb(43);
+ const auto* nested_msg42_ptr = &original_map[42].optional_nested_message();
+ const auto* nested_msg43_ptr = &original_map[43].optional_nested_message();
+
+ Map<int32, TestAllTypes> moved_to_map = std::move(original_map);
+ EXPECT_TRUE(original_map.empty());
+ EXPECT_EQ(2, moved_to_map.size());
+ EXPECT_EQ(42, moved_to_map[42].optional_nested_message().bb());
+ EXPECT_EQ(43, moved_to_map[43].optional_nested_message().bb());
+ // This test takes advantage of the fact that pointers are swapped, so there
+ // should be pointer stability.
+ EXPECT_EQ(nested_msg42_ptr, &moved_to_map[42].optional_nested_message());
+ EXPECT_EQ(nested_msg43_ptr, &moved_to_map[43].optional_nested_message());
+}
+#endif
+
} // namespace internal
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/map_test_util.cc b/src/google/protobuf/map_test_util.cc
index 3dd6aae5..31ac1736 100644
--- a/src/google/protobuf/map_test_util.cc
+++ b/src/google/protobuf/map_test_util.cc
@@ -744,6 +744,34 @@ void MapReflectionTester::SetMapFieldsViaMapReflection(
sub_foreign_message, foreign_c_, 1);
}
+void MapReflectionTester::GetMapValueViaMapReflection(Message* message,
+ const string& field_name,
+ const MapKey& map_key,
+ MapValueRef* map_val) {
+ const Reflection* reflection = message->GetReflection();
+ EXPECT_FALSE(reflection->InsertOrLookupMapValue(message, F(field_name),
+ map_key, map_val));
+}
+
+Message* MapReflectionTester::GetMapEntryViaReflection(Message* message,
+ const string& field_name,
+ int index) {
+ const Reflection* reflection = message->GetReflection();
+ return reflection->MutableRepeatedMessage(message, F(field_name), index);
+}
+
+MapIterator MapReflectionTester::MapBegin(Message* message,
+ const string& field_name) {
+ const Reflection* reflection = message->GetReflection();
+ return reflection->MapBegin(message, F(field_name));
+}
+
+MapIterator MapReflectionTester::MapEnd(Message* message,
+ const string& field_name) {
+ const Reflection* reflection = message->GetReflection();
+ return reflection->MapEnd(message, F(field_name));
+}
+
void MapReflectionTester::ClearMapFieldsViaReflection(
Message* message) {
const Reflection* reflection = message->GetReflection();
diff --git a/src/google/protobuf/map_test_util.h b/src/google/protobuf/map_test_util.h
index deaf0f4f..dd397619 100644
--- a/src/google/protobuf/map_test_util.h
+++ b/src/google/protobuf/map_test_util.h
@@ -106,6 +106,13 @@ class MapReflectionTester {
void ExpectClearViaReflection(const Message& message);
void ExpectClearViaReflectionIterator(Message* message);
void ExpectMapEntryClearViaReflection(Message* message);
+ void GetMapValueViaMapReflection(Message* message,
+ const string& field_name,
+ const MapKey& map_key, MapValueRef* map_val);
+ Message* GetMapEntryViaReflection(Message* message, const string& field_name,
+ int index);
+ MapIterator MapBegin(Message* message, const string& field_name);
+ MapIterator MapEnd(Message* message, const string& field_name);
private:
const FieldDescriptor* F(const string& name);
diff --git a/src/google/protobuf/map_test_util_impl.h b/src/google/protobuf/map_test_util_impl.h
index b3ba4e06..ad4d1a3d 100644
--- a/src/google/protobuf/map_test_util_impl.h
+++ b/src/google/protobuf/map_test_util_impl.h
@@ -33,14 +33,9 @@
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
+#include <gtest/gtest.h>
-#define EXPECT_TRUE GOOGLE_CHECK
-#define ASSERT_TRUE GOOGLE_CHECK
-#define EXPECT_FALSE(COND) GOOGLE_CHECK(!(COND))
-#define EXPECT_EQ GOOGLE_CHECK_EQ
-#define ASSERT_EQ GOOGLE_CHECK_EQ
-
namespace google {
namespace protobuf_unittest {} // forward declaration
@@ -265,23 +260,23 @@ void MapTestUtilImpl::ExpectClear(const MapMessage& message) {
template <typename EnumType, EnumType enum_value0,
EnumType enum_value1, typename MapMessage>
void MapTestUtilImpl::ExpectMapFieldsSet(const MapMessage& message) {
- EXPECT_EQ(2, message.map_int32_int32().size());
- EXPECT_EQ(2, message.map_int64_int64().size());
- EXPECT_EQ(2, message.map_uint32_uint32().size());
- EXPECT_EQ(2, message.map_uint64_uint64().size());
- EXPECT_EQ(2, message.map_sint32_sint32().size());
- EXPECT_EQ(2, message.map_sint64_sint64().size());
- EXPECT_EQ(2, message.map_fixed32_fixed32().size());
- EXPECT_EQ(2, message.map_fixed64_fixed64().size());
- EXPECT_EQ(2, message.map_sfixed32_sfixed32().size());
- EXPECT_EQ(2, message.map_sfixed64_sfixed64().size());
- EXPECT_EQ(2, message.map_int32_float().size());
- EXPECT_EQ(2, message.map_int32_double().size());
- EXPECT_EQ(2, message.map_bool_bool().size());
- EXPECT_EQ(2, message.map_string_string().size());
- EXPECT_EQ(2, message.map_int32_bytes().size());
- EXPECT_EQ(2, message.map_int32_enum().size());
- EXPECT_EQ(2, message.map_int32_foreign_message().size());
+ ASSERT_EQ(2, message.map_int32_int32().size());
+ ASSERT_EQ(2, message.map_int64_int64().size());
+ ASSERT_EQ(2, message.map_uint32_uint32().size());
+ ASSERT_EQ(2, message.map_uint64_uint64().size());
+ ASSERT_EQ(2, message.map_sint32_sint32().size());
+ ASSERT_EQ(2, message.map_sint64_sint64().size());
+ ASSERT_EQ(2, message.map_fixed32_fixed32().size());
+ ASSERT_EQ(2, message.map_fixed64_fixed64().size());
+ ASSERT_EQ(2, message.map_sfixed32_sfixed32().size());
+ ASSERT_EQ(2, message.map_sfixed64_sfixed64().size());
+ ASSERT_EQ(2, message.map_int32_float().size());
+ ASSERT_EQ(2, message.map_int32_double().size());
+ ASSERT_EQ(2, message.map_bool_bool().size());
+ ASSERT_EQ(2, message.map_string_string().size());
+ ASSERT_EQ(2, message.map_int32_bytes().size());
+ ASSERT_EQ(2, message.map_int32_enum().size());
+ ASSERT_EQ(2, message.map_int32_foreign_message().size());
EXPECT_EQ(0, message.map_int32_int32().at(0));
EXPECT_EQ(0, message.map_int64_int64().at(0));
diff --git a/src/google/protobuf/map_type_handler.h b/src/google/protobuf/map_type_handler.h
index ac987cbc..7f7b1e0e 100644
--- a/src/google/protobuf/map_type_handler.h
+++ b/src/google/protobuf/map_type_handler.h
@@ -32,7 +32,6 @@
#define GOOGLE_PROTOBUF_TYPE_HANDLER_H__
#include <google/protobuf/arena.h>
-#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/wire_format_lite_inl.h>
namespace google {
@@ -73,7 +72,7 @@ class MapValueInitializer<true, Type> {
template <typename Type>
class MapValueInitializer<false, Type> {
public:
- static inline void Initialize(Type& value, int default_enum_value) {}
+ static inline void Initialize(Type& /* value */, int /* default_enum_value */) {}
};
template <typename Type, bool is_arena_constructable>
@@ -186,9 +185,9 @@ class MapTypeHandler<WireFormatLite::TYPE_MESSAGE, Type> {
static inline Type* EnsureMutable(Type** value, Arena* arena);
// SpaceUsedInMapEntry: Return bytes used by value in MapEntry, excluding
// those already calculate in sizeof(MapField).
- static inline int SpaceUsedInMapEntry(const Type* value);
+ static inline size_t SpaceUsedInMapEntryLong(const Type* value);
// Return bytes used by value in Map.
- static inline int SpaceUsedInMap(const Type& value);
+ static inline size_t SpaceUsedInMapLong(const Type& value);
// Assign default value to given instance.
static inline void AssignDefaultValue(Type** value);
// Return default instance if value is not initialized when calling const
@@ -224,9 +223,7 @@ class MapTypeHandler<WireFormatLite::TYPE_MESSAGE, Type> {
static inline void Write(int field, const MapEntryAccessorType& value, \
io::CodedOutputStream* output); \
static inline uint8* InternalWriteToArray( \
- int field, \
- const MapEntryAccessorType& value, \
- bool deterministic, \
+ int field, const MapEntryAccessorType& value, bool deterministic, \
uint8* target); \
static inline uint8* WriteToArray(int field, \
const MapEntryAccessorType& value, \
@@ -242,9 +239,9 @@ class MapTypeHandler<WireFormatLite::TYPE_MESSAGE, Type> {
static inline void ClearMaybeByDefaultEnum(TypeOnMemory* value, \
Arena* arena, \
int default_enum); \
- static inline int SpaceUsedInMapEntry(const TypeOnMemory& value); \
- static inline int SpaceUsedInMap(const TypeOnMemory& value); \
- static inline int SpaceUsedInMap(const string& value); \
+ static inline size_t SpaceUsedInMapEntryLong(const TypeOnMemory& value); \
+ static inline size_t SpaceUsedInMapLong(const TypeOnMemory& value); \
+ static inline size_t SpaceUsedInMapLong(const string& value); \
static inline void AssignDefaultValue(TypeOnMemory* value); \
static inline const MapEntryAccessorType& DefaultIfNotInitialized( \
const TypeOnMemory& value, const TypeOnMemory& default_value); \
@@ -286,7 +283,7 @@ MapTypeHandler<WireFormatLite::TYPE_MESSAGE, Type>::ByteSize(
template <typename Type> \
inline int MapTypeHandler<WireFormatLite::TYPE_##FieldType, Type>::ByteSize( \
const MapEntryAccessorType& value) { \
- return WireFormatLite::DeclaredType##Size(value); \
+ return static_cast<int>(WireFormatLite::DeclaredType##Size(value)); \
}
GOOGLE_PROTOBUF_BYTE_SIZE(STRING, String)
@@ -304,7 +301,7 @@ GOOGLE_PROTOBUF_BYTE_SIZE(ENUM , Enum)
#define FIXED_BYTE_SIZE(FieldType, DeclaredType) \
template <typename Type> \
inline int MapTypeHandler<WireFormatLite::TYPE_##FieldType, Type>::ByteSize( \
- const MapEntryAccessorType& value) { \
+ const MapEntryAccessorType& /* value */) { \
return WireFormatLite::k##DeclaredType##Size; \
}
@@ -322,7 +319,9 @@ template <typename Type>
inline int
MapTypeHandler<WireFormatLite::TYPE_MESSAGE, Type>::GetCachedSize(
const MapEntryAccessorType& value) {
- return WireFormatLite::LengthDelimitedSize(value.GetCachedSize());
+ return static_cast<int>(
+ WireFormatLite::LengthDelimitedSize(
+ static_cast<size_t>(value.GetCachedSize())));
}
#define GET_CACHED_SIZE(FieldType, DeclaredType) \
@@ -330,7 +329,7 @@ MapTypeHandler<WireFormatLite::TYPE_MESSAGE, Type>::GetCachedSize(
inline int \
MapTypeHandler<WireFormatLite::TYPE_##FieldType, Type>::GetCachedSize( \
const MapEntryAccessorType& value) { \
- return WireFormatLite::DeclaredType##Size(value); \
+ return static_cast<int>(WireFormatLite::DeclaredType##Size(value)); \
}
GET_CACHED_SIZE(STRING, String)
@@ -349,7 +348,7 @@ GET_CACHED_SIZE(ENUM , Enum)
template <typename Type> \
inline int \
MapTypeHandler<WireFormatLite::TYPE_##FieldType, Type>::GetCachedSize( \
- const MapEntryAccessorType& value) { \
+ const MapEntryAccessorType& /* value */) { \
return WireFormatLite::k##DeclaredType##Size; \
}
@@ -467,34 +466,33 @@ MapTypeHandler<WireFormatLite::TYPE_MESSAGE,
}
template <typename Type>
-inline int
-MapTypeHandler<WireFormatLite::TYPE_MESSAGE,
- Type>::SpaceUsedInMapEntry(const Type* value) {
- return value->SpaceUsed();
+inline size_t MapTypeHandler<WireFormatLite::TYPE_MESSAGE,
+ Type>::SpaceUsedInMapEntryLong(const Type* value) {
+ return value->SpaceUsedLong();
}
template <typename Type>
-int MapTypeHandler<WireFormatLite::TYPE_MESSAGE, Type>::SpaceUsedInMap(
+size_t MapTypeHandler<WireFormatLite::TYPE_MESSAGE, Type>::SpaceUsedInMapLong(
const Type& value) {
- return value.SpaceUsed();
+ return value.SpaceUsedLong();
}
template <typename Type>
inline void MapTypeHandler<WireFormatLite::TYPE_MESSAGE, Type>::Clear(
- Type** value, Arena* arena) {
+ Type** value, Arena* /* arena */) {
if (*value != NULL) (*value)->Clear();
}
template <typename Type>
inline void
MapTypeHandler<WireFormatLite::TYPE_MESSAGE,
Type>::ClearMaybeByDefaultEnum(Type** value,
- Arena* arena,
- int default_enum_value) {
+ Arena* /* arena */,
+ int /* default_enum_value */) {
if (*value != NULL) (*value)->Clear();
}
template <typename Type>
inline void MapTypeHandler<WireFormatLite::TYPE_MESSAGE, Type>::Merge(
- const Type& from, Type** to, Arena* arena) {
+ const Type& from, Type** to, Arena* /* arena */) {
(*to)->MergeFrom(from);
}
@@ -507,20 +505,20 @@ void MapTypeHandler<WireFormatLite::TYPE_MESSAGE, Type>::DeleteNoArena(
template <typename Type>
inline void MapTypeHandler<WireFormatLite::TYPE_MESSAGE,
Type>::AssignDefaultValue(Type** value) {
- *value = const_cast<Type*>(&Type::default_instance());
+ *value = const_cast<Type*>(Type::internal_default_instance());
}
template <typename Type>
inline void MapTypeHandler<WireFormatLite::TYPE_MESSAGE,
Type>::Initialize(Type** x,
- Arena* arena) {
+ Arena* /* arena */) {
*x = NULL;
}
template <typename Type>
inline void MapTypeHandler<WireFormatLite::TYPE_MESSAGE, Type>::
- InitializeMaybeByDefaultEnum(Type** x, int default_enum_value,
- Arena* arena) {
+ InitializeMaybeByDefaultEnum(Type** x, int /* default_enum_value */,
+ Arena* /* arena */) {
*x = NULL;
}
@@ -559,19 +557,21 @@ inline bool MapTypeHandler<WireFormatLite::TYPE_MESSAGE,
return value.Get(); \
} \
template <typename Type> \
- inline int \
- MapTypeHandler<WireFormatLite::TYPE_##FieldType, Type>::SpaceUsedInMapEntry( \
- const TypeOnMemory& value) { \
+ inline size_t \
+ MapTypeHandler<WireFormatLite::TYPE_##FieldType, \
+ Type>::SpaceUsedInMapEntryLong(const TypeOnMemory& value) { \
return sizeof(value); \
} \
template <typename Type> \
- inline int MapTypeHandler<WireFormatLite::TYPE_##FieldType, \
- Type>::SpaceUsedInMap(const TypeOnMemory& value) { \
+ inline size_t \
+ MapTypeHandler<WireFormatLite::TYPE_##FieldType, Type>::SpaceUsedInMapLong( \
+ const TypeOnMemory& value) { \
return sizeof(value); \
} \
template <typename Type> \
- inline int MapTypeHandler<WireFormatLite::TYPE_##FieldType, \
- Type>::SpaceUsedInMap(const string& value) { \
+ inline size_t \
+ MapTypeHandler<WireFormatLite::TYPE_##FieldType, Type>::SpaceUsedInMapLong( \
+ const string& value) { \
return sizeof(value); \
} \
template <typename Type> \
@@ -583,7 +583,7 @@ inline bool MapTypeHandler<WireFormatLite::TYPE_MESSAGE,
template <typename Type> \
inline void MapTypeHandler<WireFormatLite::TYPE_##FieldType, Type>:: \
ClearMaybeByDefaultEnum(TypeOnMemory* value, Arena* arena, \
- int default_enum) { \
+ int /* default_enum */) { \
Clear(value, arena); \
} \
template <typename Type> \
@@ -598,18 +598,19 @@ inline bool MapTypeHandler<WireFormatLite::TYPE_MESSAGE,
} \
template <typename Type> \
inline void MapTypeHandler<WireFormatLite::TYPE_##FieldType, \
- Type>::AssignDefaultValue(TypeOnMemory* value) {} \
+ Type>::AssignDefaultValue(TypeOnMemory* /* value */) {} \
template <typename Type> \
inline void \
MapTypeHandler<WireFormatLite::TYPE_##FieldType, Type>::Initialize( \
- TypeOnMemory* value, Arena* arena) { \
+ TypeOnMemory* value, Arena* /* arena */) { \
value->UnsafeSetDefault( \
&::google::protobuf::internal::GetEmptyStringAlreadyInited()); \
} \
template <typename Type> \
inline void MapTypeHandler<WireFormatLite::TYPE_##FieldType, Type>:: \
InitializeMaybeByDefaultEnum(TypeOnMemory* value, \
- int default_enum_value, Arena* arena) { \
+ int /* default_enum_value */, \
+ Arena* arena) { \
Initialize(value, arena); \
} \
template <typename Type> \
@@ -626,12 +627,12 @@ inline bool MapTypeHandler<WireFormatLite::TYPE_MESSAGE,
MapTypeHandler<WireFormatLite::TYPE_##FieldType, \
Type>::DefaultIfNotInitialized(const TypeOnMemory& value, \
const TypeOnMemory& \
- default_value) { \
+ /* default_value */) { \
return value.Get(); \
} \
template <typename Type> \
inline bool MapTypeHandler<WireFormatLite::TYPE_##FieldType, \
- Type>::IsInitialized(const TypeOnMemory& value) { \
+ Type>::IsInitialized(const TypeOnMemory& /* value */) { \
return true; \
}
STRING_OR_BYTES_HANDLER_FUNCTIONS(STRING)
@@ -647,59 +648,58 @@ STRING_OR_BYTES_HANDLER_FUNCTIONS(BYTES)
return value; \
} \
template <typename Type> \
- inline int \
- MapTypeHandler<WireFormatLite::TYPE_##FieldType, Type>::SpaceUsedInMapEntry( \
- const TypeOnMemory& value) { \
+ inline size_t \
+ MapTypeHandler<WireFormatLite::TYPE_##FieldType, \
+ Type>::SpaceUsedInMapEntryLong(const TypeOnMemory& /* value */) { \
return 0; \
} \
template <typename Type> \
- inline int MapTypeHandler<WireFormatLite::TYPE_##FieldType, \
- Type>::SpaceUsedInMap(const TypeOnMemory& value) { \
+ inline size_t \
+ MapTypeHandler<WireFormatLite::TYPE_##FieldType, Type>::SpaceUsedInMapLong( \
+ const TypeOnMemory& /* value */) { \
return sizeof(Type); \
} \
template <typename Type> \
inline void MapTypeHandler<WireFormatLite::TYPE_##FieldType, Type>::Clear( \
- TypeOnMemory* value, Arena* arena) { \
+ TypeOnMemory* value, Arena* /* arena */) { \
*value = 0; \
} \
template <typename Type> \
- inline void \
- MapTypeHandler<WireFormatLite::TYPE_##FieldType, \
- Type>::ClearMaybeByDefaultEnum(TypeOnMemory* value, \
- Arena* arena, \
- int default_enum_value) { \
+ inline void MapTypeHandler<WireFormatLite::TYPE_##FieldType, Type>:: \
+ ClearMaybeByDefaultEnum(TypeOnMemory* value, Arena* /* arena */, \
+ int default_enum_value) { \
*value = static_cast<TypeOnMemory>(default_enum_value); \
} \
template <typename Type> \
inline void MapTypeHandler<WireFormatLite::TYPE_##FieldType, Type>::Merge( \
- const MapEntryAccessorType& from, TypeOnMemory* to, Arena* arena) { \
+ const MapEntryAccessorType& from, TypeOnMemory* to, \
+ Arena* /* arena */) { \
*to = from; \
} \
template <typename Type> \
inline void MapTypeHandler<WireFormatLite::TYPE_##FieldType, \
- Type>::DeleteNoArena(TypeOnMemory& x) {} \
+ Type>::DeleteNoArena(TypeOnMemory& /* x */) {} \
template <typename Type> \
inline void MapTypeHandler<WireFormatLite::TYPE_##FieldType, \
- Type>::AssignDefaultValue(TypeOnMemory* value) {} \
+ Type>::AssignDefaultValue(TypeOnMemory* /* value */) {} \
template <typename Type> \
inline void \
MapTypeHandler<WireFormatLite::TYPE_##FieldType, Type>::Initialize( \
- TypeOnMemory* value, Arena* arena) { \
+ TypeOnMemory* value, Arena* /* arena */) { \
*value = 0; \
} \
template <typename Type> \
- inline void \
- MapTypeHandler<WireFormatLite::TYPE_##FieldType, \
- Type>::InitializeMaybeByDefaultEnum(TypeOnMemory* value, \
- int default_enum_value, \
- Arena* arena) { \
+ inline void MapTypeHandler<WireFormatLite::TYPE_##FieldType, Type>:: \
+ InitializeMaybeByDefaultEnum(TypeOnMemory* value, \
+ int default_enum_value, \
+ Arena* /* arena */) { \
*value = static_cast<TypeOnMemory>(default_enum_value); \
} \
template <typename Type> \
inline typename MapTypeHandler<WireFormatLite::TYPE_##FieldType, \
Type>::MapEntryAccessorType* \
MapTypeHandler<WireFormatLite::TYPE_##FieldType, Type>::EnsureMutable( \
- TypeOnMemory* value, Arena* arena) { \
+ TypeOnMemory* value, Arena* /* arena */) { \
return value; \
} \
template <typename Type> \
@@ -708,12 +708,12 @@ STRING_OR_BYTES_HANDLER_FUNCTIONS(BYTES)
MapTypeHandler<WireFormatLite::TYPE_##FieldType, \
Type>::DefaultIfNotInitialized(const TypeOnMemory& value, \
const TypeOnMemory& \
- default_value) { \
+ /* default_value */) { \
return value; \
} \
template <typename Type> \
inline bool MapTypeHandler<WireFormatLite::TYPE_##FieldType, \
- Type>::IsInitialized(const TypeOnMemory& value) { \
+ Type>::IsInitialized(const TypeOnMemory& /* value */) { \
return true; \
}
PRIMITIVE_HANDLER_FUNCTIONS(INT64)
diff --git a/src/google/protobuf/map_unittest.proto b/src/google/protobuf/map_unittest.proto
index c6154f04..836dc10b 100644
--- a/src/google/protobuf/map_unittest.proto
+++ b/src/google/protobuf/map_unittest.proto
@@ -60,6 +60,7 @@ message TestMap {
map<int32 , MapEnum > map_int32_enum = 16;
map<int32 , ForeignMessage> map_int32_foreign_message = 17;
map<string , ForeignMessage> map_string_foreign_message = 18;
+ map<int32 , TestAllTypes> map_int32_all_types = 19;
}
message TestMapSubmessage {
diff --git a/src/google/protobuf/message.cc b/src/google/protobuf/message.cc
index a5a7feb6..a0d3feba 100644
--- a/src/google/protobuf/message.cc
+++ b/src/google/protobuf/message.cc
@@ -130,12 +130,12 @@ bool Message::ParsePartialFromFileDescriptor(int file_descriptor) {
return ParsePartialFromZeroCopyStream(&input) && input.GetErrno() == 0;
}
-bool Message::ParseFromIstream(istream* input) {
+bool Message::ParseFromIstream(std::istream* input) {
io::IstreamInputStream zero_copy_input(input);
return ParseFromZeroCopyStream(&zero_copy_input) && input->eof();
}
-bool Message::ParsePartialFromIstream(istream* input) {
+bool Message::ParsePartialFromIstream(std::istream* input) {
io::IstreamInputStream zero_copy_input(input);
return ParsePartialFromZeroCopyStream(&zero_copy_input) && input->eof();
}
@@ -143,7 +143,13 @@ bool Message::ParsePartialFromIstream(istream* input) {
void Message::SerializeWithCachedSizes(
io::CodedOutputStream* output) const {
- WireFormat::SerializeWithCachedSizes(*this, GetCachedSize(), output);
+ const internal::SerializationTable* table =
+ static_cast<const internal::SerializationTable*>(InternalGetTable());
+ if (table == 0) {
+ WireFormat::SerializeWithCachedSizes(*this, GetCachedSize(), output);
+ } else {
+ internal::TableSerialize(*this, table, output);
+ }
}
size_t Message::ByteSizeLong() const {
@@ -158,8 +164,8 @@ void Message::SetCachedSize(int /* size */) const {
"Must implement one or the other.";
}
-int Message::SpaceUsed() const {
- return GetReflection()->SpaceUsed(*this);
+size_t Message::SpaceUsedLong() const {
+ return GetReflection()->SpaceUsedLong(*this);
}
bool Message::SerializeToFileDescriptor(int file_descriptor) const {
@@ -172,7 +178,7 @@ bool Message::SerializePartialToFileDescriptor(int file_descriptor) const {
return SerializePartialToZeroCopyStream(&output);
}
-bool Message::SerializeToOstream(ostream* output) const {
+bool Message::SerializeToOstream(std::ostream* output) const {
{
io::OstreamOutputStream zero_copy_output(output);
if (!SerializeToZeroCopyStream(&zero_copy_output)) return false;
@@ -180,7 +186,7 @@ bool Message::SerializeToOstream(ostream* output) const {
return output->good();
}
-bool Message::SerializePartialToOstream(ostream* output) const {
+bool Message::SerializePartialToOstream(std::ostream* output) const {
io::OstreamOutputStream zero_copy_output(output);
return SerializePartialToZeroCopyStream(&zero_copy_output);
}
@@ -191,6 +197,10 @@ bool Message::SerializePartialToOstream(ostream* output) const {
Reflection::~Reflection() {}
+void Reflection::AddAllocatedMessage(Message* /* message */,
+ const FieldDescriptor* /*field */,
+ Message* /* new_entry */) const {}
+
#define HANDLE_TYPE(TYPE, CPPTYPE, CTYPE) \
template<> \
const RepeatedField<TYPE>& Reflection::GetRepeatedField<TYPE>( \
@@ -451,27 +461,27 @@ struct ShutdownRepeatedFieldRegister {
namespace internal {
template<>
-#if defined(_MSC_VER) && (_MSC_VER >= 1900)
-// Note: force noinline to workaround MSVC 2015 compiler bug, issue #240
-GOOGLE_ATTRIBUTE_NOINLINE
+#if defined(_MSC_VER) && (_MSC_VER >= 1800)
+// Note: force noinline to workaround MSVC compiler bug with /Zc:inline, issue #240
+GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
#endif
Message* GenericTypeHandler<Message>::NewFromPrototype(
const Message* prototype, google::protobuf::Arena* arena) {
return prototype->New(arena);
}
template<>
-#if defined(_MSC_VER) && (_MSC_VER >= 1900)
-// Note: force noinline to workaround MSVC 2015 compiler bug, issue #240
-GOOGLE_ATTRIBUTE_NOINLINE
+#if defined(_MSC_VER) && (_MSC_VER >= 1800)
+// Note: force noinline to workaround MSVC compiler bug with /Zc:inline, issue #240
+GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
#endif
google::protobuf::Arena* GenericTypeHandler<Message>::GetArena(
Message* value) {
return value->GetArena();
}
template<>
-#if defined(_MSC_VER) && (_MSC_VER >= 1900)
-// Note: force noinline to workaround MSVC 2015 compiler bug, issue #240
-GOOGLE_ATTRIBUTE_NOINLINE
+#if defined(_MSC_VER) && (_MSC_VER >= 1800)
+// Note: force noinline to workaround MSVC compiler bug with /Zc:inline, issue #240
+GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
#endif
void* GenericTypeHandler<Message>::GetMaybeArenaPointer(
Message* value) {
diff --git a/src/google/protobuf/message.h b/src/google/protobuf/message.h
index 872df7a9..ab018596 100644
--- a/src/google/protobuf/message.h
+++ b/src/google/protobuf/message.h
@@ -154,6 +154,13 @@ class MapReflectionFriend; // scalar_map_container.h
}
+namespace internal {
+class ReflectionOps; // reflection_ops.h
+class MapKeySorter; // wire_format.cc
+class WireFormat; // wire_format.h
+class MapFieldReflectionTest; // map_test.cc
+}
+
template<typename T>
class RepeatedField; // repeated_field.h
@@ -245,7 +252,10 @@ class LIBPROTOBUF_EXPORT Message : public MessageLite {
// using reflection (rather than the generated code implementation for
// ByteSize()). Like ByteSize(), its CPU time is linear in the number of
// fields defined for the proto.
- virtual int SpaceUsed() const;
+ virtual size_t SpaceUsedLong() const;
+
+ PROTOBUF_RUNTIME_DEPRECATED("Please use SpaceUsedLong() instead")
+ int SpaceUsed() const { return internal::ToIntSize(SpaceUsedLong()); }
// Debugging & Testing----------------------------------------------
@@ -317,18 +327,19 @@ class LIBPROTOBUF_EXPORT Message : public MessageLite {
// Typedef for backwards-compatibility.
typedef google::protobuf::Reflection Reflection;
- // Get a Descriptor for this message's type. This describes what
- // fields the message contains, the types of those fields, etc.
+ // Get a non-owning pointer to a Descriptor for this message's type. This
+ // describes what fields the message contains, the types of those fields, etc.
+ // This object remains property of the Message.
const Descriptor* GetDescriptor() const { return GetMetadata().descriptor; }
- // Get the Reflection interface for this Message, which can be used to
- // read and modify the fields of the Message dynamically (in other words,
- // without knowing the message type at compile time). This object remains
- // property of the Message.
+ // Get a non-owning pointer to the Reflection interface for this Message,
+ // which can be used to read and modify the fields of the Message dynamically
+ // (in other words, without knowing the message type at compile time). This
+ // object remains property of the Message.
//
// This method remains virtual in case a subclass does not implement
// reflection and wants to override the default behavior.
- virtual const Reflection* GetReflection() const {
+ virtual const Reflection* GetReflection() const PROTOBUF_FINAL {
return GetMetadata().reflection;
}
@@ -417,7 +428,12 @@ class LIBPROTOBUF_EXPORT Reflection {
virtual UnknownFieldSet* MutableUnknownFields(Message* message) const = 0;
// Estimate the amount of memory used by the message object.
- virtual int SpaceUsed(const Message& message) const = 0;
+ virtual size_t SpaceUsedLong(const Message& message) const = 0;
+
+ PROTOBUF_RUNTIME_DEPRECATED("Please use SpaceUsedLong() instead")
+ int SpaceUsed(const Message& message) const {
+ return internal::ToIntSize(SpaceUsedLong(message));
+ }
// Check if the given non-repeated field is set.
virtual bool HasField(const Message& message,
@@ -481,11 +497,14 @@ class LIBPROTOBUF_EXPORT Reflection {
int index1,
int index2) const = 0;
- // List all fields of the message which are currently set. This includes
- // extensions. Singular fields will only be listed if HasField(field) would
- // return true and repeated fields will only be listed if FieldSize(field)
- // would return non-zero. Fields (both normal fields and extension fields)
- // will be listed ordered by field number.
+ // List all fields of the message which are currently set, except for unknown
+ // fields, but including extension known to the parser (i.e. compiled in).
+ // Singular fields will only be listed if HasField(field) would return true
+ // and repeated fields will only be listed if FieldSize(field) would return
+ // non-zero. Fields (both normal fields and extension fields) will be listed
+ // ordered by field number.
+ // Use Reflection::GetUnknownFields() or message.unknown_fields() to also get
+ // access to fields/extensions unknown to the parser.
virtual void ListFields(
const Message& message,
std::vector<const FieldDescriptor*>* output) const = 0;
@@ -739,9 +758,9 @@ class LIBPROTOBUF_EXPORT Reflection {
// specifyed by 'field' passing ownership to the message.
// TODO(tmarek): Make virtual after all subclasses have been
// updated.
- virtual void AddAllocatedMessage(Message* /* message */,
- const FieldDescriptor* /*field */,
- Message* /* new_entry */) const {}
+ virtual void AddAllocatedMessage(Message* message,
+ const FieldDescriptor* field,
+ Message* new_entry) const;
// Get a RepeatedFieldRef object that can be used to read the underlying
@@ -853,7 +872,7 @@ class LIBPROTOBUF_EXPORT Reflection {
// reflection->SetEnumValue(message, field, new_value);
// } else {
// if (field_descriptor->enum_type()->
- // FindValueByNumver(new_value) != NULL) {
+ // FindValueByNumber(new_value) != NULL) {
// reflection->SetEnumValue(message, field, new_value);
// } else if (emit_unknown_enum_values) {
// reflection->MutableUnknownFields(message)->AddVarint(
@@ -907,7 +926,7 @@ class LIBPROTOBUF_EXPORT Reflection {
// Returns a raw pointer to the repeated field
//
- // "cpp_type" and "message_type" are decuded from the type parameter T passed
+ // "cpp_type" and "message_type" are deduced from the type parameter T passed
// to Get(Mutable)RepeatedFieldRef. If T is a generated message type,
// "message_type" should be set to its descriptor. Otherwise "message_type"
// should be set to NULL. Implementations of this method should check whether
@@ -930,6 +949,10 @@ class LIBPROTOBUF_EXPORT Reflection {
template<typename T, typename Enable>
friend class MutableRepeatedFieldRef;
friend class ::google::protobuf::python::MapReflectionFriend;
+ friend class internal::MapFieldReflectionTest;
+ friend class internal::MapKeySorter;
+ friend class internal::WireFormat;
+ friend class internal::ReflectionOps;
// Special version for specialized implementations of string. We can't call
// MutableRawRepeatedField directly here because we don't have access to
@@ -944,7 +967,7 @@ class LIBPROTOBUF_EXPORT Reflection {
// TODO(jieluo) - make the map APIs pure virtual after updating
// all the subclasses.
// Returns true if key is in map. Returns false if key is not in map field.
- virtual bool ContainsMapKey(const Message& /* message*/,
+ virtual bool ContainsMapKey(const Message& /* message */,
const FieldDescriptor* /* field */,
const MapKey& /* key */) const {
return false;
@@ -962,7 +985,7 @@ class LIBPROTOBUF_EXPORT Reflection {
// Delete and returns true if key is in the map field. Returns false
// otherwise.
- virtual bool DeleteMapValue(Message* /* mesage */,
+ virtual bool DeleteMapValue(Message* /* message */,
const FieldDescriptor* /* field */,
const MapKey& /* key */) const {
return false;
diff --git a/src/google/protobuf/message_lite.cc b/src/google/protobuf/message_lite.cc
index a42e9ec3..123b142d 100644
--- a/src/google/protobuf/message_lite.cc
+++ b/src/google/protobuf/message_lite.cc
@@ -103,15 +103,15 @@ string InitializationErrorMessage(const char* action,
// call MergePartialFromCodedStream(). However, when parsing very small
// messages, every function call introduces significant overhead. To avoid
// this without reproducing code, we use these forced-inline helpers.
-GOOGLE_ATTRIBUTE_ALWAYS_INLINE bool InlineMergeFromCodedStream(
+GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE bool InlineMergeFromCodedStream(
io::CodedInputStream* input, MessageLite* message);
-GOOGLE_ATTRIBUTE_ALWAYS_INLINE bool InlineParseFromCodedStream(
+GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE bool InlineParseFromCodedStream(
io::CodedInputStream* input, MessageLite* message);
-GOOGLE_ATTRIBUTE_ALWAYS_INLINE bool InlineParsePartialFromCodedStream(
+GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE bool InlineParsePartialFromCodedStream(
io::CodedInputStream* input, MessageLite* message);
-GOOGLE_ATTRIBUTE_ALWAYS_INLINE bool InlineParseFromArray(
+GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE bool InlineParseFromArray(
const void* data, int size, MessageLite* message);
-GOOGLE_ATTRIBUTE_ALWAYS_INLINE bool InlineParsePartialFromArray(
+GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE bool InlineParsePartialFromArray(
const void* data, int size, MessageLite* message);
inline bool InlineMergeFromCodedStream(io::CodedInputStream* input,
@@ -222,16 +222,9 @@ bool MessageLite::ParsePartialFromArray(const void* data, int size) {
// ===================================================================
-uint8* MessageLite::InternalSerializeWithCachedSizesToArray(
- bool deterministic, uint8* target) const {
- // We only optimize this when using optimize_for = SPEED. In other cases
- // we just use the CodedOutputStream path.
- int size = GetCachedSize();
- io::ArrayOutputStream out(target, size);
- io::CodedOutputStream coded_out(&out);
- SerializeWithCachedSizes(&coded_out);
- GOOGLE_CHECK(!coded_out.HadError());
- return target + size;
+uint8* MessageLite::SerializeWithCachedSizesToArray(uint8* target) const {
+ return InternalSerializeWithCachedSizesToArray(
+ io::CodedOutputStream::IsDefaultSerializationDeterministic(), target);
}
bool MessageLite::SerializeToCodedStream(io::CodedOutputStream* output) const {
@@ -351,6 +344,39 @@ string MessageLite::SerializePartialAsString() const {
return output;
}
+void MessageLite::SerializeWithCachedSizes(
+ io::CodedOutputStream* output) const {
+ GOOGLE_DCHECK(InternalGetTable());
+ internal::TableSerialize(
+ *this,
+ static_cast<const internal::SerializationTable*>(InternalGetTable()),
+ output);
+}
+
+// The table driven code optimizes the case that the CodedOutputStream buffer
+// is large enough to serialize into it directly.
+// If the proto is optimized for speed, this method will be overridden by
+// generated code for maximum speed. If the proto is optimized for size or
+// is lite, then we need to specialize this to avoid infinite recursion.
+uint8* MessageLite::InternalSerializeWithCachedSizesToArray(
+ bool deterministic, uint8* target) const {
+ const internal::SerializationTable* table =
+ static_cast<const internal::SerializationTable*>(InternalGetTable());
+ if (table == NULL) {
+ // We only optimize this when using optimize_for = SPEED. In other cases
+ // we just use the CodedOutputStream path.
+ int size = GetCachedSize();
+ io::ArrayOutputStream out(target, size);
+ io::CodedOutputStream coded_out(&out);
+ coded_out.SetSerializationDeterministic(deterministic);
+ SerializeWithCachedSizes(&coded_out);
+ GOOGLE_CHECK(!coded_out.HadError());
+ return target + size;
+ } else {
+ return internal::TableSerializeToArray(*this, table, deterministic, target);
+ }
+}
+
namespace internal {
template<>
MessageLite* GenericTypeHandler<MessageLite>::NewFromPrototype(
@@ -367,6 +393,14 @@ void GenericTypeHandler<string>::Merge(const string& from,
string* to) {
*to = from;
}
+
+bool proto3_preserve_unknown_ = true;
+
+void SetProto3PreserveUnknownsDefault(bool preserve) {
+ proto3_preserve_unknown_ = preserve;
+}
+
+
} // namespace internal
} // namespace protobuf
diff --git a/src/google/protobuf/message_lite.h b/src/google/protobuf/message_lite.h
index 5e5ed306..5cd6babc 100644
--- a/src/google/protobuf/message_lite.h
+++ b/src/google/protobuf/message_lite.h
@@ -42,21 +42,112 @@
#include <climits>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/logging.h>
-
+#include <google/protobuf/stubs/once.h>
+#include <google/protobuf/stubs/port.h>
namespace google {
namespace protobuf {
- class Arena;
+class Arena;
namespace io {
- class CodedInputStream;
- class CodedOutputStream;
- class ZeroCopyInputStream;
- class ZeroCopyOutputStream;
+class CodedInputStream;
+class CodedOutputStream;
+class ZeroCopyInputStream;
+class ZeroCopyOutputStream;
}
namespace internal {
- class WireFormatLite;
+
+class WireFormatLite;
+
+#ifndef SWIG
+// We compute sizes as size_t but cache them as int. This function converts a
+// computed size to a cached size. Since we don't proceed with serialization
+// if the total size was > INT_MAX, it is not important what this function
+// returns for inputs > INT_MAX. However this case should not error or
+// GOOGLE_CHECK-fail, because the full size_t resolution is still returned from
+// ByteSizeLong() and checked against INT_MAX; we can catch the overflow
+// there.
+inline int ToCachedSize(size_t size) { return static_cast<int>(size); }
+
+// We mainly calculate sizes in terms of size_t, but some functions that
+// compute sizes return "int". These int sizes are expected to always be
+// positive. This function is more efficient than casting an int to size_t
+// directly on 64-bit platforms because it avoids making the compiler emit a
+// sign extending instruction, which we don't want and don't want to pay for.
+inline size_t FromIntSize(int size) {
+ // Convert to unsigned before widening so sign extension is not necessary.
+ return static_cast<unsigned int>(size);
+}
+
+// For cases where a legacy function returns an integer size. We GOOGLE_DCHECK()
+// that the conversion will fit within an integer; if this is false then we
+// are losing information.
+inline int ToIntSize(size_t size) {
+ GOOGLE_DCHECK_LE(size, static_cast<size_t>(INT_MAX));
+ return static_cast<int>(size);
}
+// This type wraps a variable whose constructor and destructor are explicitly
+// called. It is particularly useful for a global variable, without its
+// constructor and destructor run on start and end of the program lifetime.
+// This circumvents the initial construction order fiasco, while keeping
+// the address of the empty string a compile time constant.
+//
+// Pay special attention to the initialization state of the object.
+// 1. The object is "uninitialized" to begin with.
+// 2. Call DefaultConstruct() only if the object is uninitialized.
+// After the call, the object becomes "initialized".
+// 3. Call get() and get_mutable() only if the object is initialized.
+// 4. Call Destruct() only if the object is initialized.
+// After the call, the object becomes uninitialized.
+template <typename T>
+class ExplicitlyConstructed {
+ public:
+ void DefaultConstruct() {
+ new (&union_) T();
+ }
+
+ void Destruct() {
+ get_mutable()->~T();
+ }
+
+#if LANG_CXX11
+ constexpr
+#endif
+ const T&
+ get() const {
+ return reinterpret_cast<const T&>(union_);
+ }
+ T* get_mutable() { return reinterpret_cast<T*>(&union_); }
+
+ private:
+ // Prefer c++14 aligned_storage, but for compatibility this will do.
+ union AlignedUnion {
+ char space[sizeof(T)];
+ int64 align_to_int64;
+ void* align_to_ptr;
+ } union_;
+};
+
+// Default empty string object. Don't use this directly. Instead, call
+// GetEmptyString() to get the reference.
+extern ExplicitlyConstructed< ::std::string> fixed_address_empty_string;
+LIBPROTOBUF_EXPORT extern ProtobufOnceType empty_string_once_init_;
+LIBPROTOBUF_EXPORT void InitEmptyString();
+
+
+LIBPROTOBUF_EXPORT inline const ::std::string& GetEmptyStringAlreadyInited() {
+ return fixed_address_empty_string.get();
+}
+
+LIBPROTOBUF_EXPORT inline const ::std::string& GetEmptyString() {
+ ::google::protobuf::GoogleOnceInit(&empty_string_once_init_, &InitEmptyString);
+ return GetEmptyStringAlreadyInited();
+}
+
+LIBPROTOBUF_EXPORT size_t StringSpaceUsedExcludingSelfLong(const string& str);
+#endif // SWIG
+} // namespace internal
+
// Interface to light weight protocol messages.
//
// This interface is implemented by all protocol message objects. Non-lite
@@ -101,18 +192,19 @@ class LIBPROTOBUF_EXPORT MessageLite {
// Get the arena, if any, associated with this message. Virtual method
// required for generic operations but most arena-related operations should
// use the GetArenaNoVirtual() generated-code method. Default implementation
- // to reduce code size by avoiding the need for per-type implementations when
- // types do not implement arena support.
+ // to reduce code size by avoiding the need for per-type implementations
+ // when types do not implement arena support.
virtual ::google::protobuf::Arena* GetArena() const { return NULL; }
- // Get a pointer that may be equal to this message's arena, or may not be. If
- // the value returned by this method is equal to some arena pointer, then this
- // message is on that arena; however, if this message is on some arena, this
- // method may or may not return that arena's pointer. As a tradeoff, this
- // method may be more efficient than GetArena(). The intent is to allow
- // underlying representations that use e.g. tagged pointers to sometimes store
- // the arena pointer directly, and sometimes in a more indirect way, and allow
- // a fastpath comparison against the arena pointer when it's easy to obtain.
+ // Get a pointer that may be equal to this message's arena, or may not be.
+ // If the value returned by this method is equal to some arena pointer, then
+ // this message is on that arena; however, if this message is on some arena,
+ // this method may or may not return that arena's pointer. As a tradeoff,
+ // this method may be more efficient than GetArena(). The intent is to allow
+ // underlying representations that use e.g. tagged pointers to sometimes
+ // store the arena pointer directly, and sometimes in a more indirect way,
+ // and allow a fastpath comparison against the arena pointer when it's easy
+ // to obtain.
virtual void* GetMaybeArenaPointer() const { return GetArena(); }
// Clear all fields of the message and set them to their default values.
@@ -130,19 +222,20 @@ class LIBPROTOBUF_EXPORT MessageLite {
// for full messages. See message.h.
virtual string InitializationErrorString() const;
- // If |other| is the exact same class as this, calls MergeFrom(). Otherwise,
+ // If |other| is the exact same class as this, calls MergeFrom(). Otherwise,
// results are undefined (probably crash).
virtual void CheckTypeAndMergeFrom(const MessageLite& other) = 0;
// Parsing ---------------------------------------------------------
// Methods for parsing in protocol buffer format. Most of these are
- // just simple wrappers around MergeFromCodedStream(). Clear() will be called
- // before merging the input.
-
- // Fill the message with a protocol buffer parsed from the given input stream.
- // Returns false on a read error or if the input is in the wrong format. A
- // successful return does not indicate the entire input is consumed, ensure
- // you call ConsumedEntireMessage() to check that if applicable.
+ // just simple wrappers around MergeFromCodedStream(). Clear() will be
+ // called before merging the input.
+
+ // Fill the message with a protocol buffer parsed from the given input
+ // stream. Returns false on a read error or if the input is in the wrong
+ // format. A successful return does not indicate the entire input is
+ // consumed, ensure you call ConsumedEntireMessage() to check that if
+ // applicable.
bool ParseFromCodedStream(io::CodedInputStream* input);
// Like ParseFromCodedStream(), but accepts messages that are missing
// required fields.
@@ -248,23 +341,28 @@ class LIBPROTOBUF_EXPORT MessageLite {
virtual size_t ByteSizeLong() const = 0;
// Legacy ByteSize() API.
+ PROTOBUF_RUNTIME_DEPRECATED("Please use ByteSizeLong() instead")
int ByteSize() const {
- size_t result = ByteSizeLong();
- GOOGLE_DCHECK_LE(result, static_cast<size_t>(INT_MAX));
- return static_cast<int>(result);
+ return internal::ToIntSize(ByteSizeLong());
}
// Serializes the message without recomputing the size. The message must not
// have changed since the last call to ByteSize(), and the value returned by
// ByteSize must be non-negative. Otherwise the results are undefined.
virtual void SerializeWithCachedSizes(
- io::CodedOutputStream* output) const = 0;
+ io::CodedOutputStream* output) const;
- // A version of SerializeWithCachedSizesToArray, below, that does
- // not guarantee deterministic serialization.
- virtual uint8* SerializeWithCachedSizesToArray(uint8* target) const {
- return InternalSerializeWithCachedSizesToArray(false, target);
- }
+ // Functions below here are not part of the public interface. It isn't
+ // enforced, but they should be treated as private, and will be private
+ // at some future time. Unfortunately the implementation of the "friend"
+ // keyword in GCC is broken at the moment, but we expect it will be fixed.
+
+ // Like SerializeWithCachedSizes, but writes directly to *target, returning
+ // a pointer to the byte immediately after the last byte written. "target"
+ // must point at a byte array of at least ByteSize() bytes. Whether to use
+ // deterministic serialization, e.g., maps in sorted order, is determined by
+ // CodedOutputStream::IsDefaultSerializationDeterministic().
+ virtual uint8* SerializeWithCachedSizesToArray(uint8* target) const;
// Returns the result of the last call to ByteSize(). An embedded message's
// size is needed both to serialize it (because embedded messages are
@@ -279,25 +377,35 @@ class LIBPROTOBUF_EXPORT MessageLite {
// method.)
virtual int GetCachedSize() const = 0;
- // Functions below here are not part of the public interface. It isn't
- // enforced, but they should be treated as private, and will be private
- // at some future time. Unfortunately the implementation of the "friend"
- // keyword in GCC is broken at the moment, but we expect it will be fixed.
-
- // Like SerializeWithCachedSizes, but writes directly to *target, returning
- // a pointer to the byte immediately after the last byte written. "target"
- // must point at a byte array of at least ByteSize() bytes. If deterministic
- // is true then we use deterministic serialization, e.g., map keys are sorted.
- // FOR INTERNAL USE ONLY!
virtual uint8* InternalSerializeWithCachedSizesToArray(bool deterministic,
uint8* target) const;
private:
+ // TODO(gerbens) make this a pure abstract function
+ virtual const void* InternalGetTable() const { return NULL; }
+
friend class internal::WireFormatLite;
+ friend class Message;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageLite);
};
+namespace internal {
+
+extern bool LIBPROTOBUF_EXPORT proto3_preserve_unknown_;
+
+// DO NOT USE: For migration only. Will be removed when Proto3 defaults to
+// preserve unknowns.
+inline bool GetProto3PreserveUnknownsDefault() {
+ return proto3_preserve_unknown_;
+}
+
+// DO NOT USE: For migration only. Will be removed when Proto3 defaults to
+// preserve unknowns.
+void LIBPROTOBUF_EXPORT SetProto3PreserveUnknownsDefault(bool preserve);
+} // namespace internal
+
+
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/message_unittest.cc b/src/google/protobuf/message_unittest.cc
index de39fff8..d328f9dd 100644
--- a/src/google/protobuf/message_unittest.cc
+++ b/src/google/protobuf/message_unittest.cc
@@ -37,9 +37,7 @@
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
-#ifdef _MSC_VER
-#include <io.h>
-#else
+#ifndef _MSC_VER
#include <unistd.h>
#endif
#include <sstream>
@@ -51,6 +49,7 @@
#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/descriptor.pb.h>
+#include <google/protobuf/arena.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
@@ -59,10 +58,18 @@
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
+#include <google/protobuf/stubs/io_win32.h>
namespace google {
namespace protobuf {
+#if defined(_MSC_VER)
+// DO NOT include <io.h>, instead create functions in io_win32.{h,cc} and import
+// them like we do below.
+using google::protobuf::internal::win32::close;
+using google::protobuf::internal::win32::open;
+#endif
+
#ifndef O_BINARY
#ifdef _O_BINARY
#define O_BINARY _O_BINARY
@@ -77,7 +84,7 @@ TEST(MessageTest, SerializeHelpers) {
protobuf_unittest::TestAllTypes message;
TestUtil::SetAllFields(&message);
- stringstream stream;
+ std::stringstream stream;
string str1("foo");
string str2("bar");
@@ -101,7 +108,7 @@ TEST(MessageTest, SerializeHelpers) {
}
TEST(MessageTest, SerializeToBrokenOstream) {
- ofstream out;
+ std::ofstream out;
protobuf_unittest::TestAllTypes message;
message.set_optional_int32(123);
@@ -112,8 +119,9 @@ TEST(MessageTest, ParseFromFileDescriptor) {
string filename = TestSourceDir() +
"/google/protobuf/testdata/golden_message";
int file = open(filename.c_str(), O_RDONLY | O_BINARY);
+ ASSERT_GE(file, 0);
- unittest::TestAllTypes message;
+ protobuf_unittest::TestAllTypes message;
EXPECT_TRUE(message.ParseFromFileDescriptor(file));
TestUtil::ExpectAllFieldsSet(message);
@@ -125,8 +133,9 @@ TEST(MessageTest, ParsePackedFromFileDescriptor) {
TestSourceDir() +
"/google/protobuf/testdata/golden_packed_fields_message";
int file = open(filename.c_str(), O_RDONLY | O_BINARY);
+ ASSERT_GE(file, 0);
- unittest::TestPackedTypes message;
+ protobuf_unittest::TestPackedTypes message;
EXPECT_TRUE(message.ParseFromFileDescriptor(file));
TestUtil::ExpectPackedFieldsSet(message);
@@ -155,7 +164,7 @@ TEST(MessageTest, ParseHelpers) {
{
// Test ParseFromIstream.
protobuf_unittest::TestAllTypes message;
- stringstream stream(data);
+ std::stringstream stream(data);
EXPECT_TRUE(message.ParseFromIstream(&stream));
EXPECT_TRUE(stream.eof());
TestUtil::ExpectAllFieldsSet(message);
@@ -248,42 +257,6 @@ TEST(MessageTest, CheckInitialized) {
"fields: a, b, c");
}
-TEST(MessageTest, CheckOverflow) {
- unittest::TestAllTypes message;
- // Create a message with size just over 2GB. This triggers integer overflow
- // when computing message size.
- const string data(1024, 'x');
- Cord one_megabyte;
- for (int i = 0; i < 1024; i++) {
- one_megabyte.Append(data);
- }
-
- for (int i = 0; i < 2 * 1024 + 1; ++i) {
- message.add_repeated_cord()->CopyFrom(one_megabyte);
- }
-
- Cord serialized;
- EXPECT_FALSE(message.AppendToCord(&serialized));
-}
-
-TEST(MessageTest, CheckBigOverflow) {
- unittest::TestAllTypes message;
- // Create a message with size just over 4GB. We should be able to detect this
- // too, even though it will make a plain "int" wrap back to a positive number.
- const string data(1024, 'x');
- Cord one_megabyte;
- for (int i = 0; i < 1024; i++) {
- one_megabyte.Append(data);
- }
-
- for (int i = 0; i < 4 * 1024 + 1; ++i) {
- message.add_repeated_cord()->CopyFrom(one_megabyte);
- }
-
- Cord serialized;
- EXPECT_FALSE(message.AppendToCord(&serialized));
-}
-
#endif // PROTOBUF_HAS_DEATH_TEST
namespace {
@@ -422,8 +395,21 @@ TEST(MessageTest, MessageIsStillValidAfterParseFails) {
EXPECT_FALSE(message.ParseFromString(invalid_data));
message.Clear();
EXPECT_EQ(0, message.optional_uint64());
+
+ // invalid data for field "optional_string". Length prefix is 1 but no
+ // payload.
+ string invalid_string_data = "\x72\x01";
+ {
+ google::protobuf::Arena arena;
+ unittest::TestAllTypes* arena_message =
+ google::protobuf::Arena::CreateMessage<unittest::TestAllTypes>(&arena);
+ EXPECT_FALSE(arena_message->ParseFromString(invalid_string_data));
+ arena_message->Clear();
+ EXPECT_EQ("", arena_message->optional_string());
+ }
}
+
namespace {
void ExpectMessageMerged(const unittest::TestAllTypes& message) {
@@ -551,6 +537,17 @@ TEST(MessageTest, MergeFrom) {
ASSERT_EQ(0, dest.repeated_uint64_size());
}
+TEST(MessageTest, IsInitialized) {
+ protobuf_unittest::TestIsInitialized msg;
+ EXPECT_TRUE(msg.IsInitialized());
+ protobuf_unittest::TestIsInitialized::SubMessage* sub_message = msg.mutable_sub_message();
+ EXPECT_TRUE(msg.IsInitialized());
+ protobuf_unittest::TestIsInitialized::SubMessage::SubGroup* sub_group = sub_message->mutable_subgroup();
+ EXPECT_FALSE(msg.IsInitialized());
+ sub_group->set_i(1);
+ EXPECT_TRUE(msg.IsInitialized());
+}
+
TEST(MessageFactoryTest, GeneratedFactoryLookup) {
EXPECT_EQ(
MessageFactory::generated_factory()->GetPrototype(
diff --git a/src/google/protobuf/metadata.h b/src/google/protobuf/metadata.h
index f9257534..0a6507c0 100644
--- a/src/google/protobuf/metadata.h
+++ b/src/google/protobuf/metadata.h
@@ -38,141 +38,21 @@
#ifndef GOOGLE_PROTOBUF_METADATA_H__
#define GOOGLE_PROTOBUF_METADATA_H__
-#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/arena.h>
-#include <google/protobuf/arenastring.h>
-#include <google/protobuf/generated_message_util.h>
+#include <google/protobuf/metadata_lite.h>
#include <google/protobuf/unknown_field_set.h>
namespace google {
namespace protobuf {
namespace internal {
-// This is the representation for messages that support arena allocation. It
-// uses a tagged pointer to either store the Arena pointer, if there are no
-// unknown fields, or a pointer to a block of memory with both the Arena pointer
-// and the UnknownFieldSet, if there are unknown fields. This optimization
-// allows for "zero-overhead" storage of the Arena pointer, relative to the
-// above baseline implementation.
-//
-// The tagged pointer uses the LSB to disambiguate cases, and uses bit 0 == 0 to
-// indicate an arena pointer and bit 0 == 1 to indicate a UFS+Arena-container
-// pointer.
-template <class T, class Derived>
-class InternalMetadataWithArenaBase {
- public:
- InternalMetadataWithArenaBase() : ptr_(NULL) {}
- explicit InternalMetadataWithArenaBase(Arena* arena) : ptr_(arena) {}
-
- ~InternalMetadataWithArenaBase() {
- if (have_unknown_fields() && arena() == NULL) {
- delete PtrValue<Container>();
- }
- ptr_ = NULL;
- }
-
- GOOGLE_ATTRIBUTE_ALWAYS_INLINE const T& unknown_fields() const {
- if (GOOGLE_PREDICT_FALSE(have_unknown_fields())) {
- return PtrValue<Container>()->unknown_fields;
- } else {
- return Derived::default_instance();
- }
- }
-
- GOOGLE_ATTRIBUTE_ALWAYS_INLINE T* mutable_unknown_fields() {
- if (GOOGLE_PREDICT_TRUE(have_unknown_fields())) {
- return &PtrValue<Container>()->unknown_fields;
- } else {
- return mutable_unknown_fields_slow();
- }
- }
-
- GOOGLE_ATTRIBUTE_ALWAYS_INLINE Arena* arena() const {
- if (GOOGLE_PREDICT_FALSE(have_unknown_fields())) {
- return PtrValue<Container>()->arena;
- } else {
- return PtrValue<Arena>();
- }
- }
-
- GOOGLE_ATTRIBUTE_ALWAYS_INLINE bool have_unknown_fields() const {
- return PtrTag() == kTagContainer;
- }
-
- GOOGLE_ATTRIBUTE_ALWAYS_INLINE void Swap(Derived* other) {
- // Semantics here are that we swap only the unknown fields, not the arena
- // pointer. We cannot simply swap ptr_ with other->ptr_ because we need to
- // maintain our own arena ptr. Also, our ptr_ and other's ptr_ may be in
- // different states (direct arena pointer vs. container with UFS) so we
- // cannot simply swap ptr_ and then restore the arena pointers. We reuse
- // UFS's swap implementation instead.
- if (have_unknown_fields() || other->have_unknown_fields()) {
- static_cast<Derived*>(this)->DoSwap(other->mutable_unknown_fields());
- }
- }
-
- GOOGLE_ATTRIBUTE_ALWAYS_INLINE void MergeFrom(const Derived& other) {
- if (other.have_unknown_fields()) {
- static_cast<Derived*>(this)->DoMergeFrom(other.unknown_fields());
- }
- }
-
- GOOGLE_ATTRIBUTE_ALWAYS_INLINE void Clear() {
- if (have_unknown_fields()) {
- static_cast<Derived*>(this)->DoClear();
- }
- }
-
- GOOGLE_ATTRIBUTE_ALWAYS_INLINE void* raw_arena_ptr() const {
- return ptr_;
- }
-
- private:
- void* ptr_;
-
- // Tagged pointer implementation.
- enum {
- // ptr_ is an Arena*.
- kTagArena = 0,
- // ptr_ is a Container*.
- kTagContainer = 1,
- };
- static const intptr_t kPtrTagMask = 1;
- static const intptr_t kPtrValueMask = ~kPtrTagMask;
-
- // Accessors for pointer tag and pointer value.
- GOOGLE_ATTRIBUTE_ALWAYS_INLINE int PtrTag() const {
- return reinterpret_cast<intptr_t>(ptr_) & kPtrTagMask;
- }
-
- template<typename U> U* PtrValue() const {
- return reinterpret_cast<U*>(
- reinterpret_cast<intptr_t>(ptr_) & kPtrValueMask);
- }
-
- // If ptr_'s tag is kTagContainer, it points to an instance of this struct.
- struct Container {
- T unknown_fields;
- Arena* arena;
- };
-
- GOOGLE_ATTRIBUTE_NOINLINE T* mutable_unknown_fields_slow() {
- Arena* my_arena = arena();
- Container* container = Arena::Create<Container>(my_arena);
- ptr_ = reinterpret_cast<void*>(
- reinterpret_cast<intptr_t>(container) | kTagContainer);
- container->arena = my_arena;
- return &(container->unknown_fields);
- }
-};
-
class InternalMetadataWithArena
: public InternalMetadataWithArenaBase<UnknownFieldSet,
InternalMetadataWithArena> {
public:
InternalMetadataWithArena() {}
explicit InternalMetadataWithArena(Arena* arena)
- : InternalMetadataWithArenaBase(arena) {}
+ : InternalMetadataWithArenaBase<UnknownFieldSet,
+ InternalMetadataWithArena>(arena) {}
void DoSwap(UnknownFieldSet* other) {
mutable_unknown_fields()->Swap(other);
@@ -191,35 +71,6 @@ class InternalMetadataWithArena
}
};
-// We store unknown fields as a string right now, because there is currently no
-// good interface for reading unknown fields into an ArenaString. We may want
-// to revisit this to allow unknown fields to be parsed onto the Arena.
-class InternalMetadataWithArenaLite
- : public InternalMetadataWithArenaBase<string,
- InternalMetadataWithArenaLite> {
- public:
- InternalMetadataWithArenaLite() {}
-
- explicit InternalMetadataWithArenaLite(Arena* arena)
- : InternalMetadataWithArenaBase(arena) {}
-
- void DoSwap(string* other) {
- mutable_unknown_fields()->swap(*other);
- }
-
- void DoMergeFrom(const string& other) {
- mutable_unknown_fields()->append(other);
- }
-
- void DoClear() {
- mutable_unknown_fields()->clear();
- }
-
- static const string& default_instance() {
- return GetEmptyStringAlreadyInited();
- }
-};
-
} // namespace internal
} // namespace protobuf
diff --git a/src/google/protobuf/metadata_lite.h b/src/google/protobuf/metadata_lite.h
new file mode 100644
index 00000000..454d088c
--- /dev/null
+++ b/src/google/protobuf/metadata_lite.h
@@ -0,0 +1,224 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#ifndef GOOGLE_PROTOBUF_METADATA_LITE_H__
+#define GOOGLE_PROTOBUF_METADATA_LITE_H__
+
+#include <google/protobuf/stubs/common.h>
+#include <google/protobuf/arena.h>
+#include <google/protobuf/message_lite.h>
+#include <google/protobuf/stubs/port.h>
+
+namespace google {
+namespace protobuf {
+namespace internal {
+
+// This is the representation for messages that support arena allocation. It
+// uses a tagged pointer to either store the Arena pointer, if there are no
+// unknown fields, or a pointer to a block of memory with both the Arena pointer
+// and the UnknownFieldSet, if there are unknown fields. This optimization
+// allows for "zero-overhead" storage of the Arena pointer, relative to the
+// above baseline implementation.
+//
+// The tagged pointer uses the LSB to disambiguate cases, and uses bit 0 == 0 to
+// indicate an arena pointer and bit 0 == 1 to indicate a UFS+Arena-container
+// pointer.
+template <class T, class Derived>
+class InternalMetadataWithArenaBase {
+ public:
+ InternalMetadataWithArenaBase() : ptr_(NULL) {}
+ explicit InternalMetadataWithArenaBase(Arena* arena) : ptr_(arena) {}
+
+ ~InternalMetadataWithArenaBase() {
+ if (have_unknown_fields() && arena() == NULL) {
+ delete PtrValue<Container>();
+ }
+ ptr_ = NULL;
+ }
+
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE const T& unknown_fields() const {
+ if (GOOGLE_PREDICT_FALSE(have_unknown_fields())) {
+ return PtrValue<Container>()->unknown_fields;
+ } else {
+ return Derived::default_instance();
+ }
+ }
+
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* mutable_unknown_fields() {
+ if (GOOGLE_PREDICT_TRUE(have_unknown_fields())) {
+ return &PtrValue<Container>()->unknown_fields;
+ } else {
+ return mutable_unknown_fields_slow();
+ }
+ }
+
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE Arena* arena() const {
+ if (GOOGLE_PREDICT_FALSE(have_unknown_fields())) {
+ return PtrValue<Container>()->arena;
+ } else {
+ return PtrValue<Arena>();
+ }
+ }
+
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE bool have_unknown_fields() const {
+ return PtrTag() == kTagContainer;
+ }
+
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void Swap(Derived* other) {
+ // Semantics here are that we swap only the unknown fields, not the arena
+ // pointer. We cannot simply swap ptr_ with other->ptr_ because we need to
+ // maintain our own arena ptr. Also, our ptr_ and other's ptr_ may be in
+ // different states (direct arena pointer vs. container with UFS) so we
+ // cannot simply swap ptr_ and then restore the arena pointers. We reuse
+ // UFS's swap implementation instead.
+ if (have_unknown_fields() || other->have_unknown_fields()) {
+ static_cast<Derived*>(this)->DoSwap(other->mutable_unknown_fields());
+ }
+ }
+
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void MergeFrom(const Derived& other) {
+ if (other.have_unknown_fields()) {
+ static_cast<Derived*>(this)->DoMergeFrom(other.unknown_fields());
+ }
+ }
+
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void Clear() {
+ if (have_unknown_fields()) {
+ static_cast<Derived*>(this)->DoClear();
+ }
+ }
+
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void* raw_arena_ptr() const {
+ return ptr_;
+ }
+
+ private:
+ void* ptr_;
+
+ // Tagged pointer implementation.
+ enum {
+ // ptr_ is an Arena*.
+ kTagArena = 0,
+ // ptr_ is a Container*.
+ kTagContainer = 1,
+ };
+ static const intptr_t kPtrTagMask = 1;
+ static const intptr_t kPtrValueMask = ~kPtrTagMask;
+
+ // Accessors for pointer tag and pointer value.
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE int PtrTag() const {
+ return reinterpret_cast<intptr_t>(ptr_) & kPtrTagMask;
+ }
+
+ template<typename U> U* PtrValue() const {
+ return reinterpret_cast<U*>(
+ reinterpret_cast<intptr_t>(ptr_) & kPtrValueMask);
+ }
+
+ // If ptr_'s tag is kTagContainer, it points to an instance of this struct.
+ struct Container {
+ T unknown_fields;
+ Arena* arena;
+ };
+
+ GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE T* mutable_unknown_fields_slow() {
+ Arena* my_arena = arena();
+ Container* container = Arena::Create<Container>(my_arena);
+ // Two-step assignment works around a bug in clang's static analyzer:
+ // https://bugs.llvm.org/show_bug.cgi?id=34198.
+ ptr_ = container;
+ ptr_ = reinterpret_cast<void*>(
+ reinterpret_cast<intptr_t>(ptr_) | kTagContainer);
+ container->arena = my_arena;
+ return &(container->unknown_fields);
+ }
+};
+
+// We store unknown fields as a string right now, because there is currently no
+// good interface for reading unknown fields into an ArenaString. We may want
+// to revisit this to allow unknown fields to be parsed onto the Arena.
+class InternalMetadataWithArenaLite
+ : public InternalMetadataWithArenaBase<string,
+ InternalMetadataWithArenaLite> {
+ public:
+ InternalMetadataWithArenaLite() {}
+
+ explicit InternalMetadataWithArenaLite(Arena* arena)
+ : InternalMetadataWithArenaBase<string,
+ InternalMetadataWithArenaLite>(arena) {}
+
+ void DoSwap(string* other) {
+ mutable_unknown_fields()->swap(*other);
+ }
+
+ void DoMergeFrom(const string& other) {
+ mutable_unknown_fields()->append(other);
+ }
+
+ void DoClear() {
+ mutable_unknown_fields()->clear();
+ }
+
+ static const string& default_instance() {
+ return GetEmptyStringAlreadyInited();
+ }
+};
+
+// This helper RAII class is needed to efficiently parse unknown fields. We
+// should only call mutable_unknown_fields if there are actual unknown fields.
+// The obvious thing to just use a stack string and swap it at the end of the
+// parse won't work, because the destructor of StringOutputStream needs to be
+// called before we can modify the string (it check-fails). Using
+// LiteUnknownFieldSetter setter(&_internal_metadata_);
+// StringOutputStream stream(setter.buffer());
+// guarantees that the string is only swapped after stream is destroyed.
+class LIBPROTOBUF_EXPORT LiteUnknownFieldSetter {
+ public:
+ explicit LiteUnknownFieldSetter(InternalMetadataWithArenaLite* metadata)
+ : metadata_(metadata) {
+ if (metadata->have_unknown_fields()) {
+ buffer_.swap(*metadata->mutable_unknown_fields());
+ }
+ }
+ ~LiteUnknownFieldSetter() {
+ if (!buffer_.empty()) metadata_->mutable_unknown_fields()->swap(buffer_);
+ }
+ string* buffer() { return &buffer_; }
+
+ private:
+ InternalMetadataWithArenaLite* metadata_;
+ string buffer_;
+};
+
+} // namespace internal
+} // namespace protobuf
+
+} // namespace google
+#endif // GOOGLE_PROTOBUF_METADATA_LITE_H__
diff --git a/src/google/protobuf/proto3_arena_unittest.cc b/src/google/protobuf/proto3_arena_unittest.cc
index 2838e0fc..3a0fb804 100644
--- a/src/google/protobuf/proto3_arena_unittest.cc
+++ b/src/google/protobuf/proto3_arena_unittest.cc
@@ -129,7 +129,8 @@ TEST(Proto3ArenaTest, Parsing) {
ExpectAllFieldsSet(*arena_message);
}
-TEST(Proto3ArenaTest, UnknownFields) {
+TEST(Proto3ArenaTest, UnknownFieldsDefaultDrop) {
+ ::google::protobuf::internal::SetProto3PreserveUnknownsDefault(false);
TestAllTypes original;
SetAllFields(&original);
@@ -150,6 +151,28 @@ TEST(Proto3ArenaTest, UnknownFields) {
arena_message->GetReflection()->GetUnknownFields(*arena_message).empty());
}
+TEST(Proto3ArenaTest, UnknownFieldsDefaultPreserve) {
+ ::google::protobuf::internal::SetProto3PreserveUnknownsDefault(true);
+ TestAllTypes original;
+ SetAllFields(&original);
+
+ Arena arena;
+ TestAllTypes* arena_message = Arena::CreateMessage<TestAllTypes>(&arena);
+ arena_message->ParseFromString(original.SerializeAsString());
+ ExpectAllFieldsSet(*arena_message);
+
+ // In proto3 we can still get a pointer to the UnknownFieldSet through
+ // reflection API.
+ UnknownFieldSet* unknown_fields =
+ arena_message->GetReflection()->MutableUnknownFields(arena_message);
+ // We can modify this UnknownFieldSet.
+ unknown_fields->AddVarint(1, 2);
+ // And the unknown fields should be changed.
+ ASSERT_NE(original.ByteSize(), arena_message->ByteSize());
+ ASSERT_FALSE(
+ arena_message->GetReflection()->GetUnknownFields(*arena_message).empty());
+}
+
TEST(Proto3ArenaTest, Swap) {
Arena arena1;
Arena arena2;
diff --git a/src/google/protobuf/reflection.h b/src/google/protobuf/reflection.h
index d5a6653c..fcb9a435 100755
--- a/src/google/protobuf/reflection.h
+++ b/src/google/protobuf/reflection.h
@@ -570,8 +570,8 @@ struct RefTypeTraits<
typedef RepeatedFieldRefIterator<T> iterator;
typedef RepeatedFieldAccessor AccessorType;
typedef string AccessorValueType;
- typedef string IteratorValueType;
- typedef string* IteratorPointerType;
+ typedef const string IteratorValueType;
+ typedef const string* IteratorPointerType;
static const FieldDescriptor::CppType cpp_type =
FieldDescriptor::CPPTYPE_STRING;
static const Descriptor* GetMessageFieldDescriptor() {
diff --git a/src/google/protobuf/reflection_ops.cc b/src/google/protobuf/reflection_ops.cc
index bb9c7f8b..d1867311 100644
--- a/src/google/protobuf/reflection_ops.cc
+++ b/src/google/protobuf/reflection_ops.cc
@@ -38,6 +38,7 @@
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/descriptor.pb.h>
+#include <google/protobuf/map_field.h>
#include <google/protobuf/unknown_field_set.h>
#include <google/protobuf/stubs/strutil.h>
@@ -158,6 +159,27 @@ bool ReflectionOps::IsInitialized(const Message& message) {
const FieldDescriptor* field = fields[i];
if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
+ if (field->is_map()) {
+ const FieldDescriptor* value_field = field->message_type()->field(1);
+ if (value_field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
+ MapFieldBase* map_field =
+ reflection->MapData(const_cast<Message*>(&message), field);
+ if (map_field->IsMapValid()) {
+ MapIterator iter(const_cast<Message*>(&message), field);
+ MapIterator end(const_cast<Message*>(&message), field);
+ for (map_field->MapBegin(&iter), map_field->MapEnd(&end);
+ iter != end; ++iter) {
+ if (!iter.GetValueRef().GetMessageValue().IsInitialized()) {
+ return false;
+ }
+ }
+ continue;
+ }
+ } else {
+ continue;
+ }
+ }
+
if (field->is_repeated()) {
int size = reflection->FieldSize(message, field);
diff --git a/src/google/protobuf/reflection_ops_unittest.cc b/src/google/protobuf/reflection_ops_unittest.cc
index 86453170..9cedb342 100644
--- a/src/google/protobuf/reflection_ops_unittest.cc
+++ b/src/google/protobuf/reflection_ops_unittest.cc
@@ -41,6 +41,7 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
+
#include <google/protobuf/stubs/strutil.h>
namespace google {
diff --git a/src/google/protobuf/repeated_field.h b/src/google/protobuf/repeated_field.h
index bbdef449..8eb6c795 100644
--- a/src/google/protobuf/repeated_field.h
+++ b/src/google/protobuf/repeated_field.h
@@ -51,15 +51,16 @@
#include <algorithm>
#endif
-#include <string>
#include <iterator>
+#include <limits>
+#include <string>
#include <google/protobuf/stubs/casts.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/type_traits.h>
#include <google/protobuf/arena.h>
-#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/message_lite.h>
+#include <google/protobuf/stubs/port.h>
// Forward-declare these so that we can make them friends.
@@ -76,6 +77,8 @@ class Message;
namespace internal {
+class MergePartialFromCodedStreamHelper;
+
static const int kMinRepeatedFieldAllocationSize = 4;
// A utility function for logging that doesn't need any template types.
@@ -116,6 +119,11 @@ class RepeatedField PROTOBUF_FINAL {
RepeatedField& operator=(const RepeatedField& other);
+#if LANG_CXX11
+ RepeatedField(RepeatedField&& other) noexcept;
+ RepeatedField& operator=(RepeatedField&& other) noexcept;
+#endif
+
bool empty() const;
int size() const;
@@ -155,6 +163,7 @@ class RepeatedField PROTOBUF_FINAL {
// The new element is uninitialized if |Element| is a POD type.
// Should be called only if Capacity() > Size().
Element* AddAlreadyReserved();
+ Element* AddNAlreadyReserved(int elements);
int Capacity() const;
// Like STL resize. Uses value to fill appended elements.
@@ -216,7 +225,11 @@ class RepeatedField PROTOBUF_FINAL {
// Returns the number of bytes used by the repeated field, excluding
// sizeof(*this)
- int SpaceUsedExcludingSelf() const;
+ size_t SpaceUsedExcludingSelfLong() const;
+
+ int SpaceUsedExcludingSelf() const {
+ return internal::ToIntSize(SpaceUsedExcludingSelfLong());
+ }
// Removes the element referenced by position.
//
@@ -238,6 +251,11 @@ class RepeatedField PROTOBUF_FINAL {
return GetArenaNoVirtual();
}
+ // For internal use only.
+ //
+ // This is public due to it being called by generated code.
+ inline void InternalSwap(RepeatedField* other);
+
private:
static const int kInitialSize = 0;
// A note on the representation here (see also comment below for
@@ -268,6 +286,7 @@ class RepeatedField PROTOBUF_FINAL {
friend class Arena;
typedef void InternalArenaConstructable_;
+
// Move the contents of |from| into |to|, possibly clobbering |from| in the
// process. For primitive types this is just a memcpy(), but it could be
// specialized for non-primitive types to, say, swap each element instead.
@@ -276,8 +295,6 @@ class RepeatedField PROTOBUF_FINAL {
// Copy the elements of |from| into |to|.
void CopyArray(Element* to, const Element* from, int size);
- inline void InternalSwap(RepeatedField* other);
-
// Internal helper expected by Arena methods.
inline Arena* GetArenaNoVirtual() const {
return (rep_ == NULL) ? NULL : rep_->arena;
@@ -291,7 +308,7 @@ class RepeatedField PROTOBUF_FINAL {
Element* e = &rep->elements[0];
Element* limit = &rep->elements[size];
for (; e < limit; e++) {
- e->Element::~Element();
+ e->~Element();
}
if (rep->arena == NULL) {
#if defined(__GXX_DELETE_WITH_SIZE__) || defined(__cpp_sized_deallocation)
@@ -303,6 +320,9 @@ class RepeatedField PROTOBUF_FINAL {
}
}
}
+
+ friend class internal::WireFormatLite;
+ const Element* unsafe_data() const;
};
template<typename Element>
@@ -321,7 +341,8 @@ namespace internal {
// shouldn't be necessary, but our compiler doesn't optimize std::copy very
// effectively.
template <typename Element,
- bool HasTrivialCopy = has_trivial_copy<Element>::value>
+ bool HasTrivialCopy =
+ has_trivial_copy<Element>::value>
struct ElementCopier {
void operator()(Element* to, const Element* from, int array_size);
};
@@ -335,8 +356,8 @@ namespace internal {
// exist on the contained type. In particular, we rely on MergeFrom() existing
// as a general proxy for the fact that a copy will work, and we also provide a
// specific override for string*.
-template<typename T>
-struct TypeImplementsMergeBehavior {
+template <typename T>
+struct TypeImplementsMergeBehaviorProbeForMergeFrom {
typedef char HasMerge;
typedef long HasNoMerge;
@@ -355,13 +376,18 @@ struct TypeImplementsMergeBehavior {
CheckType<U, bool, &U::MergeFrom>*);
template<typename U> static HasNoMerge Check(...);
- // Resovles to either google::protobuf::internal::true_type or google::protobuf::internal::false_type.
+ // Resolves to either google::protobuf::internal::true_type or google::protobuf::internal::false_type.
typedef google::protobuf::internal::integral_constant<bool,
(sizeof(Check<T>(0)) == sizeof(HasMerge))> type;
};
-template<>
-struct TypeImplementsMergeBehavior< ::std::string > {
+template <typename T, typename = void>
+struct TypeImplementsMergeBehavior :
+ TypeImplementsMergeBehaviorProbeForMergeFrom<T> {};
+
+
+template <>
+struct TypeImplementsMergeBehavior< ::std::string> {
typedef google::protobuf::internal::true_type type;
};
@@ -379,7 +405,7 @@ struct TypeImplementsMergeBehavior< ::std::string > {
// static void Merge(const Type& from, Type* to);
//
// // Only needs to be implemented if SpaceUsedExcludingSelf() is called.
-// static int SpaceUsed(const Type&);
+// static int SpaceUsedLong(const Type&);
// };
class LIBPROTOBUF_EXPORT RepeatedPtrFieldBase {
protected:
@@ -389,10 +415,10 @@ class LIBPROTOBUF_EXPORT RepeatedPtrFieldBase {
friend class GeneratedMessageReflection;
// ExtensionSet stores repeated message extensions as
- // RepeatedPtrField<MessageLite>, but non-lite ExtensionSets need to
- // implement SpaceUsed(), and thus need to call SpaceUsedExcludingSelf()
- // reinterpreting MessageLite as Message. ExtensionSet also needs to make
- // use of AddFromCleared(), which is not part of the public interface.
+ // RepeatedPtrField<MessageLite>, but non-lite ExtensionSets need to implement
+ // SpaceUsedLong(), and thus need to call SpaceUsedExcludingSelfLong()
+ // reinterpreting MessageLite as Message. ExtensionSet also needs to make use
+ // of AddFromCleared(), which is not part of the public interface.
friend class ExtensionSet;
// The MapFieldBase implementation needs to call protected methods directly,
@@ -400,6 +426,10 @@ class LIBPROTOBUF_EXPORT RepeatedPtrFieldBase {
// subclass.
friend class MapFieldBase;
+ // The table-driven MergePartialFromCodedStream implementation needs to
+ // operate on RepeatedPtrField<MessageLite>.
+ friend class MergePartialFromCodedStreamHelper;
+
// To parse directly into a proto2 generated class, the upb class GMR_Handlers
// needs to be able to modify a RepeatedPtrFieldBase directly.
friend class upb::google_opensource::GMR_Handlers;
@@ -423,6 +453,11 @@ class LIBPROTOBUF_EXPORT RepeatedPtrFieldBase {
void Delete(int index);
template <typename TypeHandler>
typename TypeHandler::Type* Add(typename TypeHandler::Type* prototype = NULL);
+#if LANG_CXX11
+ template <typename TypeHandler>
+ void Add(typename TypeHandler::Type&& value,
+ internal::enable_if<TypeHandler::Moveable>* dummy = NULL);
+#endif
template <typename TypeHandler>
void RemoveLast();
@@ -448,13 +483,13 @@ class LIBPROTOBUF_EXPORT RepeatedPtrFieldBase {
template <typename TypeHandler>
const typename TypeHandler::Type* const* data() const;
- template <typename TypeHandler>
- GOOGLE_ATTRIBUTE_ALWAYS_INLINE void Swap(RepeatedPtrFieldBase* other);
+ template <typename TypeHandler> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+ void Swap(RepeatedPtrFieldBase* other);
void SwapElements(int index1, int index2);
template <typename TypeHandler>
- int SpaceUsedExcludingSelf() const;
+ size_t SpaceUsedExcludingSelfLong() const;
// Advanced memory management --------------------------------------
@@ -493,17 +528,15 @@ class LIBPROTOBUF_EXPORT RepeatedPtrFieldBase {
inline void InternalSwap(RepeatedPtrFieldBase* other);
template <typename TypeHandler>
- void AddAllocatedInternal(typename TypeHandler::Type* value,
- google::protobuf::internal::true_type);
+ void AddAllocatedInternal(typename TypeHandler::Type* value, google::protobuf::internal::true_type);
template <typename TypeHandler>
- void AddAllocatedInternal(typename TypeHandler::Type* value,
- google::protobuf::internal::false_type);
+ void AddAllocatedInternal(typename TypeHandler::Type* value, google::protobuf::internal::false_type);
- template <typename TypeHandler> GOOGLE_ATTRIBUTE_NOINLINE
+ template <typename TypeHandler> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
void AddAllocatedSlowWithCopy(typename TypeHandler::Type* value,
Arena* value_arena,
Arena* my_arena);
- template <typename TypeHandler> GOOGLE_ATTRIBUTE_NOINLINE
+ template <typename TypeHandler> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
void AddAllocatedSlowWithoutCopy(typename TypeHandler::Type* value);
template <typename TypeHandler>
@@ -511,7 +544,7 @@ class LIBPROTOBUF_EXPORT RepeatedPtrFieldBase {
template <typename TypeHandler>
typename TypeHandler::Type* ReleaseLastInternal(google::protobuf::internal::false_type);
- template<typename TypeHandler> GOOGLE_ATTRIBUTE_NOINLINE
+ template<typename TypeHandler> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
void SwapFallback(RepeatedPtrFieldBase* other);
inline Arena* GetArenaNoVirtual() const {
@@ -568,6 +601,7 @@ class LIBPROTOBUF_EXPORT RepeatedPtrFieldBase {
// Reserve() and MergeFrom() to reduce code size. |extend_amount| must be > 0.
void** InternalExtend(int extend_amount);
+ friend class AccessorHelper;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedPtrFieldBase);
};
@@ -575,14 +609,14 @@ template <typename GenericType>
class GenericTypeHandler {
public:
typedef GenericType Type;
+#if LANG_CXX11
+ static const bool Moveable = false;
+#endif
+
static inline GenericType* New(Arena* arena) {
- return ::google::protobuf::Arena::CreateMaybeMessage<Type>(
- arena, static_cast<GenericType*>(0));
+ return ::google::protobuf::Arena::CreateMaybeMessage<Type>(arena);
}
- // We force NewFromPrototype() to be non-inline to reduce code size:
- // else, several other methods get inlined copies of message types'
- // constructors.
- GOOGLE_ATTRIBUTE_NOINLINE static GenericType* NewFromPrototype(
+ static inline GenericType* NewFromPrototype(
const GenericType* prototype, ::google::protobuf::Arena* arena = NULL);
static inline void Delete(GenericType* value, Arena* arena) {
if (arena == NULL) {
@@ -597,10 +631,10 @@ class GenericTypeHandler {
}
static inline void Clear(GenericType* value) { value->Clear(); }
- GOOGLE_ATTRIBUTE_NOINLINE static void Merge(const GenericType& from,
- GenericType* to);
- static inline int SpaceUsed(const GenericType& value) {
- return value.SpaceUsed();
+ GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
+ static void Merge(const GenericType& from, GenericType* to);
+ static inline size_t SpaceUsedLong(const GenericType& value) {
+ return value.SpaceUsedLong();
}
static inline const Type& default_instance() {
return Type::default_instance();
@@ -618,11 +652,9 @@ void GenericTypeHandler<GenericType>::Merge(const GenericType& from,
to->MergeFrom(from);
}
-// NewFromPrototype() and Merge() cannot be defined here; if they're declared
-// inline the compiler will complain about not matching GOOGLE_ATTRIBUTE_NOINLINE
-// above, and if not, compilation will result in multiple definitions. These
-// are therefore declared as specializations here and defined in
-// message_lite.cc.
+// NewFromPrototype() and Merge() are not defined inline here, as we will need
+// to do a virtual function dispatch anyways to go from Message* to call
+// New/Merge.
template<>
MessageLite* GenericTypeHandler<MessageLite>::NewFromPrototype(
const MessageLite* prototype, google::protobuf::Arena* arena);
@@ -686,13 +718,24 @@ inline const Message& GenericTypeHandler<Message>::default_instance() {
return *null;
}
-class LIBPROTOBUF_EXPORT StringTypeHandler {
+
+class StringTypeHandler {
public:
typedef string Type;
+#if LANG_CXX11
+ static const bool Moveable =
+ std::is_move_constructible<Type>::value &&
+ std::is_move_assignable<Type>::value;
+#endif
static inline string* New(Arena* arena) {
return Arena::Create<string>(arena);
}
+#if LANG_CXX11
+ static inline string* New(Arena* arena, string&& value) {
+ return Arena::Create<string>(arena, std::move(value));
+ }
+#endif
static inline string* NewFromPrototype(const string*,
::google::protobuf::Arena* arena) {
return New(arena);
@@ -713,12 +756,11 @@ class LIBPROTOBUF_EXPORT StringTypeHandler {
static inline const Type& default_instance() {
return ::google::protobuf::internal::GetEmptyString();
}
- static int SpaceUsed(const string& value) {
- return static_cast<int>(sizeof(value)) + StringSpaceUsedExcludingSelf(value);
+ static size_t SpaceUsedLong(const string& value) {
+ return sizeof(value) + StringSpaceUsedExcludingSelfLong(value);
}
};
-
} // namespace internal
// RepeatedPtrField is like RepeatedField, but used for repeated strings or
@@ -736,12 +778,20 @@ class RepeatedPtrField PROTOBUF_FINAL : public internal::RepeatedPtrFieldBase {
RepeatedPtrField& operator=(const RepeatedPtrField& other);
+#if LANG_CXX11
+ RepeatedPtrField(RepeatedPtrField&& other) noexcept;
+ RepeatedPtrField& operator=(RepeatedPtrField&& other) noexcept;
+#endif
+
bool empty() const;
int size() const;
const Element& Get(int index) const;
Element* Mutable(int index);
Element* Add();
+#if LANG_CXX11
+ void Add(Element&& value);
+#endif
const Element& operator[](int index) const { return Get(index); }
Element& operator[](int index) { return *Mutable(index); }
@@ -820,10 +870,11 @@ class RepeatedPtrField PROTOBUF_FINAL : public internal::RepeatedPtrFieldBase {
// Custom STL-like iterator that iterates over and returns the underlying
// pointers to Element rather than Element itself.
- typedef internal::RepeatedPtrOverPtrsIterator<Element, void*>
- pointer_iterator;
- typedef internal::RepeatedPtrOverPtrsIterator<const Element, const void*>
- const_pointer_iterator;
+ typedef internal::RepeatedPtrOverPtrsIterator<Element*, void*>
+ pointer_iterator;
+ typedef internal::RepeatedPtrOverPtrsIterator<const Element* const,
+ const void* const>
+ const_pointer_iterator;
pointer_iterator pointer_begin();
const_pointer_iterator pointer_begin() const;
pointer_iterator pointer_end();
@@ -831,7 +882,11 @@ class RepeatedPtrField PROTOBUF_FINAL : public internal::RepeatedPtrFieldBase {
// Returns (an estimate of) the number of bytes used by the repeated field,
// excluding sizeof(*this).
- int SpaceUsedExcludingSelf() const;
+ size_t SpaceUsedExcludingSelfLong() const;
+
+ int SpaceUsedExcludingSelf() const {
+ return internal::ToIntSize(SpaceUsedExcludingSelfLong());
+ }
// Advanced memory management --------------------------------------
// When hardcore memory management becomes necessary -- as it sometimes
@@ -948,6 +1003,11 @@ class RepeatedPtrField PROTOBUF_FINAL : public internal::RepeatedPtrFieldBase {
return GetArenaNoVirtual();
}
+ // For internal use only.
+ //
+ // This is public due to it being called by generated code.
+ using RepeatedPtrFieldBase::InternalSwap;
+
private:
// Note: RepeatedPtrField SHOULD NOT be subclassed by users.
class TypeHandler;
@@ -983,13 +1043,13 @@ inline RepeatedField<Element>::RepeatedField(Arena* arena)
: current_size_(0),
total_size_(0),
rep_(NULL) {
- // In case arena is NULL, then we do not create rep_, as code has an invariant
- // `rep_ == NULL then arena == NULL`.
- if (arena != NULL) {
- rep_ = reinterpret_cast<Rep*>(
- ::google::protobuf::Arena::CreateArray<char>(arena, kRepHeaderSize));
- rep_->arena = arena;
- }
+ // In case arena is NULL, then we do not create rep_, as code has an invariant
+ // `rep_ == NULL then arena == NULL`.
+ if (arena != NULL) {
+ rep_ = reinterpret_cast<Rep*>(
+ ::google::protobuf::Arena::CreateArray<char>(arena, kRepHeaderSize));
+ rep_->arena = arena;
+ }
}
template <typename Element>
@@ -1039,6 +1099,37 @@ RepeatedField<Element>::operator=(const RepeatedField& other) {
return *this;
}
+#if LANG_CXX11
+
+template <typename Element>
+inline RepeatedField<Element>::RepeatedField(RepeatedField&& other) noexcept
+ : RepeatedField() {
+ // We don't just call Swap(&other) here because it would perform 3 copies if
+ // the two fields are on different arenas.
+ if (other.GetArenaNoVirtual()) {
+ CopyFrom(other);
+ } else {
+ InternalSwap(&other);
+ }
+}
+
+template <typename Element>
+inline RepeatedField<Element>& RepeatedField<Element>::operator=(
+ RepeatedField&& other) noexcept {
+ // We don't just call Swap(&other) here because it would perform 3 copies if
+ // the two fields are on different arenas.
+ if (this != &other) {
+ if (this->GetArenaNoVirtual() != other.GetArenaNoVirtual()) {
+ CopyFrom(other);
+ } else {
+ InternalSwap(&other);
+ }
+ }
+ return *this;
+}
+
+#endif // LANG_CXX11
+
template <typename Element>
inline bool RepeatedField<Element>::empty() const {
return current_size_ == 0;
@@ -1067,6 +1158,14 @@ inline Element* RepeatedField<Element>::AddAlreadyReserved() {
}
template<typename Element>
+inline Element* RepeatedField<Element>::AddNAlreadyReserved(int elements) {
+ GOOGLE_DCHECK_LE(current_size_ + elements, total_size_);
+ Element* ret = &rep_->elements[current_size_];
+ current_size_ += elements;
+ return ret;
+}
+
+template<typename Element>
inline void RepeatedField<Element>::Resize(int new_size, const Element& value) {
GOOGLE_DCHECK_GE(new_size, 0);
if (new_size > current_size_) {
@@ -1186,9 +1285,17 @@ inline const Element* RepeatedField<Element>::data() const {
return rep_ ? rep_->elements : NULL;
}
+template <typename Element>
+inline const Element* RepeatedField<Element>::unsafe_data() const {
+ GOOGLE_DCHECK(rep_);
+ return rep_->elements;
+}
template <typename Element>
inline void RepeatedField<Element>::InternalSwap(RepeatedField* other) {
+ GOOGLE_DCHECK(this != other);
+ GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+
std::swap(rep_, other->rep_);
std::swap(current_size_, other->current_size_);
std::swap(total_size_, other->total_size_);
@@ -1197,7 +1304,7 @@ inline void RepeatedField<Element>::InternalSwap(RepeatedField* other) {
template <typename Element>
void RepeatedField<Element>::Swap(RepeatedField* other) {
if (this == other) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
InternalSwap(other);
} else {
RepeatedField<Element> temp(other->GetArenaNoVirtual());
@@ -1210,7 +1317,6 @@ void RepeatedField<Element>::Swap(RepeatedField* other) {
template <typename Element>
void RepeatedField<Element>::UnsafeArenaSwap(RepeatedField* other) {
if (this == other) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
@@ -1252,9 +1358,8 @@ RepeatedField<Element>::cend() const {
}
template <typename Element>
-inline int RepeatedField<Element>::SpaceUsedExcludingSelf() const {
- return rep_ ?
- (total_size_ * sizeof(Element) + kRepHeaderSize) : 0;
+inline size_t RepeatedField<Element>::SpaceUsedExcludingSelfLong() const {
+ return rep_ ? (total_size_ * sizeof(Element) + kRepHeaderSize) : 0;
}
// Avoid inlining of Reserve(): new, copy, and delete[] lead to a significant
@@ -1266,11 +1371,11 @@ void RepeatedField<Element>::Reserve(int new_size) {
Arena* arena = GetArenaNoVirtual();
new_size = std::max(google::protobuf::internal::kMinRepeatedFieldAllocationSize,
std::max(total_size_ * 2, new_size));
- GOOGLE_CHECK_LE(static_cast<size_t>(new_size),
- (std::numeric_limits<size_t>::max() - kRepHeaderSize) /
- sizeof(Element))
+ GOOGLE_DCHECK_LE(
+ static_cast<size_t>(new_size),
+ (std::numeric_limits<size_t>::max() - kRepHeaderSize) / sizeof(Element))
<< "Requested size is too large to fit into size_t.";
- size_t bytes = kRepHeaderSize + sizeof(Element) * new_size;
+ size_t bytes = kRepHeaderSize + sizeof(Element) * static_cast<size_t>(new_size);
if (arena == NULL) {
rep_ = static_cast<Rep*>(::operator new(bytes));
} else {
@@ -1334,7 +1439,7 @@ void ElementCopier<Element, HasTrivialCopy>::operator()(
template <typename Element>
struct ElementCopier<Element, true> {
void operator()(Element* to, const Element* from, int array_size) {
- memcpy(to, from, array_size * sizeof(Element));
+ memcpy(to, from, static_cast<size_t>(array_size) * sizeof(Element));
}
};
@@ -1450,6 +1555,25 @@ inline typename TypeHandler::Type* RepeatedPtrFieldBase::Add(
return result;
}
+#if LANG_CXX11
+template <typename TypeHandler>
+inline void RepeatedPtrFieldBase::Add(
+ typename TypeHandler::Type&& value,
+ internal::enable_if<TypeHandler::Moveable>*) {
+ if (rep_ != NULL && current_size_ < rep_->allocated_size) {
+ *cast<TypeHandler>(rep_->elements[current_size_++]) = std::move(value);
+ return;
+ }
+ if (!rep_ || rep_->allocated_size == total_size_) {
+ Reserve(total_size_ + 1);
+ }
+ ++rep_->allocated_size;
+ typename TypeHandler::Type* result =
+ TypeHandler::New(arena_, std::move(value));
+ rep_->elements[current_size_++] = result;
+}
+#endif
+
template <typename TypeHandler>
inline void RepeatedPtrFieldBase::RemoveLast() {
GOOGLE_DCHECK_GT(current_size_, 0);
@@ -1566,11 +1690,11 @@ inline void RepeatedPtrFieldBase::SwapElements(int index1, int index2) {
}
template <typename TypeHandler>
-inline int RepeatedPtrFieldBase::SpaceUsedExcludingSelf() const {
- int allocated_bytes = total_size_ * sizeof(void*);
+inline size_t RepeatedPtrFieldBase::SpaceUsedExcludingSelfLong() const {
+ size_t allocated_bytes = static_cast<size_t>(total_size_) * sizeof(void*);
if (rep_ != NULL) {
for (int i = 0; i < rep_->allocated_size; ++i) {
- allocated_bytes += TypeHandler::SpaceUsed(
+ allocated_bytes += TypeHandler::SpaceUsedLong(
*cast<TypeHandler>(rep_->elements[i]));
}
allocated_bytes += kRepHeaderSize;
@@ -1609,7 +1733,6 @@ void RepeatedPtrFieldBase::AddAllocatedInternal(
elems[current_size_] = value;
current_size_ = current_size_ + 1;
rep_->allocated_size = rep_->allocated_size + 1;
- return;
} else {
AddAllocatedSlowWithCopy<TypeHandler>(
value, TypeHandler::GetArena(value), arena);
@@ -1656,7 +1779,6 @@ void RepeatedPtrFieldBase::AddAllocatedInternal(
elems[current_size_] = value;
current_size_ = current_size_ + 1;
++rep_->allocated_size;
- return;
} else {
UnsafeArenaAddAllocated<TypeHandler>(value);
}
@@ -1779,7 +1901,6 @@ class RepeatedPtrField<string>::TypeHandler
: public internal::StringTypeHandler {
};
-
template <typename Element>
inline RepeatedPtrField<Element>::RepeatedPtrField()
: RepeatedPtrFieldBase() {}
@@ -1821,6 +1942,38 @@ inline RepeatedPtrField<Element>& RepeatedPtrField<Element>::operator=(
return *this;
}
+#if LANG_CXX11
+
+template <typename Element>
+inline RepeatedPtrField<Element>::RepeatedPtrField(
+ RepeatedPtrField&& other) noexcept
+ : RepeatedPtrField() {
+ // We don't just call Swap(&other) here because it would perform 3 copies if
+ // the two fields are on different arenas.
+ if (other.GetArenaNoVirtual()) {
+ CopyFrom(other);
+ } else {
+ InternalSwap(&other);
+ }
+}
+
+template <typename Element>
+inline RepeatedPtrField<Element>& RepeatedPtrField<Element>::operator=(
+ RepeatedPtrField&& other) noexcept {
+ // We don't just call Swap(&other) here because it would perform 3 copies if
+ // the two fields are on different arenas.
+ if (this != &other) {
+ if (this->GetArenaNoVirtual() != other.GetArenaNoVirtual()) {
+ CopyFrom(other);
+ } else {
+ InternalSwap(&other);
+ }
+ }
+ return *this;
+}
+
+#endif // LANG_CXX11
+
template <typename Element>
inline bool RepeatedPtrField<Element>::empty() const {
return RepeatedPtrFieldBase::empty();
@@ -1847,6 +2000,13 @@ inline Element* RepeatedPtrField<Element>::Add() {
return RepeatedPtrFieldBase::Add<TypeHandler>();
}
+#if LANG_CXX11
+template <typename Element>
+inline void RepeatedPtrField<Element>::Add(Element&& value) {
+ RepeatedPtrFieldBase::Add<TypeHandler>(std::move(value));
+}
+#endif
+
template <typename Element>
inline void RepeatedPtrField<Element>::RemoveLast() {
RepeatedPtrFieldBase::RemoveLast<TypeHandler>();
@@ -1989,7 +2149,6 @@ inline void RepeatedPtrField<Element>::Swap(RepeatedPtrField* other) {
template <typename Element>
inline void RepeatedPtrField<Element>::UnsafeArenaSwap(
RepeatedPtrField* other) {
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
if (this == other)
return;
RepeatedPtrFieldBase::InternalSwap(other);
@@ -2006,8 +2165,8 @@ inline Arena* RepeatedPtrField<Element>::GetArenaNoVirtual() const {
}
template <typename Element>
-inline int RepeatedPtrField<Element>::SpaceUsedExcludingSelf() const {
- return RepeatedPtrFieldBase::SpaceUsedExcludingSelf<TypeHandler>();
+inline size_t RepeatedPtrField<Element>::SpaceUsedExcludingSelfLong() const {
+ return RepeatedPtrFieldBase::SpaceUsedExcludingSelfLong<TypeHandler>();
}
template <typename Element>
@@ -2099,7 +2258,7 @@ class RepeatedPtrIterator
: it_(other.it_) {
// Force a compiler error if the other type is not convertible to ours.
if (false) {
- implicit_cast<Element*, OtherElement*>(0);
+ implicit_cast<Element*>(static_cast<OtherElement*>(NULL));
}
}
@@ -2165,18 +2324,17 @@ class RepeatedPtrIterator
// the array.
// The VoidPtr template parameter holds the type-agnostic pointer value
// referenced by the iterator. It should either be "void *" for a mutable
-// iterator, or "const void *" for a constant iterator.
-template<typename Element, typename VoidPtr>
+// iterator, or "const void* const" for a constant iterator.
+template <typename Element, typename VoidPtr>
class RepeatedPtrOverPtrsIterator
- : public std::iterator<std::random_access_iterator_tag, Element*> {
+ : public std::iterator<std::random_access_iterator_tag, Element> {
public:
typedef RepeatedPtrOverPtrsIterator<Element, VoidPtr> iterator;
- typedef std::iterator<
- std::random_access_iterator_tag, Element*> superclass;
+ typedef std::iterator<std::random_access_iterator_tag, Element> superclass;
// Shadow the value_type in std::iterator<> because const_iterator::value_type
// needs to be T, not const T.
- typedef typename remove_const<Element*>::type value_type;
+ typedef typename remove_const<Element>::type value_type;
// Let the compiler know that these are type names, so we don't have to
// write "typename" in front of them everywhere.
@@ -2188,7 +2346,7 @@ class RepeatedPtrOverPtrsIterator
explicit RepeatedPtrOverPtrsIterator(VoidPtr* it) : it_(it) {}
// dereferenceable
- reference operator*() const { return *reinterpret_cast<Element**>(it_); }
+ reference operator*() const { return *reinterpret_cast<Element*>(it_); }
pointer operator->() const { return &(operator*()); }
// {inc,dec}rementable
@@ -2244,6 +2402,9 @@ class RepeatedPtrOverPtrsIterator
};
void RepeatedPtrFieldBase::InternalSwap(RepeatedPtrFieldBase* other) {
+ GOOGLE_DCHECK(this != other);
+ GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+
std::swap(rep_, other->rep_);
std::swap(current_size_, other->current_size_);
std::swap(total_size_, other->total_size_);
@@ -2290,7 +2451,7 @@ RepeatedPtrField<Element>::pointer_begin() {
template <typename Element>
inline typename RepeatedPtrField<Element>::const_pointer_iterator
RepeatedPtrField<Element>::pointer_begin() const {
- return const_pointer_iterator(const_cast<const void**>(raw_mutable_data()));
+ return const_pointer_iterator(const_cast<const void* const*>(raw_data()));
}
template <typename Element>
inline typename RepeatedPtrField<Element>::pointer_iterator
@@ -2301,7 +2462,7 @@ template <typename Element>
inline typename RepeatedPtrField<Element>::const_pointer_iterator
RepeatedPtrField<Element>::pointer_end() const {
return const_pointer_iterator(
- const_cast<const void**>(raw_mutable_data() + size()));
+ const_cast<const void* const*>(raw_data() + size()));
}
@@ -2358,6 +2519,12 @@ template<typename T> class RepeatedPtrFieldBackInsertIterator
*field_->Add() = *ptr_to_value;
return *this;
}
+#if LANG_CXX11
+ RepeatedPtrFieldBackInsertIterator<T>& operator=(T&& value) {
+ *field_->Add() = std::move(value);
+ return *this;
+ }
+#endif
RepeatedPtrFieldBackInsertIterator<T>& operator*() {
return *this;
}
diff --git a/src/google/protobuf/repeated_field_reflection_unittest.cc b/src/google/protobuf/repeated_field_reflection_unittest.cc
index fcebe5ce..fd466565 100644
--- a/src/google/protobuf/repeated_field_reflection_unittest.cc
+++ b/src/google/protobuf/repeated_field_reflection_unittest.cc
@@ -189,8 +189,8 @@ TEST(RepeatedFieldReflectionTest, ExtensionFields) {
}
}
-template<typename Ref, typename MessageType, typename ValueType>
-void TestRepeatedFieldRefIterator(
+template <typename Ref, typename MessageType, typename ValueType>
+void TestRepeatedFieldRefIteratorForPrimitive(
const Ref& handle, const MessageType& message,
ValueType (MessageType::*GetFunc)(int) const) {
int index = 0;
@@ -202,6 +202,21 @@ void TestRepeatedFieldRefIterator(
EXPECT_EQ(handle.size(), index);
}
+template <typename MessageType, typename ValueType>
+void TestRepeatedFieldRefIteratorForString(
+ const RepeatedFieldRef<string>& handle, const MessageType& message,
+ ValueType (MessageType::*GetFunc)(int) const) {
+ int index = 0;
+ for (typename RepeatedFieldRef<string>::const_iterator it = handle.begin();
+ it != handle.end(); ++it) {
+ // Test both operator* and operator->
+ EXPECT_EQ((message.*GetFunc)(index), *it);
+ EXPECT_EQ((message.*GetFunc)(index).size(), it->size());
+ ++index;
+ }
+ EXPECT_EQ(handle.size(), index);
+}
+
TEST(RepeatedFieldReflectionTest, RepeatedFieldRefForRegularFields) {
TestAllTypes message;
const Reflection* refl = message.GetReflection();
@@ -312,12 +327,12 @@ TEST(RepeatedFieldReflectionTest, RepeatedFieldRefForRegularFields) {
}
// Test iterators.
- TestRepeatedFieldRefIterator(rf_int32, message,
- &TestAllTypes::repeated_int32);
- TestRepeatedFieldRefIterator(rf_double, message,
- &TestAllTypes::repeated_double);
- TestRepeatedFieldRefIterator(rf_string, message,
- &TestAllTypes::repeated_string);
+ TestRepeatedFieldRefIteratorForPrimitive(rf_int32, message,
+ &TestAllTypes::repeated_int32);
+ TestRepeatedFieldRefIteratorForPrimitive(rf_double, message,
+ &TestAllTypes::repeated_double);
+ TestRepeatedFieldRefIteratorForString(rf_string, message,
+ &TestAllTypes::repeated_string);
// Test iterators for message fields.
typedef RepeatedFieldRef<ForeignMessage>::iterator MessageIterator;
@@ -474,10 +489,10 @@ TEST(RepeatedFieldReflectionTest, RepeatedFieldRefForEnums) {
EXPECT_EQ(TestAllTypes::BAZ, message.repeated_nested_enum(i));
}
- TestRepeatedFieldRefIterator(enum_ref, message,
- &TestAllTypes::repeated_nested_enum);
- TestRepeatedFieldRefIterator(int32_ref, message,
- &TestAllTypes::repeated_nested_enum);
+ TestRepeatedFieldRefIteratorForPrimitive(enum_ref, message,
+ &TestAllTypes::repeated_nested_enum);
+ TestRepeatedFieldRefIteratorForPrimitive(int32_ref, message,
+ &TestAllTypes::repeated_nested_enum);
// Test Add()
mutable_enum_ref.Add(TestAllTypes::FOO);
diff --git a/src/google/protobuf/repeated_field_unittest.cc b/src/google/protobuf/repeated_field_unittest.cc
index ec1074c9..16919711 100644
--- a/src/google/protobuf/repeated_field_unittest.cc
+++ b/src/google/protobuf/repeated_field_unittest.cc
@@ -45,17 +45,19 @@
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/unittest.pb.h>
-#include <google/protobuf/stubs/strutil.h>
+#include <gmock/gmock.h>
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
+#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/stl_util.h>
namespace google {
-using protobuf_unittest::TestAllTypes;
-
namespace protobuf {
namespace {
+using ::protobuf_unittest::TestAllTypes;
+using ::testing::ElementsAre;
+
// Test operations on a small RepeatedField.
TEST(RepeatedField, Small) {
RepeatedField<int> field;
@@ -267,15 +269,6 @@ TEST(RepeatedField, MergeFrom) {
EXPECT_EQ(5, destination.Get(4));
}
-#ifdef PROTOBUF_HAS_DEATH_TEST
-#ifndef NDEBUG
-TEST(RepeatedField, MergeFromSelf) {
- RepeatedField<int> me;
- me.Add(3);
- EXPECT_DEATH(me.MergeFrom(me), "");
-}
-#endif // NDEBUG
-#endif // PROTOBUF_HAS_DEATH_TEST
TEST(RepeatedField, CopyFrom) {
RepeatedField<int> source, destination;
@@ -390,6 +383,142 @@ TEST(RepeatedField, SelfAssign) {
EXPECT_EQ(8, source.Get(1));
}
+#if LANG_CXX11
+
+TEST(RepeatedField, MoveConstruct) {
+ {
+ RepeatedField<int> source;
+ source.Add(1);
+ source.Add(2);
+ const int* data = source.data();
+ RepeatedField<int> destination = std::move(source);
+ EXPECT_EQ(data, destination.data());
+ EXPECT_THAT(destination, ElementsAre(1, 2));
+ // This property isn't guaranteed but it's useful to have a test that would
+ // catch changes in this area.
+ EXPECT_TRUE(source.empty());
+ }
+ {
+ Arena arena;
+ RepeatedField<int>* source =
+ Arena::CreateMessage<RepeatedField<int>>(&arena);
+ source->Add(1);
+ source->Add(2);
+ RepeatedField<int> destination = std::move(*source);
+ EXPECT_EQ(NULL, destination.GetArena());
+ EXPECT_THAT(destination, ElementsAre(1, 2));
+ // This property isn't guaranteed but it's useful to have a test that would
+ // catch changes in this area.
+ EXPECT_THAT(*source, ElementsAre(1, 2));
+ }
+}
+
+TEST(RepeatedField, MoveAssign) {
+ {
+ RepeatedField<int> source;
+ source.Add(1);
+ source.Add(2);
+ RepeatedField<int> destination;
+ destination.Add(3);
+ const int* source_data = source.data();
+ const int* destination_data = destination.data();
+ destination = std::move(source);
+ EXPECT_EQ(source_data, destination.data());
+ EXPECT_THAT(destination, ElementsAre(1, 2));
+ // This property isn't guaranteed but it's useful to have a test that would
+ // catch changes in this area.
+ EXPECT_EQ(destination_data, source.data());
+ EXPECT_THAT(source, ElementsAre(3));
+ }
+ {
+ Arena arena;
+ RepeatedField<int>* source =
+ Arena::CreateMessage<RepeatedField<int>>(&arena);
+ source->Add(1);
+ source->Add(2);
+ RepeatedField<int>* destination =
+ Arena::CreateMessage<RepeatedField<int>>(&arena);
+ destination->Add(3);
+ const int* source_data = source->data();
+ const int* destination_data = destination->data();
+ *destination = std::move(*source);
+ EXPECT_EQ(source_data, destination->data());
+ EXPECT_THAT(*destination, ElementsAre(1, 2));
+ // This property isn't guaranteed but it's useful to have a test that would
+ // catch changes in this area.
+ EXPECT_EQ(destination_data, source->data());
+ EXPECT_THAT(*source, ElementsAre(3));
+ }
+ {
+ Arena source_arena;
+ RepeatedField<int>* source =
+ Arena::CreateMessage<RepeatedField<int>>(&source_arena);
+ source->Add(1);
+ source->Add(2);
+ Arena destination_arena;
+ RepeatedField<int>* destination =
+ Arena::CreateMessage<RepeatedField<int>>(&destination_arena);
+ destination->Add(3);
+ *destination = std::move(*source);
+ EXPECT_THAT(*destination, ElementsAre(1, 2));
+ // This property isn't guaranteed but it's useful to have a test that would
+ // catch changes in this area.
+ EXPECT_THAT(*source, ElementsAre(1, 2));
+ }
+ {
+ Arena arena;
+ RepeatedField<int>* source =
+ Arena::CreateMessage<RepeatedField<int>>(&arena);
+ source->Add(1);
+ source->Add(2);
+ RepeatedField<int> destination;
+ destination.Add(3);
+ destination = std::move(*source);
+ EXPECT_THAT(destination, ElementsAre(1, 2));
+ // This property isn't guaranteed but it's useful to have a test that would
+ // catch changes in this area.
+ EXPECT_THAT(*source, ElementsAre(1, 2));
+ }
+ {
+ RepeatedField<int> source;
+ source.Add(1);
+ source.Add(2);
+ Arena arena;
+ RepeatedField<int>* destination =
+ Arena::CreateMessage<RepeatedField<int>>(&arena);
+ destination->Add(3);
+ *destination = std::move(source);
+ EXPECT_THAT(*destination, ElementsAre(1, 2));
+ // This property isn't guaranteed but it's useful to have a test that would
+ // catch changes in this area.
+ EXPECT_THAT(source, ElementsAre(1, 2));
+ }
+ {
+ RepeatedField<int> field;
+ // An alias to defeat -Wself-move.
+ RepeatedField<int>& alias = field;
+ field.Add(1);
+ field.Add(2);
+ const int* data = field.data();
+ field = std::move(alias);
+ EXPECT_EQ(data, field.data());
+ EXPECT_THAT(field, ElementsAre(1, 2));
+ }
+ {
+ Arena arena;
+ RepeatedField<int>* field =
+ Arena::CreateMessage<RepeatedField<int>>(&arena);
+ field->Add(1);
+ field->Add(2);
+ const int* data = field->data();
+ *field = std::move(*field);
+ EXPECT_EQ(data, field->data());
+ EXPECT_THAT(*field, ElementsAre(1, 2));
+ }
+}
+
+#endif // LANG_CXX11
+
TEST(RepeatedField, MutableDataIsMutable) {
RepeatedField<int> field;
field.Add(1);
@@ -783,13 +912,6 @@ TEST(RepeatedPtrField, MergeFrom) {
EXPECT_EQ("5", destination.Get(4));
}
-#ifdef PROTOBUF_HAS_DEATH_TEST
-TEST(RepeatedPtrField, MergeFromSelf) {
- RepeatedPtrField<string> me;
- me.Add()->assign("1");
- EXPECT_DEATH(me.MergeFrom(me), "");
-}
-#endif // PROTOBUF_HAS_DEATH_TEST
TEST(RepeatedPtrField, CopyFrom) {
RepeatedPtrField<string> source, destination;
@@ -923,6 +1045,142 @@ TEST(RepeatedPtrField, SelfAssign) {
EXPECT_EQ("8", source.Get(1));
}
+#if LANG_CXX11
+
+TEST(RepeatedPtrField, MoveConstruct) {
+ {
+ RepeatedPtrField<string> source;
+ *source.Add() = "1";
+ *source.Add() = "2";
+ const string* const* data = source.data();
+ RepeatedPtrField<string> destination = std::move(source);
+ EXPECT_EQ(data, destination.data());
+ EXPECT_THAT(destination, ElementsAre("1", "2"));
+ // This property isn't guaranteed but it's useful to have a test that would
+ // catch changes in this area.
+ EXPECT_TRUE(source.empty());
+ }
+ {
+ Arena arena;
+ RepeatedPtrField<string>* source =
+ Arena::CreateMessage<RepeatedPtrField<string>>(&arena);
+ *source->Add() = "1";
+ *source->Add() = "2";
+ RepeatedPtrField<string> destination = std::move(*source);
+ EXPECT_EQ(NULL, destination.GetArena());
+ EXPECT_THAT(destination, ElementsAre("1", "2"));
+ // This property isn't guaranteed but it's useful to have a test that would
+ // catch changes in this area.
+ EXPECT_THAT(*source, ElementsAre("1", "2"));
+ }
+}
+
+TEST(RepeatedPtrField, MoveAssign) {
+ {
+ RepeatedPtrField<string> source;
+ *source.Add() = "1";
+ *source.Add() = "2";
+ RepeatedPtrField<string> destination;
+ *destination.Add() = "3";
+ const string* const* source_data = source.data();
+ const string* const* destination_data = destination.data();
+ destination = std::move(source);
+ EXPECT_EQ(source_data, destination.data());
+ EXPECT_THAT(destination, ElementsAre("1", "2"));
+ // This property isn't guaranteed but it's useful to have a test that would
+ // catch changes in this area.
+ EXPECT_EQ(destination_data, source.data());
+ EXPECT_THAT(source, ElementsAre("3"));
+ }
+ {
+ Arena arena;
+ RepeatedPtrField<string>* source =
+ Arena::CreateMessage<RepeatedPtrField<string>>(&arena);
+ *source->Add() = "1";
+ *source->Add() = "2";
+ RepeatedPtrField<string>* destination =
+ Arena::CreateMessage<RepeatedPtrField<string>>(&arena);
+ *destination->Add() = "3";
+ const string* const* source_data = source->data();
+ const string* const* destination_data = destination->data();
+ *destination = std::move(*source);
+ EXPECT_EQ(source_data, destination->data());
+ EXPECT_THAT(*destination, ElementsAre("1", "2"));
+ // This property isn't guaranteed but it's useful to have a test that would
+ // catch changes in this area.
+ EXPECT_EQ(destination_data, source->data());
+ EXPECT_THAT(*source, ElementsAre("3"));
+ }
+ {
+ Arena source_arena;
+ RepeatedPtrField<string>* source =
+ Arena::CreateMessage<RepeatedPtrField<string>>(&source_arena);
+ *source->Add() = "1";
+ *source->Add() = "2";
+ Arena destination_arena;
+ RepeatedPtrField<string>* destination =
+ Arena::CreateMessage<RepeatedPtrField<string>>(&destination_arena);
+ *destination->Add() = "3";
+ *destination = std::move(*source);
+ EXPECT_THAT(*destination, ElementsAre("1", "2"));
+ // This property isn't guaranteed but it's useful to have a test that would
+ // catch changes in this area.
+ EXPECT_THAT(*source, ElementsAre("1", "2"));
+ }
+ {
+ Arena arena;
+ RepeatedPtrField<string>* source =
+ Arena::CreateMessage<RepeatedPtrField<string>>(&arena);
+ *source->Add() = "1";
+ *source->Add() = "2";
+ RepeatedPtrField<string> destination;
+ *destination.Add() = "3";
+ destination = std::move(*source);
+ EXPECT_THAT(destination, ElementsAre("1", "2"));
+ // This property isn't guaranteed but it's useful to have a test that would
+ // catch changes in this area.
+ EXPECT_THAT(*source, ElementsAre("1", "2"));
+ }
+ {
+ RepeatedPtrField<string> source;
+ *source.Add() = "1";
+ *source.Add() = "2";
+ Arena arena;
+ RepeatedPtrField<string>* destination =
+ Arena::CreateMessage<RepeatedPtrField<string>>(&arena);
+ *destination->Add() = "3";
+ *destination = std::move(source);
+ EXPECT_THAT(*destination, ElementsAre("1", "2"));
+ // This property isn't guaranteed but it's useful to have a test that would
+ // catch changes in this area.
+ EXPECT_THAT(source, ElementsAre("1", "2"));
+ }
+ {
+ RepeatedPtrField<string> field;
+ // An alias to defeat -Wself-move.
+ RepeatedPtrField<string>& alias = field;
+ *field.Add() = "1";
+ *field.Add() = "2";
+ const string* const* data = field.data();
+ field = std::move(alias);
+ EXPECT_EQ(data, field.data());
+ EXPECT_THAT(field, ElementsAre("1", "2"));
+ }
+ {
+ Arena arena;
+ RepeatedPtrField<string>* field =
+ Arena::CreateMessage<RepeatedPtrField<string>>(&arena);
+ *field->Add() = "1";
+ *field->Add() = "2";
+ const string* const* data = field->data();
+ *field = std::move(*field);
+ EXPECT_EQ(data, field->data());
+ EXPECT_THAT(*field, ElementsAre("1", "2"));
+ }
+}
+
+#endif // LANG_CXX11
+
TEST(RepeatedPtrField, MutableDataIsMutable) {
RepeatedPtrField<string> field;
*field.Add() = "1";
@@ -1586,6 +1844,38 @@ TEST_F(RepeatedFieldInsertionIteratorsTest,
EXPECT_EQ(testproto.DebugString(), goldenproto.DebugString());
}
+#if LANG_CXX11
+TEST_F(RepeatedFieldInsertionIteratorsTest, MoveStrings) {
+ std::vector<string> src = {"a", "b", "c", "d"};
+ std::vector<string> copy = src; // copy since move leaves in undefined state
+ TestAllTypes testproto;
+ std::move(copy.begin(), copy.end(),
+ RepeatedFieldBackInserter(testproto.mutable_repeated_string()));
+
+ ASSERT_THAT(testproto.repeated_string(), testing::ElementsAreArray(src));
+}
+
+TEST_F(RepeatedFieldInsertionIteratorsTest, MoveProtos) {
+ auto make_nested = [](int32 x) {
+ Nested ret;
+ ret.set_bb(x);
+ return ret;
+ };
+ std::vector<Nested> src = {make_nested(3), make_nested(5), make_nested(7)};
+ std::vector<Nested> copy = src; // copy since move leaves in undefined state
+ TestAllTypes testproto;
+ std::move(
+ copy.begin(), copy.end(),
+ RepeatedFieldBackInserter(testproto.mutable_repeated_nested_message()));
+
+ ASSERT_EQ(src.size(), testproto.repeated_nested_message_size());
+ for (int i = 0; i < src.size(); ++i) {
+ EXPECT_EQ(src[i].DebugString(),
+ testproto.repeated_nested_message(i).DebugString());
+ }
+}
+#endif
+
} // namespace
} // namespace protobuf
diff --git a/src/google/protobuf/source_context.pb.cc b/src/google/protobuf/source_context.pb.cc
index b9e5a73b..4a290e1e 100644
--- a/src/google/protobuf/source_context.pb.cc
+++ b/src/google/protobuf/source_context.pb.cc
@@ -1,7 +1,6 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/source_context.proto
-#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include <google/protobuf/source_context.pb.h>
#include <algorithm>
@@ -15,47 +14,65 @@
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
+// This is a temporary google only hack
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+#include "third_party/protobuf/version.h"
+#endif
// @@protoc_insertion_point(includes)
-
namespace google {
namespace protobuf {
-class SourceContextDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<SourceContext> {};
-SourceContextDefaultTypeInternal _SourceContext_default_instance_;
-
-namespace {
-
-::google::protobuf::Metadata file_level_metadata[1];
-
-} // namespace
+class SourceContextDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<SourceContext>
+ _instance;
+} _SourceContext_default_instance_;
+} // namespace protobuf
+} // namespace google
+namespace protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto {
+void InitDefaultsSourceContextImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ {
+ void* ptr = &::google::protobuf::_SourceContext_default_instance_;
+ new (ptr) ::google::protobuf::SourceContext();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::SourceContext::InitAsDefaultInstance();
+}
-const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fsource_5fcontext_2eproto() GOOGLE_ATTRIBUTE_COLD;
-const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fsource_5fcontext_2eproto() {
- static const ::google::protobuf::uint32 offsets[] = {
- ~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SourceContext, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SourceContext, file_name_),
- };
- return offsets;
+void InitDefaultsSourceContext() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsSourceContextImpl);
}
-static const ::google::protobuf::internal::MigrationSchema schemas[] = {
- { 0, -1, sizeof(SourceContext)},
-};
+::google::protobuf::Metadata file_level_metadata[1];
-static const ::google::protobuf::internal::DefaultInstanceData file_default_instances[] = {
- {reinterpret_cast<const ::google::protobuf::Message*>(&_SourceContext_default_instance_), NULL},
+const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+ ~0u, // no _has_bits_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::SourceContext, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::SourceContext, file_name_),
+};
+static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+ { 0, -1, sizeof(::google::protobuf::SourceContext)},
};
-namespace {
+static ::google::protobuf::Message const * const file_default_instances[] = {
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_SourceContext_default_instance_),
+};
void protobuf_AssignDescriptors() {
- protobuf_AddDesc_google_2fprotobuf_2fsource_5fcontext_2eproto();
+ AddDescriptors();
::google::protobuf::MessageFactory* factory = NULL;
AssignDescriptors(
- "google/protobuf/source_context.proto", schemas, file_default_instances, protobuf_Offsets_google_2fprotobuf_2fsource_5fcontext_2eproto(), factory,
+ "google/protobuf/source_context.proto", schemas, file_default_instances, TableStruct::offsets, factory,
file_level_metadata, NULL, NULL);
}
@@ -64,33 +81,15 @@ void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);
}
-void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
+void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 1);
}
-} // namespace
-
-void protobuf_ShutdownFile_google_2fprotobuf_2fsource_5fcontext_2eproto() {
- _SourceContext_default_instance_.Shutdown();
- delete file_level_metadata[0].reflection;
-}
-
-void protobuf_InitDefaults_google_2fprotobuf_2fsource_5fcontext_2eproto_impl() {
- GOOGLE_PROTOBUF_VERIFY_VERSION;
-
- ::google::protobuf::internal::InitProtobufDefaults();
- _SourceContext_default_instance_.DefaultConstruct();
-}
-
-void protobuf_InitDefaults_google_2fprotobuf_2fsource_5fcontext_2eproto() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &protobuf_InitDefaults_google_2fprotobuf_2fsource_5fcontext_2eproto_impl);
-}
-void protobuf_AddDesc_google_2fprotobuf_2fsource_5fcontext_2eproto_impl() {
- protobuf_InitDefaults_google_2fprotobuf_2fsource_5fcontext_2eproto();
- static const char descriptor[] = {
+void AddDescriptorsImpl() {
+ InitDefaults();
+ static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n$google/protobuf/source_context.proto\022\017"
"google.protobuf\"\"\n\rSourceContext\022\021\n\tfile"
"_name\030\001 \001(\tB\225\001\n\023com.google.protobufB\022Sou"
@@ -103,23 +102,26 @@ void protobuf_AddDesc_google_2fprotobuf_2fsource_5fcontext_2eproto_impl() {
descriptor, 251);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"google/protobuf/source_context.proto", &protobuf_RegisterTypes);
- ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_google_2fprotobuf_2fsource_5fcontext_2eproto);
}
-GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AddDesc_google_2fprotobuf_2fsource_5fcontext_2eproto_once_);
-void protobuf_AddDesc_google_2fprotobuf_2fsource_5fcontext_2eproto() {
- ::google::protobuf::GoogleOnceInit(&protobuf_AddDesc_google_2fprotobuf_2fsource_5fcontext_2eproto_once_,
- &protobuf_AddDesc_google_2fprotobuf_2fsource_5fcontext_2eproto_impl);
+void AddDescriptors() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);
}
-// Force AddDescriptors() to be called at static initialization time.
-struct StaticDescriptorInitializer_google_2fprotobuf_2fsource_5fcontext_2eproto {
- StaticDescriptorInitializer_google_2fprotobuf_2fsource_5fcontext_2eproto() {
- protobuf_AddDesc_google_2fprotobuf_2fsource_5fcontext_2eproto();
+// Force AddDescriptors() to be called at dynamic initialization time.
+struct StaticDescriptorInitializer {
+ StaticDescriptorInitializer() {
+ AddDescriptors();
}
-} static_descriptor_initializer_google_2fprotobuf_2fsource_5fcontext_2eproto_;
+} static_descriptor_initializer;
+} // namespace protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto
+namespace google {
+namespace protobuf {
// ===================================================================
+void SourceContext::InitAsDefaultInstance() {
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int SourceContext::kFileNameFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
@@ -127,7 +129,7 @@ const int SourceContext::kFileNameFieldNumber;
SourceContext::SourceContext()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fsource_5fcontext_2eproto();
+ ::protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::InitDefaultsSourceContext();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.SourceContext)
@@ -164,12 +166,12 @@ void SourceContext::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* SourceContext::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[0].descriptor;
+ ::protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const SourceContext& SourceContext::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fsource_5fcontext_2eproto();
+ ::protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::InitDefaultsSourceContext();
return *internal_default_instance();
}
@@ -183,7 +185,12 @@ SourceContext* SourceContext::New(::google::protobuf::Arena* arena) const {
void SourceContext::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.SourceContext)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
file_name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ _internal_metadata_.Clear();
}
bool SourceContext::MergePartialFromCodedStream(
@@ -198,11 +205,12 @@ bool SourceContext::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// string file_name = 1;
case 1: {
- if (tag == 10u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_file_name()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->file_name().data(), this->file_name().length(),
+ this->file_name().data(), static_cast<int>(this->file_name().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.protobuf.SourceContext.file_name"));
} else {
@@ -213,12 +221,11 @@ bool SourceContext::MergePartialFromCodedStream(
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
- DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
+ DO_(::google::protobuf::internal::WireFormat::SkipField(
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -235,16 +242,23 @@ failure:
void SourceContext::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.SourceContext)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// string file_name = 1;
if (this->file_name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->file_name().data(), this->file_name().length(),
+ this->file_name().data(), static_cast<int>(this->file_name().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.SourceContext.file_name");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
1, this->file_name(), output);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ }
// @@protoc_insertion_point(serialize_end:google.protobuf.SourceContext)
}
@@ -252,10 +266,13 @@ void SourceContext::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.SourceContext)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// string file_name = 1;
if (this->file_name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->file_name().data(), this->file_name().length(),
+ this->file_name().data(), static_cast<int>(this->file_name().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.SourceContext.file_name");
target =
@@ -263,6 +280,10 @@ void SourceContext::SerializeWithCachedSizes(
1, this->file_name(), target);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ }
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.SourceContext)
return target;
}
@@ -271,6 +292,11 @@ size_t SourceContext::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.SourceContext)
size_t total_size = 0;
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ total_size +=
+ ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ }
// string file_name = 1;
if (this->file_name().size() > 0) {
total_size += 1 +
@@ -304,6 +330,9 @@ void SourceContext::MergeFrom(const SourceContext& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.SourceContext)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
if (from.file_name().size() > 0) {
file_name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.file_name_);
@@ -333,66 +362,19 @@ void SourceContext::Swap(SourceContext* other) {
InternalSwap(other);
}
void SourceContext::InternalSwap(SourceContext* other) {
+ using std::swap;
file_name_.Swap(&other->file_name_);
- std::swap(_cached_size_, other->_cached_size_);
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata SourceContext::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[0];
+ protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// SourceContext
-
-// string file_name = 1;
-void SourceContext::clear_file_name() {
- file_name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-const ::std::string& SourceContext::file_name() const {
- // @@protoc_insertion_point(field_get:google.protobuf.SourceContext.file_name)
- return file_name_.GetNoArena();
-}
-void SourceContext::set_file_name(const ::std::string& value) {
-
- file_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
- // @@protoc_insertion_point(field_set:google.protobuf.SourceContext.file_name)
-}
-void SourceContext::set_file_name(const char* value) {
-
- file_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
- // @@protoc_insertion_point(field_set_char:google.protobuf.SourceContext.file_name)
-}
-void SourceContext::set_file_name(const char* value, size_t size) {
-
- file_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.SourceContext.file_name)
-}
-::std::string* SourceContext::mutable_file_name() {
-
- // @@protoc_insertion_point(field_mutable:google.protobuf.SourceContext.file_name)
- return file_name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-::std::string* SourceContext::release_file_name() {
- // @@protoc_insertion_point(field_release:google.protobuf.SourceContext.file_name)
-
- return file_name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
-}
-void SourceContext::set_allocated_file_name(::std::string* file_name) {
- if (file_name != NULL) {
-
- } else {
-
- }
- file_name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), file_name);
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.SourceContext.file_name)
-}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
-
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/source_context.pb.h b/src/google/protobuf/source_context.pb.h
index 22150b5e..1e5499ca 100644
--- a/src/google/protobuf/source_context.pb.h
+++ b/src/google/protobuf/source_context.pb.h
@@ -8,19 +8,21 @@
#include <google/protobuf/stubs/common.h>
-#if GOOGLE_PROTOBUF_VERSION < 3001000
+#if GOOGLE_PROTOBUF_VERSION < 3004000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3001000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3004000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
+#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
+#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
@@ -28,6 +30,24 @@
#include <google/protobuf/extension_set.h> // IWYU pragma: export
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
+
+namespace protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto {
+// Internal implementation detail -- do not use these members.
+struct LIBPROTOBUF_EXPORT TableStruct {
+ static const ::google::protobuf::internal::ParseTableField entries[];
+ static const ::google::protobuf::internal::AuxillaryParseTableField aux[];
+ static const ::google::protobuf::internal::ParseTable schema[1];
+ static const ::google::protobuf::internal::FieldMetadata field_metadata[];
+ static const ::google::protobuf::internal::SerializationTable serialization_table[];
+ static const ::google::protobuf::uint32 offsets[];
+};
+void LIBPROTOBUF_EXPORT AddDescriptors();
+void LIBPROTOBUF_EXPORT InitDefaultsSourceContextImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsSourceContext();
+inline void LIBPROTOBUF_EXPORT InitDefaults() {
+ InitDefaultsSourceContext();
+}
+} // namespace protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto
namespace google {
namespace protobuf {
class SourceContext;
@@ -35,14 +55,9 @@ class SourceContextDefaultTypeInternal;
LIBPROTOBUF_EXPORT extern SourceContextDefaultTypeInternal _SourceContext_default_instance_;
} // namespace protobuf
} // namespace google
-
namespace google {
namespace protobuf {
-// Internal implementation detail -- do not call these.
-void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fsource_5fcontext_2eproto();
-void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fsource_5fcontext_2eproto();
-
// ===================================================================
class LIBPROTOBUF_EXPORT SourceContext : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.SourceContext) */ {
@@ -56,16 +71,36 @@ class LIBPROTOBUF_EXPORT SourceContext : public ::google::protobuf::Message /* @
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ SourceContext(SourceContext&& from) noexcept
+ : SourceContext() {
+ *this = ::std::move(from);
+ }
+ inline SourceContext& operator=(SourceContext&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
static const ::google::protobuf::Descriptor* descriptor();
static const SourceContext& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const SourceContext* internal_default_instance() {
return reinterpret_cast<const SourceContext*>(
&_SourceContext_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 0;
void Swap(SourceContext* other);
+ friend void swap(SourceContext& a, SourceContext& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -86,10 +121,6 @@ class LIBPROTOBUF_EXPORT SourceContext : public ::google::protobuf::Message /* @
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
@@ -116,6 +147,9 @@ class LIBPROTOBUF_EXPORT SourceContext : public ::google::protobuf::Message /* @
static const int kFileNameFieldNumber = 1;
const ::std::string& file_name() const;
void set_file_name(const ::std::string& value);
+ #if LANG_CXX11
+ void set_file_name(::std::string&& value);
+ #endif
void set_file_name(const char* value);
void set_file_name(const char* value, size_t size);
::std::string* mutable_file_name();
@@ -128,18 +162,18 @@ class LIBPROTOBUF_EXPORT SourceContext : public ::google::protobuf::Message /* @
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
::google::protobuf::internal::ArenaStringPtr file_name_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fsource_5fcontext_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fsource_5fcontext_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fsource_5fcontext_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fsource_5fcontext_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::InitDefaultsSourceContextImpl();
};
// ===================================================================
// ===================================================================
-#if !PROTOBUF_INLINE_NOT_IN_HEADERS
+#ifdef __GNUC__
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wstrict-aliasing"
+#endif // __GNUC__
// SourceContext
// string file_name = 1;
@@ -155,7 +189,16 @@ inline void SourceContext::set_file_name(const ::std::string& value) {
file_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.SourceContext.file_name)
}
+#if LANG_CXX11
+inline void SourceContext::set_file_name(::std::string&& value) {
+
+ file_name_.SetNoArena(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.SourceContext.file_name)
+}
+#endif
inline void SourceContext::set_file_name(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
file_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.SourceContext.file_name)
@@ -186,11 +229,12 @@ inline void SourceContext::set_allocated_file_name(::std::string* file_name) {
// @@protoc_insertion_point(field_set_allocated:google.protobuf.SourceContext.file_name)
}
-#endif // !PROTOBUF_INLINE_NOT_IN_HEADERS
+#ifdef __GNUC__
+ #pragma GCC diagnostic pop
+#endif // __GNUC__
// @@protoc_insertion_point(namespace_scope)
-
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/struct.pb.cc b/src/google/protobuf/struct.pb.cc
index 8bd2f8be..fe3ba327 100644
--- a/src/google/protobuf/struct.pb.cc
+++ b/src/google/protobuf/struct.pb.cc
@@ -1,7 +1,6 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/struct.proto
-#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include <google/protobuf/struct.pb.h>
#include <algorithm>
@@ -15,80 +14,137 @@
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
+// This is a temporary google only hack
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+#include "third_party/protobuf/version.h"
+#endif
// @@protoc_insertion_point(includes)
-
namespace google {
namespace protobuf {
-class StructDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<Struct> {};
-StructDefaultTypeInternal _Struct_default_instance_;
-class ValueDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<Value> {};
-ValueDefaultTypeInternal _Value_default_instance_;
-class ListValueDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<ListValue> {};
-ListValueDefaultTypeInternal _ListValue_default_instance_;
-
-namespace {
-
-::google::protobuf::Metadata file_level_metadata[4];
-const ::google::protobuf::EnumDescriptor* file_level_enum_descriptors[1];
-struct ValueOneofInstance {
+class Struct_FieldsEntry_DoNotUseDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<Struct_FieldsEntry_DoNotUse>
+ _instance;
+} _Struct_FieldsEntry_DoNotUse_default_instance_;
+class StructDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<Struct>
+ _instance;
+} _Struct_default_instance_;
+class ValueDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<Value>
+ _instance;
int null_value_;
double number_value_;
::google::protobuf::internal::ArenaStringPtr string_value_;
bool bool_value_;
const ::google::protobuf::Struct* struct_value_;
const ::google::protobuf::ListValue* list_value_;
-} Value_default_oneof_instance_;
-
-} // namespace
-
-
-const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fstruct_2eproto() GOOGLE_ATTRIBUTE_COLD;
-const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fstruct_2eproto() {
- static const ::google::protobuf::uint32 offsets[] = {
- ~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Struct, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Struct, fields_),
- ~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Value, _internal_metadata_),
- ~0u, // no _extensions_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Value, _oneof_case_[0]),
- PROTO2_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET((&Value_default_oneof_instance_), null_value_),
- PROTO2_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET((&Value_default_oneof_instance_), number_value_),
- PROTO2_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET((&Value_default_oneof_instance_), string_value_),
- PROTO2_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET((&Value_default_oneof_instance_), bool_value_),
- PROTO2_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET((&Value_default_oneof_instance_), struct_value_),
- PROTO2_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET((&Value_default_oneof_instance_), list_value_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Value, kind_),
- ~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ListValue, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ListValue, values_),
- };
- return offsets;
+} _Value_default_instance_;
+class ListValueDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<ListValue>
+ _instance;
+} _ListValue_default_instance_;
+} // namespace protobuf
+} // namespace google
+namespace protobuf_google_2fprotobuf_2fstruct_2eproto {
+void InitDefaultsListValueImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ {
+ void* ptr = &::google::protobuf::_Struct_FieldsEntry_DoNotUse_default_instance_;
+ new (ptr) ::google::protobuf::Struct_FieldsEntry_DoNotUse();
+ }
+ {
+ void* ptr = &::google::protobuf::_Struct_default_instance_;
+ new (ptr) ::google::protobuf::Struct();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ {
+ void* ptr = &::google::protobuf::_Value_default_instance_;
+ new (ptr) ::google::protobuf::Value();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ {
+ void* ptr = &::google::protobuf::_ListValue_default_instance_;
+ new (ptr) ::google::protobuf::ListValue();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::Struct_FieldsEntry_DoNotUse::InitAsDefaultInstance();
+ ::google::protobuf::Struct::InitAsDefaultInstance();
+ ::google::protobuf::Value::InitAsDefaultInstance();
+ ::google::protobuf::ListValue::InitAsDefaultInstance();
}
-static const ::google::protobuf::internal::MigrationSchema schemas[] = {
- { 0, -1, sizeof(Struct)},
- { 5, -1, sizeof(Value)},
- { 16, -1, sizeof(ListValue)},
-};
+void InitDefaultsListValue() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsListValueImpl);
+}
-static const ::google::protobuf::internal::DefaultInstanceData file_default_instances[] = {
- {reinterpret_cast<const ::google::protobuf::Message*>(&_Struct_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_Value_default_instance_), &Value_default_oneof_instance_},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_ListValue_default_instance_), NULL},
+::google::protobuf::Metadata file_level_metadata[4];
+const ::google::protobuf::EnumDescriptor* file_level_enum_descriptors[1];
+
+const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Struct_FieldsEntry_DoNotUse, _has_bits_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Struct_FieldsEntry_DoNotUse, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Struct_FieldsEntry_DoNotUse, key_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Struct_FieldsEntry_DoNotUse, value_),
+ 0,
+ 1,
+ ~0u, // no _has_bits_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Struct, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Struct, fields_),
+ ~0u, // no _has_bits_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Value, _internal_metadata_),
+ ~0u, // no _extensions_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Value, _oneof_case_[0]),
+ ~0u, // no _weak_field_map_
+ offsetof(::google::protobuf::ValueDefaultTypeInternal, null_value_),
+ offsetof(::google::protobuf::ValueDefaultTypeInternal, number_value_),
+ offsetof(::google::protobuf::ValueDefaultTypeInternal, string_value_),
+ offsetof(::google::protobuf::ValueDefaultTypeInternal, bool_value_),
+ offsetof(::google::protobuf::ValueDefaultTypeInternal, struct_value_),
+ offsetof(::google::protobuf::ValueDefaultTypeInternal, list_value_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Value, kind_),
+ ~0u, // no _has_bits_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ListValue, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ListValue, values_),
+};
+static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+ { 0, 7, sizeof(::google::protobuf::Struct_FieldsEntry_DoNotUse)},
+ { 9, -1, sizeof(::google::protobuf::Struct)},
+ { 15, -1, sizeof(::google::protobuf::Value)},
+ { 27, -1, sizeof(::google::protobuf::ListValue)},
};
-namespace {
+static ::google::protobuf::Message const * const file_default_instances[] = {
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_Struct_FieldsEntry_DoNotUse_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_Struct_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_Value_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_ListValue_default_instance_),
+};
void protobuf_AssignDescriptors() {
- protobuf_AddDesc_google_2fprotobuf_2fstruct_2eproto();
+ AddDescriptors();
::google::protobuf::MessageFactory* factory = NULL;
AssignDescriptors(
- "google/protobuf/struct.proto", schemas, file_default_instances, protobuf_Offsets_google_2fprotobuf_2fstruct_2eproto(), factory,
+ "google/protobuf/struct.proto", schemas, file_default_instances, TableStruct::offsets, factory,
file_level_metadata, file_level_enum_descriptors, NULL);
}
@@ -97,58 +153,15 @@ void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);
}
-void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
+void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 4);
- const ::google::protobuf::Descriptor* Struct_FieldsEntry_descriptor = file_level_metadata[0].descriptor;
- ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- Struct_FieldsEntry_descriptor,
- ::google::protobuf::internal::MapEntry<
- ::std::string,
- ::google::protobuf::Value,
- ::google::protobuf::internal::WireFormatLite::TYPE_STRING,
- ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE,
- 0>::CreateDefaultInstance(
- Struct_FieldsEntry_descriptor));
-}
-
-} // namespace
-
-void protobuf_ShutdownFile_google_2fprotobuf_2fstruct_2eproto() {
- _Struct_default_instance_.Shutdown();
- delete file_level_metadata[1].reflection;
- _Value_default_instance_.Shutdown();
- delete file_level_metadata[2].reflection;
- _ListValue_default_instance_.Shutdown();
- delete file_level_metadata[3].reflection;
-}
-
-void protobuf_InitDefaults_google_2fprotobuf_2fstruct_2eproto_impl() {
- GOOGLE_PROTOBUF_VERIFY_VERSION;
-
- ::google::protobuf::internal::InitProtobufDefaults();
- _Struct_default_instance_.DefaultConstruct();
- _Value_default_instance_.DefaultConstruct();
- _ListValue_default_instance_.DefaultConstruct();
- Value_default_oneof_instance_.null_value_ = 0;
- Value_default_oneof_instance_.number_value_ = 0;
- Value_default_oneof_instance_.string_value_.UnsafeSetDefault(
- &::google::protobuf::internal::GetEmptyStringAlreadyInited());
- Value_default_oneof_instance_.bool_value_ = false;
- Value_default_oneof_instance_.struct_value_ = const_cast< ::google::protobuf::Struct*>(
- ::google::protobuf::Struct::internal_default_instance());
- Value_default_oneof_instance_.list_value_ = const_cast< ::google::protobuf::ListValue*>(
- ::google::protobuf::ListValue::internal_default_instance());
}
-void protobuf_InitDefaults_google_2fprotobuf_2fstruct_2eproto() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &protobuf_InitDefaults_google_2fprotobuf_2fstruct_2eproto_impl);
-}
-void protobuf_AddDesc_google_2fprotobuf_2fstruct_2eproto_impl() {
- protobuf_InitDefaults_google_2fprotobuf_2fstruct_2eproto();
- static const char descriptor[] = {
+void AddDescriptorsImpl() {
+ InitDefaults();
+ static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n\034google/protobuf/struct.proto\022\017google.p"
"rotobuf\"\204\001\n\006Struct\0223\n\006fields\030\001 \003(\0132#.goo"
"gle.protobuf.Struct.FieldsEntry\032E\n\013Field"
@@ -171,23 +184,24 @@ void protobuf_AddDesc_google_2fprotobuf_2fstruct_2eproto_impl() {
descriptor, 641);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"google/protobuf/struct.proto", &protobuf_RegisterTypes);
- ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_google_2fprotobuf_2fstruct_2eproto);
}
-GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AddDesc_google_2fprotobuf_2fstruct_2eproto_once_);
-void protobuf_AddDesc_google_2fprotobuf_2fstruct_2eproto() {
- ::google::protobuf::GoogleOnceInit(&protobuf_AddDesc_google_2fprotobuf_2fstruct_2eproto_once_,
- &protobuf_AddDesc_google_2fprotobuf_2fstruct_2eproto_impl);
+void AddDescriptors() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);
}
-// Force AddDescriptors() to be called at static initialization time.
-struct StaticDescriptorInitializer_google_2fprotobuf_2fstruct_2eproto {
- StaticDescriptorInitializer_google_2fprotobuf_2fstruct_2eproto() {
- protobuf_AddDesc_google_2fprotobuf_2fstruct_2eproto();
+// Force AddDescriptors() to be called at dynamic initialization time.
+struct StaticDescriptorInitializer {
+ StaticDescriptorInitializer() {
+ AddDescriptors();
}
-} static_descriptor_initializer_google_2fprotobuf_2fstruct_2eproto_;
+} static_descriptor_initializer;
+} // namespace protobuf_google_2fprotobuf_2fstruct_2eproto
+namespace google {
+namespace protobuf {
const ::google::protobuf::EnumDescriptor* NullValue_descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_enum_descriptors[0];
+ protobuf_google_2fprotobuf_2fstruct_2eproto::protobuf_AssignDescriptorsOnce();
+ return protobuf_google_2fprotobuf_2fstruct_2eproto::file_level_enum_descriptors[0];
}
bool NullValue_IsValid(int value) {
switch (value) {
@@ -201,11 +215,25 @@ bool NullValue_IsValid(int value) {
// ===================================================================
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
+Struct_FieldsEntry_DoNotUse::Struct_FieldsEntry_DoNotUse() {}
+Struct_FieldsEntry_DoNotUse::Struct_FieldsEntry_DoNotUse(::google::protobuf::Arena* arena) : SuperType(arena) {}
+void Struct_FieldsEntry_DoNotUse::MergeFrom(const Struct_FieldsEntry_DoNotUse& other) {
+ MergeFromInternal(other);
+}
+::google::protobuf::Metadata Struct_FieldsEntry_DoNotUse::GetMetadata() const {
+ ::protobuf_google_2fprotobuf_2fstruct_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fstruct_2eproto::file_level_metadata[0];
+}
+void Struct_FieldsEntry_DoNotUse::MergeFrom(
+ const ::google::protobuf::Message& other) {
+ ::google::protobuf::Message::MergeFrom(other);
+}
+
// ===================================================================
+void Struct::InitAsDefaultInstance() {
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Struct::kFieldsFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
@@ -213,7 +241,7 @@ const int Struct::kFieldsFieldNumber;
Struct::Struct()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fstruct_2eproto();
+ ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValue();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Struct)
@@ -222,9 +250,7 @@ Struct::Struct(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
fields_(arena) {
-#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
- protobuf_InitDefaults_google_2fprotobuf_2fstruct_2eproto();
-#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValue();
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Struct)
@@ -234,21 +260,11 @@ Struct::Struct(const Struct& from)
_internal_metadata_(NULL),
_cached_size_(0) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
- const ::google::protobuf::Descriptor*& Struct_FieldsEntry_descriptor = file_level_metadata[0].descriptor;
- fields_.SetAssignDescriptorCallback(
- protobuf_AssignDescriptorsOnce);
- fields_.SetEntryDescriptor(
- &Struct_FieldsEntry_descriptor);
fields_.MergeFrom(from.fields_);
// @@protoc_insertion_point(copy_constructor:google.protobuf.Struct)
}
void Struct::SharedCtor() {
- const ::google::protobuf::Descriptor*& Struct_FieldsEntry_descriptor = file_level_metadata[0].descriptor;
- fields_.SetAssignDescriptorCallback(
- protobuf_AssignDescriptorsOnce);
- fields_.SetEntryDescriptor(
- &Struct_FieldsEntry_descriptor);
_cached_size_ = 0;
}
@@ -258,11 +274,7 @@ Struct::~Struct() {
}
void Struct::SharedDtor() {
- ::google::protobuf::Arena* arena = GetArenaNoVirtual();
- if (arena != NULL) {
- return;
- }
-
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
}
void Struct::ArenaDtor(void* object) {
@@ -277,12 +289,12 @@ void Struct::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* Struct::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[1].descriptor;
+ ::protobuf_google_2fprotobuf_2fstruct_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fstruct_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const Struct& Struct::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fstruct_2eproto();
+ ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValue();
return *internal_default_instance();
}
@@ -292,7 +304,12 @@ Struct* Struct::New(::google::protobuf::Arena* arena) const {
void Struct::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Struct)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
fields_.Clear();
+ _internal_metadata_.Clear();
}
bool Struct::MergePartialFromCodedStream(
@@ -307,9 +324,10 @@ bool Struct::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// map<string, .google.protobuf.Value> fields = 1;
case 1: {
- if (tag == 10u) {
- DO_(input->IncrementRecursionDepth());
- Struct_FieldsEntry::Parser< ::google::protobuf::internal::MapField<
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
+ Struct_FieldsEntry_DoNotUse::Parser< ::google::protobuf::internal::MapField<
+ Struct_FieldsEntry_DoNotUse,
::std::string, ::google::protobuf::Value,
::google::protobuf::internal::WireFormatLite::TYPE_STRING,
::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE,
@@ -318,24 +336,22 @@ bool Struct::MergePartialFromCodedStream(
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, &parser));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- parser.key().data(), parser.key().length(),
+ parser.key().data(), static_cast<int>(parser.key().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.protobuf.Struct.FieldsEntry.key"));
} else {
goto handle_unusual;
}
- input->UnsafeDecrementRecursionDepth();
break;
}
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
- DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
+ DO_(::google::protobuf::internal::WireFormat::SkipField(
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -352,6 +368,9 @@ failure:
void Struct::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.Struct)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// map<string, .google.protobuf.Value> fields = 1;
if (!this->fields().empty()) {
typedef ::google::protobuf::Map< ::std::string, ::google::protobuf::Value >::const_pointer
@@ -361,7 +380,7 @@ void Struct::SerializeWithCachedSizes(
struct Utf8Check {
static void Check(ConstPtr p) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- p->first.data(), p->first.length(),
+ p->first.data(), static_cast<int>(p->first.length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Struct.FieldsEntry.key");
}
@@ -376,22 +395,22 @@ void Struct::SerializeWithCachedSizes(
for (::google::protobuf::Map< ::std::string, ::google::protobuf::Value >::const_iterator
it = this->fields().begin();
it != this->fields().end(); ++it, ++n) {
- items[n] = SortItem(&*it);
+ items[static_cast<ptrdiff_t>(n)] = SortItem(&*it);
}
- ::std::sort(&items[0], &items[n], Less());
- ::google::protobuf::scoped_ptr<Struct_FieldsEntry> entry;
+ ::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less());
+ ::google::protobuf::scoped_ptr<Struct_FieldsEntry_DoNotUse> entry;
for (size_type i = 0; i < n; i++) {
entry.reset(fields_.NewEntryWrapper(
- items[i]->first, items[i]->second));
+ items[static_cast<ptrdiff_t>(i)]->first, items[static_cast<ptrdiff_t>(i)]->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, *entry, output);
if (entry->GetArena() != NULL) {
entry.release();
}
- Utf8Check::Check(items[i]);
+ Utf8Check::Check(items[static_cast<ptrdiff_t>(i)]);
}
} else {
- ::google::protobuf::scoped_ptr<Struct_FieldsEntry> entry;
+ ::google::protobuf::scoped_ptr<Struct_FieldsEntry_DoNotUse> entry;
for (::google::protobuf::Map< ::std::string, ::google::protobuf::Value >::const_iterator
it = this->fields().begin();
it != this->fields().end(); ++it) {
@@ -407,6 +426,10 @@ void Struct::SerializeWithCachedSizes(
}
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ }
// @@protoc_insertion_point(serialize_end:google.protobuf.Struct)
}
@@ -414,6 +437,9 @@ void Struct::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Struct)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// map<string, .google.protobuf.Value> fields = 1;
if (!this->fields().empty()) {
typedef ::google::protobuf::Map< ::std::string, ::google::protobuf::Value >::const_pointer
@@ -423,7 +449,7 @@ void Struct::SerializeWithCachedSizes(
struct Utf8Check {
static void Check(ConstPtr p) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- p->first.data(), p->first.length(),
+ p->first.data(), static_cast<int>(p->first.length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Struct.FieldsEntry.key");
}
@@ -438,13 +464,13 @@ void Struct::SerializeWithCachedSizes(
for (::google::protobuf::Map< ::std::string, ::google::protobuf::Value >::const_iterator
it = this->fields().begin();
it != this->fields().end(); ++it, ++n) {
- items[n] = SortItem(&*it);
+ items[static_cast<ptrdiff_t>(n)] = SortItem(&*it);
}
- ::std::sort(&items[0], &items[n], Less());
- ::google::protobuf::scoped_ptr<Struct_FieldsEntry> entry;
+ ::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less());
+ ::google::protobuf::scoped_ptr<Struct_FieldsEntry_DoNotUse> entry;
for (size_type i = 0; i < n; i++) {
entry.reset(fields_.NewEntryWrapper(
- items[i]->first, items[i]->second));
+ items[static_cast<ptrdiff_t>(i)]->first, items[static_cast<ptrdiff_t>(i)]->second));
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
1, *entry, deterministic, target);
@@ -452,10 +478,10 @@ void Struct::SerializeWithCachedSizes(
if (entry->GetArena() != NULL) {
entry.release();
}
- Utf8Check::Check(items[i]);
+ Utf8Check::Check(items[static_cast<ptrdiff_t>(i)]);
}
} else {
- ::google::protobuf::scoped_ptr<Struct_FieldsEntry> entry;
+ ::google::protobuf::scoped_ptr<Struct_FieldsEntry_DoNotUse> entry;
for (::google::protobuf::Map< ::std::string, ::google::protobuf::Value >::const_iterator
it = this->fields().begin();
it != this->fields().end(); ++it) {
@@ -473,6 +499,10 @@ void Struct::SerializeWithCachedSizes(
}
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ }
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Struct)
return target;
}
@@ -481,11 +511,16 @@ size_t Struct::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.Struct)
size_t total_size = 0;
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ total_size +=
+ ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ }
// map<string, .google.protobuf.Value> fields = 1;
total_size += 1 *
::google::protobuf::internal::FromIntSize(this->fields_size());
{
- ::google::protobuf::scoped_ptr<Struct_FieldsEntry> entry;
+ ::google::protobuf::scoped_ptr<Struct_FieldsEntry_DoNotUse> entry;
for (::google::protobuf::Map< ::std::string, ::google::protobuf::Value >::const_iterator
it = this->fields().begin();
it != this->fields().end(); ++it) {
@@ -527,6 +562,9 @@ void Struct::MergeFrom(const Struct& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Struct)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
fields_.MergeFrom(from.fields_);
}
@@ -568,40 +606,61 @@ void Struct::UnsafeArenaSwap(Struct* other) {
InternalSwap(other);
}
void Struct::InternalSwap(Struct* other) {
+ using std::swap;
fields_.Swap(&other->fields_);
- std::swap(_cached_size_, other->_cached_size_);
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Struct::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[1];
+ protobuf_google_2fprotobuf_2fstruct_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fstruct_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// Struct
-// map<string, .google.protobuf.Value> fields = 1;
-int Struct::fields_size() const {
- return fields_.size();
-}
-void Struct::clear_fields() {
- fields_.Clear();
+// ===================================================================
+
+void Value::InitAsDefaultInstance() {
+ ::google::protobuf::_Value_default_instance_.null_value_ = 0;
+ ::google::protobuf::_Value_default_instance_.number_value_ = 0;
+ ::google::protobuf::_Value_default_instance_.string_value_.UnsafeSetDefault(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ ::google::protobuf::_Value_default_instance_.bool_value_ = false;
+ ::google::protobuf::_Value_default_instance_.struct_value_ = const_cast< ::google::protobuf::Struct*>(
+ ::google::protobuf::Struct::internal_default_instance());
+ ::google::protobuf::_Value_default_instance_.list_value_ = const_cast< ::google::protobuf::ListValue*>(
+ ::google::protobuf::ListValue::internal_default_instance());
}
- const ::google::protobuf::Map< ::std::string, ::google::protobuf::Value >&
-Struct::fields() const {
- // @@protoc_insertion_point(field_map:google.protobuf.Struct.fields)
- return fields_.GetMap();
+void Value::set_allocated_struct_value(::google::protobuf::Struct* struct_value) {
+ ::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
+ clear_kind();
+ if (struct_value) {
+ ::google::protobuf::Arena* submessage_arena =
+ ::google::protobuf::Arena::GetArena(struct_value);
+ if (message_arena != submessage_arena) {
+ struct_value = ::google::protobuf::internal::GetOwnedMessage(
+ message_arena, struct_value, submessage_arena);
+ }
+ set_has_struct_value();
+ kind_.struct_value_ = struct_value;
+ }
+ // @@protoc_insertion_point(field_set_allocated:google.protobuf.Value.struct_value)
}
- ::google::protobuf::Map< ::std::string, ::google::protobuf::Value >*
-Struct::mutable_fields() {
- // @@protoc_insertion_point(field_mutable_map:google.protobuf.Struct.fields)
- return fields_.MutableMap();
+void Value::set_allocated_list_value(::google::protobuf::ListValue* list_value) {
+ ::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
+ clear_kind();
+ if (list_value) {
+ ::google::protobuf::Arena* submessage_arena =
+ ::google::protobuf::Arena::GetArena(list_value);
+ if (message_arena != submessage_arena) {
+ list_value = ::google::protobuf::internal::GetOwnedMessage(
+ message_arena, list_value, submessage_arena);
+ }
+ set_has_list_value();
+ kind_.list_value_ = list_value;
+ }
+ // @@protoc_insertion_point(field_set_allocated:google.protobuf.Value.list_value)
}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
-
-// ===================================================================
-
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Value::kNullValueFieldNumber;
const int Value::kNumberValueFieldNumber;
@@ -614,7 +673,7 @@ const int Value::kListValueFieldNumber;
Value::Value()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fstruct_2eproto();
+ ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValue();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Value)
@@ -622,9 +681,7 @@ Value::Value()
Value::Value(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
-#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
- protobuf_InitDefaults_google_2fprotobuf_2fstruct_2eproto();
-#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValue();
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Value)
@@ -678,11 +735,7 @@ Value::~Value() {
}
void Value::SharedDtor() {
- ::google::protobuf::Arena* arena = GetArenaNoVirtual();
- if (arena != NULL) {
- return;
- }
-
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
if (has_kind()) {
clear_kind();
}
@@ -700,12 +753,12 @@ void Value::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* Value::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[2].descriptor;
+ ::protobuf_google_2fprotobuf_2fstruct_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fstruct_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const Value& Value::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fstruct_2eproto();
+ ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValue();
return *internal_default_instance();
}
@@ -755,7 +808,12 @@ void Value::clear_kind() {
void Value::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Value)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
clear_kind();
+ _internal_metadata_.Clear();
}
bool Value::MergePartialFromCodedStream(
@@ -770,7 +828,8 @@ bool Value::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// .google.protobuf.NullValue null_value = 1;
case 1: {
- if (tag == 8u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
int value;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
@@ -784,7 +843,8 @@ bool Value::MergePartialFromCodedStream(
// double number_value = 2;
case 2: {
- if (tag == 17u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(17u /* 17 & 0xFF */)) {
clear_kind();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
@@ -798,11 +858,12 @@ bool Value::MergePartialFromCodedStream(
// string string_value = 3;
case 3: {
- if (tag == 26u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_string_value()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->string_value().data(), this->string_value().length(),
+ this->string_value().data(), static_cast<int>(this->string_value().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.protobuf.Value.string_value"));
} else {
@@ -813,7 +874,8 @@ bool Value::MergePartialFromCodedStream(
// bool bool_value = 4;
case 4: {
- if (tag == 32u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(32u /* 32 & 0xFF */)) {
clear_kind();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
@@ -827,8 +889,9 @@ bool Value::MergePartialFromCodedStream(
// .google.protobuf.Struct struct_value = 5;
case 5: {
- if (tag == 42u) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(42u /* 42 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_struct_value()));
} else {
goto handle_unusual;
@@ -838,8 +901,9 @@ bool Value::MergePartialFromCodedStream(
// .google.protobuf.ListValue list_value = 6;
case 6: {
- if (tag == 50u) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(50u /* 50 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_list_value()));
} else {
goto handle_unusual;
@@ -849,12 +913,11 @@ bool Value::MergePartialFromCodedStream(
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
- DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
+ DO_(::google::protobuf::internal::WireFormat::SkipField(
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -871,6 +934,9 @@ failure:
void Value::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.Value)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// .google.protobuf.NullValue null_value = 1;
if (has_null_value()) {
::google::protobuf::internal::WireFormatLite::WriteEnum(
@@ -885,7 +951,7 @@ void Value::SerializeWithCachedSizes(
// string string_value = 3;
if (has_string_value()) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->string_value().data(), this->string_value().length(),
+ this->string_value().data(), static_cast<int>(this->string_value().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Value.string_value");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -909,6 +975,10 @@ void Value::SerializeWithCachedSizes(
6, *kind_.list_value_, output);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ }
// @@protoc_insertion_point(serialize_end:google.protobuf.Value)
}
@@ -916,6 +986,9 @@ void Value::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Value)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// .google.protobuf.NullValue null_value = 1;
if (has_null_value()) {
target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray(
@@ -930,7 +1003,7 @@ void Value::SerializeWithCachedSizes(
// string string_value = 3;
if (has_string_value()) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->string_value().data(), this->string_value().length(),
+ this->string_value().data(), static_cast<int>(this->string_value().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Value.string_value");
target =
@@ -946,17 +1019,21 @@ void Value::SerializeWithCachedSizes(
// .google.protobuf.Struct struct_value = 5;
if (has_struct_value()) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 5, *kind_.struct_value_, false, target);
+ InternalWriteMessageToArray(
+ 5, *kind_.struct_value_, deterministic, target);
}
// .google.protobuf.ListValue list_value = 6;
if (has_list_value()) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 6, *kind_.list_value_, false, target);
+ InternalWriteMessageToArray(
+ 6, *kind_.list_value_, deterministic, target);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ }
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Value)
return target;
}
@@ -965,6 +1042,11 @@ size_t Value::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.Value)
size_t total_size = 0;
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ total_size +=
+ ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ }
switch (kind_case()) {
// .google.protobuf.NullValue null_value = 1;
case kNullValue: {
@@ -992,14 +1074,14 @@ size_t Value::ByteSizeLong() const {
// .google.protobuf.Struct struct_value = 5;
case kStructValue: {
total_size += 1 +
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
*kind_.struct_value_);
break;
}
// .google.protobuf.ListValue list_value = 6;
case kListValue: {
total_size += 1 +
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
*kind_.list_value_);
break;
}
@@ -1033,6 +1115,9 @@ void Value::MergeFrom(const Value& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Value)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
switch (from.kind_case()) {
case kNullValue: {
set_null_value(from.null_value());
@@ -1102,404 +1187,23 @@ void Value::UnsafeArenaSwap(Value* other) {
InternalSwap(other);
}
void Value::InternalSwap(Value* other) {
- std::swap(kind_, other->kind_);
- std::swap(_oneof_case_[0], other->_oneof_case_[0]);
- std::swap(_cached_size_, other->_cached_size_);
+ using std::swap;
+ swap(kind_, other->kind_);
+ swap(_oneof_case_[0], other->_oneof_case_[0]);
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Value::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[2];
+ protobuf_google_2fprotobuf_2fstruct_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fstruct_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// Value
-
-// .google.protobuf.NullValue null_value = 1;
-bool Value::has_null_value() const {
- return kind_case() == kNullValue;
-}
-void Value::set_has_null_value() {
- _oneof_case_[0] = kNullValue;
-}
-void Value::clear_null_value() {
- if (has_null_value()) {
- kind_.null_value_ = 0;
- clear_has_kind();
- }
-}
-::google::protobuf::NullValue Value::null_value() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Value.null_value)
- if (has_null_value()) {
- return static_cast< ::google::protobuf::NullValue >(kind_.null_value_);
- }
- return static_cast< ::google::protobuf::NullValue >(0);
-}
-void Value::set_null_value(::google::protobuf::NullValue value) {
- if (!has_null_value()) {
- clear_kind();
- set_has_null_value();
- }
- kind_.null_value_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.Value.null_value)
-}
-
-// double number_value = 2;
-bool Value::has_number_value() const {
- return kind_case() == kNumberValue;
-}
-void Value::set_has_number_value() {
- _oneof_case_[0] = kNumberValue;
-}
-void Value::clear_number_value() {
- if (has_number_value()) {
- kind_.number_value_ = 0;
- clear_has_kind();
- }
-}
-double Value::number_value() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Value.number_value)
- if (has_number_value()) {
- return kind_.number_value_;
- }
- return 0;
-}
-void Value::set_number_value(double value) {
- if (!has_number_value()) {
- clear_kind();
- set_has_number_value();
- }
- kind_.number_value_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.Value.number_value)
-}
-
-// string string_value = 3;
-bool Value::has_string_value() const {
- return kind_case() == kStringValue;
-}
-void Value::set_has_string_value() {
- _oneof_case_[0] = kStringValue;
-}
-void Value::clear_string_value() {
- if (has_string_value()) {
- kind_.string_value_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- clear_has_kind();
- }
-}
-const ::std::string& Value::string_value() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Value.string_value)
- if (has_string_value()) {
- return kind_.string_value_.Get();
- }
- return *&::google::protobuf::internal::GetEmptyStringAlreadyInited();
-}
-void Value::set_string_value(const ::std::string& value) {
- if (!has_string_value()) {
- clear_kind();
- set_has_string_value();
- kind_.string_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- }
- kind_.string_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value,
- GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set:google.protobuf.Value.string_value)
-}
-void Value::set_string_value(const char* value) {
- if (!has_string_value()) {
- clear_kind();
- set_has_string_value();
- kind_.string_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- }
- kind_.string_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(value), GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set_char:google.protobuf.Value.string_value)
-}
-void Value::set_string_value(const char* value,
- size_t size) {
- if (!has_string_value()) {
- clear_kind();
- set_has_string_value();
- kind_.string_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- }
- kind_.string_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size),
- GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.Value.string_value)
-}
-::std::string* Value::mutable_string_value() {
- if (!has_string_value()) {
- clear_kind();
- set_has_string_value();
- kind_.string_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- }
- return kind_.string_value_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- // @@protoc_insertion_point(field_mutable:google.protobuf.Value.string_value)
-}
-::std::string* Value::release_string_value() {
- // @@protoc_insertion_point(field_release:google.protobuf.Value.string_value)
- if (has_string_value()) {
- clear_has_kind();
- return kind_.string_value_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- } else {
- return NULL;
- }
-}
-::std::string* Value::unsafe_arena_release_string_value() {
- // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Value.string_value)
- GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
- if (has_string_value()) {
- clear_has_kind();
- return kind_.string_value_.UnsafeArenaRelease(
- &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- } else {
- return NULL;
- }
-}
-void Value::set_allocated_string_value(::std::string* string_value) {
- if (!has_string_value()) {
- kind_.string_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- }
- clear_kind();
- if (string_value != NULL) {
- set_has_string_value();
- kind_.string_value_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), string_value,
- GetArenaNoVirtual());
- }
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.Value.string_value)
-}
-void Value::unsafe_arena_set_allocated_string_value(::std::string* string_value) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
- if (!has_string_value()) {
- kind_.string_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- }
- clear_kind();
- if (string_value) {
- set_has_string_value();
- kind_.string_value_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), string_value, GetArenaNoVirtual());
- }
- // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Value.string_value)
-}
-
-// bool bool_value = 4;
-bool Value::has_bool_value() const {
- return kind_case() == kBoolValue;
-}
-void Value::set_has_bool_value() {
- _oneof_case_[0] = kBoolValue;
-}
-void Value::clear_bool_value() {
- if (has_bool_value()) {
- kind_.bool_value_ = false;
- clear_has_kind();
- }
-}
-bool Value::bool_value() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Value.bool_value)
- if (has_bool_value()) {
- return kind_.bool_value_;
- }
- return false;
-}
-void Value::set_bool_value(bool value) {
- if (!has_bool_value()) {
- clear_kind();
- set_has_bool_value();
- }
- kind_.bool_value_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.Value.bool_value)
-}
-
-// .google.protobuf.Struct struct_value = 5;
-bool Value::has_struct_value() const {
- return kind_case() == kStructValue;
-}
-void Value::set_has_struct_value() {
- _oneof_case_[0] = kStructValue;
-}
-void Value::clear_struct_value() {
- if (has_struct_value()) {
- if (GetArenaNoVirtual() == NULL) {
- delete kind_.struct_value_;
- }
- clear_has_kind();
- }
-}
- const ::google::protobuf::Struct& Value::struct_value() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Value.struct_value)
- return has_struct_value()
- ? *kind_.struct_value_
- : ::google::protobuf::Struct::default_instance();
-}
-::google::protobuf::Struct* Value::mutable_struct_value() {
- if (!has_struct_value()) {
- clear_kind();
- set_has_struct_value();
- kind_.struct_value_ =
- ::google::protobuf::Arena::CreateMessage< ::google::protobuf::Struct >(
- GetArenaNoVirtual());
- }
- // @@protoc_insertion_point(field_mutable:google.protobuf.Value.struct_value)
- return kind_.struct_value_;
-}
-::google::protobuf::Struct* Value::release_struct_value() {
- // @@protoc_insertion_point(field_release:google.protobuf.Value.struct_value)
- if (has_struct_value()) {
- clear_has_kind();
- if (GetArenaNoVirtual() != NULL) {
- ::google::protobuf::Struct* temp = new ::google::protobuf::Struct(*kind_.struct_value_);
- kind_.struct_value_ = NULL;
- return temp;
- } else {
- ::google::protobuf::Struct* temp = kind_.struct_value_;
- kind_.struct_value_ = NULL;
- return temp;
- }
- } else {
- return NULL;
- }
-}
-void Value::set_allocated_struct_value(::google::protobuf::Struct* struct_value) {
- clear_kind();
- if (struct_value) {
- if (GetArenaNoVirtual() != NULL &&
- ::google::protobuf::Arena::GetArena(struct_value) == NULL) {
- GetArenaNoVirtual()->Own(struct_value);
- } else if (GetArenaNoVirtual() !=
- ::google::protobuf::Arena::GetArena(struct_value)) {
- ::google::protobuf::Struct* new_struct_value =
- ::google::protobuf::Arena::CreateMessage< ::google::protobuf::Struct >(
- GetArenaNoVirtual());
- new_struct_value->CopyFrom(*struct_value);
- struct_value = new_struct_value;
- }
- set_has_struct_value();
- kind_.struct_value_ = struct_value;
- }
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.Value.struct_value)
-}
- ::google::protobuf::Struct* Value::unsafe_arena_release_struct_value() {
- // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Value.struct_value)
- if (has_struct_value()) {
- clear_has_kind();
- ::google::protobuf::Struct* temp = kind_.struct_value_;
- kind_.struct_value_ = NULL;
- return temp;
- } else {
- return NULL;
- }
-}
- void Value::unsafe_arena_set_allocated_struct_value(::google::protobuf::Struct* struct_value) {
- clear_kind();
- if (struct_value) {
- set_has_struct_value();
- kind_.struct_value_ = struct_value;
- }
- // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Value.struct_value)
-}
-
-// .google.protobuf.ListValue list_value = 6;
-bool Value::has_list_value() const {
- return kind_case() == kListValue;
-}
-void Value::set_has_list_value() {
- _oneof_case_[0] = kListValue;
-}
-void Value::clear_list_value() {
- if (has_list_value()) {
- if (GetArenaNoVirtual() == NULL) {
- delete kind_.list_value_;
- }
- clear_has_kind();
- }
-}
- const ::google::protobuf::ListValue& Value::list_value() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Value.list_value)
- return has_list_value()
- ? *kind_.list_value_
- : ::google::protobuf::ListValue::default_instance();
-}
-::google::protobuf::ListValue* Value::mutable_list_value() {
- if (!has_list_value()) {
- clear_kind();
- set_has_list_value();
- kind_.list_value_ =
- ::google::protobuf::Arena::CreateMessage< ::google::protobuf::ListValue >(
- GetArenaNoVirtual());
- }
- // @@protoc_insertion_point(field_mutable:google.protobuf.Value.list_value)
- return kind_.list_value_;
-}
-::google::protobuf::ListValue* Value::release_list_value() {
- // @@protoc_insertion_point(field_release:google.protobuf.Value.list_value)
- if (has_list_value()) {
- clear_has_kind();
- if (GetArenaNoVirtual() != NULL) {
- ::google::protobuf::ListValue* temp = new ::google::protobuf::ListValue(*kind_.list_value_);
- kind_.list_value_ = NULL;
- return temp;
- } else {
- ::google::protobuf::ListValue* temp = kind_.list_value_;
- kind_.list_value_ = NULL;
- return temp;
- }
- } else {
- return NULL;
- }
-}
-void Value::set_allocated_list_value(::google::protobuf::ListValue* list_value) {
- clear_kind();
- if (list_value) {
- if (GetArenaNoVirtual() != NULL &&
- ::google::protobuf::Arena::GetArena(list_value) == NULL) {
- GetArenaNoVirtual()->Own(list_value);
- } else if (GetArenaNoVirtual() !=
- ::google::protobuf::Arena::GetArena(list_value)) {
- ::google::protobuf::ListValue* new_list_value =
- ::google::protobuf::Arena::CreateMessage< ::google::protobuf::ListValue >(
- GetArenaNoVirtual());
- new_list_value->CopyFrom(*list_value);
- list_value = new_list_value;
- }
- set_has_list_value();
- kind_.list_value_ = list_value;
- }
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.Value.list_value)
-}
- ::google::protobuf::ListValue* Value::unsafe_arena_release_list_value() {
- // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Value.list_value)
- if (has_list_value()) {
- clear_has_kind();
- ::google::protobuf::ListValue* temp = kind_.list_value_;
- kind_.list_value_ = NULL;
- return temp;
- } else {
- return NULL;
- }
-}
- void Value::unsafe_arena_set_allocated_list_value(::google::protobuf::ListValue* list_value) {
- clear_kind();
- if (list_value) {
- set_has_list_value();
- kind_.list_value_ = list_value;
- }
- // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Value.list_value)
-}
-
-bool Value::has_kind() const {
- return kind_case() != KIND_NOT_SET;
-}
-void Value::clear_has_kind() {
- _oneof_case_[0] = KIND_NOT_SET;
-}
-Value::KindCase Value::kind_case() const {
- return Value::KindCase(_oneof_case_[0]);
-}
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
+void ListValue::InitAsDefaultInstance() {
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int ListValue::kValuesFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
@@ -1507,7 +1211,7 @@ const int ListValue::kValuesFieldNumber;
ListValue::ListValue()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fstruct_2eproto();
+ ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValue();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.ListValue)
@@ -1516,9 +1220,7 @@ ListValue::ListValue(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
values_(arena) {
-#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
- protobuf_InitDefaults_google_2fprotobuf_2fstruct_2eproto();
-#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValue();
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.ListValue)
@@ -1542,11 +1244,7 @@ ListValue::~ListValue() {
}
void ListValue::SharedDtor() {
- ::google::protobuf::Arena* arena = GetArenaNoVirtual();
- if (arena != NULL) {
- return;
- }
-
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
}
void ListValue::ArenaDtor(void* object) {
@@ -1561,12 +1259,12 @@ void ListValue::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* ListValue::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[3].descriptor;
+ ::protobuf_google_2fprotobuf_2fstruct_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fstruct_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const ListValue& ListValue::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fstruct_2eproto();
+ ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValue();
return *internal_default_instance();
}
@@ -1576,7 +1274,12 @@ ListValue* ListValue::New(::google::protobuf::Arena* arena) const {
void ListValue::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.ListValue)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
values_.Clear();
+ _internal_metadata_.Clear();
}
bool ListValue::MergePartialFromCodedStream(
@@ -1591,25 +1294,22 @@ bool ListValue::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated .google.protobuf.Value values = 1;
case 1: {
- if (tag == 10u) {
- DO_(input->IncrementRecursionDepth());
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
- input, add_values()));
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_values()));
} else {
goto handle_unusual;
}
- input->UnsafeDecrementRecursionDepth();
break;
}
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
- DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
+ DO_(::google::protobuf::internal::WireFormat::SkipField(
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -1626,12 +1326,20 @@ failure:
void ListValue::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.ListValue)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// repeated .google.protobuf.Value values = 1;
- for (unsigned int i = 0, n = this->values_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->values_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 1, this->values(i), output);
+ 1, this->values(static_cast<int>(i)), output);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ }
// @@protoc_insertion_point(serialize_end:google.protobuf.ListValue)
}
@@ -1639,13 +1347,21 @@ void ListValue::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.ListValue)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// repeated .google.protobuf.Value values = 1;
- for (unsigned int i = 0, n = this->values_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->values_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 1, this->values(i), false, target);
+ InternalWriteMessageToArray(
+ 1, this->values(static_cast<int>(i)), deterministic, target);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ }
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.ListValue)
return target;
}
@@ -1654,14 +1370,19 @@ size_t ListValue::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.ListValue)
size_t total_size = 0;
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ total_size +=
+ ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ }
// repeated .google.protobuf.Value values = 1;
{
- unsigned int count = this->values_size();
+ unsigned int count = static_cast<unsigned int>(this->values_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->values(i));
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->values(static_cast<int>(i)));
}
}
@@ -1691,6 +1412,9 @@ void ListValue::MergeFrom(const ListValue& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.ListValue)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
values_.MergeFrom(from.values_);
}
@@ -1732,52 +1456,19 @@ void ListValue::UnsafeArenaSwap(ListValue* other) {
InternalSwap(other);
}
void ListValue::InternalSwap(ListValue* other) {
- values_.UnsafeArenaSwap(&other->values_);
- std::swap(_cached_size_, other->_cached_size_);
+ using std::swap;
+ values_.InternalSwap(&other->values_);
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata ListValue::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[3];
+ protobuf_google_2fprotobuf_2fstruct_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fstruct_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// ListValue
-
-// repeated .google.protobuf.Value values = 1;
-int ListValue::values_size() const {
- return values_.size();
-}
-void ListValue::clear_values() {
- values_.Clear();
-}
-const ::google::protobuf::Value& ListValue::values(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.ListValue.values)
- return values_.Get(index);
-}
-::google::protobuf::Value* ListValue::mutable_values(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.ListValue.values)
- return values_.Mutable(index);
-}
-::google::protobuf::Value* ListValue::add_values() {
- // @@protoc_insertion_point(field_add:google.protobuf.ListValue.values)
- return values_.Add();
-}
-::google::protobuf::RepeatedPtrField< ::google::protobuf::Value >*
-ListValue::mutable_values() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.ListValue.values)
- return &values_;
-}
-const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Value >&
-ListValue::values() const {
- // @@protoc_insertion_point(field_list:google.protobuf.ListValue.values)
- return values_;
-}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
-
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/struct.pb.h b/src/google/protobuf/struct.pb.h
index 1037d84c..83b7da6d 100644
--- a/src/google/protobuf/struct.pb.h
+++ b/src/google/protobuf/struct.pb.h
@@ -8,29 +8,50 @@
#include <google/protobuf/stubs/common.h>
-#if GOOGLE_PROTOBUF_VERSION < 3001000
+#if GOOGLE_PROTOBUF_VERSION < 3004000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3001000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3004000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
+#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
+#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
#include <google/protobuf/extension_set.h> // IWYU pragma: export
-#include <google/protobuf/map.h>
+#include <google/protobuf/map.h> // IWYU pragma: export
+#include <google/protobuf/map_entry.h>
#include <google/protobuf/map_field_inl.h>
#include <google/protobuf/generated_enum_reflection.h>
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
+
+namespace protobuf_google_2fprotobuf_2fstruct_2eproto {
+// Internal implementation detail -- do not use these members.
+struct LIBPROTOBUF_EXPORT TableStruct {
+ static const ::google::protobuf::internal::ParseTableField entries[];
+ static const ::google::protobuf::internal::AuxillaryParseTableField aux[];
+ static const ::google::protobuf::internal::ParseTable schema[4];
+ static const ::google::protobuf::internal::FieldMetadata field_metadata[];
+ static const ::google::protobuf::internal::SerializationTable serialization_table[];
+ static const ::google::protobuf::uint32 offsets[];
+};
+void LIBPROTOBUF_EXPORT AddDescriptors();
+void LIBPROTOBUF_EXPORT InitDefaultsListValueImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsListValue();
+inline void LIBPROTOBUF_EXPORT InitDefaults() {
+ InitDefaultsListValue();
+}
+} // namespace protobuf_google_2fprotobuf_2fstruct_2eproto
namespace google {
namespace protobuf {
class ListValue;
@@ -39,19 +60,17 @@ LIBPROTOBUF_EXPORT extern ListValueDefaultTypeInternal _ListValue_default_instan
class Struct;
class StructDefaultTypeInternal;
LIBPROTOBUF_EXPORT extern StructDefaultTypeInternal _Struct_default_instance_;
+class Struct_FieldsEntry_DoNotUse;
+class Struct_FieldsEntry_DoNotUseDefaultTypeInternal;
+LIBPROTOBUF_EXPORT extern Struct_FieldsEntry_DoNotUseDefaultTypeInternal _Struct_FieldsEntry_DoNotUse_default_instance_;
class Value;
class ValueDefaultTypeInternal;
LIBPROTOBUF_EXPORT extern ValueDefaultTypeInternal _Value_default_instance_;
} // namespace protobuf
} // namespace google
-
namespace google {
namespace protobuf {
-// Internal implementation detail -- do not call these.
-void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fstruct_2eproto();
-void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fstruct_2eproto();
-
enum NullValue {
NULL_VALUE = 0,
NullValue_INT_MIN_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32min,
@@ -74,6 +93,24 @@ inline bool NullValue_Parse(
}
// ===================================================================
+class Struct_FieldsEntry_DoNotUse : public ::google::protobuf::internal::MapEntry<Struct_FieldsEntry_DoNotUse,
+ ::std::string, ::google::protobuf::Value,
+ ::google::protobuf::internal::WireFormatLite::TYPE_STRING,
+ ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE,
+ 0 > {
+public:
+ typedef ::google::protobuf::internal::MapEntry<Struct_FieldsEntry_DoNotUse,
+ ::std::string, ::google::protobuf::Value,
+ ::google::protobuf::internal::WireFormatLite::TYPE_STRING,
+ ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE,
+ 0 > SuperType;
+ Struct_FieldsEntry_DoNotUse();
+ Struct_FieldsEntry_DoNotUse(::google::protobuf::Arena* arena);
+ void MergeFrom(const Struct_FieldsEntry_DoNotUse& other);
+ static const Struct_FieldsEntry_DoNotUse* internal_default_instance() { return reinterpret_cast<const Struct_FieldsEntry_DoNotUse*>(&_Struct_FieldsEntry_DoNotUse_default_instance_); }
+ void MergeFrom(const ::google::protobuf::Message& other) PROTOBUF_FINAL;
+ ::google::protobuf::Metadata GetMetadata() const;
+};
// -------------------------------------------------------------------
@@ -88,7 +125,21 @@ class LIBPROTOBUF_EXPORT Struct : public ::google::protobuf::Message /* @@protoc
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ Struct(Struct&& from) noexcept
+ : Struct() {
+ *this = ::std::move(from);
+ }
+ inline Struct& operator=(Struct&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
return GetArenaNoVirtual();
}
@@ -98,13 +149,19 @@ class LIBPROTOBUF_EXPORT Struct : public ::google::protobuf::Message /* @@protoc
static const ::google::protobuf::Descriptor* descriptor();
static const Struct& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const Struct* internal_default_instance() {
return reinterpret_cast<const Struct*>(
&_Struct_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 1;
void UnsafeArenaSwap(Struct* other);
void Swap(Struct* other);
+ friend void swap(Struct& a, Struct& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -125,10 +182,6 @@ class LIBPROTOBUF_EXPORT Struct : public ::google::protobuf::Message /* @@protoc
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
@@ -169,26 +222,18 @@ class LIBPROTOBUF_EXPORT Struct : public ::google::protobuf::Message /* @@protoc
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- friend class ::google::protobuf::Arena;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
- typedef ::google::protobuf::internal::MapEntryLite<
- ::std::string, ::google::protobuf::Value,
- ::google::protobuf::internal::WireFormatLite::TYPE_STRING,
- ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE,
- 0 >
- Struct_FieldsEntry;
::google::protobuf::internal::MapField<
+ Struct_FieldsEntry_DoNotUse,
::std::string, ::google::protobuf::Value,
::google::protobuf::internal::WireFormatLite::TYPE_STRING,
::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE,
0 > fields_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fstruct_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fstruct_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fstruct_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fstruct_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fstruct_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValueImpl();
};
// -------------------------------------------------------------------
@@ -203,7 +248,21 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ Value(Value&& from) noexcept
+ : Value() {
+ *this = ::std::move(from);
+ }
+ inline Value& operator=(Value&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
return GetArenaNoVirtual();
}
@@ -223,13 +282,19 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_
KIND_NOT_SET = 0,
};
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const Value* internal_default_instance() {
return reinterpret_cast<const Value*>(
&_Value_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 2;
void UnsafeArenaSwap(Value* other);
void Swap(Value* other);
+ friend void swap(Value& a, Value& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -250,10 +315,6 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
@@ -306,12 +367,21 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_
static const int kStringValueFieldNumber = 3;
const ::std::string& string_value() const;
void set_string_value(const ::std::string& value);
+ #if LANG_CXX11
+ void set_string_value(::std::string&& value);
+ #endif
void set_string_value(const char* value);
void set_string_value(const char* value, size_t size);
::std::string* mutable_string_value();
::std::string* release_string_value();
void set_allocated_string_value(::std::string* string_value);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
::std::string* unsafe_arena_release_string_value();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
void unsafe_arena_set_allocated_string_value(
::std::string* string_value);
@@ -330,17 +400,14 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_
static const int kStructValueFieldNumber = 5;
private:
void _slow_mutable_struct_value();
- void _slow_set_allocated_struct_value(
- ::google::protobuf::Arena* message_arena, ::google::protobuf::Struct** struct_value);
- ::google::protobuf::Struct* _slow_release_struct_value();
public:
const ::google::protobuf::Struct& struct_value() const;
- ::google::protobuf::Struct* mutable_struct_value();
::google::protobuf::Struct* release_struct_value();
+ ::google::protobuf::Struct* mutable_struct_value();
void set_allocated_struct_value(::google::protobuf::Struct* struct_value);
- ::google::protobuf::Struct* unsafe_arena_release_struct_value();
void unsafe_arena_set_allocated_struct_value(
::google::protobuf::Struct* struct_value);
+ ::google::protobuf::Struct* unsafe_arena_release_struct_value();
// .google.protobuf.ListValue list_value = 6;
bool has_list_value() const;
@@ -348,17 +415,14 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_
static const int kListValueFieldNumber = 6;
private:
void _slow_mutable_list_value();
- void _slow_set_allocated_list_value(
- ::google::protobuf::Arena* message_arena, ::google::protobuf::ListValue** list_value);
- ::google::protobuf::ListValue* _slow_release_list_value();
public:
const ::google::protobuf::ListValue& list_value() const;
- ::google::protobuf::ListValue* mutable_list_value();
::google::protobuf::ListValue* release_list_value();
+ ::google::protobuf::ListValue* mutable_list_value();
void set_allocated_list_value(::google::protobuf::ListValue* list_value);
- ::google::protobuf::ListValue* unsafe_arena_release_list_value();
void unsafe_arena_set_allocated_list_value(
::google::protobuf::ListValue* list_value);
+ ::google::protobuf::ListValue* unsafe_arena_release_list_value();
KindCase kind_case() const;
// @@protoc_insertion_point(class_scope:google.protobuf.Value)
@@ -375,7 +439,7 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_
inline void clear_has_kind();
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- friend class ::google::protobuf::Arena;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
union KindUnion {
@@ -390,11 +454,8 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_
mutable int _cached_size_;
::google::protobuf::uint32 _oneof_case_[1];
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fstruct_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fstruct_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fstruct_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fstruct_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fstruct_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValueImpl();
};
// -------------------------------------------------------------------
@@ -409,7 +470,21 @@ class LIBPROTOBUF_EXPORT ListValue : public ::google::protobuf::Message /* @@pro
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ ListValue(ListValue&& from) noexcept
+ : ListValue() {
+ *this = ::std::move(from);
+ }
+ inline ListValue& operator=(ListValue&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
return GetArenaNoVirtual();
}
@@ -419,13 +494,19 @@ class LIBPROTOBUF_EXPORT ListValue : public ::google::protobuf::Message /* @@pro
static const ::google::protobuf::Descriptor* descriptor();
static const ListValue& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const ListValue* internal_default_instance() {
return reinterpret_cast<const ListValue*>(
&_ListValue_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 3;
void UnsafeArenaSwap(ListValue* other);
void Swap(ListValue* other);
+ friend void swap(ListValue& a, ListValue& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -446,10 +527,6 @@ class LIBPROTOBUF_EXPORT ListValue : public ::google::protobuf::Message /* @@pro
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
@@ -492,23 +569,23 @@ class LIBPROTOBUF_EXPORT ListValue : public ::google::protobuf::Message /* @@pro
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- friend class ::google::protobuf::Arena;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::Value > values_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fstruct_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fstruct_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fstruct_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fstruct_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fstruct_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValueImpl();
};
// ===================================================================
// ===================================================================
-#if !PROTOBUF_INLINE_NOT_IN_HEADERS
+#ifdef __GNUC__
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wstrict-aliasing"
+#endif // __GNUC__
// -------------------------------------------------------------------
// Struct
@@ -624,7 +701,21 @@ inline void Value::set_string_value(const ::std::string& value) {
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.Value.string_value)
}
+#if LANG_CXX11
+inline void Value::set_string_value(::std::string&& value) {
+ // @@protoc_insertion_point(field_set:google.protobuf.Value.string_value)
+ if (!has_string_value()) {
+ clear_kind();
+ set_has_string_value();
+ kind_.string_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ }
+ kind_.string_value_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.Value.string_value)
+}
+#endif
inline void Value::set_string_value(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
if (!has_string_value()) {
clear_kind();
set_has_string_value();
@@ -641,7 +732,8 @@ inline void Value::set_string_value(const char* value,
set_has_string_value();
kind_.string_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- kind_.string_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ kind_.string_value_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
reinterpret_cast<const char*>(value), size),
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Value.string_value)
@@ -666,17 +758,6 @@ inline ::std::string* Value::release_string_value() {
return NULL;
}
}
-inline ::std::string* Value::unsafe_arena_release_string_value() {
- // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Value.string_value)
- GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
- if (has_string_value()) {
- clear_has_kind();
- return kind_.string_value_.UnsafeArenaRelease(
- &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- } else {
- return NULL;
- }
-}
inline void Value::set_allocated_string_value(::std::string* string_value) {
if (!has_string_value()) {
kind_.string_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
@@ -689,6 +770,17 @@ inline void Value::set_allocated_string_value(::std::string* string_value) {
}
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Value.string_value)
}
+inline ::std::string* Value::unsafe_arena_release_string_value() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Value.string_value)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (has_string_value()) {
+ clear_has_kind();
+ return kind_.string_value_.UnsafeArenaRelease(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ } else {
+ return NULL;
+ }
+}
inline void Value::unsafe_arena_set_allocated_string_value(::std::string* string_value) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
if (!has_string_value()) {
@@ -746,60 +838,27 @@ inline void Value::clear_struct_value() {
clear_has_kind();
}
}
-inline const ::google::protobuf::Struct& Value::struct_value() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Value.struct_value)
- return has_struct_value()
- ? *kind_.struct_value_
- : ::google::protobuf::Struct::default_instance();
-}
-inline ::google::protobuf::Struct* Value::mutable_struct_value() {
- if (!has_struct_value()) {
- clear_kind();
- set_has_struct_value();
- kind_.struct_value_ =
- ::google::protobuf::Arena::CreateMessage< ::google::protobuf::Struct >(
- GetArenaNoVirtual());
- }
- // @@protoc_insertion_point(field_mutable:google.protobuf.Value.struct_value)
- return kind_.struct_value_;
-}
inline ::google::protobuf::Struct* Value::release_struct_value() {
// @@protoc_insertion_point(field_release:google.protobuf.Value.struct_value)
if (has_struct_value()) {
clear_has_kind();
- if (GetArenaNoVirtual() != NULL) {
- ::google::protobuf::Struct* temp = new ::google::protobuf::Struct(*kind_.struct_value_);
- kind_.struct_value_ = NULL;
- return temp;
- } else {
::google::protobuf::Struct* temp = kind_.struct_value_;
- kind_.struct_value_ = NULL;
- return temp;
+ if (GetArenaNoVirtual() != NULL) {
+ temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL);
}
+ kind_.struct_value_ = NULL;
+ return temp;
} else {
return NULL;
}
}
-inline void Value::set_allocated_struct_value(::google::protobuf::Struct* struct_value) {
- clear_kind();
- if (struct_value) {
- if (GetArenaNoVirtual() != NULL &&
- ::google::protobuf::Arena::GetArena(struct_value) == NULL) {
- GetArenaNoVirtual()->Own(struct_value);
- } else if (GetArenaNoVirtual() !=
- ::google::protobuf::Arena::GetArena(struct_value)) {
- ::google::protobuf::Struct* new_struct_value =
- ::google::protobuf::Arena::CreateMessage< ::google::protobuf::Struct >(
- GetArenaNoVirtual());
- new_struct_value->CopyFrom(*struct_value);
- struct_value = new_struct_value;
- }
- set_has_struct_value();
- kind_.struct_value_ = struct_value;
- }
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.Value.struct_value)
+inline const ::google::protobuf::Struct& Value::struct_value() const {
+ // @@protoc_insertion_point(field_get:google.protobuf.Value.struct_value)
+ return has_struct_value()
+ ? *kind_.struct_value_
+ : *reinterpret_cast< ::google::protobuf::Struct*>(&::google::protobuf::_Struct_default_instance_);
}
-inline ::google::protobuf::Struct* Value::unsafe_arena_release_struct_value() {
+inline ::google::protobuf::Struct* Value::unsafe_arena_release_struct_value() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Value.struct_value)
if (has_struct_value()) {
clear_has_kind();
@@ -810,7 +869,7 @@ inline ::google::protobuf::Struct* Value::unsafe_arena_release_struct_value() {
return NULL;
}
}
-inline void Value::unsafe_arena_set_allocated_struct_value(::google::protobuf::Struct* struct_value) {
+inline void Value::unsafe_arena_set_allocated_struct_value(::google::protobuf::Struct* struct_value) {
clear_kind();
if (struct_value) {
set_has_struct_value();
@@ -818,6 +877,17 @@ inline void Value::unsafe_arena_set_allocated_struct_value(::google::protobuf::
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Value.struct_value)
}
+inline ::google::protobuf::Struct* Value::mutable_struct_value() {
+ if (!has_struct_value()) {
+ clear_kind();
+ set_has_struct_value();
+ kind_.struct_value_ =
+ ::google::protobuf::Arena::CreateMessage< ::google::protobuf::Struct >(
+ GetArenaNoVirtual());
+ }
+ // @@protoc_insertion_point(field_mutable:google.protobuf.Value.struct_value)
+ return kind_.struct_value_;
+}
// .google.protobuf.ListValue list_value = 6;
inline bool Value::has_list_value() const {
@@ -834,60 +904,27 @@ inline void Value::clear_list_value() {
clear_has_kind();
}
}
-inline const ::google::protobuf::ListValue& Value::list_value() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Value.list_value)
- return has_list_value()
- ? *kind_.list_value_
- : ::google::protobuf::ListValue::default_instance();
-}
-inline ::google::protobuf::ListValue* Value::mutable_list_value() {
- if (!has_list_value()) {
- clear_kind();
- set_has_list_value();
- kind_.list_value_ =
- ::google::protobuf::Arena::CreateMessage< ::google::protobuf::ListValue >(
- GetArenaNoVirtual());
- }
- // @@protoc_insertion_point(field_mutable:google.protobuf.Value.list_value)
- return kind_.list_value_;
-}
inline ::google::protobuf::ListValue* Value::release_list_value() {
// @@protoc_insertion_point(field_release:google.protobuf.Value.list_value)
if (has_list_value()) {
clear_has_kind();
- if (GetArenaNoVirtual() != NULL) {
- ::google::protobuf::ListValue* temp = new ::google::protobuf::ListValue(*kind_.list_value_);
- kind_.list_value_ = NULL;
- return temp;
- } else {
::google::protobuf::ListValue* temp = kind_.list_value_;
- kind_.list_value_ = NULL;
- return temp;
+ if (GetArenaNoVirtual() != NULL) {
+ temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL);
}
+ kind_.list_value_ = NULL;
+ return temp;
} else {
return NULL;
}
}
-inline void Value::set_allocated_list_value(::google::protobuf::ListValue* list_value) {
- clear_kind();
- if (list_value) {
- if (GetArenaNoVirtual() != NULL &&
- ::google::protobuf::Arena::GetArena(list_value) == NULL) {
- GetArenaNoVirtual()->Own(list_value);
- } else if (GetArenaNoVirtual() !=
- ::google::protobuf::Arena::GetArena(list_value)) {
- ::google::protobuf::ListValue* new_list_value =
- ::google::protobuf::Arena::CreateMessage< ::google::protobuf::ListValue >(
- GetArenaNoVirtual());
- new_list_value->CopyFrom(*list_value);
- list_value = new_list_value;
- }
- set_has_list_value();
- kind_.list_value_ = list_value;
- }
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.Value.list_value)
+inline const ::google::protobuf::ListValue& Value::list_value() const {
+ // @@protoc_insertion_point(field_get:google.protobuf.Value.list_value)
+ return has_list_value()
+ ? *kind_.list_value_
+ : *reinterpret_cast< ::google::protobuf::ListValue*>(&::google::protobuf::_ListValue_default_instance_);
}
-inline ::google::protobuf::ListValue* Value::unsafe_arena_release_list_value() {
+inline ::google::protobuf::ListValue* Value::unsafe_arena_release_list_value() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Value.list_value)
if (has_list_value()) {
clear_has_kind();
@@ -898,7 +935,7 @@ inline ::google::protobuf::ListValue* Value::unsafe_arena_release_list_value()
return NULL;
}
}
-inline void Value::unsafe_arena_set_allocated_list_value(::google::protobuf::ListValue* list_value) {
+inline void Value::unsafe_arena_set_allocated_list_value(::google::protobuf::ListValue* list_value) {
clear_kind();
if (list_value) {
set_has_list_value();
@@ -906,6 +943,17 @@ inline void Value::unsafe_arena_set_allocated_list_value(::google::protobuf::Li
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Value.list_value)
}
+inline ::google::protobuf::ListValue* Value::mutable_list_value() {
+ if (!has_list_value()) {
+ clear_kind();
+ set_has_list_value();
+ kind_.list_value_ =
+ ::google::protobuf::Arena::CreateMessage< ::google::protobuf::ListValue >(
+ GetArenaNoVirtual());
+ }
+ // @@protoc_insertion_point(field_mutable:google.protobuf.Value.list_value)
+ return kind_.list_value_;
+}
inline bool Value::has_kind() const {
return kind_case() != KIND_NOT_SET;
@@ -950,7 +998,9 @@ ListValue::values() const {
return values_;
}
-#endif // !PROTOBUF_INLINE_NOT_IN_HEADERS
+#ifdef __GNUC__
+ #pragma GCC diagnostic pop
+#endif // __GNUC__
// -------------------------------------------------------------------
// -------------------------------------------------------------------
@@ -960,11 +1010,9 @@ ListValue::values() const {
// @@protoc_insertion_point(namespace_scope)
-
} // namespace protobuf
} // namespace google
-#ifndef SWIG
namespace google {
namespace protobuf {
@@ -976,7 +1024,6 @@ inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::NullValue>()
} // namespace protobuf
} // namespace google
-#endif // SWIG
// @@protoc_insertion_point(global_scope)
diff --git a/src/google/protobuf/stubs/atomicops.h b/src/google/protobuf/stubs/atomicops.h
index c25492f3..64c838fb 100644
--- a/src/google/protobuf/stubs/atomicops.h
+++ b/src/google/protobuf/stubs/atomicops.h
@@ -63,28 +63,21 @@ namespace google {
namespace protobuf {
namespace internal {
-#if defined(GOOGLE_PROTOBUF_ARCH_POWER)
-#if defined(_LP64) || defined(__LP64__)
-typedef int32 Atomic32;
-typedef intptr_t Atomic64;
+#ifdef GOOGLE_PROTOBUF_ARCH_32_BIT
+ typedef intptr_t Atomic32;
+ typedef int64 Atomic64;
#else
-typedef intptr_t Atomic32;
-typedef int64 Atomic64;
-#endif
-#else
-typedef int32 Atomic32;
-#ifdef GOOGLE_PROTOBUF_ARCH_64_BIT
-// We need to be able to go between Atomic64 and AtomicWord implicitly. This
-// means Atomic64 and AtomicWord should be the same type on 64-bit.
-#if defined(__ILP32__) || defined(GOOGLE_PROTOBUF_OS_NACL)
-// NaCl's intptr_t is not actually 64-bits on 64-bit!
-// http://code.google.com/p/nativeclient/issues/detail?id=1162
-// sparcv9's pointer type is 32bits
-typedef int64 Atomic64;
-#else
-typedef intptr_t Atomic64;
-#endif
-#endif
+ typedef int32 Atomic32;
+ // We need to be able to go between Atomic64 and AtomicWord implicitly. This
+ // means Atomic64 and AtomicWord should be the same type on 64-bit.
+ #if defined(__ILP32__) || defined(GOOGLE_PROTOBUF_OS_NACL)
+ // NaCl's intptr_t is not actually 64-bits on 64-bit!
+ // http://code.google.com/p/nativeclient/issues/detail?id=1162
+ // sparcv9's pointer type is 32bits
+ typedef int64 Atomic64;
+ #else
+ typedef intptr_t Atomic64;
+ #endif
#endif
// Use AtomicWord for a machine-sized pointer. It will use the Atomic32 or
@@ -194,14 +187,6 @@ Atomic64 Release_Load(volatile const Atomic64* ptr);
#elif defined(GOOGLE_PROTOBUF_OS_AIX)
#include <google/protobuf/stubs/atomicops_internals_power.h>
-// Apple.
-#elif defined(GOOGLE_PROTOBUF_OS_APPLE)
-#if __has_feature(cxx_atomic) || _GNUC_VER >= 407
-#include <google/protobuf/stubs/atomicops_internals_generic_c11_atomic.h>
-#else // __has_feature(cxx_atomic) || _GNUC_VER >= 407
-#include <google/protobuf/stubs/atomicops_internals_macosx.h>
-#endif // __has_feature(cxx_atomic) || _GNUC_VER >= 407
-
// GCC.
#elif defined(__GNUC__)
#if defined(GOOGLE_PROTOBUF_ARCH_IA32) || defined(GOOGLE_PROTOBUF_ARCH_X64)
@@ -221,6 +206,9 @@ Atomic64 Release_Load(volatile const Atomic64* ptr);
#elif defined(GOOGLE_PROTOBUF_ARCH_POWER)
#include <google/protobuf/stubs/atomicops_internals_power.h>
#elif defined(__native_client__)
+// The static_asserts in the C++11 atomics implementation cause it to fail
+// with certain compilers, e.g. nvcc on macOS. Don't use elsewhere unless
+// the TODO in that file is addressed.
#include <google/protobuf/stubs/atomicops_internals_generic_c11_atomic.h>
#elif defined(GOOGLE_PROTOBUF_ARCH_PPC)
#include <google/protobuf/stubs/atomicops_internals_ppc_gcc.h>
diff --git a/src/google/protobuf/stubs/atomicops_internals_macosx.h b/src/google/protobuf/stubs/atomicops_internals_macosx.h
deleted file mode 100644
index c242ef73..00000000
--- a/src/google/protobuf/stubs/atomicops_internals_macosx.h
+++ /dev/null
@@ -1,225 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2012 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.
-
-// This file is an internal atomic implementation, use atomicops.h instead.
-
-#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_MACOSX_H_
-#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_MACOSX_H_
-
-#include <libkern/OSAtomic.h>
-
-namespace google {
-namespace protobuf {
-namespace internal {
-
-inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- Atomic32 prev_value;
- do {
- if (OSAtomicCompareAndSwap32(old_value, new_value,
- const_cast<Atomic32*>(ptr))) {
- return old_value;
- }
- prev_value = *ptr;
- } while (prev_value == old_value);
- return prev_value;
-}
-
-inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr,
- Atomic32 new_value) {
- Atomic32 old_value;
- do {
- old_value = *ptr;
- } while (!OSAtomicCompareAndSwap32(old_value, new_value,
- const_cast<Atomic32*>(ptr)));
- return old_value;
-}
-
-inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr,
- Atomic32 increment) {
- return OSAtomicAdd32(increment, const_cast<Atomic32*>(ptr));
-}
-
-inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr,
- Atomic32 increment) {
- return OSAtomicAdd32Barrier(increment, const_cast<Atomic32*>(ptr));
-}
-
-inline void MemoryBarrierInternal() {
- OSMemoryBarrier();
-}
-
-inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- Atomic32 prev_value;
- do {
- if (OSAtomicCompareAndSwap32Barrier(old_value, new_value,
- const_cast<Atomic32*>(ptr))) {
- return old_value;
- }
- prev_value = *ptr;
- } while (prev_value == old_value);
- return prev_value;
-}
-
-inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- return Acquire_CompareAndSwap(ptr, old_value, new_value);
-}
-
-inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) {
- *ptr = value;
-}
-
-inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) {
- *ptr = value;
- MemoryBarrierInternal();
-}
-
-inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) {
- MemoryBarrierInternal();
- *ptr = value;
-}
-
-inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) {
- return *ptr;
-}
-
-inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) {
- Atomic32 value = *ptr;
- MemoryBarrierInternal();
- return value;
-}
-
-inline Atomic32 Release_Load(volatile const Atomic32* ptr) {
- MemoryBarrierInternal();
- return *ptr;
-}
-
-#ifdef __LP64__
-
-// 64-bit implementation on 64-bit platform
-
-inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr,
- Atomic64 old_value,
- Atomic64 new_value) {
- Atomic64 prev_value;
- do {
- if (OSAtomicCompareAndSwap64(old_value, new_value,
- reinterpret_cast<volatile int64_t*>(ptr))) {
- return old_value;
- }
- prev_value = *ptr;
- } while (prev_value == old_value);
- return prev_value;
-}
-
-inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr,
- Atomic64 new_value) {
- Atomic64 old_value;
- do {
- old_value = *ptr;
- } while (!OSAtomicCompareAndSwap64(old_value, new_value,
- reinterpret_cast<volatile int64_t*>(ptr)));
- return old_value;
-}
-
-inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr,
- Atomic64 increment) {
- return OSAtomicAdd64(increment, reinterpret_cast<volatile int64_t*>(ptr));
-}
-
-inline Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr,
- Atomic64 increment) {
- return OSAtomicAdd64Barrier(increment,
- reinterpret_cast<volatile int64_t*>(ptr));
-}
-
-inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr,
- Atomic64 old_value,
- Atomic64 new_value) {
- Atomic64 prev_value;
- do {
- if (OSAtomicCompareAndSwap64Barrier(
- old_value, new_value, reinterpret_cast<volatile int64_t*>(ptr))) {
- return old_value;
- }
- prev_value = *ptr;
- } while (prev_value == old_value);
- return prev_value;
-}
-
-inline Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr,
- Atomic64 old_value,
- Atomic64 new_value) {
- // The lib kern interface does not distinguish between
- // Acquire and Release memory barriers; they are equivalent.
- return Acquire_CompareAndSwap(ptr, old_value, new_value);
-}
-
-inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) {
- *ptr = value;
-}
-
-inline void Acquire_Store(volatile Atomic64* ptr, Atomic64 value) {
- *ptr = value;
- MemoryBarrierInternal();
-}
-
-inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) {
- MemoryBarrierInternal();
- *ptr = value;
-}
-
-inline Atomic64 NoBarrier_Load(volatile const Atomic64* ptr) {
- return *ptr;
-}
-
-inline Atomic64 Acquire_Load(volatile const Atomic64* ptr) {
- Atomic64 value = *ptr;
- MemoryBarrierInternal();
- return value;
-}
-
-inline Atomic64 Release_Load(volatile const Atomic64* ptr) {
- MemoryBarrierInternal();
- return *ptr;
-}
-
-#endif // defined(__LP64__)
-
-} // namespace internal
-} // namespace protobuf
-} // namespace google
-
-#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_MACOSX_H_
diff --git a/src/google/protobuf/stubs/bytestream.h b/src/google/protobuf/stubs/bytestream.h
index 07604e17..86510d14 100644
--- a/src/google/protobuf/stubs/bytestream.h
+++ b/src/google/protobuf/stubs/bytestream.h
@@ -64,7 +64,7 @@ namespace protobuf {
namespace strings {
// An abstract interface for an object that consumes a sequence of bytes. This
-// interface offers 3 different ways to append data, and a Flush() function.
+// interface offers a way to append data as well as a Flush() function.
//
// Example:
//
diff --git a/src/google/protobuf/stubs/callback.h b/src/google/protobuf/stubs/callback.h
index bbd507a8..9ec04979 100644
--- a/src/google/protobuf/stubs/callback.h
+++ b/src/google/protobuf/stubs/callback.h
@@ -346,6 +346,29 @@ struct InternalConstRef {
typedef const base_type& type;
};
+template<typename R, typename T>
+class MethodResultCallback_0_0 : public ResultCallback<R> {
+ public:
+ typedef R (T::*MethodType)();
+ MethodResultCallback_0_0(T* object, MethodType method, bool self_deleting)
+ : object_(object),
+ method_(method),
+ self_deleting_(self_deleting) {}
+ ~MethodResultCallback_0_0() {}
+
+ R Run() {
+ bool needs_delete = self_deleting_;
+ R result = (object_->*method_)();
+ if (needs_delete) delete this;
+ return result;
+ }
+
+ private:
+ T* object_;
+ MethodType method_;
+ bool self_deleting_;
+};
+
template <typename R, typename T, typename P1, typename P2, typename P3,
typename P4, typename P5, typename A1, typename A2>
class MethodResultCallback_5_2 : public ResultCallback2<R, A1, A2> {
@@ -520,6 +543,13 @@ inline ResultCallback1<R, A1>* NewPermanentCallback(
function, false, p1);
}
+// See MethodResultCallback_0_0
+template <typename R, typename T1, typename T2>
+inline ResultCallback<R>* NewPermanentCallback(
+ T1* object, R (T2::*function)()) {
+ return new internal::MethodResultCallback_0_0<R, T1>(object, function, false);
+}
+
// See MethodResultCallback_5_2
template <typename R, typename T, typename P1, typename P2, typename P3,
typename P4, typename P5, typename A1, typename A2>
diff --git a/src/google/protobuf/stubs/common.cc b/src/google/protobuf/stubs/common.cc
index 14655916..73822168 100644..100755
--- a/src/google/protobuf/stubs/common.cc
+++ b/src/google/protobuf/stubs/common.cc
@@ -30,6 +30,7 @@
// Author: kenton@google.com (Kenton Varda)
+#include <google/protobuf/message_lite.h> // TODO(gerbens) ideally remove this.
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/once.h>
#include <google/protobuf/stubs/status.h>
@@ -416,13 +417,30 @@ uint32 ghtonl(uint32 x) {
namespace internal {
typedef void OnShutdownFunc();
-vector<void (*)()>* shutdown_functions = NULL;
-Mutex* shutdown_functions_mutex = NULL;
+struct ShutdownData {
+ ~ShutdownData() {
+ for (int i = 0; i < functions.size(); i++) {
+ functions[i]();
+ }
+ for (int i = 0; i < strings.size(); i++) {
+ strings[i]->~string();
+ }
+ for (int i = 0; i < messages.size(); i++) {
+ messages[i]->~MessageLite();
+ }
+ }
+
+ vector<void (*)()> functions;
+ vector<const std::string*> strings;
+ vector<const MessageLite*> messages;
+ Mutex mutex;
+};
+
+ShutdownData* shutdown_data = NULL;
GOOGLE_PROTOBUF_DECLARE_ONCE(shutdown_functions_init);
void InitShutdownFunctions() {
- shutdown_functions = new vector<void (*)()>;
- shutdown_functions_mutex = new Mutex;
+ shutdown_data = new ShutdownData;
}
inline void InitShutdownFunctionsOnce() {
@@ -431,8 +449,20 @@ inline void InitShutdownFunctionsOnce() {
void OnShutdown(void (*func)()) {
InitShutdownFunctionsOnce();
- MutexLock lock(shutdown_functions_mutex);
- shutdown_functions->push_back(func);
+ MutexLock lock(&shutdown_data->mutex);
+ shutdown_data->functions.push_back(func);
+}
+
+void OnShutdownDestroyString(const std::string* ptr) {
+ InitShutdownFunctionsOnce();
+ MutexLock lock(&shutdown_data->mutex);
+ shutdown_data->strings.push_back(ptr);
+}
+
+void OnShutdownDestroyMessage(const void* ptr) {
+ InitShutdownFunctionsOnce();
+ MutexLock lock(&shutdown_data->mutex);
+ shutdown_data->messages.push_back(static_cast<const MessageLite*>(ptr));
}
} // namespace internal
@@ -445,15 +475,10 @@ void ShutdownProtobufLibrary() {
// called.
// Make it safe to call this multiple times.
- if (internal::shutdown_functions == NULL) return;
+ if (internal::shutdown_data == NULL) return;
- for (int i = 0; i < internal::shutdown_functions->size(); i++) {
- internal::shutdown_functions->at(i)();
- }
- delete internal::shutdown_functions;
- internal::shutdown_functions = NULL;
- delete internal::shutdown_functions_mutex;
- internal::shutdown_functions_mutex = NULL;
+ delete internal::shutdown_data;
+ internal::shutdown_data = NULL;
}
#if PROTOBUF_USE_EXCEPTIONS
diff --git a/src/google/protobuf/stubs/common.h b/src/google/protobuf/stubs/common.h
index c595e205..ff363482 100644
--- a/src/google/protobuf/stubs/common.h
+++ b/src/google/protobuf/stubs/common.h
@@ -35,7 +35,12 @@
#ifndef GOOGLE_PROTOBUF_COMMON_H__
#define GOOGLE_PROTOBUF_COMMON_H__
+#include <algorithm>
+#include <iostream>
+#include <map>
+#include <set>
#include <string>
+#include <vector>
#include <google/protobuf/stubs/port.h>
#include <google/protobuf/stubs/macros.h>
@@ -96,27 +101,27 @@ namespace internal {
// The current version, represented as a single integer to make comparison
// easier: major * 10^6 + minor * 10^3 + micro
-#define GOOGLE_PROTOBUF_VERSION 3001000
+#define GOOGLE_PROTOBUF_VERSION 3004000
// A suffix string for alpha, beta or rc releases. Empty for stable releases.
#define GOOGLE_PROTOBUF_VERSION_SUFFIX ""
// The minimum library version which works with the current version of the
// headers.
-#define GOOGLE_PROTOBUF_MIN_LIBRARY_VERSION 3001000
+#define GOOGLE_PROTOBUF_MIN_LIBRARY_VERSION 3004000
// The minimum header version which works with the current version of
// the library. This constant should only be used by protoc's C++ code
// generator.
-static const int kMinHeaderVersionForLibrary = 3001000;
+static const int kMinHeaderVersionForLibrary = 3004000;
// The minimum protoc version which works with the current version of the
// headers.
-#define GOOGLE_PROTOBUF_MIN_PROTOC_VERSION 3001000
+#define GOOGLE_PROTOBUF_MIN_PROTOC_VERSION 3004000
// The minimum header version which works with the current version of
// protoc. This constant should only be used in VerifyVersion().
-static const int kMinHeaderVersionForProtoc = 3001000;
+static const int kMinHeaderVersionForProtoc = 3004000;
// Verifies that the headers and libraries are compatible. Use the macro
// below to call this.
@@ -195,6 +200,10 @@ namespace internal {
// Register a function to be called when ShutdownProtocolBuffers() is called.
LIBPROTOBUF_EXPORT void OnShutdown(void (*func)());
+// Destroy the string (call string destructor)
+LIBPROTOBUF_EXPORT void OnShutdownDestroyString(const std::string* ptr);
+// Destroy (not delete) the message
+LIBPROTOBUF_EXPORT void OnShutdownDestroyMessage(const void* ptr);
} // namespace internal
@@ -220,7 +229,12 @@ class FatalException : public std::exception {
// This is at the end of the file instead of the beginning to work around a bug
// in some versions of MSVC.
-using namespace std; // Don't do this at home, kids.
+// TODO(acozzette): remove these using statements
+using std::istream;
+using std::ostream;
+using std::pair;
+using std::string;
+using std::vector;
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/stubs/fastmem.h b/src/google/protobuf/stubs/fastmem.h
index 763a6e60..1f1f6ed3 100644
--- a/src/google/protobuf/stubs/fastmem.h
+++ b/src/google/protobuf/stubs/fastmem.h
@@ -111,7 +111,8 @@ inline int fastmemcmp_inlined(const char *a, const char *b, size_t n) {
b += sizeof(uint32);
}
while (a < a_limit) {
- int d = static_cast<uint32>(*a++) - static_cast<uint32>(*b++);
+ int d =
+ static_cast<int>(static_cast<uint32>(*a++) - static_cast<uint32>(*b++));
if (d) return d;
}
return 0;
diff --git a/src/google/protobuf/stubs/hash.h b/src/google/protobuf/stubs/hash.h
index bf0b88b4..218cd948 100644
--- a/src/google/protobuf/stubs/hash.h
+++ b/src/google/protobuf/stubs/hash.h
@@ -42,7 +42,7 @@
#define GOOGLE_PROTOBUF_HAVE_HASH_SET 1
// Use C++11 unordered_{map|set} if available.
-#if ((_LIBCPP_STD_VER >= 11) || \
+#if ((defined(_LIBCPP_STD_VER) && _LIBCPP_STD_VER >= 11) || \
(((__cplusplus >= 201103L) || defined(__GXX_EXPERIMENTAL_CXX0X)) && \
(__GLIBCXX__ > 20090421)))
# define GOOGLE_PROTOBUF_HAS_CXX11_HASH
@@ -92,6 +92,13 @@
# define GOOGLE_PROTOBUF_HASH_SET_CLASS hash_set
# endif
+// GCC <= 4.1 does not define std::tr1::hash for `long long int` or `long long unsigned int`
+# if __GNUC__ == 4 && defined(__GNUC__MINOR__) && __GNUC__MINOR__ <= 1
+# undef GOOGLE_PROTOBUF_HAS_TR1
+# undef GOOGLE_PROTOBUF_HAVE_HASH_MAP
+# undef GOOGLE_PROTOBUF_HAVE_HASH_SET
+# endif
+
// Version checks for MSC.
// Apparently Microsoft decided to move hash_map *back* to the std namespace in
// MSVC 2010:
@@ -343,7 +350,7 @@ struct hash<const char*> {
inline size_t operator()(const char* str) const {
size_t result = 0;
for (; *str != '\0'; str++) {
- result = 5 * result + *str;
+ result = 5 * result + static_cast<size_t>(*str);
}
return result;
}
diff --git a/src/google/protobuf/stubs/int128_unittest.cc b/src/google/protobuf/stubs/int128_unittest.cc
index 5d33292c..1ec899ad 100644
--- a/src/google/protobuf/stubs/int128_unittest.cc
+++ b/src/google/protobuf/stubs/int128_unittest.cc
@@ -370,29 +370,29 @@ TEST(Int128, DivideAndMod) {
EXPECT_EQ(r, result_r);
// Try the other way around.
- swap(q, b);
+ std::swap(q, b);
result_q = a / b;
result_r = a % b;
EXPECT_EQ(q, result_q);
EXPECT_EQ(r, result_r);
// Restore.
- swap(b, q);
+ std::swap(b, q);
// Dividend < divisor; result should be q:0 r:<dividend>.
- swap(a, b);
+ std::swap(a, b);
result_q = a / b;
result_r = a % b;
EXPECT_EQ(0, result_q);
EXPECT_EQ(a, result_r);
// Try the other way around.
- swap(a, q);
+ std::swap(a, q);
result_q = a / b;
result_r = a % b;
EXPECT_EQ(0, result_q);
EXPECT_EQ(a, result_r);
// Restore.
- swap(q, a);
- swap(b, a);
+ std::swap(q, a);
+ std::swap(b, a);
// Try a large remainder.
b = a / 2 + 1;
@@ -501,7 +501,7 @@ TEST(Int128, OStream) {
{uint128(12345), std::ios::dec | std::ios::left, 6, '_', "12345_"},
};
for (size_t i = 0; i < GOOGLE_ARRAYSIZE(cases); ++i) {
- ostringstream os;
+ std::ostringstream os;
os.flags(cases[i].flags);
os.width(cases[i].width);
os.fill(cases[i].fill);
diff --git a/src/google/protobuf/stubs/io_win32.cc b/src/google/protobuf/stubs/io_win32.cc
new file mode 100644
index 00000000..7e1cf785
--- /dev/null
+++ b/src/google/protobuf/stubs/io_win32.cc
@@ -0,0 +1,362 @@
+// 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: laszlocsomor@google.com (Laszlo Csomor)
+//
+// Implementation for long-path-aware open/mkdir/etc. on Windows.
+//
+// These functions convert the input path to an absolute Windows path
+// with "\\?\" prefix if necessary, then pass that to _wopen/_wmkdir/etc.
+// (declared in <io.h>) respectively. This allows working with files/directories
+// whose paths are longer than MAX_PATH (260 chars).
+//
+// This file is only used on Windows, it's empty on other platforms.
+
+#if defined(_MSC_VER)
+
+// Comment this out to fall back to using the ANSI versions (open, mkdir, ...)
+// instead of the Unicode ones (_wopen, _wmkdir, ...). Doing so can be useful to
+// debug failing tests if that's caused by the long path support.
+#define SUPPORT_LONGPATHS
+
+#include <ctype.h>
+#include <direct.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <io.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <wctype.h>
+#include <windows.h>
+
+#include <google/protobuf/stubs/io_win32.h>
+#include <google/protobuf/stubs/scoped_ptr.h>
+
+#include <cassert>
+#include <memory>
+#include <sstream>
+#include <string>
+#include <vector>
+
+namespace google {
+namespace protobuf {
+namespace internal {
+namespace win32 {
+namespace {
+
+using std::string;
+using std::wstring;
+
+template <typename char_type>
+struct CharTraits {
+ static bool is_alpha(char_type ch);
+};
+
+template <>
+struct CharTraits<char> {
+ static bool is_alpha(char ch) { return isalpha(ch); }
+};
+
+template <>
+struct CharTraits<wchar_t> {
+ static bool is_alpha(wchar_t ch) { return iswalpha(ch); }
+};
+
+// Returns true if the path starts with a drive letter, e.g. "c:".
+// Note that this won't check for the "\" after the drive letter, so this also
+// returns true for "c:foo" (which is "c:\${PWD}\foo").
+// This check requires that a path not have a longpath prefix ("\\?\").
+template <typename char_type>
+bool has_drive_letter(const char_type* ch) {
+ return CharTraits<char_type>::is_alpha(ch[0]) && ch[1] == ':';
+}
+
+// Returns true if the path starts with a longpath prefix ("\\?\").
+template <typename char_type>
+bool has_longpath_prefix(const char_type* path) {
+ return path[0] == '\\' && path[1] == '\\' && path[2] == '?' &&
+ path[3] == '\\';
+}
+
+template <typename char_type>
+bool is_separator(char_type c) {
+ return c == '/' || c == '\\';
+}
+
+// Returns true if the path starts with a drive specifier (e.g. "c:\").
+template <typename char_type>
+bool is_path_absolute(const char_type* path) {
+ return has_drive_letter(path) && is_separator(path[2]);
+}
+
+template <typename char_type>
+bool is_drive_relative(const char_type* path) {
+ return has_drive_letter(path) && (path[2] == 0 || !is_separator(path[2]));
+}
+
+template <typename char_type>
+void replace_directory_separators(char_type* p) {
+ for (; *p; ++p) {
+ if (*p == '/') {
+ *p = '\\';
+ }
+ }
+}
+
+string join_paths(const string& path1, const string& path2) {
+ if (path1.empty() || is_path_absolute(path2.c_str()) ||
+ has_longpath_prefix(path2.c_str())) {
+ return path2;
+ }
+ if (path2.empty()) {
+ return path1;
+ }
+
+ if (is_separator(path1[path1.size() - 1])) {
+ return is_separator(path2[0]) ? (path1 + path2.substr(1))
+ : (path1 + path2);
+ } else {
+ return is_separator(path2[0]) ? (path1 + path2)
+ : (path1 + '\\' + path2);
+ }
+}
+
+string normalize(string path) {
+ if (has_longpath_prefix(path.c_str())) {
+ path = path.substr(4);
+ }
+
+ static const string dot(".");
+ static const string dotdot("..");
+
+ std::vector<string> segments;
+ int segment_start = -1;
+ // Find the path segments in `path` (separated by "/").
+ for (int i = 0;; ++i) {
+ if (!is_separator(path[i]) && path[i] != '\0') {
+ // The current character does not end a segment, so start one unless it's
+ // already started.
+ if (segment_start < 0) {
+ segment_start = i;
+ }
+ } else if (segment_start >= 0 && i > segment_start) {
+ // The current character is "/" or "\0", so this ends a segment.
+ // Add that to `segments` if there's anything to add; handle "." and "..".
+ string segment(path, segment_start, i - segment_start);
+ segment_start = -1;
+ if (segment == dotdot) {
+ if (!segments.empty() &&
+ (!has_drive_letter(segments[0].c_str()) || segments.size() > 1)) {
+ segments.pop_back();
+ }
+ } else if (segment != dot && !segment.empty()) {
+ segments.push_back(segment);
+ }
+ }
+ if (path[i] == '\0') {
+ break;
+ }
+ }
+
+ // Handle the case when `path` is just a drive specifier (or some degenerate
+ // form of it, e.g. "c:\..").
+ if (segments.size() == 1 && segments[0].size() == 2 &&
+ has_drive_letter(segments[0].c_str())) {
+ return segments[0] + '\\';
+ }
+
+ // Join all segments.
+ bool first = true;
+ std::ostringstream result;
+ for (int i = 0; i < segments.size(); ++i) {
+ if (!first) {
+ result << '\\';
+ }
+ first = false;
+ result << segments[i];
+ }
+ // Preserve trailing separator if the input contained it.
+ if (!path.empty() && is_separator(path[path.size() - 1])) {
+ result << '\\';
+ }
+ return result.str();
+}
+
+WCHAR* as_wstring(const string& s) {
+ int len = ::MultiByteToWideChar(CP_UTF8, 0, s.c_str(), s.size(), NULL, 0);
+ WCHAR* result = new WCHAR[len + 1];
+ ::MultiByteToWideChar(CP_UTF8, 0, s.c_str(), s.size(), result, len + 1);
+ result[len] = 0;
+ return result;
+}
+
+void as_wchar_path(const string& path, wstring* wchar_path) {
+ scoped_array<WCHAR> wbuf(as_wstring(path));
+ replace_directory_separators(wbuf.get());
+ wchar_path->assign(wbuf.get());
+}
+
+bool as_windows_path(const string& path, wstring* result) {
+ if (path.empty()) {
+ result->clear();
+ return true;
+ }
+ if (is_separator(path[0]) || is_drive_relative(path.c_str())) {
+ return false;
+ }
+
+ string mutable_path = path;
+ if (!is_path_absolute(mutable_path.c_str()) &&
+ !has_longpath_prefix(mutable_path.c_str())) {
+ char cwd[MAX_PATH];
+ ::GetCurrentDirectoryA(MAX_PATH, cwd);
+ mutable_path = join_paths(cwd, mutable_path);
+ }
+ as_wchar_path(normalize(mutable_path), result);
+ if (!has_longpath_prefix(result->c_str())) {
+ // Add the "\\?\" prefix unconditionally. This way we prevent the Win32 API
+ // from processing the path and "helpfully" removing trailing dots from the
+ // path, for example.
+ // See https://github.com/bazelbuild/bazel/issues/2935
+ *result = wstring(L"\\\\?\\") + *result;
+ }
+ return true;
+}
+
+} // namespace
+
+int open(const char* path, int flags, int mode) {
+#ifdef SUPPORT_LONGPATHS
+ wstring wpath;
+ if (!as_windows_path(path, &wpath)) {
+ errno = ENOENT;
+ return -1;
+ }
+ return ::_wopen(wpath.c_str(), flags, mode);
+#else
+ return ::_open(path, flags, mode);
+#endif
+}
+
+int mkdir(const char* path, int _mode) {
+#ifdef SUPPORT_LONGPATHS
+ wstring wpath;
+ if (!as_windows_path(path, &wpath)) {
+ errno = ENOENT;
+ return -1;
+ }
+ return ::_wmkdir(wpath.c_str());
+#else // not SUPPORT_LONGPATHS
+ return ::_mkdir(path);
+#endif // not SUPPORT_LONGPATHS
+}
+
+int access(const char* path, int mode) {
+#ifdef SUPPORT_LONGPATHS
+ wstring wpath;
+ if (!as_windows_path(path, &wpath)) {
+ errno = ENOENT;
+ return -1;
+ }
+ return ::_waccess(wpath.c_str(), mode);
+#else
+ return ::_access(path, mode);
+#endif
+}
+
+int chdir(const char* path) {
+#ifdef SUPPORT_LONGPATHS
+ wstring wpath;
+ if (!as_windows_path(path, &wpath)) {
+ errno = ENOENT;
+ return -1;
+ }
+ return ::_wchdir(wpath.c_str());
+#else
+ return ::_chdir(path);
+#endif
+}
+
+int stat(const char* path, struct _stat* buffer) {
+#ifdef SUPPORT_LONGPATHS
+ wstring wpath;
+ if (!as_windows_path(path, &wpath)) {
+ errno = ENOENT;
+ return -1;
+ }
+ return ::_wstat(wpath.c_str(), buffer);
+#else // not SUPPORT_LONGPATHS
+ return ::_stat(path, buffer);
+#endif // not SUPPORT_LONGPATHS
+}
+
+FILE* fopen(const char* path, const char* mode) {
+#ifdef SUPPORT_LONGPATHS
+ wstring wpath;
+ if (!as_windows_path(path, &wpath)) {
+ errno = ENOENT;
+ return NULL;
+ }
+ scoped_array<WCHAR> wmode(as_wstring(mode));
+ return ::_wfopen(wpath.c_str(), wmode.get());
+#else
+ return ::fopen(path, mode);
+#endif
+}
+
+int close(int fd) { return ::close(fd); }
+
+int dup(int fd) { return ::_dup(fd); }
+
+int dup2(int fd1, int fd2) { return ::_dup2(fd1, fd2); }
+
+int read(int fd, void* buffer, size_t size) {
+ return ::_read(fd, buffer, size);
+}
+
+int setmode(int fd, int mode) { return ::_setmode(fd, mode); }
+
+int write(int fd, const void* buffer, size_t size) {
+ return ::_write(fd, buffer, size);
+}
+
+wstring testonly_path_to_winpath(const string& path) {
+ wstring wpath;
+ as_windows_path(path, &wpath);
+ return wpath;
+}
+
+} // namespace win32
+} // namespace internal
+} // namespace protobuf
+} // namespace google
+
+#endif // defined(_MSC_VER)
+
diff --git a/src/google/protobuf/stubs/io_win32.h b/src/google/protobuf/stubs/io_win32.h
new file mode 100644
index 00000000..a20e64c7
--- /dev/null
+++ b/src/google/protobuf/stubs/io_win32.h
@@ -0,0 +1,104 @@
+// 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: laszlocsomor@google.com (Laszlo Csomor)
+//
+// This file contains the declarations for Windows implementations of
+// commonly used POSIX functions such as open(2) and access(2), as well
+// as macro definitions for flags of these functions.
+//
+// By including this file you'll redefine open/access/etc. to
+// ::google::protobuf::internal::win32::{open/access/etc.}.
+// Make sure you don't include a header that attempts to redeclare or
+// redefine these functions, that'll lead to confusing compilation
+// errors. It's best to #include this file as the last one to ensure that.
+//
+// This file is only used on Windows, it's empty on other platforms.
+
+#ifndef GOOGLE_PROTOBUF_STUBS_IO_WIN32_H__
+#define GOOGLE_PROTOBUF_STUBS_IO_WIN32_H__
+
+#if defined(_WIN32)
+
+#include <string>
+#include <google/protobuf/stubs/port.h>
+
+// Compilers on Windows other than MSVC (e.g. Cygwin, MinGW32) define the
+// following functions already, except for mkdir.
+#ifdef _MSC_VER
+namespace google {
+namespace protobuf {
+namespace internal {
+namespace win32 {
+
+LIBPROTOBUF_EXPORT FILE* fopen(const char* path, const char* mode);
+LIBPROTOBUF_EXPORT int access(const char* path, int mode);
+LIBPROTOBUF_EXPORT int chdir(const char* path);
+LIBPROTOBUF_EXPORT int close(int fd);
+LIBPROTOBUF_EXPORT int dup(int fd);
+LIBPROTOBUF_EXPORT int dup2(int fd1, int fd2);
+LIBPROTOBUF_EXPORT int mkdir(const char* path, int _mode);
+LIBPROTOBUF_EXPORT int open(const char* path, int flags, int mode = 0);
+LIBPROTOBUF_EXPORT int read(int fd, void* buffer, size_t size);
+LIBPROTOBUF_EXPORT int setmode(int fd, int mode);
+LIBPROTOBUF_EXPORT int stat(const char* path, struct _stat* buffer);
+LIBPROTOBUF_EXPORT int write(int fd, const void* buffer, size_t size);
+LIBPROTOBUF_EXPORT std::wstring testonly_path_to_winpath(
+ const std::string& path);
+
+} // namespace win32
+} // namespace internal
+} // namespace protobuf
+} // namespace google
+#else // _MSC_VER
+#define mkdir(name, mode) mkdir(name)
+#endif // !_MSC_VER
+
+#ifndef W_OK
+#define W_OK 02 // not defined by MSVC for whatever reason
+#endif
+
+#ifndef F_OK
+#define F_OK 00 // not defined by MSVC for whatever reason
+#endif
+
+#ifndef STDIN_FILENO
+#define STDIN_FILENO 0
+#endif
+
+#ifndef STDOUT_FILENO
+#define STDOUT_FILENO 1
+#endif
+
+#endif // defined(_WIN32)
+
+#endif // GOOGLE_PROTOBUF_STUBS_IO_WIN32_H__
+
+
diff --git a/src/google/protobuf/stubs/io_win32_unittest.cc b/src/google/protobuf/stubs/io_win32_unittest.cc
new file mode 100644
index 00000000..288f27ab
--- /dev/null
+++ b/src/google/protobuf/stubs/io_win32_unittest.cc
@@ -0,0 +1,373 @@
+// 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: laszlocsomor@google.com (Laszlo Csomor)
+//
+// Unit tests for long-path-aware open/mkdir/access on Windows.
+//
+// This file is only used on Windows, it's empty on other platforms.
+
+#if defined(_MSC_VER)
+
+#define WIN32_LEAN_AND_MEAN
+#include <errno.h>
+#include <fcntl.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <wchar.h>
+#include <windows.h>
+
+#include <google/protobuf/stubs/io_win32.h>
+#include <google/protobuf/stubs/scoped_ptr.h>
+#include <google/protobuf/testing/googletest.h>
+#include <gtest/gtest.h>
+
+#include <memory>
+#include <sstream>
+#include <string>
+
+namespace google {
+namespace protobuf {
+namespace internal {
+namespace win32 {
+namespace {
+
+using std::string;
+using std::wstring;
+
+class IoWin32Test : public ::testing::Test {
+ public:
+ void SetUp();
+ void TearDown();
+
+ protected:
+ bool CreateAllUnder(wstring path);
+ bool DeleteAllUnder(wstring path);
+
+ string test_tmpdir;
+ wstring wtest_tmpdir;
+};
+
+#define ASSERT_INITIALIZED \
+ { \
+ EXPECT_FALSE(test_tmpdir.empty()); \
+ EXPECT_FALSE(wtest_tmpdir.empty()); \
+ }
+
+namespace {
+void StripTrailingSlashes(string* str) {
+ int i = str->size() - 1;
+ for (; i >= 0 && ((*str)[i] == '/' || (*str)[i] == '\\'); --i) {}
+ str->resize(i+1);
+}
+} // namespace
+
+void IoWin32Test::SetUp() {
+ test_tmpdir = string(TestTempDir());
+ wtest_tmpdir.clear();
+ if (test_tmpdir.empty()) {
+ const char* test_tmpdir_env = getenv("TEST_TMPDIR");
+ if (test_tmpdir_env != NULL && *test_tmpdir_env) {
+ test_tmpdir = string(test_tmpdir_env);
+ }
+
+ // Only Bazel defines TEST_TMPDIR, CMake does not, so look for other
+ // suitable environment variables.
+ if (test_tmpdir.empty()) {
+ static const char* names[] = {"TEMP", "TMP"};
+ for (int i = 0; i < sizeof(names)/sizeof(names[0]); ++i) {
+ const char* name = names[i];
+ test_tmpdir_env = getenv(name);
+ if (test_tmpdir_env != NULL && *test_tmpdir_env) {
+ test_tmpdir = string(test_tmpdir_env);
+ break;
+ }
+ }
+ }
+
+ // No other temp directory was found. Use the current director
+ if (test_tmpdir.empty()) {
+ char buffer[MAX_PATH];
+ // Use GetCurrentDirectoryA instead of GetCurrentDirectoryW, because the
+ // current working directory must always be shorter than MAX_PATH, even
+ // with
+ // "\\?\" prefix (except on Windows 10 version 1607 and beyond, after
+ // opting in to long paths by default [1]).
+ //
+ // [1] https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#maxpath
+ DWORD result = ::GetCurrentDirectoryA(MAX_PATH, buffer);
+ if (result > 0) {
+ test_tmpdir = string(buffer);
+ } else {
+ // Using assertions in SetUp/TearDown seems to confuse the test
+ // framework, so just leave the member variables empty in case of
+ // failure.
+ GOOGLE_CHECK_OK(false);
+ return;
+ }
+ }
+ }
+
+ StripTrailingSlashes(&test_tmpdir);
+ test_tmpdir += "\\io_win32_unittest.tmp";
+
+ // CreateDirectoryA's limit is 248 chars, see MSDN.
+ // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363855(v=vs.85).aspx
+ wtest_tmpdir = testonly_path_to_winpath(test_tmpdir);
+ if (!DeleteAllUnder(wtest_tmpdir) || !CreateAllUnder(wtest_tmpdir)) {
+ GOOGLE_CHECK_OK(false);
+ test_tmpdir.clear();
+ wtest_tmpdir.clear();
+ }
+}
+
+void IoWin32Test::TearDown() {
+ if (!wtest_tmpdir.empty()) {
+ DeleteAllUnder(wtest_tmpdir);
+ }
+}
+
+bool IoWin32Test::CreateAllUnder(wstring path) {
+ // Prepend UNC prefix if the path doesn't have it already. Don't bother
+ // checking if the path is shorter than MAX_PATH, let's just do it
+ // unconditionally.
+ if (path.find(L"\\\\?\\") != 0) {
+ path = wstring(L"\\\\?\\") + path;
+ }
+ if (::CreateDirectoryW(path.c_str(), NULL) ||
+ GetLastError() == ERROR_ALREADY_EXISTS ||
+ GetLastError() == ERROR_ACCESS_DENIED) {
+ return true;
+ }
+ if (GetLastError() == ERROR_PATH_NOT_FOUND) {
+ size_t pos = path.find_last_of(L'\\');
+ if (pos != wstring::npos) {
+ wstring parent(path, 0, pos);
+ if (CreateAllUnder(parent) && CreateDirectoryW(path.c_str(), NULL)) {
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
+bool IoWin32Test::DeleteAllUnder(wstring path) {
+ static const wstring kDot(L".");
+ static const wstring kDotDot(L"..");
+
+ // Prepend UNC prefix if the path doesn't have it already. Don't bother
+ // checking if the path is shorter than MAX_PATH, let's just do it
+ // unconditionally.
+ if (path.find(L"\\\\?\\") != 0) {
+ path = wstring(L"\\\\?\\") + path;
+ }
+ // Append "\" if necessary.
+ if (path[path.size() - 1] != '\\') {
+ path.push_back('\\');
+ }
+
+ WIN32_FIND_DATAW metadata;
+ HANDLE handle = ::FindFirstFileW((path + L"*").c_str(), &metadata);
+ if (handle == INVALID_HANDLE_VALUE) {
+ return true; // directory doesn't exist
+ }
+
+ bool result = true;
+ do {
+ wstring childname = metadata.cFileName;
+ if (kDot != childname && kDotDot != childname) {
+ wstring childpath = path + childname;
+ if ((metadata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) {
+ // If this is not a junction, delete its contents recursively.
+ // Finally delete this directory/junction too.
+ if (((metadata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) == 0 &&
+ !DeleteAllUnder(childpath)) ||
+ !::RemoveDirectoryW(childpath.c_str())) {
+ result = false;
+ break;
+ }
+ } else {
+ if (!::DeleteFileW(childpath.c_str())) {
+ result = false;
+ break;
+ }
+ }
+ }
+ } while (::FindNextFileW(handle, &metadata));
+ ::FindClose(handle);
+ return result;
+}
+
+TEST_F(IoWin32Test, AccessTest) {
+ ASSERT_INITIALIZED;
+
+ string path = test_tmpdir;
+ while (path.size() < MAX_PATH - 30) {
+ path += "\\accesstest";
+ EXPECT_EQ(mkdir(path.c_str(), 0644), 0);
+ }
+ string file = path + "\\file.txt";
+ int fd = open(file.c_str(), O_CREAT | O_WRONLY, 0644);
+ if (fd > 0) {
+ EXPECT_EQ(close(fd), 0);
+ } else {
+ EXPECT_TRUE(false);
+ }
+
+ EXPECT_EQ(access(test_tmpdir.c_str(), F_OK), 0);
+ EXPECT_EQ(access(path.c_str(), F_OK), 0);
+ EXPECT_EQ(access(path.c_str(), W_OK), 0);
+ EXPECT_EQ(access(file.c_str(), F_OK | W_OK), 0);
+ EXPECT_NE(access((file + ".blah").c_str(), F_OK), 0);
+ EXPECT_NE(access((file + ".blah").c_str(), W_OK), 0);
+
+ EXPECT_EQ(access(".", F_OK), 0);
+ EXPECT_EQ(access(".", W_OK), 0);
+ EXPECT_EQ(access((test_tmpdir + "/accesstest").c_str(), F_OK | W_OK), 0);
+ ASSERT_EQ(access((test_tmpdir + "/./normalize_me/.././accesstest").c_str(),
+ F_OK | W_OK),
+ 0);
+ EXPECT_NE(access("io_win32_unittest.AccessTest.nonexistent", F_OK), 0);
+ EXPECT_NE(access("io_win32_unittest.AccessTest.nonexistent", W_OK), 0);
+
+ ASSERT_EQ(access("c:bad", F_OK), -1);
+ ASSERT_EQ(errno, ENOENT);
+ ASSERT_EQ(access("/tmp/bad", F_OK), -1);
+ ASSERT_EQ(errno, ENOENT);
+ ASSERT_EQ(access("\\bad", F_OK), -1);
+ ASSERT_EQ(errno, ENOENT);
+}
+
+TEST_F(IoWin32Test, OpenTest) {
+ ASSERT_INITIALIZED;
+
+ string path = test_tmpdir;
+ while (path.size() < MAX_PATH) {
+ path += "\\opentest";
+ EXPECT_EQ(mkdir(path.c_str(), 0644), 0);
+ }
+ string file = path + "\\file.txt";
+ int fd = open(file.c_str(), O_CREAT | O_WRONLY, 0644);
+ if (fd > 0) {
+ EXPECT_EQ(write(fd, "hello", 5), 5);
+ EXPECT_EQ(close(fd), 0);
+ } else {
+ EXPECT_TRUE(false);
+ }
+
+ ASSERT_EQ(open("c:bad.txt", O_CREAT | O_WRONLY, 0644), -1);
+ ASSERT_EQ(errno, ENOENT);
+ ASSERT_EQ(open("/tmp/bad.txt", O_CREAT | O_WRONLY, 0644), -1);
+ ASSERT_EQ(errno, ENOENT);
+ ASSERT_EQ(open("\\bad.txt", O_CREAT | O_WRONLY, 0644), -1);
+ ASSERT_EQ(errno, ENOENT);
+}
+
+TEST_F(IoWin32Test, MkdirTest) {
+ ASSERT_INITIALIZED;
+
+ string path = test_tmpdir;
+ do {
+ path += "\\mkdirtest";
+ ASSERT_EQ(mkdir(path.c_str(), 0644), 0);
+ } while (path.size() <= MAX_PATH);
+
+ ASSERT_EQ(mkdir("c:bad", 0644), -1);
+ ASSERT_EQ(errno, ENOENT);
+ ASSERT_EQ(mkdir("/tmp/bad", 0644), -1);
+ ASSERT_EQ(errno, ENOENT);
+ ASSERT_EQ(mkdir("\\bad", 0644), -1);
+ ASSERT_EQ(errno, ENOENT);
+}
+
+TEST_F(IoWin32Test, ChdirTest) {
+ char owd[MAX_PATH];
+ EXPECT_GT(::GetCurrentDirectoryA(MAX_PATH, owd), 0);
+ string path("C:\\");
+ EXPECT_EQ(access(path.c_str(), F_OK), 0);
+ ASSERT_EQ(chdir(path.c_str()), 0);
+ EXPECT_TRUE(::SetCurrentDirectoryA(owd));
+
+ // Do not try to chdir into the test_tmpdir, it may already contain directory
+ // names with trailing dots.
+ // Instead test here with an obviously dot-trailed path. If the win32_chdir
+ // function would not convert the path to absolute and prefix with "\\?\" then
+ // the Win32 API would ignore the trailing dot, but because of the prefixing
+ // there'll be no path processing done, so we'll actually attempt to chdir
+ // into "C:\some\path\foo."
+ path = test_tmpdir + "/foo.";
+ EXPECT_EQ(mkdir(path.c_str(), 644), 0);
+ EXPECT_EQ(access(path.c_str(), F_OK), 0);
+ ASSERT_NE(chdir(path.c_str()), 0);
+}
+
+TEST_F(IoWin32Test, AsWindowsPathTest) {
+ DWORD size = GetCurrentDirectoryW(0, NULL);
+ scoped_array<wchar_t> cwd_str(new wchar_t[size]);
+ EXPECT_GT(GetCurrentDirectoryW(size, cwd_str.get()), 0);
+ wstring cwd = wstring(L"\\\\?\\") + cwd_str.get();
+
+ ASSERT_EQ(testonly_path_to_winpath("relative_mkdirtest"),
+ cwd + L"\\relative_mkdirtest");
+ ASSERT_EQ(testonly_path_to_winpath("preserve//\\trailing///"),
+ cwd + L"\\preserve\\trailing\\");
+ ASSERT_EQ(testonly_path_to_winpath("./normalize_me\\/../blah"),
+ cwd + L"\\blah");
+ std::ostringstream relpath;
+ for (wchar_t* p = cwd_str.get(); *p; ++p) {
+ if (*p == '/' || *p == '\\') {
+ relpath << "../";
+ }
+ }
+ relpath << ".\\/../\\./beyond-toplevel";
+ ASSERT_EQ(testonly_path_to_winpath(relpath.str()),
+ wstring(L"\\\\?\\") + cwd_str.get()[0] + L":\\beyond-toplevel");
+
+ // Absolute unix paths lack drive letters, driveless absolute windows paths
+ // do too. Neither can be converted to a drive-specifying absolute Windows
+ // path.
+ ASSERT_EQ(testonly_path_to_winpath("/absolute/unix/path"), L"");
+ // Though valid on Windows, we also don't support UNC paths (\\UNC\\blah).
+ ASSERT_EQ(testonly_path_to_winpath("\\driveless\\absolute"), L"");
+ // Though valid in cmd.exe, drive-relative paths are not supported.
+ ASSERT_EQ(testonly_path_to_winpath("c:foo"), L"");
+ ASSERT_EQ(testonly_path_to_winpath("c:/foo"), L"\\\\?\\c:\\foo");
+}
+
+} // namespace
+} // namespace win32
+} // namespace internal
+} // namespace protobuf
+} // namespace google
+
+#endif // defined(_MSC_VER)
+
diff --git a/src/google/protobuf/stubs/mathlimits.h b/src/google/protobuf/stubs/mathlimits.h
index 275d9539..2391ac4c 100644
--- a/src/google/protobuf/stubs/mathlimits.h
+++ b/src/google/protobuf/stubs/mathlimits.h
@@ -43,18 +43,23 @@
#ifndef UTIL_MATH_MATHLIMITS_H__
#define UTIL_MATH_MATHLIMITS_H__
-// GCC 4.9 has a bug that makes it impossible to use isinf and isnan when both
-// <math.h> and <cmath> get pulled into the same translation unit.
-// Unfortunately it is difficult to prevent this from happening, so to work
-// around the problem we use std::isinf and std::isnan from <cmath> for C++11
-// builds and otherwise use the plain isinf and isnan functions from <math.h>.
// Note that for Windows we do something different because it does not support
// the plain isinf and isnan.
#if __cplusplus >= 201103L
+// GCC 4.9 has a bug that makes isinf and isnan ambigious when both <math.h>
+// and <cmath> get pulled into the same translation unit. We use the ones in
+// std:: namespace explicitly for C++11
#include <cmath>
+#define GOOGLE_PROTOBUF_USE_STD_CMATH
+#elif _GLIBCXX_USE_C99_MATH && !_GLIBCXX_USE_C99_FP_MACROS_DYNAMIC
+// libstdc++ <cmath> header undefines the global macros and put functions in
+// std:: namespace even before C++11. Use the ones in std:: instead too.
+#include <cmath>
+#define GOOGLE_PROTOBUF_USE_STD_CMATH
#else
#include <math.h>
#endif
+
#include <string.h>
#include <cfloat>
@@ -229,7 +234,7 @@ DECL_UNSIGNED_INT_LIMITS(unsigned long long int)
// For non-Windows builds we use the std:: versions of isinf and isnan if they
// are available; see the comment about <cmath> at the top of this file for the
// details on why we need to do this.
-#if __cplusplus >= 201103L
+#ifdef GOOGLE_PROTOBUF_USE_STD_CMATH
#define ISINF std::isinf
#define ISNAN std::isnan
#else
diff --git a/src/google/protobuf/stubs/mutex.h b/src/google/protobuf/stubs/mutex.h
index 7ef1cb69..174290f6 100644
--- a/src/google/protobuf/stubs/mutex.h
+++ b/src/google/protobuf/stubs/mutex.h
@@ -70,14 +70,6 @@ class LIBPROTOBUF_EXPORT Mutex {
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Mutex);
};
-// Undefine the macros to workaround the conflicts with Google internal
-// MutexLock implementation.
-// TODO(liujisi): Remove the undef once internal macros are removed.
-#undef MutexLock
-#undef ReaderMutexLock
-#undef WriterMutexLock
-#undef MutexLockMaybe
-
// MutexLock(mu) acquires mu when constructed and releases it when destroyed.
class LIBPROTOBUF_EXPORT MutexLock {
public:
diff --git a/src/google/protobuf/stubs/port.h b/src/google/protobuf/stubs/port.h
index 72adba6d..cecefdcb 100644
--- a/src/google/protobuf/stubs/port.h
+++ b/src/google/protobuf/stubs/port.h
@@ -44,6 +44,8 @@
#include <stdint.h>
#endif
+#include <google/protobuf/stubs/platform_macros.h>
+
#undef PROTOBUF_LITTLE_ENDIAN
#ifdef _WIN32
// Assuming windows is always little-endian.
@@ -95,6 +97,8 @@
#include <byteswap.h> // IWYU pragma: export
#endif
+#define PROTOBUF_RUNTIME_DEPRECATED(message)
+
// ===================================================================
// from google3/base/port.h
@@ -106,6 +110,18 @@
#define LANG_CXX11 1
#endif
+#if LANG_CXX11 && !defined(__NVCC__)
+#define PROTOBUF_CXX11 1
+#else
+#define PROTOBUF_CXX11 0
+#endif
+
+#if PROTOBUF_CXX11
+#define PROTOBUF_FINAL final
+#else
+#define PROTOBUF_FINAL
+#endif
+
namespace google {
namespace protobuf {
@@ -175,6 +191,8 @@ static const uint64 kuint64max = GOOGLE_ULONGLONG(0xFFFFFFFFFFFFFFFF);
#endif
#endif
+#define GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE GOOGLE_ATTRIBUTE_ALWAYS_INLINE
+
#ifndef GOOGLE_ATTRIBUTE_NOINLINE
#if defined(__GNUC__) && (__GNUC__ > 3 ||(__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
// For functions we want to force not inline.
@@ -189,23 +207,7 @@ static const uint64 kuint64max = GOOGLE_ULONGLONG(0xFFFFFFFFFFFFFFFF);
#endif
#endif
-#ifndef GOOGLE_ATTRIBUTE_NORETURN
-#ifdef __GNUC__
-// Tell the compiler that a given function never returns.
-#define GOOGLE_ATTRIBUTE_NORETURN __attribute__((noreturn))
-#else
-#define GOOGLE_ATTRIBUTE_NORETURN
-#endif
-#endif
-
-#ifndef GOOGLE_ATTRIBUTE_DEPRECATED
-#ifdef __GNUC__
-// If the method/variable/type is used anywhere, produce a warning.
-#define GOOGLE_ATTRIBUTE_DEPRECATED __attribute__((deprecated))
-#else
-#define GOOGLE_ATTRIBUTE_DEPRECATED
-#endif
-#endif
+#define GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE GOOGLE_ATTRIBUTE_NOINLINE
#ifndef GOOGLE_PREDICT_TRUE
#ifdef __GNUC__
@@ -241,6 +243,8 @@ static const uint64 kuint64max = GOOGLE_ULONGLONG(0xFFFFFFFFFFFFFFFF);
__has_cpp_attribute(clang::fallthrough)
# define GOOGLE_FALLTHROUGH_INTENDED [[clang::fallthrough]]
# endif
+#elif defined(__GNUC__) && __GNUC__ > 6
+# define GOOGLE_FALLTHROUGH_INTENDED [[gnu::fallthrough]]
#endif
#ifndef GOOGLE_FALLTHROUGH_INTENDED
@@ -250,9 +254,59 @@ static const uint64 kuint64max = GOOGLE_ULONGLONG(0xFFFFFFFFFFFFFFFF);
#define GOOGLE_GUARDED_BY(x)
#define GOOGLE_ATTRIBUTE_COLD
-// x86 and x86-64 can perform unaligned loads/stores directly.
-#if defined(_M_X64) || defined(__x86_64__) || \
- defined(_M_IX86) || defined(__i386__)
+#ifdef GOOGLE_PROTOBUF_DONT_USE_UNALIGNED
+# define GOOGLE_PROTOBUF_USE_UNALIGNED 0
+#else
+# if defined(_M_X64) || defined(__x86_64__) || defined(_M_IX86) || defined(__i386__)
+# define GOOGLE_PROTOBUF_USE_UNALIGNED 1
+# else
+# define GOOGLE_PROTOBUF_USE_UNALIGNED 0
+# endif
+#endif
+
+#define GOOGLE_PROTOBUF_ATTRIBUTE_COLD GOOGLE_ATTRIBUTE_COLD
+
+#if defined(ADDRESS_SANITIZER) || defined(THREAD_SANITIZER) ||\
+ defined(MEMORY_SANITIZER)
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+uint16_t __sanitizer_unaligned_load16(const void *p);
+uint32_t __sanitizer_unaligned_load32(const void *p);
+uint64_t __sanitizer_unaligned_load64(const void *p);
+void __sanitizer_unaligned_store16(void *p, uint16_t v);
+void __sanitizer_unaligned_store32(void *p, uint32_t v);
+void __sanitizer_unaligned_store64(void *p, uint64_t v);
+#ifdef __cplusplus
+} // extern "C"
+#endif // __cplusplus
+
+inline uint16 GOOGLE_UNALIGNED_LOAD16(const void *p) {
+ return __sanitizer_unaligned_load16(p);
+}
+
+inline uint32 GOOGLE_UNALIGNED_LOAD32(const void *p) {
+ return __sanitizer_unaligned_load32(p);
+}
+
+inline uint64 GOOGLE_UNALIGNED_LOAD64(const void *p) {
+ return __sanitizer_unaligned_load64(p);
+}
+
+inline void GOOGLE_UNALIGNED_STORE16(void *p, uint16 v) {
+ __sanitizer_unaligned_store16(p, v);
+}
+
+inline void GOOGLE_UNALIGNED_STORE32(void *p, uint32 v) {
+ __sanitizer_unaligned_store32(p, v);
+}
+
+inline void GOOGLE_UNALIGNED_STORE64(void *p, uint64 v) {
+ __sanitizer_unaligned_store64(p, v);
+}
+
+#elif GOOGLE_PROTOBUF_USE_UNALIGNED
#define GOOGLE_UNALIGNED_LOAD16(_p) (*reinterpret_cast<const uint16 *>(_p))
#define GOOGLE_UNALIGNED_LOAD32(_p) (*reinterpret_cast<const uint32 *>(_p))
@@ -346,7 +400,7 @@ class Bits {
public:
static uint32 Log2FloorNonZero(uint32 n) {
#if defined(__GNUC__)
- return 31 ^ __builtin_clz(n);
+ return 31 ^ static_cast<uint32>(__builtin_clz(n));
#elif defined(COMPILER_MSVC) && defined(_M_IX86)
_asm {
bsr ebx, n
@@ -358,9 +412,14 @@ class Bits {
#endif
}
- static uint64 Log2FloorNonZero64(uint64 n) {
-#if defined(__GNUC__)
- return 63 ^ __builtin_clzll(n);
+ static uint32 Log2FloorNonZero64(uint64 n) {
+ // arm-nacl-clang runs into an instruction-selection failure when it
+ // encounters __builtin_clzll:
+ // https://bugs.chromium.org/p/nativeclient/issues/detail?id=4395
+ // To work around this, when we build for NaCl we use the portable
+ // implementation instead.
+#if defined(__GNUC__) && !defined(GOOGLE_PROTOBUF_OS_NACL)
+ return 63 ^ static_cast<uint32>(__builtin_clzll(n));
#else
return Log2FloorNonZero64_Portable(n);
#endif
@@ -387,9 +446,9 @@ class Bits {
const uint32 topbits = static_cast<uint32>(n >> 32);
if (topbits == 0) {
// Top bits are zero, so scan in bottom bits
- return Log2FloorNonZero(static_cast<uint32>(n));
+ return static_cast<int>(Log2FloorNonZero(static_cast<uint32>(n)));
} else {
- return 32 + Log2FloorNonZero(topbits);
+ return 32 + static_cast<int>(Log2FloorNonZero(topbits));
}
}
};
@@ -454,6 +513,11 @@ class BigEndian {
}
};
+#ifndef GOOGLE_ATTRIBUTE_SECTION_VARIABLE
+#define GOOGLE_ATTRIBUTE_SECTION_VARIABLE(name)
+#endif
+
+#define GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(name)
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/stubs/shared_ptr.h b/src/google/protobuf/stubs/shared_ptr.h
index d250bf4d..7da114e9 100644
--- a/src/google/protobuf/stubs/shared_ptr.h
+++ b/src/google/protobuf/stubs/shared_ptr.h
@@ -428,11 +428,11 @@ class enable_shared_from_this {
shared_ptr<T> shared_from_this() {
// Behavior is undefined if the precondition isn't satisfied; we choose
// to die with a CHECK failure.
- CHECK(!weak_this_.expired()) << "No shared_ptr owns this object";
+ GOOGLE_CHECK(!weak_this_.expired()) << "No shared_ptr owns this object";
return weak_this_.lock();
}
shared_ptr<const T> shared_from_this() const {
- CHECK(!weak_this_.expired()) << "No shared_ptr owns this object";
+ GOOGLE_CHECK(!weak_this_.expired()) << "No shared_ptr owns this object";
return weak_this_.lock();
}
@@ -456,7 +456,8 @@ class enable_shared_from_this {
template<typename T>
void shared_ptr<T>::MaybeSetupWeakThis(enable_shared_from_this<T>* ptr) {
if (ptr) {
- CHECK(ptr->weak_this_.expired()) << "Object already owned by a shared_ptr";
+ GOOGLE_CHECK(ptr->weak_this_.expired())
+ << "Object already owned by a shared_ptr";
ptr->weak_this_ = *this;
}
}
diff --git a/src/google/protobuf/stubs/stringpiece.h b/src/google/protobuf/stubs/stringpiece.h
index 8910688b..563ff75d 100644
--- a/src/google/protobuf/stubs/stringpiece.h
+++ b/src/google/protobuf/stubs/stringpiece.h
@@ -292,7 +292,7 @@ class LIBPROTOBUF_EXPORT StringPiece {
int compare(StringPiece x) const {
const stringpiece_ssize_type min_size =
length_ < x.length_ ? length_ : x.length_;
- int r = memcmp(ptr_, x.ptr_, min_size);
+ int r = memcmp(ptr_, x.ptr_, static_cast<size_t>(min_size));
if (r < 0) return -1;
if (r > 0) return 1;
if (length_ < x.length_) return -1;
@@ -310,7 +310,7 @@ class LIBPROTOBUF_EXPORT StringPiece {
// "as_string()" method defined here for existing code.
string ToString() const {
if (ptr_ == NULL) return string();
- return string(data(), size());
+ return string(data(), static_cast<size_type>(size()));
}
operator string() const {
@@ -321,12 +321,14 @@ class LIBPROTOBUF_EXPORT StringPiece {
void AppendToString(string* target) const;
bool starts_with(StringPiece x) const {
- return (length_ >= x.length_) && (memcmp(ptr_, x.ptr_, x.length_) == 0);
+ return (length_ >= x.length_) &&
+ (memcmp(ptr_, x.ptr_, static_cast<size_t>(x.length_)) == 0);
}
bool ends_with(StringPiece x) const {
return ((length_ >= x.length_) &&
- (memcmp(ptr_ + (length_-x.length_), x.ptr_, x.length_) == 0));
+ (memcmp(ptr_ + (length_-x.length_), x.ptr_,
+ static_cast<size_t>(x.length_)) == 0));
}
// Checks whether StringPiece starts with x and if so advances the beginning
@@ -398,7 +400,7 @@ inline bool operator==(StringPiece x, StringPiece y) {
}
return x.data() == y.data() || len <= 0 ||
- memcmp(x.data(), y.data(), len) == 0;
+ memcmp(x.data(), y.data(), static_cast<size_t>(len)) == 0;
}
inline bool operator!=(StringPiece x, StringPiece y) {
@@ -408,7 +410,7 @@ inline bool operator!=(StringPiece x, StringPiece y) {
inline bool operator<(StringPiece x, StringPiece y) {
const stringpiece_ssize_type min_size =
x.size() < y.size() ? x.size() : y.size();
- const int r = memcmp(x.data(), y.data(), min_size);
+ const int r = memcmp(x.data(), y.data(), static_cast<size_t>(min_size));
return (r < 0) || (r == 0 && x.size() < y.size());
}
@@ -458,7 +460,9 @@ struct StringPiecePod {
return size_;
}
- std::string ToString() const { return std::string(data_, size_); }
+ std::string ToString() const {
+ return std::string(data_, static_cast<size_t>(size_));
+ }
private:
const char* data_;
stringpiece_ssize_type size_;
@@ -473,7 +477,7 @@ template<> struct hash<StringPiece> {
size_t operator()(const StringPiece& s) const {
size_t result = 0;
for (const char *str = s.data(), *end = str + s.size(); str < end; str++) {
- result = 5 * result + *str;
+ result = 5 * result + static_cast<size_t>(*str);
}
return result;
}
diff --git a/src/google/protobuf/stubs/stringpiece_unittest.cc b/src/google/protobuf/stubs/stringpiece_unittest.cc
index a52d81f8..a6a87595 100644
--- a/src/google/protobuf/stubs/stringpiece_unittest.cc
+++ b/src/google/protobuf/stubs/stringpiece_unittest.cc
@@ -783,11 +783,13 @@ TEST(FindOneCharTest, EdgeCases) {
EXPECT_EQ(StringPiece::npos, a.rfind('x'));
}
+#ifdef PROTOBUF_HAS_DEATH_TEST
#ifndef NDEBUG
TEST(NonNegativeLenTest, NonNegativeLen) {
EXPECT_DEATH(StringPiece("xyz", -1), "len >= 0");
}
#endif // ndef DEBUG
+#endif // PROTOBUF_HAS_DEATH_TEST
} // namespace
} // namespace protobuf
diff --git a/src/google/protobuf/stubs/strutil.cc b/src/google/protobuf/stubs/strutil.cc
index 15b6e53f..1a4d71c8 100644
--- a/src/google/protobuf/stubs/strutil.cc
+++ b/src/google/protobuf/stubs/strutil.cc
@@ -227,7 +227,7 @@ void SplitStringToIteratorUsing(const string& full,
void SplitStringUsing(const string& full,
const char* delim,
vector<string>* result) {
- back_insert_iterator< vector<string> > it(*result);
+ std::back_insert_iterator< vector<string> > it(*result);
SplitStringToIteratorUsing(full, delim, it);
}
@@ -265,7 +265,7 @@ void SplitStringToIteratorAllowEmpty(const StringType& full,
void SplitStringAllowEmpty(const string& full, const char* delim,
vector<string>* result) {
- back_insert_iterator<vector<string> > it(*result);
+ std::back_insert_iterator<vector<string> > it(*result);
SplitStringToIteratorAllowEmpty(full, delim, 0, it);
}
@@ -1262,10 +1262,10 @@ char* DoubleToBuffer(double value, char* buffer) {
// this assert.
GOOGLE_COMPILE_ASSERT(DBL_DIG < 20, DBL_DIG_is_too_big);
- if (value == numeric_limits<double>::infinity()) {
+ if (value == std::numeric_limits<double>::infinity()) {
strcpy(buffer, "inf");
return buffer;
- } else if (value == -numeric_limits<double>::infinity()) {
+ } else if (value == -std::numeric_limits<double>::infinity()) {
strcpy(buffer, "-inf");
return buffer;
} else if (MathLimits<double>::IsNaN(value)) {
@@ -1380,10 +1380,10 @@ char* FloatToBuffer(float value, char* buffer) {
// this assert.
GOOGLE_COMPILE_ASSERT(FLT_DIG < 10, FLT_DIG_is_too_big);
- if (value == numeric_limits<double>::infinity()) {
+ if (value == std::numeric_limits<double>::infinity()) {
strcpy(buffer, "inf");
return buffer;
- } else if (value == -numeric_limits<double>::infinity()) {
+ } else if (value == -std::numeric_limits<double>::infinity()) {
strcpy(buffer, "-inf");
return buffer;
} else if (MathLimits<float>::IsNaN(value)) {
@@ -1401,7 +1401,7 @@ char* FloatToBuffer(float value, char* buffer) {
float parsed_value;
if (!safe_strtof(buffer, &parsed_value) || parsed_value != value) {
int snprintf_result =
- snprintf(buffer, kFloatToBufferSize, "%.*g", FLT_DIG+2, value);
+ snprintf(buffer, kFloatToBufferSize, "%.*g", FLT_DIG+3, value);
// Should never overflow; see above.
GOOGLE_DCHECK(snprintf_result > 0 && snprintf_result < kFloatToBufferSize);
diff --git a/src/google/protobuf/test_messages_proto2.proto b/src/google/protobuf/test_messages_proto2.proto
new file mode 100644
index 00000000..60dbfc75
--- /dev/null
+++ b/src/google/protobuf/test_messages_proto2.proto
@@ -0,0 +1,216 @@
+// 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.
+//
+// Test schema for proto2 messages. This test schema is used by:
+//
+// - conformance tests
+//
+
+syntax = "proto2";
+
+package protobuf_test_messages.proto2;
+option java_package = "com.google.protobuf_test_messages.proto2";
+
+// This is the default, but we specify it here explicitly.
+option optimize_for = SPEED;
+
+option cc_enable_arenas = true;
+
+// This proto includes every type of field in both singular and repeated
+// forms.
+//
+// Also, crucially, all messages and enums in this file are eventually
+// submessages of this message. So for example, a fuzz test of TestAllTypes
+// could trigger bugs that occur in any message type in this file. We verify
+// this stays true in a unit test.
+message TestAllTypesProto2 {
+ message NestedMessage {
+ optional int32 a = 1;
+ optional TestAllTypesProto2 corecursive = 2;
+ }
+
+ enum NestedEnum {
+ FOO = 0;
+ BAR = 1;
+ BAZ = 2;
+ NEG = -1; // Intentionally negative.
+ }
+
+ // Singular
+ optional int32 optional_int32 = 1;
+ optional int64 optional_int64 = 2;
+ optional uint32 optional_uint32 = 3;
+ optional uint64 optional_uint64 = 4;
+ optional sint32 optional_sint32 = 5;
+ optional sint64 optional_sint64 = 6;
+ optional fixed32 optional_fixed32 = 7;
+ optional fixed64 optional_fixed64 = 8;
+ optional sfixed32 optional_sfixed32 = 9;
+ optional sfixed64 optional_sfixed64 = 10;
+ optional float optional_float = 11;
+ optional double optional_double = 12;
+ optional bool optional_bool = 13;
+ optional string optional_string = 14;
+ optional bytes optional_bytes = 15;
+
+ optional NestedMessage optional_nested_message = 18;
+ optional ForeignMessageProto2 optional_foreign_message = 19;
+
+ optional NestedEnum optional_nested_enum = 21;
+ optional ForeignEnumProto2 optional_foreign_enum = 22;
+
+ optional string optional_string_piece = 24 [ctype=STRING_PIECE];
+ optional string optional_cord = 25 [ctype=CORD];
+
+ optional TestAllTypesProto2 recursive_message = 27;
+
+ // 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 ForeignMessageProto2 repeated_foreign_message = 49;
+
+ repeated NestedEnum repeated_nested_enum = 51;
+ repeated ForeignEnumProto2 repeated_foreign_enum = 52;
+
+ repeated string repeated_string_piece = 54 [ctype=STRING_PIECE];
+ repeated string repeated_cord = 55 [ctype=CORD];
+
+ // Map
+ map < int32, int32> map_int32_int32 = 56;
+ map < int64, int64> map_int64_int64 = 57;
+ map < uint32, uint32> map_uint32_uint32 = 58;
+ map < uint64, uint64> map_uint64_uint64 = 59;
+ map < sint32, sint32> map_sint32_sint32 = 60;
+ map < sint64, sint64> map_sint64_sint64 = 61;
+ map < fixed32, fixed32> map_fixed32_fixed32 = 62;
+ map < fixed64, fixed64> map_fixed64_fixed64 = 63;
+ map <sfixed32, sfixed32> map_sfixed32_sfixed32 = 64;
+ map <sfixed64, sfixed64> map_sfixed64_sfixed64 = 65;
+ map < int32, float> map_int32_float = 66;
+ map < int32, double> map_int32_double = 67;
+ map < bool, bool> map_bool_bool = 68;
+ map < string, string> map_string_string = 69;
+ map < string, bytes> map_string_bytes = 70;
+ map < string, NestedMessage> map_string_nested_message = 71;
+ map < string, ForeignMessageProto2> map_string_foreign_message = 72;
+ map < string, NestedEnum> map_string_nested_enum = 73;
+ map < string, ForeignEnumProto2> map_string_foreign_enum = 74;
+
+ oneof oneof_field {
+ uint32 oneof_uint32 = 111;
+ NestedMessage oneof_nested_message = 112;
+ string oneof_string = 113;
+ bytes oneof_bytes = 114;
+ bool oneof_bool = 115;
+ uint64 oneof_uint64 = 116;
+ float oneof_float = 117;
+ double oneof_double = 118;
+ NestedEnum oneof_enum = 119;
+ }
+
+ // extensions
+ extensions 120 to 200;
+
+ // groups
+ optional group Data = 201 {
+ optional int32 group_int32 = 202;
+ optional uint32 group_uint32 = 203;
+ };
+
+ // Test field-name-to-JSON-name convention.
+ // (protobuf says names can be any valid C/C++ identifier.)
+ optional int32 fieldname1 = 401;
+ optional int32 field_name2 = 402;
+ optional int32 _field_name3 = 403;
+ optional int32 field__name4_ = 404;
+ optional int32 field0name5 = 405;
+ optional int32 field_0_name6 = 406;
+ optional int32 fieldName7 = 407;
+ optional int32 FieldName8 = 408;
+ optional int32 field_Name9 = 409;
+ optional int32 Field_Name10 = 410;
+ optional int32 FIELD_NAME11 = 411;
+ optional int32 FIELD_name12 = 412;
+ optional int32 __field_name13 = 413;
+ optional int32 __Field_name14 = 414;
+ optional int32 field__name15 = 415;
+ optional int32 field__Name16 = 416;
+ optional int32 field_name17__ = 417;
+ optional int32 Field_name18__ = 418;
+
+ // message_set test case.
+ message MessageSetCorrect {
+ option message_set_wire_format = true;
+ extensions 4 to max;
+ }
+
+ message MessageSetCorrectExtension1 {
+ extend MessageSetCorrect {
+ optional MessageSetCorrectExtension1 message_set_extension = 1547769;
+ }
+ optional string str = 25;
+ }
+
+ message MessageSetCorrectExtension2 {
+ extend MessageSetCorrect {
+ optional MessageSetCorrectExtension2 message_set_extension = 4135312;
+ }
+ optional int32 i = 9;
+ }
+}
+
+message ForeignMessageProto2 {
+ optional int32 c = 1;
+}
+
+enum ForeignEnumProto2 {
+ FOREIGN_FOO = 0;
+ FOREIGN_BAR = 1;
+ FOREIGN_BAZ = 2;
+}
+
+extend TestAllTypesProto2 {
+ optional int32 extension_int32 = 120;
+}
diff --git a/src/google/protobuf/test_messages_proto3.proto b/src/google/protobuf/test_messages_proto3.proto
index 79230334..4f295aac 100644
--- a/src/google/protobuf/test_messages_proto3.proto
+++ b/src/google/protobuf/test_messages_proto3.proto
@@ -39,6 +39,7 @@ syntax = "proto3";
package protobuf_test_messages.proto3;
option java_package = "com.google.protobuf_test_messages.proto3";
+option objc_class_prefix = "Proto3";
// This is the default, but we specify it here explicitly.
option optimize_for = SPEED;
@@ -59,10 +60,10 @@ option cc_enable_arenas = true;
// submessages of this message. So for example, a fuzz test of TestAllTypes
// could trigger bugs that occur in any message type in this file. We verify
// this stays true in a unit test.
-message TestAllTypes {
+message TestAllTypesProto3 {
message NestedMessage {
int32 a = 1;
- TestAllTypes corecursive = 2;
+ TestAllTypesProto3 corecursive = 2;
}
enum NestedEnum {
@@ -98,7 +99,7 @@ message TestAllTypes {
string optional_string_piece = 24 [ctype=STRING_PIECE];
string optional_cord = 25 [ctype=CORD];
- TestAllTypes recursive_message = 27;
+ TestAllTypesProto3 recursive_message = 27;
// Repeated
repeated int32 repeated_int32 = 31;
@@ -214,6 +215,9 @@ message TestAllTypes {
int32 field__Name16 = 416;
int32 field_name17__ = 417;
int32 Field_name18__ = 418;
+
+ // Reserved for testing unknown fields
+ reserved 501 to 510;
}
message ForeignMessage {
diff --git a/src/google/protobuf/test_util_lite.cc b/src/google/protobuf/test_util_lite.cc
index 388c0cbd..79c5abec 100644
--- a/src/google/protobuf/test_util_lite.cc
+++ b/src/google/protobuf/test_util_lite.cc
@@ -35,14 +35,9 @@
#include <google/protobuf/test_util_lite.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
+#include <gtest/gtest.h>
-#define EXPECT_TRUE GOOGLE_CHECK
-#define ASSERT_TRUE GOOGLE_CHECK
-#define EXPECT_FALSE(COND) GOOGLE_CHECK(!(COND))
-#define EXPECT_EQ GOOGLE_CHECK_EQ
-#define ASSERT_EQ GOOGLE_CHECK_EQ
-
namespace google {
namespace protobuf {
diff --git a/src/google/protobuf/testing/file.cc b/src/google/protobuf/testing/file.cc
index 470512ed..f68aba9a 100644
--- a/src/google/protobuf/testing/file.cc
+++ b/src/google/protobuf/testing/file.cc
@@ -38,24 +38,31 @@
#ifdef _MSC_VER
#define WIN32_LEAN_AND_MEAN // yeah, right
#include <windows.h> // Find*File(). :(
-#include <io.h>
-#include <direct.h>
+// #include <direct.h>
#else
#include <dirent.h>
#include <unistd.h>
#endif
#include <errno.h>
+#include <google/protobuf/stubs/io_win32.h>
+
namespace google {
namespace protobuf {
#ifdef _WIN32
-#define mkdir(name, mode) mkdir(name)
// Windows doesn't have symbolic links.
#define lstat stat
-#ifndef F_OK
-#define F_OK 00 // not defined by MSVC for whatever reason
+// DO NOT include <io.h>, instead create functions in io_win32.{h,cc} and import
+// them like we do below.
#endif
+
+#ifdef _MSC_VER
+using google::protobuf::internal::win32::access;
+using google::protobuf::internal::win32::chdir;
+using google::protobuf::internal::win32::fopen;
+using google::protobuf::internal::win32::mkdir;
+using google::protobuf::internal::win32::stat;
#endif
bool File::Exists(const string& name) {
@@ -113,6 +120,9 @@ void File::WriteStringToFileOrDie(const string& contents, const string& name) {
}
bool File::CreateDir(const string& name, int mode) {
+ if (!name.empty()) {
+ GOOGLE_CHECK_OK(name[name.size() - 1] != '.');
+ }
return mkdir(name.c_str(), mode) == 0;
}
diff --git a/src/google/protobuf/testing/googletest.cc b/src/google/protobuf/testing/googletest.cc
index d45706b6..91f0ef89 100644
--- a/src/google/protobuf/testing/googletest.cc
+++ b/src/google/protobuf/testing/googletest.cc
@@ -33,14 +33,14 @@
#include <google/protobuf/testing/googletest.h>
#include <google/protobuf/testing/file.h>
+#include <google/protobuf/stubs/io_win32.h>
#include <google/protobuf/stubs/strutil.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <stdlib.h>
#ifdef _MSC_VER
-#include <io.h>
-#include <direct.h>
+// #include <direct.h>
#else
#include <unistd.h>
#endif
@@ -52,8 +52,14 @@
namespace google {
namespace protobuf {
-#ifdef _WIN32
-#define mkdir(name, mode) mkdir(name)
+#ifdef _MSC_VER
+// DO NOT include <io.h>, instead create functions in io_win32.{h,cc} and import
+// them like we do below.
+using google::protobuf::internal::win32::close;
+using google::protobuf::internal::win32::dup2;
+using google::protobuf::internal::win32::dup;
+using google::protobuf::internal::win32::mkdir;
+using google::protobuf::internal::win32::open;
#endif
#ifndef O_BINARY
@@ -111,14 +117,32 @@ string GetTemporaryDirectoryName() {
char b[L_tmpnam + 1]; // HPUX multithread return 0 if s is 0
string result = tmpnam(b);
#ifdef _WIN32
+ // Avoid a trailing dot by changing it to an underscore. On Win32 the names of
+ // files and directories can, but should not, end with dot.
+ //
+ // In MS-DOS and FAT16 filesystem the filenames were 8dot3 style so it didn't
+ // make sense to have a name ending in dot without an extension, so the shell
+ // silently ignored trailing dots. To this day the Win32 API still maintains
+ // this behavior and silently ignores trailing dots in path arguments of
+ // functions such as CreateFile{A,W}. Even POSIX API function implementations
+ // seem to wrap the Win32 API functions (e.g. CreateDirectoryA) and behave
+ // this way.
+ // It's possible to avoid this behavior and create files / directories with
+ // trailing dots (using CreateFileW / CreateDirectoryW and prefixing the path
+ // with "\\?\") but these will be degenerate in the sense that you cannot
+ // chdir into such directories (or navigate into them with Windows Explorer)
+ // nor can you open such files with some programs (e.g. Notepad).
+ if (result.back() == '.') {
+ result[result.size() - 1] = '_';
+ }
// On Win32, tmpnam() returns a file prefixed with '\', but which is supposed
// to be used in the current working directory. WTF?
if (HasPrefixString(result, "\\")) {
result.erase(0, 1);
}
- // The Win32 API accepts forward slashes as a path delimiter even though
- // backslashes are standard. Let's avoid confusion and use only forward
- // slashes.
+ // The Win32 API accepts forward slashes as a path delimiter as long as the
+ // path doesn't use the "\\?\" prefix.
+ // Let's avoid confusion and use only forward slashes.
result = StringReplace(result, "\\", "/", true);
#endif // _WIN32
return result;
@@ -262,6 +286,8 @@ namespace {
struct ForceShutdown {
~ForceShutdown() {
ShutdownProtobufLibrary();
+ // Test to shutdown the library twice, which should succeed.
+ ShutdownProtobufLibrary();
}
} force_shutdown;
diff --git a/src/google/protobuf/testing/googletest.h b/src/google/protobuf/testing/googletest.h
index c0d99e69..2db3bfee 100644
--- a/src/google/protobuf/testing/googletest.h
+++ b/src/google/protobuf/testing/googletest.h
@@ -37,9 +37,10 @@
#include <map>
#include <vector>
#include <google/protobuf/stubs/common.h>
-
+#include <gmock/gmock.h>
// Disable death tests if we use exceptions in CHECK().
-#if !PROTOBUF_USE_EXCEPTIONS && defined(GTEST_HAS_DEATH_TEST)
+#if !PROTOBUF_USE_EXCEPTIONS && defined(GTEST_HAS_DEATH_TEST) && \
+ !GTEST_OS_WINDOWS
#define PROTOBUF_HAS_DEATH_TEST
#endif
@@ -85,7 +86,7 @@ class ScopedMemoryLog {
const vector<string>& GetMessages(LogLevel error);
private:
- map<LogLevel, vector<string> > messages_;
+ std::map<LogLevel, vector<string> > messages_;
LogHandler* old_handler_;
static void HandleLog(LogLevel level, const char* filename, int line,
diff --git a/src/google/protobuf/testing/zcgunzip.cc b/src/google/protobuf/testing/zcgunzip.cc
index 76f8cfe1..349ad86e 100644
--- a/src/google/protobuf/testing/zcgunzip.cc
+++ b/src/google/protobuf/testing/zcgunzip.cc
@@ -72,7 +72,10 @@ int main(int argc, const char** argv) {
}
if (inlen > 0) {
int err = write(STDOUT_FILENO, inptr, inlen);
- assert(err == inlen);
+ if (err != inlen) {
+ fprintf(stderr, "write unexpectedly returned %d.\n", err);
+ return 1;
+ }
}
}
diff --git a/src/google/protobuf/text_format.cc b/src/google/protobuf/text_format.cc
index e3d908ec..eed2a768 100644
--- a/src/google/protobuf/text_format.cc
+++ b/src/google/protobuf/text_format.cc
@@ -42,20 +42,21 @@
#include <google/protobuf/text_format.h>
-#include <google/protobuf/descriptor.h>
-#include <google/protobuf/dynamic_message.h>
-#include <google/protobuf/repeated_field.h>
-#include <google/protobuf/wire_format_lite.h>
+#include <google/protobuf/stubs/stringprintf.h>
+#include <google/protobuf/any.h>
#include <google/protobuf/io/strtod.h>
#include <google/protobuf/io/coded_stream.h>
+#include <google/protobuf/io/tokenizer.h>
#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
-#include <google/protobuf/unknown_field_set.h>
#include <google/protobuf/descriptor.pb.h>
-#include <google/protobuf/io/tokenizer.h>
-#include <google/protobuf/any.h>
-#include <google/protobuf/stubs/stringprintf.h>
+#include <google/protobuf/descriptor.h>
+#include <google/protobuf/dynamic_message.h>
+#include <google/protobuf/repeated_field.h>
+#include <google/protobuf/unknown_field_set.h>
+#include <google/protobuf/wire_format_lite.h>
#include <google/protobuf/stubs/strutil.h>
+
#include <google/protobuf/stubs/map_util.h>
#include <google/protobuf/stubs/stl_util.h>
@@ -74,18 +75,6 @@ inline bool IsOctNumber(const string& str) {
(str[1] >= '0' && str[1] < '8'));
}
-inline bool GetAnyFieldDescriptors(const Message& message,
- const FieldDescriptor** type_url_field,
- const FieldDescriptor** value_field) {
- const Descriptor* descriptor = message.GetDescriptor();
- *type_url_field = descriptor->FindFieldByNumber(1);
- *value_field = descriptor->FindFieldByNumber(2);
- return (*type_url_field != NULL &&
- (*type_url_field)->type() == FieldDescriptor::TYPE_STRING &&
- *value_field != NULL &&
- (*value_field)->type() == FieldDescriptor::TYPE_BYTES);
-}
-
} // namespace
string Message::DebugString() const {
@@ -376,7 +365,7 @@ class TextFormat::Parser::ParserImpl {
const Descriptor* descriptor = message->GetDescriptor();
string field_name;
-
+ bool reserved_field = false;
const FieldDescriptor* field = NULL;
int start_line = tokenizer_.current().line;
int start_column = tokenizer_.current().column;
@@ -438,6 +427,8 @@ class TextFormat::Parser::ParserImpl {
if (allow_field_number_ && safe_strto32(field_name, &field_number)) {
if (descriptor->IsExtensionNumber(field_number)) {
field = reflection->FindKnownExtensionByNumber(field_number);
+ } else if (descriptor->IsReservedNumber(field_number)) {
+ reserved_field = true;
} else {
field = descriptor->FindFieldByNumber(field_number);
}
@@ -466,9 +457,13 @@ class TextFormat::Parser::ParserImpl {
LowerString(&lower_field_name);
field = descriptor->FindFieldByLowercaseName(lower_field_name);
}
+
+ if (field == NULL) {
+ reserved_field = descriptor->IsReservedName(field_name);
+ }
}
- if (field == NULL) {
+ if (field == NULL && !reserved_field) {
if (!allow_unknown_field_) {
ReportError("Message type \"" + descriptor->full_name() +
"\" has no field named \"" + field_name + "\".");
@@ -480,9 +475,10 @@ class TextFormat::Parser::ParserImpl {
}
}
- // Skips unknown field.
+ // Skips unknown or reserved fields.
if (field == NULL) {
- GOOGLE_CHECK(allow_unknown_field_);
+ GOOGLE_CHECK(allow_unknown_field_ || reserved_field);
+
// Try to guess the type of this field.
// If this field is not a message, there should be a ":" between the
// field name and the field value and also the field value should not
@@ -1159,7 +1155,8 @@ label_skip_parsing:
// ===========================================================================
// Internal class for writing text to the io::ZeroCopyOutputStream. Adapted
// from the Printer found in //google/protobuf/io/printer.h
-class TextFormat::Printer::TextGenerator {
+class TextFormat::Printer::TextGenerator
+ : public TextFormat::BaseTextGenerator {
public:
explicit TextGenerator(io::ZeroCopyOutputStream* output,
int initial_indent_level)
@@ -1168,9 +1165,8 @@ class TextFormat::Printer::TextGenerator {
buffer_size_(0),
at_start_of_line_(true),
failed_(false),
- indent_(""),
+ indent_level_(initial_indent_level),
initial_indent_level_(initial_indent_level) {
- indent_.resize(initial_indent_level_ * 2, ' ');
}
~TextGenerator() {
@@ -1185,50 +1181,45 @@ class TextFormat::Printer::TextGenerator {
// inserted at the beginning of each line of text. Indent() may be called
// multiple times to produce deeper indents.
void Indent() {
- indent_ += " ";
+ ++indent_level_;
}
// Reduces the current indent level by two spaces, or crashes if the indent
// level is zero.
void Outdent() {
- if (indent_.empty() ||
- indent_.size() < initial_indent_level_ * 2) {
+ if (indent_level_ == 0 ||
+ indent_level_ < initial_indent_level_) {
GOOGLE_LOG(DFATAL) << " Outdent() without matching Indent().";
return;
}
- indent_.resize(indent_.size() - 2);
- }
-
- // Print text to the output stream.
- void Print(const string& str) {
- Print(str.data(), str.size());
- }
-
- // Print text to the output stream.
- void Print(const char* text) {
- Print(text, strlen(text));
+ --indent_level_;
}
// Print text to the output stream.
void Print(const char* text, size_t size) {
- size_t pos = 0; // The number of bytes we've written so far.
-
- for (size_t i = 0; i < size; i++) {
- if (text[i] == '\n') {
- // Saw newline. If there is more text, we may need to insert an indent
- // here. So, write what we have so far, including the '\n'.
- Write(text + pos, i - pos + 1);
- pos = i + 1;
-
- // Setting this true will cause the next Write() to insert an indent
- // first.
+ if (indent_level_ > 0) {
+ size_t pos = 0; // The number of bytes we've written so far.
+ for (size_t i = 0; i < size; i++) {
+ if (text[i] == '\n') {
+ // Saw newline. If there is more text, we may need to insert an
+ // indent here. So, write what we have so far, including the '\n'.
+ Write(text + pos, i - pos + 1);
+ pos = i + 1;
+
+ // Setting this true will cause the next Write() to insert an indent
+ // first.
+ at_start_of_line_ = true;
+ }
+ }
+ // Write the rest.
+ Write(text + pos, size - pos);
+ } else {
+ Write(text, size);
+ if (size > 0 && text[size - 1] == '\n') {
at_start_of_line_ = true;
}
}
-
- // Write the rest.
- Write(text + pos, size - pos);
}
// True if any write to the underlying stream failed. (We don't just
@@ -1246,15 +1237,39 @@ class TextFormat::Printer::TextGenerator {
if (at_start_of_line_) {
// Insert an indent.
at_start_of_line_ = false;
- Write(indent_.data(), indent_.size());
+ WriteIndent();
if (failed_) return;
}
while (size > buffer_size_) {
// Data exceeds space in the buffer. Copy what we can and request a
// new buffer.
- memcpy(buffer_, data, buffer_size_);
- data += buffer_size_;
+ if (buffer_size_ > 0) {
+ memcpy(buffer_, data, buffer_size_);
+ data += buffer_size_;
+ size -= buffer_size_;
+ }
+ void* void_buffer = NULL;
+ failed_ = !output_->Next(&void_buffer, &buffer_size_);
+ if (failed_) return;
+ buffer_ = reinterpret_cast<char*>(void_buffer);
+ }
+
+ // Buffer is big enough to receive the data; copy it.
+ memcpy(buffer_, data, size);
+ buffer_ += size;
+ buffer_size_ -= size;
+ }
+
+ void WriteIndent() {
+ if (indent_level_ == 0) { return; }
+ GOOGLE_DCHECK(!failed_);
+ int size = 2 * indent_level_;
+
+ while (size > buffer_size_) {
+ // Data exceeds space in the buffer. Write what we can and request a new
+ // buffer.
+ memset(buffer_, ' ', buffer_size_);
size -= buffer_size_;
void* void_buffer;
failed_ = !output_->Next(&void_buffer, &buffer_size_);
@@ -1263,7 +1278,7 @@ class TextFormat::Printer::TextGenerator {
}
// Buffer is big enough to receive the data; copy it.
- memcpy(buffer_, data, size);
+ memset(buffer_, ' ', size);
buffer_ += size;
buffer_size_ -= size;
}
@@ -1274,7 +1289,7 @@ class TextFormat::Printer::TextGenerator {
bool at_start_of_line_;
bool failed_;
- string indent_;
+ int indent_level_;
int initial_indent_level_;
};
@@ -1322,6 +1337,7 @@ bool TextFormat::Parser::ParseFromString(const string& input,
return Parse(&input_stream, output);
}
+
bool TextFormat::Parser::Merge(io::ZeroCopyInputStream* input,
Message* output) {
ParserImpl parser(output->GetDescriptor(), input, error_collector_,
@@ -1339,6 +1355,7 @@ bool TextFormat::Parser::MergeFromString(const string& input,
return Merge(&input_stream, output);
}
+
bool TextFormat::Parser::MergeUsingImpl(io::ZeroCopyInputStream* /* input */,
Message* output,
ParserImpl* parser_impl) {
@@ -1387,92 +1404,277 @@ bool TextFormat::Parser::ParseFieldValueFromString(
return Parser().MergeFromString(input, output);
}
+
// ===========================================================================
-// The default implementation for FieldValuePrinter. The base class just
-// does simple formatting. That way, deriving classes could decide to fallback
-// to that behavior.
+TextFormat::BaseTextGenerator::~BaseTextGenerator() {}
+
+namespace {
+
+// A BaseTextGenerator that writes to a string.
+class StringBaseTextGenerator : public TextFormat::BaseTextGenerator {
+ public:
+ void Print(const char* text, size_t size) { output_.append(text, size); }
+
+// Some compilers do not support ref-qualifiers even in C++11 mode.
+// Disable the optimization for now and revisit it later.
+#if 0 // LANG_CXX11
+ string Consume() && { return std::move(output_); }
+#else // !LANG_CXX11
+ const string& Get() { return output_; }
+#endif // LANG_CXX11
+
+ private:
+ string output_;
+};
+
+} // namespace
+
+// The default implementation for FieldValuePrinter. We just delegate the
+// implementation to the default FastFieldValuePrinter to avoid duplicating the
+// logic.
TextFormat::FieldValuePrinter::FieldValuePrinter() {}
TextFormat::FieldValuePrinter::~FieldValuePrinter() {}
+
+#if 0 // LANG_CXX11
+#define FORWARD_IMPL(fn, ...) \
+ StringBaseTextGenerator generator; \
+ delegate_.fn(__VA_ARGS__, &generator); \
+ return std::move(generator).Consume()
+#else // !LANG_CXX11
+#define FORWARD_IMPL(fn, ...) \
+ StringBaseTextGenerator generator; \
+ delegate_.fn(__VA_ARGS__, &generator); \
+ return generator.Get()
+#endif // LANG_CXX11
+
string TextFormat::FieldValuePrinter::PrintBool(bool val) const {
- return val ? "true" : "false";
+ FORWARD_IMPL(PrintBool, val);
}
string TextFormat::FieldValuePrinter::PrintInt32(int32 val) const {
- return SimpleItoa(val);
+ FORWARD_IMPL(PrintInt32, val);
}
string TextFormat::FieldValuePrinter::PrintUInt32(uint32 val) const {
- return SimpleItoa(val);
+ FORWARD_IMPL(PrintUInt32, val);
}
string TextFormat::FieldValuePrinter::PrintInt64(int64 val) const {
- return SimpleItoa(val);
+ FORWARD_IMPL(PrintInt64, val);
}
string TextFormat::FieldValuePrinter::PrintUInt64(uint64 val) const {
- return SimpleItoa(val);
+ FORWARD_IMPL(PrintUInt64, val);
}
string TextFormat::FieldValuePrinter::PrintFloat(float val) const {
- return SimpleFtoa(val);
+ FORWARD_IMPL(PrintFloat, val);
}
string TextFormat::FieldValuePrinter::PrintDouble(double val) const {
- return SimpleDtoa(val);
+ FORWARD_IMPL(PrintDouble, val);
}
string TextFormat::FieldValuePrinter::PrintString(const string& val) const {
- string printed("\"");
- CEscapeAndAppend(val, &printed);
- printed.push_back('\"');
- return printed;
+ FORWARD_IMPL(PrintString, val);
}
string TextFormat::FieldValuePrinter::PrintBytes(const string& val) const {
return PrintString(val);
}
string TextFormat::FieldValuePrinter::PrintEnum(int32 val,
const string& name) const {
- return name;
+ FORWARD_IMPL(PrintEnum, val, name);
}
string TextFormat::FieldValuePrinter::PrintFieldName(
const Message& message,
const Reflection* reflection,
const FieldDescriptor* field) const {
- if (field->is_extension()) {
- // We special-case MessageSet elements for compatibility with proto1.
- if (field->containing_type()->options().message_set_wire_format()
- && field->type() == FieldDescriptor::TYPE_MESSAGE
- && field->is_optional()
- && field->extension_scope() == field->message_type()) {
- return StrCat("[", field->message_type()->full_name(), "]");
- } else {
- return StrCat("[", field->full_name(), "]");
- }
- } else if (field->type() == FieldDescriptor::TYPE_GROUP) {
- // Groups must be serialized with their original capitalization.
- return field->message_type()->name();
- } else {
- return field->name();
- }
+ FORWARD_IMPL(PrintFieldName, message, reflection, field);
}
string TextFormat::FieldValuePrinter::PrintMessageStart(
const Message& message,
int field_index,
int field_count,
bool single_line_mode) const {
- return single_line_mode ? " { " : " {\n";
+ FORWARD_IMPL(PrintMessageStart, message, field_index, field_count,
+ single_line_mode);
}
string TextFormat::FieldValuePrinter::PrintMessageEnd(
const Message& message,
int field_index,
int field_count,
bool single_line_mode) const {
- return single_line_mode ? "} " : "}\n";
+ FORWARD_IMPL(PrintMessageEnd, message, field_index, field_count,
+ single_line_mode);
+}
+#undef FORWARD_IMPL
+
+TextFormat::FastFieldValuePrinter::FastFieldValuePrinter() {}
+TextFormat::FastFieldValuePrinter::~FastFieldValuePrinter() {}
+void TextFormat::FastFieldValuePrinter::PrintBool(
+ bool val, BaseTextGenerator* generator) const {
+ if (val) {
+ generator->PrintLiteral("true");
+ } else {
+ generator->PrintLiteral("false");
+ }
+}
+void TextFormat::FastFieldValuePrinter::PrintInt32(
+ int32 val, BaseTextGenerator* generator) const {
+ generator->PrintString(SimpleItoa(val));
+}
+void TextFormat::FastFieldValuePrinter::PrintUInt32(
+ uint32 val, BaseTextGenerator* generator) const {
+ generator->PrintString(SimpleItoa(val));
+}
+void TextFormat::FastFieldValuePrinter::PrintInt64(
+ int64 val, BaseTextGenerator* generator) const {
+ generator->PrintString(SimpleItoa(val));
+}
+void TextFormat::FastFieldValuePrinter::PrintUInt64(
+ uint64 val, BaseTextGenerator* generator) const {
+ generator->PrintString(SimpleItoa(val));
+}
+void TextFormat::FastFieldValuePrinter::PrintFloat(
+ float val, BaseTextGenerator* generator) const {
+ generator->PrintString(SimpleFtoa(val));
+}
+void TextFormat::FastFieldValuePrinter::PrintDouble(
+ double val, BaseTextGenerator* generator) const {
+ generator->PrintString(SimpleDtoa(val));
+}
+void TextFormat::FastFieldValuePrinter::PrintEnum(
+ int32 val, const string& name, BaseTextGenerator* generator) const {
+ generator->PrintString(name);
+}
+
+void TextFormat::FastFieldValuePrinter::PrintString(
+ const string& val, BaseTextGenerator* generator) const {
+ generator->PrintLiteral("\"");
+ generator->PrintString(CEscape(val));
+ generator->PrintLiteral("\"");
+}
+void TextFormat::FastFieldValuePrinter::PrintBytes(
+ const string& val, BaseTextGenerator* generator) const {
+ PrintString(val, generator);
+}
+void TextFormat::FastFieldValuePrinter::PrintFieldName(
+ const Message& message, const Reflection* reflection,
+ const FieldDescriptor* field, BaseTextGenerator* generator) const {
+ if (field->is_extension()) {
+ generator->PrintLiteral("[");
+ // We special-case MessageSet elements for compatibility with proto1.
+ if (field->containing_type()->options().message_set_wire_format() &&
+ field->type() == FieldDescriptor::TYPE_MESSAGE &&
+ field->is_optional() &&
+ field->extension_scope() == field->message_type()) {
+ generator->PrintString(field->message_type()->full_name());
+ } else {
+ generator->PrintString(field->full_name());
+ }
+ generator->PrintLiteral("]");
+ } else if (field->type() == FieldDescriptor::TYPE_GROUP) {
+ // Groups must be serialized with their original capitalization.
+ generator->PrintString(field->message_type()->name());
+ } else {
+ generator->PrintString(field->name());
+ }
+}
+void TextFormat::FastFieldValuePrinter::PrintMessageStart(
+ const Message& message, int field_index, int field_count,
+ bool single_line_mode, BaseTextGenerator* generator) const {
+ if (single_line_mode) {
+ generator->PrintLiteral(" { ");
+ } else {
+ generator->PrintLiteral(" {\n");
+ }
+}
+void TextFormat::FastFieldValuePrinter::PrintMessageEnd(
+ const Message& message, int field_index, int field_count,
+ bool single_line_mode, BaseTextGenerator* generator) const {
+ if (single_line_mode) {
+ generator->PrintLiteral("} ");
+ } else {
+ generator->PrintLiteral("}\n");
+ }
}
namespace {
+
+// A legacy compatibility wrapper. Takes ownership of the delegate.
+class FieldValuePrinterWrapper : public TextFormat::FastFieldValuePrinter {
+ public:
+ explicit FieldValuePrinterWrapper(
+ const TextFormat::FieldValuePrinter* delegate)
+ : delegate_(delegate) {}
+
+ void SetDelegate(const TextFormat::FieldValuePrinter* delegate) {
+ delegate_.reset(delegate);
+ }
+
+ void PrintBool(bool val, TextFormat::BaseTextGenerator* generator) const {
+ generator->PrintString(delegate_->PrintBool(val));
+ }
+ void PrintInt32(int32 val, TextFormat::BaseTextGenerator* generator) const {
+ generator->PrintString(delegate_->PrintInt32(val));
+ }
+ void PrintUInt32(uint32 val, TextFormat::BaseTextGenerator* generator) const {
+ generator->PrintString(delegate_->PrintUInt32(val));
+ }
+ void PrintInt64(int64 val, TextFormat::BaseTextGenerator* generator) const {
+ generator->PrintString(delegate_->PrintInt64(val));
+ }
+ void PrintUInt64(uint64 val, TextFormat::BaseTextGenerator* generator) const {
+ generator->PrintString(delegate_->PrintUInt64(val));
+ }
+ void PrintFloat(float val, TextFormat::BaseTextGenerator* generator) const {
+ generator->PrintString(delegate_->PrintFloat(val));
+ }
+ void PrintDouble(double val, TextFormat::BaseTextGenerator* generator) const {
+ generator->PrintString(delegate_->PrintDouble(val));
+ }
+ void PrintString(const string& val,
+ TextFormat::BaseTextGenerator* generator) const {
+ generator->PrintString(delegate_->PrintString(val));
+ }
+ void PrintBytes(const string& val,
+ TextFormat::BaseTextGenerator* generator) const {
+ generator->PrintString(delegate_->PrintBytes(val));
+ }
+ void PrintEnum(int32 val, const string& name,
+ TextFormat::BaseTextGenerator* generator) const {
+ generator->PrintString(delegate_->PrintEnum(val, name));
+ }
+ void PrintFieldName(const Message& message, const Reflection* reflection,
+ const FieldDescriptor* field,
+ TextFormat::BaseTextGenerator* generator) const {
+ generator->PrintString(
+ delegate_->PrintFieldName(message, reflection, field));
+ }
+ void PrintMessageStart(const Message& message, int field_index,
+ int field_count, bool single_line_mode,
+ TextFormat::BaseTextGenerator* generator) const {
+ generator->PrintString(delegate_->PrintMessageStart(
+ message, field_index, field_count, single_line_mode));
+ }
+ void PrintMessageEnd(const Message& message, int field_index, int field_count,
+ bool single_line_mode,
+ TextFormat::BaseTextGenerator* generator) const {
+ generator->PrintString(delegate_->PrintMessageEnd(
+ message, field_index, field_count, single_line_mode));
+ }
+
+ private:
+ google::protobuf::scoped_ptr<const TextFormat::FieldValuePrinter> delegate_;
+};
+
// Our own specialization: for UTF8 escaped strings.
-class FieldValuePrinterUtf8Escaping : public TextFormat::FieldValuePrinter {
+class FastFieldValuePrinterUtf8Escaping
+ : public TextFormat::FastFieldValuePrinter {
public:
- virtual string PrintString(const string& val) const {
- return StrCat("\"", strings::Utf8SafeCEscape(val), "\"");
+ void PrintString(const string& val,
+ TextFormat::BaseTextGenerator* generator) const {
+ generator->PrintLiteral("\"");
+ generator->PrintString(strings::Utf8SafeCEscape(val));
+ generator->PrintLiteral("\"");
}
- virtual string PrintBytes(const string& val) const {
- return TextFormat::FieldValuePrinter::PrintString(val);
+ void PrintBytes(const string& val,
+ TextFormat::BaseTextGenerator* generator) const {
+ return FastFieldValuePrinter::PrintString(val, generator);
}
};
@@ -1495,19 +1697,39 @@ TextFormat::Printer::~Printer() {
}
void TextFormat::Printer::SetUseUtf8StringEscaping(bool as_utf8) {
- SetDefaultFieldValuePrinter(as_utf8
- ? new FieldValuePrinterUtf8Escaping()
- : new FieldValuePrinter());
+ SetDefaultFieldValuePrinter(as_utf8 ? new FastFieldValuePrinterUtf8Escaping()
+ : new FastFieldValuePrinter());
}
void TextFormat::Printer::SetDefaultFieldValuePrinter(
const FieldValuePrinter* printer) {
+ default_field_value_printer_.reset(new FieldValuePrinterWrapper(printer));
+}
+
+void TextFormat::Printer::SetDefaultFieldValuePrinter(
+ const FastFieldValuePrinter* printer) {
default_field_value_printer_.reset(printer);
}
bool TextFormat::Printer::RegisterFieldValuePrinter(
const FieldDescriptor* field,
const FieldValuePrinter* printer) {
+ if (field == NULL || printer == NULL) {
+ return false;
+ }
+ FieldValuePrinterWrapper* const wrapper =
+ new FieldValuePrinterWrapper(NULL);
+ if (custom_printers_.insert(std::make_pair(field, wrapper)).second) {
+ wrapper->SetDelegate(printer);
+ return true;
+ } else {
+ delete wrapper;
+ return false;
+ }
+}
+
+bool TextFormat::Printer::RegisterFieldValuePrinter(
+ const FieldDescriptor* field, const FastFieldValuePrinter* printer) {
return field != NULL && printer != NULL &&
custom_printers_.insert(std::make_pair(field, printer)).second;
}
@@ -1536,7 +1758,7 @@ bool TextFormat::Printer::Print(const Message& message,
io::ZeroCopyOutputStream* output) const {
TextGenerator generator(output, initial_indent_level_);
- Print(message, generator);
+ Print(message, &generator);
// Output false if the generator failed internally.
return !generator.failed();
@@ -1547,7 +1769,7 @@ bool TextFormat::Printer::PrintUnknownFields(
io::ZeroCopyOutputStream* output) const {
TextGenerator generator(output, initial_indent_level_);
- PrintUnknownFields(unknown_fields, generator);
+ PrintUnknownFields(unknown_fields, &generator);
// Output false if the generator failed internally.
return !generator.failed();
@@ -1565,7 +1787,7 @@ struct FieldIndexSorter {
} // namespace
bool TextFormat::Printer::PrintAny(const Message& message,
- TextGenerator& generator) const {
+ TextGenerator* generator) const {
const FieldDescriptor* type_url_field;
const FieldDescriptor* value_field;
if (!internal::GetAnyFieldDescriptors(message, &type_url_field,
@@ -1598,20 +1820,21 @@ bool TextFormat::Printer::PrintAny(const Message& message,
GOOGLE_LOG(WARNING) << type_url << ": failed to parse contents";
return false;
}
- generator.Print(StrCat("[", type_url, "]"));
- const FieldValuePrinter* printer = FindWithDefault(
+ generator->PrintLiteral("[");
+ generator->PrintString(type_url);
+ generator->PrintLiteral("]");
+ const FastFieldValuePrinter* printer = FindWithDefault(
custom_printers_, value_field, default_field_value_printer_.get());
- generator.Print(
- printer->PrintMessageStart(message, -1, 0, single_line_mode_));
- generator.Indent();
+ printer->PrintMessageStart(message, -1, 0, single_line_mode_, generator);
+ generator->Indent();
Print(*value_message, generator);
- generator.Outdent();
- generator.Print(printer->PrintMessageEnd(message, -1, 0, single_line_mode_));
+ generator->Outdent();
+ printer->PrintMessageEnd(message, -1, 0, single_line_mode_, generator);
return true;
}
void TextFormat::Printer::Print(const Message& message,
- TextGenerator& generator) const {
+ TextGenerator* generator) const {
const Descriptor* descriptor = message.GetDescriptor();
const Reflection* reflection = message.GetReflection();
if (descriptor->full_name() == internal::kAnyFullTypeName && expand_any_ &&
@@ -1643,61 +1866,13 @@ void TextFormat::Printer::PrintFieldValueToString(
io::StringOutputStream output_stream(output);
TextGenerator generator(&output_stream, initial_indent_level_);
- PrintFieldValue(message, message.GetReflection(), field, index, generator);
+ PrintFieldValue(message, message.GetReflection(), field, index, &generator);
}
-class MapEntryMessageComparator {
- public:
- explicit MapEntryMessageComparator(const Descriptor* descriptor)
- : field_(descriptor->field(0)) {}
-
- bool operator()(const Message* a, const Message* b) {
- const Reflection* reflection = a->GetReflection();
- switch (field_->cpp_type()) {
- case FieldDescriptor::CPPTYPE_BOOL: {
- bool first = reflection->GetBool(*a, field_);
- bool second = reflection->GetBool(*b, field_);
- return first < second;
- }
- case FieldDescriptor::CPPTYPE_INT32: {
- int32 first = reflection->GetInt32(*a, field_);
- int32 second = reflection->GetInt32(*b, field_);
- return first < second;
- }
- case FieldDescriptor::CPPTYPE_INT64: {
- int64 first = reflection->GetInt64(*a, field_);
- int64 second = reflection->GetInt64(*b, field_);
- return first < second;
- }
- case FieldDescriptor::CPPTYPE_UINT32: {
- uint32 first = reflection->GetUInt32(*a, field_);
- uint32 second = reflection->GetUInt32(*b, field_);
- return first < second;
- }
- case FieldDescriptor::CPPTYPE_UINT64: {
- uint64 first = reflection->GetUInt64(*a, field_);
- uint64 second = reflection->GetUInt64(*b, field_);
- return first < second;
- }
- case FieldDescriptor::CPPTYPE_STRING: {
- string first = reflection->GetString(*a, field_);
- string second = reflection->GetString(*b, field_);
- return first < second;
- }
- default:
- GOOGLE_LOG(DFATAL) << "Invalid key for map field.";
- return true;
- }
- }
-
- private:
- const FieldDescriptor* field_;
-};
-
void TextFormat::Printer::PrintField(const Message& message,
const Reflection* reflection,
const FieldDescriptor* field,
- TextGenerator& generator) const {
+ TextGenerator* generator) const {
if (use_short_repeated_primitives_ &&
field->is_repeated() &&
field->cpp_type() != FieldDescriptor::CPPTYPE_STRING &&
@@ -1714,19 +1889,10 @@ void TextFormat::Printer::PrintField(const Message& message,
count = 1;
}
- std::vector<const Message*> sorted_map_field;
- if (field->is_map()) {
- const RepeatedPtrField<Message>& map_field =
- reflection->GetRepeatedPtrField<Message>(message, field);
- for (RepeatedPtrField<Message>::const_pointer_iterator it =
- map_field.pointer_begin();
- it != map_field.pointer_end(); ++it) {
- sorted_map_field.push_back(*it);
- }
-
- MapEntryMessageComparator comparator(field->message_type());
- std::stable_sort(sorted_map_field.begin(), sorted_map_field.end(),
- comparator);
+ std::vector<const Message*> map_entries;
+ const bool is_map = field->is_map();
+ if (is_map) {
+ map_entries = DynamicMapSorter::Sort(message, count, reflection, field);
}
for (int j = 0; j < count; ++j) {
@@ -1735,93 +1901,88 @@ void TextFormat::Printer::PrintField(const Message& message,
PrintFieldName(message, reflection, field, generator);
if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
- const FieldValuePrinter* printer = FindWithDefault(
+ const FastFieldValuePrinter* printer = FindWithDefault(
custom_printers_, field, default_field_value_printer_.get());
const Message& sub_message =
field->is_repeated()
- ? (field->is_map()
- ? *sorted_map_field[j]
- : reflection->GetRepeatedMessage(message, field, j))
+ ? (is_map ? *map_entries[j]
+ : reflection->GetRepeatedMessage(message, field, j))
: reflection->GetMessage(message, field);
- generator.Print(
- printer->PrintMessageStart(
- sub_message, field_index, count, single_line_mode_));
- generator.Indent();
+ printer->PrintMessageStart(sub_message, field_index, count,
+ single_line_mode_, generator);
+ generator->Indent();
Print(sub_message, generator);
- generator.Outdent();
- generator.Print(
- printer->PrintMessageEnd(
- sub_message, field_index, count, single_line_mode_));
+ generator->Outdent();
+ printer->PrintMessageEnd(sub_message, field_index, count,
+ single_line_mode_, generator);
} else {
- generator.Print(": ");
+ generator->PrintLiteral(": ");
// Write the field value.
PrintFieldValue(message, reflection, field, field_index, generator);
if (single_line_mode_) {
- generator.Print(" ");
+ generator->PrintLiteral(" ");
} else {
- generator.Print("\n");
+ generator->PrintLiteral("\n");
}
}
}
}
void TextFormat::Printer::PrintShortRepeatedField(
- const Message& message,
- const Reflection* reflection,
- const FieldDescriptor* field,
- TextGenerator& generator) const {
+ const Message& message, const Reflection* reflection,
+ const FieldDescriptor* field, TextGenerator* generator) const {
// Print primitive repeated field in short form.
PrintFieldName(message, reflection, field, generator);
int size = reflection->FieldSize(message, field);
- generator.Print(": [");
+ generator->PrintLiteral(": [");
for (int i = 0; i < size; i++) {
- if (i > 0) generator.Print(", ");
+ if (i > 0) generator->PrintLiteral(", ");
PrintFieldValue(message, reflection, field, i, generator);
}
if (single_line_mode_) {
- generator.Print("] ");
+ generator->PrintLiteral("] ");
} else {
- generator.Print("]\n");
+ generator->PrintLiteral("]\n");
}
}
void TextFormat::Printer::PrintFieldName(const Message& message,
const Reflection* reflection,
const FieldDescriptor* field,
- TextGenerator& generator) const {
+ TextGenerator* generator) const {
// if use_field_number_ is true, prints field number instead
// of field name.
if (use_field_number_) {
- generator.Print(SimpleItoa(field->number()));
+ generator->PrintString(SimpleItoa(field->number()));
return;
}
- const FieldValuePrinter* printer = FindWithDefault(
+ const FastFieldValuePrinter* printer = FindWithDefault(
custom_printers_, field, default_field_value_printer_.get());
- generator.Print(printer->PrintFieldName(message, reflection, field));
+ printer->PrintFieldName(message, reflection, field, generator);
}
-void TextFormat::Printer::PrintFieldValue(
- const Message& message,
- const Reflection* reflection,
- const FieldDescriptor* field,
- int index,
- TextGenerator& generator) const {
+void TextFormat::Printer::PrintFieldValue(const Message& message,
+ const Reflection* reflection,
+ const FieldDescriptor* field,
+ int index,
+ TextGenerator* generator) const {
GOOGLE_DCHECK(field->is_repeated() || (index == -1))
<< "Index must be -1 for non-repeated fields";
- const FieldValuePrinter* printer
- = FindWithDefault(custom_printers_, field,
- default_field_value_printer_.get());
+ const FastFieldValuePrinter* printer = FindWithDefault(
+ custom_printers_, field, default_field_value_printer_.get());
switch (field->cpp_type()) {
-#define OUTPUT_FIELD(CPPTYPE, METHOD) \
- case FieldDescriptor::CPPTYPE_##CPPTYPE: \
- generator.Print(printer->Print##METHOD(field->is_repeated() \
- ? reflection->GetRepeated##METHOD(message, field, index) \
- : reflection->Get##METHOD(message, field))); \
- break
+#define OUTPUT_FIELD(CPPTYPE, METHOD) \
+ case FieldDescriptor::CPPTYPE_##CPPTYPE: \
+ printer->Print##METHOD( \
+ field->is_repeated() \
+ ? reflection->GetRepeated##METHOD(message, field, index) \
+ : reflection->Get##METHOD(message, field), \
+ generator); \
+ break
OUTPUT_FIELD( INT32, Int32);
OUTPUT_FIELD( INT64, Int64);
@@ -1847,10 +2008,10 @@ void TextFormat::Printer::PrintFieldValue(
value_to_print = &truncated_value;
}
if (field->type() == FieldDescriptor::TYPE_STRING) {
- generator.Print(printer->PrintString(*value_to_print));
+ printer->PrintString(*value_to_print, generator);
} else {
GOOGLE_DCHECK_EQ(field->type(), FieldDescriptor::TYPE_BYTES);
- generator.Print(printer->PrintBytes(*value_to_print));
+ printer->PrintBytes(*value_to_print, generator);
}
break;
}
@@ -1862,7 +2023,7 @@ void TextFormat::Printer::PrintFieldValue(
const EnumValueDescriptor* enum_desc =
field->enum_type()->FindValueByNumber(enum_value);
if (enum_desc != NULL) {
- generator.Print(printer->PrintEnum(enum_value, enum_desc->name()));
+ printer->PrintEnum(enum_value, enum_desc->name(), generator);
} else {
// Ordinarily, enum_desc should not be null, because proto2 has the
// invariant that set enum field values must be in-range, but with the
@@ -1870,8 +2031,8 @@ void TextFormat::Printer::PrintFieldValue(
// it is possible for the user to force an unknown integer value. So we
// simply use the integer value itself as the enum value name in this
// case.
- generator.Print(printer->PrintEnum(enum_value,
- StringPrintf("%d", enum_value)));
+ printer->PrintEnum(enum_value, StringPrintf("%d", enum_value),
+ generator);
}
break;
}
@@ -1934,90 +2095,93 @@ static string PaddedHex(IntType value) {
}
void TextFormat::Printer::PrintUnknownFields(
- const UnknownFieldSet& unknown_fields, TextGenerator& generator) const {
+ const UnknownFieldSet& unknown_fields, TextGenerator* generator) const {
for (int i = 0; i < unknown_fields.field_count(); i++) {
const UnknownField& field = unknown_fields.field(i);
string field_number = SimpleItoa(field.number());
switch (field.type()) {
case UnknownField::TYPE_VARINT:
- generator.Print(field_number);
- generator.Print(": ");
- generator.Print(SimpleItoa(field.varint()));
+ generator->PrintString(field_number);
+ generator->PrintLiteral(": ");
+ generator->PrintString(SimpleItoa(field.varint()));
if (single_line_mode_) {
- generator.Print(" ");
+ generator->PrintLiteral(" ");
} else {
- generator.Print("\n");
+ generator->PrintLiteral("\n");
}
break;
case UnknownField::TYPE_FIXED32: {
- generator.Print(field_number);
- generator.Print(": 0x");
- generator.Print(
+ generator->PrintString(field_number);
+ generator->PrintLiteral(": 0x");
+ generator->PrintString(
StrCat(strings::Hex(field.fixed32(), strings::ZERO_PAD_8)));
if (single_line_mode_) {
- generator.Print(" ");
+ generator->PrintLiteral(" ");
} else {
- generator.Print("\n");
+ generator->PrintLiteral("\n");
}
break;
}
case UnknownField::TYPE_FIXED64: {
- generator.Print(field_number);
- generator.Print(": 0x");
- generator.Print(
+ generator->PrintString(field_number);
+ generator->PrintLiteral(": 0x");
+ generator->PrintString(
StrCat(strings::Hex(field.fixed64(), strings::ZERO_PAD_16)));
if (single_line_mode_) {
- generator.Print(" ");
+ generator->PrintLiteral(" ");
} else {
- generator.Print("\n");
+ generator->PrintLiteral("\n");
}
break;
}
case UnknownField::TYPE_LENGTH_DELIMITED: {
- generator.Print(field_number);
+ generator->PrintString(field_number);
const string& value = field.length_delimited();
UnknownFieldSet embedded_unknown_fields;
if (!value.empty() && embedded_unknown_fields.ParseFromString(value)) {
// This field is parseable as a Message.
// So it is probably an embedded message.
if (single_line_mode_) {
- generator.Print(" { ");
+ generator->PrintLiteral(" { ");
} else {
- generator.Print(" {\n");
- generator.Indent();
+ generator->PrintLiteral(" {\n");
+ generator->Indent();
}
PrintUnknownFields(embedded_unknown_fields, generator);
if (single_line_mode_) {
- generator.Print("} ");
+ generator->PrintLiteral("} ");
} else {
- generator.Outdent();
- generator.Print("}\n");
+ generator->Outdent();
+ generator->PrintLiteral("}\n");
}
} else {
// This field is not parseable as a Message.
// So it is probably just a plain string.
- string printed(": \"");
- CEscapeAndAppend(value, &printed);
- printed.append(single_line_mode_ ? "\" " : "\"\n");
- generator.Print(printed);
+ generator->PrintLiteral(": \"");
+ generator->PrintString(CEscape(value));
+ if (single_line_mode_) {
+ generator->PrintLiteral("\" ");
+ } else {
+ generator->PrintLiteral("\"\n");
+ }
}
break;
}
case UnknownField::TYPE_GROUP:
- generator.Print(field_number);
+ generator->PrintString(field_number);
if (single_line_mode_) {
- generator.Print(" { ");
+ generator->PrintLiteral(" { ");
} else {
- generator.Print(" {\n");
- generator.Indent();
+ generator->PrintLiteral(" {\n");
+ generator->Indent();
}
PrintUnknownFields(field.group(), generator);
if (single_line_mode_) {
- generator.Print("} ");
+ generator->PrintLiteral("} ");
} else {
- generator.Outdent();
- generator.Print("}\n");
+ generator->Outdent();
+ generator->PrintLiteral("}\n");
}
break;
}
diff --git a/src/google/protobuf/text_format.h b/src/google/protobuf/text_format.h
index 2873d339..a2670d6b 100644
--- a/src/google/protobuf/text_format.h
+++ b/src/google/protobuf/text_format.h
@@ -49,6 +49,7 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/message.h>
+#include <google/protobuf/message_lite.h>
namespace google {
namespace protobuf {
@@ -65,21 +66,22 @@ namespace io {
class LIBPROTOBUF_EXPORT TextFormat {
public:
// Outputs a textual representation of the given message to the given
- // output stream.
+ // output stream. Returns false if printing fails.
static bool Print(const Message& message, io::ZeroCopyOutputStream* output);
// Print the fields in an UnknownFieldSet. They are printed by tag number
// only. Embedded messages are heuristically identified by attempting to
- // parse them.
+ // parse them. Returns false if printing fails.
static bool PrintUnknownFields(const UnknownFieldSet& unknown_fields,
io::ZeroCopyOutputStream* output);
// Like Print(), but outputs directly to a string.
- // Note: output will be cleared before prior to printing, and will
- // be left empty even if printing fails.
+ // Note: output will be cleared prior to printing, and will be left empty
+ // even if printing fails. Returns false if printing fails.
static bool PrintToString(const Message& message, string* output);
- // Like PrintUnknownFields(), but outputs directly to a string.
+ // Like PrintUnknownFields(), but outputs directly to a string. Returns false
+ // if printing fails.
static bool PrintUnknownFieldsToString(const UnknownFieldSet& unknown_fields,
string* output);
@@ -92,12 +94,58 @@ class LIBPROTOBUF_EXPORT TextFormat {
int index,
string* output);
- // The default printer that converts scalar values from fields into
- // their string representation.
- // You can derive from this FieldValuePrinter if you want to have
- // fields to be printed in a different way and register it at the
- // Printer.
- class LIBPROTOBUF_EXPORT FieldValuePrinter {
+ class LIBPROTOBUF_EXPORT BaseTextGenerator {
+ public:
+ virtual ~BaseTextGenerator();
+ // Print text to the output stream.
+ virtual void Print(const char* text, size_t size) = 0;
+
+ void PrintString(const string& str) { Print(str.data(), str.size()); }
+
+ template <size_t n>
+ void PrintLiteral(const char (&text)[n]) {
+ Print(text, n - 1); // n includes the terminating zero character.
+ }
+ };
+
+ // The default printer that converts scalar values from fields into their
+ // string representation.
+ // You can derive from this FastFieldValuePrinter if you want to have fields
+ // to be printed in a different way and register it at the Printer.
+ class LIBPROTOBUF_EXPORT FastFieldValuePrinter {
+ public:
+ FastFieldValuePrinter();
+ virtual ~FastFieldValuePrinter();
+ virtual void PrintBool(bool val, BaseTextGenerator* generator) const;
+ virtual void PrintInt32(int32 val, BaseTextGenerator* generator) const;
+ virtual void PrintUInt32(uint32 val, BaseTextGenerator* generator) const;
+ virtual void PrintInt64(int64 val, BaseTextGenerator* generator) const;
+ virtual void PrintUInt64(uint64 val, BaseTextGenerator* generator) const;
+ virtual void PrintFloat(float val, BaseTextGenerator* generator) const;
+ virtual void PrintDouble(double val, BaseTextGenerator* generator) const;
+ virtual void PrintString(const string& val,
+ BaseTextGenerator* generator) const;
+ virtual void PrintBytes(const string& val,
+ BaseTextGenerator* generator) const;
+ virtual void PrintEnum(int32 val, const string& name,
+ BaseTextGenerator* generator) const;
+ virtual void PrintFieldName(const Message& message,
+ const Reflection* reflection,
+ const FieldDescriptor* field,
+ BaseTextGenerator* generator) const;
+ virtual void PrintMessageStart(const Message& message, int field_index,
+ int field_count, bool single_line_mode,
+ BaseTextGenerator* generator) const;
+ virtual void PrintMessageEnd(const Message& message, int field_index,
+ int field_count, bool single_line_mode,
+ BaseTextGenerator* generator) const;
+
+ private:
+ GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FastFieldValuePrinter);
+ };
+
+ class LIBPROTOBUF_EXPORT PROTOBUF_RUNTIME_DEPRECATED("Please use FastFieldValuePrinter")
+ FieldValuePrinter {
public:
FieldValuePrinter();
virtual ~FieldValuePrinter();
@@ -124,6 +172,7 @@ class LIBPROTOBUF_EXPORT TextFormat {
bool single_line_mode) const;
private:
+ FastFieldValuePrinter delegate_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldValuePrinter);
};
@@ -162,7 +211,7 @@ class LIBPROTOBUF_EXPORT TextFormat {
single_line_mode_ = single_line_mode;
}
- bool IsInSingleLineMode() {
+ bool IsInSingleLineMode() const {
return single_line_mode_;
}
@@ -183,12 +232,13 @@ class LIBPROTOBUF_EXPORT TextFormat {
// Set true to output UTF-8 instead of ASCII. The only difference
// is that bytes >= 0x80 in string fields will not be escaped,
// because they are assumed to be part of UTF-8 multi-byte
- // sequences. This will change the default FieldValuePrinter.
+ // sequences. This will change the default FastFieldValuePrinter.
void SetUseUtf8StringEscaping(bool as_utf8);
- // Set the default FieldValuePrinter that is used for all fields that
+ // Set the default (Fast)FieldValuePrinter that is used for all fields that
// don't have a field-specific printer registered.
// Takes ownership of the printer.
+ void SetDefaultFieldValuePrinter(const FastFieldValuePrinter* printer);
void SetDefaultFieldValuePrinter(const FieldValuePrinter* printer);
// Sets whether we want to hide unknown fields or not.
@@ -233,13 +283,15 @@ class LIBPROTOBUF_EXPORT TextFormat {
truncate_string_field_longer_than_ = truncate_string_field_longer_than;
}
- // Register a custom field-specific FieldValuePrinter for fields
+ // Register a custom field-specific (Fast)FieldValuePrinter for fields
// with a particular FieldDescriptor.
// Returns "true" if the registration succeeded, or "false", if there is
// already a printer for that FieldDescriptor.
// Takes ownership of the printer on successful registration.
bool RegisterFieldValuePrinter(const FieldDescriptor* field,
const FieldValuePrinter* printer);
+ bool RegisterFieldValuePrinter(const FieldDescriptor* field,
+ const FastFieldValuePrinter* printer);
private:
// Forward declaration of an internal class used to print the text
@@ -248,43 +300,38 @@ class LIBPROTOBUF_EXPORT TextFormat {
// Internal Print method, used for writing to the OutputStream via
// the TextGenerator class.
- void Print(const Message& message,
- TextGenerator& generator) const;
+ void Print(const Message& message, TextGenerator* generator) const;
// Print a single field.
- void PrintField(const Message& message,
- const Reflection* reflection,
+ void PrintField(const Message& message, const Reflection* reflection,
const FieldDescriptor* field,
- TextGenerator& generator) const;
+ TextGenerator* generator) const;
// Print a repeated primitive field in short form.
void PrintShortRepeatedField(const Message& message,
const Reflection* reflection,
const FieldDescriptor* field,
- TextGenerator& generator) const;
+ TextGenerator* generator) const;
// Print the name of a field -- i.e. everything that comes before the
// ':' for a single name/value pair.
- void PrintFieldName(const Message& message,
- const Reflection* reflection,
+ void PrintFieldName(const Message& message, const Reflection* reflection,
const FieldDescriptor* field,
- TextGenerator& generator) const;
+ TextGenerator* generator) const;
// Outputs a textual representation of the value of the field supplied on
// the message supplied or the default value if not set.
- void PrintFieldValue(const Message& message,
- const Reflection* reflection,
- const FieldDescriptor* field,
- int index,
- TextGenerator& generator) const;
+ void PrintFieldValue(const Message& message, const Reflection* reflection,
+ const FieldDescriptor* field, int index,
+ TextGenerator* generator) const;
// Print the fields in an UnknownFieldSet. They are printed by tag number
// only. Embedded messages are heuristically identified by attempting to
// parse them.
void PrintUnknownFields(const UnknownFieldSet& unknown_fields,
- TextGenerator& generator) const;
+ TextGenerator* generator) const;
- bool PrintAny(const Message& message, TextGenerator& generator) const;
+ bool PrintAny(const Message& message, TextGenerator* generator) const;
int initial_indent_level_;
@@ -302,9 +349,9 @@ class LIBPROTOBUF_EXPORT TextFormat {
int64 truncate_string_field_longer_than_;
- google::protobuf::scoped_ptr<const FieldValuePrinter> default_field_value_printer_;
- typedef std::map<const FieldDescriptor*,
- const FieldValuePrinter*> CustomPrinterMap;
+ google::protobuf::scoped_ptr<const FastFieldValuePrinter> default_field_value_printer_;
+ typedef std::map<const FieldDescriptor*, const FastFieldValuePrinter*>
+ CustomPrinterMap;
CustomPrinterMap custom_printers_;
};
diff --git a/src/google/protobuf/text_format_unittest.cc b/src/google/protobuf/text_format_unittest.cc
index e6441339..f823bcb2 100644
--- a/src/google/protobuf/text_format_unittest.cc
+++ b/src/google/protobuf/text_format_unittest.cc
@@ -53,11 +53,12 @@
#include <google/protobuf/unittest_mset_wire_format.pb.h>
#include <google/protobuf/io/tokenizer.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
-#include <google/protobuf/stubs/mathlimits.h>
+
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/substitute.h>
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
+#include <google/protobuf/stubs/mathlimits.h>
namespace google {
@@ -454,13 +455,29 @@ TEST_F(TextFormatTest, FieldSpecificCustomPrinter) {
EXPECT_EQ("optional_int32: value-is(42)\nrepeated_int32: 42\n", text);
}
+TEST_F(TextFormatTest, FieldSpecificCustomPrinterRegisterSameFieldTwice) {
+ protobuf_unittest::TestAllTypes message;
+ TextFormat::Printer printer;
+ const FieldDescriptor* const field =
+ message.GetDescriptor()->FindFieldByName("optional_int32");
+ ASSERT_TRUE(printer.RegisterFieldValuePrinter(
+ field, new CustomInt32FieldValuePrinter()));
+ const TextFormat::FieldValuePrinter* const rejected =
+ new CustomInt32FieldValuePrinter();
+ ASSERT_FALSE(printer.RegisterFieldValuePrinter(field, rejected));
+ delete rejected;
+}
+
TEST_F(TextFormatTest, ErrorCasesRegisteringFieldValuePrinterShouldFail) {
protobuf_unittest::TestAllTypes message;
TextFormat::Printer printer;
// NULL printer.
EXPECT_FALSE(printer.RegisterFieldValuePrinter(
message.GetDescriptor()->FindFieldByName("optional_int32"),
- NULL));
+ static_cast<const TextFormat::FieldValuePrinter*>(NULL)));
+ EXPECT_FALSE(printer.RegisterFieldValuePrinter(
+ message.GetDescriptor()->FindFieldByName("optional_int32"),
+ static_cast<const TextFormat::FastFieldValuePrinter*>(NULL)));
// Because registration fails, the ownership of this printer is never taken.
TextFormat::FieldValuePrinter my_field_printer;
// NULL field
diff --git a/src/google/protobuf/timestamp.pb.cc b/src/google/protobuf/timestamp.pb.cc
index 482c0e39..36e3bb36 100644
--- a/src/google/protobuf/timestamp.pb.cc
+++ b/src/google/protobuf/timestamp.pb.cc
@@ -1,7 +1,6 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/timestamp.proto
-#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include <google/protobuf/timestamp.pb.h>
#include <algorithm>
@@ -15,48 +14,66 @@
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
+// This is a temporary google only hack
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+#include "third_party/protobuf/version.h"
+#endif
// @@protoc_insertion_point(includes)
-
namespace google {
namespace protobuf {
-class TimestampDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<Timestamp> {};
-TimestampDefaultTypeInternal _Timestamp_default_instance_;
-
-namespace {
-
-::google::protobuf::Metadata file_level_metadata[1];
-
-} // namespace
+class TimestampDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<Timestamp>
+ _instance;
+} _Timestamp_default_instance_;
+} // namespace protobuf
+} // namespace google
+namespace protobuf_google_2fprotobuf_2ftimestamp_2eproto {
+void InitDefaultsTimestampImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ {
+ void* ptr = &::google::protobuf::_Timestamp_default_instance_;
+ new (ptr) ::google::protobuf::Timestamp();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::Timestamp::InitAsDefaultInstance();
+}
-const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2ftimestamp_2eproto() GOOGLE_ATTRIBUTE_COLD;
-const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2ftimestamp_2eproto() {
- static const ::google::protobuf::uint32 offsets[] = {
- ~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Timestamp, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Timestamp, seconds_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Timestamp, nanos_),
- };
- return offsets;
+void InitDefaultsTimestamp() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsTimestampImpl);
}
-static const ::google::protobuf::internal::MigrationSchema schemas[] = {
- { 0, -1, sizeof(Timestamp)},
-};
+::google::protobuf::Metadata file_level_metadata[1];
-static const ::google::protobuf::internal::DefaultInstanceData file_default_instances[] = {
- {reinterpret_cast<const ::google::protobuf::Message*>(&_Timestamp_default_instance_), NULL},
+const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+ ~0u, // no _has_bits_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Timestamp, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Timestamp, seconds_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Timestamp, nanos_),
+};
+static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+ { 0, -1, sizeof(::google::protobuf::Timestamp)},
};
-namespace {
+static ::google::protobuf::Message const * const file_default_instances[] = {
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_Timestamp_default_instance_),
+};
void protobuf_AssignDescriptors() {
- protobuf_AddDesc_google_2fprotobuf_2ftimestamp_2eproto();
+ AddDescriptors();
::google::protobuf::MessageFactory* factory = NULL;
AssignDescriptors(
- "google/protobuf/timestamp.proto", schemas, file_default_instances, protobuf_Offsets_google_2fprotobuf_2ftimestamp_2eproto(), factory,
+ "google/protobuf/timestamp.proto", schemas, file_default_instances, TableStruct::offsets, factory,
file_level_metadata, NULL, NULL);
}
@@ -65,33 +82,15 @@ void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);
}
-void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
+void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 1);
}
-} // namespace
-
-void protobuf_ShutdownFile_google_2fprotobuf_2ftimestamp_2eproto() {
- _Timestamp_default_instance_.Shutdown();
- delete file_level_metadata[0].reflection;
-}
-
-void protobuf_InitDefaults_google_2fprotobuf_2ftimestamp_2eproto_impl() {
- GOOGLE_PROTOBUF_VERIFY_VERSION;
-
- ::google::protobuf::internal::InitProtobufDefaults();
- _Timestamp_default_instance_.DefaultConstruct();
-}
-
-void protobuf_InitDefaults_google_2fprotobuf_2ftimestamp_2eproto() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &protobuf_InitDefaults_google_2fprotobuf_2ftimestamp_2eproto_impl);
-}
-void protobuf_AddDesc_google_2fprotobuf_2ftimestamp_2eproto_impl() {
- protobuf_InitDefaults_google_2fprotobuf_2ftimestamp_2eproto();
- static const char descriptor[] = {
+void AddDescriptorsImpl() {
+ InitDefaults();
+ static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n\037google/protobuf/timestamp.proto\022\017googl"
"e.protobuf\"+\n\tTimestamp\022\017\n\007seconds\030\001 \001(\003"
"\022\r\n\005nanos\030\002 \001(\005B~\n\023com.google.protobufB\016"
@@ -103,23 +102,26 @@ void protobuf_AddDesc_google_2fprotobuf_2ftimestamp_2eproto_impl() {
descriptor, 231);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"google/protobuf/timestamp.proto", &protobuf_RegisterTypes);
- ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_google_2fprotobuf_2ftimestamp_2eproto);
}
-GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AddDesc_google_2fprotobuf_2ftimestamp_2eproto_once_);
-void protobuf_AddDesc_google_2fprotobuf_2ftimestamp_2eproto() {
- ::google::protobuf::GoogleOnceInit(&protobuf_AddDesc_google_2fprotobuf_2ftimestamp_2eproto_once_,
- &protobuf_AddDesc_google_2fprotobuf_2ftimestamp_2eproto_impl);
+void AddDescriptors() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);
}
-// Force AddDescriptors() to be called at static initialization time.
-struct StaticDescriptorInitializer_google_2fprotobuf_2ftimestamp_2eproto {
- StaticDescriptorInitializer_google_2fprotobuf_2ftimestamp_2eproto() {
- protobuf_AddDesc_google_2fprotobuf_2ftimestamp_2eproto();
+// Force AddDescriptors() to be called at dynamic initialization time.
+struct StaticDescriptorInitializer {
+ StaticDescriptorInitializer() {
+ AddDescriptors();
}
-} static_descriptor_initializer_google_2fprotobuf_2ftimestamp_2eproto_;
+} static_descriptor_initializer;
+} // namespace protobuf_google_2fprotobuf_2ftimestamp_2eproto
+namespace google {
+namespace protobuf {
// ===================================================================
+void Timestamp::InitAsDefaultInstance() {
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Timestamp::kSecondsFieldNumber;
const int Timestamp::kNanosFieldNumber;
@@ -128,7 +130,7 @@ const int Timestamp::kNanosFieldNumber;
Timestamp::Timestamp()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2ftimestamp_2eproto();
+ ::protobuf_google_2fprotobuf_2ftimestamp_2eproto::InitDefaultsTimestamp();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Timestamp)
@@ -136,9 +138,7 @@ Timestamp::Timestamp()
Timestamp::Timestamp(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
-#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
- protobuf_InitDefaults_google_2fprotobuf_2ftimestamp_2eproto();
-#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ ::protobuf_google_2fprotobuf_2ftimestamp_2eproto::InitDefaultsTimestamp();
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Timestamp)
@@ -149,14 +149,15 @@ Timestamp::Timestamp(const Timestamp& from)
_cached_size_(0) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
::memcpy(&seconds_, &from.seconds_,
- reinterpret_cast<char*>(&nanos_) -
- reinterpret_cast<char*>(&seconds_) + sizeof(nanos_));
+ static_cast<size_t>(reinterpret_cast<char*>(&nanos_) -
+ reinterpret_cast<char*>(&seconds_)) + sizeof(nanos_));
// @@protoc_insertion_point(copy_constructor:google.protobuf.Timestamp)
}
void Timestamp::SharedCtor() {
- ::memset(&seconds_, 0, reinterpret_cast<char*>(&nanos_) -
- reinterpret_cast<char*>(&seconds_) + sizeof(nanos_));
+ ::memset(&seconds_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&nanos_) -
+ reinterpret_cast<char*>(&seconds_)) + sizeof(nanos_));
_cached_size_ = 0;
}
@@ -166,11 +167,7 @@ Timestamp::~Timestamp() {
}
void Timestamp::SharedDtor() {
- ::google::protobuf::Arena* arena = GetArenaNoVirtual();
- if (arena != NULL) {
- return;
- }
-
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
}
void Timestamp::ArenaDtor(void* object) {
@@ -185,12 +182,12 @@ void Timestamp::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* Timestamp::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[0].descriptor;
+ ::protobuf_google_2fprotobuf_2ftimestamp_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2ftimestamp_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const Timestamp& Timestamp::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2ftimestamp_2eproto();
+ ::protobuf_google_2fprotobuf_2ftimestamp_2eproto::InitDefaultsTimestamp();
return *internal_default_instance();
}
@@ -200,8 +197,14 @@ Timestamp* Timestamp::New(::google::protobuf::Arena* arena) const {
void Timestamp::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Timestamp)
- ::memset(&seconds_, 0, reinterpret_cast<char*>(&nanos_) -
- reinterpret_cast<char*>(&seconds_) + sizeof(nanos_));
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
+ ::memset(&seconds_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&nanos_) -
+ reinterpret_cast<char*>(&seconds_)) + sizeof(nanos_));
+ _internal_metadata_.Clear();
}
bool Timestamp::MergePartialFromCodedStream(
@@ -216,7 +219,8 @@ bool Timestamp::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// int64 seconds = 1;
case 1: {
- if (tag == 8u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>(
@@ -229,7 +233,8 @@ bool Timestamp::MergePartialFromCodedStream(
// int32 nanos = 2;
case 2: {
- if (tag == 16u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
@@ -242,12 +247,11 @@ bool Timestamp::MergePartialFromCodedStream(
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
- DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
+ DO_(::google::protobuf::internal::WireFormat::SkipField(
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -264,6 +268,9 @@ failure:
void Timestamp::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.Timestamp)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// int64 seconds = 1;
if (this->seconds() != 0) {
::google::protobuf::internal::WireFormatLite::WriteInt64(1, this->seconds(), output);
@@ -274,6 +281,10 @@ void Timestamp::SerializeWithCachedSizes(
::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->nanos(), output);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ }
// @@protoc_insertion_point(serialize_end:google.protobuf.Timestamp)
}
@@ -281,6 +292,9 @@ void Timestamp::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Timestamp)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// int64 seconds = 1;
if (this->seconds() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(1, this->seconds(), target);
@@ -291,6 +305,10 @@ void Timestamp::SerializeWithCachedSizes(
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->nanos(), target);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ }
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Timestamp)
return target;
}
@@ -299,6 +317,11 @@ size_t Timestamp::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.Timestamp)
size_t total_size = 0;
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ total_size +=
+ ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ }
// int64 seconds = 1;
if (this->seconds() != 0) {
total_size += 1 +
@@ -339,6 +362,9 @@ void Timestamp::MergeFrom(const Timestamp& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Timestamp)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
if (from.seconds() != 0) {
set_seconds(from.seconds());
}
@@ -385,51 +411,20 @@ void Timestamp::UnsafeArenaSwap(Timestamp* other) {
InternalSwap(other);
}
void Timestamp::InternalSwap(Timestamp* other) {
- std::swap(seconds_, other->seconds_);
- std::swap(nanos_, other->nanos_);
- std::swap(_cached_size_, other->_cached_size_);
+ using std::swap;
+ swap(seconds_, other->seconds_);
+ swap(nanos_, other->nanos_);
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Timestamp::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[0];
+ protobuf_google_2fprotobuf_2ftimestamp_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2ftimestamp_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// Timestamp
-
-// int64 seconds = 1;
-void Timestamp::clear_seconds() {
- seconds_ = GOOGLE_LONGLONG(0);
-}
-::google::protobuf::int64 Timestamp::seconds() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Timestamp.seconds)
- return seconds_;
-}
-void Timestamp::set_seconds(::google::protobuf::int64 value) {
-
- seconds_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.Timestamp.seconds)
-}
-
-// int32 nanos = 2;
-void Timestamp::clear_nanos() {
- nanos_ = 0;
-}
-::google::protobuf::int32 Timestamp::nanos() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Timestamp.nanos)
- return nanos_;
-}
-void Timestamp::set_nanos(::google::protobuf::int32 value) {
-
- nanos_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.Timestamp.nanos)
-}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
-
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/timestamp.pb.h b/src/google/protobuf/timestamp.pb.h
index 63875c68..4ec7f0a0 100644
--- a/src/google/protobuf/timestamp.pb.h
+++ b/src/google/protobuf/timestamp.pb.h
@@ -8,19 +8,21 @@
#include <google/protobuf/stubs/common.h>
-#if GOOGLE_PROTOBUF_VERSION < 3001000
+#if GOOGLE_PROTOBUF_VERSION < 3004000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3001000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3004000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
+#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
+#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
@@ -28,6 +30,24 @@
#include <google/protobuf/extension_set.h> // IWYU pragma: export
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
+
+namespace protobuf_google_2fprotobuf_2ftimestamp_2eproto {
+// Internal implementation detail -- do not use these members.
+struct LIBPROTOBUF_EXPORT TableStruct {
+ static const ::google::protobuf::internal::ParseTableField entries[];
+ static const ::google::protobuf::internal::AuxillaryParseTableField aux[];
+ static const ::google::protobuf::internal::ParseTable schema[1];
+ static const ::google::protobuf::internal::FieldMetadata field_metadata[];
+ static const ::google::protobuf::internal::SerializationTable serialization_table[];
+ static const ::google::protobuf::uint32 offsets[];
+};
+void LIBPROTOBUF_EXPORT AddDescriptors();
+void LIBPROTOBUF_EXPORT InitDefaultsTimestampImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsTimestamp();
+inline void LIBPROTOBUF_EXPORT InitDefaults() {
+ InitDefaultsTimestamp();
+}
+} // namespace protobuf_google_2fprotobuf_2ftimestamp_2eproto
namespace google {
namespace protobuf {
class Timestamp;
@@ -35,14 +55,9 @@ class TimestampDefaultTypeInternal;
LIBPROTOBUF_EXPORT extern TimestampDefaultTypeInternal _Timestamp_default_instance_;
} // namespace protobuf
} // namespace google
-
namespace google {
namespace protobuf {
-// Internal implementation detail -- do not call these.
-void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2ftimestamp_2eproto();
-void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2ftimestamp_2eproto();
-
// ===================================================================
class LIBPROTOBUF_EXPORT Timestamp : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Timestamp) */ {
@@ -56,7 +71,21 @@ class LIBPROTOBUF_EXPORT Timestamp : public ::google::protobuf::Message /* @@pro
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ Timestamp(Timestamp&& from) noexcept
+ : Timestamp() {
+ *this = ::std::move(from);
+ }
+ inline Timestamp& operator=(Timestamp&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
return GetArenaNoVirtual();
}
@@ -66,13 +95,19 @@ class LIBPROTOBUF_EXPORT Timestamp : public ::google::protobuf::Message /* @@pro
static const ::google::protobuf::Descriptor* descriptor();
static const Timestamp& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const Timestamp* internal_default_instance() {
return reinterpret_cast<const Timestamp*>(
&_Timestamp_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 0;
void UnsafeArenaSwap(Timestamp* other);
void Swap(Timestamp* other);
+ friend void swap(Timestamp& a, Timestamp& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -93,10 +128,6 @@ class LIBPROTOBUF_EXPORT Timestamp : public ::google::protobuf::Message /* @@pro
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
@@ -139,24 +170,24 @@ class LIBPROTOBUF_EXPORT Timestamp : public ::google::protobuf::Message /* @@pro
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- friend class ::google::protobuf::Arena;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::int64 seconds_;
::google::protobuf::int32 nanos_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2ftimestamp_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2ftimestamp_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2ftimestamp_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2ftimestamp_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2ftimestamp_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2ftimestamp_2eproto::InitDefaultsTimestampImpl();
};
// ===================================================================
// ===================================================================
-#if !PROTOBUF_INLINE_NOT_IN_HEADERS
+#ifdef __GNUC__
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wstrict-aliasing"
+#endif // __GNUC__
// Timestamp
// int64 seconds = 1;
@@ -187,11 +218,12 @@ inline void Timestamp::set_nanos(::google::protobuf::int32 value) {
// @@protoc_insertion_point(field_set:google.protobuf.Timestamp.nanos)
}
-#endif // !PROTOBUF_INLINE_NOT_IN_HEADERS
+#ifdef __GNUC__
+ #pragma GCC diagnostic pop
+#endif // __GNUC__
// @@protoc_insertion_point(namespace_scope)
-
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/timestamp.proto b/src/google/protobuf/timestamp.proto
index 67e2eba4..06750ab1 100644
--- a/src/google/protobuf/timestamp.proto
+++ b/src/google/protobuf/timestamp.proto
@@ -52,6 +52,8 @@ option objc_class_prefix = "GPB";
// and from RFC 3339 date strings.
// See [https://www.ietf.org/rfc/rfc3339.txt](https://www.ietf.org/rfc/rfc3339.txt).
//
+// # Examples
+//
// Example 1: Compute Timestamp from POSIX `time()`.
//
// Timestamp timestamp;
@@ -92,6 +94,29 @@ option objc_class_prefix = "GPB";
// timestamp = Timestamp()
// timestamp.GetCurrentTime()
//
+// # JSON Mapping
+//
+// In JSON format, the Timestamp type is encoded as a string in the
+// [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the
+// format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z"
+// where {year} is always expressed using four digits while {month}, {day},
+// {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional
+// seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution),
+// are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone
+// is required, though only UTC (as indicated by "Z") is presently supported.
+//
+// For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past
+// 01:30 UTC on January 15, 2017.
+//
+// In JavaScript, one can convert a Date object to this format using the
+// standard [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString]
+// method. In Python, a standard `datetime.datetime` object can be converted
+// to this format using [`strftime`](https://docs.python.org/2/library/time.html#time.strftime)
+// with the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one
+// can use the Joda Time's [`ISODateTimeFormat.dateTime()`](
+// http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime--)
+// to obtain a formatter capable of generating timestamps in this format.
+//
//
message Timestamp {
diff --git a/src/google/protobuf/type.pb.cc b/src/google/protobuf/type.pb.cc
index 6e41dde8..92f6589c 100644
--- a/src/google/protobuf/type.pb.cc
+++ b/src/google/protobuf/type.pb.cc
@@ -1,7 +1,6 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/type.proto
-#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include <google/protobuf/type.pb.h>
#include <algorithm>
@@ -15,105 +14,232 @@
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
+// This is a temporary google only hack
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+#include "third_party/protobuf/version.h"
+#endif
// @@protoc_insertion_point(includes)
-
namespace google {
namespace protobuf {
-class TypeDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<Type> {};
-TypeDefaultTypeInternal _Type_default_instance_;
-class FieldDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<Field> {};
-FieldDefaultTypeInternal _Field_default_instance_;
-class EnumDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<Enum> {};
-EnumDefaultTypeInternal _Enum_default_instance_;
-class EnumValueDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<EnumValue> {};
-EnumValueDefaultTypeInternal _EnumValue_default_instance_;
-class OptionDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<Option> {};
-OptionDefaultTypeInternal _Option_default_instance_;
-
-namespace {
+class TypeDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<Type>
+ _instance;
+} _Type_default_instance_;
+class FieldDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<Field>
+ _instance;
+} _Field_default_instance_;
+class EnumDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<Enum>
+ _instance;
+} _Enum_default_instance_;
+class EnumValueDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<EnumValue>
+ _instance;
+} _EnumValue_default_instance_;
+class OptionDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<Option>
+ _instance;
+} _Option_default_instance_;
+} // namespace protobuf
+} // namespace google
+namespace protobuf_google_2fprotobuf_2ftype_2eproto {
+void InitDefaultsTypeImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
-::google::protobuf::Metadata file_level_metadata[5];
-const ::google::protobuf::EnumDescriptor* file_level_enum_descriptors[3];
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsField();
+ protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOption();
+ protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::InitDefaultsSourceContext();
+ {
+ void* ptr = &::google::protobuf::_Type_default_instance_;
+ new (ptr) ::google::protobuf::Type();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::Type::InitAsDefaultInstance();
+}
-} // namespace
-
-
-const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2ftype_2eproto() GOOGLE_ATTRIBUTE_COLD;
-const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2ftype_2eproto() {
- static const ::google::protobuf::uint32 offsets[] = {
- ~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Type, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Type, name_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Type, fields_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Type, oneofs_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Type, options_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Type, source_context_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Type, syntax_),
- ~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Field, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Field, kind_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Field, cardinality_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Field, number_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Field, name_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Field, type_url_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Field, oneof_index_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Field, packed_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Field, options_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Field, json_name_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Field, default_value_),
- ~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Enum, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Enum, name_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Enum, enumvalue_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Enum, options_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Enum, source_context_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Enum, syntax_),
- ~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumValue, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumValue, name_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumValue, number_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumValue, options_),
- ~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Option, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Option, name_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Option, value_),
- };
- return offsets;
+void InitDefaultsType() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsTypeImpl);
}
-static const ::google::protobuf::internal::MigrationSchema schemas[] = {
- { 0, -1, sizeof(Type)},
- { 10, -1, sizeof(Field)},
- { 24, -1, sizeof(Enum)},
- { 33, -1, sizeof(EnumValue)},
- { 40, -1, sizeof(Option)},
-};
+void InitDefaultsFieldImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOption();
+ {
+ void* ptr = &::google::protobuf::_Field_default_instance_;
+ new (ptr) ::google::protobuf::Field();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::Field::InitAsDefaultInstance();
+}
+
+void InitDefaultsField() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsFieldImpl);
+}
+
+void InitDefaultsEnumImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsEnumValue();
+ protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOption();
+ protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::InitDefaultsSourceContext();
+ {
+ void* ptr = &::google::protobuf::_Enum_default_instance_;
+ new (ptr) ::google::protobuf::Enum();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::Enum::InitAsDefaultInstance();
+}
+
+void InitDefaultsEnum() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsEnumImpl);
+}
+
+void InitDefaultsEnumValueImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOption();
+ {
+ void* ptr = &::google::protobuf::_EnumValue_default_instance_;
+ new (ptr) ::google::protobuf::EnumValue();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::EnumValue::InitAsDefaultInstance();
+}
-static const ::google::protobuf::internal::DefaultInstanceData file_default_instances[] = {
- {reinterpret_cast<const ::google::protobuf::Message*>(&_Type_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_Field_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_Enum_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_EnumValue_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_Option_default_instance_), NULL},
+void InitDefaultsEnumValue() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsEnumValueImpl);
+}
+
+void InitDefaultsOptionImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ protobuf_google_2fprotobuf_2fany_2eproto::InitDefaultsAny();
+ {
+ void* ptr = &::google::protobuf::_Option_default_instance_;
+ new (ptr) ::google::protobuf::Option();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::Option::InitAsDefaultInstance();
+}
+
+void InitDefaultsOption() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsOptionImpl);
+}
+
+::google::protobuf::Metadata file_level_metadata[5];
+const ::google::protobuf::EnumDescriptor* file_level_enum_descriptors[3];
+
+const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+ ~0u, // no _has_bits_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Type, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Type, name_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Type, fields_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Type, oneofs_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Type, options_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Type, source_context_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Type, syntax_),
+ ~0u, // no _has_bits_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Field, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Field, kind_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Field, cardinality_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Field, number_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Field, name_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Field, type_url_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Field, oneof_index_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Field, packed_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Field, options_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Field, json_name_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Field, default_value_),
+ ~0u, // no _has_bits_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Enum, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Enum, name_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Enum, enumvalue_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Enum, options_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Enum, source_context_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Enum, syntax_),
+ ~0u, // no _has_bits_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumValue, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumValue, name_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumValue, number_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumValue, options_),
+ ~0u, // no _has_bits_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Option, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Option, name_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Option, value_),
+};
+static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+ { 0, -1, sizeof(::google::protobuf::Type)},
+ { 11, -1, sizeof(::google::protobuf::Field)},
+ { 26, -1, sizeof(::google::protobuf::Enum)},
+ { 36, -1, sizeof(::google::protobuf::EnumValue)},
+ { 44, -1, sizeof(::google::protobuf::Option)},
};
-namespace {
+static ::google::protobuf::Message const * const file_default_instances[] = {
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_Type_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_Field_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_Enum_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_EnumValue_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_Option_default_instance_),
+};
void protobuf_AssignDescriptors() {
- protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto();
+ AddDescriptors();
::google::protobuf::MessageFactory* factory = NULL;
AssignDescriptors(
- "google/protobuf/type.proto", schemas, file_default_instances, protobuf_Offsets_google_2fprotobuf_2ftype_2eproto(), factory,
+ "google/protobuf/type.proto", schemas, file_default_instances, TableStruct::offsets, factory,
file_level_metadata, file_level_enum_descriptors, NULL);
}
@@ -122,53 +248,15 @@ void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);
}
-void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
+void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 5);
}
-} // namespace
-
-void protobuf_ShutdownFile_google_2fprotobuf_2ftype_2eproto() {
- _Type_default_instance_.Shutdown();
- delete file_level_metadata[0].reflection;
- _Field_default_instance_.Shutdown();
- delete file_level_metadata[1].reflection;
- _Enum_default_instance_.Shutdown();
- delete file_level_metadata[2].reflection;
- _EnumValue_default_instance_.Shutdown();
- delete file_level_metadata[3].reflection;
- _Option_default_instance_.Shutdown();
- delete file_level_metadata[4].reflection;
-}
-
-void protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto_impl() {
- GOOGLE_PROTOBUF_VERIFY_VERSION;
-
- ::google::protobuf::protobuf_InitDefaults_google_2fprotobuf_2fany_2eproto();
- ::google::protobuf::protobuf_InitDefaults_google_2fprotobuf_2fsource_5fcontext_2eproto();
- ::google::protobuf::internal::InitProtobufDefaults();
- _Type_default_instance_.DefaultConstruct();
- _Field_default_instance_.DefaultConstruct();
- _Enum_default_instance_.DefaultConstruct();
- _EnumValue_default_instance_.DefaultConstruct();
- _Option_default_instance_.DefaultConstruct();
- _Type_default_instance_.get_mutable()->source_context_ = const_cast< ::google::protobuf::SourceContext*>(
- ::google::protobuf::SourceContext::internal_default_instance());
- _Enum_default_instance_.get_mutable()->source_context_ = const_cast< ::google::protobuf::SourceContext*>(
- ::google::protobuf::SourceContext::internal_default_instance());
- _Option_default_instance_.get_mutable()->value_ = const_cast< ::google::protobuf::Any*>(
- ::google::protobuf::Any::internal_default_instance());
-}
-
-void protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto_impl);
-}
-void protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto_impl() {
- protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto();
- static const char descriptor[] = {
+void AddDescriptorsImpl() {
+ InitDefaults();
+ static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n\032google/protobuf/type.proto\022\017google.pro"
"tobuf\032\031google/protobuf/any.proto\032$google"
"/protobuf/source_context.proto\"\327\001\n\004Type\022"
@@ -214,25 +302,26 @@ void protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto_impl() {
descriptor, 1594);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"google/protobuf/type.proto", &protobuf_RegisterTypes);
- ::google::protobuf::protobuf_AddDesc_google_2fprotobuf_2fany_2eproto();
- ::google::protobuf::protobuf_AddDesc_google_2fprotobuf_2fsource_5fcontext_2eproto();
- ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_google_2fprotobuf_2ftype_2eproto);
+ ::protobuf_google_2fprotobuf_2fany_2eproto::AddDescriptors();
+ ::protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::AddDescriptors();
}
-GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto_once_);
-void protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto() {
- ::google::protobuf::GoogleOnceInit(&protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto_once_,
- &protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto_impl);
+void AddDescriptors() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);
}
-// Force AddDescriptors() to be called at static initialization time.
-struct StaticDescriptorInitializer_google_2fprotobuf_2ftype_2eproto {
- StaticDescriptorInitializer_google_2fprotobuf_2ftype_2eproto() {
- protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto();
+// Force AddDescriptors() to be called at dynamic initialization time.
+struct StaticDescriptorInitializer {
+ StaticDescriptorInitializer() {
+ AddDescriptors();
}
-} static_descriptor_initializer_google_2fprotobuf_2ftype_2eproto_;
+} static_descriptor_initializer;
+} // namespace protobuf_google_2fprotobuf_2ftype_2eproto
+namespace google {
+namespace protobuf {
const ::google::protobuf::EnumDescriptor* Field_Kind_descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_enum_descriptors[0];
+ protobuf_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce();
+ return protobuf_google_2fprotobuf_2ftype_2eproto::file_level_enum_descriptors[0];
}
bool Field_Kind_IsValid(int value) {
switch (value) {
@@ -286,8 +375,8 @@ const Field_Kind Field::Kind_MAX;
const int Field::Kind_ARRAYSIZE;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
const ::google::protobuf::EnumDescriptor* Field_Cardinality_descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_enum_descriptors[1];
+ protobuf_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce();
+ return protobuf_google_2fprotobuf_2ftype_2eproto::file_level_enum_descriptors[1];
}
bool Field_Cardinality_IsValid(int value) {
switch (value) {
@@ -311,8 +400,8 @@ const Field_Cardinality Field::Cardinality_MAX;
const int Field::Cardinality_ARRAYSIZE;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
const ::google::protobuf::EnumDescriptor* Syntax_descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_enum_descriptors[2];
+ protobuf_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce();
+ return protobuf_google_2fprotobuf_2ftype_2eproto::file_level_enum_descriptors[2];
}
bool Syntax_IsValid(int value) {
switch (value) {
@@ -327,26 +416,14 @@ bool Syntax_IsValid(int value) {
// ===================================================================
+void Type::InitAsDefaultInstance() {
+ ::google::protobuf::_Type_default_instance_._instance.get_mutable()->source_context_ = const_cast< ::google::protobuf::SourceContext*>(
+ ::google::protobuf::SourceContext::internal_default_instance());
+}
void Type::_slow_mutable_source_context() {
source_context_ = ::google::protobuf::Arena::Create< ::google::protobuf::SourceContext >(
GetArenaNoVirtual());
}
-::google::protobuf::SourceContext* Type::_slow_release_source_context() {
- if (source_context_ == NULL) {
- return NULL;
- } else {
- ::google::protobuf::SourceContext* temp = new ::google::protobuf::SourceContext(*source_context_);
- source_context_ = NULL;
- return temp;
- }
-}
-::google::protobuf::SourceContext* Type::unsafe_arena_release_source_context() {
- // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Type.source_context)
-
- ::google::protobuf::SourceContext* temp = source_context_;
- source_context_ = NULL;
- return temp;
-}
void Type::unsafe_arena_set_allocated_source_context(
::google::protobuf::SourceContext* source_context) {
if (GetArenaNoVirtual() == NULL) {
@@ -360,6 +437,12 @@ void Type::unsafe_arena_set_allocated_source_context(
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Type.source_context)
}
+void Type::clear_source_context() {
+ if (GetArenaNoVirtual() == NULL && source_context_ != NULL) {
+ delete source_context_;
+ }
+ source_context_ = NULL;
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Type::kNameFieldNumber;
const int Type::kFieldsFieldNumber;
@@ -372,7 +455,7 @@ const int Type::kSyntaxFieldNumber;
Type::Type()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto();
+ ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsType();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Type)
@@ -383,9 +466,7 @@ Type::Type(::google::protobuf::Arena* arena)
fields_(arena),
oneofs_(arena),
options_(arena) {
-#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
- protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto();
-#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsType();
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Type)
@@ -414,8 +495,9 @@ Type::Type(const Type& from)
void Type::SharedCtor() {
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- ::memset(&source_context_, 0, reinterpret_cast<char*>(&syntax_) -
- reinterpret_cast<char*>(&source_context_) + sizeof(syntax_));
+ ::memset(&source_context_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&syntax_) -
+ reinterpret_cast<char*>(&source_context_)) + sizeof(syntax_));
_cached_size_ = 0;
}
@@ -425,15 +507,9 @@ Type::~Type() {
}
void Type::SharedDtor() {
- ::google::protobuf::Arena* arena = GetArenaNoVirtual();
- if (arena != NULL) {
- return;
- }
-
- name_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena);
- if (this != internal_default_instance()) {
- delete source_context_;
- }
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
+ name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ if (this != internal_default_instance()) delete source_context_;
}
void Type::ArenaDtor(void* object) {
@@ -448,12 +524,12 @@ void Type::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* Type::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[0].descriptor;
+ ::protobuf_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2ftype_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const Type& Type::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto();
+ ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsType();
return *internal_default_instance();
}
@@ -463,6 +539,10 @@ Type* Type::New(::google::protobuf::Arena* arena) const {
void Type::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Type)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
fields_.Clear();
oneofs_.Clear();
options_.Clear();
@@ -472,6 +552,7 @@ void Type::Clear() {
}
source_context_ = NULL;
syntax_ = 0;
+ _internal_metadata_.Clear();
}
bool Type::MergePartialFromCodedStream(
@@ -486,11 +567,12 @@ bool Type::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// string name = 1;
case 1: {
- if (tag == 10u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.protobuf.Type.name"));
} else {
@@ -501,25 +583,24 @@ bool Type::MergePartialFromCodedStream(
// repeated .google.protobuf.Field fields = 2;
case 2: {
- if (tag == 18u) {
- DO_(input->IncrementRecursionDepth());
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
- input, add_fields()));
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_fields()));
} else {
goto handle_unusual;
}
- input->UnsafeDecrementRecursionDepth();
break;
}
// repeated string oneofs = 3;
case 3: {
- if (tag == 26u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->add_oneofs()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->oneofs(this->oneofs_size() - 1).data(),
- this->oneofs(this->oneofs_size() - 1).length(),
+ static_cast<int>(this->oneofs(this->oneofs_size() - 1).length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.protobuf.Type.oneofs"));
} else {
@@ -530,21 +611,20 @@ bool Type::MergePartialFromCodedStream(
// repeated .google.protobuf.Option options = 4;
case 4: {
- if (tag == 34u) {
- DO_(input->IncrementRecursionDepth());
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
- input, add_options()));
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_options()));
} else {
goto handle_unusual;
}
- input->UnsafeDecrementRecursionDepth();
break;
}
// .google.protobuf.SourceContext source_context = 5;
case 5: {
- if (tag == 42u) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(42u /* 42 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_source_context()));
} else {
goto handle_unusual;
@@ -554,7 +634,8 @@ bool Type::MergePartialFromCodedStream(
// .google.protobuf.Syntax syntax = 6;
case 6: {
- if (tag == 48u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(48u /* 48 & 0xFF */)) {
int value;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
@@ -568,12 +649,11 @@ bool Type::MergePartialFromCodedStream(
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
- DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
+ DO_(::google::protobuf::internal::WireFormat::SkipField(
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -590,10 +670,13 @@ failure:
void Type::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.Type)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// string name = 1;
if (this->name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Type.name");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -601,15 +684,16 @@ void Type::SerializeWithCachedSizes(
}
// repeated .google.protobuf.Field fields = 2;
- for (unsigned int i = 0, n = this->fields_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->fields_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 2, this->fields(i), output);
+ 2, this->fields(static_cast<int>(i)), output);
}
// repeated string oneofs = 3;
- for (int i = 0; i < this->oneofs_size(); i++) {
+ for (int i = 0, n = this->oneofs_size(); i < n; i++) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->oneofs(i).data(), this->oneofs(i).length(),
+ this->oneofs(i).data(), static_cast<int>(this->oneofs(i).length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Type.oneofs");
::google::protobuf::internal::WireFormatLite::WriteString(
@@ -617,9 +701,10 @@ void Type::SerializeWithCachedSizes(
}
// repeated .google.protobuf.Option options = 4;
- for (unsigned int i = 0, n = this->options_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->options_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 4, this->options(i), output);
+ 4, this->options(static_cast<int>(i)), output);
}
// .google.protobuf.SourceContext source_context = 5;
@@ -634,6 +719,10 @@ void Type::SerializeWithCachedSizes(
6, this->syntax(), output);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ }
// @@protoc_insertion_point(serialize_end:google.protobuf.Type)
}
@@ -641,10 +730,13 @@ void Type::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Type)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// string name = 1;
if (this->name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Type.name");
target =
@@ -653,16 +745,17 @@ void Type::SerializeWithCachedSizes(
}
// repeated .google.protobuf.Field fields = 2;
- for (unsigned int i = 0, n = this->fields_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->fields_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 2, this->fields(i), false, target);
+ InternalWriteMessageToArray(
+ 2, this->fields(static_cast<int>(i)), deterministic, target);
}
// repeated string oneofs = 3;
- for (int i = 0; i < this->oneofs_size(); i++) {
+ for (int i = 0, n = this->oneofs_size(); i < n; i++) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->oneofs(i).data(), this->oneofs(i).length(),
+ this->oneofs(i).data(), static_cast<int>(this->oneofs(i).length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Type.oneofs");
target = ::google::protobuf::internal::WireFormatLite::
@@ -670,17 +763,18 @@ void Type::SerializeWithCachedSizes(
}
// repeated .google.protobuf.Option options = 4;
- for (unsigned int i = 0, n = this->options_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->options_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 4, this->options(i), false, target);
+ InternalWriteMessageToArray(
+ 4, this->options(static_cast<int>(i)), deterministic, target);
}
// .google.protobuf.SourceContext source_context = 5;
if (this->has_source_context()) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 5, *this->source_context_, false, target);
+ InternalWriteMessageToArray(
+ 5, *this->source_context_, deterministic, target);
}
// .google.protobuf.Syntax syntax = 6;
@@ -689,6 +783,10 @@ void Type::SerializeWithCachedSizes(
6, this->syntax(), target);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ }
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Type)
return target;
}
@@ -697,33 +795,38 @@ size_t Type::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.Type)
size_t total_size = 0;
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ total_size +=
+ ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ }
// repeated .google.protobuf.Field fields = 2;
{
- unsigned int count = this->fields_size();
+ unsigned int count = static_cast<unsigned int>(this->fields_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->fields(i));
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->fields(static_cast<int>(i)));
}
}
// repeated string oneofs = 3;
total_size += 1 *
::google::protobuf::internal::FromIntSize(this->oneofs_size());
- for (int i = 0; i < this->oneofs_size(); i++) {
+ for (int i = 0, n = this->oneofs_size(); i < n; i++) {
total_size += ::google::protobuf::internal::WireFormatLite::StringSize(
this->oneofs(i));
}
// repeated .google.protobuf.Option options = 4;
{
- unsigned int count = this->options_size();
+ unsigned int count = static_cast<unsigned int>(this->options_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->options(i));
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->options(static_cast<int>(i)));
}
}
@@ -737,7 +840,7 @@ size_t Type::ByteSizeLong() const {
// .google.protobuf.SourceContext source_context = 5;
if (this->has_source_context()) {
total_size += 1 +
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
*this->source_context_);
}
@@ -773,6 +876,9 @@ void Type::MergeFrom(const Type& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Type)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
fields_.MergeFrom(from.fields_);
oneofs_.MergeFrom(from.oneofs_);
options_.MergeFrom(from.options_);
@@ -825,273 +931,27 @@ void Type::UnsafeArenaSwap(Type* other) {
InternalSwap(other);
}
void Type::InternalSwap(Type* other) {
- fields_.UnsafeArenaSwap(&other->fields_);
- oneofs_.UnsafeArenaSwap(&other->oneofs_);
- options_.UnsafeArenaSwap(&other->options_);
+ using std::swap;
+ fields_.InternalSwap(&other->fields_);
+ oneofs_.InternalSwap(&other->oneofs_);
+ options_.InternalSwap(&other->options_);
name_.Swap(&other->name_);
- std::swap(source_context_, other->source_context_);
- std::swap(syntax_, other->syntax_);
- std::swap(_cached_size_, other->_cached_size_);
+ swap(source_context_, other->source_context_);
+ swap(syntax_, other->syntax_);
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Type::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[0];
+ protobuf_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2ftype_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// Type
-
-// string name = 1;
-void Type::clear_name() {
- name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
-}
-const ::std::string& Type::name() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Type.name)
- return name_.Get();
-}
-void Type::set_name(const ::std::string& value) {
-
- name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set:google.protobuf.Type.name)
-}
-void Type::set_name(const char* value) {
-
- name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set_char:google.protobuf.Type.name)
-}
-void Type::set_name(const char* value,
- size_t size) {
-
- name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.Type.name)
-}
-::std::string* Type::mutable_name() {
-
- // @@protoc_insertion_point(field_mutable:google.protobuf.Type.name)
- return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
-}
-::std::string* Type::release_name() {
- // @@protoc_insertion_point(field_release:google.protobuf.Type.name)
-
- return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
-}
-::std::string* Type::unsafe_arena_release_name() {
- // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Type.name)
- GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
-
- return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
-}
-void Type::set_allocated_name(::std::string* name) {
- if (name != NULL) {
-
- } else {
-
- }
- name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name,
- GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.Type.name)
-}
-void Type::unsafe_arena_set_allocated_name(
- ::std::string* name) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
- if (name != NULL) {
-
- } else {
-
- }
- name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- name, GetArenaNoVirtual());
- // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Type.name)
-}
-
-// repeated .google.protobuf.Field fields = 2;
-int Type::fields_size() const {
- return fields_.size();
-}
-void Type::clear_fields() {
- fields_.Clear();
-}
-const ::google::protobuf::Field& Type::fields(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.Type.fields)
- return fields_.Get(index);
-}
-::google::protobuf::Field* Type::mutable_fields(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.Type.fields)
- return fields_.Mutable(index);
-}
-::google::protobuf::Field* Type::add_fields() {
- // @@protoc_insertion_point(field_add:google.protobuf.Type.fields)
- return fields_.Add();
-}
-::google::protobuf::RepeatedPtrField< ::google::protobuf::Field >*
-Type::mutable_fields() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.Type.fields)
- return &fields_;
-}
-const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Field >&
-Type::fields() const {
- // @@protoc_insertion_point(field_list:google.protobuf.Type.fields)
- return fields_;
-}
-
-// repeated string oneofs = 3;
-int Type::oneofs_size() const {
- return oneofs_.size();
-}
-void Type::clear_oneofs() {
- oneofs_.Clear();
-}
-const ::std::string& Type::oneofs(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.Type.oneofs)
- return oneofs_.Get(index);
-}
-::std::string* Type::mutable_oneofs(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.Type.oneofs)
- return oneofs_.Mutable(index);
-}
-void Type::set_oneofs(int index, const ::std::string& value) {
- // @@protoc_insertion_point(field_set:google.protobuf.Type.oneofs)
- oneofs_.Mutable(index)->assign(value);
-}
-void Type::set_oneofs(int index, const char* value) {
- oneofs_.Mutable(index)->assign(value);
- // @@protoc_insertion_point(field_set_char:google.protobuf.Type.oneofs)
-}
-void Type::set_oneofs(int index, const char* value, size_t size) {
- oneofs_.Mutable(index)->assign(
- reinterpret_cast<const char*>(value), size);
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.Type.oneofs)
-}
-::std::string* Type::add_oneofs() {
- // @@protoc_insertion_point(field_add_mutable:google.protobuf.Type.oneofs)
- return oneofs_.Add();
-}
-void Type::add_oneofs(const ::std::string& value) {
- oneofs_.Add()->assign(value);
- // @@protoc_insertion_point(field_add:google.protobuf.Type.oneofs)
-}
-void Type::add_oneofs(const char* value) {
- oneofs_.Add()->assign(value);
- // @@protoc_insertion_point(field_add_char:google.protobuf.Type.oneofs)
-}
-void Type::add_oneofs(const char* value, size_t size) {
- oneofs_.Add()->assign(reinterpret_cast<const char*>(value), size);
- // @@protoc_insertion_point(field_add_pointer:google.protobuf.Type.oneofs)
-}
-const ::google::protobuf::RepeatedPtrField< ::std::string>&
-Type::oneofs() const {
- // @@protoc_insertion_point(field_list:google.protobuf.Type.oneofs)
- return oneofs_;
-}
-::google::protobuf::RepeatedPtrField< ::std::string>*
-Type::mutable_oneofs() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.Type.oneofs)
- return &oneofs_;
-}
-
-// repeated .google.protobuf.Option options = 4;
-int Type::options_size() const {
- return options_.size();
-}
-void Type::clear_options() {
- options_.Clear();
-}
-const ::google::protobuf::Option& Type::options(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.Type.options)
- return options_.Get(index);
-}
-::google::protobuf::Option* Type::mutable_options(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.Type.options)
- return options_.Mutable(index);
-}
-::google::protobuf::Option* Type::add_options() {
- // @@protoc_insertion_point(field_add:google.protobuf.Type.options)
- return options_.Add();
-}
-::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >*
-Type::mutable_options() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.Type.options)
- return &options_;
-}
-const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >&
-Type::options() const {
- // @@protoc_insertion_point(field_list:google.protobuf.Type.options)
- return options_;
-}
-
-// .google.protobuf.SourceContext source_context = 5;
-bool Type::has_source_context() const {
- return this != internal_default_instance() && source_context_ != NULL;
-}
-void Type::clear_source_context() {
- if (GetArenaNoVirtual() == NULL && source_context_ != NULL) delete source_context_;
- source_context_ = NULL;
-}
-const ::google::protobuf::SourceContext& Type::source_context() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Type.source_context)
- return source_context_ != NULL ? *source_context_
- : *::google::protobuf::SourceContext::internal_default_instance();
-}
-::google::protobuf::SourceContext* Type::mutable_source_context() {
-
- if (source_context_ == NULL) {
- _slow_mutable_source_context();
- }
- // @@protoc_insertion_point(field_mutable:google.protobuf.Type.source_context)
- return source_context_;
-}
-::google::protobuf::SourceContext* Type::release_source_context() {
- // @@protoc_insertion_point(field_release:google.protobuf.Type.source_context)
-
- if (GetArenaNoVirtual() != NULL) {
- return _slow_release_source_context();
- } else {
- ::google::protobuf::SourceContext* temp = source_context_;
- source_context_ = NULL;
- return temp;
- }
-}
- void Type::set_allocated_source_context(::google::protobuf::SourceContext* source_context) {
- ::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
- if (message_arena == NULL) {
- delete source_context_;
- }
- if (source_context != NULL) {
- if (message_arena != NULL) {
- message_arena->Own(source_context);
- }
- }
- source_context_ = source_context;
- if (source_context) {
-
- } else {
-
- }
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.Type.source_context)
-}
-
-// .google.protobuf.Syntax syntax = 6;
-void Type::clear_syntax() {
- syntax_ = 0;
-}
-::google::protobuf::Syntax Type::syntax() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Type.syntax)
- return static_cast< ::google::protobuf::Syntax >(syntax_);
-}
-void Type::set_syntax(::google::protobuf::Syntax value) {
-
- syntax_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.Type.syntax)
-}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
+void Field::InitAsDefaultInstance() {
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Field::kKindFieldNumber;
const int Field::kCardinalityFieldNumber;
@@ -1108,7 +968,7 @@ const int Field::kDefaultValueFieldNumber;
Field::Field()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto();
+ ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsField();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Field)
@@ -1117,9 +977,7 @@ Field::Field(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
options_(arena) {
-#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
- protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto();
-#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsField();
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Field)
@@ -1151,8 +1009,8 @@ Field::Field(const Field& from)
GetArenaNoVirtual());
}
::memcpy(&kind_, &from.kind_,
- reinterpret_cast<char*>(&packed_) -
- reinterpret_cast<char*>(&kind_) + sizeof(packed_));
+ static_cast<size_t>(reinterpret_cast<char*>(&packed_) -
+ reinterpret_cast<char*>(&kind_)) + sizeof(packed_));
// @@protoc_insertion_point(copy_constructor:google.protobuf.Field)
}
@@ -1161,8 +1019,9 @@ void Field::SharedCtor() {
type_url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
json_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
default_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- ::memset(&kind_, 0, reinterpret_cast<char*>(&packed_) -
- reinterpret_cast<char*>(&kind_) + sizeof(packed_));
+ ::memset(&kind_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&packed_) -
+ reinterpret_cast<char*>(&kind_)) + sizeof(packed_));
_cached_size_ = 0;
}
@@ -1172,15 +1031,11 @@ Field::~Field() {
}
void Field::SharedDtor() {
- ::google::protobuf::Arena* arena = GetArenaNoVirtual();
- if (arena != NULL) {
- return;
- }
-
- name_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena);
- type_url_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena);
- json_name_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena);
- default_value_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena);
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
+ name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ type_url_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ json_name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ default_value_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void Field::ArenaDtor(void* object) {
@@ -1195,12 +1050,12 @@ void Field::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* Field::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[1].descriptor;
+ ::protobuf_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2ftype_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const Field& Field::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto();
+ ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsField();
return *internal_default_instance();
}
@@ -1210,13 +1065,19 @@ Field* Field::New(::google::protobuf::Arena* arena) const {
void Field::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Field)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
options_.Clear();
name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
type_url_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
json_name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
default_value_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- ::memset(&kind_, 0, reinterpret_cast<char*>(&packed_) -
- reinterpret_cast<char*>(&kind_) + sizeof(packed_));
+ ::memset(&kind_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&packed_) -
+ reinterpret_cast<char*>(&kind_)) + sizeof(packed_));
+ _internal_metadata_.Clear();
}
bool Field::MergePartialFromCodedStream(
@@ -1231,7 +1092,8 @@ bool Field::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// .google.protobuf.Field.Kind kind = 1;
case 1: {
- if (tag == 8u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
int value;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
@@ -1245,7 +1107,8 @@ bool Field::MergePartialFromCodedStream(
// .google.protobuf.Field.Cardinality cardinality = 2;
case 2: {
- if (tag == 16u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
int value;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
@@ -1259,7 +1122,8 @@ bool Field::MergePartialFromCodedStream(
// int32 number = 3;
case 3: {
- if (tag == 24u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
@@ -1272,11 +1136,12 @@ bool Field::MergePartialFromCodedStream(
// string name = 4;
case 4: {
- if (tag == 34u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.protobuf.Field.name"));
} else {
@@ -1287,11 +1152,12 @@ bool Field::MergePartialFromCodedStream(
// string type_url = 6;
case 6: {
- if (tag == 50u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(50u /* 50 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_type_url()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->type_url().data(), this->type_url().length(),
+ this->type_url().data(), static_cast<int>(this->type_url().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.protobuf.Field.type_url"));
} else {
@@ -1302,7 +1168,8 @@ bool Field::MergePartialFromCodedStream(
// int32 oneof_index = 7;
case 7: {
- if (tag == 56u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(56u /* 56 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
@@ -1315,7 +1182,8 @@ bool Field::MergePartialFromCodedStream(
// bool packed = 8;
case 8: {
- if (tag == 64u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(64u /* 64 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
@@ -1328,24 +1196,23 @@ bool Field::MergePartialFromCodedStream(
// repeated .google.protobuf.Option options = 9;
case 9: {
- if (tag == 74u) {
- DO_(input->IncrementRecursionDepth());
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
- input, add_options()));
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(74u /* 74 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_options()));
} else {
goto handle_unusual;
}
- input->UnsafeDecrementRecursionDepth();
break;
}
// string json_name = 10;
case 10: {
- if (tag == 82u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(82u /* 82 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_json_name()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->json_name().data(), this->json_name().length(),
+ this->json_name().data(), static_cast<int>(this->json_name().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.protobuf.Field.json_name"));
} else {
@@ -1356,11 +1223,12 @@ bool Field::MergePartialFromCodedStream(
// string default_value = 11;
case 11: {
- if (tag == 90u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(90u /* 90 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_default_value()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->default_value().data(), this->default_value().length(),
+ this->default_value().data(), static_cast<int>(this->default_value().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.protobuf.Field.default_value"));
} else {
@@ -1371,12 +1239,11 @@ bool Field::MergePartialFromCodedStream(
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
- DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
+ DO_(::google::protobuf::internal::WireFormat::SkipField(
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -1393,6 +1260,9 @@ failure:
void Field::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.Field)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// .google.protobuf.Field.Kind kind = 1;
if (this->kind() != 0) {
::google::protobuf::internal::WireFormatLite::WriteEnum(
@@ -1413,7 +1283,7 @@ void Field::SerializeWithCachedSizes(
// string name = 4;
if (this->name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Field.name");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -1423,7 +1293,7 @@ void Field::SerializeWithCachedSizes(
// string type_url = 6;
if (this->type_url().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->type_url().data(), this->type_url().length(),
+ this->type_url().data(), static_cast<int>(this->type_url().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Field.type_url");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -1441,15 +1311,16 @@ void Field::SerializeWithCachedSizes(
}
// repeated .google.protobuf.Option options = 9;
- for (unsigned int i = 0, n = this->options_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->options_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 9, this->options(i), output);
+ 9, this->options(static_cast<int>(i)), output);
}
// string json_name = 10;
if (this->json_name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->json_name().data(), this->json_name().length(),
+ this->json_name().data(), static_cast<int>(this->json_name().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Field.json_name");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -1459,13 +1330,17 @@ void Field::SerializeWithCachedSizes(
// string default_value = 11;
if (this->default_value().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->default_value().data(), this->default_value().length(),
+ this->default_value().data(), static_cast<int>(this->default_value().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Field.default_value");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
11, this->default_value(), output);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ }
// @@protoc_insertion_point(serialize_end:google.protobuf.Field)
}
@@ -1473,6 +1348,9 @@ void Field::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Field)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// .google.protobuf.Field.Kind kind = 1;
if (this->kind() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray(
@@ -1493,7 +1371,7 @@ void Field::SerializeWithCachedSizes(
// string name = 4;
if (this->name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Field.name");
target =
@@ -1504,7 +1382,7 @@ void Field::SerializeWithCachedSizes(
// string type_url = 6;
if (this->type_url().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->type_url().data(), this->type_url().length(),
+ this->type_url().data(), static_cast<int>(this->type_url().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Field.type_url");
target =
@@ -1523,16 +1401,17 @@ void Field::SerializeWithCachedSizes(
}
// repeated .google.protobuf.Option options = 9;
- for (unsigned int i = 0, n = this->options_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->options_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 9, this->options(i), false, target);
+ InternalWriteMessageToArray(
+ 9, this->options(static_cast<int>(i)), deterministic, target);
}
// string json_name = 10;
if (this->json_name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->json_name().data(), this->json_name().length(),
+ this->json_name().data(), static_cast<int>(this->json_name().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Field.json_name");
target =
@@ -1543,7 +1422,7 @@ void Field::SerializeWithCachedSizes(
// string default_value = 11;
if (this->default_value().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->default_value().data(), this->default_value().length(),
+ this->default_value().data(), static_cast<int>(this->default_value().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Field.default_value");
target =
@@ -1551,6 +1430,10 @@ void Field::SerializeWithCachedSizes(
11, this->default_value(), target);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ }
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Field)
return target;
}
@@ -1559,14 +1442,19 @@ size_t Field::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.Field)
size_t total_size = 0;
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ total_size +=
+ ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ }
// repeated .google.protobuf.Option options = 9;
{
- unsigned int count = this->options_size();
+ unsigned int count = static_cast<unsigned int>(this->options_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->options(i));
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->options(static_cast<int>(i)));
}
}
@@ -1655,6 +1543,9 @@ void Field::MergeFrom(const Field& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Field)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
options_.MergeFrom(from.options_);
if (from.name().size() > 0) {
set_name(from.name());
@@ -1723,415 +1614,37 @@ void Field::UnsafeArenaSwap(Field* other) {
InternalSwap(other);
}
void Field::InternalSwap(Field* other) {
- options_.UnsafeArenaSwap(&other->options_);
+ using std::swap;
+ options_.InternalSwap(&other->options_);
name_.Swap(&other->name_);
type_url_.Swap(&other->type_url_);
json_name_.Swap(&other->json_name_);
default_value_.Swap(&other->default_value_);
- std::swap(kind_, other->kind_);
- std::swap(cardinality_, other->cardinality_);
- std::swap(number_, other->number_);
- std::swap(oneof_index_, other->oneof_index_);
- std::swap(packed_, other->packed_);
- std::swap(_cached_size_, other->_cached_size_);
+ swap(kind_, other->kind_);
+ swap(cardinality_, other->cardinality_);
+ swap(number_, other->number_);
+ swap(oneof_index_, other->oneof_index_);
+ swap(packed_, other->packed_);
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Field::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[1];
+ protobuf_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2ftype_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// Field
-
-// .google.protobuf.Field.Kind kind = 1;
-void Field::clear_kind() {
- kind_ = 0;
-}
-::google::protobuf::Field_Kind Field::kind() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Field.kind)
- return static_cast< ::google::protobuf::Field_Kind >(kind_);
-}
-void Field::set_kind(::google::protobuf::Field_Kind value) {
-
- kind_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.Field.kind)
-}
-
-// .google.protobuf.Field.Cardinality cardinality = 2;
-void Field::clear_cardinality() {
- cardinality_ = 0;
-}
-::google::protobuf::Field_Cardinality Field::cardinality() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Field.cardinality)
- return static_cast< ::google::protobuf::Field_Cardinality >(cardinality_);
-}
-void Field::set_cardinality(::google::protobuf::Field_Cardinality value) {
-
- cardinality_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.Field.cardinality)
-}
-
-// int32 number = 3;
-void Field::clear_number() {
- number_ = 0;
-}
-::google::protobuf::int32 Field::number() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Field.number)
- return number_;
-}
-void Field::set_number(::google::protobuf::int32 value) {
-
- number_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.Field.number)
-}
-
-// string name = 4;
-void Field::clear_name() {
- name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
-}
-const ::std::string& Field::name() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Field.name)
- return name_.Get();
-}
-void Field::set_name(const ::std::string& value) {
-
- name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set:google.protobuf.Field.name)
-}
-void Field::set_name(const char* value) {
-
- name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set_char:google.protobuf.Field.name)
-}
-void Field::set_name(const char* value,
- size_t size) {
-
- name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.Field.name)
-}
-::std::string* Field::mutable_name() {
-
- // @@protoc_insertion_point(field_mutable:google.protobuf.Field.name)
- return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
-}
-::std::string* Field::release_name() {
- // @@protoc_insertion_point(field_release:google.protobuf.Field.name)
-
- return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
-}
-::std::string* Field::unsafe_arena_release_name() {
- // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Field.name)
- GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
-
- return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
-}
-void Field::set_allocated_name(::std::string* name) {
- if (name != NULL) {
-
- } else {
-
- }
- name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name,
- GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.Field.name)
-}
-void Field::unsafe_arena_set_allocated_name(
- ::std::string* name) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
- if (name != NULL) {
-
- } else {
-
- }
- name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- name, GetArenaNoVirtual());
- // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Field.name)
-}
-
-// string type_url = 6;
-void Field::clear_type_url() {
- type_url_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
-}
-const ::std::string& Field::type_url() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Field.type_url)
- return type_url_.Get();
-}
-void Field::set_type_url(const ::std::string& value) {
-
- type_url_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set:google.protobuf.Field.type_url)
-}
-void Field::set_type_url(const char* value) {
-
- type_url_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set_char:google.protobuf.Field.type_url)
-}
-void Field::set_type_url(const char* value,
- size_t size) {
-
- type_url_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.Field.type_url)
-}
-::std::string* Field::mutable_type_url() {
-
- // @@protoc_insertion_point(field_mutable:google.protobuf.Field.type_url)
- return type_url_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
-}
-::std::string* Field::release_type_url() {
- // @@protoc_insertion_point(field_release:google.protobuf.Field.type_url)
-
- return type_url_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
-}
-::std::string* Field::unsafe_arena_release_type_url() {
- // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Field.type_url)
- GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
-
- return type_url_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
-}
-void Field::set_allocated_type_url(::std::string* type_url) {
- if (type_url != NULL) {
-
- } else {
-
- }
- type_url_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), type_url,
- GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.Field.type_url)
-}
-void Field::unsafe_arena_set_allocated_type_url(
- ::std::string* type_url) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
- if (type_url != NULL) {
-
- } else {
-
- }
- type_url_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- type_url, GetArenaNoVirtual());
- // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Field.type_url)
-}
-
-// int32 oneof_index = 7;
-void Field::clear_oneof_index() {
- oneof_index_ = 0;
-}
-::google::protobuf::int32 Field::oneof_index() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Field.oneof_index)
- return oneof_index_;
-}
-void Field::set_oneof_index(::google::protobuf::int32 value) {
-
- oneof_index_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.Field.oneof_index)
-}
-
-// bool packed = 8;
-void Field::clear_packed() {
- packed_ = false;
-}
-bool Field::packed() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Field.packed)
- return packed_;
-}
-void Field::set_packed(bool value) {
-
- packed_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.Field.packed)
-}
-
-// repeated .google.protobuf.Option options = 9;
-int Field::options_size() const {
- return options_.size();
-}
-void Field::clear_options() {
- options_.Clear();
-}
-const ::google::protobuf::Option& Field::options(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.Field.options)
- return options_.Get(index);
-}
-::google::protobuf::Option* Field::mutable_options(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.Field.options)
- return options_.Mutable(index);
-}
-::google::protobuf::Option* Field::add_options() {
- // @@protoc_insertion_point(field_add:google.protobuf.Field.options)
- return options_.Add();
-}
-::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >*
-Field::mutable_options() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.Field.options)
- return &options_;
-}
-const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >&
-Field::options() const {
- // @@protoc_insertion_point(field_list:google.protobuf.Field.options)
- return options_;
-}
-
-// string json_name = 10;
-void Field::clear_json_name() {
- json_name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
-}
-const ::std::string& Field::json_name() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Field.json_name)
- return json_name_.Get();
-}
-void Field::set_json_name(const ::std::string& value) {
-
- json_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set:google.protobuf.Field.json_name)
-}
-void Field::set_json_name(const char* value) {
-
- json_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set_char:google.protobuf.Field.json_name)
-}
-void Field::set_json_name(const char* value,
- size_t size) {
-
- json_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.Field.json_name)
-}
-::std::string* Field::mutable_json_name() {
-
- // @@protoc_insertion_point(field_mutable:google.protobuf.Field.json_name)
- return json_name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
-}
-::std::string* Field::release_json_name() {
- // @@protoc_insertion_point(field_release:google.protobuf.Field.json_name)
-
- return json_name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
-}
-::std::string* Field::unsafe_arena_release_json_name() {
- // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Field.json_name)
- GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
-
- return json_name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
-}
-void Field::set_allocated_json_name(::std::string* json_name) {
- if (json_name != NULL) {
-
- } else {
-
- }
- json_name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), json_name,
- GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.Field.json_name)
-}
-void Field::unsafe_arena_set_allocated_json_name(
- ::std::string* json_name) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
- if (json_name != NULL) {
-
- } else {
-
- }
- json_name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- json_name, GetArenaNoVirtual());
- // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Field.json_name)
-}
-
-// string default_value = 11;
-void Field::clear_default_value() {
- default_value_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
-}
-const ::std::string& Field::default_value() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Field.default_value)
- return default_value_.Get();
-}
-void Field::set_default_value(const ::std::string& value) {
-
- default_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set:google.protobuf.Field.default_value)
-}
-void Field::set_default_value(const char* value) {
-
- default_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set_char:google.protobuf.Field.default_value)
-}
-void Field::set_default_value(const char* value,
- size_t size) {
-
- default_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.Field.default_value)
-}
-::std::string* Field::mutable_default_value() {
-
- // @@protoc_insertion_point(field_mutable:google.protobuf.Field.default_value)
- return default_value_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
-}
-::std::string* Field::release_default_value() {
- // @@protoc_insertion_point(field_release:google.protobuf.Field.default_value)
-
- return default_value_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
-}
-::std::string* Field::unsafe_arena_release_default_value() {
- // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Field.default_value)
- GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
-
- return default_value_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
-}
-void Field::set_allocated_default_value(::std::string* default_value) {
- if (default_value != NULL) {
-
- } else {
-
- }
- default_value_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), default_value,
- GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.Field.default_value)
-}
-void Field::unsafe_arena_set_allocated_default_value(
- ::std::string* default_value) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
- if (default_value != NULL) {
-
- } else {
-
- }
- default_value_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- default_value, GetArenaNoVirtual());
- // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Field.default_value)
-}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
+void Enum::InitAsDefaultInstance() {
+ ::google::protobuf::_Enum_default_instance_._instance.get_mutable()->source_context_ = const_cast< ::google::protobuf::SourceContext*>(
+ ::google::protobuf::SourceContext::internal_default_instance());
+}
void Enum::_slow_mutable_source_context() {
source_context_ = ::google::protobuf::Arena::Create< ::google::protobuf::SourceContext >(
GetArenaNoVirtual());
}
-::google::protobuf::SourceContext* Enum::_slow_release_source_context() {
- if (source_context_ == NULL) {
- return NULL;
- } else {
- ::google::protobuf::SourceContext* temp = new ::google::protobuf::SourceContext(*source_context_);
- source_context_ = NULL;
- return temp;
- }
-}
-::google::protobuf::SourceContext* Enum::unsafe_arena_release_source_context() {
- // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Enum.source_context)
-
- ::google::protobuf::SourceContext* temp = source_context_;
- source_context_ = NULL;
- return temp;
-}
void Enum::unsafe_arena_set_allocated_source_context(
::google::protobuf::SourceContext* source_context) {
if (GetArenaNoVirtual() == NULL) {
@@ -2145,6 +1658,12 @@ void Enum::unsafe_arena_set_allocated_source_context(
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Enum.source_context)
}
+void Enum::clear_source_context() {
+ if (GetArenaNoVirtual() == NULL && source_context_ != NULL) {
+ delete source_context_;
+ }
+ source_context_ = NULL;
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Enum::kNameFieldNumber;
const int Enum::kEnumvalueFieldNumber;
@@ -2156,7 +1675,7 @@ const int Enum::kSyntaxFieldNumber;
Enum::Enum()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto();
+ ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsEnum();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Enum)
@@ -2166,9 +1685,7 @@ Enum::Enum(::google::protobuf::Arena* arena)
_internal_metadata_(arena),
enumvalue_(arena),
options_(arena) {
-#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
- protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto();
-#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsEnum();
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Enum)
@@ -2196,8 +1713,9 @@ Enum::Enum(const Enum& from)
void Enum::SharedCtor() {
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- ::memset(&source_context_, 0, reinterpret_cast<char*>(&syntax_) -
- reinterpret_cast<char*>(&source_context_) + sizeof(syntax_));
+ ::memset(&source_context_, 0, static_cast<size_t>(
+ reinterpret_cast<char*>(&syntax_) -
+ reinterpret_cast<char*>(&source_context_)) + sizeof(syntax_));
_cached_size_ = 0;
}
@@ -2207,15 +1725,9 @@ Enum::~Enum() {
}
void Enum::SharedDtor() {
- ::google::protobuf::Arena* arena = GetArenaNoVirtual();
- if (arena != NULL) {
- return;
- }
-
- name_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena);
- if (this != internal_default_instance()) {
- delete source_context_;
- }
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
+ name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ if (this != internal_default_instance()) delete source_context_;
}
void Enum::ArenaDtor(void* object) {
@@ -2230,12 +1742,12 @@ void Enum::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* Enum::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[2].descriptor;
+ ::protobuf_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2ftype_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const Enum& Enum::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto();
+ ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsEnum();
return *internal_default_instance();
}
@@ -2245,6 +1757,10 @@ Enum* Enum::New(::google::protobuf::Arena* arena) const {
void Enum::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Enum)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
enumvalue_.Clear();
options_.Clear();
name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
@@ -2253,6 +1769,7 @@ void Enum::Clear() {
}
source_context_ = NULL;
syntax_ = 0;
+ _internal_metadata_.Clear();
}
bool Enum::MergePartialFromCodedStream(
@@ -2267,11 +1784,12 @@ bool Enum::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// string name = 1;
case 1: {
- if (tag == 10u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.protobuf.Enum.name"));
} else {
@@ -2282,34 +1800,31 @@ bool Enum::MergePartialFromCodedStream(
// repeated .google.protobuf.EnumValue enumvalue = 2;
case 2: {
- if (tag == 18u) {
- DO_(input->IncrementRecursionDepth());
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
- input, add_enumvalue()));
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_enumvalue()));
} else {
goto handle_unusual;
}
- input->UnsafeDecrementRecursionDepth();
break;
}
// repeated .google.protobuf.Option options = 3;
case 3: {
- if (tag == 26u) {
- DO_(input->IncrementRecursionDepth());
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
- input, add_options()));
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_options()));
} else {
goto handle_unusual;
}
- input->UnsafeDecrementRecursionDepth();
break;
}
// .google.protobuf.SourceContext source_context = 4;
case 4: {
- if (tag == 34u) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_source_context()));
} else {
goto handle_unusual;
@@ -2319,7 +1834,8 @@ bool Enum::MergePartialFromCodedStream(
// .google.protobuf.Syntax syntax = 5;
case 5: {
- if (tag == 40u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) {
int value;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
@@ -2333,12 +1849,11 @@ bool Enum::MergePartialFromCodedStream(
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
- DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
+ DO_(::google::protobuf::internal::WireFormat::SkipField(
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -2355,10 +1870,13 @@ failure:
void Enum::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.Enum)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// string name = 1;
if (this->name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Enum.name");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -2366,15 +1884,17 @@ void Enum::SerializeWithCachedSizes(
}
// repeated .google.protobuf.EnumValue enumvalue = 2;
- for (unsigned int i = 0, n = this->enumvalue_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->enumvalue_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 2, this->enumvalue(i), output);
+ 2, this->enumvalue(static_cast<int>(i)), output);
}
// repeated .google.protobuf.Option options = 3;
- for (unsigned int i = 0, n = this->options_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->options_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 3, this->options(i), output);
+ 3, this->options(static_cast<int>(i)), output);
}
// .google.protobuf.SourceContext source_context = 4;
@@ -2389,6 +1909,10 @@ void Enum::SerializeWithCachedSizes(
5, this->syntax(), output);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ }
// @@protoc_insertion_point(serialize_end:google.protobuf.Enum)
}
@@ -2396,10 +1920,13 @@ void Enum::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Enum)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// string name = 1;
if (this->name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Enum.name");
target =
@@ -2408,24 +1935,26 @@ void Enum::SerializeWithCachedSizes(
}
// repeated .google.protobuf.EnumValue enumvalue = 2;
- for (unsigned int i = 0, n = this->enumvalue_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->enumvalue_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 2, this->enumvalue(i), false, target);
+ InternalWriteMessageToArray(
+ 2, this->enumvalue(static_cast<int>(i)), deterministic, target);
}
// repeated .google.protobuf.Option options = 3;
- for (unsigned int i = 0, n = this->options_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->options_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 3, this->options(i), false, target);
+ InternalWriteMessageToArray(
+ 3, this->options(static_cast<int>(i)), deterministic, target);
}
// .google.protobuf.SourceContext source_context = 4;
if (this->has_source_context()) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 4, *this->source_context_, false, target);
+ InternalWriteMessageToArray(
+ 4, *this->source_context_, deterministic, target);
}
// .google.protobuf.Syntax syntax = 5;
@@ -2434,6 +1963,10 @@ void Enum::SerializeWithCachedSizes(
5, this->syntax(), target);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ }
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Enum)
return target;
}
@@ -2442,25 +1975,30 @@ size_t Enum::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.Enum)
size_t total_size = 0;
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ total_size +=
+ ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ }
// repeated .google.protobuf.EnumValue enumvalue = 2;
{
- unsigned int count = this->enumvalue_size();
+ unsigned int count = static_cast<unsigned int>(this->enumvalue_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->enumvalue(i));
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->enumvalue(static_cast<int>(i)));
}
}
// repeated .google.protobuf.Option options = 3;
{
- unsigned int count = this->options_size();
+ unsigned int count = static_cast<unsigned int>(this->options_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->options(i));
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->options(static_cast<int>(i)));
}
}
@@ -2474,7 +2012,7 @@ size_t Enum::ByteSizeLong() const {
// .google.protobuf.SourceContext source_context = 4;
if (this->has_source_context()) {
total_size += 1 +
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
*this->source_context_);
}
@@ -2510,6 +2048,9 @@ void Enum::MergeFrom(const Enum& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Enum)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
enumvalue_.MergeFrom(from.enumvalue_);
options_.MergeFrom(from.options_);
if (from.name().size() > 0) {
@@ -2561,217 +2102,26 @@ void Enum::UnsafeArenaSwap(Enum* other) {
InternalSwap(other);
}
void Enum::InternalSwap(Enum* other) {
- enumvalue_.UnsafeArenaSwap(&other->enumvalue_);
- options_.UnsafeArenaSwap(&other->options_);
+ using std::swap;
+ enumvalue_.InternalSwap(&other->enumvalue_);
+ options_.InternalSwap(&other->options_);
name_.Swap(&other->name_);
- std::swap(source_context_, other->source_context_);
- std::swap(syntax_, other->syntax_);
- std::swap(_cached_size_, other->_cached_size_);
+ swap(source_context_, other->source_context_);
+ swap(syntax_, other->syntax_);
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Enum::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[2];
-}
-
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// Enum
-
-// string name = 1;
-void Enum::clear_name() {
- name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
-}
-const ::std::string& Enum::name() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Enum.name)
- return name_.Get();
-}
-void Enum::set_name(const ::std::string& value) {
-
- name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set:google.protobuf.Enum.name)
-}
-void Enum::set_name(const char* value) {
-
- name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set_char:google.protobuf.Enum.name)
-}
-void Enum::set_name(const char* value,
- size_t size) {
-
- name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.Enum.name)
-}
-::std::string* Enum::mutable_name() {
-
- // @@protoc_insertion_point(field_mutable:google.protobuf.Enum.name)
- return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
-}
-::std::string* Enum::release_name() {
- // @@protoc_insertion_point(field_release:google.protobuf.Enum.name)
-
- return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
-}
-::std::string* Enum::unsafe_arena_release_name() {
- // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Enum.name)
- GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
-
- return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
-}
-void Enum::set_allocated_name(::std::string* name) {
- if (name != NULL) {
-
- } else {
-
- }
- name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name,
- GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.Enum.name)
-}
-void Enum::unsafe_arena_set_allocated_name(
- ::std::string* name) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
- if (name != NULL) {
-
- } else {
-
- }
- name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- name, GetArenaNoVirtual());
- // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Enum.name)
-}
-
-// repeated .google.protobuf.EnumValue enumvalue = 2;
-int Enum::enumvalue_size() const {
- return enumvalue_.size();
-}
-void Enum::clear_enumvalue() {
- enumvalue_.Clear();
-}
-const ::google::protobuf::EnumValue& Enum::enumvalue(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.Enum.enumvalue)
- return enumvalue_.Get(index);
-}
-::google::protobuf::EnumValue* Enum::mutable_enumvalue(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.Enum.enumvalue)
- return enumvalue_.Mutable(index);
-}
-::google::protobuf::EnumValue* Enum::add_enumvalue() {
- // @@protoc_insertion_point(field_add:google.protobuf.Enum.enumvalue)
- return enumvalue_.Add();
-}
-::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumValue >*
-Enum::mutable_enumvalue() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.Enum.enumvalue)
- return &enumvalue_;
-}
-const ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumValue >&
-Enum::enumvalue() const {
- // @@protoc_insertion_point(field_list:google.protobuf.Enum.enumvalue)
- return enumvalue_;
-}
-
-// repeated .google.protobuf.Option options = 3;
-int Enum::options_size() const {
- return options_.size();
-}
-void Enum::clear_options() {
- options_.Clear();
-}
-const ::google::protobuf::Option& Enum::options(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.Enum.options)
- return options_.Get(index);
-}
-::google::protobuf::Option* Enum::mutable_options(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.Enum.options)
- return options_.Mutable(index);
-}
-::google::protobuf::Option* Enum::add_options() {
- // @@protoc_insertion_point(field_add:google.protobuf.Enum.options)
- return options_.Add();
-}
-::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >*
-Enum::mutable_options() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.Enum.options)
- return &options_;
-}
-const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >&
-Enum::options() const {
- // @@protoc_insertion_point(field_list:google.protobuf.Enum.options)
- return options_;
-}
-
-// .google.protobuf.SourceContext source_context = 4;
-bool Enum::has_source_context() const {
- return this != internal_default_instance() && source_context_ != NULL;
-}
-void Enum::clear_source_context() {
- if (GetArenaNoVirtual() == NULL && source_context_ != NULL) delete source_context_;
- source_context_ = NULL;
-}
-const ::google::protobuf::SourceContext& Enum::source_context() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Enum.source_context)
- return source_context_ != NULL ? *source_context_
- : *::google::protobuf::SourceContext::internal_default_instance();
-}
-::google::protobuf::SourceContext* Enum::mutable_source_context() {
-
- if (source_context_ == NULL) {
- _slow_mutable_source_context();
- }
- // @@protoc_insertion_point(field_mutable:google.protobuf.Enum.source_context)
- return source_context_;
-}
-::google::protobuf::SourceContext* Enum::release_source_context() {
- // @@protoc_insertion_point(field_release:google.protobuf.Enum.source_context)
-
- if (GetArenaNoVirtual() != NULL) {
- return _slow_release_source_context();
- } else {
- ::google::protobuf::SourceContext* temp = source_context_;
- source_context_ = NULL;
- return temp;
- }
-}
- void Enum::set_allocated_source_context(::google::protobuf::SourceContext* source_context) {
- ::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
- if (message_arena == NULL) {
- delete source_context_;
- }
- if (source_context != NULL) {
- if (message_arena != NULL) {
- message_arena->Own(source_context);
- }
- }
- source_context_ = source_context;
- if (source_context) {
-
- } else {
-
- }
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.Enum.source_context)
-}
-
-// .google.protobuf.Syntax syntax = 5;
-void Enum::clear_syntax() {
- syntax_ = 0;
-}
-::google::protobuf::Syntax Enum::syntax() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Enum.syntax)
- return static_cast< ::google::protobuf::Syntax >(syntax_);
-}
-void Enum::set_syntax(::google::protobuf::Syntax value) {
-
- syntax_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.Enum.syntax)
+ protobuf_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2ftype_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
+void EnumValue::InitAsDefaultInstance() {
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int EnumValue::kNameFieldNumber;
const int EnumValue::kNumberFieldNumber;
@@ -2781,7 +2131,7 @@ const int EnumValue::kOptionsFieldNumber;
EnumValue::EnumValue()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto();
+ ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsEnumValue();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.EnumValue)
@@ -2790,9 +2140,7 @@ EnumValue::EnumValue(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
options_(arena) {
-#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
- protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto();
-#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsEnumValue();
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.EnumValue)
@@ -2824,12 +2172,8 @@ EnumValue::~EnumValue() {
}
void EnumValue::SharedDtor() {
- ::google::protobuf::Arena* arena = GetArenaNoVirtual();
- if (arena != NULL) {
- return;
- }
-
- name_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena);
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
+ name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void EnumValue::ArenaDtor(void* object) {
@@ -2844,12 +2188,12 @@ void EnumValue::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* EnumValue::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[3].descriptor;
+ ::protobuf_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2ftype_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const EnumValue& EnumValue::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto();
+ ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsEnumValue();
return *internal_default_instance();
}
@@ -2859,9 +2203,14 @@ EnumValue* EnumValue::New(::google::protobuf::Arena* arena) const {
void EnumValue::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.EnumValue)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
options_.Clear();
name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
number_ = 0;
+ _internal_metadata_.Clear();
}
bool EnumValue::MergePartialFromCodedStream(
@@ -2876,11 +2225,12 @@ bool EnumValue::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// string name = 1;
case 1: {
- if (tag == 10u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.protobuf.EnumValue.name"));
} else {
@@ -2891,7 +2241,8 @@ bool EnumValue::MergePartialFromCodedStream(
// int32 number = 2;
case 2: {
- if (tag == 16u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
@@ -2904,25 +2255,22 @@ bool EnumValue::MergePartialFromCodedStream(
// repeated .google.protobuf.Option options = 3;
case 3: {
- if (tag == 26u) {
- DO_(input->IncrementRecursionDepth());
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
- input, add_options()));
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_options()));
} else {
goto handle_unusual;
}
- input->UnsafeDecrementRecursionDepth();
break;
}
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
- DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
+ DO_(::google::protobuf::internal::WireFormat::SkipField(
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -2939,10 +2287,13 @@ failure:
void EnumValue::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.EnumValue)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// string name = 1;
if (this->name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.EnumValue.name");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -2955,11 +2306,16 @@ void EnumValue::SerializeWithCachedSizes(
}
// repeated .google.protobuf.Option options = 3;
- for (unsigned int i = 0, n = this->options_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->options_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 3, this->options(i), output);
+ 3, this->options(static_cast<int>(i)), output);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ }
// @@protoc_insertion_point(serialize_end:google.protobuf.EnumValue)
}
@@ -2967,10 +2323,13 @@ void EnumValue::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.EnumValue)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// string name = 1;
if (this->name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.EnumValue.name");
target =
@@ -2984,12 +2343,17 @@ void EnumValue::SerializeWithCachedSizes(
}
// repeated .google.protobuf.Option options = 3;
- for (unsigned int i = 0, n = this->options_size(); i < n; i++) {
+ for (unsigned int i = 0,
+ n = static_cast<unsigned int>(this->options_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 3, this->options(i), false, target);
+ InternalWriteMessageToArray(
+ 3, this->options(static_cast<int>(i)), deterministic, target);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ }
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.EnumValue)
return target;
}
@@ -2998,14 +2362,19 @@ size_t EnumValue::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.EnumValue)
size_t total_size = 0;
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ total_size +=
+ ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ }
// repeated .google.protobuf.Option options = 3;
{
- unsigned int count = this->options_size();
+ unsigned int count = static_cast<unsigned int>(this->options_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->options(i));
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
+ this->options(static_cast<int>(i)));
}
}
@@ -3049,6 +2418,9 @@ void EnumValue::MergeFrom(const EnumValue& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.EnumValue)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
options_.MergeFrom(from.options_);
if (from.name().size() > 0) {
set_name(from.name());
@@ -3096,154 +2468,30 @@ void EnumValue::UnsafeArenaSwap(EnumValue* other) {
InternalSwap(other);
}
void EnumValue::InternalSwap(EnumValue* other) {
- options_.UnsafeArenaSwap(&other->options_);
+ using std::swap;
+ options_.InternalSwap(&other->options_);
name_.Swap(&other->name_);
- std::swap(number_, other->number_);
- std::swap(_cached_size_, other->_cached_size_);
+ swap(number_, other->number_);
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata EnumValue::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[3];
+ protobuf_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2ftype_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// EnumValue
-
-// string name = 1;
-void EnumValue::clear_name() {
- name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
-}
-const ::std::string& EnumValue::name() const {
- // @@protoc_insertion_point(field_get:google.protobuf.EnumValue.name)
- return name_.Get();
-}
-void EnumValue::set_name(const ::std::string& value) {
-
- name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set:google.protobuf.EnumValue.name)
-}
-void EnumValue::set_name(const char* value) {
-
- name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set_char:google.protobuf.EnumValue.name)
-}
-void EnumValue::set_name(const char* value,
- size_t size) {
-
- name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.EnumValue.name)
-}
-::std::string* EnumValue::mutable_name() {
-
- // @@protoc_insertion_point(field_mutable:google.protobuf.EnumValue.name)
- return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
-}
-::std::string* EnumValue::release_name() {
- // @@protoc_insertion_point(field_release:google.protobuf.EnumValue.name)
-
- return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
-}
-::std::string* EnumValue::unsafe_arena_release_name() {
- // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.EnumValue.name)
- GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
-
- return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
-}
-void EnumValue::set_allocated_name(::std::string* name) {
- if (name != NULL) {
-
- } else {
-
- }
- name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name,
- GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.EnumValue.name)
-}
-void EnumValue::unsafe_arena_set_allocated_name(
- ::std::string* name) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
- if (name != NULL) {
-
- } else {
-
- }
- name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- name, GetArenaNoVirtual());
- // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.EnumValue.name)
-}
-
-// int32 number = 2;
-void EnumValue::clear_number() {
- number_ = 0;
-}
-::google::protobuf::int32 EnumValue::number() const {
- // @@protoc_insertion_point(field_get:google.protobuf.EnumValue.number)
- return number_;
-}
-void EnumValue::set_number(::google::protobuf::int32 value) {
-
- number_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.EnumValue.number)
-}
-
-// repeated .google.protobuf.Option options = 3;
-int EnumValue::options_size() const {
- return options_.size();
-}
-void EnumValue::clear_options() {
- options_.Clear();
-}
-const ::google::protobuf::Option& EnumValue::options(int index) const {
- // @@protoc_insertion_point(field_get:google.protobuf.EnumValue.options)
- return options_.Get(index);
-}
-::google::protobuf::Option* EnumValue::mutable_options(int index) {
- // @@protoc_insertion_point(field_mutable:google.protobuf.EnumValue.options)
- return options_.Mutable(index);
-}
-::google::protobuf::Option* EnumValue::add_options() {
- // @@protoc_insertion_point(field_add:google.protobuf.EnumValue.options)
- return options_.Add();
-}
-::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >*
-EnumValue::mutable_options() {
- // @@protoc_insertion_point(field_mutable_list:google.protobuf.EnumValue.options)
- return &options_;
-}
-const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >&
-EnumValue::options() const {
- // @@protoc_insertion_point(field_list:google.protobuf.EnumValue.options)
- return options_;
-}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
+void Option::InitAsDefaultInstance() {
+ ::google::protobuf::_Option_default_instance_._instance.get_mutable()->value_ = const_cast< ::google::protobuf::Any*>(
+ ::google::protobuf::Any::internal_default_instance());
+}
void Option::_slow_mutable_value() {
value_ = ::google::protobuf::Arena::Create< ::google::protobuf::Any >(
GetArenaNoVirtual());
}
-::google::protobuf::Any* Option::_slow_release_value() {
- if (value_ == NULL) {
- return NULL;
- } else {
- ::google::protobuf::Any* temp = new ::google::protobuf::Any(*value_);
- value_ = NULL;
- return temp;
- }
-}
-::google::protobuf::Any* Option::unsafe_arena_release_value() {
- // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Option.value)
-
- ::google::protobuf::Any* temp = value_;
- value_ = NULL;
- return temp;
-}
void Option::unsafe_arena_set_allocated_value(
::google::protobuf::Any* value) {
if (GetArenaNoVirtual() == NULL) {
@@ -3257,6 +2505,12 @@ void Option::unsafe_arena_set_allocated_value(
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Option.value)
}
+void Option::clear_value() {
+ if (GetArenaNoVirtual() == NULL && value_ != NULL) {
+ delete value_;
+ }
+ value_ = NULL;
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Option::kNameFieldNumber;
const int Option::kValueFieldNumber;
@@ -3265,7 +2519,7 @@ const int Option::kValueFieldNumber;
Option::Option()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto();
+ ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOption();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Option)
@@ -3273,9 +2527,7 @@ Option::Option()
Option::Option(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
-#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
- protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto();
-#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOption();
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Option)
@@ -3310,15 +2562,9 @@ Option::~Option() {
}
void Option::SharedDtor() {
- ::google::protobuf::Arena* arena = GetArenaNoVirtual();
- if (arena != NULL) {
- return;
- }
-
- name_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena);
- if (this != internal_default_instance()) {
- delete value_;
- }
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
+ name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ if (this != internal_default_instance()) delete value_;
}
void Option::ArenaDtor(void* object) {
@@ -3333,12 +2579,12 @@ void Option::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* Option::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[4].descriptor;
+ ::protobuf_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2ftype_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const Option& Option::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto();
+ ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOption();
return *internal_default_instance();
}
@@ -3348,11 +2594,16 @@ Option* Option::New(::google::protobuf::Arena* arena) const {
void Option::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Option)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
if (GetArenaNoVirtual() == NULL && value_ != NULL) {
delete value_;
}
value_ = NULL;
+ _internal_metadata_.Clear();
}
bool Option::MergePartialFromCodedStream(
@@ -3367,11 +2618,12 @@ bool Option::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// string name = 1;
case 1: {
- if (tag == 10u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.protobuf.Option.name"));
} else {
@@ -3382,8 +2634,9 @@ bool Option::MergePartialFromCodedStream(
// .google.protobuf.Any value = 2;
case 2: {
- if (tag == 18u) {
- DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_value()));
} else {
goto handle_unusual;
@@ -3393,12 +2646,11 @@ bool Option::MergePartialFromCodedStream(
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
- DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
+ DO_(::google::protobuf::internal::WireFormat::SkipField(
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -3415,10 +2667,13 @@ failure:
void Option::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.Option)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// string name = 1;
if (this->name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Option.name");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -3431,6 +2686,10 @@ void Option::SerializeWithCachedSizes(
2, *this->value_, output);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ }
// @@protoc_insertion_point(serialize_end:google.protobuf.Option)
}
@@ -3438,10 +2697,13 @@ void Option::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Option)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// string name = 1;
if (this->name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->name().data(), this->name().length(),
+ this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Option.name");
target =
@@ -3452,10 +2714,14 @@ void Option::SerializeWithCachedSizes(
// .google.protobuf.Any value = 2;
if (this->has_value()) {
target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 2, *this->value_, false, target);
+ InternalWriteMessageToArray(
+ 2, *this->value_, deterministic, target);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ }
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Option)
return target;
}
@@ -3464,6 +2730,11 @@ size_t Option::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.Option)
size_t total_size = 0;
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ total_size +=
+ ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ }
// string name = 1;
if (this->name().size() > 0) {
total_size += 1 +
@@ -3474,7 +2745,7 @@ size_t Option::ByteSizeLong() const {
// .google.protobuf.Any value = 2;
if (this->has_value()) {
total_size += 1 +
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ ::google::protobuf::internal::WireFormatLite::MessageSize(
*this->value_);
}
@@ -3504,6 +2775,9 @@ void Option::MergeFrom(const Option& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Option)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
if (from.name().size() > 0) {
set_name(from.name());
}
@@ -3550,140 +2824,20 @@ void Option::UnsafeArenaSwap(Option* other) {
InternalSwap(other);
}
void Option::InternalSwap(Option* other) {
+ using std::swap;
name_.Swap(&other->name_);
- std::swap(value_, other->value_);
- std::swap(_cached_size_, other->_cached_size_);
+ swap(value_, other->value_);
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Option::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[4];
+ protobuf_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2ftype_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// Option
-
-// string name = 1;
-void Option::clear_name() {
- name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
-}
-const ::std::string& Option::name() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Option.name)
- return name_.Get();
-}
-void Option::set_name(const ::std::string& value) {
-
- name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set:google.protobuf.Option.name)
-}
-void Option::set_name(const char* value) {
-
- name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set_char:google.protobuf.Option.name)
-}
-void Option::set_name(const char* value,
- size_t size) {
-
- name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.Option.name)
-}
-::std::string* Option::mutable_name() {
-
- // @@protoc_insertion_point(field_mutable:google.protobuf.Option.name)
- return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
-}
-::std::string* Option::release_name() {
- // @@protoc_insertion_point(field_release:google.protobuf.Option.name)
-
- return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
-}
-::std::string* Option::unsafe_arena_release_name() {
- // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Option.name)
- GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
-
- return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
-}
-void Option::set_allocated_name(::std::string* name) {
- if (name != NULL) {
-
- } else {
-
- }
- name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name,
- GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.Option.name)
-}
-void Option::unsafe_arena_set_allocated_name(
- ::std::string* name) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
- if (name != NULL) {
-
- } else {
-
- }
- name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- name, GetArenaNoVirtual());
- // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Option.name)
-}
-
-// .google.protobuf.Any value = 2;
-bool Option::has_value() const {
- return this != internal_default_instance() && value_ != NULL;
-}
-void Option::clear_value() {
- if (GetArenaNoVirtual() == NULL && value_ != NULL) delete value_;
- value_ = NULL;
-}
-const ::google::protobuf::Any& Option::value() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Option.value)
- return value_ != NULL ? *value_
- : *::google::protobuf::Any::internal_default_instance();
-}
-::google::protobuf::Any* Option::mutable_value() {
-
- if (value_ == NULL) {
- _slow_mutable_value();
- }
- // @@protoc_insertion_point(field_mutable:google.protobuf.Option.value)
- return value_;
-}
-::google::protobuf::Any* Option::release_value() {
- // @@protoc_insertion_point(field_release:google.protobuf.Option.value)
-
- if (GetArenaNoVirtual() != NULL) {
- return _slow_release_value();
- } else {
- ::google::protobuf::Any* temp = value_;
- value_ = NULL;
- return temp;
- }
-}
- void Option::set_allocated_value(::google::protobuf::Any* value) {
- ::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
- if (message_arena == NULL) {
- delete value_;
- }
- if (value != NULL) {
- if (message_arena != NULL) {
- message_arena->Own(value);
- }
- }
- value_ = value;
- if (value) {
-
- } else {
-
- }
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.Option.value)
-}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
-
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/type.pb.h b/src/google/protobuf/type.pb.h
index 73fa35a3..85bd660f 100644
--- a/src/google/protobuf/type.pb.h
+++ b/src/google/protobuf/type.pb.h
@@ -8,19 +8,21 @@
#include <google/protobuf/stubs/common.h>
-#if GOOGLE_PROTOBUF_VERSION < 3001000
+#if GOOGLE_PROTOBUF_VERSION < 3004000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3001000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3004000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
+#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
+#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
@@ -31,11 +33,38 @@
#include <google/protobuf/any.pb.h>
#include <google/protobuf/source_context.pb.h>
// @@protoc_insertion_point(includes)
+
+namespace protobuf_google_2fprotobuf_2ftype_2eproto {
+// Internal implementation detail -- do not use these members.
+struct LIBPROTOBUF_EXPORT TableStruct {
+ static const ::google::protobuf::internal::ParseTableField entries[];
+ static const ::google::protobuf::internal::AuxillaryParseTableField aux[];
+ static const ::google::protobuf::internal::ParseTable schema[5];
+ static const ::google::protobuf::internal::FieldMetadata field_metadata[];
+ static const ::google::protobuf::internal::SerializationTable serialization_table[];
+ static const ::google::protobuf::uint32 offsets[];
+};
+void LIBPROTOBUF_EXPORT AddDescriptors();
+void LIBPROTOBUF_EXPORT InitDefaultsTypeImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsType();
+void LIBPROTOBUF_EXPORT InitDefaultsFieldImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsField();
+void LIBPROTOBUF_EXPORT InitDefaultsEnumImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsEnum();
+void LIBPROTOBUF_EXPORT InitDefaultsEnumValueImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsEnumValue();
+void LIBPROTOBUF_EXPORT InitDefaultsOptionImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsOption();
+inline void LIBPROTOBUF_EXPORT InitDefaults() {
+ InitDefaultsType();
+ InitDefaultsField();
+ InitDefaultsEnum();
+ InitDefaultsEnumValue();
+ InitDefaultsOption();
+}
+} // namespace protobuf_google_2fprotobuf_2ftype_2eproto
namespace google {
namespace protobuf {
-class Any;
-class AnyDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern AnyDefaultTypeInternal _Any_default_instance_;
class Enum;
class EnumDefaultTypeInternal;
LIBPROTOBUF_EXPORT extern EnumDefaultTypeInternal _Enum_default_instance_;
@@ -48,22 +77,14 @@ LIBPROTOBUF_EXPORT extern FieldDefaultTypeInternal _Field_default_instance_;
class Option;
class OptionDefaultTypeInternal;
LIBPROTOBUF_EXPORT extern OptionDefaultTypeInternal _Option_default_instance_;
-class SourceContext;
-class SourceContextDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern SourceContextDefaultTypeInternal _SourceContext_default_instance_;
class Type;
class TypeDefaultTypeInternal;
LIBPROTOBUF_EXPORT extern TypeDefaultTypeInternal _Type_default_instance_;
} // namespace protobuf
} // namespace google
-
namespace google {
namespace protobuf {
-// Internal implementation detail -- do not call these.
-void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto();
-void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto();
-
enum Field_Kind {
Field_Kind_TYPE_UNKNOWN = 0,
Field_Kind_TYPE_DOUBLE = 1,
@@ -159,7 +180,21 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ Type(Type&& from) noexcept
+ : Type() {
+ *this = ::std::move(from);
+ }
+ inline Type& operator=(Type&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
return GetArenaNoVirtual();
}
@@ -169,13 +204,19 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i
static const ::google::protobuf::Descriptor* descriptor();
static const Type& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const Type* internal_default_instance() {
return reinterpret_cast<const Type*>(
&_Type_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 0;
void UnsafeArenaSwap(Type* other);
void Swap(Type* other);
+ friend void swap(Type& a, Type& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -196,10 +237,6 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
@@ -226,20 +263,6 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i
// accessors -------------------------------------------------------
- // string name = 1;
- void clear_name();
- static const int kNameFieldNumber = 1;
- const ::std::string& name() const;
- void set_name(const ::std::string& value);
- void set_name(const char* value);
- void set_name(const char* value, size_t size);
- ::std::string* mutable_name();
- ::std::string* release_name();
- void set_allocated_name(::std::string* name);
- ::std::string* unsafe_arena_release_name();
- void unsafe_arena_set_allocated_name(
- ::std::string* name);
-
// repeated .google.protobuf.Field fields = 2;
int fields_size() const;
void clear_fields();
@@ -259,10 +282,16 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i
const ::std::string& oneofs(int index) const;
::std::string* mutable_oneofs(int index);
void set_oneofs(int index, const ::std::string& value);
+ #if LANG_CXX11
+ void set_oneofs(int index, ::std::string&& value);
+ #endif
void set_oneofs(int index, const char* value);
void set_oneofs(int index, const char* value, size_t size);
::std::string* add_oneofs();
void add_oneofs(const ::std::string& value);
+ #if LANG_CXX11
+ void add_oneofs(::std::string&& value);
+ #endif
void add_oneofs(const char* value);
void add_oneofs(const char* value, size_t size);
const ::google::protobuf::RepeatedPtrField< ::std::string>& oneofs() const;
@@ -280,21 +309,43 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >&
options() const;
+ // string name = 1;
+ void clear_name();
+ static const int kNameFieldNumber = 1;
+ const ::std::string& name() const;
+ void set_name(const ::std::string& value);
+ #if LANG_CXX11
+ void set_name(::std::string&& value);
+ #endif
+ void set_name(const char* value);
+ void set_name(const char* value, size_t size);
+ ::std::string* mutable_name();
+ ::std::string* release_name();
+ void set_allocated_name(::std::string* name);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ ::std::string* unsafe_arena_release_name();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_name(
+ ::std::string* name);
+
// .google.protobuf.SourceContext source_context = 5;
bool has_source_context() const;
void clear_source_context();
static const int kSourceContextFieldNumber = 5;
private:
void _slow_mutable_source_context();
- ::google::protobuf::SourceContext* _slow_release_source_context();
public:
const ::google::protobuf::SourceContext& source_context() const;
- ::google::protobuf::SourceContext* mutable_source_context();
::google::protobuf::SourceContext* release_source_context();
+ ::google::protobuf::SourceContext* mutable_source_context();
void set_allocated_source_context(::google::protobuf::SourceContext* source_context);
- ::google::protobuf::SourceContext* unsafe_arena_release_source_context();
void unsafe_arena_set_allocated_source_context(
::google::protobuf::SourceContext* source_context);
+ ::google::protobuf::SourceContext* unsafe_arena_release_source_context();
// .google.protobuf.Syntax syntax = 6;
void clear_syntax();
@@ -306,7 +357,7 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- friend class ::google::protobuf::Arena;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::Field > fields_;
@@ -316,11 +367,8 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i
::google::protobuf::SourceContext* source_context_;
int syntax_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2ftype_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2ftype_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2ftype_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsTypeImpl();
};
// -------------------------------------------------------------------
@@ -335,7 +383,21 @@ class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ Field(Field&& from) noexcept
+ : Field() {
+ *this = ::std::move(from);
+ }
+ inline Field& operator=(Field&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
return GetArenaNoVirtual();
}
@@ -345,13 +407,19 @@ class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_
static const ::google::protobuf::Descriptor* descriptor();
static const Field& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const Field* internal_default_instance() {
return reinterpret_cast<const Field*>(
&_Field_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 1;
void UnsafeArenaSwap(Field* other);
void Swap(Field* other);
+ friend void swap(Field& a, Field& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -372,10 +440,6 @@ class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
@@ -492,35 +556,38 @@ class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_
// accessors -------------------------------------------------------
- // .google.protobuf.Field.Kind kind = 1;
- void clear_kind();
- static const int kKindFieldNumber = 1;
- ::google::protobuf::Field_Kind kind() const;
- void set_kind(::google::protobuf::Field_Kind value);
-
- // .google.protobuf.Field.Cardinality cardinality = 2;
- void clear_cardinality();
- static const int kCardinalityFieldNumber = 2;
- ::google::protobuf::Field_Cardinality cardinality() const;
- void set_cardinality(::google::protobuf::Field_Cardinality value);
-
- // int32 number = 3;
- void clear_number();
- static const int kNumberFieldNumber = 3;
- ::google::protobuf::int32 number() const;
- void set_number(::google::protobuf::int32 value);
+ // repeated .google.protobuf.Option options = 9;
+ int options_size() const;
+ void clear_options();
+ static const int kOptionsFieldNumber = 9;
+ const ::google::protobuf::Option& options(int index) const;
+ ::google::protobuf::Option* mutable_options(int index);
+ ::google::protobuf::Option* add_options();
+ ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >*
+ mutable_options();
+ const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >&
+ options() const;
// string name = 4;
void clear_name();
static const int kNameFieldNumber = 4;
const ::std::string& name() const;
void set_name(const ::std::string& value);
+ #if LANG_CXX11
+ void set_name(::std::string&& value);
+ #endif
void set_name(const char* value);
void set_name(const char* value, size_t size);
::std::string* mutable_name();
::std::string* release_name();
void set_allocated_name(::std::string* name);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
::std::string* unsafe_arena_release_name();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
void unsafe_arena_set_allocated_name(
::std::string* name);
@@ -529,50 +596,44 @@ class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_
static const int kTypeUrlFieldNumber = 6;
const ::std::string& type_url() const;
void set_type_url(const ::std::string& value);
+ #if LANG_CXX11
+ void set_type_url(::std::string&& value);
+ #endif
void set_type_url(const char* value);
void set_type_url(const char* value, size_t size);
::std::string* mutable_type_url();
::std::string* release_type_url();
void set_allocated_type_url(::std::string* type_url);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
::std::string* unsafe_arena_release_type_url();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
void unsafe_arena_set_allocated_type_url(
::std::string* type_url);
- // int32 oneof_index = 7;
- void clear_oneof_index();
- static const int kOneofIndexFieldNumber = 7;
- ::google::protobuf::int32 oneof_index() const;
- void set_oneof_index(::google::protobuf::int32 value);
-
- // bool packed = 8;
- void clear_packed();
- static const int kPackedFieldNumber = 8;
- bool packed() const;
- void set_packed(bool value);
-
- // repeated .google.protobuf.Option options = 9;
- int options_size() const;
- void clear_options();
- static const int kOptionsFieldNumber = 9;
- const ::google::protobuf::Option& options(int index) const;
- ::google::protobuf::Option* mutable_options(int index);
- ::google::protobuf::Option* add_options();
- ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >*
- mutable_options();
- const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >&
- options() const;
-
// string json_name = 10;
void clear_json_name();
static const int kJsonNameFieldNumber = 10;
const ::std::string& json_name() const;
void set_json_name(const ::std::string& value);
+ #if LANG_CXX11
+ void set_json_name(::std::string&& value);
+ #endif
void set_json_name(const char* value);
void set_json_name(const char* value, size_t size);
::std::string* mutable_json_name();
::std::string* release_json_name();
void set_allocated_json_name(::std::string* json_name);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
::std::string* unsafe_arena_release_json_name();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
void unsafe_arena_set_allocated_json_name(
::std::string* json_name);
@@ -581,20 +642,59 @@ class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_
static const int kDefaultValueFieldNumber = 11;
const ::std::string& default_value() const;
void set_default_value(const ::std::string& value);
+ #if LANG_CXX11
+ void set_default_value(::std::string&& value);
+ #endif
void set_default_value(const char* value);
void set_default_value(const char* value, size_t size);
::std::string* mutable_default_value();
::std::string* release_default_value();
void set_allocated_default_value(::std::string* default_value);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
::std::string* unsafe_arena_release_default_value();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
void unsafe_arena_set_allocated_default_value(
::std::string* default_value);
+ // .google.protobuf.Field.Kind kind = 1;
+ void clear_kind();
+ static const int kKindFieldNumber = 1;
+ ::google::protobuf::Field_Kind kind() const;
+ void set_kind(::google::protobuf::Field_Kind value);
+
+ // .google.protobuf.Field.Cardinality cardinality = 2;
+ void clear_cardinality();
+ static const int kCardinalityFieldNumber = 2;
+ ::google::protobuf::Field_Cardinality cardinality() const;
+ void set_cardinality(::google::protobuf::Field_Cardinality value);
+
+ // int32 number = 3;
+ void clear_number();
+ static const int kNumberFieldNumber = 3;
+ ::google::protobuf::int32 number() const;
+ void set_number(::google::protobuf::int32 value);
+
+ // int32 oneof_index = 7;
+ void clear_oneof_index();
+ static const int kOneofIndexFieldNumber = 7;
+ ::google::protobuf::int32 oneof_index() const;
+ void set_oneof_index(::google::protobuf::int32 value);
+
+ // bool packed = 8;
+ void clear_packed();
+ static const int kPackedFieldNumber = 8;
+ bool packed() const;
+ void set_packed(bool value);
+
// @@protoc_insertion_point(class_scope:google.protobuf.Field)
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- friend class ::google::protobuf::Arena;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::Option > options_;
@@ -608,11 +708,8 @@ class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_
::google::protobuf::int32 oneof_index_;
bool packed_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2ftype_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2ftype_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2ftype_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsFieldImpl();
};
// -------------------------------------------------------------------
@@ -627,7 +724,21 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ Enum(Enum&& from) noexcept
+ : Enum() {
+ *this = ::std::move(from);
+ }
+ inline Enum& operator=(Enum&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
return GetArenaNoVirtual();
}
@@ -637,13 +748,19 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i
static const ::google::protobuf::Descriptor* descriptor();
static const Enum& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const Enum* internal_default_instance() {
return reinterpret_cast<const Enum*>(
&_Enum_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 2;
void UnsafeArenaSwap(Enum* other);
void Swap(Enum* other);
+ friend void swap(Enum& a, Enum& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -664,10 +781,6 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
@@ -694,20 +807,6 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i
// accessors -------------------------------------------------------
- // string name = 1;
- void clear_name();
- static const int kNameFieldNumber = 1;
- const ::std::string& name() const;
- void set_name(const ::std::string& value);
- void set_name(const char* value);
- void set_name(const char* value, size_t size);
- ::std::string* mutable_name();
- ::std::string* release_name();
- void set_allocated_name(::std::string* name);
- ::std::string* unsafe_arena_release_name();
- void unsafe_arena_set_allocated_name(
- ::std::string* name);
-
// repeated .google.protobuf.EnumValue enumvalue = 2;
int enumvalue_size() const;
void clear_enumvalue();
@@ -732,21 +831,43 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >&
options() const;
+ // string name = 1;
+ void clear_name();
+ static const int kNameFieldNumber = 1;
+ const ::std::string& name() const;
+ void set_name(const ::std::string& value);
+ #if LANG_CXX11
+ void set_name(::std::string&& value);
+ #endif
+ void set_name(const char* value);
+ void set_name(const char* value, size_t size);
+ ::std::string* mutable_name();
+ ::std::string* release_name();
+ void set_allocated_name(::std::string* name);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ ::std::string* unsafe_arena_release_name();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_name(
+ ::std::string* name);
+
// .google.protobuf.SourceContext source_context = 4;
bool has_source_context() const;
void clear_source_context();
static const int kSourceContextFieldNumber = 4;
private:
void _slow_mutable_source_context();
- ::google::protobuf::SourceContext* _slow_release_source_context();
public:
const ::google::protobuf::SourceContext& source_context() const;
- ::google::protobuf::SourceContext* mutable_source_context();
::google::protobuf::SourceContext* release_source_context();
+ ::google::protobuf::SourceContext* mutable_source_context();
void set_allocated_source_context(::google::protobuf::SourceContext* source_context);
- ::google::protobuf::SourceContext* unsafe_arena_release_source_context();
void unsafe_arena_set_allocated_source_context(
::google::protobuf::SourceContext* source_context);
+ ::google::protobuf::SourceContext* unsafe_arena_release_source_context();
// .google.protobuf.Syntax syntax = 5;
void clear_syntax();
@@ -758,7 +879,7 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- friend class ::google::protobuf::Arena;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumValue > enumvalue_;
@@ -767,11 +888,8 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i
::google::protobuf::SourceContext* source_context_;
int syntax_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2ftype_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2ftype_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2ftype_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsEnumImpl();
};
// -------------------------------------------------------------------
@@ -786,7 +904,21 @@ class LIBPROTOBUF_EXPORT EnumValue : public ::google::protobuf::Message /* @@pro
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ EnumValue(EnumValue&& from) noexcept
+ : EnumValue() {
+ *this = ::std::move(from);
+ }
+ inline EnumValue& operator=(EnumValue&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
return GetArenaNoVirtual();
}
@@ -796,13 +928,19 @@ class LIBPROTOBUF_EXPORT EnumValue : public ::google::protobuf::Message /* @@pro
static const ::google::protobuf::Descriptor* descriptor();
static const EnumValue& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const EnumValue* internal_default_instance() {
return reinterpret_cast<const EnumValue*>(
&_EnumValue_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 3;
void UnsafeArenaSwap(EnumValue* other);
void Swap(EnumValue* other);
+ friend void swap(EnumValue& a, EnumValue& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -823,10 +961,6 @@ class LIBPROTOBUF_EXPORT EnumValue : public ::google::protobuf::Message /* @@pro
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
@@ -853,17 +987,38 @@ class LIBPROTOBUF_EXPORT EnumValue : public ::google::protobuf::Message /* @@pro
// accessors -------------------------------------------------------
+ // repeated .google.protobuf.Option options = 3;
+ int options_size() const;
+ void clear_options();
+ static const int kOptionsFieldNumber = 3;
+ const ::google::protobuf::Option& options(int index) const;
+ ::google::protobuf::Option* mutable_options(int index);
+ ::google::protobuf::Option* add_options();
+ ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >*
+ mutable_options();
+ const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >&
+ options() const;
+
// string name = 1;
void clear_name();
static const int kNameFieldNumber = 1;
const ::std::string& name() const;
void set_name(const ::std::string& value);
+ #if LANG_CXX11
+ void set_name(::std::string&& value);
+ #endif
void set_name(const char* value);
void set_name(const char* value, size_t size);
::std::string* mutable_name();
::std::string* release_name();
void set_allocated_name(::std::string* name);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
::std::string* unsafe_arena_release_name();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
void unsafe_arena_set_allocated_name(
::std::string* name);
@@ -873,34 +1028,19 @@ class LIBPROTOBUF_EXPORT EnumValue : public ::google::protobuf::Message /* @@pro
::google::protobuf::int32 number() const;
void set_number(::google::protobuf::int32 value);
- // repeated .google.protobuf.Option options = 3;
- int options_size() const;
- void clear_options();
- static const int kOptionsFieldNumber = 3;
- const ::google::protobuf::Option& options(int index) const;
- ::google::protobuf::Option* mutable_options(int index);
- ::google::protobuf::Option* add_options();
- ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >*
- mutable_options();
- const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >&
- options() const;
-
// @@protoc_insertion_point(class_scope:google.protobuf.EnumValue)
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- friend class ::google::protobuf::Arena;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::Option > options_;
::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::int32 number_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2ftype_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2ftype_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2ftype_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsEnumValueImpl();
};
// -------------------------------------------------------------------
@@ -915,7 +1055,21 @@ class LIBPROTOBUF_EXPORT Option : public ::google::protobuf::Message /* @@protoc
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ Option(Option&& from) noexcept
+ : Option() {
+ *this = ::std::move(from);
+ }
+ inline Option& operator=(Option&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
return GetArenaNoVirtual();
}
@@ -925,13 +1079,19 @@ class LIBPROTOBUF_EXPORT Option : public ::google::protobuf::Message /* @@protoc
static const ::google::protobuf::Descriptor* descriptor();
static const Option& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const Option* internal_default_instance() {
return reinterpret_cast<const Option*>(
&_Option_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 4;
void UnsafeArenaSwap(Option* other);
void Swap(Option* other);
+ friend void swap(Option& a, Option& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -952,10 +1112,6 @@ class LIBPROTOBUF_EXPORT Option : public ::google::protobuf::Message /* @@protoc
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
@@ -987,12 +1143,21 @@ class LIBPROTOBUF_EXPORT Option : public ::google::protobuf::Message /* @@protoc
static const int kNameFieldNumber = 1;
const ::std::string& name() const;
void set_name(const ::std::string& value);
+ #if LANG_CXX11
+ void set_name(::std::string&& value);
+ #endif
void set_name(const char* value);
void set_name(const char* value, size_t size);
::std::string* mutable_name();
::std::string* release_name();
void set_allocated_name(::std::string* name);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
::std::string* unsafe_arena_release_name();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
void unsafe_arena_set_allocated_name(
::std::string* name);
@@ -1002,38 +1167,37 @@ class LIBPROTOBUF_EXPORT Option : public ::google::protobuf::Message /* @@protoc
static const int kValueFieldNumber = 2;
private:
void _slow_mutable_value();
- ::google::protobuf::Any* _slow_release_value();
public:
const ::google::protobuf::Any& value() const;
- ::google::protobuf::Any* mutable_value();
::google::protobuf::Any* release_value();
+ ::google::protobuf::Any* mutable_value();
void set_allocated_value(::google::protobuf::Any* value);
- ::google::protobuf::Any* unsafe_arena_release_value();
void unsafe_arena_set_allocated_value(
::google::protobuf::Any* value);
+ ::google::protobuf::Any* unsafe_arena_release_value();
// @@protoc_insertion_point(class_scope:google.protobuf.Option)
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- friend class ::google::protobuf::Arena;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::Any* value_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2ftype_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2ftype_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2ftype_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOptionImpl();
};
// ===================================================================
// ===================================================================
-#if !PROTOBUF_INLINE_NOT_IN_HEADERS
+#ifdef __GNUC__
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wstrict-aliasing"
+#endif // __GNUC__
// Type
// string name = 1;
@@ -1049,7 +1213,16 @@ inline void Type::set_name(const ::std::string& value) {
name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.Type.name)
}
+#if LANG_CXX11
+inline void Type::set_name(::std::string&& value) {
+
+ name_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.Type.name)
+}
+#endif
inline void Type::set_name(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
GetArenaNoVirtual());
@@ -1072,13 +1245,6 @@ inline ::std::string* Type::release_name() {
return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
-inline ::std::string* Type::unsafe_arena_release_name() {
- // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Type.name)
- GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
-
- return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
-}
inline void Type::set_allocated_name(::std::string* name) {
if (name != NULL) {
@@ -1089,6 +1255,13 @@ inline void Type::set_allocated_name(::std::string* name) {
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Type.name)
}
+inline ::std::string* Type::unsafe_arena_release_name() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Type.name)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+
+ return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
inline void Type::unsafe_arena_set_allocated_name(
::std::string* name) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
@@ -1151,7 +1324,14 @@ inline void Type::set_oneofs(int index, const ::std::string& value) {
// @@protoc_insertion_point(field_set:google.protobuf.Type.oneofs)
oneofs_.Mutable(index)->assign(value);
}
+#if LANG_CXX11
+inline void Type::set_oneofs(int index, ::std::string&& value) {
+ // @@protoc_insertion_point(field_set:google.protobuf.Type.oneofs)
+ oneofs_.Mutable(index)->assign(std::move(value));
+}
+#endif
inline void Type::set_oneofs(int index, const char* value) {
+ GOOGLE_DCHECK(value != NULL);
oneofs_.Mutable(index)->assign(value);
// @@protoc_insertion_point(field_set_char:google.protobuf.Type.oneofs)
}
@@ -1168,7 +1348,14 @@ inline void Type::add_oneofs(const ::std::string& value) {
oneofs_.Add()->assign(value);
// @@protoc_insertion_point(field_add:google.protobuf.Type.oneofs)
}
+#if LANG_CXX11
+inline void Type::add_oneofs(::std::string&& value) {
+ oneofs_.Add(std::move(value));
+ // @@protoc_insertion_point(field_add:google.protobuf.Type.oneofs)
+}
+#endif
inline void Type::add_oneofs(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
oneofs_.Add()->assign(value);
// @@protoc_insertion_point(field_add_char:google.protobuf.Type.oneofs)
}
@@ -1221,14 +1408,28 @@ Type::options() const {
inline bool Type::has_source_context() const {
return this != internal_default_instance() && source_context_ != NULL;
}
-inline void Type::clear_source_context() {
- if (GetArenaNoVirtual() == NULL && source_context_ != NULL) delete source_context_;
- source_context_ = NULL;
-}
inline const ::google::protobuf::SourceContext& Type::source_context() const {
+ const ::google::protobuf::SourceContext* p = source_context_;
// @@protoc_insertion_point(field_get:google.protobuf.Type.source_context)
- return source_context_ != NULL ? *source_context_
- : *::google::protobuf::SourceContext::internal_default_instance();
+ return p != NULL ? *p : *reinterpret_cast<const ::google::protobuf::SourceContext*>(
+ &::google::protobuf::_SourceContext_default_instance_);
+}
+inline ::google::protobuf::SourceContext* Type::release_source_context() {
+ // @@protoc_insertion_point(field_release:google.protobuf.Type.source_context)
+
+ ::google::protobuf::SourceContext* temp = source_context_;
+ if (GetArenaNoVirtual() != NULL) {
+ temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL);
+ }
+ source_context_ = NULL;
+ return temp;
+}
+inline ::google::protobuf::SourceContext* Type::unsafe_arena_release_source_context() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Type.source_context)
+
+ ::google::protobuf::SourceContext* temp = source_context_;
+ source_context_ = NULL;
+ return temp;
}
inline ::google::protobuf::SourceContext* Type::mutable_source_context() {
@@ -1238,33 +1439,22 @@ inline ::google::protobuf::SourceContext* Type::mutable_source_context() {
// @@protoc_insertion_point(field_mutable:google.protobuf.Type.source_context)
return source_context_;
}
-inline ::google::protobuf::SourceContext* Type::release_source_context() {
- // @@protoc_insertion_point(field_release:google.protobuf.Type.source_context)
-
- if (GetArenaNoVirtual() != NULL) {
- return _slow_release_source_context();
- } else {
- ::google::protobuf::SourceContext* temp = source_context_;
- source_context_ = NULL;
- return temp;
- }
-}
-inline void Type::set_allocated_source_context(::google::protobuf::SourceContext* source_context) {
+inline void Type::set_allocated_source_context(::google::protobuf::SourceContext* source_context) {
::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
if (message_arena == NULL) {
- delete source_context_;
+ delete reinterpret_cast< ::google::protobuf::MessageLite*>(source_context_);
}
- if (source_context != NULL) {
- if (message_arena != NULL) {
- message_arena->Own(source_context);
- }
- }
- source_context_ = source_context;
if (source_context) {
+ ::google::protobuf::Arena* submessage_arena = NULL;
+ if (message_arena != submessage_arena) {
+ source_context = ::google::protobuf::internal::GetOwnedMessage(
+ message_arena, source_context, submessage_arena);
+ }
} else {
}
+ source_context_ = source_context;
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Type.source_context)
}
@@ -1341,7 +1531,16 @@ inline void Field::set_name(const ::std::string& value) {
name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.Field.name)
}
+#if LANG_CXX11
+inline void Field::set_name(::std::string&& value) {
+
+ name_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.Field.name)
+}
+#endif
inline void Field::set_name(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
GetArenaNoVirtual());
@@ -1364,13 +1563,6 @@ inline ::std::string* Field::release_name() {
return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
-inline ::std::string* Field::unsafe_arena_release_name() {
- // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Field.name)
- GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
-
- return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
-}
inline void Field::set_allocated_name(::std::string* name) {
if (name != NULL) {
@@ -1381,6 +1573,13 @@ inline void Field::set_allocated_name(::std::string* name) {
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Field.name)
}
+inline ::std::string* Field::unsafe_arena_release_name() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Field.name)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+
+ return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
inline void Field::unsafe_arena_set_allocated_name(
::std::string* name) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
@@ -1407,7 +1606,16 @@ inline void Field::set_type_url(const ::std::string& value) {
type_url_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.Field.type_url)
}
+#if LANG_CXX11
+inline void Field::set_type_url(::std::string&& value) {
+
+ type_url_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.Field.type_url)
+}
+#endif
inline void Field::set_type_url(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
type_url_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
GetArenaNoVirtual());
@@ -1430,13 +1638,6 @@ inline ::std::string* Field::release_type_url() {
return type_url_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
-inline ::std::string* Field::unsafe_arena_release_type_url() {
- // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Field.type_url)
- GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
-
- return type_url_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
-}
inline void Field::set_allocated_type_url(::std::string* type_url) {
if (type_url != NULL) {
@@ -1447,6 +1648,13 @@ inline void Field::set_allocated_type_url(::std::string* type_url) {
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Field.type_url)
}
+inline ::std::string* Field::unsafe_arena_release_type_url() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Field.type_url)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+
+ return type_url_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
inline void Field::unsafe_arena_set_allocated_type_url(
::std::string* type_url) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
@@ -1531,7 +1739,16 @@ inline void Field::set_json_name(const ::std::string& value) {
json_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.Field.json_name)
}
+#if LANG_CXX11
+inline void Field::set_json_name(::std::string&& value) {
+
+ json_name_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.Field.json_name)
+}
+#endif
inline void Field::set_json_name(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
json_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
GetArenaNoVirtual());
@@ -1554,13 +1771,6 @@ inline ::std::string* Field::release_json_name() {
return json_name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
-inline ::std::string* Field::unsafe_arena_release_json_name() {
- // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Field.json_name)
- GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
-
- return json_name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
-}
inline void Field::set_allocated_json_name(::std::string* json_name) {
if (json_name != NULL) {
@@ -1571,6 +1781,13 @@ inline void Field::set_allocated_json_name(::std::string* json_name) {
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Field.json_name)
}
+inline ::std::string* Field::unsafe_arena_release_json_name() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Field.json_name)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+
+ return json_name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
inline void Field::unsafe_arena_set_allocated_json_name(
::std::string* json_name) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
@@ -1597,7 +1814,16 @@ inline void Field::set_default_value(const ::std::string& value) {
default_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.Field.default_value)
}
+#if LANG_CXX11
+inline void Field::set_default_value(::std::string&& value) {
+
+ default_value_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.Field.default_value)
+}
+#endif
inline void Field::set_default_value(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
default_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
GetArenaNoVirtual());
@@ -1620,13 +1846,6 @@ inline ::std::string* Field::release_default_value() {
return default_value_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
-inline ::std::string* Field::unsafe_arena_release_default_value() {
- // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Field.default_value)
- GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
-
- return default_value_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
-}
inline void Field::set_allocated_default_value(::std::string* default_value) {
if (default_value != NULL) {
@@ -1637,6 +1856,13 @@ inline void Field::set_allocated_default_value(::std::string* default_value) {
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Field.default_value)
}
+inline ::std::string* Field::unsafe_arena_release_default_value() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Field.default_value)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+
+ return default_value_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
inline void Field::unsafe_arena_set_allocated_default_value(
::std::string* default_value) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
@@ -1667,7 +1893,16 @@ inline void Enum::set_name(const ::std::string& value) {
name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.Enum.name)
}
+#if LANG_CXX11
+inline void Enum::set_name(::std::string&& value) {
+
+ name_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.Enum.name)
+}
+#endif
inline void Enum::set_name(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
GetArenaNoVirtual());
@@ -1690,13 +1925,6 @@ inline ::std::string* Enum::release_name() {
return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
-inline ::std::string* Enum::unsafe_arena_release_name() {
- // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Enum.name)
- GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
-
- return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
-}
inline void Enum::set_allocated_name(::std::string* name) {
if (name != NULL) {
@@ -1707,6 +1935,13 @@ inline void Enum::set_allocated_name(::std::string* name) {
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Enum.name)
}
+inline ::std::string* Enum::unsafe_arena_release_name() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Enum.name)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+
+ return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
inline void Enum::unsafe_arena_set_allocated_name(
::std::string* name) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
@@ -1784,14 +2019,28 @@ Enum::options() const {
inline bool Enum::has_source_context() const {
return this != internal_default_instance() && source_context_ != NULL;
}
-inline void Enum::clear_source_context() {
- if (GetArenaNoVirtual() == NULL && source_context_ != NULL) delete source_context_;
- source_context_ = NULL;
-}
inline const ::google::protobuf::SourceContext& Enum::source_context() const {
+ const ::google::protobuf::SourceContext* p = source_context_;
// @@protoc_insertion_point(field_get:google.protobuf.Enum.source_context)
- return source_context_ != NULL ? *source_context_
- : *::google::protobuf::SourceContext::internal_default_instance();
+ return p != NULL ? *p : *reinterpret_cast<const ::google::protobuf::SourceContext*>(
+ &::google::protobuf::_SourceContext_default_instance_);
+}
+inline ::google::protobuf::SourceContext* Enum::release_source_context() {
+ // @@protoc_insertion_point(field_release:google.protobuf.Enum.source_context)
+
+ ::google::protobuf::SourceContext* temp = source_context_;
+ if (GetArenaNoVirtual() != NULL) {
+ temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL);
+ }
+ source_context_ = NULL;
+ return temp;
+}
+inline ::google::protobuf::SourceContext* Enum::unsafe_arena_release_source_context() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Enum.source_context)
+
+ ::google::protobuf::SourceContext* temp = source_context_;
+ source_context_ = NULL;
+ return temp;
}
inline ::google::protobuf::SourceContext* Enum::mutable_source_context() {
@@ -1801,33 +2050,22 @@ inline ::google::protobuf::SourceContext* Enum::mutable_source_context() {
// @@protoc_insertion_point(field_mutable:google.protobuf.Enum.source_context)
return source_context_;
}
-inline ::google::protobuf::SourceContext* Enum::release_source_context() {
- // @@protoc_insertion_point(field_release:google.protobuf.Enum.source_context)
-
- if (GetArenaNoVirtual() != NULL) {
- return _slow_release_source_context();
- } else {
- ::google::protobuf::SourceContext* temp = source_context_;
- source_context_ = NULL;
- return temp;
- }
-}
-inline void Enum::set_allocated_source_context(::google::protobuf::SourceContext* source_context) {
+inline void Enum::set_allocated_source_context(::google::protobuf::SourceContext* source_context) {
::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
if (message_arena == NULL) {
- delete source_context_;
- }
- if (source_context != NULL) {
- if (message_arena != NULL) {
- message_arena->Own(source_context);
- }
+ delete reinterpret_cast< ::google::protobuf::MessageLite*>(source_context_);
}
- source_context_ = source_context;
if (source_context) {
+ ::google::protobuf::Arena* submessage_arena = NULL;
+ if (message_arena != submessage_arena) {
+ source_context = ::google::protobuf::internal::GetOwnedMessage(
+ message_arena, source_context, submessage_arena);
+ }
} else {
}
+ source_context_ = source_context;
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Enum.source_context)
}
@@ -1862,7 +2100,16 @@ inline void EnumValue::set_name(const ::std::string& value) {
name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.EnumValue.name)
}
+#if LANG_CXX11
+inline void EnumValue::set_name(::std::string&& value) {
+
+ name_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.EnumValue.name)
+}
+#endif
inline void EnumValue::set_name(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
GetArenaNoVirtual());
@@ -1885,13 +2132,6 @@ inline ::std::string* EnumValue::release_name() {
return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
-inline ::std::string* EnumValue::unsafe_arena_release_name() {
- // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.EnumValue.name)
- GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
-
- return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
-}
inline void EnumValue::set_allocated_name(::std::string* name) {
if (name != NULL) {
@@ -1902,6 +2142,13 @@ inline void EnumValue::set_allocated_name(::std::string* name) {
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.EnumValue.name)
}
+inline ::std::string* EnumValue::unsafe_arena_release_name() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.EnumValue.name)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+
+ return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
inline void EnumValue::unsafe_arena_set_allocated_name(
::std::string* name) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
@@ -1976,7 +2223,16 @@ inline void Option::set_name(const ::std::string& value) {
name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.Option.name)
}
+#if LANG_CXX11
+inline void Option::set_name(::std::string&& value) {
+
+ name_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.Option.name)
+}
+#endif
inline void Option::set_name(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
GetArenaNoVirtual());
@@ -1999,13 +2255,6 @@ inline ::std::string* Option::release_name() {
return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
-inline ::std::string* Option::unsafe_arena_release_name() {
- // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Option.name)
- GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
-
- return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
-}
inline void Option::set_allocated_name(::std::string* name) {
if (name != NULL) {
@@ -2016,6 +2265,13 @@ inline void Option::set_allocated_name(::std::string* name) {
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Option.name)
}
+inline ::std::string* Option::unsafe_arena_release_name() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Option.name)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+
+ return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
inline void Option::unsafe_arena_set_allocated_name(
::std::string* name) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
@@ -2033,14 +2289,28 @@ inline void Option::unsafe_arena_set_allocated_name(
inline bool Option::has_value() const {
return this != internal_default_instance() && value_ != NULL;
}
-inline void Option::clear_value() {
- if (GetArenaNoVirtual() == NULL && value_ != NULL) delete value_;
- value_ = NULL;
-}
inline const ::google::protobuf::Any& Option::value() const {
+ const ::google::protobuf::Any* p = value_;
// @@protoc_insertion_point(field_get:google.protobuf.Option.value)
- return value_ != NULL ? *value_
- : *::google::protobuf::Any::internal_default_instance();
+ return p != NULL ? *p : *reinterpret_cast<const ::google::protobuf::Any*>(
+ &::google::protobuf::_Any_default_instance_);
+}
+inline ::google::protobuf::Any* Option::release_value() {
+ // @@protoc_insertion_point(field_release:google.protobuf.Option.value)
+
+ ::google::protobuf::Any* temp = value_;
+ if (GetArenaNoVirtual() != NULL) {
+ temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL);
+ }
+ value_ = NULL;
+ return temp;
+}
+inline ::google::protobuf::Any* Option::unsafe_arena_release_value() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Option.value)
+
+ ::google::protobuf::Any* temp = value_;
+ value_ = NULL;
+ return temp;
}
inline ::google::protobuf::Any* Option::mutable_value() {
@@ -2050,37 +2320,28 @@ inline ::google::protobuf::Any* Option::mutable_value() {
// @@protoc_insertion_point(field_mutable:google.protobuf.Option.value)
return value_;
}
-inline ::google::protobuf::Any* Option::release_value() {
- // @@protoc_insertion_point(field_release:google.protobuf.Option.value)
-
- if (GetArenaNoVirtual() != NULL) {
- return _slow_release_value();
- } else {
- ::google::protobuf::Any* temp = value_;
- value_ = NULL;
- return temp;
- }
-}
-inline void Option::set_allocated_value(::google::protobuf::Any* value) {
+inline void Option::set_allocated_value(::google::protobuf::Any* value) {
::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
if (message_arena == NULL) {
- delete value_;
+ delete reinterpret_cast< ::google::protobuf::MessageLite*>(value_);
}
- if (value != NULL) {
- if (message_arena != NULL) {
- message_arena->Own(value);
- }
- }
- value_ = value;
if (value) {
+ ::google::protobuf::Arena* submessage_arena = NULL;
+ if (message_arena != submessage_arena) {
+ value = ::google::protobuf::internal::GetOwnedMessage(
+ message_arena, value, submessage_arena);
+ }
} else {
}
+ value_ = value;
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Option.value)
}
-#endif // !PROTOBUF_INLINE_NOT_IN_HEADERS
+#ifdef __GNUC__
+ #pragma GCC diagnostic pop
+#endif // __GNUC__
// -------------------------------------------------------------------
// -------------------------------------------------------------------
@@ -2092,11 +2353,9 @@ inline void Option::set_allocated_value(::google::protobuf::Any* value) {
// @@protoc_insertion_point(namespace_scope)
-
} // namespace protobuf
} // namespace google
-#ifndef SWIG
namespace google {
namespace protobuf {
@@ -2118,7 +2377,6 @@ inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::Syntax>() {
} // namespace protobuf
} // namespace google
-#endif // SWIG
// @@protoc_insertion_point(global_scope)
diff --git a/src/google/protobuf/type.proto b/src/google/protobuf/type.proto
index c1e696d6..624c15ee 100644
--- a/src/google/protobuf/type.proto
+++ b/src/google/protobuf/type.proto
@@ -166,9 +166,15 @@ message EnumValue {
// A protocol buffer option, which can be attached to a message, field,
// enumeration, etc.
message Option {
- // The option's name. For example, `"java_package"`.
+ // The option's name. For protobuf built-in options (options defined in
+ // descriptor.proto), this is the short name. For example, `"map_entry"`.
+ // For custom options, it should be the fully-qualified name. For example,
+ // `"google.api.http"`.
string name = 1;
- // The option's value. For example, `"com.google.protobuf"`.
+ // The option's value packed in an Any message. If the value is a primitive,
+ // the corresponding wrapper type defined in google/protobuf/wrappers.proto
+ // should be used. If the value is an enum, it should be stored as an int32
+ // value using the google.protobuf.Int32Value type.
Any value = 2;
}
diff --git a/src/google/protobuf/unittest.proto b/src/google/protobuf/unittest.proto
index 96289cc5..45a0edad 100644
--- a/src/google/protobuf/unittest.proto
+++ b/src/google/protobuf/unittest.proto
@@ -191,6 +191,10 @@ message TestDeprecatedFields {
optional int32 deprecated_int32 = 1 [deprecated=true];
}
+message TestDeprecatedMessage {
+ option deprecated = true;
+}
+
// Define these after TestAllTypes to make sure the compiler can handle
// that.
message ForeignMessage {
@@ -393,6 +397,12 @@ message TestRequiredForeign {
optional int32 dummy = 3;
}
+message TestRequiredMessage {
+ optional TestRequired optional_message = 1;
+ repeated TestRequired repeated_message = 2;
+ required TestRequired required_message = 3;
+}
+
// Test that we can use NestedMessage from outside TestAllTypes.
message TestForeignNested {
optional TestAllTypes.NestedMessage foreign_nested = 1;
@@ -429,7 +439,14 @@ message TestRecursiveMessage {
// Test that mutual recursion works.
message TestMutualRecursionA {
+ message SubMessage {
+ optional TestMutualRecursionB b = 1;
+ }
optional TestMutualRecursionB bb = 1;
+ optional group SubGroup = 2 {
+ optional SubMessage sub_message = 3; // Needed because of bug in javatest
+ optional TestAllTypes not_in_this_scc = 4;
+ }
}
message TestMutualRecursionB {
@@ -437,6 +454,15 @@ message TestMutualRecursionB {
optional int32 optional_int32 = 2;
}
+message TestIsInitialized {
+ message SubMessage {
+ optional group SubGroup = 1 {
+ required int32 i = 2;
+ }
+ }
+ optional SubMessage sub_message = 1;
+}
+
// Test that groups have disjoint field numbers from their siblings and
// parents. This is NOT possible in proto1; only google.protobuf. When attempting
// to compile with proto1, this will emit an error; so we only include it
diff --git a/src/google/protobuf/unittest_lazy_dependencies.proto b/src/google/protobuf/unittest_lazy_dependencies.proto
new file mode 100644
index 00000000..2f5efd2a
--- /dev/null
+++ b/src/google/protobuf/unittest_lazy_dependencies.proto
@@ -0,0 +1,75 @@
+// 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: trafacz@google.com (Todd Rafacz)
+// Based on original Protocol Buffers design by
+// Sanjay Ghemawat, Jeff Dean, and others.
+//
+// A proto file we will use for unit testing.
+
+syntax = "proto2";
+
+import "google/protobuf/unittest_lazy_dependencies_custom_option.proto";
+
+// 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;
+
+// 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.lazy_imports;
+
+// 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 = "UnittestLazyImportsProto";
+
+// The following are used to test that the proto file
+// with the definition of the following field types is
+// not built when this proto file is built. Then test
+// that calling message_type() etc will build the correct
+// descriptor lazily and return it.
+
+message ImportedMessage {
+ optional LazyMessage lazy_message = 1;
+}
+
+message MessageCustomOption {
+}
+
+message MessageCustomOption2 {
+ option (lazy_enum_option) = LAZY_ENUM_0;
+}
diff --git a/src/google/protobuf/unittest_lazy_dependencies_custom_option.proto b/src/google/protobuf/unittest_lazy_dependencies_custom_option.proto
new file mode 100644
index 00000000..22438257
--- /dev/null
+++ b/src/google/protobuf/unittest_lazy_dependencies_custom_option.proto
@@ -0,0 +1,67 @@
+// 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: trafacz@google.com (Todd Rafacz)
+// Based on original Protocol Buffers design by
+// Sanjay Ghemawat, Jeff Dean, and others.
+//
+// A proto file we will use for unit testing.
+
+syntax = "proto2";
+
+import "google/protobuf/unittest_lazy_dependencies_enum.proto";
+import "google/protobuf/descriptor.proto";
+
+// 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;
+
+// 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.lazy_imports;
+
+// 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 = "UnittestLazyImportsCustomOptionProto";
+
+message LazyMessage {
+ optional int32 a = 1;
+}
+
+extend google.protobuf.MessageOptions {
+ optional LazyEnum lazy_enum_option = 138596335 [default = LAZY_ENUM_1];
+}
diff --git a/src/google/protobuf/unittest_lazy_dependencies_enum.proto b/src/google/protobuf/unittest_lazy_dependencies_enum.proto
new file mode 100644
index 00000000..9be64d85
--- /dev/null
+++ b/src/google/protobuf/unittest_lazy_dependencies_enum.proto
@@ -0,0 +1,61 @@
+// 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: trafacz@google.com (Todd Rafacz)
+// Based on original Protocol Buffers design by
+// Sanjay Ghemawat, Jeff Dean, and others.
+//
+// A proto file we will use for unit testing.
+
+syntax = "proto2";
+
+// 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;
+
+// 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.lazy_imports;
+
+// 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 = "UnittestLazyImportsEnumProto";
+
+enum LazyEnum {
+ LAZY_ENUM_0 = 0;
+ LAZY_ENUM_1 = 1;
+}
diff --git a/src/google/protobuf/unittest_lite.proto b/src/google/protobuf/unittest_lite.proto
index c39ac6b0..9a15bdaa 100644
--- a/src/google/protobuf/unittest_lite.proto
+++ b/src/google/protobuf/unittest_lite.proto
@@ -439,3 +439,18 @@ message TestHugeFieldNumbersLite {
extend TestHugeFieldNumbersLite {
optional TestAllTypesLite test_all_types_lite = 536860000;
}
+
+message TestOneofParsingLite {
+ oneof oneof_field {
+ int32 oneof_int32 = 1;
+ TestAllTypesLite oneof_submessage = 2;
+ string oneof_string = 3;
+ bytes oneof_bytes = 4 [default = "default bytes"];
+ string oneof_string_cord = 5 [ctype = CORD, default = "default Cord"];
+ bytes oneof_bytes_cord = 6 [ctype = CORD];
+ string oneof_string_string_piece = 7 [ctype = STRING_PIECE];
+ bytes oneof_bytes_string_piece = 8
+ [ctype = STRING_PIECE, default = "default StringPiece"];
+ V2EnumLite oneof_enum = 9;
+ }
+}
diff --git a/src/google/protobuf/unittest_proto3.proto b/src/google/protobuf/unittest_proto3.proto
index f59d2178..84815d42 100644
--- a/src/google/protobuf/unittest_proto3.proto
+++ b/src/google/protobuf/unittest_proto3.proto
@@ -28,35 +28,13 @@
// (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";
+import "google/protobuf/unittest_import.proto";
+
+package proto3_unittest;
// This proto includes every type of field in both singular and repeated
// forms.
@@ -69,7 +47,7 @@ message TestAllTypes {
}
enum NestedEnum {
- NESTED_ENUM_UNSPECIFIED = 0;
+ ZERO = 0;
FOO = 1;
BAR = 2;
BAZ = 3;
@@ -77,33 +55,49 @@ message TestAllTypes {
}
// 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;
+ int32 optional_int32 = 1;
+ int64 optional_int64 = 2;
+ uint32 optional_uint32 = 3;
+ uint64 optional_uint64 = 4;
+ sint32 optional_sint32 = 5;
+ sint64 optional_sint64 = 6;
+ fixed32 optional_fixed32 = 7;
+ fixed64 optional_fixed64 = 8;
+ sfixed32 optional_sfixed32 = 9;
+ sfixed64 optional_sfixed64 = 10;
+ float optional_float = 11;
+ double optional_double = 12;
+ bool optional_bool = 13;
+ string optional_string = 14;
+ bytes optional_bytes = 15;
+
+ // Groups are not allowed in proto3.
+ // optional group OptionalGroup = 16 {
+ // optional int32 a = 17;
+ // }
+
+ NestedMessage optional_nested_message = 18;
+ ForeignMessage optional_foreign_message = 19;
+ protobuf_unittest_import.ImportMessage optional_import_message = 20;
+
+ NestedEnum optional_nested_enum = 21;
+ ForeignEnum optional_foreign_enum = 22;
+
+ // Omitted (compared to unittest.proto) because proto2 enums are not allowed
+ // inside proto2 messages.
+ //
+ // optional protobuf_unittest_import.ImportEnum optional_import_enum = 23;
+
+ string optional_string_piece = 24 [ctype=STRING_PIECE];
+ string optional_cord = 25 [ctype=CORD];
// Defined in unittest_import_public.proto
protobuf_unittest_import.PublicImportMessage
- single_public_import_message = 26;
+ optional_public_import_message = 26;
+
+ NestedMessage optional_lazy_message = 27 [lazy=true];
+ protobuf_unittest_import.ImportMessage optional_lazy_import_message = 115
+ [lazy = true];
// Repeated
repeated int32 repeated_int32 = 31;
@@ -122,18 +116,28 @@ message TestAllTypes {
repeated string repeated_string = 44;
repeated bytes repeated_bytes = 45;
+ // Groups are not allowed in proto3.
+ // repeated group RepeatedGroup = 46 {
+ // optional int32 a = 47;
+ // }
+
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
+ // Omitted (compared to unittest.proto) because proto2 enums are not allowed
+ // inside proto2 messages.
+ //
+ // repeated protobuf_unittest_import.ImportEnum repeated_import_enum = 53;
+
+ repeated string repeated_string_piece = 54 [ctype=STRING_PIECE];
+ repeated string repeated_cord = 55 [ctype=CORD];
+
+ repeated NestedMessage repeated_lazy_message = 57 [lazy=true];
+
oneof oneof_field {
uint32 oneof_uint32 = 111;
NestedMessage oneof_nested_message = 112;
@@ -142,173 +146,6 @@ message TestAllTypes {
}
}
-// 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 {
@@ -328,61 +165,44 @@ message TestPackedTypes {
repeated ForeignEnum packed_enum = 103 [packed = true];
}
-// A message with the same fields as TestPackedTypes, but without packing. Used
-// to test packed <-> unpacked wire compatibility.
+// Explicitly set packed to false
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];
+ repeated int32 repeated_int32 = 1 [packed = false];
+ repeated int64 repeated_int64 = 2 [packed = false];
+ repeated uint32 repeated_uint32 = 3 [packed = false];
+ repeated uint64 repeated_uint64 = 4 [packed = false];
+ repeated sint32 repeated_sint32 = 5 [packed = false];
+ repeated sint64 repeated_sint64 = 6 [packed = false];
+ repeated fixed32 repeated_fixed32 = 7 [packed = false];
+ repeated fixed64 repeated_fixed64 = 8 [packed = false];
+ repeated sfixed32 repeated_sfixed32 = 9 [packed = false];
+ repeated sfixed64 repeated_sfixed64 = 10 [packed = false];
+ repeated float repeated_float = 11 [packed = false];
+ repeated double repeated_double = 12 [packed = false];
+ repeated bool repeated_bool = 13 [packed = false];
+ repeated TestAllTypes.NestedEnum repeated_nested_enum = 14 [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;
+// This proto includes a recusively nested message.
+message NestedTestAllTypes {
+ NestedTestAllTypes child = 1;
+ TestAllTypes payload = 2;
}
-message TestCommentInjectionMessage {
- // */ <- This should not close the generated doc comment
- string a = 1;
+// Define these after TestAllTypes to make sure the compiler can handle
+// that.
+message ForeignMessage {
+ int32 c = 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);
+enum ForeignEnum {
+ FOREIGN_ZERO = 0;
+ FOREIGN_FOO = 4;
+ FOREIGN_BAR = 5;
+ FOREIGN_BAZ = 6;
}
-
-message BarRequest {}
-message BarResponse {}
+// TestEmptyMessage is used to test behavior of unknown fields.
+message TestEmptyMessage {
+}
diff --git a/src/google/protobuf/unittest_proto3_arena.proto b/src/google/protobuf/unittest_proto3_arena.proto
index b835a6ba..ea88ec90 100644
--- a/src/google/protobuf/unittest_proto3_arena.proto
+++ b/src/google/protobuf/unittest_proto3_arena.proto
@@ -96,6 +96,8 @@ message TestAllTypes {
optional_public_import_message = 26;
NestedMessage optional_lazy_message = 27 [lazy=true];
+ protobuf_unittest_import.ImportMessage optional_lazy_import_message = 115
+ [lazy = true];
// Repeated
repeated int32 repeated_int32 = 31;
@@ -185,6 +187,7 @@ message TestUnpackedTypes {
message NestedTestAllTypes {
NestedTestAllTypes child = 1;
TestAllTypes payload = 2;
+ repeated NestedTestAllTypes repeated_child = 3;
}
// Define these after TestAllTypes to make sure the compiler can handle
@@ -203,4 +206,3 @@ enum ForeignEnum {
// TestEmptyMessage is used to test behavior of unknown fields.
message TestEmptyMessage {
}
-
diff --git a/src/google/protobuf/unknown_field_set.cc b/src/google/protobuf/unknown_field_set.cc
index 9472c4fa..0ada85e5 100644
--- a/src/google/protobuf/unknown_field_set.cc
+++ b/src/google/protobuf/unknown_field_set.cc
@@ -123,21 +123,21 @@ void UnknownFieldSet::MergeToInternalMetdata(
metadata->mutable_unknown_fields()->MergeFrom(other);
}
-int UnknownFieldSet::SpaceUsedExcludingSelf() const {
+size_t UnknownFieldSet::SpaceUsedExcludingSelfLong() const {
if (fields_ == NULL) return 0;
- int total_size = sizeof(*fields_) + sizeof(UnknownField) * fields_->size();
+ size_t total_size = sizeof(*fields_) + sizeof(UnknownField) * fields_->size();
for (int i = 0; i < fields_->size(); i++) {
const UnknownField& field = (*fields_)[i];
switch (field.type()) {
case UnknownField::TYPE_LENGTH_DELIMITED:
- total_size += sizeof(*field.length_delimited_.string_value_) +
- internal::StringSpaceUsedExcludingSelf(
- *field.length_delimited_.string_value_);
+ total_size += sizeof(*field.data_.length_delimited_.string_value_) +
+ internal::StringSpaceUsedExcludingSelfLong(
+ *field.data_.length_delimited_.string_value_);
break;
case UnknownField::TYPE_GROUP:
- total_size += field.group_->SpaceUsed();
+ total_size += field.data_.group_->SpaceUsedLong();
break;
default:
break;
@@ -146,7 +146,7 @@ int UnknownFieldSet::SpaceUsedExcludingSelf() const {
return total_size;
}
-int UnknownFieldSet::SpaceUsed() const {
+size_t UnknownFieldSet::SpaceUsedLong() const {
return sizeof(*this) + SpaceUsedExcludingSelf();
}
@@ -154,7 +154,7 @@ void UnknownFieldSet::AddVarint(int number, uint64 value) {
UnknownField field;
field.number_ = number;
field.SetType(UnknownField::TYPE_VARINT);
- field.varint_ = value;
+ field.data_.varint_ = value;
if (fields_ == NULL) fields_ = new std::vector<UnknownField>();
fields_->push_back(field);
}
@@ -163,7 +163,7 @@ void UnknownFieldSet::AddFixed32(int number, uint32 value) {
UnknownField field;
field.number_ = number;
field.SetType(UnknownField::TYPE_FIXED32);
- field.fixed32_ = value;
+ field.data_.fixed32_ = value;
if (fields_ == NULL) fields_ = new std::vector<UnknownField>();
fields_->push_back(field);
}
@@ -172,7 +172,7 @@ void UnknownFieldSet::AddFixed64(int number, uint64 value) {
UnknownField field;
field.number_ = number;
field.SetType(UnknownField::TYPE_FIXED64);
- field.fixed64_ = value;
+ field.data_.fixed64_ = value;
if (fields_ == NULL) fields_ = new std::vector<UnknownField>();
fields_->push_back(field);
}
@@ -181,10 +181,10 @@ string* UnknownFieldSet::AddLengthDelimited(int number) {
UnknownField field;
field.number_ = number;
field.SetType(UnknownField::TYPE_LENGTH_DELIMITED);
- field.length_delimited_.string_value_ = new string;
+ field.data_.length_delimited_.string_value_ = new string;
if (fields_ == NULL) fields_ = new std::vector<UnknownField>();
fields_->push_back(field);
- return field.length_delimited_.string_value_;
+ return field.data_.length_delimited_.string_value_;
}
@@ -192,10 +192,10 @@ UnknownFieldSet* UnknownFieldSet::AddGroup(int number) {
UnknownField field;
field.number_ = number;
field.SetType(UnknownField::TYPE_GROUP);
- field.group_ = new UnknownFieldSet;
+ field.data_.group_ = new UnknownFieldSet;
if (fields_ == NULL) fields_ = new std::vector<UnknownField>();
fields_->push_back(field);
- return field.group_;
+ return field.data_.group_;
}
void UnknownFieldSet::AddField(const UnknownField& field) {
@@ -276,10 +276,10 @@ bool UnknownFieldSet::ParseFromArray(const void* data, int size) {
void UnknownField::Delete() {
switch (type()) {
case UnknownField::TYPE_LENGTH_DELIMITED:
- delete length_delimited_.string_value_;
+ delete data_.length_delimited_.string_value_;
break;
case UnknownField::TYPE_GROUP:
- delete group_;
+ delete data_.group_;
break;
default:
break;
@@ -291,10 +291,10 @@ void UnknownField::Delete() {
void UnknownField::Reset() {
switch (type()) {
case UnknownField::TYPE_LENGTH_DELIMITED:
- length_delimited_.string_value_ = NULL;
+ data_.length_delimited_.string_value_ = NULL;
break;
case UnknownField::TYPE_GROUP: {
- group_ = NULL;
+ data_.group_ = NULL;
break;
}
default:
@@ -305,13 +305,13 @@ void UnknownField::Reset() {
void UnknownField::DeepCopy(const UnknownField& other) {
switch (type()) {
case UnknownField::TYPE_LENGTH_DELIMITED:
- length_delimited_.string_value_ = new string(
- *length_delimited_.string_value_);
+ data_.length_delimited_.string_value_ = new string(
+ *data_.length_delimited_.string_value_);
break;
case UnknownField::TYPE_GROUP: {
UnknownFieldSet* group = new UnknownFieldSet();
- group->InternalMergeFrom(*group_);
- group_ = group;
+ group->InternalMergeFrom(*data_.group_);
+ data_.group_ = group;
break;
}
default:
@@ -323,14 +323,14 @@ void UnknownField::DeepCopy(const UnknownField& other) {
void UnknownField::SerializeLengthDelimitedNoTag(
io::CodedOutputStream* output) const {
GOOGLE_DCHECK_EQ(TYPE_LENGTH_DELIMITED, type());
- const string& data = *length_delimited_.string_value_;
+ const string& data = *data_.length_delimited_.string_value_;
output->WriteVarint32(data.size());
output->WriteRawMaybeAliased(data.data(), data.size());
}
uint8* UnknownField::SerializeLengthDelimitedNoTagToArray(uint8* target) const {
GOOGLE_DCHECK_EQ(TYPE_LENGTH_DELIMITED, type());
- const string& data = *length_delimited_.string_value_;
+ const string& data = *data_.length_delimited_.string_value_;
target = io::CodedOutputStream::WriteVarint32ToArray(data.size(), target);
target = io::CodedOutputStream::WriteStringToArray(data, target);
return target;
diff --git a/src/google/protobuf/unknown_field_set.h b/src/google/protobuf/unknown_field_set.h
index c2ad8918..619855ed 100644
--- a/src/google/protobuf/unknown_field_set.h
+++ b/src/google/protobuf/unknown_field_set.h
@@ -43,6 +43,7 @@
#include <vector>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/logging.h>
+#include <google/protobuf/message_lite.h>
namespace google {
namespace protobuf {
@@ -106,10 +107,18 @@ class LIBPROTOBUF_EXPORT UnknownFieldSet {
// Computes (an estimate of) the total number of bytes currently used for
// storing the unknown fields in memory. Does NOT include
// sizeof(*this) in the calculation.
- int SpaceUsedExcludingSelf() const;
+ size_t SpaceUsedExcludingSelfLong() const;
+
+ int SpaceUsedExcludingSelf() const {
+ return internal::ToIntSize(SpaceUsedExcludingSelfLong());
+ }
// Version of SpaceUsed() including sizeof(*this).
- int SpaceUsed() const;
+ size_t SpaceUsedLong() const;
+
+ int SpaceUsed() const {
+ return internal::ToIntSize(SpaceUsedLong());
+ }
// Returns the number of fields present in the UnknownFieldSet.
inline int field_count() const;
@@ -214,8 +223,6 @@ class LIBPROTOBUF_EXPORT UnknownField {
inline size_t GetLengthDelimitedSize() const;
- private:
- friend class UnknownFieldSet;
// If this UnknownField contains a pointer, delete it.
void Delete();
@@ -243,7 +250,7 @@ class LIBPROTOBUF_EXPORT UnknownField {
uint64 fixed64_;
mutable union LengthDelimited length_delimited_;
UnknownFieldSet* group_;
- };
+ } data_;
};
// ===================================================================
@@ -275,10 +282,10 @@ inline int UnknownFieldSet::field_count() const {
}
inline const UnknownField& UnknownFieldSet::field(int index) const {
GOOGLE_DCHECK(fields_ != NULL);
- return (*fields_)[index];
+ return (*fields_)[static_cast<size_t>(index)];
}
inline UnknownField* UnknownFieldSet::mutable_field(int index) {
- return &(*fields_)[index];
+ return &(*fields_)[static_cast<size_t>(index)];
}
inline void UnknownFieldSet::AddLengthDelimited(
@@ -287,60 +294,62 @@ inline void UnknownFieldSet::AddLengthDelimited(
}
-inline int UnknownField::number() const { return number_; }
+
+
+inline int UnknownField::number() const { return static_cast<int>(number_); }
inline UnknownField::Type UnknownField::type() const {
return static_cast<Type>(type_);
}
inline uint64 UnknownField::varint() const {
assert(type() == TYPE_VARINT);
- return varint_;
+ return data_.varint_;
}
inline uint32 UnknownField::fixed32() const {
assert(type() == TYPE_FIXED32);
- return fixed32_;
+ return data_.fixed32_;
}
inline uint64 UnknownField::fixed64() const {
assert(type() == TYPE_FIXED64);
- return fixed64_;
+ return data_.fixed64_;
}
inline const string& UnknownField::length_delimited() const {
assert(type() == TYPE_LENGTH_DELIMITED);
- return *length_delimited_.string_value_;
+ return *data_.length_delimited_.string_value_;
}
inline const UnknownFieldSet& UnknownField::group() const {
assert(type() == TYPE_GROUP);
- return *group_;
+ return *data_.group_;
}
inline void UnknownField::set_varint(uint64 value) {
assert(type() == TYPE_VARINT);
- varint_ = value;
+ data_.varint_ = value;
}
inline void UnknownField::set_fixed32(uint32 value) {
assert(type() == TYPE_FIXED32);
- fixed32_ = value;
+ data_.fixed32_ = value;
}
inline void UnknownField::set_fixed64(uint64 value) {
assert(type() == TYPE_FIXED64);
- fixed64_ = value;
+ data_.fixed64_ = value;
}
inline void UnknownField::set_length_delimited(const string& value) {
assert(type() == TYPE_LENGTH_DELIMITED);
- length_delimited_.string_value_->assign(value);
+ data_.length_delimited_.string_value_->assign(value);
}
inline string* UnknownField::mutable_length_delimited() {
assert(type() == TYPE_LENGTH_DELIMITED);
- return length_delimited_.string_value_;
+ return data_.length_delimited_.string_value_;
}
inline UnknownFieldSet* UnknownField::mutable_group() {
assert(type() == TYPE_GROUP);
- return group_;
+ return data_.group_;
}
inline size_t UnknownField::GetLengthDelimitedSize() const {
GOOGLE_DCHECK_EQ(TYPE_LENGTH_DELIMITED, type());
- return length_delimited_.string_value_->size();
+ return data_.length_delimited_.string_value_->size();
}
inline void UnknownField::SetType(Type type) {
diff --git a/src/google/protobuf/util/delimited_message_util.cc b/src/google/protobuf/util/delimited_message_util.cc
new file mode 100644
index 00000000..16378782
--- /dev/null
+++ b/src/google/protobuf/util/delimited_message_util.cc
@@ -0,0 +1,79 @@
+// Adapted from the patch of kenton@google.com (Kenton Varda)
+// See https://github.com/google/protobuf/pull/710 for details.
+
+#include <google/protobuf/util/delimited_message_util.h>
+
+namespace google {
+namespace protobuf {
+namespace util {
+
+bool SerializeDelimitedToFileDescriptor(const MessageLite& message, int file_descriptor) {
+ io::FileOutputStream output(file_descriptor);
+ return SerializeDelimitedToZeroCopyStream(message, &output);
+}
+
+bool SerializeDelimitedToOstream(const MessageLite& message, ostream* output) {
+ {
+ io::OstreamOutputStream zero_copy_output(output);
+ if (!SerializeDelimitedToZeroCopyStream(message, &zero_copy_output)) return false;
+ }
+ return output->good();
+}
+
+bool ParseDelimitedFromZeroCopyStream(MessageLite* message, io::ZeroCopyInputStream* input, bool* clean_eof) {
+ google::protobuf::io::CodedInputStream coded_input(input);
+ return ParseDelimitedFromCodedStream(message, &coded_input, clean_eof);
+}
+
+bool ParseDelimitedFromCodedStream(MessageLite* message, io::CodedInputStream* input, bool* clean_eof) {
+ if (clean_eof != NULL) *clean_eof = false;
+ int start = input->CurrentPosition();
+
+ // Read the size.
+ uint32 size;
+ if (!input->ReadVarint32(&size)) {
+ if (clean_eof != NULL) *clean_eof = input->CurrentPosition() == start;
+ return false;
+ }
+
+ // Tell the stream not to read beyond that size.
+ google::protobuf::io::CodedInputStream::Limit limit = input->PushLimit(size);
+
+ // Parse the message.
+ if (!message->MergeFromCodedStream(input)) return false;
+ if (!input->ConsumedEntireMessage()) return false;
+
+ // Release the limit.
+ input->PopLimit(limit);
+
+ return true;
+}
+
+bool SerializeDelimitedToZeroCopyStream(const MessageLite& message, io::ZeroCopyOutputStream* output) {
+ google::protobuf::io::CodedOutputStream coded_output(output);
+ return SerializeDelimitedToCodedStream(message, &coded_output);
+}
+
+bool SerializeDelimitedToCodedStream(const MessageLite& message, io::CodedOutputStream* output) {
+ // Write the size.
+ int size = message.ByteSize();
+ output->WriteVarint32(size);
+
+ // Write the content.
+ uint8* buffer = output->GetDirectBufferForNBytesAndAdvance(size);
+ if (buffer != NULL) {
+ // Optimization: The message fits in one buffer, so use the faster
+ // direct-to-array serialization path.
+ message.SerializeWithCachedSizesToArray(buffer);
+ } else {
+ // Slightly-slower path when the message is multiple buffers.
+ message.SerializeWithCachedSizes(output);
+ if (output->HadError()) return false;
+ }
+
+ return true;
+}
+
+} // namespace util
+} // namespace protobuf
+} // namespace google
diff --git a/src/google/protobuf/util/delimited_message_util.h b/src/google/protobuf/util/delimited_message_util.h
new file mode 100644
index 00000000..302d4781
--- /dev/null
+++ b/src/google/protobuf/util/delimited_message_util.h
@@ -0,0 +1,66 @@
+// Adapted from the patch of kenton@google.com (Kenton Varda)
+// See https://github.com/google/protobuf/pull/710 for details.
+
+#ifndef GOOGLE_PROTOBUF_UTIL_DELIMITED_MESSAGE_UTIL_H__
+#define GOOGLE_PROTOBUF_UTIL_DELIMITED_MESSAGE_UTIL_H__
+
+#include <ostream>
+
+#include <google/protobuf/message_lite.h>
+#include <google/protobuf/io/coded_stream.h>
+#include <google/protobuf/io/zero_copy_stream_impl.h>
+
+namespace google {
+namespace protobuf {
+namespace util {
+
+// Write a single size-delimited message from the given stream. Delimited
+// format allows a single file or stream to contain multiple messages,
+// whereas normally writing multiple non-delimited messages to the same
+// stream would cause them to be merged. A delimited message is a varint
+// encoding the message size followed by a message of exactly that size.
+//
+// Note that if you want to *read* a delimited message from a file descriptor
+// or istream, you will need to construct an io::FileInputStream or
+// io::OstreamInputStream (implementations of io::ZeroCopyStream) and use the
+// utility function ParseDelimitedFromZeroCopyStream(). You must then
+// continue to use the same ZeroCopyInputStream to read all further data from
+// the stream until EOF. This is because these ZeroCopyInputStream
+// implementations are buffered: they read a big chunk of data at a time,
+// then parse it. As a result, they may read past the end of the delimited
+// message. There is no way for them to push the extra data back into the
+// underlying source, so instead you must keep using the same stream object.
+bool LIBPROTOBUF_EXPORT SerializeDelimitedToFileDescriptor(const MessageLite& message, int file_descriptor);
+
+bool LIBPROTOBUF_EXPORT SerializeDelimitedToOstream(const MessageLite& message, ostream* output);
+
+// Read a single size-delimited message from the given stream. Delimited
+// format allows a single file or stream to contain multiple messages,
+// whereas normally parsing consumes the entire input. A delimited message
+// is a varint encoding the message size followed by a message of exactly
+// that size.
+//
+// If |clean_eof| is not NULL, then it will be set to indicate whether the
+// stream ended cleanly. That is, if the stream ends without this method
+// having read any data at all from it, then *clean_eof will be set true,
+// otherwise it will be set false. Note that these methods return false
+// on EOF, but they also return false on other errors, so |clean_eof| is
+// needed to distinguish a clean end from errors.
+bool LIBPROTOBUF_EXPORT ParseDelimitedFromZeroCopyStream(MessageLite* message, io::ZeroCopyInputStream* input, bool* clean_eof);
+
+bool LIBPROTOBUF_EXPORT ParseDelimitedFromCodedStream(MessageLite* message, io::CodedInputStream* input, bool* clean_eof);
+
+// Write a single size-delimited message from the given stream. Delimited
+// format allows a single file or stream to contain multiple messages,
+// whereas normally writing multiple non-delimited messages to the same
+// stream would cause them to be merged. A delimited message is a varint
+// encoding the message size followed by a message of exactly that size.
+bool LIBPROTOBUF_EXPORT SerializeDelimitedToZeroCopyStream(const MessageLite& message, io::ZeroCopyOutputStream* output);
+
+bool LIBPROTOBUF_EXPORT SerializeDelimitedToCodedStream(const MessageLite& message, io::CodedOutputStream* output);
+
+} // namespace util
+} // namespace protobuf
+} // namespace google
+
+#endif // GOOGLE_PROTOBUF_UTIL_DELIMITED_MESSAGE_UTIL_H__
diff --git a/src/google/protobuf/util/delimited_message_util_test.cc b/src/google/protobuf/util/delimited_message_util_test.cc
new file mode 100644
index 00000000..157a8411
--- /dev/null
+++ b/src/google/protobuf/util/delimited_message_util_test.cc
@@ -0,0 +1,57 @@
+// Adapted from the patch of kenton@google.com (Kenton Varda)
+// See https://github.com/google/protobuf/pull/710 for details.
+
+#include <google/protobuf/util/delimited_message_util.h>
+
+#include <sstream>
+
+#include <google/protobuf/test_util.h>
+#include <google/protobuf/unittest.pb.h>
+#include <google/protobuf/testing/googletest.h>
+#include <gtest/gtest.h>
+
+namespace google {
+namespace protobuf {
+namespace util {
+
+TEST(DelimitedMessageUtilTest, DelimitedMessages) {
+ std::stringstream stream;
+
+ {
+ protobuf_unittest::TestAllTypes message1;
+ TestUtil::SetAllFields(&message1);
+ EXPECT_TRUE(SerializeDelimitedToOstream(message1, &stream));
+
+ protobuf_unittest::TestPackedTypes message2;
+ TestUtil::SetPackedFields(&message2);
+ EXPECT_TRUE(SerializeDelimitedToOstream(message2, &stream));
+ }
+
+ {
+ bool clean_eof;
+ io::IstreamInputStream zstream(&stream);
+
+ protobuf_unittest::TestAllTypes message1;
+ clean_eof = true;
+ EXPECT_TRUE(ParseDelimitedFromZeroCopyStream(&message1,
+ &zstream, &clean_eof));
+ EXPECT_FALSE(clean_eof);
+ TestUtil::ExpectAllFieldsSet(message1);
+
+ protobuf_unittest::TestPackedTypes message2;
+ clean_eof = true;
+ EXPECT_TRUE(ParseDelimitedFromZeroCopyStream(&message2,
+ &zstream, &clean_eof));
+ EXPECT_FALSE(clean_eof);
+ TestUtil::ExpectPackedFieldsSet(message2);
+
+ clean_eof = false;
+ EXPECT_FALSE(ParseDelimitedFromZeroCopyStream(&message2,
+ &zstream, &clean_eof));
+ EXPECT_TRUE(clean_eof);
+ }
+}
+
+} // namespace util
+} // namespace protobuf
+} // namespace google
diff --git a/src/google/protobuf/util/field_comparator.h b/src/google/protobuf/util/field_comparator.h
index ad560ebc..26a7ba4d 100644
--- a/src/google/protobuf/util/field_comparator.h
+++ b/src/google/protobuf/util/field_comparator.h
@@ -237,7 +237,7 @@ class LIBPROTOBUF_EXPORT DefaultFieldComparator : public FieldComparator {
// True iff default_tolerance_ has been explicitly set.
//
- // If false, then the default tolerance for flaots and doubles is that which
+ // If false, then the default tolerance for floats and doubles is that which
// is used by MathUtil::AlmostEquals().
bool has_default_tolerance_;
diff --git a/src/google/protobuf/util/field_mask_util.cc b/src/google/protobuf/util/field_mask_util.cc
index 07550e6d..4d0d3a46 100644
--- a/src/google/protobuf/util/field_mask_util.cc
+++ b/src/google/protobuf/util/field_mask_util.cc
@@ -192,6 +192,13 @@ class FieldMaskTree {
// children removed because the path matches all the node's children.
void AddPath(const string& path);
+ // Remove a path from the tree.
+ // If the path is a sub-path of an existing field path in the tree, it means
+ // we need remove the existing fied path and add all sub-paths except
+ // specified path. If the path matches an existing node in the tree, this node
+ // will be moved.
+ void RemovePath(const string& path, const Descriptor* descriptor);
+
// Calculate the intersection part of a field path with this tree and add
// the intersection field path into out.
void IntersectPath(const string& path, FieldMaskTree* out);
@@ -207,6 +214,18 @@ class FieldMaskTree {
MergeMessage(&root_, source, options, destination);
}
+ // Add required field path of the message to this tree based on current tree
+ // structure. If a message is present in the tree, add the path of its
+ // required field to the tree. This is to make sure that after trimming a
+ // message with required fields are set, check IsInitialized() will not fail.
+ void AddRequiredFieldPath(const Descriptor* descriptor) {
+ // Do nothing if the tree is empty.
+ if (root_.children.empty()) {
+ return;
+ }
+ AddRequiredFieldPath(&root_, descriptor);
+ }
+
// Trims all fields not specified by this tree from the given message.
void TrimMessage(Message* message) {
// Do nothing if the tree is empty.
@@ -249,6 +268,12 @@ class FieldMaskTree {
const FieldMaskUtil::MergeOptions& options,
Message* destination);
+ // Add required field path of the message to this tree based on current tree
+ // structure. If a message is present in the tree, add the path of its
+ // required field to the tree. This is to make sure that after trimming a
+ // message with required fields are set, check IsInitialized() will not fail.
+ void AddRequiredFieldPath(Node* node, const Descriptor* descriptor);
+
// Trims all fields not specified by this sub-tree from the given message.
void TrimMessage(const Node* node, Message* message);
@@ -315,6 +340,59 @@ void FieldMaskTree::AddPath(const string& path) {
}
}
+void FieldMaskTree::RemovePath(const string& path,
+ const Descriptor* descriptor) {
+ std::vector<string> parts = Split(path, ".");
+ if (parts.empty()) {
+ return;
+ }
+ std::vector<Node*> nodes(parts.size());
+ Node* node = &root_;
+ const Descriptor* current_descriptor = descriptor;
+ Node* new_branch_node = NULL;
+ for (int i = 0; i < parts.size(); ++i) {
+ nodes[i] = node;
+ const FieldDescriptor* field_descriptor =
+ current_descriptor->FindFieldByName(parts[i]);
+ if (field_descriptor == NULL ||
+ (field_descriptor->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE &&
+ i != parts.size() - 1)) {
+ // Invalid path.
+ if (new_branch_node != NULL) {
+ // If add any new nodes, cleanup.
+ new_branch_node->ClearChildren();
+ }
+ return;
+ }
+
+ if (node->children.empty()) {
+ if (new_branch_node == NULL) {
+ new_branch_node = node;
+ }
+ for (int i = 0; i < current_descriptor->field_count(); ++i) {
+ node->children[current_descriptor->field(i)->name()] = new Node();
+ }
+ }
+ if (ContainsKey(node->children, parts[i])) {
+ node = node->children.at(parts[i]);
+ if (field_descriptor->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
+ current_descriptor = field_descriptor->message_type();
+ }
+ } else {
+ // Path does not exist.
+ return;
+ }
+ }
+ // Remove path.
+ for (int i = parts.size() - 1; i >= 0; i--) {
+ delete nodes[i]->children[parts[i]];
+ nodes[i]->children.erase(parts[i]);
+ if (!nodes[i]->children.empty()) {
+ break;
+ }
+ }
+}
+
void FieldMaskTree::IntersectPath(const string& path, FieldMaskTree* out) {
std::vector<string> parts = Split(path, ".");
if (parts.empty()) {
@@ -456,6 +534,41 @@ void FieldMaskTree::MergeMessage(const Node* node, const Message& source,
}
}
+void FieldMaskTree::AddRequiredFieldPath(
+ Node* node, const Descriptor* descriptor) {
+ const int32 field_count = descriptor->field_count();
+ for (int index = 0; index < field_count; ++index) {
+ const FieldDescriptor* field = descriptor->field(index);
+ if (field->is_required()) {
+ const string& node_name = field->name();
+ Node*& child = node->children[node_name];
+ if (child == NULL) {
+ // Add required field path to the tree
+ child = new Node();
+ } else if (child->children.empty()){
+ // If the required field is in the tree and does not have any children,
+ // do nothing.
+ continue;
+ }
+ // Add required field in the children to the tree if the field is message.
+ if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
+ AddRequiredFieldPath(child, field->message_type());
+ }
+ } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
+ std::map<string, Node*>::const_iterator it =
+ node->children.find(field->name());
+ if (it != node->children.end()) {
+ // Add required fields in the children to the
+ // tree if the field is a message and present in the tree.
+ Node* child = it->second;
+ if (!child->children.empty()) {
+ AddRequiredFieldPath(child, field->message_type());
+ }
+ }
+ }
+ }
+}
+
void FieldMaskTree::TrimMessage(const Node* node, Message* message) {
GOOGLE_DCHECK(!node->children.empty());
const Reflection* reflection = message->GetReflection();
@@ -463,13 +576,14 @@ void FieldMaskTree::TrimMessage(const Node* node, Message* message) {
const int32 field_count = descriptor->field_count();
for (int index = 0; index < field_count; ++index) {
const FieldDescriptor* field = descriptor->field(index);
- map<string, Node*>::const_iterator it = node->children.find(field->name());
+ std::map<string, Node*>::const_iterator it =
+ node->children.find(field->name());
if (it == node->children.end()) {
reflection->ClearField(message, field);
} else {
if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
Node* child = it->second;
- if (!child->children.empty()) {
+ if (!child->children.empty() && reflection->HasField(*message, field)) {
TrimMessage(child, reflection->MutableMessage(message, field));
}
}
@@ -506,6 +620,22 @@ void FieldMaskUtil::Intersect(const FieldMask& mask1, const FieldMask& mask2,
intersection.MergeToFieldMask(out);
}
+void FieldMaskUtil::InternalSubtract(const Descriptor* descriptor,
+ const FieldMask& mask1,
+ const FieldMask& mask2, FieldMask* out) {
+ if (mask1.paths().empty()) {
+ out->Clear();
+ return;
+ }
+ FieldMaskTree tree;
+ tree.MergeFromFieldMask(mask1);
+ for (int i = 0; i < mask2.paths_size(); ++i) {
+ tree.RemovePath(mask2.paths(i), descriptor);
+ }
+ out->Clear();
+ tree.MergeToFieldMask(out);
+}
+
bool FieldMaskUtil::IsPathInFieldMask(StringPiece path, const FieldMask& mask) {
for (int i = 0; i < mask.paths_size(); ++i) {
const string& mask_path = mask.paths(i);
@@ -541,6 +671,20 @@ void FieldMaskUtil::TrimMessage(const FieldMask& mask, Message* destination) {
tree.TrimMessage(GOOGLE_CHECK_NOTNULL(destination));
}
+void FieldMaskUtil::TrimMessage(const FieldMask& mask, Message* destination,
+ const TrimOptions& options) {
+ // Build a FieldMaskTree and walk through the tree to merge all specified
+ // fields.
+ FieldMaskTree tree;
+ tree.MergeFromFieldMask(mask);
+ // If keep_required_fields is true, implicitely add required fields of
+ // a message present in the tree to prevent from trimming.
+ if (options.keep_required_fields()) {
+ tree.AddRequiredFieldPath(GOOGLE_CHECK_NOTNULL(destination->GetDescriptor()));
+ }
+ tree.TrimMessage(GOOGLE_CHECK_NOTNULL(destination));
+}
+
} // namespace util
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/util/field_mask_util.h b/src/google/protobuf/util/field_mask_util.h
index ab1f2e94..01642c6f 100644
--- a/src/google/protobuf/util/field_mask_util.h
+++ b/src/google/protobuf/util/field_mask_util.h
@@ -113,6 +113,13 @@ class LIBPROTOBUF_EXPORT FieldMaskUtil {
static void Intersect(const FieldMask& mask1, const FieldMask& mask2,
FieldMask* out);
+ // Subtracts mask2 from mask1 base of type T.
+ template <typename T>
+ static void Subtract(const FieldMask& mask1, const FieldMask& mask2,
+ FieldMask* out) {
+ InternalSubtract(T::descriptor(), mask1, mask2, out);
+ }
+
// Returns true if path is covered by the given FieldMask. Note that path
// "foo.bar" covers all paths like "foo.bar.baz", "foo.bar.quz.x", etc.
static bool IsPathInFieldMask(StringPiece path, const FieldMask& mask);
@@ -124,10 +131,17 @@ class LIBPROTOBUF_EXPORT FieldMaskUtil {
static void MergeMessageTo(const Message& source, const FieldMask& mask,
const MergeOptions& options, Message* destination);
+ class TrimOptions;
// Removes from 'message' any field that is not represented in the given
// FieldMask. If the FieldMask is empty, does nothing.
static void TrimMessage(const FieldMask& mask, Message* message);
+ // Removes from 'message' any field that is not represented in the given
+ // FieldMask with customized TrimOptions.
+ // If the FieldMask is empty, does nothing.
+ static void TrimMessage(const FieldMask& mask, Message* message,
+ const TrimOptions& options);
+
private:
friend class SnakeCaseCamelCaseTest;
// Converts a field name from snake_case to camelCase:
@@ -160,6 +174,10 @@ class LIBPROTOBUF_EXPORT FieldMaskUtil {
static void InternalGetFieldMaskForAllFields(const Descriptor* descriptor,
FieldMask* out);
+
+ static void InternalSubtract(const Descriptor* descriptor,
+ const FieldMask& mask1, const FieldMask& mask2,
+ FieldMask* out);
};
// Note that for compatibility with the defined behaviour for FieldMask in
@@ -194,6 +212,23 @@ class LIBPROTOBUF_EXPORT FieldMaskUtil::MergeOptions {
bool replace_repeated_fields_;
};
+class LIBPROTOBUF_EXPORT FieldMaskUtil::TrimOptions {
+ public:
+ TrimOptions()
+ : keep_required_fields_(false) {}
+ // When trimming message fields, the default behavior is to trim required
+ // fields of the present message if they are not specified in the field mask.
+ // If you instead want to keep required fields of the present message even
+ // they are not speicifed in the field mask, set this flag to true.
+ void set_keep_required_fields(bool value) {
+ keep_required_fields_ = value;
+ }
+ bool keep_required_fields() const { return keep_required_fields_; }
+
+ private:
+ bool keep_required_fields_;
+};
+
} // namespace util
} // namespace protobuf
diff --git a/src/google/protobuf/util/field_mask_util_test.cc b/src/google/protobuf/util/field_mask_util_test.cc
index f952786f..7939f733 100644
--- a/src/google/protobuf/util/field_mask_util_test.cc
+++ b/src/google/protobuf/util/field_mask_util_test.cc
@@ -114,6 +114,8 @@ TEST_F(SnakeCaseCamelCaseTest, RoundTripTest) {
}
using protobuf_unittest::TestAllTypes;
+using protobuf_unittest::TestRequired;
+using protobuf_unittest::TestRequiredMessage;
using protobuf_unittest::NestedTestAllTypes;
using google::protobuf::FieldMask;
@@ -346,6 +348,46 @@ TEST(FieldMaskUtilTest, TestIntersect) {
EXPECT_EQ("foo.bar.baz", FieldMaskUtil::ToString(out));
}
+TEST(FieldMaskUtilTest, TestSubtract) {
+ FieldMask mask1, mask2, out;
+ // Normal case.
+ FieldMaskUtil::FromString(
+ "optional_int32,optional_uint64,optional_nested_message,optional_foreign_"
+ "message,repeated_int32,repeated_foreign_message,repeated_nested_message."
+ "bb",
+ &mask1);
+
+ FieldMaskUtil::FromString(
+ "optional_int32,optional_nested_message.bb,optional_foreign_message.c,"
+ "repeated_int32,repeated_nested_message.bb,repeated_foreign_message.f,"
+ "repeated_foreign_message.d,repeated_nested_message.bb,repeated_uint32",
+ &mask2);
+
+ FieldMaskUtil::Subtract<TestAllTypes>(mask1, mask2, &out);
+ EXPECT_EQ(
+ "optional_foreign_message.d,optional_uint64,repeated_foreign_message.c",
+ FieldMaskUtil::ToString(out));
+
+ // mask1 is empty.
+ FieldMaskUtil::FromString("", &mask1);
+ FieldMaskUtil::Subtract<TestAllTypes>(mask1, mask2, &out);
+ EXPECT_EQ("", FieldMaskUtil::ToString(out));
+
+ // mask1 is "optional_nested_message" and mask2 is
+ // "optional_nested_message.nonexist_field".
+ FieldMaskUtil::FromString("optional_nested_message", &mask1);
+ FieldMaskUtil::FromString("optional_nested_message.nonexist_field", &mask2);
+ FieldMaskUtil::Subtract<TestAllTypes>(mask1, mask2, &out);
+ EXPECT_EQ("optional_nested_message", FieldMaskUtil::ToString(out));
+
+ // mask1 is "optional_nested_message" and mask2 is
+ // "optional_nested_message".
+ FieldMaskUtil::FromString("optional_nested_message", &mask1);
+ FieldMaskUtil::FromString("optional_nested_message", &mask2);
+ FieldMaskUtil::Subtract<TestAllTypes>(mask1, mask2, &out);
+ EXPECT_EQ("", FieldMaskUtil::ToString(out));
+}
+
TEST(FieldMaskUtilTest, TestIspathInFieldMask) {
FieldMask mask;
FieldMaskUtil::FromString("foo.bar", &mask);
@@ -618,6 +660,84 @@ TEST(FieldMaskUtilTest, TrimMessage) {
FieldMask empty_mask;
FieldMaskUtil::TrimMessage(empty_mask, &trimmed_all_types);
EXPECT_EQ(trimmed_all_types.DebugString(), all_types_msg.DebugString());
+
+ // Test trim required fields with keep_required_fields is set true.
+ FieldMaskUtil::TrimOptions options;
+ TestRequired required_msg_1;
+ required_msg_1.set_a(1234);
+ required_msg_1.set_b(3456);
+ required_msg_1.set_c(5678);
+ TestRequired trimmed_required_msg_1(required_msg_1);
+ FieldMaskUtil::FromString("dummy2", &mask);
+ options.set_keep_required_fields(true);
+ FieldMaskUtil::TrimMessage(mask, &trimmed_required_msg_1, options);
+ EXPECT_EQ(trimmed_required_msg_1.DebugString(), required_msg_1.DebugString());
+
+ // Test trim required fields with keep_required_fields is set false.
+ required_msg_1.clear_a();
+ required_msg_1.clear_b();
+ required_msg_1.clear_c();
+ options.set_keep_required_fields(false);
+ FieldMaskUtil::TrimMessage(mask, &trimmed_required_msg_1, options);
+ EXPECT_EQ(trimmed_required_msg_1.DebugString(), required_msg_1.DebugString());
+
+ // Test trim required message with keep_required_fields is set true.
+ TestRequiredMessage required_msg_2;
+ required_msg_2.mutable_optional_message()->set_a(1234);
+ required_msg_2.mutable_optional_message()->set_b(3456);
+ required_msg_2.mutable_optional_message()->set_c(5678);
+ required_msg_2.mutable_required_message()->set_a(1234);
+ required_msg_2.mutable_required_message()->set_b(3456);
+ required_msg_2.mutable_required_message()->set_c(5678);
+ required_msg_2.mutable_required_message()->set_dummy2(7890);
+ TestRequired* repeated_msg = required_msg_2.add_repeated_message();
+ repeated_msg->set_a(1234);
+ repeated_msg->set_b(3456);
+ repeated_msg->set_c(5678);
+ TestRequiredMessage trimmed_required_msg_2(required_msg_2);
+ FieldMaskUtil::FromString("optional_message.dummy2", &mask);
+ options.set_keep_required_fields(true);
+ required_msg_2.clear_repeated_message();
+ required_msg_2.mutable_required_message()->clear_dummy2();
+ FieldMaskUtil::TrimMessage(mask, &trimmed_required_msg_2, options);
+ EXPECT_EQ(trimmed_required_msg_2.DebugString(),
+ required_msg_2.DebugString());
+
+ FieldMaskUtil::FromString("required_message", &mask);
+ required_msg_2.mutable_required_message()->set_dummy2(7890);
+ trimmed_required_msg_2.mutable_required_message()->set_dummy2(7890);
+ required_msg_2.clear_optional_message();
+ FieldMaskUtil::TrimMessage(mask, &trimmed_required_msg_2, options);
+ EXPECT_EQ(trimmed_required_msg_2.DebugString(),
+ required_msg_2.DebugString());
+
+ // Test trim required message with keep_required_fields is set false.
+ FieldMaskUtil::FromString("required_message.dummy2", &mask);
+ required_msg_2.mutable_required_message()->clear_a();
+ required_msg_2.mutable_required_message()->clear_b();
+ required_msg_2.mutable_required_message()->clear_c();
+ options.set_keep_required_fields(false);
+ FieldMaskUtil::TrimMessage(mask, &trimmed_required_msg_2, options);
+ EXPECT_EQ(trimmed_required_msg_2.DebugString(),
+ required_msg_2.DebugString());
+
+ // Verify that trimming an empty message has no effect. In particular, fields
+ // mentioned in the field mask should not be created or changed.
+ TestAllTypes empty_msg;
+ FieldMaskUtil::FromString(
+ "optional_int32,optional_bytes,optional_nested_message.bb", &mask);
+ FieldMaskUtil::TrimMessage(mask, &empty_msg);
+ EXPECT_FALSE(empty_msg.has_optional_int32());
+ EXPECT_FALSE(empty_msg.has_optional_bytes());
+ EXPECT_FALSE(empty_msg.has_optional_nested_message());
+
+ // Verify trimming of oneof fields. This should work as expected even if
+ // multiple elements of the same oneof are included in the FieldMask.
+ TestAllTypes oneof_msg;
+ oneof_msg.set_oneof_uint32(11);
+ FieldMaskUtil::FromString("oneof_uint32,oneof_nested_message.bb", &mask);
+ FieldMaskUtil::TrimMessage(mask, &oneof_msg);
+ EXPECT_EQ(11, oneof_msg.oneof_uint32());
}
diff --git a/src/google/protobuf/util/internal/default_value_objectwriter.cc b/src/google/protobuf/util/internal/default_value_objectwriter.cc
index 1772219a..95b3a17d 100644
--- a/src/google/protobuf/util/internal/default_value_objectwriter.cc
+++ b/src/google/protobuf/util/internal/default_value_objectwriter.cc
@@ -65,6 +65,7 @@ DefaultValueObjectWriter::DefaultValueObjectWriter(
current_(NULL),
root_(NULL),
suppress_empty_list_(false),
+ preserve_proto_field_names_(false),
field_scrub_callback_(NULL),
ow_(ow) {}
@@ -188,6 +189,24 @@ void DefaultValueObjectWriter::RegisterFieldScrubCallBack(
field_scrub_callback_.reset(field_scrub_callback.release());
}
+DefaultValueObjectWriter::Node* DefaultValueObjectWriter::CreateNewNode(
+ const string& name, const google::protobuf::Type* type, NodeKind kind,
+ const DataPiece& data, bool is_placeholder, const std::vector<string>& path,
+ bool suppress_empty_list, FieldScrubCallBack* field_scrub_callback) {
+ return new Node(name, type, kind, data, is_placeholder, path,
+ suppress_empty_list, field_scrub_callback);
+}
+
+DefaultValueObjectWriter::Node* DefaultValueObjectWriter::CreateNewNode(
+ const string& name, const google::protobuf::Type* type, NodeKind kind,
+ const DataPiece& data, bool is_placeholder, const std::vector<string>& path,
+ bool suppress_empty_list, bool preserve_proto_field_names,
+ FieldScrubCallBack* field_scrub_callback) {
+ return new Node(name, type, kind, data, is_placeholder, path,
+ suppress_empty_list, preserve_proto_field_names,
+ field_scrub_callback);
+}
+
DefaultValueObjectWriter::Node::Node(
const string& name, const google::protobuf::Type* type, NodeKind kind,
const DataPiece& data, bool is_placeholder, const std::vector<string>& path,
@@ -200,6 +219,23 @@ DefaultValueObjectWriter::Node::Node(
is_placeholder_(is_placeholder),
path_(path),
suppress_empty_list_(suppress_empty_list),
+ preserve_proto_field_names_(false),
+ field_scrub_callback_(field_scrub_callback) {}
+
+DefaultValueObjectWriter::Node::Node(
+ const string& name, const google::protobuf::Type* type, NodeKind kind,
+ const DataPiece& data, bool is_placeholder, const std::vector<string>& path,
+ bool suppress_empty_list, bool preserve_proto_field_names,
+ FieldScrubCallBack* field_scrub_callback)
+ : name_(name),
+ type_(type),
+ kind_(kind),
+ is_any_(false),
+ data_(data),
+ is_placeholder_(is_placeholder),
+ path_(path),
+ suppress_empty_list_(suppress_empty_list),
+ preserve_proto_field_names_(preserve_proto_field_names),
field_scrub_callback_(field_scrub_callback) {}
DefaultValueObjectWriter::Node* DefaultValueObjectWriter::Node::FindChild(
@@ -363,16 +399,19 @@ void DefaultValueObjectWriter::Node::PopulateChildren(
}
// If oneof_index() != 0, the child field is part of a "oneof", which means
- // the child field is optional and we shouldn't populate its default value.
- if (field.oneof_index() != 0) continue;
+ // the child field is optional and we shouldn't populate its default
+ // primitive value.
+ if (field.oneof_index() != 0 && kind == PRIMITIVE) continue;
// If the child field is of primitive type, sets its data to the default
// value of its type.
google::protobuf::scoped_ptr<Node> child(new Node(
- field.json_name(), field_type, kind,
+ preserve_proto_field_names_ ? field.name() : field.json_name(),
+ field_type, kind,
kind == PRIMITIVE ? CreateDefaultDataPieceForField(field, typeinfo)
: DataPiece::NullData(),
- true, path, suppress_empty_list_, field_scrub_callback_));
+ true, path, suppress_empty_list_, preserve_proto_field_names_,
+ field_scrub_callback_));
new_children.push_back(child.release());
}
// Adds all leftover nodes in children_ to the beginning of new_child.
@@ -467,9 +506,10 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::StartObject(
StringPiece name) {
if (current_ == NULL) {
std::vector<string> path;
- root_.reset(new Node(name.ToString(), &type_, OBJECT, DataPiece::NullData(),
- false, path, suppress_empty_list_,
- field_scrub_callback_.get()));
+ root_.reset(CreateNewNode(string(name), &type_, OBJECT,
+ DataPiece::NullData(), false, path,
+ suppress_empty_list_, preserve_proto_field_names_,
+ field_scrub_callback_.get()));
root_->PopulateChildren(typeinfo_);
current_ = root_.get();
return this;
@@ -479,13 +519,15 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::StartObject(
if (current_->kind() == LIST || current_->kind() == MAP || child == NULL) {
// If current_ is a list or a map node, we should create a new child and use
// the type of current_ as the type of the new child.
- google::protobuf::scoped_ptr<Node> node(new Node(
- name.ToString(), ((current_->kind() == LIST || current_->kind() == MAP)
- ? current_->type()
- : NULL),
- OBJECT, DataPiece::NullData(), false,
- child == NULL ? current_->path() : child->path(),
- suppress_empty_list_, field_scrub_callback_.get()));
+ google::protobuf::scoped_ptr<Node> node(
+ CreateNewNode(string(name),
+ ((current_->kind() == LIST || current_->kind() == MAP)
+ ? current_->type()
+ : NULL),
+ OBJECT, DataPiece::NullData(), false,
+ child == NULL ? current_->path() : child->path(),
+ suppress_empty_list_, preserve_proto_field_names_,
+ field_scrub_callback_.get()));
child = node.get();
current_->AddChild(node.release());
}
@@ -515,9 +557,10 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::StartList(
StringPiece name) {
if (current_ == NULL) {
std::vector<string> path;
- root_.reset(new Node(name.ToString(), &type_, LIST, DataPiece::NullData(),
- false, path, suppress_empty_list_,
- field_scrub_callback_.get()));
+ root_.reset(CreateNewNode(string(name), &type_, LIST, DataPiece::NullData(),
+ false, path, suppress_empty_list_,
+ preserve_proto_field_names_,
+ field_scrub_callback_.get()));
current_ = root_.get();
return this;
}
@@ -525,9 +568,10 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::StartList(
Node* child = current_->FindChild(name);
if (child == NULL || child->kind() != LIST) {
google::protobuf::scoped_ptr<Node> node(
- new Node(name.ToString(), NULL, LIST, DataPiece::NullData(), false,
- child == NULL ? current_->path() : child->path(),
- suppress_empty_list_, field_scrub_callback_.get()));
+ CreateNewNode(string(name), NULL, LIST, DataPiece::NullData(), false,
+ child == NULL ? current_->path() : child->path(),
+ suppress_empty_list_, preserve_proto_field_names_,
+ field_scrub_callback_.get()));
child = node.get();
current_->AddChild(node.release());
}
@@ -586,12 +630,14 @@ void DefaultValueObjectWriter::RenderDataPiece(StringPiece name,
if (child == NULL || child->kind() != PRIMITIVE) {
// No children are found, creates a new child.
google::protobuf::scoped_ptr<Node> node(
- new Node(name.ToString(), NULL, PRIMITIVE, data, false,
- child == NULL ? current_->path() : child->path(),
- suppress_empty_list_, field_scrub_callback_.get()));
+ CreateNewNode(string(name), NULL, PRIMITIVE, data, false,
+ child == NULL ? current_->path() : child->path(),
+ suppress_empty_list_, preserve_proto_field_names_,
+ field_scrub_callback_.get()));
current_->AddChild(node.release());
} else {
child->set_data(data);
+ child->set_is_placeholder(false);
}
}
diff --git a/src/google/protobuf/util/internal/default_value_objectwriter.h b/src/google/protobuf/util/internal/default_value_objectwriter.h
index dc4551c9..09c6d23f 100644
--- a/src/google/protobuf/util/internal/default_value_objectwriter.h
+++ b/src/google/protobuf/util/internal/default_value_objectwriter.h
@@ -126,7 +126,12 @@ class LIBPROTOBUF_EXPORT DefaultValueObjectWriter : public ObjectWriter {
// are written.
void set_suppress_empty_list(bool value) { suppress_empty_list_ = value; }
- private:
+ // If set to true, original proto field names are used
+ void set_preserve_proto_field_names(bool value) {
+ preserve_proto_field_names_ = value;
+ }
+
+ protected:
enum NodeKind {
PRIMITIVE = 0,
OBJECT = 1,
@@ -142,6 +147,11 @@ class LIBPROTOBUF_EXPORT DefaultValueObjectWriter : public ObjectWriter {
const DataPiece& data, bool is_placeholder,
const std::vector<string>& path, bool suppress_empty_list,
FieldScrubCallBack* field_scrub_callback);
+ Node(const string& name, const google::protobuf::Type* type, NodeKind kind,
+ const DataPiece& data, bool is_placeholder,
+ const std::vector<string>& path, bool suppress_empty_list,
+ bool preserve_proto_field_names,
+ FieldScrubCallBack* field_scrub_callback);
virtual ~Node() {
for (int i = 0; i < children_.size(); ++i) {
delete children_[i];
@@ -157,12 +167,12 @@ class LIBPROTOBUF_EXPORT DefaultValueObjectWriter : public ObjectWriter {
// Populates children of this Node based on its type. If there are already
// children created, they will be merged to the result. Caller should pass
// in TypeInfo for looking up types of the children.
- void PopulateChildren(const TypeInfo* typeinfo);
+ virtual void PopulateChildren(const TypeInfo* typeinfo);
// If this node is a leaf (has data), writes the current node to the
// ObjectWriter; if not, then recursively writes the children to the
// ObjectWriter.
- void WriteTo(ObjectWriter* ow);
+ virtual void WriteTo(ObjectWriter* ow);
// Accessors
const string& name() const { return name_; }
@@ -187,7 +197,7 @@ class LIBPROTOBUF_EXPORT DefaultValueObjectWriter : public ObjectWriter {
is_placeholder_ = is_placeholder;
}
- private:
+ protected:
// Returns the Value Type of a map given the Type of the map entry and a
// TypeInfo instance.
const google::protobuf::Type* GetMapValueType(
@@ -220,13 +230,43 @@ class LIBPROTOBUF_EXPORT DefaultValueObjectWriter : public ObjectWriter {
// Whether to suppress empty list output.
bool suppress_empty_list_;
+ // Whether to preserve original proto field names
+ bool preserve_proto_field_names_;
+
// Pointer to function for determining whether a field needs to be scrubbed
// or not. This callback is owned by the creator of this node.
FieldScrubCallBack* field_scrub_callback_;
+ private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Node);
};
+ // Creates a new Node and returns it. Caller owns memory of returned object.
+ virtual Node* CreateNewNode(const string& name,
+ const google::protobuf::Type* type, NodeKind kind,
+ const DataPiece& data, bool is_placeholder,
+ const std::vector<string>& path,
+ bool suppress_empty_list,
+ FieldScrubCallBack* field_scrub_callback);
+
+ // Creates a new Node and returns it. Caller owns memory of returned object.
+ virtual Node* CreateNewNode(const string& name,
+ const google::protobuf::Type* type, NodeKind kind,
+ const DataPiece& data, bool is_placeholder,
+ const std::vector<string>& path,
+ bool suppress_empty_list,
+ bool preserve_proto_field_names,
+ FieldScrubCallBack* field_scrub_callback);
+
+ // Creates a DataPiece containing the default value of the type of the field.
+ static DataPiece CreateDefaultDataPieceForField(
+ const google::protobuf::Field& field, const TypeInfo* typeinfo);
+
+ protected:
+ // Returns a pointer to current Node in tree.
+ Node* current() { return current_; }
+
+ private:
// Populates children of "node" if it is an "any" Node and its real type has
// been given.
void MaybePopulateChildrenOfAny(Node* node);
@@ -235,10 +275,6 @@ class LIBPROTOBUF_EXPORT DefaultValueObjectWriter : public ObjectWriter {
// NULL.
void WriteRoot();
- // Creates a DataPiece containing the default value of the type of the field.
- static DataPiece CreateDefaultDataPieceForField(
- const google::protobuf::Field& field, const TypeInfo* typeinfo);
-
// Adds or replaces the data_ of a primitive child node.
void RenderDataPiece(StringPiece name, const DataPiece& data);
@@ -268,6 +304,9 @@ class LIBPROTOBUF_EXPORT DefaultValueObjectWriter : public ObjectWriter {
// Whether to suppress output of empty lists.
bool suppress_empty_list_;
+ // Whether to preserve original proto field names
+ bool preserve_proto_field_names_;
+
// Unique Pointer to function for determining whether a field needs to be
// scrubbed or not.
FieldScrubCallBackPtr field_scrub_callback_;
diff --git a/src/google/protobuf/util/internal/field_mask_utility.cc b/src/google/protobuf/util/internal/field_mask_utility.cc
index 53b90fb0..38835f67 100644
--- a/src/google/protobuf/util/internal/field_mask_utility.cc
+++ b/src/google/protobuf/util/internal/field_mask_utility.cc
@@ -44,11 +44,6 @@ inline util::Status CallPathSink(PathSinkCallback path_sink,
return path_sink->Run(arg);
}
-util::Status CreatePublicError(util::error::Code code,
- const string& message) {
- return util::Status(code, message);
-}
-
// Appends a FieldMask path segment to a prefix.
string AppendPathSegmentToPrefix(StringPiece prefix, StringPiece segment) {
if (prefix.empty()) {
@@ -216,7 +211,7 @@ util::Status DecodeCompactFieldMaskPaths(StringPiece paths,
StrCat("Invalid FieldMask '", paths,
"'. Cannot find matching ')' for all '('."));
}
- return util::Status::OK;
+ return util::Status();
}
} // namespace converter
diff --git a/src/google/protobuf/util/internal/json_escaping.cc b/src/google/protobuf/util/internal/json_escaping.cc
index 06d2791b..06b9a7f2 100644
--- a/src/google/protobuf/util/internal/json_escaping.cc
+++ b/src/google/protobuf/util/internal/json_escaping.cc
@@ -84,30 +84,6 @@ static const char kCommonEscapes[160][7] = {
"\\u009c", "\\u009d", "\\u009e", "\\u009f"
};
-// Determines if the given char value is a unicode high-surrogate code unit.
-// Such values do not represent characters by themselves, but are used in the
-// representation of supplementary characters in the utf-16 encoding.
-inline bool IsHighSurrogate(uint16 c) {
- // Optimized form of:
- // return c >= kMinHighSurrogate && c <= kMaxHighSurrogate;
- // (Reduced from 3 ALU instructions to 2 ALU instructions)
- return (c & ~(JsonEscaping::kMaxHighSurrogate -
- JsonEscaping::kMinHighSurrogate))
- == JsonEscaping::kMinHighSurrogate;
-}
-
-// Determines if the given char value is a unicode low-surrogate code unit.
-// Such values do not represent characters by themselves, but are used in the
-// representation of supplementary characters in the utf-16 encoding.
-inline bool IsLowSurrogate(uint16 c) {
- // Optimized form of:
- // return c >= kMinLowSurrogate && c <= kMaxLowSurrogate;
- // (Reduced from 3 ALU instructions to 2 ALU instructions)
- return (c & ~(JsonEscaping::kMaxLowSurrogate -
- JsonEscaping::kMinLowSurrogate))
- == JsonEscaping::kMinLowSurrogate;
-}
-
// Determines if the given char value is a unicode surrogate code unit (either
// high-surrogate or low-surrogate).
inline bool IsSurrogate(uint32 c) {
@@ -117,36 +93,12 @@ inline bool IsSurrogate(uint32 c) {
return (c & 0xfffff800) == JsonEscaping::kMinHighSurrogate;
}
-// Returns true if the given unicode code point cp is
-// in the supplementary character range.
-inline bool IsSupplementalCodePoint(uint32 cp) {
- // Optimized form of:
- // return kMinSupplementaryCodePoint <= cp && cp <= kMaxCodePoint;
- // (Reduced from 3 ALU instructions to 2 ALU instructions)
- return (cp & ~(JsonEscaping::kMinSupplementaryCodePoint - 1))
- < JsonEscaping::kMaxCodePoint;
-}
-
// Returns true if the given unicode code point cp is a valid
// unicode code point (i.e. in the range 0 <= cp <= kMaxCodePoint).
inline bool IsValidCodePoint(uint32 cp) {
return cp <= JsonEscaping::kMaxCodePoint;
}
-// Converts the specified surrogate pair to its supplementary code point value.
-// It is the callers' responsibility to validate the specified surrogate pair.
-inline uint32 ToCodePoint(uint16 high, uint16 low) {
- // Optimized form of:
- // return ((high - kMinHighSurrogate) << 10)
- // + (low - kMinLowSurrogate)
- // + kMinSupplementaryCodePoint;
- // (Reduced from 5 ALU instructions to 3 ALU instructions)
- return (high << 10) + low +
- (JsonEscaping::kMinSupplementaryCodePoint
- - (static_cast<unsigned>(JsonEscaping::kMinHighSurrogate) << 10)
- - JsonEscaping::kMinLowSurrogate);
-}
-
// Returns the low surrogate for the given unicode code point. The result is
// meaningless if the given code point is not a supplementary character.
inline uint16 ToLowSurrogate(uint32 cp) {
@@ -255,7 +207,7 @@ StringPiece ToHex(uint16 cp, char* buffer) {
buffer[3] = kHex[cp & 0x0f];
cp >>= 4;
buffer[2] = kHex[cp & 0x0f];
- return StringPiece(buffer).substr(0, 6);
+ return StringPiece(buffer, 6);
}
// Stores the 32-bit unicode code point as its hexadecimal digits in buffer
@@ -336,19 +288,19 @@ StringPiece EscapeCodePoint(uint32 cp, char* buffer, bool force_output) {
cp >>= 6;
if (cp <= 0x1f) {
buffer[4] = cp | 0xc0;
- sp.set(buffer + 4, 2);
+ sp = StringPiece(buffer + 4, 2);
return sp;
}
buffer[4] = (cp & 0x3f) | 0x80;
cp >>= 6;
if (cp <= 0x0f) {
buffer[3] = cp | 0xe0;
- sp.set(buffer + 3, 3);
+ sp = StringPiece(buffer + 3, 3);
return sp;
}
buffer[3] = (cp & 0x3f) | 0x80;
buffer[2] = ((cp >> 6) & 0x07) | 0xf0;
- sp.set(buffer + 2, 4);
+ sp = StringPiece(buffer + 2, 4);
}
return sp;
}
diff --git a/src/google/protobuf/util/internal/json_escaping.h b/src/google/protobuf/util/internal/json_escaping.h
index e3e329fc..9b8b2afd 100644
--- a/src/google/protobuf/util/internal/json_escaping.h
+++ b/src/google/protobuf/util/internal/json_escaping.h
@@ -86,6 +86,6 @@ class JsonEscaping {
} // namespace converter
} // namespace util
} // namespace protobuf
+} // namespace google
#endif // NET_PROTO2_UTIL_CONVERTER_STRINGS_JSON_ESCAPING_H_
-} // namespace google
diff --git a/src/google/protobuf/util/internal/json_stream_parser.cc b/src/google/protobuf/util/internal/json_stream_parser.cc
index 2af4ad90..2ada3583 100644
--- a/src/google/protobuf/util/internal/json_stream_parser.cc
+++ b/src/google/protobuf/util/internal/json_stream_parser.cc
@@ -56,6 +56,7 @@ namespace util {
// this file.
using util::Status;
namespace error {
+using util::error::CANCELLED;
using util::error::INTERNAL;
using util::error::INVALID_ARGUMENT;
} // namespace error
@@ -129,7 +130,7 @@ util::Status JsonStreamParser::Parse(StringPiece json) {
// Don't point chunk to leftover_ because leftover_ will be updated in
// ParseChunk(chunk).
chunk_storage_.swap(leftover_);
- json.AppendToString(&chunk_storage_);
+ StrAppend(&chunk_storage_, json);
chunk = StringPiece(chunk_storage_);
}
@@ -140,11 +141,11 @@ util::Status JsonStreamParser::Parse(StringPiece json) {
// Any leftover characters are stashed in leftover_ for later parsing when
// there is more data available.
- chunk.substr(n).AppendToString(&leftover_);
+ StrAppend(&leftover_, chunk.substr(n));
return status;
} else {
- chunk.CopyToString(&leftover_);
- return util::Status::OK;
+ leftover_.assign(chunk.data(), chunk.size());
+ return util::Status();
}
}
@@ -152,7 +153,7 @@ util::Status JsonStreamParser::FinishParse() {
// If we do not expect anything and there is nothing left to parse we're all
// done.
if (stack_.empty() && leftover_.empty()) {
- return util::Status::OK;
+ return util::Status();
}
// Storage for UTF8-coerced string.
@@ -183,7 +184,7 @@ util::Status JsonStreamParser::FinishParse() {
util::Status JsonStreamParser::ParseChunk(StringPiece chunk) {
// Do not do any work if the chunk is empty.
- if (chunk.empty()) return util::Status::OK;
+ if (chunk.empty()) return util::Status();
p_ = json_ = chunk;
@@ -205,7 +206,7 @@ util::Status JsonStreamParser::ParseChunk(StringPiece chunk) {
// unparsed data left, we save it for later parse.
leftover_ = p_.ToString();
}
- return util::Status::OK;
+ return util::Status();
}
util::Status JsonStreamParser::RunParser() {
@@ -246,20 +247,20 @@ util::Status JsonStreamParser::RunParser() {
}
if (!result.ok()) {
// If we were cancelled, save our state and try again later.
- if (!finishing_ && result == util::Status::CANCELLED) {
+ if (!finishing_ && result == util::Status(error::CANCELLED, "")) {
stack_.push(type);
// If we have a key we still need to render, make sure to save off the
// contents in our own storage.
if (!key_.empty() && key_storage_.empty()) {
- key_.AppendToString(&key_storage_);
+ StrAppend(&key_storage_, key_);
key_ = StringPiece(key_storage_);
}
- result = util::Status::OK;
+ result = util::Status();
}
return result;
}
}
- return util::Status::OK;
+ return util::Status();
}
util::Status JsonStreamParser::ParseValue(TokenType type) {
@@ -290,7 +291,7 @@ util::Status JsonStreamParser::ParseValue(TokenType type) {
// don't know if the next char would be e, completing it, or something
// else, making it invalid.
if (!finishing_ && p_.length() < false_len) {
- return util::Status::CANCELLED;
+ return util::Status(error::CANCELLED, "");
}
return ReportFailure("Unexpected token.");
}
@@ -328,7 +329,7 @@ util::Status JsonStreamParser::ParseStringHelper() {
// depending on if we expect more data later.
if (p_.length() == 1) {
if (!finishing_) {
- return util::Status::CANCELLED;
+ return util::Status(error::CANCELLED, "");
}
return ReportFailure("Closing quote expected in string.");
}
@@ -385,7 +386,7 @@ util::Status JsonStreamParser::ParseStringHelper() {
// start fresh.
string_open_ = 0;
Advance();
- return util::Status::OK;
+ return util::Status();
}
// Normal character, just advance past it.
Advance();
@@ -396,7 +397,7 @@ util::Status JsonStreamParser::ParseStringHelper() {
}
// If we didn't find the closing quote but we expect more data, cancel for now
if (!finishing_) {
- return util::Status::CANCELLED;
+ return util::Status(error::CANCELLED, "");
}
// End of string reached without a closing quote, report an error.
string_open_ = 0;
@@ -413,7 +414,7 @@ util::Status JsonStreamParser::ParseStringHelper() {
util::Status JsonStreamParser::ParseUnicodeEscape() {
if (p_.length() < kUnicodeEscapedLength) {
if (!finishing_) {
- return util::Status::CANCELLED;
+ return util::Status(error::CANCELLED, "");
}
return ReportFailure("Illegal hex string.");
}
@@ -430,7 +431,7 @@ util::Status JsonStreamParser::ParseUnicodeEscape() {
code <= JsonEscaping::kMaxHighSurrogate) {
if (p_.length() < 2 * kUnicodeEscapedLength) {
if (!finishing_) {
- return util::Status::CANCELLED;
+ return util::Status(error::CANCELLED, "");
}
if (!coerce_to_utf8_) {
return ReportFailure("Missing low surrogate.");
@@ -467,7 +468,7 @@ util::Status JsonStreamParser::ParseUnicodeEscape() {
// Advance past the [final] code unit escape.
p_.remove_prefix(kUnicodeEscapedLength);
parsed_storage_.append(buf, len);
- return util::Status::OK;
+ return util::Status();
}
util::Status JsonStreamParser::ParseNumber() {
@@ -497,6 +498,19 @@ util::Status JsonStreamParser::ParseNumber() {
return result;
}
+util::Status JsonStreamParser::ParseDoubleHelper(
+ const string& number, NumberResult* result) {
+ if (!safe_strtod(number, &result->double_val)) {
+ return ReportFailure("Unable to parse number.");
+ }
+ if (!loose_float_number_conversion_ &&
+ !MathLimits<double>::IsFinite(result->double_val)) {
+ return ReportFailure("Number exceeds the range of double.");
+ }
+ result->type = NumberResult::DOUBLE;
+ return util::Status();
+}
+
util::Status JsonStreamParser::ParseNumberHelper(NumberResult* result) {
const char* data = p_.data();
int length = p_.length();
@@ -524,7 +538,7 @@ util::Status JsonStreamParser::ParseNumberHelper(NumberResult* result) {
// If the entire input is a valid number, and we may have more content in the
// future, we abort for now and resume when we know more.
if (index == length && !finishing_) {
- return util::Status::CANCELLED;
+ return util::Status(error::CANCELLED, "");
}
// Create a string containing just the number, so we can use safe_strtoX
@@ -532,16 +546,11 @@ util::Status JsonStreamParser::ParseNumberHelper(NumberResult* result) {
// Floating point number, parse as a double.
if (floating) {
- if (!safe_strtod(number, &result->double_val)) {
- return ReportFailure("Unable to parse number.");
- }
- if (!loose_float_number_conversion_ &&
- !MathLimits<double>::IsFinite(result->double_val)) {
- return ReportFailure("Number exceeds the range of double.");
+ util::Status status = ParseDoubleHelper(number, result);
+ if (status.ok()) {
+ p_.remove_prefix(index);
}
- result->type = NumberResult::DOUBLE;
- p_.remove_prefix(index);
- return util::Status::OK;
+ return status;
}
// Positive non-floating point number, parse as a uint64.
@@ -550,12 +559,18 @@ util::Status JsonStreamParser::ParseNumberHelper(NumberResult* result) {
if (number.length() >= 2 && number[0] == '0') {
return ReportFailure("Octal/hex numbers are not valid JSON values.");
}
- if (!safe_strtou64(number, &result->uint_val)) {
- return ReportFailure("Unable to parse number.");
+ if (safe_strtou64(number, &result->uint_val)) {
+ result->type = NumberResult::UINT;
+ p_.remove_prefix(index);
+ return util::Status();
+ } else {
+ // If the value is too large, parse it as double.
+ util::Status status = ParseDoubleHelper(number, result);
+ if (status.ok()) {
+ p_.remove_prefix(index);
+ }
+ return status;
}
- result->type = NumberResult::UINT;
- p_.remove_prefix(index);
- return util::Status::OK;
}
// Octal/Hex numbers are not valid JSON values.
@@ -563,12 +578,18 @@ util::Status JsonStreamParser::ParseNumberHelper(NumberResult* result) {
return ReportFailure("Octal/hex numbers are not valid JSON values.");
}
// Negative non-floating point number, parse as an int64.
- if (!safe_strto64(number, &result->int_val)) {
- return ReportFailure("Unable to parse number.");
+ if (safe_strto64(number, &result->int_val)) {
+ result->type = NumberResult::INT;
+ p_.remove_prefix(index);
+ return util::Status();
+ } else {
+ // If the value is too large, parse it as double.
+ util::Status status = ParseDoubleHelper(number, result);
+ if (status.ok()) {
+ p_.remove_prefix(index);
+ }
+ return status;
}
- result->type = NumberResult::INT;
- p_.remove_prefix(index);
- return util::Status::OK;
}
util::Status JsonStreamParser::HandleBeginObject() {
@@ -577,7 +598,7 @@ util::Status JsonStreamParser::HandleBeginObject() {
ow_->StartObject(key_);
key_ = StringPiece();
stack_.push(ENTRY);
- return util::Status::OK;
+ return util::Status();
}
util::Status JsonStreamParser::ParseObjectMid(TokenType type) {
@@ -589,13 +610,13 @@ util::Status JsonStreamParser::ParseObjectMid(TokenType type) {
if (type == END_OBJECT) {
Advance();
ow_->EndObject();
- return util::Status::OK;
+ return util::Status();
}
// Found a comma, advance past it and get ready for an entry.
if (type == VALUE_SEPARATOR) {
Advance();
stack_.push(ENTRY);
- return util::Status::OK;
+ return util::Status();
}
// Illegal token after key:value pair.
return ReportFailure("Expected , or } after key:value pair.");
@@ -610,7 +631,7 @@ util::Status JsonStreamParser::ParseEntry(TokenType type) {
if (type == END_OBJECT) {
ow_->EndObject();
Advance();
- return util::Status::OK;
+ return util::Status();
}
util::Status result;
@@ -649,7 +670,7 @@ util::Status JsonStreamParser::ParseEntryMid(TokenType type) {
if (type == ENTRY_SEPARATOR) {
Advance();
stack_.push(VALUE);
- return util::Status::OK;
+ return util::Status();
}
return ReportFailure("Expected : between key:value pair.");
}
@@ -660,7 +681,7 @@ util::Status JsonStreamParser::HandleBeginArray() {
ow_->StartList(key_);
key_ = StringPiece();
stack_.push(ARRAY_VALUE);
- return util::Status::OK;
+ return util::Status();
}
util::Status JsonStreamParser::ParseArrayValue(TokenType type) {
@@ -671,7 +692,7 @@ util::Status JsonStreamParser::ParseArrayValue(TokenType type) {
if (type == END_ARRAY) {
ow_->EndList();
Advance();
- return util::Status::OK;
+ return util::Status();
}
// The ParseValue call may push something onto the stack so we need to make
@@ -679,7 +700,7 @@ util::Status JsonStreamParser::ParseArrayValue(TokenType type) {
// empty-null array value is relying on this ARRAY_MID token.
stack_.push(ARRAY_MID);
util::Status result = ParseValue(type);
- if (result == util::Status::CANCELLED) {
+ if (result == util::Status(error::CANCELLED, "")) {
// If we were cancelled, pop back off the ARRAY_MID so we don't try to
// push it on again when we try over.
stack_.pop();
@@ -695,14 +716,14 @@ util::Status JsonStreamParser::ParseArrayMid(TokenType type) {
if (type == END_ARRAY) {
ow_->EndList();
Advance();
- return util::Status::OK;
+ return util::Status();
}
// Found a comma, advance past it and expect an array value next.
if (type == VALUE_SEPARATOR) {
Advance();
stack_.push(ARRAY_VALUE);
- return util::Status::OK;
+ return util::Status();
}
// Illegal token after array value.
return ReportFailure("Expected , or ] after array value.");
@@ -712,27 +733,27 @@ util::Status JsonStreamParser::ParseTrue() {
ow_->RenderBool(key_, true);
key_ = StringPiece();
p_.remove_prefix(true_len);
- return util::Status::OK;
+ return util::Status();
}
util::Status JsonStreamParser::ParseFalse() {
ow_->RenderBool(key_, false);
key_ = StringPiece();
p_.remove_prefix(false_len);
- return util::Status::OK;
+ return util::Status();
}
util::Status JsonStreamParser::ParseNull() {
ow_->RenderNull(key_);
key_ = StringPiece();
p_.remove_prefix(null_len);
- return util::Status::OK;
+ return util::Status();
}
util::Status JsonStreamParser::ParseEmptyNull() {
ow_->RenderNull(key_);
key_ = StringPiece();
- return util::Status::OK;
+ return util::Status();
}
bool JsonStreamParser::IsEmptyNullAllowed(TokenType type) {
@@ -758,7 +779,7 @@ util::Status JsonStreamParser::ReportFailure(StringPiece message) {
util::Status JsonStreamParser::ReportUnknown(StringPiece message) {
// If we aren't finishing the parse, cancel parsing and try later.
if (!finishing_) {
- return util::Status::CANCELLED;
+ return util::Status(error::CANCELLED, "");
}
if (p_.empty()) {
return ReportFailure(StrCat("Unexpected end of string. ", message));
@@ -788,11 +809,11 @@ util::Status JsonStreamParser::ParseKey() {
// we can't know if the key was complete or not.
if (!finishing_ && p_.empty()) {
p_ = original;
- return util::Status::CANCELLED;
+ return util::Status(error::CANCELLED, "");
}
// Since we aren't using the key storage, clear it out.
key_storage_.clear();
- return util::Status::OK;
+ return util::Status();
}
JsonStreamParser::TokenType JsonStreamParser::GetNextTokenType() {
diff --git a/src/google/protobuf/util/internal/json_stream_parser.h b/src/google/protobuf/util/internal/json_stream_parser.h
index 6b9d46ee..31933b67 100644
--- a/src/google/protobuf/util/internal/json_stream_parser.h
+++ b/src/google/protobuf/util/internal/json_stream_parser.h
@@ -154,6 +154,9 @@ class LIBPROTOBUF_EXPORT JsonStreamParser {
// component.
util::Status ParseNumberHelper(NumberResult* result);
+ // Parse a number as double into a NumberResult.
+ util::Status ParseDoubleHelper(const string& number, NumberResult* result);
+
// Handles a { during parsing of a value.
util::Status HandleBeginObject();
diff --git a/src/google/protobuf/util/internal/json_stream_parser_test.cc b/src/google/protobuf/util/internal/json_stream_parser_test.cc
index ca71ff24..a11e9be0 100644
--- a/src/google/protobuf/util/internal/json_stream_parser_test.cc
+++ b/src/google/protobuf/util/internal/json_stream_parser_test.cc
@@ -694,20 +694,19 @@ TEST_F(JsonStreamParserTest, ExtraCharactersAfterObject) {
}
}
-// numbers too large
-TEST_F(JsonStreamParserTest, PositiveNumberTooBig) {
- StringPiece str = "[18446744073709551616]"; // 2^64
+TEST_F(JsonStreamParserTest, PositiveNumberTooBigIsDouble) {
+ StringPiece str = "18446744073709551616"; // 2^64
for (int i = 0; i <= str.length(); ++i) {
- ow_.StartList("");
- DoErrorTest(str, i, "Unable to parse number.");
+ ow_.RenderDouble("", 18446744073709552000.0);
+ DoTest(str, i);
}
}
-TEST_F(JsonStreamParserTest, NegativeNumberTooBig) {
- StringPiece str = "[-18446744073709551616]";
+TEST_F(JsonStreamParserTest, NegativeNumberTooBigIsDouble) {
+ StringPiece str = "-18446744073709551616";
for (int i = 0; i <= str.length(); ++i) {
- ow_.StartList("");
- DoErrorTest(str, i, "Unable to parse number.");
+ ow_.RenderDouble("", -18446744073709551616.0);
+ DoTest(str, i);
}
}
diff --git a/src/google/protobuf/util/internal/proto_writer.h b/src/google/protobuf/util/internal/proto_writer.h
index 21dff88d..0db8485c 100644
--- a/src/google/protobuf/util/internal/proto_writer.h
+++ b/src/google/protobuf/util/internal/proto_writer.h
@@ -81,32 +81,32 @@ class LIBPROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter {
virtual ~ProtoWriter();
// ObjectWriter methods.
- virtual ProtoWriter* StartObject(StringPiece name);
- virtual ProtoWriter* EndObject();
- virtual ProtoWriter* StartList(StringPiece name);
- virtual ProtoWriter* EndList();
- virtual ProtoWriter* RenderBool(StringPiece name, bool value) {
+ ProtoWriter* StartObject(StringPiece name);
+ ProtoWriter* EndObject();
+ ProtoWriter* StartList(StringPiece name);
+ ProtoWriter* EndList();
+ ProtoWriter* RenderBool(StringPiece name, bool value) {
return RenderDataPiece(name, DataPiece(value));
}
- virtual ProtoWriter* RenderInt32(StringPiece name, int32 value) {
+ ProtoWriter* RenderInt32(StringPiece name, int32 value) {
return RenderDataPiece(name, DataPiece(value));
}
- virtual ProtoWriter* RenderUint32(StringPiece name, uint32 value) {
+ ProtoWriter* RenderUint32(StringPiece name, uint32 value) {
return RenderDataPiece(name, DataPiece(value));
}
- virtual ProtoWriter* RenderInt64(StringPiece name, int64 value) {
+ ProtoWriter* RenderInt64(StringPiece name, int64 value) {
return RenderDataPiece(name, DataPiece(value));
}
- virtual ProtoWriter* RenderUint64(StringPiece name, uint64 value) {
+ ProtoWriter* RenderUint64(StringPiece name, uint64 value) {
return RenderDataPiece(name, DataPiece(value));
}
- virtual ProtoWriter* RenderDouble(StringPiece name, double value) {
+ ProtoWriter* RenderDouble(StringPiece name, double value) {
return RenderDataPiece(name, DataPiece(value));
}
- virtual ProtoWriter* RenderFloat(StringPiece name, float value) {
+ ProtoWriter* RenderFloat(StringPiece name, float value) {
return RenderDataPiece(name, DataPiece(value));
}
- virtual ProtoWriter* RenderString(StringPiece name, StringPiece value) {
+ ProtoWriter* RenderString(StringPiece name, StringPiece value) {
return RenderDataPiece(name,
DataPiece(value, use_strict_base64_decoding()));
}
@@ -114,7 +114,7 @@ class LIBPROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter {
return RenderDataPiece(
name, DataPiece(value, false, use_strict_base64_decoding()));
}
- virtual ProtoWriter* RenderNull(StringPiece name) {
+ ProtoWriter* RenderNull(StringPiece name) {
return RenderDataPiece(name, DataPiece::NullData());
}
@@ -242,7 +242,7 @@ class LIBPROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter {
ProtoWriter(const TypeInfo* typeinfo, const google::protobuf::Type& type,
strings::ByteSink* output, ErrorListener* listener);
- virtual ProtoElement* element() { return element_.get(); }
+ ProtoElement* element() { return element_.get(); }
// Helper methods for calling ErrorListener. See error_listener.h.
void InvalidName(StringPiece unknown_name, StringPiece message);
diff --git a/src/google/protobuf/util/internal/protostream_objectsource.cc b/src/google/protobuf/util/internal/protostream_objectsource.cc
index a970dc12..02360a1a 100644
--- a/src/google/protobuf/util/internal/protostream_objectsource.cc
+++ b/src/google/protobuf/util/internal/protostream_objectsource.cc
@@ -120,9 +120,12 @@ ProtoStreamObjectSource::ProtoStreamObjectSource(
own_typeinfo_(true),
type_(type),
use_lower_camel_for_enums_(false),
+ use_ints_for_enums_(false),
+ preserve_proto_field_names_(false),
recursion_depth_(0),
max_recursion_depth_(kDefaultMaxRecursionDepth),
render_unknown_fields_(false),
+ render_unknown_enum_values_(true),
add_trailing_zeros_for_timestamp_and_duration_(false) {
GOOGLE_LOG_IF(DFATAL, stream == NULL) << "Input stream is NULL.";
}
@@ -135,9 +138,12 @@ ProtoStreamObjectSource::ProtoStreamObjectSource(
own_typeinfo_(false),
type_(type),
use_lower_camel_for_enums_(false),
+ use_ints_for_enums_(false),
+ preserve_proto_field_names_(false),
recursion_depth_(0),
max_recursion_depth_(kDefaultMaxRecursionDepth),
render_unknown_fields_(false),
+ render_unknown_enum_values_(true),
add_trailing_zeros_for_timestamp_and_duration_(false) {
GOOGLE_LOG_IF(DFATAL, stream == NULL) << "Input stream is NULL.";
}
@@ -198,7 +204,11 @@ Status ProtoStreamObjectSource::WriteMessage(const google::protobuf::Type& type,
last_tag = tag;
field = FindAndVerifyField(type, tag);
if (field != NULL) {
- field_name = field->json_name();
+ if (preserve_proto_field_names_) {
+ field_name = field->name();
+ } else {
+ field_name = field->json_name();
+ }
}
}
if (field == NULL) {
@@ -232,7 +242,7 @@ Status ProtoStreamObjectSource::WriteMessage(const google::protobuf::Type& type,
if (include_start_and_end) {
ow->EndObject();
}
- return Status::OK;
+ return util::Status();
}
StatusOr<uint32> ProtoStreamObjectSource::RenderList(
@@ -314,7 +324,7 @@ Status ProtoStreamObjectSource::RenderPacked(
RETURN_IF_ERROR(RenderField(field, StringPiece(), ow));
}
stream_->PopLimit(old_limit);
- return Status::OK;
+ return util::Status();
}
Status ProtoStreamObjectSource::RenderTimestamp(
@@ -338,7 +348,7 @@ Status ProtoStreamObjectSource::RenderTimestamp(
ow->RenderString(field_name,
::google::protobuf::internal::FormatTime(seconds, nanos));
- return Status::OK;
+ return util::Status();
}
Status ProtoStreamObjectSource::RenderDuration(
@@ -379,7 +389,7 @@ Status ProtoStreamObjectSource::RenderDuration(
FormatNanos(nanos, os->add_trailing_zeros_for_timestamp_and_duration_)
.c_str());
ow->RenderString(field_name, formatted_duration);
- return Status::OK;
+ return util::Status();
}
Status ProtoStreamObjectSource::RenderDouble(const ProtoStreamObjectSource* os,
@@ -393,7 +403,7 @@ Status ProtoStreamObjectSource::RenderDouble(const ProtoStreamObjectSource* os,
os->stream_->ReadTag();
}
ow->RenderDouble(field_name, bit_cast<double>(buffer64));
- return Status::OK;
+ return util::Status();
}
Status ProtoStreamObjectSource::RenderFloat(const ProtoStreamObjectSource* os,
@@ -407,7 +417,7 @@ Status ProtoStreamObjectSource::RenderFloat(const ProtoStreamObjectSource* os,
os->stream_->ReadTag();
}
ow->RenderFloat(field_name, bit_cast<float>(buffer32));
- return Status::OK;
+ return util::Status();
}
Status ProtoStreamObjectSource::RenderInt64(const ProtoStreamObjectSource* os,
@@ -421,7 +431,7 @@ Status ProtoStreamObjectSource::RenderInt64(const ProtoStreamObjectSource* os,
os->stream_->ReadTag();
}
ow->RenderInt64(field_name, bit_cast<int64>(buffer64));
- return Status::OK;
+ return util::Status();
}
Status ProtoStreamObjectSource::RenderUInt64(const ProtoStreamObjectSource* os,
@@ -435,7 +445,7 @@ Status ProtoStreamObjectSource::RenderUInt64(const ProtoStreamObjectSource* os,
os->stream_->ReadTag();
}
ow->RenderUint64(field_name, bit_cast<uint64>(buffer64));
- return Status::OK;
+ return util::Status();
}
Status ProtoStreamObjectSource::RenderInt32(const ProtoStreamObjectSource* os,
@@ -449,7 +459,7 @@ Status ProtoStreamObjectSource::RenderInt32(const ProtoStreamObjectSource* os,
os->stream_->ReadTag();
}
ow->RenderInt32(field_name, bit_cast<int32>(buffer32));
- return Status::OK;
+ return util::Status();
}
Status ProtoStreamObjectSource::RenderUInt32(const ProtoStreamObjectSource* os,
@@ -463,7 +473,7 @@ Status ProtoStreamObjectSource::RenderUInt32(const ProtoStreamObjectSource* os,
os->stream_->ReadTag();
}
ow->RenderUint32(field_name, bit_cast<uint32>(buffer32));
- return Status::OK;
+ return util::Status();
}
Status ProtoStreamObjectSource::RenderBool(const ProtoStreamObjectSource* os,
@@ -478,7 +488,7 @@ Status ProtoStreamObjectSource::RenderBool(const ProtoStreamObjectSource* os,
os->stream_->ReadTag();
}
ow->RenderBool(field_name, buffer64 != 0);
- return Status::OK;
+ return util::Status();
}
Status ProtoStreamObjectSource::RenderString(const ProtoStreamObjectSource* os,
@@ -494,7 +504,7 @@ Status ProtoStreamObjectSource::RenderString(const ProtoStreamObjectSource* os,
os->stream_->ReadTag();
}
ow->RenderString(field_name, str);
- return Status::OK;
+ return util::Status();
}
Status ProtoStreamObjectSource::RenderBytes(const ProtoStreamObjectSource* os,
@@ -510,7 +520,7 @@ Status ProtoStreamObjectSource::RenderBytes(const ProtoStreamObjectSource* os,
os->stream_->ReadTag();
}
ow->RenderBytes(field_name, str);
- return Status::OK;
+ return util::Status();
}
Status ProtoStreamObjectSource::RenderStruct(const ProtoStreamObjectSource* os,
@@ -529,7 +539,7 @@ Status ProtoStreamObjectSource::RenderStruct(const ProtoStreamObjectSource* os,
}
}
ow->EndObject();
- return Status::OK;
+ return util::Status();
}
Status ProtoStreamObjectSource::RenderStructValue(
@@ -545,7 +555,7 @@ Status ProtoStreamObjectSource::RenderStructValue(
}
RETURN_IF_ERROR(os->RenderField(field, field_name, ow));
}
- return Status::OK;
+ return util::Status();
}
// TODO(skarvaje): Avoid code duplication of for loops and SkipField logic.
@@ -558,7 +568,7 @@ Status ProtoStreamObjectSource::RenderStructListValue(
if (tag == 0) {
ow->StartList(field_name);
ow->EndList();
- return Status::OK;
+ return util::Status();
}
while (tag != 0) {
@@ -570,7 +580,7 @@ Status ProtoStreamObjectSource::RenderStructListValue(
}
ASSIGN_OR_RETURN(tag, os->RenderList(field, field_name, tag, ow));
}
- return Status::OK;
+ return util::Status();
}
Status ProtoStreamObjectSource::RenderAny(const ProtoStreamObjectSource* os,
@@ -612,7 +622,7 @@ Status ProtoStreamObjectSource::RenderAny(const ProtoStreamObjectSource* os,
ow->RenderString("@type", type_url);
}
ow->EndObject();
- return util::Status::OK;
+ return util::Status();
}
// If there is a value but no type, we cannot render it, so report an error.
@@ -677,7 +687,7 @@ Status ProtoStreamObjectSource::RenderFieldMask(
combined.append(ConvertFieldMaskPath(str, &ToCamelCase));
}
ow->RenderString(field_name, combined);
- return Status::OK;
+ return util::Status();
}
@@ -773,7 +783,7 @@ Status ProtoStreamObjectSource::RenderField(
// Render all other non-message types.
return RenderNonMessageField(field, field_name, ow);
}
- return Status::OK;
+ return util::Status();
}
Status ProtoStreamObjectSource::RenderNonMessageField(
@@ -869,14 +879,17 @@ Status ProtoStreamObjectSource::RenderNonMessageField(
const google::protobuf::EnumValue* enum_value =
FindEnumValueByNumber(*en, buffer32);
if (enum_value != NULL) {
- if (use_lower_camel_for_enums_)
+ if (use_ints_for_enums_) {
+ ow->RenderInt32(field_name, buffer32);
+ } else if (use_lower_camel_for_enums_) {
ow->RenderString(field_name, ToCamelCase(enum_value->name()));
- else
+ } else {
ow->RenderString(field_name, enum_value->name());
- } else {
+ }
+ } else if (render_unknown_enum_values_) {
ow->RenderInt32(field_name, buffer32);
}
- } else {
+ } else if (render_unknown_enum_values_) {
ow->RenderInt32(field_name, buffer32);
}
break;
@@ -896,7 +909,7 @@ Status ProtoStreamObjectSource::RenderNonMessageField(
default:
break;
}
- return Status::OK;
+ return util::Status();
}
// TODO(skarvaje): Fix this to avoid code duplication.
@@ -1024,15 +1037,8 @@ bool ProtoStreamObjectSource::IsMap(
const google::protobuf::Field& field) const {
const google::protobuf::Type* field_type =
typeinfo_->GetTypeByTypeUrl(field.type_url());
-
- // TODO(xiaofeng): Unify option names.
return field.kind() == google::protobuf::Field_Kind_TYPE_MESSAGE &&
- (GetBoolOptionOrDefault(field_type->options(),
- "google.protobuf.MessageOptions.map_entry",
- false) ||
- GetBoolOptionOrDefault(field_type->options(), "map_entry", false) ||
- GetBoolOptionOrDefault(field_type->options(),
- "proto2.MessageOptions.map_entry", false));
+ google::protobuf::util::converter::IsMap(field, *field_type);
}
std::pair<int64, int32> ProtoStreamObjectSource::ReadSecondsAndNanos(
@@ -1072,7 +1078,7 @@ Status ProtoStreamObjectSource::IncrementRecursionDepth(
StrCat("Message too deep. Max recursion depth reached for type '",
type_name, "', field '", field_name, "'"));
}
- return Status::OK;
+ return util::Status();
}
namespace {
@@ -1128,4 +1134,3 @@ const string FormatNanos(uint32 nanos, bool with_trailing_zeros) {
} // namespace util
} // namespace protobuf
} // namespace google
-
diff --git a/src/google/protobuf/util/internal/protostream_objectsource.h b/src/google/protobuf/util/internal/protostream_objectsource.h
index 88ca652b..b56efdf4 100644
--- a/src/google/protobuf/util/internal/protostream_objectsource.h
+++ b/src/google/protobuf/util/internal/protostream_objectsource.h
@@ -110,6 +110,15 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectSource : public ObjectSource {
use_lower_camel_for_enums_ = value;
}
+ // Sets whether to always output enums as ints, by default this is off, and
+ // enums are rendered as strings.
+ void set_use_ints_for_enums(bool value) { use_ints_for_enums_ = value; }
+
+ // Sets whether to use original proto field names
+ void set_preserve_proto_field_names(bool value) {
+ preserve_proto_field_names_ = value;
+ }
+
// Sets the max recursion depth of proto message to be deserialized. Proto
// messages over this depth will fail to be deserialized.
// Default value is 64.
@@ -285,6 +294,12 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectSource : public ObjectSource {
// Whether to render enums using lowerCamelCase. Defaults to false.
bool use_lower_camel_for_enums_;
+ // Whether to render enums as ints always. Defaults to false.
+ bool use_ints_for_enums_;
+
+ // Whether to preserve proto field names
+ bool preserve_proto_field_names_;
+
// Tracks current recursion depth.
mutable int recursion_depth_;
@@ -294,6 +309,9 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectSource : public ObjectSource {
// Whether to render unknown fields.
bool render_unknown_fields_;
+ // Whether to render unknown enum values.
+ bool render_unknown_enum_values_;
+
// Whether to add trailing zeros for timestamp and duration.
bool add_trailing_zeros_for_timestamp_and_duration_;
diff --git a/src/google/protobuf/util/internal/protostream_objectsource_test.cc b/src/google/protobuf/util/internal/protostream_objectsource_test.cc
index bf29c17a..36bb1ba9 100644
--- a/src/google/protobuf/util/internal/protostream_objectsource_test.cc
+++ b/src/google/protobuf/util/internal/protostream_objectsource_test.cc
@@ -102,7 +102,9 @@ class ProtostreamObjectSourceTest
mock_(),
ow_(&mock_),
use_lower_camel_for_enums_(false),
- add_trailing_zeros_(false) {
+ use_ints_for_enums_(false),
+ add_trailing_zeros_(false),
+ render_unknown_enum_values_(true) {
helper_.ResetTypeInfo(Book::descriptor(), Proto3Message::descriptor());
}
@@ -110,11 +112,11 @@ class ProtostreamObjectSourceTest
void DoTest(const Message& msg, const Descriptor* descriptor) {
Status status = ExecuteTest(msg, descriptor);
- EXPECT_EQ(Status::OK, status);
+ EXPECT_EQ(util::Status(), status);
}
Status ExecuteTest(const Message& msg, const Descriptor* descriptor) {
- ostringstream oss;
+ std::ostringstream oss;
msg.SerializePartialToOstream(&oss);
string proto = oss.str();
ArrayInputStream arr_stream(proto.data(), proto.size());
@@ -123,6 +125,7 @@ class ProtostreamObjectSourceTest
google::protobuf::scoped_ptr<ProtoStreamObjectSource> os(
helper_.NewProtoSource(&in_stream, GetTypeUrl(descriptor)));
if (use_lower_camel_for_enums_) os->set_use_lower_camel_for_enums(true);
+ if (use_ints_for_enums_) os->set_use_ints_for_enums(true);
os->set_max_recursion_depth(64);
return os->WriteTo(&mock_);
}
@@ -270,14 +273,22 @@ class ProtostreamObjectSourceTest
void UseLowerCamelForEnums() { use_lower_camel_for_enums_ = true; }
+ void UseIntsForEnums() { use_ints_for_enums_ = true; }
+
void AddTrailingZeros() { add_trailing_zeros_ = true; }
+ void SetRenderUnknownEnumValues(bool value) {
+ render_unknown_enum_values_ = value;
+ }
+
testing::TypeInfoTestHelper helper_;
::testing::NiceMock<MockObjectWriter> mock_;
ExpectingObjectWriter ow_;
bool use_lower_camel_for_enums_;
+ bool use_ints_for_enums_;
bool add_trailing_zeros_;
+ bool render_unknown_enum_values_;
};
INSTANTIATE_TEST_CASE_P(DifferentTypeInfoSourceTest,
@@ -498,12 +509,37 @@ TEST_P(ProtostreamObjectSourceTest, EnumCaseIsUnchangedByDefault) {
DoTest(book, Book::descriptor());
}
-TEST_P(ProtostreamObjectSourceTest, UnknownEnum) {
+TEST_P(ProtostreamObjectSourceTest, UseIntsForEnumsTest) {
+ Book book;
+ book.set_type(Book::ACTION_AND_ADVENTURE);
+
+ UseIntsForEnums();
+
+ ow_.StartObject("")->RenderInt32("type", 3)->EndObject();
+ DoTest(book, Book::descriptor());
+}
+
+TEST_P(ProtostreamObjectSourceTest,
+ UnknownEnumAreDroppedWhenRenderUnknownEnumValuesIsUnset) {
Proto3Message message;
message.set_enum_value(static_cast<Proto3Message::NestedEnum>(1234));
- ow_.StartObject("")
- ->RenderInt32("enumValue", 1234)
- ->EndObject();
+
+ SetRenderUnknownEnumValues(false);
+
+ // Unknown enum values are not output.
+ ow_.StartObject("")->EndObject();
+ DoTest(message, Proto3Message::descriptor());
+}
+
+TEST_P(ProtostreamObjectSourceTest,
+ UnknownEnumAreOutputWhenRenderUnknownEnumValuesIsSet) {
+ Proto3Message message;
+ message.set_enum_value(static_cast<Proto3Message::NestedEnum>(1234));
+
+ SetRenderUnknownEnumValues(true);
+
+ // Unknown enum values are output.
+ ow_.StartObject("")->RenderInt32("enumValue", 1234)->EndObject();
DoTest(message, Proto3Message::descriptor());
}
diff --git a/src/google/protobuf/util/internal/protostream_objectwriter.cc b/src/google/protobuf/util/internal/protostream_objectwriter.cc
index c37e671c..97f96819 100644
--- a/src/google/protobuf/util/internal/protostream_objectwriter.cc
+++ b/src/google/protobuf/util/internal/protostream_objectwriter.cc
@@ -173,7 +173,7 @@ Status GetNanosFromStringPiece(StringPiece s_nanos,
*nanos = i_nanos * conversion;
}
- return Status::OK;
+ return Status();
}
} // namespace
@@ -409,7 +409,7 @@ void ProtoStreamObjectWriter::AnyWriter::Event::DeepCopy() {
// string value stays valid, we make a copy of the string value and update
// DataPiece to reference our own copy.
if (value_.type() == DataPiece::TYPE_STRING) {
- value_.str().AppendToString(&value_storage_);
+ StrAppend(&value_storage_, value_.str());
value_ = DataPiece(value_storage_, value_.use_strict_base64_decoding());
} else if (value_.type() == DataPiece::TYPE_BYTES) {
value_storage_ = value_.ToBytes().ValueOrDie();
@@ -862,7 +862,7 @@ Status ProtoStreamObjectWriter::RenderStructValue(ProtoStreamObjectWriter* ow,
ow->ProtoWriter::RenderDataPiece(
"string_value",
DataPiece(SimpleItoa(int_value.ValueOrDie()), true));
- return Status::OK;
+ return Status();
}
}
struct_field_name = "number_value";
@@ -877,13 +877,22 @@ Status ProtoStreamObjectWriter::RenderStructValue(ProtoStreamObjectWriter* ow,
ow->ProtoWriter::RenderDataPiece(
"string_value",
DataPiece(SimpleItoa(int_value.ValueOrDie()), true));
- return Status::OK;
+ return Status();
}
}
struct_field_name = "number_value";
break;
}
case DataPiece::TYPE_DOUBLE: {
+ if (ow->options_.struct_integers_as_strings) {
+ StatusOr<double> double_value = data.ToDouble();
+ if (double_value.ok()) {
+ ow->ProtoWriter::RenderDataPiece(
+ "string_value",
+ DataPiece(SimpleDtoa(double_value.ValueOrDie()), true));
+ return Status();
+ }
+ }
struct_field_name = "number_value";
break;
}
@@ -906,12 +915,12 @@ Status ProtoStreamObjectWriter::RenderStructValue(ProtoStreamObjectWriter* ow,
}
}
ow->ProtoWriter::RenderDataPiece(struct_field_name, data);
- return Status::OK;
+ return Status();
}
Status ProtoStreamObjectWriter::RenderTimestamp(ProtoStreamObjectWriter* ow,
const DataPiece& data) {
- if (data.type() == DataPiece::TYPE_NULL) return Status::OK;
+ if (data.type() == DataPiece::TYPE_NULL) return Status();
if (data.type() != DataPiece::TYPE_STRING) {
return Status(INVALID_ARGUMENT,
StrCat("Invalid data type for timestamp, value is ",
@@ -930,19 +939,19 @@ Status ProtoStreamObjectWriter::RenderTimestamp(ProtoStreamObjectWriter* ow,
ow->ProtoWriter::RenderDataPiece("seconds", DataPiece(seconds));
ow->ProtoWriter::RenderDataPiece("nanos", DataPiece(nanos));
- return Status::OK;
+ return Status();
}
static inline util::Status RenderOneFieldPath(ProtoStreamObjectWriter* ow,
StringPiece path) {
ow->ProtoWriter::RenderDataPiece(
"paths", DataPiece(ConvertFieldMaskPath(path, &ToSnakeCase), true));
- return Status::OK;
+ return Status();
}
Status ProtoStreamObjectWriter::RenderFieldMask(ProtoStreamObjectWriter* ow,
const DataPiece& data) {
- if (data.type() == DataPiece::TYPE_NULL) return Status::OK;
+ if (data.type() == DataPiece::TYPE_NULL) return Status();
if (data.type() != DataPiece::TYPE_STRING) {
return Status(INVALID_ARGUMENT,
StrCat("Invalid data type for field mask, value is ",
@@ -953,13 +962,13 @@ Status ProtoStreamObjectWriter::RenderFieldMask(ProtoStreamObjectWriter* ow,
// conversions as much as possible. Because ToSnakeCase sometimes returns the
// wrong value.
google::protobuf::scoped_ptr<ResultCallback1<util::Status, StringPiece> > callback(
- NewPermanentCallback(&RenderOneFieldPath, ow));
+ ::google::protobuf::NewPermanentCallback(&RenderOneFieldPath, ow));
return DecodeCompactFieldMaskPaths(data.str(), callback.get());
}
Status ProtoStreamObjectWriter::RenderDuration(ProtoStreamObjectWriter* ow,
const DataPiece& data) {
- if (data.type() == DataPiece::TYPE_NULL) return Status::OK;
+ if (data.type() == DataPiece::TYPE_NULL) return Status();
if (data.type() != DataPiece::TYPE_STRING) {
return Status(INVALID_ARGUMENT,
StrCat("Invalid data type for duration, value is ",
@@ -1004,14 +1013,14 @@ Status ProtoStreamObjectWriter::RenderDuration(ProtoStreamObjectWriter* ow,
ow->ProtoWriter::RenderDataPiece("seconds", DataPiece(seconds));
ow->ProtoWriter::RenderDataPiece("nanos", DataPiece(nanos));
- return Status::OK;
+ return Status();
}
Status ProtoStreamObjectWriter::RenderWrapperType(ProtoStreamObjectWriter* ow,
const DataPiece& data) {
- if (data.type() == DataPiece::TYPE_NULL) return Status::OK;
+ if (data.type() == DataPiece::TYPE_NULL) return Status();
ow->ProtoWriter::RenderDataPiece("value", data);
- return Status::OK;
+ return Status();
}
ProtoStreamObjectWriter* ProtoStreamObjectWriter::RenderDataPiece(
@@ -1238,13 +1247,7 @@ bool ProtoStreamObjectWriter::IsMap(const google::protobuf::Field& field) {
const google::protobuf::Type* field_type =
typeinfo()->GetTypeByTypeUrl(field.type_url());
- // TODO(xiaofeng): Unify option names.
- return GetBoolOptionOrDefault(field_type->options(),
- "google.protobuf.MessageOptions.map_entry",
- false) ||
- GetBoolOptionOrDefault(field_type->options(), "map_entry", false) ||
- GetBoolOptionOrDefault(field_type->options(),
- "proto2.MessageOptions.map_entry", false);
+ return google::protobuf::util::converter::IsMap(field, *field_type);
}
bool ProtoStreamObjectWriter::IsAny(const google::protobuf::Field& field) {
@@ -1269,4 +1272,3 @@ bool ProtoStreamObjectWriter::IsStructListValue(
} // namespace util
} // namespace protobuf
} // namespace google
-
diff --git a/src/google/protobuf/util/internal/protostream_objectwriter.h b/src/google/protobuf/util/internal/protostream_objectwriter.h
index 732971e1..ab534912 100644
--- a/src/google/protobuf/util/internal/protostream_objectwriter.h
+++ b/src/google/protobuf/util/internal/protostream_objectwriter.h
@@ -76,11 +76,14 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectWriter : public ProtoWriter {
public:
// Options that control ProtoStreamObjectWriter class's behavior.
struct Options {
- // Treats integer inputs in google.protobuf.Struct as strings. Normally,
- // integer values are returned in double field "number_value" of
+ // Treats numeric inputs in google.protobuf.Struct as strings. Normally,
+ // numeric values are returned in double field "number_value" of
// google.protobuf.Struct. However, this can cause precision loss for
- // int64/uint64 inputs. This option is provided for cases that want to
- // preserve integer precision.
+ // int64/uint64/double inputs. This option is provided for cases that want
+ // to preserve number precision.
+ //
+ // TODO(skarvaje): Rename to struct_numbers_as_strings as it covers double
+ // as well.
bool struct_integers_as_strings;
// Not treat unknown fields as an error. If there is an unknown fields,
diff --git a/src/google/protobuf/util/internal/protostream_objectwriter_test.cc b/src/google/protobuf/util/internal/protostream_objectwriter_test.cc
index a9b15e68..87d35b08 100644
--- a/src/google/protobuf/util/internal/protostream_objectwriter_test.cc
+++ b/src/google/protobuf/util/internal/protostream_objectwriter_test.cc
@@ -74,6 +74,8 @@ using google::protobuf::testing::Primitive;
using google::protobuf::testing::Proto3Message;
using google::protobuf::testing::Publisher;
using google::protobuf::testing::StructType;
+using google::protobuf::testing::TestJsonName1;
+using google::protobuf::testing::TestJsonName2;
using google::protobuf::testing::TimestampDuration;
using google::protobuf::testing::ValueWrapper;
using google::protobuf::testing::oneofs::OneOfsRequest;
@@ -271,6 +273,22 @@ TEST_P(ProtoStreamObjectWriterTest, CustomJsonName) {
CheckOutput(book);
}
+// Test that two messages can have different fields mapped to the same JSON
+// name. See: https://github.com/google/protobuf/issues/1415
+TEST_P(ProtoStreamObjectWriterTest, ConflictingJsonName) {
+ ResetTypeInfo(TestJsonName1::descriptor());
+ TestJsonName1 message1;
+ message1.set_one_value(12345);
+ ow_->StartObject("")->RenderInt32("value", 12345)->EndObject();
+ CheckOutput(message1);
+
+ ResetTypeInfo(TestJsonName2::descriptor());
+ TestJsonName2 message2;
+ message2.set_another_value(12345);
+ ow_->StartObject("")->RenderInt32("value", 12345)->EndObject();
+ CheckOutput(message2);
+}
+
TEST_P(ProtoStreamObjectWriterTest, IntEnumValuesAreAccepted) {
Book book;
book.set_title("Some Book");
@@ -1593,7 +1611,7 @@ TEST_P(ProtoStreamObjectWriterStructTest, RepeatedStructMapObjectKeyTest) {
TEST_P(ProtoStreamObjectWriterStructTest, OptionStructIntAsStringsTest) {
StructType struct_type;
google::protobuf::Struct* s = struct_type.mutable_object();
- s->mutable_fields()->operator[]("k1").set_number_value(123);
+ s->mutable_fields()->operator[]("k1").set_string_value("123");
s->mutable_fields()->operator[]("k2").set_bool_value(true);
s->mutable_fields()->operator[]("k3").set_string_value("-222222222");
s->mutable_fields()->operator[]("k4").set_string_value("33333333");
diff --git a/src/google/protobuf/util/internal/testdata/books.proto b/src/google/protobuf/util/internal/testdata/books.proto
index 9fe4f7aa..869271f4 100644
--- a/src/google/protobuf/util/internal/testdata/books.proto
+++ b/src/google/protobuf/util/internal/testdata/books.proto
@@ -190,3 +190,12 @@ message Cyclic {
repeated Author m_author = 5;
optional Cyclic m_cyclic = 4;
}
+
+// Test that two messages can have different fields mapped to the same JSON
+// name. See: https://github.com/google/protobuf/issues/1415
+message TestJsonName1 {
+ optional int32 one_value = 1 [json_name = "value"];
+}
+message TestJsonName2 {
+ optional int32 another_value = 1 [json_name = "value"];
+}
diff --git a/src/google/protobuf/util/internal/type_info.cc b/src/google/protobuf/util/internal/type_info.cc
index 17d58475..85d0d5c9 100644
--- a/src/google/protobuf/util/internal/type_info.cc
+++ b/src/google/protobuf/util/internal/type_info.cc
@@ -107,12 +107,14 @@ class TypeInfoForTypeResolver : public TypeInfo {
virtual const google::protobuf::Field* FindField(
const google::protobuf::Type* type, StringPiece camel_case_name) const {
- if (indexed_types_.find(type) == indexed_types_.end()) {
- PopulateNameLookupTable(type);
- indexed_types_.insert(type);
- }
+ std::map<const google::protobuf::Type*, CamelCaseNameTable>::const_iterator
+ it = indexed_types_.find(type);
+ const CamelCaseNameTable& camel_case_name_table =
+ (it == indexed_types_.end())
+ ? PopulateNameLookupTable(type, &indexed_types_[type])
+ : it->second;
StringPiece name =
- FindWithDefault(camel_case_name_table_, camel_case_name, StringPiece());
+ FindWithDefault(camel_case_name_table, camel_case_name, StringPiece());
if (name.empty()) {
// Didn't find a mapping. Use whatever provided.
name = camel_case_name;
@@ -123,6 +125,7 @@ class TypeInfoForTypeResolver : public TypeInfo {
private:
typedef util::StatusOr<const google::protobuf::Type*> StatusOrType;
typedef util::StatusOr<const google::protobuf::Enum*> StatusOrEnum;
+ typedef std::map<StringPiece, StringPiece> CamelCaseNameTable;
template <typename T>
static void DeleteCachedTypes(std::map<StringPiece, T>* cached_types) {
@@ -134,32 +137,35 @@ class TypeInfoForTypeResolver : public TypeInfo {
}
}
- void PopulateNameLookupTable(const google::protobuf::Type* type) const {
+ const CamelCaseNameTable& PopulateNameLookupTable(
+ const google::protobuf::Type* type,
+ CamelCaseNameTable* camel_case_name_table) const {
for (int i = 0; i < type->fields_size(); ++i) {
const google::protobuf::Field& field = type->fields(i);
StringPiece name = field.name();
StringPiece camel_case_name = field.json_name();
- const StringPiece* existing = InsertOrReturnExisting(
- &camel_case_name_table_, camel_case_name, name);
+ const StringPiece* existing =
+ InsertOrReturnExisting(camel_case_name_table, camel_case_name, name);
if (existing && *existing != name) {
GOOGLE_LOG(WARNING) << "Field '" << name << "' and '" << *existing
<< "' map to the same camel case name '" << camel_case_name
<< "'.";
}
}
+ return *camel_case_name_table;
}
TypeResolver* type_resolver_;
// Stores string values that will be referenced by StringPieces in
- // cached_types_, cached_enums_ and camel_case_name_table_.
+ // cached_types_, cached_enums_.
mutable std::set<string> string_storage_;
mutable std::map<StringPiece, StatusOrType> cached_types_;
mutable std::map<StringPiece, StatusOrEnum> cached_enums_;
- mutable std::set<const google::protobuf::Type*> indexed_types_;
- mutable std::map<StringPiece, StringPiece> camel_case_name_table_;
+ mutable std::map<const google::protobuf::Type*, CamelCaseNameTable>
+ indexed_types_;
};
} // namespace
diff --git a/src/google/protobuf/util/internal/utility.cc b/src/google/protobuf/util/internal/utility.cc
index 05759e85..11780ee8 100644
--- a/src/google/protobuf/util/internal/utility.cc
+++ b/src/google/protobuf/util/internal/utility.cc
@@ -48,16 +48,6 @@ namespace protobuf {
namespace util {
namespace converter {
-namespace {
-const StringPiece SkipWhiteSpace(StringPiece str) {
- StringPiece::size_type i;
- for (i = 0; i < str.size() && isspace(str[i]); ++i) {
- }
- GOOGLE_DCHECK(i == str.size() || !isspace(str[i]));
- return str.substr(i);
-}
-} // namespace
-
bool GetBoolOptionOrDefault(
const google::protobuf::RepeatedPtrField<google::protobuf::Option>& options,
const string& option_name, bool default_value) {
@@ -134,7 +124,10 @@ const StringPiece GetTypeWithoutUrl(StringPiece type_url) {
return type_url.substr(kTypeUrlSize + 1);
} else {
size_t idx = type_url.rfind('/');
- return type_url.substr(idx + 1);
+ if (idx != type_url.npos) {
+ type_url.remove_prefix(idx + 1);
+ }
+ return type_url;
}
}
@@ -356,23 +349,25 @@ bool IsValidBoolString(const string& bool_string) {
bool IsMap(const google::protobuf::Field& field,
const google::protobuf::Type& type) {
- return (
- field.cardinality() ==
- google::protobuf::Field_Cardinality_CARDINALITY_REPEATED &&
- (GetBoolOptionOrDefault(
- type.options(), "google.protobuf.MessageOptions.map_entry", false) ||
- GetBoolOptionOrDefault(type.options(), "proto2.MessageOptions.map_entry",
- false)));
+ return field.cardinality() ==
+ google::protobuf::Field_Cardinality_CARDINALITY_REPEATED &&
+ (GetBoolOptionOrDefault(type.options(), "map_entry", false) ||
+ GetBoolOptionOrDefault(type.options(),
+ "google.protobuf.MessageOptions.map_entry", false) ||
+ GetBoolOptionOrDefault(type.options(),
+ "google.protobuf.MessageOptions.map_entry",
+ false));
}
bool IsMessageSetWireFormat(const google::protobuf::Type& type) {
- return (
- GetBoolOptionOrDefault(
- type.options(),
- "google.protobuf.MessageOptions.message_set_wire_format", false) ||
- GetBoolOptionOrDefault(type.options(),
- "proto2.MessageOptions.message_set_wire_format",
- false));
+ return GetBoolOptionOrDefault(type.options(), "message_set_wire_format",
+ false) ||
+ GetBoolOptionOrDefault(type.options(),
+ "google.protobuf.MessageOptions.message_set_wire_format",
+ false) ||
+ GetBoolOptionOrDefault(
+ type.options(),
+ "google.protobuf.MessageOptions.message_set_wire_format", false);
}
string DoubleAsString(double value) {
@@ -412,4 +407,3 @@ bool SafeStrToFloat(StringPiece str, float* value) {
} // namespace util
} // namespace protobuf
} // namespace google
-
diff --git a/src/google/protobuf/util/json_format_proto3.proto b/src/google/protobuf/util/json_format_proto3.proto
index 3835b30e..8a0441c8 100644
--- a/src/google/protobuf/util/json_format_proto3.proto
+++ b/src/google/protobuf/util/json_format_proto3.proto
@@ -32,6 +32,8 @@ syntax = "proto3";
package proto3;
+option java_package = "com.google.protobuf.util";
+option java_outer_classname = "JsonFormatProto3";
import "google/protobuf/duration.proto";
import "google/protobuf/timestamp.proto";
diff --git a/src/google/protobuf/util/json_util.cc b/src/google/protobuf/util/json_util.cc
index d7ac2dba..ce3569ce 100644
--- a/src/google/protobuf/util/json_util.cc
+++ b/src/google/protobuf/util/json_util.cc
@@ -49,22 +49,27 @@ namespace protobuf {
namespace util {
namespace internal {
+ZeroCopyStreamByteSink::~ZeroCopyStreamByteSink() {
+ stream_->BackUp(buffer_size_);
+}
+
void ZeroCopyStreamByteSink::Append(const char* bytes, size_t len) {
- while (len > 0) {
- void* buffer;
- int length;
- if (!stream_->Next(&buffer, &length)) {
- // There isn't a way for ByteSink to report errors.
+ while (true) {
+ if (len <= buffer_size_) {
+ memcpy(buffer_, bytes, len);
+ buffer_ = static_cast<char*>(buffer_) + len;
+ buffer_size_ -= len;
return;
}
- if (len < length) {
- memcpy(buffer, bytes, len);
- stream_->BackUp(length - len);
- break;
- } else {
- memcpy(buffer, bytes, length);
- bytes += length;
- len -= length;
+ if (buffer_size_ > 0) {
+ memcpy(buffer_, bytes, buffer_size_);
+ bytes += buffer_size_;
+ len -= buffer_size_;
+ }
+ if (!stream_->Next(&buffer_, &buffer_size_)) {
+ // There isn't a way for ByteSink to report errors.
+ buffer_size_ = 0;
+ return;
}
}
}
@@ -79,12 +84,17 @@ util::Status BinaryToJsonStream(TypeResolver* resolver,
google::protobuf::Type type;
RETURN_IF_ERROR(resolver->ResolveMessageType(type_url, &type));
converter::ProtoStreamObjectSource proto_source(&in_stream, resolver, type);
+ proto_source.set_use_ints_for_enums(options.always_print_enums_as_ints);
+ proto_source.set_preserve_proto_field_names(
+ options.preserve_proto_field_names);
io::CodedOutputStream out_stream(json_output);
converter::JsonObjectWriter json_writer(options.add_whitespace ? " " : "",
&out_stream);
if (options.always_print_primitive_fields) {
converter::DefaultValueObjectWriter default_value_writer(
resolver, type, &json_writer);
+ default_value_writer.set_preserve_proto_field_names(
+ options.preserve_proto_field_names);
return proto_source.WriteTo(&default_value_writer);
} else {
return proto_source.WriteTo(&json_writer);
@@ -105,7 +115,7 @@ util::Status BinaryToJsonString(TypeResolver* resolver,
namespace {
class StatusErrorListener : public converter::ErrorListener {
public:
- StatusErrorListener() : status_(util::Status::OK) {}
+ StatusErrorListener() {}
virtual ~StatusErrorListener() {}
util::Status GetStatus() { return status_; }
diff --git a/src/google/protobuf/util/json_util.h b/src/google/protobuf/util/json_util.h
index 6d3cee52..dee3ddba 100644
--- a/src/google/protobuf/util/json_util.h
+++ b/src/google/protobuf/util/json_util.h
@@ -61,10 +61,17 @@ struct JsonPrintOptions {
// set to 0 will be omitted. Set this flag to true will override the default
// behavior and print primitive fields regardless of their values.
bool always_print_primitive_fields;
-
- JsonPrintOptions() : add_whitespace(false),
- always_print_primitive_fields(false) {
- }
+ // Whether to always print enums as ints. By default they are rendered as
+ // strings.
+ bool always_print_enums_as_ints;
+ // Whether to preserve proto field names
+ bool preserve_proto_field_names;
+
+ JsonPrintOptions()
+ : add_whitespace(false),
+ always_print_primitive_fields(false),
+ always_print_enums_as_ints(false),
+ preserve_proto_field_names(false) {}
};
// DEPRECATED. Use JsonPrintOptions instead.
@@ -172,12 +179,15 @@ namespace internal {
class LIBPROTOBUF_EXPORT ZeroCopyStreamByteSink : public strings::ByteSink {
public:
explicit ZeroCopyStreamByteSink(io::ZeroCopyOutputStream* stream)
- : stream_(stream) {}
+ : stream_(stream), buffer_(NULL), buffer_size_(0) {}
+ ~ZeroCopyStreamByteSink();
virtual void Append(const char* bytes, size_t len);
private:
io::ZeroCopyOutputStream* stream_;
+ void* buffer_;
+ int buffer_size_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ZeroCopyStreamByteSink);
};
diff --git a/src/google/protobuf/util/json_util_test.cc b/src/google/protobuf/util/json_util_test.cc
index 3ce779c9..25c7e96c 100644
--- a/src/google/protobuf/util/json_util_test.cc
+++ b/src/google/protobuf/util/json_util_test.cc
@@ -36,6 +36,7 @@
#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/descriptor_database.h>
#include <google/protobuf/dynamic_message.h>
+#include <google/protobuf/util/internal/testdata/maps.pb.h>
#include <google/protobuf/util/json_format_proto3.pb.h>
#include <google/protobuf/util/type_resolver.h>
#include <google/protobuf/util/type_resolver_util.h>
@@ -50,19 +51,17 @@ using proto3::FOO;
using proto3::BAR;
using proto3::TestMessage;
using proto3::TestMap;
+using proto3::TestOneof;
+using google::protobuf::testing::MapIn;
static const char kTypeUrlPrefix[] = "type.googleapis.com";
-static string GetTypeUrl(const Descriptor* message) {
- return string(kTypeUrlPrefix) + "/" + message->full_name();
-}
-
// As functions defined in json_util.h are just thin wrappers around the
// JSON conversion code in //net/proto2/util/converter, in this test we
// only cover some very basic cases to make sure the wrappers have forwarded
// parameters to the underlying implementation correctly. More detailed
// tests are contained in the //net/proto2/util/converter directory.
-class JsonUtilTest : public testing::Test {
+class JsonUtilTest : public ::testing::Test {
protected:
JsonUtilTest() {
}
@@ -156,6 +155,65 @@ TEST_F(JsonUtilTest, TestDefaultValues) {
"\"repeatedMessageValue\":[]"
"}",
ToJson(m, options));
+
+ options.preserve_proto_field_names = true;
+ m.set_string_value("i am a test string value");
+ m.set_bytes_value("i am a test bytes value");
+ EXPECT_EQ(
+ "{\"bool_value\":false,"
+ "\"int32_value\":0,"
+ "\"int64_value\":\"0\","
+ "\"uint32_value\":0,"
+ "\"uint64_value\":\"0\","
+ "\"float_value\":0,"
+ "\"double_value\":0,"
+ "\"string_value\":\"i am a test string value\","
+ "\"bytes_value\":\"aSBhbSBhIHRlc3QgYnl0ZXMgdmFsdWU=\","
+ "\"enum_value\":\"FOO\","
+ "\"repeated_bool_value\":[],"
+ "\"repeated_int32_value\":[],"
+ "\"repeated_int64_value\":[],"
+ "\"repeated_uint32_value\":[],"
+ "\"repeated_uint64_value\":[],"
+ "\"repeated_float_value\":[],"
+ "\"repeated_double_value\":[],"
+ "\"repeated_string_value\":[],"
+ "\"repeated_bytes_value\":[],"
+ "\"repeated_enum_value\":[],"
+ "\"repeated_message_value\":[]"
+ "}",
+ ToJson(m, options));
+}
+
+TEST_F(JsonUtilTest, TestPreserveProtoFieldNames) {
+ TestMessage m;
+ m.mutable_message_value();
+
+ JsonPrintOptions options;
+ options.preserve_proto_field_names = true;
+ EXPECT_EQ("{\"message_value\":{}}", ToJson(m, options));
+}
+
+TEST_F(JsonUtilTest, TestAlwaysPrintEnumsAsInts) {
+ TestMessage orig;
+ orig.set_enum_value(proto3::BAR);
+ orig.add_repeated_enum_value(proto3::FOO);
+ orig.add_repeated_enum_value(proto3::BAR);
+
+ JsonPrintOptions print_options;
+ print_options.always_print_enums_as_ints = true;
+
+ string expected_json = "{\"enumValue\":1,\"repeatedEnumValue\":[0,1]}";
+ EXPECT_EQ(expected_json, ToJson(orig, print_options));
+
+ TestMessage parsed;
+ JsonParseOptions parse_options;
+ ASSERT_TRUE(FromJson(expected_json, &parsed, parse_options));
+
+ EXPECT_EQ(proto3::BAR, parsed.enum_value());
+ EXPECT_EQ(2, parsed.repeated_enum_value_size());
+ EXPECT_EQ(proto3::FOO, parsed.repeated_enum_value(0));
+ EXPECT_EQ(proto3::BAR, parsed.repeated_enum_value(1));
}
TEST_F(JsonUtilTest, ParseMessage) {
@@ -196,6 +254,29 @@ TEST_F(JsonUtilTest, ParseMap) {
EXPECT_EQ(message.DebugString(), other.DebugString());
}
+TEST_F(JsonUtilTest, ParsePrimitiveMapIn) {
+ MapIn message;
+ JsonPrintOptions print_options;
+ print_options.always_print_primitive_fields = true;
+ JsonParseOptions parse_options;
+ EXPECT_EQ("{\"other\":\"\",\"things\":[],\"mapInput\":{}}",
+ ToJson(message, print_options));
+ MapIn other;
+ ASSERT_TRUE(FromJson(ToJson(message, print_options), &other, parse_options));
+ EXPECT_EQ(message.DebugString(), other.DebugString());
+}
+
+TEST_F(JsonUtilTest, PrintPrimitiveOneof) {
+ TestOneof message;
+ JsonPrintOptions options;
+ options.always_print_primitive_fields = true;
+ message.mutable_oneof_message_value();
+ EXPECT_EQ("{\"oneofMessageValue\":{\"value\":0}}", ToJson(message, options));
+
+ message.set_oneof_int32_value(1);
+ EXPECT_EQ("{\"oneofInt32Value\":1}", ToJson(message, options));
+}
+
TEST_F(JsonUtilTest, TestParseIgnoreUnknownFields) {
TestMessage m;
JsonParseOptions options;
diff --git a/src/google/protobuf/util/message_differencer.cc b/src/google/protobuf/util/message_differencer.cc
index 203d8388..e964e041 100644
--- a/src/google/protobuf/util/message_differencer.cc
+++ b/src/google/protobuf/util/message_differencer.cc
@@ -53,6 +53,7 @@
#include <google/protobuf/io/printer.h>
#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
+#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/dynamic_message.h>
#include <google/protobuf/text_format.h>
#include <google/protobuf/util/field_comparator.h>
@@ -150,6 +151,32 @@ class MessageDifferencer::MultipleFieldsMapKeyComparator
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MultipleFieldsMapKeyComparator);
};
+MessageDifferencer::MapEntryKeyComparator::MapEntryKeyComparator(
+ MessageDifferencer* message_differencer)
+ : message_differencer_(message_differencer) {}
+
+bool MessageDifferencer::MapEntryKeyComparator::IsMatch(
+ const Message& message1, const Message& message2,
+ const std::vector<SpecificField>& parent_fields) const {
+ // Map entry has its key in the field with tag 1. See the comment for
+ // map_entry in MessageOptions.
+ const FieldDescriptor* key = message1.GetDescriptor()->FindFieldByNumber(1);
+ // If key is not present in message1 and we're doing partial comparison or if
+ // map key is explicitly ignored treat the field as set instead,
+ const bool treat_as_set =
+ (message_differencer_->scope() == PARTIAL &&
+ !message1.GetReflection()->HasField(message1, key)) ||
+ message_differencer_->IsIgnored(message1, message2, key, parent_fields);
+
+ std::vector<SpecificField> current_parent_fields(parent_fields);
+ if (treat_as_set) {
+ return message_differencer_->Compare(message1, message2,
+ &current_parent_fields);
+ }
+ return message_differencer_->CompareFieldValueUsingParentFields(
+ message1, message2, key, -1, -1, &current_parent_fields);
+}
+
bool MessageDifferencer::Equals(const Message& message1,
const Message& message2) {
MessageDifferencer differencer;
@@ -191,8 +218,10 @@ MessageDifferencer::MessageDifferencer()
message_field_comparison_(EQUAL),
scope_(FULL),
repeated_field_comparison_(AS_LIST),
+ map_entry_key_comparator_(this),
report_matches_(false),
- output_string_(NULL) { }
+ report_moves_(true),
+ output_string_(NULL) {}
MessageDifferencer::~MessageDifferencer() {
for (int i = 0; i < owned_key_comparators_.size(); ++i) {
@@ -467,6 +496,10 @@ bool MessageDifferencer::Compare(
google::protobuf::scoped_ptr<Message> data1;
google::protobuf::scoped_ptr<Message> data2;
if (UnpackAny(message1, &data1) && UnpackAny(message2, &data2)) {
+ // Avoid DFATAL for different descriptors in google.protobuf.Any payloads.
+ if (data1->GetDescriptor() != data2->GetDescriptor()) {
+ return false;
+ }
return Compare(*data1, *data2, parent_fields);
}
}
@@ -480,8 +513,22 @@ bool MessageDifferencer::Compare(
std::vector<const FieldDescriptor*> message2_fields;
message2_fields.reserve(1 + message2.GetDescriptor()->field_count());
- reflection1->ListFields(message1, &message1_fields);
- reflection2->ListFields(message2, &message2_fields);
+ if (descriptor1->options().map_entry()) {
+ if (scope_ == PARTIAL) {
+ reflection1->ListFields(message1, &message1_fields);
+ } else {
+ // Map entry fields are always considered present.
+ for (int i = 0; i < descriptor1->field_count(); i++) {
+ message1_fields.push_back(descriptor1->field(i));
+ }
+ }
+ for (int i = 0; i < descriptor1->field_count(); i++) {
+ message2_fields.push_back(descriptor1->field(i));
+ }
+ } else {
+ reflection1->ListFields(message1, &message1_fields);
+ reflection2->ListFields(message2, &message2_fields);
+ }
// Add sentinel values to deal with the
// case where the number of the fields in
@@ -779,6 +826,8 @@ bool MessageDifferencer::IsMatch(
reflection2->GetRepeatedMessage(*message2, repeated_field, index2);
SpecificField specific_field;
specific_field.field = repeated_field;
+ specific_field.index = index1;
+ specific_field.new_index = index2;
current_parent_fields.push_back(specific_field);
match = key_comparator->IsMatch(m1, m2, current_parent_fields);
}
@@ -849,7 +898,8 @@ bool MessageDifferencer::CompareRepeatedField(
parent_fields->pop_back();
fieldDifferent = true;
} else if (reporter_ != NULL &&
- specific_field.index != specific_field.new_index) {
+ specific_field.index != specific_field.new_index &&
+ !specific_field.field->is_map() && report_moves_) {
parent_fields->push_back(specific_field);
reporter_->ReportMoved(message1, message2, *parent_fields);
parent_fields->pop_back();
@@ -940,6 +990,8 @@ bool MessageDifferencer::CompareFieldValueUsingParentFields(
bool MessageDifferencer::CheckPathChanged(
const std::vector<SpecificField>& field_path) {
for (int i = 0; i < field_path.size(); ++i) {
+ // Don't check indexes for map entries -- maps are unordered.
+ if (field_path[i].field != NULL && field_path[i].field->is_map()) continue;
if (field_path[i].index != field_path[i].new_index) return true;
}
return false;
@@ -947,7 +999,6 @@ bool MessageDifferencer::CheckPathChanged(
bool MessageDifferencer::IsTreatedAsSet(const FieldDescriptor* field) {
if (!field->is_repeated()) return false;
- if (field->is_map()) return true;
if (repeated_field_comparison_ == AS_SET)
return list_fields_.find(field) == list_fields_.end();
return (set_fields_.find(field) != set_fields_.end());
@@ -988,12 +1039,18 @@ bool MessageDifferencer::IsUnknownFieldIgnored(
return false;
}
-const MessageDifferencer::MapKeyComparator* MessageDifferencer
- ::GetMapKeyComparator(const FieldDescriptor* field) {
+const MessageDifferencer::MapKeyComparator*
+MessageDifferencer ::GetMapKeyComparator(const FieldDescriptor* field) const {
if (!field->is_repeated()) return NULL;
- if (map_field_key_comparator_.find(field) !=
- map_field_key_comparator_.end()) {
- return map_field_key_comparator_[field];
+ FieldKeyComparatorMap::const_iterator it =
+ map_field_key_comparator_.find(field);
+ if (it != map_field_key_comparator_.end()) {
+ return it->second;
+ }
+ if (field->is_map()) {
+ // field cannot already be treated as list or set since TreatAsList() and
+ // TreatAsSet() call GetMapKeyComparator() and fail if it returns non-NULL.
+ return &map_entry_key_comparator_;
}
return NULL;
}
@@ -1383,9 +1440,6 @@ bool MessageDifferencer::MatchRepeatedFieldIndices(
match_list1->assign(count1, -1);
match_list2->assign(count2, -1);
- SpecificField specific_field;
- specific_field.field = repeated_field;
-
bool success = true;
// Find potential match if this is a special repeated field.
if (key_comparator != NULL || IsTreatedAsSet(repeated_field)) {
@@ -1395,7 +1449,7 @@ bool MessageDifferencer::MatchRepeatedFieldIndices(
// algorithm will fail to find a maximum matching.
// Here we use the argumenting path algorithm.
MaximumMatcher::NodeMatchCallback* callback =
- NewPermanentCallback(
+ ::google::protobuf::NewPermanentCallback(
this, &MessageDifferencer::IsMatch,
repeated_field, key_comparator,
&message1, &message2, parent_fields);
@@ -1412,20 +1466,15 @@ bool MessageDifferencer::MatchRepeatedFieldIndices(
// Indicates any matched elements for this repeated field.
bool match = false;
- specific_field.index = i;
- specific_field.new_index = i;
-
for (int j = 0; j < count2; j++) {
if (match_list2->at(j) != -1) continue;
- specific_field.index = i;
- specific_field.new_index = j;
match = IsMatch(repeated_field, key_comparator,
&message1, &message2, parent_fields, i, j);
if (match) {
- match_list1->at(specific_field.index) = specific_field.new_index;
- match_list2->at(specific_field.new_index) = specific_field.index;
+ match_list1->at(i) = j;
+ match_list2->at(j) = i;
break;
}
}
@@ -1503,6 +1552,10 @@ void MessageDifferencer::StreamReporter::PrintPath(
} else {
printer_->PrintRaw(specific_field.field->name());
}
+ if (specific_field.field->is_map()) {
+ // Don't print index in a map field; they are semantically unordered.
+ continue;
+ }
} else {
printer_->PrintRaw(SimpleItoa(specific_field.unknown_field_number));
}
@@ -1515,6 +1568,12 @@ void MessageDifferencer::StreamReporter::PrintPath(
}
}
+void MessageDifferencer::StreamReporter::PrintPath(
+ const std::vector<SpecificField>& field_path, bool left_side,
+ const Message& message) {
+ PrintPath(field_path, left_side);
+}
+
void MessageDifferencer::
StreamReporter::PrintValue(const Message& message,
const std::vector<SpecificField>& field_path,
@@ -1592,7 +1651,7 @@ void MessageDifferencer::StreamReporter::ReportAdded(
const Message& message2,
const std::vector<SpecificField>& field_path) {
printer_->Print("added: ");
- PrintPath(field_path, false);
+ PrintPath(field_path, false, message2);
printer_->Print(": ");
PrintValue(message2, field_path, false);
printer_->Print("\n"); // Print for newlines.
@@ -1603,7 +1662,7 @@ void MessageDifferencer::StreamReporter::ReportDeleted(
const Message& message2,
const std::vector<SpecificField>& field_path) {
printer_->Print("deleted: ");
- PrintPath(field_path, true);
+ PrintPath(field_path, true, message1);
printer_->Print(": ");
PrintValue(message1, field_path, true);
printer_->Print("\n"); // Print for newlines
@@ -1627,10 +1686,10 @@ void MessageDifferencer::StreamReporter::ReportModified(
}
printer_->Print("modified: ");
- PrintPath(field_path, true);
+ PrintPath(field_path, true, message1);
if (CheckPathChanged(field_path)) {
printer_->Print(" -> ");
- PrintPath(field_path, false);
+ PrintPath(field_path, false, message2);
}
printer_->Print(": ");
PrintValue(message1, field_path, true);
@@ -1644,9 +1703,9 @@ void MessageDifferencer::StreamReporter::ReportMoved(
const Message& message2,
const std::vector<SpecificField>& field_path) {
printer_->Print("moved: ");
- PrintPath(field_path, true);
+ PrintPath(field_path, true, message1);
printer_->Print(" -> ");
- PrintPath(field_path, false);
+ PrintPath(field_path, false, message2);
printer_->Print(" : ");
PrintValue(message1, field_path, true);
printer_->Print("\n"); // Print for newlines.
@@ -1657,10 +1716,10 @@ void MessageDifferencer::StreamReporter::ReportMatched(
const Message& message2,
const std::vector<SpecificField>& field_path) {
printer_->Print("matched: ");
- PrintPath(field_path, true);
+ PrintPath(field_path, true, message1);
if (CheckPathChanged(field_path)) {
printer_->Print(" -> ");
- PrintPath(field_path, false);
+ PrintPath(field_path, false, message2);
}
printer_->Print(" : ");
PrintValue(message1, field_path, true);
@@ -1672,10 +1731,10 @@ void MessageDifferencer::StreamReporter::ReportIgnored(
const Message& message2,
const std::vector<SpecificField>& field_path) {
printer_->Print("ignored: ");
- PrintPath(field_path, true);
+ PrintPath(field_path, true, message1);
if (CheckPathChanged(field_path)) {
printer_->Print(" -> ");
- PrintPath(field_path, false);
+ PrintPath(field_path, false, message2);
}
printer_->Print("\n"); // Print for newlines.
}
@@ -1684,10 +1743,10 @@ void MessageDifferencer::StreamReporter::ReportUnknownFieldIgnored(
const Message& message1, const Message& message2,
const std::vector<SpecificField>& field_path) {
printer_->Print("ignored: ");
- PrintPath(field_path, true);
+ PrintPath(field_path, true, message1);
if (CheckPathChanged(field_path)) {
printer_->Print(" -> ");
- PrintPath(field_path, false);
+ PrintPath(field_path, false, message2);
}
printer_->Print("\n"); // Print for newlines.
}
diff --git a/src/google/protobuf/util/message_differencer.h b/src/google/protobuf/util/message_differencer.h
index d99223cb..b7d4de00 100644
--- a/src/google/protobuf/util/message_differencer.h
+++ b/src/google/protobuf/util/message_differencer.h
@@ -241,18 +241,18 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
// mutually exclusive. If a field has been both moved and modified, then
// only ReportModified will be called.
virtual void ReportMoved(
- const Message& message1,
- const Message& message2,
- const std::vector<SpecificField>& field_path) { }
+ const Message& /* message1 */,
+ const Message& /* message2 */,
+ const std::vector<SpecificField>& /* field_path */) { }
// Reports that two fields match. Useful for doing side-by-side diffs.
// This function is mutually exclusive with ReportModified and ReportMoved.
// Note that you must call set_report_matches(true) before calling Compare
// to make use of this function.
virtual void ReportMatched(
- const Message& message1,
- const Message& message2,
- const std::vector<SpecificField>& field_path) { }
+ const Message& /* message1 */,
+ const Message& /* message2 */,
+ const std::vector<SpecificField>& /* field_path */) { }
// Reports that two fields would have been compared, but the
// comparison has been skipped because the field was marked as
@@ -274,16 +274,16 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
// the fields are equal or not (perhaps with a second call to
// Compare()), if it cares.
virtual void ReportIgnored(
- const Message& message1,
- const Message& message2,
- const std::vector<SpecificField>& field_path) { }
+ const Message& /* message1 */,
+ const Message& /* message2 */,
+ const std::vector<SpecificField>& /* field_path */) { }
// Report that an unknown field is ignored. (see comment above).
// Note this is a different function since the last SpecificField in field
// path has a null field. This could break existing Reporter.
virtual void ReportUnknownFieldIgnored(
- const Message& message1, const Message& message2,
- const std::vector<SpecificField>& field_path) {}
+ const Message& /* message1 */, const Message& /* message2 */,
+ const std::vector<SpecificField>& /* field_path */) {}
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Reporter);
@@ -297,9 +297,9 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
virtual ~MapKeyComparator();
virtual bool IsMatch(
- const Message& message1,
- const Message& message2,
- const std::vector<SpecificField>& parent_fields) const {
+ const Message& /* message1 */,
+ const Message& /* message2 */,
+ const std::vector<SpecificField>& /* parent_fields */) const {
GOOGLE_CHECK(false) << "IsMatch() is not implemented.";
return false;
}
@@ -321,18 +321,18 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
// Returns true if the field should be ignored.
virtual bool IsIgnored(
- const Message& message1,
- const Message& message2,
- const FieldDescriptor* field,
- const std::vector<SpecificField>& parent_fields) = 0;
+ const Message& /* message1 */,
+ const Message& /* message2 */,
+ const FieldDescriptor* /* field */,
+ const std::vector<SpecificField>& /* parent_fields */) = 0;
// Returns true if the unknown field should be ignored.
// Note: This will be called for unknown fields as well in which case
// field.field will be null.
virtual bool IsUnknownFieldIgnored(
- const Message& message1, const Message& message2,
- const SpecificField& field,
- const std::vector<SpecificField>& parent_fields) {
+ const Message& /* message1 */, const Message& /* message2 */,
+ const SpecificField& /* field */,
+ const std::vector<SpecificField>& /* parent_fields */) {
return false;
}
};
@@ -518,6 +518,13 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
report_matches_ = report_matches;
}
+ // Tells the differencer whether or not to report moves (in a set or map
+ // repeated field). This method must be called before Compare. The default for
+ // a new differencer is true.
+ void set_report_moves(bool report_moves) {
+ report_moves_ = report_moves;
+ }
+
// Sets the scope of the comparison (as defined in the Scope enumeration
// above) that is used by this differencer when determining which fields to
// compare between the messages.
@@ -620,6 +627,11 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
const std::vector<SpecificField>& field_path);
protected:
+ // Prints the specified path of fields to the buffer. message is used to
+ // print map keys.
+ virtual void PrintPath(const std::vector<SpecificField>& field_path,
+ bool left_side, const Message& message);
+
// Prints the specified path of fields to the buffer.
virtual void PrintPath(const std::vector<SpecificField>& field_path,
bool left_side);
@@ -653,6 +665,18 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
// relies on some private methods of MessageDifferencer. That's why this
// class is declared as a nested class of MessageDifferencer.
class MultipleFieldsMapKeyComparator;
+
+ // A MapKeyComparator for use with map_entries.
+ class LIBPROTOBUF_EXPORT MapEntryKeyComparator : public MapKeyComparator {
+ public:
+ explicit MapEntryKeyComparator(MessageDifferencer* message_differencer);
+ virtual bool IsMatch(const Message& message1, const Message& message2,
+ const std::vector<SpecificField>& parent_fields) const;
+
+ private:
+ MessageDifferencer* message_differencer_;
+ };
+
// Returns true if field1's number() is less than field2's.
static bool FieldBefore(const FieldDescriptor* field1,
const FieldDescriptor* field2);
@@ -765,9 +789,10 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
const SpecificField& field,
const std::vector<SpecificField>& parent_fields);
- // Returns MapKeyComparator* when this field has been configured to
- // be treated as a map. If not, returns NULL.
- const MapKeyComparator* GetMapKeyComparator(const FieldDescriptor* field);
+ // Returns MapKeyComparator* when this field has been configured to be treated
+ // as a map or its is_map() return true. If not, returns NULL.
+ const MapKeyComparator* GetMapKeyComparator(
+ const FieldDescriptor* field) const;
// Attempts to match indices of a repeated field, so that the contained values
// match. Clears output vectors and sets their values to indices of paired
@@ -817,11 +842,13 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
// MapKeyComparator is created for comparison purpose.
std::vector<MapKeyComparator*> owned_key_comparators_;
FieldKeyComparatorMap map_field_key_comparator_;
+ MapEntryKeyComparator map_entry_key_comparator_;
std::vector<IgnoreCriteria*> ignore_criteria_;
FieldSet ignored_fields_;
bool report_matches_;
+ bool report_moves_;
string* output_string_;
diff --git a/src/google/protobuf/util/message_differencer_unittest.cc b/src/google/protobuf/util/message_differencer_unittest.cc
index 30b27dba..75cffd9f 100755
--- a/src/google/protobuf/util/message_differencer_unittest.cc
+++ b/src/google/protobuf/util/message_differencer_unittest.cc
@@ -38,6 +38,7 @@
#include <string>
#include <vector>
+#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/util/field_comparator.h>
#include <google/protobuf/util/message_differencer.h>
@@ -54,7 +55,6 @@
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
@@ -1558,6 +1558,43 @@ TEST(MessageDifferencerTest, RepeatedFieldMapTest_CustomMapKeyComparator) {
EXPECT_EQ("ignored: item[0].ra\n", output);
}
+// Compares fields by their index offset by one, so index 0 matches with 1, etc.
+class OffsetByOneMapKeyComparator
+ : public util::MessageDifferencer::MapKeyComparator {
+ public:
+ typedef util::MessageDifferencer::SpecificField SpecificField;
+ virtual bool IsMatch(const Message& message1, const Message& message2,
+ const std::vector<SpecificField>& parent_fields) const {
+ return parent_fields.back().index + 1 == parent_fields.back().new_index;
+ }
+};
+
+TEST(MessageDifferencerTest, RepeatedFieldMapTest_CustomIndexMapKeyComparator) {
+ protobuf_unittest::TestDiffMessage msg1;
+ protobuf_unittest::TestDiffMessage msg2;
+ // Treat "item" as Map, using custom key comparator to determine if two
+ // elements have the same key.
+ protobuf_unittest::TestDiffMessage::Item* item = msg1.add_item();
+ item->set_b("one");
+ item = msg2.add_item();
+ item->set_b("zero");
+ item = msg2.add_item();
+ item->set_b("one");
+ util::MessageDifferencer differencer;
+ OffsetByOneMapKeyComparator key_comparator;
+ differencer.TreatAsMapUsingKeyComparator(GetFieldDescriptor(msg1, "item"),
+ &key_comparator);
+ string output;
+ differencer.ReportDifferencesToString(&output);
+ // With the offset by one comparator msg1.item[0] should be compared to
+ // msg2.item[1] and thus be moved, msg2.item[0] should be marked as added.
+ EXPECT_FALSE(differencer.Compare(msg1, msg2));
+ EXPECT_EQ(
+ "moved: item[0] -> item[1] : { b: \"one\" }\n"
+ "added: item[0]: { b: \"zero\" }\n",
+ output);
+}
+
TEST(MessageDifferencerTest, RepeatedFieldSetTest_Subset) {
protobuf_unittest::TestDiffMessage msg1;
protobuf_unittest::TestDiffMessage msg2;
@@ -2042,6 +2079,9 @@ class ComparisonTest : public testing::Test {
unittest::TestEmptyMessage empty1_;
unittest::TestEmptyMessage empty2_;
+ unittest::TestMap map_proto1_;
+ unittest::TestMap map_proto2_;
+
UnknownFieldSet* unknown1_;
UnknownFieldSet* unknown2_;
@@ -2802,6 +2842,133 @@ TEST_F(ComparisonTest, EquivalentIgnoresUnknown) {
EXPECT_TRUE(util::MessageDifferencer::Equivalent(message1, message2));
}
+TEST_F(ComparisonTest, MapTest) {
+ Map<string, string>& map1 = *map_proto1_.mutable_map_string_string();
+ map1["key1"] = "1";
+ map1["key2"] = "2";
+ map1["key3"] = "3";
+ Map<string, string>& map2 = *map_proto2_.mutable_map_string_string();
+ map2["key3"] = "0";
+ map2["key2"] = "2";
+ map2["key1"] = "1";
+
+ EXPECT_EQ("modified: map_string_string.value: \"3\" -> \"0\"\n",
+ Run(map_proto1_, map_proto2_));
+}
+
+TEST_F(ComparisonTest, MapIgnoreKeyTest) {
+ Map<string, string>& map1 = *map_proto1_.mutable_map_string_string();
+ map1["key1"] = "1";
+ map1["key2"] = "2";
+ map1["key3"] = "3";
+ Map<string, string>& map2 = *map_proto2_.mutable_map_string_string();
+ map2["key4"] = "2";
+ map2["key5"] = "3";
+ map2["key6"] = "1";
+
+ util::MessageDifferencer differencer;
+ differencer.IgnoreField(
+ GetFieldDescriptor(map_proto1_, "map_string_string.key"));
+ EXPECT_TRUE(differencer.Compare(map_proto1_, map_proto2_));
+}
+
+TEST_F(ComparisonTest, MapRoundTripSyncTest) {
+ google::protobuf::TextFormat::Parser parser;
+ unittest::TestMap map_reflection1;
+
+ // By setting via reflection, data exists in repeated field.
+ ASSERT_TRUE(parser.ParseFromString(
+ "map_int32_foreign_message { key: 1 }", &map_reflection1));
+
+ // During copy, data is synced from repeated field to map.
+ unittest::TestMap map_reflection2 = map_reflection1;
+
+ // During comparison, data is synced from map to repeated field.
+ EXPECT_TRUE(
+ util::MessageDifferencer::Equals(map_reflection1, map_reflection2));
+}
+
+TEST_F(ComparisonTest, MapEntryPartialTest) {
+ google::protobuf::TextFormat::Parser parser;
+ unittest::TestMap map1;
+ unittest::TestMap map2;
+
+ string output;
+ util::MessageDifferencer differencer;
+ differencer.set_scope(util::MessageDifferencer::PARTIAL);
+ differencer.ReportDifferencesToString(&output);
+
+ ASSERT_TRUE(parser.ParseFromString(
+ "map_int32_foreign_message { key: 1 value { c: 1 } }", &map1));
+ ASSERT_TRUE(parser.ParseFromString(
+ "map_int32_foreign_message { key: 1 value { c: 2 }}", &map2));
+ EXPECT_FALSE(differencer.Compare(map1, map2));
+ EXPECT_EQ("modified: map_int32_foreign_message.value.c: 1 -> 2\n", output);
+
+ ASSERT_TRUE(
+ parser.ParseFromString("map_int32_foreign_message { key: 1 }", &map1));
+ EXPECT_TRUE(differencer.Compare(map1, map2));
+}
+
+TEST_F(ComparisonTest, MapEntryPartialEmptyKeyTest) {
+ google::protobuf::TextFormat::Parser parser;
+ unittest::TestMap map1;
+ unittest::TestMap map2;
+ ASSERT_TRUE(parser.ParseFromString("map_int32_foreign_message {}", &map1));
+ ASSERT_TRUE(
+ parser.ParseFromString("map_int32_foreign_message { key: 1 }", &map2));
+
+ util::MessageDifferencer differencer;
+ differencer.set_scope(util::MessageDifferencer::PARTIAL);
+ EXPECT_TRUE(differencer.Compare(map1, map2));
+}
+
+// Considers strings keys as equal if they have equal lengths.
+class LengthMapKeyComparator
+ : public util::MessageDifferencer::MapKeyComparator {
+ public:
+ typedef util::MessageDifferencer::SpecificField SpecificField;
+ virtual bool IsMatch(const Message& message1, const Message& message2,
+ const std::vector<SpecificField>& parent_fields) const {
+ const Reflection* reflection1 = message1.GetReflection();
+ const Reflection* reflection2 = message2.GetReflection();
+ const FieldDescriptor* key_field =
+ message1.GetDescriptor()->FindFieldByName("key");
+ return reflection1->GetString(message1, key_field).size() ==
+ reflection2->GetString(message2, key_field).size();
+ }
+};
+
+TEST_F(ComparisonTest, MapEntryCustomMapKeyComparator) {
+ google::protobuf::TextFormat::Parser parser;
+ protobuf_unittest::TestMap msg1;
+ protobuf_unittest::TestMap msg2;
+
+ ASSERT_TRUE(parser.ParseFromString(
+ "map_string_foreign_message { key: 'key1' value { c: 1 }}", &msg1));
+ ASSERT_TRUE(parser.ParseFromString(
+ "map_string_foreign_message { key: 'key2' value { c: 1 }}", &msg2));
+
+ util::MessageDifferencer differencer;
+ LengthMapKeyComparator key_comparator;
+ differencer.TreatAsMapUsingKeyComparator(
+ GetFieldDescriptor(msg1, "map_string_foreign_message"), &key_comparator);
+ string output;
+ differencer.ReportDifferencesToString(&output);
+ // Though the above two messages have different keys for their map entries,
+ // they are considered the same by key_comparator because their lengths are
+ // equal. However, in value comparison, all fields of the message are taken
+ // into consideration, so they are reported as different.
+ EXPECT_FALSE(differencer.Compare(msg1, msg2));
+ EXPECT_EQ("modified: map_string_foreign_message.key: \"key1\" -> \"key2\"\n",
+ output);
+ differencer.IgnoreField(
+ GetFieldDescriptor(msg1, "map_string_foreign_message.key"));
+ output.clear();
+ EXPECT_TRUE(differencer.Compare(msg1, msg2));
+ EXPECT_EQ("ignored: map_string_foreign_message.key\n", output);
+}
+
class MatchingTest : public testing::Test {
public:
typedef util::MessageDifferencer MessageDifferencer;
@@ -3146,6 +3313,24 @@ TEST(Anytest, TreatAsSet) {
EXPECT_TRUE(message_differencer.Compare(m1, m2));
}
+TEST(Anytest, TreatAsSet_DifferentType) {
+ protobuf_unittest::TestField value1;
+ value1.set_a(20);
+ value1.set_b(30);
+ protobuf_unittest::TestDiffMessage value2;
+ value2.add_rv(40);
+
+ protobuf_unittest::TestAny m1, m2;
+ m1.add_repeated_any_value()->PackFrom(value1);
+ m1.add_repeated_any_value()->PackFrom(value2);
+ m2.add_repeated_any_value()->PackFrom(value2);
+ m2.add_repeated_any_value()->PackFrom(value1);
+
+ util::MessageDifferencer message_differencer;
+ message_differencer.TreatAsSet(GetFieldDescriptor(m1, "repeated_any_value"));
+ EXPECT_TRUE(message_differencer.Compare(m1, m2));
+}
+
} // namespace
} // namespace protobuf
diff --git a/src/google/protobuf/util/time_util.cc b/src/google/protobuf/util/time_util.cc
index b11f822a..46a6f5a8 100644
--- a/src/google/protobuf/util/time_util.cc
+++ b/src/google/protobuf/util/time_util.cc
@@ -49,11 +49,9 @@ static const int kNanosPerSecond = 1000000000;
static const int kMicrosPerSecond = 1000000;
static const int kMillisPerSecond = 1000;
static const int kNanosPerMillisecond = 1000000;
-static const int kMicrosPerMillisecond = 1000;
static const int kNanosPerMicrosecond = 1000;
static const int kSecondsPerMinute = 60; // Note that we ignore leap seconds.
static const int kSecondsPerHour = 3600;
-static const char kTimestampFormat[] = "%E4Y-%m-%dT%H:%M:%S";
template <typename T>
T CreateNormalized(int64 seconds, int64 nanos);
@@ -376,19 +374,6 @@ namespace {
using google::protobuf::util::kNanosPerSecond;
using google::protobuf::util::CreateNormalized;
-// Convert a Timestamp to uint128.
-void ToUint128(const Timestamp& value, uint128* result, bool* negative) {
- if (value.seconds() < 0) {
- *negative = true;
- *result = static_cast<uint64>(-value.seconds());
- *result = *result * kNanosPerSecond - static_cast<uint32>(value.nanos());
- } else {
- *negative = false;
- *result = static_cast<uint64>(value.seconds());
- *result = *result * kNanosPerSecond + static_cast<uint32>(value.nanos());
- }
-}
-
// Convert a Duration to uint128.
void ToUint128(const Duration& value, uint128* result, bool* negative) {
if (value.seconds() < 0 || value.nanos() < 0) {
@@ -402,21 +387,6 @@ void ToUint128(const Duration& value, uint128* result, bool* negative) {
}
}
-void ToTimestamp(const uint128& value, bool negative, Timestamp* timestamp) {
- int64 seconds = static_cast<int64>(Uint128Low64(value / kNanosPerSecond));
- int32 nanos = static_cast<int32>(Uint128Low64(value % kNanosPerSecond));
- if (negative) {
- seconds = -seconds;
- nanos = -nanos;
- if (nanos < 0) {
- nanos += kNanosPerSecond;
- seconds -= 1;
- }
- }
- timestamp->set_seconds(seconds);
- timestamp->set_nanos(nanos);
-}
-
void ToDuration(const uint128& value, bool negative, Duration* duration) {
int64 seconds = static_cast<int64>(Uint128Low64(value / kNanosPerSecond));
int32 nanos = static_cast<int32>(Uint128Low64(value % kNanosPerSecond));
diff --git a/src/google/protobuf/util/time_util.h b/src/google/protobuf/util/time_util.h
index 432c9f0a..b8846935 100644
--- a/src/google/protobuf/util/time_util.h
+++ b/src/google/protobuf/util/time_util.h
@@ -237,7 +237,7 @@ inline Duration operator%(const Duration& d1, const Duration& d2) {
return result %= d2;
}
-inline ostream& operator<<(ostream& out, const Duration& d) {
+inline std::ostream& operator<<(std::ostream& out, const Duration& d) {
out << google::protobuf::util::TimeUtil::ToString(d);
return out;
}
@@ -284,7 +284,7 @@ inline Timestamp operator-(const Timestamp& t, const Duration& d) {
}
LIBPROTOBUF_EXPORT Duration operator-(const Timestamp& t1, const Timestamp& t2);
-inline ostream& operator<<(ostream& out, const Timestamp& t) {
+inline std::ostream& operator<<(std::ostream& out, const Timestamp& t) {
out << google::protobuf::util::TimeUtil::ToString(t);
return out;
}
diff --git a/src/google/protobuf/wire_format.cc b/src/google/protobuf/wire_format.cc
index 88a1a234..01704c94 100644
--- a/src/google/protobuf/wire_format.cc
+++ b/src/google/protobuf/wire_format.cc
@@ -42,6 +42,8 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/stringprintf.h>
#include <google/protobuf/descriptor.h>
+#include <google/protobuf/dynamic_message.h>
+#include <google/protobuf/map_field.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/coded_stream.h>
@@ -52,9 +54,17 @@
namespace google {
+const size_t kMapEntryTagByteSize = 2;
+
namespace protobuf {
namespace internal {
+// Forward declare static functions
+static size_t MapKeyDataOnlyByteSize(const FieldDescriptor* field,
+ const MapKey& value);
+static size_t MapValueRefDataOnlyByteSize(const FieldDescriptor* field,
+ const MapValueRef& value);
+
// ===================================================================
bool UnknownFieldSetFieldSkipper::SkipField(
@@ -74,6 +84,8 @@ void UnknownFieldSetFieldSkipper::SkipUnknownEnum(
bool WireFormat::SkipField(io::CodedInputStream* input, uint32 tag,
UnknownFieldSet* unknown_fields) {
int number = WireFormatLite::GetTagFieldNumber(tag);
+ // Field number 0 is illegal.
+ if (number == 0) return false;
switch (WireFormatLite::GetTagWireType(tag)) {
case WireFormatLite::WIRETYPE_VARINT: {
@@ -793,7 +805,16 @@ void WireFormat::SerializeWithCachedSizes(
int expected_endpoint = output->ByteCount() + size;
std::vector<const FieldDescriptor*> fields;
- message_reflection->ListFields(message, &fields);
+
+ // Fields of map entry should always be serialized.
+ if (descriptor->options().map_entry()) {
+ for (int i = 0; i < descriptor->field_count(); i++) {
+ fields.push_back(descriptor->field(i));
+ }
+ } else {
+ message_reflection->ListFields(message, &fields);
+ }
+
for (int i = 0; i < fields.size(); i++) {
SerializeFieldWithCachedSizes(fields[i], message, output);
}
@@ -812,6 +833,129 @@ void WireFormat::SerializeWithCachedSizes(
"during serialization?";
}
+static void SerializeMapKeyWithCachedSizes(const FieldDescriptor* field,
+ const MapKey& value,
+ io::CodedOutputStream* output) {
+ switch (field->type()) {
+ case FieldDescriptor::TYPE_DOUBLE:
+ case FieldDescriptor::TYPE_FLOAT:
+ case FieldDescriptor::TYPE_GROUP:
+ case FieldDescriptor::TYPE_MESSAGE:
+ case FieldDescriptor::TYPE_BYTES:
+ case FieldDescriptor::TYPE_ENUM:
+ GOOGLE_LOG(FATAL) << "Unsupported";
+ break;
+#define CASE_TYPE(FieldType, CamelFieldType, CamelCppType) \
+ case FieldDescriptor::TYPE_##FieldType: \
+ WireFormatLite::Write##CamelFieldType(1, value.Get##CamelCppType##Value(), \
+ output); \
+ break;
+ CASE_TYPE(INT64, Int64, Int64)
+ CASE_TYPE(UINT64, UInt64, UInt64)
+ CASE_TYPE(INT32, Int32, Int32)
+ CASE_TYPE(FIXED64, Fixed64, UInt64)
+ CASE_TYPE(FIXED32, Fixed32, UInt32)
+ CASE_TYPE(BOOL, Bool, Bool)
+ CASE_TYPE(UINT32, UInt32, UInt32)
+ CASE_TYPE(SFIXED32, SFixed32, Int32)
+ CASE_TYPE(SFIXED64, SFixed64, Int64)
+ CASE_TYPE(SINT32, SInt32, Int32)
+ CASE_TYPE(SINT64, SInt64, Int64)
+ CASE_TYPE(STRING, String, String)
+#undef CASE_TYPE
+ }
+}
+
+static void SerializeMapValueRefWithCachedSizes(const FieldDescriptor* field,
+ const MapValueRef& value,
+ io::CodedOutputStream* output) {
+ switch (field->type()) {
+#define CASE_TYPE(FieldType, CamelFieldType, CamelCppType) \
+ case FieldDescriptor::TYPE_##FieldType: \
+ WireFormatLite::Write##CamelFieldType(2, value.Get##CamelCppType##Value(), \
+ output); \
+ break;
+ CASE_TYPE(INT64, Int64, Int64)
+ CASE_TYPE(UINT64, UInt64, UInt64)
+ CASE_TYPE(INT32, Int32, Int32)
+ CASE_TYPE(FIXED64, Fixed64, UInt64)
+ CASE_TYPE(FIXED32, Fixed32, UInt32)
+ CASE_TYPE(BOOL, Bool, Bool)
+ CASE_TYPE(UINT32, UInt32, UInt32)
+ CASE_TYPE(SFIXED32, SFixed32, Int32)
+ CASE_TYPE(SFIXED64, SFixed64, Int64)
+ CASE_TYPE(SINT32, SInt32, Int32)
+ CASE_TYPE(SINT64, SInt64, Int64)
+ CASE_TYPE(ENUM, Enum, Enum)
+ CASE_TYPE(DOUBLE, Double, Double)
+ CASE_TYPE(FLOAT, Float, Float)
+ CASE_TYPE(STRING, String, String)
+ CASE_TYPE(BYTES, Bytes, String)
+ CASE_TYPE(MESSAGE, Message, Message)
+ CASE_TYPE(GROUP, Group, Message)
+#undef CASE_TYPE
+ }
+}
+
+class MapKeySorter {
+ public:
+ static std::vector<MapKey> SortKey(const Message& message,
+ const Reflection* reflection,
+ const FieldDescriptor* field) {
+ std::vector<MapKey> sorted_key_list;
+ for (MapIterator it =
+ reflection->MapBegin(const_cast<Message*>(&message), field);
+ it != reflection->MapEnd(const_cast<Message*>(&message), field);
+ ++it) {
+ sorted_key_list.push_back(it.GetKey());
+ }
+ MapKeyComparator comparator;
+ std::sort(sorted_key_list.begin(), sorted_key_list.end(), comparator);
+ return sorted_key_list;
+ }
+
+ private:
+ class MapKeyComparator {
+ public:
+ bool operator()(const MapKey& a, const MapKey& b) const {
+ GOOGLE_DCHECK(a.type() == b.type());
+ switch (a.type()) {
+#define CASE_TYPE(CppType, CamelCppType) \
+ case FieldDescriptor::CPPTYPE_##CppType: { \
+ return a.Get##CamelCppType##Value() < b.Get##CamelCppType##Value(); \
+ }
+ CASE_TYPE(STRING, String)
+ CASE_TYPE(INT64, Int64)
+ CASE_TYPE(INT32, Int32)
+ CASE_TYPE(UINT64, UInt64)
+ CASE_TYPE(UINT32, UInt32)
+ CASE_TYPE(BOOL, Bool)
+#undef CASE_TYPE
+
+ default:
+ GOOGLE_LOG(DFATAL) << "Invalid key for map field.";
+ return true;
+ }
+ }
+ };
+};
+
+static void SerializeMapEntry(const FieldDescriptor* field, const MapKey& key,
+ const MapValueRef& value,
+ io::CodedOutputStream* output) {
+ const FieldDescriptor* key_field = field->message_type()->field(0);
+ const FieldDescriptor* value_field = field->message_type()->field(1);
+
+ WireFormatLite::WriteTag(field->number(),
+ WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output);
+ size_t size = kMapEntryTagByteSize;
+ size += MapKeyDataOnlyByteSize(key_field, key);
+ size += MapValueRefDataOnlyByteSize(value_field, value);
+ output->WriteVarint32(size);
+ SerializeMapKeyWithCachedSizes(key_field, key, output);
+ SerializeMapValueRefWithCachedSizes(value_field, value, output);
+}
+
void WireFormat::SerializeFieldWithCachedSizes(
const FieldDescriptor* field,
const Message& message,
@@ -826,14 +970,66 @@ void WireFormat::SerializeFieldWithCachedSizes(
return;
}
+ // For map fields, we can use either repeated field reflection or map
+ // reflection. Our choice has some subtle effects. If we use repeated field
+ // reflection here, then the repeated field representation becomes
+ // authoritative for this field: any existing references that came from map
+ // reflection remain valid for reading, but mutations to them are lost and
+ // will be overwritten next time we call map reflection!
+ //
+ // So far this mainly affects Python, which keeps long-term references to map
+ // values around, and always uses map reflection. See: b/35918691
+ //
+ // Here we choose to use map reflection API as long as the internal
+ // map is valid. In this way, the serialization doesn't change map field's
+ // internal state and existing references that came from map reflection remain
+ // valid for both reading and writing.
+ if (field->is_map()) {
+ MapFieldBase* map_field =
+ message_reflection->MapData(const_cast<Message*>(&message), field);
+ if (map_field->IsMapValid()) {
+ if (output->IsSerializationDeterministic()) {
+ std::vector<MapKey> sorted_key_list =
+ MapKeySorter::SortKey(message, message_reflection, field);
+ for (std::vector<MapKey>::iterator it = sorted_key_list.begin();
+ it != sorted_key_list.end(); ++it) {
+ MapValueRef map_value;
+ message_reflection->InsertOrLookupMapValue(
+ const_cast<Message*>(&message), field, *it, &map_value);
+ SerializeMapEntry(field, *it, map_value, output);
+ }
+ } else {
+ for (MapIterator it = message_reflection->MapBegin(
+ const_cast<Message*>(&message), field);
+ it !=
+ message_reflection->MapEnd(const_cast<Message*>(&message), field);
+ ++it) {
+ SerializeMapEntry(field, it.GetKey(), it.GetValueRef(), output);
+ }
+ }
+
+ return;
+ }
+ }
+
int count = 0;
if (field->is_repeated()) {
count = message_reflection->FieldSize(message, field);
+ } else if (field->containing_type()->options().map_entry()) {
+ // Map entry fields always need to be serialized.
+ count = 1;
} else if (message_reflection->HasField(message, field)) {
count = 1;
}
+ // map_entries is for maps that'll be deterministically serialized.
+ std::vector<const Message*> map_entries;
+ if (count > 1 && field->is_map() && output->IsSerializationDeterministic()) {
+ map_entries =
+ DynamicMapSorter::Sort(message, count, message_reflection, field);
+ }
+
const bool is_packed = field->is_packed();
if (is_packed && count > 0) {
WireFormatLite::WriteTag(field->number(),
@@ -877,15 +1073,17 @@ void WireFormat::SerializeFieldWithCachedSizes(
HANDLE_PRIMITIVE_TYPE(BOOL, bool, Bool, Bool)
#undef HANDLE_PRIMITIVE_TYPE
-#define HANDLE_TYPE(TYPE, TYPE_METHOD, CPPTYPE_METHOD) \
- case FieldDescriptor::TYPE_##TYPE: \
- WireFormatLite::Write##TYPE_METHOD( \
- field->number(), \
- field->is_repeated() ? \
- message_reflection->GetRepeated##CPPTYPE_METHOD( \
- message, field, j) : \
- message_reflection->Get##CPPTYPE_METHOD(message, field), \
- output); \
+#define HANDLE_TYPE(TYPE, TYPE_METHOD, CPPTYPE_METHOD) \
+ case FieldDescriptor::TYPE_##TYPE: \
+ WireFormatLite::Write##TYPE_METHOD( \
+ field->number(), \
+ field->is_repeated() ? \
+ (map_entries.empty() ? \
+ message_reflection->GetRepeated##CPPTYPE_METHOD( \
+ message, field, j) : \
+ *map_entries[j]) : \
+ message_reflection->Get##CPPTYPE_METHOD(message, field), \
+ output); \
break;
HANDLE_TYPE(GROUP , Group , Message)
@@ -971,7 +1169,16 @@ size_t WireFormat::ByteSize(const Message& message) {
size_t our_size = 0;
std::vector<const FieldDescriptor*> fields;
- message_reflection->ListFields(message, &fields);
+
+ // Fields of map entry should always be serialized.
+ if (descriptor->options().map_entry()) {
+ for (int i = 0; i < descriptor->field_count(); i++) {
+ fields.push_back(descriptor->field(i));
+ }
+ } else {
+ message_reflection->ListFields(message, &fields);
+ }
+
for (int i = 0; i < fields.size(); i++) {
our_size += FieldByteSize(fields[i], message);
}
@@ -1002,6 +1209,9 @@ size_t WireFormat::FieldByteSize(
size_t count = 0;
if (field->is_repeated()) {
count = FromIntSize(message_reflection->FieldSize(message, field));
+ } else if (field->containing_type()->options().map_entry()) {
+ // Map entry fields always need to be serialized.
+ count = 1;
} else if (message_reflection->HasField(message, field)) {
count = 1;
}
@@ -1022,20 +1232,124 @@ size_t WireFormat::FieldByteSize(
return our_size;
}
+static size_t MapKeyDataOnlyByteSize(const FieldDescriptor* field,
+ const MapKey& value) {
+ GOOGLE_DCHECK_EQ(FieldDescriptor::TypeToCppType(field->type()), value.type());
+ switch (field->type()) {
+ case FieldDescriptor::TYPE_DOUBLE:
+ case FieldDescriptor::TYPE_FLOAT:
+ case FieldDescriptor::TYPE_GROUP:
+ case FieldDescriptor::TYPE_MESSAGE:
+ case FieldDescriptor::TYPE_BYTES:
+ case FieldDescriptor::TYPE_ENUM:
+ GOOGLE_LOG(FATAL) << "Unsupported";
+ return 0;
+#define CASE_TYPE(FieldType, CamelFieldType, CamelCppType) \
+ case FieldDescriptor::TYPE_##FieldType: \
+ return WireFormatLite::CamelFieldType##Size( \
+ value.Get##CamelCppType##Value());
+
+#define FIXED_CASE_TYPE(FieldType, CamelFieldType) \
+ case FieldDescriptor::TYPE_##FieldType: \
+ return WireFormatLite::k##CamelFieldType##Size;
+
+ CASE_TYPE(INT32, Int32, Int32);
+ CASE_TYPE(INT64, Int64, Int64);
+ CASE_TYPE(UINT32, UInt32, UInt32);
+ CASE_TYPE(UINT64, UInt64, UInt64);
+ CASE_TYPE(SINT32, SInt32, Int32);
+ CASE_TYPE(SINT64, SInt64, Int64);
+ CASE_TYPE(STRING, String, String);
+ FIXED_CASE_TYPE(FIXED32, Fixed32);
+ FIXED_CASE_TYPE(FIXED64, Fixed64);
+ FIXED_CASE_TYPE(SFIXED32, SFixed32);
+ FIXED_CASE_TYPE(SFIXED64, SFixed64);
+ FIXED_CASE_TYPE(BOOL, Bool);
+
+#undef CASE_TYPE
+#undef FIXED_CASE_TYPE
+ }
+ GOOGLE_LOG(FATAL) << "Cannot get here";
+ return 0;
+}
+
+static size_t MapValueRefDataOnlyByteSize(const FieldDescriptor* field,
+ const MapValueRef& value) {
+ switch (field->type()) {
+ case FieldDescriptor::TYPE_GROUP:
+ GOOGLE_LOG(FATAL) << "Unsupported";
+ return 0;
+#define CASE_TYPE(FieldType, CamelFieldType, CamelCppType) \
+ case FieldDescriptor::TYPE_##FieldType: \
+ return WireFormatLite::CamelFieldType##Size( \
+ value.Get##CamelCppType##Value());
+
+#define FIXED_CASE_TYPE(FieldType, CamelFieldType) \
+ case FieldDescriptor::TYPE_##FieldType: \
+ return WireFormatLite::k##CamelFieldType##Size;
+
+ CASE_TYPE(INT32, Int32, Int32);
+ CASE_TYPE(INT64, Int64, Int64);
+ CASE_TYPE(UINT32, UInt32, UInt32);
+ CASE_TYPE(UINT64, UInt64, UInt64);
+ CASE_TYPE(SINT32, SInt32, Int32);
+ CASE_TYPE(SINT64, SInt64, Int64);
+ CASE_TYPE(STRING, String, String);
+ CASE_TYPE(BYTES, Bytes, String);
+ CASE_TYPE(ENUM, Enum, Enum);
+ CASE_TYPE(MESSAGE, Message, Message);
+ FIXED_CASE_TYPE(FIXED32, Fixed32);
+ FIXED_CASE_TYPE(FIXED64, Fixed64);
+ FIXED_CASE_TYPE(SFIXED32, SFixed32);
+ FIXED_CASE_TYPE(SFIXED64, SFixed64);
+ FIXED_CASE_TYPE(DOUBLE, Double);
+ FIXED_CASE_TYPE(FLOAT, Float);
+ FIXED_CASE_TYPE(BOOL, Bool);
+
+#undef CASE_TYPE
+#undef FIXED_CASE_TYPE
+ }
+ GOOGLE_LOG(FATAL) << "Cannot get here";
+ return 0;
+}
+
size_t WireFormat::FieldDataOnlyByteSize(
const FieldDescriptor* field,
const Message& message) {
const Reflection* message_reflection = message.GetReflection();
+ size_t data_size = 0;
+
+ if (field->is_map()) {
+ MapFieldBase* map_field =
+ message_reflection->MapData(const_cast<Message*>(&message), field);
+ if (map_field->IsMapValid()) {
+ MapIterator iter(const_cast<Message*>(&message), field);
+ MapIterator end(const_cast<Message*>(&message), field);
+ const FieldDescriptor* key_field = field->message_type()->field(0);
+ const FieldDescriptor* value_field = field->message_type()->field(1);
+ for (map_field->MapBegin(&iter), map_field->MapEnd(&end); iter != end;
+ ++iter) {
+ size_t size = kMapEntryTagByteSize;
+ size += MapKeyDataOnlyByteSize(key_field, iter.GetKey());
+ size += MapValueRefDataOnlyByteSize(value_field, iter.GetValueRef());
+ data_size += WireFormatLite::LengthDelimitedSize(size);
+ }
+ return data_size;
+ }
+ }
+
size_t count = 0;
if (field->is_repeated()) {
count =
internal::FromIntSize(message_reflection->FieldSize(message, field));
+ } else if (field->containing_type()->options().map_entry()) {
+ // Map entry fields always need to be serialized.
+ count = 1;
} else if (message_reflection->HasField(message, field)) {
count = 1;
}
- size_t data_size = 0;
switch (field->type()) {
#define HANDLE_TYPE(TYPE, TYPE_METHOD, CPPTYPE_METHOD) \
case FieldDescriptor::TYPE_##TYPE: \
diff --git a/src/google/protobuf/wire_format.h b/src/google/protobuf/wire_format.h
index de8ea574..d602d214 100644
--- a/src/google/protobuf/wire_format.h
+++ b/src/google/protobuf/wire_format.h
@@ -41,16 +41,10 @@
#include <string>
#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/message.h>
#include <google/protobuf/wire_format_lite.h>
-// Do UTF-8 validation on string type in Debug build only
-#ifndef NDEBUG
-#define GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
-#endif
-
namespace google {
namespace protobuf {
namespace io {
@@ -327,6 +321,9 @@ inline void WireFormat::VerifyUTF8StringNamedField(
#ifdef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
WireFormatLite::VerifyUtf8String(
data, size, static_cast<WireFormatLite::Operation>(op), field_name);
+#else
+ // Avoid the compiler warning about unused variables.
+ (void)data; (void)size; (void)op; (void)field_name;
#endif
}
diff --git a/src/google/protobuf/wire_format_lite.cc b/src/google/protobuf/wire_format_lite.cc
index 5a8857ed..cd343b74 100644
--- a/src/google/protobuf/wire_format_lite.cc
+++ b/src/google/protobuf/wire_format_lite.cc
@@ -34,6 +34,9 @@
#include <google/protobuf/wire_format_lite_inl.h>
+#ifdef __SSE_4_1__
+#include <immintrin.h>
+#endif
#include <stack>
#include <string>
#include <vector>
@@ -120,6 +123,8 @@ WireFormatLite::kWireTypeForFieldType[MAX_FIELD_TYPE + 1] = {
bool WireFormatLite::SkipField(
io::CodedInputStream* input, uint32 tag) {
+ // Field number 0 is illegal.
+ if (WireFormatLite::GetTagFieldNumber(tag) == 0) return false;
switch (WireFormatLite::GetTagWireType(tag)) {
case WireFormatLite::WIRETYPE_VARINT: {
uint64 value;
@@ -165,6 +170,8 @@ bool WireFormatLite::SkipField(
bool WireFormatLite::SkipField(
io::CodedInputStream* input, uint32 tag, io::CodedOutputStream* output) {
+ // Field number 0 is illegal.
+ if (WireFormatLite::GetTagFieldNumber(tag) == 0) return false;
switch (WireFormatLite::GetTagWireType(tag)) {
case WireFormatLite::WIRETYPE_VARINT: {
uint64 value;
@@ -337,6 +344,94 @@ bool WireFormatLite::ReadPackedEnumPreserveUnknowns(
return true;
}
+#if !defined(PROTOBUF_LITTLE_ENDIAN)
+
+namespace {
+void EncodeFixedSizeValue(float v, uint8* dest) {
+ WireFormatLite::WriteFloatNoTagToArray(v, dest);
+}
+
+void EncodeFixedSizeValue(double v, uint8* dest) {
+ WireFormatLite::WriteDoubleNoTagToArray(v, dest);
+}
+
+void EncodeFixedSizeValue(uint32 v, uint8* dest) {
+ WireFormatLite::WriteFixed32NoTagToArray(v, dest);
+}
+
+void EncodeFixedSizeValue(uint64 v, uint8* dest) {
+ WireFormatLite::WriteFixed64NoTagToArray(v, dest);
+}
+
+void EncodeFixedSizeValue(int32 v, uint8* dest) {
+ WireFormatLite::WriteSFixed32NoTagToArray(v, dest);
+}
+
+void EncodeFixedSizeValue(int64 v, uint8* dest) {
+ WireFormatLite::WriteSFixed64NoTagToArray(v, dest);
+}
+
+void EncodeFixedSizeValue(bool v, uint8* dest) {
+ WireFormatLite::WriteBoolNoTagToArray(v, dest);
+}
+} // anonymous namespace
+
+#endif // !defined(PROTOBUF_LITTLE_ENDIAN)
+
+template <typename CType>
+static void WriteArray(const CType* a, int n, io::CodedOutputStream* output) {
+#if defined(PROTOBUF_LITTLE_ENDIAN)
+ output->WriteRaw(reinterpret_cast<const char*>(a), n * sizeof(a[0]));
+#else
+ const int kAtATime = 128;
+ uint8 buf[sizeof(CType) * kAtATime];
+ for (int i = 0; i < n; i += kAtATime) {
+ int to_do = std::min(kAtATime, n - i);
+ uint8* ptr = buf;
+ for (int j = 0; j < to_do; j++) {
+ EncodeFixedSizeValue(a[i+j], ptr);
+ ptr += sizeof(a[0]);
+ }
+ output->WriteRaw(buf, to_do * sizeof(a[0]));
+ }
+#endif
+}
+
+void WireFormatLite::WriteFloatArray(const float* a, int n,
+ io::CodedOutputStream* output) {
+ WriteArray<float>(a, n, output);
+}
+
+void WireFormatLite::WriteDoubleArray(const double* a, int n,
+ io::CodedOutputStream* output) {
+ WriteArray<double>(a, n, output);
+}
+
+void WireFormatLite::WriteFixed32Array(const uint32* a, int n,
+ io::CodedOutputStream* output) {
+ WriteArray<uint32>(a, n, output);
+}
+
+void WireFormatLite::WriteFixed64Array(const uint64* a, int n,
+ io::CodedOutputStream* output) {
+ WriteArray<uint64>(a, n, output);
+}
+
+void WireFormatLite::WriteSFixed32Array(const int32* a, int n,
+ io::CodedOutputStream* output) {
+ WriteArray<int32>(a, n, output);
+}
+
+void WireFormatLite::WriteSFixed64Array(const int64* a, int n,
+ io::CodedOutputStream* output) {
+ WriteArray<int64>(a, n, output);
+}
+
+void WireFormatLite::WriteBoolArray(const bool* a, int n,
+ io::CodedOutputStream* output) {
+ WriteArray<bool>(a, n, output);
+}
+
void WireFormatLite::WriteInt32(int field_number, int32 value,
io::CodedOutputStream* output) {
WriteTag(field_number, WIRETYPE_VARINT, output);
@@ -491,7 +586,7 @@ void WireFormatLite::WriteMessageMaybeToArray(int field_number,
}
}
-GOOGLE_ATTRIBUTE_ALWAYS_INLINE static bool ReadBytesToString(
+GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static bool ReadBytesToString(
io::CodedInputStream* input, string* value);
inline static bool ReadBytesToString(io::CodedInputStream* input,
string* value) {
@@ -540,6 +635,152 @@ bool WireFormatLite::VerifyUtf8String(const char* data,
return true;
}
+#ifdef __SSE_4_1__
+template<typename T, bool ZigZag, bool SignExtended>
+static size_t VarintSize(
+ const T* data, const int n,
+ const internal::enable_if<sizeof(T) == 4>::type* = NULL) {
+#if __cplusplus >= 201103L
+ // is_unsigned<T> => !ZigZag
+ static_assert((std::is_unsigned<T>::value ^ ZigZag) ||
+ std::is_signed<T>::value,
+ "Cannot ZigZag encode unsigned types");
+ // is_unsigned<T> => !SignExtended
+ static_assert((std::is_unsigned<T>::value ^ SignExtended) ||
+ std::is_signed<T>::value,
+ "Cannot SignExtended unsigned types");
+#endif
+
+ union vus32 {
+ uint32 u[4];
+ int32 s[4];
+ __m128i v;
+ };
+
+ static const vus32 ones = {{1, 1, 1, 1}};
+
+ // CodedOutputStream::VarintSize32SignExtended returns 10 for negative
+ // numbers. We can apply the UInt32Size algorithm, and simultaneously logical
+ // shift the MSB into the LSB to determine if it is negative.
+ static const vus32 fives = {{5, 5, 5, 5}};
+
+ // sum is the vectorized-output of calling CodedOutputStream::VarintSize32 on
+ // the processed elements.
+ //
+ // msb_sum is the count of set most-significant bits. When computing the
+ // vectorized CodedOutputStream::VarintSize32SignExtended, negative values
+ // have the most significant bit set. VarintSize32SignExtended returns 10 and
+ // VarintSize32 returns 5. msb_sum allows us to compute:
+ // VarintSize32SignExtended = msb_sum * 5 + VarintSize32
+ vus32 sum, v, msb_sum;
+ sum.v = _mm_setzero_si128();
+ msb_sum.v = _mm_setzero_si128();
+
+ int rounded = n & ~(3);
+ int i;
+ for (i = 0; i < rounded; i += 4) {
+ v.v = _mm_loadu_si128(reinterpret_cast<const __m128i*>(&data[i]));
+
+ if (ZigZag) {
+ // Note: the right-shift must be arithmetic
+ v.v = _mm_xor_si128(_mm_slli_epi32(v.v, 1), _mm_srai_epi32(v.v, 31));
+ }
+
+ sum.v = _mm_add_epi32(sum.v, ones.v);
+ if (SignExtended) {
+ msb_sum.v = _mm_add_epi32(msb_sum.v, _mm_srli_epi32(v.v, 31));
+ }
+
+ v.v = _mm_srli_epi32(v.v, 7);
+
+ for (int j = 0; j < 4; j++) {
+ __m128i min = _mm_min_epi32(v.v, ones.v);
+
+ sum.v = _mm_add_epi32(sum.v, min);
+ v.v = _mm_srli_epi32(v.v, 7);
+ }
+ }
+
+ if (SignExtended) {
+ vus32 extensions;
+ extensions.v = _mm_mullo_epi32(msb_sum.v, fives.v);
+
+ sum.v = _mm_add_epi32(sum.v, extensions.v);
+ }
+
+ // TODO(ckennelly): Can we avoid the sign conversion?
+ size_t out = _mm_cvtsi128_si32(
+ _mm_hadd_epi32(_mm_hadd_epi32(sum.v, ones.v), ones.v));
+
+ // Finish tail.
+ for (; i < n; i++) {
+ if (ZigZag) {
+ out += WireFormatLite::SInt32Size(data[i]);
+ } else if (SignExtended) {
+ out += WireFormatLite::Int32Size(data[i]);
+ } else {
+ out += WireFormatLite::UInt32Size(data[i]);
+ }
+ }
+
+ return out;
+}
+
+size_t WireFormatLite::Int32Size(const RepeatedField<int32>& value) {
+ return VarintSize<int32, false, true>(value.data(), value.size());
+}
+
+size_t WireFormatLite::UInt32Size(const RepeatedField<uint32>& value) {
+ return VarintSize<uint32, false, false>(value.data(), value.size());
+}
+
+size_t WireFormatLite::SInt32Size(const RepeatedField<int32>& value) {
+ return VarintSize<int32, true, true>(value.data(), value.size());
+}
+
+size_t WireFormatLite::EnumSize(const RepeatedField<int>& value) {
+ // On ILP64, sizeof(int) == 8, which would require a different template.
+ return VarintSize<int, false, true>(value.data(), value.size());
+}
+
+#else // !__SSE_4_1__
+size_t WireFormatLite::Int32Size(const RepeatedField<int32>& value) {
+ size_t out = 0;
+ const int n = value.size();
+ for (int i = 0; i < n; i++) {
+ out += Int32Size(value.Get(i));
+ }
+ return out;
+}
+
+size_t WireFormatLite::UInt32Size(const RepeatedField<uint32>& value) {
+ size_t out = 0;
+ const int n = value.size();
+ for (int i = 0; i < n; i++) {
+ out += UInt32Size(value.Get(i));
+ }
+ return out;
+}
+
+size_t WireFormatLite::SInt32Size(const RepeatedField<int32>& value) {
+ size_t out = 0;
+ const int n = value.size();
+ for (int i = 0; i < n; i++) {
+ out += SInt32Size(value.Get(i));
+ }
+ return out;
+}
+
+size_t WireFormatLite::EnumSize(const RepeatedField<int>& value) {
+ size_t out = 0;
+ const int n = value.size();
+ for (int i = 0; i < n; i++) {
+ out += EnumSize(value.Get(i));
+ }
+ return out;
+}
+#endif
+
} // namespace internal
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/wire_format_lite.h b/src/google/protobuf/wire_format_lite.h
index cfd1688c..cf614c02 100644
--- a/src/google/protobuf/wire_format_lite.h
+++ b/src/google/protobuf/wire_format_lite.h
@@ -41,9 +41,27 @@
#define GOOGLE_PROTOBUF_WIRE_FORMAT_LITE_H__
#include <string>
+
#include <google/protobuf/stubs/common.h>
+#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/message_lite.h>
-#include <google/protobuf/io/coded_stream.h> // for CodedOutputStream::Varint32Size
+#include <google/protobuf/stubs/port.h>
+#include <google/protobuf/repeated_field.h>
+
+// Do UTF-8 validation on string type in Debug build only
+#ifndef NDEBUG
+#define GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
+#endif
+
+// Avoid conflict with iOS where <ConditionalMacros.h> #defines TYPE_BOOL.
+//
+// If some one needs the macro TYPE_BOOL in a file that includes this header, it's
+// possible to bring it back using push/pop_macro as follows.
+//
+// #pragma push_macro("TYPE_BOOL")
+// #include this header and/or all headers that need the macro to be undefined.
+// #pragma pop_macro("TYPE_BOOL")
+#undef TYPE_BOOL
namespace google {
@@ -133,7 +151,7 @@ class LIBPROTOBUF_EXPORT WireFormatLite {
// Helper method to get the CppType for a particular Type.
static CppType FieldTypeToCppType(FieldType type);
- // Given a FieldSescriptor::Type return its WireType
+ // Given a FieldDescriptor::Type return its WireType
static inline WireFormatLite::WireType WireTypeForFieldType(
WireFormatLite::FieldType type) {
return kWireTypeForFieldType[type];
@@ -186,7 +204,7 @@ class LIBPROTOBUF_EXPORT WireFormatLite {
// type-safe, though, so prefer it if possible.
#define GOOGLE_PROTOBUF_WIRE_FORMAT_MAKE_TAG(FIELD_NUMBER, TYPE) \
static_cast<uint32>( \
- ((FIELD_NUMBER) << ::google::protobuf::internal::WireFormatLite::kTagTypeBits) \
+ (static_cast<uint32>(FIELD_NUMBER) << ::google::protobuf::internal::WireFormatLite::kTagTypeBits) \
| (TYPE))
// These are the tags for the old MessageSet format, which was defined as:
@@ -239,12 +257,8 @@ class LIBPROTOBUF_EXPORT WireFormatLite {
// of these methods are defined in wire_format_lite_inl.h; you must #include
// that file to use these.
-// Avoid ugly line wrapping
-#define input io::CodedInputStream* input_arg
-#define output io::CodedOutputStream* output_arg
-#define field_number int field_number_arg
#ifdef NDEBUG
-#define INL GOOGLE_ATTRIBUTE_ALWAYS_INLINE
+#define INL GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
#else
// Avoid excessive inlining in non-optimized builds. Without other optimizations
// the inlining is not going to provide benefits anyway and the huge resulting
@@ -259,24 +273,22 @@ class LIBPROTOBUF_EXPORT WireFormatLite {
// For primitive fields, we just use a templatized routine parameterized by
// the represented type and the FieldType. These are specialized with the
// appropriate definition for each declared type.
- template <typename CType, enum FieldType DeclaredType> INL
- static bool ReadPrimitive(input, CType* value);
+ template <typename CType, enum FieldType DeclaredType>
+ INL static bool ReadPrimitive(io::CodedInputStream* input, CType* value);
// Reads repeated primitive values, with optimizations for repeats.
// tag_size and tag should both be compile-time constants provided by the
// protocol compiler.
- template <typename CType, enum FieldType DeclaredType> INL
- static bool ReadRepeatedPrimitive(int tag_size,
- uint32 tag,
- input,
- RepeatedField<CType>* value);
+ template <typename CType, enum FieldType DeclaredType>
+ INL static bool ReadRepeatedPrimitive(int tag_size, uint32 tag,
+ io::CodedInputStream* input,
+ RepeatedField<CType>* value);
// Identical to ReadRepeatedPrimitive, except will not inline the
// implementation.
template <typename CType, enum FieldType DeclaredType>
- static bool ReadRepeatedPrimitiveNoInline(int tag_size,
- uint32 tag,
- input,
+ static bool ReadRepeatedPrimitiveNoInline(int tag_size, uint32 tag,
+ io::CodedInputStream* input,
RepeatedField<CType>* value);
// Reads a primitive value directly from the provided buffer. It returns a
@@ -290,40 +302,39 @@ class LIBPROTOBUF_EXPORT WireFormatLite {
// Reads a primitive packed field.
//
// This is only implemented for packable types.
- template <typename CType, enum FieldType DeclaredType> INL
- static bool ReadPackedPrimitive(input, RepeatedField<CType>* value);
+ template <typename CType, enum FieldType DeclaredType>
+ INL static bool ReadPackedPrimitive(io::CodedInputStream* input,
+ RepeatedField<CType>* value);
// Identical to ReadPackedPrimitive, except will not inline the
// implementation.
template <typename CType, enum FieldType DeclaredType>
- static bool ReadPackedPrimitiveNoInline(input, RepeatedField<CType>* value);
+ static bool ReadPackedPrimitiveNoInline(io::CodedInputStream* input,
+ RepeatedField<CType>* value);
// Read a packed enum field. If the is_valid function is not NULL, values for
// which is_valid(value) returns false are silently dropped.
- static bool ReadPackedEnumNoInline(input,
+ static bool ReadPackedEnumNoInline(io::CodedInputStream* input,
bool (*is_valid)(int),
RepeatedField<int>* values);
// Read a packed enum field. If the is_valid function is not NULL, values for
// which is_valid(value) returns false are appended to unknown_fields_stream.
static bool ReadPackedEnumPreserveUnknowns(
- input,
- field_number,
- bool (*is_valid)(int),
- io::CodedOutputStream* unknown_fields_stream,
- RepeatedField<int>* values);
+ io::CodedInputStream* input, int field_number, bool (*is_valid)(int),
+ io::CodedOutputStream* unknown_fields_stream, RepeatedField<int>* values);
// Read a string. ReadString(..., string* value) requires an existing string.
- static inline bool ReadString(input, string* value);
+ static inline bool ReadString(io::CodedInputStream* input, string* value);
// ReadString(..., string** p) is internal-only, and should only be called
// from generated code. It starts by setting *p to "new string"
// if *p == &GetEmptyStringAlreadyInited(). It then invokes
- // ReadString(input, *p). This is useful for reducing code size.
- static inline bool ReadString(input, string** p);
+ // ReadString(io::CodedInputStream* input, *p). This is useful for reducing
+ // code size.
+ static inline bool ReadString(io::CodedInputStream* input, string** p);
// Analogous to ReadString().
- static bool ReadBytes(input, string* value);
- static bool ReadBytes(input, string** p);
-
+ static bool ReadBytes(io::CodedInputStream* input, string* value);
+ static bool ReadBytes(io::CodedInputStream* input, string** p);
enum Operation {
PARSE = 0,
@@ -335,186 +346,322 @@ class LIBPROTOBUF_EXPORT WireFormatLite {
Operation op,
const char* field_name);
- static inline bool ReadGroup (field_number, input, MessageLite* value);
- static inline bool ReadMessage(input, MessageLite* value);
+ static inline bool ReadGroup(int field_number, io::CodedInputStream* input,
+ MessageLite* value);
+ static inline bool ReadMessage(io::CodedInputStream* input,
+ MessageLite* value);
// Like above, but de-virtualize the call to MergePartialFromCodedStream().
// The pointer must point at an instance of MessageType, *not* a subclass (or
// the subclass must not override MergePartialFromCodedStream()).
- template<typename MessageType>
- static inline bool ReadGroupNoVirtual(field_number, input,
+ template <typename MessageType>
+ static inline bool ReadGroupNoVirtual(int field_number,
+ io::CodedInputStream* input,
MessageType* value);
template<typename MessageType>
- static inline bool ReadMessageNoVirtual(input, MessageType* value);
+ static inline bool ReadMessageNoVirtual(io::CodedInputStream* input,
+ MessageType* value);
// The same, but do not modify input's recursion depth. This is useful
// when reading a bunch of groups or messages in a loop, because then the
// recursion depth can be incremented before the loop and decremented after.
template<typename MessageType>
- static inline bool ReadGroupNoVirtualNoRecursionDepth(field_number, input,
- MessageType* value);
+ static inline bool ReadGroupNoVirtualNoRecursionDepth(
+ int field_number, io::CodedInputStream* input, MessageType* value);
template<typename MessageType>
- static inline bool ReadMessageNoVirtualNoRecursionDepth(input,
- MessageType* value);
+ static inline bool ReadMessageNoVirtualNoRecursionDepth(
+ io::CodedInputStream* input, MessageType* value);
// Write a tag. The Write*() functions typically include the tag, so
// normally there's no need to call this unless using the Write*NoTag()
// variants.
- INL static void WriteTag(field_number, WireType type, output);
+ INL static void WriteTag(int field_number, WireType type,
+ io::CodedOutputStream* output);
// Write fields, without tags.
- INL static void WriteInt32NoTag (int32 value, output);
- INL static void WriteInt64NoTag (int64 value, output);
- INL static void WriteUInt32NoTag (uint32 value, output);
- INL static void WriteUInt64NoTag (uint64 value, output);
- INL static void WriteSInt32NoTag (int32 value, output);
- INL static void WriteSInt64NoTag (int64 value, output);
- INL static void WriteFixed32NoTag (uint32 value, output);
- INL static void WriteFixed64NoTag (uint64 value, output);
- INL static void WriteSFixed32NoTag(int32 value, output);
- INL static void WriteSFixed64NoTag(int64 value, output);
- INL static void WriteFloatNoTag (float value, output);
- INL static void WriteDoubleNoTag (double value, output);
- INL static void WriteBoolNoTag (bool value, output);
- INL static void WriteEnumNoTag (int value, output);
+ INL static void WriteInt32NoTag(int32 value, io::CodedOutputStream* output);
+ INL static void WriteInt64NoTag(int64 value, io::CodedOutputStream* output);
+ INL static void WriteUInt32NoTag(uint32 value, io::CodedOutputStream* output);
+ INL static void WriteUInt64NoTag(uint64 value, io::CodedOutputStream* output);
+ INL static void WriteSInt32NoTag(int32 value, io::CodedOutputStream* output);
+ INL static void WriteSInt64NoTag(int64 value, io::CodedOutputStream* output);
+ INL static void WriteFixed32NoTag(uint32 value,
+ io::CodedOutputStream* output);
+ INL static void WriteFixed64NoTag(uint64 value,
+ io::CodedOutputStream* output);
+ INL static void WriteSFixed32NoTag(int32 value,
+ io::CodedOutputStream* output);
+ INL static void WriteSFixed64NoTag(int64 value,
+ io::CodedOutputStream* output);
+ INL static void WriteFloatNoTag(float value, io::CodedOutputStream* output);
+ INL static void WriteDoubleNoTag(double value, io::CodedOutputStream* output);
+ INL static void WriteBoolNoTag(bool value, io::CodedOutputStream* output);
+ INL static void WriteEnumNoTag(int value, io::CodedOutputStream* output);
+
+ // Write array of primitive fields, without tags
+ static void WriteFloatArray(const float* a, int n,
+ io::CodedOutputStream* output);
+ static void WriteDoubleArray(const double* a, int n,
+ io::CodedOutputStream* output);
+ static void WriteFixed32Array(const uint32* a, int n,
+ io::CodedOutputStream* output);
+ static void WriteFixed64Array(const uint64* a, int n,
+ io::CodedOutputStream* output);
+ static void WriteSFixed32Array(const int32* a, int n,
+ io::CodedOutputStream* output);
+ static void WriteSFixed64Array(const int64* a, int n,
+ io::CodedOutputStream* output);
+ static void WriteBoolArray(const bool* a, int n,
+ io::CodedOutputStream* output);
// Write fields, including tags.
- static void WriteInt32 (field_number, int32 value, output);
- static void WriteInt64 (field_number, int64 value, output);
- static void WriteUInt32 (field_number, uint32 value, output);
- static void WriteUInt64 (field_number, uint64 value, output);
- static void WriteSInt32 (field_number, int32 value, output);
- static void WriteSInt64 (field_number, int64 value, output);
- static void WriteFixed32 (field_number, uint32 value, output);
- static void WriteFixed64 (field_number, uint64 value, output);
- static void WriteSFixed32(field_number, int32 value, output);
- static void WriteSFixed64(field_number, int64 value, output);
- static void WriteFloat (field_number, float value, output);
- static void WriteDouble (field_number, double value, output);
- static void WriteBool (field_number, bool value, output);
- static void WriteEnum (field_number, int value, output);
-
- static void WriteString(field_number, const string& value, output);
- static void WriteBytes (field_number, const string& value, output);
- static void WriteStringMaybeAliased(
- field_number, const string& value, output);
- static void WriteBytesMaybeAliased(
- field_number, const string& value, output);
-
- static void WriteGroup(
- field_number, const MessageLite& value, output);
- static void WriteMessage(
- field_number, const MessageLite& value, output);
+ static void WriteInt32(int field_number, int32 value,
+ io::CodedOutputStream* output);
+ static void WriteInt64(int field_number, int64 value,
+ io::CodedOutputStream* output);
+ static void WriteUInt32(int field_number, uint32 value,
+ io::CodedOutputStream* output);
+ static void WriteUInt64(int field_number, uint64 value,
+ io::CodedOutputStream* output);
+ static void WriteSInt32(int field_number, int32 value,
+ io::CodedOutputStream* output);
+ static void WriteSInt64(int field_number, int64 value,
+ io::CodedOutputStream* output);
+ static void WriteFixed32(int field_number, uint32 value,
+ io::CodedOutputStream* output);
+ static void WriteFixed64(int field_number, uint64 value,
+ io::CodedOutputStream* output);
+ static void WriteSFixed32(int field_number, int32 value,
+ io::CodedOutputStream* output);
+ static void WriteSFixed64(int field_number, int64 value,
+ io::CodedOutputStream* output);
+ static void WriteFloat(int field_number, float value,
+ io::CodedOutputStream* output);
+ static void WriteDouble(int field_number, double value,
+ io::CodedOutputStream* output);
+ static void WriteBool(int field_number, bool value,
+ io::CodedOutputStream* output);
+ static void WriteEnum(int field_number, int value,
+ io::CodedOutputStream* output);
+
+ static void WriteString(int field_number, const string& value,
+ io::CodedOutputStream* output);
+ static void WriteBytes(int field_number, const string& value,
+ io::CodedOutputStream* output);
+ static void WriteStringMaybeAliased(int field_number, const string& value,
+ io::CodedOutputStream* output);
+ static void WriteBytesMaybeAliased(int field_number, const string& value,
+ io::CodedOutputStream* output);
+
+ static void WriteGroup(int field_number, const MessageLite& value,
+ io::CodedOutputStream* output);
+ static void WriteMessage(int field_number, const MessageLite& value,
+ io::CodedOutputStream* output);
// Like above, but these will check if the output stream has enough
// space to write directly to a flat array.
- static void WriteGroupMaybeToArray(
- field_number, const MessageLite& value, output);
- static void WriteMessageMaybeToArray(
- field_number, const MessageLite& value, output);
+ static void WriteGroupMaybeToArray(int field_number, const MessageLite& value,
+ io::CodedOutputStream* output);
+ static void WriteMessageMaybeToArray(int field_number,
+ const MessageLite& value,
+ io::CodedOutputStream* output);
// Like above, but de-virtualize the call to SerializeWithCachedSizes(). The
// pointer must point at an instance of MessageType, *not* a subclass (or
// the subclass must not override SerializeWithCachedSizes()).
- template<typename MessageType>
- static inline void WriteGroupNoVirtual(
- field_number, const MessageType& value, output);
- template<typename MessageType>
- static inline void WriteMessageNoVirtual(
- field_number, const MessageType& value, output);
-
-#undef output
-#define output uint8* target
+ template <typename MessageType>
+ static inline void WriteGroupNoVirtual(int field_number,
+ const MessageType& value,
+ io::CodedOutputStream* output);
+ template <typename MessageType>
+ static inline void WriteMessageNoVirtual(int field_number,
+ const MessageType& value,
+ io::CodedOutputStream* output);
// Like above, but use only *ToArray methods of CodedOutputStream.
- INL static uint8* WriteTagToArray(field_number, WireType type, output);
+ INL static uint8* WriteTagToArray(int field_number, WireType type,
+ uint8* target);
// Write fields, without tags.
- INL static uint8* WriteInt32NoTagToArray (int32 value, output);
- INL static uint8* WriteInt64NoTagToArray (int64 value, output);
- INL static uint8* WriteUInt32NoTagToArray (uint32 value, output);
- INL static uint8* WriteUInt64NoTagToArray (uint64 value, output);
- INL static uint8* WriteSInt32NoTagToArray (int32 value, output);
- INL static uint8* WriteSInt64NoTagToArray (int64 value, output);
- INL static uint8* WriteFixed32NoTagToArray (uint32 value, output);
- INL static uint8* WriteFixed64NoTagToArray (uint64 value, output);
- INL static uint8* WriteSFixed32NoTagToArray(int32 value, output);
- INL static uint8* WriteSFixed64NoTagToArray(int64 value, output);
- INL static uint8* WriteFloatNoTagToArray (float value, output);
- INL static uint8* WriteDoubleNoTagToArray (double value, output);
- INL static uint8* WriteBoolNoTagToArray (bool value, output);
- INL static uint8* WriteEnumNoTagToArray (int value, output);
+ INL static uint8* WriteInt32NoTagToArray(int32 value, uint8* target);
+ INL static uint8* WriteInt64NoTagToArray(int64 value, uint8* target);
+ INL static uint8* WriteUInt32NoTagToArray(uint32 value, uint8* target);
+ INL static uint8* WriteUInt64NoTagToArray(uint64 value, uint8* target);
+ INL static uint8* WriteSInt32NoTagToArray(int32 value, uint8* target);
+ INL static uint8* WriteSInt64NoTagToArray(int64 value, uint8* target);
+ INL static uint8* WriteFixed32NoTagToArray(uint32 value, uint8* target);
+ INL static uint8* WriteFixed64NoTagToArray(uint64 value, uint8* target);
+ INL static uint8* WriteSFixed32NoTagToArray(int32 value, uint8* target);
+ INL static uint8* WriteSFixed64NoTagToArray(int64 value, uint8* target);
+ INL static uint8* WriteFloatNoTagToArray(float value, uint8* target);
+ INL static uint8* WriteDoubleNoTagToArray(double value, uint8* target);
+ INL static uint8* WriteBoolNoTagToArray(bool value, uint8* target);
+ INL static uint8* WriteEnumNoTagToArray(int value, uint8* target);
+
+ // Write fields, without tags. These require that value.size() > 0.
+ template<typename T>
+ INL static uint8* WritePrimitiveNoTagToArray(
+ const RepeatedField<T>& value,
+ uint8* (*Writer)(T, uint8*), uint8* target);
+ template<typename T>
+ INL static uint8* WriteFixedNoTagToArray(
+ const RepeatedField<T>& value,
+ uint8* (*Writer)(T, uint8*), uint8* target);
+
+ INL static uint8* WriteInt32NoTagToArray(
+ const RepeatedField< int32>& value, uint8* output);
+ INL static uint8* WriteInt64NoTagToArray(
+ const RepeatedField< int64>& value, uint8* output);
+ INL static uint8* WriteUInt32NoTagToArray(
+ const RepeatedField<uint32>& value, uint8* output);
+ INL static uint8* WriteUInt64NoTagToArray(
+ const RepeatedField<uint64>& value, uint8* output);
+ INL static uint8* WriteSInt32NoTagToArray(
+ const RepeatedField< int32>& value, uint8* output);
+ INL static uint8* WriteSInt64NoTagToArray(
+ const RepeatedField< int64>& value, uint8* output);
+ INL static uint8* WriteFixed32NoTagToArray(
+ const RepeatedField<uint32>& value, uint8* output);
+ INL static uint8* WriteFixed64NoTagToArray(
+ const RepeatedField<uint64>& value, uint8* output);
+ INL static uint8* WriteSFixed32NoTagToArray(
+ const RepeatedField< int32>& value, uint8* output);
+ INL static uint8* WriteSFixed64NoTagToArray(
+ const RepeatedField< int64>& value, uint8* output);
+ INL static uint8* WriteFloatNoTagToArray(
+ const RepeatedField< float>& value, uint8* output);
+ INL static uint8* WriteDoubleNoTagToArray(
+ const RepeatedField<double>& value, uint8* output);
+ INL static uint8* WriteBoolNoTagToArray(
+ const RepeatedField< bool>& value, uint8* output);
+ INL static uint8* WriteEnumNoTagToArray(
+ const RepeatedField< int>& value, uint8* output);
// Write fields, including tags.
- INL static uint8* WriteInt32ToArray(field_number, int32 value, output);
- INL static uint8* WriteInt64ToArray(field_number, int64 value, output);
- INL static uint8* WriteUInt32ToArray(field_number, uint32 value, output);
- INL static uint8* WriteUInt64ToArray(field_number, uint64 value, output);
- INL static uint8* WriteSInt32ToArray(field_number, int32 value, output);
- INL static uint8* WriteSInt64ToArray(field_number, int64 value, output);
- INL static uint8* WriteFixed32ToArray(field_number, uint32 value, output);
- INL static uint8* WriteFixed64ToArray(field_number, uint64 value, output);
- INL static uint8* WriteSFixed32ToArray(field_number, int32 value, output);
- INL static uint8* WriteSFixed64ToArray(field_number, int64 value, output);
- INL static uint8* WriteFloatToArray(field_number, float value, output);
- INL static uint8* WriteDoubleToArray(field_number, double value, output);
- INL static uint8* WriteBoolToArray(field_number, bool value, output);
- INL static uint8* WriteEnumToArray(field_number, int value, output);
-
- INL static uint8* WriteStringToArray(
- field_number, const string& value, output);
- INL static uint8* WriteBytesToArray(
- field_number, const string& value, output);
+ INL static uint8* WriteInt32ToArray(int field_number, int32 value,
+ uint8* target);
+ INL static uint8* WriteInt64ToArray(int field_number, int64 value,
+ uint8* target);
+ INL static uint8* WriteUInt32ToArray(int field_number, uint32 value,
+ uint8* target);
+ INL static uint8* WriteUInt64ToArray(int field_number, uint64 value,
+ uint8* target);
+ INL static uint8* WriteSInt32ToArray(int field_number, int32 value,
+ uint8* target);
+ INL static uint8* WriteSInt64ToArray(int field_number, int64 value,
+ uint8* target);
+ INL static uint8* WriteFixed32ToArray(int field_number, uint32 value,
+ uint8* target);
+ INL static uint8* WriteFixed64ToArray(int field_number, uint64 value,
+ uint8* target);
+ INL static uint8* WriteSFixed32ToArray(int field_number, int32 value,
+ uint8* target);
+ INL static uint8* WriteSFixed64ToArray(int field_number, int64 value,
+ uint8* target);
+ INL static uint8* WriteFloatToArray(int field_number, float value,
+ uint8* target);
+ INL static uint8* WriteDoubleToArray(int field_number, double value,
+ uint8* target);
+ INL static uint8* WriteBoolToArray(int field_number, bool value,
+ uint8* target);
+ INL static uint8* WriteEnumToArray(int field_number, int value,
+ uint8* target);
+
+ template<typename T>
+ INL static uint8* WritePrimitiveToArray(
+ int field_number,
+ const RepeatedField<T>& value,
+ uint8* (*Writer)(int, T, uint8*), uint8* target);
+
+ INL static uint8* WriteInt32ToArray(
+ int field_number, const RepeatedField< int32>& value, uint8* output);
+ INL static uint8* WriteInt64ToArray(
+ int field_number, const RepeatedField< int64>& value, uint8* output);
+ INL static uint8* WriteUInt32ToArray(
+ int field_number, const RepeatedField<uint32>& value, uint8* output);
+ INL static uint8* WriteUInt64ToArray(
+ int field_number, const RepeatedField<uint64>& value, uint8* output);
+ INL static uint8* WriteSInt32ToArray(
+ int field_number, const RepeatedField< int32>& value, uint8* output);
+ INL static uint8* WriteSInt64ToArray(
+ int field_number, const RepeatedField< int64>& value, uint8* output);
+ INL static uint8* WriteFixed32ToArray(
+ int field_number, const RepeatedField<uint32>& value, uint8* output);
+ INL static uint8* WriteFixed64ToArray(
+ int field_number, const RepeatedField<uint64>& value, uint8* output);
+ INL static uint8* WriteSFixed32ToArray(
+ int field_number, const RepeatedField< int32>& value, uint8* output);
+ INL static uint8* WriteSFixed64ToArray(
+ int field_number, const RepeatedField< int64>& value, uint8* output);
+ INL static uint8* WriteFloatToArray(
+ int field_number, const RepeatedField< float>& value, uint8* output);
+ INL static uint8* WriteDoubleToArray(
+ int field_number, const RepeatedField<double>& value, uint8* output);
+ INL static uint8* WriteBoolToArray(
+ int field_number, const RepeatedField< bool>& value, uint8* output);
+ INL static uint8* WriteEnumToArray(
+ int field_number, const RepeatedField< int>& value, uint8* output);
+
+ INL static uint8* WriteStringToArray(int field_number, const string& value,
+ uint8* target);
+ INL static uint8* WriteBytesToArray(int field_number, const string& value,
+ uint8* target);
// Whether to serialize deterministically (e.g., map keys are
// sorted) is a property of a CodedOutputStream, and in the process
// of serialization, the "ToArray" variants may be invoked. But they don't
// have a CodedOutputStream available, so they get an additional parameter
// telling them whether to serialize deterministically.
- INL static uint8* InternalWriteGroupToArray(
- field_number, const MessageLite& value, bool deterministic, output);
- INL static uint8* InternalWriteMessageToArray(
- field_number, const MessageLite& value, bool deterministic, output);
+ INL static uint8* InternalWriteGroupToArray(int field_number,
+ const MessageLite& value,
+ bool deterministic,
+ uint8* target);
+ INL static uint8* InternalWriteMessageToArray(int field_number,
+ const MessageLite& value,
+ bool deterministic,
+ uint8* target);
// Like above, but de-virtualize the call to SerializeWithCachedSizes(). The
// pointer must point at an instance of MessageType, *not* a subclass (or
// the subclass must not override SerializeWithCachedSizes()).
- template<typename MessageType>
- INL static uint8* InternalWriteGroupNoVirtualToArray(
- field_number, const MessageType& value, bool deterministic, output);
- template<typename MessageType>
+ template <typename MessageType>
+ INL static uint8* InternalWriteGroupNoVirtualToArray(int field_number,
+ const MessageType& value,
+ bool deterministic,
+ uint8* target);
+ template <typename MessageType>
INL static uint8* InternalWriteMessageNoVirtualToArray(
- field_number, const MessageType& value, bool deterministic, output);
+ int field_number, const MessageType& value, bool deterministic,
+ uint8* target);
// For backward-compatibility, the last four methods also have versions
// that are non-deterministic always.
- INL static uint8* WriteGroupToArray(
- field_number, const MessageLite& value, output) {
- return InternalWriteGroupToArray(field_number_arg, value, false, target);
+ INL static uint8* WriteGroupToArray(int field_number,
+ const MessageLite& value, uint8* target) {
+ return InternalWriteGroupToArray(field_number, value, false, target);
}
- INL static uint8* WriteMessageToArray(
- field_number, const MessageLite& value, output) {
- return InternalWriteMessageToArray(field_number_arg, value, false, target);
+ INL static uint8* WriteMessageToArray(int field_number,
+ const MessageLite& value,
+ uint8* target) {
+ return InternalWriteMessageToArray(field_number, value, false, target);
}
- template<typename MessageType>
- INL static uint8* WriteGroupNoVirtualToArray(
- field_number, const MessageType& value, output) {
- return InternalWriteGroupNoVirtualToArray(field_number_arg, value, false,
+ template <typename MessageType>
+ INL static uint8* WriteGroupNoVirtualToArray(int field_number,
+ const MessageType& value,
+ uint8* target) {
+ return InternalWriteGroupNoVirtualToArray(field_number, value, false,
target);
}
- template<typename MessageType>
- INL static uint8* WriteMessageNoVirtualToArray(
- field_number, const MessageType& value, output) {
- return InternalWriteMessageNoVirtualToArray(field_number_arg, value, false,
+ template <typename MessageType>
+ INL static uint8* WriteMessageNoVirtualToArray(int field_number,
+ const MessageType& value,
+ uint8* target) {
+ return InternalWriteMessageNoVirtualToArray(field_number, value, false,
target);
}
-#undef output
-#undef input
#undef INL
-#undef field_number
-
// Compute the byte size of a field. The XxSize() functions do NOT include
// the tag, so you must also call TagSize(). (This is because, for repeated
// fields, you should only call TagSize() once and multiply it by the element
@@ -527,6 +674,14 @@ class LIBPROTOBUF_EXPORT WireFormatLite {
static inline size_t SInt64Size ( int64 value);
static inline size_t EnumSize ( int value);
+ static size_t Int32Size (const RepeatedField< int32>& value);
+ static inline size_t Int64Size (const RepeatedField< int64>& value);
+ static size_t UInt32Size(const RepeatedField<uint32>& value);
+ static inline size_t UInt64Size(const RepeatedField<uint64>& value);
+ static size_t SInt32Size(const RepeatedField< int32>& value);
+ static inline size_t SInt64Size(const RepeatedField< int64>& value);
+ static size_t EnumSize (const RepeatedField< int>& value);
+
// These types always have the same size.
static const size_t kFixed32Size = 4;
static const size_t kFixed64Size = 8;
@@ -558,7 +713,8 @@ class LIBPROTOBUF_EXPORT WireFormatLite {
// A helper method for the repeated primitive reader. This method has
// optimizations for primitive types that have fixed size on the wire, and
// can be read using potentially faster paths.
- template <typename CType, enum FieldType DeclaredType> GOOGLE_ATTRIBUTE_ALWAYS_INLINE
+ template <typename CType, enum FieldType DeclaredType>
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
static bool ReadRepeatedFixedSizePrimitive(
int tag_size,
uint32 tag,
@@ -566,9 +722,10 @@ class LIBPROTOBUF_EXPORT WireFormatLite {
RepeatedField<CType>* value);
// Like ReadRepeatedFixedSizePrimitive but for packed primitive fields.
- template <typename CType, enum FieldType DeclaredType> GOOGLE_ATTRIBUTE_ALWAYS_INLINE
- static bool ReadPackedFixedSizePrimitive(google::protobuf::io::CodedInputStream* input,
- RepeatedField<CType>* value);
+ template <typename CType, enum FieldType DeclaredType>
+ GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+ static bool ReadPackedFixedSizePrimitive(
+ google::protobuf::io::CodedInputStream* input, RepeatedField<CType>* value);
static const CppType kFieldTypeToCppTypeMap[];
static const WireFormatLite::WireType kWireTypeForFieldType[];
@@ -638,7 +795,7 @@ inline int WireFormatLite::GetTagFieldNumber(uint32 tag) {
inline size_t WireFormatLite::TagSize(int field_number,
WireFormatLite::FieldType type) {
size_t result = io::CodedOutputStream::VarintSize32(
- field_number << kTagTypeBits);
+ static_cast<uint32>(field_number << kTagTypeBits));
if (type == TYPE_GROUP) {
// Groups have both a start and an end tag.
return result * 2;
@@ -697,20 +854,24 @@ inline double WireFormatLite::DecodeDouble(uint64 value) {
inline uint32 WireFormatLite::ZigZagEncode32(int32 n) {
// Note: the right-shift must be arithmetic
- return (static_cast<uint32>(n) << 1) ^ (n >> 31);
+ // Note: left shift must be unsigned because of overflow
+ return (static_cast<uint32>(n) << 1) ^ static_cast<uint32>(n >> 31);
}
inline int32 WireFormatLite::ZigZagDecode32(uint32 n) {
- return (n >> 1) ^ -static_cast<int32>(n & 1);
+ // Note: Using unsigned types prevent undefined behavior
+ return static_cast<int32>((n >> 1) ^ -(n & 1));
}
inline uint64 WireFormatLite::ZigZagEncode64(int64 n) {
// Note: the right-shift must be arithmetic
- return (static_cast<uint64>(n) << 1) ^ (n >> 63);
+ // Note: left shift must be unsigned because of overflow
+ return (static_cast<uint64>(n) << 1) ^ static_cast<uint64>(n >> 63);
}
inline int64 WireFormatLite::ZigZagDecode64(uint64 n) {
- return (n >> 1) ^ -static_cast<int64>(n & 1);
+ // Note: Using unsigned types prevent undefined behavior
+ return static_cast<int64>((n >> 1) ^ -(n & 1));
}
// String is for UTF-8 text only, but, even so, ReadString() can simply
diff --git a/src/google/protobuf/wire_format_lite_inl.h b/src/google/protobuf/wire_format_lite_inl.h
index 0e46e994..b264bd7e 100644
--- a/src/google/protobuf/wire_format_lite_inl.h
+++ b/src/google/protobuf/wire_format_lite_inl.h
@@ -36,11 +36,7 @@
#ifndef GOOGLE_PROTOBUF_WIRE_FORMAT_LITE_INL_H__
#define GOOGLE_PROTOBUF_WIRE_FORMAT_LITE_INL_H__
-#ifdef _MSC_VER
-// This is required for min/max on VS2013 only.
#include <algorithm>
-#endif
-
#include <string>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/logging.h>
@@ -272,7 +268,7 @@ inline bool WireFormatLite::ReadRepeatedFixedSizePrimitive(
if (size > 0) {
const uint8* buffer = reinterpret_cast<const uint8*>(void_pointer);
// The number of bytes each type occupies on the wire.
- const int per_value_size = tag_size + sizeof(value);
+ const int per_value_size = tag_size + static_cast<int>(sizeof(value));
// parentheses around (std::min) prevents macro expansion of min(...)
int elements_available =
@@ -348,8 +344,8 @@ inline bool WireFormatLite::ReadPackedFixedSizePrimitive(
int length;
if (!input->ReadVarintSizeAsInt(&length)) return false;
const int old_entries = values->size();
- const int new_entries = length / sizeof(CType);
- const int new_bytes = new_entries * sizeof(CType);
+ const int new_entries = length / static_cast<int>(sizeof(CType));
+ const int new_bytes = new_entries * static_cast<int>(sizeof(CType));
if (new_bytes != length) return false;
// We would *like* to pre-allocate the buffer to write into (for
// speed), but *must* avoid performing a very large allocation due
@@ -430,7 +426,6 @@ bool WireFormatLite::ReadPackedPrimitiveNoInline(io::CodedInputStream* input,
}
-
inline bool WireFormatLite::ReadGroup(int field_number,
io::CodedInputStream* input,
MessageLite* value) {
@@ -452,7 +447,7 @@ inline bool WireFormatLite::ReadMessage(io::CodedInputStream* input,
if (p.second < 0 || !value->MergePartialFromCodedStream(input)) return false;
// Make sure that parsing stopped when the limit was hit, not at an endgroup
// tag.
- return input->DecrementRecursionDepthAndPopLimit(p.first);
+ return input->DecrementRecursionDepthAndPopLimit(p.first);
}
// We name the template parameter something long and extremely unlikely to occur
@@ -502,6 +497,7 @@ inline bool WireFormatLite::ReadMessageNoVirtual(
// tag.
return input->DecrementRecursionDepthAndPopLimit(p.first);
}
+
template<typename MessageType_WorkAroundCppLookupDefect>
inline bool WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
io::CodedInputStream* input, MessageType_WorkAroundCppLookupDefect* value) {
@@ -671,6 +667,98 @@ inline uint8* WireFormatLite::WriteEnumNoTagToArray(int value,
return io::CodedOutputStream::WriteVarint32SignExtendedToArray(value, target);
}
+template<typename T>
+inline uint8* WireFormatLite::WritePrimitiveNoTagToArray(
+ const RepeatedField<T>& value,
+ uint8* (*Writer)(T, uint8*), uint8* target) {
+ const int n = value.size();
+ GOOGLE_DCHECK_GT(n, 0);
+
+ const T* ii = value.unsafe_data();
+ int i = 0;
+ do {
+ target = Writer(ii[i], target);
+ } while (++i < n);
+
+ return target;
+}
+
+template<typename T>
+inline uint8* WireFormatLite::WriteFixedNoTagToArray(
+ const RepeatedField<T>& value,
+ uint8* (*Writer)(T, uint8*), uint8* target) {
+#if defined(PROTOBUF_LITTLE_ENDIAN)
+ (void) Writer;
+
+ const int n = value.size();
+ GOOGLE_DCHECK_GT(n, 0);
+
+ const T* ii = value.unsafe_data();
+ const int bytes = n * static_cast<int>(sizeof(ii[0]));
+ memcpy(target, ii, static_cast<size_t>(bytes));
+ return target + bytes;
+#else
+ return WritePrimitiveNoTagToArray(value, Writer, target);
+#endif
+}
+
+inline uint8* WireFormatLite::WriteInt32NoTagToArray(
+ const RepeatedField< int32>& value, uint8* target) {
+ return WritePrimitiveNoTagToArray(value, WriteInt32NoTagToArray, target);
+}
+inline uint8* WireFormatLite::WriteInt64NoTagToArray(
+ const RepeatedField< int64>& value, uint8* target) {
+ return WritePrimitiveNoTagToArray(value, WriteInt64NoTagToArray, target);
+}
+inline uint8* WireFormatLite::WriteUInt32NoTagToArray(
+ const RepeatedField<uint32>& value, uint8* target) {
+ return WritePrimitiveNoTagToArray(value, WriteUInt32NoTagToArray, target);
+}
+inline uint8* WireFormatLite::WriteUInt64NoTagToArray(
+ const RepeatedField<uint64>& value, uint8* target) {
+ return WritePrimitiveNoTagToArray(value, WriteUInt64NoTagToArray, target);
+}
+inline uint8* WireFormatLite::WriteSInt32NoTagToArray(
+ const RepeatedField< int32>& value, uint8* target) {
+ return WritePrimitiveNoTagToArray(value, WriteSInt32NoTagToArray, target);
+}
+inline uint8* WireFormatLite::WriteSInt64NoTagToArray(
+ const RepeatedField< int64>& value, uint8* target) {
+ return WritePrimitiveNoTagToArray(value, WriteSInt64NoTagToArray, target);
+}
+inline uint8* WireFormatLite::WriteFixed32NoTagToArray(
+ const RepeatedField<uint32>& value, uint8* target) {
+ return WriteFixedNoTagToArray(value, WriteFixed32NoTagToArray, target);
+}
+inline uint8* WireFormatLite::WriteFixed64NoTagToArray(
+ const RepeatedField<uint64>& value, uint8* target) {
+ return WriteFixedNoTagToArray(value, WriteFixed64NoTagToArray, target);
+}
+inline uint8* WireFormatLite::WriteSFixed32NoTagToArray(
+ const RepeatedField< int32>& value, uint8* target) {
+ return WriteFixedNoTagToArray(value, WriteSFixed32NoTagToArray, target);
+}
+inline uint8* WireFormatLite::WriteSFixed64NoTagToArray(
+ const RepeatedField< int64>& value, uint8* target) {
+ return WriteFixedNoTagToArray(value, WriteSFixed64NoTagToArray, target);
+}
+inline uint8* WireFormatLite::WriteFloatNoTagToArray(
+ const RepeatedField< float>& value, uint8* target) {
+ return WriteFixedNoTagToArray(value, WriteFloatNoTagToArray, target);
+}
+inline uint8* WireFormatLite::WriteDoubleNoTagToArray(
+ const RepeatedField<double>& value, uint8* target) {
+ return WriteFixedNoTagToArray(value, WriteDoubleNoTagToArray, target);
+}
+inline uint8* WireFormatLite::WriteBoolNoTagToArray(
+ const RepeatedField< bool>& value, uint8* target) {
+ return WritePrimitiveNoTagToArray(value, WriteBoolNoTagToArray, target);
+}
+inline uint8* WireFormatLite::WriteEnumNoTagToArray(
+ const RepeatedField< int>& value, uint8* target) {
+ return WritePrimitiveNoTagToArray(value, WriteEnumNoTagToArray, target);
+}
+
inline uint8* WireFormatLite::WriteInt32ToArray(int field_number,
int32 value,
uint8* target) {
@@ -756,6 +844,85 @@ inline uint8* WireFormatLite::WriteEnumToArray(int field_number,
return WriteEnumNoTagToArray(value, target);
}
+template<typename T>
+inline uint8* WireFormatLite::WritePrimitiveToArray(
+ int field_number,
+ const RepeatedField<T>& value,
+ uint8* (*Writer)(int, T, uint8*), uint8* target) {
+ const int n = value.size();
+ if (n == 0) {
+ return target;
+ }
+
+ const T* ii = value.unsafe_data();
+ int i = 0;
+ do {
+ target = Writer(field_number, ii[i], target);
+ } while (++i < n);
+
+ return target;
+}
+
+inline uint8* WireFormatLite::WriteInt32ToArray(
+ int field_number, const RepeatedField< int32>& value, uint8* target) {
+ return WritePrimitiveToArray(field_number, value, WriteInt32ToArray, target);
+}
+inline uint8* WireFormatLite::WriteInt64ToArray(
+ int field_number, const RepeatedField< int64>& value, uint8* target) {
+ return WritePrimitiveToArray(field_number, value, WriteInt64ToArray, target);
+}
+inline uint8* WireFormatLite::WriteUInt32ToArray(
+ int field_number, const RepeatedField<uint32>& value, uint8* target) {
+ return WritePrimitiveToArray(field_number, value, WriteUInt32ToArray, target);
+}
+inline uint8* WireFormatLite::WriteUInt64ToArray(
+ int field_number, const RepeatedField<uint64>& value, uint8* target) {
+ return WritePrimitiveToArray(field_number, value, WriteUInt64ToArray, target);
+}
+inline uint8* WireFormatLite::WriteSInt32ToArray(
+ int field_number, const RepeatedField< int32>& value, uint8* target) {
+ return WritePrimitiveToArray(field_number, value, WriteSInt32ToArray, target);
+}
+inline uint8* WireFormatLite::WriteSInt64ToArray(
+ int field_number, const RepeatedField< int64>& value, uint8* target) {
+ return WritePrimitiveToArray(field_number, value, WriteSInt64ToArray, target);
+}
+inline uint8* WireFormatLite::WriteFixed32ToArray(
+ int field_number, const RepeatedField<uint32>& value, uint8* target) {
+ return WritePrimitiveToArray(
+ field_number, value, WriteFixed32ToArray, target);
+}
+inline uint8* WireFormatLite::WriteFixed64ToArray(
+ int field_number, const RepeatedField<uint64>& value, uint8* target) {
+ return WritePrimitiveToArray(
+ field_number, value, WriteFixed64ToArray, target);
+}
+inline uint8* WireFormatLite::WriteSFixed32ToArray(
+ int field_number, const RepeatedField< int32>& value, uint8* target) {
+ return WritePrimitiveToArray(
+ field_number, value, WriteSFixed32ToArray, target);
+}
+inline uint8* WireFormatLite::WriteSFixed64ToArray(
+ int field_number, const RepeatedField< int64>& value, uint8* target) {
+ return WritePrimitiveToArray(
+ field_number, value, WriteSFixed64ToArray, target);
+}
+inline uint8* WireFormatLite::WriteFloatToArray(
+ int field_number, const RepeatedField< float>& value, uint8* target) {
+ return WritePrimitiveToArray(field_number, value, WriteFloatToArray, target);
+}
+inline uint8* WireFormatLite::WriteDoubleToArray(
+ int field_number, const RepeatedField<double>& value, uint8* target) {
+ return WritePrimitiveToArray(field_number, value, WriteDoubleToArray, target);
+}
+inline uint8* WireFormatLite::WriteBoolToArray(
+ int field_number, const RepeatedField< bool>& value, uint8* target) {
+ return WritePrimitiveToArray(field_number, value, WriteBoolToArray, target);
+}
+inline uint8* WireFormatLite::WriteEnumToArray(
+ int field_number, const RepeatedField< int>& value, uint8* target) {
+ return WritePrimitiveToArray(field_number, value, WriteEnumToArray, target);
+}
inline uint8* WireFormatLite::WriteStringToArray(int field_number,
const string& value,
uint8* target) {
@@ -786,7 +953,7 @@ inline uint8* WireFormatLite::InternalWriteMessageToArray(
uint8* target) {
target = WriteTagToArray(field_number, WIRETYPE_LENGTH_DELIMITED, target);
target = io::CodedOutputStream::WriteVarint32ToArray(
- value.GetCachedSize(), target);
+ static_cast<uint32>(value.GetCachedSize()), target);
return value.InternalSerializeWithCachedSizesToArray(deterministic, target);
}
@@ -797,7 +964,8 @@ inline uint8* WireFormatLite::InternalWriteGroupNoVirtualToArray(
int field_number, const MessageType_WorkAroundCppLookupDefect& value,
bool deterministic, uint8* target) {
target = WriteTagToArray(field_number, WIRETYPE_START_GROUP, target);
- target = value.InternalSerializeWithCachedSizesToArray(deterministic, target);
+ target = value.MessageType_WorkAroundCppLookupDefect::
+ InternalSerializeWithCachedSizesToArray(deterministic, target);
return WriteTagToArray(field_number, WIRETYPE_END_GROUP, target);
}
template<typename MessageType_WorkAroundCppLookupDefect>
@@ -806,8 +974,11 @@ inline uint8* WireFormatLite::InternalWriteMessageNoVirtualToArray(
bool deterministic, uint8* target) {
target = WriteTagToArray(field_number, WIRETYPE_LENGTH_DELIMITED, target);
target = io::CodedOutputStream::WriteVarint32ToArray(
- value.MessageType_WorkAroundCppLookupDefect::GetCachedSize(), target);
- return value.InternalSerializeWithCachedSizesToArray(deterministic, target);
+ static_cast<uint32>(
+ value.MessageType_WorkAroundCppLookupDefect::GetCachedSize()),
+ target);
+ return value.MessageType_WorkAroundCppLookupDefect::
+ InternalSerializeWithCachedSizesToArray(deterministic, target);
}
// ===================================================================
@@ -872,6 +1043,33 @@ inline size_t WireFormatLite::LengthDelimitedSize(size_t length) {
static_cast<uint32>(length));
}
+size_t WireFormatLite::Int64Size (const RepeatedField< int64>& value) {
+ size_t out = 0;
+ const int n = value.size();
+ for (int i = 0; i < n; i++) {
+ out += Int64Size(value.Get(i));
+ }
+ return out;
+}
+
+size_t WireFormatLite::UInt64Size(const RepeatedField<uint64>& value) {
+ size_t out = 0;
+ const int n = value.size();
+ for (int i = 0; i < n; i++) {
+ out += UInt64Size(value.Get(i));
+ }
+ return out;
+}
+
+size_t WireFormatLite::SInt64Size(const RepeatedField< int64>& value) {
+ size_t out = 0;
+ const int n = value.size();
+ for (int i = 0; i < n; i++) {
+ out += SInt64Size(value.Get(i));
+ }
+ return out;
+}
+
} // namespace internal
} // namespace protobuf
diff --git a/src/google/protobuf/wire_format_unittest.cc b/src/google/protobuf/wire_format_unittest.cc
index faf27b62..cafe9a48 100644
--- a/src/google/protobuf/wire_format_unittest.cc
+++ b/src/google/protobuf/wire_format_unittest.cc
@@ -1029,6 +1029,29 @@ TEST_F(WireFormatInvalidInputTest, InvalidSubMessage) {
EXPECT_FALSE(message.ParseFromString(MakeInvalidEmbeddedMessage("\017", 1)));
}
+TEST_F(WireFormatInvalidInputTest, InvalidMessageWithExtraZero) {
+ string data;
+ {
+ // Serialize a valid proto
+ unittest::TestAllTypes message;
+ message.set_optional_int32(1);
+ message.SerializeToString(&data);
+ data.push_back(0); // Append invalid zero tag
+ }
+
+ // Control case.
+ {
+ io::ArrayInputStream ais(data.data(), data.size());
+ io::CodedInputStream is(&ais);
+ unittest::TestAllTypes message;
+ // It should fail but currently passes.
+ EXPECT_TRUE(message.MergePartialFromCodedStream(&is));
+ // Parsing from the string should fail.
+ EXPECT_FALSE(message.ParseFromString(data));
+ }
+}
+
+
TEST_F(WireFormatInvalidInputTest, InvalidGroup) {
unittest::TestAllTypes message;
@@ -1283,6 +1306,136 @@ TEST_F(Utf8ValidationTest, OldVerifyUTF8String) {
}
+TEST(RepeatedVarint, Int32) {
+ RepeatedField<int32> v;
+
+ // Insert -2^n, 2^n and 2^n-1.
+ for (int n = 0; n < 10; n++) {
+ v.Add(-(1 << n));
+ v.Add(1 << n);
+ v.Add((1 << n) - 1);
+ }
+
+ // Check consistency with the scalar Int32Size.
+ size_t expected = 0;
+ for (int i = 0; i < v.size(); i++) {
+ expected += WireFormatLite::Int32Size(v[i]);
+ }
+
+ EXPECT_EQ(expected, WireFormatLite::Int32Size(v));
+}
+
+TEST(RepeatedVarint, Int64) {
+ RepeatedField<int64> v;
+
+ // Insert -2^n, 2^n and 2^n-1.
+ for (int n = 0; n < 10; n++) {
+ v.Add(-(1 << n));
+ v.Add(1 << n);
+ v.Add((1 << n) - 1);
+ }
+
+ // Check consistency with the scalar Int64Size.
+ size_t expected = 0;
+ for (int i = 0; i < v.size(); i++) {
+ expected += WireFormatLite::Int64Size(v[i]);
+ }
+
+ EXPECT_EQ(expected, WireFormatLite::Int64Size(v));
+}
+
+TEST(RepeatedVarint, SInt32) {
+ RepeatedField<int32> v;
+
+ // Insert -2^n, 2^n and 2^n-1.
+ for (int n = 0; n < 10; n++) {
+ v.Add(-(1 << n));
+ v.Add(1 << n);
+ v.Add((1 << n) - 1);
+ }
+
+ // Check consistency with the scalar SInt32Size.
+ size_t expected = 0;
+ for (int i = 0; i < v.size(); i++) {
+ expected += WireFormatLite::SInt32Size(v[i]);
+ }
+
+ EXPECT_EQ(expected, WireFormatLite::SInt32Size(v));
+}
+
+TEST(RepeatedVarint, SInt64) {
+ RepeatedField<int64> v;
+
+ // Insert -2^n, 2^n and 2^n-1.
+ for (int n = 0; n < 10; n++) {
+ v.Add(-(1 << n));
+ v.Add(1 << n);
+ v.Add((1 << n) - 1);
+ }
+
+ // Check consistency with the scalar SInt64Size.
+ size_t expected = 0;
+ for (int i = 0; i < v.size(); i++) {
+ expected += WireFormatLite::SInt64Size(v[i]);
+ }
+
+ EXPECT_EQ(expected, WireFormatLite::SInt64Size(v));
+}
+
+TEST(RepeatedVarint, UInt32) {
+ RepeatedField<uint32> v;
+
+ // Insert 2^n and 2^n-1.
+ for (int n = 0; n < 10; n++) {
+ v.Add(1 << n);
+ v.Add((1 << n) - 1);
+ }
+
+ // Check consistency with the scalar UInt32Size.
+ size_t expected = 0;
+ for (int i = 0; i < v.size(); i++) {
+ expected += WireFormatLite::UInt32Size(v[i]);
+ }
+
+ EXPECT_EQ(expected, WireFormatLite::UInt32Size(v));
+}
+
+TEST(RepeatedVarint, UInt64) {
+ RepeatedField<uint64> v;
+
+ // Insert 2^n and 2^n-1.
+ for (int n = 0; n < 10; n++) {
+ v.Add(1 << n);
+ v.Add((1 << n) - 1);
+ }
+
+ // Check consistency with the scalar UInt64Size.
+ size_t expected = 0;
+ for (int i = 0; i < v.size(); i++) {
+ expected += WireFormatLite::UInt64Size(v[i]);
+ }
+
+ EXPECT_EQ(expected, WireFormatLite::UInt64Size(v));
+}
+
+TEST(RepeatedVarint, Enum) {
+ RepeatedField<int> v;
+
+ // Insert 2^n and 2^n-1.
+ for (int n = 0; n < 10; n++) {
+ v.Add(1 << n);
+ v.Add((1 << n) - 1);
+ }
+
+ // Check consistency with the scalar EnumSize.
+ size_t expected = 0;
+ for (int i = 0; i < v.size(); i++) {
+ expected += WireFormatLite::EnumSize(v[i]);
+ }
+
+ EXPECT_EQ(expected, WireFormatLite::EnumSize(v));
+}
+
} // namespace
} // namespace internal
} // namespace protobuf
diff --git a/src/google/protobuf/wrappers.pb.cc b/src/google/protobuf/wrappers.pb.cc
index 82a8d9e2..00e01256 100644
--- a/src/google/protobuf/wrappers.pb.cc
+++ b/src/google/protobuf/wrappers.pb.cc
@@ -1,7 +1,6 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/wrappers.proto
-#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include <google/protobuf/wrappers.pb.h>
#include <algorithm>
@@ -15,119 +14,337 @@
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
+// This is a temporary google only hack
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+#include "third_party/protobuf/version.h"
+#endif
// @@protoc_insertion_point(includes)
-
namespace google {
namespace protobuf {
-class DoubleValueDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<DoubleValue> {};
-DoubleValueDefaultTypeInternal _DoubleValue_default_instance_;
-class FloatValueDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<FloatValue> {};
-FloatValueDefaultTypeInternal _FloatValue_default_instance_;
-class Int64ValueDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<Int64Value> {};
-Int64ValueDefaultTypeInternal _Int64Value_default_instance_;
-class UInt64ValueDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<UInt64Value> {};
-UInt64ValueDefaultTypeInternal _UInt64Value_default_instance_;
-class Int32ValueDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<Int32Value> {};
-Int32ValueDefaultTypeInternal _Int32Value_default_instance_;
-class UInt32ValueDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<UInt32Value> {};
-UInt32ValueDefaultTypeInternal _UInt32Value_default_instance_;
-class BoolValueDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<BoolValue> {};
-BoolValueDefaultTypeInternal _BoolValue_default_instance_;
-class StringValueDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<StringValue> {};
-StringValueDefaultTypeInternal _StringValue_default_instance_;
-class BytesValueDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<BytesValue> {};
-BytesValueDefaultTypeInternal _BytesValue_default_instance_;
-
-namespace {
+class DoubleValueDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<DoubleValue>
+ _instance;
+} _DoubleValue_default_instance_;
+class FloatValueDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<FloatValue>
+ _instance;
+} _FloatValue_default_instance_;
+class Int64ValueDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<Int64Value>
+ _instance;
+} _Int64Value_default_instance_;
+class UInt64ValueDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<UInt64Value>
+ _instance;
+} _UInt64Value_default_instance_;
+class Int32ValueDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<Int32Value>
+ _instance;
+} _Int32Value_default_instance_;
+class UInt32ValueDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<UInt32Value>
+ _instance;
+} _UInt32Value_default_instance_;
+class BoolValueDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<BoolValue>
+ _instance;
+} _BoolValue_default_instance_;
+class StringValueDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<StringValue>
+ _instance;
+} _StringValue_default_instance_;
+class BytesValueDefaultTypeInternal {
+ public:
+ ::google::protobuf::internal::ExplicitlyConstructed<BytesValue>
+ _instance;
+} _BytesValue_default_instance_;
+} // namespace protobuf
+} // namespace google
+namespace protobuf_google_2fprotobuf_2fwrappers_2eproto {
+void InitDefaultsDoubleValueImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ {
+ void* ptr = &::google::protobuf::_DoubleValue_default_instance_;
+ new (ptr) ::google::protobuf::DoubleValue();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::DoubleValue::InitAsDefaultInstance();
+}
+
+void InitDefaultsDoubleValue() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsDoubleValueImpl);
+}
+
+void InitDefaultsFloatValueImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ {
+ void* ptr = &::google::protobuf::_FloatValue_default_instance_;
+ new (ptr) ::google::protobuf::FloatValue();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::FloatValue::InitAsDefaultInstance();
+}
+
+void InitDefaultsFloatValue() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsFloatValueImpl);
+}
+
+void InitDefaultsInt64ValueImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ {
+ void* ptr = &::google::protobuf::_Int64Value_default_instance_;
+ new (ptr) ::google::protobuf::Int64Value();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::Int64Value::InitAsDefaultInstance();
+}
+
+void InitDefaultsInt64Value() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsInt64ValueImpl);
+}
+
+void InitDefaultsUInt64ValueImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ {
+ void* ptr = &::google::protobuf::_UInt64Value_default_instance_;
+ new (ptr) ::google::protobuf::UInt64Value();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::UInt64Value::InitAsDefaultInstance();
+}
+
+void InitDefaultsUInt64Value() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsUInt64ValueImpl);
+}
+
+void InitDefaultsInt32ValueImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ {
+ void* ptr = &::google::protobuf::_Int32Value_default_instance_;
+ new (ptr) ::google::protobuf::Int32Value();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::Int32Value::InitAsDefaultInstance();
+}
+
+void InitDefaultsInt32Value() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsInt32ValueImpl);
+}
+
+void InitDefaultsUInt32ValueImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ {
+ void* ptr = &::google::protobuf::_UInt32Value_default_instance_;
+ new (ptr) ::google::protobuf::UInt32Value();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::UInt32Value::InitAsDefaultInstance();
+}
+
+void InitDefaultsUInt32Value() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsUInt32ValueImpl);
+}
+
+void InitDefaultsBoolValueImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ {
+ void* ptr = &::google::protobuf::_BoolValue_default_instance_;
+ new (ptr) ::google::protobuf::BoolValue();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::BoolValue::InitAsDefaultInstance();
+}
+
+void InitDefaultsBoolValue() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsBoolValueImpl);
+}
+
+void InitDefaultsStringValueImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ {
+ void* ptr = &::google::protobuf::_StringValue_default_instance_;
+ new (ptr) ::google::protobuf::StringValue();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::StringValue::InitAsDefaultInstance();
+}
+
+void InitDefaultsStringValue() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsStringValueImpl);
+}
+
+void InitDefaultsBytesValueImpl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ ::google::protobuf::internal::InitProtobufDefaultsForceUnique();
+#else
+ ::google::protobuf::internal::InitProtobufDefaults();
+#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
+ {
+ void* ptr = &::google::protobuf::_BytesValue_default_instance_;
+ new (ptr) ::google::protobuf::BytesValue();
+ ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::google::protobuf::BytesValue::InitAsDefaultInstance();
+}
+
+void InitDefaultsBytesValue() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsBytesValueImpl);
+}
::google::protobuf::Metadata file_level_metadata[9];
-} // namespace
-
-
-const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fwrappers_2eproto() GOOGLE_ATTRIBUTE_COLD;
-const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fwrappers_2eproto() {
- static const ::google::protobuf::uint32 offsets[] = {
- ~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DoubleValue, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DoubleValue, value_),
- ~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FloatValue, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FloatValue, value_),
- ~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Int64Value, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Int64Value, value_),
- ~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UInt64Value, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UInt64Value, value_),
- ~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Int32Value, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Int32Value, value_),
- ~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UInt32Value, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UInt32Value, value_),
- ~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(BoolValue, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(BoolValue, value_),
- ~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(StringValue, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(StringValue, value_),
- ~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(BytesValue, _internal_metadata_),
- ~0u, // no _extensions_
- ~0u, // no _oneof_case_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(BytesValue, value_),
- };
- return offsets;
-}
-
-static const ::google::protobuf::internal::MigrationSchema schemas[] = {
- { 0, -1, sizeof(DoubleValue)},
- { 5, -1, sizeof(FloatValue)},
- { 10, -1, sizeof(Int64Value)},
- { 15, -1, sizeof(UInt64Value)},
- { 20, -1, sizeof(Int32Value)},
- { 25, -1, sizeof(UInt32Value)},
- { 30, -1, sizeof(BoolValue)},
- { 35, -1, sizeof(StringValue)},
- { 40, -1, sizeof(BytesValue)},
+const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+ ~0u, // no _has_bits_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DoubleValue, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DoubleValue, value_),
+ ~0u, // no _has_bits_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FloatValue, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FloatValue, value_),
+ ~0u, // no _has_bits_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Int64Value, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Int64Value, value_),
+ ~0u, // no _has_bits_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UInt64Value, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UInt64Value, value_),
+ ~0u, // no _has_bits_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Int32Value, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Int32Value, value_),
+ ~0u, // no _has_bits_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UInt32Value, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UInt32Value, value_),
+ ~0u, // no _has_bits_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::BoolValue, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::BoolValue, value_),
+ ~0u, // no _has_bits_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::StringValue, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::StringValue, value_),
+ ~0u, // no _has_bits_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::BytesValue, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::BytesValue, value_),
};
-
-static const ::google::protobuf::internal::DefaultInstanceData file_default_instances[] = {
- {reinterpret_cast<const ::google::protobuf::Message*>(&_DoubleValue_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_FloatValue_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_Int64Value_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_UInt64Value_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_Int32Value_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_UInt32Value_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_BoolValue_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_StringValue_default_instance_), NULL},
- {reinterpret_cast<const ::google::protobuf::Message*>(&_BytesValue_default_instance_), NULL},
+static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+ { 0, -1, sizeof(::google::protobuf::DoubleValue)},
+ { 6, -1, sizeof(::google::protobuf::FloatValue)},
+ { 12, -1, sizeof(::google::protobuf::Int64Value)},
+ { 18, -1, sizeof(::google::protobuf::UInt64Value)},
+ { 24, -1, sizeof(::google::protobuf::Int32Value)},
+ { 30, -1, sizeof(::google::protobuf::UInt32Value)},
+ { 36, -1, sizeof(::google::protobuf::BoolValue)},
+ { 42, -1, sizeof(::google::protobuf::StringValue)},
+ { 48, -1, sizeof(::google::protobuf::BytesValue)},
};
-namespace {
+static ::google::protobuf::Message const * const file_default_instances[] = {
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_DoubleValue_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_FloatValue_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_Int64Value_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_UInt64Value_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_Int32Value_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_UInt32Value_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_BoolValue_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_StringValue_default_instance_),
+ reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_BytesValue_default_instance_),
+};
void protobuf_AssignDescriptors() {
- protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto();
+ AddDescriptors();
::google::protobuf::MessageFactory* factory = NULL;
AssignDescriptors(
- "google/protobuf/wrappers.proto", schemas, file_default_instances, protobuf_Offsets_google_2fprotobuf_2fwrappers_2eproto(), factory,
+ "google/protobuf/wrappers.proto", schemas, file_default_instances, TableStruct::offsets, factory,
file_level_metadata, NULL, NULL);
}
@@ -136,57 +353,15 @@ void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);
}
-void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
+void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 9);
}
-} // namespace
-
-void protobuf_ShutdownFile_google_2fprotobuf_2fwrappers_2eproto() {
- _DoubleValue_default_instance_.Shutdown();
- delete file_level_metadata[0].reflection;
- _FloatValue_default_instance_.Shutdown();
- delete file_level_metadata[1].reflection;
- _Int64Value_default_instance_.Shutdown();
- delete file_level_metadata[2].reflection;
- _UInt64Value_default_instance_.Shutdown();
- delete file_level_metadata[3].reflection;
- _Int32Value_default_instance_.Shutdown();
- delete file_level_metadata[4].reflection;
- _UInt32Value_default_instance_.Shutdown();
- delete file_level_metadata[5].reflection;
- _BoolValue_default_instance_.Shutdown();
- delete file_level_metadata[6].reflection;
- _StringValue_default_instance_.Shutdown();
- delete file_level_metadata[7].reflection;
- _BytesValue_default_instance_.Shutdown();
- delete file_level_metadata[8].reflection;
-}
-
-void protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto_impl() {
- GOOGLE_PROTOBUF_VERIFY_VERSION;
-
- ::google::protobuf::internal::InitProtobufDefaults();
- _DoubleValue_default_instance_.DefaultConstruct();
- _FloatValue_default_instance_.DefaultConstruct();
- _Int64Value_default_instance_.DefaultConstruct();
- _UInt64Value_default_instance_.DefaultConstruct();
- _Int32Value_default_instance_.DefaultConstruct();
- _UInt32Value_default_instance_.DefaultConstruct();
- _BoolValue_default_instance_.DefaultConstruct();
- _StringValue_default_instance_.DefaultConstruct();
- _BytesValue_default_instance_.DefaultConstruct();
-}
-
-void protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto() {
- static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
- ::google::protobuf::GoogleOnceInit(&once, &protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto_impl);
-}
-void protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto_impl() {
- protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
- static const char descriptor[] = {
+void AddDescriptorsImpl() {
+ InitDefaults();
+ static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n\036google/protobuf/wrappers.proto\022\017google"
".protobuf\"\034\n\013DoubleValue\022\r\n\005value\030\001 \001(\001\""
"\033\n\nFloatValue\022\r\n\005value\030\001 \001(\002\"\033\n\nInt64Val"
@@ -204,23 +379,26 @@ void protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto_impl() {
descriptor, 447);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"google/protobuf/wrappers.proto", &protobuf_RegisterTypes);
- ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_google_2fprotobuf_2fwrappers_2eproto);
}
-GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto_once_);
-void protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto() {
- ::google::protobuf::GoogleOnceInit(&protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto_once_,
- &protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto_impl);
+void AddDescriptors() {
+ static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
+ ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);
}
-// Force AddDescriptors() to be called at static initialization time.
-struct StaticDescriptorInitializer_google_2fprotobuf_2fwrappers_2eproto {
- StaticDescriptorInitializer_google_2fprotobuf_2fwrappers_2eproto() {
- protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto();
+// Force AddDescriptors() to be called at dynamic initialization time.
+struct StaticDescriptorInitializer {
+ StaticDescriptorInitializer() {
+ AddDescriptors();
}
-} static_descriptor_initializer_google_2fprotobuf_2fwrappers_2eproto_;
+} static_descriptor_initializer;
+} // namespace protobuf_google_2fprotobuf_2fwrappers_2eproto
+namespace google {
+namespace protobuf {
// ===================================================================
+void DoubleValue::InitAsDefaultInstance() {
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int DoubleValue::kValueFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
@@ -228,7 +406,7 @@ const int DoubleValue::kValueFieldNumber;
DoubleValue::DoubleValue()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
+ ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsDoubleValue();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.DoubleValue)
@@ -236,9 +414,7 @@ DoubleValue::DoubleValue()
DoubleValue::DoubleValue(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
-#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
- protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
-#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsDoubleValue();
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.DoubleValue)
@@ -263,11 +439,7 @@ DoubleValue::~DoubleValue() {
}
void DoubleValue::SharedDtor() {
- ::google::protobuf::Arena* arena = GetArenaNoVirtual();
- if (arena != NULL) {
- return;
- }
-
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
}
void DoubleValue::ArenaDtor(void* object) {
@@ -282,12 +454,12 @@ void DoubleValue::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* DoubleValue::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[0].descriptor;
+ ::protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fwrappers_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const DoubleValue& DoubleValue::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
+ ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsDoubleValue();
return *internal_default_instance();
}
@@ -297,7 +469,12 @@ DoubleValue* DoubleValue::New(::google::protobuf::Arena* arena) const {
void DoubleValue::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.DoubleValue)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
value_ = 0;
+ _internal_metadata_.Clear();
}
bool DoubleValue::MergePartialFromCodedStream(
@@ -312,7 +489,8 @@ bool DoubleValue::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// double value = 1;
case 1: {
- if (tag == 9u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(9u /* 9 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
@@ -325,12 +503,11 @@ bool DoubleValue::MergePartialFromCodedStream(
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
- DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
+ DO_(::google::protobuf::internal::WireFormat::SkipField(
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -347,11 +524,18 @@ failure:
void DoubleValue::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.DoubleValue)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// double value = 1;
if (this->value() != 0) {
::google::protobuf::internal::WireFormatLite::WriteDouble(1, this->value(), output);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ }
// @@protoc_insertion_point(serialize_end:google.protobuf.DoubleValue)
}
@@ -359,11 +543,18 @@ void DoubleValue::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.DoubleValue)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// double value = 1;
if (this->value() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(1, this->value(), target);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ }
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.DoubleValue)
return target;
}
@@ -372,6 +563,11 @@ size_t DoubleValue::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.DoubleValue)
size_t total_size = 0;
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ total_size +=
+ ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ }
// double value = 1;
if (this->value() != 0) {
total_size += 1 + 8;
@@ -403,6 +599,9 @@ void DoubleValue::MergeFrom(const DoubleValue& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.DoubleValue)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
if (from.value() != 0) {
set_value(from.value());
}
@@ -446,36 +645,22 @@ void DoubleValue::UnsafeArenaSwap(DoubleValue* other) {
InternalSwap(other);
}
void DoubleValue::InternalSwap(DoubleValue* other) {
- std::swap(value_, other->value_);
- std::swap(_cached_size_, other->_cached_size_);
+ using std::swap;
+ swap(value_, other->value_);
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata DoubleValue::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[0];
+ protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fwrappers_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// DoubleValue
-
-// double value = 1;
-void DoubleValue::clear_value() {
- value_ = 0;
-}
-double DoubleValue::value() const {
- // @@protoc_insertion_point(field_get:google.protobuf.DoubleValue.value)
- return value_;
-}
-void DoubleValue::set_value(double value) {
-
- value_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.DoubleValue.value)
-}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
+void FloatValue::InitAsDefaultInstance() {
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int FloatValue::kValueFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
@@ -483,7 +668,7 @@ const int FloatValue::kValueFieldNumber;
FloatValue::FloatValue()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
+ ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsFloatValue();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.FloatValue)
@@ -491,9 +676,7 @@ FloatValue::FloatValue()
FloatValue::FloatValue(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
-#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
- protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
-#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsFloatValue();
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.FloatValue)
@@ -518,11 +701,7 @@ FloatValue::~FloatValue() {
}
void FloatValue::SharedDtor() {
- ::google::protobuf::Arena* arena = GetArenaNoVirtual();
- if (arena != NULL) {
- return;
- }
-
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
}
void FloatValue::ArenaDtor(void* object) {
@@ -537,12 +716,12 @@ void FloatValue::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* FloatValue::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[1].descriptor;
+ ::protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fwrappers_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const FloatValue& FloatValue::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
+ ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsFloatValue();
return *internal_default_instance();
}
@@ -552,7 +731,12 @@ FloatValue* FloatValue::New(::google::protobuf::Arena* arena) const {
void FloatValue::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.FloatValue)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
value_ = 0;
+ _internal_metadata_.Clear();
}
bool FloatValue::MergePartialFromCodedStream(
@@ -567,7 +751,8 @@ bool FloatValue::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// float value = 1;
case 1: {
- if (tag == 13u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(13u /* 13 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>(
@@ -580,12 +765,11 @@ bool FloatValue::MergePartialFromCodedStream(
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
- DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
+ DO_(::google::protobuf::internal::WireFormat::SkipField(
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -602,11 +786,18 @@ failure:
void FloatValue::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.FloatValue)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// float value = 1;
if (this->value() != 0) {
::google::protobuf::internal::WireFormatLite::WriteFloat(1, this->value(), output);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ }
// @@protoc_insertion_point(serialize_end:google.protobuf.FloatValue)
}
@@ -614,11 +805,18 @@ void FloatValue::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.FloatValue)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// float value = 1;
if (this->value() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteFloatToArray(1, this->value(), target);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ }
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.FloatValue)
return target;
}
@@ -627,6 +825,11 @@ size_t FloatValue::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.FloatValue)
size_t total_size = 0;
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ total_size +=
+ ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ }
// float value = 1;
if (this->value() != 0) {
total_size += 1 + 4;
@@ -658,6 +861,9 @@ void FloatValue::MergeFrom(const FloatValue& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.FloatValue)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
if (from.value() != 0) {
set_value(from.value());
}
@@ -701,36 +907,22 @@ void FloatValue::UnsafeArenaSwap(FloatValue* other) {
InternalSwap(other);
}
void FloatValue::InternalSwap(FloatValue* other) {
- std::swap(value_, other->value_);
- std::swap(_cached_size_, other->_cached_size_);
+ using std::swap;
+ swap(value_, other->value_);
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata FloatValue::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[1];
+ protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fwrappers_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// FloatValue
-
-// float value = 1;
-void FloatValue::clear_value() {
- value_ = 0;
-}
-float FloatValue::value() const {
- // @@protoc_insertion_point(field_get:google.protobuf.FloatValue.value)
- return value_;
-}
-void FloatValue::set_value(float value) {
-
- value_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.FloatValue.value)
-}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
+void Int64Value::InitAsDefaultInstance() {
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Int64Value::kValueFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
@@ -738,7 +930,7 @@ const int Int64Value::kValueFieldNumber;
Int64Value::Int64Value()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
+ ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsInt64Value();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Int64Value)
@@ -746,9 +938,7 @@ Int64Value::Int64Value()
Int64Value::Int64Value(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
-#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
- protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
-#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsInt64Value();
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Int64Value)
@@ -773,11 +963,7 @@ Int64Value::~Int64Value() {
}
void Int64Value::SharedDtor() {
- ::google::protobuf::Arena* arena = GetArenaNoVirtual();
- if (arena != NULL) {
- return;
- }
-
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
}
void Int64Value::ArenaDtor(void* object) {
@@ -792,12 +978,12 @@ void Int64Value::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* Int64Value::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[2].descriptor;
+ ::protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fwrappers_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const Int64Value& Int64Value::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
+ ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsInt64Value();
return *internal_default_instance();
}
@@ -807,7 +993,12 @@ Int64Value* Int64Value::New(::google::protobuf::Arena* arena) const {
void Int64Value::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Int64Value)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
value_ = GOOGLE_LONGLONG(0);
+ _internal_metadata_.Clear();
}
bool Int64Value::MergePartialFromCodedStream(
@@ -822,7 +1013,8 @@ bool Int64Value::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// int64 value = 1;
case 1: {
- if (tag == 8u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>(
@@ -835,12 +1027,11 @@ bool Int64Value::MergePartialFromCodedStream(
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
- DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
+ DO_(::google::protobuf::internal::WireFormat::SkipField(
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -857,11 +1048,18 @@ failure:
void Int64Value::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.Int64Value)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// int64 value = 1;
if (this->value() != 0) {
::google::protobuf::internal::WireFormatLite::WriteInt64(1, this->value(), output);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ }
// @@protoc_insertion_point(serialize_end:google.protobuf.Int64Value)
}
@@ -869,11 +1067,18 @@ void Int64Value::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Int64Value)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// int64 value = 1;
if (this->value() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(1, this->value(), target);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ }
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Int64Value)
return target;
}
@@ -882,6 +1087,11 @@ size_t Int64Value::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.Int64Value)
size_t total_size = 0;
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ total_size +=
+ ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ }
// int64 value = 1;
if (this->value() != 0) {
total_size += 1 +
@@ -915,6 +1125,9 @@ void Int64Value::MergeFrom(const Int64Value& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Int64Value)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
if (from.value() != 0) {
set_value(from.value());
}
@@ -958,36 +1171,22 @@ void Int64Value::UnsafeArenaSwap(Int64Value* other) {
InternalSwap(other);
}
void Int64Value::InternalSwap(Int64Value* other) {
- std::swap(value_, other->value_);
- std::swap(_cached_size_, other->_cached_size_);
+ using std::swap;
+ swap(value_, other->value_);
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Int64Value::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[2];
+ protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fwrappers_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// Int64Value
-
-// int64 value = 1;
-void Int64Value::clear_value() {
- value_ = GOOGLE_LONGLONG(0);
-}
-::google::protobuf::int64 Int64Value::value() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Int64Value.value)
- return value_;
-}
-void Int64Value::set_value(::google::protobuf::int64 value) {
-
- value_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.Int64Value.value)
-}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
+void UInt64Value::InitAsDefaultInstance() {
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int UInt64Value::kValueFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
@@ -995,7 +1194,7 @@ const int UInt64Value::kValueFieldNumber;
UInt64Value::UInt64Value()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
+ ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsUInt64Value();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.UInt64Value)
@@ -1003,9 +1202,7 @@ UInt64Value::UInt64Value()
UInt64Value::UInt64Value(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
-#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
- protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
-#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsUInt64Value();
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.UInt64Value)
@@ -1030,11 +1227,7 @@ UInt64Value::~UInt64Value() {
}
void UInt64Value::SharedDtor() {
- ::google::protobuf::Arena* arena = GetArenaNoVirtual();
- if (arena != NULL) {
- return;
- }
-
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
}
void UInt64Value::ArenaDtor(void* object) {
@@ -1049,12 +1242,12 @@ void UInt64Value::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* UInt64Value::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[3].descriptor;
+ ::protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fwrappers_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const UInt64Value& UInt64Value::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
+ ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsUInt64Value();
return *internal_default_instance();
}
@@ -1064,7 +1257,12 @@ UInt64Value* UInt64Value::New(::google::protobuf::Arena* arena) const {
void UInt64Value::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.UInt64Value)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
value_ = GOOGLE_ULONGLONG(0);
+ _internal_metadata_.Clear();
}
bool UInt64Value::MergePartialFromCodedStream(
@@ -1079,7 +1277,8 @@ bool UInt64Value::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// uint64 value = 1;
case 1: {
- if (tag == 8u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_UINT64>(
@@ -1092,12 +1291,11 @@ bool UInt64Value::MergePartialFromCodedStream(
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
- DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
+ DO_(::google::protobuf::internal::WireFormat::SkipField(
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -1114,11 +1312,18 @@ failure:
void UInt64Value::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.UInt64Value)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// uint64 value = 1;
if (this->value() != 0) {
::google::protobuf::internal::WireFormatLite::WriteUInt64(1, this->value(), output);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ }
// @@protoc_insertion_point(serialize_end:google.protobuf.UInt64Value)
}
@@ -1126,11 +1331,18 @@ void UInt64Value::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.UInt64Value)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// uint64 value = 1;
if (this->value() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt64ToArray(1, this->value(), target);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ }
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.UInt64Value)
return target;
}
@@ -1139,6 +1351,11 @@ size_t UInt64Value::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.UInt64Value)
size_t total_size = 0;
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ total_size +=
+ ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ }
// uint64 value = 1;
if (this->value() != 0) {
total_size += 1 +
@@ -1172,6 +1389,9 @@ void UInt64Value::MergeFrom(const UInt64Value& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.UInt64Value)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
if (from.value() != 0) {
set_value(from.value());
}
@@ -1215,36 +1435,22 @@ void UInt64Value::UnsafeArenaSwap(UInt64Value* other) {
InternalSwap(other);
}
void UInt64Value::InternalSwap(UInt64Value* other) {
- std::swap(value_, other->value_);
- std::swap(_cached_size_, other->_cached_size_);
+ using std::swap;
+ swap(value_, other->value_);
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata UInt64Value::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[3];
+ protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fwrappers_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// UInt64Value
-
-// uint64 value = 1;
-void UInt64Value::clear_value() {
- value_ = GOOGLE_ULONGLONG(0);
-}
-::google::protobuf::uint64 UInt64Value::value() const {
- // @@protoc_insertion_point(field_get:google.protobuf.UInt64Value.value)
- return value_;
-}
-void UInt64Value::set_value(::google::protobuf::uint64 value) {
-
- value_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.UInt64Value.value)
-}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
+void Int32Value::InitAsDefaultInstance() {
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Int32Value::kValueFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
@@ -1252,7 +1458,7 @@ const int Int32Value::kValueFieldNumber;
Int32Value::Int32Value()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
+ ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsInt32Value();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Int32Value)
@@ -1260,9 +1466,7 @@ Int32Value::Int32Value()
Int32Value::Int32Value(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
-#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
- protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
-#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsInt32Value();
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Int32Value)
@@ -1287,11 +1491,7 @@ Int32Value::~Int32Value() {
}
void Int32Value::SharedDtor() {
- ::google::protobuf::Arena* arena = GetArenaNoVirtual();
- if (arena != NULL) {
- return;
- }
-
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
}
void Int32Value::ArenaDtor(void* object) {
@@ -1306,12 +1506,12 @@ void Int32Value::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* Int32Value::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[4].descriptor;
+ ::protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fwrappers_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const Int32Value& Int32Value::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
+ ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsInt32Value();
return *internal_default_instance();
}
@@ -1321,7 +1521,12 @@ Int32Value* Int32Value::New(::google::protobuf::Arena* arena) const {
void Int32Value::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Int32Value)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
value_ = 0;
+ _internal_metadata_.Clear();
}
bool Int32Value::MergePartialFromCodedStream(
@@ -1336,7 +1541,8 @@ bool Int32Value::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// int32 value = 1;
case 1: {
- if (tag == 8u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
@@ -1349,12 +1555,11 @@ bool Int32Value::MergePartialFromCodedStream(
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
- DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
+ DO_(::google::protobuf::internal::WireFormat::SkipField(
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -1371,11 +1576,18 @@ failure:
void Int32Value::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.Int32Value)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// int32 value = 1;
if (this->value() != 0) {
::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->value(), output);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ }
// @@protoc_insertion_point(serialize_end:google.protobuf.Int32Value)
}
@@ -1383,11 +1595,18 @@ void Int32Value::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Int32Value)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// int32 value = 1;
if (this->value() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->value(), target);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ }
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Int32Value)
return target;
}
@@ -1396,6 +1615,11 @@ size_t Int32Value::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.Int32Value)
size_t total_size = 0;
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ total_size +=
+ ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ }
// int32 value = 1;
if (this->value() != 0) {
total_size += 1 +
@@ -1429,6 +1653,9 @@ void Int32Value::MergeFrom(const Int32Value& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Int32Value)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
if (from.value() != 0) {
set_value(from.value());
}
@@ -1472,36 +1699,22 @@ void Int32Value::UnsafeArenaSwap(Int32Value* other) {
InternalSwap(other);
}
void Int32Value::InternalSwap(Int32Value* other) {
- std::swap(value_, other->value_);
- std::swap(_cached_size_, other->_cached_size_);
+ using std::swap;
+ swap(value_, other->value_);
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Int32Value::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[4];
+ protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fwrappers_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// Int32Value
-
-// int32 value = 1;
-void Int32Value::clear_value() {
- value_ = 0;
-}
-::google::protobuf::int32 Int32Value::value() const {
- // @@protoc_insertion_point(field_get:google.protobuf.Int32Value.value)
- return value_;
-}
-void Int32Value::set_value(::google::protobuf::int32 value) {
-
- value_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.Int32Value.value)
-}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
+void UInt32Value::InitAsDefaultInstance() {
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int UInt32Value::kValueFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
@@ -1509,7 +1722,7 @@ const int UInt32Value::kValueFieldNumber;
UInt32Value::UInt32Value()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
+ ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsUInt32Value();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.UInt32Value)
@@ -1517,9 +1730,7 @@ UInt32Value::UInt32Value()
UInt32Value::UInt32Value(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
-#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
- protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
-#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsUInt32Value();
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.UInt32Value)
@@ -1544,11 +1755,7 @@ UInt32Value::~UInt32Value() {
}
void UInt32Value::SharedDtor() {
- ::google::protobuf::Arena* arena = GetArenaNoVirtual();
- if (arena != NULL) {
- return;
- }
-
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
}
void UInt32Value::ArenaDtor(void* object) {
@@ -1563,12 +1770,12 @@ void UInt32Value::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* UInt32Value::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[5].descriptor;
+ ::protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fwrappers_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const UInt32Value& UInt32Value::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
+ ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsUInt32Value();
return *internal_default_instance();
}
@@ -1578,7 +1785,12 @@ UInt32Value* UInt32Value::New(::google::protobuf::Arena* arena) const {
void UInt32Value::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.UInt32Value)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
value_ = 0u;
+ _internal_metadata_.Clear();
}
bool UInt32Value::MergePartialFromCodedStream(
@@ -1593,7 +1805,8 @@ bool UInt32Value::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// uint32 value = 1;
case 1: {
- if (tag == 8u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
@@ -1606,12 +1819,11 @@ bool UInt32Value::MergePartialFromCodedStream(
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
- DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
+ DO_(::google::protobuf::internal::WireFormat::SkipField(
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -1628,11 +1840,18 @@ failure:
void UInt32Value::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.UInt32Value)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// uint32 value = 1;
if (this->value() != 0) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(1, this->value(), output);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ }
// @@protoc_insertion_point(serialize_end:google.protobuf.UInt32Value)
}
@@ -1640,11 +1859,18 @@ void UInt32Value::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.UInt32Value)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// uint32 value = 1;
if (this->value() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(1, this->value(), target);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ }
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.UInt32Value)
return target;
}
@@ -1653,6 +1879,11 @@ size_t UInt32Value::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.UInt32Value)
size_t total_size = 0;
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ total_size +=
+ ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ }
// uint32 value = 1;
if (this->value() != 0) {
total_size += 1 +
@@ -1686,6 +1917,9 @@ void UInt32Value::MergeFrom(const UInt32Value& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.UInt32Value)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
if (from.value() != 0) {
set_value(from.value());
}
@@ -1729,36 +1963,22 @@ void UInt32Value::UnsafeArenaSwap(UInt32Value* other) {
InternalSwap(other);
}
void UInt32Value::InternalSwap(UInt32Value* other) {
- std::swap(value_, other->value_);
- std::swap(_cached_size_, other->_cached_size_);
+ using std::swap;
+ swap(value_, other->value_);
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata UInt32Value::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[5];
+ protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fwrappers_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// UInt32Value
-
-// uint32 value = 1;
-void UInt32Value::clear_value() {
- value_ = 0u;
-}
-::google::protobuf::uint32 UInt32Value::value() const {
- // @@protoc_insertion_point(field_get:google.protobuf.UInt32Value.value)
- return value_;
-}
-void UInt32Value::set_value(::google::protobuf::uint32 value) {
-
- value_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.UInt32Value.value)
-}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
+void BoolValue::InitAsDefaultInstance() {
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int BoolValue::kValueFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
@@ -1766,7 +1986,7 @@ const int BoolValue::kValueFieldNumber;
BoolValue::BoolValue()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
+ ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsBoolValue();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.BoolValue)
@@ -1774,9 +1994,7 @@ BoolValue::BoolValue()
BoolValue::BoolValue(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
-#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
- protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
-#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsBoolValue();
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.BoolValue)
@@ -1801,11 +2019,7 @@ BoolValue::~BoolValue() {
}
void BoolValue::SharedDtor() {
- ::google::protobuf::Arena* arena = GetArenaNoVirtual();
- if (arena != NULL) {
- return;
- }
-
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
}
void BoolValue::ArenaDtor(void* object) {
@@ -1820,12 +2034,12 @@ void BoolValue::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* BoolValue::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[6].descriptor;
+ ::protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fwrappers_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const BoolValue& BoolValue::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
+ ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsBoolValue();
return *internal_default_instance();
}
@@ -1835,7 +2049,12 @@ BoolValue* BoolValue::New(::google::protobuf::Arena* arena) const {
void BoolValue::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.BoolValue)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
value_ = false;
+ _internal_metadata_.Clear();
}
bool BoolValue::MergePartialFromCodedStream(
@@ -1850,7 +2069,8 @@ bool BoolValue::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// bool value = 1;
case 1: {
- if (tag == 8u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
@@ -1863,12 +2083,11 @@ bool BoolValue::MergePartialFromCodedStream(
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
- DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
+ DO_(::google::protobuf::internal::WireFormat::SkipField(
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -1885,11 +2104,18 @@ failure:
void BoolValue::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.BoolValue)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// bool value = 1;
if (this->value() != 0) {
::google::protobuf::internal::WireFormatLite::WriteBool(1, this->value(), output);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ }
// @@protoc_insertion_point(serialize_end:google.protobuf.BoolValue)
}
@@ -1897,11 +2123,18 @@ void BoolValue::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.BoolValue)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// bool value = 1;
if (this->value() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(1, this->value(), target);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ }
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.BoolValue)
return target;
}
@@ -1910,6 +2143,11 @@ size_t BoolValue::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.BoolValue)
size_t total_size = 0;
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ total_size +=
+ ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ }
// bool value = 1;
if (this->value() != 0) {
total_size += 1 + 1;
@@ -1941,6 +2179,9 @@ void BoolValue::MergeFrom(const BoolValue& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.BoolValue)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
if (from.value() != 0) {
set_value(from.value());
}
@@ -1984,36 +2225,22 @@ void BoolValue::UnsafeArenaSwap(BoolValue* other) {
InternalSwap(other);
}
void BoolValue::InternalSwap(BoolValue* other) {
- std::swap(value_, other->value_);
- std::swap(_cached_size_, other->_cached_size_);
+ using std::swap;
+ swap(value_, other->value_);
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata BoolValue::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[6];
-}
-
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// BoolValue
-
-// bool value = 1;
-void BoolValue::clear_value() {
- value_ = false;
-}
-bool BoolValue::value() const {
- // @@protoc_insertion_point(field_get:google.protobuf.BoolValue.value)
- return value_;
-}
-void BoolValue::set_value(bool value) {
-
- value_ = value;
- // @@protoc_insertion_point(field_set:google.protobuf.BoolValue.value)
+ protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fwrappers_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
+void StringValue::InitAsDefaultInstance() {
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int StringValue::kValueFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
@@ -2021,7 +2248,7 @@ const int StringValue::kValueFieldNumber;
StringValue::StringValue()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
+ ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsStringValue();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.StringValue)
@@ -2029,9 +2256,7 @@ StringValue::StringValue()
StringValue::StringValue(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
-#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
- protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
-#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsStringValue();
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.StringValue)
@@ -2060,12 +2285,8 @@ StringValue::~StringValue() {
}
void StringValue::SharedDtor() {
- ::google::protobuf::Arena* arena = GetArenaNoVirtual();
- if (arena != NULL) {
- return;
- }
-
- value_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena);
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
+ value_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void StringValue::ArenaDtor(void* object) {
@@ -2080,12 +2301,12 @@ void StringValue::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* StringValue::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[7].descriptor;
+ ::protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fwrappers_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const StringValue& StringValue::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
+ ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsStringValue();
return *internal_default_instance();
}
@@ -2095,7 +2316,12 @@ StringValue* StringValue::New(::google::protobuf::Arena* arena) const {
void StringValue::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.StringValue)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
value_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ _internal_metadata_.Clear();
}
bool StringValue::MergePartialFromCodedStream(
@@ -2110,11 +2336,12 @@ bool StringValue::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// string value = 1;
case 1: {
- if (tag == 10u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_value()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->value().data(), this->value().length(),
+ this->value().data(), static_cast<int>(this->value().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.protobuf.StringValue.value"));
} else {
@@ -2125,12 +2352,11 @@ bool StringValue::MergePartialFromCodedStream(
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
- DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
+ DO_(::google::protobuf::internal::WireFormat::SkipField(
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -2147,16 +2373,23 @@ failure:
void StringValue::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.StringValue)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// string value = 1;
if (this->value().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->value().data(), this->value().length(),
+ this->value().data(), static_cast<int>(this->value().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.StringValue.value");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
1, this->value(), output);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ }
// @@protoc_insertion_point(serialize_end:google.protobuf.StringValue)
}
@@ -2164,10 +2397,13 @@ void StringValue::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.StringValue)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// string value = 1;
if (this->value().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
- this->value().data(), this->value().length(),
+ this->value().data(), static_cast<int>(this->value().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.StringValue.value");
target =
@@ -2175,6 +2411,10 @@ void StringValue::SerializeWithCachedSizes(
1, this->value(), target);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ }
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.StringValue)
return target;
}
@@ -2183,6 +2423,11 @@ size_t StringValue::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.StringValue)
size_t total_size = 0;
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ total_size +=
+ ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ }
// string value = 1;
if (this->value().size() > 0) {
total_size += 1 +
@@ -2216,6 +2461,9 @@ void StringValue::MergeFrom(const StringValue& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.StringValue)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
if (from.value().size() > 0) {
set_value(from.value());
}
@@ -2259,88 +2507,22 @@ void StringValue::UnsafeArenaSwap(StringValue* other) {
InternalSwap(other);
}
void StringValue::InternalSwap(StringValue* other) {
+ using std::swap;
value_.Swap(&other->value_);
- std::swap(_cached_size_, other->_cached_size_);
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata StringValue::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[7];
+ protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fwrappers_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// StringValue
-
-// string value = 1;
-void StringValue::clear_value() {
- value_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
-}
-const ::std::string& StringValue::value() const {
- // @@protoc_insertion_point(field_get:google.protobuf.StringValue.value)
- return value_.Get();
-}
-void StringValue::set_value(const ::std::string& value) {
-
- value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set:google.protobuf.StringValue.value)
-}
-void StringValue::set_value(const char* value) {
-
- value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set_char:google.protobuf.StringValue.value)
-}
-void StringValue::set_value(const char* value,
- size_t size) {
-
- value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.StringValue.value)
-}
-::std::string* StringValue::mutable_value() {
-
- // @@protoc_insertion_point(field_mutable:google.protobuf.StringValue.value)
- return value_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
-}
-::std::string* StringValue::release_value() {
- // @@protoc_insertion_point(field_release:google.protobuf.StringValue.value)
-
- return value_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
-}
-::std::string* StringValue::unsafe_arena_release_value() {
- // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.StringValue.value)
- GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
-
- return value_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
-}
-void StringValue::set_allocated_value(::std::string* value) {
- if (value != NULL) {
-
- } else {
-
- }
- value_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value,
- GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.StringValue.value)
-}
-void StringValue::unsafe_arena_set_allocated_value(
- ::std::string* value) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
- if (value != NULL) {
-
- } else {
-
- }
- value_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- value, GetArenaNoVirtual());
- // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.StringValue.value)
-}
-
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
+void BytesValue::InitAsDefaultInstance() {
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int BytesValue::kValueFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
@@ -2348,7 +2530,7 @@ const int BytesValue::kValueFieldNumber;
BytesValue::BytesValue()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
- protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
+ ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsBytesValue();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.BytesValue)
@@ -2356,9 +2538,7 @@ BytesValue::BytesValue()
BytesValue::BytesValue(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
-#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
- protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
-#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsBytesValue();
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.BytesValue)
@@ -2387,12 +2567,8 @@ BytesValue::~BytesValue() {
}
void BytesValue::SharedDtor() {
- ::google::protobuf::Arena* arena = GetArenaNoVirtual();
- if (arena != NULL) {
- return;
- }
-
- value_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena);
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
+ value_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void BytesValue::ArenaDtor(void* object) {
@@ -2407,12 +2583,12 @@ void BytesValue::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* BytesValue::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[8].descriptor;
+ ::protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fwrappers_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const BytesValue& BytesValue::default_instance() {
- protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
+ ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsBytesValue();
return *internal_default_instance();
}
@@ -2422,7 +2598,12 @@ BytesValue* BytesValue::New(::google::protobuf::Arena* arena) const {
void BytesValue::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.BytesValue)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
value_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ _internal_metadata_.Clear();
}
bool BytesValue::MergePartialFromCodedStream(
@@ -2437,7 +2618,8 @@ bool BytesValue::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// bytes value = 1;
case 1: {
- if (tag == 10u) {
+ if (static_cast< ::google::protobuf::uint8>(tag) ==
+ static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadBytes(
input, this->mutable_value()));
} else {
@@ -2448,12 +2630,11 @@ bool BytesValue::MergePartialFromCodedStream(
default: {
handle_unusual:
- if (tag == 0 ||
- ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ if (tag == 0) {
goto success;
}
- DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
+ DO_(::google::protobuf::internal::WireFormat::SkipField(
+ input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -2470,12 +2651,19 @@ failure:
void BytesValue::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.BytesValue)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// bytes value = 1;
if (this->value().size() > 0) {
::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased(
1, this->value(), output);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ }
// @@protoc_insertion_point(serialize_end:google.protobuf.BytesValue)
}
@@ -2483,6 +2671,9 @@ void BytesValue::SerializeWithCachedSizes(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.BytesValue)
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
// bytes value = 1;
if (this->value().size() > 0) {
target =
@@ -2490,6 +2681,10 @@ void BytesValue::SerializeWithCachedSizes(
1, this->value(), target);
}
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ }
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.BytesValue)
return target;
}
@@ -2498,6 +2693,11 @@ size_t BytesValue::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.BytesValue)
size_t total_size = 0;
+ if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ total_size +=
+ ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
+ (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ }
// bytes value = 1;
if (this->value().size() > 0) {
total_size += 1 +
@@ -2531,6 +2731,9 @@ void BytesValue::MergeFrom(const BytesValue& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.BytesValue)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
if (from.value().size() > 0) {
set_value(from.value());
}
@@ -2574,88 +2777,19 @@ void BytesValue::UnsafeArenaSwap(BytesValue* other) {
InternalSwap(other);
}
void BytesValue::InternalSwap(BytesValue* other) {
+ using std::swap;
value_.Swap(&other->value_);
- std::swap(_cached_size_, other->_cached_size_);
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata BytesValue::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- return file_level_metadata[8];
-}
-
-#if PROTOBUF_INLINE_NOT_IN_HEADERS
-// BytesValue
-
-// bytes value = 1;
-void BytesValue::clear_value() {
- value_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
-}
-const ::std::string& BytesValue::value() const {
- // @@protoc_insertion_point(field_get:google.protobuf.BytesValue.value)
- return value_.Get();
-}
-void BytesValue::set_value(const ::std::string& value) {
-
- value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set:google.protobuf.BytesValue.value)
-}
-void BytesValue::set_value(const char* value) {
-
- value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set_char:google.protobuf.BytesValue.value)
-}
-void BytesValue::set_value(const void* value,
- size_t size) {
-
- value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set_pointer:google.protobuf.BytesValue.value)
-}
-::std::string* BytesValue::mutable_value() {
-
- // @@protoc_insertion_point(field_mutable:google.protobuf.BytesValue.value)
- return value_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
-}
-::std::string* BytesValue::release_value() {
- // @@protoc_insertion_point(field_release:google.protobuf.BytesValue.value)
-
- return value_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
-}
-::std::string* BytesValue::unsafe_arena_release_value() {
- // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.BytesValue.value)
- GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
-
- return value_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
-}
-void BytesValue::set_allocated_value(::std::string* value) {
- if (value != NULL) {
-
- } else {
-
- }
- value_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value,
- GetArenaNoVirtual());
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.BytesValue.value)
-}
-void BytesValue::unsafe_arena_set_allocated_value(
- ::std::string* value) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
- if (value != NULL) {
-
- } else {
-
- }
- value_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- value, GetArenaNoVirtual());
- // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.BytesValue.value)
+ protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
+ return ::protobuf_google_2fprotobuf_2fwrappers_2eproto::file_level_metadata[kIndexInFileMessages];
}
-#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
-
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/wrappers.pb.h b/src/google/protobuf/wrappers.pb.h
index cf8e1693..be49c3ec 100644
--- a/src/google/protobuf/wrappers.pb.h
+++ b/src/google/protobuf/wrappers.pb.h
@@ -8,19 +8,21 @@
#include <google/protobuf/stubs/common.h>
-#if GOOGLE_PROTOBUF_VERSION < 3001000
+#if GOOGLE_PROTOBUF_VERSION < 3004000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3001000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3004000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
+#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
+#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
@@ -28,6 +30,48 @@
#include <google/protobuf/extension_set.h> // IWYU pragma: export
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
+
+namespace protobuf_google_2fprotobuf_2fwrappers_2eproto {
+// Internal implementation detail -- do not use these members.
+struct LIBPROTOBUF_EXPORT TableStruct {
+ static const ::google::protobuf::internal::ParseTableField entries[];
+ static const ::google::protobuf::internal::AuxillaryParseTableField aux[];
+ static const ::google::protobuf::internal::ParseTable schema[9];
+ static const ::google::protobuf::internal::FieldMetadata field_metadata[];
+ static const ::google::protobuf::internal::SerializationTable serialization_table[];
+ static const ::google::protobuf::uint32 offsets[];
+};
+void LIBPROTOBUF_EXPORT AddDescriptors();
+void LIBPROTOBUF_EXPORT InitDefaultsDoubleValueImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsDoubleValue();
+void LIBPROTOBUF_EXPORT InitDefaultsFloatValueImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsFloatValue();
+void LIBPROTOBUF_EXPORT InitDefaultsInt64ValueImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsInt64Value();
+void LIBPROTOBUF_EXPORT InitDefaultsUInt64ValueImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsUInt64Value();
+void LIBPROTOBUF_EXPORT InitDefaultsInt32ValueImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsInt32Value();
+void LIBPROTOBUF_EXPORT InitDefaultsUInt32ValueImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsUInt32Value();
+void LIBPROTOBUF_EXPORT InitDefaultsBoolValueImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsBoolValue();
+void LIBPROTOBUF_EXPORT InitDefaultsStringValueImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsStringValue();
+void LIBPROTOBUF_EXPORT InitDefaultsBytesValueImpl();
+void LIBPROTOBUF_EXPORT InitDefaultsBytesValue();
+inline void LIBPROTOBUF_EXPORT InitDefaults() {
+ InitDefaultsDoubleValue();
+ InitDefaultsFloatValue();
+ InitDefaultsInt64Value();
+ InitDefaultsUInt64Value();
+ InitDefaultsInt32Value();
+ InitDefaultsUInt32Value();
+ InitDefaultsBoolValue();
+ InitDefaultsStringValue();
+ InitDefaultsBytesValue();
+}
+} // namespace protobuf_google_2fprotobuf_2fwrappers_2eproto
namespace google {
namespace protobuf {
class BoolValue;
@@ -59,14 +103,9 @@ class UInt64ValueDefaultTypeInternal;
LIBPROTOBUF_EXPORT extern UInt64ValueDefaultTypeInternal _UInt64Value_default_instance_;
} // namespace protobuf
} // namespace google
-
namespace google {
namespace protobuf {
-// Internal implementation detail -- do not call these.
-void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto();
-void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
-
// ===================================================================
class LIBPROTOBUF_EXPORT DoubleValue : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.DoubleValue) */ {
@@ -80,7 +119,21 @@ class LIBPROTOBUF_EXPORT DoubleValue : public ::google::protobuf::Message /* @@p
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ DoubleValue(DoubleValue&& from) noexcept
+ : DoubleValue() {
+ *this = ::std::move(from);
+ }
+ inline DoubleValue& operator=(DoubleValue&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
return GetArenaNoVirtual();
}
@@ -90,13 +143,19 @@ class LIBPROTOBUF_EXPORT DoubleValue : public ::google::protobuf::Message /* @@p
static const ::google::protobuf::Descriptor* descriptor();
static const DoubleValue& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const DoubleValue* internal_default_instance() {
return reinterpret_cast<const DoubleValue*>(
&_DoubleValue_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 0;
void UnsafeArenaSwap(DoubleValue* other);
void Swap(DoubleValue* other);
+ friend void swap(DoubleValue& a, DoubleValue& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -117,10 +176,6 @@ class LIBPROTOBUF_EXPORT DoubleValue : public ::google::protobuf::Message /* @@p
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
@@ -157,16 +212,13 @@ class LIBPROTOBUF_EXPORT DoubleValue : public ::google::protobuf::Message /* @@p
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- friend class ::google::protobuf::Arena;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
double value_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fwrappers_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fwrappers_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fwrappers_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsDoubleValueImpl();
};
// -------------------------------------------------------------------
@@ -181,7 +233,21 @@ class LIBPROTOBUF_EXPORT FloatValue : public ::google::protobuf::Message /* @@pr
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ FloatValue(FloatValue&& from) noexcept
+ : FloatValue() {
+ *this = ::std::move(from);
+ }
+ inline FloatValue& operator=(FloatValue&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
return GetArenaNoVirtual();
}
@@ -191,13 +257,19 @@ class LIBPROTOBUF_EXPORT FloatValue : public ::google::protobuf::Message /* @@pr
static const ::google::protobuf::Descriptor* descriptor();
static const FloatValue& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const FloatValue* internal_default_instance() {
return reinterpret_cast<const FloatValue*>(
&_FloatValue_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 1;
void UnsafeArenaSwap(FloatValue* other);
void Swap(FloatValue* other);
+ friend void swap(FloatValue& a, FloatValue& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -218,10 +290,6 @@ class LIBPROTOBUF_EXPORT FloatValue : public ::google::protobuf::Message /* @@pr
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
@@ -258,16 +326,13 @@ class LIBPROTOBUF_EXPORT FloatValue : public ::google::protobuf::Message /* @@pr
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- friend class ::google::protobuf::Arena;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
float value_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fwrappers_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fwrappers_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fwrappers_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsFloatValueImpl();
};
// -------------------------------------------------------------------
@@ -282,7 +347,21 @@ class LIBPROTOBUF_EXPORT Int64Value : public ::google::protobuf::Message /* @@pr
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ Int64Value(Int64Value&& from) noexcept
+ : Int64Value() {
+ *this = ::std::move(from);
+ }
+ inline Int64Value& operator=(Int64Value&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
return GetArenaNoVirtual();
}
@@ -292,13 +371,19 @@ class LIBPROTOBUF_EXPORT Int64Value : public ::google::protobuf::Message /* @@pr
static const ::google::protobuf::Descriptor* descriptor();
static const Int64Value& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const Int64Value* internal_default_instance() {
return reinterpret_cast<const Int64Value*>(
&_Int64Value_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 2;
void UnsafeArenaSwap(Int64Value* other);
void Swap(Int64Value* other);
+ friend void swap(Int64Value& a, Int64Value& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -319,10 +404,6 @@ class LIBPROTOBUF_EXPORT Int64Value : public ::google::protobuf::Message /* @@pr
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
@@ -359,16 +440,13 @@ class LIBPROTOBUF_EXPORT Int64Value : public ::google::protobuf::Message /* @@pr
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- friend class ::google::protobuf::Arena;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::int64 value_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fwrappers_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fwrappers_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fwrappers_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsInt64ValueImpl();
};
// -------------------------------------------------------------------
@@ -383,7 +461,21 @@ class LIBPROTOBUF_EXPORT UInt64Value : public ::google::protobuf::Message /* @@p
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ UInt64Value(UInt64Value&& from) noexcept
+ : UInt64Value() {
+ *this = ::std::move(from);
+ }
+ inline UInt64Value& operator=(UInt64Value&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
return GetArenaNoVirtual();
}
@@ -393,13 +485,19 @@ class LIBPROTOBUF_EXPORT UInt64Value : public ::google::protobuf::Message /* @@p
static const ::google::protobuf::Descriptor* descriptor();
static const UInt64Value& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const UInt64Value* internal_default_instance() {
return reinterpret_cast<const UInt64Value*>(
&_UInt64Value_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 3;
void UnsafeArenaSwap(UInt64Value* other);
void Swap(UInt64Value* other);
+ friend void swap(UInt64Value& a, UInt64Value& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -420,10 +518,6 @@ class LIBPROTOBUF_EXPORT UInt64Value : public ::google::protobuf::Message /* @@p
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
@@ -460,16 +554,13 @@ class LIBPROTOBUF_EXPORT UInt64Value : public ::google::protobuf::Message /* @@p
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- friend class ::google::protobuf::Arena;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::uint64 value_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fwrappers_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fwrappers_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fwrappers_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsUInt64ValueImpl();
};
// -------------------------------------------------------------------
@@ -484,7 +575,21 @@ class LIBPROTOBUF_EXPORT Int32Value : public ::google::protobuf::Message /* @@pr
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ Int32Value(Int32Value&& from) noexcept
+ : Int32Value() {
+ *this = ::std::move(from);
+ }
+ inline Int32Value& operator=(Int32Value&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
return GetArenaNoVirtual();
}
@@ -494,13 +599,19 @@ class LIBPROTOBUF_EXPORT Int32Value : public ::google::protobuf::Message /* @@pr
static const ::google::protobuf::Descriptor* descriptor();
static const Int32Value& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const Int32Value* internal_default_instance() {
return reinterpret_cast<const Int32Value*>(
&_Int32Value_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 4;
void UnsafeArenaSwap(Int32Value* other);
void Swap(Int32Value* other);
+ friend void swap(Int32Value& a, Int32Value& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -521,10 +632,6 @@ class LIBPROTOBUF_EXPORT Int32Value : public ::google::protobuf::Message /* @@pr
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
@@ -561,16 +668,13 @@ class LIBPROTOBUF_EXPORT Int32Value : public ::google::protobuf::Message /* @@pr
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- friend class ::google::protobuf::Arena;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::int32 value_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fwrappers_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fwrappers_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fwrappers_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsInt32ValueImpl();
};
// -------------------------------------------------------------------
@@ -585,7 +689,21 @@ class LIBPROTOBUF_EXPORT UInt32Value : public ::google::protobuf::Message /* @@p
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ UInt32Value(UInt32Value&& from) noexcept
+ : UInt32Value() {
+ *this = ::std::move(from);
+ }
+ inline UInt32Value& operator=(UInt32Value&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
return GetArenaNoVirtual();
}
@@ -595,13 +713,19 @@ class LIBPROTOBUF_EXPORT UInt32Value : public ::google::protobuf::Message /* @@p
static const ::google::protobuf::Descriptor* descriptor();
static const UInt32Value& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const UInt32Value* internal_default_instance() {
return reinterpret_cast<const UInt32Value*>(
&_UInt32Value_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 5;
void UnsafeArenaSwap(UInt32Value* other);
void Swap(UInt32Value* other);
+ friend void swap(UInt32Value& a, UInt32Value& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -622,10 +746,6 @@ class LIBPROTOBUF_EXPORT UInt32Value : public ::google::protobuf::Message /* @@p
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
@@ -662,16 +782,13 @@ class LIBPROTOBUF_EXPORT UInt32Value : public ::google::protobuf::Message /* @@p
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- friend class ::google::protobuf::Arena;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::uint32 value_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fwrappers_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fwrappers_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fwrappers_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsUInt32ValueImpl();
};
// -------------------------------------------------------------------
@@ -686,7 +803,21 @@ class LIBPROTOBUF_EXPORT BoolValue : public ::google::protobuf::Message /* @@pro
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ BoolValue(BoolValue&& from) noexcept
+ : BoolValue() {
+ *this = ::std::move(from);
+ }
+ inline BoolValue& operator=(BoolValue&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
return GetArenaNoVirtual();
}
@@ -696,13 +827,19 @@ class LIBPROTOBUF_EXPORT BoolValue : public ::google::protobuf::Message /* @@pro
static const ::google::protobuf::Descriptor* descriptor();
static const BoolValue& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const BoolValue* internal_default_instance() {
return reinterpret_cast<const BoolValue*>(
&_BoolValue_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 6;
void UnsafeArenaSwap(BoolValue* other);
void Swap(BoolValue* other);
+ friend void swap(BoolValue& a, BoolValue& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -723,10 +860,6 @@ class LIBPROTOBUF_EXPORT BoolValue : public ::google::protobuf::Message /* @@pro
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
@@ -763,16 +896,13 @@ class LIBPROTOBUF_EXPORT BoolValue : public ::google::protobuf::Message /* @@pro
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- friend class ::google::protobuf::Arena;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
bool value_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fwrappers_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fwrappers_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fwrappers_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsBoolValueImpl();
};
// -------------------------------------------------------------------
@@ -787,7 +917,21 @@ class LIBPROTOBUF_EXPORT StringValue : public ::google::protobuf::Message /* @@p
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ StringValue(StringValue&& from) noexcept
+ : StringValue() {
+ *this = ::std::move(from);
+ }
+ inline StringValue& operator=(StringValue&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
return GetArenaNoVirtual();
}
@@ -797,13 +941,19 @@ class LIBPROTOBUF_EXPORT StringValue : public ::google::protobuf::Message /* @@p
static const ::google::protobuf::Descriptor* descriptor();
static const StringValue& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const StringValue* internal_default_instance() {
return reinterpret_cast<const StringValue*>(
&_StringValue_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 7;
void UnsafeArenaSwap(StringValue* other);
void Swap(StringValue* other);
+ friend void swap(StringValue& a, StringValue& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -824,10 +974,6 @@ class LIBPROTOBUF_EXPORT StringValue : public ::google::protobuf::Message /* @@p
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
@@ -859,12 +1005,21 @@ class LIBPROTOBUF_EXPORT StringValue : public ::google::protobuf::Message /* @@p
static const int kValueFieldNumber = 1;
const ::std::string& value() const;
void set_value(const ::std::string& value);
+ #if LANG_CXX11
+ void set_value(::std::string&& value);
+ #endif
void set_value(const char* value);
void set_value(const char* value, size_t size);
::std::string* mutable_value();
::std::string* release_value();
void set_allocated_value(::std::string* value);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
::std::string* unsafe_arena_release_value();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
void unsafe_arena_set_allocated_value(
::std::string* value);
@@ -872,16 +1027,13 @@ class LIBPROTOBUF_EXPORT StringValue : public ::google::protobuf::Message /* @@p
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- friend class ::google::protobuf::Arena;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::internal::ArenaStringPtr value_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fwrappers_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fwrappers_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fwrappers_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsStringValueImpl();
};
// -------------------------------------------------------------------
@@ -896,7 +1048,21 @@ class LIBPROTOBUF_EXPORT BytesValue : public ::google::protobuf::Message /* @@pr
CopyFrom(from);
return *this;
}
+ #if LANG_CXX11
+ BytesValue(BytesValue&& from) noexcept
+ : BytesValue() {
+ *this = ::std::move(from);
+ }
+ inline BytesValue& operator=(BytesValue&& from) noexcept {
+ if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+ #endif
inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
return GetArenaNoVirtual();
}
@@ -906,13 +1072,19 @@ class LIBPROTOBUF_EXPORT BytesValue : public ::google::protobuf::Message /* @@pr
static const ::google::protobuf::Descriptor* descriptor();
static const BytesValue& default_instance();
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const BytesValue* internal_default_instance() {
return reinterpret_cast<const BytesValue*>(
&_BytesValue_default_instance_);
}
+ static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
+ 8;
void UnsafeArenaSwap(BytesValue* other);
void Swap(BytesValue* other);
+ friend void swap(BytesValue& a, BytesValue& b) {
+ a.Swap(&b);
+ }
// implements Message ----------------------------------------------
@@ -933,10 +1105,6 @@ class LIBPROTOBUF_EXPORT BytesValue : public ::google::protobuf::Message /* @@pr
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
- const PROTOBUF_FINAL {
- return InternalSerializeWithCachedSizesToArray(false, output);
- }
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
@@ -968,12 +1136,21 @@ class LIBPROTOBUF_EXPORT BytesValue : public ::google::protobuf::Message /* @@pr
static const int kValueFieldNumber = 1;
const ::std::string& value() const;
void set_value(const ::std::string& value);
+ #if LANG_CXX11
+ void set_value(::std::string&& value);
+ #endif
void set_value(const char* value);
void set_value(const void* value, size_t size);
::std::string* mutable_value();
::std::string* release_value();
void set_allocated_value(::std::string* value);
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
::std::string* unsafe_arena_release_value();
+ PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
void unsafe_arena_set_allocated_value(
::std::string* value);
@@ -981,23 +1158,23 @@ class LIBPROTOBUF_EXPORT BytesValue : public ::google::protobuf::Message /* @@pr
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- friend class ::google::protobuf::Arena;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::internal::ArenaStringPtr value_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto_impl();
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto_impl();
- friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2fwrappers_2eproto();
- friend void protobuf_ShutdownFile_google_2fprotobuf_2fwrappers_2eproto();
-
+ friend struct ::protobuf_google_2fprotobuf_2fwrappers_2eproto::TableStruct;
+ friend void ::protobuf_google_2fprotobuf_2fwrappers_2eproto::InitDefaultsBytesValueImpl();
};
// ===================================================================
// ===================================================================
-#if !PROTOBUF_INLINE_NOT_IN_HEADERS
+#ifdef __GNUC__
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wstrict-aliasing"
+#endif // __GNUC__
// DoubleValue
// double value = 1;
@@ -1139,7 +1316,16 @@ inline void StringValue::set_value(const ::std::string& value) {
value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.StringValue.value)
}
+#if LANG_CXX11
+inline void StringValue::set_value(::std::string&& value) {
+
+ value_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.StringValue.value)
+}
+#endif
inline void StringValue::set_value(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
GetArenaNoVirtual());
@@ -1162,13 +1348,6 @@ inline ::std::string* StringValue::release_value() {
return value_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
-inline ::std::string* StringValue::unsafe_arena_release_value() {
- // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.StringValue.value)
- GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
-
- return value_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
-}
inline void StringValue::set_allocated_value(::std::string* value) {
if (value != NULL) {
@@ -1179,6 +1358,13 @@ inline void StringValue::set_allocated_value(::std::string* value) {
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.StringValue.value)
}
+inline ::std::string* StringValue::unsafe_arena_release_value() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.StringValue.value)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+
+ return value_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
inline void StringValue::unsafe_arena_set_allocated_value(
::std::string* value) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
@@ -1209,7 +1395,16 @@ inline void BytesValue::set_value(const ::std::string& value) {
value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.BytesValue.value)
}
+#if LANG_CXX11
+inline void BytesValue::set_value(::std::string&& value) {
+
+ value_.Set(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_set_rvalue:google.protobuf.BytesValue.value)
+}
+#endif
inline void BytesValue::set_value(const char* value) {
+ GOOGLE_DCHECK(value != NULL);
value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
GetArenaNoVirtual());
@@ -1232,13 +1427,6 @@ inline ::std::string* BytesValue::release_value() {
return value_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
-inline ::std::string* BytesValue::unsafe_arena_release_value() {
- // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.BytesValue.value)
- GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
-
- return value_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
-}
inline void BytesValue::set_allocated_value(::std::string* value) {
if (value != NULL) {
@@ -1249,6 +1437,13 @@ inline void BytesValue::set_allocated_value(::std::string* value) {
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.BytesValue.value)
}
+inline ::std::string* BytesValue::unsafe_arena_release_value() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.BytesValue.value)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+
+ return value_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
inline void BytesValue::unsafe_arena_set_allocated_value(
::std::string* value) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
@@ -1262,7 +1457,9 @@ inline void BytesValue::unsafe_arena_set_allocated_value(
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.BytesValue.value)
}
-#endif // !PROTOBUF_INLINE_NOT_IN_HEADERS
+#ifdef __GNUC__
+ #pragma GCC diagnostic pop
+#endif // __GNUC__
// -------------------------------------------------------------------
// -------------------------------------------------------------------
@@ -1282,7 +1479,6 @@ inline void BytesValue::unsafe_arena_set_allocated_value(
// @@protoc_insertion_point(namespace_scope)
-
} // namespace protobuf
} // namespace google
diff --git a/src/libprotobuf-lite.map b/src/libprotobuf-lite.map
new file mode 100644
index 00000000..39155466
--- /dev/null
+++ b/src/libprotobuf-lite.map
@@ -0,0 +1,9 @@
+{
+ global:
+ extern "C++" {
+ *google*;
+ };
+
+ local:
+ *;
+};
diff --git a/src/libprotobuf.map b/src/libprotobuf.map
new file mode 100644
index 00000000..39155466
--- /dev/null
+++ b/src/libprotobuf.map
@@ -0,0 +1,9 @@
+{
+ global:
+ extern "C++" {
+ *google*;
+ };
+
+ local:
+ *;
+};
diff --git a/src/libprotoc.map b/src/libprotoc.map
new file mode 100644
index 00000000..39155466
--- /dev/null
+++ b/src/libprotoc.map
@@ -0,0 +1,9 @@
+{
+ global:
+ extern "C++" {
+ *google*;
+ };
+
+ local:
+ *;
+};
diff --git a/tests.sh b/tests.sh
index ce149bc9..50c45fa9 100755
--- a/tests.sh
+++ b/tests.sh
@@ -61,8 +61,9 @@ build_cpp_distcheck() {
make dist
# List all files that should be included in the distribution package.
- git ls-files | grep "^\(java\|python\|objectivec\|csharp\|js\|ruby\|php\|cmake\|examples\)" |\
- grep -v ".gitignore" | grep -v "java/compatibility_tests" > dist.lst
+ git ls-files | grep "^\(java\|python\|objectivec\|csharp\|js\|ruby\|php\|cmake\|examples\|src/google/protobuf/.*\.proto\)" |\
+ grep -v ".gitignore" | grep -v "java/compatibility_tests" |\
+ grep -v "python/compatibility_tests" | grep -v "csharp/compatibility_tests" > dist.lst
# Unzip the dist tar file.
DIST=`ls *.tar.gz`
tar -xf $DIST
@@ -86,38 +87,30 @@ build_cpp_distcheck() {
}
build_csharp() {
- # Just for the conformance tests. We don't currently
- # need to really build protoc, but it's simplest to keep with the
- # conventions of the other builds.
+ # Required for conformance tests and to regenerate protos.
internal_build_cpp
NUGET=/usr/local/bin/nuget.exe
- if [ "$TRAVIS" == "true" ]; then
- # Install latest version of Mono
- sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF
- sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 1397BC53640DB551
- echo "deb http://download.mono-project.com/repo/debian wheezy main" | sudo tee /etc/apt/sources.list.d/mono-xamarin.list
- sudo apt-get update -qq
- sudo apt-get install -qq mono-devel referenceassemblies-pcl nunit
-
- # Then install the dotnet SDK as per Ubuntu 14.04 instructions on dot.net.
- sudo sh -c 'echo "deb [arch=amd64] https://apt-mo.trafficmanager.net/repos/dotnet-release/ trusty main" > /etc/apt/sources.list.d/dotnetdev.list'
- sudo apt-key adv --keyserver apt-mo.trafficmanager.net --recv-keys 417A0893
- sudo apt-get update -qq
- sudo apt-get install -qq dotnet-dev-1.0.0-preview2-003121
- fi
-
# Perform "dotnet new" once to get the setup preprocessing out of the
# way. That spews a lot of output (including backspaces) into logs
# otherwise, and can cause problems. It doesn't matter if this step
# is performed multiple times; it's cheap after the first time anyway.
+ # (It also doesn't matter if it's unnecessary, which it will be on some
+ # systems. It's necessary on Jenkins in order to avoid unprintable
+ # characters appearing in the JUnit output.)
mkdir dotnettmp
(cd dotnettmp; dotnet new > /dev/null)
rm -rf dotnettmp
- (cd csharp/src; dotnet restore)
+ # Check that the protos haven't broken C# codegen.
+ # TODO(jonskeet): Fail if regenerating creates any changes.
+ csharp/generate_protos.sh
+
csharp/buildall.sh
cd conformance && make test_csharp && cd ..
+
+ # Run csharp compatibility test between 3.0.0 and the current version.
+ csharp/compatibility_tests/v3.0.0/test.sh 3.0.0
}
build_golang() {
@@ -137,7 +130,7 @@ build_golang() {
export PATH="$GOPATH/bin:$PATH"
go get github.com/golang/protobuf/protoc-gen-go
- cd examples && make gotest && cd ..
+ cd examples && PROTO_PATH="-I../src -I." make gotest && cd ..
}
use_java() {
@@ -242,9 +235,10 @@ internal_install_python_deps() {
sudo apt-get install -y python-software-properties # for apt-add-repository
sudo apt-add-repository -y ppa:fkrull/deadsnakes
sudo apt-get update -qq
- sudo apt-get install -y python2.6 python2.6-dev
sudo apt-get install -y python3.3 python3.3-dev
sudo apt-get install -y python3.4 python3.4-dev
+ sudo apt-get install -y python3.5 python3.5-dev
+ sudo apt-get install -y python3.6 python3.6-dev
fi
}
@@ -286,7 +280,7 @@ build_python() {
cd python
# Only test Python 2.6/3.x on Linux
if [ $(uname -s) == "Linux" ]; then
- envlist=py\{26,27,33,34\}-python
+ envlist=py\{27,33,34,35,36\}-python
else
envlist=py27-python
fi
@@ -300,10 +294,9 @@ build_python_cpp() {
export LD_LIBRARY_PATH=../src/.libs # for Linux
export DYLD_LIBRARY_PATH=../src/.libs # for OS X
cd python
- # Only test Python 2.6/3.x on Linux
+ # Only test Python 3.x on Linux
if [ $(uname -s) == "Linux" ]; then
- # py26 is currently disabled due to json_format
- envlist=py\{27,33,34\}-cpp
+ envlist=py\{27,33,34,35,36\}-cpp
else
envlist=py27-cpp
fi
@@ -311,6 +304,16 @@ build_python_cpp() {
cd ..
}
+build_python_compatibility() {
+ internal_build_cpp
+ # Use the unit-tests extraced from 2.5.0 to test the compatibilty.
+ cd python/compatibility_tests/v2.5.0
+ # Test between 2.5.0 and the current version.
+ ./test.sh 2.5.0
+ # Test between 3.0.0-beta-1 and the current version.
+ ./test.sh 3.0.0-beta-1
+}
+
build_ruby21() {
internal_build_cpp # For conformance tests.
cd ruby && bash travis-test.sh ruby-2.1 && cd ..
@@ -336,6 +339,7 @@ build_ruby_all() {
build_javascript() {
internal_build_cpp
cd js && npm install && npm test && cd ..
+ cd conformance && make test_nodejs && cd ..
}
generate_php_test_proto() {
@@ -344,9 +348,25 @@ generate_php_test_proto() {
# Generate test file
rm -rf generated
mkdir generated
- ../../src/protoc --php_out=generated proto/test.proto proto/test_include.proto proto/test_no_namespace.proto
+ ../../src/protoc --php_out=generated \
+ proto/test.proto \
+ proto/test_include.proto \
+ proto/test_no_namespace.proto \
+ proto/test_prefix.proto \
+ proto/test_php_namespace.proto \
+ proto/test_empty_php_namespace.proto \
+ proto/test_reserved_enum_lower.proto \
+ proto/test_reserved_enum_upper.proto \
+ proto/test_reserved_enum_value_lower.proto \
+ proto/test_reserved_enum_value_upper.proto \
+ proto/test_reserved_message_lower.proto \
+ proto/test_reserved_message_upper.proto \
+ proto/test_service.proto \
+ proto/test_service_namespace.proto \
+ proto/test_descriptors.proto
pushd ../../src
- ./protoc --php_out=../php/tests/generated google/protobuf/empty.proto
+ ./protoc --php_out=../php/tests/generated -I../php/tests -I. \
+ ../php/tests/proto/test_import_descriptor_proto.proto
popd
popd
}
@@ -356,12 +376,9 @@ use_php() {
PHP=`which php`
PHP_CONFIG=`which php-config`
PHPIZE=`which phpize`
- rm $PHP
- rm $PHP_CONFIG
- rm $PHPIZE
- cp "/usr/bin/php$VERSION" $PHP
- cp "/usr/bin/php-config$VERSION" $PHP_CONFIG
- cp "/usr/bin/phpize$VERSION" $PHPIZE
+ ln -sfn "/usr/local/php-${VERSION}/bin/php" $PHP
+ ln -sfn "/usr/local/php-${VERSION}/bin/php-config" $PHP_CONFIG
+ ln -sfn "/usr/local/php-${VERSION}/bin/phpize" $PHPIZE
generate_php_test_proto
}
@@ -389,37 +406,38 @@ use_php_bc() {
build_php5.5() {
use_php 5.5
+
pushd php
rm -rf vendor
cp -r /usr/local/vendor-5.5 vendor
- ./vendor/bin/phpunit
+ wget https://phar.phpunit.de/phpunit-4.8.0.phar -O /usr/bin/phpunit
+ phpunit
+ popd
+ pushd conformance
+ make test_php
popd
}
build_php5.5_c() {
use_php 5.5
- cd php/tests && /bin/bash ./test.sh && cd ../..
+ wget https://phar.phpunit.de/phpunit-4.8.0.phar -O /usr/bin/phpunit
+ pushd php/tests
+ /bin/bash ./test.sh
+ popd
+ # TODO(teboring): Add it back
+ # pushd conformance
+ # make test_php_c
+ # popd
}
build_php5.5_zts_c() {
use_php_zts 5.5
- wget https://phar.phpunit.de/phpunit-old.phar -O /usr/bin/phpunit
- cd php/tests && /bin/bash ./test.sh && cd ../..
-}
-
-build_php5.5_32() {
- use_php_bc 5.5
- pushd php
- rm -rf vendor
- cp -r /usr/local/vendor-5.5 vendor
- ./vendor/bin/phpunit
- popd
-}
-
-build_php5.5_c_32() {
- use_php_bc 5.5
- wget https://phar.phpunit.de/phpunit-old.phar -O /usr/bin/phpunit
+ wget https://phar.phpunit.de/phpunit-4.8.0.phar -O /usr/bin/phpunit
cd php/tests && /bin/bash ./test.sh && cd ../..
+ # TODO(teboring): Add it back
+ # pushd conformance
+ # make test_php_zts_c
+ # popd
}
build_php5.6() {
@@ -427,13 +445,32 @@ build_php5.6() {
pushd php
rm -rf vendor
cp -r /usr/local/vendor-5.6 vendor
- ./vendor/bin/phpunit
+ wget https://phar.phpunit.de/phpunit-5.7.0.phar -O /usr/bin/phpunit
+ phpunit
+ popd
+ pushd conformance
+ make test_php
popd
}
build_php5.6_c() {
use_php 5.6
+ wget https://phar.phpunit.de/phpunit-5.7.0.phar -O /usr/bin/phpunit
+ cd php/tests && /bin/bash ./test.sh && cd ../..
+ # TODO(teboring): Add it back
+ # pushd conformance
+ # make test_php_c
+ # popd
+}
+
+build_php5.6_zts_c() {
+ use_php_zts 5.6
+ wget https://phar.phpunit.de/phpunit-5.7.0.phar -O /usr/bin/phpunit
cd php/tests && /bin/bash ./test.sh && cd ../..
+ # TODO(teboring): Add it back
+ # pushd conformance
+ # make test_php_zts_c
+ # popd
}
build_php5.6_mac() {
@@ -444,7 +481,7 @@ build_php5.6_mac() {
export PATH="$PHP_FOLDER/bin:$PATH"
# Install phpunit
- curl https://phar.phpunit.de/phpunit.phar -L -o phpunit.phar
+ curl https://phar.phpunit.de/phpunit-5.6.10.phar -L -o phpunit.phar
chmod +x phpunit.phar
sudo mv phpunit.phar /usr/local/bin/phpunit
@@ -455,6 +492,10 @@ build_php5.6_mac() {
# Test
cd php/tests && /bin/bash ./test.sh && cd ../..
+ # TODO(teboring): Add it back
+ # pushd conformance
+ # make test_php_c
+ # popd
}
build_php7.0() {
@@ -462,28 +503,114 @@ build_php7.0() {
pushd php
rm -rf vendor
cp -r /usr/local/vendor-7.0 vendor
- ./vendor/bin/phpunit
+ wget https://phar.phpunit.de/phpunit-5.6.0.phar -O /usr/bin/phpunit
+ phpunit
+ popd
+ pushd conformance
+ make test_php
popd
}
build_php7.0_c() {
use_php 7.0
+ wget https://phar.phpunit.de/phpunit-5.6.0.phar -O /usr/bin/phpunit
cd php/tests && /bin/bash ./test.sh && cd ../..
+ # TODO(teboring): Add it back
+ # pushd conformance
+ # make test_php_c
+ # popd
}
-build_php_all() {
+build_php7.0_zts_c() {
+ use_php_zts 7.0
+ wget https://phar.phpunit.de/phpunit-5.6.0.phar -O /usr/bin/phpunit
+ cd php/tests && /bin/bash ./test.sh && cd ../..
+ # TODO(teboring): Add it back.
+ # pushd conformance
+ # make test_php_zts_c
+ # popd
+}
+
+build_php7.0_mac() {
+ generate_php_test_proto
+ # Install PHP
+ curl -s https://php-osx.liip.ch/install.sh | bash -s 7.0
+ PHP_FOLDER=`find /usr/local -type d -name "php7-7.0*"` # The folder name may change upon time
+ export PATH="$PHP_FOLDER/bin:$PATH"
+
+ # Install phpunit
+ curl https://phar.phpunit.de/phpunit-5.6.0.phar -L -o phpunit.phar
+ chmod +x phpunit.phar
+ sudo mv phpunit.phar /usr/local/bin/phpunit
+
+ # Install valgrind
+ echo "#! /bin/bash" > valgrind
+ chmod ug+x valgrind
+ sudo mv valgrind /usr/local/bin/valgrind
+
+ # Test
+ cd php/tests && /bin/bash ./test.sh && cd ../..
+ # TODO(teboring): Add it back
+ # pushd conformance
+ # make test_php_c
+ # popd
+}
+
+build_php_compatibility() {
+ internal_build_cpp
+ php/tests/compatibility_test.sh
+}
+
+build_php7.1() {
+ use_php 7.1
+ pushd php
+ rm -rf vendor
+ cp -r /usr/local/vendor-7.1 vendor
+ wget https://phar.phpunit.de/phpunit-5.6.0.phar -O /usr/bin/phpunit
+ phpunit
+ popd
+ pushd conformance
+ # TODO(teboring): Add it back
+ # make test_php
+ popd
+}
+
+build_php7.1_c() {
+ use_php 7.1
+ wget https://phar.phpunit.de/phpunit-5.6.0.phar -O /usr/bin/phpunit
+ cd php/tests && /bin/bash ./test.sh && cd ../..
+ pushd conformance
+ # make test_php_c
+ popd
+}
+
+build_php7.1_zts_c() {
+ use_php_zts 7.1
+ wget https://phar.phpunit.de/phpunit-5.6.0.phar -O /usr/bin/phpunit
+ cd php/tests && /bin/bash ./test.sh && cd ../..
+ pushd conformance
+ # make test_php_c
+ popd
+}
+
+build_php_all_32() {
build_php5.5
build_php5.6
build_php7.0
+ build_php7.1
build_php5.5_c
build_php5.6_c
- # build_php7.0_c
+ build_php7.0_c
+ build_php7.1_c
build_php5.5_zts_c
+ build_php5.6_zts_c
+ build_php7.0_zts_c
+ build_php7.1_zts_c
}
-build_php_all_32() {
- build_php5.5_32
- build_php5.5_c_32
+build_php_all() {
+ build_php_all_32
+ build_php_compatibility
}
# Note: travis currently does not support testing more than one language so the
@@ -513,6 +640,7 @@ Usage: $0 { cpp |
objectivec_cocoapods_integration |
python |
python_cpp |
+ python_compatibility |
ruby21 |
ruby22 |
jruby |
@@ -523,6 +651,9 @@ Usage: $0 { cpp |
php5.6_c |
php7.0 |
php7.0_c |
+ php_compatibility |
+ php7.1 |
+ php7.1_c |
php_all)
"
exit 1
diff --git a/third_party/benchmark b/third_party/benchmark
-Subproject 360e66c1c4777c99402cf8cd535aa510fee1657
+Subproject 5b7683f49e1e9223cf9927b24f6fd3d6bd82e3f
diff --git a/update_file_lists.sh b/update_file_lists.sh
index d76a1610..9c0fbdc5 100755
--- a/update_file_lists.sh
+++ b/update_file_lists.sh
@@ -135,7 +135,7 @@ for HEADER in $PUBLIC_HEADERS; do
done | sort | uniq | sed "s/^/mkdir include\\\\/" >> $EXTRACT_INCLUDES_BAT
for HEADER in $PUBLIC_HEADERS; do
WINPATH=$(echo $HEADER | sed 's;/;\\;g')
- echo "copy \${PROTOBUF_SOURCE_WIN32_PATH}\\..\\src\\$WINPATH include\\$WINPATH" >> $EXTRACT_INCLUDES_BAT
+ echo "copy \"\${PROTOBUF_SOURCE_WIN32_PATH}\\..\\src\\$WINPATH\" include\\$WINPATH" >> $EXTRACT_INCLUDES_BAT
done
################################################################################